sym¶
- wrenfold.sym.abs(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The absolute value function \(\lvert x \rvert\).
Examples
>>> sym.abs(3) 3 >>> x = sym.symbols('x') >>> sym.abs(x) abs(x) >>> sym.abs(x).diff(x) x/abs(x)
- wrenfold.sym.acos(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The inverse cosine function \(\cos^{-1}{x}\).
Examples
>>> x = sym.symbols('x') >>> sym.acos(x) acos(x) >>> sym.acos(0) pi/2
- wrenfold.sym.acosh(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The inverse hyperbolic cosine function \(\cosh^{-1}{x}\).
Examples
>>> x = sym.symbols('x') >>> sym.acosh(x) acosh(x)
- wrenfold.sym.addition(args: list[wrenfold.sym.Expr]) wrenfold.sym.Expr ¶
Construct addition expression from provided operands.
- wrenfold.sym.asin(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The inverse sine function \(\sin^{-1}{x}\).
Examples
>>> x = sym.symbols('x') >>> sym.asin(x) asin(x) >>> sym.asin(-1) -pi/2
- wrenfold.sym.asinh(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The inverse hyperbolic sine function \(\sinh^{-1}{x}\).
Examples
>>> x = sym.symbols('x') >>> sym.asinh(x) asinh(x)
- wrenfold.sym.atan(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The inverse tangent function \(\tan^{-1}{x}\).
Examples
>>> x = sym.symbols('x') >>> sym.atan(x) atan(x) >>> sym.atan(-x) -atan(x)
- wrenfold.sym.atan2(y: wrenfold.sym.Expr, x: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
Two-argument inverse tangent function \(\text{atan2}\left(y, x\right)\). Returns the angle \(\theta \in [-\pi, \pi]\) such that:
\[\begin{split}\begin{align} x &= \sqrt{x^2 + y^2}\cdot\cos\theta \\ y &= \sqrt{x^2 + y^2}\cdot\sin\theta \end{align}\end{split}\]Examples
>>> sym.atan2(1, 0) pi/2 >>> x, y = sym.symbols('x, y') >>> sym.atan2(y, x).diff(x) -y/(x**2 + y**2)
- wrenfold.sym.atanh(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The inverse hyperbolic tangent function \(\tanh^{-1}{x}\).
Examples
>>> x = sym.symbols('x') >>> sym.atanh(x) atanh(x)
- wrenfold.sym.compare(a: wrenfold.sym.Expr, b: wrenfold.sym.Expr) int ¶
Determine relative ordering of two scalar-valued expressions. Note that this is not a mathematical ordering. Expressions are first ordered by their expression type, and then by the contents of the underlying concrete expressions. For non-leaf expressions (for instance addition or multiplication), a lexicographical ordering of the children is used to determine relative order.
- Parameters:
a – The first expression.
b – The second expression.
- Returns:
-1
ifa
belongs beforeb
.0
ifa
is identical tob
.+1
ifa
belongs afterb
.
Examples
>>> x, y = sym.symbols('x, y') >>> sym.compare(x, y) -1 >>> sym.compare(y, x) 1 >>> sym.compare(5, 8) -1 >>> sym.compare(sym.sin(x), sym.cos(x)) 1
- wrenfold.sym.cos(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The cosine function \(\cos{x}\).
- Parameters:
arg – Argument in radians.
Examples
>>> x = sym.symbols('x') >>> sym.cos(x) cos(x) >>> sym.cos(sym.pi) -1
- wrenfold.sym.cosh(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The hyperbolic cosine function \(\cosh{x}\).
Examples
>>> x = sym.symbols('x') >>> sym.cosh(x) cosh(x) >>> sym.cosh(x * sp.I) cos(x)
- wrenfold.sym.derivative(function: wrenfold.sym.Expr, arg: wrenfold.sym.Expr, order: int = 1) wrenfold.sym.Expr ¶
Create a deferred derivative expression. This expression type is used to represent the derivatives of abstract symbolic functions.
- Parameters:
function – Function to be differentiated.
arg – Argument with respect to which the derivative is taken.
order – The order of the derivative.
Examples
>>> x, y = sym.symbols('x, y') >>> sym.derivative(x * x, x) Derivative(x**2, x) >>> f = sym.Function('f') >>> f(x, y).diff(x) Derivative(f(x, y), x)
- Raises:
wrenfold.exceptions.TypeError – If
arg
is not a variable expression.wrenfold.exceptions.InvalidArgumentError – If
order <= 0
.
- wrenfold.sym.det(m: wrenfold.sym.MatrixExpr) wrenfold.sym.Expr ¶
Compute the determinant of the matrix. For 2x2 and 3x3 matrices, a hardcoded formula is employed. For sizes 4x4 and above, the matrix is first decomposed via full-pivoting LU decomposition.
Caution
When computing the LU decomposition, the pivot selection step cannot know apriori which symbolic expressions might evaluate to zero at runtime. As a result, the decomposition ordering could produce
NaN
values at runtime when numerical values are substituted into this expression.- Returns:
The matrix determinant as a scalar-valued expression.
- Raises:
wrenfold.sym.DimensionError – If the matrix is not square.
Examples
>>> x = sym.symbols('x') >>> m = sym.matrix([[sym.cos(x), -sym.sin(x)], [sym.sin(x), sym.cos(x)]]) >>> m.det() cos(x)**2 + sin(x)**2
References
- wrenfold.sym.diag(*args, **kwargs)¶
Overloaded function.
diag(values: list[wrenfold.sym.MatrixExpr]) -> wrenfold.sym.MatrixExpr
Diagonally stack the provided matrices. Off-diagonal blocks are filled with zeroes.
- Raises:
wrenfold.sym.DimensionError – If the input is empty.
Examples
>>> x, y, z = sym.symbols('x, y, z') >>> m = sym.matrix([[x, 0], [y*z, 5]]) >>> sym.diagonal([m, sym.eye(2)]) [[x, 0, 0, 0], [y*z, 5, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
diag(values: list[wrenfold.sym.Expr]) -> wrenfold.sym.MatrixExpr
Overload of
wrenfold.sym.diag()
that accepts a list of scalars.
- wrenfold.sym.distribute(expr: wrenfold.sym.Expr | wrenfold.sym.MatrixExpr | wrenfold.sym.CompoundExpr | wrenfold.sym.BooleanExpr) wrenfold.sym.Expr | wrenfold.sym.MatrixExpr | wrenfold.sym.CompoundExpr | wrenfold.sym.BooleanExpr ¶
Expand the mathematical expression.
distribute
will recursively traverse the expression tree and multiply out any product of additions and subtractions. For example:\[\left(x + y\right)\cdot(4 - y) \rightarrow 4 \cdot x + 4 \cdot y - x \cdot y - y^{2}\]Powers of the form \(f\left(x\right)^{\frac{n}{2}}\) where \(n\) is an integer are also expanded:
\[\left(x + 2\right)^{\frac{3}{2}} \rightarrow x \cdot \left(x + 2\right)^{\frac{1}{2}} + 2 \cdot \left(x + 2\right)^{\frac{1}{2}}\]- Returns:
The input expression after expansion.
Examples
>>> x, y = sym.symbols('x, y') >>> f = (x - 2) * (y + x) * (y - 3) >>> f.distribute() 6*x + 6*y - 5*x*y + x**2*y + x*y**2 - 3*x**2 - 2*y**2
- wrenfold.sym.eliminate_subexpressions(*args, **kwargs)¶
Overloaded function.
eliminate_subexpressions(expr: wrenfold.sym.Expr, make_variable: Optional[Callable[[int], wrenfold.sym.Expr]] = None, min_occurrences: int = 2) -> tuple[wrenfold.sym.Expr, list[tuple[wrenfold.sym.Expr, wrenfold.sym.Expr]]]
Extract common subexpressions from a scalar-valued expression. The expression tree is traversed and unique expressions are counted. Those that appear
min_occurrences
or more times are replaced with a variable.This is not the same algorithm used during code-generation. Rather, it is a simplified version that pulls out atomic expressions. Additions and multiplications will not be broken down into smaller pieces in order to reduce the operation count. The intended use case is to allow a human to more easily inspect a complex nested expression by breaking it into pieces.
- Parameters:
expr – The expression to operate on.
make_variable – A callable that accepts an integer indicating the index of the next variable. It should return an appropriately named variable expression. By default, the names
v0, v1, ..., v{N}
will be used.min_occurrences – The number of times an expression must appear as part of a unique parent in order to be extracted.
Examples
>>> x, y = sym.symbols('x, y') >>> f = sym.cos(x * y) - sym.sin(x * y) + 5 * sym.abs(sym.cos(x * y)) >>> g, replacements = sym.eliminate_subexpressions(f) >>> replacements [(v0, x*y), (v1, cos(v0))] >>> g v1 + 5*abs(v1) - sin(v0)
eliminate_subexpressions(expr: wrenfold.sym.MatrixExpr, make_variable: Optional[Callable[[int], wrenfold.sym.Expr]] = None, min_occurences: int = 2) -> tuple[wrenfold.sym.MatrixExpr, list[tuple[wrenfold.sym.Expr, wrenfold.sym.Expr]]]
Matrix-valued overload.
- wrenfold.sym.eq(a: wrenfold.sym.Expr, b: wrenfold.sym.Expr) wrenfold.sym.BooleanExpr ¶
Boolean-valued relational expression \(a = b\), or
==
operator.Examples
>>> sym.eq(2, 5) False >>> x, y = sym.symbols('x, y') >>> sym.eq(3*x, y/2) 3*x == y/2
- wrenfold.sym.eye(rows: int, cols: int | None = None) wrenfold.sym.MatrixExpr ¶
Create an identity matrix.
- Parameters:
rows – Number of rows in the resulting matrix.
cols – Number of columns. By default this will match the number of rows.
- Raises:
wrenfold.sym.DimensionError – If the dimensions are non-positive.
- wrenfold.sym.float(value: float) wrenfold.sym.Expr ¶
Create a constant expression from a float.
Tip
Typically you do not need to explicitly call this method, since python floats involved in mathematical operations will automatically be promoted to
sym.Expr
:y = x + 2.87 # Equivalent to: y = x + sym.float(2.87)
- Parameters:
value – A python float.
- Returns:
If the argument is infinite, a
complex_infinity
expression.If the argument is
nan
, anundefined
expression.Otherwise, a
float_constant
expression.
- wrenfold.sym.floor(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The floor function, sometimes written as \(\lfloor x \rfloor\) or \(\text{floor}\left(x\right)\). This function returns the largest integer such that \(\lfloor x \rfloor \le x\).
- Returns:
If the input can be immediately evaluated, an integer constant.
Otherwise, a
function
expression.
Examples
>>> sym.floor(6.7) 6 >>> sym.floor(-3.1) -4 >>> sym.floor(sym.rational(-5, 40)) -2 >>> x = sym.symbols('x') >>> sym.floor(x) floor(x)
- wrenfold.sym.full_piv_lu(m: wrenfold.sym.MatrixExpr) tuple[wrenfold.sym.MatrixExpr, wrenfold.sym.MatrixExpr, wrenfold.sym.MatrixExpr, wrenfold.sym.MatrixExpr] ¶
Factorize a matrix using complete pivoting LU decomposition.
- wrenfold.sym.ge(a: wrenfold.sym.Expr, b: wrenfold.sym.Expr) wrenfold.sym.BooleanExpr ¶
Boolean-valued relational expression \(a \ge b\), or
>=
operator.a >= b
will be automatically canonicalized tob <= a
.Examples
>>> sym.ge(2, 2) True >>> x, y = sym.symbols('x, y') >>> sym.ge(x, y) y <= x
- wrenfold.sym.get_variables(expr: wrenfold.sym.Expr) list[wf::variable] ¶
Retrieve all concrete variable expressions from a symbolic expression tree, and return them in a list.
- Parameters:
expr – A scalar-valued expression.
- Returns:
A list of
wrenfold.sym.Variable
(concrete variable expressions).
Examples
>>> x, y, z = sym.symbols('x, y, z') >>> sym.get_variables(x**2 + y * 3 - sym.cos(z)) [x, y, z] >>> sym.get_variables(x * 3) [x] >>> vs = sym.get_variables(sym.cos(x * y)) >>> type(vs[0]) wrenfold.sym.Variable
- wrenfold.sym.gt(a: wrenfold.sym.Expr, b: wrenfold.sym.Expr) wrenfold.sym.BooleanExpr ¶
Boolean-valued relational expression \(a \gt b\), or
>
operator.a > b
will be automatically canonicalized tob < a
.Examples
>>> sym.gt(2.12, 2) True >>> x, y = sym.symbols('x, y') >>> sym.gt(x, y) y < x
- wrenfold.sym.hstack(values: list[wrenfold.sym.MatrixExpr]) wrenfold.sym.MatrixExpr ¶
Horizontally (joining rows) stack the provided matrices. Number of rows must be the same for every input.
- Raises:
wrenfold.sym.DimensionError – If there is a dimension mismatch, or the input is empty.
- wrenfold.sym.integer(value: int) wrenfold.sym.Expr ¶
Create a constant expression from an integer.
Tip
Typically you do not need to explicitly call this method, since python integers involved in mathematical operations will automatically be promoted to
sym.Expr
:y = x + 3 # Equivalent to: y = x + sym.integer(3)
- Parameters:
value – A python integer.
- Returns:
An
integer_constant
expression representing the argument.- Raises:
TypeError – If the input argument exceeds the range of a signed 64-bit integer.
- wrenfold.sym.iverson(arg: wrenfold.sym.BooleanExpr) wrenfold.sym.Expr ¶
Cast a boolean expression to an integer scalar expression. The iverson bracket of boolean-valued argument \(P\) is defined as:
\[\begin{split}\text{iverson}\left(P\right) = \begin{cases} 1 & P = \text{true} \\ 0 & P = \text{false} \end{cases}\end{split}\]The iverson bracket can be used to convert
sym.BooleanExpr
intosym.Expr
.- Returns:
Boolean constants
sym.true
andsym.false
are converted to one and zero directly.Otherwise, an
iverson_bracket
expression is returned.
Examples
>>> sym.iverson(sym.integer(1) < 3) 1
- wrenfold.sym.jacobian(functions: list[wrenfold.sym.Expr] | wrenfold.sym.MatrixExpr, vars: list[wrenfold.sym.Expr] | wrenfold.sym.MatrixExpr, use_abstract: bool = False) wrenfold.sym.MatrixExpr ¶
Compute the Jacobian of a vector-valued function with respect to multiple variables.
Given
functions
of lengthN
andvars
of lengthM
, this method produces an(N, M)
shaped matrix where element[i, j]
is the partial derivative offunctions[i]
taken with respect tovars[j]
.- Parameters:
functions – An iterable of scalar-valued expressions to differentiate.
vars – An iterable of
variable
orcompound_expression_element
expressions.use_abstract – See
wrenfold.sym.Expr.diff()
.
- Returns:
The Jacobian matrix of shape
(N, M)
.- Raises:
sym.DimensionError – If the dimensions of
functions
orvars
are invalid.
Examples
>>> x, y = sym.symbols('x, y') >>> J = sym.jacobian([x + 1, sym.sin(y*x), x*y**2], [x, y]) >>> J.shape (3, 2) >>> J [[1, 0], [y*cos(x*y), x*cos(x*y)], [y**2, 2*x*y]]
References
- wrenfold.sym.le(a: wrenfold.sym.Expr, b: wrenfold.sym.Expr) wrenfold.sym.BooleanExpr ¶
Boolean-valued relational expression \(a \le b\), or
<=
operator.Examples
>>> sym.le(1, sym.rational(3, 2)) True >>> x, y = sym.symbols('x, y') >>> sym.le(x, y) x <= y
- wrenfold.sym.log(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The natural logarithm \(\ln{x}\).
- Parameters:
arg – Argument to the logarithm.
Examples
>>> x = sym.symbols('x') >>> sym.log(x + 3) log(x + 3) >>> sym.log(sym.E) 1 >>> sym.log(1) 0
- wrenfold.sym.lt(a: wrenfold.sym.Expr, b: wrenfold.sym.Expr) wrenfold.sym.BooleanExpr ¶
Boolean-valued relational expression \(a \lt b\), or
<
operator.Examples
>>> sym.lt(2, 3) True >>> x, y = sym.symbols('x, y') >>> sym.lt(x, y) x < y
- wrenfold.sym.matrix(rows: Iterable) wrenfold.sym.MatrixExpr ¶
Construct a matrix from an iterator over rows. Inputs are vertically concatenated to create a matrix expression.
- Parameters:
rows – Either
Iterable[sym.Expr]
orIterable[Iterable[sym.Expr]]
.
Tip
If the input is an iterable of expressions, the result will have column-vector shape.
- Returns:
A matrix of expressions.
- Raises:
wrenfold.sym.DimensionError – If the input is empty, or the number of columns is inconsistent between rows.
Examples
>>> sym.matrix([1,2,3]) [[1], [2], [3]] >>> sym.matrix([(1,2,3), (x, y, z)]) [[1, 2, 3], [x, y, z]] >>> def yield_rows(): >>> yield sym.matrix([sym.pi, x, 0]).T >>> yield sym.matrix([-2, y**2, sym.cos(x)]).T >>> sym.matrix(yield-rows()) [[pi, x, 0], [-2, y**2, cos(x)]]
- wrenfold.sym.matrix_of_symbols(prefix: str, rows: int, cols: int) wrenfold.sym.MatrixExpr ¶
Construct a matrix of
variable
expressions with the provided prefix.- Parameters:
prefix – String prefix for variable names. Variables will be named
{prefix}_{row}_{col}
.rows – Number of rows.
cols – Number of cols.
- Returns:
A
(rows, cols)
shaped matrix filled withvariable
expressions.- Raises:
wrenfold.sym.DimensionError – If the dimensions are non-positive.
- wrenfold.sym.max(a: wrenfold.sym.Expr, b: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The maximum of two scalar values \(\text{max}\left(a, b\right)\), defined as:
\[\begin{split}\text{max}\left(a, b\right) = \begin{cases} b & a \lt b \\ a & a \ge b \end{cases}\end{split}\]- Returns:
If \(a \lt b\) can be immediately evaluated, the larger of
a
andb
will be returned.Otherwise, a
sym.where
expression.
Examples
>>> x, y = sym.symbols('x, y') >>> sym.max(x, y) where(x < y, y, x) >>> sym.max(2, 3) 3
- wrenfold.sym.min(a: wrenfold.sym.Expr, b: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The minimum of two scalar values \(\text{min}\left(a, b\right)\), defined as:
\[\begin{split}\text{min}\left(a, b\right) = \begin{cases} b & b \lt a \\ a & a \ge b \end{cases}\end{split}\]- Returns:
If \(a \lt b\) can be immediately evaluated, the smaller of
a
andb
will be returned.Otherwise, a
sym.where
expression.
Examples
>>> x, y = sym.symbols('x, y') >>> sym.min(x, y) where(y < x, y, x) >>> sym.min(sym.rational(2, 3), sym.rational(3, 4)) 2/3
- wrenfold.sym.multiplication(args: list[wrenfold.sym.Expr]) wrenfold.sym.Expr ¶
Construct multiplication expression from provided operands.
- wrenfold.sym.pow(base: wrenfold.sym.Expr, exp: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
Construct a power expression: \(\text{pow}\left(x, y\right) \rightarrow x^y\).
pow
will attempt to apply simplifications where possible. Some common cases include:The inputs are numerical values and can be evaluated immediately.
Various undefined forms: \(b^{\tilde{\infty}}\), \({\tilde{\infty}}^0\), \(0^0\).
Distribution of integer powers: \(\left(x \cdot y\right)^n \rightarrow x^n \cdot y^n\)
Collapsing of powers, when appropriate: \(\left(\sqrt{x}\right)^2 \rightarrow x\)
Interactions with complex infinity: \(\tilde{\infty}^n \rightarrow \tilde{\infty}\), \(\tilde{\infty}^{-n} \rightarrow 0\), \(0^{-n} \rightarrow \tilde{\infty}\).
- Parameters:
base – Base of the power.
exp – Exponent of the power.
- Returns:
A symbolic expresssion corresponding to
base ** exp
. The expression need not have underlying typepower
, as a simplification may have occurred.
Examples
>>> sym.pow(3, 2) 9 >>> sym.pow(24, sym.rational(1, 2)) 2*6**(1/2) >>> sym.pow(0, -1) nan >>> sym.pow(sym.zoo, -1) 0 >>> x, w = sym.symbols('x, w') >>> sym.pow(x * w, 2) x**2*w**2 >>> sym.pow(sym.sqrt(x), 2) x >>> sym.sqrt(sym.pow(x, 2)) (x**2)**(1/2)
- wrenfold.sym.rational(n: int, d: int) wrenfold.sym.Expr ¶
Create a constant expression from the quotient of two integers. The rational will be simplified by dividing out the greatest common divisor.
- Parameters:
n – The numerator.
d – The denominator.
- Returns:
If the quotient simplifies to an integer, an integer_constant expression.
Otherwise, a
rational_constant
expression.
- Raises:
wrenfold.exceptions.ArithmeticError – If
d
is zero.
Examples
>>> sym.rational(5, 10) # Equivalent to: sym.integer(5) / 10 1/2 >>> sym.rational(-2, 7) -2/7
- wrenfold.sym.row_vector(*args) wrenfold.sym.MatrixExpr ¶
Create a row-vector from the provided arguments.
- Parameters:
args – The elements of the vector.
- Returns:
A
(1, M)
row vector, whereM
is the number of args.- Raises:
wrenfold.sym.DimensionError – If no arguments are provided.
Examples
>>> x, y = sym.symbols('x, y') >>> sym.row_vector(x * 2, 0, y + 3) [[2*x, 0, 3 + y]]
- wrenfold.sym.sign(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The sign/signum function \(\text{sign}\left(x\right)\), defined as:
\[\begin{split}\text{sign}\left(x\right) = \begin{cases} -1 & x \lt 0 \\ 0 & x = 0 \\ 1 & x \gt 0 \end{cases}\end{split}\]Tip
Like other functions for which no finite derivative exists, by default wrenfold will assume \(\frac{\partial}{\partial x}\text{sign}\left(x\right) = 0\). See
wrenfold.sym.Expr.diff()
for alternative behavior.Caution
Some floating-point implementations of
sign
have the behaviorsign(+0.0) = 1
andsign(-0.0) = -1
. The symbolicsign
function in wrenfold produces zero for all numerical zero-valued inputs.- Returns:
[-1, 0, 1]
. * Otherwise, afunction
expression.- Return type:
If the input can be immediately evaluated, one of
Examples
>>> x = sym.symbols('x') >>> sym.sign(x) sign(x) >>> sym.sign(x).diff(x) 0 >>> sym.sign(-0.78231) -1
- wrenfold.sym.sin(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The sine function \(\sin{x}\).
- Parameters:
arg – Argument in radians.
Examples
>>> x = sym.symbols('x') >>> sym.sin(x) sin(x) >>> sym.sin(0) 0
- wrenfold.sym.sinh(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The hyperbolic sine function \(\sinh{x}\).
Examples
>>> x = sym.symbols('x') >>> sym.sinh(x) sinh(x) >>> sym.sinh(x * sp.I) I*sin(x)
- wrenfold.sym.sqrt(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The square root function \(\sqrt{x}\). This is an alias for
sym.pow(x, sym.rational(1, 2))
.
- wrenfold.sym.stop_derivative(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
Wrap a scalar-valued expression in order to block propagation of derivatives.
stop_derivative
acts like a function whose derivative is always zero.- Parameters:
arg – Scalar-valued expression to wrap.
Examples
>>> x, y = sym.symbols('x, y') >>> f = sym.stop_derivative(x * y) * y >>> f.diff(x) 0 >>> f.diff(y) StopDerivative(x * y)
- wrenfold.sym.subs(*args, **kwargs)¶
Overloaded function.
subs(expr: Union[wrenfold.sym.Expr, wrenfold.sym.MatrixExpr, wrenfold.sym.CompoundExpr, wrenfold.sym.BooleanExpr], pairs: list[Union[tuple[wrenfold.sym.Expr, wrenfold.sym.Expr], tuple[wrenfold.sym.BooleanExpr, wrenfold.sym.BooleanExpr]]]) -> Union[wrenfold.sym.Expr, wrenfold.sym.MatrixExpr, wrenfold.sym.CompoundExpr, wrenfold.sym.BooleanExpr]
Traverse the expression tree and replace target expressions with corresponding substitutions. The list of replacements is executed in order, such that substitutions that appear later in the list of
(target, replacement)
pairs may leverage the result of earlier ones.- Parameters:
pairs – A list of tuples. Each tuple contains a
(target, replacement)
pair, where the target is the expression to find and the replacement is the expression to substitute in its place. The pairs may be scalar-valued or boolean-valued expressions.- Returns:
The input expression after performing replacements.
Examples
>>> x, y = sym.symbols('x, y') >>> sym.cos(x).subs([(x, y*2), (y, sym.pi)]) 1 >>> (sym.pow(x, 2) * y).subs(x * y, 3) 3*x >>> (x + 2*y - 5).subs(x + 2*y, y) -5 + y
subs(expr: Union[wrenfold.sym.Expr, wrenfold.sym.MatrixExpr, wrenfold.sym.CompoundExpr, wrenfold.sym.BooleanExpr], target: wrenfold.sym.Expr, replacement: wrenfold.sym.Expr) -> Union[wrenfold.sym.Expr, wrenfold.sym.MatrixExpr, wrenfold.sym.CompoundExpr, wrenfold.sym.BooleanExpr]
Overload of
subs
that performs a single scalar-valued substitution.subs(expr: Union[wrenfold.sym.Expr, wrenfold.sym.MatrixExpr, wrenfold.sym.CompoundExpr, wrenfold.sym.BooleanExpr], target: wrenfold.sym.BooleanExpr, replacement: wrenfold.sym.BooleanExpr) -> Union[wrenfold.sym.Expr, wrenfold.sym.MatrixExpr, wrenfold.sym.CompoundExpr, wrenfold.sym.BooleanExpr]
Overload of
subs
that performs a single boolean-valued substitution.
- wrenfold.sym.substitution(input: wrenfold.sym.Expr, target: wrenfold.sym.Expr, replacement: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
Create a deferred substitution expression.
- Parameters:
input – The expression that would be modified by the substitution.
target – The target expression being replaced.
replacement – The substituted expression.
Examples
>>> x, y = sym.symbols('x, y') >>> f = sym.substitution(x**2 + y, y, sym.cos(x)) >>> print(f) Subs(y + x**2, y, cos(x)) >>> f.args (y + x**2, y, cos(x))
- Raises:
wrenfold.exceptions.TypeError – If
target
is a numeric constant.
- wrenfold.sym.symbols(names: str | Iterable, real: bool = False, positive: bool = False, nonnegative: bool = False, complex: bool = False) wrenfold.sym.Expr | list ¶
Create instances of
variable
expressions with the provided names. The argumentnames
may be either:A single string containing multiple names separated by whitespace or commas. The string will be split into parts - each of which becomes a variable. If the string contains a single element, a single
sym.Expr
will be returned.An iterable of strings. In this case, each string will be processed per the previous rule and a list of
sym.Expr
will be returned. This rule is applied recursively, such thatIterable[Iterable[str]]
will produce return typeList[List[sym.Expr]]
.
- Parameters:
names – String or nested iterable of strings indicating the variable names.
real – Indicate the symbols are real-valued.
positive – Indicate the symbols are positive and real-valued.
nonnegative – Indicate the symbols are non-negative and real-valued.
complex – Indicate the symbols are complex.
- Returns:
A
variable
expression, or a nested iterable ofvariable
expressions.
Examples
>>> sym.symbols('x') # Creating a single symbol. x >>> sym.symbols('x, y') # Multiple symbols from a single string. [x, y] >>> sym.symbols([('w', 'x'), ('y', 'z')]) # Nested iterable of symbols. [[w, x], [y, z]]
Caution
wrenfold does not yet support the range-syntax implemented in sympy, so evaluating
sym.symbols('x:5')
will not produce the expected result.
- wrenfold.sym.tan(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The tangent function \(\tan{x}\).
- Parameters:
arg – Argument in radians.
Examples
>>> x = sym.symbols('x') >>> sym.tan(x) tan(x) >>> sym.tan(sym.pi/2) zoo
- wrenfold.sym.tanh(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
The hyperbolic tangent function \(\tanh{x}\).
Examples
>>> x = sym.symbols('x') >>> sym.tanh(x) tanh(x) >>> sym.tanh(x * sp.I) I*tan(x)
- wrenfold.sym.unevaluated(arg: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
Wrap a scalar-valued expression to prevent automatic simplifications/combinations in downstream operations. This is similar in intent to SymPy’s
UnevaluatedExpr
.- Parameters:
arg – Scalar-valued expression to wrap.
Examples
>>> x, y = sym.symbols('x, y') >>> f = sym.unevaluated(x * y) * y >>> f # Products are not combined automatically. y*(x*y) >>> f.diff(y) # Derivatives retain the parentheses. y*(x) + (x*y)
- wrenfold.sym.unique_symbols(count: int, real: bool = False, positive: bool = False, nonnegative: bool = False, complex: bool = False) wrenfold.sym.Expr | list ¶
Create instances of
variable
expressions with unique identities that can never be accidentally re-used. This is useful if you need temporary variables that will later be replaced by substitution, and want to be certain that their names do not conflict with other symbols.- Parameters:
count – Number of symbols to create. If one, a single expression is returned. If greater than one, a list of expressions is returned.
Examples
>>> sym.unique_symbols(count=2) [$u_1, $u_2] >>> sym.unique_symbols(count=1) $u_3
- wrenfold.sym.vec(m: wrenfold.sym.MatrixExpr) wrenfold.sym.MatrixExpr ¶
Vectorize matrix in column-major order.
- Parameters:
m – Matrix to flatten.
- Returns:
New column-vector matrix formed by vertically stacking the columns of
m
.
- wrenfold.sym.vector(*args) wrenfold.sym.MatrixExpr ¶
Create a column-vector from the provided arguments.
- Parameters:
args – The elements of the vector.
- Returns:
A
(N, 1)
column vector, whereN
is the number of args.- Raises:
wrenfold.sym.DimensionError – If no arguments are provided.
Examples
>>> x, y = sym.symbols('x, y') >>> sym.vector(x * 2, 0, y + 3) [[2*x], [0], [3 + y]]
- wrenfold.sym.vstack(values: list[wrenfold.sym.MatrixExpr]) wrenfold.sym.MatrixExpr ¶
Vertically (joining columns) stack the provided matrices. Number of columns must be the same for every input.
- Raises:
wrenfold.sym.DimensionError – If there is a dimension mismatch, or the input is empty.
- wrenfold.sym.where(*args, **kwargs)¶
Overloaded function.
where(c: wrenfold.sym.BooleanExpr, a: wrenfold.sym.Expr, b: wrenfold.sym.Expr) -> wrenfold.sym.Expr
where(c, a, b)
will select between eithera
orb
, depending on the boolean-valued expressionc
. Whenc
is true,a
is returned, otherwiseb
is returned:\[\begin{split}\text{where}\left(c, a, b\right) = \begin{cases} a & c = \text{true} \\ b & c = \text{false} \end{cases}\end{split}\]In generated code, conditional expressions are converted to if-else statements.
Tip
When differentiated, the discontinuity introduced by the conditional is ignored. The derivatives of
a
andb
are computed, and a new conditional statement is formed.- Parameters:
c – The boolean-valued condition used to switch between values.
a – Returned if
c
is true.b – Returned if
c
is false.
- Returns:
If the truthiness of
c
can be immediately evaluated,a
orb
is returned directly.Otherwise, a
conditional
expression.
Examples
>>> x, y = sym.symbols('x, y') >>> sym.where(x > y, sym.cos(x), sym.sin(y)) where(y < x, cos(x), sin(y)) >>> sym.where(x > y, sym.pi * x, 0).subs(x, 3).subs(y, 2) 3*pi >>> sym.where(x > y, 4*x**3, 2*y).diff(x) where(y < x, 12*x**2, 0)
where(c: wrenfold.sym.BooleanExpr, a: wrenfold.sym.MatrixExpr, b: wrenfold.sym.MatrixExpr) -> wrenfold.sym.MatrixExpr
Overload of
wrenfold.sym.where()
for matrix arguments. Accepts two identically-shaped matricesa, b
and a boolean-valued expressionc
.- Parameters:
c – Boolean-valued expression.
a – Matrix whose elements are selected when
c
is True.b – Matrix whose elements are selected when
c
is False.
- Returns:
A new matrix where element
[i, j]
evaluates tosym.where(c, a[i, j], b[i, j])
.- Raises:
wrenfold.sym.DimensionError – If the dimensions of
a
andb
do not match.
- wrenfold.sym.zeros(rows: int, cols: int) wrenfold.sym.MatrixExpr ¶
Create a matrix of zeros with the specified shape.
- Parameters:
rows – Number of rows. Must be positive.
cols – Number of cols. Must be positive.
- Returns:
A
(rows, cols)
matrix of zeroes.- Raises:
wrenfold.sym.DimensionError – If the dimensions are non-positive.
Examples
>>> sym.zeros(2, 3) [[0, 0, 0], [0, 0, 0]]
- class wrenfold.sym.BooleanExpr¶
A boolean-valued symbolic expression.
- __bool__(self: wrenfold.sym.BooleanExpr) bool ¶
Coerce expression to boolean.
- __eq__(self: wrenfold.sym.BooleanExpr, other: wrenfold.sym.BooleanExpr) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- __hash__(self: wrenfold.sym.BooleanExpr) int ¶
Compute hash.
- __init__(*args, **kwargs)¶
- property args¶
Arguments of
self
as a tuple.
- expression_tree_str(self: wrenfold.sym.BooleanExpr) str ¶
- is_identical_to(self: wrenfold.sym.BooleanExpr, other: wrenfold.sym.BooleanExpr) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- subs(*args, **kwargs)¶
Overloaded function.
subs(self: wrenfold.sym.BooleanExpr, target: wf::scalar_expr, substitute: wf::scalar_expr) -> wrenfold.sym.BooleanExpr
subs(self: wrenfold.sym.BooleanExpr, target: wrenfold.sym.BooleanExpr, substitute: wrenfold.sym.BooleanExpr) -> wrenfold.sym.BooleanExpr
subs(self: wrenfold.sym.BooleanExpr, pairs: list[Union[tuple[wf::scalar_expr, wf::scalar_expr], tuple[wrenfold.sym.BooleanExpr, wrenfold.sym.BooleanExpr]]]) -> wrenfold.sym.BooleanExpr
- property type_name¶
Retrieve the name of the underlying C++ expression type. See
wrenfold.sym.Expr.type_name()
.
- class wrenfold.sym.CompoundExpr¶
A compound expression is an instance of an aggregate type with members that have been initialized from symbolic expressions. It is used to represent a user-provided struct in the symbolic expression tree. This enables a couple of functionalities:
User types can be passed as input and output arguments from generated functions.
User types can be passed as inputs and outputs from external (non-generated) functions that are invoked from within a generated function.
- __bool__(self: wrenfold.sym.CompoundExpr) None ¶
- __eq__(self: wrenfold.sym.CompoundExpr, other: wrenfold.sym.CompoundExpr) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- __hash__(self: wrenfold.sym.CompoundExpr) int ¶
Compute hash.
- __init__(*args, **kwargs)¶
- is_identical_to(self: wrenfold.sym.CompoundExpr, other: wrenfold.sym.CompoundExpr) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- property type_name¶
Retrieve the name of the underlying C++ expression type. See
wrenfold.sym.Expr.type_name()
.
- class wrenfold.sym.Expr¶
A scalar-valued symbolic expression.
- __abs__(self: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
- __add__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
- __bool__(self: wrenfold.sym.Expr) None ¶
Coerce expression to bool.
- __eq__(self: wrenfold.sym.Expr, other: wrenfold.sym.Expr) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- __ge__(*args, **kwargs)¶
Overloaded function.
__ge__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) -> wrenfold.sym.BooleanExpr
__ge__(self: wrenfold.sym.Expr, arg0: int) -> wrenfold.sym.BooleanExpr
__ge__(self: wrenfold.sym.Expr, arg0: float) -> wrenfold.sym.BooleanExpr
- __gt__(*args, **kwargs)¶
Overloaded function.
__gt__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) -> wrenfold.sym.BooleanExpr
__gt__(self: wrenfold.sym.Expr, arg0: int) -> wrenfold.sym.BooleanExpr
__gt__(self: wrenfold.sym.Expr, arg0: float) -> wrenfold.sym.BooleanExpr
- __hash__(self: wrenfold.sym.Expr) int ¶
Compute hash.
- __init__(*args, **kwargs)¶
Overloaded function.
__init__(self: wrenfold.sym.Expr, arg0: int) -> None
__init__(self: wrenfold.sym.Expr, arg0: float) -> None
- __le__(*args, **kwargs)¶
Overloaded function.
__le__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) -> wrenfold.sym.BooleanExpr
__le__(self: wrenfold.sym.Expr, arg0: int) -> wrenfold.sym.BooleanExpr
__le__(self: wrenfold.sym.Expr, arg0: float) -> wrenfold.sym.BooleanExpr
- __lt__(*args, **kwargs)¶
Overloaded function.
__lt__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) -> wrenfold.sym.BooleanExpr
__lt__(self: wrenfold.sym.Expr, arg0: int) -> wrenfold.sym.BooleanExpr
__lt__(self: wrenfold.sym.Expr, arg0: float) -> wrenfold.sym.BooleanExpr
- __mul__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
- __neg__(self: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
- __pow__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
other_a
- __radd__(*args, **kwargs)¶
Overloaded function.
__radd__(self: wrenfold.sym.Expr, arg0: int) -> wrenfold.sym.Expr
__radd__(self: wrenfold.sym.Expr, arg0: float) -> wrenfold.sym.Expr
- __rmul__(*args, **kwargs)¶
Overloaded function.
__rmul__(self: wrenfold.sym.Expr, arg0: int) -> wrenfold.sym.Expr
__rmul__(self: wrenfold.sym.Expr, arg0: float) -> wrenfold.sym.Expr
- __rpow__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
other_a
- __rsub__(*args, **kwargs)¶
Overloaded function.
__rsub__(self: wrenfold.sym.Expr, arg0: int) -> wrenfold.sym.Expr
__rsub__(self: wrenfold.sym.Expr, arg0: float) -> wrenfold.sym.Expr
- __rtruediv__(*args, **kwargs)¶
Overloaded function.
__rtruediv__(self: wrenfold.sym.Expr, arg0: int) -> wrenfold.sym.Expr
__rtruediv__(self: wrenfold.sym.Expr, arg0: float) -> wrenfold.sym.Expr
- __sub__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
- __truediv__(self: wrenfold.sym.Expr, arg0: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
- property args¶
Arguments of
self
as a tuple.
- collect(*args, **kwargs)¶
Overloaded function.
collect(self: wrenfold.sym.Expr, term: wrenfold.sym.Expr) -> wrenfold.sym.Expr
Overload of
collect
that accepts a single variable.collect(self: wrenfold.sym.Expr, terms: list[wrenfold.sym.Expr]) -> wrenfold.sym.Expr
Combine coefficients of the specified expression(s) (and powers thereof) into additive sums. Given a target expression \(x\),
collect
traverse the expression tree and identifies terms that appear in products with the target. Terms multiplied by matching powers of \(x\) are summed into a new combined coefficient. For example:A single power of \(x\) exists in the input:
\[x\cdot\pi + x \cdot y + x \rightarrow x\cdot\left(\pi + y + 1\right)\]Both \(x\) and \(x^2\) exist in the input:
\[x^2\cdot\sin{y} - x\cdot 5 + x^2 \cdot 4 + x\cdot\pi \rightarrow x\cdot\left(-5 + \pi\right) + x^2\left(4 + \sin{y}\right)\]When multiple input variables are specified,
collect
will group recursively starting with the first variable, then proceeding to the second. For example, if we take the expression:\[x^2 \cdot y \cdot \cos{w} + 3 \cdot y \cdot x^2 + x \cdot y^2 + x \cdot y^2 \cdot \pi - 5 \cdot x^2 \cdot y^2 + x \cdot w\]And collect it with respect to
[x, y]
, we obtain:\[x^2 \cdot \left(y \cdot \left(3 + \cos{w}\right) - 5 \cdot y^2\right) + x \cdot \left(w + y^2 \cdot \left(1 + \pi\right)\right)\]- Parameters:
terms – Sequence of expressions whose coefficients we will collect.
- Returns:
The collected expression.
Examples
>>> x, y, w = sym.symbols('x, y, w') >>> f = x**2*y*sym.cos(w) + 3*y*x**2 + x*y**2 + x*y**2*sym.pi - 5*x**2*y**2 + x*w >>> f.collect(x) x*(w + pi*y**2 + y**2) + x**2*(3*y + y*cos(w) - 5*y**2) >>> f.collect([x, y]) x*(w + y**2*(1 + pi)) + x**2*(y*(3 + cos(w)) - 5*y**2) >>> f.collect([y, x]) w*x + x**2*y*(3 + cos(w)) + y**2*(x*(1 + pi) - 5*x**2)
- diff(self: wrenfold.sym.Expr, var: wrenfold.sym.Expr, order: int = 1, use_abstract: bool = False) wrenfold.sym.Expr ¶
Differentiate the expression with respect to the specified variable.
- Parameters:
var – Scalar variable with respect to which the derivative is taken. Must be of type
variable
orcompound_expression_element
. Differentiation with respect to arbitrary expressions is not permitted.order – Order of the derivative, where 1 is the first derivative.
use_abstract – Governs behavior when a non-differentiable expression is encountered. If false (the default), the value zero is substituted. This is not mathematically accurate, but is often more computationally useful than introducing an expression that would produce
nan
orinf
when evaluated. Ifuse_abstract=True
, an abstractderivative
expression is inserted instead.
- Returns:
Derivative of
self
takenorder
times with respect tovar
.
Examples
Taking the derivative with respect to a variable:
>>> x, y = sym.symbols('x, y') >>> f = x * sym.sin(x * y) + 3 >>> f.diff(x) x*y*cos(x*y) + sin(x*y) >>> f.diff(x, order=2) -x*y**2*sin(x*y) + 2*y*cos(x*y) >>> f.diff(y) x**2*cos(x*y)
- distribute(self: wrenfold.sym.Expr) wrenfold.sym.Expr ¶
- eval(self: wrenfold.sym.Expr) int | float | complex | wrenfold.sym.Expr ¶
Evaluate the mathematical expression into a numeric value. Traverses the expression tree, converting every numeric literal and constant into a double precision float. Operations are recursively evaluated until the result is obtained.
Important
Unlike
sympy.evalf
, no special care is taken to preserve fixed precision. This operation will allow floating point error to propagate normally. Built-in math functions likesin
orlog
will call their C++ STL equivalent.- Returns:
The evaluated result. Typically the result is
float
orcomplex
. If the final result is not coercible to one of these, it will be returned assym.Expr
.
Examples
>>> x = sym.symbols('x') >>> f = sym.cos(sym.pi / 3 + x) >>> f.subs(x, sym.pi).eval() -0.4999999999999998 >>> sym.sin(sym.pi/4 + sym.pi*sym.I/6).eval() >>> (0.8062702490019065+0.3873909064828401j)
- expression_tree_str(self: wrenfold.sym.Expr) str ¶
Recursively traverses the expression tree and creates a pretty-printed string describing the expression. This can be a useful representation for diffing math expression trees.
- Returns:
String representation of the expression tree.
Example
>>> x, y = sym.symbols('x, y') >>> print((x*y + 5).expression_tree_str()) Addition: ├─ Integer (5) └─ Multiplication: ├─ Variable (x, unknown) └─ Variable (y, unknown)
- is_identical_to(self: wrenfold.sym.Expr, other: wrenfold.sym.Expr) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- subs(*args, **kwargs)¶
Overloaded function.
subs(self: wrenfold.sym.Expr, pairs: list[Union[tuple[wrenfold.sym.Expr, wrenfold.sym.Expr], tuple[wrenfold.sym.BooleanExpr, wrenfold.sym.BooleanExpr]]]) -> wrenfold.sym.Expr
See
wrenfold.sym.subs()
.subs(self: wrenfold.sym.Expr, target: wrenfold.sym.Expr, substitute: wrenfold.sym.Expr) -> wrenfold.sym.Expr
Overload of
subs
that performs a single scalar-valued substitution.subs(self: wrenfold.sym.Expr, target: wrenfold.sym.BooleanExpr, substitute: wrenfold.sym.BooleanExpr) -> wrenfold.sym.Expr
Overload of
subs
that performs a single boolean-valued substitution.
- property type_name¶
Retrieve the name of the underlying C++ expression type.
- Returns:
String name of the underlying expression type.
Example
>>> x, y = sym.symbols('x, y') >>> print(x.type_name) Variable >>> print((x + y).type_name) Addition
- class wrenfold.sym.Function¶
A scalar-valued symbolic function. Used to construct expressions of undefined functions.
- __call__(self: wrenfold.sym.Function, *args) wrenfold.sym.Expr ¶
Invoke the symbolic function with the provided scalar expressions, and return a new scalar expression.
- __eq__(self: wrenfold.sym.Function, other: wrenfold.sym.Function) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- __hash__(self: wrenfold.sym.Function) int ¶
Compute hash.
- __init__(self: wrenfold.sym.Function, name: str) None ¶
Declare a new symbolic function with the provided string name. Two functions with the same name are considered equivalent.
- Parameters:
name – Function name.
Examples
>>> x, y = sym.symbols('x, y') >>> f = sym.Function('f') >>> f(x) f(x) >>> f(x, y ** 2).diff(x) Derivative(f(x, y**2), x)
- Raises:
wrenfold.exceptions.InvalidArgumentError – If the input string is empty.
- is_identical_to(self: wrenfold.sym.Function, other: wrenfold.sym.Function) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- property name¶
Name of the function.
- class wrenfold.sym.MatrixExpr¶
A matrix-valued symbolic expression.
- property T¶
Alias for
wrenfold.sym.MatrixExpr.transpose()
.
- __add__(self: wrenfold.sym.MatrixExpr, arg0: wrenfold.sym.MatrixExpr) wrenfold.sym.MatrixExpr ¶
- __array__(self: wrenfold.sym.MatrixExpr, **kwargs) numpy.ndarray ¶
Convert to numpy array.
- __bool__(self: wrenfold.sym.MatrixExpr) None ¶
- __eq__(self: wrenfold.sym.MatrixExpr, other: wrenfold.sym.MatrixExpr) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- __getitem__(*args, **kwargs)¶
Overloaded function.
__getitem__(self: wrenfold.sym.MatrixExpr, row: int) -> Union[wrenfold.sym.Expr, wrenfold.sym.MatrixExpr]
Retrieve a row from the matrix.
__getitem__(self: wrenfold.sym.MatrixExpr, row_col: tuple[int, int]) -> wrenfold.sym.Expr
Retrieve a row and column from the matrix.
__getitem__(self: wrenfold.sym.MatrixExpr, slice: slice) -> wrenfold.sym.MatrixExpr
Slice along rows.
__getitem__(self: wrenfold.sym.MatrixExpr, slices: tuple[slice, slice]) -> wrenfold.sym.MatrixExpr
Slice along rows and cols.
__getitem__(self: wrenfold.sym.MatrixExpr, row_and_col_slice: tuple[int, slice]) -> wrenfold.sym.MatrixExpr
Slice a specific row.
__getitem__(self: wrenfold.sym.MatrixExpr, row_slice_and_col: tuple[slice, int]) -> wrenfold.sym.MatrixExpr
Slice a specific column.
- __hash__(self: wrenfold.sym.MatrixExpr) int ¶
Compute hash.
- __init__(self: wrenfold.sym.MatrixExpr, rows: Iterable) None ¶
Construct from an iterable of values. See
wrenfold.sym.matrix()
.
- __iter__(self: wrenfold.sym.MatrixExpr) Iterator[wrenfold.sym.Expr | wrenfold.sym.MatrixExpr] ¶
Iterate over rows in the matrix.
- __len__(self: wrenfold.sym.MatrixExpr) int ¶
Number of rows in the matrix.
- __mul__(*args, **kwargs)¶
Overloaded function.
__mul__(self: wrenfold.sym.MatrixExpr, arg0: wrenfold.sym.MatrixExpr) -> wrenfold.sym.MatrixExpr
__mul__(self: wrenfold.sym.MatrixExpr, arg0: wrenfold.sym.Expr) -> wrenfold.sym.MatrixExpr
- __neg__(self: wrenfold.sym.MatrixExpr) wrenfold.sym.MatrixExpr ¶
Element-wise negation of the matrix.
- __rmul__(self: wrenfold.sym.MatrixExpr, arg0: wrenfold.sym.Expr) wrenfold.sym.MatrixExpr ¶
- __sub__(self: wrenfold.sym.MatrixExpr, arg0: wrenfold.sym.MatrixExpr) wrenfold.sym.MatrixExpr ¶
- __truediv__(self: wrenfold.sym.MatrixExpr, arg0: wrenfold.sym.Expr) wrenfold.sym.MatrixExpr ¶
- col_join(self: wrenfold.sym.MatrixExpr, other: wrenfold.sym.MatrixExpr) wrenfold.sym.MatrixExpr ¶
Vertically stack
self
andother
.- Parameters:
other – Matrix to stack below
self
.- Raises:
wrenfold.sym.DimensionError – If the number of columns does not match.
- collect(*args, **kwargs)¶
Overloaded function.
collect(self: wrenfold.sym.MatrixExpr, var: wrenfold.sym.Expr) -> wrenfold.sym.MatrixExpr
Invokes
wrenfold.sym.Expr.collect()
on every element of the matrix. This overload accepts a single variable.collect(self: wrenfold.sym.MatrixExpr, var: list[wrenfold.sym.Expr]) -> wrenfold.sym.MatrixExpr
Invokes
wrenfold.sym.Expr.collect()
on every element of the matrix. This overload accepts a list of variables, and collects recursively in the order they are specified.
- det(self: wrenfold.sym.MatrixExpr) wrenfold.sym.Expr ¶
Alias for
wrenfold.sym.det()
.
- diff(self: wrenfold.sym.MatrixExpr, var: wrenfold.sym.Expr, order: int = 1, use_abstract: bool = False) wrenfold.sym.MatrixExpr ¶
Differentiate every element of the matrix with respect to the specified variable.
See
wrenfold.sym.Expr.diff()
for meaning of the arguments.- Returns:
A new matrix (with the same shape as
self
) where each element is the derivative of the corresponding input element, takenorder
times with respect tovar
.
Examples
>>> x = sym.symbols('x') >>> m = sym.matrix([[x, sym.sin(x)], [22, -x**2]]) >>> m.diff(x) [[1, cos(x)], [0, -2*x]]
- distribute(self: wrenfold.sym.MatrixExpr) wrenfold.sym.MatrixExpr ¶
Invoke
wrenfold.sym.distribute()
on every element of the matrix.
- eval(self: wrenfold.sym.MatrixExpr) numpy.ndarray ¶
Invoke
wrenfold.sym.Expr.eval()
on every element of the matrix, and return a numpy array containing the resulting values.
- expression_tree_str(self: wrenfold.sym.MatrixExpr) str ¶
- property is_empty¶
True if the matrix empty (either zero rows or cols). This should only occur with empty slices.
- is_identical_to(self: wrenfold.sym.MatrixExpr, other: wrenfold.sym.MatrixExpr) bool ¶
Check for strict equality. This is not the same as mathematical equivalence.
- jacobian(self: wrenfold.sym.MatrixExpr, vars: list[wrenfold.sym.Expr] | wrenfold.sym.MatrixExpr, use_abstract: bool = False) wrenfold.sym.MatrixExpr ¶
See
wrenfold.sym.jacobian()
. Equivalent tosym.jacobian(self, vars)
.
- norm(self: wrenfold.sym.MatrixExpr) wrenfold.sym.Expr ¶
The L2 norm of the matrix, or square root of
wrenfold.sym.MatrixExpr.squared_norm()
.
- reshape(*args, **kwargs)¶
Overloaded function.
reshape(self: wrenfold.sym.MatrixExpr, rows: int, cols: int) -> wrenfold.sym.MatrixExpr
Reshape a matrix and return a copy with the new shape. The underlying order (row-major) of elements in
self
is unchanged. The expressions are simply copied into a new matrix with the requested number of rows and columns. The total number of elements must remain unchanged.- Parameters:
rows – Number of rows in the output.
cols – Number of columns in the output.
- Returns:
A new matrix with shape
(rows, cols)
.- Raises:
wrenfold.sym.DimensionError – If the specified dimensions are invalid.
Examples
>>> sym.matrix([1, 2, 3, 4]).reshape(2, 2) [[1, 2], [3, 4]]
reshape(self: wrenfold.sym.MatrixExpr, shape: tuple[int, int]) -> wrenfold.sym.MatrixExpr
Overload of
reshape
that accepts a (row, col) tuple.
- row_join(self: wrenfold.sym.MatrixExpr, other: wrenfold.sym.MatrixExpr) wrenfold.sym.MatrixExpr ¶
Horizontally stack
self
andother
.- Parameters:
other – Matrix to stack to the right of
self
.- Raises:
wrenfold.sym.DimensionError – If the number of rows does not match.
- property shape¶
Shape of the matrix in (row, col) format.
- property size¶
Total number of elements.
- squared_norm(self: wrenfold.sym.MatrixExpr) wrenfold.sym.Expr ¶
The sum of squared elements of
self
, or the squared L2 norm.- Returns:
A scalar-valued expression.
Examples
>>> x, y = sym.symbols('x, y') >>> m = sym.matrix([[x, y], [2, 0]]) >>> m.squared_norm() 4 + x**2 + y**2
- subs(*args, **kwargs)¶
Overloaded function.
subs(self: wrenfold.sym.MatrixExpr, target: wrenfold.sym.Expr, substitute: wrenfold.sym.Expr) -> wrenfold.sym.MatrixExpr
Overload of
subs
that performs a single scalar-valued substitution.subs(self: wrenfold.sym.MatrixExpr, target: wrenfold.sym.BooleanExpr, substitute: wrenfold.sym.BooleanExpr) -> wrenfold.sym.MatrixExpr
Overload of
subs
that performs a single boolean-valued substitution.subs(self: wrenfold.sym.MatrixExpr, pairs: list[Union[tuple[wrenfold.sym.Expr, wrenfold.sym.Expr], tuple[wrenfold.sym.BooleanExpr, wrenfold.sym.BooleanExpr]]]) -> wrenfold.sym.MatrixExpr
Invoke
wrenfold.sym.subs()
on every element of the matrix.
- to_flat_list(self: wrenfold.sym.MatrixExpr) list ¶
Convert to a flat list assembled in the storage order (row-major) of the matrix.
- to_list(self: wrenfold.sym.MatrixExpr) list ¶
Convert to a list of lists.
- transpose(self: wrenfold.sym.MatrixExpr) wrenfold.sym.MatrixExpr ¶
Transpose the matrix by swapping rows and columns. If
self
has dimensions(N, M)
, the result will be an(M, N)
matrix where element[i, j]
isself[j, i]
.- Returns:
The transposed matrix.
Examples
>>> x, y = sym.symbols('x, y') >>> m = sym.matrix([[x, y*2], [sym.cos(x), 0]]) >>> m [[x, 2*y], [cos(x), 0]] >>> m.transpose() [[x, cos(x)], [2*y, 0]]
- property type_name¶
Retrieve the name of the underlying C++ expression type. See
wrenfold.sym.Expr.type_name()
.
- unary_map(self: wrenfold.sym.MatrixExpr, func: Callable[[wrenfold.sym.Expr], wrenfold.sym.Expr]) wrenfold.sym.MatrixExpr ¶
Perform a unary map operation on
self
. The provided callablefunc
is invoked on every element of the matrix (traversing in row-major order). The returned values are used to create a new matrix with the same shape as the input.- Parameters:
func – A callable that accepts and returns
sym.Expr
.- Returns:
The mapped matrix.
Examples
>>> x, y = sym.symbols('x, y') >>> m = sym.matrix([[x, y], [2, sym.pi]]) >>> m.unary_map(lambda v: v * 2) [[2*x, 2*y], [4, 2*pi]]