def SPoCK_plot_traj(alt_ics_dict, exp_num): pardict, fndict, vardict, icsdict = init_SPoCK() DSargs = dst.args() DSargs.pars = pardict DSargs.varspecs = vardict DSargs.fnspecs = fndict DSargs.ics = alt_ics_dict #Load initial conditions given my argument DSargs.name = 'SPoCK' DSargs.tdata = [0, 600] DSargs.xdomain = { 'X': [0, 10**9], 'Y': [0, 10**9], 'A': [0, 10**9], 'B': [0, 10**9], } spock_ode = dst.Vode_ODEsystem(DSargs) fixedpoints_csv_path = "/Users/behzakarkaria/Documents/UCL/Barnes Lab/PhD Project/research_code/SPoCK_model/parameter_csv/fixedponts.csv" plot_out_path = "/Users/behzakarkaria/Documents/UCL/Barnes Lab/PhD Project/research_code/SPoCK_model/parameter_csv/fixedpoint_plots/" traj = spock_ode.compute('traj_1') pts = traj.sample() with PdfPages(plot_out_path + "exp_" + str(exp_num) + ".pdf") as pdf: plt.figure(1) plt.plot(pts['t'], pts['X'], label="X") plt.plot(pts['t'], pts['Y'], label="Y") plt.xlabel("t") plt.ylabel("population") plt.yscale('log') plt.legend(loc=4) # bottom left location pdf.savefig(plt.figure(1)) plt.show() plt.close()
def SPoCK_bifurcation(alt_ics_dict): pardict, fndict, vardict, icsdict = init_SPoCK() DSargs = dst.args() DSargs.pars = pardict DSargs.varspecs = vardict DSargs.fnspecs = fndict DSargs.ics = alt_ics_dict DSargs.name = 'SPoCK' DSargs.tdata = [0, 10000] DSargs.xdomain = { 'X': [0, 10**9], 'Y': [0, 10**9], 'A': [0, 10**9], 'B': [0, 10**9], } spock_ode = dst.Vode_ODEsystem(DSargs) #spock_ode.set(pars = {'w': 1} ) # Lower bound of the control parameter 'i' #traj = spock_ode.compute('test_trj') # integrate ODE # setup continuation class PC = dst.ContClass(spock_ode) PCargs = dst.args(name='EQ1', type='EP-C') PCargs.freepars = ['A_c'] PCargs.StepSize = 10 PCargs.MaxNumPoints = 10000 PCargs.MaxStepSize = 20 PCargs.MinStepSize = 10 PCargs.MaxTestIters = 10000 PCargs.LocBifPoints = 'all' PCargs.SaveEigen = True PCargs.verbosity = 2 PC.newCurve(PCargs) PC['EQ1'].backward() print(PC['EQ1'].info()) PCargs = dst.args(name='EQ2', type='EP-C') PCargs.initpoint = 'EQ1:H1' PCargs.freepars = ['A_c'] PCargs.StopAtPoints = ['BP'] PCargs.MaxNumPoints = 10 PCargs.MaxStepSize = 20 PCargs.MinStepSize = 10 PCargs.StepSize = 10 PCargs.LocBifPoints = 'all' PCargs.SaveEigen = True PC.newCurve(PCargs) PC['EQ2'].forward() plot_out_path = "/Users/behzakarkaria/Documents/UCL/Barnes Lab/PhD Project/research_code/SPoCK_model/parameter_csv/fixedpoint_plots/" with PdfPages(plot_out_path + "bifurcation_Ac_X" + ".pdf") as pdf: fig1 = plt.figure(1) ax = fig1.add_subplot(figsize=(18, 12.5)) #ax.set_xlim(10**0, 10**9) #ax.set_ylim(10**0, 10**9) #ax.set_xscale('symlog', basex=10) #ax.set_yscale('symlog', basey=10) PC.display(('A_c', 'X'), stability=True) pdf.savefig(fig1) with PdfPages(plot_out_path + "bifurcation_Ac_Y" + ".pdf") as pdf: fig2 = plt.figure(2) fig2.add_subplot(figsize=(18, 12.5)) ax2 = plt.gca() #ax2.set_xlim(0, 10**9) #ax2.set_ylim(0, 10**9) #ax2.set_xscale('symlog', basex=10) #ax2.set_yscale('symlog', basey=10) PC.display(('A_c', 'X'), stability=True, figure=fig2) pdf.savefig(ax2.get_figure())
def SPoCK_phase_plane(fixed_points_dict): pardict, fndict, vardict, icsdict = init_SPoCK() DSargs = dst.args() DSargs.pars = pardict DSargs.varspecs = vardict DSargs.fnspecs = fndict DSargs.ics = icsdict DSargs.name = 'SPoCK' DSargs.tdata = [0, 1500] DSargs.xdomain = { 'X': [0, 10**9], 'Y': [0, 10**9], 'A': [0, 10**9], 'B': [0, 10**9], } spock_ode = dst.Vode_ODEsystem(DSargs) print("loaded ode system") #pp.plot_PP_vf(spock_ode, 'X', 'Y', scale_exp=0, N=50, subdomain={'X':[X_lower ,X_Upper], 'Y':[Y_lower,Y_Upper]} ) #plot vector field #ax.quiver(X_quiv, Y_quiv, dxs, dys, angles='xy', pivot='middle', units='inches', ) plt.figure(1) fig, ax = plt.subplots(figsize=(18, 12.5)) ax.set_xscale('log', basex=10) ax.set_yscale('log', basey=10) ax.set_xlim(10**0, 10**8) ax.set_ylim(10**0, 10**9) ax = custom_PP_vf_2(spock_ode, 'X', 'Y', ax, scale_exp=-1, N=150, subdomain={ 'X': [0, 9], 'Y': [0, 9] }) #ax = custom_PP_vf_2(spock_ode, 'X', 'Y', ax, scale_exp=-1, N=50, subdomain={'X': [2, 4], 'Y': [2, 3]}) print("finished plotting vf") # subdomain = {'X': [0, 0.7e9], 'A': [0, 0.8e9] count = 0 for dict in fixed_points_dict: DSargs = dst.args() DSargs.pars = pardict DSargs.varspecs = vardict DSargs.fnspecs = fndict DSargs.ics = dict DSargs.name = 'SPoCK' DSargs.tdata = [0, 600] DSargs.xdomain = { 'X': [0, 10**9], 'Y': [0, 10**9], 'A': [0, 10**9], 'B': [0, 10**9], } spock_ode = dst.Vode_ODEsystem(DSargs) traj = spock_ode.compute('traj_1') try: pts = traj.sample() except AttributeError: print("No solution found") continue ax.plot(pts['X'], pts['Y']) #ax.plot(pts['t'], pts['B']) plt.xlabel('X') plt.ylabel('Y') print(count) count = count + 1 phase_plot_path = "/Users/behzakarkaria/Documents/UCL/Barnes Lab/PhD Project/research_code/SPoCK_model/parameter_csv/" pdf_page_obj = PdfPages(phase_plot_path + "phase_plots_5_fp" + ".pdf") pdf_page_obj.savefig(ax.get_figure()) pdf_page_obj.close() plt.show()
def SPoCK_find_fixedpoints(): pardict, fndict, vardict, icsdict = init_SPoCK() DSargs = dst.args() DSargs.pars = pardict DSargs.varspecs = vardict DSargs.fnspecs = fndict DSargs.ics = icsdict DSargs.name = 'SPoCK' DSargs.tdata = [0, 50000] DSargs.xdomain = { 'X': [0, 10**9], 'Y': [0, 10**9], 'A': [0, 10**9], 'B': [0, 10**9], } spock_ode = dst.Vode_ODEsystem(DSargs) jac_fun = make_jac_pydstool(spock_ode) fp_coords = pp.find_fixedpoints(spock_ode, n=10, eps=1e-50, jac=jac_fun, subdomain={ 'X': [0, 10**9], 'Y': [0, 10**9], 'A': [0, 10**9], 'B': [0, 10**9] }) fixedpoints_pdf_path = "/Users/behzakarkaria/Documents/UCL/Barnes Lab/PhD Project/research_code/SPoCK_model/parameter_csv/" plt.figure(1) fig, ax = plt.subplots(figsize=(18, 12.5)) ax.set_xscale('symlog', basex=10) ax.set_yscale('symlog', basey=10) ax.set_ylim(0, 10**9) ax.set_xlim(0, 10**9) good_coords = [] for fp in fp_coords: try: fp_obj = pp.fixedpoint_nD( spock_ode, dst.Point(fp), coords=fp, jac=jac_fun, eps=1e-20 ) #Does he tolerance here matter when we find the points above with a good tolerance? good_coords.append(fp) except: continue if fp_obj.stability == 'u': style = 'wo' elif fp_obj.stability == 'c': style = 'co' else: # 's' style = 'ko' print("") print(fp_obj.stability) print('X:', fp_obj.fp_coords['X']) print('Y:', fp_obj.fp_coords['Y']) print("") try: ax.plot(fp_obj.fp_coords['X'], fp_obj.fp_coords['Y'], style) except ValueError: continue plt.xlabel("X") plt.ylabel("Y") #plt.title('Fixed points \n w = 1*10**-2, D = 0.2 ') pdf_page_obj = PdfPages(fixedpoints_pdf_path + "fixedpoints_XY" + ".pdf") pdf_page_obj.savefig(ax.get_figure()) pdf_page_obj.close() fixedpoints_csv_path = "/Users/behzakarkaria/Documents/UCL/Barnes Lab/PhD Project/research_code/SPoCK_model/parameter_csv/fixedponts.csv" fieldnames = ('index', 'X', 'Y', 'A', 'B') index = 0 for fp_dict in good_coords: fp_dict['index'] = index index = index + 1 data_frame = pd.DataFrame.from_records(good_coords) data_frame.to_csv(fixedpoints_csv_path)
'active': True}, varnames=['x'], parnames=['a'], targetlang='python') # targetlang is redundant (defaults to python) DSargs = args(name='vanderpol') # struct-like data DSargs.events = [event_x_a] DSargs.pars = pars DSargs.tdata = [0, 3] DSargs.algparams = {'max_pts': 3000, 'init_step': 0.02, 'stiff': True} DSargs.varspecs = {'x': xstr, 'y': ystr} DSargs.xdomain = {'x': [-2.2, 2.5], 'y': [-2, 2]} DSargs.fnspecs = {'Jacobian': (['t','x','y'], """[[(1-x*x)/eps, 1/eps ], [ -1, 0 ]]""")} DSargs.ics = icdict vdp = dst.Vode_ODEsystem(DSargs) traj = vdp.compute('test_traj') pts = traj.sample() evs = traj.getEvents('event_x_a') # figure 1 is the time evolution of the two variables plt.figure(1) plt.plot(pts['t'], pts['x'], 'b', linewidth=2) plt.plot(pts['t'], pts['y'], 'r', linewidth=2) # figure 2 is the phase plane plt.figure(2) # phase plane tools are in the Toolbox module from PyDSTool.Toolbox import phaseplane as pp
def defineDFBAModel(SpeciesDict , MediaDF, cobraonly, with_essential): print("Defining Dynamical model... \n") ParDef = dict() VarDef = dict() ICS = dict() exchange_list = [] mediaDerivedComponents = {} for i, row in MediaDF.iterrows(): N = cleanupname(row.Reaction) mediaDerivedComponents[N] = row['Flux Value'] / (24.0) # Per hour number_of_species = len(SpeciesDict.keys()) for species in SpeciesDict.keys(): print("\nReading species " + str(species)) SpeciesDict[species]['SpeciesModel'] = cobra.io.read_sbml_model(SpeciesDict[species]['File']) SpeciesDict[species]['OriginalLB'] = {r.id:r.lower_bound/10.0 for r in SpeciesDict[species]['SpeciesModel'].exchanges} SpeciesDict[species]['solution'] = SpeciesDict[species]['SpeciesModel'].optimize() SpeciesDict[species]['Name'] = SpeciesDict[species]['SpeciesModel'].name.split(' ')[0] + '_' \ + SpeciesDict[species]['SpeciesModel'].name.split(' ')[1].replace('.','') SpeciesDict[species]['exchanges'] = [r.id for r in SpeciesDict[species]['SpeciesModel'].exchanges] exchange_list += SpeciesDict[species]['exchanges'] Name=SpeciesDict[species]['Name'] ICS[Name] = SpeciesDict[species]['initAbundance'] ParDef['mu' + '_' + Name] = SpeciesDict[species]['solution'].objective_value VarDef[Name] = 'mu_' + Name + ' * ' + Name + ' - ' + 'Dilution * ' + Name if not cobraonly: variable_dict = { 'P':'((k_PM*B)/(gamma_12+B))*(delta_Po+delta_PI*P^np/(P^np+gamma_PI^np))*(1-V_S2*S/(S+gamma_s2))+(k_PE*max(0,R_E-T_RE))*Ep/(1+gamma_PE*I_E)-mu_4*P', 'Ep': 'mu_E*(Ep/(Ep+gamma_E))-(d1+d2*max(0,P-V_S1*S/(S+gamma_s1)-T_EP))*Ep', } scale = 0.2 mu_E = 0.5/2.0/scale gamma_E = 0.5 d1 = 0.125/2.0/scale d2 = 0.625/10/scale E_max = (mu_E - gamma_E*d1)/d1 parameter_dict = { 'V_L': 10, 'V_M':50, 'd_BL':0.5, 'k_dif':0.1,# 5, 'k_AD':0.5,#e6 'k_3':5, #6e6, 'k_AT':1e-3,#0.015, 'alpha_EM':1.8, 'epsilon_0':0.1, 'epsilon_max':0.21, 'a_1':0.5,# 'gamma_1':5,#e6, 'k_1':1, 'alpha_RE':2, 'mu_RE':0.1, 'k_IE':19,# 'gamma_IE':1.0,#10, 'alpha_11':0.1,#e-7, 'mu_IE':1, 'T':0.075, #0.5,#1.1e6, 'k_5':8, 'k_PM':0.025/scale, 'gamma_12':1.1e-1,#1.2e1,#1.2e5, 'k_PE':0.001/scale, 'T_RE':0.65, 'gamma_PE':1, 'mu_4':0.05/scale, 'T_I':1, 'mu_E': mu_E, 'gamma_E':gamma_E, 'd1': d1, 'd2': d2, 'E_max': E_max, 'epsilon_E': 0.1, 'mu_B':0.0, 'V_S1' : 0.1, 'T_EP' : 0.9e-3, # 0.05 'gamma_s1' : 1, 'V_S2' : 0.4, 'gamma_s2' : 1, 'delta_muc': 0.3, 'alpha_muc': 1, 'k_max': 0.1, 'gamma_dif': 0.75, 'S' : 0, 'n1': 2, 'ne' : 2, 'np': 2, 'k_epsilon' : 1, 'delta_PI' : 1.5, 'delta_Po' : 0.5, 'gamma_PI' :0.3 } initial_conditions = { 'R_E':0, 'I_E':0, 'B':0, 'P':0, 'Ep':3.5 } ParDef.update(parameter_dict) ICS.update(initial_conditions) VarDef.update(variable_dict) exponent = 1 List_of_names = [ SpeciesDict[sp]['Name'] for sp in SpeciesDict.keys()] sum_of_species = ' + '.join([ name + '_M' for name in List_of_names]) epsilon = '(epsilon_0 + epsilon_E * (E_max - Ep)^ne/((E_max-Ep)^ne+k_epsilon^ne))' VarDef['B'] = 'max(0,(' + epsilon + '*(' + sum_of_species +') - T)) - k_5 * P * B + mu_B * B' for name in List_of_names: VarDef[name] += ' - (k_max * gamma_dif^n1 / (gamma_dif^n1 + '\ '(Ep * (delta_muc + S * (1 - delta_muc) / '\ '(S + alpha_muc)))^n1)) * ('+ name + ' * 10^'\ + str(exponent) + ' / V_L - ' + name +'_M / V_M)' ICS[name + '_M'] = 0.1*SpeciesDict[species]['initAbundance'] # 0.0 # This should be non zero VarDef[name + '_M'] = '(k_max * gamma_dif^n1/ (gamma_dif^n1 + '\ '(Ep * (delta_muc + S * (1 - delta_muc) / (S+alpha_muc)))^n1))'\ '*(' + name + '*10^'+str(exponent)+'/V_L- ' + name + '_M/V_M)'\ ' - (k_AD * ' + name + '_M)/(k_3+' + sum_of_species +')'\ ' - (k_AT*R_E*'+ name+'_M)*Ep/(alpha_EM + R_E)'\ ' - ' + epsilon +'*'+name+'_M' if 'Shigella_flexneri' in name: epsilon2 = '(epsilon_shig_0 + epsilon_E * (E_max - Ep)^ne/((E_max-Ep)^ne+k_epsilon^ne))' VarDef[name + '_M'] = '(k_max * gamma_dif^n1 / (gamma_dif^n1 + (Ep * '\ '(delta_muc + S * (1 - delta_muc) / (S+alpha_muc)))^n1))'\ '*(' + name + '*10^'+str(exponent)+'/V_L - ' + name + '_M/V_M)'\ ' - (k_AD * ' + name + '_M)/(k_3+' + sum_of_species +')'\ ' - (k_AT*R_E*'+ name+'_M)*Ep/(alpha_EM + R_E)'\ ' - ' + epsilon2 +'*'+name+'_M' VarDef['B_shigella'] = '('+epsilon2+'* Shigella_flexneri_M)/('+ epsilon +\ '*('+sum_of_species +'- Shigella_flexneri_M' +') + '\ + epsilon2 + '* Shigella_flexneri_M )*max(0, ('\ + epsilon + '*(' + sum_of_species +') + 100*(' + epsilon2\ + ' * Shigella_flexneri_M) - T * ( K_T/ (K_T + B_shigella) )))'\ ' - k_5 * P * B_shigella + mu_shigella * B_shigella' VarDef['B'] = '(' + epsilon + ' * (' + sum_of_species + ')/('\ + epsilon+'*('+sum_of_species +'- Shigella_flexneri_M'\ +') + '+epsilon2 +'*Shigella_flexneri_M ))'\ + '*max(0,(' + epsilon + '*(' + sum_of_species +')'\ ' + ' + epsilon2 + ' * Shigella_flexneri_M -T * '\ '(K_T/(K_T+B_shigella)))) - k_5 * P * B + mu_B * B' ICS['B_shigella'] = 0.0 ParDef['epsilon_shig_0'] = 0.18 ParDef['K_T'] = 0.05 ParDef['mu_shigella'] = 0.05 ######################## VarDef['R_E'] = '(a_1*(' + sum_of_species + ')*(k_1*P+T_I))/((gamma_1+('\ + sum_of_species + '))*(1+alpha_RE*I_E))-mu_RE*R_E' VarDef['I_E'] = '(k_IE * R_E) / (gamma_IE + R_E) + alpha_11 * ('\ + sum_of_species + ') - mu_IE * I_E' ParDef['Dilution'] = 0.002 all_exchanges = set() for ex in exchange_list: all_exchanges.add(ex) #################################################################################################### if with_essential: print("Finding the essential nutrients for each species") ClustersMissed = list(requiredNutrients(SpeciesDict,MediaDF,True)) print("Number of essential nutrients to be added is " + str(len(ClustersMissed))) #################################################################################################### for rid in all_exchanges: VarDef[rid] = '- Dilution * ' + rid ICS[rid] = 1.0 if rid in mediaDerivedComponents.keys(): ParDef[rid + '_influx'] = mediaDerivedComponents[rid] VarDef[rid] += ' + ' + rid + '_influx' if with_essential: if rid in ClustersMissed: ParDef[rid + '_artificial'] = 0.01 ######################################################### VarDef[rid] += ' + ' + rid + '_artificial' for species in SpeciesDict.keys(): if 'h2o' in rid: # Check to see if a unique metabolite is represented only once print(species, rid) if rid in SpeciesDict[species]['exchanges']: Name = SpeciesDict[species]['Name'] ParDef[rid + '_' + Name] = SpeciesDict[species]['solution'].fluxes[rid] VarDef[rid] += ' + ' + rid + '_' + Name + ' * ' + Name ModelDef = dst.args(name='Comunity', pars=ParDef, varspecs=VarDef, ics=ICS) ModelDS = dst.Vode_ODEsystem(ModelDef) print("Done!") return (SpeciesDict, ModelDef, ModelDS)