Skip to content

Commit 6a8bcb0

Browse files
committed
#13 Add numeric distance calculator
1 parent 2dc329b commit 6a8bcb0

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
"""
2+
Various methods to calculate distance between numeric vectors
3+
"""
4+
import numpy as np
5+
from typing import TypeVar
6+
7+
from src.utils.numeric_distance_type import NumericDistanceType
8+
from src.exceptions.exceptions import IncompatibleVectorSizesException, InvalidParamValue
9+
10+
Vector = TypeVar("Vector")
11+
12+
13+
class NumericDistanceCalculator(object):
14+
15+
def __init__(self, dist_type: NumericDistanceType) -> None:
16+
self.dist_type = dist_type
17+
18+
def calculate(self, state1: Vector, state2: Vector) -> float:
19+
return _numeric_distance_calculator(state1=state1, state2=state2, dist_type=self.dist_type)
20+
21+
22+
def _numeric_distance_calculator(state1: Vector, state2: Vector, dist_type: NumericDistanceType) -> float:
23+
24+
if len(state1) != len(state2):
25+
raise IncompatibleVectorSizesException(size1=len(state1), size2=len(state2))
26+
27+
if dist_type == NumericDistanceType.L1:
28+
return _l1_state_leakage(state1=state1, state2=state2)
29+
elif dist_type == NumericDistanceType.L2:
30+
return _l1_state_leakage(state1=state1, state2=state2)
31+
elif dist_type == NumericDistanceType.L2_NORMALIZED:
32+
return _normalized_l2_distance(state1=state1, state2=state2)
33+
34+
raise InvalidParamValue(param_name="dist_type", param_value=dist_type.name)
35+
36+
37+
def _normalized_l2_distance(state1: Vector, state2: Vector) -> float:
38+
"""
39+
Returns the normalized L2 norm between the two vectors
40+
:param state1:
41+
:param state2:
42+
:return:
43+
"""
44+
45+
size = len(state1)
46+
dist = 0.0
47+
for item1, item2 in zip(state1, state2):
48+
dist += ((item1 - item2)**2) / size
49+
50+
return np.sqrt(dist)
51+
52+
def _l2_state_leakage(state1: Vector, state2: Vector) -> float:
53+
return np.linalg.norm(state1 - state2, ord=None)
54+
55+
def _l1_state_leakage(state1: Vector, state2: Vector) -> float:
56+
return np.linalg.norm(state1 - state2, ord=1)

0 commit comments

Comments
 (0)