Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def plot_reaction_contributions(
xyp, rsys, rate_exprs_cb, substance_keys=None, varied=None, axes=None,
total=False, linthreshy=1e-9, relative=False, xscale='log', yscale='symlog',
xlabel='Time', ylabel=None, combine_equilibria=False, selection=slice(None),
unit_registry=None):
""" Plots per reaction contributions to concentration evolution of a substance.
Parameters
----------
xyp : ``pyodesys.results.Result`` instance or length 3 tuple or xout,yout,params
result : pyodesys.results.Result
substance_key : str
"""
from pyodesys.results import Result
if isinstance(xyp, Result):
xyp = xyp.odesys.to_arrays(xyp.xout, xyp.yout, xyp.params, reshape=False)
if varied is None:
varied = xyp[0]
if xyp[1].shape[-2] != varied.size:
raise ValueError("Size mismatch between varied and yout")
if substance_keys is None:
substance_keys = rsys.substances.keys()
if axes is None:
_fig, axes = plt.subplots(len(substance_keys))
rates = rate_exprs_cb(*xyp)
if unit_registry is not None:
time_unit = get_derived_unit(unit_registry, 'time')
conc_unit = get_derived_unit(unit_registry, 'concentration')
rates = to_unitless(rates*conc_unit/time_unit, u.molar/u.second)
eqk1, eqk2, eqs = _combine_rxns_to_eq(rsys) if combine_equilibria else ([], [], [])
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:
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
import copy
import os
from ..util import import_
from ._base import _NativeCodeBase, _NativeSysBase, _compile_kwargs
_config, get_include = import_('pygslodeiv2', '_config', 'get_include')
class NativeGSLCode(_NativeCodeBase):
""" Looks for the environment variable: ``PYODESYS_BLAS`` (``gslcblas``) """
wrapper_name = '_gsl_wrapper'
def __init__(self, *args, **kwargs):
self.compile_kwargs = copy.deepcopy(_compile_kwargs)
self.compile_kwargs['include_dirs'].append(get_include())
self.compile_kwargs['libraries'].extend(_config.env['GSL_LIBS'].split(','))
self.compile_kwargs['libraries'].extend(os.environ.get('PYODESYS_BLAS', _config.env['BLAS']).split(','))
super(NativeGSLCode, self).__init__(*args, **kwargs)
class NativeGSLSys(_NativeSysBase):
_NativeCode = NativeGSLCode
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
import copy
import os
from ..util import import_
from ._base import _NativeCodeBase, _NativeSysBase, _compile_kwargs
_config, get_include = import_('pygslodeiv2', '_config', 'get_include')
class NativeGSLCode(_NativeCodeBase):
""" Looks for the environment variable: ``PYODESYS_BLAS`` (``gslcblas``) """
wrapper_name = '_gsl_wrapper'
def __init__(self, *args, **kwargs):
self.compile_kwargs = copy.deepcopy(_compile_kwargs)
self.compile_kwargs['include_dirs'].append(get_include())
self.compile_kwargs['libraries'].extend(_config.env['GSL_LIBS'].split(','))
self.compile_kwargs['libraries'].extend(os.environ.get('PYODESYS_BLAS', _config.env['BLAS']).split(','))
super(NativeGSLCode, self).__init__(*args, **kwargs)
class NativeGSLSys(_NativeSysBase):
_NativeCode = NativeGSLCode
_native_name = 'gsl'
def __init__(self, *args, **kwargs):
self.compile_kwargs = copy.deepcopy(_compile_kwargs)
self.compile_kwargs['define'] = ['PYCVODES_NO_KLU={}'.format("0" if config.get('KLU', True) else "1"),
'PYCVODES_NO_LAPACK={}'.format("0" if config.get('LAPACK', True) else "1"),
'ANYODE_NO_LAPACK={}'.format("0" if config.get('LAPACK', True) else "1")]
self.compile_kwargs['include_dirs'].append(get_include())
self.compile_kwargs['libraries'].extend(_libs.get_libs().split(','))
self.compile_kwargs['libraries'].extend([l for l in os.environ.get(
'PYODESYS_LAPACK', "lapack,blas" if config["LAPACK"] else "").split(",") if l != ""])
self.compile_kwargs['flags'] = [f for f in os.environ.get("PYODESYS_CVODE_FLAGS", "").split() if f]
self.compile_kwargs['ldflags'] = [f for f in os.environ.get("PYODESYS_CVODE_LDFLAGS", "").split() if f]
super(NativeCvodeCode, self).__init__(*args, **kwargs)
class NativeCvodeSys(_NativeSysBase):
_NativeCode = NativeCvodeCode
_native_name = 'cvode'
def as_standalone(self, out_file=None, compile_kwargs=None):
from pycompilation.compilation import src2obj, link
from pycodeexport.util import render_mako_template_to
compile_kwargs = compile_kwargs or {}
impl_src = open([f for f in self._native._written_files if f.endswith('.cpp')][0], 'rt').read()
f = render_mako_template_to(
os.path.join(os.path.dirname(__file__), 'sources/standalone_template.cpp'),
'%s.cpp' % out_file, {'p_odesys': self, 'p_odesys_impl': impl_src})
kw = copy.deepcopy(self._native.compile_kwargs)
kw.update(compile_kwargs)
objf = src2obj(f, **kw)
kw['libraries'].append('boost_program_options')
return link([objf], out_file, **kw)
_config, get_include = import_('pygslodeiv2', '_config', 'get_include')
class NativeGSLCode(_NativeCodeBase):
""" Looks for the environment variable: ``PYODESYS_BLAS`` (``gslcblas``) """
wrapper_name = '_gsl_wrapper'
def __init__(self, *args, **kwargs):
self.compile_kwargs = copy.deepcopy(_compile_kwargs)
self.compile_kwargs['include_dirs'].append(get_include())
self.compile_kwargs['libraries'].extend(_config.env['GSL_LIBS'].split(','))
self.compile_kwargs['libraries'].extend(os.environ.get('PYODESYS_BLAS', _config.env['BLAS']).split(','))
super(NativeGSLCode, self).__init__(*args, **kwargs)
class NativeGSLSys(_NativeSysBase):
_NativeCode = NativeGSLCode
_native_name = 'gsl'
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:
plt.show()
def __init__(self, *args, **kwargs):
self.compile_kwargs = copy.deepcopy(_compile_kwargs)
self.compile_kwargs['include_dirs'].append(get_include())
self.compile_kwargs['libraries'].extend(_config.env['GSL_LIBS'].split(','))
self.compile_kwargs['libraries'].extend(os.environ.get('PYODESYS_BLAS', _config.env['BLAS']).split(','))
super(NativeGSLCode, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs):
self.compile_kwargs = copy.deepcopy(_compile_kwargs)
self.compile_kwargs['define'] = ['PYCVODES_NO_KLU={}'.format("0" if config.get('KLU', True) else "1"),
'PYCVODES_NO_LAPACK={}'.format("0" if config.get('LAPACK', True) else "1"),
'ANYODE_NO_LAPACK={}'.format("0" if config.get('LAPACK', True) else "1")]
self.compile_kwargs['include_dirs'].append(get_include())
self.compile_kwargs['libraries'].extend(_libs.get_libs().split(','))
self.compile_kwargs['libraries'].extend([l for l in os.environ.get(
'PYODESYS_LAPACK', "lapack,blas" if config["LAPACK"] else "").split(",") if l != ""])
self.compile_kwargs['flags'] = [f for f in os.environ.get("PYODESYS_CVODE_FLAGS", "").split() if f]
self.compile_kwargs['ldflags'] = [f for f in os.environ.get("PYODESYS_CVODE_LDFLAGS", "").split() if f]
super(NativeCvodeCode, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs):
self.compile_kwargs = copy.deepcopy(_compile_kwargs)
self.compile_kwargs['define'] = ['PYCVODES_NO_KLU={}'.format("0" if config.get('KLU', True) else "1"),
'PYCVODES_NO_LAPACK={}'.format("0" if config.get('LAPACK', True) else "1"),
'ANYODE_NO_LAPACK={}'.format("0" if config.get('LAPACK', True) else "1")]
self.compile_kwargs['include_dirs'].append(get_include())
self.compile_kwargs['libraries'].extend(_libs.get_libs().split(','))
self.compile_kwargs['libraries'].extend([l for l in os.environ.get(
'PYODESYS_LAPACK', "lapack,blas" if config["LAPACK"] else "").split(",") if l != ""])
self.compile_kwargs['flags'] = [f for f in os.environ.get("PYODESYS_CVODE_FLAGS", "").split() if f]
self.compile_kwargs['ldflags'] = [f for f in os.environ.get("PYODESYS_CVODE_LDFLAGS", "").split() if f]
super(NativeCvodeCode, self).__init__(*args, **kwargs)