numga 2.0.0__py3-none-any.whl
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.
- numga/__init__.py +71 -0
- numga/algebra/__init__.py +6 -0
- numga/algebra/algebra.py +580 -0
- numga/algebra/bitops.py +88 -0
- numga/algebra/description.py +190 -0
- numga/algebra/self_product.py +58 -0
- numga/algebras.py +120 -0
- numga/backend/__init__.py +7 -0
- numga/backend/context.py +323 -0
- numga/backend/dense.py +183 -0
- numga/backend/exact.py +171 -0
- numga/backend/jax.py +265 -0
- numga/backend/numpy.py +144 -0
- numga/backend/sparse.py +164 -0
- numga/backend/torch.py +286 -0
- numga/binding.py +320 -0
- numga/expression.py +210 -0
- numga/extension.py +230 -0
- numga/extensions/__init__.py +3 -0
- numga/extensions/_linalg.py +63 -0
- numga/extensions/_scalar_functions.py +23 -0
- numga/extensions/arithmetic.py +130 -0
- numga/extensions/coefficients.py +18 -0
- numga/extensions/decompose.py +91 -0
- numga/extensions/fields.py +373 -0
- numga/extensions/forms.py +183 -0
- numga/extensions/grade_transforms.py +50 -0
- numga/extensions/invariant_decomposition.py +243 -0
- numga/extensions/inverse.py +186 -0
- numga/extensions/logexp.py +230 -0
- numga/extensions/norms.py +103 -0
- numga/extensions/optimized.py +162 -0
- numga/extensions/outermorphism.py +86 -0
- numga/extensions/roots.py +114 -0
- numga/extensions/scalar.py +104 -0
- numga/extensions/spectra.py +91 -0
- numga/extensions/systems.py +253 -0
- numga/extensions/trace.py +122 -0
- numga/extensor/__init__.py +4 -0
- numga/extensor/application.py +156 -0
- numga/extensor/extensor.py +979 -0
- numga/extensor/fields.py +320 -0
- numga/extensor/namespaces.py +78 -0
- numga/extensor/operands.py +144 -0
- numga/flyweight.py +39 -0
- numga/gatype/__init__.py +36 -0
- numga/gatype/dispatch.py +480 -0
- numga/gatype/errors.py +19 -0
- numga/gatype/factory.py +181 -0
- numga/gatype/gatype.py +900 -0
- numga/gatype/metric.py +71 -0
- numga/gatype/orientation.py +48 -0
- numga/gatype/pattern.py +155 -0
- numga/gatype/propagation.py +345 -0
- numga/gatype/queries.py +211 -0
- numga/gatype/rules.py +137 -0
- numga/gatype/traits.py +619 -0
- numga/multivector/__init__.py +4 -0
- numga/multivector/factory.py +204 -0
- numga/multivector/subalgebra.py +117 -0
- numga/operator/__init__.py +5 -0
- numga/operator/factory.py +724 -0
- numga/operator/format.py +110 -0
- numga/operator/kernel.py +198 -0
- numga/render/__init__.py +41 -0
- numga/render/camera.py +147 -0
- numga/render/contours.py +141 -0
- numga/render/drawing.py +279 -0
- numga/render/flow.py +323 -0
- numga/render/meshes.py +191 -0
- numga/render/planar.py +12 -0
- numga/render/quadrics.py +163 -0
- numga/render/scene.py +58 -0
- numga/render/simplices.py +399 -0
- numga/render/solids.py +922 -0
- numga/sparse/__init__.py +7 -0
- numga/sparse/extensor.py +534 -0
- numga/sparse/numeric.py +221 -0
- numga/subspace/__init__.py +7 -0
- numga/subspace/factory.py +317 -0
- numga/subspace/subspace.py +274 -0
- numga/topology.py +612 -0
- numga/wgsl/__init__.py +24 -0
- numga/wgsl/dialect.py +1643 -0
- numga/wgsl/library.py +94 -0
- numga/wgsl/page.py +43 -0
- numga/wgsl/runner.py +395 -0
- numga-2.0.0.dist-info/METADATA +113 -0
- numga-2.0.0.dist-info/RECORD +92 -0
- numga-2.0.0.dist-info/WHEEL +5 -0
- numga-2.0.0.dist-info/licenses/LICENSE +21 -0
- numga-2.0.0.dist-info/top_level.txt +1 -0
numga/__init__.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
"""The top-level `numga` namespace exposes geometric algebras (`Algebra`), blade subspaces
|
|
2
|
+
(`SubSpace`), extensor types and traits (`GAType`, `Orientation`, `Trait`), multilinear values and
|
|
3
|
+
maps (`Extensor`, `MultivectorFactory`, `OperatorFactory`), and backend execution contexts
|
|
4
|
+
(`ExactContext`, `NumpyContext`, `JaxContext`, `TorchContext`). Optional JAX and PyTorch contexts
|
|
5
|
+
load lazily on attribute access so importing `numga` requires only NumPy.
|
|
6
|
+
|
|
7
|
+
Algebraic conventions and product rules are introduced in `docs/conventions.md`, extensor map and
|
|
8
|
+
binding syntax in `docs/extensor_syntax.md`, intrinsic and extrinsic orientation in
|
|
9
|
+
`docs/orientation.md`, discrete fields over sites in `docs/fields.md`, simplicial complexes in
|
|
10
|
+
`docs/topology.md`, WebGPU shaders and rendering in `docs/rendering.md`, and type-dispatch and
|
|
11
|
+
backend internals in `docs/internals.md`."""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from .algebra import Algebra, AlgebraDescription
|
|
16
|
+
from .backend import Context, ExactContext, NumpyContext
|
|
17
|
+
from .binding import AxisTransform, AxisTransformKind, BindingPlan
|
|
18
|
+
from .extensor import Extensor, concatenate, stack, where
|
|
19
|
+
from .extension import ExtensionMethod
|
|
20
|
+
from . import expression
|
|
21
|
+
from .gatype import (
|
|
22
|
+
EMPTY_TRAITS,
|
|
23
|
+
ROTOR_TRAITS,
|
|
24
|
+
AmbiguousGATypeDispatchWarning,
|
|
25
|
+
Blade,
|
|
26
|
+
BladeProduct,
|
|
27
|
+
CoefficientOrthogonal,
|
|
28
|
+
GAType,
|
|
29
|
+
GATypeDispatch,
|
|
30
|
+
GATypeError,
|
|
31
|
+
GATypeFactory,
|
|
32
|
+
GATypePattern,
|
|
33
|
+
CliffordConjugateProduct,
|
|
34
|
+
CliffordConjugateProductNonzero,
|
|
35
|
+
CliffordConjugateProductOne,
|
|
36
|
+
CliffordConjugateProductScalar,
|
|
37
|
+
CliffordConjugateProductZero,
|
|
38
|
+
GradeInvolutionProduct,
|
|
39
|
+
Orientation,
|
|
40
|
+
ProductFact,
|
|
41
|
+
ProductRelation,
|
|
42
|
+
ProductResult,
|
|
43
|
+
SelfProduct,
|
|
44
|
+
ReverseProduct,
|
|
45
|
+
ReverseProductNonzero,
|
|
46
|
+
ReverseProductOne,
|
|
47
|
+
ReverseProductScalar,
|
|
48
|
+
ReverseProductZero,
|
|
49
|
+
Trait,
|
|
50
|
+
TraitSet,
|
|
51
|
+
Versor,
|
|
52
|
+
VersorProduct,
|
|
53
|
+
)
|
|
54
|
+
from .multivector import MultivectorFactory
|
|
55
|
+
from .operator import OperatorFactory, SymbolicKernel
|
|
56
|
+
from .subspace import SubSpace, SubSpaceFactory, SupportKey
|
|
57
|
+
|
|
58
|
+
# Default extension overloads register once core classes exist.
|
|
59
|
+
from . import extensions as _extensions
|
|
60
|
+
|
|
61
|
+
__version__ = "2.0.0"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def __getattr__(name: str) -> type[Context]:
|
|
65
|
+
if name == "JaxContext":
|
|
66
|
+
from .backend.jax import JaxContext
|
|
67
|
+
return JaxContext
|
|
68
|
+
if name == "TorchContext":
|
|
69
|
+
from .backend.torch import TorchContext
|
|
70
|
+
return TorchContext
|
|
71
|
+
raise AttributeError(f"module 'numga' has no attribute {name!r}")
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""The `numga.algebra` package defines backend-independent geometric algebra descriptions,
|
|
2
|
+
canonical bit-mask blades, and Cayley product tables."""
|
|
3
|
+
|
|
4
|
+
from .algebra import Algebra, BladeProduct, OrientedBlade, ProductTable
|
|
5
|
+
from .description import AlgebraDescription, parse_description
|
|
6
|
+
|
numga/algebra/algebra.py
ADDED
|
@@ -0,0 +1,580 @@
|
|
|
1
|
+
"""A finite-dimensional geometric algebra with up to 64 orthogonal generators maps each canonical
|
|
2
|
+
basis blade to a non-negative integer bit mask whose `i`-th bit records generator `i` in increasing
|
|
3
|
+
index order. Because the metric is diagonal with entries in `(+1, -1, 0)`, the geometric product of
|
|
4
|
+
any two canonical basis blades produces a single output mask `left ^ right` scaled by an integer
|
|
5
|
+
sign in `(-1, 0, +1)` combining pairwise generator swaps with negative and null metric contractions.
|
|
6
|
+
|
|
7
|
+
`Algebra` accepts an `AlgebraDescription`, a compact interleaved string such as `"x+y+z+w0"`, or a
|
|
8
|
+
`(p, q, r)` count tuple; per-generator metric sequences go through `Algebra.from_signature` so a
|
|
9
|
+
three-dimensional metric tuple `(1, 1, 1)` cannot collide with signature counts. Instances are
|
|
10
|
+
weakly interned by `(description, subspace_factory, gatype_factory, multivector_factory)` so
|
|
11
|
+
repeated constructions of `Algebra("x+y+")` return the same `Algebra` object and their extensors
|
|
12
|
+
interoperate, whereas stock algebras with custom layouts or value constructors such as `PGA3D`
|
|
13
|
+
remain distinct from plain `Algebra("w0x+y+z+")`.
|
|
14
|
+
|
|
15
|
+
Each `Algebra` owns the per-algebra flyweight namespaces that are independent of a numerical array
|
|
16
|
+
backend: `subspace` for signed blade layouts, `gatype` for whole-extensor types and static trait
|
|
17
|
+
deduction, `operator` for exact bilinear kernels, and `exact` for symbolic integer-array execution,
|
|
18
|
+
while storing the `multivector_factory` callable bound by each numerical `Context`.
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
from collections.abc import Callable, Iterable
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from operator import index
|
|
26
|
+
from types import NotImplementedType
|
|
27
|
+
from typing import TYPE_CHECKING, NamedTuple
|
|
28
|
+
import weakref
|
|
29
|
+
|
|
30
|
+
import numpy as np
|
|
31
|
+
|
|
32
|
+
from .bitops import (
|
|
33
|
+
bit_count,
|
|
34
|
+
mask_from_indices,
|
|
35
|
+
parity_to_sign,
|
|
36
|
+
permutation_sign,
|
|
37
|
+
unsigned_dtype,
|
|
38
|
+
)
|
|
39
|
+
from .description import AlgebraDescription
|
|
40
|
+
|
|
41
|
+
if TYPE_CHECKING:
|
|
42
|
+
from numga.backend.context import Context
|
|
43
|
+
from numga.backend.exact import ExactContext
|
|
44
|
+
from numga.multivector.factory import MultivectorFactory
|
|
45
|
+
from numga.gatype.factory import GATypeFactory
|
|
46
|
+
from numga.operator.factory import OperatorFactory
|
|
47
|
+
from numga.subspace.factory import SubSpaceFactory
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class BladeProduct(NamedTuple):
|
|
51
|
+
"""Multiplying two canonical basis blades yields an integer `coefficient` in `(-1, 0, +1)` and
|
|
52
|
+
a canonical output `blade` mask."""
|
|
53
|
+
|
|
54
|
+
coefficient: int
|
|
55
|
+
blade: int
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def mask(self) -> int:
|
|
59
|
+
return self.blade
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class OrientedBlade(NamedTuple):
|
|
63
|
+
"""Parsing a spelled exterior blade yields its canonical `blade` mask and permutation `sign` in
|
|
64
|
+
`(-1, +1)`."""
|
|
65
|
+
|
|
66
|
+
blade: int
|
|
67
|
+
sign: int
|
|
68
|
+
|
|
69
|
+
@property
|
|
70
|
+
def mask(self) -> int:
|
|
71
|
+
return self.blade
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True, slots=True, eq=False)
|
|
75
|
+
class ProductTable:
|
|
76
|
+
"""Pairwise geometric products across two ordered blade sequences store immutable output
|
|
77
|
+
`blades` and integer `coefficients` matrices."""
|
|
78
|
+
|
|
79
|
+
blades: np.ndarray
|
|
80
|
+
coefficients: np.ndarray
|
|
81
|
+
|
|
82
|
+
def __post_init__(self) -> None:
|
|
83
|
+
blades = np.asarray(self.blades)
|
|
84
|
+
coefficients = np.asarray(self.coefficients, dtype=np.int8)
|
|
85
|
+
if blades.shape != coefficients.shape or blades.ndim != 2:
|
|
86
|
+
raise ValueError("product-table arrays must be equally shaped matrices")
|
|
87
|
+
|
|
88
|
+
# Arrays backed by immutable bytes cannot be made writeable again by a caller,
|
|
89
|
+
# unlike an owning ndarray with only its writeable flag cleared.
|
|
90
|
+
frozen_blades = np.frombuffer(blades.tobytes(), dtype=blades.dtype).reshape(
|
|
91
|
+
blades.shape
|
|
92
|
+
)
|
|
93
|
+
frozen_coefficients = np.frombuffer(
|
|
94
|
+
coefficients.tobytes(), dtype=np.int8
|
|
95
|
+
).reshape(coefficients.shape)
|
|
96
|
+
object.__setattr__(self, "blades", frozen_blades)
|
|
97
|
+
object.__setattr__(self, "coefficients", frozen_coefficients)
|
|
98
|
+
|
|
99
|
+
@property
|
|
100
|
+
def shape(self) -> tuple[int, int]:
|
|
101
|
+
return self.blades.shape
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _describe(specification: AlgebraDescription | str | tuple[int, int, int]) -> AlgebraDescription:
|
|
105
|
+
if isinstance(specification, AlgebraDescription):
|
|
106
|
+
description = specification
|
|
107
|
+
elif isinstance(specification, str):
|
|
108
|
+
description = AlgebraDescription.parse(specification)
|
|
109
|
+
elif isinstance(specification, tuple) and len(specification) == 3:
|
|
110
|
+
description = AlgebraDescription.from_pqr(*specification)
|
|
111
|
+
else:
|
|
112
|
+
raise TypeError(
|
|
113
|
+
"Algebra expects an AlgebraDescription, compact string, or (p, q, r) tuple"
|
|
114
|
+
)
|
|
115
|
+
if description.dimension > 64:
|
|
116
|
+
raise ValueError("the bit-mask implementation supports at most 64 generators")
|
|
117
|
+
return description
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# Weakly interning algebras by description and factory callables lets repeated constructions share one Algebra instance.
|
|
121
|
+
_interned = weakref.WeakValueDictionary()
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
@dataclass(frozen=True, slots=True, init=False, weakref_slot=True)
|
|
125
|
+
class Algebra:
|
|
126
|
+
"""An immutable geometric algebra represents basis blades as canonical integer bit masks and
|
|
127
|
+
interns instances by description and factory callables."""
|
|
128
|
+
|
|
129
|
+
description: AlgebraDescription
|
|
130
|
+
_subspace_factory: SubSpaceFactory = field(compare=False, repr=False)
|
|
131
|
+
_gatype_factory: GATypeFactory = field(compare=False, repr=False)
|
|
132
|
+
_exact_context: ExactContext = field(compare=False, repr=False)
|
|
133
|
+
_operator_factory: OperatorFactory = field(compare=False, repr=False)
|
|
134
|
+
_multivector_factory: Callable = field(compare=False, repr=False)
|
|
135
|
+
|
|
136
|
+
def __new__(
|
|
137
|
+
cls,
|
|
138
|
+
specification: AlgebraDescription | str | tuple[int, int, int],
|
|
139
|
+
*,
|
|
140
|
+
subspace_factory: Callable | None = None,
|
|
141
|
+
gatype_factory: Callable | None = None,
|
|
142
|
+
multivector_factory: Callable | None = None,
|
|
143
|
+
) -> Algebra:
|
|
144
|
+
key = (_describe(specification), subspace_factory, gatype_factory, multivector_factory)
|
|
145
|
+
try:
|
|
146
|
+
return _interned[key]
|
|
147
|
+
except KeyError:
|
|
148
|
+
instance = object.__new__(cls)
|
|
149
|
+
_interned[key] = instance
|
|
150
|
+
return instance
|
|
151
|
+
|
|
152
|
+
def __init__(
|
|
153
|
+
self,
|
|
154
|
+
specification: AlgebraDescription | str | tuple[int, int, int],
|
|
155
|
+
*,
|
|
156
|
+
subspace_factory: Callable | None = None,
|
|
157
|
+
gatype_factory: Callable | None = None,
|
|
158
|
+
multivector_factory: Callable | None = None,
|
|
159
|
+
) -> None:
|
|
160
|
+
# Returning an already-interned instance from __new__ still invokes __init__.
|
|
161
|
+
try:
|
|
162
|
+
self.description
|
|
163
|
+
return
|
|
164
|
+
except AttributeError:
|
|
165
|
+
pass
|
|
166
|
+
object.__setattr__(self, "description", _describe(specification))
|
|
167
|
+
|
|
168
|
+
# Owning the construction namespaces ties their flyweight pools to the algebra's lifetime.
|
|
169
|
+
from numga.backend.exact import ExactContext
|
|
170
|
+
from numga.gatype.factory import GATypeFactory
|
|
171
|
+
from numga.operator.factory import OperatorFactory
|
|
172
|
+
from numga.subspace.factory import SubSpaceFactory
|
|
173
|
+
|
|
174
|
+
object.__setattr__(self, "_subspace_factory", (subspace_factory or SubSpaceFactory)(self))
|
|
175
|
+
object.__setattr__(self, "_gatype_factory", (gatype_factory or GATypeFactory)(self))
|
|
176
|
+
# Storing the multivector factory callable lets every Context specialize value constructors.
|
|
177
|
+
from numga.multivector.factory import MultivectorFactory
|
|
178
|
+
object.__setattr__(self, "_multivector_factory", multivector_factory or MultivectorFactory)
|
|
179
|
+
object.__setattr__(self, "_exact_context", ExactContext(self))
|
|
180
|
+
object.__setattr__(self, "_operator_factory", OperatorFactory(self))
|
|
181
|
+
|
|
182
|
+
@classmethod
|
|
183
|
+
def from_description(
|
|
184
|
+
cls,
|
|
185
|
+
description: AlgebraDescription,
|
|
186
|
+
*,
|
|
187
|
+
subspace_factory: Callable | None = None,
|
|
188
|
+
gatype_factory: Callable | None = None,
|
|
189
|
+
multivector_factory: Callable | None = None,
|
|
190
|
+
) -> Algebra:
|
|
191
|
+
return cls(
|
|
192
|
+
description,
|
|
193
|
+
subspace_factory=subspace_factory,
|
|
194
|
+
gatype_factory=gatype_factory,
|
|
195
|
+
multivector_factory=multivector_factory,
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
@classmethod
|
|
199
|
+
def from_signature(
|
|
200
|
+
cls,
|
|
201
|
+
signature: Iterable[int],
|
|
202
|
+
basis_names: Iterable[str] | None = None,
|
|
203
|
+
*,
|
|
204
|
+
subspace_factory: Callable | None = None,
|
|
205
|
+
gatype_factory: Callable | None = None,
|
|
206
|
+
multivector_factory: Callable | None = None,
|
|
207
|
+
) -> Algebra:
|
|
208
|
+
"""Per-generator metric squares in `(-1, 0, +1)` build an algebra without colliding with
|
|
209
|
+
`(p, q, r)` count tuples."""
|
|
210
|
+
return cls(
|
|
211
|
+
AlgebraDescription.from_signature(signature, basis_names),
|
|
212
|
+
subspace_factory=subspace_factory,
|
|
213
|
+
gatype_factory=gatype_factory,
|
|
214
|
+
multivector_factory=multivector_factory,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
@classmethod
|
|
218
|
+
def from_pqr(
|
|
219
|
+
cls,
|
|
220
|
+
p: int,
|
|
221
|
+
q: int,
|
|
222
|
+
r: int,
|
|
223
|
+
basis_names: Iterable[str] | None = None,
|
|
224
|
+
*,
|
|
225
|
+
subspace_factory: Callable | None = None,
|
|
226
|
+
gatype_factory: Callable | None = None,
|
|
227
|
+
multivector_factory: Callable | None = None,
|
|
228
|
+
) -> Algebra:
|
|
229
|
+
"""Signature counts `(p, q, r)` order `+1` generators before `-1` and `0`."""
|
|
230
|
+
return cls(
|
|
231
|
+
AlgebraDescription.from_pqr(p, q, r, basis_names),
|
|
232
|
+
subspace_factory=subspace_factory,
|
|
233
|
+
gatype_factory=gatype_factory,
|
|
234
|
+
multivector_factory=multivector_factory,
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
def dimension(self) -> int:
|
|
239
|
+
return self.description.dimension
|
|
240
|
+
|
|
241
|
+
@property
|
|
242
|
+
def blade_count(self) -> int:
|
|
243
|
+
return 1 << self.dimension
|
|
244
|
+
|
|
245
|
+
@property
|
|
246
|
+
def basis_names(self) -> tuple[str, ...]:
|
|
247
|
+
return self.description.basis_names
|
|
248
|
+
|
|
249
|
+
@property
|
|
250
|
+
def signature(self) -> tuple[int, ...]:
|
|
251
|
+
return self.description.signature
|
|
252
|
+
|
|
253
|
+
@property
|
|
254
|
+
def pqr(self) -> tuple[int, int, int]:
|
|
255
|
+
return self.description.pqr
|
|
256
|
+
|
|
257
|
+
@property
|
|
258
|
+
def subspace(self) -> SubSpaceFactory:
|
|
259
|
+
"""Canonical `SubSpace` supports and signed blade layouts are pooled per algebra."""
|
|
260
|
+
return self._subspace_factory
|
|
261
|
+
|
|
262
|
+
@property
|
|
263
|
+
def gatype(self) -> GATypeFactory:
|
|
264
|
+
"""Whole-extensor `GAType` instances and static trait derivations are pooled per algebra."""
|
|
265
|
+
return self._gatype_factory
|
|
266
|
+
|
|
267
|
+
@property
|
|
268
|
+
def operator(self) -> OperatorFactory:
|
|
269
|
+
"""Exact bilinear and unary `SymbolicKernel` tables are cached per algebra."""
|
|
270
|
+
return self._operator_factory
|
|
271
|
+
|
|
272
|
+
@property
|
|
273
|
+
def exact(self) -> ExactContext:
|
|
274
|
+
"""Symbolic integer-array execution runs in an algebra-owned `ExactContext`."""
|
|
275
|
+
return self._exact_context
|
|
276
|
+
|
|
277
|
+
@property
|
|
278
|
+
def blade_dtype(self) -> np.dtype:
|
|
279
|
+
return unsigned_dtype(self.dimension)
|
|
280
|
+
|
|
281
|
+
@property
|
|
282
|
+
def blade_masks(self) -> range:
|
|
283
|
+
"""Canonical integer blade masks span `range(blade_count)` lazily without allocating an
|
|
284
|
+
array."""
|
|
285
|
+
return range(self.blade_count)
|
|
286
|
+
|
|
287
|
+
@property
|
|
288
|
+
def basis_vector_masks(self) -> tuple[int, ...]:
|
|
289
|
+
return tuple(1 << generator for generator in range(self.dimension))
|
|
290
|
+
|
|
291
|
+
@property
|
|
292
|
+
def pseudoscalar_mask(self) -> int:
|
|
293
|
+
return self.blade_count - 1
|
|
294
|
+
|
|
295
|
+
@property
|
|
296
|
+
def positive_mask(self) -> int:
|
|
297
|
+
return mask_from_indices(
|
|
298
|
+
generator for generator, sign in enumerate(self.signature) if sign == 1
|
|
299
|
+
)
|
|
300
|
+
|
|
301
|
+
@property
|
|
302
|
+
def negative_mask(self) -> int:
|
|
303
|
+
return mask_from_indices(
|
|
304
|
+
generator for generator, sign in enumerate(self.signature) if sign == -1
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
@property
|
|
308
|
+
def degenerate_mask(self) -> int:
|
|
309
|
+
return mask_from_indices(
|
|
310
|
+
generator for generator, sign in enumerate(self.signature) if sign == 0
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
@property
|
|
314
|
+
def negatives(self) -> int:
|
|
315
|
+
return self.negative_mask
|
|
316
|
+
|
|
317
|
+
@property
|
|
318
|
+
def positives(self) -> int:
|
|
319
|
+
return self.positive_mask
|
|
320
|
+
|
|
321
|
+
@property
|
|
322
|
+
def zeros(self) -> int:
|
|
323
|
+
return self.degenerate_mask
|
|
324
|
+
|
|
325
|
+
@property
|
|
326
|
+
def blade_nbytes(self) -> int:
|
|
327
|
+
return self.blade_dtype.itemsize
|
|
328
|
+
|
|
329
|
+
@property
|
|
330
|
+
def pseudo_scalar_squared(self) -> int:
|
|
331
|
+
return self.pseudoscalar_squared
|
|
332
|
+
|
|
333
|
+
@property
|
|
334
|
+
def n_dimensions(self) -> int:
|
|
335
|
+
return self.dimension
|
|
336
|
+
|
|
337
|
+
@property
|
|
338
|
+
def n_blades(self) -> int:
|
|
339
|
+
return self.blade_count
|
|
340
|
+
|
|
341
|
+
@property
|
|
342
|
+
def n_grades(self) -> int:
|
|
343
|
+
return self.dimension + 1
|
|
344
|
+
|
|
345
|
+
def __len__(self) -> int:
|
|
346
|
+
return self.blade_count
|
|
347
|
+
|
|
348
|
+
@property
|
|
349
|
+
def pseudoscalar_squared(self) -> int:
|
|
350
|
+
return self.geometric_product(
|
|
351
|
+
self.pseudoscalar_mask, self.pseudoscalar_mask
|
|
352
|
+
).coefficient
|
|
353
|
+
|
|
354
|
+
def _mask(self, blade: int) -> int:
|
|
355
|
+
try:
|
|
356
|
+
mask = index(blade)
|
|
357
|
+
except TypeError as error:
|
|
358
|
+
raise TypeError("a blade mask must be an integer") from error
|
|
359
|
+
if mask < 0 or mask >= self.blade_count:
|
|
360
|
+
raise ValueError(
|
|
361
|
+
f"blade mask {mask} is outside this {self.dimension}-dimensional algebra"
|
|
362
|
+
)
|
|
363
|
+
return mask
|
|
364
|
+
|
|
365
|
+
def _masks_to_array(self, blades: Iterable[int] | np.ndarray) -> np.ndarray:
|
|
366
|
+
if isinstance(blades, np.ndarray):
|
|
367
|
+
arr = blades
|
|
368
|
+
elif isinstance(blades, (list, tuple, range)):
|
|
369
|
+
if not blades:
|
|
370
|
+
return np.empty(0, dtype=self.blade_dtype)
|
|
371
|
+
arr = np.asarray(blades)
|
|
372
|
+
else:
|
|
373
|
+
blades_tuple = tuple(blades)
|
|
374
|
+
if not blades_tuple:
|
|
375
|
+
return np.empty(0, dtype=self.blade_dtype)
|
|
376
|
+
arr = np.asarray(blades_tuple)
|
|
377
|
+
|
|
378
|
+
if arr.dtype.kind not in ("i", "u"):
|
|
379
|
+
raise TypeError("a blade mask must be an integer")
|
|
380
|
+
if np.any((arr < 0) | (arr >= self.blade_count)):
|
|
381
|
+
raise ValueError(
|
|
382
|
+
f"blade mask is outside this {self.dimension}-dimensional algebra"
|
|
383
|
+
)
|
|
384
|
+
return arr.astype(self.blade_dtype)
|
|
385
|
+
|
|
386
|
+
def bit_dot(
|
|
387
|
+
self, left: int | np.ndarray, right: int | np.ndarray
|
|
388
|
+
) -> int | np.ndarray:
|
|
389
|
+
"""Bitwise overlap counts how many basis generators appear in both `left` and `right`."""
|
|
390
|
+
if isinstance(left, (int, np.integer)) and isinstance(right, (int, np.integer)):
|
|
391
|
+
return (int(left) & int(right)).bit_count()
|
|
392
|
+
return bit_count(np.bitwise_and(left, right))
|
|
393
|
+
|
|
394
|
+
def grade(self, blade: int | Iterable[int] | np.ndarray) -> int | np.ndarray:
|
|
395
|
+
"""Set bits in a canonical blade mask count the basis generators in its wedge product."""
|
|
396
|
+
if isinstance(blade, (int, np.integer)):
|
|
397
|
+
return self._mask(blade).bit_count()
|
|
398
|
+
return bit_count(self._masks_to_array(blade))
|
|
399
|
+
|
|
400
|
+
def complement(self, blade: int | Iterable[int] | np.ndarray) -> int | np.ndarray:
|
|
401
|
+
"""XORing with `pseudoscalar_mask` toggles every generator bit to give the unsigned
|
|
402
|
+
complement mask."""
|
|
403
|
+
if isinstance(blade, (int, np.integer)):
|
|
404
|
+
return self._mask(blade) ^ self.pseudoscalar_mask
|
|
405
|
+
return np.bitwise_xor(self._masks_to_array(blade), self.pseudoscalar_mask)
|
|
406
|
+
|
|
407
|
+
def involute_sign(self, blade: int | Iterable[int] | np.ndarray) -> int | np.ndarray:
|
|
408
|
+
"""Grade involution multiplies grade `k` by `(-1)**k`."""
|
|
409
|
+
grade = self.grade(blade)
|
|
410
|
+
return parity_to_sign(grade)
|
|
411
|
+
|
|
412
|
+
involute = involute_sign
|
|
413
|
+
|
|
414
|
+
def reverse_sign(self, blade: int | Iterable[int] | np.ndarray) -> int | np.ndarray:
|
|
415
|
+
"""Reversing generator order in a `k`-blade multiplies by `(-1)**(k * (k - 1) // 2)`."""
|
|
416
|
+
grade = self.grade(blade)
|
|
417
|
+
if isinstance(grade, (int, np.integer)):
|
|
418
|
+
return parity_to_sign(int(grade) * (int(grade) - 1) // 2)
|
|
419
|
+
return parity_to_sign((grade * (grade - 1)) // 2)
|
|
420
|
+
|
|
421
|
+
reverse = reverse_sign
|
|
422
|
+
|
|
423
|
+
def conjugate_sign(self, blade: int | Iterable[int] | np.ndarray) -> int | np.ndarray:
|
|
424
|
+
"""Clifford conjugation composes grade involution with reversion, multiplying grade `k` by
|
|
425
|
+
`(-1)**(k * (k + 1) // 2)`."""
|
|
426
|
+
grade = self.grade(blade)
|
|
427
|
+
if isinstance(grade, (int, np.integer)):
|
|
428
|
+
return parity_to_sign(int(grade) * (int(grade) + 1) // 2)
|
|
429
|
+
return parity_to_sign((grade * (grade + 1)) // 2)
|
|
430
|
+
|
|
431
|
+
conjugate = conjugate_sign
|
|
432
|
+
|
|
433
|
+
def cayley(
|
|
434
|
+
self, left: np.ndarray, right: np.ndarray
|
|
435
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
436
|
+
"""Pairwise XOR gives the output blade masks of `left * right`, paired with the adjacent
|
|
437
|
+
generator swap counts needed to restore canonical increasing generator order."""
|
|
438
|
+
left = np.asarray(left, dtype=self.blade_dtype)
|
|
439
|
+
right = np.asarray(right, dtype=self.blade_dtype)
|
|
440
|
+
cayley = np.bitwise_xor(left, right)
|
|
441
|
+
|
|
442
|
+
if self.dimension > 1:
|
|
443
|
+
shifted = right
|
|
444
|
+
swaps = 0
|
|
445
|
+
for _ in range(self.dimension - 1):
|
|
446
|
+
shifted = np.left_shift(shifted, 1)
|
|
447
|
+
swaps = swaps + self.bit_dot(left, shifted)
|
|
448
|
+
swaps = np.asarray(swaps, dtype=np.int8)
|
|
449
|
+
else:
|
|
450
|
+
swaps = np.zeros(np.broadcast_shapes(left.shape, right.shape), dtype=np.int8)
|
|
451
|
+
|
|
452
|
+
return cayley, swaps
|
|
453
|
+
|
|
454
|
+
def product(
|
|
455
|
+
self, left: Iterable[int] | np.ndarray, right: Iterable[int] | np.ndarray
|
|
456
|
+
) -> tuple[np.ndarray, np.ndarray]:
|
|
457
|
+
"""Evaluating the outer geometric product across two blade sequences yields
|
|
458
|
+
`[len(left), len(right)]` arrays of canonical output masks and `int8` signs in `(-1, 0, +1)`
|
|
459
|
+
combining reordering swaps with metric contractions."""
|
|
460
|
+
arr_left = self._masks_to_array(left)
|
|
461
|
+
arr_right = self._masks_to_array(right)
|
|
462
|
+
|
|
463
|
+
# Generators present on both sides contract under the diagonal metric.
|
|
464
|
+
doubles = np.bitwise_and.outer(arr_left, arr_right)
|
|
465
|
+
negatives = self.bit_dot(doubles, self.negative_mask)
|
|
466
|
+
zeros = self.bit_dot(doubles, self.degenerate_mask)
|
|
467
|
+
|
|
468
|
+
cayley, swaps = self.cayley(arr_left[:, None], arr_right[None, :])
|
|
469
|
+
signs = parity_to_sign(negatives + swaps) * (zeros == 0)
|
|
470
|
+
return cayley, signs.astype(np.int8)
|
|
471
|
+
|
|
472
|
+
def parse_blade(self, blade: str | Iterable[str]) -> OrientedBlade:
|
|
473
|
+
"""Parsing an exterior blade spelling yields its canonical generator mask and permutation
|
|
474
|
+
sign. Strings accept `"1"` or `""` for the scalar, a single generator name, caret-delimited
|
|
475
|
+
tokens such as `"e0^e1"`, or concatenated single-character names such as `"yx"`, while
|
|
476
|
+
string iterables resolve multi-character generator names directly."""
|
|
477
|
+
if isinstance(blade, str):
|
|
478
|
+
if blade in ("", "1"):
|
|
479
|
+
tokens = ()
|
|
480
|
+
elif "^" in blade:
|
|
481
|
+
tokens = tuple(blade.split("^"))
|
|
482
|
+
if any(not token for token in tokens):
|
|
483
|
+
raise ValueError("a caret-delimited blade contains an empty token")
|
|
484
|
+
elif blade in self.basis_names:
|
|
485
|
+
tokens = (blade,)
|
|
486
|
+
elif all(len(name) == 1 for name in self.basis_names):
|
|
487
|
+
tokens = tuple(blade)
|
|
488
|
+
else:
|
|
489
|
+
raise ValueError(
|
|
490
|
+
"multi-character basis names require caret-delimited or tuple spelling"
|
|
491
|
+
)
|
|
492
|
+
else:
|
|
493
|
+
tokens = tuple(blade)
|
|
494
|
+
|
|
495
|
+
positions = []
|
|
496
|
+
for token in tokens:
|
|
497
|
+
if not isinstance(token, str):
|
|
498
|
+
raise TypeError("blade tokens must be strings")
|
|
499
|
+
try:
|
|
500
|
+
positions.append(self.basis_names.index(token))
|
|
501
|
+
except ValueError as error:
|
|
502
|
+
raise ValueError(f"unknown basis generator {token!r}") from error
|
|
503
|
+
if len(set(positions)) != len(positions):
|
|
504
|
+
raise ValueError("a basis blade cannot repeat a generator")
|
|
505
|
+
|
|
506
|
+
return OrientedBlade(
|
|
507
|
+
mask_from_indices(positions),
|
|
508
|
+
permutation_sign(positions),
|
|
509
|
+
)
|
|
510
|
+
|
|
511
|
+
def blade_name(self, blade: int) -> str:
|
|
512
|
+
"""Canonical blade names list generators in increasing index order, joined with `"^"` when
|
|
513
|
+
any generator name has multiple characters, with mask `0` named `"1"`."""
|
|
514
|
+
mask = self._mask(blade)
|
|
515
|
+
if mask == 0:
|
|
516
|
+
return "1"
|
|
517
|
+
names = tuple(
|
|
518
|
+
name
|
|
519
|
+
for generator, name in enumerate(self.basis_names)
|
|
520
|
+
if mask & (1 << generator)
|
|
521
|
+
)
|
|
522
|
+
separator = "" if all(len(name) == 1 for name in self.basis_names) else "^"
|
|
523
|
+
return separator.join(names)
|
|
524
|
+
|
|
525
|
+
def oriented_blade_name(self, blade: int, sign: int) -> str:
|
|
526
|
+
"""Negative orientation swaps the first two generators (`"zx"` for `-"xz"`), using a leading
|
|
527
|
+
`"-"` only on scalars and vectors so spellings round-trip through `subspace.from_blades`."""
|
|
528
|
+
name = self.blade_name(blade)
|
|
529
|
+
if sign > 0:
|
|
530
|
+
return name
|
|
531
|
+
separator = "" if all(len(name) == 1 for name in self.basis_names) else "^"
|
|
532
|
+
names = name.split(separator) if separator else list(name)
|
|
533
|
+
if len(names) < 2 or name == "1":
|
|
534
|
+
return "-" + name
|
|
535
|
+
return separator.join([names[1], names[0], *names[2:]])
|
|
536
|
+
|
|
537
|
+
def geometric_product(self, left: int, right: int) -> BladeProduct:
|
|
538
|
+
"""Two canonical basis blades multiply to a single output mask `left ^ right` and integer
|
|
539
|
+
coefficient in `(-1, 0, +1)`; contractions on null generators return coefficient `0` with
|
|
540
|
+
the deterministic XOR mask."""
|
|
541
|
+
left_mask = self._mask(left)
|
|
542
|
+
right_mask = self._mask(right)
|
|
543
|
+
output = left_mask ^ right_mask
|
|
544
|
+
|
|
545
|
+
doubles = left_mask & right_mask
|
|
546
|
+
if doubles & self.degenerate_mask:
|
|
547
|
+
return BladeProduct(0, output)
|
|
548
|
+
|
|
549
|
+
negatives = (doubles & self.negative_mask).bit_count()
|
|
550
|
+
swaps = 0
|
|
551
|
+
shifted = right_mask
|
|
552
|
+
for _ in range(self.dimension - 1):
|
|
553
|
+
shifted <<= 1
|
|
554
|
+
swaps += (left_mask & shifted).bit_count()
|
|
555
|
+
|
|
556
|
+
return BladeProduct(parity_to_sign(negatives + swaps), output)
|
|
557
|
+
|
|
558
|
+
def geometric_product_table(
|
|
559
|
+
self,
|
|
560
|
+
left_blades: Iterable[int],
|
|
561
|
+
right_blades: Iterable[int],
|
|
562
|
+
) -> ProductTable:
|
|
563
|
+
"""Ordered left and right blade supports determine an immutable `ProductTable` of canonical
|
|
564
|
+
output masks and integer signs."""
|
|
565
|
+
blades, coefficients = self.product(left_blades, right_blades)
|
|
566
|
+
return ProductTable(blades, coefficients)
|
|
567
|
+
|
|
568
|
+
def __mul__(self, other: object) -> Algebra | NotImplementedType:
|
|
569
|
+
"""Multiplying two algebras with disjoint generator names constructs their orthogonal
|
|
570
|
+
direct-sum algebra."""
|
|
571
|
+
if not isinstance(other, Algebra):
|
|
572
|
+
return NotImplemented
|
|
573
|
+
return Algebra(self.description * other.description)
|
|
574
|
+
|
|
575
|
+
def __repr__(self) -> str:
|
|
576
|
+
try:
|
|
577
|
+
specification = self.description.to_compact_string()
|
|
578
|
+
except ValueError:
|
|
579
|
+
return f"Algebra({self.description!r})"
|
|
580
|
+
return f"Algebra({specification!r})"
|