Example #1
0
def bistability_analysis():
    f2_range = linspace(0, 0.4, 41)
    t = linspace(0, 50000, 1000)
    ion()
    ss_aBax_vals_up = []
    ss_aBax_vals_down = []

    for f2 in f2_range:
        model.parameters['Bid_0'].value = f2 * 1e-1
        bax_total = 2e-1

        # Do "up" portion of hysteresis plot
        model.parameters['aBax_0'].value = 0
        model.parameters['cBax_0'].value = bax_total
        x = odesolve(model, t)
        figure('up')
        plot(t, x['aBax_']/bax_total)
        ss_aBax_vals_up.append(x['aBax_'][-1]/bax_total)

        # Do "down" portion of hysteresis plot
        model.parameters['aBax_0'].value = bax_total
        model.parameters['cBax_0'].value = 0
        x = odesolve(model, t)
        figure('down')
        plot(t, x['aBax_']/bax_total)
        ss_aBax_vals_down.append(x['aBax_'][-1]/bax_total)

    figure()
    plot(f2_range, ss_aBax_vals_up, 'r')
    plot(f2_range, ss_aBax_vals_down, 'g')
Example #2
0
def bistability_analysis():
    f2_range = linspace(0, 0.4, 41)
    t = linspace(0, 50000, 1000)
    ion()
    ss_aBax_vals_up = []
    ss_aBax_vals_down = []

    for f2 in f2_range:
        model.parameters['Bid_0'].value = f2 * 1e-1
        bax_total = 2e-1

        # Do "up" portion of hysteresis plot
        model.parameters['aBax_0'].value = 0
        model.parameters['cBax_0'].value = bax_total
        x = odesolve(model, t)
        figure('up')
        plot(t, x['aBax_'] / bax_total)
        ss_aBax_vals_up.append(x['aBax_'][-1] / bax_total)

        # Do "down" portion of hysteresis plot
        model.parameters['aBax_0'].value = bax_total
        model.parameters['cBax_0'].value = 0
        x = odesolve(model, t)
        figure('down')
        plot(t, x['aBax_'] / bax_total)
        ss_aBax_vals_down.append(x['aBax_'][-1] / bax_total)

    figure()
    plot(f2_range, ss_aBax_vals_up, 'r')
    plot(f2_range, ss_aBax_vals_down, 'g')
Example #3
0
File: mca.py Project: abulovic/pysb
def time_dep_sensitivity(model, t, results = None, delta=0.1, parameters=[]):
	if not parameters:
		return
	all_param_results = {}

	if results is None:
		results = odesolve(model, t)
	print 'Solving time-dependent sensitivity analysis for %d parameters' % len(parameters)

	for param in parameters:
		if param.name.startswith('__'):
			continue
		print 'Solving for', param.name
		
		oldval = param.value

		newval_left = param.value * (1. + 0.5 * delta)
		model.parameters[param.name].value = newval_left
		new_results_left = odesolve(model, t)

		newval_right = param.value * (1. - 0.5 * delta)
		model.parameters[param.name].value = newval_right
		new_results_right = odesolve(model, t)

		model.parameters[param.name].value = oldval

		all_param_results[param.name] = sens_res(param.name,
												 new_results_left,
												 new_results_right,
												 delta * param.value)
	
	return all_param_results
Example #4
0
def plot_effect_of_pore_reverse_rate():
    ci = color_iter()

    pore_reverse_rates = [1e-2, 1e-4, 1e-6]
    t = np.linspace(0, 5000, 500)
    plt.figure()

    for pore_reverse_rate in pore_reverse_rates:
        params_dict = {'Bax_0': 50., 'Vesicles_0': 50.,
                        'pore_reverse_rate_k': pore_reverse_rate}
        b = one_cpt.Builder(params_dict=params_dict)
        b.build_model_bax_schwarz_reversible()
        x = odesolve(b.model, t)
        avg_pores = x['pores']/b.model.parameters['Vesicles_0'].value
        col = ci.next()
        plt.plot(t, avg_pores, color=col, linestyle='-',
                 label="Pores, reverse rate %g" % pore_reverse_rate)
        plt.plot(t, 1 - np.exp(-avg_pores), color=col, linestyle='--',
                 label="Dye release, reverse rate %g" % pore_reverse_rate)

    plt.legend(loc='upper left')
    plt.xlabel('Time (sec)')
    plt.ylabel('Dye release/Avg. pores')
    plt.title('Dye release/pore formation with varying reverse rates')
    plt.show()
Example #5
0
def plot_fraction_bax_bound(model, figure_id=None):
    bax_concs = np.logspace(0, 4, 40)
    t = np.linspace(0, 3000, 1000)

    #plt.figure()
    ss_mBax_values = []
    for bax_conc in bax_concs:
        model.parameters['Bax_0'].value = bax_conc
        x = odesolve(model, t)
        mBax_frac = x['mBax'] / model.parameters['Bax_0'].value
        ss_mBax_value = mBax_frac[-1]
        ss_mBax_values.append(ss_mBax_value)
        #plt.plot(t, mBax_frac)
    #plt.show()

    ss_mBax_values = np.array(ss_mBax_values)

    if figure_id is not None:
        plt.figure(figure_id)
    else:
        plt.figure()

    plt.semilogx(bax_concs, ss_mBax_values, linewidth=2)
    plt.xlabel('Bax concentration (nM)')
    plt.ylabel('Pct. Bax at liposomes')
    plt.ylim([0, 1])
    plt.title('Frac Bax bound vs. Bax conc')
    plt.show()
Example #6
0
def plot_liposome_titration(builder=one_cpt.Builder()):
    b = builder
    b.translocate_Bax()
    b.model.parameters['Bax_0'].value = 100
    t = np.linspace(0, 3000, 1000)
    lipo_concs = np.logspace(-2, 4, 40)
    ss_mBax_values = []

    # Plot timecourses
    plt.ion()
    #plt.figure()

    for lipo_conc in lipo_concs:
        b.model.parameters['Vesicles_0'].value = lipo_conc
        x = odesolve(b.model, t)
        mBax_frac = x['mBax'] / b.model.parameters['Bax_0'].value
        plt.plot(t, mBax_frac)
        ss_mBax_value = mBax_frac[-1]
        ss_mBax_values.append(ss_mBax_value)
    plt.show()
    ss_mBax_values = np.array(ss_mBax_values)

    # Plot liposome titration
    plt.figure()
    plt.plot(lipo_concs, ss_mBax_values)
    plt.xlabel('Liposome concentration (nM)')
    plt.ylabel('Pct. Bax at liposomes (Bax_0 = %d nM)' %
               b.model.parameters['Bax_0'].value)
    plt.title('Bax/Liposome binding curve')
    plt.show()
Example #7
0
    def sensitivity(self,tspan=None, parameters_ref=None, sp_SA=None, sampling_method = 'saltelli', analyze_method='sobol',N=1 , verbose=True):
      
        ana_meth = importlib.import_module('SALib.analyze.%s'%analyze_method)
      
        if tspan is not None:
            self.tspan = tspan
        elif self.tspan is None:
            raise Exception("'time t' must be defined.")
        
        if sp_SA is None:
            raise Exception("A species to do the sensitivity analysis on must be defined")
        if sp_SA not in [str(sp) for sp in self.model.species] and sp_SA  not in [str(obs.name) for obs in self.model.observables]:
            raise Exception("Species is not in model species")

        ref = odesolve(self.model, self.tspan, param_values=parameters_ref)

        if verbose: print "Getting parameters information"
        self.pars_info(parameters_ref, sampling_method=sampling_method, N=N)
        
        if verbose: print "Simulating with parameters from sampling"
        p=multiprocessing.Pool(2)
        func = partial(self.sim_model,sp_SA=sp_SA)
        self.sim = p.map(func, self.param_sets)
        self.output = [sum((r - ref[sp_SA])**2) for r in self.sim]
          
        if verbose: print "Sensitivity analysis"
        self.sa_result = ana_meth.analyze(self.problem, numpy.array(self.output), print_to_console=True)
Example #8
0
def test_integrate_with_expression():

    Monomer('s1')
    Monomer('s9')
    Monomer('s16')
    Monomer('s20')

    Parameter('ka',2e-5)
    Parameter('ka20', 1e5)

    Initial(s9(), Parameter('s9_0', 10000))

    Observable('s1_obs', s1())
    Observable('s9_obs', s9())
    Observable('s16_obs', s16())
    Observable('s20_obs', s20())

    Expression('keff', (ka*ka20)/(ka20+s9_obs))

    Rule('R1', None >> s16(), ka)
    Rule('R2', None >> s20(), ka)
    Rule('R3', s16() + s20() >> s16() + s1(), keff)

    time = linspace(0, 40, 100)
    x = odesolve(model, time)
Example #9
0
def test_simulation():
    time = np.linspace(0, 18000, 1801)
    x = odesolve(model, time)
    expectedx_final = {'IkBan_obs': 3145.8443053128276,
                       'NFkBn_obs': 178.06326194655537,
                       'IkBap_NFkBc_obs': 1.3899039187480429e-07,
                       'IkBa_on_obs': 0.045201392272254615,
                       'IKKKa_obs': 0.00054704675357157236,
                       'A20_off_obs': 1.9547986077277453,
                       'A20t_obs': 6.2762670477040663,
                       'IkBan_NFkBn_obs': 28.012691613691331,
                       'IKKn_obs': 199999.9951281352,
                       'IKKa_obs': 2.3395704210536575e-08,
                       'TNFR1a_obs': 5.3362282855621739e-06,
                       'IkBa_off_obs': 1.9547986077277459,
                       'TNF_ext_obs': 9.5649122910157076e-08,
                       'A20_on_obs': 0.045201392272254573,
                       'IkBap_obs': 2.3942600622297971e-09,
                       'IKKii_obs': 0.0045466692017435365,
                       'IKKKn_obs': 99999.999452953241,
                       'IKKi_obs': 0.00032517206132429724,
                       'TNFR1i_obs': 1999.9999946637713,
                       'IkBat_obs': 6.2762670477040681,
                       'NFkBc_obs': 139.40965738805579,
                       'IkBac_obs': 8607.2535257899253,
                       'A20_obs': 5714.7212868294837,
                       'IkBa_NFkB_obs': 99655.514388905125}
    for i in expectedx_final.keys():
        final_obs = x[i][-1]
        if abs(final_obs - expectedx_final[i]) > 1e-3:
            raise ValueError("%s: Expected %f, got %f, diff %e" %
                            (i, expectedx_final[i], final_obs, final_obs -
                             expectedx_final[i]))
Example #10
0
    def tropicalize(self, tspan=None, param_values=None, diff_par=1, ignore=1, epsilon=1, find_passengers_by='imp_nodes',
                    plot_imposed_trace=False, verbose=False):
        """
        tropicalization of driver species
        :param diff_par:
        :param find_passengers_by: Option to find passenger species. 'imp_nodes' finds the nodes that only have one edge.
        'qssa' finds passenger species using the quasi steady state approach
        :param plot_imposed_trace: Option to plot imposed trace
        :param tspan: Time span
        :param param_values: PySB model parameter values
        :param ignore: Initial time points to ignore
        :param epsilon: Order of magnitude difference between solution of ODE and imposed trace to consider species as
        passenger
        :param verbose: Verbose
        :return:
        """

        if verbose:
            print("Solving Simulation")

        if tspan is not None:
            self.tspan = tspan
        else:
            raise SimulatorException("'tspan' must be defined.")

        if param_values is not None:
            # accept vector of parameter values as an argument
            if len(param_values) != len(self.model.parameters):
                raise Exception("param_values must be the same length as model.parameters")
            if not isinstance(param_values, numpy.ndarray):
                param_values = numpy.array(param_values)
        else:
            # create parameter vector from the values in the model
            param_values = numpy.array([p.value for p in self.model.parameters])

        # convert model parameters into dictionary
        self.param_values = dict((p.name, param_values[i]) for i, p in enumerate(self.model.parameters))

        self.y = odesolve(self.model, self.tspan, self.param_values)

        if verbose:
            print("Getting Passenger species")
        if find_passengers_by == 'qssa':
            if plot_imposed_trace:
                self.find_passengers(self.y[ignore:], epsilon, plot=plot_imposed_trace)
            else:
                self.find_passengers(self.y[ignore:], epsilon)
        elif find_passengers_by == 'imp_nodes':
            self.find_nonimportant_nodes()
        else:
            raise Exception("equations to tropicalize must be chosen")

        if verbose:
            print("equation to tropicalize")
        self.equations_to_tropicalize()

        if verbose:
            print("Getting signatures")
        self.signal_signature(self.y[ignore:], diff_par=diff_par)
        return
Example #11
0
def synthetic_data(model, tspan, obs_list=None, sigma=0.1, seed=None):
    from pysb.integrate import odesolve
    random = numpy.random.RandomState(seed)
    ysim = odesolve(model, tspan)
    ysim_array = ysim.view().reshape(len(tspan), len(ysim.dtype))
    ysim_array *= (random.randn(*ysim_array.shape) * sigma + 1)
    return ysim
def test_build_models():
    model_names = [#'t', 'ta', 'tai', 'taid', 'taidt', 'tair', 'taird',
                   #'tairdt', 'tad', 'tadt', 'tar', 'tard', 'tardt',
                    #---
                   #'bax_heat',
                   #'bax_heat_reversible',
                   #'bax_heat_dimer',
                   #'bax_heat_dimer_reversible',
                   #'bax_heat_auto1',
                   #'bax_heat_auto2',
                    #---
                   #'bax_heat_bh3_auto2',
                   #'bax_heat_auto1_reversible_activation',
                   #'bax_heat_auto2_reversible_activation',
                   #'bax_heat_auto1_reversible',
                   #'bax_heat_auto2_reversible',
                   #'bax_heat_auto1_dimer',
                   #'bax_heat_auto2_dimer',
                   #'bax_heat_auto1_dimer_reversible',
                   #'bax_heat_auto2_dimer_reversible',
                   #'bax_heat_bh3_exposure_auto2',
                   #'bax_schwarz',
                   #'bax_schwarz_reversible',
                   #'bax_schwarz_dimer',
                   #'bax_schwarz_dimer_reversible',
                   #'bax_schwarz_tetramer_reversible',
    ]

    for model_name in model_names:
        print "Running model %s" % model_name
        b = Builder()
        eval("b.build_model_%s()" % model_name)
        x = odesolve(b.model, t)
        plot_model(t, x, 'build_model_%s' % model_name)
Example #13
0
def run_figure_sim(model):
    """Run the C8 dose-response series shown in Fig. 11 of [Albeck2008]_.

    Returns
    -------
    [t, outputs] : list containing two numpy.array objects
        t: The time coordinates of each timepoint, in seconds, from 0 to
            60,000 seconds (15 hours), at 60-second intervals.
        outputs: A 901 x 7 array. Each row corresponds to the fraction of Smac
            released into the cytosol at each timepoint. Each column correspond
            to a distinct caspase 8 dose, from lowest to highest:
            [1, 5, 10, 50, 100, 500, 1000], in molecules per cell.
    """
    # Set timepoints and c8 doses
    tf = 15 * 3600  # 15 hours
    t = np.linspace(0, tf, (tf / 60) + 1)
    c8_doses = [0.01e2, 0.05e2, 0.1e2, 0.5e2, 1e2, 5e2, 10e2]

    outputs = np.empty((len(t), len(c8_doses)))
    for i, c8_dose in enumerate(c8_doses):
        model.parameters['C8_0'].value = c8_dose
        x = odesolve(model, t, rtol=rtol)
        frac_Smac_release = x['cSmac'] / model.parameters['Smac_0'].value
        outputs[:, i] = frac_Smac_release

    return [t, outputs]
Example #14
0
def run_figure_sim(model):
    """Run the C8 dose-response series shown in Fig. 11 of [Albeck2008]_.

    Returns
    -------
    [t, outputs] : list containing two numpy.array objects
        t: The time coordinates of each timepoint, in seconds, from 0 to
            60,000 seconds (15 hours), at 60-second intervals.
        outputs: A 901 x 7 array. Each row corresponds to the fraction of Smac
            released into the cytosol at each timepoint. Each column correspond
            to a distinct caspase 8 dose, from lowest to highest:
            [1, 5, 10, 50, 100, 500, 1000], in molecules per cell.
    """
    # Set timepoints and c8 doses
    tf = 15 * 3600 # 15 hours
    t = np.linspace(0, tf, (tf / 60) + 1)
    c8_doses = [0.01e2, 0.05e2, 0.1e2, 0.5e2, 1e2, 5e2, 10e2]

    outputs = np.empty((len(t), len(c8_doses)))
    for i, c8_dose in enumerate(c8_doses):
        model.parameters['C8_0'].value = c8_dose
        x = odesolve(model, t, rtol=rtol)
        frac_Smac_release = x['cSmac'] / model.parameters['Smac_0'].value
        outputs[:,i] = frac_Smac_release

    return [t, outputs]
Example #15
0
def test_integrate_with_expression():
    """Ensure a model with Expressions simulates."""

    Monomer('s1')
    Monomer('s9')
    Monomer('s16')
    Monomer('s20')

    # Parameters should be able to contain s(\d+) without error
    Parameter('ks0',2e-5)
    Parameter('ka20', 1e5)

    Initial(s9(), Parameter('s9_0', 10000))

    Observable('s1_obs', s1())
    Observable('s9_obs', s9())
    Observable('s16_obs', s16())
    Observable('s20_obs', s20())

    Expression('keff', (ks0*ka20)/(ka20+s9_obs))

    Rule('R1', None >> s16(), ks0)
    Rule('R2', None >> s20(), ks0)
    Rule('R3', s16() + s20() >> s16() + s1(), keff)

    time = np.linspace(0, 40)
    x = odesolve(model, time)
Example #16
0
def plot_model_data():
    """Plots a simulation of the model along with the data."""
    plt.ion()
    x = odesolve(model, tspan)
    plt.plot(tspan, x['A_'])
    plt.plot(tspan, synthetic_data['A_'])
    plt.show()
Example #17
0
def run_model(tmax=12000, fittype='explin'):
    t = linspace(0, tmax, 1000)
    x = odesolve(model, t)
    figure()
    plot(t, (x['ctBid'])/tBid_0.value, label='ctBid')
    plot(t, (x['mtBid'])/tBid_0.value, label='mtBid')
    plot(t, (x['cBax'])/Bax_0.value, label='cBax')
    plot(t, (x['mBax'])/Bax_0.value, label='mBax')
    #plot(t, x['metBid']/tBid_0.value, label='metBid')
    #plot(t, x['mtBid']/tBid_0.value, label='mtBid')
    #plot(t, x['mftBid']/tBid_0.value, label='mftBid')
    #plot(t, x['mfBax']/Bax_0.value, label='mfBax')
    #plot(t, x['meBax']/Bax_0.value, label='meBax')
    #plot(t, x['tBidBax']/Bax_0.value, label='tBidBax')
    #plot(t, x['tBidiBax']/Bax_0.value, label='tBidiBax')
    #plot(t, (x['iBax']+x['pBax'])/Bax_0.value, label='ipBax')
    #plot(t, (x['iBax'])/Bax_0.value, label='iBax')
    #plot(t, (x['eiBax'])/Bax_0.value, label='eiBax')
    #plot(t, (2*x['ePore'])/Bax_0.value, label='ePore')
    #plot(t, (2*x['fPore'])/Bax_0.value, label='fPore')
    #plot(t, (x['pBax'])/Bax_0.value, label='pBax')
    #plot(t, (2*(x['Bax2']+(2*x['Bax4'])))/Bax_0.value, label='Bax2')
    #plot(t, (2*x['Bax2'])/Bax_0.value, label='Bax2')
    #plot(t, (4*x['Bax4'])/Bax_0.value, label='Bax4')
    #plot(t, x['pBax']/Bax_0.value, label='pBax')
    #plot(t, x['eVes']/Vesicles_0.value, label='eVes')
    legend()
    xlabel("Time (seconds)")
    ylabel("Normalized Concentration")
Example #18
0
    def main(self):
        output = []
        ligand_array = []
        observables = self.make_model()

        write_columns(observables)
        write_model_attributes(self.model.rules, "rules")
        write_model_attributes(self.model.parameters, "parameters")
        write_model_attributes(self.model.observables, "observables")

        np.savetxt("time", self.tspan, fmt='%f')

        for ligand in self.p_ligand:
            self.model.parameters['Ls_0'].value = ligand
            ligand_array.append(ligand)

            y = odesolve(self.model, self.tspan, compiler="python")

            if len(observables) > 1:
                output_array = y[observables[0]] + y[observables[1]]
                if self.num_samples == 1:
                    np.savetxt("{0}_output".format(observables[0]), y[observables[0]], fmt='%f')
                    np.savetxt("{0}_output".format(observables[1]), y[observables[1]], fmt='%f')
                    np.savetxt("output_array", output_array, fmt='%f')

                output.append(output_array[-1])
            else:
                output_array = y[observables[0]]
                output.append(output_array[-1])

        np.savetxt("Ligand_concentrations", ligand_array, fmt='%f')
        np.savetxt("output", output, fmt='%f')
Example #19
0
def test_integrate_with_expression():
    """Ensure a model with Expressions simulates."""

    Monomer('s1')
    Monomer('s9')
    Monomer('s16')
    Monomer('s20')

    # Parameters should be able to contain s(\d+) without error
    Parameter('ks0', 2e-5)
    Parameter('ka20', 1e5)

    Initial(s9(), Parameter('s9_0', 10000))

    Observable('s1_obs', s1())
    Observable('s9_obs', s9())
    Observable('s16_obs', s16())
    Observable('s20_obs', s20())

    Expression('keff', (ks0 * ka20) / (ka20 + s9_obs))

    Rule('R1', None >> s16(), ks0)
    Rule('R2', None >> s20(), ks0)
    Rule('R3', s16() + s20() >> s16() + s1(), keff)

    time = np.linspace(0, 40)
    x = odesolve(model, time)
Example #20
0
def fig_4b():
    print("Simulating model for figure 4B...")

    t = linspace(0, 6 * 3600, 6 * 60 + 1)  # 6 hours
    x = odesolve(model, t)

    x_norm = c_[x['Bid_unbound'], x['PARP_unbound'], x['mSmac_unbound']]
    x_norm = 1 - x_norm / x_norm[
        0, :]  # gets away without max() since first values are largest

    # this is what I originally thought 4B was plotting. it's actually very close. -JLM
    #x_norm = array([x['tBid_total'], x['CPARP_total'], x['cSmac_total']]).T
    #x_norm /= x_norm.max(0)

    tp = t / 3600  # x axis as hours

    figure("Figure 4B")
    plot(tp, x_norm[:, 0], 'b', label='IC substrate (tBid)')
    plot(tp, x_norm[:, 1], 'y', label='EC substrate (cPARP)')
    plot(tp, x_norm[:, 2], 'r', label='MOMP (cytosolic Smac)')
    legend(loc='upper left', bbox_to_anchor=(0, 1)).draw_frame(False)
    xlabel('Time (hr)')
    ylabel('fraction')
    a = gca()
    a.set_ylim((-.05, 1.05))
Example #21
0
def plot_model_data():
    """Plots a simulation of the model along with the data."""
    plt.ion()
    x = odesolve(model, tspan)
    plt.plot(tspan, x['A_'])
    plt.plot(tspan, synthetic_data['A_'])
    plt.show()
Example #22
0
def synthetic_data(model, tspan, obs_list=None, sigma=0.1, seed=None):
    from pysb.integrate import odesolve

    random = numpy.random.RandomState(seed)
    ysim = odesolve(model, tspan)
    ysim_array = ysim.view().reshape(len(tspan), len(ysim.dtype))
    ysim_array *= random.randn(*ysim_array.shape) * sigma + 1
    return ysim
Example #23
0
def main():
    t = linspace(0, 60)
    y = pint.odesolve(model, t)
    print y['A_total'][-1], y['B_total'][-1]
    plot(t, y['A_total'])
    plot(t, y['B_total'])
    legend([o.name for o in model.observables])
    show()
Example #24
0
def main():
    t = linspace(0, 60)
    y = pint.odesolve(model, t)
    print y.A_total[-1], y.B_total[-1]
    plot(t, y.A_total)
    plot(t, y.B_total)
    legend([o.name for o in model.observables])
    show()
    def visualize(self, fig_path='', tspan=None, parameters=None, verbose=False):
        if verbose:
            print("Solving Simulation")

        if tspan is not None:
            self.tspan = tspan
        elif self.tspan is None:
            raise Exception("'tspan' must be defined.")

        if parameters is not None:
            # accept vector of parameter values as an argument
            if len(parameters) != len(self.model.parameters):
                raise Exception("parameters must be the same length as model.parameters")
            if not isinstance(parameters, numpy.ndarray):
                parameters = numpy.array(parameters)
        else:
            # create parameter vector from the values in the model
            parameters = numpy.array([p.value for p in self.model.parameters])

        new_pars = dict((p.name, parameters[i]) for i, p in enumerate(self.model.parameters))
        self.parameters = new_pars

        self.y = odesolve(self.model, self.tspan, self.parameters)

        if verbose:
            print("Creating graph")
        self.species_graph()
        self.sp_graph.layout(prog='dot',
                             args="-Gstart=50 -Gesep=1.5 -Gnodesep=0.8 -Gsep=0.5  -Gsplines=true -Gsize=30.75,10.75\! "
                                  "-Gratio=fill -Grankdir=LR -Gdpi=200! -Gordering=in")
        self.sp_graph.add_node('t',
                               label='time',
                               shape='oval',
                               fillcolor='white', style="filled", color="transparent",
                               fontsize="50",
                               margin="0,0",
                               pos="20,20!")

        self.edges_colors(self.y)
        self.nodes_colors(self.y)

        if os.path.exists(fig_path):
            directory = fig_path
        else:
            directory = os.getcwd() + '/visualizations'
            os.makedirs(directory)

        if verbose:
            "Generating images"
        for kx, time in enumerate(self.tspan):
            self.sp_graph.get_node('t').attr['label'] = 'time:' + ' ' + '%d' % time + ' ' + 'sec'
            map(functools.partial(change_edge_colors, graph=self.sp_graph), list(self.colors_time_edges.index),
                list(self.colors_time_edges.iloc[:, kx]))
            map(functools.partial(change_node_colors, graph=self.sp_graph), list(self.colors_time_nodes.index),
                list(self.colors_time_nodes.iloc[:, kx]))
            self.sp_graph.draw(directory + '/file' + '%03d' % kx + '.png')
Example #26
0
def plot_pores_and_efflux(model):
    t = np.linspace(0, 5000, 500)
    x = odesolve(model, t)
    plt.figure()
    avg_pores = x['pores']/model.parameters['Vesicles_0'].value
    plt.plot(t, avg_pores, 'r', label="Pores/Ves")
    plt.plot(t, 1 - np.exp(-avg_pores), 'b', label="Dye release")
    plt.legend(loc='lower right')
    plt.xlabel('Time (sec)')
    plt.show()
def add_subplot(traj, title, params):
    plt.title(title)
    plt.plot(tspan, traj, '0.5', lw=2, alpha=0.25)
    plt.plot(tspan, traj.mean(1), 'k-*', lw=3, label="Mean")
    plt.plot(tspan, traj.min(1), 'b--', lw=3, label="Minimum")
    plt.plot(tspan, traj.max(1), 'r--', lw=3, label="Maximum")
    y = odesolve(model, tspan, params)
    plt.plot(tspan, y[name], 'g--', lw=3, label="ODE")
    plt.ylim(0, 800)
    plt.xlabel('Time')
    plt.ylabel('X molecules')
Example #28
0
    def tropicalize(self, tspan=None, param_values=None, ignore=1, epsilon=1, plot_imposed_trace=False, verbose=False):
        """
        tropicalization of driver species
        :param plot_imposed_trace: Option to plot imposed trace
        :param tspan: Time span
        :param param_values: PySB model parameter values
        :param ignore: Initial time points to ignore
        :param epsilon: Order of magnitude difference between solution of ODE and imposed trace to consider species as
        passenger
        :param verbose: Verbose
        :return:
        """

        if verbose:
            print("Solving Simulation")

        if tspan is not None:
            self.tspan = tspan
        else:
            raise SimulatorException("'tspan' must be defined.")

        if param_values is not None:
            # accept vector of parameter values as an argument
            if len(param_values) != len(self.model.parameters):
                raise Exception("param_values must be the same length as model.parameters")
            if not isinstance(param_values, numpy.ndarray):
                param_values = numpy.array(param_values)
        else:
            # create parameter vector from the values in the model
            param_values = numpy.array([p.value for p in self.model.parameters])

        # convert model parameters into dictionary
        self.param_values = dict((p.name, param_values[i]) for i, p in enumerate(self.model.parameters))

        self.y = odesolve(self.model, self.tspan, self.param_values)

        if verbose:
            print("Getting Passenger species")
        if plot_imposed_trace:
            self.find_passengers(self.y[ignore:], epsilon, plot=plot_imposed_trace)
        else:
            self.find_passengers(self.y[ignore:], epsilon)

        if verbose:
            print("equation to tropicalize")
        self.equations_to_tropicalize()

        if verbose:
            print("Getting tropicalized equations")
        self.final_tropicalization()
        self.data_drivers(self.y[ignore:])
        return
Example #29
0
def simulate(f2=0.5, tmax=3000):
    t = linspace(0, tmax, 100)  
    ion()
    figure()
    model.parameters['Bid_0'].value = f2 * 1e-1
    x = odesolve(model, t)
    plot(t, x['aBax_']/model.parameters['Bax_0'].value, label='aBax')
    plot(t, x['Bid_']/model.parameters['Bid_0'].value, label='Bid free')
    plot(t, x['Bcl2_']/model.parameters['Bcl2_0'].value, label='Bcl2 free')
    plot(t, x['Bcl2_Bid_']/model.parameters['Bid_0'].value, label='Bcl2-Bid')
    plot(t, x['Bcl2_Bax_']/model.parameters['Bax_0'].value, label='Bcl2-Bax')
    legend()
    return x
Example #30
0
def run_model_ode(tmax=12000):
    from pysb.integrate import odesolve
    t = np.linspace(0, tmax, 1000)
    x = odesolve(model, t)

    ci = color_iter()
    plt.figure(1)
    # Translocation
    plt.plot(t, (x['ctBid'])/tBid_0.value, label='ctBid', color=ci.next())
    plt.plot(t, (x['mtBid'])/tBid_0.value, label='mtBid', color=ci.next())
    plt.plot(t, (x['cBax'])/Bax_0.value, label='cBax', color=ci.next())
    plt.plot(t, (x['mBax'])/Bax_0.value, label='mBax', color=ci.next())
    plt.legend()
Example #31
0
def simulate(f2=0.5, tmax=3000):
    t = linspace(0, tmax, 100)
    ion()
    figure()
    model.parameters['Bid_0'].value = f2 * 1e-1
    x = odesolve(model, t)
    plot(t, x['aBax_'] / model.parameters['Bax_0'].value, label='aBax')
    plot(t, x['Bid_'] / model.parameters['Bid_0'].value, label='Bid free')
    plot(t, x['Bcl2_'] / model.parameters['Bcl2_0'].value, label='Bcl2 free')
    plot(t, x['Bcl2_Bid_'] / model.parameters['Bid_0'].value, label='Bcl2-Bid')
    plot(t, x['Bcl2_Bax_'] / model.parameters['Bax_0'].value, label='Bcl2-Bax')
    legend()
    return x
Example #32
0
def run_model():
    t = linspace(0,200,100)
    Pep_0 = 1e-6
    L_0 = 10e-6

    figure()
    x = odesolve(model,t)

    plot(t, x['eVes']/L_0 , label='eVes')
    plot(t, x['wPep']/Pep_0, label='wPep')
    plot(t, x['lfPep']/Pep_0, label='lfPep')
    plot(t, x['lePep']/Pep_0, label='lePep')
    xlabel('Time (s)')
    ylabel('Fraction of peptide species')
    #ylabel('Percentage Dye Release')
    legend()
Example #33
0
def fig_4a():
    print("Simulating model for figure 4A...")
    t = linspace(0, 20 * 3600,
                 20 * 60 + 1)  # 20 hours, in seconds, 1 min sampling
    dt = t[1] - t[0]

    Ls_exp = Lsat / array([1, 4, 20, 100, 500])
    Td_exp = [144.2, 178.7, 236, 362.5, 656.5]
    Td_std = [32.5, 32.2, 36.4, 78.6, 171.6]
    Ts_exp = [21.6, 23.8, 27.2, 22.0, 19.0]
    Ts_std = [9.5, 9.5, 12.9, 7.7, 10.5]

    CVenv = 0.2
    # num steps was originally 40, but 15 is plenty smooth enough for screen display
    Ls = floor(logspace(1, 5, 15))

    fs = empty_like(Ls)
    Ts = empty_like(Ls)
    Td = empty_like(Ls)
    print("Scanning over %d values of L_0" % len(Ls))
    for i in range(len(Ls)):
        model.parameters['L_0'].value = Ls[i]

        print("  L_0 = %g" % Ls[i])
        x = odesolve(model, t)

        fs[i] = (x['PARP_unbound'][0] -
                 x['PARP_unbound'][-1]) / x['PARP_unbound'][0]
        dP = 60 * (x['PARP_unbound'][:-1] - x['PARP_unbound'][1:]) / (
            dt * x['PARP_unbound'][0])  # in minutes
        ttn = argmax(dP)
        dPmax = dP[ttn]
        Ts[i] = 1 / dPmax  # minutes
        Td[i] = t[ttn] / 60  # minutes

    figure("Figure 4A")
    plot(Ls / Lfactor, Td, 'g-', Ls / Lfactor, (1 - CVenv) * Td, 'g--',
         Ls / Lfactor, (1 + CVenv) * Td, 'g--')
    errorbar(Ls_exp / Lfactor, Td_exp, Td_std, None, 'go', capsize=0),
    ylabel('Td (min)'),
    xlabel('TRAIL (ng/ml)'),
    a = gca()
    a.set_xscale('log')
    a.set_xlim((min(Ls) / Lfactor, max(Ls) / Lfactor))
    a.set_ylim((0, 1000))

    model.parameters['L_0'].value = L_0_baseline
Example #34
0
def plot_from_params(params_dict):
    """Plot the model output using the given parameter value."""

    # The specific model may need to be changed here
    m1c = tBid_Bax_1c(params_dict=params_dict)
    m1c.build_model2()
    model = m1c.model

    plt.ion()

    plt.plot(tspan, ydata_norm)
    output = odesolve(model, tspan)
    #output_array = output.view().reshape(len(tspan), len(output.dtype))
    iBax = 2*output['Bax2'] + 4*output['Bax4']
    iBax_norm = iBax / max(iBax)
    plt.plot(tspan, iBax_norm[:])

    plt.show()
Example #35
0
def figure_2a():
    """Reproduce the dose-response in Figure 2a of [Chen2007febs]_.

    Despite the fact that the PySB versions of the two models exactly reproduce
    the ODEs given in the supplement of the Chen et al. paper, this function
    does not quantitatively reproduce the plots in Figure 2. The steady-state
    output of both models is slightly higher than shown in the figure: for
    example, the steady-state fraction of oligomerized Bax produced by the
    PySB direct model for 0 input stimulus is 0.85, whereas the intercept shown
    in the plot is clearly lower than this. The same is true for the indirect
    model.

    The reasons for this are not clear, as the parameter values and ODE
    structure have been verified to be identical. There appears to be a
    discrepancy in the way that the dose-response curves are calculated,
    possibly in the timepoint used for sampling the steady-state value.
    """

    f_range = linspace(0, 20, 50)
    t = linspace(0, 50000, 1000)
    ion()
    figure()

    for model in [direct, indirect]:
        ss_Bax4_vals = []

        for f in f_range:
            if model is direct:
                model.parameters['Bid_0'].value = 1 + (f * 1)
                model.parameters['Bad_0'].value = 2 + (f * 2)
            else:
                model.parameters['Bid_0'].value = 3 + (f * 3)

            # Calculate the fraction of oligomerized Bax
            x = odesolve(model, t)
            Bax_frac = (4*x['Bax4_'])/model.parameters['Bax_0'].value
            ss_Bax4_val = Bax_frac[-1]
            ss_Bax4_vals.append(ss_Bax4_val)

        plot(f_range, ss_Bax4_vals, label='DM' if model is direct else 'IM')
        ylim([0.75, 1])

    legend(loc='lower right')
Example #36
0
def figure_2a():
    """Reproduce the dose-response in Figure 2a of [Chen2007febs]_.

    Despite the fact that the PySB versions of the two models exactly reproduce
    the ODEs given in the supplement of the Chen et al. paper, this function
    does not quantitatively reproduce the plots in Figure 2. The steady-state
    output of both models is slightly higher than shown in the figure: for
    example, the steady-state fraction of oligomerized Bax produced by the
    PySB direct model for 0 input stimulus is 0.85, whereas the intercept shown
    in the plot is clearly lower than this. The same is true for the indirect
    model.

    The reasons for this are not clear, as the parameter values and ODE
    structure have been verified to be identical. There appears to be a
    discrepancy in the way that the dose-response curves are calculated,
    possibly in the timepoint used for sampling the steady-state value.
    """

    f_range = linspace(0, 20, 50)
    t = linspace(0, 50000, 1000)
    ion()
    figure()

    for model in [direct, indirect]:
        ss_Bax4_vals = []

        for f in f_range:
            if model is direct:
                model.parameters['Bid_0'].value = 1 + (f * 1)
                model.parameters['Bad_0'].value = 2 + (f * 2)
            else:
                model.parameters['Bid_0'].value = 3 + (f * 3)

            # Calculate the fraction of oligomerized Bax
            x = odesolve(model, t)
            Bax_frac = (4 * x['Bax4_']) / model.parameters['Bax_0'].value
            ss_Bax4_val = Bax_frac[-1]
            ss_Bax4_vals.append(ss_Bax4_val)

        plot(f_range, ss_Bax4_vals, label='DM' if model is direct else 'IM')
        ylim([0.75, 1])

    legend(loc='lower right')
Example #37
0
def fig_4a():
    print("Simulating model for figure 4A...")
    t = linspace(0, 20*3600, 20*60+1)  # 20 hours, in seconds, 1 min sampling
    dt = t[1] - t[0]

    Ls_exp = Lsat / array([1, 4, 20, 100, 500])
    Td_exp = [144.2, 178.7, 236,   362.5, 656.5]
    Td_std = [32.5,   32.2,  36.4,  78.6, 171.6]
    Ts_exp = [21.6,   23.8,  27.2,  22.0,  19.0]
    Ts_std = [9.5,     9.5,  12.9,   7.7,  10.5]

    CVenv = 0.2
    # num steps was originally 40, but 15 is plenty smooth enough for screen display
    Ls = floor(logspace(1,5,15)) 

    fs = empty_like(Ls)
    Ts = empty_like(Ls)
    Td = empty_like(Ls)
    print("Scanning over %d values of L_0" % len(Ls))
    for i in range(len(Ls)):
        model.parameters['L_0'].value = Ls[i]

        print("  L_0 = %g" % Ls[i])
        x = odesolve(model, t)

        fs[i] = (x['PARP_unbound'][0] - x['PARP_unbound'][-1]) / x['PARP_unbound'][0]
        dP = 60 * (x['PARP_unbound'][:-1] - x['PARP_unbound'][1:]) / (dt * x['PARP_unbound'][0])  # in minutes
        ttn = argmax(dP)
        dPmax = dP[ttn]
        Ts[i] = 1 / dPmax  # minutes
        Td[i] = t[ttn] / 60  # minutes

    figure("Figure 4A")
    plot(Ls/Lfactor, Td, 'g-', Ls/Lfactor, (1-CVenv)*Td, 'g--', Ls/Lfactor, (1+CVenv)*Td, 'g--')
    errorbar(Ls_exp/Lfactor, Td_exp, Td_std, None, 'go', capsize=0),
    ylabel('Td (min)'),
    xlabel('TRAIL (ng/ml)'),
    a = gca()
    a.set_xscale('log')
    a.set_xlim((min(Ls) / Lfactor, max(Ls) / Lfactor))
    a.set_ylim((0, 1000))

    model.parameters['L_0'].value = L_0_baseline
Example #38
0
def fig_4b():
    t = linspace(0, 6*3600, 6*60+1)  # 6 hours
    x = odesolve(model, t)

    x_norm = c_[x['Bid_unbound'], x['PARP_unbound'], x['mSmac_unbound']]
    x_norm = 1 - x_norm / x_norm[0, :]  # gets away without max() since first values are largest

    # this is what I originally thought 4B was plotting.  oddly it's very close.
    #x_norm = array([x['tBid_total'], x['CPARP_total'], x['cSmac_total']]).T
    #x_norm /= x_norm.max(0)

    tp = t / 3600  # x axis as hours

    figure()
    plot(tp, x_norm[:,0], 'b', label='IC substrate (tBid)')
    plot(tp, x_norm[:,1], 'y', label='EC substrate (cPARP)')
    plot(tp, x_norm[:,2], 'r', label='MOMP (cytosolic Smac)')
    legend(loc='upper left', bbox_to_anchor=(0,1)).draw_frame(False)
    xlabel('Time (hr)')
    ylabel('fraction')
    a = gca()
    a.set_ylim((-.05, 1.05))
Example #39
0
    def sensitivity(self,
                    tspan=None,
                    parameters_ref=None,
                    sp_SA=None,
                    sampling_method='saltelli',
                    analyze_method='sobol',
                    N=1,
                    verbose=True):

        ana_meth = importlib.import_module('SALib.analyze.%s' % analyze_method)

        if tspan is not None:
            self.tspan = tspan
        elif self.tspan is None:
            raise Exception("'time t' must be defined.")

        if sp_SA is None:
            raise Exception(
                "A species to do the sensitivity analysis on must be defined")
        if sp_SA not in [
                str(sp) for sp in self.model.species
        ] and sp_SA not in [str(obs.name) for obs in self.model.observables]:
            raise Exception("Species is not in model species")

        ref = odesolve(self.model, self.tspan, param_values=parameters_ref)

        if verbose: print "Getting parameters information"
        self.pars_info(parameters_ref, sampling_method=sampling_method, N=N)

        if verbose: print "Simulating with parameters from sampling"
        p = multiprocessing.Pool(2)
        func = partial(self.sim_model, sp_SA=sp_SA)
        self.sim = p.map(func, self.param_sets)
        self.output = [sum((r - ref[sp_SA])**2) for r in self.sim]

        if verbose: print "Sensitivity analysis"
        self.sa_result = ana_meth.analyze(self.problem,
                                          numpy.array(self.output),
                                          print_to_console=True)
Example #40
0
    def main(self):
        sos_array = []
        output = []
        observables = self.make_model()

        write_columns(observables)
        write_model_attributes(model.rules, "rules")
        write_model_attributes(model.parameters, "parameters")
        write_model_attributes(model.observables, "observables")

        np.savetxt("time", self.tspan, fmt='%f')

        for sos in self.sos:
            model.parameters['Sos_0'].value = sos
            y = odesolve(model, self.tspan, compiler="python")

            sos_array.append(sos)
            # print(y[observables[0]][-1])
            output.append(y[observables[0]][-1])

        df = pd.DataFrame({'Sos': sos_array, 'RasGTP': output})
        df.to_csv("./sos_rasgtp", sep='\t')
    def main(self):
        output_array = []
        ligand_array = []
        ls_ss_array = []
        r_ss_array = []
        lf_ss_array = []

        self.make_model()

        write_model_attributes(self.model.rules, "rules")
        write_model_attributes(self.model.parameters, "parameters")
        write_model_attributes(self.model.observables, "observables")

        np.savetxt("time", self.tspan, fmt='%f')

        for ligand in self.p_ligand:
            self.model.parameters['Ls_0'].value = ligand
            ligand_array.append(ligand)

            y = odesolve(self.model, self.tspan, compiler="python")

            output = y['O_SP']
            ls_ss = y['O_Ls']
            r_ss = y['O_R']

            if self.self_foreign:
                lf_ss = y['O_Lf']
                lf_ss_array.append(lf_ss[-1])

            output_array.append(output[-1])
            ls_ss_array.append(ls_ss[-1])
            r_ss_array.append(r_ss[-1])

        np.savetxt("Ligand_concentrations", ligand_array, fmt='%f')
        np.savetxt("output", output_array, fmt='%f')
        np.savetxt("ls_ss", ls_ss_array, fmt='%f')
        np.savetxt("lf_ss", lf_ss_array, fmt='%f')
        np.savetxt("r_ss", r_ss_array, fmt='%f')
    def visualize(self, fig_path='', tspan=None, parameters=None, verbose=False):
        if verbose:
            print("Solving Simulation")

        if tspan is not None:
            self.tspan = tspan
        elif self.tspan is None:
            raise Exception("'tspan' must be defined.")

        if parameters is not None:
            # accept vector of parameter values as an argument
            if len(parameters) != len(self.model.parameters):
                raise Exception("parameters must be the same length as model.parameters")
            if not isinstance(parameters, numpy.ndarray):
                parameters = numpy.array(parameters)
        else:
            # create parameter vector from the values in the model
            parameters = numpy.array([p.value for p in self.model.parameters])

        new_pars = dict((p.name, parameters[i]) for i, p in enumerate(self.model.parameters))
        self.parameters = new_pars

        self.y = odesolve(self.model, self.tspan, self.parameters)

        if verbose:
            print("Creating graph")
        self.species_graph()

        self.sp_graph.add_node('t',
                               label='time',
                               shape='oval',
                               fillcolor='white', style="filled", color="transparent",
                               fontsize="50",
                               margin="0,0",
                               pos="20,20!")
        nx.write_gexf(self.sp_graph, '/home/oscar/Desktop/gexf_try1.gexf', version="1.2draft")
Example #43
0
def howells_figure2ab(model):
    """Reproduce Figure 2a/b from Howells (2011)."""
    model.parameters['Bcl2_0'].value = 0.1  # Total Bcl2
    model.parameters['Bax_0'].value = 0.2   # Total Bax
    model.parameters['Bid_0'].value = 0.018 # Total tBid
    model.parameters['Bad_0'].value = 0.025 # Total Bad
    Bcl2_free_0 = Parameter('Bcl2_free_0',
            model.parameters['Bcl2_0'].value -
            model.parameters['Bid_0'].value, _export=False) # free Bcl2
    model.add_component(Bcl2_free_0)

    # Reset initial conditions
    model.initial_conditions = []
    c = model.all_components()
    # pBad1433_0 = total Bad
    model.initial(c['Bad'](bf=None, state='C', serine='B'), c['Bad_0'])
    # Bax_inac_0 = total Bax
    model.initial(c['Bax'](bf=None, s1=None, s2=None, state='C'),
                       c['Bax_0'])
    # tBid:Bcl2_0 = total tBid
    model.initial(c['Bid'](state='T', bf=1) % c['Bcl2'](bf=1),
                       c['Bid_0'])
    # Bcl2_free = Bcl2_0 - tBid_0
    model.initial(c['Bcl2'](bf=None), Bcl2_free_0)

    t = np.linspace(0, 300*60, 101)
    x = odesolve(model, t)
    plt.figure()
    plt.ion()
    t = t / 60
    plt.plot(t, x['Bax4_'], label='Bak_poly')
    plt.plot(t, x['Bcl2_'], label='Bcl2')
    plt.plot(t, x['pBad1433_'], label='pBad:14-3-3')
    plt.plot(t, x['Bad_Bcl2_'], label='Bad:Bcl2')
    plt.plot(t, x['Bax_Bcl2_'], label='Bax:Bcl2')
    plt.legend(loc='upper right')
Example #44
0
def plot_tbid_titration(model):
    plt.ion()
    bid_concs = np.logspace(0, 4, 40)
    t = np.linspace(0, 10000, 1000)
    initial_rates = []

    plt.figure()
    for bid_conc in bid_concs:
        model.parameters['tBid_0'].value = bid_conc
        x = odesolve(model, t)
        avg_pores = x['pores']/model.parameters['Vesicles_0'].value
        plt.plot(t, avg_pores)
        initial_rate = avg_pores[10] / t[10]
        initial_rates.append(initial_rate)
    initial_rates = np.array(initial_rates)
    plt.title('Avg. pores with Bid titration')
    plt.xlabel('Time')
    plt.ylabel('Avg. pores per liposome')
    plt.show()

    # Run a regression against the points and calculate the initial_rate
    log_concs = np.log(bid_concs)
    log_initial_rates = np.log(initial_rates)
    (slope, intercept) = np.polyfit(log_concs, log_initial_rates, 1)
    fitted_initial_rates = (slope * log_concs) + intercept

    # Figure with slope and intercept info
    plt.figure()
    plt.figtext(0.2, 0.8, 'Slope: %.4f' % slope)
    plt.figtext(0.2, 0.75, 'Intercept: %.4f' % intercept)
    plt.plot(log_concs, log_initial_rates, 'b')
    plt.plot(log_concs, fitted_initial_rates, 'r')
    plt.xlabel('Log([Bid])')
    plt.ylabel('Log(V_i)')
    plt.title("Log-Log plot of initial rate vs. Bid conc")
    plt.show()
Example #45
0
from .erbb_exec import model
import numpy as np
from pysb.integrate import odesolve

t = np.linspace(0, 2000, num=2000)

yout = odesolve(model, t)
Example #46
0
from simple_reaction_pyurdme import model
from pysb_pyurdme import run_pyurdme
import numpy as np
import matplotlib.pyplot as plt
import pyurdme
from pysb.integrate import odesolve

model.diffusivities = [('E(b=None)', 0.001), ('P(b=None)', 0.2)]

initial_dist = {
    'E(b=None)': ['set_initial_condition_place_near', [0.5, 0.5]],
    'S(b=None)': ['set_initial_condition_place_near', [1, 0.5]]
}

mesh = pyurdme.URDMEMesh.generate_unit_square_mesh(40, 40)

tspan = np.linspace(0, 5, 500)
y = odesolve(model, tspan)
# plt.plot(tspan,y['__s2'])
# plt.show()
result = run_pyurdme(model, tspan, mesh, initial_dist)
Example #47
0
    y['OBS_p16'] /= max(y['OBS_p16']) if max(y['OBS_p16']) > 0.0 else 1
    y['OBS_Rb'] /= max(y['OBS_Rb']) if max(y['OBS_Rb']) > 0.0 else 1
    y['OBS_CycD_CDK46'] /= max(
        y['OBS_CycD_CDK46']) if max(y['OBS_CycD_CDK46']) > 0.0 else 1


t = linspace(0, 3000, 300)

vol = 1e-19
# ** Set No Damage **
# set_volume(vol)

Na_V = constants.N_A * vol

set_dna_damage(0.0)  # For volume, * Na_V
y = odesolve(model, t, verbose=True, rtol=1e-15, atol=1e-15)
# set_dna_damage(0.0 * Na_V) # For volume, * Na_V
# y = run_ssa(model,t,verbose=True, rtol = 1e-15, atol = 1e-15)
normalize_output(y)

pl.figure()
for obs in ["OBS_p27", "OBS_E2F", "OBS_CycE", "OBS_CycA"]:
    pl.plot(t, y[obs], label=re.match(r"OBS_(\w+)", obs).group(1), linewidth=3)
pl.legend(loc=0, prop={'size': 16})
pl.ylim(ymax=1.2)
pl.xlabel("Time (arbitrary units)", fontsize=22)
pl.ylabel("Protein Level", fontsize=22)
pl.xticks(fontsize=18)
pl.yticks(fontsize=18)
pl.title("Protein Dynamics (No DNA Damage)", fontsize=22)
pl.savefig("G1_S Cell Cycle No DNA Damage1.png", format="png")
Example #48
0
#!/usr/bin/env python
"""Simulate the bax_pore model and plot the results."""

from __future__ import print_function
from pylab import *
from pysb.integrate import odesolve

from bax_pore import model

t = linspace(0, 100)
print("Simulating...")
x = odesolve(model, t)

p = plot(t, c_[x['BAX4'], x['BAX4_inh']])
figlegend(p, ['BAX4', 'BAX4_inh'], 'upper left')
show()
Example #49
0
Parameter('k_CD44_div', 0.3)
Parameter('k_CD44_die', 0.2)
Rule('CD44_div', CD44() >> CD44() + CD44(), k_CD44_div)
Rule('CD44_die', CD44() >> None, k_CD44_die)

Parameter('k_TPC_diff_Hes1', 0.5)
Parameter('k_TPC_diff_CD44', 0.1)
Rule('TPC_diff_Hes1', TPC() >> Hes1(), k_TPC_diff_Hes1)
Rule('TPC_diff_CD44', TPC() >> CD44(), k_TPC_diff_CD44)

###########################################################################

# In vivo tumors have on average 50% TPCs, 20% Hes1 cells, 5% CD44+ cells, and 25% unknown cell types.

tspan = np.linspace(0, 10, 101)
x = odesolve(model, tspan, verbose=True)
# x = run_ssa(model, tspan[-1], len(tspan)-1, verbose=True)

cell_tot = x['TPC_tot'] + x['Hes1_tot'] + x['CD44_tot']

print('TPC frac:   %g (%g)' % (x['TPC_tot'][-1] / cell_tot[-1], 50 / 80))
print('Hes1+ frac: %g (%g)' % (x['Hes1_tot'][-1] / cell_tot[-1], 25 / 80))
print('CD44+ frac: %g (%g)' % (x['CD44_tot'][-1] / cell_tot[-1], 5 / 80))

plt.figure()
plt.plot(tspan, x['TPC_tot'], lw=3, color='b', label='TPC')
plt.plot(tspan, x['Hes1_tot'], lw=3, color='g', label='Hes1+')
plt.plot(tspan, x['CD44_tot'], lw=3, color='r', label='CD44+')
# plt.annotate("A" , (0.2, 0.8), xycoords='axes fraction', fontsize=24)
plt.xlabel('time (d)', fontsize=16)
plt.ylabel('cell count', fontsize=16)
Example #50
0
Monomer('L', ['s'])
Monomer('R', ['s'])

# Declare the parameters
Parameter('L_0', 100)
Parameter('R_0', 200)
Parameter('kf', 1e-3)
Parameter('kr', 1e-3)

# Declare the initial conditions
Initial(L(s=None), L_0)
Initial(R(s=None), R_0)

# Declare the binding rule
Rule('L_binds_R', L(s=None) + R(s=None) <> L(s=1) % R(s=1), kf, kr)

# Observe the complex
Observable('LR', L(s=1) % R(s=1))

if __name__ == '__main__':
    print __doc__
    # Simulate the model through 40 seconds
    time = linspace(0, 40, 100)
    print "Simulating..."
    x = odesolve(model, time)
    # Plot the trajectory of LR
    plot(time, x['LR'])
    xlabel('Time (seconds)')
    ylabel('Amount of LR')
    show()
Example #51
0
# Integrates Robertson's example, as defined in robertson.py, and
# plots the trajectories.

from pylab import *
from pysb.integrate import odesolve

from robertson import model

# solve from t=0 to t=40
t = linspace(0, 40)

yrec = odesolve(model, t, rtol=1e-4, atol=[1e-8, 1e-14, 1e-6])

# build a normal array with the values from the recarray
y = yrec.view().reshape(len(yrec), len(yrec[0]))
# plot trajectories, each normalized to the range 0-1
p = plot(t, y / y.max(0))
figlegend(p, ['y1', 'y2', 'y3'], 'upper right')
show()
Example #52
0
#!/usr/bin/env python

from pysb.integrate import odesolve
from pylab import linspace, plot, legend, show

from kinase_cascade import model

tspan = linspace(0, 1200)
print "Simulating..."
yfull = odesolve(model, tspan)
plot(tspan, yfull['ppMEK'], label='ppMEK')
plot(tspan, yfull['ppERK'], label='ppERK')
legend(loc='upper left')
show()
Example #53
0
from pysb.examples.robertson import model
from pysb.integrate import odesolve
import numpy
import matplotlib.pyplot as plt
import sys

scenario = 2
if len(sys.argv) > 1:
    scenario = int(sys.argv[1])

seed = 2
random = numpy.random.RandomState(seed)
sigma = 0.1
ntimes = 20
tspan = numpy.linspace(0, 40, ntimes)
ysim = odesolve(model, tspan)
ysim_array = ysim.view(float).reshape(len(ysim), -1)
yspecies = ysim_array[:, :len(model.species)]
ydata = yspecies * (random.randn(*yspecies.shape) * sigma + 1)
ysim_max = yspecies.max(0)
ydata_norm = ydata / ysim_max


def likelihood(mcmc, position):
    yout = mcmc.simulate(position)
    yout_norm = yout / ysim_max
    if scenario == 3:
        # fit to "perfect" data
        ret = numpy.sum((yspecies / ysim_max - yout_norm)**2 / (2 * sigma**2))
    else:
        # fit to noisy data
Example #54
0
import G1_S_v1 as m
import pylab as pl
from pysb.integrate import odesolve
from sympy import sympify

# Set to False to plot I, Mdm2, p21, p53
cyclins = True

#################################
## Force PySB to generate ODEs ##
#################################
t = pl.linspace(0,3000, num = 300)
y = odesolve(m.model,t)

###############
## Overrides ##
###############
_source = "s30"
#m.model.odes[24] = sympify("k60*s32 + k61*s28 - k62*s24 - k73*s24*s25*s28 + k73*s24*s25*s31 - k74*s24*s25")
m.model.odes[25] = sympify("k63*" + _source + " + k66*s27**9/(k65**9 + s27**9) - k64*s25") #!!!
m.model.odes[27] = sympify("(k70*s24*s28)/(1 + k71*s24*s25) - k67*s27") #!!!
m.model.odes[28] = sympify("-k72*s28") #!!!
#m.model.odes[18] = sympify("k40*s32 + k41/(1 + k42*s23) - k43*s18 - k44*s18*s5")
#m.model.odes[23] = sympify("-k45*s21*s23 + k55*s22 + k56*s32 - k57*s23 + k58/(1 + k59*s18)")

###########
## Solve ##
###########
t = pl.linspace(0,3000, num = 300)
y = odesolve(m.model,t)
Example #55
0
    if m == 'tyson':
        from pysb.examples.tyson_oscillator import model
        tspan = np.linspace(0, 100, 100)
    elif m == 'ras':
        from ras_amp_pka import model
        tspan = np.linspace(0, 1500, 100)
    elif m == 'earm':
        from earm.lopez_embedded import model
        tspan = np.linspace(0, 20000, 100)

    colors = cm.rainbow(np.linspace(0, 1, len(model.observables)))

    x = odesolve(model,
                 tspan,
                 atol=1e-6,
                 rtol=1e-6,
                 nsteps=20000,
                 verbose=True)

    for i, obs in enumerate(model.observables):
        ax.plot(tspan,
                x[obs.name] / np.nanmax(x[obs.name]),
                lw=3,
                label=obs.name.lstrip('obs_'),
                c=colors[i])

    if m == 'ras':
        ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5), fontsize=8)
    else:
        ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))
Example #56
0
import pickle

from anrm import merge
from pysb.integrate import odesolve

from anrm.irvin_anrm_experiment_10 import model

#Edit parameters
new_params = pickle.load(open('TNFa_H2_Calibrated_Params_exp10.pkl'))
param_edits = merge.Edit_Parameters(model.parameters, new_params)
merged_parameters = param_edits.merged_parameters

pysb.core.Model('m')

m.monomers = model.monomers
m.compartments = model.compartments
m.parameters = merged_parameters
m.rules = model.rules
m.observables = model.observables
m.initial_conditions = model.initial_conditions

t = np.linspace(0, 20000, 100)
yout = odesolve(m, t)

p.ion()
p.plot(t, yout['Obs_cPARP'], label='Cleaved Parp')
p.plot(t, yout['Obs_MLKL'], label='MLKL')

p.xlabel('time [sec]')
p.ylabel('PARP concentration [molecules per cell]')
p.legend()
Example #57
0
Rule('A_D', A(d=None) + D(s=None) <> A(d=1) % D(s=1), k_A_D, l_A_D)
Rule('B_D', B(d=None) + D(s=None) <> B(d=1) % D(s=1), k_B_D, l_B_D)

Initial(A(d=None), Parameter('A_0', 1))
Initial(B(d=None), Parameter('B_0', 1.1))
Initial(D(s=None), Parameter('D_0', 1))

Observable('tA', A(d=None))
Observable('tB', B(d=None))
Observable('tD', D(s=None))
Observable('tAD', A(d=1) % D(s=1))
Observable('tBD', B(d=1) % D(s=1))

t = np.linspace(0, 3, 10000)
z1 = odesolve(
    model,
    t)  #, integrator='vode', with_jacobian=True, rtol=1e-20, atol=1e-20)
pl.figure()
pl.xlim(0, 3)
pl.ylim(0, 1)
pl.title('A_0=1,B_0=1.1,D_0=1 with k_ad, 0.4,>k_bd, 0.3')
pl.plot(t, z1['tA'], label="A")
pl.plot(t, z1['tB'], label="B")
pl.plot(t, z1['tD'], label="D")
pl.plot(t, z1['tAD'], label="AD")
pl.plot(t, z1['tBD'], label="BD")
pl.legend()
pl.xlabel("Time")
pl.ylabel("Concentrations")
pl.show()
from pysb import *
from pysb.integrate import odesolve
from nbd_model import model

params_dict = { }

#tspan = nbd.time_c62
nbd_avgs, nbd_stds = nbd.calc_norm_avg_std()
#ydata_norm = nbd_avgs[1] # NBD_62c 

# Plot data curves
plt.ion()
plt.plot(nbd.time_other, nbd_avgs[0], 'r,', label='c3 data', alpha=0.2)
plt.plot(nbd.time_c62, nbd_avgs[1], 'g,', label='c62 data', alpha=0.2)
plt.plot(nbd.time_other, nbd_avgs[2], 'b,', label='c120 data', alpha=0.2)
plt.plot(nbd.time_other, nbd_avgs[3], 'm,', label='c122 data', alpha=0.2)
plt.plot(nbd.time_other, nbd_avgs[4], 'k,', label='c126 data', alpha=0.2)

# Plot model curves
tspan = nbd.time_other
x = odesolve(model, tspan)
plt.plot(tspan, x['Baxc3'] * model.parameters['c3_scaling'].value,
         'r', label='c3 model')
plt.plot(tspan, x['Baxc62'], 'g', label='c62 model')
plt.plot(tspan, x['Baxc120'], 'b', label='c120 model')
plt.plot(tspan, x['Baxc122'], 'm', label='c122 model')
plt.plot(tspan, x['Baxc126'], 'k', label='c126 model')
plt.show()
plt.legend(loc='lower right')

Example #59
0
 def sim_model(self, par, sp_SA=None):
     y = odesolve(self.model, self.tspan, par)
     return y[sp_SA]