Every symcompR expression is a tree: an operation (its type) applied to arguments, down to atoms such as symbols and numbers. This vignette shows how to inspect that tree, substitute into it, match patterns against it, rewrite it with rules, and keep parts of it unevaluated.
library(symcompR)
x <- Symbol("x"); y <- Symbol("y"); z <- Symbol("z")
a <- Symbol("a"); b <- Symbol("b")
f <- Function("f"); g <- Function("g")Many functions here return lists of expressions. A small helper prints them on one line.
show <- function(l) vapply(l, sstr, "")Inspecting structure
e <- x^2 * sin(y) + 3
sym_type(e)
#> [1] "Add"
show(sym_args(e))
#> [1] "3" "x^2*sin(y)"
has(e, y)
#> [1] TRUE
has(e, z)
#> [1] FALSE
show(free_symbols(e))
#> [1] "x" "y"
show(atoms(e))
#> [1] "3" "y" "x" "2"
show(atoms(e, "Symbol"))
#> [1] "y" "x"
show(atoms(e, "Integer"))
#> [1] "3" "2"
show(atoms(e, "Function"))
#> [1] "sin(y)"Bound variables, such as an integration variable, are not free:
show(free_symbols(Integral(x * y, list(x, 0, 1))))
#> [1] "y"count_ops() counts the operations in an expression; with
visual = TRUE it shows which ones. The simplification
functions use it as a measure of complexity.
count_ops(x^2 + sin(x) / y)
#> [1] 4
count_ops(x^2 + sin(x) / y, visual = TRUE)
#> ADD + DIV + POW + SINpostorder_traversal() and
preorder_traversal() visit every subexpression.
bottom_up() rebuilds an expression by applying a function
to every subexpression, starting from the leaves.
length(postorder_traversal(e))
#> [1] 8
vapply(preorder_traversal(sin(cos(x))), sstr, "")
#> [1] "sin(cos(x))" "cos(x)" "x"
bottom_up(sin(2 * x) + cos(2 * x)^2, expand_trig)
#> (2*cos(x)^2 - 1)^2 + 2*sin(x)*cos(x)Substitution
subs() replaces subexpressions; replacements given in a
list are applied one after the other, unless
simultaneous = TRUE. xreplace() replaces exact
subtrees only, without any mathematical matching.
subs(x^2 + y, x, 2)
#> y + 4
subs(x + y * z, y * z, a)
#> a + x
subs(x + y, list(list(x, y), list(y, x)))
#> 2*x
subs(x + y, list(list(x, y), list(y, x)), simultaneous = TRUE)
#> x + y
xreplace(x * y + 1, list(list(x * y, z)))
#> z + 1Subs() is an unevaluated substitution, used for example
for derivatives evaluated at a point.
Pattern matching and rewriting
Wildcards, unification, rule based rewriting, and expression paths
are covered in
vignette("pattern-matching", package = "symcompR").
Extracting parts
extract_multiplicatively(2 * x, 2)
#> x
extract_multiplicatively((x * y)^3, x^2 * y)
#> x*y^2
extract_additively(x + 3, 2)
#> x + 1
as_coefficient(2 * sym_I * x, sym_I)
#> 2*xRelations
Eq(), Ne(), Lt(),
Le(), Gt(), and Ge() create
relations. They evaluate to TRUE or FALSE when
the answer is determined, and stay symbolic otherwise.
r <- Eq(x^2, 4)
lhs(r)
#> x^2
rhs(r)
#> 4
Ne(x, 1)
#> Ne(x, 1)
Gt(x, 1) & Lt(x, 3)
#> (x > 1) & (x < 3)
subs(Eq(x + 1, 3), x, 2)
#> True
Lt(2, 3)
#> TrueNote that == compares structure, not mathematical
equality:
expand((x + 1)^2) == x^2 + 2 * x + 1
#> [1] TRUE
(x + 1)^2 == x^2 + 2 * x + 1
#> [1] FALSEUnevaluated expressions
UnevaluatedExpr() protects a subexpression from
automatic simplification until doit() is called.
x * UnevaluatedExpr(1 / x)
#> x*1/x
doit(x * UnevaluatedExpr(1 / x))
#> 1evaluate(FALSE, expr) evaluates expr with
automatic evaluation turned off, as SymPy’s evaluate(False)
context manager: sums, products, powers, relations and function calls
stay as written.
Kinds and classes
expr_kind() is SymPy’s .kind: the
mathematical kind of an object, whatever its class.
isinstance() tests an expression against SymPy class names,
following SymPy’s class hierarchy.
expr_kind(x + 1)
#> NumberKind
expr_kind(x > 1)
#> BooleanKind
expr_kind(Matrix(list(1, x)))
#> MatrixKind(NumberKind)
expr_kind(FiniteSet(1, x))
#> SetKind(NumberKind)
isinstance(x, "Atom")
#> [1] TRUE
isinstance(x + 1, c("Number", "Add"))
#> [1] TRUEAnonymous functions
Lambda() creates a symbolic function;
rcall() applies it.
sq <- Lambda(x, x^2)
sq
#> Lambda(x, x^2)
rcall(sq, 3)
#> 9
apply_lambda(sq, 3)
#> 9Singleton constants
The S_* objects are the singletons of SymPy’s
S registry. They are ordinary symcompR expressions, and
TribonacciConstant is one more named constant.
Small constructors and helpers
Add(), Mul(), and Pow() build
a sum, a product, and a power, ln() is the natural
logarithm, Id() is the identity, and Tuple()
holds a fixed sequence of expressions. sym_name() returns
the name of a symbol, is_sym() tests for a symcompR object,
as_sym() converts R values and strings,
numbered_symbols() makes a run of fresh symbols, and
sym_prod() multiplies a list. sym_poly() is
the poly() function of SymPy.
Add(x, y, 2)
#> x + y + 2
Mul(2, x, y)
#> 2*x*y
Pow(x, 2)
#> x^2
ln(x)
#> log(x)
Id(x)
#> x
Tuple(1, x)
#> (1, x)
sym_name(x)
#> [1] "x"
c(is_sym(x), is_sym(2))
#> [1] TRUE FALSE
as_sym("x + 1")
#> x + 1
show(numbered_symbols("y", 3))
#> [1] "y0" "y1" "y2"
sym_prod(list(1, 2, 3, x))
#> 6*x
sym_poly(x^2 + 2 * x + 1)
#> Poly(x^2 + 2*x + 1, x, domain='ZZ')sym_ordered() sorts expressions into SymPy’s canonical
order, sym_reshape() regroups a flat list, and
nfloat() turns the rational coefficients of an expression
into floats while leaving its powers exact. comp() compares
two numbers to a tolerance.
show(sym_ordered(list(x^2, x, S(1), y)))
#> [1] "1" "x" "y" "x^2"
vapply(sym_reshape(as.list(0:5), 2), function(r) paste(unlist(r), collapse = " "), "")
#> [1] "0 1" "2 3" "4 5"
nfloat(x^2 + 2 * x / 3)
#> x^2 + 0.666666666666667*x
c(comp(1, 1.001, 0.01), comp(1, 1.1, 0.01))
#> [1] TRUE FALSEsym_rf() and ff() are the rising and
falling factorials; with an integer second argument they expand into
products.
sym_rf(x, 3)
#> x*(x + 1)*(x + 2)
ff(x, 3)
#> x*(x - 2)*(x - 1)
expand(expand_func(ff(x, 3)))
#> x^3 - 3*x^2 + 2*xInteger helpers
integer_log(y, x) returns the largest e
with x^e <= y and whether the power is exact,
num_digits() counts digits in a base,
trailing() counts the trailing zero bits, and
arity() counts the arguments of an R function.
str(integer_log(125, 5))
#> List of 2
#> $ e : num 3
#> $ exact: logi TRUE
str(integer_log(126, 5))
#> List of 2
#> $ e : num 3
#> $ exact: logi FALSE
c(num_digits(123456), num_digits(255, 16), trailing(48))
#> [1] 6 2 4
arity(function(a, b) a)
#> [1] 2Content, primitive parts, and signs
add_primitive() and as_content_primitive()
pull the rational content out of a sum, gcd_terms() factors
out common terms without full factorization, and
extract_branch_factor() splits a polar exponential into a
principal part and a number of turns.
could_extract_minus_sign() tells whether an expression
reads more naturally with its sign flipped.
show(add_primitive(2 * x + 4))
#> [1] "2" "x + 2"
show(as_content_primitive(2 * x + 6 * y))
#> [1] "2" "x + 3*y"
gcd_terms((x + 1)^2 * y + (x + 1) * y^2)
#> y*(x + 1)*(x + y + 1)
show(extract_branch_factor(exp_polar(5 * sym_I * sym_pi)))
#> [1] "exp_polar(I*pi)" "2"
c(could_extract_minus_sign(-x - y), could_extract_minus_sign(x - y))
#> [1] TRUE FALSEfactor_nc() factors expressions with noncommutative
symbols, keeping the order of the factors.
Relation constructors
The relational classes have constructors under their SymPy class
names, and Rel() picks the class from an operator string.
Contains() states that an element lies in a set; it
evaluates when the answer is known.
Equality(x, 1)
#> Eq(x, 1)
GreaterThan(x, 1)
#> x >= 1
LessThan(x, 1)
#> x <= 1
StrictGreaterThan(x, 1)
#> x > 1
StrictLessThan(x, 1)
#> x < 1
Unequality(x, 1)
#> Ne(x, 1)
Le(x, 1)
#> x <= 1
Rel(x, 1, "<")
#> x < 1
Contains(x, Interval(0, 1))
#> Contains(x, Interval(0, 1))
Contains(Rational(1, 2), Interval(0, 1))
#> TrueDictionaries
Dict() is SymPy’s immutable dictionary of expressions,
with dict_get(), dict_keys(),
dict_values(), and dict_items().
d <- Dict(list(x, y), list(1, 2))
d
#> {x: 1, y: 2}
dict_get(d, x)
#> 1
show(dict_keys(d))
#> [1] "x" "y"
show(dict_values(d))
#> [1] "1" "2"
show(dict_items(d))
#> [1] "(x, 1)" "(y, 2)"Exact numbers as gmp objects
as_bigq() and as_bigz() return the exact
value of a rational or integer as a gmp number.
Dummy symbols
Dummy() creates a symbol that is never equal to any
other symbol, even one with the same name. It is used internally for
temporary variables.
Indexed objects
IndexedBase() and Idx() represent
subscripted quantities such as matrix entries, and
get_indices() finds the free indices of a product,
following the summation convention for repeated indices.
i <- Idx("i"); j <- Idx("j")
A <- IndexedBase("A"); v <- IndexedBase("v")
A(i, j) * v(j)
#> A[i, j]*v[j]
show(get_indices(A(i, j) * v(j))$indices)
#> [1] "i"