├── .gitignore ├── CONTRIBUTORS ├── LICENSE ├── MANIFEST.in ├── README.md ├── VersionUpdates.txt ├── pyproject.toml ├── requirements.txt ├── setup.py ├── stochpy ├── __init__.py ├── core2 │ ├── InfixParser.py │ ├── PyscesCore2.py │ ├── PyscesCore2Interfaces.py │ ├── __init__.py │ ├── lex.py │ ├── version.py │ └── yacc.py ├── implementations │ ├── DelayedDirectMethod.py │ ├── DelayedNRM.py │ ├── DirectMethod.py │ ├── FastSingleMoleculeMethod.py │ ├── FirstReactionMethod.py │ ├── NextReactionMethod.py │ ├── SingleMoleculeMethod.py │ ├── StochPyTools.py │ ├── TauLeaping.py │ └── __init__.py ├── lib │ ├── __init__.py │ ├── lex.py │ └── yacc.py ├── modules │ ├── Analysis.py │ ├── PyscesInterfaces.py │ ├── PyscesMiniModel.py │ ├── PyscesParse.py │ ├── SBML2PSC.py │ ├── SimulatorOutput2StochPy.py │ ├── StochPyCellDivision.py │ ├── StochPyCellDivisionPlot.py │ ├── StochPyDemo.py │ ├── StochPyPlot.py │ ├── StochPyPrint.py │ ├── StochPyUtils.py │ ├── StochSim.py │ └── __init__.py ├── pscmodels │ ├── Autoreg.py │ ├── BirthDeath.py │ ├── Burstmodel.py │ ├── CellDivision.py │ ├── DecayingDimerizing.py │ ├── GeneDuplication.py │ ├── ImmigrationDeath.py │ ├── Isomerization.py │ ├── Polymerase.py │ ├── Schlogl.py │ ├── Signaling3cCD.py │ ├── SignalingTimeVaryingL.py │ ├── TranscriptionIntermediate.py │ ├── __init__.py │ ├── chain1500.py │ ├── chain5.py │ ├── chain50.py │ ├── chain500.py │ ├── dsmts_001_01.py │ ├── dsmts_001_11.py │ ├── dsmts_001_19.py │ ├── dsmts_002_10.py │ ├── dsmts_003_03.py │ └── dsmts_003_04.py └── tools │ ├── ExtrapolateExtant.py │ ├── ParseDistributions.py │ ├── Priority_queue.py │ ├── Progress_bar.py │ ├── __init__.py │ └── kSolver.py └── testing └── example_tests.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | 103 | # stochpy 104 | wing-stochpy.wpr 105 | wing-stochpy.wpu -------------------------------------------------------------------------------- /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # StochPy Stochastic modeling in Python 2 | 3 | 4 | Copyright (c) 2011-2021, Timo R. Maarleveld, Brett G. Olivier, and Frank J. Bruggeman 5 | All rights reserved. 6 | 7 | StochPy is distributed under a BSD style licence. 8 | 9 | File releases: http://sourceforge.net/projects/stochpy 10 | Source code: https://github.com/SystemsBioinformatics/stochpy 11 | 12 | ## Author information 13 | 14 | Timo R. Maarleveld, Brett G. Olivier and Frank J. Bruggeman 15 | Centrum Wiskunde en Informatica, Amsterdam, Netherlands 16 | Vrije Universiteit Amsterdam, Amsterdam, Netherlands 17 | 18 | ## Major code contributors to the StochPy codebase 19 | 20 | - Brett G. Olivier (@bgoli) 21 | - Catharina Meyer 22 | 23 | ## GitHub contributions (per release): 24 | 25 | ### Release 2.4 26 | Thanks for the contributions @zesloth, @enricozb and @developerfab 27 | 28 | Please let us know if you feel you should be included in this list. 29 | 30 | Last updated: 2021-04-30 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2021, Systems Biology Lab, Vrije Universiteit Amsterdam 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | 1. Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | 2. Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | 3. Neither the name of the copyright holder nor the names of its 17 | contributors may be used to endorse or promote products derived from 18 | this software without specific prior written permission. 19 | 20 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 23 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 24 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 25 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 26 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 27 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 28 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 29 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 30 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include CONTRIBUTORS 2 | include LICENSE 3 | include README.md 4 | include requirements.txt 5 | include VersionUpdates.txt 6 | include pyproject.toml 7 | include stochpy/* 8 | include stochpy/core2/* 9 | include stochpy/implementations/* 10 | include stochpy/lib/* 11 | include stochpy/modules/* 12 | include stochpy/pscmodels/* 13 | include stochpy/tools/* 14 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # StochPy Stochastic modeling in Python 2 | 3 | StochPy is a versatile stochastic modeling package which is designed for stochastic simulation of molecular control networks 4 | 5 | * File releases 2.3 and earlier: http://sourceforge.net/projects/stochpy 6 | * File releases 2.4+: PyPI and Github. 7 | * Source code: https://github.com/SystemsBioinformatics/stochpy 8 | 9 | StochPy is open source software distributed under the BSD 3-Clause License, see LICENSE file for more details. 10 | 11 | ## Documentation 12 | 13 | Documentation can be found in the user guide (see Documentation directory or in [sourceforge](http://stochpy.sourceforge.net/html/userguide.html)) 14 | 15 | ## Installation 16 | 17 | The following software is required before installing StochPy (see user guide for more details): 18 | 19 | - Python 2.6+ or Python 3.4+ 20 | - [NumPy 1.x+](http://www.numpy.org) 21 | - [SciPy](https://scipy.org) 22 | - [Matplotlib](https://matplotlib.org) (optional) 23 | - [libsbml](http://sbml.org/Software/libSBML) (optional) 24 | - [libxml2](http://xmlsoft.org) (optional) 25 | - [mpmath](http://mpmath.org) (optional) 26 | 27 | Install StochPy and dependencies with PIP using the following command (in your StochPy Python virtual environment): 28 | ```bash 29 | pip install scipy matplotlib python-libsbml jedi==0.17.2 ipython stochpy 30 | ``` 31 | 32 | If you are using Anaconda, create a custom conda environment for StochPy, for example: 33 | ```bash 34 | conda create -n "stochpy39" -c sbmlteam python=3.9 pip scipy matplotlib sympy ipython 35 | ``` 36 | activate your new environment, install StochPy (only required once per environment) and start ipython. 37 | ```bash 38 | conda activate stochpy39 39 | pip install stochpy 40 | ipython 41 | 42 | ``` 43 | 44 | #### Linux/MAC OS/Cygwin from source. 45 | 46 | In the directory where you downloaded/cloned the StochPy source, for example, the git main branch: 47 | ```bash 48 | sudo python setup.py install 49 | ``` 50 | 51 | ### Windows 52 | 53 | Use the available windows installer or use PyPI (described above). 54 | 55 | ## Getting Started 56 | 57 | You can run `ipython` and import `stochpy`: 58 | 59 | ```py 60 | import stochpy 61 | smod = stochpy.SSA() 62 | ``` 63 | 64 | ### Basic Simulation with the Direct method 65 | ```py 66 | smod.DoStochSim(IsTrackPropensities=True) 67 | smod.data_stochsim.simulation_endtime 68 | smod.data_stochsim.simulation_timesteps 69 | smod.GetWaitingtimes() 70 | smod.PrintWaitingtimesMeans() 71 | ``` 72 | 73 | ### Do some Plotting 74 | ```py 75 | smod.PlotSpeciesTimeSeries() 76 | smod.PlotWaitingtimesDistributions() 77 | smod.PlotPropensitiesTimeSeries() 78 | ``` 79 | 80 | ### Write data to a text file 81 | ```py 82 | smod.Export2File() 83 | smod.Export2File(analysis='distribution') 84 | smod.Export2File(analysis='distribution',datatype='species') 85 | smod.Export2File(analysis='mean',datatype='species') 86 | smod.Export2File(analysis='std',datatype='species') 87 | smod.Export2File(analysis='autocorrelation',datatype='species') 88 | ``` 89 | 90 | ### Show the means from the data of 3-th trajectory 91 | ```py 92 | smod.DoStochSim(trajectories=3) # multiple trajectories 93 | smod.data_stochsim.simulation_trajectory 94 | smod.PrintSpeciesMeans() 95 | smod.PrintSpeciesStandardDeviations() 96 | ``` 97 | 98 | ### Switch to data from trajectory 1 and show the means of each species 99 | ```py 100 | smod.GetTrajectoryData(1) 101 | smod.PrintSpeciesMeans() 102 | smod.PrintSpeciesStandardDeviations() 103 | ``` 104 | 105 | ### Do one long simulation 106 | ```py 107 | smod.DoStochSim(trajectories=1,end=1000000,mode='steps') 108 | smod.PrintSpeciesMeans() 109 | smod.PrintSpeciesStandardDeviations() 110 | ``` 111 | 112 | ### Plot the PDF for different bin sizes 113 | ```py 114 | smod.PlotSpeciesDistributions() 115 | smod.PlotSpeciesDistributions(bin_size=5) # larger bin size 116 | smod.PlotSpeciesDistributions(bin_size=10) # again a larger bin size 117 | smod.Export2File(analysis='distribution',datatype='species') 118 | ``` 119 | 120 | ### Usage of the Reload Function: `Ksyn = 20, kdeg = 0.2` 121 | ```py 122 | smod.ChangeParameter('Ksyn',20.0) 123 | smod.ChangeParameter('Kdeg',0.2) 124 | smod.DoStochSim() 125 | smod.PrintSpeciesMeans() # should be ~Ksyn/Kdeg 126 | ``` 127 | 128 | ### Use another model to show the Interpolation features 129 | ```py 130 | smod.Model('dsmts-001-01.xml.psc') 131 | smod.DoStochSim(trajectories=1000,end=50,mode='time') 132 | smod.GetRegularGrid(npoints=51) 133 | smod.PlotAverageSpeciesTimeSeries() 134 | smod.PrintAverageSpeciesTimeSeries() 135 | smod.Export2File(datatype='species',analysis='timeseries',IsAverage=True) 136 | ``` 137 | 138 | ### Test each method for different models: 139 | ```py 140 | smod.Model('Autoreg.psc') 141 | smod.DoStochSim(trajectories=1,end=1000,mode='steps') 142 | smod.Method('NextReactionMethod') 143 | smod.DoStochSim(trajectories=1,end=1000,mode='steps') 144 | smod.data_stochsim.species 145 | smod.PlotWaitingtimesDistributions() 146 | smod.Method('FirstReactionMethod') 147 | smod.DoStochSim(trajectories=1,end=1000,mode='steps') 148 | smod.Method('TauLeaping') 149 | smod.DoStochSim(trajectories=1,end=1000,mode='steps') 150 | ``` 151 | ```py 152 | smod.Model('DecayingDimerizing.psc') 153 | smod.DoStochSim(method = 'Direct',trajectories=1,end=50,mode='time') 154 | smod.DoStochSim(method = 'NextReactionMethod',trajectories=1,end=50,mode='time') 155 | smod.DoStochSim(method = 'FirstReactionMethod',trajectories=1,end=50,mode='time') 156 | smod.PlotWaitingtimesDistributions() 157 | smod.DoStochSim(method = 'TauLeaping',trajectories=1,end=50,mode='time',epsilon=0.03) # Should outperform all other implementations 158 | smod.PlotSpeciesTimeSeries() 159 | #smod.PlotWaitingtimesDistributions() # Should give an error 160 | ``` 161 | ```py 162 | smod.Model('chain500.psc') 163 | smod.DoStochSim(method = 'Direct',trajectories=1,end=10000,mode='steps') 164 | smod.DoStochSim(method = 'NextReactionMethod',trajectories=1,end=10000,mode='steps') # should outperform the direct method and all other implementations 165 | ``` 166 | 167 | ### Use the Next Reaction Method to test a model with a time event 168 | ```py 169 | smod.Model('dsmts-003-03.xml.psc') 170 | smod.DoStochSim(method = 'NextReactionMethod') 171 | smod.DoTestsuite() 172 | ``` 173 | 174 | ### Use the First Reaction method to test a model with a concentration event 175 | ```py 176 | smod.Model('dsmts-003-04.xml.psc') 177 | smod.DoStochSim(method = 'FirstReactionMethod') 178 | smod.DoTestsuite() 179 | ``` 180 | 181 | ### Volume Models 182 | ```py 183 | smod.Model('dsmts-001-11.xml.psc') 184 | smod.DoStochSim(method = 'Direct',trajectories=1000,end=50,mode ='time') 185 | smod.PrintAverageSpeciesTimeSeries() 186 | ``` 187 | 188 | ## Author information 189 | 190 | 191 | Timo R. Maarleveld, Brett G. Olivier, and Frank J. Bruggeman 192 | Centrum Wiskunde en Informatica, Amsterdam, Netherlands 193 | VU University, Amsterdam, Netherlands 194 | 195 | > e-mail: tmd200@users.sourceforge.net 196 | 197 | ## Publication 198 | 199 | StochPy: A Comprehensive, User-Friendly Tool for Simulating Stochastic Biological Processes 200 | http://dx.doi.org/10.1371/journal.pone.0079345 201 | 202 | ## Licence 203 | Copyright (c) 2011-2021, Timo R. Maarleveld, Brett G. Olivier, and Frank J. Bruggeman 204 | Vrije Universiteit Amsterdam. All rights reserved. 205 | 206 | StochPy is open source software distributed under the BSD 3-Clause License see LICENSE file for more details. 207 | -------------------------------------------------------------------------------- /VersionUpdates.txt: -------------------------------------------------------------------------------- 1 | Updates 2.5 2 | ----------- 3 | - Python 3.10 compatibility. 4 | - Setup fixed to work with newer setuptools, pythons. 5 | - Numpy compatibility fixes. 6 | 7 | 8 | Updates 2.4: 9 | ------------ 10 | - Python 3 compatibility fixes 11 | - updated documentation, packaging and metadata 12 | 13 | 14 | Updates 2.3: 15 | ------------ 16 | - improved sampling method to calculate extant cell species AND volumes (new) 17 | - we allow plotting of mother and baby cell species AND volume at birth 18 | - we use a different function for plotting distributions (gives the user more flexibility) 19 | - Silence Mode 20 | - support of events in cell division simulations 21 | - bug resolved for an event that changes the value of parameters 22 | - the cell division module works now also with the tau leap method 23 | - we added DNA replication to the cell division module 24 | - fixed a bug in the interface to StochKit for models with customized reactions 25 | - with the next reaction method (and the delayed one), it was not possible to change parameters. This is now possible 26 | 27 | 28 | Updates 2.2.2: 29 | -------------- 30 | - the use of colors in the plotting functions is now more intuitively 31 | - we solved a bug in PlotAverageSpeciesDistributions: we again allow for non-integer values of *nstd* 32 | 33 | Updates 2.2.1: 34 | -------------- 35 | - We solved an issue with the species order if you use the interface to StochKit 36 | - propensities distributions are calculated correctly again 37 | 38 | Updates 2.2.0: 39 | ------------- 40 | - (fast) Single molecule method. See documentation for more details 41 | - improved methods to determine the order of the reaction 42 | - extra arguments for DoStochSim which provide more options for the tau-leaping method 43 | - high-level function for cell age distribution 44 | - improved calculation of cell age 45 | - 2D trapezoidal rule for calculating the extant cell population 46 | - different sampling method 47 | - more advanced warning messages 48 | - bug removed in Endtime() of the cell division module 49 | - new plotting function for the extant cell population in the cell division module 50 | - all functionalities work now if you decide to track only a subset of species through time (before e.g. GetSpeciesAutocorrelations() was not working) 51 | - *rate_selection* added to stochastic simulation algorithms 52 | - removed a bug in DelayedDirect with respect to handling of time events 53 | - speed improvement for GetRegularGrid() and we now use n_samples in stead of npoints as arguments 54 | 55 | Updates 2.1.1: 56 | -------------- 57 | - We corrected a bug in the tau-leaping method which was introduced in 2.1 58 | - We added 'critical_reactions' as argument to the DoStochSim method which allows users to predefine reactions that can only fire once during a tau leaping time step 59 | 60 | Updates 2.1: 61 | ------------ 62 | - Python 3 support 63 | - *DumpTrajectoryData* improved 64 | 65 | Updates 2.0.1 66 | ------------- 67 | - SetVolumeDependencies settings still work after changing initial species of parameters in the ChangeInitialSpeciesAmount or ChangeParameters functions. 68 | - Solved potential bugs in SetVolumeDependencies. We for instance now check if the first argument is a boolean (as it should be) 69 | 70 | 71 | Updates 2.0.0 72 | ------------- 73 | - delayed stochastic algorithms 74 | - single molecule stochastic algorithms 75 | - volume dependency 76 | - completely new cell division module 77 | - improved event handling 78 | - improved matplotlib handling 79 | - PlotPropensitiesAutocorrelations() works again correctly 80 | - Works now properly with StochKit 2.0.10 and higher 81 | 82 | Updates 1.2.0 83 | ------------- 84 | - track output of specific species 85 | - faster implementation of the Next Reaction Method 86 | - we added a argument which allows users to save only the last data point 87 | - improved functionality of ChangeInitialSpeciesAmount and ChangeParameter; made modifications are stored after choosing e.g. a different simulation algorithm 88 | - More efficient use of memory 89 | 90 | Updates 1.1.5 91 | ------------- 92 | - Improved statusbar functionalities 93 | - Improved functionalities for the Nucleosome Tool plug-in 94 | - Improved DeleteTempfiles high-level function 95 | 96 | Updates 1.1.4 97 | ------------- 98 | - Removed potential bug in high-level execute function 99 | - Incorporated functionalities for Nucleosome simulator plug-in 100 | 101 | Updates 1.1.3 102 | ------------- 103 | - Simulating indicator for single trajectory simulations 104 | - Progress Bar for multiple trajectory simulations 105 | - Improved model handling 106 | - trajectories, mode, method, end are reset if the user not specifically uses the high-level functionalities that are designed for this. An example: 107 | >>> smod.DoStochSim(trajectories=1000,end=100,mode='time') generates 1000 trajectories until t=100 108 | >>> smod.DoStochSim() then generates 1 trajectory with 1000 time steps 109 | >>> smod.Trajectories(1000) 110 | >>> smod.DoStochSim(end=100, mode='time') then generates 1000 trajectories until t = 100 111 | >>> smod.DoStochSim() then generates 1000 trajectories with 1000 time steps each 112 | - Improved CellDivision Module 113 | - Improved help messages 114 | 115 | Updates 1.1.2 116 | ------------- 117 | - Removed a potential bug in the next reaction method 118 | 119 | 120 | Updates 1.1.1 121 | ------------- 122 | - We added a functionality to import earlier exported simulations into StochPy: Import2StochPy 123 | - Removed a bug in the data storing procedure of the tau-leaping implementation 124 | - Modified the default Export2File functionality 125 | 126 | Updates 1.1.0 127 | ------------- 128 | 129 | - We added the option to analyze propensity means, standard deviations, distributions, and (raw) moments. As a result, we altered some names in the data_stochsim data object: 130 | 1. data_stochsim.means --> data_stochsim.species_means 131 | 2. data_stochsim.standard_deviations --> data_stochsim.species_standard_devations 132 | 3. data_stochsim.moments --> data_stochsim.species_moments 133 | - Similar data objects are created for propensities: 134 | 1. data_stochsim.propensities_means 135 | 2. data_stochsim.propensities_standard_deviations 136 | 3. data_stochsim.propensities_moments 137 | - User can print propensity means and standard deviations with: PrintPropensitiesMeans() and PrintPropensitiesStandardDeviations() 138 | - In addition to the previous point we added the possibility to do analyses for propensities of multiple trajectories with PlotAveragedPropensitiesTimeCourses() and PrintAveragedPropensitiesTimeCourses() 139 | - User can analyse auto correlations of species and propensities: GetSpeciesAutocorrelations(),GetPropensitiesAutocorrelations(), PlotSpeciesAutocorrelations(),PlotPropensitiesAutocorrelations(), Export2File(...) 140 | - User can analyse averaged distributions of species and propensities: smodGetAverageSpeciesDistributions(),smod.GetAveragePropensitiesDistributions(),smod.PlotAverageSpeciesDistributions(),smod.PlotAveragePropensitiesDistributions 141 | - Write2File() is not longer supported. Users must exploit Export2File which has the same functionalities 142 | - Arguments of Export2File are completely altered. For more information see the latest user guide 143 | - Improved handling of (SBML) events 144 | - Error messages are more effective 145 | - More arguments for plotting functions 146 | - Solved bug in headers of export2file 147 | - Improved error handling when incorrect color codes are used 148 | 149 | - We decided to change the name of a couple of functions to prevent potential confusion: 150 | 1. GetInterpolatedData(frames) --> GetRegularGrid(npoints) 151 | 2. PlotInterpolatedData() --> PlotAverageSpeciesTimeCourses() 152 | 3. PrintInterpolatedData() --> PrintAverageSpeciesTimeCourse() 153 | 4. PrintTimeSim() --> PrintSpeciesTimeCourses() 154 | 5. PlotTimesim() --> PlotSpeciesTimeCourses() 155 | 6. ShowMeans() --> PrintSpeciesMeans() 156 | 7. ShowStandardDeviations() --> PrintSpeciesStandardDeviations() 157 | 158 | 9. PlotWaitingtimes() --> PlotWaitingtimesDistributions() 159 | 10. PrintWaitingtimes() --> PrintWaitingtimesDistributions() 160 | 11. GetMeanWaitingtimes() --> GetWaitingtimesMeans() 161 | 12. PrintMeanWaitingtimes() --> PrintWaitingtimesMeans() 162 | 13. data_stochsim.waitingtimes_mean --> data_stochsim.waiting_times_means 163 | Note that the old functions names are not longer supported. 164 | - xlabel, ylabel, and IsLegend are additional arguments in all plotting functions 165 | 166 | - data_stochsim_interpolated --> data_stochsim_grid 167 | - The warning message - "Warning: do not use net stoichiometries for framed-based simulators. Use X > {2} in stead of $pool > X" - is always shown if users of StochPy exploit Cain and/or StochKit solvers 168 | - Solved Potential bug in calculating distributions in StochKit interface 169 | 170 | 171 | Updates 1.0.9 172 | ------------- 173 | - Improved the working of SaveInteractiveSession(filename,path). From this version, iPython remembers all the steps before importing StochPy 174 | - fixed more bugs in CellDivision module (multiple trajectories problem) 175 | - corrected the "version" 176 | 177 | Updates 1.0.8 178 | ------------- 179 | - interactive modification of initial species amounts with ChangeInitialSpeciesAmounts(species,value) 180 | - fixed bugs in CellDivision module 181 | 182 | Updates 1.0.7.1: 183 | ---------------- 184 | - fixed bug in parsing models to StochPy directory 185 | - fixed bug in high-level function DoCompleteStochSim() 186 | 187 | Updates 1.0.7: 188 | -------------- 189 | - StochPyDemo 190 | - improved Export2File function 191 | - corrected a bug for time/amount event at floating numbers 192 | - Previously, simulations done until t=50 where actually done until the first time point where t>50. From this version, simulations stop at the specified value beforehand for all exact implementations 193 | - print waiting times and print mean waiting times works correctly for multiple trajectories 194 | - added exporting of mean waiting times ("meanwaitingtimes") to Export2File 195 | 196 | Updates 1.0.6: 197 | -------------- 198 | - interactive modification of parameters with ChangeParameter(parameter,value) 199 | - corrected bugs in PlotWaitingtimes() 200 | - added and revised some examples in the utilities module 201 | - added alpha version of DoCompleteStochSim(self,error = 0.001,size=100000). Simulation is done until the first four moments converge 202 | - corrected mistakes in the test script 203 | 204 | Updates 1.0.5: 205 | -------------- 206 | - StochPy.SaveInteractiveSession(filename,path) if you want to store the interactive modelling session 207 | - additional argument 'maxpoints2plot' for PlotTimeSimulation and PlotPropensities to allow faster plotting of large simulations. This argument is by default set to 10000 points which is normally enough to get nice and fast plots. 208 | - StochPyCellDivions as an example of performing sequential simulations 209 | - StochPyCain: you can use the Cain solvers in StochPy if you want faster (but less accurate) solvers. You need to download and install a separate package, StochPyCain. 210 | - StochPyKit you can use the StochKit solvers in StochPy if you want faster (but less accurate) solvers. You need to download and install a separate package, StochPyKit. 211 | - You cannot use the Plotting, Printing, or Exporting functions before doing a simulation. In previous versions, a simulation was started if no simulation was done such that plotting was possible, but this version gives an error message. 212 | - Corrected some bugs in the Nucleosome simulator Module 213 | 214 | Updates 1.0.4: 215 | -------------- 216 | - bugs removed from the StochPy Utils part 217 | - reset number of trajectories, timesteps, etc. back to normal setting after the use of the DoTestsuite() function 218 | 219 | Updates 1.0.3: 220 | -------------- 221 | - Bug removed from Interpolated function 222 | - More plotting functionalities 223 | 224 | Updates 1.0.2: 225 | -------------- 226 | - Added StochPyUtils 227 | - Removed a bug in the determination of the distribution, mean, and standard deviation for each species. 228 | - More plotting functionalities 229 | 230 | Updates 1.0.1: 231 | -------------- 232 | - Added binning options to the PlotDistributions functions, which makes this a "probability distribution function" plotter 233 | - significant speed-up for calculating the distributions, means, and standard deviations of each species in the model 234 | - bug removal in the Tau-Leaping implementation 235 | - both data_stochsim and data_stochsim_interpolated are removed as soon as a new model is selected 236 | - more information is available in the help of every function 237 | 238 | Updates 1.0.0: 239 | -------------- 240 | - Added functionality 241 | * Data objects 242 | -> data_stochsim: holds all simulation data from one trajectory 243 | -> data_stochsim_interpolated holds all interpolated simulation data 244 | * if multiple trajectories are simulated, data_stochsim is dumped for every trajectory 245 | By default, the data of the last trajectory is not dumped, but stored in data_stochsim 246 | The user can use the new high-level function, GetTrajectoryData(n) see new High-level functions, to obtain data from one of the trajectories 247 | * Events and Assignments are supported 248 | * More plotting options (title, linestyle 249 | * sim_mode replaces booleans IsTimeSteps and IsEndTime (sim_mode = 'time' or sim_mode = 'steps') 250 | 251 | - New high-level functions (alphabetic order): 252 | * GetMeans() 253 | * GetTrajectoryData(n) where n is the trajectory number 254 | * Mode(sim_mode) note that the user can still use Timesteps(timesteps) and Endtime(endtime) 255 | 256 | - Altered high-level functions (alphabetic order): 257 | * Delete() --> DeleteTempFiles() 258 | * MeanWaitingtimes --> PrintMeanWaitingtimes() 259 | * Overview() --> ShowOverview() 260 | * PlotInterpolSim --> PlotInterpolatedData() 261 | * PrintMeans() --> ShowMeans() 262 | * PrintInterpolSim --> PrintInterpolatedData() 263 | * PrintSDs() --> ShowStandardDeviations() 264 | * Run() --> doStochSim(arguments) [Run() is still available in this version] 265 | * Species() --> ShowSpecies() 266 | 267 | - Altered names (alphabetic order): 268 | * self.endtime and self.timesteps merged into self.sim_end 269 | * self.Interactive --> self.IsInteractive 270 | * self.method --> self.sim_method 271 | * self.ModelDir --> self.model_dir 272 | * self.ModelFile --> self.model_file 273 | * self.OutputDir --> self.output_dir 274 | * self.run_done --> self.IsSimulationDone 275 | * self.TempDir --> self.temp_dir 276 | * self.Traj --> self.sim_trajectories 277 | 278 | - Removed Bugs: 279 | * species names are correct in plots 280 | 281 | Updates 0.9.7: 282 | -------------- 283 | 284 | - StochPy uses a better method for interpolation 285 | - New functions for the nucleosome simulation module 286 | 287 | 288 | Updates 0.9.6: 289 | -------------- 290 | 291 | - Matrix multiplication - X + = np.dot(N,R) - is replaced by: X += N[i], where i is the reaction that fires for the Direct Method, First Reaction Method and the Next Reaction Method. Much more efficient for models with a lot of species 292 | - bugs are fixed in Next Reaction Method. 293 | - sparse models - chain5, chain50, chain500 and chain1500 - were built with ChainModel and added to the example files. These are used to show how the Next Reaction Method works. 294 | - dependency graph is build is a faster way 295 | - temp directory is created, where ".dat" files are saved to 296 | - information about runs (like number of time steps) is written to a log file 297 | - high level function "Testsuite" is added. Automatically, 10.000 runs are done and the mean and standard deviation for each second (0,1,2...) are calculated 298 | 299 | 300 | Updates 0.9.5: 301 | -------------- 302 | - plotting options are improved. User can plot only variables of interest: ssa.PlotTimeSim("A") or ssa.PlotTimeSim(["A","B"]) 303 | - plotting multiple simulations with different colors if 1 species is plotted 304 | - plot screens are allowed to stay open if the user wants to continue working in the interactive session 305 | - bug corrected in the optimized tau leaping algorithm with regard to printing the output to a txt file 306 | - high level functions MeanWaitingTimes() is added 307 | - ".dat" files are deleted after a simulation 308 | - high levels functions for system overview are added: Species(), Overview() 309 | 310 | 311 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=42", "wheel", "numpy>=1.21.6"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "StochPy" 7 | version = "2.5" 8 | description = "StochPy (Stochastic modeling in Python) provides several stochastic simulation algorithms to simulate (bio)chemical systems of reactions in a stochastic manner." 9 | readme = "README.md" 10 | authors = [ 11 | {name = "T.R. Maarleveld", email = "tmd200@users.sourceforge.net"}, 12 | ] 13 | maintainers = [ 14 | {name = "Brett Olivier", email = "tmd200@users.sourceforge.net"}, 15 | ] 16 | license = {text = "BSD License"} 17 | requires-python = ">=3.7" 18 | classifiers = [ 19 | "Development Status :: 5 - Production/Stable", 20 | "Development Status :: 6 - Mature", 21 | "Environment :: Console", 22 | "Intended Audience :: End Users/Desktop", 23 | "Intended Audience :: Science/Research", 24 | "License :: OSI Approved :: BSD License", 25 | "Natural Language :: English", 26 | "Operating System :: OS Independent", 27 | "Programming Language :: Python :: 3.7", 28 | "Programming Language :: Python :: 3.8", 29 | "Programming Language :: Python :: 3.9", 30 | "Programming Language :: Python :: 3.10", 31 | "Programming Language :: Python :: 3.11", 32 | "Topic :: Scientific/Engineering :: Bio-Informatics", 33 | ] 34 | keywords = ["Bioinformatics", "Computational Systems Biology", "Modeling", "Simulation", "Stochastic Simulation Algorithms", "Stochastic"] 35 | dependencies = [ 36 | "numpy>=1.21.6", 37 | "scipy", 38 | "matplotlib" 39 | ] 40 | 41 | [project.urls] 42 | "Homepage" = "http://stochpy.sourceforge.net" 43 | "Download" = "https://github.com/SystemsBioinformatics/stochpy" 44 | "Bug Tracker" = "https://github.com/SystemsBioinformatics/stochpy/issues" 45 | 46 | [tool.setuptools] 47 | package-dir = {"stochpy" = "stochpy"} 48 | packages = [ 49 | "stochpy", 50 | "stochpy.lib", 51 | "stochpy.modules", 52 | "stochpy.pscmodels", 53 | "stochpy.implementations", 54 | "stochpy.core2", 55 | "stochpy.tools" 56 | ] 57 | include-package-data = true -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy 2 | scipy 3 | matplotlib 4 | python-libsbml 5 | lxml 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | from __future__ import division, print_function, absolute_import 3 | __doc__ = "StochPy (Stochastic modeling in Python) provides several stochastic simulation algorithms to simulate (bio)chemical systems of reactions in a stochastic manner." 4 | __version__ = "2.5" 5 | import os 6 | import sys 7 | import time 8 | 9 | local_path = os.path.dirname(os.path.abspath(os.sys.argv[0])) 10 | 11 | 12 | from setuptools import setup, find_packages, find_namespace_packages 13 | 14 | install_requires_src = ['numpy', 'packaging', 'python_libsbml', 'lxml', 'scipy', 'matplotlib', 'ipython'] 15 | extras_require_src = {'all': ['numpy', 'packaging', 'python_libsbml', 'lxml', 'scipy', 'matplotlib', 'ipython']} 16 | tests_require_src = ['numpy', 'packaging', 'python_libsbml', 'lxml', 'scipy', 'matplotlib', 'ipython'] 17 | mydata_files = [] 18 | 19 | #mypackages = ['stochpy','stochpy.lib','stochpy.modules','stochpy.pscmodels','stochpy.implementations','stochpy.core2','stochpy.tools'] # My subpackage list 20 | mypackages = find_packages(where='stochpy', 21 | include=['lib', 'modules', 'pscmodels', 'implementations', 'core2', 'tools']) 22 | 23 | setup( 24 | package_dir={"stochpy": "stochpy"}, 25 | packages=mypackages, 26 | name="StochPy", 27 | version=__version__, 28 | description=__doc__, 29 | long_description=""" 30 | Welcome to the installation of StochPy {0:s}! 31 | StochPy (Stochastic modeling in Python) is a flexible software tool for stochastic simulation in cell biology. It provides various stochastic simulation algorithms, SBML support, analyses of the probability distributions of molecule copy numbers and event waiting times, analyses of stochastic time series, and a range of additional statistical functions and plotting facilities for stochastic simulations. 32 | """.format(__version__), 33 | author="T.R. Maarleveld", 34 | author_email="tmd200@users.sourceforge.net", 35 | maintainer="Brett Olivier", 36 | maintainer_email="tmd200@users.sourceforge.net", 37 | url="http://stochpy.sourceforge.net", 38 | download_url="https://github.com/SystemsBioinformatics/stochpy", 39 | license="BSD License", 40 | keywords="Bioinformatics, Computational Systems Biology, Bioinformatics, Modeling, Simulation, Stochastic Simulation Algorithms, Stochastic", 41 | install_requires=install_requires_src, 42 | extras_require=extras_require_src, 43 | python_requires='>=3.7', 44 | platforms=["Windows", "Linux", "Mac"], # "Solaris", "", "Unix"], 45 | classifiers=[ 46 | 'Development Status :: 5 - Production/Stable', 47 | 'Development Status :: 6 - Mature', 48 | 'Environment :: Console', 49 | 'Intended Audience :: End Users/Desktop', 50 | 'Intended Audience :: Science/Research', 51 | 'Natural Language :: English', 52 | 'Operating System :: OS Independent', 53 | 'Programming Language :: Python :: 3.7', 54 | 'Programming Language :: Python :: 3.8', 55 | 'Programming Language :: Python :: 3.9', 56 | 'Programming Language :: Python :: 3.10', 57 | 'Programming Language :: Python :: 3.11', 58 | 'Topic :: Scientific/Engineering :: Bio-Informatics' 59 | ], 60 | data_files=mydata_files 61 | ) 62 | -------------------------------------------------------------------------------- /stochpy/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy - Stochastic modeling in Python (http://stochpy.sourceforge.net) 4 | 5 | Copyright (C) 2010-2015 T.R Maarlveld, B.G. Olivier, F.J. Bruggeman all rights reserved. 6 | 7 | Timo R. Maarleveld (tmd200@users.sourceforge.net) 8 | Centrum Wiskunde & Informatica, Amsterdam, Netherlands 9 | VU University, Amsterdam, Netherlands 10 | 11 | Permission to use, modify, and distribute this software is given under the 12 | terms of the StochPy (BSD style) license. 13 | 14 | NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 15 | """ 16 | from __future__ import division, print_function, absolute_import 17 | 18 | __doc__ = """ 19 | StochPy: Stochastic Modeling in Python 20 | ===================================== 21 | 22 | StochPy (Stochastic modeling in Python) is a flexible software tool for stochastic simulation in cell biology. It provides various stochastic 23 | simulation algorithms, SBML support, analyses of the probability distributions of molecule copy numbers and event waiting times, analyses of stochastic time 24 | series, and a range of additional statistical functions and plotting facilities for stochastic simulations. 25 | 26 | Options: 27 | -------- 28 | - Stochastic Simulations 29 | - Variety of stochastic simulation output analysis: 30 | --> Time Simulation 31 | --> Distribution 32 | --> Waiting times 33 | --> Propensities 34 | - Cell Division simulations 35 | - SBML and PSC MDL input format. 36 | 37 | StochPy can be used in an interactive Python shell: 38 | 39 | Usage 40 | ----- 41 | >>> import stochpy 42 | >>> utils = stochpy.Utils() 43 | >>> utils.doExample1() 44 | >>> utils.doExample2() 45 | >>> smod = stochpy.SSA() # stochastic simulation algorithm module 46 | >>> help(smod) 47 | >>> help(stochpy.SSA) # (some windows versions) 48 | >>> stochpy? 49 | >>> smod.DoStochSim() 50 | >>> smod.PlotSpeciesTimeSeries() 51 | >>> converter = stochpy.SBML2PSC() 52 | >>> converter?? 53 | >>> help(stochpy.SBML2PSC) 54 | """ 55 | 56 | from .core2.version import __version__ 57 | 58 | import os,shutil,sys 59 | 60 | try: 61 | import readline 62 | _IsReadline = True 63 | except: 64 | _IsReadline = False 65 | 66 | try: 67 | from numpy.distutils.core import setup, Extension 68 | _IsNumPy = True 69 | except Exception as ex: 70 | _IsNumPy = False 71 | print(ex) 72 | print("StochPy requires NumPy") 73 | print("See http://numpy.scipy.org/ for more information about NumPy") 74 | os.sys.exit(-1) 75 | 76 | try: 77 | import matplotlib 78 | _IsMPL = True 79 | except: 80 | _IsMPL = False 81 | print("Warning: The Matplotlib module is not available, so plotting is not possible") 82 | print("Info: See http://matplotlib.sourceforge.net/ for more information about Matplotlib.") 83 | 84 | _IsPlotting = False 85 | try: 86 | import matplotlib.pyplot as plt 87 | _IsPlotting = True 88 | except Exception as er: 89 | print(er) 90 | 91 | def InitiateModels(directory): 92 | """ 93 | Build several models written in PSC MDL and SBML 94 | 95 | Input: 96 | - *directory* (string) 97 | """ 98 | from .pscmodels import Burstmodel 99 | from .pscmodels import BirthDeath 100 | from .pscmodels import ImmigrationDeath 101 | from .pscmodels import DecayingDimerizing 102 | from .pscmodels import Autoreg 103 | from .pscmodels import CellDivision as celldivision 104 | from .pscmodels import GeneDuplication 105 | from .pscmodels import dsmts_001_01 106 | from .pscmodels import dsmts_001_11 107 | from .pscmodels import dsmts_001_19 108 | from .pscmodels import dsmts_002_10 109 | from .pscmodels import dsmts_003_03 110 | from .pscmodels import dsmts_003_04 111 | from .pscmodels import chain5 112 | from .pscmodels import chain50 113 | from .pscmodels import chain500 114 | from .pscmodels import chain1500 115 | from .pscmodels import Isomerization 116 | from .pscmodels import Polymerase 117 | from .pscmodels import TranscriptionIntermediate 118 | from .pscmodels import Schlogl 119 | from .pscmodels import SignalingTimeVaryingL 120 | from .pscmodels import Signaling3cCD 121 | 122 | models = {} 123 | models['Signaling3cCD.psc'] = Signaling3cCD.model 124 | models['SignalingTimeVaryingL.psc'] = SignalingTimeVaryingL.model 125 | models['Schlogl.psc'] = Schlogl.model 126 | models['Burstmodel.psc'] = Burstmodel.model 127 | models['ImmigrationDeath.psc'] = ImmigrationDeath.model 128 | models['BirthDeath.psc'] = BirthDeath.model 129 | models['DecayingDimerizing.psc'] = DecayingDimerizing.model 130 | models['Autoreg.psc'] = Autoreg.model 131 | models['Autoreg.xml'] = Autoreg.xml_model 132 | models['CellDivision.psc'] = celldivision.model 133 | models['GeneDuplication.psc'] = GeneDuplication.model 134 | models['Isomerization.psc'] = Isomerization.model 135 | models['Polymerase.psc'] = Polymerase.model 136 | models['TranscriptionIntermediate.psc'] = TranscriptionIntermediate.model 137 | models['dsmts-001-01.xml.psc'] = dsmts_001_01.model 138 | models['dsmts-001-01.xml'] = dsmts_001_01.xml_model 139 | models['dsmts-001-11.xml.psc'] = dsmts_001_11.model 140 | models['dsmts-001-11.xml'] = dsmts_001_11.xml_model 141 | models['dsmts-001-19.xml.psc'] = dsmts_001_19.model 142 | models['dsmts-001-19.xml'] = dsmts_001_19.xml_model 143 | models['dsmts-002-10.xml.psc'] = dsmts_002_10.model 144 | models['dsmts-002-10.xml'] = dsmts_002_10.xml_model 145 | models['dsmts-003-03.xml.psc'] = dsmts_003_03.model 146 | models['dsmts-003-03.xml'] = dsmts_003_03.xml_model 147 | models['dsmts-003-04.xml.psc'] = dsmts_003_04.model 148 | models['dsmts-003-04.xml'] = dsmts_003_04.xml_model 149 | models['chain5.psc'] = chain5.model 150 | models['chain50.psc'] = chain50.model 151 | models['chain500.psc'] = chain500.model 152 | models['chain1500.psc'] = chain1500.model 153 | 154 | model_names = list(models) 155 | dir_models = os.listdir(directory) 156 | for mod_name in model_names: 157 | if mod_name not in dir_models: 158 | print("Info: Model {0:s} copied to {1:s}".format(mod_name ,directory) ) 159 | file_out = open(os.path.join(directory,mod_name),'w') 160 | file_out.write(models[mod_name]) 161 | file_out.close() 162 | 163 | 164 | output_dir = None 165 | model_dir = None 166 | if os.sys.platform != 'win32': 167 | if not os.path.exists(os.path.join(os.path.expanduser('~'),'Stochpy')): 168 | os.makedirs(os.path.join(os.path.expanduser('~'),'Stochpy')) 169 | if not os.path.exists(os.path.join(os.path.expanduser('~'),'Stochpy', 'pscmodels')): 170 | os.makedirs(os.path.join(os.path.expanduser('~'),'Stochpy','pscmodels')) 171 | if not os.path.exists(os.path.join(os.path.expanduser('~'),'Stochpy', 'temp')): 172 | os.makedirs(os.path.join(os.path.expanduser('~'),'Stochpy','temp')) 173 | 174 | output_dir = os.path.join(os.path.expanduser('~'),'Stochpy') 175 | model_dir = os.path.join(os.path.expanduser('~'),'Stochpy','pscmodels') 176 | temp_dir = os.path.join(os.path.expanduser('~'),'Stochpy','temp') 177 | InitiateModels(model_dir) 178 | else: 179 | if not os.path.exists(os.path.join(os.getenv('HOMEDRIVE')+os.path.sep,'Stochpy')): 180 | os.makedirs(os.path.join(os.getenv('HOMEDRIVE')+os.path.sep,'Stochpy')) 181 | if not os.path.exists(os.path.join(os.getenv('HOMEDRIVE')+os.path.sep,'Stochpy','pscmodels')): 182 | os.makedirs(os.path.join(os.getenv('HOMEDRIVE')+os.path.sep,'Stochpy','pscmodels')) 183 | if not os.path.exists(os.path.join(os.getenv('HOMEDRIVE')+os.path.sep,'Stochpy','temp')): 184 | os.makedirs(os.path.join(os.getenv('HOMEDRIVE')+os.path.sep,'Stochpy','temp')) 185 | 186 | output_dir = os.path.join(os.getenv('HOMEDRIVE')+os.path.sep,'Stochpy',) 187 | model_dir = os.path.join(os.getenv('HOMEDRIVE')+os.path.sep,'Stochpy','pscmodels') 188 | temp_dir = os.path.join(os.getenv('HOMEDRIVE')+os.path.sep,'Stochpy','temp') 189 | InitiateModels(model_dir) 190 | 191 | from .modules.SBML2PSC import SBML2PSC 192 | from .modules.StochSim import SSA 193 | from .modules.StochPyUtils import Utils 194 | from .modules.StochPyCellDivision import CellDivision 195 | from .modules.StochPyDemo import Demo 196 | from .modules import Analysis as Analysis 197 | 198 | try: 199 | from .modules.NucleosomeTool import NucleosomeModelBuilder 200 | from .modules.NucleosomeTool import NucleosomeSimulator 201 | except Exception as er: 202 | pass # ignore 203 | 204 | def DeletePreviousOutput(path,type): 205 | """ 206 | Delete output of earlier simulations 207 | 208 | Input: 209 | - *path* (string) 210 | - *type* (string) 211 | """ 212 | for filename in os.listdir(path): 213 | if filename.endswith(type): 214 | filename_path = os.path.join(path,filename) 215 | os.remove(filename_path) 216 | 217 | def DeleteExistingData(path): 218 | """ 219 | Delete all existing StochKit simulation data 220 | 221 | Input: 222 | - *path* (string) 223 | """ 224 | if os.path.exists(path): 225 | for maps in os.listdir(path): 226 | dir2delete = os.path.join(path,maps) 227 | shutil.rmtree(dir2delete, ignore_errors=True) 228 | 229 | def SaveInteractiveSession(filename='interactiveSession.py',path=output_dir): 230 | """ 231 | Save the interactive session 232 | 233 | Input: 234 | - *filename*: [default = interactiveSession.py'] (string) 235 | - *path*: (string) 236 | """ 237 | if not _IsReadline: 238 | print("Error: install 'readline' first") 239 | elif _IsReadline: 240 | historyPath = os.path.join(path,filename) 241 | if not os.path.exists(path): 242 | os.makedirs(directory) 243 | 244 | readline.write_history_file(historyPath) 245 | file_in = open(historyPath,'r') 246 | history_list = file_in.readlines() 247 | n_import_statement = 0 248 | for command in history_list: 249 | if 'import' in command and 'stochpy' in command: 250 | n_import_statement +=1 251 | 252 | n=0 253 | file_out = open(historyPath,'w') 254 | for command in history_list: 255 | if 'import' in command and 'stochpy' in command: 256 | n+=1 257 | if n==n_import_statement: 258 | file_out.write(command) 259 | file_out.close() 260 | print("Info: Interactive session successfully saved at {0:s}".format(historyPath) ) 261 | print("Info: use 'ipython {0:s} to restart modeling with this interactive session".format(filename) ) 262 | 263 | 264 | DeletePreviousOutput(temp_dir,'.dat') 265 | DeletePreviousOutput(temp_dir,'.xml') 266 | DeletePreviousOutput(temp_dir,'.txt') 267 | DeletePreviousOutput(temp_dir,'temp_parse_module') 268 | DeleteExistingData(temp_dir) 269 | #readline.clear_history() 270 | 271 | print(""" 272 | ####################################################################### 273 | # # 274 | # Welcome to the interactive StochPy environment # 275 | # # 276 | ####################################################################### 277 | # StochPy: Stochastic modeling in Python # 278 | # http://stochpy.sourceforge.net # 279 | # Copyright(C) T.R Maarleveld, B.G. Olivier, F.J Bruggeman 2010-2015 # 280 | # DOI: 10.1371/journal.pone.0079345 # 281 | # Email: tmd200@users.sourceforge.net # 282 | # VU University, Amsterdam, Netherlands # 283 | # Centrum Wiskunde Informatica, Amsterdam, Netherlands # 284 | # StochPy is distributed under the BSD licence. # 285 | ####################################################################### 286 | """) 287 | print("Version {0:s}".format(__version__) ) 288 | print("Output Directory: {0:s}".format(output_dir) ) 289 | print("Model Directory: {0:s}".format(model_dir) ) 290 | #print("Warning: Figure freezing? Try a different matplotlib backend (stochpy.plt.switch_backend) and/or set IsInteractive to False (see user guide)") 291 | -------------------------------------------------------------------------------- /stochpy/core2/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy - Stochastic Modeling in Python (http://stochpy.sourceforge.net) 4 | 5 | Copyright (C) 2010-2014 T.R Maarlveld, B.G. Olivier F.J. Bruggeman all rights reserved. 6 | 7 | Timo R. Maarleveld (tmd200@users.sourceforge.net) 8 | VU University, Amsterdam, Netherlands 9 | 10 | Permission to use, modify, and distribute this software is given under the 11 | terms of the StochPy (BSD style) license. 12 | 13 | NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 14 | """ 15 | -------------------------------------------------------------------------------- /stochpy/core2/version.py: -------------------------------------------------------------------------------- 1 | """ 2 | StochPy Version 3 | =============== 4 | 5 | Written by T.R. Maarleveld, Amsterdam, The Netherlands 6 | E-mail: tmd200@users.sourceforge.net 7 | Last Change: September 25, 2025 8 | """ 9 | 10 | MAJOR = 2 11 | MINOR = 5 12 | MICRO = 0 13 | STATUS = '' 14 | 15 | def current_version(): 16 | return '%s.%s.%s%s' % (MAJOR, MINOR, MICRO, STATUS) 17 | 18 | def current_version_tuple(): 19 | return (MAJOR, MINOR, MICRO) 20 | 21 | __version__ = current_version() 22 | -------------------------------------------------------------------------------- /stochpy/implementations/DelayedNRM.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | Modified Next Reaction Method with delays 4 | ========================================= 5 | 6 | This module performs the Next Reaction Method with delay from Anderson [1], Algorithm 7. 7 | Note that the definition of Cai is used for types of delayed reactions: consuming and non-consuming. 8 | 9 | [1] David F. Anderson "A modified next reaction mehtod for simulating chemical systems with 10 | time dependent propensities and delays", J. Phys. Chem., 2007, 127, 214107 11 | 12 | Author: M. Moinat, T.R. Maarleveld 13 | Adapted from 'NextReactionMethod' by T.R. Maarleveld, Amsterdam, The Netherlands 14 | Last Change: June 08, 2015 15 | """ 16 | from __future__ import division, print_function, absolute_import 17 | import sys,copy,time,os 18 | 19 | from .StochPyTools import __species__,StochPySSA_Shared,np 20 | 21 | ############################################################# 22 | 23 | class DelayedNRM(StochPySSA_Shared): 24 | """ 25 | Modified Next Reaction Method from Anderson 2007 [1]. 26 | 27 | [1] David F. Anderson "A modified next reaction mehtod for simulating chemical systems with 28 | time dependent propensities and delays", J. Phys. Chem., 2007, 127, 214107 29 | 30 | Input: 31 | - *model_file* filename.psc 32 | - *model_dir* /home/user/Stochpy/pscmodels/filename.psc 33 | """ 34 | def __init__(self,model_file,model_dir,IsQuiet=False): 35 | self.Parse(model_file,model_dir,IsQuiet=IsQuiet,IsNRM = True, IsDelayed=True,IsSMM = False) 36 | 37 | def Execute(self,settings,IsStatusBar=False): 38 | """ 39 | Generates steps of the Markov jump process. 40 | 41 | Input: 42 | - *settings* (class object) 43 | """ 44 | if settings.IsSeed: 45 | np.random.seed(5) 46 | 47 | self._IsInitial = True 48 | self.settings = settings 49 | self.sim_t = copy.copy(settings.starttime) 50 | self.X_matrix = copy.deepcopy(settings.X_matrix) 51 | self.fixed_species_amount = copy.deepcopy(self.parse.fixed_species_amount) 52 | 53 | try: 54 | self.volume_code = settings.volume_code 55 | except AttributeError: # No volume_code present in settings 56 | self.volume_code = "self._current_volume = 1" 57 | 58 | #self.species_to_update = [s for s in range(self.n_species)] # ensure that the first run updates all species 59 | self.BuildInits() # Step 1 60 | self.Propensities() # Step 2 61 | 62 | if not self.sim_t: 63 | self.timestep = 1 64 | self.sim_output = [] 65 | self.propensities_output = [] 66 | self.V_output = [] 67 | self._IsTrackPropensities = copy.copy(settings.IsTrackPropensities) 68 | self.SpeciesSelection() 69 | self.RateSelection() 70 | self.SetEvents() # April 15, moved into here, because otherwise each new cell division cycle starts with a time event, if specified 71 | if not settings.IsOnlyLastTimepoint: 72 | self.Initial_Conditions() 73 | # Delayed Direct method specific 74 | self.Tstruct = [(0, np.nan), (np.inf, np.nan)] # Will hold delayed reactions 75 | 76 | #Step 3 Initialize P 77 | m_randoms = np.random.random(size = self.n_reactions) 78 | self.P = -1*np.log(m_randoms) # Exponential (unit rate) distribution 79 | self.T = np.zeros(self.n_reactions) # Step 1 80 | self.BuildTaus() # Step 4, initialization 81 | 82 | nstep_counter = 1 83 | t1 = time.time() 84 | while self.sim_t < settings.endtime and self.timestep < settings.timesteps: 85 | if self.sim_a_mu.sum() == 0 and len(self.Tstruct) <= 2: # All reactants got exhausted and no delayed reactions pending. 86 | settings.endtime = 10**50 87 | break 88 | 89 | self.RunExactTimestep() # Step 5-10 90 | self.HandleEvents() 91 | 92 | #Update system, only if max time or steps is not passed 93 | if (self.sim_t < settings.endtime) and (self.timestep < settings.timesteps): 94 | # Bug Fix Maxim september 05, 2014 95 | if self._IsPerformEvent: 96 | m_randoms = np.random.random(size = self.n_reactions) 97 | self.P = -1*np.log(m_randoms) # Exponential (unit rate) distribution 98 | self.T = np.zeros(self.n_reactions) # Step 1 99 | self.BuildTaus() # Step 4, initialization 100 | self.species_to_update = [s for s in range(self.n_species)] 101 | else: 102 | self.UpdateTP() # Steps 11,12 103 | 104 | self.Propensities() # Step 13 105 | 106 | #Update taus (and order) 107 | self.BuildTaus() # Step 4, iterative 108 | 109 | if not settings.IsOnlyLastTimepoint: #16-01-2014 110 | self.GenerateOutput() 111 | 112 | if (self.sim_t < settings.endtime): 113 | self.timestep += 1 114 | t2 = time.time() 115 | if IsStatusBar and t2-t1> 1: 116 | t1 = time.time() 117 | sys.stdout.write('\rsimulating {0:s}\r'.format('.'*nstep_counter) ) 118 | sys.stdout.flush() 119 | nstep_counter+=1 120 | if nstep_counter > 10: 121 | nstep_counter = 1 122 | 123 | if settings.IsOnlyLastTimepoint or settings.endtime != 10**50: 124 | self.GenerateOutput() 125 | 126 | if IsStatusBar and t1 and not settings.quiet: 127 | sys.stdout.write('\rsimulation done! \n') 128 | 129 | def BuildInits(self): 130 | """ Build initials that are necessary to generate a trajectory """ 131 | self.rFire= np.ones(self.n_reactions) 132 | self.sim_a_mu_zero = [] 133 | for i in range(self.n_reactions): 134 | self.sim_a_mu_zero.append({'t1':0,'a_alpha_old':0,'tau_alpha':0}) 135 | self.sim_taus = None # necessary for iteration 136 | 137 | def BuildTaus(self): 138 | """ (Re)Calculates and orders taus """ 139 | self.sim_taus = (self.P - self.T)/self.sim_a_mu # Calculates all initial taus from P and T arrays. 140 | self.tauPairs = [(tau, reaction_index) for reaction_index, tau in enumerate(self.sim_taus)] 141 | self.tauPairs.sort() # Sorts on reaction times (taus), ascending. 142 | 143 | def UpdateTP(self): 144 | """ Update T and P """ 145 | #Update all T's (= a kind of integral) 146 | self.T += self.sim_a_mu * self.tau # Step 8 147 | 148 | #Only update P of reaction that initiated (so is not a completed delayed reaction). Only random generated each step is here 149 | if not self._IsCompletionDelayed: 150 | random = np.random.random() 151 | self.P[self.reaction_index] += -1*np.log(random) 152 | 153 | def RunExactTimestep(self): 154 | """ Perform a direct SSA time step """ 155 | self.GetTauReaction() # Step 5 156 | self.sim_t += self.tau # Step 6 157 | if self.sim_t < self.settings.endtime: 158 | #Perform reaction 159 | if self._IsCompletionDelayed: # Step 7, complete the delayed reaction. 160 | self.CompleteReaction() 161 | if self.reactions_NonConsuming: # Saves time if no nonconsuming 162 | self.CheckReactantExhaustion() # 9-01-2014 Prevents negative species due to delayed nonconsuming reactions. 163 | else: 164 | self.InitiateReaction() # Steps 8,9,10 165 | 166 | self.prop_to_update = self.parse.dep_graph[self.reaction_index] # Propensities to update, does not see difference N_matrix_reactants or N_matrix_products into account 167 | if self.reaction_index not in self.prop_to_update: 168 | self.prop_to_update.append(self.reaction_index) # Always add fired reaction to update 169 | self.rFire= np.zeros(self.n_reactions) 170 | for pos in self.prop_to_update: 171 | self.rFire[pos] = 1 # Makes sure that in Propensities() only changed propensities get updated 172 | else: 173 | self.sim_t = self.settings.endtime 174 | self.reaction_index = np.nan 175 | 176 | def GetTauReaction(self): 177 | """ Gets minimum tau, corresponding reaction index and whether it initiates or completes """ 178 | #Tau is relative, not absolute as in normal NRM (!!!) 179 | self.minimum_reaction = self.tauPairs[0] # Pick first initiation reaction to occur 180 | self.tau_reaction = self.minimum_reaction[0] # Pick tau of the reaction 181 | 182 | self.minimum_delay = self.Tstruct[1] # From sorted Tstruct (on index 0 is the initial (0, np.nan)) 183 | self.tau_delay = self.minimum_delay[0] - self.sim_t # Convert from absolute to relative time 184 | 185 | if self.tau_reaction <= self.tau_delay: # Initiate a reaction 186 | self.tau = self.tau_reaction 187 | self.reaction_index = self.minimum_reaction[1] 188 | self._IsCompletionDelayed = False 189 | else: # A delayed reaction completes (self.tau_delay < self.tau_reaction) 190 | self.tau = self.tau_delay 191 | self.reaction_index = self.minimum_delay[1] 192 | self._IsCompletionDelayed = True 193 | 194 | def InitiateReaction(self): 195 | """ Initiates a reaction based on being delayed (consuming or nonconsuming) or not """ 196 | if self.reaction_index in self.reactions_Consuming: # Step 10, Consuming delayed 197 | self.X_matrix += self.N_matrix_transpose_reactants[self.reaction_index] # Updates only reactants 198 | self.species_to_update = self.parse.reactant_indices[ self.reaction_index ] 199 | self.add_delay() 200 | elif self.reaction_index in self.reactions_NonConsuming: # Step 9, Non-consuming delayed 201 | self.add_delay() 202 | self.species_to_update = [] 203 | else: # Step 8, A normal, non-delayed reaction 204 | self.X_matrix += self.N_matrix_transpose[self.reaction_index] 205 | self.species_to_update = self.parse.reaction_affects[ self.reaction_index ] 206 | 207 | def CompleteReaction(self): 208 | """ Completes a delayed reaction, depending on consuming or not or not""" 209 | if self.reaction_index in self.reactions_Consuming: # Only updates products 210 | self.X_matrix += self.N_matrix_transpose_products[self.reaction_index] 211 | self.species_to_update = self.parse.product_indices[ self.reaction_index ] 212 | elif self.reaction_index in self.reactions_NonConsuming: # Updates reactants and products 213 | self.X_matrix += self.N_matrix_transpose[self.reaction_index] 214 | self.species_to_update = self.parse.reaction_affects[ self.reaction_index ] 215 | else: 216 | print("This should not happen. A non-delayed reaction is completing with a delay...") 217 | 218 | self.Tstruct.pop(1) # Remove the completion time from the list, assumes Tstruct is sorted and Tstruct[0] = (0,np.nan) 219 | 220 | def add_delay(self): 221 | """ Adds delay time from distribution, specified in DoDelayedStochSim (StochSim.py) """ 222 | delay = self.distr_functions[ self.reaction_index ]( *self.distr_parameters[ self.reaction_index ] ) # Each delayed reaction has its own distribution 223 | 224 | if type(delay) == np.ndarray: 225 | print("Warning! Delay parameters don't match the distribution ({0} with {1})".format(self.distr_functions[ self.reaction_index ], self.distr_parameters[ self.reaction_index ])) 226 | delay = delay[0] 227 | 228 | #Check for negative delays 229 | i=0 230 | while delay < 0: 231 | print("Warning: The chosen distribution ({0}) produced a negative delay. Drawing new delay.".format(self.distr_functions[ self.reaction_index ])) 232 | if i==0: 233 | print("Delay distributions will be distorted and simulation speed will be drastically lower.") 234 | delay = self.distr_functions[ self.reaction_index ]( *self.distr_parameters[ self.reaction_index ] ) 235 | i += 1 236 | if i >= 10: 237 | print("Error: negatives delays keep occuring. Please choose different delay distributions.") 238 | sys.exit(1) 239 | 240 | #Add ABSOLUTE completion time and resort Tstruct 241 | self.Tstruct.insert(-1, (delay + self.sim_t, self.reaction_index)) 242 | self.Tstruct.sort() 243 | 244 | def CheckReactantExhaustion(self): 245 | """ Checks wheter a reactant is exhausted after completion and deletes the pending delayed reactions of this reactant.""" 246 | for r_nonconsuming in self.reactions_NonConsuming: 247 | for r in self.parse.reactant_indices[r_nonconsuming]: 248 | if self.X_matrix[r] == 0: # Reactant Exhausted 249 | # Remove all pending r_nonconsuming reactions from Tstruct, if one of reactants exhausted. Order is not affected. 250 | self.Tstruct = [tau_pair for tau_pair in self.Tstruct if tau_pair[1] != r_nonconsuming] 251 | #list(filter(lambda tau_pair: tau_pair[1] != r_nonconsuming, self.Tstruct)) Python 3.x 252 | -------------------------------------------------------------------------------- /stochpy/implementations/DirectMethod.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | Direct Method 4 | ============= 5 | This module performs the Direct Stochastic Simulation Algorithm from Gillespie (1977) [1]. 6 | 7 | This algorithm is used to generate exact realizations of the Markov jump process. Of course, the algorithm is stochastic, so these realizations are different for each run. 8 | 9 | Only molecule populations are specified. Positions and velocities, such as in Molecular Dynamics (MD) are ignored. This makes the algorithm much faster, because non-reactive molecular collisions can be ignored.different 10 | Still, this exact SSA is quite slow, because it insists on simulating every individual reaction event, which takes a lot of time if the reactant population is large. Furthermore, even larger problems arise if the model contains distinct processes operating on different time scales [2]. 11 | 12 | [1] Gillespie D.T (1977), "Exact stochastic simulation of coupled chemical reactions", J.Phys. Chem. 81:2340-2361 13 | [2] Wilkinson D.J (2009), "Stochastic Modelling for quantitative description of heterogeneous biological systems", Nat Rev Genet; 0(2):122-133 14 | 15 | Written by T.R. Maarleveld, Amsterdam, The Netherlands 16 | E-mail: tmd200@users.sourceforge.net 17 | Last Change: June 23, 2015 18 | """ 19 | 20 | from __future__ import division, print_function, absolute_import 21 | 22 | __doc__ = """ 23 | Direct Method 24 | ============= 25 | This program performs the direct Stochastic Simulation Algorithm from Gillespie (1977) [1].This algorithm is used to generate exact realizations of the Markov jump process. Of course, the algorithm is stochastic, so these realizations are different for each run. 26 | 27 | Only molecule populations are specified. Positions and velocities, such as in Molecular Dynamics (MD) are ignored. This makes the algorithm much faster, because non-reactive molecular collisions can be ignored. 28 | Still, this exact SSA is quite slow, because it insists on simulating every individual reaction event, which takes a lot of time if the reactant population is large. Furthermore, even larger problems arise if the model contains distinct processes operating on different time-scales [2]. 29 | 30 | [1] Gillespie D.T (1977), "Exact stochastic simulation of coupled chemical reactions", J.Phys. Chem. 81:2340-2361 31 | [2] Wilkinson D.J (2009), "Stochastic Modelling for quantitative description of heterogeneous biological systems", Nat Rev Genet; 0(2):122-133 32 | """ 33 | ############################# IMPORTS #################################### 34 | 35 | import sys,copy,time,os,operator 36 | from .StochPyTools import __species__,StochPySSA_Shared,np 37 | 38 | ########################### END IMPORTS ################################## 39 | 40 | class DirectMethod(StochPySSA_Shared): 41 | """ 42 | Direct Stochastic Simulation Algorithm from Gillespie (1977) [1]. 43 | 44 | This algorithm is used to generate exact realizations of the Markov jump process. Of course, the algorithm is stochastic, so these realizations are different for each run. 45 | 46 | [1] Gillespie D.T (1977), "Exact stochastic simulation of coupled chemical reactions", J.Phys. Chem. 81:2340-2361 47 | 48 | Input: 49 | - *model_file* filename.psc 50 | - *model_dir* /home/user/Stochpy/pscmodels/filename.psc 51 | """ 52 | def __init__(self,model_file,model_dir,IsQuiet=False): 53 | self.Parse(model_file,model_dir,IsQuiet=IsQuiet) 54 | 55 | 56 | def Execute(self,settings,IsStatusBar=False): 57 | """ 58 | Generates a trajectory of the Markov jump process. 59 | 60 | Input: 61 | - *settings* (class object) 62 | """ 63 | if settings.IsSeed: 64 | np.random.seed(5) 65 | 66 | self._IsInitial = True 67 | self.settings = settings 68 | self.sim_t = copy.copy(settings.starttime) # does not have to start at zero if we perform sequential simulations 69 | self.X_matrix = copy.deepcopy(settings.X_matrix) 70 | self.fixed_species_amount = copy.deepcopy(self.parse.fixed_species_amount) 71 | 72 | try: 73 | self.volume_code = settings.volume_code 74 | except AttributeError: # No volume_code present in settings 75 | self.volume_code = "self._current_volume = 1" 76 | 77 | #self.species_to_update = [s for s in range(self.n_species)] # ensure that the first run updates all species 78 | self.Propensities() 79 | 80 | if not self.sim_t: 81 | self.timestep = 1 82 | self.sim_output = [] 83 | self.propensities_output = [] 84 | self.V_output = [] 85 | self._IsTrackPropensities = copy.copy(settings.IsTrackPropensities) 86 | self.SpeciesSelection() 87 | self.RateSelection() 88 | self.SetEvents() # April 15, moved into here, because otherwise each new cell division cycle starts with a time event, if specified 89 | if not settings.IsOnlyLastTimepoint: 90 | self.Initial_Conditions() 91 | 92 | nstep_counter = 1 93 | t1 = time.time() 94 | while (self.sim_t < settings.endtime) and (self.timestep < settings.timesteps): 95 | if self.sim_a_0 <= 0: # All reactants got exhausted 96 | settings.endtime = 10**50 97 | break 98 | 99 | self.RunExactTimestep() # Run direct SSA 100 | self.HandleEvents() 101 | 102 | # Update Propensities selectively 103 | if self.sim_t < settings.endtime: 104 | if not self._IsPerformEvent: 105 | self.species_to_update = self.parse.reaction_affects[self.reaction_index] # Determine vars to update 106 | else: 107 | self.species_to_update = [s for s in range(self.n_species)] 108 | 109 | self.Propensities() 110 | 111 | if not settings.IsOnlyLastTimepoint: # Store Output 112 | self.GenerateOutput() 113 | 114 | self._IsPerformEvent = False # set to false (or just to make sure). 115 | t2 = time.time() 116 | if IsStatusBar and t2-t1> 1: 117 | t1 = time.time() 118 | sys.stdout.write('\rsimulating {0:s}\r'.format('.'*nstep_counter) ) 119 | sys.stdout.flush() 120 | nstep_counter+=1 121 | if nstep_counter > 10: 122 | nstep_counter = 1 123 | sys.stdout.write('\rsimulating {0:s} '.format('.'*nstep_counter)) 124 | sys.stdout.flush() 125 | if settings.IsOnlyLastTimepoint or settings.endtime != 10**50: 126 | self.GenerateOutput() 127 | if IsStatusBar and t1 and not settings.quiet: 128 | sys.stdout.write('\rsimulation done! \n') 129 | 130 | 131 | def RunExactTimestep(self): 132 | """ Calculates a time step of the Direct Method """ 133 | if self.sim_t == 0: 134 | randoms = np.random.random(1000) 135 | self.randoms_log = np.log(randoms)*-1 136 | self.randoms = np.random.random(1000) 137 | self.count = 0 138 | elif self.count == 1000: 139 | randoms = np.random.random(1000) 140 | self.randoms_log = np.log(randoms)*-1 141 | self.randoms = np.random.random(1000) 142 | self.count = 0 143 | 144 | self.sim_tau = self.randoms_log[self.count]/float(self.sim_a_0) # reaction time generation 145 | self.sim_r2 = self.randoms[self.count] # Draw random number 2 [0-1] 146 | self.count +=1 147 | 148 | if (self.sim_t + self.sim_tau) < self.settings.endtime: 149 | self.sim_t += self.sim_tau # Time update 150 | self.reaction_index = 0 151 | sum_of_as = self.sim_a_mu[self.reaction_index] 152 | criteria = self.sim_r2*self.sim_a_0 153 | while sum_of_as < criteria: # Use r2 to determine which reaction will occur 154 | self.reaction_index += 1 # Index 155 | sum_of_as += self.sim_a_mu[self.reaction_index] 156 | 157 | try: 158 | self.X_matrix += self.N_matrix_transpose[self.reaction_index] 159 | self.timestep += 1 160 | except MemoryError as ex: 161 | print(ex) 162 | sys.exit() 163 | else: 164 | self.sim_t = self.settings.endtime 165 | self.reaction_index = np.nan 166 | -------------------------------------------------------------------------------- /stochpy/implementations/FirstReactionMethod.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | First Reaction Method 4 | ===================== 5 | This module performs the first reaction method Stochastic Simulation Algorithm from Gillespie (1977). 6 | 7 | This algorithm is used to generate exact realizations of the Markov jump process. Of course, the algorithm is stochastic, so these realizations are different for each run. 8 | 9 | Only molecule populations are specified. Positions and velocities, such as in Molecular Dynamics (MD) are ignored. This makes the algorithm much faster, because non-reactive molecular collisions can be ignored.different 10 | Still, this exact SSA is quite slow, because it insists on simulating every individual reaction event, which takes a lot of time if the reactant population is large. 11 | Furthermore, even larger problems arise if the model contains distinct processes operating on different time-scales. 12 | 13 | Written by T.R. Maarleveld, Amsterdam, The Netherlands 14 | E-mail: tmd200@users.sourceforge.net 15 | Last Change: June 23, 2015 16 | """ 17 | 18 | from __future__ import division, print_function, absolute_import 19 | 20 | ############################## IMPORTS ################################### 21 | 22 | import sys,copy,time,os 23 | from .StochPyTools import __species__,StochPySSA_Shared,np 24 | 25 | ########################### END IMPORTS ################################## 26 | 27 | class FirstReactionMethod(StochPySSA_Shared): 28 | """ 29 | First Reaction Method from Gillespie (1977) 30 | 31 | This algorithm is used to generate exact realizations of the Markov jump process. Of course, the algorithm is stochastic, so these realizations are different for each run. 32 | 33 | Input: 34 | - *model_file* filename.psc 35 | - *model_dir* /home/user/Stochpy/pscmodels/filename.psc 36 | """ 37 | def __init__(self,model_file,model_dir,IsQuiet=False): 38 | self.Parse(model_file,model_dir,IsQuiet=IsQuiet) 39 | 40 | 41 | def Execute(self,settings,IsStatusBar=False): 42 | """ 43 | Generates T trajectories of the Markov jump process. 44 | 45 | Input: 46 | - *settings* (class object) 47 | """ 48 | if settings.IsSeed: 49 | np.random.seed(5) 50 | 51 | self._IsInitial = True 52 | self.settings = settings 53 | self.sim_t = copy.copy(settings.starttime) 54 | self.fixed_species_amount = copy.deepcopy(self.parse.fixed_species_amount) 55 | self.X_matrix = copy.deepcopy(settings.X_matrix) 56 | 57 | #New Volume addition (also modification in self.propensities) 58 | try: 59 | self.volume_code = settings.volume_code 60 | except AttributeError: 61 | self.volume_code = "self._current_volume = 1" # No volume_code present in settings (normal mode) 62 | 63 | self.Propensities() 64 | 65 | if not self.sim_t: 66 | self.timestep = 1 67 | self.sim_output = [] 68 | self.propensities_output = [] 69 | self.V_output = [] 70 | self._IsTrackPropensities = copy.copy(settings.IsTrackPropensities) 71 | self.SpeciesSelection() 72 | self.RateSelection() 73 | self.SetEvents() 74 | if not settings.IsOnlyLastTimepoint: 75 | self.Initial_Conditions() 76 | 77 | nstep_counter = 1 78 | t1 = time.time() 79 | while self.sim_t < settings.endtime and self.timestep < settings.timesteps: 80 | if self.sim_a_0 <= 0: # All reactants got exhausted 81 | settings.endtime = 10**50 82 | break 83 | 84 | #print(self.sim_t) 85 | self.RunExactTimestep() # Run SSA time step 86 | self.HandleEvents() 87 | 88 | # Update Propensities 89 | if self.sim_t < settings.endtime: 90 | if not self._IsPerformEvent: 91 | self.species_to_update = self.parse.reaction_affects[self.reaction_index] # Determine vars to update 92 | else: 93 | self.species_to_update = [s for s in range(self.n_species)] 94 | 95 | self.Propensities() 96 | 97 | if not settings.IsOnlyLastTimepoint: # Store Output 98 | self.GenerateOutput() 99 | 100 | self._IsPerformEvent = False # set to false (or just to make sure). 101 | t2 = time.time() 102 | if IsStatusBar and t2-t1> 1: 103 | t1 = time.time() 104 | sys.stdout.write('\rsimulating {0:s}\r'.format('.'*nstep_counter) ) 105 | sys.stdout.flush() 106 | nstep_counter+=1 107 | if nstep_counter > 10: 108 | nstep_counter = 1 109 | sys.stdout.write('\rsimulating {0:s} '.format('.'*nstep_counter)) 110 | sys.stdout.flush() 111 | if settings.IsOnlyLastTimepoint or settings.endtime != 10**50: 112 | self.GenerateOutput() 113 | if IsStatusBar and t1 and not settings.quiet: 114 | t1 = time.time() 115 | sys.stdout.write('\rsimulation done! \n') 116 | 117 | 118 | def RunExactTimestep(self): 119 | """ Perform a direct SSA time step and pre-generate M random numbers """ 120 | randoms = np.random.random(self.n_reactions) # Regenerate for each time step M random numbers 121 | self.randoms_log = np.log(randoms)*-1 122 | #print(self.sim_t,self.sim_a_mu,self.X_matrix) 123 | self.sim_taus_list = (self.randoms_log[0:self.n_reactions]/self.sim_a_mu).tolist() 124 | self.sim_tau = min(self.sim_taus_list) # Select minimum tau 125 | 126 | if (self.sim_t + self.sim_tau) < self.settings.endtime: 127 | self.sim_t += self.sim_tau 128 | self.reaction_index = self.sim_taus_list.index(self.sim_tau) 129 | try: 130 | self.X_matrix += self.N_matrix_transpose[self.reaction_index] 131 | self.timestep += 1 132 | except MemoryError as ex: 133 | print(ex) 134 | sys.exit() 135 | else: 136 | self.sim_t = self.settings.endtime 137 | self.reaction_index = np.nan 138 | -------------------------------------------------------------------------------- /stochpy/implementations/NextReactionMethod.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | Next Reaction Method 4 | ==================== 5 | This module performs the Next Reaction Method from Gibson and Bruck [1]. Therefore, it is also called the Gibson and Bruck algorithm. 6 | 7 | [1] M.A. Gibson and J. "Bruck Efficient Exact Stochastic Simulation of Chemical Systems with Many Species and Many 8 | Channels", J. Phys. Chem., 2000, 104, 1876-1889 9 | 10 | Written by T.R. Maarleveld, Amsterdam, The Netherlands, Speed improvements by M. Moinat. 11 | E-mail: tmd200@users.sourceforge.net 12 | Last Change: June 23, 2015 13 | """ 14 | 15 | ############################# IMPORTS #################################### 16 | 17 | from __future__ import division, print_function, absolute_import 18 | 19 | import time,os,sys,copy 20 | 21 | from ..tools.Priority_queue import PQDict 22 | from .StochPyTools import __species__,StochPySSA_Shared,np 23 | 24 | ########################### END IMPORTS ################################## 25 | 26 | class NextReactionMethod(StochPySSA_Shared): 27 | """ 28 | Next Reaction Method from Gibson and Bruck 2000 [1]. 29 | 30 | [1] M.A. Gibson and J. "Bruck Efficient Exact Stochastic Simulation of Chemical Systems with Many Species and Many Channels", J. Phys. Chem., 2000,104,1876-1889 31 | 32 | Input: 33 | - *model_file* filename.psc 34 | - *model_dir* /home/user/Stochpy/pscmodels/filename.psc 35 | """ 36 | def __init__(self,model_file,model_dir,IsQuiet=False): 37 | self.Parse(model_file,model_dir,IsQuiet=IsQuiet,IsNRM=True,IsDelayed = False, IsSMM = False) 38 | 39 | 40 | def Execute(self,settings,IsStatusBar=False): 41 | """ 42 | Generates T trajectories of the Markov jump process. 43 | 44 | Input: 45 | - *settings* (class object) 46 | """ 47 | if settings.IsSeed: 48 | np.random.seed(5) 49 | 50 | self._IsInitial = True 51 | self.settings = settings 52 | self.sim_t = copy.copy(settings.starttime) 53 | self.X_matrix = copy.deepcopy(settings.X_matrix) 54 | self.fixed_species_amount = copy.deepcopy(self.parse.fixed_species_amount) 55 | 56 | try: 57 | self.volume_code = settings.volume_code 58 | except AttributeError: 59 | self.volume_code = "self._current_volume = 1" # No volume_code present in settings (normal mode) 60 | 61 | self.BuildPropensityCodes() 62 | self.Propensities() 63 | 64 | if not self.sim_t: 65 | self.timestep = 1 66 | self.sim_output = [] 67 | self.propensities_output = [] 68 | self.V_output = [] 69 | self._IsTrackPropensities = copy.copy(settings.IsTrackPropensities) 70 | self.SpeciesSelection() 71 | self.RateSelection() 72 | self.SetEvents() 73 | self.InitialMonteCarloStep() # Initialize Tau Heap 74 | if not settings.IsOnlyLastTimepoint: 75 | self.Initial_Conditions() 76 | else: 77 | #print(self._IsPerformEvent) 78 | self.UpdateHeap() # Update the heap because of the changed propensities after e.g. division 79 | 80 | nstep_counter = 1 81 | t1 = time.time() 82 | while self.sim_t < self.settings.endtime and self.timestep < self.settings.timesteps: 83 | if self.sim_a_0 <= 0: # All reactants got exhausted 84 | settings.endtime = 10**50 85 | break 86 | 87 | self.RunExactTimestep() # Run time step 88 | self.HandleEvents() 89 | 90 | if self.sim_t < settings.endtime: 91 | self.Propensities() # Update Propensities 92 | self.UpdateHeap() 93 | 94 | if not settings.IsOnlyLastTimepoint: 95 | self.GenerateOutput() # Store Output 96 | 97 | self._IsPerformEvent = False # set to false (or just to make sure). 98 | t2 = time.time() 99 | if IsStatusBar and t2-t1> 1: 100 | t1 = time.time() 101 | sys.stdout.write('\rsimulating {0:s}\r'.format('.'*nstep_counter) ) 102 | sys.stdout.flush() 103 | nstep_counter+=1 104 | if nstep_counter > 10: 105 | nstep_counter = 1 106 | sys.stdout.write('\rsimulating {0:s} '.format('.'*nstep_counter)) 107 | sys.stdout.flush() 108 | if settings.IsOnlyLastTimepoint or settings.endtime != 10**50: 109 | self.GenerateOutput() 110 | 111 | if IsStatusBar and t1 and not settings.quiet: 112 | sys.stdout.write('\rsimulation done! \n') 113 | 114 | 115 | def InitialMonteCarloStep(self): 116 | """ Monte Carlo step to determine all taus and to create a pqdict indexed priority queue """ 117 | randoms = np.random.random(self.n_reactions) # Pre-generate for each reaction random numbers 118 | self.randoms_log_init = -1 * np.log(randoms) 119 | self.sim_taus = self.randoms_log_init/self.sim_a_mu + self.sim_t # Make all taus absolute with sim_t (= given starttime) 120 | 121 | pairs = [(j, self.sim_taus[j]) for j in range(self.n_reactions)] #(key, priority) pairs 122 | self.heap = PQDict(pairs) 123 | 124 | ##Build initial randoms for tau's to come, always at start of execution NRM 125 | self.randoms_log = -1 * np.log( np.random.random(1000) ) # Pre-generate random numbers 126 | self.count = 0 127 | 128 | 129 | def UpdateHeap(self): #03-11-2013 130 | """ Renews the changed propensities in the priority queue heap. """ 131 | if not self._IsPerformEvent: 132 | self.prop_to_update = self.parse.dep_graph[self.reaction_index] # Propensities to update 133 | else: 134 | self.prop_to_update = [r for r in range(self.n_reactions)] 135 | 136 | if self.count >= (1000-len(self.prop_to_update)): 137 | randoms = np.random.random(1000) # Pre-generate random numbers 138 | self.randoms_log = -1 * np.log(randoms) 139 | self.count = 0 140 | 141 | for j in self.prop_to_update: #Updated propensities should also be updated in the heap 142 | if j == self.reaction_index: #5c 143 | tau_new = self.randoms_log[self.count]/self.sim_a_mu[j] + self.sim_t 144 | self.count += 1 145 | else: #5b, changed propensity 146 | if self.sim_a_mu_prev[j] == 0: 147 | ##Note: due to zero propensity (and an inf tau), it is difficult to reuse random. Assume getting new random is faster. 148 | tau_new = self.randoms_log[self.count]/self.sim_a_mu[j] + self.sim_t 149 | self.count += 1 150 | else: #Normal update 151 | tau_alpha = self.sim_taus[j] #Faster than getting from heap directly (self.heap[j]) 152 | tau_new = self.sim_a_mu_prev[j]/self.sim_a_mu[j]*(tau_alpha- self.sim_t) + self.sim_t 153 | #Note, no exception for self.sim_a_mu == 0. Then tau_new automatically becomes infinite (faster than if statement to except this) 154 | self.sim_taus[j] = tau_new #Keep track of the reaction taus, parallel to the heap. 155 | self.heap.updateitem(j, tau_new) #Updates the tau with index j and resorts the heap. 156 | 157 | 158 | def Propensities(self): 159 | """ Determines the propensities to fire for each reaction at the current time point. At t=0, all the rate equations are compiled. """ 160 | #print(self._IsInitial) 161 | if self._IsInitial: 162 | self.sim_a_mu = np.zeros(self.n_reactions) # Initialize a(mu) 163 | [setattr(__species__,self.parse.species[s],self.X_matrix[s]) for s in range(self.n_species)] # Set species quantities 164 | [setattr(__species__,self.fixed_species[s],self.fixed_species_amount[s]) for s in range(len(self.fixed_species))] 165 | self.reaction_fired = -1 # Update all propensities 166 | self._IsInitial=False 167 | else: 168 | self.sim_a_mu_prev = copy.copy(self.sim_a_mu) # Backup old propensity 169 | if self._IsPerformEvent: 170 | [setattr(__species__,self.parse.species[s],self.X_matrix[s]) for s in range(self.n_species)] #Update all species, to be sure. 171 | self.reaction_fired = -1 # Update all propensities 172 | else: 173 | self.species_to_update = self.parse.reaction_affects[self.reaction_index] # Determine vars to update 174 | [setattr(__species__,self.parse.species[s],self.X_matrix[s]) for s in self.species_to_update] 175 | self.reaction_fired = self.reaction_index # Update the propensities that depend on this reaction 176 | 177 | propensity_eval_code = self.propensity_codes[ self.reaction_fired ] #21-11-2013, select code of subset to be updated. [-1] updates all 178 | self.rateFunc(propensity_eval_code, self.sim_a_mu) # Calc. Propensities and put result in sim_a_mu 179 | #print(self.X_matrix,self.sim_a_mu) 180 | assert self.sim_a_mu.min() >= 0, "Error: Negative propensities are found" 181 | self.sim_a_mu = abs(self.sim_a_mu) # -0 to 0 182 | self.sim_a_0 = self.sim_a_mu.sum() 183 | 184 | 185 | def RunExactTimestep(self): 186 | """ Perform a direct SSA time step and pre-generate M random numbers """ 187 | self.minimum = self.heap.peek() # peek() returns item at top of heap (has lowest tau) 188 | self.reaction_index = self.minimum[0] # Pick reaction to executeO(1) 189 | self.sim_tau = self.minimum[1] # Pick tau O(1) 190 | 191 | if self.sim_tau < self.settings.endtime: 192 | self.sim_t = self.sim_tau # New time 193 | try: 194 | self.X_matrix += self.N_matrix_transpose[self.reaction_index] 195 | self.timestep += 1 196 | except MemoryError as ex: 197 | print(ex) 198 | sys.exit() 199 | else: 200 | self.sim_t = self.settings.endtime 201 | self.reaction_index = np.nan 202 | -------------------------------------------------------------------------------- /stochpy/implementations/SingleMoleculeMethod.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | Single Molecule Method (SMM) 4 | ============================ 5 | 6 | Performs full single molecule stochastic simulation with support for also second-order reactions. 7 | 8 | Note: do not use net stoichiometries 9 | 10 | Written by M. Moinat and T.R. Maarleveld, Amsterdam, The Netherlands 11 | Adapted from NextReactionmethod.py by T. Maarleveld. 12 | E-mail: tmd200@users.sourceforge.net 13 | Last Change: June 08, 2015 14 | """ 15 | 16 | from __future__ import division, print_function, absolute_import 17 | 18 | import sys,copy,time,os,re,functools 19 | 20 | from .StochPyTools import __species__,StochPySSA_Shared,np 21 | 22 | ############################################################# 23 | 24 | class SingleMoleculeMethod(StochPySSA_Shared): 25 | """ 26 | Performs full single molecule stochastic simulation with single molecule support for second order reactions. 27 | 28 | Input: 29 | - *File* filename.psc 30 | - *dir* /home/user/Stochpy/pscmodels/filename.psc 31 | """ 32 | def __init__(self,model_file,model_dir,IsQuiet=False): 33 | self.Parse(model_file,model_dir,IsQuiet=IsQuiet,IsTauleaping = False, IsNRM = False, IsDelayed = False, IsSMM =True) 34 | 35 | def EvaluatePropensities(self): 36 | """Evaluate propensities to the rate constants, to get the rate parameter for automatically set exponential reactions. """ 37 | species_amount = 10000 #Replace by 1000, divide by 1000 38 | for j in self.auto_exponential_reactions: 39 | propensity = self.parse.propensities[j] 40 | # Fill in the current 'species_amount' for fixed species. 41 | for s_id, s_amount in zip(self.fixed_species,self.fixed_species_amount): 42 | propensity = re.sub('(__species__.{0:s})([^\w]|$)'.format(s_id), str(s_amount) + r'\2', propensity) 43 | 44 | # Replace all other species by 45 | propensity, n_subs = re.subn('__species__.\w+', str(species_amount), propensity) 46 | 47 | # Evaluates the propensity formula and divide by to correct for each replaced in species. 48 | k = eval(propensity)/(species_amount**n_subs) 49 | try: 50 | k = float(k) 51 | except ValueError: 52 | print("Warning: Defaulting to rate=1 for {0:s}".format(propensity) ) 53 | k = 1.0 54 | if k == 0: # k = 0, scale = large (infinite) 55 | self.distr_parameters[j] = np.inf 56 | else: 57 | self.distr_parameters[j] = [ 1.0/k ] # Convert from rate to scale and make iterable for unpacking 58 | 59 | 60 | def Execute(self,settings,IsStatusBar=False): 61 | """ 62 | Generates T trajectories of the Markov jump process. 63 | 64 | Input: 65 | - *settings* (class object) 66 | """ 67 | if settings.IsSeed: 68 | np.random.seed(5) 69 | 70 | self.settings = settings 71 | self.fixed_species_amount = copy.deepcopy(self.parse.fixed_species_amount) 72 | self.X_matrix = copy.deepcopy(settings.X_matrix) 73 | self.sim_t = copy.copy(settings.starttime) 74 | 75 | try: 76 | self.volume_code = settings.volume_code 77 | except AttributeError: 78 | self.volume_code = "self._current_volume = 1" # No volume_code present in settings (normal mode) 79 | exec(self.volume_code) 80 | 81 | self.EvaluatePropensities() # 31-03-2014. Evaluate propensities of automatically set exponential reactions. 82 | self.InitializeTauArrays() 83 | 84 | if not self.sim_t: # Only at sim_t == 0 85 | self.timestep = 1 86 | self.sim_output = [] 87 | self.propensities_output = [] 88 | self.V_output = [] 89 | self._IsTrackPropensities = False 90 | self.SpeciesSelection() 91 | 92 | self.SetEvents() 93 | if not settings.IsOnlyLastTimepoint: 94 | self.Initial_Conditions() 95 | 96 | nstep_counter = 1 97 | t1 = time.time() 98 | while self.sim_t < settings.endtime and self.timestep < settings.timesteps: 99 | self.n_reactionsPending = functools.reduce(lambda x, y: x + y.size, self.tau_arrays, 0) # Sums sizes of all arrays of taus. 100 | if self.n_reactionsPending <= 0: 101 | settings.endtime = 10**50 102 | break # No molecules can react anymore 103 | 104 | self.RunExactTimestep() 105 | self.HandleEvents() 106 | 107 | if not self._IsPerformEvent: 108 | if (self.sim_t < settings.endtime) and (self.timestep < settings.timesteps): 109 | self.UpdateHeap() 110 | #print(len(self.tau_arrays[0]),len(self.tau_arrays[1])) 111 | else: 112 | # If event performed, recalculate rates (for change in fixed species) and completely rebuild tau arrays. 113 | self.EvaluatePropensities() 114 | self.InitializeTauArrays() 115 | 116 | if not settings.IsOnlyLastTimepoint: 117 | self.GenerateOutput() 118 | 119 | if (self.sim_t < settings.endtime): 120 | self.timestep += 1 121 | 122 | t2 = time.time() 123 | if IsStatusBar and t2-t1> 1: 124 | t1 = time.time() 125 | sys.stdout.write('\r') 126 | sys.stdout.write('simulating {0:s}'.format('.'*nstep_counter) ) 127 | sys.stdout.flush() 128 | nstep_counter+=1 129 | if nstep_counter > 10: 130 | nstep_counter = 1 131 | 132 | if settings.IsOnlyLastTimepoint or settings.endtime != 10**50: 133 | self.GenerateOutput() 134 | 135 | if IsStatusBar and t1 and not settings.quiet: 136 | sys.stdout.write('\rsimulation done! \n') 137 | 138 | def RunExactTimestep(self): 139 | """ Perform a direct SSA time step """ 140 | # Get minimum tau 141 | self.minimums = [(taus.min(),j) for j,taus in enumerate(self.tau_arrays) if taus.size > 0 ] 142 | minimum = min(self.minimums) 143 | self.reaction_index = minimum[1] 144 | self.tau = minimum[0] 145 | 146 | if self.tau < self.settings.endtime: 147 | self.sim_t = self.tau # Tau is absolute 148 | try: 149 | self.X_matrix += self.N_matrix_transpose[self.reaction_index] 150 | except MemoryError as ex: 151 | print(ex) 152 | sys.exit() 153 | else: 154 | self.sim_t = self.settings.endtime 155 | self.reaction_index = np.nan 156 | 157 | def InitializeTauArrays(self): 158 | """ 159 | Initializes a list of the arrays which will contain for every reaction the absolute time of reaction. 160 | 161 | 1) zero-order reaction: an array of one element is created. 162 | 2) first-order reaction: an array with one row and n columns is created. 163 | 3) second-order reaction: an array with n rows and m columns is created. 164 | 4) molecule number 0, an empty array is created. 165 | """ 166 | self.tau_arrays = [] 167 | for j in range(self.n_reactions): 168 | #reactant_indices = self.parse.reactant_indices[j] 169 | depends_on = self.parse.depends_on[j] 170 | array_shape = [self.X_matrix[i] for i in depends_on] # Also works for zero order and no reactants. 171 | #print(0,depends_on) 172 | #print(1,array_shape) 173 | try: 174 | if self.distr_parameters[j] != np.inf: 175 | tau_array = self.distr_functions[j](*self.distr_parameters[j], size = array_shape) # use provided distribution and parameters to generate a tau_array 176 | else: 177 | tau_array = np.array([]) # empty array 178 | except MemoryError: 179 | print("Error: Too many putative reaction times have to be generated") 180 | sys.exit() 181 | #print(2,tau_array) 182 | # Check for negative waiting times. 183 | assert (tau_array >= 0).all(), "Error: Negative waiting time(s) generated by the distribution '{0:s}'!".format(self.distr_functions[j].__name__) 184 | tau_array += self.sim_t # Makes time absolute (for sequential reaction, then sim_t!=0) 185 | 186 | if self.parse.reaction_orders[j] == 2 and depends_on[0] == depends_on[1]: # If e.g. y+y>y2, make y1 reacting with itself infinite. 187 | np.fill_diagonal(tau_array, np.inf) 188 | 189 | self.tau_arrays.append( tau_array ) 190 | 191 | def UpdateHeap(self): 192 | """ Updates the heap by removing reacted molecules and adding formed molecules. Draws waiting time for zero order reaction.""" 193 | self.Remove_Taus_Reactants() 194 | self.Add_Taus_Products() 195 | # If zero order reaction fired, replace its tau. 196 | if self.parse.reaction_orders[ self.reaction_index ] == 0: 197 | j = self.reaction_index 198 | new_tau = self.distr_functions[j](*self.distr_parameters[j]) 199 | assert new_tau >= 0, "Error: Negative waiting time(s) generated by the distribution '{0:s}'!".format(self.distr_functions[j].__name__) 200 | self.tau_arrays[j] = new_tau + self.sim_t 201 | 202 | def Remove_Taus_Reactants(self): 203 | """ 204 | For the molecules reacted in the last reaction, delete the waiting times (taus) for these specific molecules. 205 | """ 206 | # Search for specific molecules that reacted. 207 | molecules = [x[0] for x in np.where(self.tau_arrays[self.reaction_index] == self.tau)] # Specific molecule(s) that reacted. If self.tau occurs more than once, the where takes the first. 208 | #species_reacted = self.parse.reactant_indices[self.reaction_index] # Species' that reacted in last reaction. 209 | species_reacted = self.parse.depends_on[self.reaction_index] # Species' that reacted in last reaction. 210 | molecules_reacted = list(zip(molecules, species_reacted)) # =[(mol1,sp1),(mol2,sp2)]; sp1_mol1 reacted with sp2_mol2. e.g. x_3 with y_4. 211 | molecules_reacted.sort( reverse=True ) # Prevents indexing error. (If y needs to be deleted twice, always delete the one with higher index first. ) 212 | # Delete the molecules from every array they occur in. 213 | for (mol_num, s_index) in molecules_reacted: 214 | reactions_affected = self.parse.species_depends_on[ s_index ] 215 | for j in reactions_affected: 216 | if self.distr_parameters[j] != np.inf: # reactions with "inf" have k=0 217 | if self.parse.reaction_orders[j] == 1: 218 | self.tau_arrays[j] = np.delete(self.tau_arrays[j], mol_num) 219 | elif self.parse.reaction_orders[j] == 2: 220 | reacts = self.parse.depends_on[j] 221 | axis = reacts.index(s_index) # Specifying molecule on row or column 222 | self.tau_arrays[j] = np.delete(self.tau_arrays[j], mol_num, axis) 223 | if reacts[0] == reacts[1]: # e.g. y + y > z. axis was 0. 224 | self.tau_arrays[j] = np.delete(self.tau_arrays[j], mol_num, 1) # Also delete the molecule on the columns. 225 | else: # An error should be raised earlier, but just to be safe 226 | raise Warning("Error: The SMM does not support third-order reactions. Use the fSMM and model it as a normal reaction.") 227 | 228 | def Add_Taus_Products(self): 229 | """ For the molecules produced in the last reaction, add the absolute tau for every reaction they are reactant in. """ 230 | species_produced = self.products[self.reaction_index] # self.parse.product_indices 231 | for s_index in species_produced: 232 | reactions_affected = self.parse.species_depends_on[s_index] 233 | for j in reactions_affected: 234 | #reacts = self.parse.reactant_indices[j] 235 | reacts = self.parse.depends_on[j] 236 | #print(3,j,self.tau_arrays[j]) 237 | if self.parse.reaction_orders[j] == 1: 238 | new_tau = self.distr_functions[j](*self.distr_parameters[j]) 239 | assert new_tau >= 0, "Error: Negative waiting time(s) generated by the distribution '{0:s}'!".format(self.distr_functions[j].__name__) 240 | self.tau_arrays[j] = np.append( self.tau_arrays[j], new_tau + self.sim_t ) 241 | elif self.parse.reaction_orders[j] == 2: # Second-order reaction 242 | axis = reacts.index(s_index) # Check whether produced species on row (=0) or column (=1) 243 | temp_arr = self.tau_arrays[j] 244 | if axis == 0: 245 | new_row = self.distr_functions[j](*self.distr_parameters[j], size = temp_arr.shape[1]) # Taus for every molecule it reacts with 246 | assert (new_row >= 0).all(), "Error: Negative waiting time(s) generated by the distribution '{0:s}'!".format(self.distr_functions[j].__name__) 247 | self.tau_arrays[j] = np.row_stack( (temp_arr, new_row + self.sim_t) ) 248 | elif axis == 1: 249 | new_col = self.distr_functions[j](*self.distr_parameters[j], size = temp_arr.shape[0]) 250 | assert (new_col >= 0).all(), "Error: Negative waiting time(s) generated by the distribution '{0:s}'!".format(self.distr_functions[j].__name__) 251 | self.tau_arrays[j] = np.column_stack( (temp_arr, new_col + self.sim_t) ) 252 | 253 | if reacts[0] == reacts[1]: # axis was 0, row already filled 254 | new_col = self.distr_functions[j](*self.distr_parameters[j], size = temp_arr.shape[0]+1) 255 | assert (new_col >= 0).all(), "Error: Negative waiting time(s) generated by the distribution '{0:s}'!".format(self.distr_functions[j].__name__) 256 | new_col[-1] = np.inf # Put infinite on the diagonal 257 | self.tau_arrays[j] = np.column_stack( (self.tau_arrays[j], new_col + self.sim_t) ) 258 | else: # An error should be raised earlier, but just to be safe 259 | raise Warning("Error: The SMM does not support third-order reactions. Use the fSMM and model it as a normal reaction.") 260 | #print(4,j,self.tau_arrays[j]) 261 | -------------------------------------------------------------------------------- /stochpy/implementations/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy - Stochastic Modeling in Python (http://stochpy.sourceforge.net) 4 | 5 | Copyright (C) 2010-2014 T.R Maarlveld, B.G. Olivier F.J. Bruggeman all rights reserved. 6 | 7 | Timo R. Maarleveld (tmd200@users.sourceforge.net) 8 | VU University, Amsterdam, Netherlands 9 | 10 | Permission to use, modify, and distribute this software is given under the 11 | terms of the StochPy (BSD style) license. 12 | 13 | NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 14 | """ 15 | -------------------------------------------------------------------------------- /stochpy/lib/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy - Stochastic Modeling in Python (http://stochpy.sourceforge.net) 4 | 5 | Copyright (C) 2010-2013 T.R Maarlveld, B.G. Olivier F.J. Bruggeman all rights reserved. 6 | 7 | Timo R. Maarleveld (tmd200@users.sourceforge.net) 8 | VU University, Amsterdam, Netherlands 9 | 10 | Permission to use, modify, and distribute this software is given under the 11 | terms of the StochPy (BSD style) license. 12 | 13 | NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 14 | """ 15 | -------------------------------------------------------------------------------- /stochpy/modules/PyscesInterfaces.py: -------------------------------------------------------------------------------- 1 | """ 2 | PySCeS - Python Simulator for Cellular Systems (http://pysces.sourceforge.net) 3 | 4 | Copyright (C) 2004-2014 B.G. Olivier, J.M. Rohwer, J.-H.S Hofmeyr all rights reserved, 5 | 6 | Brett G. Olivier (bgoli@users.sourceforge.net) 7 | Triple-J Group for Molecular Cell Physiology 8 | Stellenbosch University, South Africa. 9 | 10 | Permission to use, modify, and distribute this software is given under the 11 | terms of the PySceS (BSD style) license. See LICENSE.txt that came with 12 | this distribution for specifics. 13 | 14 | NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 15 | Brett G. Olivier 16 | """ 17 | from __future__ import division, print_function, absolute_import 18 | 19 | __doc__ = """ 20 | PyscesInterfaces 21 | ---------------- 22 | 23 | Interfaces converting to and from PySCeS models - makes use of Brett's Core2 24 | """ 25 | 26 | import os 27 | from ..core2.PyscesCore2Interfaces import PscToCore, SbmlToCore, CoreToPsc, CoreToSBML 28 | from ..core2.PyscesCore2 import NewCore 29 | 30 | from stochpy import model_dir, output_dir 31 | 32 | class Core2interfaces(object): 33 | """ 34 | Defines interfaces for translating PySCeS model objects into and from other formats. 35 | """ 36 | core = None 37 | sbml = None 38 | core2sbml = None 39 | core2psc = None 40 | sbml2core = None 41 | sbml_level = 2 42 | sbml_version = 1 43 | 44 | def __buildPscComponents__(self): 45 | """ 46 | Builds the PSC file 47 | """ 48 | self.core2psc.setHeader() 49 | self.core2psc.setFixed() 50 | self.core2psc.setCompartments() 51 | self.core2psc.setFunctions() 52 | self.core2psc.setReactions() 53 | self.core2psc.setAssignmentRules() 54 | self.core2psc.setRateRules() 55 | self.core2psc.setEvents() 56 | self.core2psc.setSpecies() 57 | self.core2psc.setParameters() 58 | self.core2psc.setNotes() 59 | 60 | def __buildSbmlComponents__(self): 61 | """ 62 | The SBML file build commands 63 | """ 64 | self.core2sbml.createModel() 65 | self.core2sbml.setDescription() 66 | self.core2sbml.setUnits() 67 | self.core2sbml.setCompartments() 68 | self.core2sbml.setSpecies() 69 | self.core2sbml.setParameters() 70 | self.core2sbml.setReactions() 71 | self.core2sbml.setEvents() 72 | self.core2sbml.setRules() 73 | 74 | def writeMod2SBML(self, mod, filename=None, directory=None, iValues=True, getdocument=False, getstrbuf=False): 75 | """ 76 | Writes a PySCeS model object to an SBML file. 77 | 78 | - *filename*: writes .xml or .xml if None 79 | - *directory*: (optional) an output directory 80 | - *iValues*: if True then the models initial values are used (or the current values if False). 81 | - *getdocument*: if True an SBML document object is returned instead of writing to disk or 82 | - *getstrbuf*: if True a StringIO buffer is returned instead of writing to disk 83 | """ 84 | self.core = NewCore(mod, iValues=iValues) 85 | ## assert os.sys.platform != 'win32', '\nSBML translation currently only supported on Linux (Mac?)' 86 | assert self.core != None, "\nPlease set a PySCeS model or Core2 object" 87 | self.core2sbml = CoreToSBML(self.core) 88 | self.core2sbml.level = self.sbml_level 89 | self.core2sbml.version = self.sbml_version 90 | assert self.core2sbml.SBML != None, "\nProblems loading SBML/Python interface" 91 | self.__buildSbmlComponents__() 92 | if filename == None: filename = self.core.name 93 | if filename[-4:] != '.xml': filename += '.xml' 94 | if getdocument: 95 | return self.core2sbml.getSBMLdocument() 96 | elif getstrbuf: 97 | return self.core2sbml.getSBMLFileAsStrBuf() 98 | else: 99 | self.core2sbml.writeSBML2file(filename, directory) 100 | 101 | 102 | def readSBMLToCore(self, filename, directory=None, netStoich=True): 103 | """ 104 | Reads the SBML file specified with filename and converts it into 105 | a core2 object stochpy.interface.core 106 | 107 | - *filename*: the SBML file 108 | - *directory*: (optional) the SBML file directory None means try the current working directory 109 | - *netStoich* [default = True] use net stoichiometry 110 | """ 111 | if directory != None: 112 | fpath = os.path.join(directory, filename) 113 | assert os.path.exists(fpath), "\nFile \"{0:s}\" does not exist!".format(fpath) 114 | 115 | self.sbml2core = SbmlToCore() 116 | self.sbml2core.getSbmlStringFromDisk(filename, Dir=directory) 117 | self.sbml2core.getSbmlModel() 118 | self.sbml2core.getParsedModel() 119 | self.sbml2core.getUnits() 120 | self.core = NewCore(self.sbml2core, netStoich=netStoich) 121 | 122 | def writeCore2PSC(self, filename=None, directory=None, getstrbuf=False): 123 | """ 124 | Writes a Core2 object to a PSC file. 125 | 126 | - *filename*: writes .xml or .xml if None 127 | - *directory*: (optional) an output directory 128 | - *getstrbuf*: if True a StringIO buffer is returned instead of writing to disk 129 | """ 130 | assert self.core != None, "\nPlease set a PySCeS model or Core2 object" 131 | ## print 'Using existing self.core' 132 | self.core2psc = CoreToPsc(self.core) 133 | self.__buildPscComponents__() 134 | if filename == None: filename = self.core.name 135 | if filename[-4:] != '.psc': filename += '.psc' 136 | if not getstrbuf: 137 | self.core2psc.write(filename, directory, getstrbuf) 138 | else: 139 | return self.core2psc.write(filename, directory, getstrbuf) 140 | 141 | 142 | def writeCore2SBML(self, filename=None, directory=None, getdocument=False): 143 | """ 144 | Writes Core2 object to an SBML file. 145 | 146 | - *filename*: writes .xml or .xml if None 147 | - *directory*: (optional) an output directory 148 | - *getdocument*: if True an SBML document object is returned instead of writing to disk or 149 | """ 150 | assert self.core != None, "\nPlease set a PySCeS model or Core2 object" 151 | ## print 'Using existing self.core' 152 | self.core2sbml = CoreToSBML(self.core) 153 | self.core2sbml.level = self.sbml_level 154 | self.core2sbml.version = self.sbml_version 155 | assert self.core2sbml.SBML != None, "\nProblems loading SBML/Python interface" 156 | self.__buildSbmlComponents__() 157 | if filename == None: filename = self.core.name 158 | if filename[-4:] != '.xml': filename += '.xml' 159 | if not getdocument: 160 | self.core2sbml.writeSBML2file(filename, directory) 161 | else: 162 | return self.core2sbml.getSBMLdocument() 163 | 164 | def convertSBML2PSC(self, sbmlfile, sbmldir=None, pscfile=None, pscdir=None, netStoich=True,quiet=False): 165 | """ 166 | Convert an SBML file to a PySCeS MDL input file. 167 | 168 | - *sbmlfile*: the SBML file name 169 | - *sbmldir*: the directory of SBML files (if None current working directory is assumed) 170 | - *pscfile*: the output PSC file name (if None *sbmlfile*.psc is used) 171 | - *pscdir*: the PSC output directory (if None the stochpy.model_dir is used) 172 | - *netStoich*: defaults to True, use a net stoichiometry 173 | 174 | """ 175 | if sbmldir == None or not os.path.exists(sbmldir): 176 | sbmldir = os.getcwd() 177 | if not os.path.exists(os.path.join(sbmldir,sbmlfile)): 178 | raise RuntimeError('\nSBML file \"{0:s}\" does not exist!'.format(os.path.join(sbmldir,sbmlfile)) ) 179 | if pscdir == None or not os.path.exists(pscdir): 180 | pscdir = model_dir 181 | if pscfile == None: 182 | pscfile = '{0:s}.psc'.format(sbmlfile) 183 | 184 | self.readSBMLToCore(filename=sbmlfile, directory=sbmldir, netStoich=netStoich) 185 | self.writeCore2PSC(filename=pscfile, directory=pscdir, getstrbuf=False) 186 | if not quiet: 187 | print('\nSBML2PSC\nin : {0:s}\nout: {1:s}'.format(os.path.join(sbmldir,sbmlfile),os.path.join(pscdir,pscfile))) 188 | 189 | # def convertPSC2SBML(self, pscfile, pscdir=None, sbmlfile=None, sbmldir=None, netStoich=True): 190 | # """ 191 | # Convert an SBML file to a PySCeS MDL input file. 192 | # 193 | # - *pscfile*: the output PSC file name 194 | # - *pscdir*: the PSC output directory (if None current working directory is assumed) 195 | # - *sbmlfile*: the SBML file name (if None *sbmlfile*.psc is used) 196 | # - *sbmldir*: the directory of SBML files (if None the stochpy.model_dir is used) 197 | # - *netStoich*: defaults to True, use a net stoichiometry 198 | # """ 199 | # if pscdir == None or not os.path.exists(pscdir): 200 | # pscdir = os.getcwd() 201 | # if not os.path.exists(os.path.join(pscdir,pscfile)): 202 | # raise RuntimeError('\nSBML file \"{0:s}\" does not exist!'.format(os.path.join(pscdir,pscfile))) 203 | # if sbmldir == None or not os.path.exists(sbmldir): 204 | # sbmldir = model_dir 205 | # if sbmlfile == None: 206 | # sbmlfile = '{0:s}.psc'.format(pscfile) 207 | 208 | # self.readPSCToCore(filename=pscfile, directory=pscdir, netStoich=netStoich) 209 | # self.writeCore2SBML(filename=sbmlfile, directory=sbmldir, getstrbuf=False) 210 | # print('\nPSC2SBML\nin : {0:s}\nout: {1:s}'.format(os.path.join(pscdir,pscfile),os.path.join(sbmldir,sbmlfile))) 211 | -------------------------------------------------------------------------------- /stochpy/modules/SBML2PSC.py: -------------------------------------------------------------------------------- 1 | """ 2 | Written by T.R. Maarleveld, Amsterdam, The Netherlands 3 | E-mail: tmd200@users.sourceforge.net 4 | Last Change: Augustus 06, 2014 5 | """ 6 | from __future__ import division, print_function, absolute_import 7 | 8 | from . import PyscesInterfaces 9 | 10 | class SBML2PSC(): 11 | """ 12 | Module that converts SBML models into PSC models if libxml and libsbml are installed 13 | 14 | Usage: 15 | >>> converter = stochpy.SBML2PSC() 16 | >>> converter.SBML2PSC('Burstmodel.xml','/home/user/Stochpy/pscmodels/') 17 | """ 18 | def __init__(self,sbmlfile, sbmldir=None, pscfile=None, pscdir=None,quiet=False): 19 | """ 20 | Converts a SBML file to a PySCeS MDL input file. 21 | 22 | Input: 23 | - *sbmlfile*: the SBML file name 24 | - *sbmldir*: [default = None] the directory of SBML files (if None current working directory is assumed) 25 | - *pscfile*: [default = None] the output PSC file name (if None *sbmlfile*.psc is used) 26 | - *pscdir*: [default = None] the PSC output directory (if None the pysces.model_dir is used) 27 | """ 28 | PyscesInterfaces.Core2interfaces().convertSBML2PSC(sbmlfile,sbmldir,pscfile,pscdir, netStoich=True,quiet=quiet) 29 | -------------------------------------------------------------------------------- /stochpy/modules/SimulatorOutput2StochPy.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | Cain/StochSkit Output to StochPy 4 | ================================ 5 | 6 | Written by T.R. Maarleveld, Amsterdam, The Netherlands 7 | E-mail: tmd200@users.sourceforge.net 8 | Last Change: January 06, 2015 9 | """ 10 | from __future__ import division, print_function, absolute_import 11 | 12 | import numpy as np 13 | 14 | class Species(): 15 | def __init__(self): 16 | """ Object that is created to store the species quantities """ 17 | pass 18 | 19 | def GetCainTimeSim(species_quantities,sim_time,n_frames,n_species): 20 | """ 21 | get Cain time simulation output 22 | 23 | Input: 24 | - *species_quantities* (list) 25 | - *sim_time* (float) 26 | - *n_frames* (int) 27 | - *n_species* (int) 28 | """ 29 | sim_output = [] 30 | n=0 31 | species_quantities = [int(s_amount) for s_amount in species_quantities] 32 | for frame in range(n_frames): 33 | time_event = [sim_time[frame]] 34 | time_event += [species_quantities[n+m] for m in range(n_species)] 35 | n+=n_species 36 | sim_output.append(time_event) 37 | return np.array(sim_output,dtype=int) 38 | 39 | def GetStochKitTimeSim(file_in,sim_time,species_order): 40 | """ 41 | get stochkit time simulation output 42 | 43 | Input: 44 | - *file_in* (file) 45 | - *sim_time* (float) 46 | - *species_order* (list) 47 | """ 48 | sim_output = [] 49 | IsInit = True 50 | frame_id = 0 51 | for line in file_in: 52 | dat = line.strip().split('\t') 53 | if IsInit and dat[0] == 'time': 54 | time_event_len = len(dat) 55 | species = dat[1:] 56 | IsInit = False 57 | else: 58 | time_event = [int(s_amount) for s_amount in dat[1:]] 59 | time_event.insert(0,sim_time[frame_id]) 60 | sim_output.append(time_event) 61 | frame_id +=1 62 | #print(species,species_order) 63 | Arr_sim_output = np.array(sim_output,dtype=int) 64 | if species != species_order: 65 | Arr_sim_output_cc = np.array(sim_output,dtype=int) 66 | for i,s_id in enumerate(species_order): 67 | s_index = species.index(s_id) 68 | Arr_sim_output[:,i+1] = Arr_sim_output_cc[:,s_index+1] 69 | 70 | return Arr_sim_output,species_order 71 | 72 | def GetPropensities(SSAmodule,sim_output): 73 | """ 74 | get Propensities 75 | 76 | Input: 77 | - *SSAmodule* (python object) 78 | - *sim_output* (list) 79 | """ 80 | code_str = """""" 81 | for i in range(SSAmodule.n_reactions): 82 | code_str += "prop_vec[{0:d}]={1}\n".format(i,SSAmodule.parse.propensities[i]) 83 | req_eval_code = compile(code_str,"RateEqEvaluationCode","exec") 84 | __species__ = Species() 85 | propensities_output = [] 86 | propensities_distributions = [{} for i in range(SSAmodule.n_reactions)] 87 | for i in range(len(sim_output)): 88 | prop_vec = np.zeros(SSAmodule.n_reactions) 89 | [setattr(__species__,SSAmodule.parse.species[s],sim_output[i][s+1]) for s in range(SSAmodule.n_species)] 90 | try: 91 | exec(req_eval_code) 92 | except Exception as er: 93 | print(er) 94 | prop_vec = list(prop_vec) 95 | prop_vec.insert(0,sim_output[i][0]) 96 | propensities_output.append(prop_vec) 97 | return propensities_output#,propensities_distributions 98 | -------------------------------------------------------------------------------- /stochpy/modules/StochPyDemo.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | Demo of StochPy Functionalities 4 | =============================== 5 | 6 | Written by T.R. Maarleveld, Amsterdam, The Netherlands 7 | E-mail: tmd200@users.sourceforge.net 8 | Last Change: August 06, 2015 9 | """ 10 | from __future__ import division, print_function, absolute_import 11 | 12 | import stochpy 13 | smod = stochpy.SSA() 14 | 15 | try: input = raw_input # raw_input is renamed to input in python 3.x 16 | except NameError: pass 17 | 18 | class Demo(): 19 | def __init__(self,DoSimulations = True): 20 | """ 21 | Demo class, by default all demo's are simulated. 22 | 23 | Input: 24 | - *DoSimulations* (Boolean) 25 | """ 26 | input("press any button to continue\n") 27 | if DoSimulations: 28 | self.DoDemoSimulations() 29 | 30 | def Demo1(self): 31 | """ Use the Immigration-Death model for doing basic simulations with the direct method, some plotting and exportation of results """ 32 | print("\n### (1) Basic simulations with the Immigration-Death model ###") 33 | input("press any button to continue\n") 34 | print(">>> smod = stochpy.SSA() # start SSA module") 35 | print(">>> smod.DoStochSim(IsTrackPropensities=True)") 36 | smod.DoStochSim(IsTrackPropensities=True) 37 | print(">>> smod.PrintWaitingtimesMeans()") 38 | smod.PrintWaitingtimesMeans() 39 | print(">>> smod.PlotSpeciesTimeSeries() # plot time series of species") 40 | smod.PlotSpeciesTimeSeries() 41 | print(">>> smod.PlotPropensitiesTimeSeries() # plot time series of propensities") 42 | smod.PlotPropensitiesTimeSeries() 43 | print(">>> smod.PlotWaitingtimesDistributions()") 44 | smod.PlotWaitingtimesDistributions() 45 | print(">>> smod.Export2File()") 46 | smod.Export2File() 47 | print(">>> smod.Export2File(analysis='timeseries',datatype='propensities')") 48 | smod.Export2File(analysis='timeseries',datatype='propensities') 49 | print(">>> smod.Export2File(analysis='distribution',datatype='waitingtimes')") 50 | smod.Export2File(analysis='distribution',datatype='waitingtimes') 51 | 52 | def Demo2(self): 53 | """ Use the Immigration-Death model for a stochastic simulation with multiple trajectories """ 54 | print("\n### (2) Multiple trajectories ###") 55 | input("press any button to continue\n") 56 | print(">>> smod.DoStochSim(trajectories=3,end=3000,mode='steps') # multiple trajectories") 57 | smod.DoStochSim(trajectories=3,end=3000) 58 | print(">>> smod.PlotSpeciesTimeSeries()") 59 | smod.PlotSpeciesTimeSeries() 60 | print(">>> smod.data_stochsim.simulation_trajectory # trajectory number") 61 | smod.data_stochsim.simulation_trajectory 62 | print(">>> smod.PrintSpeciesMeans()") 63 | smod.PrintSpeciesMeans() 64 | print(">>> smod.PrintSpeciesStandardDeviations") 65 | smod.PrintSpeciesStandardDeviations() 66 | print(">>> smod.GetTrajectoryData(1) # switch to data from trajectory 1") 67 | smod.GetTrajectoryData(1) 68 | print(">>> smod.data_stochsim.simulation_trajectory # trajectory number") 69 | smod.data_stochsim.simulation_trajectory 70 | print(">>> smod.PrintSpeciesMeans()") 71 | smod.PrintSpeciesMeans() 72 | print(">>> smod.PrintSpeciesStandardDeviations") 73 | smod.PrintSpeciesStandardDeviations() 74 | 75 | def Demo3(self): 76 | """ Use the Immigration-Death model to demonstrate probability density functions """ 77 | print("\n### (3) Probability density functions (100000 time points) ###") 78 | input("press any button to continue\n") 79 | print(">>> smod.DoStochSim(trajectories=1,end=1000000,mode='steps',IsTrackPropensities=1)") 80 | smod.DoStochSim(trajectories=1,end=100000,mode='steps',IsTrackPropensities=1) 81 | print(">>> smod.PlotSpeciesDistributions() # plot species distributions") 82 | smod.PlotSpeciesDistributions() 83 | print(">>> smod.PlotPropensitiesDistributions('R2')") 84 | smod.PlotPropensitiesDistributions('R2') 85 | 86 | def Demo4(self): 87 | """ Use Birth-Death model to illustrate averaging multiple simulations """ 88 | print("\n### (4) Averaging multiple simulations with the Birth-Death model ###") 89 | input("press any button to continue\n") 90 | print(">>> smod.Model('dsmts-001-01.xml.psc') # parse a different model") 91 | smod.Model('dsmts-001-01.xml.psc') 92 | print(">>> smod.DoStochSim(trajectories=1000,end=50,mode='time')") 93 | smod.DoStochSim(trajectories=1000,end=50,mode='time') 94 | print(">>> smod.GetRegularGrid(n_samples=51)") 95 | smod.GetRegularGrid(n_samples=51) 96 | print(">>> smod.PrintAverageSpeciesTimeSeries()") 97 | smod.PrintAverageSpeciesTimeSeries() 98 | print(">>> smod.PlotAverageSpeciesTimeSeries()") 99 | smod.PlotAverageSpeciesTimeSeries() 100 | print(">>> smod.Export2File(analysis='timeseries',datatype='species', IsAverage = True)") 101 | smod.Export2File(analysis='timeseries',datatype='species', IsAverage = True) 102 | 103 | def Demo5(self): 104 | """ Use Decaying-Dimerizing model to illustrate performance differences between different stochastic simulation algorithms """ 105 | print("\n### (5) Use Decaying-Dimerizing model to illustrate performance differences between different stochastic simulation algorithms ###") 106 | input("press any button to continue\n") 107 | print(">>> smod.Model('DecayingDimerizing.psc')") 108 | smod.Model('DecayingDimerizing.psc') 109 | print(">>> smod.DoStochSim(method = 'direct',trajectories=1,end=50,mode='time')") 110 | smod.DoStochSim(method = 'direct',trajectories=1,end=50,mode='time') 111 | print(">>> smod.PlotWaitingtimesDistributions()") 112 | smod.PlotWaitingtimesDistributions() 113 | print(">>> smod.DoStochSim(method = 'Tauleap',trajectories=1,end=50,mode='time',epsilon=0.03) # should outperform all other implementations") 114 | smod.DoStochSim(method = 'Tauleap',trajectories=1,end=50,mode='time',epsilon=0.03) 115 | print(">>> smod.PlotSpeciesTimeSeries() # plot time series of species") 116 | smod.PlotSpeciesTimeSeries() 117 | print(">>> stochpy.plt.xscale('log')") 118 | stochpy.plt.xscale('log') 119 | 120 | def Demo6(self): 121 | """ Demo of StochPy's next reaction method handling events""" 122 | print("\n### (6) Demo of StochPy's next reaction method handling events ###") 123 | input("press any button to continue\n") 124 | print(">>> smod.Model('dsmts-003-03.xml.psc')") 125 | smod.Model('dsmts-003-03.xml.psc') 126 | print(">>> smod.DoStochSim(method = 'NextReactionMethod',trajectories=1000,end=50,mode='time')") 127 | smod.DoStochSim(method = 'NextReactionMethod',trajectories=1000,end=50,mode='time') 128 | print(">>> smod.GetRegularGrid()") 129 | smod.GetRegularGrid() 130 | print(">>> smod.PlotAverageSpeciesTimeSeries()") 131 | smod.PlotAverageSpeciesTimeSeries() 132 | 133 | def Demo7(self): 134 | """ Demo of StochPy's first reaction method handling events""" 135 | print("\n### (7) Demo of StochPy's first reaction method handling events ###") 136 | input("press any button to continue\n") 137 | print(">>> smod.Model('dsmts-003-04.xml.psc')") 138 | smod.Model('dsmts-003-04.xml.psc') 139 | print(">>> smod.DoStochSim(method = 'FirstReactionMethod',trajectories=1000,end=50,mode='time')") 140 | smod.DoStochSim(method = 'FirstReactionMethod',trajectories=1000,end=50,mode='time') 141 | print(">>> smod.GetRegularGrid()") 142 | smod.GetRegularGrid() 143 | print(">>> smod.PlotAverageSpeciesTimeSeries()") 144 | smod.PlotAverageSpeciesTimeSeries() 145 | 146 | def Demo8(self): 147 | """ Demo of StochPy's direct method for supporting events """ 148 | print("\n### (8) Demo of StochPy's direct method handling events ###") 149 | input("press any button to continue\n") 150 | print(">>> smod.Model('dsmts-02-10.xml.psc')") 151 | smod.Model('dsmts-002-10.xml.psc') 152 | print(">>> smod.DoStochSim(method = 'direct',trajectories=1000,end=50,mode='time')") 153 | smod.DoStochSim(method = 'direct',trajectories=1000,end=50,mode='time') 154 | print(">>> smod.GetRegularGrid()") 155 | smod.GetRegularGrid() 156 | print(">>> smod.PlotAverageSpeciesTimeSeries()") 157 | smod.PlotAverageSpeciesTimeSeries() 158 | 159 | def Demo9(self): 160 | """ Demo of StochPy's direct method for handling volume and HasOnlySubstanceUnits """ 161 | print("\n### (9) Demo of StochPy's direct method for handling volume and HasOnlySubstanceUnits ###") 162 | input("press any button to continue\n") 163 | print(">>> smod.Model('dsmts-02-11.xml.psc')") 164 | smod.Model('dsmts-001-11.xml.psc') 165 | print(">>> smod.DoStochSim(method = 'direct',trajectories=1000,end=50,mode='time')") 166 | smod.DoStochSim(method = 'direct',trajectories=1000,end=50,mode ='time') 167 | print(">>> smod.GetRegularGrid()") 168 | smod.GetRegularGrid() 169 | print(">>> smod.PlotAverageSpeciesTimeSeries()") 170 | smod.PlotAverageSpeciesTimeSeries() 171 | 172 | def Demo10(self): 173 | """ Demo of StochPy for doing (preprogrammed) Sequential simulations """ 174 | print("\n### (10) Demo of StochPy for doing (preprogrammed) Sequential simulations ###") 175 | input("press any button to continue\n") 176 | print(">>> cmod = stochpy.CellDivision() # start cell division module") 177 | cmod = stochpy.CellDivision() 178 | print(">>> cmod.DoCellDivisionStochSim(mode='generations',end = 3, trajectories=1)") 179 | cmod.DoCellDivisionStochSim(mode='generations',end = 3,trajectories=1) 180 | print(">>> cmod.PlotSpeciesTimeSeries() # plot time series of species") 181 | cmod.PlotSpeciesTimeSeries() 182 | 183 | def Demo11(self): 184 | """ StochPy Demo which illustrates delayed SSAs """ 185 | print(">>> smod.Model('Isomerization.psc')") 186 | smod.Model('Isomerization.psc') 187 | print(">>> smod.DoStochSim(mode='time',end=10,trajectories=1000)") 188 | smod.DoStochSim(mode='time',end=10,trajectories=1000) 189 | print(">>> smod.GetRegularGrid(n_samples=51)") 190 | smod.GetRegularGrid(n_samples=51) 191 | print(">>> smod.PlotAverageSpeciesTimeSeries()") 192 | smod.PlotAverageSpeciesTimeSeries() 193 | 194 | print(">>> smod.SetDelayParameters({'R1':('fixed',5)})") 195 | smod.SetDelayParameters({'R1':('fixed',5)}) 196 | print(">>> smod.DoDelayedStochSim(mode='time',end=10,trajectories=1000)") 197 | smod.DoDelayedStochSim(mode='time',end=10,trajectories=1000) 198 | print(">>> smod.GetRegularGrid()") 199 | smod.GetRegularGrid() 200 | print(">>> smod.PlotAverageSpeciesTimeSeries()") 201 | smod.PlotAverageSpeciesTimeSeries() 202 | 203 | def DoDemoSimulations(self): 204 | self.Demo1() 205 | self.Demo2() 206 | self.Demo3() 207 | self.Demo4() 208 | self.Demo5() 209 | self.Demo6() 210 | self.Demo7() 211 | self.Demo8() 212 | self.Demo9() 213 | self.Demo10() 214 | self.Demo11() 215 | -------------------------------------------------------------------------------- /stochpy/modules/StochPyPrint.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy printing class 4 | ====================== 5 | 6 | Written by T.R. Maarleveld and M. Moinat, Amsterdam, The Netherlands 7 | E-mail: tmd200@users.sourceforge.net 8 | Last Change: August 05, 2015 9 | """ 10 | 11 | ############################ IMPORTS ################################ 12 | from __future__ import division, print_function, absolute_import 13 | 14 | class PrintingFunctions(): 15 | 16 | def PrintSpeciesTimeSeries(self): 17 | """ Print time simulation output for each generated trajectory """ 18 | assert self._IsSimulationDone, "First do a stochastic simulation" 19 | for n in range(1,self.sim_trajectories_done+1): 20 | if self.sim_trajectories_done > 1: 21 | self.GetTrajectoryData(n) 22 | print('Time', "\t", end="") 23 | for s_id in self.sim_species_tracked: 24 | print(s_id,"\t",end="") 25 | print() 26 | for timepoint in self.data_stochsim.getSpecies(): 27 | for value in timepoint: 28 | print(value,"\t",end="") 29 | print() 30 | 31 | 32 | def PrintPropensitiesTimeSeries(self): 33 | """ Print a time series of the propensities each generated trajectory """ 34 | assert (self._IsTrackPropensities and self._IsSimulationDone), "First do a stochastic simulation with tracking propensities (use the IsTrackPropensities flag in DoStochSim)" 35 | for n in range(1,self.sim_trajectories_done+1): 36 | if self.sim_trajectories_done > 1: 37 | self.GetTrajectoryData(n) 38 | print('Time', "\t", end="") 39 | for r_id in self.sim_rates_tracked: 40 | print(r_id,"\t",end="") 41 | print() 42 | for timepoint in self.data_stochsim.getPropensities(): 43 | for value in timepoint: 44 | print(value,"\t",end="") 45 | print() 46 | 47 | 48 | def PrintSpeciesDistributions(self): 49 | """ Print obtained distributions for each generated trajectory """ 50 | assert self._IsSimulationDone, "First do a stochastic simulation" 51 | assert not self._IsOnlyLastTimepoint, "Determining statistics is disabled when saving only the last time point" 52 | for n in range(1,self.sim_trajectories_done+1): 53 | if self.sim_trajectories_done > 1: 54 | self.GetTrajectoryData(n) 55 | for i,L_species_dist in enumerate(self.data_stochsim.species_distributions): 56 | print("Copy number ({0:s})\tPMF".format(self.sim_species_tracked[i]) ) 57 | for m in range(len(L_species_dist[0])): 58 | x = L_species_dist[0][m] 59 | p_x = L_species_dist[1][m] 60 | if not p_x < 0.001: 61 | print("{0:d}\t{1:0.3f}".format(x,p_x)) 62 | else: 63 | print("{0:d}\t{1:0.3e}".format(x,p_x)) 64 | 65 | 66 | def PrintPropensitiesDistributions(self): 67 | """ Print obtained distributions for each generated trajectory """ 68 | assert (self._IsTrackPropensities and self._IsSimulationDone),"First do a stochastic simulation" 69 | assert not self._IsOnlyLastTimepoint, "Determining statistics is disabled when saving only the last time point" 70 | for n in range(1,self.sim_trajectories_done+1): 71 | if self.sim_trajectories_done > 1: 72 | self.GetTrajectoryData(n) 73 | 74 | for j,L_prop_dist in enumerate(self.data_stochsim.propensities_distributions): 75 | print("Propensity ({0:s})\tPMF".format(self.sim_rates_tracked[j]) ) 76 | for m in range(len(L_prop_dist[0])): 77 | x = L_prop_dist[0][m] 78 | p_x = L_prop_dist[1][m] 79 | if not p_x < 0.001: 80 | print("{0}\t{1:0.3f}".format(x,p_x)) 81 | else: 82 | print("{0}\t{1:0.3e}".format(x,p_x)) 83 | 84 | 85 | def PrintWaitingtimesDistributions(self): 86 | """ Print obtained waiting times """ 87 | assert not self._IsTauleaping, "Tau-Leaping method does not allow for calculation of waiting times" 88 | if (not self.data_stochsim.HAS_WAITINGTIMES) and (not self._IsTauleaping): 89 | self.GetWaitingtimes() 90 | for n in range(1,self.sim_trajectories_done+1): 91 | if self.sim_trajectories_done > 1: 92 | self.GetTrajectoryData(n) 93 | for r_id in self.data_stochsim.waiting_times: 94 | print("Waiting times\t({0:s})".format(r_id) ) 95 | waiting_times_r = self.data_stochsim.waiting_times[r_id] 96 | for wtime in waiting_times_r: 97 | if not wtime < 0.001: 98 | print("{0:0.3f}".format(wtime)) 99 | else: 100 | print("{0:0.3e}".format(wtime)) 101 | 102 | 103 | def PrintSpeciesMeans(self): 104 | """ Print the means (3 decimals) of each species for the selected trajectory""" 105 | assert self._IsSimulationDone, "First do a stochastic simulation" 106 | assert not self._IsOnlyLastTimepoint, "Determining statistics is disabled when saving only the last time point" 107 | print("Species\tMean") 108 | for s_id in self.data_stochsim.species_labels: 109 | mu = self.data_stochsim.species_means[s_id] 110 | if not mu < 0.001: 111 | print("{0:s}\t{1:0.3f}".format(s_id,mu)) 112 | else: 113 | print("{0:s}\t{1:0.3e}".format(s_id,mu)) 114 | 115 | 116 | def PrintSpeciesStandardDeviations(self): 117 | """ Print the standard deviations (3 decimals) of each species for the selected trajectory""" 118 | assert self._IsSimulationDone, "First do a stochastic simulation" 119 | assert not self._IsOnlyLastTimepoint, "Determining statistics is disabled when saving only the last time point" 120 | print("Species\tStandard Deviation") 121 | for s_id in self.data_stochsim.species_labels: 122 | sigma = self.data_stochsim.species_standard_deviations[s_id] 123 | if not sigma < 0.001: 124 | print("{0:s}\t{1:0.3f}".format(s_id,sigma)) 125 | else: 126 | print("{0:s}\t{1:0.3e}".format(s_id,sigma)) 127 | 128 | 129 | def PrintPropensitiesMeans(self): 130 | """ Print the means of each propensity for the selected trajectory""" 131 | assert (self._IsTrackPropensities and self._IsSimulationDone), "First do a stochastic simulation with tracking propensities (use the IsTrackPropensities flag in DoStochSim)" 132 | assert not self._IsOnlyLastTimepoint, "Determining statistics is disabled when saving only the last time point" 133 | print("Reaction\tMean") 134 | for r_id in self.sim_rates_tracked: 135 | mu = self.data_stochsim.propensities_means[r_id] 136 | if not mu < 0.001: 137 | print("{0:s}\t{1:0.3f}".format(r_id,mu)) 138 | else: 139 | print("{0:s}\t{1:0.3e}".format(r_id,mu)) 140 | 141 | 142 | def PrintPropensitiesStandardDeviations(self): 143 | """ Print the standard deviations of each propensity for the selected trajectory""" 144 | assert (self._IsTrackPropensities and self._IsSimulationDone), "First do a stochastic simulation with tracking propensities (use the IsTrackPropensities flag in DoStochSim)" 145 | assert not self._IsOnlyLastTimepoint, "Determining statistics is disabled when saving only the last time point" 146 | print("Reaction\tStandard Deviation") 147 | for r_id in self.sim_rates_tracked: 148 | std = self.data_stochsim.propensities_standard_deviations[r_id] 149 | if not std < 0.001: 150 | print("{0:s}\t{1:0.3f}".format(r_id,std)) 151 | else: 152 | print("{0:s}\t{1:0.3e}".format(r_id,std)) 153 | 154 | 155 | def PrintWaitingtimesMeans(self): 156 | """ Print the waiting time means for the selected trajectory """ 157 | assert not self._IsTauleaping, "Tau-Leaping method does not allow for calculation of waiting times" 158 | if (not self.data_stochsim.HAS_WAITINGTIMES) and (not self._IsTauleaping): 159 | self.GetWaitingtimes() 160 | 161 | for n in range(1,self.sim_trajectories_done+1): 162 | if self.sim_trajectories_done > 1: 163 | self.GetTrajectoryData(n) 164 | print("Reaction\tMean") 165 | for j,r_id in enumerate(self.SSA.rate_names): 166 | mu = self.data_stochsim.waiting_times_means[j] 167 | if not mu < 0.001: 168 | print("{0:s}\t{1:0.3f}".format(r_id,mu)) 169 | else: 170 | print("{0:s}\t{1:0.3e}".format(r_id,mu)) 171 | 172 | 173 | def PrintWaitingtimesStandardDeviations(self): 174 | """ Print the waiting time standard deviations for the selected trajectory """ 175 | assert not self._IsTauleaping, "Tau-Leaping method does not allow for calculation of waiting times" 176 | if (not self.data_stochsim.HAS_WAITINGTIMES) and (not self._IsTauleaping): 177 | self.GetWaitingtimes() 178 | for n in range(1,self.sim_trajectories_done+1): 179 | if self.sim_trajectories_done > 1: 180 | self.GetTrajectoryData(n) 181 | print("Reaction\tStandard deviation") 182 | for j,r_id in enumerate(self.SSA.rate_names): 183 | std = self.data_stochsim.waiting_times_standard_deviations[j] 184 | if not std < 0.001: 185 | print("{0:s}\t{1:0.3f}".format(s_id,std)) 186 | else: 187 | print("{0:s}\t{1:0.3e}".format(s_id,std)) 188 | 189 | 190 | def PrintAverageSpeciesTimeSeries(self): 191 | """ Analyze the average output over all generated trajectories """ 192 | if not self.HAS_AVERAGE: 193 | print("*** WARNING ***: No regular grid is created yet. Use GetRegularGrid(n_samples) if averaged results are unsatisfactory (e.g. more or less 'points')") 194 | self.GetRegularGrid() 195 | for s_id in self.data_stochsim.species_labels: 196 | print("\t{0:s} (Mean)\t{0:s} (STD)".format(s_id),end="") 197 | print() 198 | for x,t in enumerate(self.data_stochsim_grid.time): 199 | print(t,end="") 200 | for i in range(len(self.data_stochsim_grid.species_labels)): 201 | mu = self.data_stochsim_grid.species_means[x,i] 202 | sigma = self.data_stochsim_grid.species_standard_deviations[x,i] 203 | if not mu < 0.001 and not sigma < 0.001: 204 | print("\t{0:0.3f}\t{1:0.3f}".format(mu,sigma),end="") 205 | elif not mu < 0.001: 206 | print("\t{0:0.3f}\t{1:0.3e}".format(mu,sigma),end="") 207 | else: 208 | print("\t{0:0.3e}\t{1:0.3e}".format(mu,sigma),end="") 209 | print() 210 | 211 | 212 | def PrintAveragePropensitiesTimeSeries(self): 213 | """ Analyze the average output over all generated trajectories """ 214 | assert self._IsTrackPropensities, "First do a stochastic simulation with tracking propensities (use the IsTrackPropensities flag in DoStochSim)" 215 | if (not self.HAS_AVERAGE) and (self._IsTrackPropensities): 216 | print("*** WARNING ***: No regular grid is created yet. Use GetRegularGrid(n_samples) if averaged results are unsatisfactory (e.g. more or less 'points')") 217 | self.GetRegularGrid() 218 | print("Time",end="") 219 | for r_id in self.sim_rates_tracked: 220 | print("\t{0:s} (Mean)\t{0:s} (STD)".format(r_id),end="") 221 | print() 222 | for x,t in enumerate(self.data_stochsim_grid.time): 223 | print(t,end="") 224 | for j in range(len(self.sim_rates_tracked)): 225 | mu = self.data_stochsim_grid.propensities_means[x,j] 226 | sigma = self.data_stochsim_grid.propensities_standard_deviations[x,j] 227 | if not mu < 0.001 and not sigma < 0.001: 228 | print("\t{0:0.3f}\t{1:0.3f}".format(mu,sigma),end="") 229 | elif not mu < 0.001: 230 | print("\t{0:0.3f}\t{1:0.3e}".format(mu,sigma),end="") 231 | else: 232 | print("\t{0:0.3e}\t{1:0.3e}".format(mu,sigma),end="") 233 | print() 234 | -------------------------------------------------------------------------------- /stochpy/modules/StochPyUtils.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy Utils 4 | ============= 5 | 6 | Module that contains functions that are created by the users of stochpy. New functions will be added in the next releases of stochpy. 7 | 8 | Written by T.R. Maarleveld, Amsterdam, The Netherlands 9 | E-mail: tmd200@users.sourceforge.net 10 | Last Change: August 06, 2015 11 | """ 12 | 13 | from __future__ import division, print_function, absolute_import 14 | import stochpy as _stochpy_ 15 | import copy,numpy as np 16 | mod = None 17 | 18 | def GetAnalyticalPDF(kon,koff,kdeg,ksyn): 19 | """ Get the analytical probability density function. The analytical solution is taken from Sharezaei and Swain 2008 - Analytical distributions for stochastic gene expression """ 20 | import mpmath 21 | mpmath.mp.pretty = True 22 | x_values = np.linspace(0,50,10000) 23 | y_values = [] 24 | for m in x_values: 25 | a = ((ksyn/kdeg)**m)*np.exp(-ksyn/kdeg)/mpmath.factorial(m) 26 | b = mpmath.mp.gamma((kon/kdeg)+m) * mpmath.mp.gamma(kon/kdeg + koff/kdeg)/ (mpmath.mp.gamma(kon/kdeg + koff/kdeg + m)* mpmath.mp.gamma(kon/kdeg)) 27 | c = mpmath.mp.hyp1f1(koff/kdeg,kon/kdeg + koff/kdeg + m,ksyn/kdeg) 28 | y_values.append(a*b*c) 29 | return x_values,y_values 30 | 31 | 32 | def GetAnalyticalWaitingtimes(kon,koff,ksyn): 33 | """ Get analytical waiting times """ 34 | import mpmath 35 | mpmath.mp.pretty = True 36 | A = mpmath.sqrt(-4*ksyn*kon+(koff + kon + ksyn)**2) 37 | x = [] 38 | for i in np.linspace(-20,5,5000): 39 | x.append(mpmath.exp(i)) 40 | y = [] 41 | for t in x: 42 | B = koff + ksyn - (mpmath.exp(t*A)*(koff+ksyn-kon))-kon+A+ mpmath.exp(t*A)*A 43 | p01diff = mpmath.exp(-0.5*t*(koff + kon + ksyn+A))*B/(2.0*A) 44 | y.append(p01diff*ksyn) 45 | return (x,y) 46 | 47 | 48 | def doSequentialSim(smod,n_generations,cell_division_times): 49 | """ Model protein synthesis subject to cell division """ 50 | ### Start sequential modelling part ### 51 | for i in range(1,n_generations): 52 | ### divide each species between two daughter cells ### 53 | for j in range(0,len(smod.data_stochsim.species_labels)): 54 | species_amount = smod.SSA.sim_output[-1][1:][j] 55 | if species_amount: 56 | smod.settings.X_matrix[j] = np.random.binomial(n=species_amount,p=0.5,size=1) 57 | 58 | ### replace last time point with species amounts after division ### 59 | species_after_division = copy.deepcopy(list(smod.settings.X_matrix)) 60 | species_after_division.insert(0,cell_division_times[0:i].sum()) # add time of cell division 61 | species_after_division.append(np.nan) # no specific reaction occured at cell division 62 | smod.SSA.sim_output[-1] = copy.deepcopy(species_after_division) 63 | 64 | ### Set settings for new simulation and simulate the next generation ### 65 | smod.settings.starttime = copy.deepcopy(smod.SSA.sim_output[-1][0]) 66 | smod.settings.endtime += cell_division_times[i] 67 | smod.SSA.Execute(smod.settings) 68 | ### End sequential modelling part ### 69 | smod.FillDataStochsim() # add all data to data_stochsim object 70 | return smod 71 | 72 | class Utils(): 73 | def __init__(self): 74 | print("See http://stochpy.sf.net/examples.html for more explanation about these examples") 75 | global mod 76 | mod = _stochpy_.SSA() 77 | 78 | def DoExample1(self): 79 | """ Immigration Death example (available at http://stochpy.sourceforge.net/examples.html) """ 80 | mod.Model('ImmigrationDeath.psc') # Ksyn = 10, Kdeg = 0.2, and mRNA(init) = 50 81 | lambda_ = 50 82 | N = 1000000 83 | data = np.random.poisson(lambda_,N) 84 | mod.DoStochSim(end=N,mode='steps') 85 | mod.PlotSpeciesDistributions(linestyle= 'solid') 86 | n, bins, patches = _stochpy_.plt.hist(data-0.5, max(data)-min(data),normed=1, facecolor='green') 87 | mod.PrintSpeciesMeans() 88 | mod.PrintSpeciesStandardDeviations() 89 | 90 | def DoExample2(self): 91 | """ SBML events and Interpolation example (available at http://stochpy.sourceforge.net/examples.html) """ 92 | mod.Model('dsmts-003-04.xml.psc') 93 | mod.DoStochSim(end = 50,mode = 'time',trajectories = 1000) 94 | mod.GetRegularGrid() 95 | mod.PlotAverageSpeciesTimeSeries() 96 | mod.PrintAverageSpeciesTimeSeries() 97 | 98 | def DoExample3(self): 99 | """ Burstmodel example (available at http://stochpy.sourceforge.net/examples.html) """ 100 | mod.Model('Burstmodel.psc') # Parameter values in Burstmodel.psc: kon = koff = 0.05 101 | ntimesteps = 1000000 102 | mod.ChangeParameter("kon",0.05) 103 | mod.ChangeParameter("koff",0.05) 104 | mod.DoStochSim(end=ntimesteps,mode='steps',trajectories=1) 105 | mod.plot.plotnum = 1 106 | mod.PlotSpeciesDistributions(species2plot = 'mRNA', colors=['#00FF00'],linestyle = 'solid') # Usage of html color codes 107 | mod.PlotWaitingtimesDistributions('R3', colors=['#00FF00'],linestyle = 'None',marker='o') 108 | 109 | mod.ChangeParameter("kon",5.0) 110 | mod.ChangeParameter("koff",5.0) 111 | mod.DoStochSim(end=ntimesteps,mode='steps',trajectories=1) 112 | mod.plot.plotnum = 1 113 | mod.PlotSpeciesDistributions(species2plot = 'mRNA', colors='r',linestyle = 'solid') 114 | 115 | kon = 0.05 116 | koff = 0.05 117 | kdeg = 2.5 118 | ksyn = 80.0 119 | x,y = GetAnalyticalPDF(kon,koff,kdeg,ksyn) 120 | _stochpy_.plt.figure(1) 121 | _stochpy_.plt.step(x,y,color ='k') 122 | 123 | kon = 5.0 124 | koff = 5.0 125 | x,y = GetAnalyticalPDF(kon,koff,kdeg,ksyn) 126 | _stochpy_.plt.step(x,y,color ='k') 127 | _stochpy_.plt.xlabel('mRNA copy number per cell') 128 | _stochpy_.plt.ylabel('Probability mass') 129 | _stochpy_.plt.legend(['Bimodal','Unimodal', 'Analytical solution'],numpoints=1,frameon=False) 130 | _stochpy_.plt.title('') 131 | _stochpy_.plt.ylim([0,0.045]) 132 | 133 | mod.PlotWaitingtimesDistributions('R3', colors=['r'],linestyle = 'None',marker='v') 134 | kon = 0.05 135 | koff = 0.05 136 | (x,y) = GetAnalyticalWaitingtimes(kon,koff,ksyn) 137 | _stochpy_.plt.figure(2) 138 | _stochpy_.plt.plot(x,y,color ='k') 139 | 140 | kon = 5.0 141 | koff = 5.0 142 | (x,y) = GetAnalyticalWaitingtimes(kon,koff,ksyn) 143 | _stochpy_.plt.plot(x,y,color ='k') 144 | _stochpy_.plt.xlabel('Time between RNA synthesis events') 145 | _stochpy_.plt.ylabel('Probability density') 146 | _stochpy_.plt.legend(['Bimodal','Unimodal', 'Analytical solution'],numpoints=1,frameon=False,loc='lower left') 147 | _stochpy_.plt.title('') 148 | _stochpy_.plt.xlim([10**-7,10**3]) 149 | _stochpy_.plt.ylim([10**-9,10**3]) 150 | 151 | def DoExample4(self): 152 | """ Second Burstmodel example (available at http://stochpy.sourceforge.net/examples.html) """ 153 | import matplotlib.gridspec as gridspec 154 | sim_end = 100 155 | mod.Model('Burstmodel.psc') 156 | mod.ChangeParameter("kon",0.05) 157 | mod.ChangeParameter("koff",0.05) 158 | mod.DoStochSim(end=sim_end,mode='time',trajectories=1) 159 | 160 | # Use a nice grid to plot 4 figures 161 | gs = gridspec.GridSpec(4,1,width_ratios=[1],height_ratios=[0.3,1,0.3,1]) 162 | ax1 = _stochpy_.plt.subplot(gs[0]) 163 | mod.plot.ResetPlotnum() 164 | mod.PlotSpeciesTimeSeries(species2plot = 'ONstate',IsLegend=False) 165 | _stochpy_.plt.ion() 166 | _stochpy_.plt.xlabel('') # remove xlabel 167 | _stochpy_.plt.ylabel('') # remove ylabel 168 | _stochpy_.plt.xlim([0,sim_end]) # set x lim 169 | _stochpy_.plt.xticks([]) # remove x ticks 170 | _stochpy_.plt.ylim([0,1.1]) # set y lim 171 | _stochpy_.plt.yticks([]) # remove y lim 172 | _stochpy_.plt.text(-5.5,0.9,'ON') 173 | _stochpy_.plt.text(-5.5,0,'OFF') 174 | _stochpy_.plt.text(101,0.35,'A',fontsize = 14) 175 | 176 | ax2 = _stochpy_.plt.subplot(gs[1]) 177 | mod.plot.ResetPlotnum() 178 | mod.PlotSpeciesTimeSeries(species2plot ='mRNA',colors = ['#32CD32'],IsLegend=False,title='') 179 | _stochpy_.plt.xlim([0,sim_end]) 180 | _stochpy_.plt.xticks([]) 181 | _stochpy_.plt.xlabel('') 182 | _stochpy_.plt.ylabel('mRNA') 183 | _stochpy_.plt.yticks([0,20,40,60]) 184 | _stochpy_.plt.text(101,27,'B',fontsize = 14) 185 | 186 | mod.ChangeParameter("kon",5.0) 187 | mod.ChangeParameter("koff",5.0) 188 | 189 | ax3 = _stochpy_.plt.subplot(gs[2]) 190 | mod.plot.ResetPlotnum() 191 | mod.DoStochSim(end=sim_end,mode='time') 192 | mod.PlotSpeciesTimeSeries(species2plot ='ONstate',IsLegend=False,title='') 193 | _stochpy_.plt.xlabel('') 194 | _stochpy_.plt.ylabel('') 195 | _stochpy_.plt.xlim([0,sim_end]) 196 | _stochpy_.plt.xticks([]) 197 | _stochpy_.plt.ylim([0,1.1]) 198 | _stochpy_.plt.yticks([]) 199 | _stochpy_.plt.text(-5.5,0.9,'ON') 200 | _stochpy_.plt.text(-5.5,0,'OFF') 201 | _stochpy_.plt.text(101,0.35,'C',fontsize = 14) 202 | 203 | ax4 = _stochpy_.plt.subplot(gs[3]) 204 | mod.plot.ResetPlotnum() 205 | mod.PlotSpeciesTimeSeries(species2plot ='mRNA',colors = ['r'],IsLegend=False,title='') 206 | _stochpy_.plt.xlim([0,sim_end]) 207 | _stochpy_.plt.xlabel('Time (min)') 208 | _stochpy_.plt.ylabel('mRNA') 209 | _stochpy_.plt.xticks([0,20,40,60,80,100]) 210 | _stochpy_.plt.yticks([0,20,40,60]) 211 | _stochpy_.plt.text(101,27,'D',fontsize = 14) 212 | 213 | def DoExample5(self): 214 | """ Protein turnover example with and without cell division (available at http://stochpy.sourceforge.net/examples.html) """ 215 | smod = _stochpy_.SSA(model_file='CellDivision.psc',dir=_stochpy_.model_dir) # start SSA module with CellDivision model 216 | ### do protein synthesis without cell division ### 217 | smod.DoStochSim(end=10,mode='time') 218 | smod.PlotSpeciesTimeSeries(species2plot= 'Protein') 219 | smod.DoStochSim(end=300,mode='time') 220 | smod.PlotSpeciesDistributions(species2plot='Protein') 221 | 222 | ### do protein synthesis with cell division ### 223 | n_generations=10 224 | cell_division_times = abs(np.random.gamma(scale=0.1,shape=3,size=n_generations)) # cell division times with a gamma distribution 225 | smod.DoStochSim(end=cell_division_times[0],mode='time',trajectories=1) 226 | smod = doSequentialSim(smod,n_generations,cell_division_times) 227 | smod.PlotSpeciesTimeSeries(species2plot= 'Protein') 228 | n_generations=500 229 | cell_division_times = abs(np.random.gamma(scale=0.1,shape=3,size=n_generations)) # cell division times with a gamma distribution 230 | smod.DoStochSim(end=cell_division_times[0],mode='time',trajectories=1) 231 | smod = doSequentialSim(smod,n_generations,cell_division_times) 232 | smod.PlotSpeciesDistributions(species2plot='Protein') 233 | -------------------------------------------------------------------------------- /stochpy/modules/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy - Stochastic Modeling in Python (http://stochpy.sourceforge.net) 4 | 5 | Copyright (C) 2010-2014 T.R Maarlveld, B.G. Olivier F.J. Bruggeman all rights reserved. 6 | 7 | Timo R. Maarleveld (tmd200@users.sourceforge.net) 8 | VU University, Amsterdam, Netherlands 9 | 10 | Permission to use, modify, and distribute this software is given under the 11 | terms of the StochPy (BSD style) license. 12 | 13 | NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 14 | """ 15 | -------------------------------------------------------------------------------- /stochpy/pscmodels/Autoreg.py: -------------------------------------------------------------------------------- 1 | model = """# Generated by PySCeS 0.7.0 (2010-10-07 19:43) 2 | 3 | # Keywords 4 | Description: Auto-regulatory network 5 | Modelname: AutoRegulatoryNetwork 6 | Output_In_Conc: True 7 | Species_In_Conc: False 8 | 9 | # GlobalUnitDefinitions 10 | UnitVolume: litre, 1.0, 0, 1 11 | UnitLength: metre, 1.0, 0, 1 12 | UnitSubstance: item, 1.0, 0, 1 13 | UnitArea: metre, 1.0, 0, 2 14 | UnitTime: second, 1.0, 0, 1 15 | 16 | # Compartments 17 | Compartment: Cell, 1.0, 3 18 | 19 | # Reactions 20 | RepressionBinding@Cell: 21 | P2 + Gene > P2Gene 22 | RepressionBinding_k1*Gene*P2 23 | 24 | ProteinDegradation@Cell: 25 | P > $pool 26 | ProteinDegradation_k6*P 27 | 28 | Dimerisation@Cell: 29 | {2.0}P > P2 30 | Dimerisation_k4*0.5*P*(P-1) 31 | 32 | Dissociation@Cell: 33 | P2 > {2.0}P 34 | Dissociation_k4r*P2 35 | 36 | Transcription@Cell: 37 | $pool > Rna 38 | Transcription_k2*Gene 39 | 40 | RnaDegradation@Cell: 41 | Rna > $pool 42 | RnaDegradation_k5*Rna 43 | 44 | Translation@Cell: 45 | $pool > P 46 | Translation_k3*Rna 47 | 48 | ReverseRepressionBinding@Cell: 49 | P2Gene > P2 + Gene 50 | ReverseRepressionBinding_k1r*P2Gene 51 | 52 | # Fixed species 53 | 54 | # Variable species 55 | P2@Cell = 0.0 56 | P@Cell = 0.0 57 | Rna@Cell = 0.0 58 | Gene@Cell = 10.0 59 | P2Gene@Cell = 0.0 60 | 61 | # Parameters 62 | RepressionBinding_k1 = 1.0 63 | ProteinDegradation_k6 = 0.01 64 | Dimerisation_k4 = 1.0 65 | Dissociation_k4r = 1.0 66 | Transcription_k2 = 0.01 67 | RnaDegradation_k5 = 0.1 68 | Translation_k3 = 10.0 69 | ReverseRepressionBinding_k1r = 10.0 70 | """ 71 | 72 | xml_model = """ 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | k1 106 | Gene 107 | P2 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | k1r 128 | P2Gene 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | k2 149 | Gene 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | k3 170 | Rna 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | k4 190 | 0.5 191 | P 192 | 193 | 194 | P 195 | 1 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | k4r 216 | P2 217 | 218 | 219 | 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | k5 233 | Rna 234 | 235 | 236 | 237 | 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | 249 | k6 250 | P 251 | 252 | 253 | 254 | 255 | 256 | 257 | 258 | 259 | 260 | 261 | """ 262 | 263 | -------------------------------------------------------------------------------- /stochpy/pscmodels/BirthDeath.py: -------------------------------------------------------------------------------- 1 | model = """# Stochastic Simulation Algorithm input file 2 | # --> mRNA --> 3 | 4 | # Reactions 5 | R1: 6 | mRNA > {2} mRNA 7 | Ksyn*mRNA 8 | 9 | R2: 10 | mRNA > $pool 11 | Kdeg*mRNA 12 | 13 | # Fixed species 14 | 15 | # Variable species 16 | mRNA = 100 17 | 18 | # Parameters 19 | Ksyn = 2.9 20 | Kdeg = 3 21 | """ 22 | -------------------------------------------------------------------------------- /stochpy/pscmodels/Burstmodel.py: -------------------------------------------------------------------------------- 1 | model = """ 2 | # PySCeS test input file 3 | # Stochastic Simulation Algorithm input format 4 | # BurstModel 5 | 6 | R1: 7 | ONstate > OFFstate 8 | koff*ONstate 9 | 10 | R2: 11 | OFFstate > ONstate 12 | kon*OFFstate 13 | 14 | R3: 15 | ONstate > mRNA + ONstate 16 | ksyn*ONstate 17 | 18 | R4: 19 | mRNA > $pool 20 | kdeg*mRNA 21 | 22 | # InitPar 23 | kon = 0.05 24 | koff = 0.05 25 | kdeg = 2.5 26 | ksyn = 80 27 | 28 | # InitVar 29 | ONstate = 0 30 | OFFstate = 1 31 | mRNA = 0 32 | """ 33 | 34 | -------------------------------------------------------------------------------- /stochpy/pscmodels/CellDivision.py: -------------------------------------------------------------------------------- 1 | model = """# Stochastic Simulation Algorithm input format 2 | 3 | R1: 4 | $pool > TF 5 | kTFsyn 6 | R2: 7 | TF > $pool 8 | kTFdeg*TF 9 | R3: 10 | TFactive > $pool 11 | kTFdeg*TFactive 12 | R4: 13 | TF > TFactive 14 | kActivate*TF 15 | R5: 16 | TFactive > TF 17 | kInactivate*TFactive 18 | R6: 19 | TFactive > mRNA + TFactive 20 | kmRNAsyn*(TFactive/(TFactive+kX)) 21 | R7: 22 | mRNA > $pool 23 | kmRNAdeg*mRNA 24 | R8: 25 | mRNA > Protein + mRNA 26 | kProteinsyn*mRNA 27 | R9: 28 | Protein > $pool 29 | kProteindeg*Protein 30 | 31 | # InitPar 32 | kTFsyn = 200 33 | kTFdeg = 20 34 | kActivate = 2000 35 | kInactivate = 200 36 | kX = 5 37 | kmRNAsyn = 240 38 | kmRNAdeg = 20 39 | kProteinsyn = 400 40 | kProteindeg = 2 41 | 42 | # InitVar 43 | TF = 2 44 | TFactive = 10 45 | mRNA = 10 46 | Protein = 220 47 | """ 48 | -------------------------------------------------------------------------------- /stochpy/pscmodels/DecayingDimerizing.py: -------------------------------------------------------------------------------- 1 | model = """ 2 | # PySCeS test input file 3 | # Stochastic Simulation Algorithm input format 4 | # Decay Dimerazing model 5 | 6 | # S1 --> 0 7 | # 2S1 --> S2 8 | # S2 --> 2S1 9 | # S2 --> S3 10 | 11 | R1: 12 | S1 > $pool 13 | S1*k1 14 | 15 | R2: 16 | S1 + S1 > S2 17 | 0.5*k2*S1*(S1-1) 18 | 19 | R3: 20 | S2 > S1 + S1 21 | k3*S2 22 | 23 | R4: 24 | S2 > S3 25 | k4*S2 26 | 27 | #InitPar 28 | k1 = 1.0 29 | k2 = 0.002 30 | k3 = 0.5 31 | k4 = 0.04 32 | 33 | #InitVar 34 | S1 = 100000 35 | S2 = 0.0 36 | S3 = 0.0 37 | """ 38 | -------------------------------------------------------------------------------- /stochpy/pscmodels/GeneDuplication.py: -------------------------------------------------------------------------------- 1 | model = """ 2 | 3 | # Reactions 4 | R1: 5 | G1 > G1 + mRNA1 6 | Ksyn*G1 7 | 8 | R2: 9 | mRNA1 > $pool 10 | Kdeg*mRNA1 11 | R3: 12 | G2 > G2 + mRNA2 13 | Ksyn*G2 14 | R4: 15 | mRNA2 > $pool 16 | Kdeg*mRNA2 17 | 18 | # Fixed species 19 | 20 | # Variable species 21 | mRNA1 = 50.0 22 | G1 = 1 23 | mRNA2 = 50.0 24 | G2 = 1 25 | 26 | # Parameters 27 | Ksyn = 10 28 | Kdeg = 0.2 29 | """ 30 | -------------------------------------------------------------------------------- /stochpy/pscmodels/ImmigrationDeath.py: -------------------------------------------------------------------------------- 1 | model = """# Stochastic Simulation Algorithm input file 2 | # --> mRNA --> 3 | 4 | # Reactions 5 | R1: 6 | $pool > mRNA 7 | Ksyn 8 | 9 | R2: 10 | mRNA > $pool 11 | Kdeg*mRNA 12 | 13 | # Fixed species 14 | 15 | # Variable species 16 | mRNA = 50.0 17 | 18 | # Parameters 19 | Ksyn = 10 20 | Kdeg = 0.2 21 | """ 22 | -------------------------------------------------------------------------------- /stochpy/pscmodels/Isomerization.py: -------------------------------------------------------------------------------- 1 | model = """# Simple model to illustrate the effect of delays 2 | 3 | # Reactions 4 | R1: 5 | X > Y 6 | k1*X 7 | 8 | 9 | # InitPar 10 | k1 = 0.5 11 | 12 | # InitVar 13 | X = 20 14 | Y = 0 15 | """ 16 | -------------------------------------------------------------------------------- /stochpy/pscmodels/Polymerase.py: -------------------------------------------------------------------------------- 1 | model = """# NonConsuming vs Consuming delayed reactions 2 | 3 | # Reactions 4 | R1: 5 | polymerase > mRNA + polymerase 6 | Ksyn*polymerase 7 | 8 | R2: 9 | mRNA > $pool 10 | Kdeg*mRNA 11 | 12 | # Variable species 13 | polymerase = 10 14 | mRNA = 0 15 | 16 | # Parameters 17 | Ksyn = 0.5 18 | Kdeg = 0.1 19 | """ 20 | -------------------------------------------------------------------------------- /stochpy/pscmodels/Schlogl.py: -------------------------------------------------------------------------------- 1 | model = """ 2 | # Schlogl model (Schlogl 1972, Chemical reaction models for nonequilibrium phase transitions) 3 | 4 | FIX: A B 5 | 6 | # Reactions 7 | R1: 8 | A + {2} X > {3} X 9 | 1/2*c1*A*X*(X-1) 10 | 11 | R2: 12 | {3} X > A + {2} X 13 | 1/6*c2*X*(X-1)*(X-2) 14 | R3: 15 | B > X 16 | c3 * B 17 | R4: 18 | X > B 19 | c4*X 20 | 21 | # Fixed species 22 | A = 100000 23 | B = 200000 24 | 25 | # Variable species 26 | X = 250 27 | 28 | c1 = 3*10**-7 29 | c2 = 10**-4 30 | c3 = 10**-3 31 | c4 = 3.5 32 | """ 33 | -------------------------------------------------------------------------------- /stochpy/pscmodels/Signaling3cCD.py: -------------------------------------------------------------------------------- 1 | model = """# signalling pathway incl. feedback 2 | # R and S on the same operon 3 | # Delay can be applied such that mRNA_S is produced after mRNA_R via mRNA_prelim 4 | # RP dimerises before activating genes 5 | # Rate constants set for bistability in Cell Division module 6 | # Set DNA and DNAa as 'Non-dividing' species in Stochpy 7 | 8 | 9 | #Reactions 10 | R1f: 11 | S > SL 12 | k1f*S*L 13 | 14 | R2: 15 | SL > SLP 16 | k2*SL 17 | 18 | R3f: 19 | SLP > SP 20 | k3f*SLP 21 | 22 | R4f: 23 | SLP + R > SLPR 24 | k4f*SLP*R 25 | 26 | R5f: 27 | SP + R > SPR 28 | k5f*SP*R 29 | 30 | R6f: 31 | SLPR > SL + RP 32 | k6f*SLPR 33 | 34 | R7f: 35 | SPR > S + RP 36 | k7f*SPR 37 | 38 | R8f: 39 | RP + S > RPS 40 | k8f*RP*S 41 | 42 | R9: 43 | RPS > R + S 44 | k9*RPS 45 | 46 | R10f: 47 | SLPR > SPR 48 | k10f*SLPR 49 | 50 | R11: 51 | RP > R 52 | k11*RP 53 | 54 | R12: 55 | SP > S 56 | k12*SP 57 | 58 | R13: 59 | SLP > SL 60 | k13*SLP 61 | 62 | R1b: 63 | SL > S 64 | k1b*SL 65 | 66 | R3b: 67 | SP > SLP 68 | k3b*SP*L 69 | 70 | R4b: 71 | SLPR > SLP + R 72 | k4b*SLPR 73 | 74 | R5b: 75 | SPR > SP + R 76 | k5b*SPR 77 | 78 | R6b: 79 | SL + RP > SLPR 80 | k6b*SL*RP 81 | 82 | R7b: 83 | S + RP > SPR 84 | k7b*S*RP 85 | 86 | R8b: 87 | RPS > S + RP 88 | k8b*RPS 89 | 90 | R10b: 91 | SPR > SLPR 92 | k10b*SPR*L 93 | 94 | #Basal transcription/translation and degradation 95 | 96 | #Reaction names correspond to relevant parameter names in Table S2 of the Supplementary Information 97 | #Recation names are further appended by letters if multiple reactions are associated with the same parameter 98 | 99 | #Note: mRNA_prelim is a 'trick' species to model production of mRNA_S strictly after delay following mRNA_R production 100 | Rp1a: 101 | $pool > mRNA_R + mRNA_Sprelim 102 | kr1*(DNA+DNAa) 103 | 104 | Rp1b: 105 | mRNA_Sprelim > mRNA_S #approximately instantaneous reaction (so mRNA_prelim doesn't really 'exist') 106 | 10000*mRNA_Sprelim 107 | Rp3a: 108 | $pool > R 109 | kr2*mRNA_R 110 | Rd1a: 111 | mRNA_R > $pool 112 | kr3*mRNA_R 113 | Rp3b: 114 | $pool > S 115 | ks2*mRNA_S 116 | 117 | Rd1b: 118 | mRNA_S > $pool 119 | ks3*mRNA_S 120 | 121 | 122 | #Feedback reactions 123 | 124 | RDimerf: 125 | RP + RP > RPDimer 126 | kDimerf*RP*(RP-1) 127 | 128 | RDimerb: 129 | RPDimer > RP + RP 130 | kDimerb*RPDimer 131 | 132 | RActf: 133 | RPDimer + DNA > DNAa 134 | kActf*RPDimer*DNA 135 | 136 | RActb: 137 | DNAa > RPDimer + DNA 138 | kActb*DNAa 139 | 140 | Rp2: 141 | $pool > mRNA_R + mRNA_Sprelim 142 | kr6*DNAa 143 | 144 | 145 | #Fixed Species 146 | 147 | #Variable species: 148 | DNA = 1 149 | DNAa = 0 150 | S = 0 151 | SL = 0 152 | SP = 0 153 | SLP = 100 154 | SLPR = 0 155 | SPR = 0 156 | RPS = 0 157 | RP = 80 158 | RPDimer = 0 159 | R = 0 160 | mRNA_R = 5 161 | mRNA_S = 5 162 | mRNA_Sprelim = 0 163 | 164 | # Parameters 165 | L=200 166 | k1f = 0.01 167 | k1b = 0.059 168 | k2 = 0.1 169 | k3f = 0.001 170 | k3b =0.001 171 | k4f = 0.0238 172 | k4b = 0.001 173 | k5f = 0.0238 174 | k5b = 0.001 175 | k6f = 19.8 176 | k6b = 0.001 177 | k7f = 19.8 178 | k7b = 0.001 179 | k8f = 0.0238 180 | k8b = 0.2 181 | k9 = 0.5 182 | k10f = 0.001 183 | k10b = 0.001 184 | k11 = 0.0001 185 | k12 = 0.0001 186 | k13 = 0.0001 187 | 188 | kr1 = 0.003 189 | kr2 = 0.002 190 | kr3 = 0.002 191 | kr6 = 0.1 192 | 193 | ks2 = 0.002 194 | ks3 = 0.002 195 | 196 | kDimerf = 0.001 197 | kDimerb = 1 198 | kActf = 0.001 199 | kActb = 0.01 200 | 201 | 202 | 203 | """ 204 | -------------------------------------------------------------------------------- /stochpy/pscmodels/SignalingTimeVaryingL.py: -------------------------------------------------------------------------------- 1 | model = """# signalling pathway with response times to stepwise L changes, 'up-down' staircase 2 | 3 | FIX: L 4 | 5 | #Reactions 6 | R1f: 7 | S > SL 8 | k1f*S*L 9 | 10 | R2: 11 | SL > SLP 12 | k2*SL 13 | 14 | R3f: 15 | SLP > SP 16 | k3f*SLP 17 | 18 | R4f: 19 | SLP + R > SLPR 20 | k4f*SLP*R 21 | 22 | R5f: 23 | SP + R > SPR 24 | k5f*SP*R 25 | 26 | R6f: 27 | SLPR > SL + RP 28 | k6f*SLPR 29 | 30 | R7f: 31 | SPR > S + RP 32 | k7f*SPR 33 | 34 | R8f: 35 | RP + S > RPS 36 | k8f*RP*S 37 | 38 | R9: 39 | RPS > R + S 40 | k9*RPS 41 | 42 | R10f: 43 | SLPR > SPR 44 | k10f*SLPR 45 | 46 | R11: 47 | RP > R 48 | k11*RP 49 | 50 | R12: 51 | SP > S 52 | k12*SP 53 | 54 | R13: 55 | SLP > SL 56 | k13*SLP 57 | 58 | R1b: 59 | SL > S 60 | k1b*SL 61 | 62 | R3b: 63 | SP > SLP 64 | k3b*SP*L 65 | 66 | R4b: 67 | SLPR > SLP + R 68 | k4b*SLPR 69 | 70 | R5b: 71 | SPR > SP + R 72 | k5b*SPR 73 | 74 | R6b: 75 | SL + RP > SLPR 76 | k6b*SL*RP 77 | 78 | R7b: 79 | S + RP > SPR 80 | k7b*S*RP 81 | 82 | R8b: 83 | RPS > S + RP 84 | k8b*RPS 85 | 86 | R10b: 87 | SPR > SLPR 88 | k10b*SPR*L 89 | 90 | #Event Definitions 91 | 92 | Event: jump1, operator.ge(_TIME_,200), 0.0 93 | { 94 | L = 20 95 | } 96 | 97 | Event: jump2, operator.ge(_TIME_,400), 0.0 98 | { 99 | L = 40 100 | } 101 | 102 | Event: jump3, operator.ge(_TIME_,600), 0.0 103 | { 104 | L = 60 105 | } 106 | 107 | Event: jump4, operator.ge(_TIME_,800), 0.0 108 | { 109 | L = 80 110 | } 111 | 112 | Event: jump5, operator.ge(_TIME_,1000), 0.0 113 | { 114 | L = 100 115 | } 116 | 117 | Event: jump6, operator.ge(_TIME_,1400), 0.0 118 | { 119 | L = 80 120 | } 121 | 122 | Event: jump7, operator.ge(_TIME_,1600), 0.0 123 | { 124 | L = 60 125 | } 126 | 127 | Event: jump8, operator.ge(_TIME_,1800), 0.0 128 | { 129 | L = 40 130 | } 131 | 132 | Event: jump9, operator.ge(_TIME_,2000), 0.0 133 | { 134 | L = 20 135 | } 136 | 137 | Event: jump10, operator.ge(_TIME_,2200), 0.0 138 | { 139 | L = 1 140 | } 141 | 142 | #Fixed species 143 | 144 | #Variable species: 145 | S = 100 146 | SL = 0 147 | SP = 0 148 | SLP = 0 149 | SLPR = 0 150 | SPR = 0 151 | L = 1 152 | RPS = 0 153 | RP = 0 154 | R = 100 155 | 156 | # Parameters 157 | k1f = 0.01 158 | k1b = 0.059 159 | k2 = 0.1 160 | k3f = 0.001 161 | k3b =0.001 162 | k4f = 0.0238 163 | k4b = 0.001 164 | k5f = 0.0238 165 | k5b = 0.001 166 | k6f = 19.8 167 | k6b = 0.001 168 | k7f = 19.8 169 | k7b = 0.001 170 | k8f = 0.0238 171 | k8b = 0.2 172 | k9 = 0.5 173 | k10f = 0.001 174 | k10b = 0.001 175 | k11 = 0.0001 176 | k12 = 0.0001 177 | k13 = 0.0001 178 | """ 179 | -------------------------------------------------------------------------------- /stochpy/pscmodels/TranscriptionIntermediate.py: -------------------------------------------------------------------------------- 1 | model = """# Stochastic Simulation Algorithm input format 2 | 3 | R1: 4 | Polymerase > PolymeraseMoving 5 | kini*Polymerase 6 | 7 | R2: 8 | PolymeraseMoving > mRNA + Polymerase 9 | 0.1*PolymeraseMoving # SingleMolecule non-exponential reaction. 10 | 11 | R3: 12 | mRNA > $pool 13 | kdeg*mRNA 14 | 15 | #Species 16 | mRNA = 0 17 | Polymerase = 10 18 | PolymeraseMoving = 0 19 | 20 | # Rates 21 | kini = 1/60 #1/min 22 | kdeg = 1/600 #1/10 min 23 | """ 24 | -------------------------------------------------------------------------------- /stochpy/pscmodels/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy - Stochastic Modeling in Python (http://stochpy.sourceforge.net) 4 | 5 | Copyright (C) 2010-2013 T.R Maarlveld, B.G. Olivier F.J. Bruggeman all rights reserved. 6 | 7 | Timo R. Maarleveld (tmd200@users.sourceforge.net) 8 | VU University, Amsterdam, Netherlands 9 | 10 | Permission to use, modify, and distribute this software is given under the 11 | terms of the StochPy (BSD style) license. 12 | 13 | NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 14 | """ 15 | -------------------------------------------------------------------------------- /stochpy/pscmodels/chain5.py: -------------------------------------------------------------------------------- 1 | model = """R1: 2 | S1 > S2 3 | k1*S1 4 | R2: 5 | S2 > S1 6 | k1*S2 7 | R3: 8 | S2 > S3 9 | k1*S2 10 | R4: 11 | S3 > S2 12 | k1*S3 13 | R5: 14 | S3 > S4 15 | k1*S3 16 | R6: 17 | S4 > S3 18 | k1*S4 19 | R7: 20 | S4 > S5 21 | k1*S4 22 | R8: 23 | S5 > S4 24 | k1*S5 25 | 26 | # InitPar 27 | k1 = 1 # noise 28 | 29 | # InitVar 30 | S1 = 1 31 | S2 = 0 32 | S3 = 0 33 | S4 = 0 34 | S5 = 0 35 | """ 36 | -------------------------------------------------------------------------------- /stochpy/pscmodels/chain50.py: -------------------------------------------------------------------------------- 1 | model = """R1: 2 | S1 > S2 3 | k1*S1 4 | R2: 5 | S2 > S1 6 | k1*S2 7 | R3: 8 | S2 > S3 9 | k1*S2 10 | R4: 11 | S3 > S2 12 | k1*S3 13 | R5: 14 | S3 > S4 15 | k1*S3 16 | R6: 17 | S4 > S3 18 | k1*S4 19 | R7: 20 | S4 > S5 21 | k1*S4 22 | R8: 23 | S5 > S4 24 | k1*S5 25 | R9: 26 | S5 > S6 27 | k1*S5 28 | R10: 29 | S6 > S5 30 | k1*S6 31 | R11: 32 | S6 > S7 33 | k1*S6 34 | R12: 35 | S7 > S6 36 | k1*S7 37 | R13: 38 | S7 > S8 39 | k1*S7 40 | R14: 41 | S8 > S7 42 | k1*S8 43 | R15: 44 | S8 > S9 45 | k1*S8 46 | R16: 47 | S9 > S8 48 | k1*S9 49 | R17: 50 | S9 > S10 51 | k1*S9 52 | R18: 53 | S10 > S9 54 | k1*S10 55 | R19: 56 | S10 > S11 57 | k1*S10 58 | R20: 59 | S11 > S10 60 | k1*S11 61 | R21: 62 | S11 > S12 63 | k1*S11 64 | R22: 65 | S12 > S11 66 | k1*S12 67 | R23: 68 | S12 > S13 69 | k1*S12 70 | R24: 71 | S13 > S12 72 | k1*S13 73 | R25: 74 | S13 > S14 75 | k1*S13 76 | R26: 77 | S14 > S13 78 | k1*S14 79 | R27: 80 | S14 > S15 81 | k1*S14 82 | R28: 83 | S15 > S14 84 | k1*S15 85 | R29: 86 | S15 > S16 87 | k1*S15 88 | R30: 89 | S16 > S15 90 | k1*S16 91 | R31: 92 | S16 > S17 93 | k1*S16 94 | R32: 95 | S17 > S16 96 | k1*S17 97 | R33: 98 | S17 > S18 99 | k1*S17 100 | R34: 101 | S18 > S17 102 | k1*S18 103 | R35: 104 | S18 > S19 105 | k1*S18 106 | R36: 107 | S19 > S18 108 | k1*S19 109 | R37: 110 | S19 > S20 111 | k1*S19 112 | R38: 113 | S20 > S19 114 | k1*S20 115 | R39: 116 | S20 > S21 117 | k1*S20 118 | R40: 119 | S21 > S20 120 | k1*S21 121 | R41: 122 | S21 > S22 123 | k1*S21 124 | R42: 125 | S22 > S21 126 | k1*S22 127 | R43: 128 | S22 > S23 129 | k1*S22 130 | R44: 131 | S23 > S22 132 | k1*S23 133 | R45: 134 | S23 > S24 135 | k1*S23 136 | R46: 137 | S24 > S23 138 | k1*S24 139 | R47: 140 | S24 > S25 141 | k1*S24 142 | R48: 143 | S25 > S24 144 | k1*S25 145 | R49: 146 | S25 > S26 147 | k1*S25 148 | R50: 149 | S26 > S25 150 | k1*S26 151 | R51: 152 | S26 > S27 153 | k1*S26 154 | R52: 155 | S27 > S26 156 | k1*S27 157 | R53: 158 | S27 > S28 159 | k1*S27 160 | R54: 161 | S28 > S27 162 | k1*S28 163 | R55: 164 | S28 > S29 165 | k1*S28 166 | R56: 167 | S29 > S28 168 | k1*S29 169 | R57: 170 | S29 > S30 171 | k1*S29 172 | R58: 173 | S30 > S29 174 | k1*S30 175 | R59: 176 | S30 > S31 177 | k1*S30 178 | R60: 179 | S31 > S30 180 | k1*S31 181 | R61: 182 | S31 > S32 183 | k1*S31 184 | R62: 185 | S32 > S31 186 | k1*S32 187 | R63: 188 | S32 > S33 189 | k1*S32 190 | R64: 191 | S33 > S32 192 | k1*S33 193 | R65: 194 | S33 > S34 195 | k1*S33 196 | R66: 197 | S34 > S33 198 | k1*S34 199 | R67: 200 | S34 > S35 201 | k1*S34 202 | R68: 203 | S35 > S34 204 | k1*S35 205 | R69: 206 | S35 > S36 207 | k1*S35 208 | R70: 209 | S36 > S35 210 | k1*S36 211 | R71: 212 | S36 > S37 213 | k1*S36 214 | R72: 215 | S37 > S36 216 | k1*S37 217 | R73: 218 | S37 > S38 219 | k1*S37 220 | R74: 221 | S38 > S37 222 | k1*S38 223 | R75: 224 | S38 > S39 225 | k1*S38 226 | R76: 227 | S39 > S38 228 | k1*S39 229 | R77: 230 | S39 > S40 231 | k1*S39 232 | R78: 233 | S40 > S39 234 | k1*S40 235 | R79: 236 | S40 > S41 237 | k1*S40 238 | R80: 239 | S41 > S40 240 | k1*S41 241 | R81: 242 | S41 > S42 243 | k1*S41 244 | R82: 245 | S42 > S41 246 | k1*S42 247 | R83: 248 | S42 > S43 249 | k1*S42 250 | R84: 251 | S43 > S42 252 | k1*S43 253 | R85: 254 | S43 > S44 255 | k1*S43 256 | R86: 257 | S44 > S43 258 | k1*S44 259 | R87: 260 | S44 > S45 261 | k1*S44 262 | R88: 263 | S45 > S44 264 | k1*S45 265 | R89: 266 | S45 > S46 267 | k1*S45 268 | R90: 269 | S46 > S45 270 | k1*S46 271 | R91: 272 | S46 > S47 273 | k1*S46 274 | R92: 275 | S47 > S46 276 | k1*S47 277 | R93: 278 | S47 > S48 279 | k1*S47 280 | R94: 281 | S48 > S47 282 | k1*S48 283 | R95: 284 | S48 > S49 285 | k1*S48 286 | R96: 287 | S49 > S48 288 | k1*S49 289 | R97: 290 | S49 > S50 291 | k1*S49 292 | R98: 293 | S50 > S49 294 | k1*S50 295 | 296 | # InitPar 297 | k1 = 1 # noise 298 | 299 | # InitVar 300 | S1 = 1 301 | S2 = 0 302 | S3 = 0 303 | S4 = 0 304 | S5 = 0 305 | S6 = 0 306 | S7 = 0 307 | S8 = 0 308 | S9 = 0 309 | S10 = 0 310 | S11 = 0 311 | S12 = 0 312 | S13 = 0 313 | S14 = 0 314 | S15 = 0 315 | S16 = 0 316 | S17 = 0 317 | S18 = 0 318 | S19 = 0 319 | S20 = 0 320 | S21 = 0 321 | S22 = 0 322 | S23 = 0 323 | S24 = 0 324 | S25 = 0 325 | S26 = 0 326 | S27 = 0 327 | S28 = 0 328 | S29 = 0 329 | S30 = 0 330 | S31 = 0 331 | S32 = 0 332 | S33 = 0 333 | S34 = 0 334 | S35 = 0 335 | S36 = 0 336 | S37 = 0 337 | S38 = 0 338 | S39 = 0 339 | S40 = 0 340 | S41 = 0 341 | S42 = 0 342 | S43 = 0 343 | S44 = 0 344 | S45 = 0 345 | S46 = 0 346 | S47 = 0 347 | S48 = 0 348 | S49 = 0 349 | S50 = 0 350 | """ 351 | -------------------------------------------------------------------------------- /stochpy/pscmodels/dsmts_001_01.py: -------------------------------------------------------------------------------- 1 | model = """# Generated by PySCeS 0.7.2 (2010-08-10 13:12) 2 | 3 | # Keywords 4 | Description: Birth-death model (001), variant 02 5 | Modelname: BirthDeath02 6 | Output_In_Conc: True 7 | Species_In_Conc: False 8 | 9 | # GlobalUnitDefinitions 10 | UnitVolume: litre, 1.0, 0, 1 11 | UnitLength: metre, 1.0, 0, 1 12 | UnitSubstance: item, 1.0, 0, 1 13 | UnitArea: metre, 1.0, 0, 2 14 | UnitTime: second, 1.0, 0, 1 15 | 16 | # Compartments 17 | Compartment: Cell, 1.0, 3 18 | 19 | # Reactions 20 | Death@Cell: 21 | X > $pool 22 | Death_Mu*X 23 | 24 | Birth@Cell: 25 | $pool > X 26 | Birth_Lambda*X 27 | 28 | # Fixed species 29 | 30 | # Variable species 31 | X@Cell = 100.0 32 | 33 | # Parameters 34 | Death_Mu = 0.11 35 | Birth_Lambda = 0.1 36 | """ 37 | 38 | xml_model = """ 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | Lambda 71 | X 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | Mu 85 | X 86 | 87 | 88 | 89 | 90 | 91 | 92 | """ 93 | 94 | -------------------------------------------------------------------------------- /stochpy/pscmodels/dsmts_001_11.py: -------------------------------------------------------------------------------- 1 | model = """# Generated by PySCeS 0.7.2 (2010-08-10 13:12) 2 | 3 | # Keywords 4 | Description: Birth-death model (001), variant 11 5 | Modelname: BirthDeath11 6 | Output_In_Conc: True 7 | Species_In_Conc: True 8 | 9 | # GlobalUnitDefinitions 10 | UnitVolume: litre, 1.0, 0, 1 11 | UnitLength: metre, 1.0, 0, 1 12 | UnitSubstance: item, 1.0, 0, 1 13 | UnitArea: metre, 1.0, 0, 2 14 | UnitTime: second, 1.0, 0, 1 15 | 16 | # Compartments 17 | Compartment: Cell, 2.0, 3 18 | 19 | # Reactions 20 | Death@Cell: 21 | X > $pool 22 | Mu*X 23 | 24 | Birth@Cell: 25 | $pool > X 26 | Lambda*X 27 | 28 | # Fixed species 29 | 30 | # Variable species 31 | X@Cell = 100.0 32 | 33 | # Parameters 34 | Mu = 0.11 35 | Lambda = 0.1 36 | """ 37 | 38 | xml_model=""" 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | Lambda 71 | X 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | Mu 85 | X 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | """ 94 | -------------------------------------------------------------------------------- /stochpy/pscmodels/dsmts_001_19.py: -------------------------------------------------------------------------------- 1 | model = """# Generated by PySCeS 0.8.0 (2012-03-08 12:14) 2 | 3 | # Keywords 4 | Description: Birth-death model (001), variant 01 5 | Modelname: BirthDeath01 6 | Output_In_Conc: True 7 | Species_In_Conc: False 8 | 9 | # GlobalUnitDefinitions 10 | UnitVolume: litre, 1.0, 0, 1 11 | UnitLength: metre, 1.0, 0, 1 12 | UnitSubstance: item, 1.0, 0, 1 13 | UnitArea: metre, 1.0, 0, 2 14 | UnitTime: second, 1.0, 0, 1 15 | 16 | # Compartments 17 | Compartment: Cell, 1.0, 3 18 | 19 | # Reactions 20 | Death@Cell: 21 | X > $pool 22 | Mu*X 23 | 24 | Birth@Cell: 25 | $pool > X 26 | Lambda*X 27 | 28 | # Assignment rules 29 | !F y = 2.0*X 30 | 31 | # Fixed species 32 | 33 | # Variable species 34 | y@Cell = 0.0 35 | X@Cell = 100.0 36 | 37 | # Parameters 38 | Mu = 0.11 39 | Lambda = 0.1 40 | """ 41 | 42 | xml_model=""" 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 2 69 | X 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | Lambda 87 | X 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | Mu 101 | X 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | """ 110 | 111 | -------------------------------------------------------------------------------- /stochpy/pscmodels/dsmts_002_10.py: -------------------------------------------------------------------------------- 1 | model = """# Generated by PySCeS 0.8.0 (2012-07-04 09:55) 2 | 3 | # Keywords 4 | Description: Immigration-Death (002), variant 10 5 | Modelname: ImmigrationDeath09 6 | Output_In_Conc: True 7 | Species_In_Conc: False 8 | 9 | # GlobalUnitDefinitions 10 | UnitVolume: litre, 1.0, 0, 1 11 | UnitLength: metre, 1.0, 0, 1 12 | UnitSubstance: item, 1.0, 0, 1 13 | UnitArea: metre, 1.0, 0, 2 14 | UnitTime: second, 1.0, 0, 1 15 | 16 | # Compartments 17 | Compartment: Cell, 1.0, 3 18 | 19 | # Reactions 20 | Death@Cell: 21 | X > $pool 22 | Mu*X 23 | 24 | Immigration@Cell: 25 | $pool > X 26 | Alpha 27 | 28 | # Event definitions 29 | Event: reset, operator.ge(_TIME_,22.5), 0.0 30 | { 31 | X = 20 32 | } 33 | 34 | # Fixed species 35 | 36 | # Variable species 37 | X@Cell = 0.0 38 | 39 | # Parameters 40 | Mu = 0.1 41 | Alpha = 1.0 42 | """ 43 | 44 | xml_model=""" 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | Alpha 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | Mu 84 | X 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | t 97 | 22.5 98 | 99 | 100 | 101 | 102 | 103 | 104 | 20 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | """ 113 | 114 | -------------------------------------------------------------------------------- /stochpy/pscmodels/dsmts_003_03.py: -------------------------------------------------------------------------------- 1 | model = """ 2 | # Generated by PySCeS 0.7.2 (2010-08-10 13:12) 3 | 4 | # Keywords 5 | Description: Dimerisation model (003), variant 03 6 | Modelname: Dimerisation03 7 | Output_In_Conc: True 8 | Species_In_Conc: False 9 | 10 | # GlobalUnitDefinitions 11 | UnitVolume: litre, 1.0, 0, 1 12 | UnitLength: metre, 1.0, 0, 1 13 | UnitSubstance: item, 1.0, 0, 1 14 | UnitArea: metre, 1.0, 0, 2 15 | UnitTime: second, 1.0, 0, 1 16 | 17 | # Compartments 18 | Compartment: Cell, 1.0, 3 19 | 20 | # Reactions 21 | Dimerisation@Cell: 22 | {2.0}P > P2 23 | k1*P*(P-1)/2 24 | 25 | Disassociation@Cell: 26 | P2 > {2.0}P 27 | k2*P2 28 | 29 | # Event definitions 30 | Event: reset, operator.ge(_TIME_,25), 0.0 31 | { 32 | P2 = 0 33 | P = 100 34 | } 35 | 36 | # Fixed species 37 | 38 | # Variable species 39 | P2@Cell = 0.0 40 | P@Cell = 100.0 41 | 42 | # Parameters 43 | k1 = 0.001 44 | k2 = 0.01 45 | """ 46 | 47 | xml_model=""" 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | k1 83 | P 84 | 85 | 86 | P 87 | 1 88 | 89 | 90 | 2 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | k2 107 | P2 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | t 120 | 25 121 | 122 | 123 | 124 | 125 | 126 | 127 | 100 128 | 129 | 130 | 131 | 132 | 0 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | """ 141 | 142 | -------------------------------------------------------------------------------- /stochpy/pscmodels/dsmts_003_04.py: -------------------------------------------------------------------------------- 1 | model = """# Generated by PySCeS 0.7.2 (2010-08-10 13:12) 2 | 3 | # Keywords 4 | Description: Dimerisation model (003), variant 04 5 | Modelname: Dimerisation04 6 | Output_In_Conc: True 7 | Species_In_Conc: False 8 | 9 | # GlobalUnitDefinitions 10 | UnitVolume: litre, 1.0, 0, 1 11 | UnitLength: metre, 1.0, 0, 1 12 | UnitSubstance: item, 1.0, 0, 1 13 | UnitArea: metre, 1.0, 0, 2 14 | UnitTime: second, 1.0, 0, 1 15 | 16 | # Compartments 17 | Compartment: Cell, 1.0, 3 18 | 19 | # Reactions 20 | Dimerisation@Cell: 21 | {2.0}P > P2 22 | k1*P*(P-1)/2 23 | 24 | Disassociation@Cell: 25 | P2 > {2.0}P 26 | k2*P2 27 | 28 | # Event definitions 29 | Event: reset, gt(P2, 30), 0.0 30 | { 31 | P2 = 0 32 | P = 100 33 | } 34 | 35 | # Fixed species 36 | 37 | # Variable species 38 | P2@Cell = 0.0 39 | P@Cell = 100.0 40 | 41 | # Parameters 42 | k1 = 0.001 43 | k2 = 0.01 44 | """ 45 | 46 | xml_model = """ 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | k1 82 | P 83 | 84 | 85 | P 86 | 1 87 | 88 | 89 | 2 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | k2 106 | P2 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | P2 119 | 30 120 | 121 | 122 | 123 | 124 | 125 | 126 | 100 127 | 128 | 129 | 130 | 131 | 0 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | """ 140 | 141 | -------------------------------------------------------------------------------- /stochpy/tools/ParseDistributions.py: -------------------------------------------------------------------------------- 1 | """ 2 | Parse Distributions 3 | =================== 4 | 5 | Tools to parse model input for delayed, cell division and next reaction methods. 6 | 7 | Written by Maxim Moinat and T.R. Maarleveld, Amsterdam, The Netherlands 8 | E-mail: tmd200@users.sourceforge.net 9 | Last Change: May 26, 2015 10 | """ 11 | 12 | import sys, numpy as np 13 | 14 | def retrieve_index(input_, lst_names): 15 | """ 16 | Converts identifiers (or indices) to indices 17 | 18 | Input: 19 | - *name_or_index* 20 | - *lst_names* 21 | """ 22 | if input_ in lst_names: 23 | index = lst_names.index(input_) # Index according to order in lst_names 24 | else: 25 | if isinstance(input_,int) and input_ < len(lst_names): # Treat input as index if this is true 26 | index = input_ 27 | else: 28 | raise Warning("'{0}' is not recognized. Choose one of {1} or {2}.".format(input_, lst_names, range(len(lst_names)))) 29 | return index 30 | 31 | def convertInput2Indices(input_,lst_names): 32 | """ 33 | convert input (indices, identifiers, or a combination) to indices 34 | 35 | Input: 36 | - *input_* (str,int,list) Example: 'R1',1,['R1',1'] 37 | - *lst_names* (lst) Example: ['R1','R2','R3'] 38 | 39 | Returns: 40 | [0], [1], [0,1] 41 | """ 42 | output = [] 43 | if type(input_) in [str, int]: 44 | input_ = [input_] 45 | for name in input_: 46 | index = retrieve_index(name, lst_names) 47 | output.append(index) 48 | return output 49 | 50 | def convertInput2IndicesAndValues(input_, lst_names, default_value): 51 | """ 52 | Converts identifiers (or indices) to indices 53 | 54 | Input: 55 | - *input_* (list, dict, tuple) 56 | Examples: ['R1','R2'] --> [(0,default_value),(1,default_value)] 57 | {'R1':2,'R2':4} --> [(0,2),(1,4)] 58 | ['R1',('R2',4)] --> [(0,default_value),(1,4)] 59 | ['R1',('R1',3)('R2',4)] --> [(0,default_value),(1,4)] Note: we use only the first instance of a reaction 60 | - *lst_names* (list) of which we extract the indices 61 | - *default_value* (float) value assigned if no value given 62 | 63 | Output: 64 | - list of (,value) pairs or list of indices, where the index is the place of the name in lst_names 65 | - or list of indices linking 66 | """ 67 | output = [] 68 | detected_indices = [] 69 | if type(input_) in [str, int]: # Convert to list if single name or index is specified. 70 | input_ = [input_] 71 | 72 | for name_value in input_: 73 | if type(name_value) in [list,set,tuple] and len(name_value) == 2: #The name and value are specified 74 | index = retrieve_index(name_value[0], lst_names) 75 | value = name_value[1] 76 | 77 | elif type(name_value) in [str, int]: # No value specified, 78 | index = retrieve_index(name_value, lst_names) 79 | if isinstance(input_,dict): 80 | value = input_[name_value] # If input_ dictionary, is the key. 81 | else: 82 | value = default_value 83 | else: 84 | raise Warning("Unexpected format {0}".format(name_value)) 85 | 86 | if index not in detected_indices: # Make sure that each index goes in there only once, i.e. the first one only 87 | output.append((index,value)) 88 | detected_indices.append(index) 89 | return output 90 | 91 | def ParseDistributions(distributions, reaction_names): 92 | """ 93 | Returns two dictionaries specifying for each reaction the function and parameter. 94 | 95 | Input: 96 | - *distributions* (dict): dict containing tuples or lists specifying (name, parameters) of the distribution. Example: {"R1": ("fixed",1),'R2':('gamma',0.059,223)} 97 | - *reaction_names* (list) 98 | 99 | Output: 100 | - *distr_functions*, *distr_parameters* [dictionaries] 101 | - Keys: index corresponding to list in 102 | - Values: a NumPy random function and list of all parameters, respectively. 103 | 104 | #Note: the NumPy exponential distribution uses the SCALE parameter! scale = 1/rate 105 | """ 106 | if distributions == None: 107 | return {},{} #For SMM: no distributions given, then initialize as empty dicts 108 | elif type(distributions) == dict: 109 | distr_functions, distr_parameters = ParseDistributionDictionaries(distributions, reaction_names) 110 | else: 111 | raise Warning("Distributions input must be provided as a dictionary") 112 | return distr_functions, distr_parameters 113 | 114 | def ParseDistributionDictionaries(distr_dict, reaction_names): 115 | """ 116 | Assigns NumPy distribution functions and parameters to specific reactions specified as keys in input *distr_dict* 117 | 118 | We support both reaction identifiers and indices 119 | 120 | Input 121 | - *distr_dict* (dict) Example: {"R1": ("fixed",1),'R2':('gamma',0.059,223)} 122 | - *reaction_names* (list) 123 | """ 124 | functions = {} 125 | parameters = {} 126 | for r in distr_dict: 127 | if type(r) == str and r in reaction_names: # r is a string 128 | r_index = reaction_names.index(r) 129 | elif type(r) == int and r < len(reaction_names): # r is an index 130 | r_index = r 131 | else: 132 | raise Warning("Reaction name ('{0}') is not found in the model. Choose one of ({1}) or an index.".format(r, reaction_names) ) 133 | 134 | function, parm = MakeDistributionFunction(distr_dict[r]) 135 | functions[r_index] = function 136 | parameters[r_index] = parm 137 | 138 | return functions, parameters 139 | 140 | def MakeDistributionFunction(function_parm): 141 | """ 142 | Make the function and parameters 143 | 144 | Input: 145 | - *function_parm* (tuple or list) distribution name followed by all parameters. Example: ('gamma',0.059,223) 146 | 147 | Output: 148 | - *distr_function* Example: 149 | - *distr_parm* Example: (0.059,223) 150 | 151 | The distribution NumPy function with the parameters distr_function(*distr_parm, size = 5) generates 5 random variables. 152 | """ 153 | distr_name = function_parm[0].lower() 154 | distr_parm = function_parm[1:] 155 | if distr_name == 'fixed': 156 | distr_function = lambda x, size=None: np.ones(size)*float(x) if size != None else float(x) # allow multiple fixed values produced 157 | distr_function.__module__ = None # Purely cosmetic 158 | distr_function.__name__ = 'fixed' # Purely cosmetic 159 | else: 160 | try: 161 | distr_function = np.random.__dict__[ distr_name ] 162 | except KeyError: 163 | raise Warning("The distribution function name '{0}' is not recognized.".format(distr_name) ) 164 | 165 | #Check whether the distribution function and parameters correspond. 166 | try: 167 | float(distr_function(*distr_parm)) #The float() gives error when a list is formed (i.e. the size parameter is assigned) 168 | except: 169 | raise Warning("Error: the parameters specified {0} do not correspond to a(n) '{1}' distribution".format(distr_parm, distr_name)) 170 | return distr_function, distr_parm 171 | 172 | def hypoexp_pdf(x, rates_list): 173 | n_rates = len(rates_list) 174 | 175 | alpha = np.array([1] + [0]*(n_rates-1)) 176 | theta = np.zeros((n_rates,n_rates)) 177 | for i in range(n_rates-1): 178 | rate = rates_list[i] 179 | theta[i][i] = -rate 180 | theta[i][i+1] = rate 181 | theta[-1][-1] = -rates_list[-1] 182 | 183 | exp_xtheta = linalg.expm(x*theta) 184 | 185 | column_vector = np.ones((n_rates,1)) 186 | sumtheta = theta.dot(column_vector) 187 | 188 | result = - alpha.dot(exp_xtheta.dot(sumtheta)) 189 | return result[0] 190 | -------------------------------------------------------------------------------- /stochpy/tools/Progress_bar.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | Progress bar 4 | =========== 5 | 6 | Written by Maxim Moinat and TR Maarleveld, Amsterdam, The Netherlands 7 | E-mail: tmd200@users.sourceforge.net 8 | Last Change: February 18, 2015 9 | """ 10 | 11 | from __future__ import division, print_function, absolute_import 12 | import sys,time 13 | 14 | class Progress_bar(): 15 | """ 16 | A progress bar for slow iterative processes. 17 | Give problems if print statements are in the iterative process, the bar is then not refreshed but recreated 18 | """ 19 | def __init__(self, cycles_total, total_signs = 20, done_msg = "Info: Done"): 20 | self.i = 0 21 | self.end = cycles_total 22 | self.total_signs = total_signs 23 | 24 | self.basic_bar = "[%%-%ss] %%d%%%%, Runtime: %%.2f sec" % self.total_signs 25 | self.done_msg = done_msg 26 | 27 | self.t1 = time.time() 28 | #self.update(add = 0) # Shows bar before start of iteration (no step is added) 29 | #Without above line, there can be a slight delay with start script and showing of bar. -> Line disabled for compatibility with StochSim 30 | 31 | def update(self, add = 1,quiet=False): 32 | self.i += add 33 | #Remove bar if end of loop reached. Note: 100% is never printed, the progressbar immediately ends when reached. 34 | if self.i >= self.end: # With one cycle the progressbar will not be printed at all, (unless initialized) -> Not printed for compatibility with StochSim 35 | self.done_bar(quiet) 36 | return None # Escapes the function 37 | 38 | self.frac = self.i/float(self.end) 39 | self.n_signs = int(self.total_signs * self.frac) 40 | self.print_() 41 | 42 | def print_(self): 43 | self.t2 = time.time() 44 | self.new_bar = self.basic_bar %('|'*self.n_signs, self.frac*100, self.t2-self.t1) 45 | sys.stdout.write('\r') # Resets cursor to begin of sentence, which is to be rewritten 46 | sys.stdout.write(self.new_bar) 47 | sys.stdout.flush() 48 | 49 | def done_bar(self,quiet): 50 | if self.done_msg == 'time': # Special end message: the simulation time 51 | self.end_time = time.time() 52 | self.done_msg = "Info: Simulation time: {0}".format(self.end_time - self.t1) 53 | 54 | sys.stdout.write('\r') 55 | if not quiet: 56 | sys.stdout.write(self.done_msg + ' '*(len(self.basic_bar)+self.total_signs)) # + '\n') # Done message, some excess whitespace to make sure to delete the completed progress bar, and newline to print possible new text on the next line 57 | else: 58 | sys.stdout.write(' '*(len(self.basic_bar)+self.total_signs)+'\r') 59 | sys.stdout.flush() 60 | 61 | def main(): 62 | NUMBER_OF_EVENTS = 10 63 | t1 = time.time() 64 | 65 | bar = Progress_bar(cycles_total = NUMBER_OF_EVENTS, total_signs = 20, done_msg = 'time') 66 | for i in range(NUMBER_OF_EVENTS): 67 | for g in range(1000): 68 | a = [g]*g**2 69 | s = 0 70 | for j in a: 71 | s+= j 72 | bar.update() 73 | 74 | t2 = time.time() 75 | 76 | print(t2 - t1) 77 | 78 | if __name__ == '__main__': 79 | main() 80 | -------------------------------------------------------------------------------- /stochpy/tools/__init__.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy - Stochastic Modeling in Python (http://stochpy.sourceforge.net) 4 | 5 | Copyright (C) 2010-2014 T.R Maarlveld, B.G. Olivier F.J. Bruggeman all rights reserved. 6 | 7 | Timo R. Maarleveld (tmd200@users.sourceforge.net) 8 | VU University, Amsterdam, Netherlands 9 | 10 | Permission to use, modify, and distribute this software is given under the 11 | terms of the StochPy (BSD style) license. 12 | 13 | NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 14 | """ 15 | -------------------------------------------------------------------------------- /testing/example_tests.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | """ 3 | StochPy - Stochastic modeling in Python (http://stochpy.sourceforge.net) 4 | 5 | Copyright (C) 2010-2025 T.R Maarlveld, B.G. Olivier, F.J. Bruggeman. All rights reserved. 6 | 7 | This file: 8 | Author: Brett G. Olivier (b.g.olivier@vu.nl) 9 | Address: Vrije Universiteit Amsterdam, Amsterdam, Netherlands. 10 | 11 | 12 | Permission to use, modify, and distribute this software is given under the 13 | terms of the StochPy (BSD style) license. 14 | 15 | NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. 16 | """ 17 | 18 | print('# StochPy Basic tests') 19 | 20 | print('## Import and load') 21 | 22 | import stochpy 23 | smod = stochpy.SSA() 24 | 25 | print('\nDone.\n\n## Basic Simulation with the Direct method') 26 | 27 | smod.DoStochSim(IsTrackPropensities=True) 28 | smod.data_stochsim.simulation_endtime 29 | smod.data_stochsim.simulation_timesteps 30 | smod.GetWaitingtimes() 31 | smod.PrintWaitingtimesMeans() 32 | 33 | print('\nDone.\n\n## Do some Plotting') 34 | 35 | smod.PlotSpeciesTimeSeries() 36 | smod.PlotWaitingtimesDistributions() 37 | smod.PlotPropensitiesTimeSeries() 38 | 39 | print('\nDone.\n\n## Write data to a text file') 40 | 41 | smod.Export2File() 42 | smod.Export2File(analysis='distribution') 43 | smod.Export2File(analysis='distribution',datatype='species') 44 | smod.Export2File(analysis='mean',datatype='species') 45 | smod.Export2File(analysis='std',datatype='species') 46 | smod.Export2File(analysis='autocorrelation',datatype='species') 47 | 48 | print('\nDone.\n\n## Show the means from the data of 3-th trajectory') 49 | 50 | smod.DoStochSim(trajectories=3) # multiple trajectories 51 | smod.data_stochsim.simulation_trajectory 52 | smod.PrintSpeciesMeans() 53 | smod.PrintSpeciesStandardDeviations() 54 | 55 | print('\nDone.\n\n## Switch to data from trajectory 1 and show the means of each species') 56 | 57 | smod.GetTrajectoryData(1) 58 | smod.PrintSpeciesMeans() 59 | smod.PrintSpeciesStandardDeviations() 60 | 61 | print('\nDone.\n\n## Do one long simulation') 62 | 63 | smod.DoStochSim(trajectories=1,end=1000000,mode='steps') 64 | smod.PrintSpeciesMeans() 65 | smod.PrintSpeciesStandardDeviations() 66 | 67 | print('\nDone.\n\n## Plot the PDF for different bin sizes') 68 | 69 | smod.PlotSpeciesDistributions() 70 | smod.PlotSpeciesDistributions(bin_size=5) # larger bin size 71 | smod.PlotSpeciesDistributions(bin_size=10) # again a larger bin size 72 | smod.Export2File(analysis='distribution',datatype='species') 73 | 74 | print('\nDone.\n\n## Usage of the Reload Function: `Ksyn = 20, kdeg = 0.2`') 75 | 76 | smod.ChangeParameter('Ksyn',20.0) 77 | smod.ChangeParameter('Kdeg',0.2) 78 | smod.DoStochSim() 79 | smod.PrintSpeciesMeans() # should be ~Ksyn/Kdeg 80 | 81 | print('\nDone.\n\n## Use another model to show the Interpolation features') 82 | 83 | smod.Model('dsmts-001-01.xml.psc') 84 | smod.DoStochSim(trajectories=1000,end=50,mode='time') 85 | smod.GetRegularGrid(n_samples=51) 86 | smod.PlotAverageSpeciesTimeSeries() 87 | smod.PrintAverageSpeciesTimeSeries() 88 | smod.Export2File(datatype='species',analysis='timeseries',IsAverage=True) 89 | 90 | print('\nDone.\n\n## Test each method for different models:') 91 | 92 | smod.Model('Autoreg.psc') 93 | smod.DoStochSim(trajectories=1,end=1000,mode='steps') 94 | smod.Method('NextReactionMethod') 95 | smod.DoStochSim(trajectories=1,end=1000,mode='steps') 96 | smod.data_stochsim.species 97 | smod.PlotWaitingtimesDistributions() 98 | smod.Method('FirstReactionMethod') 99 | smod.DoStochSim(trajectories=1,end=1000,mode='steps') 100 | smod.Method('TauLeaping') 101 | smod.DoStochSim(trajectories=1,end=1000,mode='steps') 102 | 103 | smod.Model('DecayingDimerizing.psc') 104 | smod.DoStochSim(method = 'Direct',trajectories=1,end=50,mode='time') 105 | smod.DoStochSim(method = 'NextReactionMethod',trajectories=1,end=50,mode='time') 106 | smod.DoStochSim(method = 'FirstReactionMethod',trajectories=1,end=50,mode='time') 107 | smod.PlotWaitingtimesDistributions() 108 | smod.DoStochSim(method = 'TauLeaping',trajectories=1,end=50,mode='time',epsilon=0.03) # Should outperform all other implementations 109 | smod.PlotSpeciesTimeSeries() 110 | #smod.PlotWaitingtimesDistributions() # Should give an error 111 | 112 | smod.Model('chain500.psc') 113 | smod.DoStochSim(method = 'Direct',trajectories=1,end=10000,mode='steps') 114 | smod.DoStochSim(method = 'NextReactionMethod',trajectories=1,end=10000,mode='steps') # should outperform the direct method and all other implementations 115 | 116 | print('\n### Use the Next Reaction Method to test a model with a time event\n') 117 | 118 | smod.Model('dsmts-003-03.xml.psc') 119 | smod.DoStochSim(method = 'NextReactionMethod') 120 | smod.DoTestsuite() 121 | 122 | print('\n### Use the First Reaction method to test a model with a concentration event\n') 123 | 124 | smod.Model('dsmts-003-04.xml.psc') 125 | smod.DoStochSim(method = 'FirstReactionMethod') 126 | smod.DoTestsuite() 127 | 128 | print('\n### Volume Models\n') 129 | 130 | smod.Model('dsmts-001-11.xml.psc') 131 | smod.DoStochSim(method = 'Direct',trajectories=1000,end=50,mode ='time') 132 | smod.PrintAverageSpeciesTimeSeries() 133 | --------------------------------------------------------------------------------