pydy API Reference
Python Dynamics toolkit for multi-body dynamic modeling, simulation, and visualization built on SymPy.
pydy.system.PyDyFutureWarning
Python Library Documentation: class PyDyFutureWarning in module pydy.utils class PyDyFutureWarning(builtins.FutureWarning) | Method resolution order: | PyDyFutureWarning | builtins.FutureWarning | builtins.Warning | builtins.Exception | builtins.BaseException | builtins.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object | | ---------------------------------------------------------------------- | Methods inherited from builtins.FutureWarning: | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | ---------------------------------------------------------------------- | Static methods inherited from builtins.FutureWarning: | | __new__(*args, **kwargs) class method of builtins.FutureWarning | Create and return a new object. See help(type) for accurate signature. | | ---------------------------------------------------------------------- | Methods inherited from builtins.BaseException: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __reduce__(...) | Helper for pickle. | | __repr__(self, /) | Return repr(self). | | __setstate__(...) | | __str__(self, /) | Return str(self). | | add_note(...) | Exception.add_note(note) -- | add a note to the exception | | with_traceback(...) | Exception.with_traceback(tb) -- | set self.__traceback__ to tb and return self. | | ---------------------------------------------------------------------- | Data descriptors inherited from builtins.BaseException: | | __cause__ | exception cause | | __context__ | exception context | | __dict__ | | __suppress_context__ | | __traceback__ | | args
pydy.system.SYMPY_VERSION
Error rendering doc: No Python documentation found for '1.13.3'. Use help() to get the interactive help utility. Use help(str) for help on the str class.
pydy.system.System
Python Library Documentation: class System in module pydy.system
class System(builtins.object)
| System(eom_method, constants=None, specifieds=None, ode_solver=None, initial_conditions=None, times=None)
|
| See the class's attributes for a description of the arguments to
| this constructor.
|
| The parameters to this constructor are all attributes of the System.
| Actually, they are properties. With the exception of ``eom_method``,
| these attributes can be modified directly at any future point.
|
| Parameters
| ----------
| eom_method : sympy.physics.mechanics.KanesMethod
| You must have called ``KanesMethod.kanes_equations()`` *before*
| constructing this ``System``.
| constants : dict, optional (default: all 1.0)
| This dictionary maps SymPy Symbol objects to floats.
| specifieds : dict, optional (default: all 0)
| This dictionary maps SymPy Functions of time objects, or tuples of
| them, to floats, NumPy arrays, or functions of the state and time.
| ode_solver : function, optional (default: scipy.integrate.odeint)
| This function computes the derivatives of the states.
| initial_conditions : dict, optional (default: all zero)
| This dictionary maps SymPy Functions of time objects to floats.
| times : array_like, shape(n,), optional
| An array_like object, which contains time values over which
| equations are integrated. It has to be supplied before
| System.integrate() can be called.
|
| Methods defined here:
|
| __init__(self, eom_method, constants=None, specifieds=None, ode_solver=None, initial_conditions=None, times=None)
| Initialize self. See help(type(self)) for accurate signature.
|
| evaluate_ode(self)
| Returns the right hand side of the differential equations evaluated
| at the set initial_conditions at the first time value.
|
| Returns
| =======
| x_dot : ndarray
| Time derivative of the states at time t.
|
| Notes
| =====
|
| To see the order of the state values use::
|
| help(system.evaluate_ode_function)
|
| generate_ode_function(self, **kwargs)
| Calls ``pydy.codegen.ode_function_generators.generate_ode_function``
| with the appropriate arguments, and sets the ``evaluate_ode_function``
| attribute to the resulting function.
|
| Parameters
| ----------
| kwargs
| All other kwargs are passed onto
| ``pydy.codegen.ode_function_generators.generate_ode_function()``.
| Don't specify the ``specifieds`` keyword argument though; the
| ``System`` class takes care of those.
|
| Returns
| -------
| evaluate_ode_function : function
| A function which evaluates the derivaties of the states.
|
| Notes
| -----
| If the Cython generator is selected and you have a custom
| ``ode_solver`` set, either ensure that solver only passes C contiguous
| arrays to the generated ode function or set the kwarg
| ``force_c_contiguous`` to ``True``. Forcing C contiguous arrays
| introduces a performance penalty due to the necessity of copying
| arrays.
|
| integrate(self, **solver_kwargs)
| Integrates the equations ``evaluate_ode_function()`` using
| ``ode_solver``.
|
| It is necessary to have first generated an ode function. If you have
| not done so, we do so automatically by invoking
| ``generate_ode_function()``. However, if you want to customize how this
| function is generated (e.g., change the generator to cython), you can
| call ``generate_ode_function()`` on your own (before calling
| ``integrate()``).
|
| Parameters
| ----------
| **solver_kwargs
| Optional arguments that are passed on to the ``ode_solver``.
|
| Returns
| -------
| x_history : np.array, shape(num_integrator_time_steps, 2)
| The trajectory of states (coordinates and speeds) through the
| requested time interval. num_integrator_time_steps is either
| len(times) if len(times) > 2, or is determined by the
| ``ode_solver``.
|
| ----------------------------------------------------------------------
| Readonly properties defined here:
|
| constants_symbols
| A set of the symbolic constants (not functions of time) in the
| system.
|
| coordinates
| Returns a list of the symbolic functions of time representing the
| system's generalized coordinates.
|
| eom_method
| This is a sympy.physics.mechanics.KanesMethod. The method used to
| generate the equations of motion. Read-only.
|
| evaluate_ode_function
| A function generated by ``generate_ode_function`` that computes
| the state derivatives:
|
| x' = evaluate_ode_function(x, t, *args)
|
| This function is used by the ``ode_solver``.
|
| specifieds_symbols
| A set of the dynamicsymbols you must specify.
|
| speeds
| Returns a list of the symbolic functions of time representing the
| system's generalized speeds.
|
| states
| Returns a list of the symbolic functions of time representing the
| system's states, i.e. generalized coordinates plus the generalized
| speeds. These are in the same order as used in integration (as
| passed into evaluate_ode_function) and match the order of the mass
| matrix and forcing vector.
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables
|
| __weakref__
| list of weak references to the object
|
| constants
| A dict that provides the numerical values for the constants in the
| problem (all non-dynamics symbols). Keys are the symbols for the
| constants, and values are floats. Constants that are not specified in
| this dict are given a default value of 1.0.
|
| initial_conditions
| Initial conditions for all states (coordinates and speeds). Keys
| are the symbols for the coordinates and speeds, and values are
| floats. Coordinates or speeds that are not specified in this dict
| are given a default value of 0.0.
|
| ode_solver
| A function that performs forward integration. It must have the
| same signature as scipy.integrate.odeint, which is::
|
| x_history = ode_solver(f, x0, t, args=(args,))
|
| where f is a function f(x, t, args), x0 are the initial conditions,
| x_history is the state time history, x is the state, t is the time,
| and args is a keyword argument takes arguments that are then passed
| to f. The default solver is odeint.
|
| specifieds
| A dict that provides numerical values for the specified quantities
| in the problem (all dynamicsymbols that are not defined by the
| equations of motion). There are two possible formats. (1) is more
| flexible, but (2) is more efficient (by a factor of 3).
|
| (1) Keys are the symbols for the specified quantities, or a tuple of
| symbols, and values are the floats, arrays of floats, or functions that
| generate the values. If a dictionary value is a function, it must have
| the same signature as ``f(x, t)``, the ode right-hand-side function
| (see the documentation for the ``ode_solver`` attribute). You needn't
| provide values for all specified symbols. Those for which you do not
| give a value will default to 0.0.
|
| (2) There are two keys: 'symbols' and 'values'. The value for 'symbols'
| is an iterable of *all* the specified quantities in the order that you
| have provided them in 'values'. Values is an ndarray, whose length is
| `len(sys.specifieds_symbols)`, or a function of x and t that returns an
| ndarray (also of length `len(sys.specifieds_symbols)`). NOTE: You must
| provide values for all specified symbols. In this case, we do *not*
| provide default values.
|
| NOTE: If you switch formats with the same instance of System, you
| *must* call `generate_ode_function()` before calling `integrate()`
| again.
|
| Examples
| --------
| Here are examples for (1). Keys can be individual symbols, or a tuple
| of symbols. Length of a value must match the length of the
| corresponding key. Values can be functions that return iterables::
|
| sys = System(km)
| sys.specifieds = {(a, b, c): np.ones(3), d: lambda x, t: -3 * x[0]}
| sys.specifieds = {(a, b, c): lambda x, t: np.ones(3)}
|
| Here are examples for (2):
|
| sys.specifieds = {'symbols': (a, b, c, d),
| 'values': np.ones(4)}
| sys.specifieds = {'symbols': (a, b, c, d),
| 'values': lambda x, t: np.ones(4)}
|
| times
| An array-like object, containing time values over which the
| equations of motion are integrated, numerically.
|
| The object should be in a format which the integration module to be
| used can accept.
pydy.system.dynamicsymbols
Python Library Documentation: function dynamicsymbols in module sympy.physics.vector.functions
dynamicsymbols(names, level=0, **assumptions)
Uses symbols and Function for functions of time.
Creates a SymPy UndefinedFunction, which is then initialized as a function
of a variable, the default being Symbol('t').
Parameters
==========
names : str
Names of the dynamic symbols you want to create; works the same way as
inputs to symbols
level : int
Level of differentiation of the returned function; d/dt once of t,
twice of t, etc.
assumptions :
- real(bool) : This is used to set the dynamicsymbol as real,
by default is False.
- positive(bool) : This is used to set the dynamicsymbol as positive,
by default is False.
- commutative(bool) : This is used to set the commutative property of
a dynamicsymbol, by default is True.
- integer(bool) : This is used to set the dynamicsymbol as integer,
by default is False.
Examples
========
>>> from sympy.physics.vector import dynamicsymbols
>>> from sympy import diff, Symbol
>>> q1 = dynamicsymbols('q1')
>>> q1
q1(t)
>>> q2 = dynamicsymbols('q2', real=True)
>>> q2.is_real
True
>>> q3 = dynamicsymbols('q3', positive=True)
>>> q3.is_positive
True
>>> q4, q5 = dynamicsymbols('q4,q5', commutative=False)
>>> bool(q4*q5 != q5*q4)
True
>>> q6 = dynamicsymbols('q6', integer=True)
>>> q6.is_integer
True
>>> diff(q1, Symbol('t'))
Derivative(q1(t), t)
pydy.system.find_dynamicsymbols
Python Library Documentation: function find_dynamicsymbols in module sympy.physics.mechanics.functions
find_dynamicsymbols(expression, exclude=None, reference_frame=None)
Find all dynamicsymbols in expression.
Explanation
===========
If the optional ``exclude`` kwarg is used, only dynamicsymbols
not in the iterable ``exclude`` are returned.
If we intend to apply this function on a vector, the optional
``reference_frame`` is also used to inform about the corresponding frame
with respect to which the dynamic symbols of the given vector is to be
determined.
Parameters
==========
expression : SymPy expression
exclude : iterable of dynamicsymbols, optional
reference_frame : ReferenceFrame, optional
The frame with respect to which the dynamic symbols of the
given vector is to be determined.
Examples
========
>>> from sympy.physics.mechanics import dynamicsymbols, find_dynamicsymbols
>>> from sympy.physics.mechanics import ReferenceFrame
>>> x, y = dynamicsymbols('x, y')
>>> expr = x + x.diff()*y
>>> find_dynamicsymbols(expr)
{x(t), y(t), Derivative(x(t), t)}
>>> find_dynamicsymbols(expr, exclude=[x, y])
{Derivative(x(t), t)}
>>> a, b, c = dynamicsymbols('a, b, c')
>>> A = ReferenceFrame('A')
>>> v = a * A.x + b * A.y + c * A.z
>>> find_dynamicsymbols(v, reference_frame=A)
{a(t), b(t), c(t)}
pydy.system.generate_ode_function
Python Library Documentation: function generate_ode_function in module pydy.codegen.ode_function_generators
generate_ode_function(*args, **kwargs)
Generates a numerical function which can evaluate the right hand
side of the first order ordinary differential equations from a
system described by one of the following three symbolic forms:
[1] x' = F(x, t, r, p)
[2] M(x, p) x' = F(x, t, r, p)
[3] M(q, p) u' = F(q, u, t, r, p)
q' = G(q, u, t, r, p)
where
- x : states, i.e. [q, u]
- t : time
- r : specified (exogenous) inputs
- p : constants
- q : generalized coordinates
- u : generalized speeds
- M : mass matrix (full or minimum)
- F : right hand side (full or minimum)
- G : right hand side of the kinematical differential equations
The generated function is of the form F(x, t, p) or F(x, t, r, p)
depending on whether the system has specified inputs or not.
Parameters
==========
right_hand_side : SymPy Matrix, shape(n, 1)
A column vector containing the symbolic expressions for the
right hand side of the ordinary differential equations. If the
right hand side has been solved for symbolically then only F is
required, see form [1]; if not then the mass matrix must also be
supplied, see forms [2, 3].
coordinates : sequence of SymPy Functions
The generalized coordinates. These must be ordered in the same
order as the rows in M, F, and/or G and be functions of time.
speeds : sequence of SymPy Functions
The generalized speeds. These must be ordered in the same order
as the rows in M, F, and/or G and be functions of time.
constants : sequence of SymPy Symbols, optional
All of the constants present in the equations of motion. The
order does not matter.
mass_matrix : sympy.Matrix, shape(n, n), optional
This can be either the "full" mass matrix as in [2] or the
"minimal" mass matrix as in [3]. The rows and columns must be
ordered to match the order of the coordinates and speeds. In the
case of the full mass matrix, the coordinates should always be
ordered before the speeds, i.e. x = [q, u].
coordinate_derivatives : sympy.Matrix, shape(m, 1), optional
If the "minimal" mass matrix, form [3], is supplied, then this
column vector represents the right hand side of the kinematical
differential equations.
specifieds : sequence of SymPy Functions
The specified exogenous inputs to the system. These should be
functions of time and the order does not matter.
linear_sys_solver : string or function
Specify either ``numpy`` or ``scipy`` to use the linear solvers
provided in each package or supply a function that solves a linear
system ``Ax=b`` with the call signature ``x = solve(A, b)``. For
example, if you need to use custom kwargs for the SciPy solver,
pass in a lambda function that wraps the solver and sets them. If
``sympy`` or ``sympy:<method>`` is provided, the linear system will
be solved symbolically in an efficient manner. ``<method>`` method
can be any valid method for
:external+sympy:meth:`~sympy.matrices.matrixbase.MatrixBase.solve`,
such as ``LU``, ``CH``, or ``CRAMER``. The default is ``LU`` if
only ``sympy`` is provided. The symbolic solve only works with the
Cython generator.
constants_arg_type : string
The generated function accepts two different types of arguments
for the numerical values of the constants: either a ndarray of
the constants values in the correct order or a dictionary
mapping the constants symbols to the numerical values. If None,
this is determined inside of the generated function and can
cause a significant slow down for performance critical code. If
you know apriori what arg types you need to support choose
either ``array`` or ``dictionary``. Note that ``array`` is
faster than ``dictionary``.
specifieds_arg_type : string
The generated function accepts three different types of
arguments for the numerical values of the specifieds: either a
ndarray of the specifieds values in the correct order, a
function that generates the correctly ordered ndarray, or a
dictionary mapping the specifieds symbols or tuples of thereof
to floats, ndarrays, or functions. If None, this is determined
inside of the generated function and can cause a significant
slow down for performance critical code. If you know apriori
what arg types you want to support choose either ``array``,
``function``, or ``dictionary``. The speed of each, from fast to
slow, are ``array``, ``function``, ``dictionary``, None.
time_first : boolean, optional
By default the argument order of the generated function is ``F(x,
t, r, p)`` and, if this is set to true, it will be ``F(t, x, r,
p)``.
generator : string or ODEFunctionGenerator, optional
The method used for generating the numeric right hand side. The string
options are ``{'lambdify'|'theano'|'cython'|'symjit'}`` with ``lambdify``
being the default. You can also pass in a custom subclass of
ODEFunctionGenerator.
kwargs
Extra keyword arguments are passed to the :py:class:`ODEFunctionGenerator`.
Returns
=======
rhs : function
A function which evaluates the derivaties of the states. See the
function's docstring for more details after generation.
pydy.system.odeint
Python Library Documentation: function odeint in module scipy.integrate._odepack_py
odeint(func, y0, t, args=(), Dfun=None, col_deriv=0, full_output=0, ml=None, mu=None, rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0, mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0, tfirst=False)
Integrate a system of ordinary differential equations.
.. note:: For new code, use `scipy.integrate.solve_ivp` to solve a
differential equation.
Solve a system of ordinary differential equations using lsoda from the
FORTRAN library odepack.
Solves the initial value problem for stiff or non-stiff systems
of first order ode-s::
dy/dt = func(y, t, ...) [or func(t, y, ...)]
where y can be a vector.
.. note:: By default, the required order of the first two arguments of
`func` are in the opposite order of the arguments in the system
definition function used by the `scipy.integrate.ode` class and
the function `scipy.integrate.solve_ivp`. To use a function with
the signature ``func(t, y, ...)``, the argument `tfirst` must be
set to ``True``.
Parameters
----------
func : callable(y, t, ...) or callable(t, y, ...)
Computes the derivative of y at t.
If the signature is ``callable(t, y, ...)``, then the argument
`tfirst` must be set ``True``.
`func` must not modify the data in `y`, as it is a
view of the data used internally by the ODE solver.
y0 : array
Initial condition on y (can be a vector).
t : array
A sequence of time points for which to solve for y. The initial
value point should be the first element of this sequence.
This sequence must be monotonically increasing or monotonically
decreasing; repeated values are allowed.
args : tuple, optional
Extra arguments to pass to function.
Dfun : callable(y, t, ...) or callable(t, y, ...)
Gradient (Jacobian) of `func`.
If the signature is ``callable(t, y, ...)``, then the argument
`tfirst` must be set ``True``.
`Dfun` must not modify the data in `y`, as it is a
view of the data used internally by the ODE solver.
col_deriv : bool, optional
True if `Dfun` defines derivatives down columns (faster),
otherwise `Dfun` should define derivatives across rows.
full_output : bool, optional
True if to return a dictionary of optional outputs as the second output
printmessg : bool, optional
Whether to print the convergence message
tfirst : bool, optional
If True, the first two arguments of `func` (and `Dfun`, if given)
must ``t, y`` instead of the default ``y, t``.
.. versionadded:: 1.1.0
Returns
-------
y : array, shape (len(t), len(y0))
Array containing the value of y for each desired time in t,
with the initial value `y0` in the first row.
infodict : dict, only returned if full_output == True
Dictionary containing additional output information
======= ============================================================
key meaning
======= ============================================================
'hu' vector of step sizes successfully used for each time step
'tcur' vector with the value of t reached for each time step
(will always be at least as large as the input times)
'tolsf' vector of tolerance scale factors, greater than 1.0,
computed when a request for too much accuracy was detected
'tsw' value of t at the time of the last method switch
(given for each time step)
'nst' cumulative number of time steps
'nfe' cumulative number of function evaluations for each time step
'nje' cumulative number of jacobian evaluations for each time step
'nqu' a vector of method orders for each successful step
'imxer' index of the component of largest magnitude in the
weighted local error vector (e / ewt) on an error return, -1
otherwise
'lenrw' the length of the double work array required
'leniw' the length of integer work array required
'mused' a vector of method indicators for each successful time step:
1: adams (nonstiff), 2: bdf (stiff)
======= ============================================================
Other Parameters
----------------
ml, mu : int, optional
If either of these are not None or non-negative, then the
Jacobian is assumed to be banded. These give the number of
lower and upper non-zero diagonals in this banded matrix.
For the banded case, `Dfun` should return a matrix whose
rows contain the non-zero bands (starting with the lowest diagonal).
Thus, the return matrix `jac` from `Dfun` should have shape
``(ml + mu + 1, len(y0))`` when ``ml >=0`` or ``mu >=0``.
The data in `jac` must be stored such that ``jac[i - j + mu, j]``
holds the derivative of the ``i``\ th equation with respect to the
``j``\ th state variable. If `col_deriv` is True, the transpose of
this `jac` must be returned.
rtol, atol : float, optional
The input parameters `rtol` and `atol` determine the error
control performed by the solver. The solver will control the
vector, e, of estimated local errors in y, according to an
inequality of the form ``max-norm of (e / ewt) <= 1``,
where ewt is a vector of positive error weights computed as
``ewt = rtol * abs(y) + atol``.
rtol and atol can be either vectors the same length as y or scalars.
Defaults to 1.49012e-8.
tcrit : ndarray, optional
Vector of critical points (e.g., singularities) where integration
care should be taken.
h0 : float, (0: solver-determined), optional
The step size to be attempted on the first step.
hmax : float, (0: solver-determined), optional
The maximum absolute step size allowed.
hmin : float, (0: solver-determined), optional
The minimum absolute step size allowed.
ixpr : bool, optional
Whether to generate extra printing at method switches.
mxstep : int, (0: solver-determined), optional
Maximum number of (internally defined) steps allowed for each
integration point in t.
mxhnil : int, (0: solver-determined), optional
Maximum number of messages printed.
mxordn : int, (0: solver-determined), optional
Maximum order to be allowed for the non-stiff (Adams) method.
mxords : int, (0: solver-determined), optional
Maximum order to be allowed for the stiff (BDF) method.
See Also
--------
solve_ivp : solve an initial value problem for a system of ODEs
ode : a more object-oriented integrator based on VODE
quad : for finding the area under a curve
Examples
--------
The second order differential equation for the angle `theta` of a
pendulum acted on by gravity with friction can be written::
theta''(t) + b*theta'(t) + c*sin(theta(t)) = 0
where `b` and `c` are positive constants, and a prime (') denotes a
derivative. To solve this equation with `odeint`, we must first convert
it to a system of first order equations. By defining the angular
velocity ``omega(t) = theta'(t)``, we obtain the system::
theta'(t) = omega(t)
omega'(t) = -b*omega(t) - c*sin(theta(t))
Let `y` be the vector [`theta`, `omega`]. We implement this system
in Python as:
>>> import numpy as np
>>> def pend(y, t, b, c):
... theta, omega = y
... dydt = [omega, -b*omega - c*np.sin(theta)]
... return dydt
...
We assume the constants are `b` = 0.25 and `c` = 5.0:
>>> b = 0.25
>>> c = 5.0
For initial conditions, we assume the pendulum is nearly vertical
with `theta(0)` = `pi` - 0.1, and is initially at rest, so
`omega(0)` = 0. Then the vector of initial conditions is
>>> y0 = [np.pi - 0.1, 0.0]
We will generate a solution at 101 evenly spaced samples in the interval
0 <= `t` <= 10. So our array of times is:
>>> t = np.linspace(0, 10, 101)
Call `odeint` to generate the solution. To pass the parameters
`b` and `c` to `pend`, we give them to `odeint` using the `args`
argument.
>>> from scipy.integrate import odeint
>>> sol = odeint(pend, y0, t, args=(b, c))
The solution is an array with shape (101, 2). The first column
is `theta(t)`, and the second is `omega(t)`. The following code
plots both components.
>>> import matplotlib.pyplot as plt
>>> plt.plot(t, sol[:, 0], 'b', label='theta(t)')
>>> plt.plot(t, sol[:, 1], 'g', label='omega(t)')
>>> plt.legend(loc='best')
>>> plt.xlabel('t')
>>> plt.grid()
>>> plt.show()
pydy.system.repeat
Python Library Documentation: class repeat in module itertools class repeat(builtins.object) | repeat(object [,times]) -> create an iterator which returns the object | for the specified number of times. If not specified, returns the object | endlessly. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __length_hint__(...) | Private method returning an estimate of len(list(it)). | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling. | | __repr__(self, /) | Return repr(self). | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) | Create and return a new object. See help(type) for accurate signature.