### Run Jupyter Notebook for Examples Source: https://github.com/biocircuits/bioscrape/wiki/Installation Launch the Jupyter Notebook server to access and run example notebooks. Ensure you are in the main package directory. ```bash jupyter notebook ``` -------------------------------- ### Install Build Tools on Ubuntu Source: https://github.com/biocircuits/bioscrape/wiki/Installation Installs the g++ compiler and other essential build tools on Ubuntu systems. This command requires administrator privileges. ```bash sudo apt-get install build-essential ``` -------------------------------- ### Install Bioscrape Beta Release Source: https://github.com/biocircuits/bioscrape/blob/master/README.md Install a beta version of Bioscrape by specifying the version number. ```bash pip install bioscrape==1.0.4 ``` -------------------------------- ### Install Bioscrape Package Source: https://github.com/biocircuits/bioscrape/wiki/Installation Use this command to install the bioscrape package from its source directory. Ensure Anaconda and a C++ compiler are installed first. ```bash python setup.py install ``` -------------------------------- ### Setup an ArrayDelayQueue Source: https://github.com/biocircuits/bioscrape/wiki/Delays This code demonstrates how to set up an ArrayDelayQueue for managing delayed reactions. Parameters control the queue's capacity and temporal resolution. ```python q = ArrayDelayQueue.setup_queue(num_reactions, num_timepoints, dt) ``` -------------------------------- ### Log Uniform Prior Example Source: https://github.com/biocircuits/bioscrape/wiki/Parameter-Inference Sets a log-uniform prior distribution for a parameter, defined by a lower and upper bound. ```python {'k1': ['log-uniform', 5, 10]} ``` -------------------------------- ### Gaussian Prior Example Source: https://github.com/biocircuits/bioscrape/wiki/Parameter-Inference Sets a Gaussian prior distribution for a parameter, specifying the mean and standard deviation. ```python {'k1': ['gaussian', 0, 10]} ``` -------------------------------- ### Model Setup and Simulation with Parameter Conditions Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/Bioscrape Inference - Getting Started.ipynb Sets up a bioscrape model with species, reactions, and parameters. It then simulates the model's output under various parameter conditions, plotting the results to visualize the effect of parameter changes. ```python import bioscrape as bs from bioscrape.types import Model from bioscrape.simulator import py_simulate_model import numpy as np import pylab as plt import pandas as pd species = ['I','X'] reactions = [(['X'], [], 'massaction', {'k':'d1'}), ([], ['X'], 'hillpositive', {'s1':'I', 'k':'k1', 'K':'KR', 'n':2})] k1 = 50.0 d1 = 0.5 params = [('k1', k1), ('d1', d1), ('KR', 20)] initial_condition = {'X':0, 'I':0} M = Model(species = species, reactions = reactions, parameters = params, initial_condition_dict = initial_condition) num_trajectories = 4 # each with different initial condition parameter_condition_list = [{'d1':0.01},{'d1':0.1},{'d1':1},{'d1':10}] timepoints = np.linspace(0,5,100) result_list = [] M.set_species({"I":20}) for param_cond in parameter_condition_list: M.set_params(param_cond) result = py_simulate_model(timepoints, Model = M)['X'] result_list.append(result) plt.plot(timepoints, result, label = 'd1 =' + str(list(param_cond.values())[0])) plt.xlabel('Time') plt.ylabel('[X]') plt.legend() plt.show() ``` -------------------------------- ### Log Gaussian Prior Example Source: https://github.com/biocircuits/bioscrape/wiki/Parameter-Inference Sets a log-Gaussian prior distribution for a parameter, specifying the mean and standard deviation. ```python {'k1': ['log-gaussian', 0, 10]} ``` -------------------------------- ### Install Emcee Package with Conda Source: https://github.com/biocircuits/bioscrape/wiki/Installation Install the 'emcee' package, a Python library for affine-invariant Markov chain Monte Carlo (MCMC) exploration, using the astropy channel on Anaconda. ```bash conda install -c astropy emcee ``` -------------------------------- ### Install Bioscrape using pip Source: https://github.com/biocircuits/bioscrape/wiki/Installation Use this command to install Bioscrape and its dependencies. This method requires a configured C++ compiler. ```bash pip install bioscrape ``` -------------------------------- ### Model Setup and Trajectory Generation Source: https://github.com/biocircuits/bioscrape/blob/master/tests/Likelihood and Data Objects.ipynb Sets up a simple bioscape model, generates multiple noisy trajectories with optional variations in initial conditions and timepoints, and prepares the data for log-likelihood calculations. Requires bioscape, numpy, and pylab. ```python import bioscrape as bs from bioscrape.types import Model from bioscrape.simulator import py_simulate_model import numpy as np import pylab as plt #Create a Model species = ["X"] reactions = [(["X"], [], "massaction", {"k":"d1"}), ([], ["X"], "massaction", {"k":"k1"})] k1 = 10.0 d1 = .2 params = [("k1", k1), ("d1", d1)] initial_condition = {"X":0} M = Model(species = species, reactions = reactions, parameters = params, initial_condition_dict = initial_condition) M.py_initialize() N = 10 #Number of trajectories nT = 50 #number of timepoints noise_std = 5 #Standar deviation of the guassian noise added onto the measurements MultipleTimepoints = True #Different timepoints for each trajectory? timepoint_list = [] timepoints = np.linspace(np.random.randint(0, 10), np.random.randint(10, 100), nT) #Generate Trajectories R = [] #Results as Pandas Dataframes Data = [] #Results will become a numpy array MultipleInitialConditions = True #Different initial conditions for each trajectory? X0_list = [] #multiple initial conditions will be saved for inference for n in range(N): if MultipleInitialConditions: initial_condition = {"X": np.random.randint(0, 100)} X0_list.append(initial_condition) if MultipleTimepoints: timepoints = np.linspace(np.random.randint(0, 10, 1), np.random.randint(10, 100, 1), num = 50).flatten() timepoint_list.append(timepoints) M.set_species(initial_condition) r = py_simulate_model(timepoints, Model = M, stochastic = True) R.append(r) noisy_data = r["X"].to_numpy() + np.random.normal(loc = 0, scale = noise_std, size = nT) Data.append(noisy_data) #Plot Results plt.figure() Data = np.array(Data) Data = np.reshape(Data, ( np.shape(Data)+ (1,))) # To make sure Data has shape - N X T X M (where M = len(measured_species)) for n in range(N): plt.plot(R[n]['time'], R[n]["X"], color = (n/N, 0, 1-n/N)) plt.plot(R[n]['time'], Data[n], 'o', color = (n/N, 0, 1-n/N)) _ = plt.xlabel("time") _ = plt.ylabel("X") ``` -------------------------------- ### Initialize Sensitivity Analysis Object Source: https://github.com/biocircuits/bioscrape/blob/master/examples/Sensitivity Analysis using Bioscrape.ipynb Creates a SensitivityAnalysis object for a given model and computes the Jacobian matrix. This is a setup step for more advanced sensitivity computations. ```python from bioscrape.analysis import SensitivityAnalysis sens_obj = SensitivityAnalysis(M) sens_obj.compute_J(states) ``` -------------------------------- ### Uniform Prior Example Source: https://github.com/biocircuits/bioscrape/wiki/Parameter-Inference Sets a uniform prior distribution for a parameter. The prior is defined by a lower and upper bound. ```python {'k1': ['uniform', 0,10]} ``` -------------------------------- ### Exponential Prior Example Source: https://github.com/biocircuits/bioscrape/wiki/Parameter-Inference Sets an exponential prior distribution for a parameter. The parameter required is the inverse of the mean. ```python {'k1': ['exponential', 5]} ``` -------------------------------- ### Run Unit Tests with Pytest Source: https://github.com/biocircuits/bioscrape/wiki/Installation Execute the unit test suite to verify the installation. Navigate to the bioscrape root directory before running this command. ```bash pytest ``` -------------------------------- ### Parameter Inference Setup Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/Bioscrape Inference - Getting Started.ipynb Initializes the parameter inference process using Bioscrape's py_inference function. It loads experimental data, defines a prior distribution for parameters, and specifies simulation settings. ```python from bioscrape.inference import py_inference # Import data from CSV # Import a CSV file for each experiment run exp_data = [] for i in range(num_trajectories): df = pd.read_csv('data/birth_death_data_multiple_param_conditions.csv', usecols = ['timepoints', 'X'+str(i)]) df.columns = ['timepoints', 'X'] exp_data.append(df) prior = {'k1' : ['uniform', 0, 100]} sampler, pid = py_inference(Model = M, exp_data = exp_data, measurements = ['X'], time_column = ['timepoints'], parameter_conditions = parameter_condition_list, nwalkers = 5, init_seed = 0.15, nsteps = 2000, sim_type = 'deterministic', convergence_check=True, params_to_estimate = ['k1'], prior = prior) ``` -------------------------------- ### Install Xcode Command Line Tools on macOS Source: https://github.com/biocircuits/bioscrape/wiki/Installation Installs the Xcode command line tools, which include the g++ compiler and other necessary development utilities on macOS. This is required if 'g++' is not found in the terminal. ```bash xcode-select --install ``` -------------------------------- ### Simulating Multiplicative Volume Event with Mass Action Source: https://github.com/biocircuits/bioscrape/blob/master/lineage tests/Event and Rule Testing.ipynb This example demonstrates a lineage model with a multiplicative volume event. It configures reactions and the model, then uses an SSA simulator to produce and plot simulation results, including species concentration and volume. ```python LM2 = LineageModel(reactions = rxns, initialize_model = True, initial_condition_dict = {"X": 0, "A":2}) LM2.create_volume_event("multiplicative", {"growth_rate":g/10}, "massaction", {"k":.1, "species":"X"}, print_out = False) LM2.py_initialize() print("Simulating Model 2") stoch_result = ssa_simulator.py_SimulateSingleCell(timepoints, Model = LM2) stoch_sim_output = stoch_result.py_get_result() X_ind = LM2.get_species_index('X') volume = stoch_result.py_get_volume() plt.figure() plt.title("Multiplicative Volume Event with unimolecular(X) massaction propensity") plt.plot(timepoints, stoch_sim_output[:, X_ind], label = "X") plt.plot(timepoints, volume, label = "Volume") plt.legend() ``` -------------------------------- ### Basic Plotting Configuration and Imports Source: https://github.com/biocircuits/bioscrape/blob/master/examples/Advanced Examples and Developer Overview.ipynb Sets up plotting configurations using Matplotlib and imports the NumPy library for numerical operations. This is a foundational step for running examples in the BioSCRAPE package. ```python %matplotlib inline import matplotlib.pyplot as plt import matplotlib as mpl #%config InlineBackend.figure_f.ormats=['svg'] mpl.rc('axes', prop_cycle=(mpl.cycler('color', ['r', 'k', 'b','g','y','m','c']) )) mpl.rc('xtick', labelsize=12) mpl.rc('ytick', labelsize=12) import numpy as np ``` -------------------------------- ### Simulate Gene Expression Model with Delay Source: https://github.com/biocircuits/bioscrape/blob/master/examples/Advanced Examples and Developer Overview.ipynb Simulates a gene expression model with delays using DelaySSASimulator and ArrayDelayQueue. Requires setup of the delay queue and passing it to the simulation function. Results are then retrieved and plotted. ```python # Simulate the simple gene expression model WITH delay. # import a couple of additional types that we need from bioscrape.simulator import ArrayDelayQueue from bioscrape.simulator import DelaySSASimulator # Create a delay queue with setup_queue(num_reactions, num_timepoints, dt) # so this delay queue will go up to 1500 * 0.01 = 15 time units in the future. # You want to pick the delay queue resolution to be small for accuracy, and then # have enough time points to capture the maximum length delay that could possibly # occur. q = ArrayDelayQueue.setup_queue(4,1500,0.01) # Like before when we created an SSA simulator, now we create a DelaySSASimulator delay_simulator = DelaySSASimulator() # Simulate just like before, but now we need to pass the DelayQueue q as an # extra argument. The delayqueue is part of the initial state as well, as any # reactions already on the queue will occur. # In this case, however, the queue is empty to begin with. answer = delay_simulator.py_delay_simulate(s,q,timepoints) # Recover the state trajctory from the simulation. state = answer.py_get_result() mrna_ind = m.get_species_index('mRNA') prot_ind = m.get_species_index('protein') # Plot the mRNA plt.plot(timepoints,state[:,mrna_ind]) plt.xlim((0,120)) plt.xlabel('Time') plt.ylabel('mRNA') # Plot the Protein plt.figure() plt.plot(timepoints,state[:,prot_ind]) plt.xlim((0,120)) plt.xlabel('Time') plt.ylabel('Protein') ``` -------------------------------- ### Running Bayesian Inference with Bioscrape Source: https://github.com/biocircuits/bioscrape/wiki/Examples Perform Bayesian inference to identify model parameters using experimental data. This example demonstrates loading an SBML model and experimental data, defining priors, and running the inference using MCMC. ```python from bioscrape.types import Model import pandas as pd from bioscrape.inference import py_inference # Load an SBML model # (you can get this file in `inference examples/models/` directory) M = Model(sbml_filename='toy_sbml_model.xml') # Load experimental data # (you can find test data in `inference examples/data/` directory) df = pd.read_csv('test_data.csv', delimiter = '\t', names = ['X','time'], skiprows = 1) # Use built-in priors, # For 'd1': a Gaussian distribution of mean 0.2 and standard deviation of 20, # while ensuring the parameter remains positive # For 'k1': a Uniform distribution with minimum value 0 and maximum value 100 prior = {'d1' : ['gaussian', 0.2, 20, 'positive'], 'k1' : ['uniform', 0, 100]} # Run Bayesian inference sampler, pid = py_inference(Model = M, exp_data = df, measurements = ['X'], time_column = ['time'], nwalkers = 20, nsteps = 5500, params_to_estimate = ['d1', 'k1'], prior = prior) # A sampler object containing all samples is returned. # The pid object consists of various utilities for further analysis. # This will plot the resulting posterior parameter distributions as well. ``` -------------------------------- ### Clone Bioscrape Repository Source: https://github.com/biocircuits/bioscrape/wiki/Installation Clone the Bioscrape repository to access example notebooks and other resources locally. This is an alternative to pip installation. ```bash git clone https://github.com/biocircuits/bioscrape/ ``` -------------------------------- ### Display Initial Conditions List Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/individual examples/Multiple trajectories initial conditions.ipynb Shows the list of initial conditions used for the simulations. This is useful for verification. ```python initial_condition_list ``` -------------------------------- ### Install Specific Bioscrape Version Source: https://github.com/biocircuits/bioscrape/blob/master/README.md Install a particular tagged stable release of Bioscrape by specifying the version number. ```bash pip install bioscrape==1.2.2 ``` -------------------------------- ### Install Latest Bioscrape Version Source: https://github.com/biocircuits/bioscrape/blob/master/README.md Use this command to install the most recent stable release of Bioscrape via pip. ```bash $ pip install bioscrape ``` -------------------------------- ### Initialize Bioscrape Model and Simulator Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/individual examples/Multiple trajectories.ipynb Imports necessary libraries and loads a SBML model for simulation. Ensure 'toy_sbml_model.xml' is available in the working directory. ```python %matplotlib inline import bioscrape as bs from bioscrape.types import Model from bioscrape.simulator import py_simulate_model import numpy as np import pylab as plt import pandas as pd M = Model(sbml_filename = 'toy_sbml_model.xml') ``` -------------------------------- ### Update Conda and Anaconda Source: https://github.com/biocircuits/bioscrape/wiki/Installation Update your Anaconda installation to ensure you have the latest versions of conda and anaconda. These commands are optional if Anaconda was just installed. ```bash conda update conda conda update anaconda ``` -------------------------------- ### Simulate Model with PySimulate Source: https://github.com/biocircuits/bioscrape/blob/master/tests/Saving and loading SBML and Bioscrape XML.ipynb Sets up timepoints and simulates the loaded SBML model using `py_simulate_model`. Ensure the model is properly loaded before simulation. ```python from bioscrape.simulator import py_simulate_model timepoints = np.linspace(0,10000,100) results = py_simulate_model(timepoints, Model = M) ``` -------------------------------- ### Install Python-LibSBML with Conda Source: https://github.com/biocircuits/bioscrape/wiki/Installation Install the 'python-libsbml' package, which is necessary for loading and saving SBML model files, using the sbmlteam channel on Anaconda. ```bash conda install -c sbmlteam python-libsbml ``` -------------------------------- ### Initialize Model and Data for Inference Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/individual examples/Priors in Bioscrape Inference.ipynb Sets up the Bioscrape model and experimental data, defining species and initial conditions before parameter inference. ```python %matplotlib inline import bioscrape as bs from bioscrape.types import Model from bioscape.inference import py_inference import numpy as np import pylab as plt import pandas as pd # Import a bioscrape/SBML model M = Model(sbml_filename = '../models/toy_sbml_model.xml') # Import data from CSV # Import a CSV file for each experiment run df = pd.read_csv('../data/test_data.csv', delimiter = '\t', names = ['X','time'], skiprows = 1) M.set_species({'X':df['X'][0]}) ``` -------------------------------- ### Initialize simulation performance dictionary Source: https://github.com/biocircuits/bioscrape/blob/master/examples/Benchmarking bioscrape performance.ipynb Initializes a dictionary to store simulation performance metrics. ```python sim_performance = {} ``` -------------------------------- ### Build Lineage Model with Death Rules Source: https://github.com/biocircuits/bioscrape/blob/master/lineage examples/Lineage Examples.ipynb Initializes a LineageModel with species, division, growth, and death rules. Use this to define the behavior of cells in a simulation. ```python from bioscrape.lineage import LineageModel, LineageVolumeSplitter #For building our Model from bioscrape.lineage import py_SimulateCellLineage import numpy as np import pylab as plt import time as pytime from time import process_time #Load Toggle CRN vsplit_options = { "default":"binomial", "volume":"binomial", "dna_lacI_tetR":"duplicate", "dna_tetR_lacI":"duplicate" } copy_number = 1 x0 = {"dna_lacI_tetR": copy_number, "dna_tetR_lacI":copy_number} Mtoggle_rules = LineageModel(sbml_filename = "ToggleCRN.xml", initial_condition_dict = x0) print("Species in Mtoggle", list(Mtoggle_rules.get_species())) g = .015 vsplit = LineageVolumeSplitter(Mtoggle_rules, options = vsplit_options) #Model Division and Volume with Deterministic Rules Delta = 1 Mtoggle_rules.create_division_rule("deltaV", {"threshold":Delta}, vsplit) Mtoggle_rules.create_volume_rule("linear", {"growth_rate":g}) #If either protein exceeds the count of 1000, the cell dies Mtoggle_rules.create_death_rule("species", {"specie":"protein_tetR", "threshold":2500, "comp":">") Mtoggle_rules.create_death_rule("species", {"specie":"protein_lacI", "threshold":2500, "comp":">") ``` -------------------------------- ### Install Python-LibSBML with Pip for Python 3.8 Source: https://github.com/biocircuits/bioscrape/wiki/Installation If you are using Python 3.8, you may need to install a specific version of 'python-libsbml' using pip instead of conda. ```bash pip install python-libsbml ``` -------------------------------- ### Setting up SBML File Paths and Lineage Models Source: https://github.com/biocircuits/bioscrape/blob/master/lineage tests/Interacting Lineages via SBML.ipynb This snippet initializes SBML file paths and creates `LineageModel` objects. It dynamically selects SBML files based on the number of cells (N) and handles potential `ValueError` for invalid N. ```python %matplotlib inline import bioscrape as bs import libsbml from bioscrape.lineage import py_SimulateInteractingCellLineage from bioscrape.lineage import py_SimulateSingleCell from bioscrape.lineage import LineageModel import numpy as np import pylab as plt #Number of cells N = 20 sbml_file_path = "C:\\Users\\wp_ix\\OneDrive\\Caltech\\Code\\bioscrape lineages\\sbml models\" f1 = "cell_to_cell_comm_model_1.xml" f2 = "cell_to_cell_comm_model_2.xml" f5 = "cell_to_cell_comm_model_5.xml" f20 = "cell_to_cell_comm_model_10.xml" f100 = "cell_to_cell_comm_model_100.xml" sbml_file1 = sbml_file_path+f1 if N == 1: sbml_file2 = sbml_file_path+f1 elif N == 2: sbml_file2 = sbml_file_path+f2 elif N == 5: sbml_file2 = sbml_file_path+f5 elif N == 20: sbml_file2 = sbml_file_path+f20 elif N == 100: sbml_file2 = sbml_file_path+f100 else: raise ValueError("Invalid Value of N") M1 = LineageModel(sbml_filename = sbml_file1) M2 = LineageModel(sbml_filename = sbml_file2) print(M2.get_species()) timepoints = np.arange(0, 50, .001) results2 = py_SimulateSingleCell(timepoints, Model = M2) data_crn = results2 print(data_crn.shape) print(timepoints[-1]) global_sync_period = .01 lineage = py_SimulateInteractingCellLineage(timepoints, global_sync_period, models = [M1], initial_cell_states = [N], global_species = ["A", "B"], global_species_method = 3) data_approx = [] print("lineages returned:", lineage.py_size()) for i in range(lineage.py_size()): sch = lineage.py_get_schnitz(i) data_approx.append(sch.py_get_dataframe(Model = M1)) t = sch.py_get_time() print("i=", i, "t0=", t[0], "tf=", t[1], "len(t)=", len(t))#, t.shape, t) #for j in range(6): #print("\tj=", j ,sch.py_get_data()[:, j]) print([data_approx[i].shape for i in range(N)]) ``` -------------------------------- ### Install Core Python Dependencies with Conda Source: https://github.com/biocircuits/bioscrape/wiki/Installation Install essential Python packages required for BioScrape using the Anaconda package manager. This includes libraries for scientific computing, data manipulation, and visualization. ```bash conda install -c anaconda lxml beautifulsoup4 numpy scipy cython jupyter matplotlib sympy pandas ``` -------------------------------- ### Define Lineage Model Parameters Source: https://github.com/biocircuits/bioscrape/blob/master/lineage tests/Interacting Lineage Tests.ipynb Sets up the species, parameters, reactions, and rules for a lineage model, including volume and death events. ```python import numpy as np import pylab as plt from bioscrape.lineage import LineageModel from bioscrape.lineage import LineageVolumeSplitter from bioscrape.lineage import py_SimulateInteractingCellLineage from bioscrape.lineage import py_SimulateSingleCell species = ["Abx", "aux"] kC, KC = .5, 10 D, d = .02, .01 kaux, daux = 10., .1 kAbx, KAbx = 5, 10 parameters = [("kC", kC), ("KC", KC), ("D", D), ("d", d), ("kaux", kaux), ("daux", daux), ("kAbx", kAbx), ("KAbx", KAbx)] x0 = {"Abx":0, "aux":0} rxn1 = ([], ["Abx"], "hillpositive", {"k":"kAbx", "K":"KAbx", "s1":"aux", "n":2}) # 0 --> Abx rxn2 = (["Abx"], [], "massaction", {"k":"d"}) #Abx --> 0 rxn3 = ([], ["aux"], "general", {"rate":"_kaux"}) #0 --> aux rxn4 = (["aux"], [], "massaction", {"k":"daux"}) #aux --> 0 reactions = [rxn1, rxn2, rxn3, rxn4] M1 = LineageModel(species = species, parameters = parameters, reactions = reactions, initial_condition_dict = x0) M1.create_volume_rule("ode", {"equation": "_kC*1/(1+(Abx/_KC)^2)"}) M1.create_division_rule("deltaV", {"threshold":1}, LineageVolumeSplitter(M1)) M1.create_death_event("death", {}, "general", {"rate":"_D"}) ``` -------------------------------- ### Run Stochastic MCMC for Parameter Identification Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/individual examples/Stochastic Inference.ipynb This snippet shows how to import experimental data, define priors, and run the py_inference function for stochastic MCMC parameter identification. It sets up the model, experimental data, and specifies parameters to estimate. ```python from bioscrape.inference import py_inference # Import data from CSV # Import a CSV file for each experiment run exp_data = [] for i in range(num_trajectories): df = pd.read_csv('../data/birth_death_data_multiple_conditions.csv', usecols = ['timepoints', 'X'+str(i)]) df.columns = ['timepoints', 'X'] exp_data.append(df) prior = {'k1' : ['uniform', 0, 100]} sampler, pid = py_inference(Model = M, exp_data = exp_data, measurements = ['X'], time_column = ['timepoints'], nwalkers = 15, init_seed = 0.15, nsteps = 5000, sim_type = 'stochastic', params_to_estimate = ['k1'], prior = prior, plot_show = False, convergence_check = False) ``` -------------------------------- ### Get Autocorrelation Time Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/individual examples/Linear Model.ipynb Retrieves the autocorrelation time for the MCMC chains. This value is crucial for assessing chain convergence. ```python pid.autocorrelation_time ``` -------------------------------- ### Parameter Variable Prefix in General Equations Source: https://github.com/biocircuits/bioscrape/wiki/BioSCRAPE-XML Indicates a parameter defined in the XML model. Variables starting with an underscore '_' refer to these parameters. ```xml _k ``` -------------------------------- ### Benchmark libRoadRunner deterministic simulation Source: https://github.com/biocircuits/bioscrape/blob/master/examples/Benchmarking bioscrape performance.ipynb Loads the same SBML model using libRoadRunner, runs a deterministic simulation, and records the time taken. The simulation results are plotted, and performance is stored. ```python rr = roadrunner.RoadRunner("models/repressilator_sbml.xml") t0 = time.time() results = rr.simulate(0, 200, 200000) tf = time.time() plt.title("Time taken = {:0.3f} seconds".format(tf-t0)) plt.ylabel("Species (concentration)") plt.xlabel("Time") rr.plot() sim_performance["roadrunner"] = {} sim_performance["roadrunner"]["deterministic"] = tf-t0 ``` -------------------------------- ### Import necessary packages for bioscrape and simulation Source: https://github.com/biocircuits/bioscrape/blob/master/examples/Benchmarking bioscrape performance.ipynb Imports required libraries for bioscrape, simulation, plotting, and time measurement. Ensure libroadrunner is installed. ```python #Import all packages ### NOTE: Make sure that you install libroadrunner by running `pip install libroadrunner` to run this notebook #### import matplotlib.pyplot as plt import time from bioscrape.types import Model from bioscrape.simulator import ModelCSimInterface, DeterministicSimulator, SSASimulator import roadrunner import numpy as np ``` -------------------------------- ### Positive Gaussian Prior Example Source: https://github.com/biocircuits/bioscrape/wiki/Parameter-Inference Sets a Gaussian prior distribution for a parameter that only accepts positive values. This is achieved by appending the 'positive' keyword. ```python {'k1': ['gaussian', 0, 10, 'positive']} ``` -------------------------------- ### Create Reaction with Mass-Action Propensity Source: https://github.com/biocircuits/bioscrape/wiki/Propensities Use this to create a reaction with a mass-action propensity. It requires a list of reactants, products, the propensity type 'massaction', and a dictionary for parameters like 'k'. ```python reaction = Reaction(list_of_reactants, list_of_products, "massaction", {"k":"k1"}) ``` -------------------------------- ### Import SBML Model and Estimate Single Parameter Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/Bioscrape Inference - Getting Started.ipynb Imports an SBML model and experimental data, sets an initial species value, defines a Gaussian prior for parameter 'd1', and performs MCMC inference to estimate 'd1'. ```python import bioscrape as bs from bioscrape.types import Model from bioscrape.inference import py_inference import numpy as np import pylab as plt import pandas as pd # Import a bioscrape/SBML model M = Model(sbml_filename = 'models/toy_sbml_model.xml') # Import data from CSV # Import a CSV file for each experiment run df = pd.read_csv('data/test_data.csv', delimiter = '\t', names = ['X','time'], skiprows = 1) M.set_species({'X':df['X'][0]}) # Create prior for parameters prior = {'d1' : ['gaussian', 0.2, 200]} sampler, pid = py_inference(Model = M, exp_data = df, measurements = ['X'], time_column = ['time'], nwalkers = 5, init_seed = np.array([2]), nsteps = 3000, sim_type = 'deterministic', params_to_estimate = ['d1'], prior = prior) ``` -------------------------------- ### Simulate Toggle Switch Model Source: https://github.com/biocircuits/bioscrape/blob/master/examples/Sensitivity Analysis using Bioscrape.ipynb Defines and simulates a toggle switch model using bioscrape. Requires numpy and matplotlib for setup and visualization. ```python import numpy as np from bioscrape.types import Model from bioscrape.simulator import py_simulate_model # Toggle Switch dynamics species = ["m_t", "m_l", "p_t", "p_l"] params = [("K",100),("b_t",50),("b_l",10),("d_t",5),("d_l",5), ("del_t",0.01), ("del_l",0.02), ("beta_t", 0.02), ("beta_l", 0.01)] rxn1 = ([], ["m_t"], "hillnegative", {"s1":"p_l", "k":"K", "K":"b_t", "n":2}) rxn2 = (["m_t"],[], "massaction", {"k":"d_t"}) rxn3 = ([], ["m_l"], "hillnegative", {"s1":"p_t", "k":"K", "K":"b_l", "n":2}) rxn4 = (["m_l"],[], "massaction", {"k":"d_l"}) rxn5 = (["p_t"],[], "massaction", {"k":"del_t"}) rxn6 = ([], ["p_t"], "general", {"rate":"beta_t*m_t"}) rxn7 = (["p_l"],[], "massaction", {"k":"del_l"}) rxn8 = ([], ["p_l"], "general", {"rate":"beta_l*m_l"}) reactions = [rxn1, rxn2, rxn3, rxn4, rxn5, rxn6, rxn7, rxn8] x0 = {"m_t":1e-5, "m_l":1e-5, "p_t":1e-5, "p_l":1e-5} M = Model(species = species, parameters = params, reactions = reactions, initial_condition_dict = x0) timepoints = np.linspace(0,100,100) %matplotlib inline import matplotlib.pyplot as plt import matplotlib as mpl #%config InlineBackend.figure_f.ormats=['svg'] color_list = ['b', 'orange', 'b','g','y','m','c'] mpl.rc('axes', prop_cycle=(mpl.cycler('color', color_list) )) mpl.rc('xtick', labelsize=20) mpl.rc('ytick', labelsize=20) solutions = py_simulate_model(timepoints, Model = M, stochastic = False) plt.plot(timepoints, solutions['p_t'], lw = 4,label = "TetR") plt.plot(timepoints, solutions['p_l'], lw = 4, label = "LacI") plt.legend(fontsize = 20) plt.xlabel('Time', fontsize = 20) plt.ylabel('Concentration', fontsize = 20); ``` -------------------------------- ### Run MCMC Inference with Initial Seed Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/Bioscrape Inference - Getting Started.ipynb This snippet demonstrates how to initialize and run the MCMC sampler with a numpy array specifying initial parameter values. Ensure you have your model and experimental data prepared. ```python from bioscrape.inference import py_inference # Import data from CSV # Import a CSV file for each experiment run exp_data = [] for i in range(num_trajectories): df = pd.read_csv('data/birth_death_data.csv', usecols = ['timepoints', 'X'+str(i)]) df.columns = ['timepoints', 'X'] exp_data.append(df) prior = {'k1' : ['uniform', 0, 100],'d1' : ['uniform',0,10]} sampler, pid = py_inference(Model = M, exp_data = exp_data, measurements = ['X'], time_column = ['timepoints'], nwalkers = 5, init_seed = np.array([20, 2]), nsteps = 5000, sim_type = 'deterministic', params_to_estimate = ['k1', 'd1'], prior = prior) ``` -------------------------------- ### Basic Pytest Test Example Source: https://github.com/biocircuits/bioscrape/blob/master/tests/How to write bioscrape tests.ipynb A simple Pytest test function demonstrating a basic assertion. This is useful for ensuring old bugs stay squashed. ```python def inc(x): return x + 1 def test_answer(): assert inc(3) == 5 ``` -------------------------------- ### Plotting MCMC Simulation Results Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/individual examples/Multiple trajectories initial conditions.ipynb Plots simulation results based on MCMC samples. This is a repeat of the first plotting example, likely for verification or demonstration. ```python M_fit = M timepoints = pid.timepoints[0] flat_samples = sampler.get_chain(discard=200, thin=15, flat=True) inds = np.random.randint(len(flat_samples), size=200) for init_cond in initial_condition_list: for ind in inds: sample = flat_samples[ind] for pi, pi_val in zip(pid.params_to_estimate, sample): M_fit.set_parameter(pi, pi_val) M_fit.set_species(init_cond) plt.plot(timepoints, py_simulate_model(timepoints, Model= M_fit)['X'], "C1", alpha=0.6) # plt.errorbar(, y, yerr=yerr, fmt=".k", capsize=0) for i in range(num_trajectories): plt.plot(timepoints, list(pid.exp_data[i]['X']), 'b', alpha = 0.1) plt.plot(timepoints, result_list[i], "k") # plt.legend(fontsize=14) plt.xlabel("Time") plt.ylabel("[X]"); ``` -------------------------------- ### Initialize Model and Run MCMC Inference Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/individual examples/Birth death model.ipynb Initializes a bioscrape Model, loads experimental data, sets up priors, and runs the MCMC parameter identification procedure to estimate 'd1' and 'k1'. ```python %matplotlib inline import bioscrape as bs from bioscrape.types import Model from bioscrape.inference import py_inference import numpy as np import pylab as plt import pandas as pd # Import a bioscrape/SBML model M = Model(sbml_filename = '../models/toy_sbml_model.xml') # Import data from CSV # Import a CSV file for each experiment run df = pd.read_csv('../data/test_data.csv', delimiter = '\t', names = ['X','time'], skiprows = 1) M.set_species({'X':df['X'][0]}) prior = {'d1' : ['gaussian', 0.2, 20], 'k1' : ['uniform', 0, 100]} sampler, pid = py_inference(Model = M, exp_data = df, measurements = ['X'], time_column = ['time'], nwalkers = 20, init_seed = 0.15, nsteps = 5500, sim_type = 'deterministic', params_to_estimate = ['d1', 'k1'], prior = prior) ``` -------------------------------- ### Get Parameter Dictionary Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/individual examples/Inference with Delay Models.ipynb Retrieves the current parameter dictionary of the delay model. This is useful for inspecting the estimated or default parameter values after an inference procedure. ```python M_delay.get_parameter_dictionary() ``` -------------------------------- ### Import Libraries and Setup Plotting Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/Inference with Delay Models.ipynb Imports necessary libraries for numerical operations, plotting, and Bioscrape simulation. Sets up inline plotting and high-resolution figure formatting. ```python import numpy as np import pandas as pd # Plotting code: %matplotlib inline %config InlineBackend.figure_format = "retina" from matplotlib import rcParams rcParams["savefig.dpi"] = 100 rcParams["figure.dpi"] = 100 rcParams["font.size"] = 20 import matplotlib.pyplot as plt ``` -------------------------------- ### Setting Up Cell Division and Death Events Source: https://github.com/biocircuits/bioscrape/blob/master/lineage examples/Lineage Examples.ipynb Configures a LineageModel with stochastic growth, division, and death events. It specifies volume splitting options and uses 'massaction' for growth/division and 'hillpositive' for death. ```python #Use the Same Parameters for both cell types g = .005 kgrow = 1. kdeath = 1.0 Kdeath = 2500 x0 = {"dna_lacI_tetR": copy_number, "dna_tetR_lacI":copy_number} Mtoggle_events = LineageModel(sbml_filename = "ToggleCRN.xml", initial_condition_dict = x0) vsplit_options = { "default":"binomial", "volume":"binomial", "dna_lacI_tetR":"duplicate", "dna_tetR_lacI":"duplicate" } vsplit = LineageVolumeSplitter(Mtoggle_events, options = vsplit_options) #Mtoggle_events.create_division_rule("deltaV", {"threshold":1.0}, vsplit) Mtoggle_events.create_volume_event("linear volume", {"growth_rate":g}, "massaction", {"k":kgrow, "species":""}) Mtoggle_events.create_division_event("division", {}, "massaction", {"k":kgrow/1000., "species":""}, vsplit) #Too much waste and the cell dies Mtoggle_events.create_death_event("death", {}, "hillpositive", {"k":kdeath, "s1":"protein_lacI", "n":4, "K":Kdeath}) Mtoggle_events.create_death_event("death", {}, "hillpositive", {"k":kdeath, "s1":"protein_tetR", "n":4, "K":Kdeath}) ``` -------------------------------- ### Simulate Cell Lineage and Get Schnitzes Source: https://github.com/biocircuits/bioscrape/blob/master/lineage examples/Lineage Examples.ipynb Simulates cell lineage over specified timepoints and retrieves cell data organized by generation. This is useful for analyzing population dynamics. ```python from time import process_time #Do the simulation! timepoints = np.arange(0, 800, 1.0) print("Simulating") ts = process_time() lineage = py_SimulateCellLineage(timepoints = timepoints, Model = Mtoggle_rules) te = process_time() print("Simulation C=complete in", te-ts, "s") #Lineage objects effectively trees. They contain a are lists of Schnitzes, each with a parent and 2 daughters (which could be none) #For analysis and plotting purposes, it can be effective to use the function get_schnitzes_by_generation #this returns a list of lists where the ith entry is a list of all Schnitzes of generation i sch_tree = lineage.get_schnitzes_by_generation() print("Total Cells Simulated = ", sum([len(L) for L in sch_tree]),"\nCells of each generation:", [len(L) for L in sch_tree]) ``` -------------------------------- ### Simulating General Volume Event with Mass Action Source: https://github.com/biocircuits/bioscrape/blob/master/lineage tests/Event and Rule Testing.ipynb This snippet illustrates a lineage model incorporating a general volume event defined by a custom equation. It initializes the model, simulates using SSA, and plots the resulting species concentration and volume. ```python LM3 = LineageModel(reactions = rxns, initialize_model = False, initial_condition_dict = {"X": 0, "A":2}) LM3.create_volume_event("general", {"equation": "volume+"+".01*(X-20)^2"}, "massaction", {"k":.1, "species":"X"}) LM3.py_initialize() print("Simulating Model 3") stoch_result = ssa_simulator.py_SimulateSingleCell(timepoints, Model = LM1) stoch_sim_output = stoch_result.py_get_result() X_ind = LM3.get_species_index('X') volume = stoch_result.py_get_volume() plt.figure() plt.title("GeneralVolumeEvent (v = v+.01*(X-20)^2) with a first order massaction hill function of X") plt.plot(timepoints, stoch_sim_output[:, X_ind], label = "X") plt.plot(timepoints, volume, label = "Volume") plt.legend() ``` -------------------------------- ### Initialize Bioscrape Model and Run Inference Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/individual examples/Priors in Bioscrape Inference.ipynb Loads a bioscrape model and experimental data, then sets up and runs a Markov Chain Monte Carlo (MCMC) parameter inference procedure. This snippet demonstrates how to define a Gaussian prior for a specific parameter. ```python %matplotlib inline import bioscrape as bs from bioscrape.types import Model from bioscape.inference import py_inference import numpy as np import pylab as plt import pandas as pd # Import a bioscrape/SBML model M = Model(sbml_filename = '../models/toy_sbml_model.xml') # Import data from CSV # Import a CSV file for each experiment run df = pd.read_csv('../data/test_data.csv', delimiter = '\t', names = ['X','time'], skiprows = 1) M.set_species({'X':df['X'][0]}) # Create prior for parameters prior = {'d1' : ['gaussian', 0.2, 200, 'positive']} sampler, pid = py_inference(Model = M, exp_data = df, measurements = ['X'], time_column = ['time'], nwalkers = 5, init_seed = 0.15, nsteps = 1500, sim_type = 'deterministic', params_to_estimate = ['d1'], prior = prior) ``` -------------------------------- ### Species Variable Naming in General Equations Source: https://github.com/biocircuits/bioscrape/wiki/BioSCRAPE-XML Represents a species within the XML model. Variables starting with a letter refer to species and follow specific naming rules. ```xml A ``` -------------------------------- ### Estimate Multiple Parameters with Different Priors Source: https://github.com/biocircuits/bioscrape/blob/master/inference examples/Bioscrape Inference - Getting Started.ipynb Imports an SBML model and experimental data, sets an initial species value, defines Gaussian and uniform priors for parameters 'd1' and 'k1' respectively, and performs MCMC inference to estimate both parameters. ```python import bioscrape as bs from bioscrape.types import Model from bioscrape.inference import py_inference import numpy as np import pylab as plt import pandas as pd # Import a bioscrape/SBML model M = Model(sbml_filename = 'models/toy_sbml_model.xml') # Import data from CSV # Import a CSV file for each experiment run df = pd.read_csv('data/test_data.csv', delimiter = '\t', names = ['X','time'], skiprows = 1) M.set_species({'X':df['X'][0]}) prior = {'d1' : ['gaussian', 0.2, 20], 'k1' : ['uniform', 0, 100]} sampler, pid = py_inference(Model = M, exp_data = df, measurements = ['X'], time_column = ['time'], nwalkers = 20, init_seed = 0.15, nsteps = 5500, sim_type = 'deterministic', params_to_estimate = ['d1', 'k1'], prior = prior) ``` -------------------------------- ### General Propensity Reaction with AND Gate Source: https://github.com/biocircuits/bioscrape/wiki/Propensities Defines a reaction using a general propensity expression. This example shows a small leak combined with an AND gate logic on species X and Y. ```python reaction = Reaction(list_of_reactants, list_of_products, "general", {"rate":" 0.15 + X / (X+_Kx) * Y^_n / (Y^_n+_Ky^_n)"}) ```