How to use the pysces.model function in pysces

To help you get started, we’ve selected a few pysces examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github PySCeS / pysces / pysces / examples / testinvalidstate.py View on Github external
#!/usr/bin/env python
# Testing the new parallel scanner class - detection of invalid states
# --jr20101218

import os
backupdir = os.getcwd()

import numpy as np
import pysces

tbox=pysces.PyscesUtils.TimerBox()
import time

m=pysces.model('isola2a')

ser = pysces.Scanner(m)

print("Serial execution...")
print("Start: ", tbox.normal_timer('SER'))
print(next(tbox.SER))
t1=time.time()
ser.quietRun = True
ser.addScanParameter('V4',0.01,200,2000,log=True)
ser.addUserOutput('J_R1', 'A')
ser.Run()
print("Done: ", next(tbox.SER))
t2=time.time()
print("Duration: %.2f seconds" % (t2-t1))
ser.statespersecond = len(ser.ScanSpace)/(t2-t1)
print("States per second: %.1f" % ser.statespersecond)
github davidcraft / SimKern / Testing / testpysces.py View on Github external
def sim_plot(pscfilename):
    '''
    Takes in a psc file, creates a pysces model, finds the steady states,
    and plots the values of each Species concentration over time
    Returns : a model object
    '''
    model = pysces.model(pscfilename)
    model.sim_start = 0.0
    model.sim_end = 20
    model.sim_points = 50
    model.Simulate()
    model.doState()
    model.doSimPlot(end=10.0,points=210,plot='species', fmt='lines',filename = None)
    return model
github PySCeS / pysces / pysces / examples / testRunScatter.py View on Github external
#!/usr/bin/env python
# Testing the new parallel scanner class

import os
backupdir = os.getcwd()

import numpy as np
import pysces

tbox=pysces.PyscesUtils.TimerBox()
import time

m=pysces.model('isola2a')

print("\n\nParallel execution...using RunScatter")
par2 = pysces.ParScanner(m)
t5=time.time()
par2.addScanParameter('V4',60,100,11)
par2.addScanParameter('V1',100,130,16)
par2.addScanParameter('V2',100,130,16,slave=True)
par2.addScanParameter('V3',80,90,6)
par2.addUserOutput('J_R1', 'A', 'ecR4_X', 'ccJR1_R1')
#par2.addUserOutput('J_R1', 'A')
par2.RunScatter()
t6=time.time()
print("Duration: %.2f seconds" % (t6-t5))
par2.statespersecond = par2.Tsteps/(t6-t5)
print("States per second: %.1f" % par2.statespersecond)
github robclewley / pydstool / PyDSTool / Toolbox / PySCes_SBML.py View on Github external
def get_pysces_model(filename, target='Vode'):
    path, fname = os.path.split(filename)
    m = pysces.model(fname, dir=path)

    max_t = np.Inf

    parlist = m.__fixed_species__ + m.__parameters__
    pardict = dict([(pname, p['initial']) for pname, p in m.__pDict__.items()])
    varlist = m.__species__ # list ['s0', 's1', 's2']

    icdict = dict([(vname, v['initial']) for vname, v in m.__sDict__.items() if not v['fixed']])
    fixed_species = dict([(pname, p['initial']) for pname, p in m.__sDict__.items() if p['fixed']])
    pardict.update(fixed_species)

    fnspecs = {}
    for R in m.__reactions__: # list ['R1', 'R2', 'R3', 'R4']
        R_info = m.__nDict__[R]
        #assert R_info['Modifiers'] == []
        assert R_info['Type'] == 'Rever'
github PySCeS / pysces / pysces / examples / pysces_stochpy.py View on Github external
# Typical continuous result. Now let's assume this is a stochastic system and do a discrete 
# simulation to the same end time using the Direct method 
mod.doStochSim(end=ENDTIME, mode='time', method='Direct')
# we can plot the results with this function and save the results
mod.StochSimPlot()
pysces.plt.export('%s_par_set_1_stochastic_endtime' % MODEL_NAME, CDIR)

# or we can do everything at once, lets try simulate to a number of steps and plot the results
mod.doStochSimPlot(end=ENDSTEPS, mode='steps', method='Direct')
pysces.plt.export('%s_par_set_1_stochastic_maxsteps' % MODEL_NAME, CDIR)

input('\npress  to continue\n')

# a cool feature of PySCeS is a totally encapsulated model object which means
# we can create an independent object from the same file, let's instantiate mod2
mod2 = pysces.model('Burstmodel.psc', CDIR)

# This time however we want to change some parameters ... in PySCeS this is
# done in 'real' time

# Set parameter set 2
mod2.koff = 50
mod2.kon = 50
mod2.ksyn = 80
mod2.kdeg = 2.5

# again lets to a continous simulation to endtime with 2*endtime time points
# and save the results to a file
mod2.doSimPlot(ENDTIME, 2*ENDTIME)
pysces.plt.export('%s_par_set_2_deterministic' % MODEL_NAME, CDIR)

# However as a continous model we also have access to PySCeS other functionality, 
github leihuang / infotopo0 / model / rxnnet / mca.py View on Github external
def cmp_pysces(rxnid_v='RBCO', rxnid_J='TPI'):
    """
    FIXME **
    """
    import pandas as pd
    import pysces  # the import would force changing the directory (can we change it?)


    sbmlname = 'model_poolman2000_arnold1.xml'
    sbmldir = '/Users/lei/Dropbox/Research/CalvinCycle/models'
    
    pysces.interface.convertSBML2PSC(sbmlname, sbmldir=sbmldir)
    
    mod = pysces.model(sbmlname)
    
    mod.doLoad()
    mod.doMca()
    
    s = pd.Series(dict([(k.rstrip('_ss'),v) for (k,v) in mod.__dict__.items() 
                        if k.endswith('_ss')]))
    J = pd.Series(dict([(k,v) for (k,v) in mod.__dict__.items() 
                        if k.startswith('J_')]))
    
    CJ_Jid_vid = mod.__dict__['ccJ%s_%s'%(rxnid_J, rxnid_v)]
    
    return CJ_Jid_vid
github PySCeS / pysces / pysces / kraken / KrakenServer.py View on Github external
args = args[0]
        print('Args', args)
        self.RESULT = None
        self.setStatus('INITIALISING')
        client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        client.connect((self.client_address[0], CFSERVE_PORT))
        client.send('GET')
        GO = True
        model = ''
        while GO:
            data = client.recv(self.block_size)
            model += data
            if data == '':
                GO = False
        self.model_name = args[0]
        self.model = pysces.model(self.model_name, loader="string", fString=model)
        if self.debug: print('P_INIT ... ok.')
        self.setStatus('DONE_INITIALISE')
        return True
github PySCeS / pysces / pysces / examples / pysces_stochpy.py View on Github external
graphs generated will be both displayed and saved as PNG format files. 


NO WARRANTY OF FITNESS OF ANY KIND FOR ANYTHING ... SERIOUSLY!
(C) Brett G. Olivier Amsterdam 2011. All rights reserved
"""

# First we need to import PySCeS 0.8.0 or newer and store the current directory in CDIR
import os, time 
CDIR = os.path.dirname(os.path.abspath(os.sys.argv[0]))
import numpy, pysces

# Next we instantiate a PySCeS model object (load the input file from the current directory)
# and set the simulation endtime/endsteps. Note how in this input file we specify that this 
# model should be simulated stochastically and that the output should be displayed in amounts. 
mod = pysces.model('Burstmodel.psc', CDIR)
MODEL_NAME = 'Burstmodel'
ENDTIME = 100
ENDSTEPS = 10000

# First let's assume this model represents a determinisitic system and do a continuous 
# simulation to endtime with 2*endtime time points with LSODA or CVODE. 
mod.doSimPlot(ENDTIME, 2*ENDTIME)
# Save the results to a file using the PySCeS plotting library (pysces.plt.*)
pysces.plt.export('%s_par_set_1_deterministic' % MODEL_NAME, CDIR)

# Typical continuous result. Now let's assume this is a stochastic system and do a discrete 
# simulation to the same end time using the Direct method 
mod.doStochSim(end=ENDTIME, mode='time', method='Direct')
# we can plot the results with this function and save the results
mod.StochSimPlot()
pysces.plt.export('%s_par_set_1_stochastic_endtime' % MODEL_NAME, CDIR)
github PySCeS / pysces / pysces / RateChar.py View on Github external
"""
        assert solver in (0,1,2), "\nSolver mode can only be one of (0, 1, 2)!"
        #if summary:
            #assert hasattr(self, 'summaryfile'), "\nSummary mode can only be called from doAllRateChar method."
        # base steady state
        basemod = self._psc_mod
        basemod.doMca()
        assert fixed in basemod.species, "\nInvalid fixed species."
        basemod_fstr = self.pscMod2str(basemod)
        basemod.mode_elas_deriv=1
        mymap = ModelMap(basemod)
        OrigFix, Fstr = self.stripFixed(basemod_fstr)
        print(Fstr)
        h1 = self.augmentFixString(OrigFix, fixed)
        model1 = self._mod + '_' + fixed
        mod = pysces.model(model1, loader="string", fString=h1+'\n'+Fstr)
        #mod.doLoad()   # no longer needed as of PySCeS 0.7.0
        mod.SetQuiet()
        mod.mode_solver = solver
        mod.doState()
        mod.mode_elas_deriv = 1
        setattr(mod,fixed,getattr(basemod,fixed+'_ss'))
        mod.doMcaRC()
        # get fluxes directly linked to fixed species
        FixSubstrateFor = ['J_' + r for r in getattr(mymap, fixed).isSubstrateOf()]
        FixProductFor = ['J_' + r for r in getattr(mymap, fixed).isProductOf()]
        print('Fixed species is Substrate for: ', FixSubstrateFor)
        print('Fixed species is Product for:   ', FixProductFor)
        # set scan distances
        scan_min = getattr(basemod,fixed+'_ss')/self.min_concrange_factor
        scan_max = getattr(basemod,fixed+'_ss')*self.max_concrange_factor
        # do scan               
github PySCeS / pysces / pysces / PyscesModelMap.py View on Github external
self.name = name
        self.value = value
        self.components = []

    def setComponent(self, comp):
        self.components.append(comp)
        setattr(self, comp.name, comp)

    def hasComponents(self):
        return MapList([a.name for a in self.components])



if __name__ == '__main__':
    import pysces
    M = pysces.model('pysces_model_linear1')
    M.doLoad()

    print('\nModel', M.ModelFile)
    print('=============')
    modmap = ModelMap(M)

    print('Reactions\n', modmap.hasReactions())
    print('Species\n', modmap.hasSpecies())
    print('FixedSpecies\n', modmap.hasFixedSpecies())
    print(' ')
    print('R1 has reagents\n', modmap.R1.hasReagents())
    print('R1 has sub\n', modmap.R1.hasSubstrates())
    print('R1 has prod\n', modmap.R1.hasProducts())
    print('R1 has mod\n', modmap.R1.hasModifiers())
    print(' ')
    print('s2 is reagent\n', modmap.s2.isReagentOf())