httk.core.vectors.fracvector

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

Attributes

Classes

FracVector

FracVector is a general immutable N-dimensional vector (tensor) class for performing

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, ...][source]
class httk.core.vectors.fracvector.FracVector(noms: Noms, denom: int = 1)[source]

FracVector is a general immutable N-dimensional vector (tensor) class for performing linear algebra with fractional numbers.

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.

nested_map: ClassVar[collections.abc.Callable[Ellipsis, Any]][source]
nested_map_fractions: ClassVar[collections.abc.Callable[Ellipsis, Any]][source]
noms: Noms[source]
denom: int[source]
classmethod use(old: Any) FracVector[source]

Make sure the variable is a FracVector, and if not, convert it.

classmethod create(noms: Any, denom: int | None = None, simplify: bool = True, chain: bool = False, min_accuracy: fractions.Fraction | None = fractions.Fraction(1, 10000)) Self[source]

Create a FracVector from various types of sequences.

Simplest use:

FracVector.create(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:
  • noms – any nested sequence of Fraction-constructible objects.

  • denom – an optional common denominator to divide all nominators with.

  • simplify – if True, return a FracVector with the smallest possible denominator.

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

  • min_accuracy – 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.create([[fracvector1], [fracvector2]])
horizontal_fracvector = FracVector.create([fracvector1, fracvector2], chain=True)
classmethod create_fast(noms: Any, common_denom: int = 1, max_denom: int | None = None, denom: int | None = None, simplify: bool = True, chain: bool = False) Self[source]

Optimized version of create() that takes advantage of the fact that the type of noms is a nested list of ints (of depth 2 or 3) over a single common_denom.

get_append(other: Any) Self[source]
get_extend(other: Any) Self[source]
get_insert(pos: int, other: Any) Self[source]
get_prepend(other: Any) Self[source]
get_prextend(other: Any) Self[source]
get_stacked(other: Any) Self[source]

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]]. (The legacy version wrapped other in a redundant extra list, producing a ragged, non-rectangular result.)

get_prestacked(other: Any) Self[source]

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]].

get_stackedinsert(pos: int, other: Any) Self[source]
classmethod chain_vecs(vecs: Any) Self[source]

Optimized chaining of FracVectors.

Parameters:

vecs – a list (or tuple) of fracvectors that all share the same denominator.

Returns the same thing as FracVector.create(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).

classmethod stack_vecs(vecs: Any) Self[source]

Optimized stacking of FracVectors.

Parameters:

vecs – a list (or tuple) of fracvectors that all share the same denominator.

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

classmethod eye(dims: tuple[int, Ellipsis]) Self[source]

Create a diagonal one-matrix with the given dimensions.

classmethod zeros(dims: tuple[int, Ellipsis]) Self[source]

Create a zero matrix with the given dimensions.

classmethod random(dims: tuple[int, Ellipsis], minnom: int = -100, maxnom: int = 100, denom: int = 100) Self[source]

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

classmethod from_tuple(t: tuple[int, Noms]) Self[source]

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.

classmethod from_floats(data: Any, resolution: int = 2**32) Self[source]

Create a FracVector from a (nested) list or tuple of floats. You can convert a numpy array with this method if you use A.tolist().

Parameters:
  • l – the (nested) list or tuple of floats.

  • resolution – the resolution used for interpreting the given floating point numbers. Default is 2**32.

classmethod create_cos(data: Any, degrees: bool = False, limit: bool = False, find_best_rational: bool = True, prec: fractions.Fraction = fractions.Fraction(1, 1000000)) Self[source]

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.create(data).cos(), which creates the best possible fractional approximations of data and then takes cos on that.

classmethod create_sin(data: Any, degrees: bool = False, limit: bool = False, prec: fractions.Fraction = fractions.Fraction(1, 1000000)) Self[source]

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.create(data).sin(), which creates the best possible fractional approximations of data and then takes sin on that.

classmethod create_exp(data: Any, prec: fractions.Fraction = fractions.Fraction(1, 1000000), limit: bool = False) Self[source]

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.create(data).exp(), which creates the best possible fractional approximations of data and then takes exp on that.

classmethod pi(prec: fractions.Fraction = fractions.Fraction(1, 1000000), limit: bool = False) Self[source]

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

property dim: tuple[int, Ellipsis][source]

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[source]

Return the integer nominator of a scalar FracVector.

validate() bool[source]
to_tuple() tuple[int, Noms][source]

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

to_floats() Any[source]

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

to_float() float[source]

Convert a scalar FracVector to a single float.

to_fractions() Any[source]

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

to_ints() Any[source]

Convert the FracVector to a (nested) list of integers, rounded off as best possible.

to_strings(accuracy: int = 8) Any[source]

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

to_string(accuracy: int = 8) str[source]

Convert a scalar FracVector to a single string.

to_fraction() fractions.Fraction[source]

Convert a scalar FracVector to a fraction.

to_int() int[source]

Convert a scalar FracVector to an integer (truncating as necessary).

flatten() Self[source]

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

classmethod set_common_denom(A: Any, B: Any) tuple[Self, Self, int][source]

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.

sign() int[source]

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

T() Self[source]

Return the transpose, A^T.

det() Self[source]

Return the determinant of the FracVector as a scalar FracVector.

inv() Self[source]

Return the matrix inverse, A^-1.

simplify() Self[source]

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.

simplify_fast(depth: int) Self[source]

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.

set_denominator(set_denom: int = 1000000000) Self[source]

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

limit_denominator(max_denom: int = 1000000000) Self[source]

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.

floor() int[source]

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

modf() tuple[FracVector, FracVector][source]

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).

ceil() int[source]

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

normalize() Self[source]

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

normalize_half() Self[source]

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()
mul(other: Any) Self[source]

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()).

dot(other: FracVector) Self[source]

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

lengthsqr() Self[source]

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

cross(other: FracVector) Self[source]

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

reciprocal() Self[source]

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

metric_product(vecA: FracVector, vecB: FracVector) Self[source]

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

cos(prec: fractions.Fraction | None = None, degrees: bool = False, limit: bool = False) Self[source]

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

Parameters:
  • prec – the precision (should be set as a fraction).

  • degrees – if True, interpret the elements in degrees.

  • limit – if True, require the denominator to be smaller than or equal to the precision.

sin(prec: fractions.Fraction | None = None, degrees: bool = False, limit: bool = False) Self[source]

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

Parameters:
  • prec – the precision (should be set as a fraction).

  • degrees – if True, interpret the elements in degrees.

  • limit – if True, require the denominator to be smaller than or equal to the precision.

acos(prec: fractions.Fraction | None = None, degrees: bool = False, limit: bool = False) Self[source]

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

Parameters:
  • prec – the precision (should be set as a fraction).

  • degrees – if True, return the result in degrees.

  • limit – if True, require the denominator to be smaller than or equal to the precision.

asin(prec: fractions.Fraction | None = None, degrees: bool = False, limit: bool = False) Self[source]

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

Parameters:
  • prec – the precision (should be set as a fraction).

  • degrees – if True, return the result in degrees.

  • limit – if True, require the denominator to be smaller than or equal to the precision.

exp(prec: fractions.Fraction | None = None, limit: bool = False) Self[source]

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

Parameters:
  • prec – the precision (should be set as a fraction).

  • limit – if True, require the denominator to be smaller than or equal to the precision.

sqrt(prec: fractions.Fraction | None = None, limit: bool = False) Self[source]

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

Parameters:
  • prec – the precision (should be set as a fraction).

  • limit – if True, require the denominator to be smaller than or equal to the precision.

max() Self[source]

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

nargmax() list[Any][source]

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

argmax() Any[source]

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

min() Self[source]

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

nargmin() list[Any][source]

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

argmin() Any[source]

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

class httk.core.vectors.fracvector.FracScalar(nom: int, denom: int)[source]

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.

noms[source]
denom[source]
classmethod create(noms: Any, denom: int | None = None, simplify: bool = True, chain: bool = False, min_accuracy: fractions.Fraction | None = fractions.Fraction(1, 10000)) Self[source]

Create a FracScalar.

FracScalar.create(something) where something may be any object that can be used in the constructor of the Python Fraction class (also works with strings!).

Note: for signature-compatibility with FracVector.create(), this accepts chain and min_accuracy, but (as in the legacy implementation) it ignores them and converts strings exactly via the Fraction constructor.