API Reference
This section provides a complete reference for all classes, functions, and modules in the Plumial package.
Core Classes
Core mathematical objects for Collatz conjecture analysis.
- class plumial.core.B[source]
Bases:
objectNamespace for predefined basis constants.
This provides convenient access to commonly used mathematical bases for Collatz-like sequences and polynomial operations.
Examples
>>> # Use predefined bases >>> P(281).encode(B.Collatz).k() >>> P(281).encode(B.Symbolic).k() >>> >>> # Create custom basis >>> custom = Basis(5, 2) >>> P(281).encode(custom).k()
- Collatz = Basis(3, 2)
Standard Collatz basis (3x+1, /2)
- Collatz_5_2 = Basis(5, 2)
5x+1 Collatz variant basis
- Collatz_5_4 = Basis(5, 4)
5x+1, /4 Collatz variant basis
- Collatz_7_2 = Basis(7, 2)
7x+1 Collatz variant basis
- Collatz_7_4 = Basis(7, 4)
7x+1, /4 Collatz variant basis
- Symbolic = Basis(g, h)
Symbolic basis using symbolic g,h variables
- class plumial.core.Basis(g, h)[source]
Bases:
objectRepresents a mathematical coordinate system defined by (g,h) parameters.
A basis provides both semantic access methods (odd/even path parameters) and concrete access methods (g/h parameters) for different contexts.
Examples
>>> # Create bases >>> symbolic_basis = Basis(S.g, S.h) >>> collatz_basis = Basis(3, 2) >>> >>> # Semantic access >>> collatz_basis.odd() # Returns 3 (odd-path parameter) >>> collatz_basis.even() # Returns 2 (even-path parameter) >>> >>> # Concrete access >>> collatz_basis.g() # Returns 3 (g parameter) >>> collatz_basis.h() # Returns 2 (h parameter) >>> >>> # Modern encoding approach >>> P(281).encode(collatz_basis).k() # Encode then evaluate
- __init__(g, h)[source]
Initialize a basis with (g,h) parameters.
- Parameters:
g (
Any) – The g parameter (odd-path parameter)h (
Any) – The h parameter (even-path parameter)
- dict()[source]
Return {‘g’: g, ‘h’: h} dict for keyword unpacking.
This enables usage like: method(**basis.dict())
- Return type:
Dict[str,Any]- Returns:
Dictionary with ‘g’ and ‘h’ keys
- even()[source]
Return the even-path parameter (h).
This method provides semantic access to the parameter that governs transformations when even bits are encountered in path polynomials.
- Return type:
Any- Returns:
The h parameter
- g()[source]
Return the g parameter (alias for odd()).
This method provides concrete access to the g parameter for contexts where the traditional g,h notation is preferred.
- Return type:
Any- Returns:
The g parameter
- h()[source]
Return the h parameter (alias for even()).
This method provides concrete access to the h parameter for contexts where the traditional g,h notation is preferred.
- Return type:
Any- Returns:
The h parameter
- is_concrete()[source]
Return true if the basis has concrete (numeric) axes.
- Return type:
Any- Returns:
True if the axes are both numeric, false otherwise.
- odd()[source]
Return the odd-path parameter (g).
This method provides semantic access to the parameter that governs transformations when odd bits are encountered in path polynomials.
- Return type:
Any- Returns:
The g parameter
- sym_dict()[source]
Return {g_sym: g, h_sym: h} dict for symbolic substitution.
This enables usage like: expression.subs(basis.sym_dict())
- Return type:
Dict[Any,Any]- Returns:
Dictionary mapping symbolic variables to basis values
Examples
>>> from plumial.utils.symbolic import g, h >>> basis = B.Collatz >>> expr = g**2 + h**3 >>> result = expr.subs(basis.sym_dict()) # Evaluates with g=3, h=2
- plumial.core.D(o=None, e=None, n=None, basis=None)[source]
Factory function for creating D instances from bit counts.
This is the main entry point for creating D objects. It supports multiple calling patterns for flexibility.
- Parameters:
o (
Optional[int]) – Number of odd bitse (
Optional[int]) – Number of even bitsn (
Optional[int]) – Total number of bits (alternative parameter)basis (
Optional[Basis]) – The mathematical basis for this encoding (default: symbolic basis)
- Return type:
- Returns:
_D instance representing the d-polynomial h^e - g^o
- Raises:
ValueError – If parameters are invalid or inconsistent
- Usage Patterns:
D(o, e): Direct polynomial specification h^e - g^o
D(o=2, e=5): Named parameters
D(o=2, n=7): Named, compute e = n - o
D(e=5, n=7): Named, compute o = n - e
Examples
>>> d1 = D(2, 5) # h^5 - g^2 >>> d2 = D(o=2, e=5, basis=B.Collatz) # With specific basis >>> d3 = D(o=2, n=7) # Compute e = 7 - 2 = 5 >>> d4 = D(e=5, n=7) # Compute o = 7 - 5 = 2
- plumial.core.P(p, basis=None, pred=None, next=None)[source]
Factory function for creating P instances with improved caching.
This is the main entry point for creating path objects in the plumial library. It provides intelligent caching for performance while supporting basis-aware encoding and cycle linking for predecessor/successor relationships.
- Parameters:
p – The p-value (positive integer or binary string representing the path)
basis (
Optional[Basis]) – The mathematical basis for this encoding (default: symbolic basis)pred (
Optional[_P]) – Optional predecessor P instance for cycle linkingnext (
Optional[_P]) – Optional next P instance for cycle linking
- Return type:
- Returns:
_P instance, either from cache or newly created
- Raises:
ValueError – If p <= 0 (p-values must be positive) or invalid binary string
Examples
>>> p1 = P(133) # Uses symbolic basis and cache >>> p2 = P(133) # Returns same instance from cache >>> assert p1 is p2 >>> p3 = P('10000101') # Binary string for 133 >>> assert p1.p() == p3.p() >>> collatz_p = P(133, basis=B.Collatz) # Different basis >>> assert collatz_p != p1 # Different basis means different object
- plumial.core.resolve_basis(basis=None, g=None, h=None)[source]
Resolve basis from various parameter combinations.
This utility function handles the different ways a basis can be specified and returns a consistent Basis object.
- Parameters:
basis (
Optional[Basis]) – Explicit Basis objectg (
Any) – g parameter for custom basish (
Any) – h parameter for custom basis
- Return type:
- Returns:
Resolved Basis object
- Raises:
ValueError – If parameters are inconsistent or incomplete
Examples
>>> resolve_basis(B.Collatz) # Use existing basis >>> resolve_basis(g=3, h=2) # Create from parameters >>> resolve_basis() # Returns symbolic basis
Core Implementation Details
P Class (Path Polynomials)
Factory Function
- plumial.core.P.P(p, basis=None, pred=None, next=None)[source]
Factory function for creating P instances with improved caching.
This is the main entry point for creating path objects in the plumial library. It provides intelligent caching for performance while supporting basis-aware encoding and cycle linking for predecessor/successor relationships.
- Parameters:
p – The p-value (positive integer or binary string representing the path)
basis (
Optional[Basis]) – The mathematical basis for this encoding (default: symbolic basis)pred (
Optional[_P]) – Optional predecessor P instance for cycle linkingnext (
Optional[_P]) – Optional next P instance for cycle linking
- Return type:
- Returns:
_P instance, either from cache or newly created
- Raises:
ValueError – If p <= 0 (p-values must be positive) or invalid binary string
Examples
>>> p1 = P(133) # Uses symbolic basis and cache >>> p2 = P(133) # Returns same instance from cache >>> assert p1 is p2 >>> p3 = P('10000101') # Binary string for 133 >>> assert p1.p() == p3.p() >>> collatz_p = P(133, basis=B.Collatz) # Different basis >>> assert collatz_p != p1 # Different basis means different object
Path Object Methods
The P() function returns a path object with the following methods:
|
Internal class representing a path polynomial in Collatz analysis. |
- plumial.core.P._P.k
- plumial.core.P._P.a
- plumial.core.P._P.x
- plumial.core.P._P.f
- plumial.core.P._P.encode
- plumial.core.P._P.cycle
- plumial.core.P._P.uv
- plumial.core.P._P.next
- plumial.core.P._P.pred
- plumial.core.P._P.p
- plumial.core.P._P.n
- plumial.core.P._P.o
- plumial.core.P._P.e
- plumial.core.P._P.c
- plumial.core.P._P.r
- plumial.core.P._P.basis
- plumial.core.P._P.isforced
- plumial.core.P._P.b
- plumial.core.P._P.ax
- plumial.core.P._P.d
Return the d-polynomial or its evaluation. |
|
Calculate the k polynomial. |
|
Calculate the a coefficient. |
|
Calculate the x polynomial. |
|
Calculate the f polynomial (GCD factor). |
|
|
Create a new P object encoded in a different basis. |
|
Iterate through the cycle. |
Generate UV polynomial representation. |
|
Get the next element in the cycle. |
|
Get the predecessor element in the cycle. |
|
Return the p-value. |
|
Return the number of path bits. |
|
Return the number of odd bits. |
|
Return the number of even bits. |
|
Calculate the ceiling of log_h(g). |
|
Calculate the remainder: c() * o() - e(). |
|
Return the basis of this encoding. |
|
Determine if the cycle is forced by the p-value bit pattern. |
|
|
Return binary string representation of the p-value. |
Calculate a pair of polynomials a,x such that x*d = a*k. |
|
Return the D object. |
- class plumial.core.P._P(p, basis=None, pred=None, next=None)[source]
Bases:
objectInternal class representing a path polynomial in Collatz analysis.
This class encapsulates the mathematical structure of a Collatz path polynomial, providing methods for polynomial evaluation, cycle navigation, and various mathematical transformations. It maintains cached expressions for performance and supports both symbolic and numerical operations.
The class implements the mathematical relationships between different polynomial representations used in Collatz analysis, including UV polynomials, difference polynomials, and the fundamental relationship x*d = a*k.
This class should not be instantiated directly. Use the P() factory function instead.
- _p
The integer p-value this polynomial represents
- _d
Cached D object D(p)
- _next
Cached next element in the cycle
- _pred
Cached predecessor element in the cycle
- _expr_*
Cached symbolic expressions for various polynomial forms
- G()[source]
Create column vector of g powers from g^(o-1) down to g^0.
This method delegates to the D object’s G() method to generate a column vector containing powers of g in descending order, used for matrix operations with polynomial coefficients.
- Return type:
MutableDenseMatrix- Returns:
SymPy Matrix column vector with g powers [g^(o-1), g^(o-2), …, g^1, g^0]
- Mathematical Structure:
For o odd bits, creates: [g^(o-1), g^(o-2), …, g^1, g^0]^T
Examples
>>> p = P(133) # o=2, e=5 >>> g_vector = p.G() >>> # Returns Matrix([[g], [1]]) for powers g^1, g^0
- Matrix Operations:
>>> p = P(281) # o=3, e=5 >>> G_vec = p.G() >>> # Returns Matrix([[g**2], [g], [1]]) for use in polynomial operations
Note
This method delegates to the associated D object: self._d.G()
- H()[source]
Create matrix of k polynomial coefficients for odd cycle elements.
This method generates a matrix where each row contains the coefficients of the k polynomial (with respect to g) for each odd p-value in the cycle. This is used for matrix operations analyzing the polynomial structure of Collatz cycles.
- Return type:
MutableDenseMatrix- Returns:
SymPy Matrix with each row containing k polynomial coefficients for odd cycle elements
- Mathematical Structure:
For each odd p in cycle, extract coefficients of p.k() polynomial w.r.t. g Matrix shape: (number_of_odd_elements, max_polynomial_degree + 1)
Examples
>>> p = P(133) # Cycle with odd elements >>> h_matrix = p.H() >>> # Returns matrix with k polynomial coefficients for each odd cycle element
- Matrix Operations:
>>> p = P(281) # 8-element cycle >>> H_mat = p.H() >>> # Matrix with rows for each odd element's k polynomial coefficients
Note
Only processes odd cycle elements as these are most relevant for analysis
- __init__(p, basis=None, pred=None, next=None)[source]
Initialize a path polynomial.
- Parameters:
Note
This constructor is internal. Use P() factory function instead.
- a()[source]
Calculate the a coefficient.
- Return type:
Union[Expr,int,float]- Returns:
a coefficient or its evaluation
- ax()[source]
Calculate a pair of polynomials a,x such that x*d = a*k.
This method computes the polynomial factorization that satisfies the fundamental relationship x*d = a*k, where d is the d-polynomial and k is the k polynomial. The factorization separates the d-polynomial ratio d/k into numerator (a) and denominator (x) components.
- Return type:
Tuple[Expr,Expr]- Returns:
Tuple of (a_polynomial, x_polynomial) where both are SymPy expressions
- Mathematical Relationship:
x * d = a * k a = d / f (where f is the GCD factor) x = k / f
Examples
>>> p = P(133) >>> a, x = p.ax() >>> # Verify the relationship symbolically >>> d_poly = p.d() >>> k_poly = p.k() >>> assert sy.expand(x * d_poly) == sy.expand(a * k_poly)
- b(width=0)[source]
Return binary string representation of the p-value.
- Parameters:
width (
int) – Minimum width (right-justified with zeros, default: 0)- Return type:
str- Returns:
Binary string representation
Examples
>>> p = P(133) >>> p.b() '10000101' >>> p.b(10) '0010000101'
- c()[source]
Calculate the ceiling of log_h(g).
Delegates to the D object’s c() method.
- Return type:
Union[Expr,int,float]- Returns:
Ceiling value, either symbolic or evaluated based on the basis
- d()[source]
Return the d-polynomial or its evaluation.
- Return type:
Union[Expr,int,float,Rational]- Returns:
Difference polynomial h^e - g^o, either symbolic or evaluated
Examples
>>> p = P(133) >>> p.d() # Symbolic form h**5 - g**2 >>> collatz_p = P(133).encode(B.Collatz) >>> collatz_p.d() # Uses basis automatically 23
- encode(basis=None, g=None, h=None)[source]
Create a new P object encoded in a different basis.
This method enables the transitive encoding property where P objects can be transformed between different coordinate systems while preserving the underlying p-value identity.
- Parameters:
basis (
Optional[Basis]) – Target basis for encodingg (
Union[int,float,None]) – g parameter for custom basis (alternative to basis parameter)h (
Union[int,float,None]) – h parameter for custom basis (alternative to basis parameter)
- Return type:
- Returns:
New P object with same p-value but different basis
Examples
>>> p = P(281) # Symbolic basis >>> collatz_p = p.encode(B.Collatz) # Collatz basis >>> custom_p = p.encode(g=5, h=2) # Custom basis >>> back_p = collatz_p.encode() # Back to symbolic basis >>> assert back_p == p # Round-trip equality
- f()[source]
Calculate the f polynomial (GCD factor).
The f polynomial represents the greatest common divisor factor that appears in the relationship between the d-polynomial d and the k polynomial. It is computed as the GCD of d and k, with special handling for even/odd values of g.
- Return type:
Union[Expr,int,float]- Returns:
f polynomial (symbolic) or its numerical evaluation
- Mathematical Background:
f = gcd(d, k) where d is the d-polynomial and k is the k polynomial For even g: f is computed over the entire cycle For odd g: f is the simple GCD of d and k
Examples
>>> p = P(133) >>> f_symbolic = p.f() # Symbolic form >>> collatz_p = P(133).encode(B.Collatz) >>> f_numeric = collatz_p.f() # Numerical evaluation
- isforced()[source]
Determine if the cycle is forced by the p-value bit pattern.
A cycle is considered “forced” if the next operation cannot be determined by inspecting the LSB bit of the x-value alone, but instead is determined by the LSB bit of the p-value. This occurs when:
The p-value contains any adjacent 1 bits in its binary representation, OR
The top and bottom path bits are both 1
This is a critical property for Collatz analysis: any counterexample to the Collatz conjecture would have isforced() == False.
- Return type:
bool- Returns:
True if the cycle is forced by the p-value bit pattern, False otherwise
- Mathematical Background:
For unforced cycles: all(p.x(3,2) % 2 == p.p() % 2 for p in cycle) For forced cycles: the above condition is False for at least one element
Examples
>>> P(9).isforced() # Unforced cycle False >>> P(291).isforced() # Forced cycle True >>> # Verify unforced property for P(9) >>> all(p.x(3,2) % 2 == p.p() % 2 for p in P(9).cycle()) True >>> # Verify forced property for P(291) >>> all(p.x(3,2) % 2 == p.p() % 2 for p in P(291).cycle()) False
- k()[source]
Calculate the k polynomial.
The k polynomial is derived from the gh transformation of the uv polynomial.
- Return type:
Union[Expr,int,float]- Returns:
k polynomial or its evaluation
Examples
>>> p = P(133) >>> p.k() # Symbolic form # Returns symbolic k polynomial >>> collatz_p = P(133).encode(B.Collatz) >>> collatz_p.k() # Uses basis automatically # Returns numerical value using Collatz basis
- r()[source]
Calculate the remainder: c() * o() - e().
Delegates to the D object’s r() method.
- Return type:
Union[Expr,int,float]- Returns:
Remainder value, either symbolic or evaluated based on the basis
D Class (Difference Polynomials)
Factory Function
- plumial.core.D.D(o=None, e=None, n=None, basis=None)[source]
Factory function for creating D instances from bit counts.
This is the main entry point for creating D objects. It supports multiple calling patterns for flexibility.
- Parameters:
o (
Optional[int]) – Number of odd bitse (
Optional[int]) – Number of even bitsn (
Optional[int]) – Total number of bits (alternative parameter)basis (
Optional[Basis]) – The mathematical basis for this encoding (default: symbolic basis)
- Return type:
- Returns:
_D instance representing the d-polynomial h^e - g^o
- Raises:
ValueError – If parameters are invalid or inconsistent
- Usage Patterns:
D(o, e): Direct polynomial specification h^e - g^o
D(o=2, e=5): Named parameters
D(o=2, n=7): Named, compute e = n - o
D(e=5, n=7): Named, compute o = n - e
Examples
>>> d1 = D(2, 5) # h^5 - g^2 >>> d2 = D(o=2, e=5, basis=B.Collatz) # With specific basis >>> d3 = D(o=2, n=7) # Compute e = 7 - 2 = 5 >>> d4 = D(e=5, n=7) # Compute o = 7 - 5 = 2
D Object Methods
The D() function returns a d-polynomial object with the following methods:
|
Internal class representing a d-polynomial d_p(g,h) = h^e - g^o. |
Evaluate the d-polynomial. |
|
|
Create a new D object encoded in a different basis. |
Return the symbolic expression h^e - g^o. |
|
Calculate the ceiling of log_h(g). |
|
Calculate the remainder: c() * o() - e(). |
|
Return total number of bits (computed as o + e). |
|
Return number of odd bits. |
|
Return number of even bits. |
|
Return the basis of this encoding. |
- class plumial.core.D._D(o, e, basis=None)[source]
Bases:
objectInternal class representing a d-polynomial d_p(g,h) = h^e - g^o.
This class encapsulates the mathematical structure of a d-polynomial used in Collatz sequence analysis. It provides methods for symbolic manipulation and numerical evaluation.
The class maintains the fundamental parameters n, o, e for the polynomial form h^e - g^o.
This class should not be instantiated directly. Use the D() factory function instead.
- Mathematical Structure:
n: total number of bits (path length)
o: number of odd bits (3x+1 operations)
e: number of even bits (halving operations), where e = n - o
The polynomial form: h^e - g^o
- _o
Number of odd bits
- _e
Number of even bits
- _n
Total number of bits (computed as o + e)
- _expr
Cached symbolic expression
- G()[source]
Create column vector of g powers from g^(o-1) down to g^0.
This method generates a column vector containing powers of g in descending order, used for matrix operations with polynomial coefficients. The vector has o elements corresponding to the number of odd bits.
- Return type:
MutableDenseMatrix- Returns:
SymPy Matrix column vector with g powers [g^(o-1), g^(o-2), …, g^1, g^0]
- Mathematical Structure:
For o odd bits, creates: [g^(o-1), g^(o-2), …, g^1, g^0]^T
Examples
>>> d = D(2, 5) # o=2, e=5 >>> g_vector = d.G() >>> # Returns Matrix([[g], [1]]) for powers g^1, g^0
- Matrix Operations:
>>> d = D(3, 4) # o=3, e=4 >>> G_vec = d.G() >>> # Returns Matrix([[g**2], [g], [1]]) for use in polynomial operations
- __init__(o, e, basis=None)[source]
Initialize d-polynomial from odd and even bit counts.
- Parameters:
o (
int) – Number of odd bits (must be >= 0)e (
int) – Number of even bits (must be >= 0)basis (
Optional[Basis]) – The mathematical basis for this encoding (default: symbolic basis)
- Raises:
ValueError – If o < 0 or e < 0
Note
This constructor is internal. Use D() factory function instead.
- as_expr()[source]
Return the symbolic expression h^e - g^o.
- Return type:
Expr- Returns:
SymPy expression representing the d-polynomial
- c()[source]
Calculate the ceiling of log_h(g).
This method computes ceil(log_h(g)) where log_h(g) is the logarithm of g with base h. The result represents an important mathematical bound related to the d-polynomial structure.
- Return type:
Union[Expr,int,float,Rational]- Returns:
Ceiling value, either symbolic or evaluated based on the basis
- Mathematical Formula:
c = ceil(log_h(g)) = ceil(log(g) / log(h))
Examples
>>> d = D(2, 5) >>> d.c() # Symbolic form >>> collatz_d = D(2, 5).encode(B.Collatz) >>> collatz_d.c() # Numerical evaluation for g=3, h=2
- d()[source]
Evaluate the d-polynomial.
- Return type:
Union[Expr,int,float,Rational]- Returns:
Evaluated expression or symbolic form
Examples
>>> d = D(2, 5) >>> d.d() # Symbolic form h**5 - g**2 >>> collatz_d = D(2, 5).encode(B.Collatz) >>> collatz_d.d() # Uses basis automatically 23
- encode(basis=None, g=None, h=None)[source]
Create a new D object encoded in a different basis.
This method enables the transitive encoding property where D objects can be transformed between different coordinate systems while preserving the underlying mathematical structure.
- Parameters:
basis (
Optional[Basis]) – Target basis for encodingg (
Union[int,float,None]) – g parameter for custom basis (alternative to basis parameter)h (
Union[int,float,None]) – h parameter for custom basis (alternative to basis parameter)
- Return type:
- Returns:
New D object with same n,o values but different basis
Examples
>>> d = D(2, 5) # Symbolic basis >>> collatz_d = d.encode(B.Collatz) # Collatz basis >>> custom_d = d.encode(g=5, h=2) # Custom basis >>> back_d = collatz_d.encode() # Back to symbolic basis >>> assert back_d == d # Round-trip equality
- r()[source]
Calculate the remainder: c() * o() - e().
This method computes the remainder value defined as the ceiling of log_h(g) times the number of odd bits minus the number of even bits.
- Return type:
Union[Expr,int,float,Rational]- Returns:
Remainder value, either symbolic or evaluated based on the basis
- Mathematical Formula:
r = c * o - e = ceil(log_h(g)) * o - e
Examples
>>> d = D(2, 5) >>> d.r() # Symbolic form >>> collatz_d = D(2, 5).encode(B.Collatz) >>> collatz_d.r() # Numerical evaluation: 2 * 2 - 5 = -1
Basis System
Basis and coordinate system objects for Plumial mathematical operations.
This module provides the foundation for encoding mathematical objects within specific coordinate systems (bases) defined by (g,h) parameters.
- class plumial.core.basis.B[source]
Bases:
objectNamespace for predefined basis constants.
This provides convenient access to commonly used mathematical bases for Collatz-like sequences and polynomial operations.
Examples
>>> # Use predefined bases >>> P(281).encode(B.Collatz).k() >>> P(281).encode(B.Symbolic).k() >>> >>> # Create custom basis >>> custom = Basis(5, 2) >>> P(281).encode(custom).k()
- Collatz = Basis(3, 2)
Standard Collatz basis (3x+1, /2)
- Collatz_5_2 = Basis(5, 2)
5x+1 Collatz variant basis
- Collatz_5_4 = Basis(5, 4)
5x+1, /4 Collatz variant basis
- Collatz_7_2 = Basis(7, 2)
7x+1 Collatz variant basis
- Collatz_7_4 = Basis(7, 4)
7x+1, /4 Collatz variant basis
- Symbolic = Basis(g, h)
Symbolic basis using symbolic g,h variables
- class plumial.core.basis.Basis(g, h)[source]
Bases:
objectRepresents a mathematical coordinate system defined by (g,h) parameters.
A basis provides both semantic access methods (odd/even path parameters) and concrete access methods (g/h parameters) for different contexts.
Examples
>>> # Create bases >>> symbolic_basis = Basis(S.g, S.h) >>> collatz_basis = Basis(3, 2) >>> >>> # Semantic access >>> collatz_basis.odd() # Returns 3 (odd-path parameter) >>> collatz_basis.even() # Returns 2 (even-path parameter) >>> >>> # Concrete access >>> collatz_basis.g() # Returns 3 (g parameter) >>> collatz_basis.h() # Returns 2 (h parameter) >>> >>> # Modern encoding approach >>> P(281).encode(collatz_basis).k() # Encode then evaluate
- __init__(g, h)[source]
Initialize a basis with (g,h) parameters.
- Parameters:
g (
Any) – The g parameter (odd-path parameter)h (
Any) – The h parameter (even-path parameter)
- dict()[source]
Return {‘g’: g, ‘h’: h} dict for keyword unpacking.
This enables usage like: method(**basis.dict())
- Return type:
Dict[str,Any]- Returns:
Dictionary with ‘g’ and ‘h’ keys
- even()[source]
Return the even-path parameter (h).
This method provides semantic access to the parameter that governs transformations when even bits are encountered in path polynomials.
- Return type:
Any- Returns:
The h parameter
- g()[source]
Return the g parameter (alias for odd()).
This method provides concrete access to the g parameter for contexts where the traditional g,h notation is preferred.
- Return type:
Any- Returns:
The g parameter
- h()[source]
Return the h parameter (alias for even()).
This method provides concrete access to the h parameter for contexts where the traditional g,h notation is preferred.
- Return type:
Any- Returns:
The h parameter
- is_concrete()[source]
Return true if the basis has concrete (numeric) axes.
- Return type:
Any- Returns:
True if the axes are both numeric, false otherwise.
- odd()[source]
Return the odd-path parameter (g).
This method provides semantic access to the parameter that governs transformations when odd bits are encountered in path polynomials.
- Return type:
Any- Returns:
The g parameter
- sym_dict()[source]
Return {g_sym: g, h_sym: h} dict for symbolic substitution.
This enables usage like: expression.subs(basis.sym_dict())
- Return type:
Dict[Any,Any]- Returns:
Dictionary mapping symbolic variables to basis values
Examples
>>> from plumial.utils.symbolic import g, h >>> basis = B.Collatz >>> expr = g**2 + h**3 >>> result = expr.subs(basis.sym_dict()) # Evaluates with g=3, h=2
- plumial.core.basis.resolve_basis(basis=None, g=None, h=None)[source]
Resolve basis from various parameter combinations.
This utility function handles the different ways a basis can be specified and returns a consistent Basis object.
- Parameters:
basis (
Optional[Basis]) – Explicit Basis objectg (
Any) – g parameter for custom basish (
Any) – h parameter for custom basis
- Return type:
- Returns:
Resolved Basis object
- Raises:
ValueError – If parameters are inconsistent or incomplete
Examples
>>> resolve_basis(B.Collatz) # Use existing basis >>> resolve_basis(g=3, h=2) # Create from parameters >>> resolve_basis() # Returns symbolic basis
Utility Modules
Symbolic Variables
Symbolic variable definitions for Collatz conjecture analysis.
This module provides centralized symbolic variables used throughout the mathematical computations. It maintains compatibility with the original collatz library while providing better organization and documentation.
- class plumial.utils.symbolic.FunctionsNamespace[source]
Bases:
objectNamespace class for functions to mimic the original F module usage pattern.
This allows code like: F.isodd(p), F.k(3,2), F.next_func(p) where F = FunctionsNamespace()
- class plumial.utils.symbolic.IndexedNamespace[source]
Bases:
objectNamespace class for indexed symbols to mimic the original I module usage pattern.
This allows code like: I.p[0], I.x[i], I.k[i,j] where I = IndexedNamespace()
- class plumial.utils.symbolic.SymbolNamespace[source]
Bases:
objectNamespace class to mimic the original symbols module usage pattern.
This allows code like: S.g, S.h, S.u, S.v where S = SymbolNamespace()
- plumial.utils.symbolic.create_polynomial_expression(powers)[source]
Create a polynomial expression from symbol powers.
- Parameters:
powers (
Dict[str,int]) – Dictionary mapping symbol names to their powers- Return type:
Expr- Returns:
SymPy polynomial expression
Examples
>>> create_polynomial_expression({'g': 2, 'h': 3}) g**2*h**3 >>> create_polynomial_expression({'u': 1, 'v': 2}) u*v**2
- plumial.utils.symbolic.extract_coefficients(expr, variable)[source]
Extract coefficients of powers of a variable from an expression.
- Parameters:
expr (
Expr) – SymPy expressionvariable (
Symbol) – Variable to extract coefficients for
- Return type:
Dict[int,Expr]- Returns:
Dictionary mapping powers to coefficients
Examples
>>> expr = 3*g**2 + 2*g + 5 >>> extract_coefficients(expr, g) {0: 5, 1: 2, 2: 3}
- plumial.utils.symbolic.get_indexed_symbol(name)[source]
Get an indexed symbol by name.
- Parameters:
name (
str) – Base symbol name (e.g., ‘p’, ‘x’, ‘k’)- Return type:
IndexedBase- Returns:
SymPy indexed base
- Raises:
KeyError – If indexed symbol name is not found
Examples
>>> get_indexed_symbol('p') p >>> get_indexed_symbol('p')[0] p[0]
- plumial.utils.symbolic.get_symbol(name)[source]
Get a symbol by name.
- Parameters:
name (
str) – Symbol name (e.g., ‘g’, ‘h’, ‘u’, ‘v’)- Return type:
Symbol- Returns:
SymPy symbol
- Raises:
KeyError – If symbol name is not found
Examples
>>> get_symbol('g') g >>> get_symbol('h') h
- plumial.utils.symbolic.gh_to_uv_transform(gh_expr)[source]
Transform g,h polynomial to u,v form using TRANSFORM_GH_TO_UV.
This implements the reverse substitution g → u/v, h → v which transforms k polynomials back to sigma polynomials (with appropriate scaling).
- Parameters:
gh_expr (
Expr) – Expression in g and h variables- Return type:
Expr- Returns:
Expression in u and v variables
Examples
>>> # For expressions that result from u,v → g,h transformation: >>> gh_expr = g*h + h**2 # This came from u + v**2 originally >>> gh_to_uv_transform(gh_expr) u + v**2 >>> # Using the constant directly: >>> gh_expr.subs(TRANSFORM_GH_TO_UV) u + v**2
- plumial.utils.symbolic.substitute_values(expr, **kwargs)[source]
Substitute values into an expression using symbol names.
- Parameters:
expr (
Expr) – SymPy expression**kwargs – Symbol names and their values (e.g., g=3, h=2)
- Return type:
Expr- Returns:
Expression with substituted values
Examples
>>> expr = g**2 + h >>> substitute_values(expr, g=3, h=2) 11
- plumial.utils.symbolic.uv_to_gh_transform(uv_expr)[source]
Transform u,v polynomial to g,h form using TRANSFORM_UV_TO_GH.
This implements the substitution u → g·h, v → h which transforms sigma polynomials to k polynomials (after appropriate scaling).
- Parameters:
uv_expr (
Expr) – Expression in u and v variables- Return type:
Expr- Returns:
Expression in g and h variables
Examples
>>> uv_expr = u**2 + v >>> uv_to_gh_transform(uv_expr) g**2*h**2 + h >>> # Using the constant directly: >>> uv_expr.subs(TRANSFORM_UV_TO_GH) g**2*h**2 + h
Functions Module
Functions module for functional programming with P-objects.
This module provides a comprehensive set of functional utilities for working with P-class objects in Collatz analysis. It enables elegant, composable operations through curried functions, filters, and data transformations.
- The module follows functional programming principles to enable clean code like:
P(p).cycle(filter=F.isodd, map=F.k(3,2))
- Usage Patterns:
>>> from plumial.utils import F >>> # Simple getters >>> F.n(p_obj) # Get bit count >>> F.d(p_obj) # Get d-polynomial >>> >>> # Curried functions >>> k_func = F.k() # Returns lambda p: p.k() >>> values = [k_func(p) for p in cycle] >>> >>> # Filters >>> odd_elements = [p for p in cycle if F.isodd(p)]
- plumial.utils.functions.a()[source]
Return curried function for a-value extraction.
- Return type:
Callable[[PValueProtocol],Any]- Returns:
Lambda function that extracts a-value from P-object
Examples
>>> a_func = F.a() >>> result = a_func(p_obj) # Equivalent to p_obj.a()
- plumial.utils.functions.as_expr(p)[source]
Extract expression representation from P-object.
- Return type:
Any
- plumial.utils.functions.as_poly(p)[source]
Extract polynomial representation from P-object.
- Return type:
Any
- plumial.utils.functions.b(p, width=0)[source]
Extract binary string representation from P-object.
- Return type:
str
- plumial.utils.functions.compose(*functions)[source]
Compose multiple functions into a single function.
- Parameters:
*functions – Functions to compose (applied right to left)
- Returns:
Composed function
Examples
>>> composed = F.compose(F.n, F.next_func) >>> result = composed(p_obj) # n(next_func(p_obj))
- plumial.utils.functions.cycle_length(p)[source]
Get the length of the cycle containing this P-object.
- Return type:
int
- plumial.utils.functions.cycle_max(p)[source]
Get the maximum p-value in the cycle containing this P-object.
- Return type:
int
- plumial.utils.functions.cycle_min(p)[source]
Get the minimum p-value in the cycle containing this P-object.
- Return type:
int
- plumial.utils.functions.f()[source]
Return curried function for f-value extraction.
- Return type:
Callable[[PValueProtocol],Any]- Returns:
Lambda function that extracts f-value from P-object
- plumial.utils.functions.identity_map(p)[source]
Identity mapping function - returns input unchanged.
- Return type:
- plumial.utils.functions.identity_reducer(acc, p)[source]
Identity reducer function - returns accumulator unchanged.
- Return type:
Any
- plumial.utils.functions.is_cycle_start(p)[source]
Check if this P-object represents the start of its cycle (minimum p-value).
- Return type:
bool
- plumial.utils.functions.isfalse(p)[source]
Always return False - useful as a filter.
- Return type:
bool
- plumial.utils.functions.isforced(p)[source]
Check if the cycle is forced by the p-value bit pattern.
- Return type:
bool
- plumial.utils.functions.ismin(p)[source]
Check if p-value is minimal in its cycle.
- Return type:
bool
- plumial.utils.functions.isnot(filter_func)[source]
Return inverted filter function.
- Parameters:
filter_func (
Callable[[PValueProtocol],bool]) – Original filter function- Return type:
Callable[[PValueProtocol],bool]- Returns:
Inverted filter function
Examples
>>> not_odd = F.isnot(F.isodd) >>> even_elements = [p for p in cycle if not_odd(p)]
- plumial.utils.functions.istrue(p)[source]
Always return True - useful as a filter.
- Return type:
bool
- plumial.utils.functions.k()[source]
Return curried function for k-value extraction.
- Return type:
Callable[[PValueProtocol],Any]- Returns:
Lambda function that extracts k-value from P-object
Examples
>>> k_func = F.k() >>> values = [k_func(p) for p in cycle]
- plumial.utils.functions.map_filter(map_func=None, filter_func=None)[source]
Create a combined map-filter function for cycle processing.
- Parameters:
map_func (
Callable) – Function to apply to each elementfilter_func (
Callable) – Function to filter elements
- Returns:
Combined function for use in cycle operations
Examples
>>> mf = F.map_filter(F.k(), F.isodd) >>> # Use with P(p).cycle() method
- plumial.utils.functions.to_dataframe(iterator)[source]
Convert iterator of P-objects to pandas DataFrame.
- Parameters:
iterator (
Iterator[PValueProtocol]) – Iterator yielding P-objects- Return type:
DataFrame- Returns:
Pandas DataFrame with P-object data
Examples
>>> df = F.to_dataframe(P(133).cycle()) >>> print(df.head())
- plumial.utils.functions.to_object(p)[source]
Convert P-object to dictionary representation.
- Parameters:
p (
PValueProtocol) – P-object to convert- Return type:
Dict[str,Any]- Returns:
Dictionary with p-object properties
Examples
>>> obj_dict = F.to_object(p_obj) >>> print(obj_dict) # {'p': 133, 'n': 7, 'o': 2, 'e': 5, ...}
- plumial.utils.functions.x()[source]
Return curried function for x-value extraction.
- Return type:
Callable[[PValueProtocol],Any]- Returns:
Lambda function that extracts x-value from P-object
Binary Operations
Binary operations for Collatz conjecture analysis.
This module provides comprehensive bit manipulation functions for working with p-values, cycle navigation, and binary representations used in Collatz sequence analysis.
The module implements the core bit-level operations that underlie the mathematical structure of Collatz sequences, including:
- Key Concepts:
P-values: Binary-encoded representations of Collatz sequence paths
MSB encoding: The most significant bit encodes the path length
Cycle bits: Lower bits encode the actual sequence operations
Odd/Even bits: Correspond to 3x+1 and halving operations respectively
- Functions:
Bit counting: n(), o(), e() for analyzing bit structure
Cycle navigation: next_p(), pred_p(), cycle() for traversing sequences
Binary conversion: binary_string(), from_binary_string() for representations
Analysis: bit_pattern_analysis(), cycle_statistics() for detailed examination
- Mathematical Background:
P-values use a special encoding where: - MSB (position n): Length bit (always 1) - Lower n bits: Actual cycle operations - Odd bits (1): Correspond to 3x+1 operations - Even bits (0): Correspond to halving operations
Examples
>>> p = 133 # Binary: 10000101
>>> n(p) # 7 (total path bits)
>>> o(p) # 2 (odd operations: 3x+1)
>>> e(p) # 5 (even operations: halving)
>>> list(cycle(p)) # Full cycle starting from p=133
- plumial.utils.binary.binary_string(b, width=0)[source]
Generate binary string representation of integer.
- Parameters:
b (
int) – Integer to convertwidth (
int) – Minimum width (right-justified with zeros)
- Return type:
str- Returns:
Binary string representation
Examples
>>> binary_string(133) '10000101' >>> binary_string(133, 10) '0010000101'
- plumial.utils.binary.bit_pattern_analysis(p)[source]
Analyze the bit pattern of a p-value.
- Parameters:
p (
int) – The p-value- Return type:
Dict[str,Union[str,int,List[int]]]- Returns:
Dictionary with pattern analysis
Examples
>>> bit_pattern_analysis(133) { 'binary': '10000101', 'n': 7, 'o': 2, 'e': 5, 'odd_positions': [0, 7], 'even_positions': [1, 2, 3, 4, 5, 6] }
- plumial.utils.binary.cycle(p, first_only=False)[source]
Enumerate the cycle of p values.
- Parameters:
p (
int) – Starting p-valuefirst_only (
bool) – If True, stop after the first repetition
- Yields:
p-values in the cycle
- Return type:
Iterator[int]
Examples
>>> list(cycle(9)) # Full cycle [9, 10, 5, 6, 3, 8, 4, 2]
- plumial.utils.binary.cycle_statistics(p)[source]
Calculate statistics for a p-value cycle.
- Parameters:
p (
int) – Starting p-value- Return type:
Dict[str,Union[int,List[int]]]- Returns:
Dictionary with cycle statistics
- plumial.utils.binary.e(p)[source]
Calculate the number of ‘even’ bits in p.
- Parameters:
p (
int) – The p-value (must be > 0)- Return type:
int- Returns:
Number of even bits (n - o)
Examples
>>> e(133) # n=7, o=2, so e=5 5
- plumial.utils.binary.from_binary_string(s)[source]
Convert binary string to integer.
- Parameters:
s (
str) – Binary string (e.g., ‘10000101’)- Return type:
int- Returns:
Integer value
Examples
>>> from_binary_string('10000101') 133
- plumial.utils.binary.is_odd(p)[source]
Check if p represents an odd step in Collatz sequence.
- Parameters:
p (
int) – The p-value- Return type:
bool- Returns:
True if p is odd, False otherwise
- plumial.utils.binary.n(p)[source]
Calculate the number of path bits implied by p.
- Parameters:
p (
int) – The p-value (must be > 0)- Return type:
int- Returns:
Number of path bits (bit_length - 1)
Examples
>>> n(133) # 133 = 0b10000101 7
- plumial.utils.binary.next_p(p)[source]
Rotate the MSB-1 into the LSB and shift other bits left.
This implements the bit rotation for cycle navigation in Collatz analysis.
- Parameters:
p (
int) – The p-value- Return type:
int- Returns:
Next p-value in the cycle
Examples
>>> next_p(133) # Binary rotation 198
- plumial.utils.binary.o(p)[source]
Calculate the number of ‘odd’ bits in p.
- Parameters:
p (
int) – The p-value (must be > 0)- Return type:
int- Returns:
Number of odd bits (bit_count - 1)
Examples
>>> o(133) # 133 = 0b10000101 has 3 ones 2
- plumial.utils.binary.odd_bit_indices(p_obj, matrix=False)[source]
Generate indices of odd bits in a p-value.
- Parameters:
p_obj (
PValueProtocol) – P object with p() and n() methodsmatrix (
bool) – If True, return matrix indices (o,e), else vector indices (i,)
- Yields:
Tuples of indices where odd bits occur
- Return type:
Iterator[Tuple[int,...]]
Examples
>>> p = P(133) >>> list(odd_bit_indices(p)) # Vector form [(0,), (7,)] >>> list(odd_bit_indices(p, matrix=True)) # Matrix form [(0, 0), (1, 5)]
- plumial.utils.binary.p_from_binary_pattern(pattern)[source]
Create p-value from binary pattern string.
- Parameters:
pattern (
str) – Binary pattern (without leading MSB)- Return type:
int- Returns:
p-value with MSB set
Examples
>>> p_from_binary_pattern('0000101') 133 # '1' + '0000101' = '10000101'
Matrix Utilities
Matrix and vector utilities for polynomial manipulation.
This module provides utility functions for converting between symbolic expressions and matrix/vector representations used in Collatz analysis.
- plumial.utils.matrix_utils.eat_minus_1(expr, check=True)[source]
Normalize expression to move leading negative coefficients into terms.
This function ensures expressions like -1*(g-4)*(4+g) are rendered as (4-g)*(4+g).
- Parameters:
expr (
Expr) – Expression to normalizecheck (
bool) – Whether to verify the result matches the original
- Return type:
Expr- Returns:
Normalized expression
- plumial.utils.matrix_utils.expr_as_vector(expr, dim=None, symbol=g)[source]
Convert a polynomial expression to a vector of coefficients.
- Parameters:
expr (
Expr) – Symbolic expression to convertdim (
Optional[int]) – Desired dimension (pads with zeros if needed)symbol (
Symbol) – Symbol to extract coefficients for
- Return type:
MutableDenseMatrix- Returns:
SymPy Matrix representing coefficient vector
- plumial.utils.matrix_utils.vector_as_expr(v, expand=True, symbol=g)[source]
Convert a coefficient vector back to a polynomial expression.
- Parameters:
v (
MutableDenseMatrix) – Vector of coefficientsexpand (
bool) – Whether to expand the resultsymbol (
Symbol) – Symbol for the polynomial variable
- Return type:
Expr- Returns:
Symbolic expression
Type System
Type definitions and aliases for the Plumial library.
This module provides common type aliases and protocols used throughout the library for better type safety and code readability.
- plumial.types.BinaryPattern
Type alias for binary pattern strings.
- plumial.types.BitAnalysis
Type alias for bit pattern analysis results.
alias of
Dict[str,str|int|List[int]]
- plumial.types.BitPosition
Type alias for bit position tuples.
alias of
Tuple[int, …]
- plumial.types.BitPositionIterator
Type alias for iterators yielding bit position tuples.
alias of
Iterator[Tuple[int, …]]
- plumial.types.CacheInfo
Type alias for functools cache info objects.
- class plumial.types.CacheableProtocol(*args, **kwargs)[source]
Bases:
ProtocolProtocol for objects that support caching operations.
Objects implementing this protocol must provide methods to manage cache state and retrieve cache information.
- __init__(*args, **kwargs)
- plumial.types.CoefficientsDict
Type alias for polynomial coefficient dictionaries.
alias of
Dict[int,Expr]
- plumial.types.CycleIterator
Type alias for iterators yielding cycle values.
alias of
Iterator[int]
- plumial.types.CycleStatistics
Type alias for cycle statistics dictionaries.
alias of
Dict[str,int|List[int]]
- plumial.types.DEFAULT_G_VALUE: int = 3
Default value for the g parameter in Collatz analysis.
- plumial.types.DEFAULT_H_VALUE: int = 2
Default value for the h parameter in Collatz analysis.
- class plumial.types.DPolynomialProtocol(*args, **kwargs)[source]
Bases:
ProtocolProtocol for objects that behave like D objects.
Objects implementing this protocol must provide methods to access polynomial properties and evaluation.
- __init__(*args, **kwargs)
- plumial.types.ExpressionList
Type alias for lists of symbolic expressions.
alias of
List[Expr]
- plumial.types.FactorResult
Type alias for polynomial factorization results.
- plumial.types.GCDResult
Type alias for GCD computation results.
alias of
Expr|int|float
- plumial.types.IndexedDict
Type alias for indexed symbol lookup dictionaries.
alias of
Dict[str,IndexedBase]
- plumial.types.MAX_CACHE_SIZE: int = 1000
Default maximum size for LRU caches.
- class plumial.types.MathematicalExpressionProtocol(*args, **kwargs)[source]
Bases:
ProtocolProtocol for objects that can be used in mathematical expressions.
This protocol defines the interface for objects that can participate in symbolic mathematical operations.
- __init__(*args, **kwargs)
- plumial.types.NumericOrSymbolic
Type alias for values that can be either numeric or symbolic.
alias of
Expr|int|float|Rational
- plumial.types.NumericType
Type alias for numeric values (int or float).
alias of
int|float
- plumial.types.OptionalNumeric
Type alias for optional numeric values.
alias of
int|float|None
- plumial.types.OptionalSymbolic
Type alias for optional symbolic values.
alias of
Symbol|Expr|None
- class plumial.types.PValueProtocol(*args, **kwargs)[source]
Bases:
ProtocolProtocol for objects that behave like P-values.
Objects implementing this protocol must provide methods to access the p-value and its bit count properties.
- __init__(*args, **kwargs)
- plumial.types.PolynomialTuple
Type alias for polynomial pairs (e.g., a,x polynomials).
alias of
Tuple[Expr,Expr]
- plumial.types.PowersDict
Type alias for polynomial powers dictionaries.
alias of
Dict[str,int]
- plumial.types.SubstitutionDict
Type alias for symbolic substitution dictionaries.
alias of
Dict[Symbol|Expr,Expr|int|float|Rational]
- plumial.types.SymbolDict
Type alias for symbol lookup dictionaries.
alias of
Dict[str,Symbol]
- plumial.types.SymbolicType
Type alias for SymPy symbolic objects.
alias of
Symbol|Expr
- plumial.types.is_d_polynomial_like(obj)[source]
Check if an object implements the DPolynomialProtocol.
- Parameters:
obj (
Any) – Object to check- Return type:
bool- Returns:
True if object has required methods, False otherwise
Examples
>>> from plumial.core.D import D >>> d_obj = D(2, 5) >>> is_d_polynomial_like(d_obj) True >>> is_d_polynomial_like("not a polynomial") False
- plumial.types.is_numeric(value)[source]
Check if a value is numeric (int or float).
- Parameters:
value (
Any) – Value to check- Return type:
bool- Returns:
True if value is int or float, False otherwise
Examples
>>> is_numeric(42) True >>> is_numeric(3.14) True >>> is_numeric("not a number") False
- plumial.types.is_p_value_like(obj)[source]
Check if an object implements the PValueProtocol.
- Parameters:
obj (
Any) – Object to check- Return type:
bool- Returns:
True if object has p() and n() methods, False otherwise
Examples
>>> from plumial import P >>> p_obj = P(133) >>> is_p_value_like(p_obj) True >>> is_p_value_like(42) False
- plumial.types.is_symbolic(value)[source]
Check if a value is a SymPy symbolic object.
- Parameters:
value (
Any) – Value to check- Return type:
bool- Returns:
True if value is a SymPy symbol or expression, False otherwise
Examples
>>> import sympy as sy >>> x = sy.Symbol('x') >>> is_symbolic(x) True >>> is_symbolic(42) False