httk.core.vectors.fracvector

Exact-rational vector (tensor) algebra: FracVector and FracScalar.

Attributes

Classes

FracVectorBase

Shared implementation for immutable FracVector and mutable

FracVector

Immutable exact-rational vector that is also its own vector backend.

FracScalar

Represents the fractional number nom/denom. This is a subclass of FracVector with the

Module Contents

type httk.core.vectors.fracvector.Noms = int | tuple[Noms, ...]
class httk.core.vectors.fracvector.FracVectorBase(values, *, denom=None, simplify=False, chain=False, min_accuracy=fractions.Fraction(1, 10000))

Shared implementation for immutable FracVector and mutable MutableFracVector N-dimensional exact-rational tensors.

A FracVector consists of a multidimensional tuple of integer nominators, and a single shared integer denominator.

Since FracVectors are immutable, every operation on a FracVector returns a new FracVector with the result of the operation. A created FracVector never changes. Hence, they are safe to use as keys in dictionaries, to use in sets, etc.

Note: most methods return FracVector results that are not simplified (i.e., the FracVector returned does not have the smallest possible integer denominator). To return a FracVector with the smallest possible denominator, just call simplify() at the last step.

Create a FracVector from various types of sequences.

Simplest use:

FracVector(some_kind_of_sequence)

where some_kind_of_sequence can be any nested list or tuple of objects that can be used in the constructor of the Python Fraction class (also works with strings!). If any object found while traveling the items has a .to_fractions() method, it will be called and is expected to return a fraction or list or tuple of fractions.

Parameters:
  • values (Any) – A nested sequence of objects accepted by fractions.Fraction.

  • denom (int | None) – An optional additional common denominator for all nominators.

  • simplify (bool) – Whether to return a FracVector with the smallest possible denominator.

  • chain (bool) – Whether to remove the outermost dimension and chain the sub-sequences. I.e., if input=[[1, 2, 3], [4, 5, 6]] then FracVector(input, chain=True) gives [1, 2, 3, 4, 5, 6].

  • min_accuracy (fractions.Fraction | None) – The minimum accuracy assumed in string input. The default is 1/10000, i.e. 0.33 = 0.3300 = 33/100, whereas 0.3333 = 1/3. Set it to None to assume infinite accuracy, i.e. convert exactly whatever string is given (unless a standard deviation is given as a parenthesis after the string).

Note: FracVector itself implements .to_fractions(), and hence the same constructor allows stacking several FracVector objects like this:

vertical_fracvector = FracVector([[fracvector1], [fracvector2]])
horizontal_fracvector = FracVector([fracvector1, fracvector2], chain=True)
nested_map: ClassVar[collections.abc.Callable[Ellipsis, Any]]
nested_map_fractions: ClassVar[collections.abc.Callable[Ellipsis, Any]]
noms: Noms
denom: int
get_append(other)

Return a new vector with other appended as one element.

Parameters:

other (Any) – The element to append.

Returns:

The extended vector.

Return type:

Self

get_extend(other)

Return a new vector with the elements of other appended.

Parameters:

other (Any) – The elements to append.

Returns:

The extended vector.

Return type:

Self

get_insert(pos, other)

Return a new vector with other inserted at pos.

Parameters:
  • pos (int) – The insertion position.

  • other (Any) – The element to insert.

Returns:

The extended vector.

Return type:

Self

get_prepend(other)

Return a new vector with other prepended as one element.

Parameters:

other (Any) – The element to prepend.

Returns:

The extended vector.

Return type:

Self

get_prextend(other)

Return a new vector with the elements of other prepended.

Parameters:

other (Any) – The elements to prepend.

Returns:

The extended vector.

Return type:

Self

get_stacked(other)

Return a new FracVector with other stacked after self along a new leading axis.

self and other must have the same shape; the result gains one extra outermost dimension of size two (numpy stack-like). E.g. stacking the row [1, 2, 3] with [4, 5, 6] gives [[1, 2, 3], [4, 5, 6]].

Parameters:

other (Any) – A vector with the same shape as self.

Returns:

The stacked vector.

Return type:

Self

get_prestacked(other)

Return a new FracVector with other stacked before self along a new leading axis.

The mirror of get_stacked(): stacking [1, 2, 3] in front with [4, 5, 6] gives [[4, 5, 6], [1, 2, 3]].

Parameters:

other (Any) – A vector with the same shape as self.

Returns:

The prestacked vector.

Return type:

Self

get_stackedinsert(pos, other)

Return a new vector with other inserted at pos along the flattened axis.

Parameters:
  • pos (int) – The insertion position.

  • other (Any) – The element to insert.

Returns:

The extended vector.

Return type:

Self

classmethod chain_vecs(vecs)

Optimized chaining of FracVectors.

Parameters:

vecs (Any) – FracVectors that all share the same denominator.

Returns:

The same thing as FracVector(vecs, chain=True), i.e., removes the outermost dimension and chains the sub-sequences. If input=[[1, 2, 3], [4, 5, 6]] then it gives [1, 2, 3, 4, 5, 6], but this method assumes all vectors share the same denominator (it raises an exception if this is not true).

Return type:

Self

classmethod stack_vecs(vecs)

Optimized stacking of FracVectors.

Parameters:

vecs (Any) – FracVectors that all share the same denominator.

Returns:

The same thing as FracVector(vecs), but only works if all vectors share the same denominator (raises an exception if this is not true).

Return type:

Self

classmethod eye(dims)

Create a diagonal one-matrix with the given dimensions.

Parameters:

dims (tuple[int, Ellipsis]) – The shape of the diagonal tensor.

Returns:

The diagonal one-matrix.

Return type:

Self

classmethod zeros(dims)

Create a zero matrix with the given dimensions.

Parameters:

dims (tuple[int, Ellipsis]) – The shape of the zero tensor.

Returns:

The zero matrix.

Return type:

Self

classmethod random(dims, minnom=-100, maxnom=100, denom=100)

Create a matrix with the given dimensions filled with random rational numbers.

Parameters:
  • dims (tuple[int, Ellipsis]) – The shape of the generated matrix.

  • minnom (int) – The inclusive lower bound for generated nominators.

  • maxnom (int) – The inclusive upper bound for generated nominators.

  • denom (int) – The shared denominator for generated values.

Returns:

The generated matrix.

Return type:

Self

classmethod from_tuple(t)

Return a FracVector created from the tuple representation (denom, noms), as returned by the to_tuple() method. from_tuple(v.to_tuple()) reconstructs v exactly.

Parameters:

t (tuple[int, Noms]) – The (denom, noms) representation to reconstruct.

Returns:

The reconstructed FracVector.

Return type:

Self

classmethod from_cos(data, degrees=False, limit=False, find_best_rational=True, prec=fractions.Fraction(1, 1000000))

Create a FracVector as the cosine of the argument data. If data is composed of strings, the standard deviation of the numbers is taken into account, and the best possible fractional approximation to the cosines of the data is returned within the standard deviation.

This is not the same as FracVector(data).cos(), which creates the best possible fractional approximations of data and then takes cos on that.

Parameters:
  • data (Any) – Values to transform elementwise.

  • degrees (bool) – Whether to interpret values in degrees.

  • limit (bool) – Whether to bound the resulting denominator by the precision.

  • find_best_rational (bool) – Whether to choose the best rational within each input interval.

  • prec (fractions.Fraction) – The requested approximation precision.

Returns:

The elementwise cosine vector.

Return type:

Self

classmethod from_sin(data, degrees=False, limit=False, prec=fractions.Fraction(1, 1000000))

Create a FracVector as the sine of the argument data. If data is composed of strings, the standard deviation of the numbers is taken into account, and the best possible fractional approximation to the sines of the data is returned within the standard deviation.

This is not the same as FracVector(data).sin(), which creates the best possible fractional approximations of data and then takes sin on that.

Parameters:
  • data (Any) – Values to transform elementwise.

  • degrees (bool) – Whether to interpret values in degrees.

  • limit (bool) – Whether to bound the resulting denominator by the precision.

  • prec (fractions.Fraction) – The requested approximation precision.

Returns:

The elementwise sine vector.

Return type:

Self

classmethod from_exp(data, prec=fractions.Fraction(1, 1000000), limit=False)

Create a FracVector as the exponent of the argument data. If data is composed of strings, the standard deviation of the numbers is taken into account, and the best possible fractional approximation to the exponents of the data is returned within the standard deviation.

This is not the same as FracVector(data).exp(), which creates the best possible fractional approximations of data and then takes exp on that.

Parameters:
  • data (Any) – Values to transform elementwise.

  • prec (fractions.Fraction) – The requested approximation precision.

  • limit (bool) – Whether to bound the resulting denominator by the precision.

Returns:

The elementwise exponential vector.

Return type:

Self

classmethod pi(prec=fractions.Fraction(1, 1000000), limit=False)

Create a scalar FracVector with a rational approximation of pi to precision prec.

Parameters:
  • prec (fractions.Fraction) – The requested approximation precision.

  • limit (bool) – Whether to bound the denominator by the precision.

Returns:

A scalar rational approximation of pi.

Return type:

Self

property dim: tuple[int, Ellipsis]

A tuple with the dimensionality of each dimension of the FracVector (the noms are assumed to be a nested list of rectangular shape).

property nom: int

Return the integer nominator of a scalar FracVector.

validate()

Return whether the vector’s stored structure is valid.

to_tuple()

Return the FracVector on tuple representation (denom, ...noms...).

Returns:

The denominator and nested nominators.

Return type:

tuple[int, Noms]

to_floats()

Convert the FracVector to a (nested) list of floats.

Returns:

The values converted to floats.

Return type:

Any

to_float()

Convert a scalar FracVector to a single float.

Returns:

The scalar value as a float.

Return type:

float

to_fractions()

Convert the FracVector to a (nested) list of fractions.

Returns:

The values converted to fractions.Fraction instances.

Return type:

Any

to_fraction()

Convert a scalar FracVector to a fraction.

Returns:

The scalar value as a fraction.

Return type:

fractions.Fraction

flatten()

Return a FracVector that has been flattened out to a single row vector.

Returns:

The flattened vector.

Return type:

Self

classmethod set_common_denom(A, B)

Used internally to combine two different FracVectors.

Returns a tuple (A2, B2, denom) where A2 is numerically equal to A, and B2 is numerically equal to B, but A2 and B2 are both set on the same shared denominator denom, which is the product of the denominators of A and B.

Parameters:
  • A (Any) – The first vector or value.

  • B (Any) – The second vector or value.

Returns:

The converted first vector, second vector, and shared denominator.

Return type:

tuple[Self, Self, int]

sign()

Return the sign of the scalar FracVector: -1, 0 or 1.

Returns:

-1, 0, or 1 according to the scalar sign.

Return type:

int

T()

Return the transpose, A^T.

Returns:

The transposed vector or matrix.

Return type:

Self

det()

Return the determinant of the FracVector as a scalar FracVector.

Returns:

The determinant.

Return type:

Self

inv()

Return the matrix inverse, A^-1.

Returns:

The inverse scalar or matrix.

Return type:

Self

simplify()

Return a reduced FracVector. I.e., each element has the same numerical value but the new FracVector represents them using the smallest possible shared denominator.

The result is canonical: two numerically equal FracVectors always simplify to the same (denom, noms) pair. That requires normalizing the sign as well as reducing by the greatest common divisor, since (1, 0, 0)/-2 and (-1, 0, 0)/2 are the same value and neither is reducible. Canonicality is what __hash__ relies on to stay consistent with __eq__.

Returns:

The reduced, canonical vector.

Return type:

Self

simplify_fast(depth)

Return a reduced FracVector, taking advantage of a known nesting depth. I.e., each element has the same numerical value but the new FracVector represents them using the smallest possible shared denominator.

Parameters:

depth (int) – The known nesting depth of the nominators.

Returns:

The reduced vector.

Return type:

Self

set_denominator(set_denom=1000000000)

Return a FracVector of reduced resolution where every element is the closest numerical approximation using this denominator.

Parameters:

set_denom (int) – The denominator to use for the approximation.

Returns:

The approximated vector.

Return type:

Self

limit_denominator(max_denom=1000000000)

Return a FracVector of reduced resolution.

Each element in the returned FracVector is the closest numerical approximation that is allowed by a fraction with maximally this denominator. Note: since all elements must be put on a common denominator, the result may have a larger denominator than max_denom.

Parameters:

max_denom (int) – The largest denominator allowed for each element’s approximation.

Returns:

The approximated vector.

Return type:

Self

floor()

Return the integer that is equal to or just below the value stored in a scalar FracVector.

Returns:

The floor of the scalar value.

Return type:

int

modf()

Return the fractional and integer parts of each element as the pair (fractional, integer) of exact FracVectors sharing this vector’s denominator.

Both parts carry the sign of the element and the integer part truncates toward zero, matching the conventions of math.modf() (e.g. the value -5/2 splits into -1/2 and -2).

Returns:

The fractional and integer parts, in that order.

Return type:

tuple[FracVector, FracVector]

ceil()

Return the integer that is equal to or just above the value stored in a scalar FracVector.

Returns:

The ceiling of the scalar value.

Return type:

int

normalize()

Add/remove an integer +/-N to each element to place it in the range [0, 1).

Returns:

The normalized vector.

Return type:

Self

normalize_half()

Add/remove an integer +/-N to each element to place it in the range [-1/2, 1/2).

This is useful to find the shortest vector C between two points A, B in a space with periodic boundary conditions [0, 1):

C = (A - B).normalize_half()
Returns:

The vector normalized into the half-open interval.

Return type:

Self

mul(other)

Return the result of multiplying the vector with other using matrix multiplication.

Note that for two 1D FracVectors, A.dot(B) is not the same as A.mul(B), but rather A.mul(B.T()).

Parameters:

other (Any) – The vector or scalar to multiply.

Returns:

The exact matrix product.

Return type:

Self

dot(other)

Return the vector dot product of the 1D vector with the 1D vector other, i.e., A . B. The same as A * B.T().

Parameters:

other (FracVector) – The other 1-D vector.

Returns:

The exact dot product.

Return type:

Self

lengthsqr()

Return the square of the length of the vector. The same as A * A.T().

Returns:

The exact squared length.

Return type:

Self

cross(other)

Return the vector cross product of the 3-element 1D vector with the 3-element 1D vector other, i.e., A x B.

Parameters:

other (FracVector) – The other 3-element vector.

Returns:

The exact cross product.

Return type:

Self

reciprocal()

Return the reciprocal matrix of a 3x3 matrix (the rows are the reciprocal vectors, without the 2*pi factor).

Returns:

The reciprocal matrix.

Return type:

Self

metric_product(vecA, vecB)

Return the result of the metric product using the present square FracVector as the metric matrix. The same as vecA * self * vecB.T().

Parameters:
  • vecA (FracVector) – The first vector or matrix operand.

  • vecB (FracVector) – The second vector or matrix operand.

Returns:

The metric product.

Return type:

Self

cos(prec=None, degrees=False, limit=False)

Return a FracVector where every element is the cosine of the element in the source FracVector.

Parameters:
  • prec (fractions.Fraction | None) – The requested approximation precision.

  • degrees (bool) – Whether to interpret the elements in degrees.

  • limit (bool) – Whether to limit the denominator to at most 1 / prec.

Returns:

The elementwise cosine vector.

Return type:

Self

sin(prec=None, degrees=False, limit=False)

Return a FracVector where every element is the sine of the element in the source FracVector.

Parameters:
  • prec (fractions.Fraction | None) – The requested approximation precision.

  • degrees (bool) – Whether to interpret the elements in degrees.

  • limit (bool) – Whether to limit the denominator to at most 1 / prec.

Returns:

The elementwise sine vector.

Return type:

Self

acos(prec=None, degrees=False, limit=False)

Return a FracVector where every element is the arccos of the element in the source FracVector.

Parameters:
  • prec (fractions.Fraction | None) – The requested approximation precision.

  • degrees (bool) – Whether to return the result in degrees.

  • limit (bool) – Whether to limit the denominator to at most 1 / prec.

Returns:

The elementwise arccosine vector.

Return type:

Self

asin(prec=None, degrees=False, limit=False)

Return a FracVector where every element is the arcsin of the element in the source FracVector.

Parameters:
  • prec (fractions.Fraction | None) – The requested approximation precision.

  • degrees (bool) – Whether to return the result in degrees.

  • limit (bool) – Whether to limit the denominator to at most 1 / prec.

Returns:

The elementwise arcsine vector.

Return type:

Self

exp(prec=None, limit=False)

Return a FracVector where every element is the exponent of the element in the source FracVector.

Parameters:
  • prec (fractions.Fraction | None) – The requested approximation precision.

  • limit (bool) – Whether to limit the denominator to at most 1 / prec.

Returns:

The elementwise exponential vector.

Return type:

Self

sqrt(prec=None, limit=False)

Return a FracVector where every element is the sqrt of the element in the source FracVector.

Parameters:
  • prec (fractions.Fraction | None) – The requested approximation precision.

  • limit (bool) – Whether to limit the denominator to at most 1 / prec.

Returns:

The elementwise square-root vector.

Return type:

Self

max()

Return the maximum element across all dimensions in the FracVector. max(fracvector) works for a 1D vector.

Returns:

The maximum scalar element.

Return type:

Self

nargmax()

Return a list of indices of all maximum elements across all dimensions in the FracVector.

Returns:

The indices of all maximum elements.

Return type:

list[Any]

argmax()

Return the index of the maximum element across all dimensions in the FracVector.

Returns:

The index of one maximum element.

Return type:

Any

min()

Return the minimum element across all dimensions in the FracVector. min(fracvector) works for a 1D vector.

Returns:

The minimum scalar element.

Return type:

Self

nargmin()

Return a list of indices for all minimum elements across all dimensions in the FracVector.

Returns:

The indices of all minimum elements.

Return type:

list[Any]

argmin()

Return the index of the minimum element across all dimensions in the FracVector.

Returns:

The index of one minimum element.

Return type:

Any

class httk.core.vectors.fracvector.FracVector(values, *, denom=None, simplify=False, chain=False, min_accuracy=fractions.Fraction(1, 10000))

Bases: FracVectorBase, httk.core.vectors.vector_backend.VectorBackend

Immutable 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.fracvector.FracScalar(value, *, denom=None, simplify=False, chain=False, min_accuracy=fractions.Fraction(1, 10000))

Bases: FracVector

Represents 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) where something may be any object that can be used in the constructor of the Python Fraction class (also works with strings!).

For signature compatibility with the FracVector constructor, this accepts but ignores chain and min_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.