API Reference

High-level façade for the applied_dynamics-dynamics package.

This module does not import applied_dynamics.apis at import time (to avoid cycles). It offers: - System presets via applied_dynamics.design - Symbolic derivation (Lagrange engine) for any applied_dynamics.core.System - Convenience wrappers for common systems (pendulums, planar 2R, cart+absorber) - Optional numeric simulation hooks (adapter over applied_dynamics.integrators) - Problem-API helpers used by CLI/tests - Class diagram utilities via applied_dynamics.tools.diagram

class applied_dynamics.app.AppInfo(name: str = 'applied_dynamics-dynamics', version: str = '0.1.0', homepage: str = 'https://example.local/applied')[source]

Immutable metadata about the application.

homepage: str = 'https://example.local/applied'
name: str = 'applied_dynamics-dynamics'
version: str = '0.1.0'
class applied_dynamics.app.AppliedApp(in_dir: str | Path | None = None, out_dir: str | Path | None = None)[source]

High-level façade for applied_dynamics dynamics workflows.

Responsibilities

  • Build System presets from applied_dynamics.design.

  • Derive symbolic equations of motion_kinematics using the Lagrange engine.

  • Optional numerical simulation front-end (wrapping applied_dynamics.integrators).

  • Problem-API helpers used by CLI/tests (derive / simulate / batch).

  • Class diagram helpers (DOT / Mermaid Markdown).

class_diagram_dot() → str[source]

Return Graphviz DOT for the applied_dynamics package classes.

derive(sys: System) → DerivationResult[source]

Symbolically derive the EOM for any System using the applied_dynamics.dynamics.LagrangeEngine.

derive_cart_absorber(M: int | float, m: int | float, l: int | float, k: int | float, g: int | float) → DerivationResult[source]
derive_from_path(path: str | Path) → DerivationResult[source]
derive_planar_2r(m1: int | float, m2: int | float, l1: int | float, l2: int | float, g: int | float) → DerivationResult[source]
derive_problem(problem: Mapping[str, Any]) → DerivationResult[source]

Derive EOM for a problem dict with a ‘model’ section.

derive_simple_pendulum(m: int | float, l: int | float, g: int | float) → DerivationResult[source]
derive_spherical_pendulum(m: int | float, l: int | float, g: int | float) → DerivationResult[source]
generate_class_diagram(out_markdown: Path) → Path[source]

Discover classes in the applied_dynamics package and emit Mermaid classDiagram.

preset(name: str, **params: Any) → System[source]

Generic preset builder routed to applied_dynamics.design.DesignLibrary.

preset_cart_absorber(M: int | float, m: int | float, l: int | float, k: int | float, g: int | float) → System[source]
preset_planar_2r(m1: int | float, m2: int | float, l1: int | float, l2: int | float, g: int | float) → System[source]
preset_simple_pendulum(m: int | float, l: int | float, g: int | float) → System[source]
preset_spherical_pendulum(m: int | float, l: int | float, g: int | float) → System[source]
run_all_to_out() → List[DerivationResult][source]

Derive a handful of canonical systems and dump artifacts to applied_dynamics/out.

simulate_symbolic(sys: System, t_span: Tuple[float, float], y0: Sequence[float], *, steps: int = 1000, method: str = 'RK45', rtol: float = 1e-06, atol: float = 1e-09, args: Mapping[str, Any] | None = None) → Mapping[str, Any][source]

Simulate a System from its symbolic EOM by auto-lambdifying the ODE right-hand side (see applied_dynamics.integrators).

class applied_dynamics.app.DerivationResult(name: str, q: MutableDenseMatrix, qd: MutableDenseMatrix, L: Expr, K: Expr, V: Expr, Q: MutableDenseMatrix, EOM: MutableDenseMatrix)[source]

Symbolic derivation artifacts for a system.

EOM: MutableDenseMatrix
K: Expr
L: Expr
Q: MutableDenseMatrix
V: Expr
name: str
q: MutableDenseMatrix
qd: MutableDenseMatrix

Core object model for applied_dynamics dynamics (Lagrangian mechanics).

What’s inside

  • Inertia — rigid-body mass properties & parallel-axis shift

  • FrameState — (q, q̇) container used by energy providers

  • Energy (Protocol) — kinetic() / potential() contract

  • System (ABC) — base class for Lagrange-ready systems:
    • lagrangian_state() → (q, qd, t)

    • energy() → Energy

    • generalized_forces(fs) → Q(q, q̇, t)

    • lagrangian() → K - V

    • mass_matrix() → ∂²K/∂q̇∂q̇ᵀ

    • equations_of_motion() → Euler–Lagrange LHS

Design notes

class applied_dynamics.core.Energy(*args, **kwargs)[source]

Kinetic & potential energy providers for a system.

kinetic(fs: FrameState) → Expr[source]
potential(fs: FrameState) → Expr[source]
class applied_dynamics.core.Expr(*args)[source]

Base class for algebraic expressions.

Explanation

Everything that requires arithmetic operations to be defined should subclass this class, instead of Basic (which should be used only for argument storage and expression manipulation, i.e. pattern matching, substitutions, etc).

If you want to override the comparisons of expressions: Should use _eval_is_ge for inequality, or _eval_is_eq, with multiple dispatch. _eval_is_ge return true if x >= y, false if x < y, and None if the two types are not comparable or the comparison is indeterminate

See also

sympy.core.basic.Basic

adjoint()[source]
apart(x=None, **args)[source]

See the apart function in sympy.polys

args_cnc(cset=False, warn=True, split_1=True)[source]

Return [commutative factors, non-commutative factors] of self.

Explanation

self is treated as a Mul and the ordering of the factors is maintained. If cset is True the commutative factors will be returned in a set. If there were repeated factors (as may happen with an unevaluated Mul) then an error will be raised unless it is explicitly suppressed by setting warn to False.

Note: -1 is always separated from a Number unless split_1 is False.

Examples

>>> from sympy import symbols, oo
>>> A, B = symbols('A B', commutative=0)
>>> x, y = symbols('x y')
>>> (-2*x*y).args_cnc()
[[-1, 2, x, y], []]
>>> (-2.5*x).args_cnc()
[[-1, 2.5, x], []]
>>> (-2*x*A*B*y).args_cnc()
[[-1, 2, x, y], [A, B]]
>>> (-2*x*A*B*y).args_cnc(split_1=False)
[[-2, x, y], [A, B]]
>>> (-2*x*y).args_cnc(cset=True)
[{-1, 2, x, y}, []]

The arg is always treated as a Mul:

>>> (-2 + x + A).args_cnc()
[[], [x - 2 + A]]
>>> (-oo).args_cnc() # -oo is a singleton
[[-1, oo], []]
as_base_exp() → tuple[Expr, Expr][source]
as_coeff_Add(rational=False) → tuple['Number', Expr][source]

Efficiently extract the coefficient of a summation.

as_coeff_Mul(rational: bool = False) → tuple['Number', Expr][source]

Efficiently extract the coefficient of a product.

as_coeff_add(*deps) → tuple[Expr, tuple[Expr, ...]][source]

Return the tuple (c, args) where self is written as an Add, a.

c should be a Rational added to any terms of the Add that are independent of deps.

args should be a tuple of all other terms of a; args is empty if self is a Number or if self is independent of deps (when given).

This should be used when you do not know if self is an Add or not but you want to treat self as an Add or if you want to process the individual arguments of the tail of self as an Add.

  • if you know self is an Add and want only the head, use self.args[0];

  • if you do not want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail.

  • if you want to split self into an independent and dependent parts use self.as_independent(*deps)

>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_add()
(3, ())
>>> (3 + x).as_coeff_add()
(3, (x,))
>>> (3 + x + y).as_coeff_add(x)
(y + 3, (x,))
>>> (3 + y).as_coeff_add(x)
(y + 3, ())
as_coeff_exponent(x) → tuple[Expr, Expr][source]

c*x**e -> c,e where x can be any symbolic expression.

as_coeff_mul(*deps, **kwargs) → tuple[Expr, tuple[Expr, ...]][source]

Return the tuple (c, args) where self is written as a Mul, m.

c should be a Rational multiplied by any factors of the Mul that are independent of deps.

args should be a tuple of all other factors of m; args is empty if self is a Number or if self is independent of deps (when given).

This should be used when you do not know if self is a Mul or not but you want to treat self as a Mul or if you want to process the individual arguments of the tail of self as a Mul.

  • if you know self is a Mul and want only the head, use self.args[0];

  • if you do not want to process the arguments of the tail but need the tail then use self.as_two_terms() which gives the head and tail;

  • if you want to split self into an independent and dependent parts use self.as_independent(*deps)

>>> from sympy import S
>>> from sympy.abc import x, y
>>> (S(3)).as_coeff_mul()
(3, ())
>>> (3*x*y).as_coeff_mul()
(3, (x, y))
>>> (3*x*y).as_coeff_mul(x)
(3*y, (x,))
>>> (3*y).as_coeff_mul(x)
(3*y, ())
as_coefficient(expr: Expr) → Expr | None[source]

Extracts symbolic coefficient at the given expression. In other words, this functions separates ‘self’ into the product of ‘expr’ and ‘expr’-free coefficient. If such separation is not possible it will return None.

Examples

>>> from sympy import E, pi, sin, I, Poly
>>> from sympy.abc import x
>>> E.as_coefficient(E)
1
>>> (2*E).as_coefficient(E)
2
>>> (2*sin(E)*E).as_coefficient(E)

Two terms have E in them so a sum is returned. (If one were desiring the coefficient of the term exactly matching E then the constant from the returned expression could be selected. Or, for greater precision, a method of Poly can be used to indicate the desired term from which the coefficient is desired.)

>>> (2*E + x*E).as_coefficient(E)
x + 2
>>> _.args[0]  # just want the exact match
2
>>> p = Poly(2*E + x*E); p
Poly(x*E + 2*E, x, E, domain='ZZ')
>>> p.coeff_monomial(E)
2
>>> p.nth(0, 1)
2

Since the following cannot be written as a product containing E as a factor, None is returned. (If the coefficient 2*x is desired then the coeff method should be used.)

>>> (2*E*x + x).as_coefficient(E)
>>> (2*E*x + x).coeff(E)
2*x
>>> (E*(x + 1) + x).as_coefficient(E)
>>> (2*pi*I).as_coefficient(pi*I)
2
>>> (2*I).as_coefficient(pi*I)

See also

coeff

return sum of terms have a given factor

as_coeff_Add

separate the additive constant from an expression

as_coeff_Mul

separate the multiplicative constant from an expression

as_independent

separate x-dependent terms/factors from others

sympy.polys.polytools.Poly.coeff_monomial

efficiently find the single coefficient of a monomial in Poly

sympy.polys.polytools.Poly.nth

like coeff_monomial but powers of monomial terms are used

as_coefficients_dict(*syms)[source]

Return a dictionary mapping terms to their Rational coefficient. Since the dictionary is a defaultdict, inquiries about terms which were not present will return a coefficient of 0.

If symbols syms are provided, any multiplicative terms independent of them will be considered a coefficient and a regular dictionary of syms-dependent generators as keys and their corresponding coefficients as values will be returned.

Examples

>>> from sympy.abc import a, x, y
>>> (3*x + a*x + 4).as_coefficients_dict()
{1: 4, x: 3, a*x: 1}
>>> _[a]
0
>>> (3*a*x).as_coefficients_dict()
{a*x: 3}
>>> (3*a*x).as_coefficients_dict(x)
{x: 3*a}
>>> (3*a*x).as_coefficients_dict(y)
{1: 3*a*x}
as_content_primitive(radical=False, clear=True)[source]

This method should recursively remove a Rational from all arguments and return that (content) and the new self (primitive). The content should always be positive and Mul(*foo.as_content_primitive()) == foo. The primitive need not be in canonical form and should try to preserve the underlying structure if possible (i.e. expand_mul should not be applied to self).

Examples

>>> from sympy import sqrt
>>> from sympy.abc import x, y, z
>>> eq = 2 + 2*x + 2*y*(3 + 3*y)

The as_content_primitive function is recursive and retains structure:

>>> eq.as_content_primitive()
(2, x + 3*y*(y + 1) + 1)

Integer powers will have Rationals extracted from the base:

>>> ((2 + 6*x)**2).as_content_primitive()
(4, (3*x + 1)**2)
>>> ((2 + 6*x)**(2*y)).as_content_primitive()
(1, (2*(3*x + 1))**(2*y))

Terms may end up joining once their as_content_primitives are added:

>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(11, x*(y + 1))
>>> ((3*(x*(1 + y)) + 2*x*(3 + 3*y))).as_content_primitive()
(9, x*(y + 1))
>>> ((3*(z*(1 + y)) + 2.0*x*(3 + 3*y))).as_content_primitive()
(1, 6.0*x*(y + 1) + 3*z*(y + 1))
>>> ((5*(x*(1 + y)) + 2*x*(3 + 3*y))**2).as_content_primitive()
(121, x**2*(y + 1)**2)
>>> ((x*(1 + y) + 0.4*x*(3 + 3*y))**2).as_content_primitive()
(1, 4.84*x**2*(y + 1)**2)

Radical content can also be factored out of the primitive:

>>> (2*sqrt(2) + 4*sqrt(10)).as_content_primitive(radical=True)
(2, sqrt(2)*(1 + 2*sqrt(5)))

If clear=False (default is True) then content will not be removed from an Add if it can be distributed to leave one or more terms with integer coefficients.

>>> (x/2 + y).as_content_primitive()
(1/2, x + 2*y)
>>> (x/2 + y).as_content_primitive(clear=False)
(1, x/2 + y)
as_expr(*gens)[source]

Convert a polynomial to a SymPy expression.

Examples

>>> from sympy import sin
>>> from sympy.abc import x, y
>>> f = (x**2 + x*y).as_poly(x, y)
>>> f.as_expr()
x**2 + x*y
>>> sin(x).as_expr()
sin(x)
as_independent(*deps, **hint) → tuple[Expr, Expr][source]

A mostly naive separation of a Mul or Add into arguments that are not are dependent on deps. To obtain as complete a separation of variables as possible, use a separation method first, e.g.:

  • separatevars() to change Mul, Add and Pow (including exp) into Mul

  • .expand(mul=True) to change Add or Mul into Add

  • .expand(log=True) to change log expr into an Add

The only non-naive thing that is done here is to respect noncommutative ordering of variables and to always return (0, 0) for self of zero regardless of hints.

For nonzero self, the returned tuple (i, d) has the following interpretation:

  • i will has no variable that appears in deps

  • d will either have terms that contain variables that are in deps, or be equal to 0 (when self is an Add) or 1 (when self is a Mul)

  • if self is an Add then self = i + d

  • if self is a Mul then self = i*d

  • otherwise (self, S.One) or (S.One, self) is returned.

To force the expression to be treated as an Add, use the hint as_Add=True

Examples

– self is an Add

>>> from sympy import sin, cos, exp
>>> from sympy.abc import x, y, z
>>> (x + x*y).as_independent(x)
(0, x*y + x)
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> (2*x*sin(x) + y + x + z).as_independent(x)
(y + z, 2*x*sin(x) + x)
>>> (2*x*sin(x) + y + x + z).as_independent(x, y)
(z, 2*x*sin(x) + x + y)

– self is a Mul

>>> (x*sin(x)*cos(y)).as_independent(x)
(cos(y), x*sin(x))

non-commutative terms cannot always be separated out when self is a Mul

>>> from sympy import symbols
>>> n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
>>> (n1 + n1*n2).as_independent(n2)
(n1, n1*n2)
>>> (n2*n1 + n1*n2).as_independent(n2)
(0, n1*n2 + n2*n1)
>>> (n1*n2*n3).as_independent(n1)
(1, n1*n2*n3)
>>> (n1*n2*n3).as_independent(n2)
(n1, n2*n3)
>>> ((x-n1)*(x-y)).as_independent(x)
(1, (x - y)*(x - n1))

– self is anything else:

>>> (sin(x)).as_independent(x)
(1, sin(x))
>>> (sin(x)).as_independent(y)
(sin(x), 1)
>>> exp(x+y).as_independent(x)
(1, exp(x + y))

– force self to be treated as an Add:

>>> (3*x).as_independent(x, as_Add=True)
(0, 3*x)

– force self to be treated as a Mul:

>>> (3+x).as_independent(x, as_Add=False)
(1, x + 3)
>>> (-3+x).as_independent(x, as_Add=False)
(1, x - 3)

Note how the below differs from the above in making the constant on the dep term positive.

>>> (y*(-3+x)).as_independent(x)
(y, x - 3)
– use .as_independent() for true independence testing instead

of .has(). The former considers only symbols in the free symbols while the latter considers all symbols

>>> from sympy import Integral
>>> I = Integral(x, (x, 1, 2))
>>> I.has(x)
True
>>> x in I.free_symbols
False
>>> I.as_independent(x) == (I, 1)
True
>>> (I + x).as_independent(x) == (I, x)
True

Note: when trying to get independent terms, a separation method might need to be used first. In this case, it is important to keep track of what you send to this routine so you know how to interpret the returned values

>>> from sympy import separatevars, log
>>> separatevars(exp(x+y)).as_independent(x)
(exp(y), exp(x))
>>> (x + x*y).as_independent(y)
(x, x*y)
>>> separatevars(x + x*y).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).as_independent(y)
(x, y + 1)
>>> (x*(1 + y)).expand(mul=True).as_independent(y)
(x, x*y)
>>> a, b=symbols('a b', positive=True)
>>> (log(a*b).expand(log=True)).as_independent(b)
(log(a), log(b))

See also

separatevars, expand_log, sympy.core.add.Add.as_two_terms, sympy.core.mul.Mul.as_two_terms, as_coeff_mul

as_leading_term(*symbols, logx=None, cdir=0)[source]

Returns the leading (nonzero) term of the series expansion of self.

The _eval_as_leading_term routines are used to do this, and they must always return a non-zero value.

Examples

>>> from sympy.abc import x
>>> (1 + x + x**2).as_leading_term(x)
1
>>> (1/x**2 + x + x**2).as_leading_term(x)
x**(-2)
as_numer_denom() → tuple[Expr, Expr][source]

Return the numerator and the denominator of an expression.

expression -> a/b -> a, b

This is just a stub that should be defined by an object’s class methods to get anything else.

See also

normal

return a/b instead of (a, b)

as_ordered_factors(order=None)[source]

Return list of ordered factors (if Mul) else [self].

as_ordered_terms(order=None, data=False)[source]

Transform an expression to an ordered list of terms.

Examples

>>> from sympy import sin, cos
>>> from sympy.abc import x
>>> (sin(x)**2*cos(x) + sin(x)**2 + 1).as_ordered_terms()
[sin(x)**2*cos(x), sin(x)**2, 1]
as_poly(*gens, **args)[source]

Converts self to a polynomial or returns None.

Explanation

>>> from sympy import sin
>>> from sympy.abc import x, y
>>> print((x**2 + x*y).as_poly())
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + x*y).as_poly(x, y))
Poly(x**2 + x*y, x, y, domain='ZZ')
>>> print((x**2 + sin(y)).as_poly(x, y))
None
as_powers_dict()[source]

Return self as a dictionary of factors with each factor being treated as a power. The keys are the bases of the factors and the values, the corresponding exponents. The resulting dictionary should be used with caution if the expression is a Mul and contains non- commutative factors since the order that they appeared will be lost in the dictionary.

See also

as_ordered_factors

An alternative for noncommutative applications, returning an ordered list of factors.

args_cnc

Similar to as_ordered_factors, but guarantees separation of commutative and noncommutative factors.

as_real_imag(deep=True, **hints) → tuple[Expr, Expr][source]

Performs complex expansion on ‘self’ and returns a tuple containing collected both real and imaginary parts. This method cannot be confused with re() and im() functions, which does not perform complex expansion at evaluation.

However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function.

>>> from sympy import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag()
(x, y)
>>> from sympy.abc import z, w
>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))
as_terms()[source]

Transform an expression to a list of terms.

aseries(x=None, n=6, bound=0, hir=False)[source]

Asymptotic Series expansion of self. This is equivalent to self.series(x, oo, n).

Parameters:
  • self (Expression) – The expression whose series is to be expanded.

  • x (Symbol) – It is the variable of the expression to be calculated.

  • n (Value) – The value used to represent the order in terms of x**n, up to which the series is to be expanded.

  • hir (Boolean) – Set this parameter to be True to produce hierarchical series. It stops the recursion at an early level and may provide nicer and more useful results.

  • bound (Value, Integer) – Use the bound parameter to give limit on rewriting coefficients in its normalised form.

Examples

>>> from sympy import sin, exp
>>> from sympy.abc import x
>>> e = sin(1/x + exp(-x)) - sin(1/x)
>>> e.aseries(x)
(1/(24*x**4) - 1/(2*x**2) + 1 + O(x**(-6), (x, oo)))*exp(-x)
>>> e.aseries(x, n=3, hir=True)
-exp(-2*x)*sin(1/x)/2 + exp(-x)*cos(1/x) + O(exp(-3*x), (x, oo))
>>> e = exp(exp(x)/(1 - 1/x))
>>> e.aseries(x)
exp(exp(x)/(1 - 1/x))
>>> e.aseries(x, bound=3)
exp(exp(x)/x**2)*exp(exp(x)/x)*exp(-exp(x) + exp(x)/(1 - 1/x) - exp(x)/x - exp(x)/x**2)*exp(exp(x))

For rational expressions this method may return original expression without the Order term. >>> (1/x).aseries(x, n=8) 1/x

Returns:

Asymptotic series expansion of the expression.

Return type:

Expr

Notes

This algorithm is directly induced from the limit computational algorithm provided by Gruntz. It majorly uses the mrv and rewrite sub-routines. The overall idea of this algorithm is first to look for the most rapidly varying subexpression w of a given expression f and then expands f in a series in w. Then same thing is recursively done on the leading coefficient till we get constant coefficients.

If the most rapidly varying subexpression of a given expression f is f itself, the algorithm tries to find a normalised representation of the mrv set and rewrites f using this normalised representation.

If the expansion contains an order term, it will be either O(x ** (-n)) or O(w ** (-n)) where w belongs to the most rapidly varying expression of self.

References

See also

Expr.aseries

See the docstring of this function for complete details of this wrapper.

cancel(*gens, **args)[source]

See the cancel function in sympy.polys

coeff(x: Expr, n=1, right=False, _first=True)[source]

Returns the coefficient from the term(s) containing x**n. If n is zero then all terms independent of x will be returned.

Explanation

When x is noncommutative, the coefficient to the left (default) or right of x can be returned. The keyword ‘right’ is ignored when x is commutative.

Examples

>>> from sympy import symbols
>>> from sympy.abc import x, y, z

You can select terms that have an explicit negative in front of them:

>>> (-x + 2*y).coeff(-1)
x
>>> (x - 2*y).coeff(-1)
2*y

You can select terms with no Rational coefficient:

>>> (x + 2*y).coeff(1)
x
>>> (3 + 2*x + 4*x**2).coeff(1)
0

You can select terms independent of x by making n=0; in this case expr.as_independent(x)[0] is returned (and 0 will be returned instead of None):

>>> (3 + 2*x + 4*x**2).coeff(x, 0)
3
>>> eq = ((x + 1)**3).expand() + 1
>>> eq
x**3 + 3*x**2 + 3*x + 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 2]
>>> eq -= 2
>>> [eq.coeff(x, i) for i in reversed(range(4))]
[1, 3, 3, 0]

You can select terms that have a numerical term in front of them:

>>> (-x - 2*y).coeff(2)
-y
>>> from sympy import sqrt
>>> (x + sqrt(2)*x).coeff(sqrt(2))
x

The matching is exact:

>>> (3 + 2*x + 4*x**2).coeff(x)
2
>>> (3 + 2*x + 4*x**2).coeff(x**2)
4
>>> (3 + 2*x + 4*x**2).coeff(x**3)
0
>>> (z*(x + y)**2).coeff((x + y)**2)
z
>>> (z*(x + y)**2).coeff(x + y)
0

In addition, no factoring is done, so 1 + z*(1 + y) is not obtained from the following:

>>> (x + z*(x + x*y)).coeff(x)
1

If such factoring is desired, factor_terms can be used first:

>>> from sympy import factor_terms
>>> factor_terms(x + z*(x + x*y)).coeff(x)
z*(y + 1) + 1
>>> n, m, o = symbols('n m o', commutative=False)
>>> n.coeff(n)
1
>>> (3*n).coeff(n)
3
>>> (n*m + m*n*m).coeff(n) # = (1 + m)*n*m
1 + m
>>> (n*m + m*n*m).coeff(n, right=True) # = (1 + m)*n*m
m

If there is more than one possible coefficient 0 is returned:

>>> (n*m + m*n).coeff(n)
0

If there is only one possible coefficient, it is returned:

>>> (n*m + x*m*n).coeff(m*n)
x
>>> (n*m + x*m*n).coeff(m*n, right=1)
1

See also

as_coefficient

separate the expression into a coefficient and factor

as_coeff_Add

separate the additive constant from an expression

as_coeff_Mul

separate the multiplicative constant from an expression

as_independent

separate x-dependent terms/factors from others

sympy.polys.polytools.Poly.coeff_monomial

efficiently find the single coefficient of a monomial in Poly

sympy.polys.polytools.Poly.nth

like coeff_monomial but powers of monomial terms are used

collect(syms, func=None, evaluate=True, exact=False, distribute_order_term=True)[source]

See the collect function in sympy.simplify

combsimp()[source]

See the combsimp function in sympy.simplify

conjugate()[source]

Returns the complex conjugate of ‘self’.

could_extract_minus_sign() → bool[source]

Return True if self has -1 as a leading factor or has more literal negative signs than positive signs in a sum, otherwise False.

Examples

>>> from sympy.abc import x, y
>>> e = x - y
>>> {i.could_extract_minus_sign() for i in (e, -e)}
{False, True}

Though the y - x is considered like -(x - y), since it is in a product without a leading factor of -1, the result is false below:

>>> (x*(y - x)).could_extract_minus_sign()
False

To put something in canonical form wrt to sign, use signsimp:

>>> from sympy import signsimp
>>> signsimp(x*(y - x))
-x*(x - y)
>>> _.could_extract_minus_sign()
True
count_ops(visual=False)[source]

Wrapper for count_ops that returns the operation count.

default_assumptions: ClassVar[StdFactKB] = {}
diff(*symbols, **assumptions)[source]
dir(x, cdir)[source]
equals(other, failing_expression=False)[source]

Return True if self == other, False if it does not, or None. If failing_expression is True then the expression which did not simplify to a 0 will be returned instead of None.

Explanation

If self is a Number (or complex number) that is not zero, then the result is False.

If self is a number and has not evaluated to zero, evalf will be used to test whether the expression evaluates to zero. If it does so and the result has significance (i.e. the precision is either -1, for a Rational result, or is greater than 1) then the evalf value will be used to return True or False.

expand(deep=True, modulus=None, power_base=True, power_exp=True, mul=True, log=True, multinomial=True, basic=True, **hints)[source]

Expand an expression using hints.

See the docstring of the expand() function in sympy.core.function for more information.

property expr_free_symbols

Like free_symbols, but returns the free symbols only if they are contained in an expression node.

Examples

>>> from sympy.abc import x, y
>>> (x + y).expr_free_symbols
{x, y}

If the expression is contained in a non-expression object, do not return the free symbols. Compare:

>>> from sympy import Tuple
>>> t = Tuple(x + y)
>>> t.expr_free_symbols
set()
>>> t.free_symbols
{x, y}
extract_additively(c)[source]

Return self - c if it’s possible to subtract c from self and make all matching coefficients move towards zero, else return None.

Examples

>>> from sympy.abc import x, y
>>> e = 2*x + 3
>>> e.extract_additively(x + 1)
x + 2
>>> e.extract_additively(3*x)
>>> e.extract_additively(4)
>>> (y*(x + 1)).extract_additively(x + 1)
>>> ((x + 1)*(x + 2*y + 1) + 3).extract_additively(x + 1)
(x + 1)*(x + 2*y) + 3
extract_branch_factor(allow_half=False)[source]

Try to write self as exp_polar(2*pi*I*n)*z in a nice way. Return (z, n).

>>> from sympy import exp_polar, I, pi
>>> from sympy.abc import x, y
>>> exp_polar(I*pi).extract_branch_factor()
(exp_polar(I*pi), 0)
>>> exp_polar(2*I*pi).extract_branch_factor()
(1, 1)
>>> exp_polar(-pi*I).extract_branch_factor()
(exp_polar(I*pi), -1)
>>> exp_polar(3*pi*I + x).extract_branch_factor()
(exp_polar(x + I*pi), 1)
>>> (y*exp_polar(-5*pi*I)*exp_polar(3*pi*I + 2*pi*x)).extract_branch_factor()
(y*exp_polar(2*pi*x), -1)
>>> exp_polar(-I*pi/2).extract_branch_factor()
(exp_polar(-I*pi/2), 0)

If allow_half is True, also extract exp_polar(I*pi):

>>> exp_polar(I*pi).extract_branch_factor(allow_half=True)
(1, 1/2)
>>> exp_polar(2*I*pi).extract_branch_factor(allow_half=True)
(1, 1)
>>> exp_polar(3*I*pi).extract_branch_factor(allow_half=True)
(1, 3/2)
>>> exp_polar(-I*pi).extract_branch_factor(allow_half=True)
(1, -1/2)
extract_multiplicatively(c: Expr) → Expr | None[source]

Return None if it’s not possible to make self in the form c * something in a nice way, i.e. preserving the properties of arguments of self.

Examples

>>> from sympy import symbols, Rational
>>> x, y = symbols('x,y', real=True)
>>> ((x*y)**3).extract_multiplicatively(x**2 * y)
x*y**2
>>> ((x*y)**3).extract_multiplicatively(x**4 * y)
>>> (2*x).extract_multiplicatively(2)
x
>>> (2*x).extract_multiplicatively(3)
>>> (Rational(1, 2)*x).extract_multiplicatively(3)
x/6
factor(*gens, **args)[source]

See the factor() function in sympy.polys.polytools

fourier_series(limits=None)[source]

Compute fourier sine/cosine series of self.

See the docstring of the fourier_series() in sympy.series.fourier for more information.

fps(x=None, x0=0, dir=1, hyper=True, order=4, rational=True, full=False)[source]

Compute formal power power series of self.

See the docstring of the fps() function in sympy.series.formal for more information.

gammasimp()[source]

See the gammasimp function in sympy.simplify

getO() → Expr | None[source]

Returns the additive O(..) symbol if there is one, else None.

getn()[source]

Returns the order of the expression.

Explanation

The order is determined either from the O(…) term. If there is no O(…) term, it returns None.

Examples

>>> from sympy import O
>>> from sympy.abc import x
>>> (1 + x + O(x**2)).getn()
2
>>> (1 + x).getn()
integrate(*args, **kwargs)[source]

See the integrate function in sympy.integrals

invert(g, *gens, **args)[source]

Return the multiplicative inverse of self mod g where self (and g) may be symbolic expressions).

See also

sympy.core.intfunc.mod_inverse, sympy.polys.polytools.invert

is_algebraic_expr(*syms)[source]

This tests whether a given expression is algebraic or not, in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form.

This function returns False for expressions that are “algebraic expressions” with symbolic exponents. This is a simple extension to the is_rational_function, including rational exponentiation.

Examples

>>> from sympy import Symbol, sqrt
>>> x = Symbol('x', real=True)
>>> sqrt(1 + x).is_rational_function()
False
>>> sqrt(1 + x).is_algebraic_expr()
True

This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be an algebraic expression to become one.

>>> from sympy import exp, factor
>>> a = sqrt(exp(x)**2 + 2*exp(x) + 1)/(exp(x) + 1)
>>> a.is_algebraic_expr(x)
False
>>> factor(a).is_algebraic_expr()
True

References

is_constant(*wrt, **flags)[source]

Return True if self is constant, False if not, or None if the constancy could not be determined conclusively.

Explanation

If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, a few strategies are tried:

1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if wrt is different than the free symbols.

2) differentiation with respect to variables in ‘wrt’ (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols.

3) finding out zeros of denominator expression with free_symbols. It will not be constant if there are zeros. It gives more negative answers for expression that are not constant.

If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag failing_number is True – in that case the numerical value will be returned.

If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing.

Examples

>>> from sympy import cos, sin, Sum, S, pi
>>> from sympy.abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
True
>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
True
is_meromorphic(x, a)[source]

This tests whether an expression is meromorphic as a function of the given symbol x at the point a.

This method is intended as a quick test that will return None if no decision can be made without simplification or more detailed analysis.

Examples

>>> from sympy import zoo, log, sin, sqrt
>>> from sympy.abc import x
>>> f = 1/x**2 + 1 - 2*x**3
>>> f.is_meromorphic(x, 0)
True
>>> f.is_meromorphic(x, 1)
True
>>> f.is_meromorphic(x, zoo)
True
>>> g = x**log(3)
>>> g.is_meromorphic(x, 0)
False
>>> g.is_meromorphic(x, 1)
True
>>> g.is_meromorphic(x, zoo)
False
>>> h = sin(1/x)*x**2
>>> h.is_meromorphic(x, 0)
False
>>> h.is_meromorphic(x, 1)
True
>>> h.is_meromorphic(x, zoo)
True

Multivalued functions are considered meromorphic when their branches are meromorphic. Thus most functions are meromorphic everywhere except at essential singularities and branch points. In particular, they will be meromorphic also on branch cuts except at their endpoints.

>>> log(x).is_meromorphic(x, -1)
True
>>> log(x).is_meromorphic(x, 0)
False
>>> sqrt(x).is_meromorphic(x, -1)
True
>>> sqrt(x).is_meromorphic(x, 0)
False
property is_number

Returns True if self has no free symbols and no undefined functions (AppliedUndef, to be precise). It will be faster than if not self.free_symbols, however, since is_number will fail as soon as it hits a free symbol or undefined function.

Examples

>>> from sympy import Function, Integral, cos, sin, pi
>>> from sympy.abc import x
>>> f = Function('f')
>>> x.is_number
False
>>> f(1).is_number
False
>>> (2*x).is_number
False
>>> (2 + Integral(2, x)).is_number
False
>>> (2 + Integral(2, (x, 1, 2))).is_number
True

Not all numbers are Numbers in the SymPy sense:

>>> pi.is_number, pi.is_Number
(True, False)

If something is a number it should evaluate to a number with real and imaginary parts that are Numbers; the result may not be comparable, however, since the real and/or imaginary part of the result may not have precision.

>>> cos(1).is_number and cos(1).is_comparable
True
>>> z = cos(1)**2 + sin(1)**2 - 1
>>> z.is_number
True
>>> z.is_comparable
False

See also

sympy.core.basic.Basic.is_comparable

is_polynomial(*syms)[source]

Return True if self is a polynomial in syms and False otherwise.

This checks if self is an exact polynomial in syms. This function returns False for expressions that are “polynomials” with symbolic exponents. Thus, you should be able to apply polynomial algorithms to expressions for which this returns True, and Poly(expr, *syms) should work if and only if expr.is_polynomial(*syms) returns True. The polynomial does not have to be in expanded form. If no symbols are given, all free symbols in the expression will be used.

This is not part of the assumptions system. You cannot do Symbol(‘z’, polynomial=True).

Examples

>>> from sympy import Symbol, Function
>>> x = Symbol('x')
>>> ((x**2 + 1)**4).is_polynomial(x)
True
>>> ((x**2 + 1)**4).is_polynomial()
True
>>> (2**x + 1).is_polynomial(x)
False
>>> (2**x + 1).is_polynomial(2**x)
True
>>> f = Function('f')
>>> (f(x) + 1).is_polynomial(x)
False
>>> (f(x) + 1).is_polynomial(f(x))
True
>>> (1/f(x) + 1).is_polynomial(f(x))
False
>>> n = Symbol('n', nonnegative=True, integer=True)
>>> (x**n + 1).is_polynomial(x)
False

This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a polynomial to become one.

>>> from sympy import sqrt, factor, cancel
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)
>>> a.is_polynomial(y)
False
>>> factor(a)
y + 1
>>> factor(a).is_polynomial(y)
True
>>> b = (y**2 + 2*y + 1)/(y + 1)
>>> b.is_polynomial(y)
False
>>> cancel(b)
y + 1
>>> cancel(b).is_polynomial(y)
True

See also .is_rational_function()

is_rational_function(*syms)[source]

Test whether function is a ratio of two polynomials in the given symbols, syms. When syms is not given, all free symbols will be used. The rational function does not have to be in expanded or in any kind of canonical form.

This function returns False for expressions that are “rational functions” with symbolic exponents. Thus, you should be able to call .as_numer_denom() and apply polynomial algorithms to the result for expressions for which this returns True.

This is not part of the assumptions system. You cannot do Symbol(‘z’, rational_function=True).

Examples

>>> from sympy import Symbol, sin
>>> from sympy.abc import x, y
>>> (x/y).is_rational_function()
True
>>> (x**2).is_rational_function()
True
>>> (x/sin(y)).is_rational_function(y)
False
>>> n = Symbol('n', integer=True)
>>> (x**n + 1).is_rational_function(x)
False

This function does not attempt any nontrivial simplifications that may result in an expression that does not appear to be a rational function to become one.

>>> from sympy import sqrt, factor
>>> y = Symbol('y', positive=True)
>>> a = sqrt(y**2 + 2*y + 1)/y
>>> a.is_rational_function(y)
False
>>> factor(a)
(y + 1)/y
>>> factor(a).is_rational_function(y)
True

See also is_algebraic_expr().

is_scalar = True
leadterm(x, logx=None, cdir=0)[source]

Returns the leading term a*x**b as a tuple (a, b).

Examples

>>> from sympy.abc import x
>>> (1+x+x**2).leadterm(x)
(1, 0)
>>> (1/x**2+x+x**2).leadterm(x)
(1, -2)
limit(x, xlim, dir='+')[source]

Compute limit x->xlim.

lseries(x=None, x0=0, dir='+', logx=None, cdir=0)[source]

Wrapper for series yielding an iterator of the terms of the series.

Note: an infinite series will yield an infinite iterator. The following, for exaxmple, will never terminate. It will just keep printing terms of the sin(x) series:

for term in sin(x).lseries(x):
    print term

The advantage of lseries() over nseries() is that many times you are just interested in the next term in the series (i.e. the first term for example), but you do not know how many you should ask for in nseries() using the “n” parameter.

See also nseries().

normal()[source]

Return the expression as a fraction.

expression -> a/b

See also

as_numer_denom

return (a, b) instead of a/b

nseries(x=None, x0=0, n=6, dir='+', logx=None, cdir=0)[source]

Wrapper to _eval_nseries if assumptions allow, else to series.

If x is given, x0 is 0, dir=’+’, and self has x, then _eval_nseries is called. This calculates “n” terms in the innermost expressions and then builds up the final series just by “cross-multiplying” everything out.

The optional logx parameter can be used to replace any log(x) in the returned series with a symbolic value to avoid evaluating log(x) at 0. A symbol to use in place of log(x) should be provided.

Advantage – it’s fast, because we do not have to determine how many terms we need to calculate in advance.

Disadvantage – you may end up with less terms than you may have expected, but the O(x**n) term appended will always be correct and so the result, though perhaps shorter, will also be correct.

If any of those assumptions is not met, this is treated like a wrapper to series which will try harder to return the correct number of terms.

See also lseries().

Examples

>>> from sympy import sin, log, Symbol
>>> from sympy.abc import x, y
>>> sin(x).nseries(x, 0, 6)
x - x**3/6 + x**5/120 + O(x**6)
>>> log(x+1).nseries(x, 0, 5)
x - x**2/2 + x**3/3 - x**4/4 + O(x**5)

Handling of the logx parameter — in the following example the expansion fails since sin does not have an asymptotic expansion at -oo (the limit of log(x) as x approaches 0):

>>> e = sin(log(x))
>>> e.nseries(x, 0, 6)
Traceback (most recent call last):
...
PoleError: ...
...
>>> logx = Symbol('logx')
>>> e.nseries(x, 0, 6, logx=logx)
sin(logx)

In the following example, the expansion works but only returns self unless the logx parameter is used:

>>> e = x**y
>>> e.nseries(x, 0, 2)
x**y
>>> e.nseries(x, 0, 2, logx=logx)
exp(logx*y)
nsimplify(constants=(), tolerance=None, full=False)[source]

See the nsimplify function in sympy.simplify

powsimp(*args, **kwargs)[source]

See the powsimp function in sympy.simplify

primitive() → tuple[Number, Expr][source]

Return the positive Rational that can be extracted non-recursively from every term of self (i.e., self is treated like an Add). This is like the as_coeff_Mul() method but primitive always extracts a positive Rational (never a negative or a Float).

Examples

>>> from sympy.abc import x
>>> (3*(x + 1)**2).primitive()
(3, (x + 1)**2)
>>> a = (6*x + 2); a.primitive()
(2, 3*x + 1)
>>> b = (x/2 + 3); b.primitive()
(1/2, x + 6)
>>> (a*b).primitive() == (1, a*b)
True
radsimp(**kwargs)[source]

See the radsimp function in sympy.simplify

ratsimp()[source]

See the ratsimp function in sympy.simplify

removeO() → Expr[source]

Removes the additive O(..) symbol if there is one

round(n=None)[source]

Return x rounded to the given decimal place.

If a complex number would results, apply round to the real and imaginary components of the number.

Examples

>>> from sympy import pi, E, I, S, Number
>>> pi.round()
3
>>> pi.round(2)
3.14
>>> (2*pi + E*I).round()
6 + 3*I

The round method has a chopping effect:

>>> (2*pi + I/10).round()
6
>>> (pi/10 + 2*I).round()
2*I
>>> (pi/10 + E*I).round(2)
0.31 + 2.72*I

Notes

The Python round function uses the SymPy round method so it will always return a SymPy number (not a Python float or int):

>>> isinstance(round(S(123), -2), Number)
True
separate(deep=False, force=False)[source]

See the separate function in sympy.simplify

series(x=None, x0=0, n=6, dir='+', logx=None, cdir=0)[source]

Series expansion of “self” around x = x0 yielding either terms of the series one by one (the lazy series given when n=None), else all the terms at once when n != None.

Returns the series expansion of “self” around the point x = x0 with respect to x up to O((x - x0)**n, x, x0) (default n is 6).

If x=None and self is univariate, the univariate symbol will be supplied, otherwise an error will be raised.

Parameters:
  • expr (Expression) – The expression whose series is to be expanded.

  • x (Symbol) – It is the variable of the expression to be calculated.

  • x0 (Value) – The value around which x is calculated. Can be any value from -oo to oo.

  • n (Value) – The value used to represent the order in terms of x**n, up to which the series is to be expanded.

  • dir (String, optional) – The series-expansion can be bi-directional. If dir="+", then (x->x0+). If dir="-", then (x->x0-). For infinite ``x0 (oo or -oo), the dir argument is determined from the direction of the infinity (i.e., dir="-" for oo).

  • logx (optional) – It is used to replace any log(x) in the returned series with a symbolic value rather than evaluating the actual value.

  • cdir (optional) – It stands for complex direction, and indicates the direction from which the expansion needs to be evaluated.

Examples

>>> from sympy import cos, exp, tan
>>> from sympy.abc import x, y
>>> cos(x).series()
1 - x**2/2 + x**4/24 + O(x**6)
>>> cos(x).series(n=4)
1 - x**2/2 + O(x**4)
>>> cos(x).series(x, x0=1, n=2)
cos(1) - (x - 1)*sin(1) + O((x - 1)**2, (x, 1))
>>> e = cos(x + exp(y))
>>> e.series(y, n=2)
cos(x + 1) - y*sin(x + 1) + O(y**2)
>>> e.series(x, n=2)
cos(exp(y)) - x*sin(exp(y)) + O(x**2)

If n=None then a generator of the series terms will be returned.

>>> term=cos(x).series(n=None)
>>> [next(term) for i in range(2)]
[1, -x**2/2]

For dir=+ (default) the series is calculated from the right and for dir=- the series from the left. For smooth functions this flag will not alter the results.

>>> abs(x).series(dir="+")
x
>>> abs(x).series(dir="-")
-x
>>> f = tan(x)
>>> f.series(x, 2, 6, "+")
tan(2) + (1 + tan(2)**2)*(x - 2) + (x - 2)**2*(tan(2)**3 + tan(2)) +
(x - 2)**3*(1/3 + 4*tan(2)**2/3 + tan(2)**4) + (x - 2)**4*(tan(2)**5 +
5*tan(2)**3/3 + 2*tan(2)/3) + (x - 2)**5*(2/15 + 17*tan(2)**2/15 +
2*tan(2)**4 + tan(2)**6) + O((x - 2)**6, (x, 2))
>>> f.series(x, 2, 3, "-")
tan(2) + (2 - x)*(-tan(2)**2 - 1) + (2 - x)**2*(tan(2)**3 + tan(2))
+ O((x - 2)**3, (x, 2))

For rational expressions this method may return original expression without the Order term. >>> (1/x).series(x, n=8) 1/x

Returns:

Expr – Series expansion of the expression about x0

Return type:

Expression

Raises:
  • TypeError – If “n” and “x0” are infinity objects

  • PoleError – If “x0” is an infinity object

sort_key(order=None)[source]

Return a sort key.

Examples

>>> from sympy import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
taylor_term(n, x, *previous_terms)[source]

General method for the taylor term.

This method is slow, because it differentiates n-times. Subclasses can redefine it to make it faster by using the “previous_terms”.

together(*args, **kwargs)[source]

See the together function in sympy.polys

transpose()[source]
trigsimp(**args)[source]

See the trigsimp function in sympy.simplify

class applied_dynamics.core.FrameState(q: MutableDenseMatrix, qd: MutableDenseMatrix)[source]

Pose-independent generalized state for Lagrangian systems.

q: MutableDenseMatrix
qd: MutableDenseMatrix
class applied_dynamics.core.Inertia(m: ~sympy.core.symbol.Symbol | float, I: ~sympy.matrices.dense.MutableDenseMatrix, com_B: ~sympy.matrices.dense.MutableDenseMatrix = <factory>)[source]

Rigid-body mass properties expressed in the body frame.

Parameters:
  • m (Symbol | float) – Mass.

  • I (Matrix (3×3)) – Inertia about the body-frame origin (typically CoM frame).

  • com_B (Vec3, optional) – Center of mass coordinates in the body frame, default 0.

Notes

Parallel-axis shift uses

I_shifted = I + m (||r||² I₃ - r rᵀ)

I: MutableDenseMatrix
com_B: MutableDenseMatrix
m: Symbol | float
parallel_axis(r_BC: MutableDenseMatrix) → Inertia[source]

Return inertia shifted by vector r_BC (body frame).

applied_dynamics.core.Matrix

alias of MutableDenseMatrix

class applied_dynamics.core.Symbol(name, **assumptions)[source]

Symbol class is used to create symbolic variables.

Explanation

Symbolic variables are placeholders for mathematical symbols that can represent numbers, constants, or any other mathematical entities and can be used in mathematical expressions and to perform symbolic computations.

Assumptions:

commutative = True positive = True real = True imaginary = True complex = True complete list of more assumptions- predicates

You can override the default assumptions in the constructor.

Examples

>>> from sympy import Symbol
>>> x = Symbol("x", positive=True)
>>> x.is_positive
True
>>> x.is_negative
False

passing in greek letters:

>>> from sympy import Symbol
>>> alpha = Symbol('alpha')
>>> alpha
α

Trailing digits are automatically treated like subscripts of what precedes them in the name. General format to add subscript to a symbol : <var_name> = Symbol('<symbol_name>_<subscript>')

>>> from sympy import Symbol
>>> alpha_i = Symbol('alpha_i')
>>> alpha_i
αᵢ
param AtomicExpr:

type AtomicExpr:

variable name

param Boolean:

type Boolean:

Assumption with a boolean value(True or False)

as_dummy()[source]

Return the expression with any objects having structurally bound symbols replaced with unique, canonical symbols within the object in which they appear and having only the default assumption for commutativity being True. When applied to a symbol a new symbol having only the same commutativity will be returned.

Examples

>>> from sympy import Integral, Symbol
>>> from sympy.abc import x
>>> r = Symbol('r', real=True)
>>> Integral(r, (r, x)).as_dummy()
Integral(_0, (_0, x))
>>> _.variables[0].is_real is None
True
>>> r.as_dummy()
_r

Notes

Any object that has structurally bound variables should have a property, bound_symbols that returns those symbols appearing in the object.

as_real_imag(deep=True, **hints)[source]

Performs complex expansion on ‘self’ and returns a tuple containing collected both real and imaginary parts. This method cannot be confused with re() and im() functions, which does not perform complex expansion at evaluation.

However it is possible to expand both re() and im() functions and get exactly the same results as with a single call to this function.

>>> from sympy import symbols, I
>>> x, y = symbols('x,y', real=True)
>>> (x + y*I).as_real_imag()
(x, y)
>>> from sympy.abc import z, w
>>> (z + w*I).as_real_imag()
(re(z) - im(w), re(w) + im(z))
as_set()[source]

Rewrites Boolean expression in terms of real sets.

Examples

>>> from sympy import Symbol, Eq, Or, And
>>> x = Symbol('x', real=True)
>>> Eq(x, 0).as_set()
{0}
>>> (x > 0).as_set()
Interval.open(0, oo)
>>> And(-2 < x, x < 2).as_set()
Interval.open(-2, 2)
>>> Or(x < -2, 2 < x).as_set()
Union(Interval.open(-oo, -2), Interval.open(2, oo))
property assumptions0

Return object type assumptions.

For example:

Symbol(‘x’, real=True) Symbol(‘x’, integer=True)

are different objects. In other words, besides Python type (Symbol in this case), the initial assumptions are also forming their typeinfo.

Examples

>>> from sympy import Symbol
>>> from sympy.abc import x
>>> x.assumptions0
{'commutative': True}
>>> x = Symbol("x", positive=True)
>>> x.assumptions0
{'commutative': True, 'complex': True, 'extended_negative': False,
 'extended_nonnegative': True, 'extended_nonpositive': False,
 'extended_nonzero': True, 'extended_positive': True, 'extended_real':
 True, 'finite': True, 'hermitian': True, 'imaginary': False,
 'infinite': False, 'negative': False, 'nonnegative': True,
 'nonpositive': False, 'nonzero': True, 'positive': True, 'real':
 True, 'zero': False}
property binary_symbols

Return from the atoms of self those which are free symbols.

Not all free symbols are Symbol (see examples)

For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method.

Any other method that uses bound variables should implement a free_symbols method.

Examples

>>> from sympy import Derivative, Integral, IndexedBase
>>> from sympy.abc import x, y, n
>>> (x + 1).free_symbols
{x}
>>> Integral(x, y).free_symbols
{x, y}

Not all free symbols are actually symbols:

>>> IndexedBase('F')[0].free_symbols
{F, F[0]}

The symbols of differentiation are not included unless they appear in the expression being differentiated.

>>> Derivative(x + y, y).free_symbols
{x, y}
>>> Derivative(x, y).free_symbols
{x}
>>> Derivative(x, (y, n)).free_symbols
{n, x}

If you want to know if a symbol is in the variables of the Derivative you can do so as follows:

>>> Derivative(x, y).has_free(y)
True
default_assumptions: ClassVar[StdFactKB] = {}
property free_symbols

Return from the atoms of self those which are free symbols.

Not all free symbols are Symbol (see examples)

For most expressions, all symbols are free symbols. For some classes this is not true. e.g. Integrals use Symbols for the dummy variables which are bound variables, so Integral has a method to return all symbols except those. Derivative keeps track of symbols with respect to which it will perform a derivative; those are bound variables, too, so it has its own free_symbols method.

Any other method that uses bound variables should implement a free_symbols method.

Examples

>>> from sympy import Derivative, Integral, IndexedBase
>>> from sympy.abc import x, y, n
>>> (x + 1).free_symbols
{x}
>>> Integral(x, y).free_symbols
{x, y}

Not all free symbols are actually symbols:

>>> IndexedBase('F')[0].free_symbols
{F, F[0]}

The symbols of differentiation are not included unless they appear in the expression being differentiated.

>>> Derivative(x + y, y).free_symbols
{x, y}
>>> Derivative(x, y).free_symbols
{x}
>>> Derivative(x, (y, n)).free_symbols
{n, x}

If you want to know if a symbol is in the variables of the Derivative you can do so as follows:

>>> Derivative(x, y).has_free(y)
True
is_Symbol = True
is_comparable = False
is_constant(*wrt, **flags)[source]

Return True if self is constant, False if not, or None if the constancy could not be determined conclusively.

Explanation

If an expression has no free symbols then it is a constant. If there are free symbols it is possible that the expression is a constant, perhaps (but not necessarily) zero. To test such expressions, a few strategies are tried:

1) numerical evaluation at two random points. If two such evaluations give two different values and the values have a precision greater than 1 then self is not constant. If the evaluations agree or could not be obtained with any precision, no decision is made. The numerical testing is done only if wrt is different than the free symbols.

2) differentiation with respect to variables in ‘wrt’ (or all free symbols if omitted) to see if the expression is constant or not. This will not always lead to an expression that is zero even though an expression is constant (see added test in test_expr.py). If all derivatives are zero then self is constant with respect to the given symbols.

3) finding out zeros of denominator expression with free_symbols. It will not be constant if there are zeros. It gives more negative answers for expression that are not constant.

If neither evaluation nor differentiation can prove the expression is constant, None is returned unless two numerical values happened to be the same and the flag failing_number is True – in that case the numerical value will be returned.

If flag simplify=False is passed, self will not be simplified; the default is True since self should be simplified before testing.

Examples

>>> from sympy import cos, sin, Sum, S, pi
>>> from sympy.abc import a, n, x, y
>>> x.is_constant()
False
>>> S(2).is_constant()
True
>>> Sum(x, (x, 1, 10)).is_constant()
True
>>> Sum(x, (x, 1, n)).is_constant()
False
>>> Sum(x, (x, 1, n)).is_constant(y)
True
>>> Sum(x, (x, 1, n)).is_constant(n)
False
>>> Sum(x, (x, 1, n)).is_constant(x)
True
>>> eq = a*cos(x)**2 + a*sin(x)**2 - a
>>> eq.is_constant()
True
>>> eq.subs({x: pi, a: 2}) == eq.subs({x: pi, a: 3}) == 0
True
>>> (0**x).is_constant()
False
>>> x.is_constant()
False
>>> (x**x).is_constant()
False
>>> one = cos(x)**2 + sin(x)**2
>>> one.is_constant()
True
>>> ((one - 1)**(x + 1)).is_constant() in (True, False) # could be 0 or 1
True
is_symbol = True
property kind

Default kind for all SymPy object. If the kind is not defined for the object, or if the object cannot infer the kind from its arguments, this will be returned.

Examples

>>> from sympy import Expr
>>> Expr().kind
UndefinedKind
name: str
sort_key(order=None)[source]

Return a sort key.

Examples

>>> from sympy import S, I
>>> sorted([S(1)/2, I, -I], key=lambda x: x.sort_key())
[1/2, -I, I]
>>> S("[x, 1/x, 1/x**2, x**2, x**(1/2), x**(1/4), x**(3/2)]")
[x, 1/x, x**(-2), x**2, sqrt(x), x**(1/4), x**(3/2)]
>>> sorted(_, key=lambda x: x.sort_key())
[x**(-2), 1/x, x**(1/4), sqrt(x), x, x**(3/2), x**2]
class applied_dynamics.core.System[source]

Minimal abstract base class for systems amenable to Lagrange’s equations.

Subclasses must implement:
  • energy(self) -> Energy

  • generalized_forces(self, fs) -> Matrix

  • lagrangian_state(self) -> (q, qd, t)

The helpers lagrangian(), mass_matrix(), and equations_of_motion() are provided here and use applied_dynamics.dynamics (lazy-imported).

abstractmethod energy() → Energy[source]
equations_of_motion() → MutableDenseMatrix[source]
Return the Euler–Lagrange equations (left-hand side), i.e.,

d/dt(∂L/∂q̇) − ∂L/∂q − Q = 0

so the resulting vector equals 0 at dynamics satisfaction.

Uses applied_dynamics.dynamics.LagrangeEngine.

abstractmethod generalized_forces(fs: FrameState) → MutableDenseMatrix[source]
lagrangian() → Expr[source]

Compute L = K - V from the model’s Energy (symbolic).

abstractmethod lagrangian_state() → Tuple[MutableDenseMatrix, MutableDenseMatrix, Symbol][source]
Returns:

  • q (Matrix) – Column of generalized coordinates, e.g. Matrix([θ(t), φ(t), …]).

  • qd (Matrix) – Column of generalized velocities, e.g. Matrix([θ̇(t), φ̇(t), …]).

  • t (Symbol) – Time symbol used by the system (typically sp.symbols('t')).

mass_matrix() → MutableDenseMatrix[source]

Return the mass matrix M(q) = ∂²K/∂q̇∂q̇ᵀ.

applied_dynamics.core.as_column(x) → MutableDenseMatrix[source]

Return x as a SymPy column Matrix.

Symbolic dynamics helpers for the applied_dynamics module.

What’s inside

  • LagrangeEngine
    • equations_of_motion(q_funcs, t, K, V, Q=None, R=None)

      → Euler–Lagrange with optional Rayleigh dissipation.

    • linearize_mqb(eoms, q_funcs, t)

      → factor EOMs as M(q) qdd + b(q, qd) = 0 (LHS form).

  • mass_matrix_from_lagrangian(K, qd)

    → symmetric Hessian wrt q̇

  • NewtonEuler

    → small helpers for momenta & cross ops (optional use)

Design goals

  • Pure SymPy (no external dependencies).

  • No circular imports to models or app code.

  • Keep equations left-hand side = 0 for testability and composition.

class applied_dynamics.dynamics.LagrangeEngine(use_rayleigh: bool = True)[source]

Generic Euler–Lagrange equations generator.

The returned EOM vector is the left-hand side:

E(q, q̇, q̈, t) = d/dt(∂L/∂q̇) − ∂L/∂q + ∂R/∂q̇ − Q = 0

where R(q̇) is the Rayleigh dissipation (optional) and Q are generalized non-conservative forces (column vector).

equations_of_motion(q_funcs: Sequence[Function], t: Symbol, K: Expr, V: Expr, Q: MutableDenseMatrix | None = None, R: Expr | None = None) → MutableDenseMatrix[source]

Compute Euler–Lagrange equations for a set of generalized coordinates.

Parameters:
  • q_funcs (sequence of sympy.Function) – Constructors for q_i (e.g., Function(‘theta’)).

  • t (Symbol) – Time symbol.

  • K (Expr) – Kinetic and potential energy.

  • V (Expr) – Kinetic and potential energy.

  • Q (Matrix, optional) – Generalized non-conservative forces column vector.

  • R (Expr, optional) – Rayleigh dissipation function R(q̇). If provided (and use_rayleigh), contributes +∂R/∂q̇ on the LHS (so physical damping is -∂R/∂q̇ on the RHS).

Returns:

Column vector of EOM left-hand sides (equals zero at satisfaction).

Return type:

Matrix

linearize_mqb(eoms: MutableDenseMatrix, q_funcs: Sequence[Function], t: Symbol) → Tuple[MutableDenseMatrix, MutableDenseMatrix, List[Symbol]][source]
Factor left-hand side equations as:

M(q) q̈ + b(q, q̇) = 0

This is done by replacing q(t), q̇(t), q̈(t) with algebraic symbols, extracting coefficients of q̈, and putting the remainder in b.

Returns:

  • M : (n×n) mass matrix (symbolic)

  • b : (n×1) symbolic remainder so that M*qdd + b = 0

  • qdd_symbols : the algebraic symbols used for q̈ (for later substitution)

Return type:

(M, b, qdd_symbols)

use_rayleigh: bool = True
class applied_dynamics.dynamics.NewtonEuler[source]

Small helpers for momentum & cross-ops.

angular_momentum_com(I_C: MutableDenseMatrix, omega: MutableDenseMatrix) → MutableDenseMatrix[source]

H_C = I_C ω

static cross_mat(v: MutableDenseMatrix) → MutableDenseMatrix[source]

Skew-symmetric cross product matrix [v]^ such that [v]^ w = v × w.

linear_momentum(m: Symbol | float, v: MutableDenseMatrix) → MutableDenseMatrix[source]

p = m v

resultant_force(p: MutableDenseMatrix, t: Symbol) → MutableDenseMatrix[source]

F = d/dt p

resultant_moment_about(H_P: MutableDenseMatrix, t: Symbol) → MutableDenseMatrix[source]

M_P = d/dt H_P

shift_angular_momentum(H_C: MutableDenseMatrix, r_PC: MutableDenseMatrix, p: MutableDenseMatrix) → MutableDenseMatrix[source]

Shift angular_velocity momentum from CoM to point P: H_P = H_C + r_PC × p.

applied_dynamics.dynamics.mass_matrix_from_lagrangian(K: Expr, qd: Sequence[Expr]) → MutableDenseMatrix[source]
Extract the mass matrix M(q) from a quadratic kinetic energy:

K(q, q̇) ≈ 1/2 q̇ᵀ M(q) q̇

via Hessian wrt q̇, symmetrized for robustness.

class applied_dynamics.models.CartPendulumAbsorber(M: Symbol, m: Symbol, l: Symbol, k: Symbol, g: Symbol)[source]

Vibration absorber: cart of mass M with a pendulum bob (m, l) and spring k. Generalized coordinates: (x, θ)

M: Symbol
g: Symbol
k: Symbol
kinetic(fs: FrameState) → Expr[source]
l: Symbol
lagrangian_state() → Tuple[MutableDenseMatrix, MutableDenseMatrix, Symbol][source]
Returns:

  • q (Matrix) – Column of generalized coordinates, e.g. Matrix([θ(t), φ(t), …]).

  • qd (Matrix) – Column of generalized velocities, e.g. Matrix([θ̇(t), φ̇(t), …]).

  • t (Symbol) – Time symbol used by the system (typically sp.symbols('t')).

m: Symbol
potential(fs: FrameState) → Expr[source]
th

alias of theta

class x(*args)
default_assumptions: ClassVar[StdFactKB] = {}
name: str = 'x'
class applied_dynamics.models.EMParticle(m: Symbol, e: Symbol)[source]

Charged particle in an electromagnetic field (10.388–10.392):

L = 1/2 m ||v||^2 - e φ(t, x, y, z) + e v·A(t, x, y, z)

Coordinates: q = (x, y, z)

class A1(*args)
default_assumptions: ClassVar[StdFactKB] = {}
name: str = 'A1'
class A2(*args)
default_assumptions: ClassVar[StdFactKB] = {}
name: str = 'A2'
class A3(*args)
default_assumptions: ClassVar[StdFactKB] = {}
name: str = 'A3'
class Phi(*args)
default_assumptions: ClassVar[StdFactKB] = {}
name: str = 'Phi'
e: Symbol
kinetic(fs: FrameState) → Expr[source]
lagrangian(q: List[float] | MutableDenseMatrix | None = None, qd: List[float] | MutableDenseMatrix | None = None) → Expr | float[source]

Return L = K - V (symbolic). If q and qd are provided, return a float after substitution.

lagrangian_state() → Tuple[MutableDenseMatrix, MutableDenseMatrix, Symbol][source]
Returns:

  • q (Matrix) – Column of generalized coordinates, e.g. Matrix([θ(t), φ(t), …]).

  • qd (Matrix) – Column of generalized velocities, e.g. Matrix([θ̇(t), φ̇(t), …]).

  • t (Symbol) – Time symbol used by the system (typically sp.symbols('t')).

m: Symbol
potential(fs: FrameState) → Expr[source]
class x(*args)
default_assumptions: ClassVar[StdFactKB] = {}
name: str = 'x'
class y(*args)
default_assumptions: ClassVar[StdFactKB] = {}
name: str = 'y'
class z(*args)
default_assumptions: ClassVar[StdFactKB] = {}
name: str = 'z'
class applied_dynamics.models.ModelBase(*args, **kwargs)[source]
Mixin that provides:
  • properties q, qd, dof

  • lagrangian(q=None, qd=None): K - V (numeric if q/qd given)

  • energy(q=None, qd=None): {“K”: K, “V”: V}

  • equations_of_motion(q=None, qd=None):
    • symbolic if no args

    • numeric array if q/qd given (with d2q/dt2 → 0)

Models implement:
  • lagrangian_state() -> (q_vec, qd_vec, t)

  • kinetic(fs) and potential(fs)

  • generalized_forces(fs) (default: zeros)

property dof: int
energy(q: List[float] | MutableDenseMatrix | None = None, qd: List[float] | MutableDenseMatrix | None = None) → Dict[str, Expr | float][source]

Return {“K”: K, “V”: V}. If q and qd are provided, numerically substitute.

equations_of_motion(q: List[float] | MutableDenseMatrix | None = None, qd: List[float] | MutableDenseMatrix | None = None)[source]

Build Lagrange EOMs.

Returns:

  • - If q, qd are None (sp.Matrix (symbolic column))

  • - If q, qd are provided (np.ndarray, 1-D numeric vector with d2q/dt2 set to 0.)

generalized_forces(fs: FrameState) → MutableDenseMatrix[source]
lagrangian(q: List[float] | MutableDenseMatrix | None = None, qd: List[float] | MutableDenseMatrix | None = None) → Expr | float[source]

Return L = K - V (symbolic). If q and qd are provided, return a float after substitution.

property q: MutableDenseMatrix
property qd: MutableDenseMatrix
class applied_dynamics.models.Planar2R(m1: Symbol, m2: Symbol, l1: Symbol, l2: Symbol, g: Symbol)[source]

Planar 2R manipulator with point masses at link ends (compact textbook form). Generalized coordinates: (θ1, θ2)

g: Symbol
kinetic(fs: FrameState) → Expr[source]
l1: Symbol
l2: Symbol
lagrangian_state() → Tuple[MutableDenseMatrix, MutableDenseMatrix, Symbol][source]
Returns:

  • q (Matrix) – Column of generalized coordinates, e.g. Matrix([θ(t), φ(t), …]).

  • qd (Matrix) – Column of generalized velocities, e.g. Matrix([θ̇(t), φ̇(t), …]).

  • t (Symbol) – Time symbol used by the system (typically sp.symbols('t')).

m1: Symbol
m2: Symbol
potential(fs: FrameState) → Expr[source]
th1

alias of theta1

th2

alias of theta2

class applied_dynamics.models.SimplePendulum(m: Symbol, l: Symbol, g: Symbol)[source]

Simple pendulum with angle θ about pivot; bob mass at distance l.

g: Symbol
kinetic(fs: FrameState) → Expr[source]
l: Symbol
lagrangian_state() → Tuple[MutableDenseMatrix, MutableDenseMatrix, Symbol][source]
Returns:

  • q (Matrix) – Column of generalized coordinates, e.g. Matrix([θ(t), φ(t), …]).

  • qd (Matrix) – Column of generalized velocities, e.g. Matrix([θ̇(t), φ̇(t), …]).

  • t (Symbol) – Time symbol used by the system (typically sp.symbols('t')).

m: Symbol
potential(fs: FrameState) → Expr[source]
th

alias of theta

class applied_dynamics.models.SphericalPendulum(m: Symbol, l: Symbol, g: Symbol)[source]

Spherical pendulum with angles (θ, φ) and constant rod length l.

g: Symbol
kinetic(fs: FrameState) → Expr[source]
l: Symbol
lagrangian_state() → Tuple[MutableDenseMatrix, MutableDenseMatrix, Symbol][source]
Returns:

  • q (Matrix) – Column of generalized coordinates, e.g. Matrix([θ(t), φ(t), …]).

  • qd (Matrix) – Column of generalized velocities, e.g. Matrix([θ̇(t), φ̇(t), …]).

  • t (Symbol) – Time symbol used by the system (typically sp.symbols('t')).

m: Symbol
ph

alias of phi

potential(fs: FrameState) → Expr[source]
th

alias of theta

class applied_dynamics.models.Trebuchet(m1: Symbol, m2: Symbol, a: Symbol, b: Symbol, l: Symbol, g: Symbol)[source]

Minimal planar trebuchet (per 10.342–10.346 simplification):

q = (θ, α, y)

θ : main arm angle wrt +x (counterclockwise) α : secondary arm (sling) relative angle y : vertical slider offset for projectile (positive up)

a: Symbol
al

alias of alpha

b: Symbol
g: Symbol
kinetic(fs: FrameState) → Expr[source]
l: Symbol
lagrangian_state() → Tuple[MutableDenseMatrix, MutableDenseMatrix, Symbol][source]
Returns:

  • q (Matrix) – Column of generalized coordinates, e.g. Matrix([θ(t), φ(t), …]).

  • qd (Matrix) – Column of generalized velocities, e.g. Matrix([θ̇(t), φ̇(t), …]).

  • t (Symbol) – Time symbol used by the system (typically sp.symbols('t')).

m1: Symbol
m2: Symbol
potential(fs: FrameState) → Expr[source]
th

alias of theta

class y(*args)
default_assumptions: ClassVar[StdFactKB] = {}
name: str = 'y'
class applied_dynamics.models.VehicleOnEarth(m: Symbol, R: Symbol)[source]

Point-mass constrained to a spherical Earth of radius R (constant altitude).

Coordinates: q = (λ, φ) [latitude λ, longitude φ] Kinetic energy (standard spherical metric):

K = 1/2 m R^2 ( λ̇^2 + (cos λ)^2 φ̇^2 )

Potential: constant (set V = 0).

R: Symbol
kinetic(fs: FrameState) → Expr[source]
la

alias of lat

lagrangian_state() → Tuple[MutableDenseMatrix, MutableDenseMatrix, Symbol][source]
Returns:

  • q (Matrix) – Column of generalized coordinates, e.g. Matrix([θ(t), φ(t), …]).

  • qd (Matrix) – Column of generalized velocities, e.g. Matrix([θ̇(t), φ̇(t), …]).

  • t (Symbol) – Time symbol used by the system (typically sp.symbols('t')).

lo

alias of lon

m: Symbol
potential(fs: FrameState) → Expr[source]

I/O, schema, and builders for applied_dynamics-dynamics problems.

Two common actions are supported at the file level:

  1. Derive (symbolic): {

    “action”: “derive”, “model”: “simple_pendulum” | “spherical_pendulum” | “planar2r” | “cart_absorber”, “params”: { … model-specific symbolic/numeric parameters … }

    }

  2. Simulate (numeric integration): {

    “action”: “simulate”, “model”: “<same as above>”, “params”: { … numeric parameters … }, “t_span”: [t0, tf], “x0”: [initial_state…], “options”: { “method”: “RK45”, “rtol”: 1e-6, “atol”: 1e-9, “max_step”: null }

    }

Features

  • JSON and YAML input (auto-detected by extension).

  • JSON Schema validation for model specs and derive/simulate requests.

  • Builders for applied_dynamics.core.System via applied_dynamics.design.DesignLibrary.

  • Helpers to save/load problem payloads and results.

Examples

Derive (Planar 2R, symbolic): {

“action”: “derive”, “model”: “planar2r”, “params”: {“m1”: “m1”, “m2”: “m2”, “l1”: “l1”, “l2”: “l2”, “g”: “g”}

}

Simulate (Simple pendulum, numeric): {

“action”: “simulate”, “model”: “simple_pendulum”, “params”: {“m”: 1.0, “l”: 1.0, “g”: 9.81}, “t_span”: [0.0, 10.0], “x0”: [0.2, 0.0], # [theta, theta_dot] “options”: {“method”: “RK45”, “rtol”: 1e-6, “atol”: 1e-9}

}

applied_dynamics.io.build_system_from_model(model: str, params: Mapping[str, Any]) → System[source]

Build a applied_dynamics.core.System via applied_dynamics.design.DesignLibrary.

applied_dynamics.io.derive_schema() → Dict[str, Any][source]

Schema for derive (symbolic) requests.

applied_dynamics.io.is_derive(payload: Mapping[str, Any]) → bool[source]
applied_dynamics.io.is_simulate(payload: Mapping[str, Any]) → bool[source]
applied_dynamics.io.load_json_or_yaml(path: str | Path) → Dict[str, Any][source]

Load dict from a JSON or YAML file based on extension.

applied_dynamics.io.load_problem_from_file(path: str | Path, *, validate: bool = True) → Dict[str, Any][source]

Load an applied_dynamics-dynamics problem (derive or simulate) from JSON/YAML.

applied_dynamics.io.model_schema() → Dict[str, Any][source]

Schema for high-level applied_dynamics-dynamics model specs. We accept numerics or symbol-names (strings) for parameters.

applied_dynamics.io.pick_action(payload: Mapping[str, Any]) → str[source]
applied_dynamics.io.problem_schema() → Dict[str, Any][source]

Top-level schema: either a derive or simulate request.

applied_dynamics.io.save_derivation_json(path: str | Path, result: Mapping[str, Any]) → None[source]

Save a symbolic derivation result as JSON (stringified SymPy is fine).

applied_dynamics.io.save_problem_json(path: str | Path, payload: Mapping[str, Any]) → None[source]

Save a derive/simulate payload to JSON (no validation enforced here).

applied_dynamics.io.save_simulation_json(path: str | Path, t: Sequence[float], x: Sequence[Sequence[float]], **meta: Any) → None[source]

Save a numeric solution (t, x) to JSON, with optional metadata (events, options…).

applied_dynamics.io.simulate_schema() → Dict[str, Any][source]

Schema for simulate (numeric integration) requests.

applied_dynamics.io.validate_derive_payload(payload: Mapping[str, Any]) → None[source]
applied_dynamics.io.validate_model(model: str, params: Mapping[str, Any]) → None[source]
applied_dynamics.io.validate_problem(problem: Mapping[str, Any]) → None[source]
applied_dynamics.io.validate_simulate_payload(payload: Mapping[str, Any]) → None[source]

Utility decorators, math helpers, and path_planning constants for applied_dynamics dynamics.

Highlights

  • Decorators:
    • timed(fn) → records fn runtime on wrapper.last_runtime

    • ensure_shape(*shape) → validate ndarray shape

    • ensure_sympy_shape(r, c) → validate sympy Matrix shape

    • timeit(fn) → back-compat: returns (result, dt)

  • Numeric helpers:
    • TOL, almost_equal(a, b), clamp(x, lo, hi), normalize(v)

  • Lie/SE(3) helpers commonly used across dynamics sims:
    • skew(v), vex(S), homogeneous(R, t)

  • Paths & I/O helpers:
    • APPLIED_ROOT, IN_DIR, OUT_DIR

    • ensure_outfile(path_planning)

    • Result dataclass (light result carrier)

class applied_dynamics.utils.Result(name: str, data: Dict[str, Any], notes: str = '')[source]

Lightweight result carrier for computations.

data: Dict[str, Any]
name: str
notes: str = ''
applied_dynamics.utils.TOL: float = 1e-09

Default absolute tolerance for numerical comparisons.

applied_dynamics.utils.almost_equal(a: Sequence[float] | ndarray, b: Sequence[float] | ndarray, *, atol: float = 1e-09, rtol: float = 1e-09) → bool[source]

Elementwise closeness for arrays.

applied_dynamics.utils.clamp(x: float, lo: float, hi: float) → float[source]

Clamp a scalar to [lo, hi].

applied_dynamics.utils.ensure_outfile(path: Path) → Path[source]

Ensure parent directory exists and return the path_planning.

applied_dynamics.utils.ensure_shape(*shape: int) → Callable[[Callable[[...], ndarray]], Callable[[...], ndarray]][source]

Validate the ndarray shape of the return value.

Parameters:

shape (tuple[int]) – Expected shape, e.g., (6,) or (4, 4).

applied_dynamics.utils.ensure_sympy_shape(rows: int, cols: int) → Callable[[Callable[[...], MutableDenseMatrix]], Callable[[...], MutableDenseMatrix]][source]

Validate the SymPy Matrix shape of the return value.

Examples

>>> @ensure_sympy_shape(2, 1)
... def f(): return sp.Matrix([1, 2])
applied_dynamics.utils.homogeneous(R: ndarray, t: Sequence[float] | ndarray) → ndarray[source]

Compose a 4×4 homogeneous transform from (R, t).

applied_dynamics.utils.normalize(v: Sequence[float] | ndarray, eps: float = 1e-12) → ndarray[source]

Return a unit-length copy of vector v; if ||v|| < eps, returns v unchanged.

applied_dynamics.utils.skew(v: Sequence[float] | ndarray) → ndarray[source]

Skew-symmetric matrix [v]^ of a 3-vector.

applied_dynamics.utils.timed(fn: Callable[[...], T]) → Callable[[...], T][source]

Measure wall-clock runtime of fn.

The wrapper exposes a float attribute last_runtime with the duration.

Examples

>>> @timed
... def f(x): return x**2
>>> _ = f(3)
>>> f.last_runtime >= 0.0
True
applied_dynamics.utils.timeit(fn: Callable[[...], T]) → Callable[[...], Tuple[T, float]][source]

Back-compat decorator matching the old API: returns (result, dt).

Prefer timed() for new code; keep this to avoid breaking callers.

applied_dynamics.utils.vex(S: ndarray) → ndarray[source]

Vee operator (inverse_kinematics of skew). Extract vector from a 3×3 skew-symmetric matrix.

Class diagram generator for the applied_dynamics dynamics module.

Parity with inverse_kinematics.tools.diagram: - OOP façade: DiagramTool + DiagramConfig - Backends: DOT (Graphviz) text, PlantUML text, optional python-graphviz render - JSON model export - Themed styles (light/dark), package clustering, legend, rank direction - Back-compat helpers: render_dot() and render_puml() for simple imports - CLI: python -m applied_dynamics.tools.diagram <dot|plantuml|graphviz|json|all> …

Typical usage

# Text artifacts python -m applied_dynamics.tools.diagram dot –out applied_dynamics/out/classes.dot python -m applied_dynamics.tools.diagram plantuml –out applied_dynamics/out/classes.puml

# Render via python-graphviz (no ‘dot’ binary needed) python -m applied_dynamics.tools.diagram graphviz –fmt png –dpi 260 –outstem classes

# All artifacts (JSON + DOT + PUML + tries graphviz) python -m applied_dynamics.tools.diagram all

class applied_dynamics.tools.diagram.DiagramConfig(packages: 'Tuple[str, ...]' = ('applied_dynamics.core', 'applied_dynamics.dynamics', 'applied_dynamics.models', 'applied_dynamics.io', 'applied_dynamics.utils', 'applied_dynamics.app', 'applied_dynamics.apis', 'applied_dynamics.tools'), out_dir: 'Path' = PosixPath('applied_dynamics/out'), theme: 'str' = 'light', rankdir: 'str' = 'LR', cluster_by_module: 'bool' = True, add_legend: 'bool' = False)[source]
add_legend: bool = False
cluster_by_module: bool = True
out_dir: Path = PosixPath('applied_dynamics/out')
packages: Tuple[str, ...] = ('applied_dynamics.core', 'applied_dynamics.dynamics', 'applied_dynamics.models', 'applied_dynamics.io', 'applied_dynamics.utils', 'applied_dynamics.app', 'applied_dynamics.apis', 'applied_dynamics.tools')
rankdir: str = 'LR'
theme: str = 'light'
class applied_dynamics.tools.diagram.DiagramTool(config: DiagramConfig | None = None)[source]

Façade for class diagrams of the applied_dynamics package.

discover() → Model[source]
emit_dot(*, out_file: str | None = None) → str[source]
emit_plantuml(*, out_file: str | None = None) → str[source]
export_model_json(*, out_file: str = 'classes.json') → str[source]
render_all() → Dict[str, str][source]
render_graphviz(*, fmt: str = 'png', dpi: int = 220, out_stem: str = 'classes', engine: str = 'dot') → str[source]
applied_dynamics.tools.diagram.render_dot(packages: Sequence[str] = ('applied_dynamics.core', 'applied_dynamics.dynamics', 'applied_dynamics.models', 'applied_dynamics.io', 'applied_dynamics.utils', 'applied_dynamics.app', 'applied_dynamics.apis', 'applied_dynamics.tools'), *, theme: str = 'light', rankdir: str = 'LR', cluster_by_module: bool = True, add_legend: bool = False) → str[source]
applied_dynamics.tools.diagram.render_puml(packages: Sequence[str] = ('applied_dynamics.core', 'applied_dynamics.dynamics', 'applied_dynamics.models', 'applied_dynamics.io', 'applied_dynamics.utils', 'applied_dynamics.app', 'applied_dynamics.apis', 'applied_dynamics.tools'), *, theme: str = 'light', cluster_by_module: bool = True, add_legend: bool = False) → str[source]

Python APIs for the applied_dynamics dynamics package.

Layers

  1. AppliedDynamicsAPI — test-oriented façade exposing quick symbolic derivations. Returns applied_dynamics.utils.Result payloads, keeping a single LagrangeEngine.

  2. AppliedService — optional, app-oriented façade mirroring the inverse_kinematics module style. Useful for batch runs, file I/O helpers, and diagram generation without tying to a web framework.

Design notes

  • Avoid circular imports by importing AppliedApp only inside methods that use it.

  • Keep return shapes stable for tests (Result objects with fields like EOM/K/V/M).

class applied_dynamics.apis.AppliedDynamicsAPI(engine: ~applied_dynamics.dynamics.LagrangeEngine = <factory>)[source]

Lightweight façade used by tests to run quick symbolic derivations.

Methods return Result(name, data) where data typically includes:
  • “EOM”: sympy Matrix (Euler–Lagrange equations, left-hand side)

  • “K”: kinetic energy (Expr)

  • “V”: potential energy (Expr)

  • “M”: mass matrix M(q) when relevant

derive_cart_absorber() → Result[source]
derive_planar_2r() → Result[source]
derive_simple_pendulum() → Result[source]
derive_spherical_pendulum() → Result[source]
engine: LagrangeEngine
class applied_dynamics.apis.AppliedService[source]

Higher-level façade around AppliedApp. Not required by current tests, but useful for parity with the inverse_kinematics module’s service and for scripting.

run_all() → List[Result][source]

Run the app’s bundled derivations and return their results in-memory.

save_result_json(name: str, payload: Dict[str, Any], out_dir: Path | None = None) → str[source]

Save a dict payload as JSON under applied_dynamics/out (or a custom out_dir). Returns the full path_planning as a string.