|
| 1 | +import numpy as np |
| 2 | + |
| 3 | +from objectbox.c import * |
| 4 | +from objectbox.model.properties import VectorDistanceType |
| 5 | + |
| 6 | + |
| 7 | +def check_float_vector(vector: Union[np.ndarray, List[float]], vector_name: str): |
| 8 | + """ Checks that the given vector is a float vector (either np.ndarray or Python's list). """ |
| 9 | + if isinstance(vector, np.ndarray) and vector.dtype != np.float32: |
| 10 | + raise Exception(f"{vector_name} dtype is expected to be np.float32, got: {vector.dtype}") |
| 11 | + elif isinstance(vector, list) and len(vector) > 0 and (type(vector[0]) is not float): |
| 12 | + raise Exception(f"{vector_name} is expected to be a float list, got vector[0]: {type(vector[0])}") |
| 13 | + |
| 14 | + |
| 15 | +def vector_distance_f32(distance_type: VectorDistanceType, |
| 16 | + vector1: Union[np.ndarray, List[float]], |
| 17 | + vector2: Union[np.ndarray, List[float]], |
| 18 | + dimension: int) -> float: |
| 19 | + """ Utility function to calculate the distance of two vectors. """ |
| 20 | + check_float_vector(vector1, "vector1") |
| 21 | + check_float_vector(vector2, "vector2") |
| 22 | + return obx_vector_distance_float32(distance_type, |
| 23 | + c_array(vector1, ctypes.c_float), |
| 24 | + c_array(vector2, ctypes.c_float), |
| 25 | + dimension) |
| 26 | + |
| 27 | + |
| 28 | +def vector_distance_to_relevance(distance_type: VectorDistanceType, distance: float) -> float: |
| 29 | + """ Converts the given distance to a relevance score in range [0.0, 1.0], according to its type. """ |
| 30 | + return obx_vector_distance_to_relevance(distance_type, distance) |
0 commit comments