httk.core.vectors¶
Exact-rational vectors (FracVector/FracScalar/MutableFracVector) and
the Vector backend/view family that lets the same tensor data be viewed as the exact
representation, plain nested sequences, or (optionally) numpy arrays.
The exact-math helpers live in httk.core.exactmath (type-preserving exact transcendentals
on Fraction and Decimal) and httk.core.vectors.vectormath (functional math wrappers).
Submodules¶
- httk.core.vectors.fracvector
- httk.core.vectors.leaf_codecs
- httk.core.vectors.mutablefracvector
- httk.core.vectors.numeric
- httk.core.vectors.scalar_like
- httk.core.vectors.surdvector
- httk.core.vectors.vector_api
- httk.core.vectors.vector_backend
- httk.core.vectors.vector_frac_view
- httk.core.vectors.vector_like
- httk.core.vectors.vector_native_backend
- httk.core.vectors.vector_native_view
- httk.core.vectors.vector_numpy_backend
- httk.core.vectors.vector_numpy_view
- httk.core.vectors.vector_surd_view
- httk.core.vectors.vector_view
- httk.core.vectors.vectormath
Attributes¶
Classes¶
Represents the fractional number |
|
Immutable exact-rational vector that is also its own vector backend. |
|
A leaf codec: a documented conversion of one exact |
|
Same as |
|
A scalar |
|
An immutable exact tensor over the squarefree-radical field |
|
Abstract base class for the canonical vector interface. |
|
Abstract base class for all backends of vector (tensor) data. |
|
A view presenting an underlying vector backend as an exact |
|
Backend for a vector backed by plain nested sequences. |
|
A view presenting an underlying vector backend as nested tuples, with a selectable leaf codec. |
|
A view presenting an underlying vector backend as an exact |
|
Abstract base class for all views of vector (tensor) data. |
Functions¶
Return the registered leaf-codec names in registration order. |
|
|
Register or replace a codec under its |
Return whether the optional numpy dependency is available for the numeric helpers. |
|
|
Present |
|
Convert a single scalar value to a plain |
Package Contents¶
- class httk.core.vectors.FracScalar(value, *, denom=None, simplify=True, chain=False, min_accuracy=fractions.Fraction(1, 10000))[source]¶
Bases:
FracVectorRepresents the fractional number
nom/denom. This is a subclass of FracVector with the purpose of making it clear when a scalar fracvector is needed/used.Convert a value into a FracScalar.
FracScalar(something)wheresomethingmay be any object that can be used in the constructor of the Python Fraction class (also works with strings!).For signature compatibility with the
FracVectorconstructor, this accepts but ignoreschainandmin_accuracy, and converts strings exactly via the Fraction constructor.- Parameters:
value (Any) – The scalar value or values to convert.
denom (int | None) – An optional additional denominator.
simplify (bool) – Whether to reduce the resulting denominator.
chain (bool) – An accepted compatibility parameter; it does not affect scalar creation.
min_accuracy (fractions.Fraction | None) – An accepted compatibility parameter; scalar strings are exact.
- class httk.core.vectors.FracVector(values, *, denom=None, simplify=True, chain=False, min_accuracy=fractions.Fraction(1, 10000))[source]¶
Bases:
FracVectorBase,httk.core.vectors.vector_backend.VectorBackendImmutable exact-rational vector that is also its own vector backend.
- property fractions: httk.core.vectors.vector_api.Fractions¶
Return this vector in the exact nested Fraction interchange format.
- class httk.core.vectors.LeafCodec[source]¶
A leaf codec: a documented conversion of one exact
fractions.Fractionleaf into a presentation leaf.A codec is an orthogonal layer beside the vector backends: given a value already reduced to the canonical Fraction hub, it produces the requested element type. Its
from_fractiondocuments both its exactness contract (when the result is exact) and its default conversion (what it does when an exact result is impossible); on data it never raises.- Parameters:
name – The canonical name used to select the codec.
from_fraction – The conversion operation applied to each exact hub leaf.
check_options – The option-validation operation.
- from_fraction: collections.abc.Callable[Ellipsis, Any]¶
Convert
(value: fractions.Fraction, **options) -> leaffrom the canonical Fraction hub.
- check_options: collections.abc.Callable[[dict[str, Any]], None]¶
Validate an options mapping eagerly, raising
ValueErroron any invalid option.
- httk.core.vectors.known_leaf_codecs()[source]¶
Return the registered leaf-codec names in registration order.
- httk.core.vectors.register_leaf_codec(codec)[source]¶
Register or replace a codec under its
name.- Parameters:
codec (LeafCodec) – The codec to register.
- class httk.core.vectors.MutableFracVector(values, *, denom=None, simplify=True, chain=False, min_accuracy=fractions.Fraction(1, 10000))[source]¶
Bases:
httk.core.vectors.fracvector.FracVectorBaseSame as
FracVector, only this version allows assignment of elements, e.g.:mfracvec[2, 7] = 5
and, e.g.:
mfracvec[:, 7] = [1, 2, 3, 4]
Other than this, the FracVector methods exist and do the same, i.e., they return copies of the fracvector, rather than modifying it.
- Parameters:
values (Any) – A rational value-like to convert, such as nested sequences or scalars.
denom (int | None) – An optional additional common denominator.
simplify (bool) – Whether to reduce the resulting denominator.
chain (bool) – Whether to flatten the outermost nested sequence.
min_accuracy (fractions.Fraction | None) – Minimum accuracy for decimal values, or
Nonefor exact conversion.
Methods with
set_*prefixes perform mutating operations, e.g.:A.set_T()
replaces A with its own transpose, whereas:
A.T()
just returns a new MutableFracVector that is the transpose of A, leaving A unmodified.
- nested_map: ClassVar[collections.abc.Callable[Ellipsis, Any]]¶
- nested_inmap: ClassVar[collections.abc.Callable[Ellipsis, Any]]¶
- nested_map_fractions: ClassVar[collections.abc.Callable[Ellipsis, Any]]¶
- noms: Any¶
- invalidate()[source]¶
Internal method to call when the MutableFracVector is changed in such a way that cached properties are invalidated (e.g.,
_dim).- Returns:
None.
- Return type:
None
- set_inv()[source]¶
Change the MutableFracVector inline into its own inverse:
self -> self^-1.- Returns:
The inverse scalar when
selfis scalar; otherwiseNoneafter mutation.- Return type:
Any
- set_simplify()[source]¶
Change the MutableFracVector; reduces any common factor between the denominator and all nominators.
- set_set_denominator(resolution=1000000000)[source]¶
Change the MutableFracVector; reduces resolution.
- Parameters:
resolution (int) – The new denominator; each element becomes the closest numerical approximation using this denominator.
- type httk.core.vectors.NumericVector = float | numpy.ndarray[source]¶
- httk.core.vectors.numpy_available()[source]¶
Return whether the optional numpy dependency is available for the numeric helpers.
This reads the vectors package’s
_numpy_availableflag freshly on each call (the flag set whenhttk.core.vectorsconditionally imports/registers the numpy backend), so tests may monkeypatchhttk.core.vectors._numpy_availableto exercise the numpy-absent path.- Returns:
Truewhen numpy is available, otherwiseFalse.- Return type:
- httk.core.vectors.to_numeric(obj)[source]¶
Present
objas plain numpy numbers: anumpy.ndarrayfor a tensor, afloatfor a scalar.A tensor becomes a base-class
float64numpy.ndarray(never a view subclass) viaVectorNumpyView; a scalar input (shape()) returns a plainfloatviato_numeric_scalar()(never a 0-d array).The numeric presentation is numpy-backed, so this always requires numpy: it raises
ImportError(naming thehttk-core[numpy]extra) when numpy is not installed, uniformly, so the contract is predictable regardless of the input shape. Useto_numeric_scalar()directly for a single float without a numpy requirement.- Parameters:
obj (httk.core.vectors.vector_like.VectorLike | float | str | fractions.Fraction) – The vector-like value to present numerically.
- Returns:
The converted scalar or tensor value.
- Raises:
ImportError – If numpy is unavailable.
TypeError – If the value cannot be converted to the numeric presentation.
- Return type:
- httk.core.vectors.to_numeric_scalar(obj)[source]¶
Convert a single scalar value to a plain
float, deterministically.A
SurdScalar(or scalarSurdVector) and a scalarFracVectorrender through their own exactto_float(); aFraction,int,float, or numericstrrender viaany_to_fraction(). A non-scalar shape raisesTypeError.Unlike
to_numeric(), this needs no numpy: a plainfloatconversion has no numpy dependency, so it works unconditionally and never raises for a missing numpy.
- type httk.core.vectors.ScalarLike = int | float | str | fractions.Fraction | decimal.Decimal | fracvector.FracScalar | surdvector.SurdScalar[source]¶
- class httk.core.vectors.SurdScalar(value)[source]¶
Bases:
SurdVectorA scalar
SurdVector(shape()): a single field element \(\sum_r q_r\sqrt r\).Adds the scalar-only operations — the field inverse, exact sign and ordering, and Decimal rendering — that need a single value rather than a tensor.
- Parameters:
value (Any) – A rational scalar/nested sequence accepted by
FracVector, or an existing SurdVector or SurdScalar, returned unchanged.
- inverse()[source]¶
Return the multiplicative inverse
1/self(raisesZeroDivisionErroron zero).- Returns:
The exact multiplicative inverse.
- Return type:
- sign()[source]¶
Return the exact sign of the value:
-1,0or1.For an irrational value the sign is decided by refining rational lower/upper bounds on each
sqrt(r)(frominteger_sqrt()at increasing precision) and summing the weighted intervals until the total interval excludes zero — which always happens in finitely many steps because a nonzero surd is bounded away from zero.- Returns:
-1,0, or1according to the exact sign.- Return type:
- classmethod cos_degrees(q)[source]¶
Return
cos(q degrees)as an exactSurdScalar, or None when it is not a surd.The value lies in the squarefree-radical field precisely when the angle, reduced modulo 360, is a multiple of 15 or of 36 degrees — e.g. \(\cos 30° = \tfrac{\sqrt3}2\), \(\cos 15° = \tfrac{\sqrt6+\sqrt2}4\), \(\cos 36° = \tfrac{1+\sqrt5}4\).
qmay be an int,Fraction, or numeric string (parsed viaany_to_fraction()).That list is complete: \(\cos(2\pi a/b)\) lies in a field generated by square roots of rationals iff the Galois group \((\mathbb{Z}/b)^\times/\{\pm1\}\) of \(\mathbb{Q}(\cos 2\pi/b)\) has exponent at most 2, which holds exactly for \(b \in \{1,2,3,4,5,6,8,10,12,24\}\) — the rational-degree angles that are multiples of 15° or 36°. (Niven’s theorem is the rational-value special case of this classification.) A
Noneresult is therefore a proof that the exact cosine lies outside \(\mathbb{Q}[\sqrt n]\) — usecos()withdegrees=Truefor a deterministic rational approximation in that case.- Parameters:
q (Any) – The angle in degrees.
- Returns:
The exact cosine, or
Noneoutside the surd field.- Return type:
SurdScalar | None
- classmethod sin_degrees(q)[source]¶
Return
sin(q degrees)as an exactSurdScalar, orNonewhen the value lies outside the supported surd field (when90 - qis not in the exact surd-cosine set).Computed as
cos(90 - q)degrees, so exactness follows the same classification ascos_degrees()applied to90 - q: exact when90 - qis a multiple of 15 or 36 degrees, andNoneotherwise (a proof that the exact sine is outside the field). For example,sin(54°)is exact because it iscos(36°).- Parameters:
q (Any) – The angle in degrees.
- Returns:
The exact sine, or
Noneoutside the surd field.- Return type:
SurdScalar | None
- acos_degrees()[source]¶
Return the exact
arccosof this value in degrees over \([0, 180]\), or None.This is the reverse table lookup: the result is an exact rational number of degrees precisely when the value equals the cosine of a multiple of 15° or 36° (the complete set of rational-degree angles with surd cosines — see
cos_degrees()), decided by exact surd equality; otherwise None (the exact angle is then irrational in degrees). RaisesValueError— decided exactly viasign()— when the value lies outside \([-1, 1]\).- Returns:
The exact angle in degrees, or
Nonewhen not represented by the table.- Return type:
fractions.Fraction | None
- to_float(prec=fractions.Fraction(1, 10**30))[source]¶
Return the value as a float via a high-precision exact rational approximation.
- Parameters:
prec (fractions.Fraction) – The maximum approximation error.
- Returns:
The value as a float.
- Return type:
- to_decimal(digits=None, rounding='half_even', max_refinements=None)[source]¶
Render the value as a correctly-rounded
decimal.Decimal.Reuses the exact-math module’s Ziv refinement loop (
_to_decimal): a rational value renders exactly (its finite expansion when it fits, else quantized), and an irrational surd — never on a rational rounding boundary — is rendered by refining the rational approximation until the rounding is determined.digits(significant digits; default: the active decimal context precision),rounding("half_even"/"down") andmax_refinementsmatchsqrt()in Decimal mode.- Parameters:
- Returns:
The correctly rounded decimal value.
- Return type:
Any
- class httk.core.vectors.SurdVector(value)[source]¶
Bases:
httk.core.vectors.vector_backend.VectorBackendAn immutable exact tensor over the squarefree-radical field \(\mathbb{Q}[\sqrt n : n\ \text{squarefree}]\).
A SurdVector is a map
{squarefree radicand -> FracVector coefficient}(all coefficients sharing onedim); radicand1is the rational part. It is stored canonically — coefficients simplified, all-zero coefficients dropped — so the representation is unique and equality/zero-detection are exact. LikeFracVectorit is immutable and hashable.See the module docstring for the field facts, the fractional-vs-Cartesian motivation, and the magnitude-vs-linear-structure purpose boundary.
- Parameters:
value (Any) – An existing SurdVector or SurdScalar, returned unchanged, or a rational scalar/nested sequence accepted by
FracVector; rational values become the radicand-1 component.
- classmethod from_components(components, dim)[source]¶
Build from trusted component vectors and a shared shape.
- classmethod from_radicand_map(mapping)[source]¶
Compose a SurdVector from a
{radicand -> coefficient}mapping.Radicands are positive integers and need not be squarefree — each is normalized via
square_part(sqrt(radicand) = s*sqrt(r)) and the coefficients (FracVector-like, all of one shape) folded together canonically.
- classmethod sqrt_of(q)[source]¶
Return the exact square root of a nonnegative rational
qas aSurdScalar.The result is a plain rational when
qis a perfect square (e.g.sqrt_of(4/9) == 2/3) and otherwise a single-radical surd (sqrt_of(8) == 2*sqrt(2)).sqrt(p/q)is normalized assqrt(p*q)/qso the stored radicand is always a positive squarefree integer (sqrt_of(1/2) == sqrt(2)/2). RaisesValueErroron a negative argument — there is no exact square root of a surd (no nested radicals), only of a rational.- Parameters:
q (Any) – A nonnegative rational value.
- Returns:
Its exact square root.
- Return type:
- classmethod zero(dim=())[source]¶
The zero SurdVector of shape
dim(aSurdScalarfor the default()).- Parameters:
- Returns:
The zero SurdVector or SurdScalar.
- Return type:
- property is_rational: bool¶
True iff the value is purely rational (only the radicand-1 term is present).
- property radicands: tuple[int, Ellipsis]¶
The sorted squarefree radicands present in the canonical form.
- coefficient(radicand)[source]¶
Return the FracVector coefficient of
sqrt(radicand)(a zero tensor when absent).- Parameters:
radicand (int) – The radicand whose coefficient to retrieve.
- Returns:
The coefficient, or a zero tensor when absent.
- Return type:
- T()[source]¶
Return the transpose, transposing each radicand’s coefficient tensor.
- Returns:
The transposed tensor.
- Return type:
- dot(other)[source]¶
Return the vector dot product of two 1-D SurdVectors (
sum a_i b_i).- Parameters:
other (Any) – The other 1-D SurdVector.
- Returns:
The exact scalar dot product.
- Return type:
- lengthsqr()[source]¶
Return the squared length
A * A^Tas aSurdScalar.- Returns:
The exact squared length.
- Return type:
- length()[source]¶
Return the exact length
sqrt(lengthsqr)as aSurdScalar.Exact precisely when
lengthsqris rational — which canonical arithmetic guarantees for a difference of Cartesian sites under a rational metric (the crystallographic case). Whenlengthsqris itself irrational the length would be a nested radical (sqrt(a + b*sqrt(c))), which is outside the field, so this raisesValueError.- Returns:
The exact length when the squared length is rational.
- Return type:
- det()[source]¶
Return the determinant of a 3x3 SurdVector as a
SurdScalar.- Returns:
The exact determinant.
- Return type:
- inv()[source]¶
Return the inverse of a 3x3 SurdVector via the adjugate and the scalar field inverse.
- Returns:
The exact inverse matrix.
- Return type:
- to_fractions_approx(prec=fractions.Fraction(1, 10**30))[source]¶
A deterministic nested list of
fractions.Fractionwithinprecof the true value.Exact (not merely within
prec) whenever the value is rational. This is thecompute(prec)-shaped rational approximation reused by the Decimal rendering.- Parameters:
prec (fractions.Fraction) – The maximum elementwise approximation error.
- Returns:
Nested rational approximations of the values.
- Return type:
Any
- to_floats(prec=fractions.Fraction(1, 10**30))[source]¶
Return a nested list of floats via a high-precision exact rational approximation.
- Parameters:
prec (fractions.Fraction) – The maximum elementwise approximation error.
- Returns:
Nested floating-point approximations of the values.
- Return type:
Any
- property fractions: httk.core.vectors.vector_api.Fractions¶
Return the exact or deterministic rational hub representation.
- class httk.core.vectors.VectorAPI[source]¶
Bases:
abc.ABCAbstract base class for the canonical vector interface.
It declares the
fractionsaccessor (a nested tuple offractions.Fraction, or a bare Fraction for a scalar) that every vector backend produces from its own native representation and every vector view builds its presentation from, together with thedimshape tuple. The interchange is exact whenfractions_exactis True; members such as irrational surds whose hub is a deterministic approximation report False, and exact construction paths refuse them. This is the single interchange format; there is no pairwise conversion between backends.On top of the two abstract accessors it provides the guaranteed float renderings
to_floats()andto_float(), derived from thefractionshub — so whatever object the family hands you,.to_floats()works. (The exact value typesFracVectorandSurdVectorhonor the same contract with their own implementations, while the numpy backend adds a dtype-guarded fast path with the hub as fallback. Surd values render floats at fixed high precision independent of the decimal context, unlike the hub’s context-precision reduction.- property fractions_exact: bool¶
Return whether
fractionsreproduces this value exactly.Members whose Fraction interchange may be a deterministic approximation override this property with
False; exact construction paths must refuse those members.
- property dim: tuple[int, Ellipsis]¶
- Abstractmethod:
Return the tensor shape as a tuple of dimensions.
- to_floats()[source]¶
Return the value as nested lists of floats.
The value as (possibly nested) plain lists of
float— a barefloatfor a scalar.Derived from the
fractionshub; whenfractions_exactis False, the result is the member’s deterministic approximation. Nested lists match thenumpy.ndarray.tolist()convention and are directly JSON-serializable.- Returns:
The rendered value.
- Return type:
Any
- class httk.core.vectors.VectorBackend(backend, **hints)[source]¶
Bases:
httk.core.views.Backend[VectorBackend],httk.core.vectors.vector_api.VectorAPIAbstract base class for all backends of vector (tensor) data.
Concrete backends carry a native representation (an exact FracVector, plain nested sequences, or a numpy array) and produce the canonical exactness-preserving
fractionsinterchange declared byVectorAPIfrom it.Concrete subclasses select the accepted input and optional dispatch hints in their
_backend_adopthooks.- backend_classes: ClassVar[list[type[httk.core.views.Backend[Any]]]]¶
- class httk.core.vectors.VectorFracView(obj, **hints)[source]¶
Bases:
httk.core.vectors.vector_view.VectorView,httk.core.vectors.fracvector.FracVectorA view presenting an underlying vector backend as an exact
FracVector.This view is a genuine FracVector, so it can be passed anywhere a FracVector is accepted, and it exposes the full exact-rational algebra (
det/inv/*/…). It is built lazily on first access — adopting a frac backend’s FracVector directly, otherwise converting from the backend’s exactfractionsinterchange — so the round-trip is exactness-preserving for the frac and native backends. (numpy values are binary rationals, so a numpy source round-trips to the exact float64 rational, not necessarily the original decimal fraction.)Because inherited FracVector algebra builds its results with the low-level
self.__class__.from_noms_and_denom(noms, denom)constructor, results built that way are plain (backend-less) FracVector values presented through this class.- Parameters:
obj (httk.core.vectors.vector_like.VectorLike) – The source value to present.
**hints (Any) – Backend-selection and view-conversion hints.
- property noms: httk.core.vectors.fracvector.Noms¶
Return the materialized numerator data.
- type httk.core.vectors.VectorLike = vector_backend.VectorBackend | vector_view.VectorView | fracvector.FracVector | surdvector.SurdVector | tuple[Any, ...] | list[Any] | 'numpy.ndarray'[source]¶
- class httk.core.vectors.VectorNativeBackend(obj, **hints)[source]¶
Bases:
httk.core.vectors.vector_backend.VectorBackendBackend for a vector backed by plain nested sequences.
The native representation is a (possibly nested) rectangular list or tuple whose leaves are
int,float,decimal.Decimal,fractions.Fraction, orstr. Conversion into the exactfractionsinterchange goes throughFracVector, so string-uncertainty parsing (e.g."0.33342(10)") works here too.unwrapreturns the original raw object.- Parameters:
obj (Any) – The rectangular source data to wrap.
**hints (Any) – Optional backend-selection hints.
- property native: Any¶
The original nested list/tuple this backend wraps, leaves untouched.
This is the same object returned by
unwrap(), exposed as a named accessor so the native view can present a natively-held vector’s leaves verbatim (its preserve-original default) without reaching into private state.
- property fractions: httk.core.vectors.vector_api.Fractions¶
Return the native value in the exact Fraction interchange format.
- class httk.core.vectors.VectorNativeView(obj, **hints)[source]¶
Bases:
httk.core.vectors.vector_view.VectorView,tupleA view presenting an underlying vector backend as nested tuples, with a selectable leaf codec.
The leaf codec is the element-domain axis (see
httk.core.vectors.leaf_codecs); it is chosen with theleaf=hint plus any codec options (rounding=,digits=, …). There are three modes:preserve-original (
leaf=None, and the source is natively-held data): the backend’s original nested leaves are presented verbatim — the same objects, only containers tuple-ized (Decimal\ s in, the sameDecimal\ s out).exact default (
leaf=None, source crossing from a frac/numpy backend): the"exact"codec —intwhen integral, elsefractions.Fraction, never a float.explicit codec (
leaf="int"/"float"/"decimal"/"fraction"/…): every element is converted from the backend’s exactfractionsinterchange through that codec.
The codec name and its options are validated eagerly at construction (an unknown codec name or invalid option raises
ValueError); a codec never raises on the data — a value it cannot represent exactly takes the codec’s documented default conversion, because the backend keeps the exact original. A scalar source is presented as a single-element tuple.- Parameters:
obj (httk.core.vectors.vector_like.VectorLike) – The source value to present.
**hints (Any) – Backend-selection, leaf-codec, and codec-option hints.
- class httk.core.vectors.VectorSurdView(obj, **hints)[source]¶
Bases:
httk.core.vectors.vector_view.VectorView,httk.core.vectors.surdvector.SurdVectorA view presenting an underlying vector backend as an exact
SurdVector.This view is a genuine SurdVector, so it exposes the full exact surd algebra (
det/inv/*/length/...). It is built lazily on first access, following the immutable-subclass pattern of :class:`~httk.core.vectors.vector_frac_view.VectorFracView`: from a surd backend it adopts the exact SurdVector directly, and from a frac/native/numpy backend it embeds the backend's exact rational ``fractionsat radicand 1 — exactly, since every rational is a surd.(numpy values are binary rationals, so a numpy source embeds the exact float64 rational, not necessarily the original decimal fraction — the same caveat as
VectorFracView.)- Parameters:
obj (httk.core.vectors.vector_like.VectorLike) – The source value to present.
**hints (Any) – Backend-selection and view-conversion hints.
- class httk.core.vectors.VectorView[source]¶
Bases:
httk.core.views.View[httk.core.vectors.vector_backend.VectorBackend]Abstract base class for all views of vector (tensor) data.
Concrete views present a backend through a specific container or leaf domain while retaining access to the underlying backend.