### Setup GillesPy2 Environment Source: https://github.com/stochss/gillespy2/blob/main/examples/Models/Extra_Models/Speed_Comparisons/Hybrid_Switching_Decay_Model_Performance.ipynb Imports necessary libraries and configures the Python path to access GillesPy2. Ensure GillesPy2 is installed and accessible in the parent directories. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../../../..'))) ``` ```python import matplotlib.pyplot as plt ``` ```python import time from datetime import datetime ``` ```python import gillespy2 ``` -------------------------------- ### Run Automatic Switch Min Example with TauHybridCSolver Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Hybrid_Switching_Tests.ipynb Runs the automatic switching minimum population example model using the TauHybridCSolver and plots the results. ```python %time resultsC_min = model_min.run(solver=gillespy2.TauHybridCSolver) #solver=gillespy2.TauHybridCSolver(model=model_min) #%time resultsC_min = solver.run() resultsC_min.plot() ``` -------------------------------- ### Run Automatic Switch Min Example with TauHybridSolver Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Hybrid_Switching_Tests.ipynb Runs the automatic switching minimum population example model using the TauHybridSolver and plots the results. ```python model_min = create_automatic_switch_min_example(max_stoch_pop=1500) %time resultsP_min = model_min.run(solver=gillespy2.TauHybridSolver) resultsP_min.plot() ``` -------------------------------- ### Run Automatic Switch Example with TauHybridCSolver Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Hybrid_Switching_Tests.ipynb Runs the automatic switching example model using the TauHybridCSolver and plots the results. This solver is optimized for C-based computations. ```python %time resultsC_cv = model_cv.run(solver=gillespy2.TauHybridCSolver) #solver_cv=gillespy2.TauHybridCSolver(model=model_cv) #%time resultsC_cv = solver_cv.run() resultsC_cv.plot() ``` -------------------------------- ### Environment Setup Source: https://github.com/stochss/gillespy2/blob/main/examples/Models/Extra_Models/Speed_Comparisons/Tau_Solver_Run_Time_Comparison.ipynb Configures the Python path and imports necessary libraries for simulation and visualization. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../../../..'))) ``` ```python import matplotlib.pyplot as plt ``` ```python import time ``` ```python import gillespy2 ``` -------------------------------- ### Setup Environment and Imports Source: https://github.com/stochss/gillespy2/blob/main/examples/Models/Extra_Models/Dimerization.ipynb Configures the system path and imports necessary libraries for simulation and visualization. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../../..'))) ``` ```python import matplotlib.pyplot as plt ``` ```python import gillespy2 ``` -------------------------------- ### Install GillesPy2 from GitHub Repository Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_sources/getting_started/installation/installation.rst.txt Install GillesPy2 directly from its GitHub repository using pip. This is useful for installing development versions or if PyPI is unavailable. ```bash python3 -m pip install git+https@github.com:GillesPy2/GillesPy2.git --user --upgrade ``` -------------------------------- ### Setup Environment for GillesPy2 Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Events.ipynb Imports necessary modules and adjusts the system path to include the GillesPy2 library. This is a common setup step for running GillesPy2 scripts. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../..'))) ``` ```python import gillespy2 ``` -------------------------------- ### Install GillesPy2 from GitHub repository Source: https://github.com/stochss/gillespy2/blob/main/README.md Install GillesPy2 directly from the GitHub repository using pip. This is an alternative to installing from PyPI. ```sh python3 -m pip install https://github.com/StochSS/GillesPy2/archive/main.zip --user --upgrade ``` -------------------------------- ### Select Simulation Solvers Source: https://context7.com/stochss/gillespy2/llms.txt Demonstrates basic model setup for simulation using available solvers. ```python import gillespy2 # Create a model model = gillespy2.Model(name='SolverExample') k = gillespy2.Parameter(name='k', expression=0.1) A = gillespy2.Species(name='A', initial_value=1000) decay = gillespy2.Reaction(name='decay', rate=k, reactants={A: 1}, products={}) model.add([k, A, decay]) model.timespan(gillespy2.TimeSpan.linspace(t=100, num_points=101)) ``` -------------------------------- ### Run Automatic Switch Example with TauHybridSolver Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Hybrid_Switching_Tests.ipynb Runs the automatic switching example model using the TauHybridSolver and plots the results. This solver is suitable for continuous simulations. ```python model_cv = create_automatic_switch_example(tol=0.04) %time resultsP_cv = model_cv.run(solver=gillespy2.TauHybridSolver) resultsP_cv.plot() ``` -------------------------------- ### Configure Environment and Imports Source: https://github.com/stochss/gillespy2/blob/main/examples/Models/Extra_Models/Tyson_Oscillator.ipynb Setup the Python path and import necessary libraries for model definition and visualization. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../../..'))) ``` ```python import matplotlib.pyplot as plt from matplotlib import gridspec ``` ```python import gillespy2 ``` -------------------------------- ### GET /solvers/tau_leaping_c_solver/settings Source: https://github.com/stochss/gillespy2/blob/main/docs/classes/gillespy2.solvers.cpp.md Retrieves the supported settings for the TauLeapingCSolver. ```APIDOC ## GET /solvers/tau_leaping_c_solver/settings ### Description Returns a list of arguments supported by the TauLeapingCSolver.run method. ### Response #### Success Response (200) - **settings** (tuple) - A tuple of strings denoting all keyword arguments for the solver's run method. ``` -------------------------------- ### Setup Environment Imports Source: https://github.com/stochss/gillespy2/blob/main/examples/Results_Management.ipynb Initial imports and path configuration required for the GillesPy2 environment. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../'))) ``` ```python import pickle ``` ```python import gillespy2 ``` -------------------------------- ### Environment Setup Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Hybrid_Switching_Tests.ipynb Standard boilerplate for configuring the Python environment and importing necessary GillesPy2 modules. ```python %load_ext autoreload %autoreload 2 ``` ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../..'))) ``` ```python import matplotlib.pyplot as plt ``` ```python import gillespy2 ``` ```python import gillespy2.solvers.numpy.tau_hybrid_solver ``` -------------------------------- ### Configure ODESolver Integrator Options Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/ode_solver.html Example dictionary format for passing integrator-specific options to the solver. ```python {max_step : 0, rtol : .01} ``` -------------------------------- ### Setup Environment for GillesPy2 Source: https://github.com/stochss/gillespy2/blob/main/examples/Models/Extra_Models/Brusselator.ipynb Add the parent directory to the system path to ensure GillesPy2 can be imported correctly. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../../..'))) ``` -------------------------------- ### GET /solvers/TauLeapingCSolver/settings Source: https://github.com/stochss/gillespy2/blob/main/docs/classes/gillespy2.solvers.md Retrieves the supported configuration settings for the TauLeapingCSolver. ```APIDOC ## GET /solvers/TauLeapingCSolver/settings ### Description Returns a list of all supported keyword arguments for the TauLeapingCSolver run method. ### Method GET ### Response #### Success Response (200) - **settings** (tuple) - A tuple of strings representing supported keyword arguments. ``` -------------------------------- ### Setup Environment for GillesPy2 Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Hybrid_Switching_Example.ipynb Imports necessary libraries and configures the Python path for GillesPy2. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../..'))) ``` ```python import matplotlib.pyplot as plt ``` ```python import gillespy2 ``` -------------------------------- ### Setup GillesPy2 Environment Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Variable_C_Example.ipynb Imports necessary libraries and configures the Python path to access GillesPy2. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../..'))) ``` ```python import numpy as np ``` ```python import gillespy2 ``` -------------------------------- ### GET /solver/settings Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/tau_leaping_solver.html Retrieves the supported configuration settings for the TauLeapingSolver run method. ```APIDOC ## get_solver_settings ### Description Returns a list of arguments supported by the tau_leaping_solver.run method. ### Response #### Success Response (200) - **settings** (tuple) - A tuple of strings denoting all keyword arguments for the run() method. ``` -------------------------------- ### GET /solvers/ode_c_solver/settings Source: https://github.com/stochss/gillespy2/blob/main/docs/classes/gillespy2.solvers.cpp.md Retrieves the supported settings and integrator options for the ODE C-solver. ```APIDOC ## GET /solvers/ode_c_solver/settings ### Description Returns the configuration settings and supported integrator options for the ODEC solver. ### Method GET ### Response #### Success Response (200) - **settings** (tuple) - A list of arguments supported by the solver's run method. - **integrator_options** (dict) - Supported options for the SUNDIALS integrators. ``` -------------------------------- ### Import GillesPy2 dependencies Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/TauHybridAlgorithmDiagram.ipynb Setup the environment by adding the GillesPy2 path and importing necessary libraries. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../../GillesPy2/'))) import gillespy2 from matplotlib import pyplot as plt ``` -------------------------------- ### Load Test Models Source: https://github.com/stochss/gillespy2/blob/main/examples/Tau_Validation.ipynb Configures the path to include test models and imports the example models module. ```python sys.path.append('../test/') import example_models ``` -------------------------------- ### Get solver settings method Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/core/gillespySolver.html Abstract method for retrieving solver-specific configuration settings. ```python def get_solver_settings(self): ''' Abstract function for getting a solvers settings. ''' raise SimulationError("This abstract solver class cannot be used directly") ``` -------------------------------- ### Get Public Variables of Jsonify Object Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/core/jsonify.html Retrieves a dictionary of public variables from a Jsonify object. Keys starting with an underscore are excluded. ```python def public_vars(self) -> dict: """ Gets a dictionary of public vars that exist on self. Keys starting with '_' are ignored. :returns: A dictionary containing all public ('_'-prefixed) variables on the object. """ return {k: v for k, v in vars(self).items() if not k.startswith("_")} ``` -------------------------------- ### Initialize Simulation and ODE Solver Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/ode_solver.html Sets up the initial state, compiles propensity functions, and configures the ODE solver for simulation. ```python def __run(self, curr_state, curr_time, timeline, trajectory_base, tmpSpecies, live_grapher, t=20, number_of_trajectories=1, increment=0.05, integrator='lsoda', integrator_options={}, resume=None, **kwargs): timeStopped = 0 if resume is not None: if resume[0].model != self.model: raise gillespyError.ModelError('When resuming, one must not alter the model being resumed.') if t < resume['time'][-1]: raise gillespyError.ExecutionError( "'t' must be greater than previous simulations end time, or set in the run() method as the " "simulations next end time") # compile reaction propensity functions for eval c_prop = OrderedDict() for r_name, reaction in self.model.listOfReactions.items(): c_prop[r_name] = compile(reaction.ode_propensity_function, '', 'eval') result = trajectory_base[0] entry_count = 0 y0 = [0] * len(self.model.listOfSpecies) curr_state[0] = OrderedDict() if resume is not None: for i, s in enumerate(tmpSpecies): curr_state[0][s] = tmpSpecies[s] y0[i] = tmpSpecies[s] else: for i, s in enumerate(self.model.listOfSpecies.values()): curr_state[0][s.name] = s.initial_value y0[i] = s.initial_value for p_name, param in self.model.listOfParameters.items(): curr_state[0][p_name] = param.value if 'vol' not in curr_state[0]: curr_state[0]['vol'] = 1.0 rhs = ode(ODESolver.__f).set_integrator(integrator, **integrator_options) ``` -------------------------------- ### Start Gillespy2 Simulation Thread Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/tau_hybrid_solver.html Initiates a simulation in a separate thread. Handles live output display setup and timer management. Catches and stores exceptions for later re-raising. ```python curr_time = [0] # Current Simulation Time curr_state = [None] live_grapher = [None] sim_thread = threading.Thread(target=self.___run, args=(curr_state, curr_time, timeline, trajectory_base, initial_state, live_grapher,), kwargs={'t': t, 'number_of_trajectories': number_of_trajectories, 'increment': increment, 'seed': seed, 'debug': debug, 'profile': profile, 'tau_tol': tau_tol, 'event_sensitivity': event_sensitivity, 'integrator_options': integrator_options}) try: sim_thread.start() if live_output is not None: live_output_options['type'] = live_output import gillespy2.core.liveGraphing gillespy2.core.liveGraphing.valid_graph_params(live_output_options) if live_output_options['type'] == "graph": for i, s in enumerate(list(self.model._listOfSpecies.keys())): if self.model.listOfSpecies[s].mode == 'continuous': log.warning('display "type" = "graph" not recommended with continuous species. ') break live_grapher[0] = gillespy2.core.liveGraphing.LiveDisplayer(self.model, timeline, number_of_trajectories, live_output_options) display_timer = gillespy2.core.liveGraphing.RepeatTimer(live_output_options['interval'], live_grapher[0].display, args=(curr_state, curr_time, trajectory_base, live_output)) display_timer.start() sim_thread.join(timeout=timeout) if live_grapher[0] is not None: display_timer.cancel() self.stop_event.set() while self.result is None: pass except: pass if hasattr(self, 'has_raised_exception'): raise self.has_raised_exception return Results.build_from_solver_results(self, live_output_options) ``` -------------------------------- ### Install GillesPy2 with SBML support Source: https://github.com/stochss/gillespy2/blob/main/README.md Install GillesPy2 with support for importing and exporting SBML models. This requires the libSBML library to be installed. ```sh pip install gillespy2[sbml] ``` -------------------------------- ### Initialize Solver Build Process Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/cpp/tau_hybrid_c_solver.html Prepares the model for simulation by creating options and processing rate rules. ```python def _build(self, model: "Union[Model, SanitizedModel]", simulation_name: str, variable: bool, debug: bool = False, custom_definitions=None) -> str: variable = variable or len(model.listOfEvents) > 0 sanitized_model = self.__create_options(SanitizedModel(model, variable=variable)) for rate_rule in model.listOfRateRules.values(): sanitized_model.use_rate_rule(rate_rule) # determine if a constant stepsize has been requested if self.constant_tau_stepsize is not None: ``` -------------------------------- ### Install GillesPy2 from Local Clone Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_sources/getting_started/installation/installation.rst.txt Clone the GillesPy2 repository locally and then install it using pip. This method allows for modifications to the source code before installation. ```bash git clone --recursive https@github.com:GillesPy2/GillesPy2.git ``` ```bash cd GillesPy2 ``` ```bash python3 -m pip install . --user --upgrade ``` -------------------------------- ### Initialize Simulation State and Parameters Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/ssa_solver.html Sets up the simulation environment by seeding the random number generator, initializing species and parameter mappings, and creating a dictionary of constant parameters for propensity evaluation. ```python random.seed(seed) species_mappings, species, parameter_mappings, number_species = nputils.numpy_initialization(self.model) # create dictionary of all constant parameters for propensity evaluation parameters = {'V': self.model.volume} for paramName, param in self.model.listOfParameters.items(): parameters[parameter_mappings[paramName]] = param.value ``` -------------------------------- ### Simulation Setup and Timeline Generation Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/tau_leaping_solver.html This snippet sets up simulation events, handles timeout parameters, warns about unsupported keyword arguments, and generates the simulation timeline, either from scratch or by resuming a previous simulation. ```python self.stop_event = Event() self.pause_event = Event() if timeout is not None and timeout <= 0: timeout = None if len(kwargs) > 0: for key in kwargs: log.warning('Unsupported keyword argument to {0} solver: {1}'.format(self.name, key)) # create numpy array for timeline if resume is not None: # start where we last left off if resuming a simulatio lastT = resume['time'][-1] step = lastT - resume['time'][-2] timeline = np.arange(lastT, t+step, step) else: timeline = np.linspace(0, t, int(round(t / increment + 1))) ``` -------------------------------- ### Install GillesPy2 using pip Source: https://github.com/stochss/gillespy2/blob/main/README.md Install GillesPy2 from the Python Package Index using pip. This command is suitable for Linux, macOS, and Windows. ```sh python3 -m pip install gillespy2 --user --upgrade ``` -------------------------------- ### Initialize and Run ODECSolver Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/cpp/ode_c_solver.html Initializes the ODECSolver with a model and optional resume data, then prepares and runs the simulation. It includes validation steps for the model, time span, and parameters before execution. ```python self = ODECSolver(model, resume=resume) if model is not None: log.warning('model = gillespy2.model is deprecated. Future releases ' 'of GillesPy2 may not support this feature.') if self.model is None: if model is None: raise SimulationError("A model is required to run the simulation.") self._set_model(model=model) self.model.compile_prep() self.validate_model(self.model, model) self.validate_sbml_features(model=self.model) self.validate_tspan(increment=increment, t=t) if increment is None: increment = self.model.tspan[-1] - self.model.tspan[-2] if t is None: t = self.model.tspan[-1] # Validate parameters prior to running the model. self._validate_type(variables, dict, "'variables' argument must be a dictionary.") self._validate_resume(t, resume) self._validate_kwargs(**kwargs) if resume is not None: t = abs(t - int(resume["time"][-1])) number_timesteps = int(round(t / increment + 1)) args = { "timesteps": number_timesteps, "end": t, "increment": increment, "interval": str(number_timesteps), } if self.variable: populations = cutils.update_species_init_values(self.model.listOfSpecies, self.species, variables, resume) parameter_values = cutils.change_param_values(self.model.listOfParameters, self.parameters, self.model.volume, variables) args.update({ "init_pop": populations, "parameters": parameter_values }) elif variables: log.warning("'variables' argument ignored, because solver has variable=False.") if integrator_options is not None: integrator_options = ODECSolver.validate_integrator_options(integrator_options) args.update(integrator_options) seed = self._validate_seed(seed) if seed is not None: args.update({ "seed": seed }) if live_output is not None: live_output_options['type'] = live_output display_args = { "model": self.model, "number_of_trajectories": number_of_trajectories, "timeline": np.linspace(0, t, number_timesteps), "live_output_options": live_output_options, "resume": bool(resume) } else: display_args = None args = self._make_args(args) decoder = IterativeSimDecoder.create_default(1, number_timesteps, len(self.model.listOfSpecies)) sim_exec = self._build(self.model, self.target, self.variable, False) sim_status = self._run(sim_exec, args, decoder, timeout, display_args) if sim_status == SimulationReturnCode.FAILED: raise ExecutionError("Error encountered while running simulation C++ file:\n" f"Return code: {int(sim_status)}.\n") trajectories, time_stopped = decoder.get_output() simulation_data = self._format_output(trajectories) if sim_status == SimulationReturnCode.PAUSED: simulation_data = self._make_resume_data(time_stopped, simulation_data, t) if resume is not None: simulation_data = self._update_resume_data(resume, simulation_data, time_stopped) self.result = simulation_data self.rc = int(sim_status) return sum([Results.build_from_solver_results(self, live_output_options)] * number_of_trajectories) ``` -------------------------------- ### Getting a Logger Instance Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/logging.html Obtain a logger instance by name. It's recommended to get loggers for specific modules to organize log messages. ```python logger = logging.getLogger(__name__) ``` -------------------------------- ### Initialize simulation process Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/tau_hybrid_solver.html Entry point for processing simulation steps, including initial state validation. ```python def __simulate(self, integrator_options, curr_state, y0, curr_time, propensities, species, parameters, compiled_reactions, active_rr, y_map, trajectory, save_times, save_index, delayed_events, trigger_states, event_sensitivity, tau_step, debug, det_spec, det_rxn): """ Function to process simulation until next step, which can be a stochastic reaction firing, an event trigger or assignment, or end of simulation. :param curr_state: Contains all state variables for system at current time :type curr_state: dict :param curr_time: Represents current time :type curr_time: float :param save_times: Currently unreached save points :type save_times: list :returns: curr_state, curr_time, save_times, sol """ # first check if we have a valid state: self.__simulate_negative_state_check(curr_state) if curr_time == 0.0: # save state at beginning of simulation save_index = self.__save_state_to_output( ``` -------------------------------- ### Configure Live Output Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/ssa_solver.html Sets up live output and graphing for the simulation. This involves validating graph parameters and initializing a LiveDisplayer to visualize simulation progress in real-time. ```python import gillespy2.core.liveGraphing live_output_options['type'] = live_output gillespy2.core.liveGraphing.valid_graph_params(live_output_options) if resume is not None: resumeTest = True # If resuming, relay this information to live_grapher else: resumeTest = False live_grapher[0] = gillespy2.core.liveGraphing.LiveDisplayer(self.model, timeline, number_of_trajectories, live_output_options,resume = resumeTest) display_timer = gillespy2.core.liveGraphing.RepeatTimer(live_output_options['interval'], live_grapher[0].display, args=(curr_state, total_time, trajectory_base, live_output )) display_timer.start() ``` -------------------------------- ### Instantiate and Run Model Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Bimolecular_reactions.ipynb Creates a model instance and executes the simulation with timing. ```python model = create_model(A=999,B=1) ``` ```python %time result = model.run() ``` -------------------------------- ### BuildEngine.prepare Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/cpp/build/build_engine.html Prepares the template directory for compilation by generating necessary C++ header files from a GillesPy2 model. ```APIDOC ## POST /gillespy2/solvers/cpp/build/BuildEngine/prepare ### Description Prepares the template directory for compilation. This includes copying the C++ template directory, removing sample definitions, and generating a new template_definitions.h file based on the provided model. ### Method POST ### Parameters #### Request Body - **model** (gillespy2.Model) - Required - The GillesPy2 model to generate definitions for. - **variable** (bool) - Optional - Enables support for non-constant parameter values. ### Response #### Success Response (200) - **output_dir** (str) - The path of the directory where the template was prepared. ``` -------------------------------- ### Install GillesPy2 from local source clone Source: https://github.com/stochss/gillespy2/blob/main/README.md Clone the GillesPy2 repository using git and then install it locally using pip. This method is useful for development or when working with the source code. ```sh git clone https://github.com/StochSS/GillesPy2.git cd GillesPy2 python3 -m pip install . --user --upgrade ``` -------------------------------- ### Start Simulation Thread Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/ssa_solver.html Starts the simulation in a separate thread to allow for non-blocking execution and potential live output updates. It passes necessary state variables and simulation parameters to the runner. ```python sim_thread = Thread(target=self.___run, args=(curr_state, total_time, timeline, trajectory_base, live_grapher,), kwargs={'t': t, 'number_of_trajectories': number_of_trajectories, 'increment': increment, 'seed': seed, 'debug': debug, 'resume': resume, }) sim_thread.start() ``` -------------------------------- ### Instantiate Model Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Photosynthesis.ipynb Creates an instance of the photosynthesis model. ```python model = create_photosynthesis() ``` -------------------------------- ### Get Current Stack Frame Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/logging.html Provides a way to get the current frame object for the caller's stack frame. Uses sys._getframe if available, otherwise falls back to an exception-based method. ```python if hasattr(sys, '_getframe'): currentframe = lambda: sys._getframe(3) else: #pragma: no cover def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise Exception except Exception: return sys.exc_info()[2].tb_frame.f_back ``` -------------------------------- ### Initialize simulation state Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/tau_hybrid_solver.html Sets up the initial population values for parameters, species, and reaction states. ```python def __initialize_state(self, curr_state, debug): """ Initialize curr_state for each trajectory. """ # intialize parameters to current state for p in self.model.listOfParameters: curr_state[p] = self.model.listOfParameters[p].value # initialize species population state for s in self.model.listOfSpecies: curr_state[s] = self.model.listOfSpecies[s].initial_value # Set reactions to uniform random number for i, r in enumerate(self.model.listOfReactions): curr_state[r] = math.log(np.random.uniform(0, 1)) if debug: ``` -------------------------------- ### GET /model/species Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Retrieves a species object from the model by name. ```APIDOC ## GET /model/species ### Description Returns a species object by name. ### Parameters #### Query Parameters - **name** (str) - Required - Name of the species object to be returned. ### Response #### Success Response (200) - **species** (gillespy2.Species) - The specified species object. #### Errors - **ModelError** - If the species is not part of the model. ``` -------------------------------- ### GET /model/element Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Retrieves a specific model element by its name. ```APIDOC ## GET /model/element ### Description Get a model element specified by name. ### Parameters #### Query Parameters - **name** (str) - Required - Name of the element to be returned. ### Response #### Success Response (200) - **element** (Object) - The specified gillespy2.Model element (Species, Parameters, Reactions, Events, RateRules, FunctionDefinitions, or TimeSpan). #### Errors - **ModelError** - If the element is not part of the model. ``` -------------------------------- ### Initialize NumPy Arrays for Simulation Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/CLE_solver.html Sets up species and parameter mappings using NumPy for efficient simulation. ```python species_mappings, species, parameter_mappings, number_species = nputils.numpy_initialization(self.model) ``` -------------------------------- ### GET /model/components Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Methods to retrieve all or specific components from the model. ```APIDOC ## GET /get_all_assignment_rules ### Description Get all of the assignment rules in the model object. ### Response #### Success Response (200) - **Return** (dict) - A dict of all assignment rules in the form {name: reaction object}. ## GET /get_all_reactions ### Description Get all of the reactions in the model object. ### Response #### Success Response (200) - **Return** (OrderedDict) - A dict of all reactions in the form {name: reaction object}. ## GET /get_assignment_rule ### Description Returns an assignment rule object by name. ### Parameters #### Path Parameters - **name** (str) - Required - Name of the assignment rule object to be returned. ### Response #### Success Response (200) - **Return** (gillespy2.AssignmentRule) - The specified assignment rule object. #### Error Handling - **ModelError** - Raised if the assignment rule is not part of the model. ``` -------------------------------- ### GET /model/all_components Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Retrieves collections of various model components. ```APIDOC ## GET /model/all_components ### Description Endpoints to retrieve all events, function definitions, parameters, rate rules, reactions, or species. ### Method GET ### Response #### Success Response (200) - **dict/OrderedDict** - Returns a dictionary mapping names to the respective objects (events, functions, parameters, rate rules, reactions, or species). ``` -------------------------------- ### POST /model/initialize Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/core/model.html Initializes a new model instance with specific configuration parameters for simulation. ```APIDOC ## POST /model/initialize ### Description Creates an empty model instance. This constructor sets up the internal data structures for species, parameters, reactions, and rules. ### Method POST ### Endpoint /model/initialize ### Parameters #### Request Body - **name** (str) - Optional - The name that the model is referenced by. - **population** (bool) - Optional - True for discrete stochastic (population) model, False for deterministic (concentration) model. - **volume** (float) - Optional - The volume of the system, used for conversion between population and concentration forms. - **tspan** (numpy ndarray) - Optional - The timepoints at which the model should be simulated. - **annotation** (str) - Optional - Further description of the model. ### Request Example { "name": "my_model", "population": true, "volume": 1.0, "tspan": [0, 10, 20], "annotation": "A simple stochastic model" } ### Response #### Success Response (200) - **status** (string) - Confirmation that the model has been initialized. ``` -------------------------------- ### GET /model/assignment_rules Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Retrieves all assignment rules defined in the model. ```APIDOC ## GET /model/assignment_rules ### Description Get all of the assignment rules in the model object. ### Method GET ### Response #### Success Response (200) - **dict** - A dict of all assignment rules in the model, in the form: {name: reaction object}. ``` -------------------------------- ### GET /jsonify/json Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Converts the object into a JSON string representation. ```APIDOC ## GET /jsonify/json ### Description Convert the object into a JSON string. ### Parameters #### Query Parameters - **encode_private** (bool) - Optional - If True all private (prefixed of '_') will be encoded. ### Response #### Success Response (200) - **json_string** (str) - The JSON representation of the object. ``` -------------------------------- ### Initialize GillesPy2 Environment Source: https://github.com/stochss/gillespy2/blob/main/examples/Tau_Validation.ipynb Sets up the Python path and imports the core GillesPy2 library. ```python import sys sys.path.append('..') import gillespy2 ``` -------------------------------- ### GET /tau_hybrid_solver/features Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/tau_hybrid_solver.html Retrieves the set of features supported by the TauHybridSolver. ```APIDOC ## GET /tau_hybrid_solver/features ### Description Returns the set of features supported by the TauHybridSolver, such as Events, RateRules, AssignmentRules, and FunctionDefinitions. ### Method GET ### Response #### Success Response (200) - **features** (set) - A set of supported feature classes. ``` -------------------------------- ### GET /model/parameters Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/core/model.html Retrieves all parameters currently defined in the model. ```APIDOC ## GET /model/parameters ### Description Returns a dictionary of all parameters in the model. ### Method GET ### Endpoint /model/parameters ### Response #### Success Response (200) - **parameters** (OrderedDict) - A dictionary in the form {name : parameter object}. ``` -------------------------------- ### Create Automatic Switching Min Example Model Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/Hybrid_Switching_Tests.ipynb Initializes a GillesPy2 model with species A, B, and C, defining reactions and parameters. Supports setting a minimum population threshold for switching. ```python def create_automatic_switch_min_example(parameter_values=None, max_stoch_pop=100): # Initialize Model model = gillespy2.Model(name="Automatic Switch Example") # Define Variables (GillesPy2.Species) A = gillespy2.Species(name='A', initial_value=400, switch_min=max_stoch_pop) B = gillespy2.Species(name='B', initial_value=10000, switch_min=max_stoch_pop) C = gillespy2.Species(name='C', initial_value=10000, switch_min=max_stoch_pop) # Add Variables to Model model.add_species([A, B, C]) # Define Parameters k1 = gillespy2.Parameter(name='k1', expression= 3e-4) k2 = gillespy2.Parameter(name='k2', expression= 0.5e-2) k3 = gillespy2.Parameter(name='k3', expression = 2e-1) # Add Parameters to Model model.add_parameter([k1, k2, k3]) # Define Reactions r1 = gillespy2.Reaction(name="r1",reactants={'A': 1, 'B': 1}, products={'B': 1, 'C': 1}, rate='k1') r2 = gillespy2.Reaction(name="r2",reactants={'B': 1}, products={}, rate='k2') r3 = gillespy2.Reaction(name="r3",reactants={'C': 1}, products={'A': 1}, rate='k3') # Add Reactions to Model model.add_reaction([r1, r2, r3]) # Define Timespan tspan = gillespy2.TimeSpan.linspace(t=600, num_points=601) # Set Model Timespan model.timespan(tspan) return model ``` -------------------------------- ### CLESolver Initialization and Deprecation Warnings Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/CLE_solver.html This snippet shows the initialization of the CLESolver, including handling deprecated model parameters and issuing warnings for unsupported keyword arguments. It also demonstrates the setup for simulation time and trajectory data. ```python from gillespy2 import log if self is None: # Post deprecation block # raise SimulationError("CLESolver must be instantiated to run the simulation") # Pre deprecation block log.warning( "`gillespy2.Model.run(solver=CLESolver)` is deprecated.\n\nYou should use `gillespy2.Model.run(solver=CLESolver(model=gillespy2.Model))\nFuture releases of GillesPy2 may not support this feature." ) self = CLESolver(model=model, debug=debug, profile=profile) if model is not None: log.warning('model = gillespy2.model is deprecated. Future releases ' \ 'of GillesPy2 may not support this feature.') if self.model is None: if model is None: raise SimulationError("A model is required to run the simulation.") self.model = copy.deepcopy(model) self.model.compile_prep() self.validate_model(self.model, model) self.validate_sbml_features(model=self.model) self.validate_tspan(increment=increment, t=t) if increment is None: increment = self.model.tspan[-1] - self.model.tspan[-2] if t is None: t = self.model.tspan[-1] self.stop_event = Event() self.pause_event = Event() if timeout is not None and timeout <= 0: timeout = None if len(kwargs) > 0: for key in kwargs: log.warning('Unsupported keyword argument to {0} solver: {1}'.format(self.name, key)) ``` -------------------------------- ### GET /model/assignment_rule Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Retrieves a specific assignment rule object by name. ```APIDOC ## GET /model/assignment_rule ### Description Returns an assignment rule object by name. ### Method GET ### Parameters #### Query Parameters - **name** (str) - Required - Name of the assignment rule object to be returned. ### Response #### Success Response (200) - **gillespy2.AssignmentRule** - The specified assignment rule object. #### Error Response - **ModelError** - Raised if the assignment rule is not part of the model. ``` -------------------------------- ### Jsonify Method Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/genindex.html Method to get public variables for JSON serialization. ```APIDOC ## Jsonify.public_vars() ### Description Returns the public variables of an object, suitable for JSON serialization. ### Method N/A ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Setup GillesPy2 Environment Source: https://github.com/stochss/gillespy2/blob/main/examples/Models/Extra_Models/Genetic_Toggle_Switch.ipynb Imports necessary libraries and configures the Python path to access GillesPy2. Ensure this is run before using the library. ```python import os import sys sys.path.insert(1, os.path.abspath(os.path.join(os.getcwd(), '../../..'))) ``` ```python import gillespy2 ``` -------------------------------- ### GET /model/function-definitions/{name} Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/core/model.html Retrieves a specific function definition by its name. ```APIDOC ## GET /model/function-definitions/{name} ### Description Returns a function definition object by name. ### Method GET ### Parameters #### Path Parameters - **name** (str) - Required - Name of the function definition object to be returned. ### Response #### Success Response (200) - **function_definition** (gillespy2.FunctionDefinition) - The specified function definition object. ``` -------------------------------- ### GET /model/events Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/core/model.html Retrieves all events currently defined in the model object. ```APIDOC ## GET /model/events ### Description Retrieves a dictionary of all events in the model. ### Method GET ### Response #### Success Response (200) - **events** (dict) - A dictionary where keys are event names and values are event objects. ``` -------------------------------- ### Initialize Reaction with Reactants and Products Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/core/reaction.html Initializes a reaction with specified reactants and products, updating internal dictionaries. Handles mass-action kinetics if marate is provided. ```python if name in self.reactants: self.reactants[name] += reactants[reactant] else: self.reactants[name] = reactants[reactant] if products is not None: for product in products: ptype = type(product).__name__ name = product.name if ptype == 'Species' else product if name in self.products: self.products[name] += products[product] else: self.products[name] = products[product] if self.marate is not None: rtype = type(self.marate).__name__ if rtype == 'Parameter': self.marate = self.marate.name self.massaction = True self.type = "mass-action" self._create_mass_action() else: self.massaction = False self.type = "customized" if self.propensity_function is None: self.propensity_function = self.ode_propensity_function if self.ode_propensity_function is None: self.ode_propensity_function = self.propensity_function propensity = self._create_custom_propensity(self.propensity_function) self.propensity_function = propensity ode_propensity = self._create_custom_propensity(self.ode_propensity_function) self.ode_propensity_function = ode_propensity self.validate(coverage="initialized") ``` -------------------------------- ### Get All Reactions API Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/core/model.html Retrieves all reactions currently present in the model. ```APIDOC ## GET /api/model/reactions ### Description Get all of the reactions in the model object. ### Method GET ### Endpoint /api/model/reactions ### Response #### Success Response (200) - **reactions** (OrderedDict) - A dict of all reactions in the model, in the form: {name : reaction object}. ``` -------------------------------- ### GET /model/solver Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Method to determine the best solver for the current model configuration. ```APIDOC ## GET /get_best_solver ### Description Finds the best solver for the user's simulation. Note that specific components like AssignmentRules, RateRules, FunctionDefinitions, Events, and Species with dynamic/continuous populations require the TauHybridSolver. ``` -------------------------------- ### GET /jsonify/dict Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Converts the object into a dictionary format suitable for JSON encoding. ```APIDOC ## GET /jsonify/dict ### Description Convert the object into a dictionary ready for JSON encoding. By default, returns a dictionary of the object's public types. ### Response #### Success Response (200) - **data** (dict) - The backing variable dictionary of the object. ``` -------------------------------- ### Initialize Reaction Dependencies Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/numpy/tau_hybrid_solver.html Builds a dependency map for reactions based on reactants and products to facilitate differential equation creation. ```python dependencies = OrderedDict() # If considering deterministic changes, create dependency data # structure for creating diff eqs later for reaction in self.model.listOfReactions: dependencies[reaction] = set() [dependencies[reaction].add(reactant.name) for reactant in self.model.listOfReactions[reaction].reactants] [dependencies[reaction].add(product.name) for product in self.model.listOfReactions[reaction].products] ``` -------------------------------- ### GET /jsonify/hash Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/classes/gillespy2.core.html Retrieves an MD5 hash of the object's JSON representation. ```APIDOC ## GET /jsonify/hash ### Description Returns an MD5 hash of the object's sorted JSON representation. ### Parameters #### Query Parameters - **ignore_whitespace** (bool) - Optional - If set to True all whitespace will be stripped from the JSON prior to being hashed. - **hash_private_vals** (bool) - Optional - If set to True all private and non-private variables will be included in the hash. ### Response #### Success Response (200) - **hash** (str) - An MD5 hash of the object's sorted JSON representation. ``` -------------------------------- ### Initialize Make Class for C++ Solver Build Source: https://github.com/stochss/gillespy2/blob/main/docs/build/html/_modules/gillespy2/solvers/cpp/build/make.html Initializes the Make class, setting up directories for compilation. Ensure that the output and object directories do not exist as files. ```python class Make(): def __init__(self, makefile: str, output_dir: str, obj_dir: str = None, template_dir: str = None): self.makefile = Path(makefile).resolve() self.self_dir = Path(__file__).parent self.cbase_dir = self.self_dir.joinpath("../c_base").resolve() self.output_dir = Path(output_dir).resolve() # obj_dir is, presumably, only supplied if caching is enabled. # If not supplied, it should be assumed ethereal and cleaned up # with the rest of the tmp directory. if obj_dir is None: self.obj_dir = self.output_dir.joinpath("gillespy2_obj").resolve() else: self.obj_dir = Path(obj_dir).resolve() if template_dir is None: self.template_dir = self.output_dir.joinpath("gillespy2_template").resolve() else: self.template_dir = Path(template_dir).resolve() for path in [self.output_dir, self.obj_dir]: if path.is_file(): raise gillespyError.DirectoryError( f"Error while attempting to open directory:\n" f"- {path} is actually a file." ) if not path.is_dir(): path.mkdir() self.output_file = "GillesPy2_Simulation.exe" self.output_file = Path(self.output_dir, self.output_file) # SCons can either be an executable or a Python package. scons_exe = shutil.which("scons") if scons_exe is None: self.scons_cmd = [str(Path(sys.executable).resolve()), "-m", "SCons"] elif find_spec("SCons") is not None: self.scons_cmd = [str(Path(scons_exe).resolve())] else: raise BuildError("SCons must be installed in order to compile solver with C++") ``` -------------------------------- ### Instantiate Brusselator Model Source: https://github.com/stochss/gillespy2/blob/main/examples/Models/Extra_Models/Brusselator.ipynb Call the create_brusselator function to get an instance of the model. ```python model = create_brusselator() ``` -------------------------------- ### Instantiate the Stochastic Model Source: https://github.com/stochss/gillespy2/blob/main/examples/Advanced_Features/SBML_Import_Test.ipynb Creates an instance of the stochastic model using the previously defined `create_stochastic_example` function and the imported concentration model. ```python stoch_model = create_stochastic_example(model) ```