def __init__(self, psc_file, variable_names, v_name, ranges, psc_string=None): self.psc_file = psc_file self.psc_string = psc_string self.variable_names = variable_names self.v_name = 'J_{0}'.format(v_name) if v_name[0:2] != 'J_' else v_name self.ranges = ranges import pysces if self.psc_string is None: self.mod = pysces.model(self.psc_file) else: self.mod = pysces.model(self.psc_file, loader='string', fString=self.psc_string) self.mod.SetQuiet() self.variables = None self.v = numpy.array([]) self.scanner = pysces.Scanner(self.mod) for n, r in zip(self.variable_names, self.ranges): self.scanner.addScanParameter(n, r[0], r[1], r[2]) self.scanner.addUserOutput(self.v_name) self.scanner.Run() results = self.scanner.getResultMatrix() self.variables = results[:, 0:-1] self.v = results[:, -1]
def __init__(self, psc_file, variable_names, v_name, ranges, psc_string=None): self.psc_file = psc_file self.psc_string = psc_string self.variable_names = variable_names self.v_name = 'J_{0}'.format(v_name) if v_name[0:2] != 'J_' else v_name self.ranges = ranges import pysces if self.psc_string is None: self.mod = pysces.model(self.psc_file) else: self.mod = pysces.model(self.psc_file, loader='string', fString=self.psc_string) self.mod.SetQuiet() self.variables = None self.v = numpy.array([]) self.scanner = pysces.Scanner(self.mod) for n, r in zip(self.variable_names, self.ranges): self.scanner.addScanParameter(n, r[0], r[1], r[2]) self.scanner.addUserOutput(self.v_name) self.scanner.Run() results = self.scanner.getResultMatrix() self.variables = results[:, 0:-1] self.v = results[:, -1] # self.v = self.v.reshape(len(self.v), 1)
def _init(self, parameters): import pysces if self.psc_string is None: self.mod = pysces.model(self.psc_file) else: self.mod = pysces.model(self.psc_file, loader='string', fString=self.psc_string) self.mod.SetQuiet() self.parameter_names = [i.name for i in parameters]
def test_statemetab_linear1(self): lin = pysces.model('pysces_test_linear1.psc', self.model_dir) lin.doLoad() lin.hybrd_mesg = 0 lin.State() linmet = array([23.1025641, 38.61538462, 38.94871795], 'd') assert_array_almost_equal(lin.state_species, linmet)
def fitness(self, verbose=True): time = 1000 if not self.cached_fitness is None: return self.cached_fitness with open("/home/calebsimmons/Hungry_Monsters/hungry_monsters/template.psc") as f: template = "".join(f.readlines()) model = ( (template % tuple(self.genotype)) .replace("alpha", str(Chromosome.mrna_cost)) .replace("beta", str(Chromosome.protein_cost)) .replace("gamma", str(Chromosome.sugar_benefit)) .replace("delta", str(Chromosome.enzyme_mrna_cost)) .replace("zeta", str(Chromosome.enzyme_cost)) ) filename = "/home/calebsimmons/Hungry_Monsters/hungry_monsters/model%s.psc" % self.serial_no with open(filename, "w") as f: f.write(model) mod = stochpy.SSA(Method="TauLeaping", File=filename, dir=".") mod.DoStochSim(epsilon=1, mode="steps", end=time) mod.PlotTimeSim(species2plot=["ATP"]) atp_label = mod.data_stochsim.species_labels.index("ATP") self.cached_fitness = mod.data_stochsim.species[-1][atp_label] # mod2 = Parser(filename) # atp_label2 = getATP(stochsimm(mod2.parse())) # self.cached_fitness2 = atp_label2[-1] mod3 = pysces.model(filename, dir="/home/calebsimmons/Hungry_Monsters/hungry_monsters") mod3.doSim(end=60, points=3000) mod3.SimPlot(plot=["ATP"]) self.cached_fitness = mod3.data_sim.getSimData("ATP")[-1][1] if verbose: print self.cached_fitness return self.cached_fitness
def fix_metabolite(mod, fix, model_name=None): """ Fix a metabolite in a model and return a new model with the fixed metabolite. Parameters ---------- mod : PysMod The original model. fix : str The metabolite to fix. model_name : str, optional (Default : none) The file name to use when saving the model (in psc/orca). If None it defaults to original_model_name_fix. Returns ------- PysMod A new model instance with an additional fixed species. """ assert fix in mod.species, "\nInvalid fixed species." if model_name is None: model_name = get_model_name(mod) + '_' + fix mod_str = mod_to_str(mod) fix_head, mod_str_sans_fix = strip_fixed(mod_str) new_fix_head = augment_fix_sting(fix_head, fix) new_mod = model(model_name, loader="string", fString=new_fix_head + '\n' + mod_str_sans_fix) return new_mod
def test_cc_branch1(self): bra = pysces.model('pysces_test_branch1.psc', self.model_dir) bra.doLoad() bra.hybrd_mesg = 0 bra.State() bra.EvalEvar() bra.EvalCC() bracc=[0.25338970963029361000,-0.13797075277724413000,\ -0.21457061516904127000,0.32372624345386269000,0.39406892242342095000,0.38135649243870806000,\ -0.13797075277724413000,0.25338970963029356000,0.39406892242342095000,0.32372624345386258000,\ -0.21457061516904130000,0.38135649243870812000,-0.13797075277724413000,0.25338970963029356000,\ 0.39406892242342095000,0.32372624345386258000,-0.21457061516904130000,0.38135649243870812000,\ 0.05770947842652475500,0.05770947842652472700,0.08974915362718985400,0.32372624345386269000,\ 0.08974915362718984000,0.38135649243870817000,0.25338970963029361000,-0.13797075277724413000,\ -0.21457061516904127000,0.32372624345386269000,0.39406892242342095000,0.38135649243870806000,\ 0.05770947842652474100,0.05770947842652471300,0.08974915362718984000,0.32372624345386264000,\ 0.08974915362718982600,0.38135649243870806000,-0.23751396180748979000,-0.23751396180748979000,\ -0.36937913195668803000,0.55728841856739109000,-0.36937913195668803000,0.65649776896096446000,\ -0.08622262758262820600,-0.08622262758262820600,-0.13409249329650016000,-0.48367318660804903000,\ -0.13409249329650016000,0.92430342836630586000,-0.79249085140642661000,-0.14644930661681688000,\ -0.22775636995026044000,0.34361981023636490000,0.41828517483934929000,0.40479154289778968000,\ -0.14644930661681685000,-0.79249085140642661000,0.41828517483934929000,0.34361981023636484000,\ -0.22775636995026050000,0.40479154289778979000] bracc_new = [] for x in range(bra.cc_all.shape[0]): for y in range(bra.cc_all.shape[1]): bracc_new.append(round(bra.cc_all[x,y],2)) for x in range(len(bracc)): bracc[x] = round(bracc[x],2) #os.sys.stderr.write(str(bracc[x]) + ' --> ' + str(bracc_new[x])+'\n') assert_array_almost_equal(bracc,bracc_new)
def test_statemetab_branch1(self): bra = pysces.model('pysces_test_branch1.psc', self.model_dir) bra.doLoad() bra.hybrd_mesg = 0 bra.State() bramet = array([4.8583996, 1.88547254, 1.49124431, 1.49124431], 'd') assert_array_almost_equal(bra.state_species, bramet)
def test_stateflux_linear1(self): lin = pysces.model('pysces_test_linear1.psc', self.model_dir) lin.doLoad() lin.hybrd_mesg = 0 lin.State() linflux = array([76.8974359, 76.8974359, 76.8974359, 76.8974359], 'd') assert_array_almost_equal(lin.state_flux, linflux)
def test_statemetab_branch1(self): bra = pysces.model('pysces_test_branch1.psc', self.model_dir) bra.doLoad() bra.hybrd_mesg = 0 bra.State() bramet = array([4.8583996,1.88547254,1.49124431,1.49124431],'d') assert_array_almost_equal(bra.state_species,bramet)
def fitness(self, verbose=True): time = 1000 if not self.cached_fitness is None: return self.cached_fitness with open( "/home/calebsimmons/Hungry_Monsters/hungry_monsters/template.psc" ) as f: template = "".join(f.readlines()) model = (template % tuple(self.genotype))\ .replace("alpha",str(Chromosome.mrna_cost))\ .replace("beta",str(Chromosome.protein_cost))\ .replace("gamma",str(Chromosome.sugar_benefit))\ .replace("delta",str(Chromosome.enzyme_mrna_cost))\ .replace('zeta',str(Chromosome.enzyme_cost)) filename = "/home/calebsimmons/Hungry_Monsters/hungry_monsters/model%s.psc" % self.serial_no with open(filename, 'w') as f: f.write(model) mod = stochpy.SSA(Method="TauLeaping", File=filename, dir='.') mod.DoStochSim(epsilon=1, mode="steps", end=time) mod.PlotTimeSim(species2plot=["ATP"]) atp_label = mod.data_stochsim.species_labels.index('ATP') self.cached_fitness = mod.data_stochsim.species[-1][atp_label] #mod2 = Parser(filename) #atp_label2 = getATP(stochsimm(mod2.parse())) #self.cached_fitness2 = atp_label2[-1] mod3 = pysces.model( filename, dir='/home/calebsimmons/Hungry_Monsters/hungry_monsters') mod3.doSim(end=60, points=3000) mod3.SimPlot(plot=["ATP"]) self.cached_fitness = mod3.data_sim.getSimData("ATP")[-1][1] if verbose: print self.cached_fitness return self.cached_fitness
def test_statemetab_moiety1(self): moi = pysces.model('pysces_test_moiety1.psc', self.model_dir) moi.doLoad() moi.hybrd_mesg = 0 moi.State() moimet = array([3.6886875,16.25569882,7.3113125,4.39229787,41.02504596,2.60770213,0.42718994,2.57281006,2.44791155,17.0012171],'d') assert_array_almost_equal(moi.state_species,moimet)
def test_stateflux_linear1(self): lin = pysces.model('pysces_test_linear1.psc', self.model_dir) lin.doLoad() lin.hybrd_mesg = 0 lin.State() linflux = array([76.8974359, 76.8974359, 76.8974359, 76.8974359],'d') assert_array_almost_equal(lin.state_flux,linflux)
def test_cc_branch1(self): bra = pysces.model('pysces_test_branch1.psc', self.model_dir) bra.doLoad() bra.hybrd_mesg = 0 bra.State() bra.EvalEvar() bra.EvalCC() bracc=[0.25338970963029361000,-0.13797075277724413000,\ -0.21457061516904127000,0.32372624345386269000,0.39406892242342095000,0.38135649243870806000,\ -0.13797075277724413000,0.25338970963029356000,0.39406892242342095000,0.32372624345386258000,\ -0.21457061516904130000,0.38135649243870812000,-0.13797075277724413000,0.25338970963029356000,\ 0.39406892242342095000,0.32372624345386258000,-0.21457061516904130000,0.38135649243870812000,\ 0.05770947842652475500,0.05770947842652472700,0.08974915362718985400,0.32372624345386269000,\ 0.08974915362718984000,0.38135649243870817000,0.25338970963029361000,-0.13797075277724413000,\ -0.21457061516904127000,0.32372624345386269000,0.39406892242342095000,0.38135649243870806000,\ 0.05770947842652474100,0.05770947842652471300,0.08974915362718984000,0.32372624345386264000,\ 0.08974915362718982600,0.38135649243870806000,-0.23751396180748979000,-0.23751396180748979000,\ -0.36937913195668803000,0.55728841856739109000,-0.36937913195668803000,0.65649776896096446000,\ -0.08622262758262820600,-0.08622262758262820600,-0.13409249329650016000,-0.48367318660804903000,\ -0.13409249329650016000,0.92430342836630586000,-0.79249085140642661000,-0.14644930661681688000,\ -0.22775636995026044000,0.34361981023636490000,0.41828517483934929000,0.40479154289778968000,\ -0.14644930661681685000,-0.79249085140642661000,0.41828517483934929000,0.34361981023636484000,\ -0.22775636995026050000,0.40479154289778979000] bracc_new = [] for x in range(bra.cc_all.shape[0]): for y in range(bra.cc_all.shape[1]): bracc_new.append(round(bra.cc_all[x, y], 2)) for x in range(len(bracc)): bracc[x] = round(bracc[x], 2) #os.sys.stderr.write(str(bracc[x]) + ' --> ' + str(bracc_new[x])+'\n') assert_array_almost_equal(bracc, bracc_new)
def test_stateflux_moiety1(self): moi = pysces.model('pysces_test_moiety1.psc', self.model_dir) moi.doLoad() moi.hybrd_mesg = 0 moi.State() moiflux = array([250.01825652,250.01825652,250.01825652,250.01825652,250.01825652,250.01825652,250.01825652],'d') assert_array_almost_equal(moi.state_flux,moiflux)
def test_stateflux_branch1(self): bra = pysces.model('pysces_test_branch1.psc', self.model_dir) bra.doLoad() bra.hybrd_mesg = 0 bra.State() braflux = array([2.42139889,2.42139889,1.21069945,1.21069945,1.21069945,1.21069945],'d') assert_array_almost_equal(bra.state_flux,braflux)
def test_statemetab_linear1(self): lin = pysces.model('pysces_test_linear1.psc', self.model_dir) lin.doLoad() lin.hybrd_mesg = 0 lin.State() linmet = array([23.1025641, 38.61538462, 38.94871795],'d') assert_array_almost_equal(lin.state_species,linmet)
def sbml2pysces(self,model_xml): ''' Use pysces to read the SBML file ''' current_dir=os.getcwd() pysces_filename=os.path.join(current_dir,model_xml[-4]+'.psc') pysces.interface.convertSBML2PSC(model_xml,pscfile=pysces_filename) return pysces.model(pysces_filename)
def test_stateflux_branch1(self): bra = pysces.model('pysces_test_branch1.psc', self.model_dir) bra.doLoad() bra.hybrd_mesg = 0 bra.State() braflux = array([ 2.42139889, 2.42139889, 1.21069945, 1.21069945, 1.21069945, 1.21069945 ], 'd') assert_array_almost_equal(bra.state_flux, braflux)
def test_stateflux_moiety1(self): moi = pysces.model('pysces_test_moiety1.psc', self.model_dir) moi.doLoad() moi.hybrd_mesg = 0 moi.State() moiflux = array([ 250.01825652, 250.01825652, 250.01825652, 250.01825652, 250.01825652, 250.01825652, 250.01825652 ], 'd') assert_array_almost_equal(moi.state_flux, moiflux)
def test_statemetab_moiety1(self): moi = pysces.model('pysces_test_moiety1.psc', self.model_dir) moi.doLoad() moi.hybrd_mesg = 0 moi.State() moimet = array([ 3.6886875, 16.25569882, 7.3113125, 4.39229787, 41.02504596, 2.60770213, 0.42718994, 2.57281006, 2.44791155, 17.0012171 ], 'd') assert_array_almost_equal(moi.state_species, moimet)
def test_elas_linear1(self): lin = pysces.model('pysces_test_linear1.psc', self.model_dir) lin.doLoad() lin.hybrd_mesg = 0 lin.State() lin.EvalEvar() line = [-0.30043348,0.,0., 1.50216739,-0.50216739,0., 0.,1.50650217,-0.50650217, 0.,0.,1.01300433] line_new = [] for x in range(lin.elas_var.shape[0]): for y in range(lin.elas_var.shape[1]): line_new.append(round(lin.elas_var[x,y],2)) for x in range(len(line)): line[x] = round(line[x],2) assert_array_almost_equal(line,line_new)
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' arglist = [] for reagent in R_info['Reagents']: r = reagent.replace('self.', '') if r in varlist: arglist.append(r) arglist.sort() fnspecs[R] = (arglist, R_info['RateEq'].replace('self.', '')) varspecs = make_varspecs(m, fnspecs) for fname, fspec in m.__userfuncs__.items(): # Don't know how these are implemented yet fnspec[fname] = fspec dsargs = args(name=fname[:-3], varspecs=varspecs, fnspecs=fnspecs, pars=pardict, ics=icdict, tdata=[0, max_t]) genclassname = target + '_ODEsystem' try: genclass = getattr(Generator, genclassname) except AttributeError: raise TypeError("Invalid ODE solver type") return genclass(dsargs)
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' arglist = [] for reagent in R_info['Reagents']: r = reagent.replace('self.','') if r in varlist: arglist.append(r) arglist.sort() fnspecs[R] = (arglist, R_info['RateEq'].replace('self.','')) varspecs = make_varspecs(m, fnspecs) for fname, fspec in m.__userfuncs__.items(): # Don't know how these are implemented yet fnspec[fname] = fspec dsargs = args(name=fname[:-3], varspecs=varspecs, fnspecs=fnspecs, pars=pardict, ics=icdict, tdata=[0, max_t]) genclassname = target + '_ODEsystem' try: genclass = getattr(Generator, genclassname) except AttributeError: raise TypeError("Invalid ODE solver type") return genclass(dsargs)
def test_cc_moiety1(self): moi = pysces.model('pysces_test_moiety1.psc', self.model_dir) moi.doLoad() moi.hybrd_mesg = 0 moi.State() moi.EvalEvar() moi.EvalCC() moicc = moicc=[0.01114694087227875000,0.07381787576415140000,\ 0.18139104475836643000,0.04685617079784056700,0.25208717198140801000,0.04329618737852313600,\ 0.39140460844743269000,0.01114694087227862500,0.07381787576415056700,0.18139104475836440000,\ 0.04685617079784004000,0.25208717198140518000,0.04329618737852265100,0.39140460844742830000,\ 0.01114694087227874000,0.07381787576415133100,0.18139104475836623000,0.04685617079784051800,\ 0.25208717198140773000,0.04329618737852309500,0.39140460844743230000,0.01114694087227875000,\ 0.07381787576415140000,0.18139104475836643000,0.04685617079784056700,0.25208717198140801000,\ 0.04329618737852313600,0.39140460844743269000,0.01114694087227875000,0.07381787576415140000,\ 0.18139104475836643000,0.04685617079784056700,0.25208717198140801000,0.04329618737852313600,\ 0.39140460844743269000,0.01114694087227876100,0.07381787576415146900,0.18139104475836659000,\ 0.04685617079784060900,0.25208717198140823000,0.04329618737852317800,0.39140460844743302000,\ 0.01114694087227875200,0.07381787576415141400,0.18139104475836645000,0.04685617079784057400,\ 0.25208717198140806000,0.04329618737852314300,0.39140460844743280000,-0.96946517151898726000,\ 0.07237057005414701500,0.17783461222620814000,0.04593748812318156800,0.24714464011293155000,\ 0.04244730330314599300,0.38373055769937375000,-0.00493043463469603270,-0.03265059135931840800,\ -0.08023158100034956400,0.14913606725290945000,\ 0.02650472034900546900,0.11529508789995771000,-0.17312326850750914000,-0.00258941341724495350,\ -0.01714775382110165000,-0.04213679882643606200,0.25950964810000904000,-0.07785637143685617000,\ -0.02885675558547331700,-0.09092255501289707400,-0.00651179467430067560,-0.04312275948862360300,\ -0.10596460973080281000,-0.02003169777867189200,0.40783108111031047000,-0.00355036168876400080,\ -0.22864985774914801000,-0.07520202175595115700,-0.49800690277268156000,1.11329060303376930000,\ 0.28758054022385904000,1.54718927875470390000,0.26573108181778565000,-2.64058257930148920000,\ 0.08511194652599511600,-0.37976718223865702000,-0.93319355560031703000,-0.24105862936563618000,\ -1.29690043219020780000,-0.22274375836758617000,2.98855161123640300000,-0.01413200623441426100,\ 0.06305662607990611400,0.15494766227242857000,0.04002542759392844300,0.21533763168639128000,\ 0.03698442240380646300,-0.49621976380204558000,0.01332315621836589900,0.08822932693215754200,\ 0.21680398717628285000,-0.25121007495788511000,0.32322678367369212000,-0.85819164176559659000,\ 0.46781846272298522000,0.01096817827331699600,0.07263406439629339900,0.17848209108569948000,\ 0.03374050370795465800,-0.68693259335574453000,0.00598007183654026410,0.38512768405594056000,\ 0.00513245176028354240,0.03398840011328187900,0.08351894906745090100,-0.51437161070192172000,\ 0.15431837495286327000,0.05719670138973560700,0.18021673341830685000] moicc_new = [] for x in range(moi.cc_all.shape[0]): for y in range(moi.cc_all.shape[1]): moicc_new.append(round(moi.cc_all[x, y], 2)) for x in range(len(moicc)): moicc[x] = round(moicc[x], 2) #os.sys.stderr.write(str(moicc[x]) + ' --> ' + str(moicc_new[x])+'\n') assert_array_almost_equal(moicc, moicc_new)
def load_data2d(file_name, mod=None, ltxe=None): """ Loads a gzipped cPickle file containing a Data2D object. Optionally a model can be provided (which is useful when loading data that reference the same model. For the same reason a LatexExpr object can be supplied. """ with gzip.open(file_name, 'rb') as f: data_2dobj = pickle.load(f) if not mod: data_2dobj.mod = pysces.model(data_2dobj.mod) else: data_2dobj.mod = mod if ltxe: del data_2dobj._ltxe data_2dobj._ltxe = ltxe return data_2dobj
def test_cc_moiety1(self): moi = pysces.model('pysces_test_moiety1.psc', self.model_dir) moi.doLoad() moi.hybrd_mesg = 0 moi.State() moi.EvalEvar() moi.EvalCC() moicc = moicc=[0.01114694087227875000,0.07381787576415140000,\ 0.18139104475836643000,0.04685617079784056700,0.25208717198140801000,0.04329618737852313600,\ 0.39140460844743269000,0.01114694087227862500,0.07381787576415056700,0.18139104475836440000,\ 0.04685617079784004000,0.25208717198140518000,0.04329618737852265100,0.39140460844742830000,\ 0.01114694087227874000,0.07381787576415133100,0.18139104475836623000,0.04685617079784051800,\ 0.25208717198140773000,0.04329618737852309500,0.39140460844743230000,0.01114694087227875000,\ 0.07381787576415140000,0.18139104475836643000,0.04685617079784056700,0.25208717198140801000,\ 0.04329618737852313600,0.39140460844743269000,0.01114694087227875000,0.07381787576415140000,\ 0.18139104475836643000,0.04685617079784056700,0.25208717198140801000,0.04329618737852313600,\ 0.39140460844743269000,0.01114694087227876100,0.07381787576415146900,0.18139104475836659000,\ 0.04685617079784060900,0.25208717198140823000,0.04329618737852317800,0.39140460844743302000,\ 0.01114694087227875200,0.07381787576415141400,0.18139104475836645000,0.04685617079784057400,\ 0.25208717198140806000,0.04329618737852314300,0.39140460844743280000,-0.96946517151898726000,\ 0.07237057005414701500,0.17783461222620814000,0.04593748812318156800,0.24714464011293155000,\ 0.04244730330314599300,0.38373055769937375000,-0.00493043463469603270,-0.03265059135931840800,\ -0.08023158100034956400,0.14913606725290945000,\ 0.02650472034900546900,0.11529508789995771000,-0.17312326850750914000,-0.00258941341724495350,\ -0.01714775382110165000,-0.04213679882643606200,0.25950964810000904000,-0.07785637143685617000,\ -0.02885675558547331700,-0.09092255501289707400,-0.00651179467430067560,-0.04312275948862360300,\ -0.10596460973080281000,-0.02003169777867189200,0.40783108111031047000,-0.00355036168876400080,\ -0.22864985774914801000,-0.07520202175595115700,-0.49800690277268156000,1.11329060303376930000,\ 0.28758054022385904000,1.54718927875470390000,0.26573108181778565000,-2.64058257930148920000,\ 0.08511194652599511600,-0.37976718223865702000,-0.93319355560031703000,-0.24105862936563618000,\ -1.29690043219020780000,-0.22274375836758617000,2.98855161123640300000,-0.01413200623441426100,\ 0.06305662607990611400,0.15494766227242857000,0.04002542759392844300,0.21533763168639128000,\ 0.03698442240380646300,-0.49621976380204558000,0.01332315621836589900,0.08822932693215754200,\ 0.21680398717628285000,-0.25121007495788511000,0.32322678367369212000,-0.85819164176559659000,\ 0.46781846272298522000,0.01096817827331699600,0.07263406439629339900,0.17848209108569948000,\ 0.03374050370795465800,-0.68693259335574453000,0.00598007183654026410,0.38512768405594056000,\ 0.00513245176028354240,0.03398840011328187900,0.08351894906745090100,-0.51437161070192172000,\ 0.15431837495286327000,0.05719670138973560700,0.18021673341830685000] moicc_new = [] for x in range(moi.cc_all.shape[0]): for y in range(moi.cc_all.shape[1]): moicc_new.append(round(moi.cc_all[x,y],2)) for x in range(len(moicc)): moicc[x] = round(moicc[x],2) #os.sys.stderr.write(str(moicc[x]) + ' --> ' + str(moicc_new[x])+'\n') assert_array_almost_equal(moicc,moicc_new)
def test_elas_linear1(self): lin = pysces.model('pysces_test_linear1.psc', self.model_dir) lin.doLoad() lin.hybrd_mesg = 0 lin.State() lin.EvalEvar() line = [ -0.30043348, 0., 0., 1.50216739, -0.50216739, 0., 0., 1.50650217, -0.50650217, 0., 0., 1.01300433 ] line_new = [] for x in range(lin.elas_var.shape[0]): for y in range(lin.elas_var.shape[1]): line_new.append(round(lin.elas_var[x, y], 2)) for x in range(len(line)): line[x] = round(line[x], 2) assert_array_almost_equal(line, line_new)
def test_elas_branch1(self): bra = pysces.model('pysces_test_branch1.psc', self.model_dir) bra.doLoad() bra.hybrd_mesg = 0 bra.State() bra.EvalEvar() brae = [-0.66930781448548349, 0.0, 0.0, 0.0, 0.78845903183743249,\ -0.52920041809870422, 0.0, 0.0, 0.0, 0.95441603882382564,\ -0.60578219088834051, 0.0, 0.0, 0.95441603882382564, 0.0,\ -0.60578219088834051, 0.0, 0.0, 0.9421058792599355, 0.0, 0.0,\ 0.0, 0.0, 0.9421058792599355] brae_new = [] for x in range(bra.elas_var.shape[0]): for y in range(bra.elas_var.shape[1]): brae_new.append(round(bra.elas_var[x,y],2)) for x in range(len(brae)): brae[x] = round(brae[x],2) assert_array_almost_equal(brae,brae_new)
def load_model(fpath): cdir = os.getcwd() d, fname = os.path.split(fpath) mod = pysces.model(fname, d) mod.Simulate() S = np.copy(mod.Nmatrix.array) pre = np.copy(S) pre[pre == 1] = 0 pre[pre == -1] = 1 places, transitions = mod.Nmatrix.getLabels() init = list(getattr(mod, place+"_init") for place in places) rate_getter = attrgetter("rate") rates = list(rate_getter(getattr(mod, transition)) for transition in transitions) os.chdir(cdir) return StochasticPetriNet._make([pre, np.array(init), S, np.array(rates), places, transitions])
def test_elas_branch1(self): bra = pysces.model('pysces_test_branch1.psc', self.model_dir) bra.doLoad() bra.hybrd_mesg = 0 bra.State() bra.EvalEvar() brae = [-0.66930781448548349, 0.0, 0.0, 0.0, 0.78845903183743249,\ -0.52920041809870422, 0.0, 0.0, 0.0, 0.95441603882382564,\ -0.60578219088834051, 0.0, 0.0, 0.95441603882382564, 0.0,\ -0.60578219088834051, 0.0, 0.0, 0.9421058792599355, 0.0, 0.0,\ 0.0, 0.0, 0.9421058792599355] brae_new = [] for x in range(bra.elas_var.shape[0]): for y in range(bra.elas_var.shape[1]): brae_new.append(round(bra.elas_var[x, y], 2)) for x in range(len(brae)): brae[x] = round(brae[x], 2) assert_array_almost_equal(brae, brae_new)
def test_cc_linear1(self): lin = pysces.model("pysces_test_linear1.psc", self.model_dir) lin.doLoad() lin.hybrd_mesg = 0 lin.State() lin.EvalEvar() lin.EvalCC() lincc = [ 0.02564102564102570300, 0.05128205128205126600, 0.15384615384615383000, 0.76923076923076916000, 0.02564102564102571000, 0.05128205128205128000, 0.15384615384615385000, 0.76923076923076938000, 0.02564102564102571000, 0.05128205128205128000, 0.15384615384615385000, 0.76923076923076938000, 0.02564102564102570300, 0.05128205128205126600, 0.15384615384615383000, 0.76923076923076916000, -0.30636428644396779000, -0.61272857288793536000, 0.15318214322198387000, 0.76591071610991934000, -0.08534676570192656400, -0.17069353140385327000, -0.51208059421155983000, 0.76812089131733974000, -0.96185074526088343000, 0.05062372343478333000, 0.15187117030435002000, 0.75935585152175000000, ] lincc_new = [] for x in range(lin.cc_all.shape[0]): for y in range(lin.cc_all.shape[1]): lincc_new.append(round(lin.cc_all[x, y], 2)) for x in range(len(lincc)): lincc[x] = round(lincc[x], 2) assert_array_almost_equal(lincc, lincc_new)
def P_INIT(self, *args): 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
def load_model(fpath): cdir = os.getcwd() d, fname = os.path.split(fpath) mod = pysces.model(fname, d) mod.Simulate() S = np.copy(mod.Nmatrix.array) pre = np.copy(S) pre[pre == 1] = 0 pre[pre == -1] = 1 places, transitions = mod.Nmatrix.getLabels() init = list(getattr(mod, place + "_init") for place in places) rate_getter = attrgetter("rate") rates = list( rate_getter(getattr(mod, transition)) for transition in transitions) os.chdir(cdir) return StochasticPetriNet._make( [pre, np.array(init), S, np.array(rates), places, transitions])
def main (): # Check for file if len (sys.argv) < 2: s.write ("Error! Please supply a filename.\n") sys.exit (1) # Load model and convert to SBML m = pysces.model (sys.argv [1], dir=CWD) m.doLoad() sbml = pysces.interface.writeMod2SBML (m, getstrbuf=True).getvalue() # Output to 'model_' + current time + '.sbml' name = CWD + "/model_" + time.strftime ("%m%d%H%M%S") + ".sbml" out = open (name, 'w') out.write (sbml) out.flush () out.close () # Finished s.write ("Success! {} printed.\n".format (name))
def test_cc_linear1(self): lin = pysces.model('pysces_test_linear1.psc', self.model_dir) lin.doLoad() lin.hybrd_mesg = 0 lin.State() lin.EvalEvar() lin.EvalCC() lincc=[0.02564102564102570300,0.05128205128205126600,\ 0.15384615384615383000,0.76923076923076916000,0.02564102564102571000,0.05128205128205128000,\ 0.15384615384615385000,0.76923076923076938000,0.02564102564102571000,0.05128205128205128000,\ 0.15384615384615385000,0.76923076923076938000,0.02564102564102570300,0.05128205128205126600,\ 0.15384615384615383000,0.76923076923076916000,-0.30636428644396779000,-0.61272857288793536000,\ 0.15318214322198387000,0.76591071610991934000,-0.08534676570192656400,-0.17069353140385327000,\ -0.51208059421155983000,0.76812089131733974000,-0.96185074526088343000,0.05062372343478333000,\ 0.15187117030435002000,0.75935585152175000000] lincc_new = [] for x in range(lin.cc_all.shape[0]): for y in range(lin.cc_all.shape[1]): lincc_new.append(round(lin.cc_all[x, y], 2)) for x in range(len(lincc)): lincc[x] = round(lincc[x], 2) assert_array_almost_equal(lincc, lincc_new)
def test_elas_moiety1(self): moi = pysces.model('pysces_test_moiety1.psc', self.model_dir) moi.doLoad() moi.hybrd_mesg = 0 moi.State() moi.EvalEvar() moie = [1.4753672613878632,-0.47536726138786306,-0.47536726138786312,\ 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.4278931518740323,0.0,\ 1.4278931518740325,-0.42789315187403271,-0.42789315187403271,\ 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0514524437327983,0.0,\ 1.0514524437327983,-0.051452443732798468,0.0,0.0,0.0,0.0,\ 0.0,-0.04300468618304179,0.0,1.0430046861830418,0.0,0.0,\ -0.043004686183041797,0.0,-0.073768363069393092,0.0,\ 1.0737683630693931,0.0,0.0,0.0,0.0,0.0,1.0737683630693931,\ 0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.029048874655981143,\ 1.0290488746559812,0.0,-0.029048874655981143,0.0,0.0,0.0,\ 0.0,0.0,0.0,0.0,0.0,0.0, 1.0199985395848277] moie_new = [] for x in range(moi.elas_var.shape[0]): for y in range(moi.elas_var.shape[1]): moie_new.append(round(moi.elas_var[x,y],2)) for x in range(len(moie)): moie[x] = round(moie[x],2) assert_array_almost_equal(moie,moie_new)
def test_elas_moiety1(self): moi = pysces.model('pysces_test_moiety1.psc', self.model_dir) moi.doLoad() moi.hybrd_mesg = 0 moi.State() moi.EvalEvar() moie = [1.4753672613878632,-0.47536726138786306,-0.47536726138786312,\ 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.4278931518740323,0.0,\ 1.4278931518740325,-0.42789315187403271,-0.42789315187403271,\ 0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,1.0514524437327983,0.0,\ 1.0514524437327983,-0.051452443732798468,0.0,0.0,0.0,0.0,\ 0.0,-0.04300468618304179,0.0,1.0430046861830418,0.0,0.0,\ -0.043004686183041797,0.0,-0.073768363069393092,0.0,\ 1.0737683630693931,0.0,0.0,0.0,0.0,0.0,1.0737683630693931,\ 0.0,0.0,0.0,0.0,0.0,0.0,0.0,-0.029048874655981143,\ 1.0290488746559812,0.0,-0.029048874655981143,0.0,0.0,0.0,\ 0.0,0.0,0.0,0.0,0.0,0.0, 1.0199985395848277] moie_new = [] for x in range(moi.elas_var.shape[0]): for y in range(moi.elas_var.shape[1]): moie_new.append(round(moi.elas_var[x, y], 2)) for x in range(len(moie)): moie[x] = round(moie[x], 2) assert_array_almost_equal(moie, moie_new)
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()
outcomes[10][0][t]) if QueueNTrajectories[-1,iteration] == 0: QueueExtinction[iteration,0] = 1 else: QueueExtinction[iteration,0] = 0 for i in range(0,n_runs): print "CDI Queue Iteration %i of %i" % (i+1,n_runs) CDIQueueRun(CDIQueue,i) numpy.savetxt('CDIQueueOutcomes.csv',QueueOutcomes,delimiter=',' ,header="Incident,Recur,N",comments='') numpy.savetxt('CDIQueueDTrajectories.csv',QueueDTrajectories,delimiter=',' ,header="D",comments='') numpy.savetxt('CDIQueueNTrajectories.csv',QueueNTrajectories,delimiter=',' ,header="N",comments='') numpy.savetxt('CDIQueueExtinction.csv',QueueExtinction,delimiter=',',header="Extinction",comments='') print "C. difficile Queue Model - Runs Complete" ####################### # Deterministic Model # ####################### import pysces detCDI = pysces.model('CDIpool.psc', dir=workingdir) detCDI.doSim(end=end_time,points=end_time*10) detTS = detCDI.data_sim.getSpecies() detHead = "Time," + ','.join(detCDI.species) os.chdir(workingdir) numpy.savetxt('CDIDeterministic.csv',detTS,delimiter=',',header=detHead,comments='')
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 ' '
def run(dir_method, json_method, dir_model, json_model, dir_results, dir_solver, json_solver, dir_data=None, file_data=None, exp_sign='_exp_'): config_method = Config(os.path.join(dir_method, json_method)) config_model = Config(os.path.join(dir_model, json_model)) config_solver = Config(os.path.join(dir_solver, json_solver)) # Experiment name exp_name = exp_sign + config_method.config['method_name'] + '_' # Load PySCES model mod = pysces.model(config_model.config['mod_name'], dir=dir_model) # Solver settings mod.__settings__["mode_sim_max_iter"] = config_solver.config[ "mode_sim_max_iter"] mod.__settings__['lsoda_atol'] = config_solver.config['lsoda_atol'] mod.__settings__['lsoda_rtol'] = config_solver.config['lsoda_rtol'] mod.__settings__['lsoda_mxordn'] = config_solver.config['lsoda_mxordn'] mod.__settings__['lsoda_mxords'] = config_solver.config['lsoda_mxords'] mod.__settings__['lsoda_mxstep'] = config_solver.config['lsoda_mxstep'] # =====REAL DATA PREPARATION===== # Remove fixed_species from params. We do it only once. params = remove_fixed(mod.parameters, mod.fixed_species, compartment=config_model.config['compartment']) if dir_data is not None: config_model.config['real_data'] = True mod.sim_start = config_model.config['sim_start'] mod.sim_end = config_model.config['sim_end'] mod.sim_points = config_model.config['sim_points'] x_obs = np.load(os.path.join(dir_data, file_data)) else: config_model.config['real_data'] = False x_obs, t = generate_data(mod, params, sim_start=config_model.config['sim_start'], sim_end=config_model.config['sim_end'], sim_points=config_model.config['sim_points'], noise=config_model.config['noise']) real_params = read_real_parameters(mod, params) real_params_array = dict_to_array(real_params, params) np.save(os.path.join(dir_results, exp_name + 'x_obs.npy'), x_obs) np.save(os.path.join(dir_results, exp_name + 't.npy'), t) np.save(os.path.join(dir_results, exp_name + 'real_params_array.npy'), real_params_array) json.dump( real_params, open(os.path.join(dir_results, exp_name + 'real_params.json'), "w")) json.dump( params, open(os.path.join(dir_results, exp_name + 'params.json'), "w")) pickle.dump(mod, open(os.path.join(dir_results, exp_name + 'mod.pkl'), "wb")) # =======EXPERIMENT======= # dump, just in case, configs pickle.dump( config_method.config, open(os.path.join(dir_results, exp_name + 'config_method.pkl'), "wb")) pickle.dump( config_model.config, open(os.path.join(dir_results, exp_name + 'config_model.pkl'), "wb")) # Init method # -get all classes in the file classes = [x for x in dir(EA) if isclass(getattr(EA, x))] # -check whether the provided name is available assert config_method.config[ 'method_name'] in classes, 'Wrong name of the method! Please pick one of the following methods: {}'.format( classes) # -initialize the appropriate class module = __import__("algorithms.population_optimization_algorithms", fromlist=[config_method.config['method_name']]) my_class = getattr(module, config_method.config['method_name']) method = my_class(config_method.config, config_model.config) # Init parameters theta = np.random.uniform(low=config_model.config['low'], high=config_model.config['high'], size=(config_method.config['pop_size'], len(params))) theta = np.clip(theta, a_min=config_method.config['clip_min'], a_max=config_method.config['clip_max']) # Calcute their energy E = calculate_fitness(x_obs, theta, mod, params, dist=method.dist, config_model=config_model.config, config_method=config_method.config) # -=Start experiment=- best_E = [np.min(E)] all_E = E all_theta = theta clock_start = time.time() print('START ~~~~~~>') g = config_method.config['generations'] for i in range(g): print(f'========> Generation {i+1}/{g}') theta, E = method.step(theta, E, x_obs, mod, params) if np.min(E) < best_E[-1]: best_E.append(np.min(E)) else: best_E.append(best_E[-1]) all_theta = np.concatenate((all_theta, theta), 0) all_E = np.concatenate((all_E, E), 0) # SAVING np.save(os.path.join(dir_results, exp_name + 'all_theta.npy'), all_theta) np.save(os.path.join(dir_results, exp_name + 'all_E.npy'), all_E) np.save(os.path.join(dir_results, exp_name + 'best_E.npy'), np.asarray(best_E)) # early stopping if i > config_method.config['patience']: if best_E[-config_method.config['patience']] == best_E[-1]: break print('~~~~~~> END') clock_stop = time.time() print('Time elapsed: {}'.format(clock_stop - clock_start)) np.save(os.path.join(dir_results, exp_name + 'time.npy'), np.asarray(clock_stop - clock_start))
#!/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, engine='ipcluster') t5 = time.time() par2.addScanParameter('V4', 60, 100, 11) par2.addScanParameter('V1', 100, 130, 16) par2.addScanParameter('V2', 100, 130, 16, follower=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) os.chdir(backupdir)
#!/usr/bin/env python import os dir = os.getcwd() import numpy as np import matplotlib.pyplot as plt import pysces models = [("PT test", "Wajima2009_PTtest.xml", 0, 7), \ ("aPTT test", "Wajima2009_aPTTtest.xml", 2, 6)] figure = "Wajima2009_tests.png" for model in models: pysces.PyscesInterfaces.Core2interfaces().convertSBML2PSC(sbmlfile=model[1], sbmldir=dir, pscfile=model[1], pscdir=dir) mod = pysces.model(model[1], dir=dir) os.chdir(dir) mod.doSim(end=0.025, points=500) x = mod.data_sim.getSpecies() x[0] = x[1] # we don't want pre-dilution concentration in the time course plot x[0,-1] = 0 # start the time at 0 x = x.transpose() data = lambda name: x[mod.data_sim.species_labels.index(name)+1] time = mod.data_sim.getTime() * 3600 # we want seconds here, not hours plot = lambda species, norm: plt.plot(time, data(species)/max(data(norm))*100) plt.subplot(221 + model[2]) # rows, cols, num pdict = {"Fg":"F", "II":"IIa", "X":"Xa"} for key in pdict.keys(): plot(pdict[key], key)
def getPyscesModel(): A = tc_allItems(); N = fromMatrix( tc_getStoichiometry(A), True ); rates0 = fromTC( tc_getRates(A) ); params = fromTC( tc_getParameters(A) ); fixed = fromTC( tc_getFixedVariables(A) ); inits = fromTC( tc_getInitialValues(A) ); funcsNames = fromTC( tc_getForcingFunctionNames(A) ); funcsAssign0 = fromTC( tc_getForcingFunctionAssignments(A) ); triggers = fromTC( tc_getEventTriggers() ); events0 = fromTC( tc_getEventResponses() ); #tc_deleteItemsArray(A); emptyExists = False; modelString = ''; rates = []; funcsAssign = []; events = []; p = re.compile('\^'); for i in rates0: rates.append(p.sub('**',i)); for i in funcsAssign0: funcsAssign.append(p.sub('**',i)); for i in events0: events.append(p.sub('**',i)); reacs = len(rates); species = len(N[0]); for i in range(0,reacs): #for each reaction lhs = []; rhs = []; for j in range(0,species): #get reactants and products n = N[2][j][i]; if n > 0: if n != 1.0: rhs.append("{" + str(n) + "}" + str(N[0][j])); #product else: rhs.append(str(N[0][j])); elif n < 0: n = -n; if n != 1.0: lhs.append("{" + str(n) + "}" + str(N[0][j])); #reactants else: lhs.append(str(N[0][j])); #full reaction and its rate if len(lhs) > 0 or len(rhs) > 0: modelString += N[1][i] + ":\n"; #print its name if len(lhs) == 0: lhs.append("EMPTY"); emptyExists = True; if len(rhs) == 0: rhs.append("EMPTY"); emptyExists = True; modelString += " " + "+".join(lhs) + " > " + "+".join(rhs) + "\n"; modelString += " " + rates[i] + "\n\n"; #we are done with reactions. moving on to params, events, functions, etc. fix = ''; if emptyExists: fix = "FIX: EMPTY"; n = len(fixed[0]); if n > 0 and len(fixed[0]) == len(fixed[2][0]): if not emptyExists: fix += "FIX:"; for i in range(0,n): fix += " " + fixed[0][0][i]; modelString = fix + "\n\n" + modelString; modelString += "# Init ext\n"; #fixed variables if n > 0 and len(fixed[0]) == len(fixed[2][0]): for i in range(0,n): modelString += fixed[0][i] + " = " + str(fixed[2][0][i]) + "\n"; #initial variables hashInits = {}; n = len(inits[0]); if n > 0 and len(inits[0]) == len(inits[2][0]): modelString += "\n# Init vars\n"; for i in range(0,n): hashInits[ inits[0][i] ] = inits[2][0][i]; modelString += inits[0][i] + " = " + str(inits[2][0][i]) + "\n"; for j in N[0]: if not hashInits.has_key(j): modelString += j + " = 0.0\n"; #parameters -- remove unused parameters n = len(params[0]); if n > 0 and len(params[0]) == len(params[2][0]): modelString += "\n# Init params\n"; for i in range(0,n): #for each parameter modelString += params[0][i] + " = " + str(params[2][0][i]) + "\n"; n = len(funcsNames); if n > 0 and len(funcsNames) == len(funcsAssign): modelString += "\n# Forcing functions\n"; for i in range(0,n): modelString += "!F " + funcsNames[i] + " = " + funcsAssign[i] + "\n"; n = len(triggers); if n > 0 and len(triggers) == len(events): modelString += "\n# Events\n"; for i in range(0,n): modelString += "Event: event" + str(i) + "," + triggers[i] + " , 0 {" + events[i] + "}\n"; p = re.compile("\^"); p.sub("**",modelString); #return modelString; mod = pysces.model("model",loader="string",fString=modelString); mod.doLoad(); return mod;
QueueMedian[iteration,1] = numpy.median(QueuePredator[:,iteration]) QueueMedian[iteration,2] = numpy.median(QueueTotal[:,iteration]) QueueMean[iteration,0] = numpy.mean(QueuePrey[:,iteration]) QueueMean[iteration,1] = numpy.mean(QueuePredator[:,iteration]) QueueMean[iteration,2] = numpy.mean(QueueTotal[:,iteration]) for i in range(0,n_runs): LVQueueRun(LVqueue,i) print "LV Queue Iteration %i of %i" % (i+1,n_runs) numpy.savetxt('QueuePrey.csv',QueuePrey,delimiter=',',header="Prey",comments='') numpy.savetxt('QueuePredator.csv',QueuePredator,delimiter=',',header="Predator",comments='') numpy.savetxt('QueueTotal.csv',QueueTotal,delimiter=',',header="TotalN",comments='') numpy.savetxt('LVqueueExtinction.csv',QueueExtinction,delimiter=',',header="Prey,Predator,N",comments='') numpy.savetxt('LVqueueMedian.csv',QueueMedian,delimiter=',', header="Prey,Predator,N",comments='') numpy.savetxt('LVqueueMean.csv',QueueMean,delimiter=',',header="Prey,Predator,N",comments='') print "LV Queue Model - Runs Complete" ####################### # Deterministic Model # ####################### import pysces detLV = pysces.model('LVpool.psc', dir=workingdir) detLV.doSim(end=end_time,points=end_time*10) detLVTS = detLV.data_sim.getSpecies() detLVHead = "Time," + ','.join(detLV.species) os.chdir(workingdir) numpy.savetxt('LVDeterministic.csv',detLVTS,delimiter=',',header=detLVHead,comments='')
def __init__(self, name, value=None): 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 ' '
#!/usr/bin/env python # Simulation D'alcantara with pysces import pysces #mod = pysces.model('/home/mattions/Work/model/diff_eq/Fernandez/BIOMD0000000152.xml') mod = pysces.model('/home/mattions/Work/model/diff_eq/Dalcantara_model/dAlcantara2003.xml') mod.doLoad() mod.doSimPlot(end=600.00)
#!/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') 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',60,100,11) ser.addScanParameter('V1',100,160,16) ser.addScanParameter('V2',100,130,16,slave=True) ser.addScanParameter('V3',80,90,6) ser.addUserOutput('J_R1', 'A', 'ecR4_X','ccJR1_R1') #ser.addUserOutput('J_R1', 'A') ser.Run() print("Done: ", next(tbox.SER)) t2=time.time() print("Duration: %.2f seconds" % (t2-t1))
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()
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 " "
S = self.pcMod.data_sim.getSpecies()[:, 1:] # print 'called!' return S if __name__ == "__main__": #nr samples to generate N = 10000 burn = 5000 thin = 5 force = False fname = 'testLogInverseModel1.pkl' #initialize the pysces model pcMod = pysces.model('pysces_test_linear2') pcMod.sim_end = 5 pcMod.sim_points = 60 #initialize "data" pcMod.Simulate() D = pcMod.data_sim.getSpecies()[:, 1:] D += sigmaExp * randn(D.shape[0], D.shape[1]) #get initial parameters nK = 0 for p in pcMod.parameters: if p[0] == 'k': nK += 1 k0 = zeros(nK) for p in pcMod.parameters:
def bounceSpecies(S, fname='speciesBounce.spc'): with open(fname, 'w') as f: for i, s in enumerate(S): f.write('s%d = %.3e\n' % (i + 1, s[-1])) def spc(pcMod): return pcMod.data_sim.getSpecies()[:, 1:].T if __name__ == '__main__': #------------------------------------------------------- # initialize the pysces model #------------------------------------------------------- modName = 'R-ERK_s.psc' pcMod = pysces.model(modName) pcMod.__settings__["lsoda_mxstep"] = 2000 # pcMod.sim_end = 5e2 # pcMod.Simulate() # bounceSpecies(spc(pcMod)) # pcMod.__settings__['mode_sim_init'] = 3 pcMod.sim_end = 1e5 pcMod.sim_points = 200 idxDic, nmDic, sDic = loadSpeciesDict(modName[:-4] + '_speciesDictionary.txt') #------------------------------------------------------- #u,sv,vh = linalg.svd(pcMod.nmatrix) #figure() #plot(sv)
def playgame(currentdir,stochastic,parameter1,parameter2): #parameter 1 determines final level #parameter 2 determines #type should be 0 or 1 -> toggle between stochastic and deterministic if stochastic: #stochastic #change directory smod = stochpy.SSA() smod.Model(os.path.join(currentdir, 'mRNAproteinIulia.psc')) #change parameters smod.ChangeParameter("Ksynmrna",parameter1) smod.ChangeParameter("Kdeg2",parameter2) #smod.ChangeInitialSpeciesCopyNumber("Kdeg1",parameter2) #smod.data_stochsim.simulation_endtime #smod.data_stochsim.simulation_timesteps = 51.0 smod.Timesteps(50) smod.Endtime(50) smod.DoStochSim(end=50) #Only plot as a test #smod.PlotSpeciesTimeSeries() #pysces.plt.setAxisLabel('x', label='time') #pysces.plt.setAxisLabel('y', label='expression levels') #plt.savefig(currentdir+'/stoch.png') simvalues_stoch = smod.data_stochsim.getSpecies() x_values = range(5,51,5) #arrange results time_val = [] mRNA_val = [] protein_val =[] for list in simvalues_stoch: time_val.append(list[0]) mRNA_val.append(list[1]) protein_val.append(list[2]) time_val_rounded = [] for i in time_val: time_val_rounded.append(int(round(i))) count = 0 mRNA_final = [] protein_final = [] for val in range(0,len(mRNA_val)-1): mRNA_final.append([mRNA_val[val]] * ((time_val_rounded[count+1] - time_val_rounded[count]))) protein_final.append([protein_val[val]] * ((time_val_rounded[count+1] - time_val_rounded[count]))) count = count + 1 time_final = range(1,51) mRNA_final = flatten(mRNA_final) protein_final = flatten(protein_final) simvalues = zip(time_final,mRNA_final,protein_final) else: #deterministic print(currentdir+'pysces_determ.psc') mod = pysces.model('pysces_determ', dir=os.getcwd()) #change params mod.Ksynmrna = parameter1 mod.Kdeg2 = parameter2 mod.doSim(end=50.0, points=50.0) mod.Simulate() #print os.getcwd(), '\n\n\n' #mod.doSimPlot() #plot here to check it works but don't actually plot mod.sim_start = 1.0 mod.doSimPlot(end=50.0, points=51, plot='species', fmt='lines', filename=None) #pysces.plt.p_activateInterface('matplotlib') #pysces.plt.setAxisLabel('x', label='time') #pysces.plt.setAxisLabel('y', label='expression levels') #plt.savefig(currentdir+'/simpledeterm.png') #plt.close() #get simulation values simvalues = mod.data_sim.getSpecies() # print(mod.data_sim.getSpecies()) os.chdir(currentdir) with open("simvalues.csv","wb") as f: writer = csv.writer(f) writer.writerows(simvalues) return simvalues
model_file = 'BIOMD0000000860.xml' # environment import os cDir = os.path.dirname(os.path.abspath(os.sys.argv[0])) import pysces import numpy as np import pickle model_dir = os.path.join(cDir, 'models') out_dir = os.path.join(cDir, 'out', model_file) data_dir = os.path.join(cDir, 'ref_data', model_file) if not os.path.exists(out_dir): os.makedirs(out_dir) pysces.output_dir = out_dir # code pysces.interface.convertSBML2PSC(model_file, sbmldir=model_dir, pscdir=out_dir) mod = pysces.model(model_file + '.psc', dir=out_dir) mod.doSim(4 * 3600, 4 * 3600 + 1) mod.SimPlot() pysces.plt.export(model_file, directory=out_dir, outtype='png') ref_sim_data = pickle.load(open(data_dir + '/simdata.pkl', 'rb')) assert np.allclose(mod.data_sim.getAllSimData(), ref_sim_data), \ "Data doesn't match reference!" print('\nOutput path: \"{}\"\n\nDone.\n'.format(out_dir))
def __load_sbml__(self): psc_file_name = self.sbml_file_name + ".psc" pysces.interface.convertSBML2PSC(self.sbml_file_name) self.pyscesModel = pysces.model(psc_file_name) self.pyscesModel.doLoad()
def run(mod_name='wolf1', sim_start=0.0, sim_end=30., sim_points=30, exp_sign='exp_1_', method_name='DE', generations=5, pop_size=500, clip_min=0., clip_max=15., a=-100., b=100., scale=1., p=-1., std=0.1, gamma=0.75, CR=0.9, best=False, dist_name='truncnorm', low=0., high=100., indices=None, compartment=True, patience=100, noise=0.1, dir_model='C:\\Dev\\github\\abcde\\', slash='\\'): # Experiment name exp_name = exp_sign + method_name + '_' # Load PySCES model mod = pysces.model(mod_name, dir=dir_model) # Solver settings mod.__settings__["mode_sim_max_iter"] = 0 mod.__settings__['lsoda_atol'] = 1.0e-012 mod.__settings__['lsoda_rtol'] = 1.0e-007 mod.__settings__['lsoda_mxordn'] = 12 mod.__settings__['lsoda_mxords'] = 5 mod.__settings__['lsoda_mxstep'] = 0 # =====REAL DATA PREPARATION===== # Remove fixed_species from params. Do it only once params = remove_fixed(mod.parameters, mod.fixed_species, compartment=compartment) x_obs, t = generate_data(mod, params, sim_start=sim_start, sim_end=sim_end, sim_points=sim_points, noise=noise) real_params = read_real_parameters(mod, params) real_params_array = dict_to_array(real_params, params) np.save(dir_model + 'results' + slash + exp_name + 'x_obs.npy', x_obs) np.save(dir_model + 'results' + slash + exp_name + 't.npy', t) np.save(dir_model + 'results' + slash + exp_name + 'real_params_array.npy', real_params_array) json.dump( real_params, open(dir_model + 'results' + slash + exp_name + 'real_params.json', "w")) json.dump( params, open(dir_model + 'results' + slash + exp_name + 'params.json', "w")) pickle.dump( mod, open(dir_model + 'results' + slash + exp_name + 'mod.pkl', "wb")) # =======EXPERIMENT======= # config conf = Config(method_name=method_name, generations=generations, pop_size=pop_size, clip_min=clip_min, clip_max=clip_max, a=a, b=b, scale=scale, p=p, std=std, gamma=gamma, CR=CR, best=best, dist_name=dist_name, indices=indices, patience=patience) pickle.dump( conf.config, open(dir_model + 'results' + slash + exp_name + 'config.pkl', "wb")) # Init method if method_name in ['DE']: method = DE(conf.config) elif method_name in ['RevDE']: method = RevDE(conf.config) elif method_name in ['ES']: method = ES(conf.config) elif method_name in ['EDA']: method = EDA(conf.config) elif method_name in ['RevDEknn']: method = RevDEknn(conf.config) elif method_name in ['EDAknn']: method = RevDEknn(conf.config) else: raise ValueError('Wrong method! Only DE, ABC_DE and ABC_MH.') # Init parameters theta = np.random.uniform(low=low, high=high, size=(conf.config['pop_size'], len(params))) theta = np.clip(theta, a_min=conf.config['clip_min'], a_max=conf.config['clip_max']) # Calcute their energy E = calculate_fitness(x_obs, theta, mod, params, dist=method.dist, conf=conf.config) # Start experiment best_E = [np.min(E)] all_E = E all_theta = theta clock_start = time.time() print('START ~~~~~~>') g = conf.config['generations'] for i in range(conf.config['generations']): print(f'========> Generation {i+1}/{g}') theta, E = method.step(theta, E, x_obs, mod, params) if np.min(E) < best_E[-1]: best_E.append(np.min(E)) else: best_E.append(best_E[-1]) all_theta = np.concatenate((all_theta, theta), 0) all_E = np.concatenate((all_E, E), 0) # SAVING np.save(dir_model + 'results' + slash + exp_name + 'all_theta.npy', all_theta) np.save(dir_model + 'results' + slash + exp_name + 'all_E.npy', all_E) np.save(dir_model + 'results' + slash + exp_name + 'best_E.npy', np.asarray(best_E)) # early stopping if i > patience: if best_E[-patience] == best_E[-1]: break print('~~~~~~> END') clock_stop = time.time() print('Time elapsed: {}'.format(clock_stop - clock_start)) np.save(dir_model + 'results' + slash + exp_name + 'time.npy', np.asarray(clock_stop - clock_start))