Skip to content

Commit

Permalink
Merge pull request #166 from biocircuits/dev
Browse files Browse the repository at this point in the history
Enhanced documentation with Bioscrape v1.2.2
  • Loading branch information
ayush9pandey authored Feb 25, 2023
2 parents acb4734 + 1be7f3c commit 18a8135
Show file tree
Hide file tree
Showing 19 changed files with 593 additions and 440 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,4 @@ mcmc_results.txt
lmfit_results.csv
mcmc_results.txt
unzip_dist.py
pip-wheel-metadata/*
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,13 @@ Further details about the installation process can be found in the [Bioscrape wi
Please report any bugs that you find [here](https://github.com/biocircuits/bioscrape/issues).
Or, even better, fork the repository on [GitHub](https://github.com/biocircuits/bioscrape),
and create a pull request (PR). We welcome all changes, big or small, and we
will help you make the PR if you are new to `git` (just ask on the issue). More details on contributing to bioscrape are available on the [`Contributing`](https://github.com/biocircuits/bioscrape/blob/master/contributing.md) page.
will help you make the PR if you are new to `git` (just ask on the issue). The [CONTRIBUTING.md](https://github.com/biocircuits/bioscrape/blob/master/CONTRIBUTING.md) file has more detailed set of instructions on contributing to the software.

# Versions

Bioscrape versions:

* 1.2.1 (latest stable release): To install run `pip install bioscrape`
* 1.2.2 (latest release): To install run `pip install bioscrape`
* 1.2.0 (tagged stable release): To install run `pip install bioscrape==1.2.0`
* 1.0.4 (beta release): To install run `pip install bioscrape==1.0.4`

Expand Down
38 changes: 33 additions & 5 deletions bioscrape/analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
from bioscrape.simulator import ModelCSimInterface, DeterministicSimulator
from scipy.integrate import odeint
import numpy as np
from typing import List, Union

def py_sensitivity_analysis(model, timepoints, normalize, **kwargs):
def py_sensitivity_analysis(model: Model, timepoints: np.ndarray,
normalize: bool, **kwargs) -> np.ndarray:
"""User interface function to perform sensitivity analysis
on a bioscrape model. The sensitivity coefficients are computed
where each coefficient s_ij = rate of change of x_i with parameter p_j
Expand All @@ -22,15 +24,41 @@ def py_sensitivity_analysis(model, timepoints, normalize, **kwargs):
numpy.ndarray: A numpy array of size:
len(timepoints) x len(parameters) x len(states)
"""
sens_obj = SensitivityAnalysis(model)
ans_df = sens_obj.propagator.py_simulate(sens_obj.sim_interface, timepoints).py_get_dataframe(sens_obj.M)
dx = kwargs.get("dx", 0.01)
precision = kwargs.get("precision", 10)
sens_obj = SensitivityAnalysis(model, dx=dx, precision=precision)
ans_df = sens_obj.propagator.py_simulate(sens_obj.sim_interface,
timepoints).py_get_dataframe(sens_obj.M)
solutions_array = np.array(ans_df.iloc[:,range(0,len(ans_df.T) - 1)])
return sens_obj.compute_SSM(solutions_array, timepoints, normalize, **kwargs)

def py_get_jacobian(model, state, **kwargs):
def py_get_jacobian(model: Model, state: Union[list, np.ndarray], **kwargs) -> np.ndarray:
"""User interfacce function to compute Jacobian (df/dx) of the model.
Args:
model (Model): Bioscrape Model
state (Union[list, np.ndarray]): The state values (vector of length n)
at which to compute the Jacobian
Returns:
np.ndarray: A (n x n) Jacobian matrix, where n = len(state)
"""
return SensitivityAnalysis(model).compute_J(state, **kwargs)

def py_get_sensitivity_to_parameter(model, state, param_name, **kwargs):
def py_get_sensitivity_to_parameter(model: Model, state: Union[list, np.ndarray],
param_name: str, **kwargs) -> np.ndarray:
"""User interface function to compute the sensitivity to parameter (df/dp)
where p is the parameter and f is the model
Args:
model (Model): Bioscrape Model
state (Union[list, np.ndarray]): The state values (vector of length n)
at which to compute df/dp
param_name (str): The parameter name for which df/dp is computed
Returns:
np.ndarray: A np.ndarray of size (n x 1), where n is the length of state
"""
return SensitivityAnalysis(model).compute_Zj(state, param_name, **kwargs)

class SensitivityAnalysis(Model):
Expand Down
49 changes: 48 additions & 1 deletion bioscrape/inference.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,54 @@ def py_inference(Model = None, params_to_estimate = None, exp_data = None, initi
parameter_conditions = None, measurements = None, time_column = None, nwalkers = None,
nsteps = None, init_seed = None, prior = None, sim_type = None, inference_type = 'emcee',
method = 'mcmc', plot_show = True, **kwargs):

"""
User level interface for running bioscrape inference module.
Args:
Model (bioscrape.types.Model): Bioscrape Model object
params_to_estimate (List[str]): A list of parameter names in the Model to estimate
exp_data (List[pd.DataFrame], pd.Dataframe): A pandas.DataFrame or a list of pandas.Dataframe
that consists of the required experimental data\
initial_conditions (List[dict], dict): A list of dictionaries of initial conditions corresponding to each
data trajectory in exp_data or a single dictionary if one trajectory
parameter_conditions (List[dict], dict): A list of dictionaries of parameter conditions corresponding to each
data trajectory in exp_data or a single dictionary if one trajectory
measurements (List[str], str): Names of species in the Model that are measured, either as a list if multiple outputs
or a single measurement.
time_column (str): The column name of the exp_data that contains the time points in the data, for time-series inference
nwalkers (int): The number of walkers for the Markov Chain Monte Carlo sampling. See emcee.EnsembleSampler for more info.
nsteps (int): The number of steps for the Markov Chain Monte Carlo sampling. See emcee.EnsembleSampler for more info.
init_seed (Union[float, np.ndarray, list. "prior"]): The parameter that controls the initial parameter
values for the sampling.
If a float "r" is passed, then the initial values
are sampled from a Gaussian ball of radius "r" around mean values
set as Model parameter values
If a np.ndarray or a list is passed, then the length must be same
as the number of `params_to_estimate`. These values are then
used as initial values for the sampler.
If the keyword "prior" is passed, then the initial values are sampled
from the prior distributions specified for each parameter value.
prior (dict): The prior dict specifies the prior for each parameter in params_to_estimate. The syntax is
{"parameter1": ["uniform", min_value, max_value],
"parameter2": ["gaussian", mean, std, "positive"]}
The "positive" keyword ensures that the prior rejects all negative values for the parameter.
Refer to the full documentation on priors on our Wiki: https://github.com/biocircuits/bioscrape/wiki
sim_type (Union["deterministic", "stochastic"]): A str that is either "deterministic" or "stochastic" to set the
type of simulation for the inference run.
inference_type (Union["emcee", "lmfit"]): A str that specifies the kind of inference to run. Currently, only two packages
are supported: emcee and lmfit.
method (str): For inference_type = emcee, this argument should not be used. For lmfit, method is passed into the method
keyword of the lmfit call. More details here:
https://lmfit.github.io/lmfit-py/fitting.html#choosing-different-fitting-methods
plot_show (bool): If set to `True`, bioscrape will try to display the generated plots from the inference run.
If set to `False`, not plots will be shown.
Returns:
for inference_type = "emcee":
sampler, pid: A tuple consisting of the emcee.EnsembleSampler and the bioscrape pid object
for inference_type = "lmfit":
minimizer_result: A lmfit.MinimizerResult object that consists of the minimizer information.
Raises:
ValueError: When `inference_type` argument is set to something other than the currently supported modules.
"""
if Model is None:
raise ValueError('Model object cannot be None.')

Expand Down
25 changes: 25 additions & 0 deletions bioscrape/simulator.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2103,6 +2103,31 @@ cdef class DelayVolumeSSASimulator(DelayVolumeSimulator):
#A wrapper function to allow easy simulation of Models
def py_simulate_model(timepoints, Model = None, Interface = None, stochastic = False,
delay = None, safe = False, volume = False, return_dataframe = True, **keywords):
"""
User interface function to simulate a Bioscrape Model.
Args:
timepoints (np.ndarray): An array that contains the times for the simulation run.
Model (bioscrape.types.Model): The bioscrape Model object to run.
Interface (bioscrape.simulator.CSimInterface): Specifies particular model simulation interface to use.
Default: None, to create the interface automatically.
Developers may use this to pass existing interfaces to speed up simulations.
stochastic (bool): If `True`, a stochastic simulation using the Gillespie stochastic simulation algorithm is run.
If `False` (default), a deterministic simulation using python scipy.integrate.odeint is run.
delay (bool): If `True`, a delay simulator is initialized.
If `False` or None (default), delay simulator is not initialized.
safe (bool): If `True`, a safe model model simulation interface is initialized.
A safe model simulator issues warnings when ill-conditioned situations occur in simulation
(for example, a negative propensity of a reaction)
If `False` (default), normal model simulation interface is used.
volume (bool): If `True`, a volume is initialized for the simulation (relevant for lineage simulations)
If `False` (default), volume is not used in simulations.
Refer to the lineage module for more information.
return_dataframe (bool): If `True` (default), a Pandas dataframe with the simulation results is returned.
If `False`, a bioscrape simulation result object is returned.
Returns:
pandas.DataFrame with the simulation results if return_dataframe is set to `True`
or a bioscrape simulation result object is returned if it is set to `False`.
"""


#Check model and interface
Expand Down
30 changes: 26 additions & 4 deletions bioscrape/types.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1502,15 +1502,37 @@ cdef class StateDependentVolume(Volume):
############################## #############################

cdef class Model:
def __init__(self, filename = None, species = [], reactions = [],
def __init__(self, sbml_filename = None, filename = None, species = [], reactions = [],
parameters = [], rules = [], initial_condition_dict = None,
sbml_filename = None, input_printout = False,
initialize_model = True, **kwargs):
input_printout = False, initialize_model = True, **kwargs):
"""
Read in a model from a file using old bioscrape XML format (now deprecated), SBML format, or by
specifying the model programmatically using the API.
Model API documentation is available on bioscrape Wiki:
https://github.com/biocircuits/bioscrape/wiki
Args:
sbml_filename (str): The SBML filename to import the model.
Note that you cannot any other arguments when importing from SBML.
You can import the SBML model, then edit the model with the API.
filename (str): The (old bioscrape XML) file to read the model. Recommended way to import
a model is by importing an SBML using `sbml_filename` argument
species (List[str]): A list of species names, when constructing the model.
reaction (List[tuple]): A list of reaction tuples. Each reaction tuple includes a list
of reactants, a list of products, a propensity string,
and the propensity dict.
Refer to the documentation on bioscrape Wiki for more information.
parameters (List[tuples]): A list of tuples where each tuple specifies the parameter name
and a value for the parameter.
rules (List[(tuples)]): A list of tuples where each tuple describe a model rule.
initial_condition_dict (dict): A dictionary of initial conditions where each key is a species name
and the value is the initial condition value.
input_printout (bool, default: False): If True, verbose print statements are printed out.
If False, the print statements are silenced.
initial_model (bool, default: True): If True, the model is initialized =>
Model arrays are created and basic validity checks are run.
If False, the model is not initialized.
:param filename: (str) the file to read the model
"""

########################################################################
Expand Down
33 changes: 12 additions & 21 deletions examples/Advanced Examples and Developer Overview.ipynb

Large diffs are not rendered by default.

62 changes: 32 additions & 30 deletions examples/Basic Examples - START HERE.ipynb

Large diffs are not rendered by default.

91 changes: 62 additions & 29 deletions examples/Benchmarking bioscrape performance.ipynb

Large diffs are not rendered by default.

29 changes: 13 additions & 16 deletions examples/Fast Statistics for SSA Trajectories.ipynb

Large diffs are not rendered by default.

18 changes: 13 additions & 5 deletions examples/Sensitivity Analysis using Bioscrape.ipynb

Large diffs are not rendered by default.

25 changes: 0 additions & 25 deletions examples/sbml_loading.py

This file was deleted.

83 changes: 44 additions & 39 deletions inference examples/Bioscrape Inference - Getting Started.ipynb

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -642,7 +642,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.3"
"version": "3.7.4"
}
},
"nbformat": 4,
Expand Down
12 changes: 6 additions & 6 deletions lineage examples/Lineage Examples.ipynb

Large diffs are not rendered by default.

66 changes: 66 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
[build-system]
requires = ["setuptools>=64", "Cython", "numpy", "wheel"]
build-backend = "setuptools.build_meta"

[tool.distutils.bdist_wheel]
universal = true

[project]
name = "Bioscrape"
version = "1.2.2"
description = "Biological Stochastic Simulation of Single Cell Reactions and Parameter Estimation"
authors = [{name='Ayush Pandey'},
{name='William Poole'},
{name='Anandh Swaminathan'}]
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: Cython',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Topic :: Software Development',
'Topic :: Scientific/Engineering',
'Operating System :: OS Independent',
]
license = {file = "LICENSE"}
readme = "README.md"
keywords=["SBML", "synthetic biology", "modeling",
"Chemical Reaction Network", "CRN simulator", "stochastic",
"parameter inference"]
dependencies = [
"numpy",
"matplotlib",
"pytest",
"scipy",
"cython",
"python-libsbml",
"beautifulsoup4",
"sympy",
"emcee",
"pandas",
"corner",
"lmfit"
]
requires-python = ">=3.7"

[project.optional-dependencies]
test = [
"pytest",
]

[project.urls]
"Homepage" = "https://github.com/biocircuits/bioscrape/"
"Bug Tracker" = "https://github.com/biocircuits/bioscrape/issues"

[tool.setuptools]
packages = ["bioscrape"]
include-package-data = true
package-dir = {"bioscrape"="bioscrape"}

[tool.setuptools.exclude-package-data]
"*" = ["*.c", "*.h"]
Loading

0 comments on commit 18a8135

Please sign in to comment.