| 1 |
from math import sqrt |
| 2 |
|
| 3 |
from lunr.exceptions import BaseLunrException |
| 4 |
|
| 5 |
|
| 6 |
class Vector: |
| 7 |
"""A vector is used to construct the vector space of documents and queries. |
| 8 |
These vectors support operations to determine the similarity between two |
| 9 |
documents or a document and a query. |
| 10 |
|
| 11 |
Normally no parameters are required for initializing a vector, but in the |
| 12 |
case of loading a previously dumped vector the raw elements can be provided |
| 13 |
to the constructor. |
| 14 |
|
| 15 |
For performance reasons vectors are implemented with a flat array, where an |
| 16 |
elements index is immediately followed by its value. |
| 17 |
E.g. [index, value, index, value]. |
| 18 |
|
| 19 |
TODO: consider implemetation as 2-tuples. |
| 20 |
|
| 21 |
This allows the underlying array to be as sparse as possible and still |
| 22 |
offer decent performance when being used for vector calculations. |
| 23 |
""" |
| 24 |
|
| 25 |
def __init__(self, elements=None): |
| 26 |
self._magnitude = 0 |
| 27 |
self.elements = elements or [] |
| 28 |
|
| 29 |
def __repr__(self): |
| 30 |
return "<Vector magnitude={}>".format(self.magnitude) |
| 31 |
|
| 32 |
def __iter__(self): |
| 33 |
return iter(self.elements) |
| 34 |
|
| 35 |
def position_for_index(self, index): |
| 36 |
"""Calculates the position within the vector to insert a given index. |
| 37 |
|
| 38 |
This is used internally by insert and upsert. If there are duplicate |
| 39 |
indexes then the position is returned as if the value for that index |
| 40 |
were to be updated, but it is the callers responsibility to check |
| 41 |
whether there is a duplicate at that index |
| 42 |
""" |
| 43 |
if not self.elements: |
| 44 |
return 0 |
| 45 |
|
| 46 |
start = 0 |
| 47 |
end = int(len(self.elements) / 2) |
| 48 |
slice_length = end - start |
| 49 |
pivot_point = int(slice_length / 2) |
| 50 |
pivot_index = self.elements[pivot_point * 2] |
| 51 |
|
| 52 |
while slice_length > 1: |
| 53 |
if pivot_index < index: |
| 54 |
start = pivot_point |
| 55 |
elif pivot_index > index: |
| 56 |
end = pivot_point |
| 57 |
else: |
| 58 |
break |
| 59 |
|
| 60 |
slice_length = end - start |
| 61 |
pivot_point = start + int(slice_length / 2) |
| 62 |
pivot_index = self.elements[pivot_point * 2] |
| 63 |
|
| 64 |
if pivot_index == index: |
| 65 |
return pivot_point * 2 |
| 66 |
elif pivot_index > index: |
| 67 |
return pivot_point * 2 |
| 68 |
else: |
| 69 |
return (pivot_point + 1) * 2 |
| 70 |
|
| 71 |
def insert(self, insert_index, val): |
| 72 |
"""Inserts an element at an index within the vector. |
| 73 |
|
| 74 |
Does not allow duplicates, will throw an error if there is already an |
| 75 |
entry for this index. |
| 76 |
""" |
| 77 |
|
| 78 |
def prevent_duplicates(index, val): |
| 79 |
raise BaseLunrException("Duplicate index") |
| 80 |
|
| 81 |
self.upsert(insert_index, val, prevent_duplicates) |
| 82 |
|
| 83 |
def upsert(self, insert_index, val, fn=None): |
| 84 |
"""Inserts or updates an existing index within the vector. |
| 85 |
|
| 86 |
Args: |
| 87 |
- insert_index (int): The index at which the element should be |
| 88 |
inserted. |
| 89 |
- val (int|float): The value to be inserted into the vector. |
| 90 |
- fn (callable, optional): An optional callable taking two |
| 91 |
arguments, the current value and the passed value to generate |
| 92 |
the final inserted value at the position in case of collision. |
| 93 |
""" |
| 94 |
fn = fn or (lambda current, passed: passed) |
| 95 |
self._magnitude = 0 |
| 96 |
position = self.position_for_index(insert_index) |
| 97 |
if position < len(self.elements) and self.elements[position] == insert_index: |
| 98 |
self.elements[position + 1] = fn(self.elements[position + 1], val) |
| 99 |
else: |
| 100 |
self.elements.insert(position, val) |
| 101 |
self.elements.insert(position, insert_index) |
| 102 |
|
| 103 |
def to_list(self): |
| 104 |
"""Converts the vector to an array of the elements within the vector""" |
| 105 |
output = [] |
| 106 |
for i in range(1, len(self.elements), 2): |
| 107 |
output.append(self.elements[i]) |
| 108 |
return output |
| 109 |
|
| 110 |
def serialize(self): |
| 111 |
# TODO: the JS version forces rounding on the elements upon insertion |
| 112 |
# to ensure symmetry upon serialization |
| 113 |
return [round(element, 3) for element in self.elements] |
| 114 |
|
| 115 |
@property |
| 116 |
def magnitude(self): |
| 117 |
if not self._magnitude: |
| 118 |
sum_of_squares = 0 |
| 119 |
for i in range(1, len(self.elements), 2): |
| 120 |
value = self.elements[i] |
| 121 |
sum_of_squares += value * value |
| 122 |
|
| 123 |
self._magnitude = sqrt(sum_of_squares) |
| 124 |
|
| 125 |
return self._magnitude |
| 126 |
|
| 127 |
def dot(self, other): |
| 128 |
"""Calculates the dot product of this vector and another vector.""" |
| 129 |
dot_product = 0 |
| 130 |
a = self.elements |
| 131 |
b = other.elements |
| 132 |
a_len = len(a) |
| 133 |
b_len = len(b) |
| 134 |
i = j = 0 |
| 135 |
|
| 136 |
while i < a_len and j < b_len: |
| 137 |
a_val = a[i] |
| 138 |
b_val = b[j] |
| 139 |
if a_val < b_val: |
| 140 |
i += 2 |
| 141 |
elif a_val > b_val: |
| 142 |
j += 2 |
| 143 |
else: |
| 144 |
dot_product += a[i + 1] * b[j + 1] |
| 145 |
i += 2 |
| 146 |
j += 2 |
| 147 |
|
| 148 |
return dot_product |
| 149 |
|
| 150 |
def similarity(self, other): |
| 151 |
"""Calculates the cosine similarity between this vector and another |
| 152 |
vector.""" |
| 153 |
if self.magnitude == 0 or other.magnitude == 0: |
| 154 |
return 0 |
| 155 |
|
| 156 |
return self.dot(other) / self.magnitude |