lombokvector 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,168 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined in Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or Object
36
+ form, made available under the License, as indicated by a copyright
37
+ notice that is included in or attached to the work (an example is
38
+ provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship, thus excluding
44
+ simple mechanical transformations or merely linking (or binding by
45
+ name) to the interfaces of, the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original Work and any Derivative Works thereof, that is
49
+ intentionally submitted to, or incorporated into, the Work by
50
+ Licensor for inclusion in the Work by the copyright owner or by an
51
+ individual or Legal Entity authorized to submit on behalf of the
52
+ copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, such as but not limited to
55
+ communication on electronic mailing lists, source code control
56
+ systems, and issue tracking systems that are managed by, or on behalf
57
+ of, the Licensor for the purpose of discussing and improving the Work,
58
+ but excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by Licensor and
63
+ subsequently incorporated into the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the
83
+ Work or Derivative Works thereof in any medium, with or without
84
+ modifications, and in Source or Object form, provided that You
85
+ meet the following conditions:
86
+
87
+ (a) You must give any other recipients of the Work or
88
+ Derivative Works a copy of this License; and
89
+
90
+ (b) You must cause any modified files to carry prominent notices
91
+ stating that You changed the files; and
92
+
93
+ (c) You must retain, in the Source form of any Derivative Works
94
+ that You distribute, all copyright, patent, trademark, and
95
+ attribution notices from the Source form of the Work,
96
+ excluding those notices that do not pertain to any part of
97
+ the Derivative Works; and
98
+
99
+ (d) If the Work includes a "NOTICE" text file, then any
100
+ Derivative Works that You distribute must include a readable
101
+ copy of the attribution notices contained
102
+ within such NOTICE file, excluding those notices that do not
103
+ pertain to any part of the Derivative Works, in at least one
104
+ of the following places: within a NOTICE text file distributed
105
+ as part of the Derivative Works; within the Source form or
106
+ documentation, if provided along with the Derivative Works; or,
107
+ within a display generated by the Derivative Works, if and
108
+ wherever such third-party notices normally appear.
109
+
110
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
111
+ any Contribution intentionally submitted for inclusion in the Work
112
+ by You to the Licensor shall be under the terms and conditions of
113
+ this License, without any additional terms or conditions.
114
+ Notwithstanding the above, nothing herein shall supersede or modify
115
+ the terms of any separate license agreement you may have executed
116
+ with Licensor regarding such Contribution.
117
+
118
+ 6. Trademarks. This License does not grant permission to use the trade
119
+ names, trademarks, service marks, or product names of the Licensor,
120
+ except as required for reasonable and customary use in describing the
121
+ origin of the Work and reproducing the content of the NOTICE file.
122
+
123
+ 7. Disclaimer of Warranty. Unless required by applicable law or
124
+ agreed to in writing, Licensor provides the Work (and each
125
+ Contributor provides its Contributions) on an "AS IS" BASIS,
126
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
127
+ implied, including, without limitation, any warranties or conditions
128
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
129
+ PARTICULAR PURPOSE.
130
+
131
+ 8. Limitation of Liability. In no event and under no legal theory,
132
+ whether in tort (including negligence), contract, or otherwise,
133
+ unless required by applicable law (such as deliberate and grossly
134
+ negligent acts) or agreed to in writing, shall any Contributor be
135
+ liable to You for damages, including any direct, indirect, special,
136
+ incidental, or consequential damages of any character arising as a
137
+ result of this License or out of the use or inability to use the
138
+ Work (including but not limited to damages for loss of goodwill,
139
+ work stoppage, computer failure or malfunction, or any and all
140
+ other commercial damages or losses), even if such Contributor
141
+ has been advised of the possibility of such damages.
142
+
143
+ 9. Accepting Warranty or Additional Liability. While redistributing
144
+ the Work or Derivative Works thereof, You may choose to offer,
145
+ and charge a fee for, acceptance of support, warranty, indemnity,
146
+ or other liability obligations and/or rights consistent with this
147
+ License. However, in accepting such obligations, You may act only
148
+ on Your own behalf and on Your sole responsibility, not on behalf
149
+ of any other Contributor, and only if You agree to indemnify,
150
+ defend, and hold each Contributor harmless for any liability
151
+ incurred by, or claims asserted against, such Contributor by reason
152
+ of your accepting any such warranty or additional liability.
153
+
154
+ END OF TERMS AND CONDITIONS
155
+
156
+ Copyright 2024-2026 codinglombok
157
+
158
+ Licensed under the Apache License, Version 2.0 (the "License");
159
+ you may not use this file except in compliance with the License.
160
+ You may obtain a copy of the License at
161
+
162
+ http://www.apache.org/licenses/LICENSE-2.0
163
+
164
+ Unless required by applicable law or agreed to in writing, software
165
+ distributed under the License is distributed on an "AS IS" BASIS,
166
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
167
+ See the License for the specific language governing permissions and
168
+ limitations under the License.
@@ -0,0 +1,29 @@
1
+ Metadata-Version: 2.4
2
+ Name: lombokvector
3
+ Version: 0.1.0
4
+ Summary: Vector math with bit-identical results across Python, Rust, TypeScript, Go and PHP: dot product, cosine similarity, L2 distance, normalization, batch ranking. Pure Python, zero dependencies.
5
+ Author: codinglombok
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/codinglombok/LombokVector
8
+ Project-URL: Issues, https://github.com/codinglombok/LombokVector/issues
9
+ Keywords: vector,cosine-similarity,embedding,deterministic
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Dynamic: license-file
18
+
19
+ # LombokVector for Python
20
+
21
+ Python package `lombokvector` (binary64, Python 3.9+, pure Python): dot product, cosine similarity, Euclidean distance, normalization, and batch ranking with results that are bit-identical to the other LombokVector ports. Zero runtime dependencies.
22
+
23
+ ```
24
+ pip install lombokvector
25
+ ```
26
+
27
+ The summation order and every operation are defined in [docs/SPEC_LombokVector_v0.1.0.md](https://github.com/codinglombok/LombokVector/blob/main/docs/SPEC_LombokVector_v0.1.0.md); this port reproduces the shared vector file bit for bit in CI. Usage for all languages: [main README](https://github.com/codinglombok/LombokVector#readme) and [docs/API_LombokVector_v0.1.0.md](https://github.com/codinglombok/LombokVector/blob/main/docs/API_LombokVector_v0.1.0.md).
28
+
29
+ License: Apache-2.0.
@@ -0,0 +1,11 @@
1
+ # LombokVector for Python
2
+
3
+ Python package `lombokvector` (binary64, Python 3.9+, pure Python): dot product, cosine similarity, Euclidean distance, normalization, and batch ranking with results that are bit-identical to the other LombokVector ports. Zero runtime dependencies.
4
+
5
+ ```
6
+ pip install lombokvector
7
+ ```
8
+
9
+ The summation order and every operation are defined in [docs/SPEC_LombokVector_v0.1.0.md](https://github.com/codinglombok/LombokVector/blob/main/docs/SPEC_LombokVector_v0.1.0.md); this port reproduces the shared vector file bit for bit in CI. Usage for all languages: [main README](https://github.com/codinglombok/LombokVector#readme) and [docs/API_LombokVector_v0.1.0.md](https://github.com/codinglombok/LombokVector/blob/main/docs/API_LombokVector_v0.1.0.md).
10
+
11
+ License: Apache-2.0.
@@ -0,0 +1,245 @@
1
+ """LombokVector for Python: binary64 vector math whose results are
2
+ bit-identical to the Rust, TypeScript, Go and PHP ports. Every sum uses the
3
+ 8-lane order of docs/SPEC_LombokVector_v0.1.0.md section 2. Pure Python,
4
+ no dependencies."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import math
9
+ from typing import List, NamedTuple, Sequence
10
+
11
+ __version__ = "0.1.0"
12
+ __all__ = [
13
+ "ScoredIndex",
14
+ "VectorError",
15
+ "batch_cosine",
16
+ "batch_dot",
17
+ "batch_l2",
18
+ "cosine_similarity",
19
+ "distance_matrix_cosine",
20
+ "dot_product",
21
+ "inner_product",
22
+ "l2_distance",
23
+ "l2_norm",
24
+ "normalize",
25
+ "vec_add",
26
+ "vec_mul_scalar",
27
+ "vec_sub",
28
+ ]
29
+
30
+ Vector = Sequence[float]
31
+
32
+
33
+ class VectorError(ValueError):
34
+ """Raised by every operation; ``code`` is stable across ports:
35
+ ``DIMENSION_MISMATCH``, ``EMPTY_VECTOR``, ``ZERO_MAGNITUDE``, ``NON_FINITE``."""
36
+
37
+ def __init__(self, code: str, message: str) -> None:
38
+ super().__init__(f"{code}: {message}")
39
+ self.code = code
40
+
41
+
42
+ class ScoredIndex(NamedTuple):
43
+ """A candidate's position in the input and its score."""
44
+
45
+ index: int
46
+ score: float
47
+
48
+
49
+ def _check_pair(a: Vector, b: Vector) -> None:
50
+ if len(a) == 0:
51
+ raise VectorError("EMPTY_VECTOR", "vector has no elements")
52
+ if len(a) != len(b):
53
+ raise VectorError("DIMENSION_MISMATCH", f"expected {len(a)} elements, got {len(b)}")
54
+
55
+
56
+ def _check_single(a: Vector) -> None:
57
+ if len(a) == 0:
58
+ raise VectorError("EMPTY_VECTOR", "vector has no elements")
59
+
60
+
61
+ def _finite(x: float) -> float:
62
+ if not math.isfinite(x):
63
+ raise VectorError("NON_FINITE", "result is infinite or NaN")
64
+ return x
65
+
66
+
67
+ # --- SPEC section 2: the 8-lane reduction ------------------------------------
68
+
69
+
70
+ def _combine(s: List[float]) -> float:
71
+ return ((s[0] + s[1]) + (s[2] + s[3])) + ((s[4] + s[5]) + (s[6] + s[7]))
72
+
73
+
74
+ def _dot(a: Vector, b: Vector) -> float:
75
+ s = [0.0] * 8
76
+ for i in range(len(a)):
77
+ s[i & 7] += float(a[i]) * float(b[i])
78
+ return _combine(s)
79
+
80
+
81
+ def _sumsq(a: Vector) -> float:
82
+ s = [0.0] * 8
83
+ for i in range(len(a)):
84
+ x = float(a[i])
85
+ s[i & 7] += x * x
86
+ return _combine(s)
87
+
88
+
89
+ def _l2sq(a: Vector, b: Vector) -> float:
90
+ s = [0.0] * 8
91
+ for i in range(len(a)):
92
+ d = float(a[i]) - float(b[i])
93
+ s[i & 7] += d * d
94
+ return _combine(s)
95
+
96
+
97
+ def _sqrt(x: float) -> float:
98
+ # x is a finite sum of squares, so it is never negative
99
+ return _finite(math.sqrt(x))
100
+
101
+
102
+ def _div(x: float, y: float) -> float:
103
+ if y == 0.0: # IEEE 754 gives an infinity or NaN; Python raises instead
104
+ raise VectorError("NON_FINITE", "result is infinite or NaN")
105
+ return _finite(x / y)
106
+
107
+
108
+ def _cos(d: float, na: float, nb: float) -> float:
109
+ c = _div(d, na * nb)
110
+ return -1.0 if c < -1.0 else 1.0 if c > 1.0 else c
111
+
112
+
113
+ # --- SPEC section 3: operations ----------------------------------------------
114
+
115
+
116
+ def dot_product(a: Vector, b: Vector) -> float:
117
+ """Dot product."""
118
+ _check_pair(a, b)
119
+ return _finite(_dot(a, b))
120
+
121
+
122
+ def inner_product(a: Vector, b: Vector) -> float:
123
+ """Same as :func:`dot_product` for real vectors."""
124
+ return dot_product(a, b)
125
+
126
+
127
+ def l2_norm(a: Vector) -> float:
128
+ """Euclidean norm."""
129
+ _check_single(a)
130
+ return _sqrt(_finite(_sumsq(a)))
131
+
132
+
133
+ def l2_distance(a: Vector, b: Vector) -> float:
134
+ """Euclidean distance."""
135
+ _check_pair(a, b)
136
+ return _sqrt(_finite(_l2sq(a, b)))
137
+
138
+
139
+ def cosine_similarity(a: Vector, b: Vector) -> float:
140
+ """Cosine similarity clamped to [-1, 1]; ``ZERO_MAGNITUDE`` when either norm is 0."""
141
+ _check_pair(a, b)
142
+ d = _finite(_dot(a, b))
143
+ na = _sqrt(_finite(_sumsq(a)))
144
+ nb = _sqrt(_finite(_sumsq(b)))
145
+ if na == 0.0 or nb == 0.0:
146
+ raise VectorError("ZERO_MAGNITUDE", "vector has magnitude zero")
147
+ return _cos(d, na, nb)
148
+
149
+
150
+ def normalize(a: Vector) -> List[float]:
151
+ """Unit-length copy: ``a[i] * (1 / norm)``."""
152
+ _check_single(a)
153
+ n = _sqrt(_finite(_sumsq(a)))
154
+ if n == 0.0:
155
+ raise VectorError("ZERO_MAGNITUDE", "vector has magnitude zero")
156
+ inv = _div(1.0, n)
157
+ return [_finite(float(x) * inv) for x in a]
158
+
159
+
160
+ def vec_add(a: Vector, b: Vector) -> List[float]:
161
+ """Element-wise sum."""
162
+ _check_pair(a, b)
163
+ return [_finite(float(x) + float(y)) for x, y in zip(a, b)]
164
+
165
+
166
+ def vec_sub(a: Vector, b: Vector) -> List[float]:
167
+ """Element-wise difference."""
168
+ _check_pair(a, b)
169
+ return [_finite(float(x) - float(y)) for x, y in zip(a, b)]
170
+
171
+
172
+ def vec_mul_scalar(a: Vector, s: float) -> List[float]:
173
+ """Every element multiplied by ``s``."""
174
+ _check_single(a)
175
+ s = float(s)
176
+ return [_finite(float(x) * s) for x in a]
177
+
178
+
179
+ # --- batch and matrix ----------------------------------------------------------
180
+
181
+
182
+ def _rank(scores: List[float], descending: bool) -> List[ScoredIndex]:
183
+ # sorted() is stable, so equal scores keep index order
184
+ order = sorted(range(len(scores)), key=(lambda i: -scores[i]) if descending else (lambda i: scores[i]))
185
+ return [ScoredIndex(i, scores[i]) for i in order]
186
+
187
+
188
+ def _check_candidate(query: Vector, c: Vector) -> None:
189
+ if len(c) != len(query):
190
+ raise VectorError("DIMENSION_MISMATCH", f"expected {len(query)} elements, got {len(c)}")
191
+
192
+
193
+ def batch_cosine(query: Vector, candidates: Sequence[Vector]) -> List[ScoredIndex]:
194
+ """Cosine similarity of ``query`` with each candidate, descending; a zero candidate scores 0."""
195
+ _check_single(query)
196
+ qn = _sqrt(_finite(_sumsq(query)))
197
+ if qn == 0.0:
198
+ raise VectorError("ZERO_MAGNITUDE", "query has magnitude zero")
199
+ scores = []
200
+ for c in candidates:
201
+ _check_candidate(query, c)
202
+ d = _finite(_dot(query, c))
203
+ cn = _sqrt(_finite(_sumsq(c)))
204
+ scores.append(0.0 if cn == 0.0 else _cos(d, qn, cn))
205
+ return _rank(scores, True)
206
+
207
+
208
+ def batch_dot(query: Vector, candidates: Sequence[Vector]) -> List[ScoredIndex]:
209
+ """Dot product of ``query`` with each candidate, descending."""
210
+ _check_single(query)
211
+ scores = []
212
+ for c in candidates:
213
+ _check_candidate(query, c)
214
+ scores.append(_finite(_dot(query, c)))
215
+ return _rank(scores, True)
216
+
217
+
218
+ def batch_l2(query: Vector, candidates: Sequence[Vector]) -> List[ScoredIndex]:
219
+ """Euclidean distance from ``query`` to each candidate, ascending."""
220
+ _check_single(query)
221
+ scores = []
222
+ for c in candidates:
223
+ _check_candidate(query, c)
224
+ scores.append(_sqrt(_finite(_l2sq(query, c))))
225
+ return _rank(scores, False)
226
+
227
+
228
+ def distance_matrix_cosine(a: Sequence[Vector], b: Sequence[Vector]) -> List[List[float]]:
229
+ """``out[i][j]`` = cosine similarity of ``a[i]`` and ``b[j]``; 0 when either has magnitude zero."""
230
+ if len(a) == 0 or len(b) == 0:
231
+ raise VectorError("EMPTY_VECTOR", "vector set is empty")
232
+ first = a[0]
233
+ _check_single(first)
234
+ for v in list(a) + list(b):
235
+ _check_candidate(first, v)
236
+ na = [_sqrt(_finite(_sumsq(v))) for v in a]
237
+ nb = [_sqrt(_finite(_sumsq(v))) for v in b]
238
+ out = []
239
+ for i, va in enumerate(a):
240
+ row = []
241
+ for j, vb in enumerate(b):
242
+ d = _finite(_dot(va, vb))
243
+ row.append(0.0 if na[i] == 0.0 or nb[j] == 0.0 else _cos(d, na[i], nb[j]))
244
+ out.append(row)
245
+ return out
File without changes
@@ -0,0 +1,29 @@
1
+ Metadata-Version: 2.4
2
+ Name: lombokvector
3
+ Version: 0.1.0
4
+ Summary: Vector math with bit-identical results across Python, Rust, TypeScript, Go and PHP: dot product, cosine similarity, L2 distance, normalization, batch ranking. Pure Python, zero dependencies.
5
+ Author: codinglombok
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/codinglombok/LombokVector
8
+ Project-URL: Issues, https://github.com/codinglombok/LombokVector/issues
9
+ Keywords: vector,cosine-similarity,embedding,deterministic
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.9
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Dynamic: license-file
18
+
19
+ # LombokVector for Python
20
+
21
+ Python package `lombokvector` (binary64, Python 3.9+, pure Python): dot product, cosine similarity, Euclidean distance, normalization, and batch ranking with results that are bit-identical to the other LombokVector ports. Zero runtime dependencies.
22
+
23
+ ```
24
+ pip install lombokvector
25
+ ```
26
+
27
+ The summation order and every operation are defined in [docs/SPEC_LombokVector_v0.1.0.md](https://github.com/codinglombok/LombokVector/blob/main/docs/SPEC_LombokVector_v0.1.0.md); this port reproduces the shared vector file bit for bit in CI. Usage for all languages: [main README](https://github.com/codinglombok/LombokVector#readme) and [docs/API_LombokVector_v0.1.0.md](https://github.com/codinglombok/LombokVector/blob/main/docs/API_LombokVector_v0.1.0.md).
28
+
29
+ License: Apache-2.0.
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ lombokvector/__init__.py
5
+ lombokvector/py.typed
6
+ lombokvector.egg-info/PKG-INFO
7
+ lombokvector.egg-info/SOURCES.txt
8
+ lombokvector.egg-info/dependency_links.txt
9
+ lombokvector.egg-info/top_level.txt
10
+ tests/test_api.py
11
+ tests/test_vectors.py
@@ -0,0 +1 @@
1
+ lombokvector
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "lombokvector"
7
+ version = "0.1.0"
8
+ description = "Vector math with bit-identical results across Python, Rust, TypeScript, Go and PHP: dot product, cosine similarity, L2 distance, normalization, batch ranking. Pure Python, zero dependencies."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE"]
12
+ authors = [{ name = "codinglombok" }]
13
+ requires-python = ">=3.9"
14
+ keywords = ["vector", "cosine-similarity", "embedding", "deterministic"]
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ "Topic :: Scientific/Engineering :: Mathematics",
19
+ "Typing :: Typed",
20
+ ]
21
+ dependencies = []
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/codinglombok/LombokVector"
25
+ Issues = "https://github.com/codinglombok/LombokVector/issues"
26
+
27
+ [tool.setuptools]
28
+ packages = ["lombokvector"]
29
+
30
+ [tool.setuptools.package-data]
31
+ lombokvector = ["py.typed"]
32
+
33
+ [tool.pytest.ini_options]
34
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,68 @@
1
+ import math
2
+
3
+ import pytest
4
+
5
+ import lombokvector as lv
6
+
7
+
8
+ def code(c):
9
+ return pytest.raises(lv.VectorError, match=f"^{c}:")
10
+
11
+
12
+ def test_basic_values():
13
+ assert lv.dot_product([1, 2, 3], [4, 5, 6]) == 32.0
14
+ assert lv.inner_product([1, 2, 3], [4, 5, 6]) == 32.0
15
+ assert lv.l2_norm([3, 4]) == 5.0
16
+ assert lv.l2_distance([1, 2, 3], [4, 5, 6]) == math.sqrt(27)
17
+ assert lv.cosine_similarity([1, 0], [0, 1]) == 0.0
18
+ assert lv.normalize([3, 4]) == [3 * 0.2, 4 * 0.2]
19
+ assert lv.vec_add([1, 2], [3, 4]) == [4.0, 6.0]
20
+ assert lv.vec_sub([1, 2], [3, 4]) == [-2.0, -2.0]
21
+ assert lv.vec_mul_scalar([1, 2], 3) == [3.0, 6.0]
22
+ assert lv.vec_mul_scalar([-2], 0) == [-0.0] and math.copysign(1, lv.vec_mul_scalar([-2], 0)[0]) == -1
23
+
24
+
25
+ def test_lane_order():
26
+ assert lv.dot_product([1e16, 1, -1e16, 1], [1, 1, 1, 1]) == 0.0
27
+
28
+
29
+ def test_errors():
30
+ with code("EMPTY_VECTOR"):
31
+ lv.dot_product([], [])
32
+ with code("DIMENSION_MISMATCH"):
33
+ lv.dot_product([1], [1, 2])
34
+ with code("ZERO_MAGNITUDE"):
35
+ lv.cosine_similarity([0, 0], [1, 1])
36
+ with code("ZERO_MAGNITUDE"):
37
+ lv.normalize([0])
38
+ with code("NON_FINITE"):
39
+ lv.l2_norm([math.nan])
40
+ with code("NON_FINITE"):
41
+ lv.vec_add([math.inf], [1])
42
+ with code("NON_FINITE"):
43
+ lv.cosine_similarity([1e200, 1e200], [1, 1])
44
+ with code("EMPTY_VECTOR"):
45
+ lv.vec_mul_scalar([], 1)
46
+ with code("ZERO_MAGNITUDE"):
47
+ lv.batch_cosine([0, 0], [])
48
+ with code("DIMENSION_MISMATCH"):
49
+ lv.batch_dot([1], [[1, 2]])
50
+ with code("DIMENSION_MISMATCH"):
51
+ lv.batch_l2([1], [[1, 2]])
52
+ with code("EMPTY_VECTOR"):
53
+ lv.distance_matrix_cosine([], [[1]])
54
+ with code("EMPTY_VECTOR"):
55
+ lv.distance_matrix_cosine([[]], [[]])
56
+ with code("DIMENSION_MISMATCH"):
57
+ lv.distance_matrix_cosine([[1, 0]], [[1]])
58
+ e = lv.VectorError("NON_FINITE", "x")
59
+ assert isinstance(e, ValueError) and e.code == "NON_FINITE" and str(e) == "NON_FINITE: x"
60
+
61
+
62
+ def test_batch_ranking():
63
+ r = lv.batch_dot([1, 1], [[1, 0], [0, 1], [2, -1], [-1, 2]])
64
+ assert [x.index for x in r] == [0, 1, 2, 3]
65
+ assert lv.batch_l2([0, 0], [[3, 4], [1, 0], [0, 1]]) == [(1, 1.0), (2, 1.0), (0, 5.0)]
66
+ assert [x.index for x in lv.batch_cosine([1, 1], [[0, 0], [1, 1]])] == [1, 0]
67
+ assert lv.distance_matrix_cosine([[1, 0], [0, 0]], [[1, 0]]) == [[1.0], [0.0]]
68
+ assert lv.__version__ == "0.1.0"
@@ -0,0 +1,54 @@
1
+ """Runs the binary64 cases of the shared vectors: every bit pattern must match."""
2
+
3
+ import json
4
+ import pathlib
5
+ import struct
6
+
7
+ import pytest
8
+
9
+ import lombokvector as lv
10
+
11
+ DOC = json.loads((pathlib.Path(__file__).resolve().parents[2] / "vectors" / "lombokvector-vectors-v1.json").read_text(encoding="utf-8"))
12
+ CASES = [c for c in DOC["cases"] if c["precision"] == "f64"]
13
+
14
+
15
+ def bits(x):
16
+ return "0x%016x" % struct.unpack("<Q", struct.pack("<d", x))[0]
17
+
18
+
19
+ def run(op, a):
20
+ if op == "dot":
21
+ return bits(lv.dot_product(a[0], a[1]))
22
+ if op == "norm":
23
+ return bits(lv.l2_norm(a[0]))
24
+ if op == "l2":
25
+ return bits(lv.l2_distance(a[0], a[1]))
26
+ if op == "cosine":
27
+ return bits(lv.cosine_similarity(a[0], a[1]))
28
+ if op == "normalize":
29
+ return [bits(x) for x in lv.normalize(a[0])]
30
+ if op == "add":
31
+ return [bits(x) for x in lv.vec_add(a[0], a[1])]
32
+ if op == "sub":
33
+ return [bits(x) for x in lv.vec_sub(a[0], a[1])]
34
+ if op == "scale":
35
+ return [bits(x) for x in lv.vec_mul_scalar(a[0], a[1])]
36
+ if op in ("batch_cosine", "batch_dot", "batch_l2"):
37
+ fn = {"batch_cosine": lv.batch_cosine, "batch_dot": lv.batch_dot, "batch_l2": lv.batch_l2}[op]
38
+ return [[r.index, bits(r.score)] for r in fn(a[0], a[1])]
39
+ if op == "matrix_cosine":
40
+ return [[bits(x) for x in row] for row in lv.distance_matrix_cosine(a[0], a[1])]
41
+ raise ValueError(op)
42
+
43
+
44
+ def test_at_least_100_cases():
45
+ assert len(CASES) >= 100
46
+
47
+
48
+ @pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
49
+ def test_vector(case):
50
+ try:
51
+ got = {"value": run(case["op"], case["args"])}
52
+ except lv.VectorError as e:
53
+ got = {"error": e.code}
54
+ assert got == case["expected"]