How to use the pyodesys.symbolic.SymbolicSys function in pyodesys

To help you get started, we’ve selected a few pyodesys examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github bjodah / pyodesys / examples / van_der_pol.py View on Github external
def main(y0='1,0', mu=1.0, tend=10., nt=50, savefig='None', plot=False,
         savetxt='None', integrator='scipy', dpi=100, kwargs='',
         verbose=False):
    assert nt > 1
    y = sp.symarray('y', 2)
    p = sp.Symbol('p', real=True)
    f = [y[1], -y[0] + p*y[1]*(1 - y[0]**2)]
    odesys = SymbolicSys(zip(y, f), params=[p], names=True)
    tout = np.linspace(0, tend, nt)
    y0 = list(map(float, y0.split(',')))
    kwargs = dict(eval(kwargs) if kwargs else {})
    xout, yout, info = odesys.integrate(
        tout, y0, [mu], integrator=integrator, **kwargs)
    if verbose:
        print(info)
    if savetxt != 'None':
        np.savetxt(stack_1d_on_left(xout, yout), savetxt)
    if plot:
        import matplotlib.pyplot as plt
        odesys.plot_result()
        plt.legend()
        if savefig != 'None':
            plt.savefig(savefig, dpi=dpi)
        else:
github bjodah / pyodesys / pyodesys / native / _base.py View on Github external
'exprs': list(map(_ccode, invar_exprs))
            },
            p_nroots=self.odesys.nroots,
            p_constructor=[],
            p_get_dx_max=False
        )
        ns.update(self.namespace_default)
        ns.update(self.namespace)
        ns.update(self.namespace_override)
        for k, v in self.namespace_extend.items():
            ns[k].extend(v)

        return ns


class _NativeSysBase(SymbolicSys):

    _NativeCode = None
    _native_name = None

    def __init__(self, *args, **kwargs):
        namespace_override = kwargs.pop('namespace_override', {})
        namespace_extend = kwargs.pop('namespace_extend', {})
        save_temp = kwargs.pop('save_temp', False)
        if 'init_indep' not in kwargs:  # we need to trigger append_iv for when invariants are used
            kwargs['init_indep'] = True
            kwargs['init_dep'] = True
        super(_NativeSysBase, self).__init__(*args, **kwargs)
        self._native = self._NativeCode(self, save_temp=save_temp,
                                        namespace_override=namespace_override,
                                        namespace_extend=namespace_extend)
github bjodah / pyodesys / pyodesys / symbolic.py View on Github external
derivs = [invar.diff(dep) for dep in deps]
        if all([deriv.is_Number for deriv in derivs]):
            linear_invar.append(derivs)
            if use_names:
                lin_names.append(names[idx])
        else:
            nonlinear_invar.append(invar)
            if use_names:
                nonlin_names.append(names[idx])
    if names is None:
        return linear_invar, nonlinear_invar
    else:
        return linear_invar, nonlinear_invar, lin_names, nonlin_names


class TransformedSys(SymbolicSys):
    """ SymbolicSys with variable transformations.

    Parameters
    ----------
    dep_exprs : iterable of pairs
        see :class:`SymbolicSys`
    indep : Symbol
        see :class:`SymbolicSys`
    dep_transf : iterable of (expression, expression) pairs
        pairs of (forward, backward) transformations for the dependents
        variables
    indep_transf : pair of expressions
        forward and backward transformation of the independent variable
    params :
        see :class:`SymbolicSys`
    exprs_process_cb : callbable
github bjodah / pyodesys / examples / _chem_kinet.py View on Github external
def from_b64_gz_pkl(data, pop=('params',), **kwargs):
    imported = pickle.loads(gzip.decompress(codecs.decode(data.encode('utf-8'), 'base64')))
    popped = [imported.pop(k) for k in pop]
    if 'SymbSys' not in kwargs:
        kwargs['SymbSys'] = SymbolicSys
    if 'dep_by_name' not in kwargs:
        kwargs['dep_by_name'] = True
    imported.update(kwargs)
    return get_odesys(**imported), popped
github bjodah / pyodesys / pyodesys / symbolic.py View on Github external
dep_transf_cbs=repeat(cls._scale_fw_bw(dep_scaling)),
            indep_transf_cbs=cls._scale_fw_bw(indep_scaling),
            **kwargs
        )


def _append(arr, *iterables):
    if isinstance(arr, np.ndarray):
        return np.concatenate((arr,) + iterables)
    arr = arr[:]
    for iterable in iterables:
        arr += type(arr)(iterable)
    return arr


class PartiallySolvedSystem(SymbolicSys):
    """ Use analytic expressions for some dependent variables

    Parameters
    ----------
    original_system : SymbolicSys
    analytic_factory : callable
        User provided callback for expressing analytic solutions to a set of
        dependent variables in ``original_system``. The callback should have
        the signature: ``my_factory(x0, y0, p0, backend) -> dict``, where the returned
        dictionary maps dependent variabels (from ``original_system.dep``)
        to new expressions in remaining variables and initial conditions.
    \\*\\*kwargs : dict
        Keyword arguments passed onto :class:`SymbolicSys`.

    Attributes
    ----------
github bjodah / pyodesys / examples / pydy_double_pendulum.py View on Github external
def main(m=1, g=9.81, l=1, q1=.1, q2=.2, u1=0, u2=0, tend=10., nt=200,
         savefig='None', plot=False, savetxt='None', integrator='scipy',
         dpi=100, kwargs="", verbose=False):
    assert nt > 1
    kwargs = dict(eval(kwargs) if kwargs else {})
    odesys = SymbolicSys(get_equations(m, g, l), params=())
    tout = np.linspace(0, tend, nt)
    y0 = [q1, q2, u1, u2]
    xout, yout, info = odesys.integrate(
        tout, y0, integrator=integrator, **kwargs)
    if verbose:
        print(info)
    if savetxt != 'None':
        np.savetxt(stack_1d_on_left(xout, yout), savetxt)
    if plot:
        import matplotlib.pyplot as plt
        odesys.plot_result(xout, yout)
        if savefig != 'None':
            plt.savefig(savefig, dpi=dpi)
        else:
            plt.show()
github bjodah / pyodesys / pyodesys / symbolic.py View on Github external
...         p[0]*y[0] - p[1]*y[1]
    ...     ], 2, 2)
    >>> dep0 = odesys.dep[0]
    >>> partsys = PartiallySolvedSystem(odesys, lambda x0, y0, p0, be: {
    ...         dep0: y0[0]*be.exp(-p0[0]*(odesys.indep-x0))
    ...     })
    >>> print(partsys.exprs)  # doctest: +SKIP
    (_Dummy_29*p_0*exp(-p_0*(-_Dummy_28 + x)) - p_1*y_1,)
    >>> y0, k = [3, 2], [3.5, 2.5]
    >>> xout, yout, info = partsys.integrate([0, 1], y0, k, integrator='scipy')
    >>> info['success'], yout.shape[1]
    (True, 2)

    """

    _attrs_to_copy = SymbolicSys._attrs_to_copy + ('free_names', 'free_latex_names', 'original_dep')

    def __init__(self, original_system, analytic_factory, **kwargs):
        self._ori_sys = original_system
        self.analytic_factory = _ensure_4args(analytic_factory)
        roots = kwargs.pop('roots', self._ori_sys.roots)
        _be = self._ori_sys.be
        init_indep = self._ori_sys.init_indep or self._mk_init_indep(name=self._ori_sys.indep, be=self._ori_sys.be)
        init_dep = self._ori_sys.init_dep or self._ori_sys._mk_init_dep()
        if 'pre_processors' in kwargs or 'post_processors' in kwargs:
            raise NotImplementedError("Cannot override pre-/postprocessors")
        if 'backend' in kwargs and Backend(kwargs['backend']) != _be:
            raise ValueError("Cannot mix backends.")
        _pars = self._ori_sys.params
        if self._ori_sys.par_by_name:
            _pars = dict(zip(self._ori_sys.param_names, _pars))
github bjodah / pyodesys / pyodesys / symbolic.py View on Github external
kwargs['names'] = _names = [y.name for y in self.dep]
        if self.indep is not None and _names not in (None, ()):
            if self.indep.name in _names:
                raise ValueError("Independent variable cannot share name with any dependent variable")

        _param_names = kwargs.get('param_names', None)
        if _param_names is True:
            kwargs['param_names'] = [p.name for p in self.params]

        self.sparse = sparse  # needed by get_j_ty_callback
        self.band = kwargs.get('band', None)  # needed by get_j_ty_callback
        # bounds needed by get_f_ty_callback:
        self.lower_bounds = None if lower_bounds is None else np.array(lower_bounds)*np.ones(self.ny)
        self.upper_bounds = None if upper_bounds is None else np.array(upper_bounds)*np.ones(self.ny)

        super(SymbolicSys, self).__init__(
            self.get_f_ty_callback(),
            jac=self.get_j_ty_callback(),
            dfdx=self.get_dfdx_callback(),
            jtimes=self.get_jtimes_callback(),
            first_step_cb=self.get_first_step_callback(),
            roots_cb=self.get_roots_callback(),
            nroots=None if roots is None else len(roots),
            autonomous_exprs=_is_autonomous(self.indep, self.exprs),
            **kwargs)

        if self.sparse:
            self.nnz = len(self._rowvals)
        self.linear_invariants = linear_invariants
        self.nonlinear_invariants = nonlinear_invariants
        self.linear_invariant_names = linear_invariant_names or None
        if self.linear_invariant_names is not None:
github bjodah / pyodesys / benchmarks / benchmarks / pydy_double_pendulum.py View on Github external
def setup(self):
        self.odesys = SymbolicSys(_get_equations(1, 9.81, 1))
        self.tout = np.linspace(0, 10., 200)
        self.y0 = [.1, .2, 0, 0]