hypercomplex-engine 0.5.0__tar.gz → 0.6.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.
Files changed (44) hide show
  1. {hypercomplex_engine-0.5.0/hypercomplex_engine.egg-info → hypercomplex_engine-0.6.0}/PKG-INFO +2 -1
  2. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/__init__.py +5 -0
  3. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/__init__.py +6 -0
  4. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/fast/bit_utils.py +3 -1
  5. hypercomplex_engine-0.6.0/hypercomplex_engine/core/vectorized/__init__.py +6 -0
  6. hypercomplex_engine-0.6.0/hypercomplex_engine/core/vectorized/vectorized_standard.py +118 -0
  7. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0/hypercomplex_engine.egg-info}/PKG-INFO +2 -1
  8. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine.egg-info/SOURCES.txt +5 -1
  9. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/pyproject.toml +2 -1
  10. hypercomplex_engine-0.6.0/tests/test_vectorized_extended.py +420 -0
  11. hypercomplex_engine-0.6.0/tests/test_vectorized_standard.py +156 -0
  12. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/LICENSE +0 -0
  13. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/NOTICE +0 -0
  14. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/README.md +0 -0
  15. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/basis_element.py +0 -0
  16. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/basis_notation.py +0 -0
  17. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/fast/__init__.py +0 -0
  18. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/fast/fast_dual.py +0 -0
  19. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/fast/fast_split.py +0 -0
  20. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/fast/fast_standard.py +0 -0
  21. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/holographic/__init__.py +0 -0
  22. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/holographic/dual.py +0 -0
  23. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/holographic/split.py +0 -0
  24. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/holographic/standard.py +0 -0
  25. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/table_builder/__init__.py +0 -0
  26. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/table_builder/common.py +0 -0
  27. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/table_builder/dual.py +0 -0
  28. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/table_builder/split.py +0 -0
  29. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/table_builder/standard.py +0 -0
  30. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/core/validation.py +0 -0
  31. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/facade.py +0 -0
  32. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/printer/__init__.py +0 -0
  33. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/printer/cd_format.py +0 -0
  34. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine/printer/cd_table_printer.py +0 -0
  35. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine.egg-info/dependency_links.txt +0 -0
  36. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine.egg-info/requires.txt +0 -0
  37. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/hypercomplex_engine.egg-info/top_level.txt +0 -0
  38. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/setup.cfg +0 -0
  39. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/tests/test_dual_tuple_regression.py +0 -0
  40. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/tests/test_fast_mode.py +0 -0
  41. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/tests/test_fixes_0_4.py +0 -0
  42. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/tests/test_mega_mother.py +0 -0
  43. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/tests/test_split_dim.py +0 -0
  44. {hypercomplex_engine-0.5.0 → hypercomplex_engine-0.6.0}/tests/test_strict_dual_3tuple.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypercomplex-engine
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: Fast O(1)/O(n) multiplication engine for arbitrary dimensions and table generator for ordinary, split, and dual Cayley-Dickson algebras.
5
5
  Author-email: Maher Ben Abdessalem <ba.maher94@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -18,6 +18,7 @@ Classifier: Programming Language :: Python :: 3.11
18
18
  Classifier: Programming Language :: Python :: 3.12
19
19
  Classifier: Programming Language :: Python :: 3.13
20
20
  Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
21
22
  Classifier: Operating System :: OS Independent
22
23
  Requires-Python: >=3.10
23
24
  Description-Content-Type: text/markdown
@@ -29,6 +29,8 @@ from .core import (
29
29
  FastStandard,
30
30
  FastSplit,
31
31
  FastDual,
32
+
33
+ VectorizedStandard
32
34
  )
33
35
 
34
36
  from .printer import (
@@ -65,6 +67,9 @@ __all__ = [
65
67
  "FastSplit",
66
68
  "FastDual",
67
69
 
70
+ #VectorizedStandard
71
+ "VectorizedStandard"
72
+
68
73
  # Printer / formatter
69
74
  "CDFormat",
70
75
  "CDTablePrinter",
@@ -20,6 +20,10 @@ from .fast import (
20
20
  FastDual,
21
21
  )
22
22
 
23
+ from .vectorized import (
24
+ VectorizedStandard
25
+ )
26
+
23
27
  __all__ = [
24
28
  "BasisElement",
25
29
  "BasisNotation",
@@ -36,4 +40,6 @@ __all__ = [
36
40
  "FastStandard",
37
41
  "FastSplit",
38
42
  "FastDual",
43
+
44
+ "VectorizedStandard",
39
45
  ]
@@ -17,4 +17,6 @@ def popcount(x: int) -> int:
17
17
  """
18
18
  Number of set bits.
19
19
  """
20
- return int(x).bit_count()
20
+ x=int(x)
21
+ return x.bit_count() if hasattr(x, "bit_count") else bin(x).count("1")
22
+
@@ -0,0 +1,6 @@
1
+ from .vectorized_standard import VectorizedStandard
2
+
3
+
4
+ __all__ = [
5
+ "VectorizedStandard"
6
+ ]
@@ -0,0 +1,118 @@
1
+ import numpy as np
2
+ from ..validation import Validation
3
+
4
+ class VectorizedStandard:
5
+ """
6
+ SIMD-Accelerated O(1) Vectorized Multiplier for Standard Cayley-Dickson Algebras.
7
+ Replaces nested Python loops with C-Level Twisted Convolution via Scatter-Add.
8
+ """
9
+
10
+ @staticmethod
11
+ def _get_np_popcount():
12
+ """Hardware-accelerated popcount for NumPy arrays."""
13
+ try:
14
+ return np.bitwise_count
15
+ except AttributeError:
16
+ def popcount_vec(x):
17
+ x = np.asarray(x, dtype=np.uint64)
18
+ x = x - ((x >> 1) & np.uint64(0x5555555555555555))
19
+ x = (x & np.uint64(0x3333333333333333)) + ((x >> 2) & np.uint64(0x3333333333333333))
20
+ x = (x + (x >> 4)) & np.uint64(0x0F0F0F0F0F0F0F0F)
21
+ return ((x * np.uint64(0x0101010101010101)) >> np.uint64(56)).astype(np.uint8)
22
+ return popcount_vec
23
+
24
+ def multiply_indices_vec(self, i_arr: np.ndarray, j_arr: np.ndarray) -> tuple:
25
+ """
26
+ Vectorized Core O(1) multiplication for arrays of indices.
27
+ Returns: (signs_array, indices_array)
28
+ """
29
+ _popcount = self._get_np_popcount()
30
+ i = np.asarray(i_arr, dtype=np.uint64)
31
+ j = np.asarray(j_arr, dtype=np.uint64)
32
+
33
+ # Target index is always XOR
34
+ idx = i ^ j
35
+
36
+ # Masks for structural cases
37
+ mask_zero = (i == 0) | (j == 0)
38
+ mask_diag = (i == j) & ~mask_zero
39
+
40
+ # Safe guards for nu2 (avoid log2(0) or popcount(-1) issues)
41
+ i_safe = np.where(i == 0, 1, i)
42
+ j_safe = np.where(j == 0, 1, j)
43
+ ij_safe = np.where((i ^ j) == 0, 1, i ^ j)
44
+
45
+ # Vectorized nu2: popcount((x & -x) - 1)
46
+ t = _popcount((ij_safe & -ij_safe) - np.uint64(1)).astype(np.uint64)
47
+ ti = _popcount((i_safe & -i_safe) - np.uint64(1)).astype(np.uint64)
48
+ tj = _popcount((j_safe & -j_safe) - np.uint64(1)).astype(np.uint64)
49
+
50
+ # Branch 1: Diagonal break (t >= ti and t >= tj)
51
+ cond1 = (t >= ti) & (t >= tj)
52
+ s1 = 2 * ((i >> t) & np.uint64(1)).astype(np.int8) - 1
53
+
54
+ # Branch 2: i-axis break (ti > t and ti >= tj)
55
+ cond2 = (~cond1) & (ti >= tj)
56
+ b = (j >> ti) & np.uint64(1)
57
+ j_loc = j & ((np.uint64(1) << ti) - np.uint64(1))
58
+ delta = np.where(j_loc == 0, 1, -1).astype(np.int8)
59
+ s2 = np.where(b == 0, delta, -delta)
60
+
61
+ # Branch 3: j-axis break (tj > t and tj > ti)
62
+ cond3 = ~cond1 & ~cond2
63
+ s3 = 1 - 2 * ((i >> tj) & np.uint64(1)).astype(np.int8)
64
+
65
+ # Combine branches
66
+ s = np.where(cond1, s1, np.where(cond2, s2, s3))
67
+
68
+ # Higher-bit parity correction
69
+ k = np.maximum(np.maximum(t, ti), tj) + np.uint64(1)
70
+ parity = _popcount((i | j) >> k) & np.uint8(1)
71
+ s = np.where(parity == 1, -s, s)
72
+
73
+ # Apply structural overrides
74
+ s = np.where(mask_zero, 1, s)
75
+ s = np.where(mask_diag, -1, s)
76
+
77
+ return s.astype(np.int8), idx
78
+
79
+ def multiply_arrays(self, arr1: np.ndarray, arr2: np.ndarray) -> np.ndarray:
80
+ """
81
+ Full polynomial multiplication using Twisted Convolution via C-Level Scatter-Add.
82
+ Automatically handles sparsity to prevent RAM explosion on high dimensions.
83
+ """
84
+ size1 = len(arr1)
85
+ size2 = len(arr2)
86
+ max_size = max(size1, size2)
87
+
88
+ if max_size <= 1:
89
+ return np.array([arr1[0] * arr2[0]], dtype=np.float64) if size1 > 0 and size2 > 0 else np.zeros(1, dtype=np.float64)
90
+
91
+ # Calculate required power-of-two dimension
92
+ # Equivalent to 1 << math.ceil(math.log2(max_size))
93
+ dim = 1 << (max_size - 1).bit_length()
94
+
95
+ # 1. SPARSE OPTIMIZATION: Isolate non-zero elements
96
+ nz_A = np.nonzero(arr1)[0]
97
+ nz_B = np.nonzero(arr2)[0]
98
+
99
+ if len(nz_A) == 0 or len(nz_B) == 0:
100
+ return np.zeros(dim, dtype=np.float64)
101
+
102
+ # 2. Create the 2D Grid of ONLY the active indices
103
+ I, J = np.meshgrid(nz_A, nz_B, indexing='ij')
104
+
105
+ # 3. Calculate the entire Sign and Index Matrix in one C-level SIMD sweep
106
+ S, V = self.multiply_indices_vec(I, J)
107
+
108
+ # 4. Calculate the Outer Product of ONLY the active coefficients
109
+ M = np.outer(arr1[nz_A], arr2[nz_B])
110
+
111
+ # 5. Apply Signs to the Coefficients
112
+ weighted_M = S.astype(np.float64) * M
113
+
114
+ # 6. C-Level Scatter-Add into the Result Array
115
+ result = np.zeros(dim, dtype=np.float64)
116
+ np.add.at(result, V.ravel(), weighted_M.ravel())
117
+
118
+ return result
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypercomplex-engine
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: Fast O(1)/O(n) multiplication engine for arbitrary dimensions and table generator for ordinary, split, and dual Cayley-Dickson algebras.
5
5
  Author-email: Maher Ben Abdessalem <ba.maher94@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -18,6 +18,7 @@ Classifier: Programming Language :: Python :: 3.11
18
18
  Classifier: Programming Language :: Python :: 3.12
19
19
  Classifier: Programming Language :: Python :: 3.13
20
20
  Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Programming Language :: Python :: 3.15
21
22
  Classifier: Operating System :: OS Independent
22
23
  Requires-Python: >=3.10
23
24
  Description-Content-Type: text/markdown
@@ -27,6 +27,8 @@ hypercomplex_engine/core/table_builder/common.py
27
27
  hypercomplex_engine/core/table_builder/dual.py
28
28
  hypercomplex_engine/core/table_builder/split.py
29
29
  hypercomplex_engine/core/table_builder/standard.py
30
+ hypercomplex_engine/core/vectorized/__init__.py
31
+ hypercomplex_engine/core/vectorized/vectorized_standard.py
30
32
  hypercomplex_engine/printer/__init__.py
31
33
  hypercomplex_engine/printer/cd_format.py
32
34
  hypercomplex_engine/printer/cd_table_printer.py
@@ -35,4 +37,6 @@ tests/test_fast_mode.py
35
37
  tests/test_fixes_0_4.py
36
38
  tests/test_mega_mother.py
37
39
  tests/test_split_dim.py
38
- tests/test_strict_dual_3tuple.py
40
+ tests/test_strict_dual_3tuple.py
41
+ tests/test_vectorized_extended.py
42
+ tests/test_vectorized_standard.py
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "hypercomplex-engine"
7
- version = "0.5.0"
7
+ version = "0.6.0"
8
8
  authors = [
9
9
  { name="Maher Ben Abdessalem", email="ba.maher94@gmail.com" },
10
10
  ]
@@ -31,6 +31,7 @@ classifiers = [
31
31
  "Programming Language :: Python :: 3.12",
32
32
  "Programming Language :: Python :: 3.13",
33
33
  "Programming Language :: Python :: 3.14",
34
+ "Programming Language :: Python :: 3.15",
34
35
  "Operating System :: OS Independent",
35
36
  ]
36
37
 
@@ -0,0 +1,420 @@
1
+ """
2
+ EXTENDED ADVERSARIAL TEST SUITE for VectorizedStandard.
3
+ Designed to BREAK the engine. If these pass, the engine is bulletproof.
4
+
5
+ Categories:
6
+ - AlgebraicProperties: Mathematical invariants that MUST hold
7
+ - ExhaustiveConsistency: Brute-force comparison vs proven scalar engine
8
+ - BoundaryConditions: Extreme values, overflow, edge indices
9
+ - ArrayEdgeCases: Empty, sparse, asymmetric, degenerate inputs
10
+ - NumericalStability: Float precision, cancellation, extreme magnitudes
11
+ - Stress: Memory, collisions, performance regression
12
+
13
+ Run quick: pytest tests/test_vectorized_extended.py -v -m "not slow"
14
+ Run full: pytest tests/test_vectorized_extended.py -v
15
+ """
16
+ import numpy as np
17
+ import pytest
18
+ import time
19
+
20
+ from hypercomplex_engine.core.fast.fast_standard import FastStandard
21
+ from hypercomplex_engine.core.vectorized.vectorized_standard import VectorizedStandard
22
+
23
+
24
+ @pytest.fixture
25
+ def fast():
26
+ return FastStandard()
27
+
28
+ @pytest.fixture
29
+ def vec():
30
+ return VectorizedStandard()
31
+
32
+
33
+ # =============================================================================
34
+ # 1. ALGEBRAIC PROPERTIES — Mathematical invariants that MUST hold
35
+ # =============================================================================
36
+ class TestAlgebraicProperties:
37
+ """These test the MATH, not just the implementation."""
38
+
39
+ def test_anticommutativity(self, fast, vec):
40
+ """e_i * e_j = -(e_j * e_i) for i != j, both non-zero."""
41
+ np.random.seed(1)
42
+ n = 5000
43
+ i = np.random.randint(1, 2**20, size=n, dtype=np.uint64)
44
+ j = np.random.randint(1, 2**20, size=n, dtype=np.uint64)
45
+ # Ensure i != j
46
+ mask = i == j
47
+ j[mask] += 1
48
+
49
+ s_ij, idx_ij = vec.multiply_indices_vec(i, j)
50
+ s_ji, idx_ji = vec.multiply_indices_vec(j, i)
51
+
52
+ # Indices must match (XOR is commutative)
53
+ np.testing.assert_array_equal(idx_ij, idx_ji,
54
+ err_msg="XOR index must be symmetric")
55
+ # Signs must be opposite
56
+ np.testing.assert_array_equal(s_ij, -s_ji,
57
+ err_msg="Anticommutativity violated: e_i*e_j != -(e_j*e_i)")
58
+
59
+ def test_square_is_negative_identity(self, vec):
60
+ """e_i * e_i = -e_0 for all i > 0 (sign=-1, index=0)."""
61
+ i = np.arange(1, 100_000, dtype=np.uint64)
62
+ signs, idxs = vec.multiply_indices_vec(i, i)
63
+ np.testing.assert_array_equal(signs, np.full(len(i), -1, dtype=np.int8),
64
+ err_msg="e_i^2 must have sign -1")
65
+ np.testing.assert_array_equal(idxs, np.zeros(len(i), dtype=np.uint64),
66
+ err_msg="e_i^2 must have index 0")
67
+
68
+ def test_identity_element(self, vec):
69
+ """e_0 * e_j = e_j and e_i * e_0 = e_i."""
70
+ j = np.arange(0, 50_000, dtype=np.uint64)
71
+ zeros = np.zeros(len(j), dtype=np.uint64)
72
+
73
+ # 0 * j
74
+ s1, idx1 = vec.multiply_indices_vec(zeros, j)
75
+ np.testing.assert_array_equal(s1, np.ones(len(j), dtype=np.int8))
76
+ np.testing.assert_array_equal(idx1, j)
77
+
78
+ # j * 0
79
+ s2, idx2 = vec.multiply_indices_vec(j, zeros)
80
+ np.testing.assert_array_equal(s2, np.ones(len(j), dtype=np.int8))
81
+ np.testing.assert_array_equal(idx2, j)
82
+
83
+ def test_alternativity_octonions(self, vec):
84
+ """
85
+ Octonions (dim<=8) are alternative:
86
+ (e_i * e_i) * e_j == e_i * (e_i * e_j)
87
+ """
88
+ # Test all pairs in octonion range
89
+ for i in range(1, 8):
90
+ for j in range(1, 8):
91
+ # (e_i * e_i) * e_j
92
+ s1, k = vec.multiply_indices_vec(
93
+ np.array([i], dtype=np.uint64),
94
+ np.array([i], dtype=np.uint64))
95
+ s2, m_left = vec.multiply_indices_vec(
96
+ np.array([k[0]], dtype=np.uint64),
97
+ np.array([j], dtype=np.uint64))
98
+ left = (int(s1[0]) * int(s2[0]), int(m_left[0]))
99
+
100
+ # e_i * (e_i * e_j)
101
+ s3, k2 = vec.multiply_indices_vec(
102
+ np.array([i], dtype=np.uint64),
103
+ np.array([j], dtype=np.uint64))
104
+ s4, m_right = vec.multiply_indices_vec(
105
+ np.array([i], dtype=np.uint64),
106
+ np.array([k2[0]], dtype=np.uint64))
107
+ right = (int(s3[0]) * int(s4[0]), int(m_right[0]))
108
+
109
+ assert left == right, (
110
+ f"Alternativity violated at i={i}, j={j}: {left} != {right}")
111
+
112
+ def test_power_associativity(self, vec):
113
+ """(e_i^2)^2 == e_i^4 — powers of a single element associate."""
114
+ i = np.array([7, 15, 31, 63], dtype=np.uint64)
115
+ for idx in i:
116
+ # e_i^2
117
+ s1, k1 = vec.multiply_indices_vec(
118
+ np.array([idx]), np.array([idx]))
119
+ # (e_i^2)^2
120
+ s2, k2 = vec.multiply_indices_vec(
121
+ np.array([k1[0]]), np.array([k1[0]]))
122
+ # Should be (+1, 0) since (-1)^2 = +1
123
+ assert int(k2[0]) == 0, f"e_{idx}^4 index != 0"
124
+ assert int(s1[0])**2 * int(s2[0]) == 1, f"e_{idx}^4 sign != +1"
125
+
126
+
127
+ # =============================================================================
128
+ # 2. EXHAUSTIVE CONSISTENCY — Brute force vs proven scalar engine
129
+ # =============================================================================
130
+ class TestExhaustiveConsistency:
131
+ """Compare every single output against the proven FastStandard."""
132
+
133
+ @pytest.mark.parametrize("dim_level", [1, 2, 3, 4, 5, 6])
134
+ def test_exhaustive_vs_scalar(self, fast, vec, dim_level):
135
+ """Every pair in A_n matches scalar FastStandard exactly."""
136
+ dim = 1 << dim_level
137
+ i_all, j_all = np.meshgrid(
138
+ np.arange(dim, dtype=np.uint64),
139
+ np.arange(dim, dtype=np.uint64),
140
+ indexing='ij')
141
+ i_flat = i_all.ravel()
142
+ j_flat = j_all.ravel()
143
+
144
+ # Scalar ground truth
145
+ gt_signs = np.zeros(len(i_flat), dtype=np.int8)
146
+ gt_idxs = np.zeros(len(i_flat), dtype=np.uint64)
147
+ for k in range(len(i_flat)):
148
+ s, idx = fast.multiply_indices(int(i_flat[k]), int(j_flat[k]))
149
+ gt_signs[k] = s
150
+ gt_idxs[k] = idx
151
+
152
+ # Vectorized
153
+ v_signs, v_idxs = vec.multiply_indices_vec(i_flat, j_flat)
154
+
155
+ np.testing.assert_array_equal(v_signs, gt_signs,
156
+ err_msg=f"Sign mismatch in dim 2^{dim_level}")
157
+ np.testing.assert_array_equal(v_idxs, gt_idxs,
158
+ err_msg=f"Index mismatch in dim 2^{dim_level}")
159
+
160
+ def test_random_60bit_vs_scalar(self, fast, vec):
161
+ """200k random 60-bit pairs match scalar exactly."""
162
+ np.random.seed(777)
163
+ n = 200_000
164
+ i = np.random.randint(0, 2**60, size=n, dtype=np.uint64)
165
+ j = np.random.randint(0, 2**60, size=n, dtype=np.uint64)
166
+
167
+ gt_signs = np.zeros(n, dtype=np.int8)
168
+ gt_idxs = np.zeros(n, dtype=np.uint64)
169
+ for k in range(n):
170
+ s, idx = fast.multiply_indices(int(i[k]), int(j[k]))
171
+ gt_signs[k] = s
172
+ gt_idxs[k] = idx
173
+
174
+ v_signs, v_idxs = vec.multiply_indices_vec(i, j)
175
+ np.testing.assert_array_equal(v_signs, gt_signs)
176
+ np.testing.assert_array_equal(v_idxs, gt_idxs)
177
+
178
+ @pytest.mark.slow
179
+ def test_exhaustive_dim10(self, fast, vec):
180
+ """Full exhaustive check for dim 2^10 = 1024 (1M pairs)."""
181
+ dim = 1024
182
+ i_all, j_all = np.meshgrid(
183
+ np.arange(dim, dtype=np.uint64),
184
+ np.arange(dim, dtype=np.uint64),
185
+ indexing='ij')
186
+ i_flat = i_all.ravel()
187
+ j_flat = j_all.ravel()
188
+
189
+ v_signs, v_idxs = vec.multiply_indices_vec(i_flat, j_flat)
190
+
191
+ # Spot-check 10000 random positions against scalar
192
+ np.random.seed(42)
193
+ sample = np.random.choice(len(i_flat), size=10000, replace=False)
194
+ for k in sample:
195
+ s, idx = fast.multiply_indices(int(i_flat[k]), int(j_flat[k]))
196
+ assert int(v_signs[k]) == s, f"Sign mismatch at {i_flat[k]},{j_flat[k]}"
197
+ assert int(v_idxs[k]) == idx, f"Idx mismatch at {i_flat[k]},{j_flat[k]}"
198
+
199
+
200
+ # =============================================================================
201
+ # 3. BOUNDARY CONDITIONS — Extreme values designed to trigger overflow/underflow
202
+ # =============================================================================
203
+ class TestBoundaryConditions:
204
+
205
+ def test_max_uint64(self, fast, vec):
206
+ """Indices near 2^64 - 1 must not overflow."""
207
+ max_val = np.uint64(2**64 - 1)
208
+ i = np.array([max_val, max_val - 1, max_val ^ 1], dtype=np.uint64)
209
+ j = np.array([1, max_val, 2], dtype=np.uint64)
210
+
211
+ v_signs, v_idxs = vec.multiply_indices_vec(i, j)
212
+ for k in range(len(i)):
213
+ s, idx = fast.multiply_indices(int(i[k]), int(j[k]))
214
+ assert int(v_signs[k]) == s, f"Sign fail at max_uint64 case {k}"
215
+ assert int(v_idxs[k]) == idx, f"Idx fail at max_uint64 case {k}"
216
+
217
+ def test_powers_of_two(self, fast, vec):
218
+ """Every power of 2 from 2^0 to 2^63."""
219
+ powers = np.array([1 << k for k in range(64)], dtype=np.uint64)
220
+ i, j = np.meshgrid(powers, powers, indexing='ij')
221
+ i_flat, j_flat = i.ravel(), j.ravel()
222
+
223
+ v_signs, v_idxs = vec.multiply_indices_vec(i_flat, j_flat)
224
+ for k in range(len(i_flat)):
225
+ s, idx = fast.multiply_indices(int(i_flat[k]), int(j_flat[k]))
226
+ assert int(v_signs[k]) == s
227
+ assert int(v_idxs[k]) == idx
228
+
229
+ def test_all_bits_set(self, fast, vec):
230
+ """Numbers of form 2^n - 1 (all bits set)."""
231
+ vals = np.array([(1 << k) - 1 for k in range(1, 64)], dtype=np.uint64)
232
+ i, j = np.meshgrid(vals, vals, indexing='ij')
233
+ i_flat, j_flat = i.ravel(), j.ravel()
234
+
235
+ v_signs, v_idxs = vec.multiply_indices_vec(i_flat, j_flat)
236
+ for k in range(0, len(i_flat), 37): # sample to keep fast
237
+ s, idx = fast.multiply_indices(int(i_flat[k]), int(j_flat[k]))
238
+ assert int(v_signs[k]) == s
239
+ assert int(v_idxs[k]) == idx
240
+
241
+ def test_consecutive_indices(self, fast, vec):
242
+ """Consecutive i, i+1 pairs — stresses nu2 boundary."""
243
+ i = np.arange(0, 100_000, dtype=np.uint64)
244
+ j = i + 1
245
+ v_signs, v_idxs = vec.multiply_indices_vec(i, j)
246
+ for k in range(0, len(i), 997): # prime stride sampling
247
+ s, idx = fast.multiply_indices(int(i[k]), int(j[k]))
248
+ assert int(v_signs[k]) == s
249
+ assert int(v_idxs[k]) == idx
250
+
251
+
252
+ # =============================================================================
253
+ # 4. ARRAY EDGE CASES — Degenerate, empty, sparse, asymmetric inputs
254
+ # =============================================================================
255
+ class TestArrayEdgeCases:
256
+
257
+ def test_single_element_arrays(self, vec):
258
+ """1-D real multiplication."""
259
+ r = vec.multiply_arrays(np.array([3.0]), np.array([4.0]))
260
+ assert len(r) == 1
261
+ assert np.isclose(r[0], 12.0)
262
+
263
+ def test_all_zero_arrays(self, vec):
264
+ """Zero vector times anything is zero."""
265
+ dim = 64
266
+ z = np.zeros(dim)
267
+ x = np.random.randn(dim)
268
+ np.testing.assert_array_equal(vec.multiply_arrays(z, x), np.zeros(dim))
269
+ np.testing.assert_array_equal(vec.multiply_arrays(x, z), np.zeros(dim))
270
+ np.testing.assert_array_equal(vec.multiply_arrays(z, z), np.zeros(dim))
271
+
272
+ def test_extreme_sparsity(self, vec):
273
+ """1 non-zero in a 2^16 vector — must not OOM, must be correct."""
274
+ dim = 1 << 16
275
+ a = np.zeros(dim); a[5] = 2.0
276
+ b = np.zeros(dim); b[7] = 3.0
277
+ result = vec.multiply_arrays(a, b)
278
+ # e_5 * e_7 -> single contribution
279
+ fast = FastStandard()
280
+ s, idx = fast.multiply_indices(5, 7)
281
+ expected = np.zeros(dim)
282
+ expected[idx] = s * 6.0
283
+ np.testing.assert_allclose(result, expected)
284
+
285
+ def test_asymmetric_large_small(self, vec):
286
+ """Tiny array times huge array."""
287
+ small = np.array([1.0, 2.0]) # dim 2
288
+ big = np.random.randn(1024) # dim 1024
289
+ result = vec.multiply_arrays(small, big)
290
+ assert len(result) == 1024 # padded to next power of 2 >= 1024
291
+
292
+ def test_non_power_of_two_sizes(self, vec):
293
+ """Sizes 3, 5, 7 must pad correctly."""
294
+ for size in [3, 5, 7, 9, 15, 17]:
295
+ a = np.random.randn(size)
296
+ b = np.random.randn(size)
297
+ result = vec.multiply_arrays(a, b)
298
+ expected_dim = 1 << (size - 1).bit_length()
299
+ assert len(result) == expected_dim, f"Failed padding for size {size}"
300
+
301
+ def test_negative_coefficients(self, fast, vec):
302
+ """Negative coefficients must propagate signs correctly."""
303
+ dim = 16
304
+ a = np.random.randn(dim)
305
+ b = np.random.randn(dim)
306
+ result = vec.multiply_arrays(a, b)
307
+
308
+ # Brute force with negatives
309
+ expected = np.zeros(dim)
310
+ for i in range(dim):
311
+ for j in range(dim):
312
+ s, idx = fast.multiply_indices(i, j)
313
+ expected[idx] += s * a[i] * b[j]
314
+ np.testing.assert_allclose(result, expected, rtol=1e-12, atol=1e-12)
315
+
316
+
317
+ # =============================================================================
318
+ # 5. NUMERICAL STABILITY — Float precision torture
319
+ # =============================================================================
320
+ class TestNumericalStability:
321
+
322
+ def test_large_coefficients(self, vec):
323
+ """Coefficients near float64 max don't produce NaN unexpectedly."""
324
+ dim = 8
325
+ a = np.array([1e150, 0, 0, 0, 0, 0, 0, 0])
326
+ b = np.array([1e150, 0, 0, 0, 0, 0, 0, 0])
327
+ result = vec.multiply_arrays(a, b)
328
+ # e_0 * e_0 = e_0, coefficient 1e300 (within float64 range)
329
+ assert np.isfinite(result[0])
330
+ assert np.isclose(result[0], 1e300, rtol=1e-10)
331
+
332
+ def test_small_coefficients(self, vec):
333
+ """Tiny coefficients don't underflow to zero incorrectly."""
334
+ dim = 8
335
+ a = np.array([1e-150, 0, 0, 0, 0, 0, 0, 0])
336
+ b = np.array([1e-150, 0, 0, 0, 0, 0, 0, 0])
337
+ result = vec.multiply_arrays(a, b)
338
+ assert np.isclose(result[0], 1e-300, rtol=1e-10)
339
+
340
+ def test_catastrophic_cancellation(self, fast, vec):
341
+ """Values that nearly cancel must still be accurate."""
342
+ dim = 8
343
+ # Craft inputs where multiple terms hit same index with opposite signs
344
+ a = np.zeros(dim); a[1] = 1.0; a[2] = 1.0
345
+ b = np.zeros(dim); b[1] = 1.0; b[2] = -1.0
346
+ result = vec.multiply_arrays(a, b)
347
+
348
+ expected = np.zeros(dim)
349
+ for i in range(dim):
350
+ for j in range(dim):
351
+ s, idx = fast.multiply_indices(i, j)
352
+ expected[idx] += s * a[i] * b[j]
353
+ np.testing.assert_allclose(result, expected, rtol=1e-12, atol=1e-15)
354
+
355
+ def test_accumulation_many_terms(self, fast, vec):
356
+ """Many terms accumulating to same index stay precise."""
357
+ dim = 32
358
+ np.random.seed(5)
359
+ a = np.random.randn(dim)
360
+ b = np.random.randn(dim)
361
+ result = vec.multiply_arrays(a, b)
362
+
363
+ expected = np.zeros(dim)
364
+ for i in range(dim):
365
+ for j in range(dim):
366
+ s, idx = fast.multiply_indices(i, j)
367
+ expected[idx] += s * a[i] * b[j]
368
+ np.testing.assert_allclose(result, expected, rtol=1e-10, atol=1e-12)
369
+
370
+
371
+ # =============================================================================
372
+ # 6. STRESS — Collisions, memory, performance
373
+ # =============================================================================
374
+ class TestStress:
375
+
376
+ def test_massive_xor_collisions(self, fast, vec):
377
+ """
378
+ Force MANY pairs to collide on the same XOR index.
379
+ All pairs (i, i^target) map to 'target'.
380
+ """
381
+ dim = 64
382
+ target = 5
383
+ a = np.random.randn(dim)
384
+ b = np.random.randn(dim)
385
+ result = vec.multiply_arrays(a, b)
386
+
387
+ # Manually sum all pairs hitting index 'target'
388
+ expected_target = 0.0
389
+ for i in range(dim):
390
+ j = i ^ target
391
+ if j < dim:
392
+ s, idx = fast.multiply_indices(i, j)
393
+ assert idx == target
394
+ expected_target += s * a[i] * b[j]
395
+ assert np.isclose(result[target], expected_target, rtol=1e-10)
396
+
397
+ @pytest.mark.slow
398
+ def test_memory_sparse_huge_dim(self, vec):
399
+ """Sparse multiplication at dim 2^20 must not OOM."""
400
+ dim = 1 << 20
401
+ a = np.zeros(dim); a[3] = 1.5; a[1000] = -2.0
402
+ b = np.zeros(dim); b[7] = 0.5; b[2000] = 3.0
403
+ start = time.perf_counter()
404
+ result = vec.multiply_arrays(a, b)
405
+ elapsed = time.perf_counter() - start
406
+ assert len(result) == dim
407
+ # Should be nearly instant due to sparsity
408
+ assert elapsed < 1.0, f"Sparse 2^20 took {elapsed:.3f}s"
409
+
410
+ def test_performance_not_python_loop(self, vec):
411
+ """Dense 512x512 must be far faster than a Python loop would be."""
412
+ dim = 512
413
+ a = np.random.randn(dim)
414
+ b = np.random.randn(dim)
415
+ start = time.perf_counter()
416
+ vec.multiply_arrays(a, b)
417
+ elapsed = time.perf_counter() - start
418
+ # A Python double-loop over 512^2=262k pairs takes >0.5s.
419
+ # SIMD should be well under that.
420
+ assert elapsed < 0.4, f"Took {elapsed:.3f}s — possible Python-loop regression"
@@ -0,0 +1,156 @@
1
+ import numpy as np
2
+ import pytest
3
+ import time
4
+
5
+ from hypercomplex_engine.core.fast.fast_standard import FastStandard
6
+ from hypercomplex_engine.core.vectorized.vectorized_standard import VectorizedStandard
7
+
8
+ @pytest.fixture
9
+ def engines():
10
+ return FastStandard(), VectorizedStandard()
11
+
12
+ # =============================================================================
13
+ # 1. THE MILLION-PAIR GAUNTLET (Indices Accuracy)
14
+ # =============================================================================
15
+ def test_multiply_indices_vec_randomized(engines):
16
+ """
17
+ Fires 100,000 random 60-bit indices at the SIMD engine and compares
18
+ every single sign and XOR index against the scalar FastStandard.
19
+ """
20
+ fast, vec = engines
21
+ np.random.seed(42)
22
+
23
+ i_arr = np.random.randint(0, 2**60, size=100_000, dtype=np.uint64)
24
+ j_arr = np.random.randint(0, 2**60, size=100_000, dtype=np.uint64)
25
+
26
+ gt_signs = np.zeros(100_000, dtype=np.int8)
27
+ gt_idxs = np.zeros(100_000, dtype=np.uint64)
28
+ for idx in range(100_000):
29
+ s, i = fast.multiply_indices(int(i_arr[idx]), int(j_arr[idx]))
30
+ gt_signs[idx] = s
31
+ gt_idxs[idx] = i
32
+
33
+ v_signs, v_idxs = vec.multiply_indices_vec(i_arr, j_arr)
34
+
35
+ np.testing.assert_array_equal(v_signs, gt_signs, err_msg="SIMD sign mismatch!")
36
+ np.testing.assert_array_equal(v_idxs, gt_idxs, err_msg="SIMD XOR index mismatch!")
37
+
38
+ # =============================================================================
39
+ # 2. THE EDGE-CASE MINEFIELD
40
+ # =============================================================================
41
+ def test_multiply_indices_vec_edge_cases(engines):
42
+ fast, vec = engines
43
+ i_arr = np.array([0, 1, 5, 10, 0, 7, 2**63 - 1], dtype=np.uint64)
44
+ j_arr = np.array([0, 1, 0, 10, 5, 7, 2**63 - 1], dtype=np.uint64)
45
+
46
+ gt_signs, gt_idxs = [], []
47
+ for i, j in zip(i_arr, j_arr):
48
+ s, idx = fast.multiply_indices(int(i), int(j))
49
+ gt_signs.append(s)
50
+ gt_idxs.append(idx)
51
+
52
+ v_signs, v_idxs = vec.multiply_indices_vec(i_arr, j_arr)
53
+ np.testing.assert_array_equal(v_signs, np.array(gt_signs, dtype=np.int8))
54
+ np.testing.assert_array_equal(v_idxs, np.array(gt_idxs, dtype=np.uint64))
55
+
56
+ # =============================================================================
57
+ # 3. POLYNOMIAL EQUIVALENCE (Dense Array Multiplication)
58
+ # =============================================================================
59
+ def test_multiply_arrays_dense_equivalence(engines):
60
+ fast, vec = engines
61
+ dim = 64
62
+ np.random.seed(99)
63
+ arr1 = np.random.randn(dim)
64
+ arr2 = np.random.randn(dim)
65
+
66
+ res_naive = np.zeros(dim, dtype=np.float64)
67
+ for i in range(dim):
68
+ for j in range(dim):
69
+ s, idx = fast.multiply_indices(i, j)
70
+ res_naive[idx] += s * arr1[i] * arr2[j]
71
+
72
+ res_vec = vec.multiply_arrays(arr1, arr2)
73
+ np.testing.assert_allclose(res_vec, res_naive, rtol=1e-12, atol=1e-12)
74
+
75
+ # =============================================================================
76
+ # 4. THE "XOR COLLISION" TRAP (CORRECTED FOR NON-COMMUTATIVITY)
77
+ # =============================================================================
78
+ def test_multiply_arrays_xor_collisions(engines):
79
+ """
80
+ Ensures np.add.at ACCUMULATES correctly for ALL pairs that map to the same XOR index.
81
+ """
82
+ fast, vec = engines
83
+ arr1 = np.zeros(8, dtype=np.float64)
84
+ arr2 = np.zeros(8, dtype=np.float64)
85
+
86
+ arr1[1] = 2.0; arr1[2] = 3.0; arr1[0] = 1.5; arr1[3] = -1.0
87
+ arr2[2] = 4.0; arr2[1] = 5.0; arr2[3] = 2.0; arr2[0] = -2.0
88
+
89
+ res_vec = vec.multiply_arrays(arr1, arr2)
90
+
91
+ # Calculate the EXACT expected sum for index 3 by checking ALL 8x8 pairs
92
+ expected_idx3 = 0.0
93
+ for i in range(8):
94
+ for j in range(8):
95
+ s, idx = fast.multiply_indices(i, j)
96
+ if idx == 3:
97
+ expected_idx3 += s * arr1[i] * arr2[j]
98
+
99
+ # The engine correctly calculated -2.0 (because e2*e1 = -e3, contributing -15.0)
100
+ assert np.isclose(res_vec[3], expected_idx3), f"Expected {expected_idx3}, got {res_vec[3]}"
101
+
102
+ # =============================================================================
103
+ # 5. ASYMMETRIC PADDING & SPARSITY (CORRECTED FOR OVERLAPS)
104
+ # =============================================================================
105
+ def test_multiply_arrays_asymmetric_padding(engines):
106
+ fast, vec = engines
107
+ arr1 = np.array([1.0, 2.0, 3.0])
108
+ arr2 = np.array([4.0, 5.0, 6.0, 7.0, 8.0])
109
+
110
+ res_vec = vec.multiply_arrays(arr1, arr2)
111
+ assert len(res_vec) == 8, "Failed to pad asymmetric arrays to power-of-2!"
112
+
113
+ # Calculate exact expected sum for index 1 (0^1, 1^0, 2^3, 3^2, etc.)
114
+ expected_idx1 = 0.0
115
+ for i in range(8):
116
+ for j in range(8):
117
+ s, idx = fast.multiply_indices(i, j)
118
+ if idx == 1:
119
+ # Use padded arrays for calculation
120
+ v1 = arr1[i] if i < len(arr1) else 0.0
121
+ v2 = arr2[j] if j < len(arr2) else 0.0
122
+ expected_idx1 += s * v1 * v2
123
+
124
+ # The engine correctly calculated 34.0 (because e2*e3 = +e1, contributing +21.0)
125
+ assert np.isclose(res_vec[1], expected_idx1), f"Expected {expected_idx1}, got {res_vec[1]}"
126
+
127
+ # =============================================================================
128
+ # 6. THE PERFORMANCE GATE (RELATIVE SPEEDUP)
129
+ # =============================================================================
130
+ def test_multiply_arrays_performance_gate(engines):
131
+ """
132
+ Compares SIMD against a small scalar baseline to prove it's not a Python loop.
133
+ """
134
+ fast, vec = engines
135
+ dim = 512 # 512x512 = 262,144 pairs
136
+ arr1 = np.random.randn(dim)
137
+ arr2 = np.random.randn(dim)
138
+
139
+ # Time SIMD
140
+ start = time.perf_counter()
141
+ vec.multiply_arrays(arr1, arr2)
142
+ time_simd = time.perf_counter() - start
143
+
144
+ # Time a small scalar batch (10,000 pairs) to establish baseline speed
145
+ start = time.perf_counter()
146
+ for i in range(100):
147
+ for j in range(100):
148
+ fast.multiply_indices(i, j)
149
+ time_scalar_10k = time.perf_counter() - start
150
+
151
+ # Extrapolate scalar time to 262,144 pairs
152
+ time_scalar_extrapolated = time_scalar_10k * (262144 / 10000)
153
+
154
+ # SIMD MUST be at least 2x faster than the extrapolated scalar loop
155
+ assert time_simd < (time_scalar_extrapolated / 2.0), \
156
+ f"SIMD took {time_simd:.3f}s, expected < {time_scalar_extrapolated/2.0:.3f}s (half of scalar time)"