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
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
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.
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)
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)
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.
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 match2>>> p=Poly(2*E+x*E);pPoly(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.)
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.
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).
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)
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
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
>>> fromsympyimportseparatevars,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))
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.
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.
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.
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.
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.
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.
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.
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.
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.
>>> (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 1True
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.
Returns True if self has no free symbols and no
undefined functions (AppliedUndef, to be precise). It will be
faster than ifnotself.free_symbols, however, since
is_number will fail as soon as it hits a free symbol
or undefined function.
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.
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).
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).
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.
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:
forterminsin(x).lseries(x):printterm
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.
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.
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):
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).
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-).Forinfinite``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.
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.
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.
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>')
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.
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.
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.
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.
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.
>>> (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 1True
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.
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).
AppliedDynamicsAPI — test-oriented façade exposing quick symbolic derivations.
Returns applied_dynamics.utils.Result payloads, keeping a single LagrangeEngine.
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.
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.