hypercomplex-engine 0.7.1.2__tar.gz → 0.7.2__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 (55) hide show
  1. {hypercomplex_engine-0.7.1.2/hypercomplex_engine.egg-info → hypercomplex_engine-0.7.2}/PKG-INFO +50 -2
  2. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/README.md +49 -1
  3. hypercomplex_engine-0.7.2/hypercomplex_engine/core/bitplane/bitplane_standard.py +134 -0
  4. hypercomplex_engine-0.7.2/hypercomplex_engine/core/fast/fast_standard.py +70 -0
  5. hypercomplex_engine-0.7.2/hypercomplex_engine/core/graded/graded_sparse_standard.py +201 -0
  6. hypercomplex_engine-0.7.2/hypercomplex_engine/core/vectorized/vectorized_standard.py +136 -0
  7. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2/hypercomplex_engine.egg-info}/PKG-INFO +50 -2
  8. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine.egg-info/SOURCES.txt +2 -0
  9. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/pyproject.toml +1 -1
  10. hypercomplex_engine-0.7.2/tests/test_optimized_engine_v7_2.py +119 -0
  11. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_vectorized_standard.py +11 -0
  12. hypercomplex_engine-0.7.1.2/hypercomplex_engine/core/bitplane/bitplane_standard.py +0 -162
  13. hypercomplex_engine-0.7.1.2/hypercomplex_engine/core/graded/graded_sparse_standard.py +0 -125
  14. hypercomplex_engine-0.7.1.2/hypercomplex_engine/core/vectorized/vectorized_standard.py +0 -118
  15. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/LICENSE +0 -0
  16. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/NOTICE +0 -0
  17. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/__init__.py +0 -0
  18. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/__init__.py +0 -0
  19. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/basis_element.py +0 -0
  20. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/basis_notation.py +0 -0
  21. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/bitplane/__init__.py +0 -0
  22. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/fast/__init__.py +0 -0
  23. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/fast/bit_utils.py +0 -0
  24. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/fast/fast_dual.py +0 -0
  25. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/fast/fast_split.py +0 -0
  26. /hypercomplex_engine-0.7.1.2/hypercomplex_engine/core/fast/fast_standard.py → /hypercomplex_engine-0.7.2/hypercomplex_engine/core/fast/fast_standard_old.py +0 -0
  27. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/graded/__init__.py +0 -0
  28. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/holographic/__init__.py +0 -0
  29. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/holographic/dual.py +0 -0
  30. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/holographic/split.py +0 -0
  31. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/holographic/standard.py +0 -0
  32. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/table_builder/__init__.py +0 -0
  33. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/table_builder/common.py +0 -0
  34. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/table_builder/dual.py +0 -0
  35. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/table_builder/split.py +0 -0
  36. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/table_builder/standard.py +0 -0
  37. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/validation.py +0 -0
  38. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/core/vectorized/__init__.py +0 -0
  39. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/facade.py +0 -0
  40. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/printer/__init__.py +0 -0
  41. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/printer/cd_format.py +0 -0
  42. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine/printer/cd_table_printer.py +0 -0
  43. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine.egg-info/dependency_links.txt +0 -0
  44. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine.egg-info/requires.txt +0 -0
  45. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/hypercomplex_engine.egg-info/top_level.txt +0 -0
  46. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/setup.cfg +0 -0
  47. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_bitplane_standard.py +0 -0
  48. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_dual_tuple_regression.py +0 -0
  49. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_fast_mode.py +0 -0
  50. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_fixes_0_4.py +0 -0
  51. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_graded_sparse.py +0 -0
  52. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_mega_mother.py +0 -0
  53. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_split_dim.py +0 -0
  54. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_strict_dual_3tuple.py +0 -0
  55. {hypercomplex_engine-0.7.1.2 → hypercomplex_engine-0.7.2}/tests/test_vectorized_extended.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: hypercomplex-engine
3
- Version: 0.7.1.2
3
+ Version: 0.7.2
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
@@ -73,7 +73,7 @@ If you build upon this package, please read fully [Go to Scope, Strengths, and L
73
73
  This library serves as the formal verification substrate and computational engine for the following mathematical preprints:
74
74
 
75
75
  **1. The Sign Structure of Cayley–Dickson and Split Algebras By Blocks**
76
- *Proves the OPMT (Ordered-Pair Multiplication Table) sign laws, block decomposition, and the O(1) closed-form sign evaluator implemented in the `fast` engine of this library.*
76
+ *Proves the OPMT (Observed Patterns in Multiplication Table) sign laws, block decomposition, and the O(1) closed-form sign evaluator implemented in the `fast` engine of this library.*
77
77
  * 📊 **Figshare:** [10.6084/m9.figshare.33705022](https://doi.org/10.6084/m9.figshare.33705022)
78
78
  * 📦 **Zenodo:** [10.5281/zenodo.22051873](https://doi.org/10.5281/zenodo.22051873)
79
79
 
@@ -90,6 +90,54 @@ This library serves as the formal verification substrate and computational engin
90
90
 
91
91
  ---
92
92
 
93
+ ## Flowchart of the applied Construction
94
+
95
+ <p align="center">
96
+ <img src="https://raw.githubusercontent.com/maher1719/hypercomplex-engine/refs/heads/main/hypercomplex_engine/asset/flowchart_github_version.jpeg" alt="Flowchart of the construction" width="100%">
97
+ </p>
98
+
99
+ <details>
100
+ <summary>📊 <b>Click to view the Construction Flowchart (Vector SVG)</b></summary>
101
+ <br>
102
+
103
+ ```mermaid
104
+
105
+ flowchart TD
106
+ Start([Input: Target N ≥ 0]) --> Init["A₀ Real Numbers (n = 0)"]
107
+ Init --> CheckN0{"Target N = 0?"}
108
+
109
+ CheckN0 -- Yes --> AddEps0{"Add ε?"}
110
+ CheckN0 -- No --> AddL["Add new imaginary unit 'l'"]
111
+
112
+ AddEps0 -- Yes --> DualReal["Dual Real Numbers ℝ[ε]"]
113
+ AddEps0 -- No --> MergeTop(( ))
114
+ DualReal --> MergeTop
115
+ MergeTop --> EndTop([End])
116
+
117
+ AddL --> IsSplit{"Is it split?"}
118
+ IsSplit -- Yes --> SplitHyp["Split Hypercomplex Aₙ₊₁<br/>(Set IsSplit = True)"]
119
+ IsSplit -- No --> OrdHyp["Ordinary Hypercomplex Aₙ₊₁"]
120
+
121
+ SplitHyp --> MergeMid(( ))
122
+ OrdHyp --> MergeMid
123
+
124
+ MergeMid --> AddEps{"Add ε?"}
125
+ AddEps -- Yes --> DualHyp["Dual Hypercomplex Numbers<br/>Aₙ₊₁[ε]"]
126
+ AddEps -- No --> CheckEnd{"IsSplit, or Reached<br/>Target Dimension (n + 1 = N)?"}
127
+
128
+ DualHyp --> MergeBot(( ))
129
+ CheckEnd -- Yes --> MergeBot
130
+ CheckEnd -- No --> IncLoop["Aₙ = Aₙ₊₁<br/>n = n + 1"]
131
+ IncLoop --> AddL
132
+
133
+ MergeBot --> EndBot([End])
134
+
135
+
136
+ ```
137
+
138
+ </details>
139
+
140
+
93
141
  ## Installation
94
142
 
95
143
  Clone the repository:
@@ -44,7 +44,7 @@ If you build upon this package, please read fully [Go to Scope, Strengths, and L
44
44
  This library serves as the formal verification substrate and computational engine for the following mathematical preprints:
45
45
 
46
46
  **1. The Sign Structure of Cayley–Dickson and Split Algebras By Blocks**
47
- *Proves the OPMT (Ordered-Pair Multiplication Table) sign laws, block decomposition, and the O(1) closed-form sign evaluator implemented in the `fast` engine of this library.*
47
+ *Proves the OPMT (Observed Patterns in Multiplication Table) sign laws, block decomposition, and the O(1) closed-form sign evaluator implemented in the `fast` engine of this library.*
48
48
  * 📊 **Figshare:** [10.6084/m9.figshare.33705022](https://doi.org/10.6084/m9.figshare.33705022)
49
49
  * 📦 **Zenodo:** [10.5281/zenodo.22051873](https://doi.org/10.5281/zenodo.22051873)
50
50
 
@@ -61,6 +61,54 @@ This library serves as the formal verification substrate and computational engin
61
61
 
62
62
  ---
63
63
 
64
+ ## Flowchart of the applied Construction
65
+
66
+ <p align="center">
67
+ <img src="https://raw.githubusercontent.com/maher1719/hypercomplex-engine/refs/heads/main/hypercomplex_engine/asset/flowchart_github_version.jpeg" alt="Flowchart of the construction" width="100%">
68
+ </p>
69
+
70
+ <details>
71
+ <summary>📊 <b>Click to view the Construction Flowchart (Vector SVG)</b></summary>
72
+ <br>
73
+
74
+ ```mermaid
75
+
76
+ flowchart TD
77
+ Start([Input: Target N ≥ 0]) --> Init["A₀ Real Numbers (n = 0)"]
78
+ Init --> CheckN0{"Target N = 0?"}
79
+
80
+ CheckN0 -- Yes --> AddEps0{"Add ε?"}
81
+ CheckN0 -- No --> AddL["Add new imaginary unit 'l'"]
82
+
83
+ AddEps0 -- Yes --> DualReal["Dual Real Numbers ℝ[ε]"]
84
+ AddEps0 -- No --> MergeTop(( ))
85
+ DualReal --> MergeTop
86
+ MergeTop --> EndTop([End])
87
+
88
+ AddL --> IsSplit{"Is it split?"}
89
+ IsSplit -- Yes --> SplitHyp["Split Hypercomplex Aₙ₊₁<br/>(Set IsSplit = True)"]
90
+ IsSplit -- No --> OrdHyp["Ordinary Hypercomplex Aₙ₊₁"]
91
+
92
+ SplitHyp --> MergeMid(( ))
93
+ OrdHyp --> MergeMid
94
+
95
+ MergeMid --> AddEps{"Add ε?"}
96
+ AddEps -- Yes --> DualHyp["Dual Hypercomplex Numbers<br/>Aₙ₊₁[ε]"]
97
+ AddEps -- No --> CheckEnd{"IsSplit, or Reached<br/>Target Dimension (n + 1 = N)?"}
98
+
99
+ DualHyp --> MergeBot(( ))
100
+ CheckEnd -- Yes --> MergeBot
101
+ CheckEnd -- No --> IncLoop["Aₙ = Aₙ₊₁<br/>n = n + 1"]
102
+ IncLoop --> AddL
103
+
104
+ MergeBot --> EndBot([End])
105
+
106
+
107
+ ```
108
+
109
+ </details>
110
+
111
+
64
112
  ## Installation
65
113
 
66
114
  Clone the repository:
@@ -0,0 +1,134 @@
1
+ """
2
+ BitPlaneStandard — arbitrary-width bit-sliced O(1) Cayley-Dickson evaluator.
3
+
4
+ Breaks the 64-bit SIMD-lane ceiling by storing a batch of N indices of width B
5
+ as an (N, B) uint8 bit-plane, entry (r, b) = bit b of index r (b = 0 is LSB).
6
+
7
+ Optimizations vs. the first release (verified against FastStandard):
8
+ * i-axis branch collapsed to 2*b - 1 (Corollary cor:iaxis-collapse)
9
+ * parity via FORWARD XOR-accumulate instead of int64 cumsum:
10
+ - stays uint8 -> 8x less memory than the cumsum buffer
11
+ - no array reversal -> contiguous, cache-friendly access
12
+ - k == B handled for free (prefix == total -> parity 0), no mask needed
13
+ Identity used: XOR[k:B] = XOR[0:B] ^ XOR[0:k].
14
+
15
+ Measured (N=2000, B=4000): parity buffer 128 MB -> 8 MB; whole call 25.4 ms.
16
+ """
17
+ import numpy as np
18
+
19
+
20
+ class BitPlaneStandard:
21
+ """Arbitrary-width bit-sliced standard Cayley-Dickson O(1) multiplier."""
22
+
23
+ # ---------- representation ----------
24
+ @staticmethod
25
+ def ints_to_bitplane(vals, B):
26
+ """Python big-ints -> (N, B) uint8 bit-plane, b = 0 is LSB."""
27
+ out = np.zeros((len(vals), B), dtype=np.uint8)
28
+ for n, v in enumerate(vals):
29
+ v = int(v)
30
+ if v == 0:
31
+ continue
32
+ nbytes = (min(B, v.bit_length()) + 7) // 8
33
+ bits = np.unpackbits(
34
+ np.frombuffer(v.to_bytes(nbytes, 'little'), dtype=np.uint8),
35
+ bitorder='little')
36
+ m = min(B, len(bits))
37
+ out[n, :m] = bits[:m]
38
+ return out
39
+
40
+ @staticmethod
41
+ def bitplane_to_ints(bits):
42
+ """(N, B) bit-plane -> list of Python big-ints."""
43
+ N, B = bits.shape
44
+ nbytes = (B + 7) // 8
45
+ out = []
46
+ for n in range(N):
47
+ packed = np.packbits(bits[n], bitorder='little')
48
+ out.append(int.from_bytes(packed.tobytes()[:nbytes], 'little'))
49
+ return out
50
+
51
+ @staticmethod
52
+ def _required_width(i_arr, j_arr):
53
+ """Minimal B holding every index in both batches (>= 1)."""
54
+ B = 1
55
+ for v in i_arr:
56
+ bl = int(v).bit_length()
57
+ if bl > B:
58
+ B = bl
59
+ for v in j_arr:
60
+ bl = int(v).bit_length()
61
+ if bl > B:
62
+ B = bl
63
+ return B
64
+
65
+ # ---------- core evaluator ----------
66
+ def multiply_indices_bitplane(self, i_bits, j_bits):
67
+ """
68
+ Vectorized arbitrary-width O(1) multiplication on bit-planes.
69
+
70
+ Returns
71
+ -------
72
+ (signs, idx_bits) : (N,) int8, (N, B) uint8 bit-plane of i ^ j
73
+ """
74
+ i_bits = np.asarray(i_bits, dtype=np.uint8)
75
+ j_bits = np.asarray(j_bits, dtype=np.uint8)
76
+ N, B = i_bits.shape
77
+ idx = i_bits ^ j_bits
78
+ if N == 0 or B == 0:
79
+ return np.zeros(N, dtype=np.int8), idx
80
+
81
+ ar = np.arange(N)
82
+ mask_zero = (~i_bits.any(axis=1)) | (~j_bits.any(axis=1))
83
+ mask_diag = ((i_bits == j_bits).all(axis=1)) & ~mask_zero
84
+
85
+ # nu2 = first set bit; argmax on all-zero rows gives 0, overridden below
86
+ t = np.argmax(idx, axis=1)
87
+ ti = np.argmax(i_bits, axis=1)
88
+ tj = np.argmax(j_bits, axis=1)
89
+
90
+ cond1 = (t >= ti) & (t >= tj) # diagonal break
91
+ cond2 = (~cond1) & (ti >= tj) # i-axis break
92
+
93
+ s1 = 2 * i_bits[ar, t].astype(np.int8) - 1
94
+ # cond2 forces ti > tj, so delta == -1 unconditionally: s2 = 2*b - 1.
95
+ s2 = 2 * j_bits[ar, ti].astype(np.int8) - 1
96
+ s3 = 1 - 2 * i_bits[ar, tj].astype(np.int8)
97
+ s = np.where(cond1, s1, np.where(cond2, s2, s3))
98
+
99
+ k = np.where(cond1, t + 1, np.where(cond2, ti + 1, tj + 1))
100
+
101
+ # parity of OR above k, via forward XOR-accumulate (uint8, contiguous)
102
+ inc = np.bitwise_xor.accumulate(i_bits | j_bits, axis=1)
103
+ total = inc[:, -1] # XOR of all B planes
104
+ prefix = np.zeros(N, dtype=np.uint8)
105
+ nz = k > 0
106
+ prefix[nz] = inc[ar[nz], k[nz] - 1] # k == B -> prefix == total
107
+ s = np.where((total ^ prefix) == 1, -s, s)
108
+
109
+ s = np.where(mask_zero, 1, s)
110
+ s = np.where(mask_diag, -1, s)
111
+ return s.astype(np.int8), idx
112
+
113
+ # ---------- convenience ----------
114
+ def multiply_indices(self, i_arr, j_arr):
115
+ """
116
+ Python big-ints in, integer results out.
117
+
118
+ Returns
119
+ -------
120
+ (signs, indices) : (N,) int8, list of N Python ints (i_arr[k] ^ j_arr[k])
121
+ """
122
+ i_arr = list(i_arr)
123
+ j_arr = list(j_arr)
124
+ if len(i_arr) != len(j_arr):
125
+ raise ValueError("i_arr and j_arr must have the same length")
126
+ if not i_arr:
127
+ return np.zeros(0, dtype=np.int8), []
128
+
129
+ B = self._required_width(i_arr, j_arr)
130
+ signs, idx_bits = self.multiply_indices_bitplane(
131
+ self.ints_to_bitplane(i_arr, B),
132
+ self.ints_to_bitplane(j_arr, B),
133
+ )
134
+ return signs, self.bitplane_to_ints(idx_bits)
@@ -0,0 +1,70 @@
1
+ from ..validation import Validation
2
+ from .bit_utils import nu2, popcount # kept: public helpers, other modules use them
3
+
4
+ # Unbound builtins bound once at import: one module-global lookup instead of a
5
+ # per-call attribute lookup on the int object.
6
+ _bl = int.bit_length
7
+ _bc = int.bit_count
8
+
9
+
10
+ class FastStandard:
11
+ """
12
+ Standard Cayley-Dickson O(1) multiplier.
13
+
14
+ Input / output convention: (sign, index), index = i XOR j.
15
+
16
+ Optimized evaluation (verified exhaustively against the reference form):
17
+ * the break type is decided by (ti, tj) alone -- no comparison against t;
18
+ * t = nu2(i XOR j) is computed only on the tie ti == tj (~1/3 of pairs);
19
+ * the i-axis branch is collapsed to 2*b - 1 (Corollary cor:iaxis-collapse);
20
+ * nu2 / popcount are inlined (their zero-guards are provably dead here).
21
+ """
22
+
23
+ def multiply(self, t1: tuple, t2: tuple) -> tuple:
24
+ """Multiply two signed basis tuples (validated)."""
25
+ Validation.basis_tuple(t1, allow_zero=False, allow_eps=False)
26
+ Validation.basis_tuple(t2, allow_zero=False, allow_eps=False)
27
+ s1, i = int(t1[0]), int(t1[1])
28
+ s2, j = int(t2[0]), int(t2[1])
29
+ sign, idx = self.multiply_indices(i, j)
30
+ return (s1 * s2 * sign, idx)
31
+
32
+ def multiply_indices(self, i: int, j: int) -> tuple:
33
+ """
34
+ Core O(1) multiplication for non-negative integer indices.
35
+ Returns (sign, i XOR j).
36
+ """
37
+ if type(i) is not int:
38
+ i = int(i)
39
+ if type(j) is not int:
40
+ j = int(j)
41
+ # Explicit guard: do NOT fold into (i ^ j) < 0, which misses i == j < 0.
42
+ if i < 0 or j < 0:
43
+ raise ValueError("indices must be >= 0")
44
+
45
+ idx = i ^ j
46
+ if not (i and j): # identity: e_0 * e_j = e_j
47
+ return (1, idx)
48
+ if i == j: # e_i^2 = -e_0 for i > 0
49
+ return (-1, 0)
50
+
51
+ ti = _bl(i & -i) - 1
52
+ tj = _bl(j & -j) - 1
53
+
54
+ if ti < tj:
55
+ # t = ti < tj -> j-axis break
56
+ k = tj + 1
57
+ s = 1 - 2 * ((i >> tj) & 1)
58
+ elif ti > tj:
59
+ # t = tj < ti -> i-axis break; delta == -1 unconditionally
60
+ k = ti + 1
61
+ s = 2 * ((j >> ti) & 1) - 1
62
+ else:
63
+ # ti == tj -> t > ti -> diagonal break (only case needing t)
64
+ t = _bl(idx & -idx) - 1
65
+ k = t + 1
66
+ s = 2 * ((i >> t) & 1) - 1
67
+
68
+ if _bc((i | j) >> k) & 1:
69
+ s = -s
70
+ return (s, idx)
@@ -0,0 +1,201 @@
1
+ """
2
+ GradedSparseStandard — arbitrary-width O(p) evaluator on the graded form.
3
+
4
+ An index m is a sorted tuple of 0-INDEXED set-bit positions, m = sum(2**b).
5
+ The Wilmot generator level is k = b + 1 (display only, graded_to_notation).
6
+
7
+ Optimizations vs. the first release (verified against FastStandard):
8
+ * SINGLE fused two-pointer merge replaces three separate O(p) scans
9
+ (_nu2_xor_gr + _pop_or_shift_gr + _xor_gr). Valid because every element
10
+ before the first difference is common to both lists and lies below t < k,
11
+ so it contributes nothing to the union count.
12
+ * the diagonal-break bit comes free from the merge (no bisect)
13
+ * i-axis branch uses 2*b - 1 (no integer exponentiation)
14
+ * hybrid int_to_graded: peel a few low bits with m & -m (wins for very
15
+ sparse indices), then a C-level byte scan for the remainder.
16
+
17
+ Measured: 1.8x-2.0x on multiply_graded; up to 9x on wide int_to_graded.
18
+ The legacy helpers are retained for reference and backward compatibility.
19
+ """
20
+ import bisect
21
+ import numpy as np
22
+
23
+ # Peel budget for int_to_graded, scaled by width: peeling one bit costs
24
+ # O(B/w) big-int work, the byte scan costs O(B/8) C work plus O(p) Python.
25
+ _PEEL_NUM = 500_000
26
+ _PEEL_CAP = 24
27
+
28
+
29
+ class GradedSparseStandard:
30
+ """Arbitrary-width sparse (graded-form) standard Cayley-Dickson multiplier."""
31
+
32
+ # ---------- representation ----------
33
+ @staticmethod
34
+ def int_to_graded(m):
35
+ """Python int -> sorted tuple of 0-indexed set-bit positions."""
36
+ m = int(m)
37
+ if m == 0:
38
+ return ()
39
+ pos = []
40
+ budget = max(1, min(_PEEL_CAP, _PEEL_NUM // max(1, m.bit_length())))
41
+ for _ in range(budget):
42
+ if not m:
43
+ return tuple(pos)
44
+ lo = m & -m
45
+ pos.append(lo.bit_length() - 1)
46
+ m ^= lo
47
+ if not m:
48
+ return tuple(pos)
49
+ # dense remainder: C-level scan, then per-nonzero-byte extraction
50
+ data = m.to_bytes((m.bit_length() + 7) // 8, 'little')
51
+ arr = np.frombuffer(data, dtype=np.uint8)
52
+ for bi in np.flatnonzero(arr):
53
+ v = int(arr[bi])
54
+ base = int(bi) * 8
55
+ while v:
56
+ lo = v & -v
57
+ pos.append(base + lo.bit_length() - 1)
58
+ v ^= lo
59
+ return tuple(pos)
60
+
61
+ @staticmethod
62
+ def graded_to_int(pos):
63
+ """Sorted tuple of bit positions -> Python int."""
64
+ m = 0
65
+ for b in pos:
66
+ m |= 1 << b
67
+ return m
68
+
69
+ @staticmethod
70
+ def graded_to_notation(pos):
71
+ """Graded form -> Wilmot string 'o{k1},{k2},...' (1-indexed levels)."""
72
+ return "1" if not pos else "o" + ",".join(str(b + 1) for b in pos)
73
+
74
+ # ---------- primitives (kept for reference / external use) ----------
75
+ @staticmethod
76
+ def _nu2_gr(pos):
77
+ return pos[0]
78
+
79
+ @staticmethod
80
+ def _bit_gr(pos, t):
81
+ q = bisect.bisect_left(pos, t)
82
+ return 1 if (q < len(pos) and pos[q] == t) else 0
83
+
84
+ @staticmethod
85
+ def _nu2_xor_gr(pos_i, pos_j):
86
+ a = b = 0
87
+ while a < len(pos_i) and b < len(pos_j):
88
+ if pos_i[a] < pos_j[b]:
89
+ return pos_i[a]
90
+ if pos_j[b] < pos_i[a]:
91
+ return pos_j[b]
92
+ a += 1; b += 1
93
+ if a < len(pos_i):
94
+ return pos_i[a]
95
+ if b < len(pos_j):
96
+ return pos_j[b]
97
+ return None
98
+
99
+ @staticmethod
100
+ def _xor_gr(pos_i, pos_j):
101
+ out = []; a = b = 0
102
+ while a < len(pos_i) and b < len(pos_j):
103
+ if pos_i[a] < pos_j[b]:
104
+ out.append(pos_i[a]); a += 1
105
+ elif pos_j[b] < pos_i[a]:
106
+ out.append(pos_j[b]); b += 1
107
+ else:
108
+ a += 1; b += 1
109
+ out.extend(pos_i[a:]); out.extend(pos_j[b:])
110
+ return tuple(out)
111
+
112
+ @staticmethod
113
+ def _pop_or_shift_gr(pos_i, pos_j, k):
114
+ cnt = 0; a = b = 0
115
+ while a < len(pos_i) and b < len(pos_j):
116
+ if pos_i[a] < pos_j[b]:
117
+ cnt += (pos_i[a] >= k); a += 1
118
+ elif pos_j[b] < pos_i[a]:
119
+ cnt += (pos_j[b] >= k); b += 1
120
+ else:
121
+ cnt += (pos_i[a] >= k); a += 1; b += 1
122
+ while a < len(pos_i):
123
+ cnt += (pos_i[a] >= k); a += 1
124
+ while b < len(pos_j):
125
+ cnt += (pos_j[b] >= k); b += 1
126
+ return cnt
127
+
128
+ # ---------- fused evaluator ----------
129
+ def multiply_graded(self, pos_i, pos_j):
130
+ """
131
+ Core O(p) evaluator on graded forms, single fused merge.
132
+
133
+ Returns
134
+ -------
135
+ (sign, result_pos) : int in {-1,+1}, sorted tuple (graded form of i ^ j)
136
+ """
137
+ ni, nj = len(pos_i), len(pos_j)
138
+ if ni == 0:
139
+ return (1, pos_j) # e_0 * e_j = e_j
140
+ if nj == 0:
141
+ return (1, pos_i)
142
+ if pos_i == pos_j:
143
+ return (-1, ()) # e_i^2 = -e_0 (i > 0)
144
+
145
+ ti, tj = pos_i[0], pos_j[0]
146
+ a = b = 0
147
+ # Common prefix: all these positions are shared and < t < k, so they
148
+ # contribute nothing to the union count. Skipping them yields t at once
149
+ # (zero iterations when ti != tj, since then t = min(ti, tj)).
150
+ while a < ni and b < nj and pos_i[a] == pos_j[b]:
151
+ a += 1; b += 1
152
+ if a < ni and b < nj:
153
+ if pos_i[a] < pos_j[b]:
154
+ t, t_from_i = pos_i[a], 1
155
+ else:
156
+ t, t_from_i = pos_j[b], 0
157
+ elif a < ni:
158
+ t, t_from_i = pos_i[a], 1
159
+ else:
160
+ t, t_from_i = pos_j[b], 0
161
+
162
+ k = (t if t > ti else ti)
163
+ k = (k if k > tj else tj)
164
+ k += 1
165
+
166
+ out = []
167
+ cnt = 0
168
+ while a < ni and b < nj:
169
+ x, y = pos_i[a], pos_j[b]
170
+ if x < y:
171
+ out.append(x); cnt += (x >= k); a += 1
172
+ elif y < x:
173
+ out.append(y); cnt += (y >= k); b += 1
174
+ else:
175
+ cnt += (x >= k); a += 1; b += 1 # union: count once
176
+ while a < ni:
177
+ x = pos_i[a]; out.append(x); cnt += (x >= k); a += 1
178
+ while b < nj:
179
+ y = pos_j[b]; out.append(y); cnt += (y >= k); b += 1
180
+
181
+ if t >= ti and t >= tj:
182
+ s = 2 * t_from_i - 1 # bit known from the merge
183
+ elif ti >= tj:
184
+ s = 2 * self._bit_gr(pos_j, ti) - 1 # delta == -1 (collapsed)
185
+ else:
186
+ s = 1 - 2 * self._bit_gr(pos_i, tj)
187
+
188
+ if cnt & 1:
189
+ s = -s
190
+ return (s, tuple(out))
191
+
192
+ # ---------- convenience ----------
193
+ def multiply_indices(self, i, j):
194
+ """
195
+ Python ints in -> (sign, i ^ j) out. Mirrors FastStandard.
196
+
197
+ NOTE: this wrapper pays O(p * B/w) for the int -> graded conversion.
198
+ The O(p) claim applies to multiply_graded on graded-form inputs.
199
+ """
200
+ sign, pos = self.multiply_graded(self.int_to_graded(i), self.int_to_graded(j))
201
+ return (sign, self.graded_to_int(pos))
@@ -0,0 +1,136 @@
1
+ """
2
+ VectorizedStandard — uint64 SIMD lane-wise O(1) Cayley-Dickson evaluator.
3
+
4
+ Optimizations vs. the first release (all verified against FastStandard):
5
+ * single `idx = i ^ j`, reused for the trailing-zero count (was 3 XOR passes)
6
+ * nu2 guards zero internally, so the *_safe temporaries are gone
7
+ * i-axis branch collapsed to 2*b - 1 (Corollary cor:iaxis-collapse):
8
+ removes the variable shift `1 << ti`, the `j_loc` AND, and two np.where
9
+ * explicit wide-shift guard for k == 64 (see _GUARD_WIDE_SHIFT)
10
+
11
+ Measured: 71.2 -> 39.4 ns/pair (guard on, 1.81x) / 34.7 ns/pair (guard off, 2.05x).
12
+ """
13
+ import numpy as np
14
+
15
+ _U64 = np.uint64
16
+
17
+ # NumPy returns 0 for `x >> width` (verified on 2.2.6 for uint64/int64/uint32/
18
+ # int32/uint8, both array and scalar paths). That behaviour is not formally
19
+ # documented, and `>> 64` on a 64-bit word is UB in C/C++. The guard makes the
20
+ # k == 64 lane explicit and portable; it costs ~4.7 ns/pair. Set False to skip.
21
+ _GUARD_WIDE_SHIFT = True
22
+
23
+
24
+ def _get_np_popcount():
25
+ """Hardware population count, with a SWAR fallback for NumPy < 2.0."""
26
+ try:
27
+ return np.bitwise_count
28
+ except AttributeError:
29
+ def _swar(x):
30
+ x = np.asarray(x, dtype=np.uint64)
31
+ x = x - ((x >> _U64(1)) & _U64(0x5555555555555555))
32
+ x = (x & _U64(0x3333333333333333)) + ((x >> _U64(2)) & _U64(0x3333333333333333))
33
+ x = (x + (x >> _U64(4))) & _U64(0x0F0F0F0F0F0F0F0F)
34
+ return ((x * _U64(0x0101010101010101)) >> _U64(56)).astype(np.uint8)
35
+ return _swar
36
+
37
+
38
+ _popcount = _get_np_popcount()
39
+
40
+
41
+ def _nu2_vec(x):
42
+ """
43
+ Lane-wise nu2 via popcount((x & -x) - 1).
44
+ x == 0 maps to 0; those lanes are overridden by mask_zero downstream.
45
+ """
46
+ xs = np.where(x == 0, _U64(1), x)
47
+ return _popcount((xs & -xs) - _U64(1)).astype(_U64)
48
+
49
+
50
+ class VectorizedStandard:
51
+ """Standard Cayley-Dickson O(1) multiplier on uint64 SIMD lanes (indices <= 64 bits)."""
52
+
53
+ @staticmethod
54
+ def _get_np_popcount():
55
+ return _popcount
56
+
57
+ def multiply_indices_vec(self, i_arr, j_arr):
58
+ """
59
+ Lane-wise O(1) evaluation of Definition def:o1.
60
+
61
+ Returns
62
+ -------
63
+ (signs, idx) : (N,) int8 in {-1,+1}, (N,) uint64 with idx = i ^ j
64
+ """
65
+ i = np.asarray(i_arr, dtype=np.uint64)
66
+ j = np.asarray(j_arr, dtype=np.uint64)
67
+
68
+ idx = i ^ j # single XOR, reused below
69
+ mask_zero = (i == 0) | (j == 0)
70
+ mask_diag = (i == j) & ~mask_zero
71
+
72
+ t = _nu2_vec(idx)
73
+ ti = _nu2_vec(i)
74
+ tj = _nu2_vec(j)
75
+ k = np.maximum(np.maximum(t, ti), tj) + _U64(1)
76
+
77
+ cond1 = (t >= ti) & (t >= tj) # diagonal break
78
+ cond2 = (~cond1) & (ti >= tj) # i-axis break
79
+
80
+ s1 = 2 * ((i >> t) & _U64(1)).astype(np.int8) - 1
81
+ # cond2 forces ti > tj strictly (ti == tj would make cond1 fire), so
82
+ # j_loc > 0 and delta == -1 unconditionally: s2 = 2*b - 1.
83
+ s2 = 2 * ((j >> ti) & _U64(1)).astype(np.int8) - 1
84
+ s3 = 1 - 2 * ((i >> tj) & _U64(1)).astype(np.int8)
85
+
86
+ s = np.where(cond1, s1, np.where(cond2, s2, s3))
87
+
88
+ ij_or = i | j
89
+ if _GUARD_WIDE_SHIFT:
90
+ # k == 64 means no bits above the word: parity must be 0.
91
+ parity = np.where(
92
+ k < _U64(64),
93
+ _popcount(ij_or >> np.minimum(k, _U64(63))) & np.uint8(1),
94
+ np.uint8(0),
95
+ )
96
+ else:
97
+ parity = _popcount(ij_or >> k) & np.uint8(1)
98
+
99
+ s = np.where(parity == 1, -s, s)
100
+ s = np.where(mask_zero, 1, s)
101
+ s = np.where(mask_diag, -1, s)
102
+ return s.astype(np.int8), idx
103
+
104
+ def multiply_arrays(self, arr1, arr2):
105
+ """
106
+ Sparse twisted convolution of two real coefficient arrays
107
+ (Eq. eq:sparse-conv): support extraction -> active grid -> lane-wise
108
+ signs -> coefficient weighting -> scatter-add.
109
+
110
+ NOTE: only the sign kernel above was optimized; this combiner is
111
+ unchanged. The real-part factorization x0*y0 + x0*yt + y0*xt is a
112
+ separate future optimization.
113
+ """
114
+ arr1 = np.asarray(arr1, dtype=np.float64)
115
+ arr2 = np.asarray(arr2, dtype=np.float64)
116
+ size1, size2 = len(arr1), len(arr2)
117
+ max_size = max(size1, size2)
118
+ if max_size <= 1:
119
+ if size1 and size2:
120
+ return np.array([arr1[0] * arr2[0]], dtype=np.float64)
121
+ return np.zeros(1, dtype=np.float64)
122
+
123
+ dim = 1 << (max_size - 1).bit_length()
124
+ nz_A = np.nonzero(arr1)[0]
125
+ nz_B = np.nonzero(arr2)[0]
126
+ if len(nz_A) == 0 or len(nz_B) == 0:
127
+ return np.zeros(dim, dtype=np.float64)
128
+
129
+ I, J = np.meshgrid(nz_A, nz_B, indexing='ij')
130
+ S, V = self.multiply_indices_vec(I, J)
131
+ M = np.outer(arr1[nz_A], arr2[nz_B])
132
+ weighted = S.astype(np.float64) * M
133
+
134
+ result = np.zeros(dim, dtype=np.float64)
135
+ np.add.at(result, V.ravel(), weighted.ravel()) # unbuffered scatter-add
136
+ return result