def test_nfsim_different_initials_lengths(self): A = self.model.monomers['A'] B = self.model.monomers['B'] sim = BngSimulator(self.model, tspan=np.linspace(0, 1), initials={B(): [150, 250, 350]}) sim.run(initials={A(): [275, 375]})
def test_nfsim(): model = robertson.model # Reset equations from any previous network generation model.reset_equations() sim = BngSimulator(model, tspan=np.linspace(0, 1)) x = sim.run(n_runs=1, method='nf', seed=_BNG_SEED) observables = np.array(x.observables) assert len(observables) == 50 A = model.monomers['A'] x = sim.run(n_runs=2, method='nf', tspan=np.linspace(0, 1), initials={A(): 100}, seed=_BNG_SEED) assert np.allclose(x.dataframe.loc[0, 0.0], [100.0, 0.0, 0.0])
def test_stop_if(): Model() Monomer('A') Rule('A_synth', None >> A(), Parameter('k', 1)) Observable('Atot', A()) Expression('exp_const', k + 1) Expression('exp_dyn', Atot + 1) sim = BngSimulator(model, verbose=5) tspan = np.linspace(0, 100, 101) x = sim.run(tspan, stop_if='Atot>9', seed=_BNG_SEED) # All except the last Atot value should be <=9 assert all(x.observables['Atot'][:-1] <= 9) assert x.observables['Atot'][-1] > 9 # Starting with Atot > 9 should terminate simulation immediately y = sim.run(tspan, initials=x.species[-1], stop_if='Atot>9') assert len(y.observables) == 1
def test_bng_ode_with_expressions(): model = expression_observables.model model.reset_equations() sim = BngSimulator(model, tspan=np.linspace(0, 1)) x = sim.run(n_runs=1, method='ode') assert len(x.expressions) == 50 assert len(x.observables) == 50
def seg_model(num_cells, k_death, k_division, n_sims): dip_dist = [] dip_dist1 = [] Model() Monomer("Cell") Parameter('CellInit', num_cells) Initial(Cell(), CellInit) Observable("Obs_Cell", Cell()) Parameter("k_div", k_division) Parameter("k_dth", k_death) Rule("Cell_Div", Cell() >> Cell() + Cell(), k_div) Rule("Cell_Death", Cell() >> None, k_dth) t1 = np.linspace(0, 168, 169) # 7 days sim = BngSimulator(model, tspan=t1, verbose=False) # , seed = 1095205711) x1 = sim.run(n_runs=n_sims, verbose=False) # returns np.array with species and obs plt.figure() for sim in range(n_sims): plt.plot(x1.tout[sim], (np.log2(x1.all[sim]["Obs_Cell"]/x1.all[sim]["Obs_Cell"][0])), '0.5', lw=2, label = "Simulated Data" if sim == 0 else "") plt.plot(x1.tout[sim][80:], (np.log2(x1.all[sim]["Obs_Cell"][80:] / x1.all[sim]["Obs_Cell"][0])), 'r', lw=2, label="Simulated Data" if sim == 0 else "") print(x1.tout[1][80:]) slope, intercept, r_value, p_value, std_err = sp.stats.linregress(x1.tout[sim][80:], np.log2( x1.all[sim]["Obs_Cell"][80:]/x1.all[sim]["Obs_Cell"][0])) if math.isnan(slope) == False: dip_dist = dip_dist + [slope] plt.plot(x1.tout[sim], intercept + slope * x1.tout[sim], 'k', label = "Fitted Lines" if sim == 0 else "", lw = 2) slope, intercept, r_value, p_value, std_err = sp.stats.linregress(x1.tout[sim], np.log2( x1.all[sim]["Obs_Cell"] / x1.all[sim]["Obs_Cell"][0])) if math.isnan(slope) == False: dip_dist1 = dip_dist1 + [slope] plt.plot(x1.tout[sim], intercept + slope * x1.tout[sim], 'k', label="Fitted Lines" if sim == 0 else "", lw=2) plt.legend(loc = "upper left") plt.xlabel("Time (hours)", weight = "bold") plt.ylabel("log2(cell count)", weight = "bold") plt.title("Model Trajectories", weight = "bold") plt.figure() sns.distplot(dip_dist, hist = False, color = "k", kde_kws={"shade": True}) sns.distplot(dip_dist1, hist = False, color = "r", kde_kws={"shade": True}) plt.axvline(x=(k_division-k_death)/np.log(2), color = 'k', ls = '--', lw = 3) plt.xlabel("DIP Rate", weight = "bold") plt.ylabel("Density", weight = "bold") plt.title("DIP Rate Distribution - 100 cells", weight = "bold")
def test_hpp(): model = robertson.model # Reset equations from any previous network generation model.reset_equations() A = robertson.model.monomers['A'] klump = Parameter('klump', 10000, _export=False) model.add_component(klump) population_maps = [PopulationMap(A(), klump)] sim = BngSimulator(model, tspan=np.linspace(0, 1)) x = sim.run(n_runs=1, method='nf', population_maps=population_maps, seed=_BNG_SEED) observables = np.array(x.observables) assert len(observables) == 50
def test_hpp(): model = robertson.model # Reset equations from any previous network generation model.reset_equations() A = robertson.model.monomers['A'] klump = Parameter('klump', 10000, _export=False) model.add_component(klump) population_maps = [ PopulationMap(A(), klump) ] sim = BngSimulator(model, tspan=np.linspace(0, 1)) x = sim.run(n_runs=1, method='nf', population_maps=population_maps, seed=_BNG_SEED) observables = np.array(x.observables) assert len(observables) == 50
def run_LSDspikeIn_model(n_wells, n_cell_types, percent, n_cells): low_dips = -0.04 high_dips = 0.02 dips = np.linspace(low_dips, high_dips, n_cell_types) dip_mean = -0.01 dip_var = 0.01 # print("DIP RATES") # print(dips) # print("Death rates") # print(-dips+(0.03*np.log(2))) # Discretize normal distribution of dip rates - used in post drug simulation normal = sp.norm.pdf(dips, dip_mean, dip_var) sum = 0 for i in range(1, n_cell_types): sum += normal[i] * (dips[i] - dips[i - 1]) normal_hist = normal * (dips[1] - dips[0]) Model() [Monomer("Cell", ['dip'], {'dip': ["%d" %i for i in range(n_cell_types)]})] Monomer("Cell_resistant") # print(model.monomers) Parameter('cellInit_0', 0) # list(choice).count(1)) [Parameter('cellInit_%d' %i)for i in range(1,n_cell_types)] Parameter('Cell_resistant_0', 0) # list(choice).count(0)) # print(model.parameters) Initial(Cell(dip = "0"), cellInit_0) # could not be a string - parameter only - didn't know how to set up [Initial(Cell(dip = "%d" %i), model.parameters["cellInit_%d" %i]) for i in range(1,n_cell_types)] Initial(Cell_resistant, Cell_resistant_0) # print(model.initial_conditions) [Observable("Obs_Cell%d" %i, Cell(dip = "%d" %i)) for i in range(n_cell_types)] Observable("Obs_All", Cell()) Observable("Obs_Cell_resistant", Cell_resistant()) # print(model.observables) # print(dips) k_div = 0.04 * np.log(2) [Parameter("k_div_%d" % i, k_div) for i in range(len(dips))] k_death = k_div - (dips*np.log(2)) [Parameter("k_death_%d" % i, k) for i,k in enumerate(k_death)] Parameter('k_div_resistant', 0.04 * np.log(2)) Parameter('k_death_resistant', 0.005 * np.log(2)) # print(model.parameters) [Rule("Cell%d_Div" %i, Cell(dip = "%d" %i) >> Cell(dip = "%d" %i) + Cell(dip = "%d" %i), model.parameters["k_div_%d" %i]) for i in range(len(dips))] [Rule("Cell%d_Death" %i, Cell(dip = "%d" %i) >> None, model.parameters["k_death_%d" %i]) for i in range(len(k_death))] Rule('Cell_resistant_Div', Cell_resistant() >> Cell_resistant() + Cell_resistant(), k_div_resistant) Rule('Cell_resistant_Death', Cell_resistant() >> None, k_death_resistant) # print(model.rules) # quit() distr_normal = [] distr_resistant = [] count = 0 # preDrug_cellNormal = [] # preDrug_cellResistant = [] for exp in range(n_wells): #cFP # num_cells = 1 #LSD num_cells = np.random.poisson(n_cells) # the 2 provides two choices (0 and 1), which correspond to two populations choice = np.random.choice(2, num_cells, p=[percent, 1-percent]) # print(choice) if num_cells != 0: normal_init = list(choice).count(1) resistant_init = list(choice).count(0) cellInit_0.value = normal_init Cell_resistant_0.value = resistant_init # print(cellInit_0) # print(Cell_resistant_0) t1 = np.linspace(0,168,169) # 7 days sim = BngSimulator(model, tspan=t1, verbose=False)#, seed = 1095205711) # Why do the n_cells = 0 start off with 1? x1 = sim.run(n_runs = 1, param_values={"k_death_0": 0.005 * np.log(2)}, verbose = False) # returns np.array with species and obs # all_cells = np.array(x1.observables) # cell_tot = all_cells["Obs_All"].T[-1] # print(np.array(x1.all).shape) # quit() # print(x1.all) # print(type(x1.all)) # The total well subpopulation count before drug addition cell_tot = x1.observables["Obs_Cell0"][-1] cell_tot_resistant = x1.observables["Obs_Cell_resistant"][-1] # preDrug_cellNormal.append(cell_tot) # preDrug_cellResistant.append(cell_tot_resistant) # For when n_wells > 1 # cell_tot = [x[-1]["Obs_Cell0"] for x in x1.all] # cell_tot_resistant = [x[-1]["Obs_Cell_resistant"] for x in x1.all] # print(cell_tot) # print(cell_tot_resistant) # print("Sim 1 Finished.") cell_pop = np.random.multinomial(int(round(cell_tot)), normal_hist) # *100 for true normal # print(cell_pop) t2 = np.linspace(0, 144, 145) # 6 days in drug x2 = sim.run(tspan=t2, param_values={"k_death_0": model.parameters['k_death_0'].value, "Cell_resistant_0": cell_tot_resistant}, n_sim=1, initials={model.species[i]: pop for i, pop in enumerate(cell_pop)}, verbose=False) # print(cell_tot_resistant) if np.sum(cell_pop) != 0: slope, intercept, r_value, p_value, std_err = sp.stats.linregress(t2, np.log2( x2.observables["Obs_All"] / x2.observables["Obs_All"][0])) if math.isnan(slope) == False: distr_normal = distr_normal + [slope] # print "Normal", slope if cell_tot_resistant != 0: slope, intercept, r_value, p_value, std_err = sp.stats.linregress(t2, np.log2( x2.observables["Obs_Cell_resistant"] / x2.observables["Obs_Cell_resistant"][0])) if math.isnan(slope) == False: distr_resistant = distr_resistant + [slope] # print "Resistant", slope # plt.figure() # plt.plot(t1, np.log2(x1.observables["Obs_Cell0"]), 'g', lw=2) # plt.plot(t1, np.log2(x1.observables["Obs_Cell_resistant"]), 'r', lw=2) # plt.plot(t1[-1] + x2.tout[0], np.log2(x2.observables["Obs_All"]), 'g', lw = 2) # plt.plot(t1[-1] + x2.tout[0], np.log2(x2.observables["Obs_Cell_resistant"]), 'r', lw = 2) # plt.axvline(x=168, linewidth=4, color='k') # plt.xlabel("Time (hours)", weight = "bold") # plt.ylabel("log2(cell count)", weight = "bold") # plt.title("LSD %d Resistant Spike-In: Well %d" % (percent*100, exp), weight = "bold") count = count + 1 print("Well") print(count) print(distr_normal) print(distr_resistant) plt.figure() bins = np.linspace(-0.04, 0.06, 101) # bins = np.histogram(np.hstack((distr_resistant, distr_normal)), bins=100)[1] if len(distr_normal) >= 2: sns.distplot(distr_normal, bins, kde=False, color="g", kde_kws={"shade": True}, label = "Parental") # elif len(distr_normal) == 1: # rs = np.random.RandomState(0) # num_elements = len(distr_normal) # x = rs.normal(10, 1, num_elements) # sns.distplot(np.r_[x,x], bins, kde=False, color="g", kde_kws={"shade": True}, label="Parental") if len(distr_resistant) >= 2: sns.distplot(distr_resistant, bins, kde=False, color="r", kde_kws={"shade": True}, label = "Resistant") else: pass # elif len(distr_resistant) == 1: # rs1 = np.random.RandomState(0) # num_elements1 = len(distr_resistant) # x1 = rs1.normal(10, 1, num_elements1) # sns.distplot(np.r_[x1,x1], bins, kde=False, color="r", kde_kws={"shade": True},label="Resistant") plt.axvline(x=(k_div-((k_death_4.value+k_death_5.value)/2))/np.log(2), color = 'g', ls = '--', lw = 3, label = "Parental DIP Mean") plt.axvline(x=(k_div_resistant.value-k_death_resistant.value)/np.log(2), color = 'r', ls = '--', lw = 3, label = "Resistant DIP Mean") plt.axvline(x=0, color = 'k', ls = '--', lw = 3) # bins = np.histogram(np.hstack((distr_resistant, distr_normal)), bins=100)[1] plt.xlabel("DIP Rate", weight="bold") plt.ylabel("Frequency", weight = "bold") plt.xlim(-0.04, 0.06) plt.ylim(0,400) # plt.ylim(0,100*(n_wells/384)) plt.title("LSD DIP Distribution %.4f%% Resistant Spike-In (%d Cells, %d Wells) " % (percent*100, n_cells, n_wells), weight = "bold") plt.legend(loc="upper left") np.save("LSDspikein_normalDIPs_%.6fresistant_%dcells_%dwells.npy" % (percent, n_cells, n_wells), distr_normal) np.save("LSDspikein_resistantDIPs_%.6fresistant_%dcells_%dwells.npy" % (percent, n_cells, n_wells), distr_resistant) plt.savefig("LSDspikein_DIPdistr_%.6fresistant_%dcells_%dwells.pdf" % (percent, n_cells, n_wells))
def run_barcoding_model(n_exp, n_barcodes, n_cell_types, percent): all_post_drug_counts = [] ### SKMEL5 SC01 DIP Rate Distribution low_dips = -0.062 high_dips = -0.002 dips = np.linspace(low_dips, high_dips, n_cell_types) dip_mean = -0.033 dip_var = 0.01 # Discretize normal distribution of dip rates - used in post drug simulation normal = sp.norm.pdf(dips, dip_mean, dip_var) print(normal) sum = 0 for i in range(1, n_cell_types): sum += normal[i] * (dips[i] - dips[i - 1]) print(sum) normal_hist = normal * (dips[1] - dips[0]) print(normal_hist) print(dips) Model() [Monomer("Cell", ['dip'], {'dip': ["%d" %i for i in range(n_cell_types)]})] Monomer("Cell_resistant") print(model.monomers) # Monomer("Cell", ['dip'], {"dip": ["0","1"]}) Parameter('cellInit_0', 1) [Parameter('cellInit_%d' %i)for i in range(1,n_cell_types)] # Resistant initial parameter will be overwritten later Parameter('Cell_resistant_0', 0) # list(choice).count(0)) # Parameter('Cell_1init') print(model.parameters) Initial(Cell(dip = "0"), cellInit_0) # could not be a string - parameter only - didn't know how to set up [Initial(Cell(dip = "%d" %i), model.parameters["cellInit_%d" %i]) for i in range(1,n_cell_types)] Initial(Cell_resistant, Cell_resistant_0) # for ic in model.initial_conditions: # print ic print(model.initial_conditions) [Observable("Obs_Cell%d" %i, Cell(dip = "%d" %i)) for i in range(n_cell_types)] Observable("Obs_All", Cell()) Observable("Obs_Cell_resistant", Cell_resistant()) print(model.observables) print(dips) k_div = 0.04 * np.log(2) [Parameter("k_div_%d" % i, k_div) for i in range(len(dips))] k_death = k_div - (dips*np.log(2)) [Parameter("k_death_%d" % i, k) for i,k in enumerate(k_death)] Parameter('k_div_resistant', 0.04 * np.log(2)) Parameter('k_death_resistant', 0.005 * np.log(2)) [Rule("Cell%d_Div" %i, Cell(dip = "%d" %i) >> Cell(dip = "%d" %i) + Cell(dip = "%d" %i), model.parameters["k_div_%d" %i]) for i in range(len(dips))] [Rule("Cell%d_Death" %i, Cell(dip = "%d" %i) >> None, model.parameters["k_death_%d" %i]) for i in range(len(k_death))] Rule('Cell_resistant_Div', Cell_resistant() >> Cell_resistant() + Cell_resistant(), k_div_resistant) Rule('Cell_resistant_Death', Cell_resistant() >> None, k_death_resistant) print(model.rules) for exp in range(n_exp): # Pre-drug run - all have the same DIP rate +/- stochasticity t1 = np.linspace(0,336,337) # 14 days sim = BngSimulator(model, tspan=t1, verbose=False)#, seed = 1095205711) # Why do the n_cells = 0 start off with 1? SOLVED # Use n_runs = n_barcodes x1 = sim.run(n_runs = n_barcodes, param_values={"k_death_0": 0.005}, verbose = False) # returns np.array with species and obs # all_cells = np.array(x1.observables) # cell_tot = all_cells["Obs_All"].T[-1] # print(np.array(x1.all).shape) # quit() # print(x1.all) # print(type(x1.all)) cell_tot = [x[-1]["Obs_Cell0"] for x in x1.all] print(cell_tot) # print(len(cell_tot)) # print(int(round(percent*len(cell_tot)))) # print(list(enumerate(cell_tot))) cell_tot_resistant_list = random.sample(list(enumerate(cell_tot)), int(round(percent*len(cell_tot)))) # cell_tot_resistant = np.random.choice(list(enumerate(cell_tot)), int(round(percent*len(cell_tot)))) resistant_indecies = [] for index,elem in cell_tot_resistant_list: resistant_indecies.append(index) # print(resistant_indecies) # print(cell_tot_resistant[[0]]) cell_tot_resistant = [x for i,x in cell_tot_resistant_list] cell_tot_sensitive = [x for i,x in enumerate(cell_tot) if i not in resistant_indecies] print(cell_tot_resistant) print(cell_tot_sensitive) print("Sim 1 Finished.") post_drug_counts = [] quit() ### Give resistant and sensitive populations their own simulations ## What should I do? # setup different cell_pop(s) for resistant and sensitive ## sensitive - keep same DIP rate distribution ## resistant - either use PySB "resistant" parameters or overwrite in the sim.run call # keep index information for easier plotting - all in same cell_pop for ind, cell in enumerate(cell_tot_sensitive): print("%d:%d" % (exp,ind)) if cell == 0: post_drug_counts.append(0.) else: # rounding and taking integer is safe way to handle number.0 cell_pop = np.random.multinomial(int(round(cell)), normal_hist) # *100 for true normal # print(cell_pop) # Normal Histogram Multinomial Selection of DIP Rates plt.figure("DIP Rate Distribution Barcode #%d" % ind) plt.bar(dips-0.5*(dips[1]-dips[0]), 1.*cell_pop/int(round(cell)), dips[1]-dips[0], label = "n_cells = %d" %int(cell)) # *100 for true normal plt.plot(dips, normal_hist, lw = 2, color = "r") plt.legend(loc = 0) t2 = np.linspace(0,168,169) # 7 days in drug x2 = sim.run(tspan = t2, param_values={"k_death_0": model.parameters['k_death_0'].value}, n_sim=1, initials={model.species[i]:pop for i,pop in enumerate(cell_pop)}, verbose= False) # ,"cellInit_0": 0}, - FIXED THIS PROBLEM post_drug_counts.append(x2.all["Obs_All"][-1]) print(x1.all[ind]["Obs_Cell0"]) plt.figure() plt.plot(x1.tout[ind], np.log2(x1.all[ind]["Obs_Cell0"]), '0.5', lw = 2) a = np.array(x1.observables)["Obs_Cell0"] print(np.array([tr[:] for tr in a])) # quit() # plt.plot(x1.tout, np.array([tr[:] for tr in a]), '0.5') plt.plot(t1[-1] + x2.tout[0], np.log2(x2.observables["Obs_All"]), '0.5', lw = 2) plt.axvline(x = 336, linewidth = 4, color = 'red') plt.axvline(x = 504, linewidth = 4, color = 'blue') plt.xlabel("Time (hours)") plt.ylabel("log2(cell count)") plt.xlim([0,550]) plt.title("Barcoding Model - 100 barcodes, 10 experiments, 15 states") # plt.figure("Experiment #%d Barcode #%d" % (exp,ind)) # plt.plot(t1, x1.all[int(cell)]["Obs_Cell0"],'0.5', lw=4, alpha=0.25) # for i,obs in enumerate(model.observables): # print(x1.all[int(cell)]) # quit() # plt.plot(t1, x1.all[obs.name], lw = 2, label = obs.name, color = colors[i]) # plt.plot(t1, x1.all[obs.name], '0.5', lw=4, alpha=0.25) # plt.plot(t1[-1]+t2, x2.all[obs.name], '0.5', lw = 4, alpha = 0.25) # plt.plot(t1, x1.all[obs.name], lw = 2, label = obs.name, color = colors[i]) # plt.plot(t1[-1]+t2, x2.all[obs.name], lw = 2, label = obs.name) # plt.annotate(s = "n_cells = %d" % cell, xy = (0.1,0.1), xycoords = "axes fraction", fontsize = 24) # plt.text(-0.04, 2800, r'$\mu=%g$' % (np.mean(distr_all))) # plt.legend(loc = 0) print(post_drug_counts) all_post_drug_counts.append(post_drug_counts) print(all_post_drug_counts) # np.save("barcoding_data_%dbar%dexp%dstates.npy" % (b, e, s), all_post_drug_counts) # np.save("barcoding_data_100bar10exp15states_forpres.npy", all_post_drug_counts) plt.show()
# # # # print len(model.rules) # print len(model.initial_conditions) # print len(model.reactions) # print model.species #quit() plt.figure() t = linspace(0, 200, 201) # sims = 5 sim = BngSimulator(model, tspan=t, verbose=False) x1 = sim.run(tspan=t, verbose=False, n_runs=sims, cleanup=False, method='ssa') # tout = x1.tout y1 = np.array(x1.observables) print(y1['Obs_All']) print(y1['Obs_All'].T) print((np.log2(y1['Obs_All'])).T) print((np.log2(y1['Obs_All']).T/np.log2(y1['Obs_All']).T[0])) print(x1.all[-1]["Obs_All"]) plot_mean_min_max('Obs_All', color = 'red') y = odesolve(model = model,tspan = t, verbose = True) plt.plot(t, np.log2(y["Obs_All"]/y["Obs_All"][0]), 'r-', lw=4, label = "100% SC01")
def run_barcoding_model(n_exp, n_barcodes, n_cell_types): all_post_drug_counts = [] low_dips = -0.062 high_dips = -0.002 dips = np.linspace(low_dips, high_dips, n_cell_types) dip_mean = -0.033 dip_var = 0.01 # Discretize normal distribution of dip rates - used in post drug simulation normal = sp.norm.pdf(dips, dip_mean, dip_var) print(normal) sum = 0 for i in range(1, n_cell_types): sum += normal[i] * (dips[i] - dips[i - 1]) print(sum) normal_hist = normal * (dips[1] - dips[0]) print(normal_hist) print(dips) Model() [Monomer("Cell", ['dip'], {'dip': ["%d" %i for i in range(n_cell_types)]})] print(model.monomers) # Monomer("Cell", ['dip'], {"dip": ["0","1"]}) Parameter('cellInit_0', 1) [Parameter('cellInit_%d' %i)for i in range(1,n_cell_types)] # Parameter('Cell_1init') print(model.parameters) Initial(Cell(dip = "0"), cellInit_0) # could not be a string - parameter only - didn't know how to set up [Initial(Cell(dip = "%d" %i), model.parameters["cellInit_%d" %i]) for i in range(1,n_cell_types)] # for ic in model.initial_conditions: # print ic print(model.initial_conditions) [Observable("Obs_Cell%d" %i, Cell(dip = "%d" %i)) for i in range(n_cell_types)] Observable("Obs_All", Cell()) print(model.observables) print(dips) k_div = 0.03 [Parameter("k_div_%d" % i, k_div) for i in range(len(dips))] k_death = -dips+k_div [Parameter("k_death_%d" % i, k) for i,k in enumerate(k_death)] print(model.parameters) [Rule("Cell%d_Div" %i, Cell(dip = "%d" %i) >> Cell(dip = "%d" %i) + Cell(dip = "%d" %i), model.parameters["k_div_%d" %i]) for i in range(len(dips))] [Rule("Cell%d_Death" %i, Cell(dip = "%d" %i) >> None, model.parameters["k_death_%d" %i]) for i in range(len(k_death))] print(model.rules) for exp in range(n_exp): t1 = np.linspace(0,336,337) # 14 days sim = BngSimulator(model, tspan=t1, verbose=False)#, seed = 1095205711) # Why do the n_cells = 0 start off with 1? x1 = sim.run(n_runs = n_barcodes, param_values={"k_death_0": 0.005}, verbose = False) # returns np.array with species and obs # all_cells = np.array(x1.observables) # cell_tot = all_cells["Obs_All"].T[-1] # print(np.array(x1.all).shape) # quit() # print(x1.all) # print(type(x1.all)) cell_tot = [x[-1]["Obs_Cell0"] for x in x1.all] print(cell_tot) print("Sim 1 Finished.") post_drug_counts = [] for ind, cell in enumerate(cell_tot): print("%d:%d" % (exp,ind)) if cell == 0: post_drug_counts.append(0.) else: # rounding and taking integer is safe way to handle number.0 cell_pop = np.random.multinomial(int(round(cell)), normal_hist) # *100 for true normal # print(cell_pop) ## Normal Histogram Multinomial Selection of DIP Rates # plt.figure("DIP Rate Distribution Barcode #%d" % ind) # plt.bar(dips-0.5*(dips[1]-dips[0]), 1.*cell_pop/int(round(cell)), dips[1]-dips[0], label = "n_cells = %d" %int(cell)) # *100 for true normal # plt.plot(dips, normal_hist, lw = 2, color = "r") # plt.legend(loc = 0) t2 = np.linspace(0,168,169) # 7 days in drug x2 = sim.run(tspan = t2, param_values={"k_death_0": model.parameters['k_death_0'].value}, n_sim=1, initials={model.species[i]:pop for i,pop in enumerate(cell_pop)}, verbose= False) # ,"cellInit_0": 0}, - FIXED THIS PROBLEM post_drug_counts.append(x2.all["Obs_All"][-1]) # plt.figure("Experiment #%d Barcode #%d" % (exp,ind)) # plt.plot(t1, x1.all[int(cell)]["Obs_Cell0"],'0.5', lw=4, alpha=0.25) # for i,obs in enumerate(model.observables): # plt.plot(t1, x1.all[obs.name], lw = 2, label = obs.name, color = colors[i]) # plt.plot(t1[-1]+t2, x2.all[obs.name], lw = 2, label = obs.name) # plt.annotate(s = "n_cells = %d" % cell, xy = (0.1,0.1), xycoords = "axes fraction", fontsize = 24) # plt.text(-0.04, 2800, r'$\mu=%g$' % (np.mean(distr_all))) # plt.legend(loc = 0) print(post_drug_counts) all_post_drug_counts.append(post_drug_counts) print(all_post_drug_counts) np.save("barcoding_data_%dbar%dexp%dstates.npy" % (b, e, s), all_post_drug_counts)
class TestNfSim(object): def setUp(self): self.model = robertson.model self.model.reset_equations() self.sim = BngSimulator(self.model, tspan=np.linspace(0, 1)) self.param_values_2sets = [[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]] def test_nfsim_2runs(self): x = self.sim.run(n_runs=1, method='nf', seed=_BNG_SEED) observables = np.array(x.observables) assert len(observables) == 50 A = self.model.monomers['A'] x = self.sim.run(n_runs=2, method='nf', tspan=np.linspace(0, 1), initials={A(): 100}, seed=_BNG_SEED) assert (x.nsims == 2) assert np.allclose(x.dataframe.loc[0, 0.0], [100.0, 0.0, 0.0]) def test_nfsim_2initials(self): # Test with two initials A = self.model.monomers['A'] x2 = self.sim.run(method='nf', tspan=np.linspace(0, 1), initials={A(): [100, 200]}, seed=_BNG_SEED) assert x2.nsims == 2 assert np.allclose(x2.dataframe.loc[0, 0.0], [100.0, 0.0, 0.0]) assert np.allclose(x2.dataframe.loc[1, 0.0], [200.0, 0.0, 0.0]) def test_nfsim_2params(self): # Test with two param_values x3 = self.sim.run(method='nf', tspan=np.linspace(0, 1), param_values=self.param_values_2sets, seed=_BNG_SEED) assert x3.nsims == 2 assert np.allclose(x3.param_values, self.param_values_2sets) def test_nfsim_2initials_2params(self): # Test with two initials and two param_values A = self.model.monomers['A'] x = self.sim.run(method='nf', tspan=np.linspace(0, 1), initials={A(): [101, 201]}, param_values=[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]], seed=_BNG_SEED) assert x.nsims == 2 assert np.allclose(x.dataframe.loc[0, 0.0], [101.0, 0.0, 0.0]) @raises(ValueError) def test_nfsim_different_initials_lengths(self): A = self.model.monomers['A'] B = self.model.monomers['B'] sim = BngSimulator(self.model, tspan=np.linspace(0, 1), initials={B(): [150, 250, 350]}) sim.run(initials={A(): [275, 375]}) @raises(ValueError) def test_nfsim_different_initials_params_lengths(self): A = self.model.monomers['A'] sim = BngSimulator(self.model, tspan=np.linspace(0, 1), initials={A(): [150, 250, 350]}, param_values=self.param_values_2sets)
class TestBngSimulator(object): @with_model def setUp(self): Monomer('A', ['a']) Monomer('B', ['b']) Parameter('ksynthA', 100) Parameter('ksynthB', 100) Parameter('kbindAB', 100) Parameter('A_init', 0) Parameter('B_init', 0) Initial(A(a=None), A_init) Initial(B(b=None), B_init) Observable("A_free", A(a=None)) Observable("B_free", B(b=None)) Observable("AB_complex", A(a=1) % B(b=1)) Rule('A_synth', None >> A(a=None), ksynthA) Rule('B_synth', None >> B(b=None), ksynthB) Rule('AB_bind', A(a=None) + B(b=None) >> A(a=1) % B(b=1), kbindAB) self.model = model generate_equations(self.model) # Convenience shortcut for accessing model monomer objects self.mon = lambda m: self.model.monomers[m] # This timespan is chosen to be enough to trigger a Jacobian evaluation # on the various solvers. self.time = np.linspace(0, 1) self.sim = BngSimulator(self.model, tspan=self.time) def test_1_simulation(self): x = self.sim.run() assert np.allclose(x.tout, self.time) def test_multi_simulations(self): x = self.sim.run(n_runs=10) assert np.shape(x.observables) == (10, 50) # Check initials are getting correctly reset on each simulation assert np.allclose(x.species[-1][0, :], x.species[0][0, :]) def test_change_parameters(self): x = self.sim.run(n_runs=10, param_values={'ksynthA': 200}, initials={self.model.species[0]: 100}) species = np.array(x.all) assert species[0][0][0] == 100. def test_bng_pla(self): self.sim.run(n_runs=5, method='pla', seed=_BNG_SEED) def test_tout_matches_tspan(self): # Linearly spaced, starting from 0 assert all(self.sim.run(tspan=[0, 10, 20]).tout[0] == [0, 10, 20]) # Non-linearly spaced, starting from 0 assert all(self.sim.run(tspan=[0, 10, 30]).tout[0] == [0, 10, 30]) # Linearly spaced, starting higher than 0 assert all(self.sim.run(tspan=[10, 20, 30]).tout[0] == [10, 20, 30]) # Linearly spaced, starting higher than 0 assert all(self.sim.run(tspan=[5, 20, 30]).tout[0] == [5, 20, 30]) def tearDown(self): self.model = None self.time = None self.sim = None
import matplotlib.pyplot as plt import numpy as np from pysb.simulator.bng import BngSimulator from kinase_cascade import model # We will integrate from t=0 to t=40 t = np.linspace(0, 40, 50) # Simulate the model print("Simulating...") sim = BngSimulator(model) x = sim.run(tspan=t, verbose=False, n_runs=5, method='ssa') tout = x.tout y = np.array(x.observables) plt.plot(tout.T, y['ppMEK'].T) plt.show()
u_line = np.linspace(u_min, u_max, num_u) s_line = np.zeros(num_u) for i in range(0, num_u): s_line[i] = (beta/d_s)*u_line[i] # ---------------------------------------------------------- # Define observed times. tmin = 0 tmax = 50 num_t = 100 t = np.linspace(tmin, tmax, num_t) # Simulate model. simulator = BngSimulator(model, tspan=t) simresult = simulator.run(method='ssa') # ssa: discrete stochastic simulations yout = simresult.all # Plot results. plt.plot(t, yout['o_g_0'], label="$g_0$") plt.plot(t, yout['o_g_1'], label="$g_1$") plt.plot(t, yout['o_u'], label='$u$') plt.plot(t, yout['o_s'], label="$s$") plt.plot(t, yout['o_p'], label="$p$") plt.xlabel('$t$') plt.ylabel('molecule number') plt.title('Molecule number vs time')