Exemplo n.º 1
0
def Baserun(pdict):
    model = stochpy.SSA()
    ignored = pdict
    model.Model(model_file='protective_decolV04.psc', dir=workingdir)
    model.Endtime(end_time)
    model.DoStochSim()
    model.ShowSpecies()
def Metapop_exp(iteration):
    model = stochpy.SSA()
    model.Model(model_file='1dr_3nurseratio.psc.txt', dir=workingdir)
    model.Endtime(end_time)

    model.DoStochSim()
    model.ShowSpecies()
Exemplo n.º 3
0
    def stoch_simulate(self, amounts, t=20):
        """
        Stochastic discrete simulation of the CRN until time `t` with initial
        molecule count `amounts`. The species that are omitted from the
        dictionary of initial concentrations are assumed to have an initial
        count of 0. The simulation runs until time `t` unless the
        propensities all reach zero. If that's the case, the system has
        reached a steady state, and the simulation stops.

        args:
            amount: Dict[Species, int]
                A map describing each species' initial count.
            t: Union[float, int]
                The upper bound of the time to run the simulation to.
        """

        # Write psc file
        pscfile = utils.datadir(f"{self.name}.psc")
        self.write_pscfile(pscfile, amounts)

        # invoke stochpy
        smod = stochpy.SSA()
        smod.Model(pscfile)
        smod.DoStochSim(mode="time", end=t)

        # return data
        data = {}
        for sp in self.species:
            if sp.name != "nothing":
                data[sp] = smod.data_stochsim.getSimData(sp.name)[:, 1]
                if "time" not in data:
                    data["time"] = smod.data_stochsim.getSimData(sp.name)[:, 0]

        return Simulation(data, stochastic=True)
Exemplo n.º 4
0
    def DoExample5(self):
        """ Protein turnover example with and without cell division (available at http://stochpy.sourceforge.net/examples.html) """
        smod = _stochpy_.SSA(model_file='CellDivision.psc',
                             dir=_stochpy_.model_dir
                             )  # start SSA module with CellDivision model
        ### do protein synthesis without cell division ###
        smod.DoStochSim(end=10, mode='time')
        smod.PlotSpeciesTimeSeries(species2plot='Protein')
        smod.DoStochSim(end=300, mode='time')
        smod.PlotSpeciesDistributions(species2plot='Protein')

        ### do protein synthesis with cell division ###
        n_generations = 10
        cell_division_times = abs(
            np.random.gamma(scale=0.1, shape=3, size=n_generations)
        )  # cell division times with a gamma distribution
        smod.DoStochSim(end=cell_division_times[0],
                        mode='time',
                        trajectories=1)
        smod = doSequentialSim(smod, n_generations, cell_division_times)
        smod.PlotSpeciesTimeSeries(species2plot='Protein')
        n_generations = 500
        cell_division_times = abs(
            np.random.gamma(scale=0.1, shape=3, size=n_generations)
        )  # cell division times with a gamma distribution
        smod.DoStochSim(end=cell_division_times[0],
                        mode='time',
                        trajectories=1)
        smod = doSequentialSim(smod, n_generations, cell_division_times)
        smod.PlotSpeciesDistributions(species2plot='Protein')
Exemplo n.º 5
0
def get_sim(filename, filedir=None, outdir=None, argDict=dict(), paramDict=dict(), interval=0.5,
            suffix='_TS_data.txt'):
    smod = stochpy.SSA()
    smod.Model(filename, filedir)
    if paramDict:

        for param in paramDict:
            smod.ChangeParameter(param, paramDict[param])
            val = paramDict[param]
            if val != 0:
                exp = int(np.log10(val))
                new_val = int(val * 1.0 / 10**exp)
                suffix += '_' + param + '_' + str(new_val) + 'e' + str(exp)
            else:
                suffix += '_' + param + '_' + str(val) + 'e0'
        suffix += '.txt'

    smod.DoStochSim(**argDict)

    smod.Export2File(analysis='timeseries', datatype='species', directory=outdir)

    import csv
    with open(outdir + filename + '_species_timeseries1.txt', 'rU') as csvfile:
        csvfile.readline()
        reader = csv.DictReader(csvfile, delimiter='\t')
        dictToVector = collections.OrderedDict()
        for field in reader.fieldnames:
            dictToVector[field] = []
        for row in reader:
            for field in dictToVector:
                dictToVector[field].append(eval(row[field]))

    for field in dictToVector:
        dictToVector[field] = np.array(dictToVector[field])
    #print "dictToVector is ", dictToVector


    max_time = max(dictToVector['Time'])

    times = np.arange(0, max_time, interval)
    # indices = [min([x for x in range(len(dictToVector['Time'])) if dictToVector['Time'][x] > t])
    #            for t in times]
    indices = [np.nonzero(dictToVector['Time'] > t)[0][0] for t in times]
    #print "Indices are ", indices[0:10]

    newdictToVector = collections.OrderedDict()

    for key in dictToVector:
        newdictToVector[key] = dictToVector[key][np.ix_(indices)]


    out_file = outdir + filename + suffix
    with open(out_file, 'w') as csvfile:
        writer = csv.writer(csvfile, delimiter='\t')
        writer.writerow([key for key in newdictToVector])
        for i in range(len(indices)):
            writer.writerow([newdictToVector[key][i] for key in newdictToVector])
    print "Data written to ", out_file

    return smod, newdictToVector, times
Exemplo n.º 6
0
    def __init__(
        self,
        n_init_settings,
        n_trajs,
        obs_state_bounds,
        param_space_bounds,
        model_name,
        time_step,
        T,
        obs_state_dim,
        non_obs_state_dim,
    ):

        self.n_init_settings = n_init_settings
        self.n_trajs = n_trajs
        self.n_training_points = n_init_settings * n_trajs
        self.obs_state_bounds = obs_state_bounds
        self.obs_state_dim = obs_state_dim
        self.non_obs_state_dim = non_obs_state_dim
        self.global_state_space_dim = obs_state_dim + non_obs_state_dim
        self.stoch_mod = stochpy.SSA(IsInteractive=False)
        self.stoch_mod.Model(model_name + '.psc')
        self.directory_name = model_name
        self.time_step = time_step
        self.T = T  # end time
        self.param_space_bounds = param_space_bounds
        self.param_space_dim = param_space_bounds.shape[0]
Exemplo n.º 7
0
 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
Exemplo n.º 8
0
def Baseline(iteration):
    model = stochpy.SSA()
    model.Model(model_file='MRSA_Colonization.psc', dir=workingdir)
    model.Endtime(end_time)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    Incident = outcomes[4][0][-1]
    acquisitions[iteration, 0] = Incident
Exemplo n.º 9
0
def Run(filename,k):
    model = stochpy.SSA()
    model.Model(model_file=filename, dir=workingdir)
    model.Endtime(end_time)
    model.ChangeParameter('psi',k)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    acquisitions = outcomes[4][0][-1]
    return acquisitions
Exemplo n.º 10
0
def Football(beta_draw):
    model = stochpy.SSA()
    model.Model(model_file='football_beta_sweep.psc', dir=workingdir)
    model.Endtime(end_time)
    model.ChangeParameter('betaF', beta_draw)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    cases = outcomes[2][0][-1]
    return cases
Exemplo n.º 11
0
def Efficient(iteration):
    model = stochpy.SSA()
    model.Model(model_file='MRSA_Colonization.psc', dir=workingdir)
    model.ChangeParameter('tau', (2.389 * 0.823))
    model.Endtime(end_time)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    Incident = outcomes[4][0][-1]
    acquisitions[iteration, 2] = Incident
def FirstIt(iteration):
    model = stochpy.SSA()
    model.Model(model_file="2dr3nurseratiov2.psc",
                dir='C:/Users/ssjoh/Documents/Lofgren/Iterations')
    model.Endtime(end_time)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    Incident = outcomes[16][0][-1]
    acquisitions[iteration, 1] = Incident
Exemplo n.º 13
0
def RedHH(iteration):
    model = stochpy.SSA()
    model.Model(model_file='MRSA_Colonization.psc', dir=workingdir)
    model.ChangeParameter('rho', (4.154 * 0.823))
    model.ChangeParameter('iota', (6.520))
    model.Endtime(end_time)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    Incident = outcomes[4][0][-1]
    acquisitions[iteration, 3] = Incident
Exemplo n.º 14
0
    def fitness(self,verbose=True):
        time = 100
        if not self.cached_fitness is None:
            return self.cached_fitness

#        with open ("template.psc") as f:
#            template = f.read()
#            model = template % tuple(self.genotype)
#            replace = {
#                'alpha': Chromosome.mrna_cost,
#                'beta': Chromosome.protein_cost,
#                'gamma': Chromosome.sugar_benefit,
#                'delta': Chromosome.enzyme_mrna_cost,
#                'zeta': Chromosome.enzyme_cost
#                }
#            for k, v in replace.iteritems():
#                model.replace (k, str(v))
#            filename = "model%s.psc" % self.serial_no
#            with open (filename, 'w') as f:
#                f.write (model)

        with open("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 = "model%s.psc" % self.serial_no
            with open(filename,'w') as f:
                f.write(model)
       
        while self.cached_fitness == None:
            try:
                mod = stochpy.SSA(Method="Direct", File=filename,dir='.')
                mod.DoStochSim(epsilon=.01,mode="time",end=time)   
                atp_gained_label = mod.data_stochsim.species_labels.index('ATP_gained')
                atp_spent_label = mod.data_stochsim.species_labels.index('ATP_spent')
                self.cached_fitness = mod.data_stochsim.species[-1][atp_gained_label] - mod.data_stochsim.species[-1][atp_spent_label]
            except AssertionError:
                continue

        mod.PlotTimeSim(species2plot=["ATP_gained",'ATP_spent'])
        #mod2 = Parser(filename)
        #atp_label2 = getATP(stochsimm(mod2.parse()))
        #self.cached_fitness2 = atp_label2[-1]
        #mod3 = pysces.model(filename,dir='.')
        #mod3.doSim(end = 1200 , points = 1000)
        #mod3.SimPlot(plot=["ATP",'S'])
        #self.cached_fitness3 = mod3.data_sim.getSimData("ATP")[-1][1]
        if verbose:
            print self.cached_fitness
        return self.cached_fitness
Exemplo n.º 15
0
def Reduced(iteration):
    model = stochpy.SSA()
    model.Model(model_file='MRSA_Colonization.psc', dir=workingdir)
    percentchange = random.uniform(0.50, 1)
    model.ChangeParameter('rho', (4.154 * percentchange))
    model.Endtime(end_time)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    Incident = outcomes[4][0][-1]
    acquisitions[iteration, 0] = (1 - percentchange) * 100
    acquisitions[iteration, 1] = Incident
Exemplo n.º 16
0
def StochProcess3():
    #This uses the stochpy module
    smod = stochpy.SSA()  #Instance of a Stochastic Simulation Algorithm
    smod.DoStochSim(IsTrackPropensities=True)
    smod.PlotSpeciesTimeSeries()
    smod.PlotPropensitiesTimeSeries()
    #Somemore functions
    smod.DoStochSim(end=10**5)
    smod.GetSpeciesAutocorrelations()
    smod.PlotSpeciesAutocorrelations(nlags=25)
    smod.GetWaitingtimes()
    smod.PlotWaitingtimesDistributions()
    stochpy.plt.xlim([10**-4, 10**0])
Exemplo n.º 17
0
def LowBetaHighPrevHighMix(iteration, scen):
    model = stochpy.SSA()
    model.Model(model_file='football_highmix_highprev.psc', dir=workingdir)
    model.Endtime(end_time)
    model.ChangeParameter('beta', 0.25)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    cases = outcomes[2][0][-1]
    symptom = outcomes[4][0][-1]
    results[iteration + (n_runs * scen), 0] = 5
    results[iteration + (n_runs * scen), 1] = cases
    results[iteration + (n_runs * scen), 2] = symptom
Exemplo n.º 18
0
def HighControl(iteration, scen):
    model = stochpy.SSA()
    model.Model(model_file='no_football.psc', dir=workingdir)
    model.Endtime(end_time)
    model.ChangeParameter('beta', 0.30)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    cases = outcomes[2][0][-1]
    symptom = outcomes[4][0][-1]
    results[iteration + (n_runs * scen), 0] = 1
    results[iteration + (n_runs * scen), 1] = cases
    results[iteration + (n_runs * scen), 2] = symptom
Exemplo n.º 19
0
    def __init__(self, n_init_states, n_trajs, state_space_bounds, model_name,
                 time_step, T):

        self.n_init_states = n_init_states
        self.n_trajs = n_trajs
        self.n_training_points = n_init_states * n_trajs
        self.state_space_bounds = state_space_bounds
        self.state_space_dim = state_space_bounds.shape[0]
        self.stoch_mod = stochpy.SSA(IsInteractive=False)
        self.stoch_mod.Model(model_name + '.psc')
        self.directory_name = model_name
        self.time_step = time_step
        self.T = T  # end time
        self.conc_flag = False
def Football(pdict):
    model = stochpy.SSA()
    model.Model(model_file='football_highmix_highprev.psc', dir=workingdir)
    model.Endtime(end_time)
    model.ChangeParameter('beta', 0.25)
    model.ChangeParameter('sigma', pdict['sigma'] * 0.5)
    model.ChangeParameter('gamma', pdict['gamma'] * 0.1960784)
    model.ChangeParameter('alpha', pdict['alpha'] * 0.80)
    model.ChangeParameter('delta_I', pdict['delta_I'] * 0.20)
    model.ChangeParameter('delta_A', pdict['delta_A'] * 0.20)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    cases = outcomes[2][0][-1]
    return cases
Exemplo n.º 21
0
 def __init__(self, n_init_states, n_trajs, state_space_bounds, model_name,
              time_step, T):
     # state_space_bounds : shape = (state_space_dim,2)
     # param_space_bounds : shape = (param_space_dim,2)
     self.n_init_states = n_init_states
     self.n_trajs = n_trajs
     self.n_training_points = n_init_states * n_trajs
     self.state_space_bounds = state_space_bounds
     self.state_space_dim = state_space_bounds.shape[0]
     self.stoch_mod = stochpy.SSA(IsInteractive=False)
     self.stoch_mod.Model(model_name + '.psc')
     self.directory_name = model_name
     self.time_step = time_step
     self.T = T  # end time
     self.N = None  # population size
def simulate(mu, initmRNA):
    smod = stochpy.SSA()
    smod.Model('Transc-Transl.psc')

    smod.ChangeInitialSpeciesCopyNumber("S1", initmRNA)
    traj = max(10, int(round(1e6 * (poisson(mu, initmRNA)))))
    print "Simulating " + str(traj) + " trajectories"
    smod.DoStochSim(end=5, mode='time', trajectories=traj)

    smod.GetRegularGrid()

    fp = open("poisssim" + str(mu) + "_" + str(initmRNA) + ".pkl", "wb")
    pickle.dump(smod.data_stochsim_grid, fp)
    fp.close()
    del smod
    return
Exemplo n.º 23
0
def benchmark(fdir, method, tfinal, nsaves, nreal, seed, n_sample):
    # initialize
    smod = stochpy.SSA()
    times = []

    smod.Model(model_file='stochpy.psc', dir=fdir)

    random.seed(seed)

    for i in range(n_sample):
        print(f"sample {i+1} / {n_sample}")
        smod.DoStochSim(trajectories=nreal,
                        end=tfinal,
                        method=method,
                        mode="time")
        times.append(smod.simulation_time)

    return times
def Efficient(iteration):
    model = stochpy.SSA()
    model.Model(model_file='MRSA_Colonization.psc', dir=workingdir)
    model.ChangeParameter('rho',random.uniform(3.3232,4.9848))
    model.ChangeParameter('sigma',random.uniform(0.0432,0.0648))
    model.ChangeParameter('psi',random.uniform(0.0745144,0.1117716))
    model.ChangeParameter('theta',random.uniform(0.007592,0.011388))
    colonized_admits = random.uniform(0.06232,0.09348)
    model.ChangeParameter('nu_C',colonized_admits)
    model.ChangeParameter('nu_U',1-colonized_admits)
    model.ChangeParameter('iota',random.uniform(4.592,6.888))
    model.ChangeParameter('tau',random.uniform(1.572918,2.359376))
    model.Endtime(end_time)
    model.DoStochSim()
    model.GetRegularGrid(n_samples=end_time)
    outcomes = model.data_stochsim_grid.species
    Incident = outcomes[4][0][-1]
    acquisitions[iteration,2] = Incident
Exemplo n.º 25
0
def Baserun(iterations):
    for k in range(0, iterations):
        pdict = {
            'epsilon1': random.uniform(0.015, 0.417),
            'epsilon2': random.uniform(0.1, 96)
        }
        model = stochpy.SSA()
        model.Model(model_file='protective_decol.psc', dir=workingdir)
        model.ChangeParameter('epsilon1', pdict['epsilon1'])
        model.Endtime(end_time)
        model.ChangeParameter('epsilon2', 1 / pdict['epsilon2'])
        model.DoStochSim()
        model.GetRegularGrid(n_samples=end_time)
        outcomes = model.data_stochsim_grid.species
        cases[k, 0] = outcomes[16][0][-1]
        cases[k, 1] = outcomes[34][0][-1]
        cases[k, 2] = outcomes[40][0][-1]
        cases[k, 3] = pdict['epsilon1']
        cases[k, 4] = pdict['epsilon2']
    return cases
Exemplo n.º 26
0
def Baserun(iterations):
    for k in range(0, iterations):
        #pdict = {'epsilon1':random.uniform(0.01,0.39),
        #'epsilon2':random.uniform(0.1,48)
        #}
        model = stochpy.SSA()
        model.Model(model_file='protective_decolV04.psc', dir=workingdir)
        model.Endtime(end_time)
        #model.ChangeParameter('epsilon1',pdict['epsilon1'])
        #model.ChangeParameter('epsilon2',1/pdict['epsilon2'])
        model.DoStochSim()
        model.GetRegularGrid(n_samples)
        outcomes = model.data_stochsim_grid.species
        cases[k, 0] = outcomes[16][0][-1]
        cases[k, 1] = outcomes[17][0][-1]
        cases[k, 2] = outcomes[28][0][-1]
        cases[k, 3] = outcomes[36][0][-1]
        cases[k, 4] = outcomes[42][0][-1]
        for t in range(0, n_samples):
            acq_traj[t, k] = outcomes[16][0][t]
        #con_traj[t,k]=outcomes[16][0][t]+outcomes[19][0][t]+outcomes[21][0][t]+outcomes[23][0][t]+outcomes[25][0][t]+outcomes[27][0][t]+outcomes[35][0][t]+outcomes[37][0][t]+outcomes[38][0][t]+outcomes[39][0][t]+outcomes[40][0][t]+outcomes[41][0][t]
    return cases
Exemplo n.º 27
0
def get_sim(filename,
            filedir=None,
            outdir=None,
            argDict=dict(),
            paramDict=dict(),
            interval=0.5,
            suffix='_TS_data.txt'):
    """


    :param filename: name of .psc file (specifying diff eq's, values)
    :param filedir: directory of .psc file
    :param outdir: directory of output file

    :param argDict: dict containing keyword args for the smod.Model() call
    :param paramDict: dict containing parameter values. This can be empty;
        otherwise the default values are used
    :param interval: interval to keep in our array. For example, if the simulation
    produces a value for each second (which we can't control), setting interval to 5
    will result in a vector spaced at 5 seconds.
    :param suffix: any suffix to append
    :return: smod, newdictToVector, times

    smod: the original stochpy simulation model
    newdictToVector: a dictionary of form:
        "A" -> vector of "A"'s values
        "time" -> vector of time
    times: the timepoints of our simulation
    """
    smod = stochpy.SSA()
    smod.Model(filename, filedir)
    if paramDict:

        # suffix will note the parameters that were set
        for param in paramDict:
            smod.ChangeParameter(param, paramDict[param])
            val = paramDict[param]
            if val != 0:
                exp = int(np.log10(val))
                new_val = int(val * 1.0 / 10**exp)
                suffix += '_' + param + '_' + str(new_val) + 'e' + str(exp)
            else:
                suffix += '_' + param + '_' + str(val) + 'e0'
        suffix += '.txt'

    smod.DoStochSim(**argDict)

    # species was simulated
    smod.Export2File(analysis='timeseries',
                     datatype='species',
                     directory=outdir)

    # now load it into dictionary vector
    import csv
    with open(os.path.join(outdir, filename + '_species_timeseries1.txt'),
              'rU') as csvfile:
        csvfile.readline()
        reader = csv.DictReader(csvfile, delimiter='\t')
        dictToVector = collections.OrderedDict()
        for field in reader.fieldnames:
            dictToVector[field] = []
        for row in reader:
            for field in dictToVector:
                dictToVector[field].append(eval(row[field]))

    for field in dictToVector:
        dictToVector[field] = np.array(dictToVector[field])

    max_time = max(dictToVector['Time'])

    # get the spaced intervals we want
    times = np.arange(0, max_time, interval)
    indices = [np.nonzero(dictToVector['Time'] > t)[0][0] for t in times]

    newdictToVector = collections.OrderedDict()
    for key in dictToVector:
        newdictToVector[key] = dictToVector[key][np.ix_(indices)]

    # Save
    out_file = os.path.join(outdir, filename + suffix)
    with open(out_file, 'w') as csvfile:
        writer = csv.writer(csvfile, delimiter='\t')
        writer.writerow([key for key in newdictToVector])
        for i in range(len(indices)):
            writer.writerow(
                [newdictToVector[key][i] for key in newdictToVector])
    print "Data written to ", out_file

    return smod, newdictToVector, times
Exemplo n.º 28
0
import stochpy
from scipy import *
from numpy import *
import matplotlib.pyplot as plt

smod = stochpy.SSA(model_file='ge.psc', dir='data')
smod.DoStochSim(end=1.0e3, mode='time')
smod.PlotSpeciesTimeSeries()
stochpy.plt.title("Your own title")
stochpy.plt.show()
#stochpy.plt.savefig("stochpy_plot.pdf")
S = smod.data_stochsim
t = reshape(S.time, len(S.time))

#print(S.species[:,0])

#plt.plot(t, S.species[:,1], label='1')
#plt.legend()
#plt.xlabel('Time (hours)')
#plt.ylabel('Species')
##plt.yscale('log')
#plt.axis([-5,250,1.0e-4,1.0e10])
#plt.tick_params( axis='both',labelsize=12)
#plt.show()
import stochpy
from scipy import *
from numpy import *
import matplotlib.pyplot as plt

smod = stochpy.SSA(model_file='bact_phage_model.psc', dir='data')
smod.DoStochSim(end=13.0, mode='time')
smod.PlotSpeciesTimeSeries()
stochpy.plt.yscale('log')

#S = smod.data_stochsim
#t= reshape(S.time, len(S.time))
#print(S.species[:,0])

#plt.plot(t, S.species[:,1], label='1')
#plt.legend()
#plt.xlabel('Time (hours)')
#plt.ylabel('Species')
##plt.yscale('log')
#plt.axis([-5,250,1.0e-4,1.0e10])
#plt.tick_params( axis='both',labelsize=12)
#plt.show()
Exemplo n.º 30
0
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