Esempio n. 1
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)

    solver = Solver(model, time)
    solver.run()

    assert solver.yexpr_view.shape == (len(time),
                                       len(model.expressions_dynamic()))
    assert solver.yobs_view.shape == (len(time), len(model.observables))
Esempio n. 2
0
 def test_lsoda_jac_solver_run(self):
     """Test lsoda and analytic jacobian."""
     solver_lsoda_jac = Solver(self.model,
                               self.time,
                               integrator='lsoda',
                               use_analytic_jacobian=True)
     solver_lsoda_jac.run()
Esempio n. 3
0
def test_one_cpt_lipo_sites_comparison_tBid():
    """Simulation of one_cpt and the lipo_sites model with tBid_0 numbers
    of sites per liposome should give the same result."""
    sites_per_liposome_list = [10., 1000.]
    for test_ix, sites_per_liposome in enumerate(sites_per_liposome_list):
        params_dict = {'tBid_0': 10., 'sites_per_liposome': sites_per_liposome}
        ocb = one_cpt.Builder(params_dict=params_dict)
        lsb = lipo_sites.Builder(params_dict=params_dict)
        t = np.linspace(0, 100, 1000)
        y_list = []
        for builder in (ocb, lsb):
            builder.translocate_tBid()
            sol = Solver(builder.model, t)
            sol.run()
            y_list.append(sol.yobs['mtBid'])

        if test_ix == 0:
            ok_(not np.allclose(y_list[0], y_list[1], atol=1.5e-3),
                'one_cpt and lipo_sites simulations should be different '
                'under these conditions.')
        elif test_ix == 1:
            # The two arrays have a maximal absolute difference of 1.5e-3
            ok_(np.allclose(y_list[0], y_list[1], atol=1.5e-3),
                'one_cpt and lipo_sites simulations should be approximately '
                'equal under these conditions.')
        else:
            raise Exception('Unexpected test index.')
Esempio n. 4
0
def test_lipo_sites_builder():
    """lipo_sites_builder builds and runs without error."""
    lsb = lipo_sites.Builder()
    lsb.translocate_Bax()
    t = np.linspace(0, 100)
    sol = Solver(lsb.model, t)
    sol.run()
Esempio n. 5
0
def visualize():
    for ACC_NO in ACC_NOs:
        dot_r = render_reactions.run(models[ACC_NO])
        dotfile_r = open('model_reactions-' + ACC_NO + '.dot', 'w')
        dotfile_r.write(dot_r)
        dotfile_r.close()
        system('dot -T pdf model_reactions-' + ACC_NO +
               '.dot -o model_reactions-' + ACC_NO + '.pdf')
        dot_s = render_species.run(models[ACC_NO])
        dotfile_s = open('model_species-' + ACC_NO + '.dot', 'w')
        dotfile_s.write(dot_s)
        dotfile_s.close()
        system('ccomps -x model_species-' + ACC_NO +
               '.dot | dot | gvpack -m0 | neato -n2 -T pdf -o model_species-' +
               ACC_NO + '.pdf')
        # Run the simulation
        solver = Solver(models[ACC_NO], t)
        solver.run()
        yout = solver.yobs
        # Plot simulation results for the observables in the model
        pl.ion()
        pl.figure()
        for observ in outputs[ACC_NO]:
            pl.plot(t, yout[observ], label=observ)
        pl.legend()
        pl.xlabel("Time (minutes)")
        pl.ylabel("Distribution of radioactive iron/body compartments")
        pl.savefig('model_results-' + ACC_NO + '.png')
        pl.clf()
Esempio n. 6
0
def scatter_plot():
    n = 100
    mod = models['adequate']
    for param in param_bounds.keys():
        prob = {
            'num_vars': 1,
            'names': [param],
            'bounds': [param_bounds[param]]
        }
        par_sets = [p[0] for p in sampling_method.sample(prob, n)]
        solver = Solver(mod, t)
        res_sets = {out: [] for out in outputs['adequate']}
        for par_set in par_sets:
            pars = {p.name: p.value for p in mod.parameters}
            pars[param] = par_set
            solver.run(pars)
            for out in outputs['adequate']:
                res_sets[out].append(solver.yobs[out][-1])  # last result
        # Plot simulation results for the observables in the model
        pl.ion()
        pl.figure(figsize=(8, 8))
        for res in res_sets.keys():
            pl.scatter(par_sets, res_sets[res], label=res)
        pl.legend()
        pl.xlabel(param)
        pl.ylabel("Outputs")
        pl.savefig('scatterplots/' + param + '.png', dpi=300)
        pl.clf()
Esempio n. 7
0
 def test_vode_jac_solver_run(self):
     """Test vode and analytic jacobian."""
     solver_vode_jac = Solver(self.model,
                              self.time,
                              integrator='vode',
                              use_analytic_jacobian=True)
     solver_vode_jac.run()
Esempio n. 8
0
def run_query(model, query):
    m = re.match('Is the amount of (.+) ([^ ]+) in time?', query)
    target_str = m.groups()[0]
    pattern_str = m.groups()[1]

    ts = numpy.linspace(0, 100, 10)
    solver = Solver(model, ts)
    solver.run()

    if target_str == 'A-B complex':
        target = 'AB'

    if target_str == 'A':
        target = 'A'

    for i, a in enumerate(solver.yobs[target]):
        solver.yobs[target][i] = 1 if a > 50 else 0

    if pattern_str == 'sustained':
        fstr = sustained_formula(target)
    elif pattern_str == 'transient':
        fstr = transient_formula(target)
    elif pattern_str == 'unchanged':
        fstr = noact_formula(target)

    print '\n\n'
    print '-----------'
    print query
    print 'LTL formula: %s' % fstr
    mc = ModelChecker(fstr, solver.yobs)
    print solver.yobs[target]
    print 'Result:', mc.truth
    print '-----------'
Esempio n. 9
0
    def plot_func_single(self, x, data_ix, ax=None, alpha=1.0):
        x = 10 ** x

        s = Solver(self.builder.model, self.time)
        # Set the parameters appropriately for the simulation:
        # Iterate over the globally fit parameters
        for g_ix, p in enumerate(self.builder.global_params):
            p.value = x[g_ix]
        # Iterate over the locally fit parameters
        for l_ix, p in enumerate(self.builder.local_params):
            ix_offset = len(self.builder.global_params) + \
                        data_ix * len(self.builder.local_params)
            p.value = x[l_ix + ix_offset]
        # Now fill in the initial condition parameters
        for p_name, values in self.params.iteritems():
            p = self.builder.model.parameters[p_name]
            p.value = values[data_ix]
        # Now run the simulation
        s.run()
        # Plot the observable
        if ax is None:
            ax = plt.gca()
        if self.use_expr:
            ax.plot(self.time, s.yexpr[self.obs_name], color='r',
                     alpha=alpha)
        else:
            ax.plot(self.time, s.yobs[self.obs_name], color='r',
                     alpha=alpha)
Esempio n. 10
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)

    solver = Solver(model, time)
    solver.run()

    assert solver.yexpr_view.shape == (len(time),
                                       len(model.expressions_dynamic()))
    assert solver.yobs_view.shape == (len(time), len(model.observables))
Esempio n. 11
0
def plot_liposome_titration_insertion_kinetics(model):
    """Plot the insertion kinetics of Bax over a liposome titration."""
    lipo_concs = np.logspace(-2, 2, 40)
    t = np.linspace(0, 12000, 100)

    fmax_list = []
    k_list = []

    for lipo_conc in lipo_concs:
        model.parameters['Vesicles_0'].value = lipo_conc

        # Get the SS mBax value
        #b_trans.model.parameters['Vesicles_0'].value = lipo_conc
        #s = Solver(b_trans.model, t)
        #s.run()
        #max_mBax = s.yobs['mBax'][-1]

        # Get the iBax curve
        s = Solver(model, t)
        s.run()
        iBax = s.yobs['iBax'] / model.parameters['Bax_0'].value
        plt.plot(t, iBax, 'r')

        # Fit to single exponential
        fmax = fitting.Parameter(0.9)
        k = fitting.Parameter(0.01)
        def single_exp(t):
            return (fmax() * (1 - np.exp(-k()*t)))
        fitting.fit(single_exp, [fmax, k], iBax, t)
        plt.plot(t, single_exp(t), 'b')

        fmax_list.append(fmax())
        k_list.append(k())

    plt.title('Inserted Bax with liposome titration')
    plt.xlabel('Time')
    plt.ylabel('Fraction of inserted Bax')
    plt.show()

    # Make plots of k and fmax as a function of lipo concentration
    fmax_list = np.array(fmax_list)
    k_list = np.array(k_list)

    # k
    plt.figure()
    plt.plot(lipo_concs, k_list, 'ro')
    plt.xlabel('Liposomes (nM)')
    plt.ylabel('$k$')
    plt.title("$k$ vs. Liposome conc")
    plt.ylim([0, 0.0020])
    plt.show()

    # Fmax 
    plt.figure()
    plt.plot(lipo_concs, fmax_list, 'ro')
    plt.xlabel('Liposomes (nM)')
    plt.ylabel('$F_{max}$')
    plt.title("$F_{max}$ vs. Liposome conc")
    plt.show()
def lipo_titration(builder, ax):
    t = np.linspace(0, tmax, 1e3)
    sol = Solver(bd.model, t)
    lipo_concs = np.logspace(-1, 1.5, 7)
    for i, lipo_conc in enumerate(lipo_concs):
        bd['Vesicles_0'].value = lipo_conc
        sol.run()
        ax.plot(t, sol.yexpr['NBD'], color=color_list[i])
Esempio n. 13
0
def test_earm_integration():
    t = np.linspace(0, 1e4, 1000)
    # Run with and without inline
    Solver._use_inline = False
    sol = Solver(earm_1_0.model, t, use_analytic_jacobian=True)
    sol.run()
    Solver._use_inline = True
    sol = Solver(earm_1_0.model, t, use_analytic_jacobian=True)
    sol.run()
Esempio n. 14
0
def test_earm_integration():
    t = np.linspace(0, 1e4, 1000)
    # Run with and without inline
    Solver._use_inline = False
    sol = Solver(earm_1_0.model, t, use_analytic_jacobian=True)
    sol.run()
    Solver._use_inline = True
    sol = Solver(earm_1_0.model, t, use_analytic_jacobian=True)
    sol.run()
Esempio n. 15
0
def test_ic_expression_with_one_parameter():
    Monomer('A')
    Parameter('k1', 1)
    Expression('e1', k1)
    Rule('A_deg', A() >> None, k1)
    Initial(A(), e1)
    generate_equations(model)
    t = np.linspace(0, 1000, 100)
    sol = Solver(model, t, use_analytic_jacobian=True)
    sol.run()
Esempio n. 16
0
def check_runtime(model, tspan, iterations, use_inline, use_analytic_jacobian):
    Solver._use_inline = use_inline
    sol = Solver(model, tspan, use_analytic_jacobian=use_analytic_jacobian)
    start_time = timeit.default_timer()
    for i in range(iterations):
        sol.run()
    elapsed = timeit.default_timer() - start_time
    print("use_inline=%s, use_analytic_jacobian=%s, %d iterations" %
          (use_inline, use_analytic_jacobian, iterations))
    print("Time: %f sec\n" % elapsed)
Esempio n. 17
0
def test_ic_expression_with_one_parameter():
    Monomer('A')
    Parameter('k1', 1)
    Expression('e1', k1)
    Rule('A_deg', A() >> None, k1)
    Initial(A(), e1)
    generate_equations(model)
    t = np.linspace(0, 1000, 100)
    sol = Solver(model, t, use_analytic_jacobian=True)
    sol.run()
Esempio n. 18
0
def check_runtime(model, tspan, iterations, use_inline, use_analytic_jacobian):
    Solver._use_inline = use_inline
    sol = Solver(model, tspan, use_analytic_jacobian=use_analytic_jacobian)
    start_time = timeit.default_timer()
    for i in range(iterations):
        sol.run()
    elapsed = timeit.default_timer() - start_time
    print "use_inline=%s, use_analytic_jacobian=%s, %d iterations" % \
          (use_inline, use_analytic_jacobian, iterations)
    print "Time: %f sec\n" % elapsed
Esempio n. 19
0
def test_robertson_integration():
    t = np.linspace(0, 100)
    # Run with and without inline
    Solver._use_inline = False
    sol = Solver(robertson.model, t, use_analytic_jacobian=True)
    sol.run()
    assert sol.y.shape[0] == t.shape[0]
    # Run with and without inline
    Solver._use_inline = True
    sol = Solver(robertson.model, t, use_analytic_jacobian=True)
    sol.run()
Esempio n. 20
0
def simulate_vemurafenib_treatment(model, ts, y0):
    # New initial conditions for simulation post event
    y_init = y0
    y_init[model.observables['Vem_free'].species[0]] = 2e5

    # Continue model simulation with y_init as new initial condition
    solver = Solver(model, ts)
    solver.run(y0=y_init)

    # Concatenate the two simulations
    return solver.yobs, solver.y
Esempio n. 21
0
def test_robertson_integration():
    t = np.linspace(0, 100)
    # Run with and without inline
    Solver._use_inline = False
    sol = Solver(robertson.model, t, use_analytic_jacobian=True)
    sol.run()
    assert sol.y.shape[0] == t.shape[0]
    # Run with and without inline
    Solver._use_inline = True
    sol = Solver(robertson.model, t, use_analytic_jacobian=True)
    sol.run()
def test_2conf_irrev_formula():
    params_dict = {'c1_scaling': 5}
    bd = Builder(params_dict=params_dict)
    bd.build_model_multiconf(2, 1., reversible=False, normalized_data=True)
    t = np.linspace(0, 4000, 100)
    sol = Solver(bd.model, t)
    sol.run()
    nbd_sol = sol.yexpr['NBD']
    nbd_func = bd.obs_func(t)
    ok_(np.allclose(nbd_sol, nbd_func),
        'Integrated NBD does not match closed form NBD for 2conf model')
Esempio n. 23
0
def simulate_vemurafenib_treatment(model, ts, y0):
    # New initial conditions for simulation post event
    y_init = y0
    y_init[model.observables['Vem_free'].species[0]] = 2e5

    # Continue model simulation with y_init as new initial condition
    solver = Solver(model, ts)
    solver.run(y0=y_init)

    # Concatenate the two simulations
    return solver.yobs, solver.y
Esempio n. 24
0
def run_one_model(model, data, prior_vals, ns, pool=None):
    # Vector of estimated parameters
    pe = [p for p in model.parameters if p.name.startswith('k')]

    # Generate model equations
    generate_equations(model)
    Solver._use_inline = True
    sol = Solver(model, numpy.linspace(0, 10, 10))
    sol.run()

    # Number of temperatures, dimensions and walkers
    ntemps = 20
    ndim = len(pe)
    blocksize = 48
    nwalkers = get_num_walkers(ndim, blocksize)
    print 'Running %d walkers at %d temperatures for %d steps.' %\
          (nwalkers, ntemps, ns)

    sampler = emcee.PTSampler(ntemps,
                              nwalkers,
                              ndim,
                              likelihood,
                              prior,
                              threads=1,
                              pool=pool,
                              betas=None,
                              a=2.0,
                              Tmax=None,
                              loglargs=[model, data],
                              logpargs=[model, prior_vals],
                              loglkwargs={},
                              logpkwargs={})

    # Random initial parameters for walkers
    p0 = numpy.ones((ntemps, nwalkers, ndim))
    for i in range(ntemps):
        for j in range(nwalkers):
            for k, pp in enumerate(pe):
                p0[i, j, k] = prior_vals.vals[j][pp.name]
    print p0
    # Run sampler
    fname = scratch_path + 'chain_%s.dat' % model.name
    step = 0
    for result in sampler.sample(p0, iterations=ns, storechain=True):
        print '---'
        position = result[0]
        with open(fname, 'a') as fh:
            for w in range(nwalkers):
                for t in range(ntemps):
                    pos_str = '\t'.join(['%f' % p for p in position[t][w]])
                    fh.write('%d\t%d\t%d\t%s\n' % (step, w, t, pos_str))
        step += 1
    return sampler
Esempio n. 25
0
def test_earm_integration():
    """Ensure earm_1_0 model simulates."""
    t = np.linspace(0, 1e3)
    # Run with or without inline
    sol = Solver(earm_1_0.model, t)
    sol.run()
    if Solver._use_inline:
        # Also run without inline
        Solver._use_inline = False
        sol = Solver(earm_1_0.model, t)
        sol.run()
        Solver._use_inline = True
Esempio n. 26
0
def test_earm_integration():
    """Ensure earm_1_0 model simulates."""
    t = np.linspace(0, 1e3)
    # Run with or without inline
    sol = Solver(earm_1_0.model, t)
    sol.run()
    if Solver._use_inline:
        # Also run without inline
        Solver._use_inline = False
        sol = Solver(earm_1_0.model, t)
        sol.run()
        Solver._use_inline = True
Esempio n. 27
0
def plot_bax_titration_insertion_kinetics(model):
    """Plot the insertion kinetics of Bax over a Bax titration."""
    bax_concs = np.logspace(-1, 3, 40)
    t = np.linspace(0, 12000, 100)

    fmax_list = []
    k_list = []

    for bax_conc in bax_concs:
        model.parameters['Bax_0'].value = bax_conc

        # Get the iBax curve
        s = Solver(model, t)
        s.run()
        iBax = s.yobs['iBax'] / model.parameters['Bax_0'].value
        plt.plot(t, iBax, 'r')

        # Fit to single exponential
        fmax = fitting.Parameter(0.9)
        k = fitting.Parameter(0.01)
        def single_exp(t):
            return (fmax() * (1 - np.exp(-k()*t)))
        fitting.fit(single_exp, [fmax, k], iBax, t)
        plt.plot(t, single_exp(t), 'b')

        fmax_list.append(fmax())
        k_list.append(k())

    plt.title('Inserted Bax with Bax titration')
    plt.xlabel('Time')
    plt.ylabel('Fraction of inserted Bax')
    plt.show()

    # Make plots of k and fmax as a function of lipo concentration
    fmax_list = np.array(fmax_list)
    k_list = np.array(k_list)

    # k
    plt.figure()
    plt.plot(bax_concs, k_list, 'ro')
    plt.xlabel('Bax (nM)')
    plt.ylabel('$k$')
    plt.title("$k$ vs. Bax conc")
    plt.show()

    # Fmax 
    plt.figure()
    plt.plot(bax_concs, fmax_list, 'ro')
    plt.xlabel('Bax (nM)')
    plt.ylabel('$F_{max}$')
    plt.title("$F_{max}$ vs. Bax conc")
    plt.show()
def sim_experiment(model, exp, pd=None):
    if pd is None:
        pd = {}
    pd['ERK_0'] = exp.ERKtot * exp.ERK[0]
    pd['ERKpT_0'] = exp.ERKtot * exp.ERKpT[0]
    pd['ERKpY_0'] = exp.ERKtot * exp.ERKpY[0]
    pd['ERKpTpY_0'] = exp.ERKtot * exp.ERKpTpY[0]
    pd['MEK_0'] = exp.MEKtot
    pd['MKP_0'] = exp.MKPtot

    solver = Solver(model, exp.ts, use_analytic_jacobian=True)
    solver.run(pd)
    return solver.yobs
Esempio n. 29
0
def get_steady_state(model, y0):
    sim_hours = 1
    t = np.linspace(0, sim_hours*3600, sim_hours*60)
    solver = Solver(model, t)
    ss = False
    y_init = y0
    while not ss:
        solver.run(y0=y_init)
        ss = is_steady_state(solver.yobs)
        y_init = solver.y[-1]
    steady_state = solver.yobs[-1]
    timecourse = solver.yobs
    return steady_state, timecourse
Esempio n. 30
0
def test_piecewise_expression():
    Monomer('A')
    Observable('A_total', A())
    Expression(
        'A_deg_expr',
        Piecewise((0, A_total < 400.0), (0.001, A_total < 500.0),
                  (0.01, True)))
    Initial(A(), Parameter('A_0', 1000))
    Rule('A_deg', A() >> None, A_deg_expr)
    generate_equations(model)
    t = np.linspace(0, 1000, 100)
    sol = Solver(model, t, use_analytic_jacobian=True)
    sol.run()
Esempio n. 31
0
def get_steady_state(model, y0):
    sim_hours = 1
    t = np.linspace(0, sim_hours * 3600, sim_hours * 60)
    solver = Solver(model, t)
    ss = False
    y_init = y0
    while not ss:
        solver.run(y0=y_init)
        ss = is_steady_state(solver.yobs)
        y_init = solver.y[-1]
    steady_state = solver.yobs[-1]
    timecourse = solver.yobs
    return steady_state, timecourse
Esempio n. 32
0
def test_nested_expression():
    Monomer('A')
    Monomer('B')
    Parameter('k1', 1)
    Observable('o1', B())
    Expression('e1', o1*10)
    Expression('e2', e1+5)
    Initial(A(), Parameter('A_0', 1000))
    Initial(B(), Parameter('B_0', 1))
    Rule('A_deg', A() >> None, e2)
    generate_equations(model)
    t = np.linspace(0, 1000, 100)
    sol = Solver(model, t, use_analytic_jacobian=True)
    sol.run()
Esempio n. 33
0
def test_nested_expression():
    Monomer('A')
    Monomer('B')
    Parameter('k1', 1)
    Observable('o1', B())
    Expression('e1', o1 * 10)
    Expression('e2', e1 + 5)
    Initial(A(), Parameter('A_0', 1000))
    Initial(B(), Parameter('B_0', 1))
    Rule('A_deg', A() >> None, e2)
    generate_equations(model)
    t = np.linspace(0, 1000, 100)
    sol = Solver(model, t, use_analytic_jacobian=True)
    sol.run()
Esempio n. 34
0
def test_robertson_integration():
    """Ensure robertson model simulates."""
    t = np.linspace(0, 100)
    # Run with or without inline
    sol = Solver(robertson.model, t)
    sol.run()
    assert sol.y.shape[0] == t.shape[0]
    if Solver._use_inline:
        # Also run without inline
        Solver._use_inline = False
        sol = Solver(robertson.model, t)
        sol.run()
        assert sol.y.shape[0] == t.shape[0]
        Solver._use_inline = True
Esempio n. 35
0
def test_robertson_integration():
    """Ensure robertson model simulates."""
    t = np.linspace(0, 100)
    # Run with or without inline
    sol = Solver(robertson.model, t)
    sol.run()
    assert sol.y.shape[0] == t.shape[0]
    if Solver._use_inline:
        # Also run without inline
        Solver._use_inline = False
        sol = Solver(robertson.model, t)
        sol.run()
        assert sol.y.shape[0] == t.shape[0]
        Solver._use_inline = True
def test_3conf_irrev_formula_k1_k2_different():
    params_dict = {'c1_scaling': 8,
                   'c2_scaling': 2,
                   'c0_to_c1_k': 0.05,
                   'c1_to_c2_k': 0.005
            }
    bd = Builder(params_dict=params_dict)
    bd.build_model_multiconf(3, 1., reversible=False, normalized_data=True)
    t = np.linspace(0, 4000, 100)
    sol = Solver(bd.model, t)
    sol.run()
    nbd_sol = sol.yexpr['NBD']
    nbd_func = bd.obs_func(t)
    ok_(np.allclose(nbd_sol, nbd_func),
        'Integrated NBD does not match closed form NBD for 3conf model')
    def bax_titration_experiment(self, t, ydata):
        self['Bax_NBD_0'].value = 200.
        self['Vesicles_0'].value = 1.9
        bax_concs = np.array([0, 10, 20, 40, 80, 160, 320, 640])

        plt.figure()
        for bax_conc in bax_concs:
            self['Bax_unlab_0'].value = bax_conc
            baseline = self['cBax_NBD'].value * self['Bax_NBD_0'].value
            solver = Solver(self.model, t)
            solver.run()
            plt.plot(t, solver.yexpr['NBD'] / baseline, label='Bax %d' % bax_conc)
            print "baseline = %f" % baseline
        plt.legend(loc='upper left')

        plt.plot(t, ydata / (self['cBax_NBD'].value * 185))
Esempio n. 38
0
def synthetic_data(model, tspan, obs_list=None, sigma=0.1):
    #from pysb.integrate import odesolve
    from pysb.integrate import Solver
    solver = Solver(model, tspan)
    solver.run()

    # Sample from a normal distribution with variance sigma and mean 1
    # (randn generates a matrix of random numbers sampled from a normal
    # distribution with mean 0 and variance 1)
    # 
    # Note: This modifies yobs_view (the view on yobs) so that the changes 
    # are reflected in yobs (which is returned by the function). Since a new
    # Solver object is constructed for each function invocation this does not
    # cause problems in this case.
    solver.yobs_view *= ((numpy.random.randn(*solver.yobs_view.shape) * sigma) + 1)
    return solver.yobs
Esempio n. 39
0
    def plot_func(self, x=None):
        """Plots the timecourses with the parameter values given by x.

        Parameters
        ----------
        x : np.array or list
            The parameters to use for the plot. These should be in the same
            order used by the objective function: globally fit parameters
            first, then a set of local parameters for each of the timecourses
            being fit.
        """
        if x is None:
            if self.result is None:
                raise ValueError('x must be a vector of parameter values.')
            else:
                # If minimize was run, the parameters will be in the 'x'
                # attribute of the result object
                try:
                    x = 10 ** self.result.x
                # If leastsq was run, the parameters will be the first entry
                # in the result tuple
                except AttributeError:
                    x = 10 ** self.result[0]

        s = Solver(self.builder.model, self.time)
        # Iterate over each entry in the data array
        for data_ix, data in enumerate(self.data):
            # Set the parameters appropriately for the simulation:
            # Iterate over the globally fit parameters
            for g_ix, p in enumerate(self.builder.global_params):
                p.value = x[g_ix]
            # Iterate over the locally fit parameters
            for l_ix, p in enumerate(self.builder.local_params):
                ix_offset = len(self.builder.global_params) + \
                            data_ix * len(self.builder.local_params)
                p.value = x[l_ix + ix_offset]
            # Now fill in the initial condition parameters
            for p_name, values in self.params.iteritems():
                p = self.builder.model.parameters[p_name]
                p.value = values[data_ix]
            # Now run the simulation
            s.run()
            # Plot the observable
            if self.use_expr:
                plt.plot(self.time, s.yexpr[self.obs_name], color='r')
            else:
                plt.plot(self.time, s.yobs[self.obs_name], color='r')
Esempio n. 40
0
    def plot_func(self, x=None):
        """Plots the timecourses with the parameter values given by x.

        Parameters
        ----------
        x : np.array or list
            The parameters to use for the plot. These should be in the same
            order used by the objective function: globally fit parameters
            first, then a set of local parameters for each of the timecourses
            being fit.
        """
        if x is None:
            if self.result is None:
                raise ValueError('x must be a vector of parameter values.')
            else:
                # If minimize was run, the parameters will be in the 'x'
                # attribute of the result object
                try:
                    x = 10**self.result.x
                # If leastsq was run, the parameters will be the first entry
                # in the result tuple
                except AttributeError:
                    x = 10**self.result[0]

        s = Solver(self.builder.model, self.time)
        # Iterate over each entry in the data array
        for data_ix, data in enumerate(self.data):
            # Set the parameters appropriately for the simulation:
            # Iterate over the globally fit parameters
            for g_ix, p in enumerate(self.builder.global_params):
                p.value = x[g_ix]
            # Iterate over the locally fit parameters
            for l_ix, p in enumerate(self.builder.local_params):
                ix_offset = len(self.builder.global_params) + \
                            data_ix * len(self.builder.local_params)
                p.value = x[l_ix + ix_offset]
            # Now fill in the initial condition parameters
            for p_name, values in self.params.iteritems():
                p = self.builder.model.parameters[p_name]
                p.value = values[data_ix]
            # Now run the simulation
            s.run()
            # Plot the observable
            if self.use_expr:
                plt.plot(self.time, s.yexpr[self.obs_name], color='r')
            else:
                plt.plot(self.time, s.yobs[self.obs_name], color='r')
Esempio n. 41
0
 def simulate_model(self, model, target_entity):
     '''
     Simulate a model and return the observed dynamics of
     a given target agent.
     '''
     # TODO: where does the maximal time point come from?
     monomer = self.get_monomer(model, target_entity)
     obs_name = self.get_obs_name(model, monomer)
     ts = numpy.linspace(0, 100, 100)
     solver = Solver(model, ts)
     solver.run()
     yobs_target = solver.yobs[obs_name]
     plt.ion()
     plt.plot(ts, yobs_target, label=obs_name)
     plt.show()
     plt.legend()
     return yobs_target
Esempio n. 42
0
def sim_experiment(model, exp, pd=None, solver=None):
    if pd is None:
        pd = {}
    pd['ERK_0'] = exp.ERKtot * exp.ERK[0]
    pd['ERKpT_0'] = exp.ERKtot * exp.ERKpT[0]
    pd['ERKpY_0'] = exp.ERKtot * exp.ERKpY[0]
    pd['ERKpTpY_0'] = exp.ERKtot * exp.ERKpTpY[0]
    pd['MEK_0'] = exp.MEKtot
    pd['MKP_0'] = exp.MKPtot

    if solver is None:
        Solver._use_inline = True
        solver = Solver(model, exp.ts, use_analytic_jacobian=True)
    else:
        solver.set_tspan(exp.ts)
    solver.run(pd)
    return solver.yobs
Esempio n. 43
0
def sim_experiment(model, exp, pd=None, solver=None):
    if pd is None:
        pd = {}
    pd['ERK_0'] = exp.ERKtot * exp.ERK[0]
    pd['ERKpT_0'] = exp.ERKtot * exp.ERKpT[0]
    pd['ERKpY_0'] = exp.ERKtot * exp.ERKpY[0]
    pd['ERKpTpY_0'] = exp.ERKtot * exp.ERKpTpY[0]
    pd['MEK_0'] = exp.MEKtot
    pd['MKP_0'] = exp.MKPtot

    if solver is None:
        Solver._use_inline = True
        solver = Solver(model, exp.ts, use_analytic_jacobian=True)
    else:
        solver.set_tspan(exp.ts)
    solver.run(pd)
    return solver.yobs
Esempio n. 44
0
def synthetic_data(model, tspan, obs_list=None, sigma=0.1):
    #from pysb.integrate import odesolve
    from pysb.integrate import Solver
    solver = Solver(model, tspan)
    solver.run()

    # Sample from a normal distribution with variance sigma and mean 1
    # (randn generates a matrix of random numbers sampled from a normal
    # distribution with mean 0 and variance 1)
    #
    # Note: This modifies yobs_view (the view on yobs) so that the changes
    # are reflected in yobs (which is returned by the function). Since a new
    # Solver object is constructed for each function invocation this does not
    # cause problems in this case.
    solver.yobs_view *= (
        (numpy.random.randn(*solver.yobs_view.shape) * sigma) + 1)
    return solver.yobs
Esempio n. 45
0
 def simulate_model(self, model, target_entity):
     '''
     Simulate a model and return the observed dynamics of
     a given target agent.
     '''
     # TODO: where does the maximal time point come from?
     monomer = self.get_monomer(model, target_entity)
     obs_name = self.get_obs_name(model, monomer)
     ts = numpy.linspace(0, 100, 100)
     solver = Solver(model, ts)
     solver.run()
     yobs_target = solver.yobs[obs_name]
     plt.ion()
     plt.plot(ts, yobs_target, label=obs_name)
     plt.show()
     plt.legend()
     return yobs_target
Esempio n. 46
0
def run_model(model):
    sim_hours = 200
    ts = np.linspace(0, sim_hours * 3600, sim_hours * 60)
    solver = Solver(model, ts)
    solver.run()
    plt.figure(figsize=(2, 2), dpi=300)
    set_fig_params()
    plt.plot(ts, solver.yobs['p53_active'], 'r')
    #if model.name == 'p53_ATR':
    #    plt.plot(ts, solver.yobs['atr_active'], 'b')
    #else:
    #    plt.plot(ts, solver.yobs['atm_active'], 'b')
    plt.xticks([])
    plt.xlabel('Time (a.u.)', fontsize=12)
    plt.ylabel('Active p53', fontsize=12)
    plt.yticks([])
    plt.savefig(model.name + '.pdf')
    return ts, solver
Esempio n. 47
0
def run_model(model):
    sim_hours = 200
    ts = np.linspace(0, sim_hours*3600, sim_hours*60)
    solver = Solver(model, ts)
    solver.run()
    plt.figure(figsize=(2,2), dpi=300)
    set_fig_params()
    plt.plot(ts, solver.yobs['p53_active'], 'r')
    #if model.name == 'p53_ATR':
    #    plt.plot(ts, solver.yobs['atr_active'], 'b')
    #else:
    #    plt.plot(ts, solver.yobs['atm_active'], 'b')
    plt.xticks([])
    plt.xlabel('Time (a.u.)', fontsize=12)
    plt.ylabel('Active p53', fontsize=12)
    plt.yticks([])
    plt.savefig(model.name + '.pdf')
    return ts, solver
Esempio n. 48
0
def run_one_model(model, data, prior_vals, ns, pool=None):
    # Vector of estimated parameters
    pe = [p for p in model.parameters if p.name.startswith('k')]

    # Generate model equations
    generate_equations(model)
    Solver._use_inline = True
    sol = Solver(model, numpy.linspace(0,10,10))
    sol.run()

    # Number of temperatures, dimensions and walkers
    ntemps = 20
    ndim = len(pe)
    blocksize = 48
    nwalkers = get_num_walkers(ndim, blocksize)
    print 'Running %d walkers at %d temperatures for %d steps.' %\
          (nwalkers, ntemps, ns)

    sampler = emcee.PTSampler(ntemps, nwalkers, ndim, likelihood, prior,
         threads=1, pool=pool, betas=None, a=2.0, Tmax=None,
         loglargs=[model, data], logpargs=[model, prior_vals],
         loglkwargs={}, logpkwargs={})

    # Random initial parameters for walkers
    p0 = numpy.ones((ntemps, nwalkers, ndim))
    for i in range(ntemps):
        for j in range(nwalkers):
            for k, pp in enumerate(pe):
                p0[i, j, k] = prior_vals.vals[j][pp.name]
    print p0
    # Run sampler
    fname = scratch_path + 'chain_%s.dat' % model.name
    step = 0
    for result in sampler.sample(p0, iterations=ns, storechain=True):
        print '---'
        position = result[0]
        with open(fname, 'a') as fh:
            for w in range(nwalkers):
                for t in range(ntemps):
                    pos_str = '\t'.join(['%f' % p for p in position[t][w]])
                    fh.write('%d\t%d\t%d\t%s\n' % (step, w, t, pos_str))
        step += 1
    return sampler
Esempio n. 49
0
def run_model(model):
    sim_hours = 20
    ts = np.linspace(0, sim_hours * 3600, sim_hours * 60)
    tst = time.time()
    solver = Solver(model, ts)
    solver.run()
    te = time.time()
    print('Simulation took %.2fs' % (te - tst))
    plt.figure(figsize=(1.8, 1), dpi=300)
    set_fig_params()
    plt.plot(ts, solver.yobs['p53_active'], 'r')
    plt.xticks([])
    plt.xlabel('Time (a.u.)', fontsize=7)
    plt.ylabel('Active p53', fontsize=7)
    plt.yticks([])
    ax = plt.gca()
    format_axis(ax)
    #plt.subplots_adjust()
    plt.savefig(model.name + '.pdf')
    return ts, solver
Esempio n. 50
0
    def run_one_cpt(self):
        """Run a deterministic simulation using the one_cpt implementation.

        Builds the model using the :py:meth:`Job.build` method, then runs
        a deterministic simulation for the duration specified by
        ``self.tmax`` and returns the results.

        Returns
        -------
        tuple of (numpy.array, numpy.recarray)
            The first entry is the vector of timepoints; the second is the
            record array of the model observables.
        """

        b = self.one_cpt_builder()
        # We add one extra point so that the time coordinates of the
        # one_cpt and n_cpt/site_cpt simulations line up
        t = np.linspace(0, self.tmax, self.n_steps + 1)
        s = Solver(b.model, t)
        s.run()
        return (t, s.yobs)
Esempio n. 51
0
def run_model(model):
    sim_hours = 20
    ts = np.linspace(0, sim_hours*3600, sim_hours*60)
    tst = time.time()
    solver = Solver(model, ts)
    solver.run()
    te = time.time()
    print('Simulation took %.2fs' % (te-tst))
    plt.figure(figsize=(1.8, 1), dpi=300)
    set_fig_params()
    plt.plot(ts, solver.yobs['p53_active'], 'r')
    plt.xticks([])
    plt.xlabel('Time (a.u.)', fontsize=7)
    plt.ylabel('Active p53', fontsize=7)
    plt.yticks([])
    ax = plt.gca()
    format_axis(ax)
    #plt.subplots_adjust()
    if not _no_plot:
        plt.savefig(model.name + '.pdf')
    return ts, solver
Esempio n. 52
0
 def simulate_model(self, model, agent_target):
     '''
     Simulate a model and return the observed dynamics of 
     a given target agent.
     '''
     monomer = self.get_monomer(model, agent_target)
     obs_name = self.get_obs_name(model, monomer)
     obs_pattern = monomer(act='active')
     self.get_create_observable(model, obs_name, obs_pattern)
     # TODO: where does the maximal time point come from?
     ts = numpy.linspace(0, 100, 100)
     try:
         solver = Solver(model, ts)
     except pysb.bng.GenerateNetworkError:
         warnings.warn('Could not generate network')
         return None
     solver.run()
     yobs_target = solver.yobs[obs_name]
     plt.ion()
     plt.plot(ts, yobs_target, label=obs_name)
     plt.show()
     plt.legend()
     return yobs_target
def test_5conf_irrev_formula_k1_k2_k3_k4_different():
    params_dict = {'c1_scaling': 8,
                   'c2_scaling': 2,
                   'c3_scaling': 6,
                   'c4_scaling': 1.5,
                   'c0_to_c1_k': 0.05,
                   'c1_to_c2_k': 0.005,
                   'c2_to_c3_k': 0.001,
                   'c3_to_c4_k': 0.002,
            }
    bd = Builder(params_dict=params_dict)
    bd.build_model_multiconf(5, 1., reversible=False, normalized_data=True)
    t = np.linspace(0, 4000, 100)
    sol = Solver(bd.model, t)
    sol.run()
    nbd_sol = sol.yexpr['NBD']
    nbd_func = bd.obs_func(t)
    plt.ion()
    plt.figure()
    plt.plot(t, nbd_sol)
    plt.plot(t, nbd_func)
    ok_(np.allclose(nbd_sol, nbd_func),
        'Integrated NBD does not match closed form NBD for 5conf model')
Esempio n. 54
0
# for s in sos_range:
for r in Ras_range:
    wt_holder_row = []
    v600e_holder_row = []
    erk_holder_row = []
    kras_holder_row = []
    sos_holder_row = []
    for v in Vemurafenib_range:

        model.parameters['KRAS_0'].value = r
        # model.parameters['SOS_0'].value = s
        model.parameters['Vem_0'].value = v

        ts = np.linspace(0, 1e5, 100)
        solver = Solver(model, ts)
        solver.run()

        wt_holder_row.append(solver.yobs['BRAF_WT_active'][-1])
        v600e_holder_row.append(solver.yobs['BRAF_V600E_active'][-1])
        erk_holder_row.append(solver.yobs['ERK_P'][-1])
        kras_holder_row.append(solver.yobs['active_KRAS'][-1])
        sos_holder_row.append(solver.yobs['active_SOS'][-1])

    RAF_WT_level.append(wt_holder_row)
    RAF_V600E_level.append(v600e_holder_row)
    ERK_P_level.append(erk_holder_row)
    KRAS_level.append(kras_holder_row)
    SOS_level.append(sos_holder_row)

wt = np.array(RAF_WT_level, dtype='float')
v600e = np.array(RAF_V600E_level, dtype='float')
from pyDOE import *
from scipy.stats.distributions import norm
import numdifftools as nd

# Simulate the model

# Create time vector using np.linspace function
num_timepoints = 101
num_dim = 3
t = np.linspace(0, 200, num_timepoints)

# Get instance of the Solver
sol = Solver(model, t, use_analytic_jacobian=False)

# Perform the integration
sol.run()

# Get instance of Sensitivity object
sens = Sensitivity(model, t)

# sol.y contains timecourses for all of the species
# (model.species gives matched list of species)

# sol.yobs contains timecourse only for the observables
# Indexed by the name of the observable

# Plot the timecourses for A, B, and C
plt.ion()
plt.figure()

# Iterate over the observables
Esempio n. 56
0
class TestSolver(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

        # This timespan is chosen to be enough to trigger a Jacobian evaluation
        # on the various solvers.
        self.time = np.linspace(0, 1)
        self.solver = Solver(self.model, self.time, integrator='vode')

    def tearDown(self):
        self.model = None
        self.time = None
        self.solver = None

    def test_vode_solver_run(self):
        """Test vode."""
        self.solver.run()

    def test_vode_jac_solver_run(self):
        """Test vode and analytic jacobian."""
        solver_vode_jac = Solver(self.model,
                                 self.time,
                                 integrator='vode',
                                 use_analytic_jacobian=True)
        solver_vode_jac.run()

    def test_lsoda_solver_run(self):
        """Test lsoda."""
        solver_lsoda = Solver(self.model, self.time, integrator='lsoda')
        solver_lsoda.run()

    def test_lsoda_jac_solver_run(self):
        """Test lsoda and analytic jacobian."""
        solver_lsoda_jac = Solver(self.model,
                                  self.time,
                                  integrator='lsoda',
                                  use_analytic_jacobian=True)
        solver_lsoda_jac.run()

    @raises(NotImplementedError)
    def test_y0_as_dictionary_monomer_species(self):
        """Test y0 with model-defined species."""
        self.solver.run(y0={
            "A(a=None)": 10,
            "B(b=1) % A(a=1)": 0,
            "B(b=None)": 0
        })
        assert np.allclose(self.solver.y[0, 0], 10)

    @raises(NotImplementedError)
    def test_y0_as_dictionary_with_bound_species(self):
        """Test y0 with dynamically generated species."""
        self.solver.run(y0={
            "A(a=None)": 0,
            "B(b=1) % A(a=1)": 100,
            "B(b=None)": 0
        })
        assert np.allclose(self.solver.y[0, 3], 100)

    @raises(NotImplementedError)
    def test_y0_invalid_dictionary_key(self):
        """Test y0 with invalid monomer name."""
        self.solver.run(y0={"C(c=None)": 1})

    @raises(NotImplementedError)
    def test_y0_non_numeric_value(self):
        """Test y0 with non-numeric value."""
        self.solver.run(y0={"A(a=None)": 'eggs'})

    def test_param_values_as_dictionary(self):
        """Test param_values as a dictionary."""
        self.solver.run(param_values={'kbindAB': 0})
        # kbindAB=0 should ensure no AB_complex is produced.
        assert np.allclose(self.solver.yobs["AB_complex"], 0)

    @raises(IndexError)
    def test_param_values_invalid_dictionary_key(self):
        """Test param_values with invalid parameter name."""
        self.solver.run(param_values={'spam': 150})

    @raises(ValueError, TypeError)
    def test_param_values_non_numeric_value(self):
        """Test param_values with non-numeric value."""
        self.solver.run(param_values={'ksynthA': 'eggs'})
Esempio n. 57
0
 def test_lsoda_solver_run(self):
     """Test lsoda."""
     solver_lsoda = Solver(self.model, self.time, integrator='lsoda')
     solver_lsoda.run()
Esempio n. 58
0
class NS:
    def __init__(self, model, objective_function, process_data, data,
                 population, max_iterations, target_score, set_number,
                 proc_number):

        self.model = model
        self.objective_function = objective_function
        self.data = data
        self.model_solver = None
        self.prior_1kf = [-4, 0]
        self.prior_2kf = [-10, -2]  # [-8, -4]
        self.prior_1kr = [-5, 1]  # [-4, 0]
        self.prior_1kc = [-4, 3]  # [-1, 3]
        self.iterations = max_iterations
        self.scalar = 10.0
        self.reduction = 0.9
        self.scalar_reductions = 0
        self.scalar_limit = .0001
        self.iteration = 0
        self.simulations = 0
        self.useless = 10
        self.N = population
        self.target_score = target_score
        self.set_number = set_number - 1
        self.time = []
        self.working_set = None
        self.params = []
        self.stop = 'None'
        self.process_num = proc_number
        self.dummy = [x for x in range(self.process_num)]
        self.processed_data = process_data(self.data)
        self._initiate_log()
        self._nested_sampling_KDE()
        self._output()

    def _output(self):

        summary_index = 0
        while isfile(self.model.name + '_results_' + str(summary_index) +
                     '.txt'):
            summary_index += 1
        summary_object = self.model.name + '_results_' + str(
            summary_index) + '.txt'

        summary = open(summary_object, 'w')
        summary.write(self.model.name + '_results' + '\n')
        summary.write('parameters: ' + str(len(self.params)) + '\n')
        summary.write('iterations: ' + str(self.iteration) + '\n')
        summary.write('simulations: ' + str(self.simulations) + '\n')
        summary.write('scalar: ' + str(self.scalar) + '\n')
        summary.write('scalar reduction: ' + str(self.scalar_reductions) +
                      '\n')
        summary.write('stop criteria: ' + self.stop + '\n\n')

        summary.write('parameter sets\n')
        self.working_set.sort()
        for i, each in enumerate(self.working_set):
            summary.write(str(i + 1) + ' score: ' + str(each[0]) + '\n')
        summary.write('\n')
        for i, each in enumerate(self.working_set):
            summary.write(''.join(str(each[1])[1:-1]) + '\n')
        summary.write('\n')

        summary.close()

    def _initiate_log(self):
        def parallel_initialize(num_tasks):

            count = 0
            pop_list = []
            while count < num_tasks:
                coords = []
                np.random.seed()
                for item in self.params:
                    if isinstance(item, list):
                        coords.append(10**(np.random.uniform(item[0],
                                                             item[1])))
                    else:
                        coords.append(item)
                objective = self._compute_objective(coords)
                pop_list.append([objective, coords])
                print objective
                count += 1

            return pop_list

        # retrieve time points from data
        for each in self.processed_data:
            self.time.append(float(each[0]))

        # set parameter values or prior ranges (log-space)
        for each in self.model.parameters:

            if each.name[-2:] == '_0':
                self.params.append(each.value)
            if each.name[-3:] == '1kf':
                self.params.append(self.prior_1kf)
            if each.name[-3:] == '2kf':
                self.params.append(self.prior_2kf)
            if each.name[-3:] == '1kr':
                self.params.append(self.prior_1kr)
            if each.name[-3:] == '1kc':
                self.params.append(self.prior_1kc)

        # create solver object
        self.model_solver = Solver(self.model,
                                   self.time,
                                   integrator='lsoda',
                                   integrator_options={
                                       'atol': 1e-8,
                                       'rtol': 1e-8,
                                       'mxstep': 20000
                                   })

        # distribute the working set population among processes
        tasks_per_process = [
            int(ceil((float(self.N)) / float(self.process_num)))
            for _ in range(self.process_num)
        ]
        sum_tpp = sum(tasks_per_process)
        while sum_tpp < self.N:
            sum_tpp += 1
            tasks_per_process[-1] += 1

        # construct, in parallel, the working population of N parameter sets
        p = pp.ProcessPool(self.process_num)
        self.working_set = list(
            itertools.chain.from_iterable(
                p.map(parallel_initialize, tasks_per_process)))
        self.working_set.sort()

    def _compute_objective(self, point):

        # simulate a point
        self.model_solver.run(point)

        # construct simulation trajectories
        sim_trajectories = [['time']]
        for each in self.model.observables:
            sim_trajectories[0].append(each.name)

        for i, each in enumerate(self.model_solver.yobs):
            sim_trajectories.append([self.time[i]] + list(each))

        # calculate the cost
        cost = self.objective_function(self.processed_data, sim_trajectories)
        if isinstance(cost, float):
            return cost
        else:
            return False

    def _nested_sampling_KDE(self):

        useless_samples = 0
        iteration = 1
        score_criteria = self.working_set[self.set_number][0]

        def KDE_sample_log(dummy):

            # select data point
            np.random.seed()
            data_point = np.random.randint(0, len(self.working_set) - 1)
            coordinates = self.working_set[data_point][1]

            # select parameter values individually from normal with respect to prior boundary
            new_point = []
            for i, item in enumerate(coordinates):
                if isinstance(self.params[i], float):
                    new_point.append(self.params[i])
                else:
                    accept = False
                    log_coord = None

                    while not accept:
                        log_coord = np.random.normal(log10(item), self.scalar)
                        if self.params[i][0] <= log_coord <= self.params[i][1]:
                            accept = True
                    new_point.append(10**log_coord)

            return new_point

        def compute_objective(point):

            # simulate a point
            self.model_solver.run(point)

            # construct simulation trajectories
            sim_trajectories = [['time']]
            for item in self.model.observables:
                sim_trajectories[0].append(item.name)

            for i, item in enumerate(self.model_solver.yobs):
                sim_trajectories.append([self.time[i]] + list(item))

            # calculate the cost
            cost = self.objective_function(self.processed_data,
                                           sim_trajectories)
            if isinstance(cost, float):
                return cost
            else:
                return False

        def parallel_nested_sampling(dummy):

            # sample from the prior
            test_point = KDE_sample_log(dummy)

            # calculate objective
            test_point_objective = compute_objective(test_point)

            return [test_point_objective, test_point]

        # test new points until termination criteria are met

        p = pp.ProcessPool(self.process_num)
        while iteration <= self.iterations and self.scalar > self.scalar_limit and score_criteria > self.target_score:

            print iteration, self.scalar, score_criteria
            self.simulations += self.process_num
            self.iteration = iteration

            if useless_samples >= self.useless:
                self.scalar *= self.reduction
                useless_samples = 0
                self.scalar_reductions += 1

            provisional_points = p.map(parallel_nested_sampling, self.dummy)
            new_points = []
            for each in provisional_points:
                if not isnan(each[0]):
                    if each[0] < self.working_set[-1][0]:
                        new_points.append(each)
                        iteration += 1
                    else:
                        useless_samples += 1
                else:
                    useless_samples += 1

            score_criteria = self.working_set[self.set_number][0]

            self.working_set.extend(new_points)
            self.working_set.sort()
            self.working_set = self.working_set[:self.N]

        if iteration > self.iterations:
            self.stop = 'iterations'
        if self.scalar <= self.scalar_limit:
            self.stop = 'scalar limit'
        if score_criteria <= self.target_score:
            self.stop = 'target score reached'

        self.working_set.sort()

    def _KDE_sample_log(self, dummy):

        # select data point
        np.random.seed()
        data_point = np.random.randint(0, len(self.working_set) - 1)
        coordinates = self.working_set[data_point][1]

        # select parameter values individually from normal with respect to prior boundary
        new_point = []
        for i, each in enumerate(coordinates):
            if isinstance(self.params[i], float):
                new_point.append(self.params[i])
            else:
                accept = False
                log_coord = None

                while not accept:
                    log_coord = np.random.normal(log10(each), self.scalar)
                    if self.params[i][0] <= log_coord <= self.params[i][1]:
                        accept = True
                new_point.append(10**log_coord)

        return new_point
Esempio n. 59
0
class TRA(object):
    def __init__(self, kappa):
        if kappa is None:
            self.ode_mode = True
        else:
            self.ode_mode = False
        if not self.ode_mode:
            self.kappa = kappa
            kappa_ver = kappa.version()
            if kappa_ver is None or kappa_ver.get('version_id') is None:
                raise SimulatorError('Invalid Kappa client.')
            logger.info('Using kappa version %s / build %s' %
                         (kappa_ver.get('version_id'),
                          kappa_ver.get('version_build')))
        else:
            logger.info('Using ODE mode in TRA.')

    def check_property(self, model, pattern, conditions=None):
        # TODO: handle multiple entities (observables) in pattern
        # TODO: set max_time based on some model property if not given
        # TODO: make number of simulations and number of time points adaptive

        # Make an observable for the simulations
        obs = get_create_observable(model, pattern.entities[0])

        # Make pattern
        fstr = get_ltl_from_pattern(pattern, obs)
        given_pattern = (fstr is not None)

        # Set the time limit for the simulations
        if pattern.time_limit is None:
            max_time = 20000.0
        elif pattern.time_limit.ub > 0:
            max_time = pattern.time_limit.get_ub_seconds()
        # The numer of time points to get output at
        num_times = 100
        # The periof at which the output is sampled
        plot_period = int(1.0*max_time / num_times)
        if pattern.time_limit and pattern.time_limit.lb > 0:
            min_time = pattern.time_limit.get_lb_seconds()
            min_time_idx = int(num_times * (1.0*min_time / max_time))
        else:
            min_time_idx = 0

        # The number of independent simulations to perform
        num_sim = 10
        # Run simulations
        tspan, results = self.run_simulations(model, conditions, num_sim,
                                              min_time_idx, max_time,
                                              plot_period)

        fig_path = self.plot_results(tspan, results, obs.name)

        # Discretize observations
        [self.discretize_obs(yobs, obs.name) for yobs in results]
        # We check for the given pattern
        if given_pattern:
            truths = []
            for yobs in results:
                # Run model checker on the given pattern
                MC = mc.ModelChecker(fstr, yobs)
                logger.info('Main property %s' % MC.truth)
                truths.append(MC.truth)
            sat_rate = numpy.count_nonzero(truths) / (1.0*num_sim)
            make_suggestion = (sat_rate < 0.3)
            if make_suggestion:
                logger.info('MAKING SUGGESTION with sat rate %.2f.' % sat_rate)
        else:
            make_suggestion = True

        # If no suggestion is to be made, we return
        if not make_suggestion:
            return sat_rate, num_sim, None, fig_path

        # Run model checker on all patterns
        all_patterns = get_all_patterns(obs.name)
        for fs, pat in all_patterns:
            logger.info('Testing pattern: %s' % pat)
            truths = []
            for yobs in results:
                MC = mc.ModelChecker(fs, yobs)
                logger.info('Property %s' % MC.truth)
                truths.append(MC.truth)
            sat_rate_new = numpy.count_nonzero(truths) / (1.0*num_sim)
            if sat_rate_new > 0.5:
                if not given_pattern:
                    return sat_rate_new, num_sim, pat, fig_path
                else:
                    return sat_rate, num_sim, pat, fig_path

    def plot_results(self, tspan, results, obs_name):
        plt.figure()
        plt.ion()
        lr = matplotlib.patches.Rectangle((0,0), tspan[-1], 50, color='red',
                                           alpha=0.1)
        hr = matplotlib.patches.Rectangle((0,50), tspan[-1], 50, color='green',
                                           alpha=0.1)
        ax = plt.gca()
        ax.add_patch(lr)
        ax.add_patch(hr)
        for yobs in results:
            plt.plot(tspan, yobs[obs_name])
        plt.ylim(0, max(numpy.max(yobs[obs_name]), 100.0))
        plt.xlabel('Time (s)')
        plt.ylabel('Amount (molecules)')
        plt.title('Simulation results')
        dir_path = os.path.dirname(os.path.realpath(__file__))
        fig_path = os.path.join(dir_path, '%s.png' % obs_name)
        plt.savefig(fig_path)
        return fig_path

    def run_simulations(self, model, conditions, num_sim, min_time_idx,
                        max_time, plot_period):
        self.sol = None
        results = []
        for i in range(num_sim):
            # Apply molecular condition to model
            try:
                model_sim = self.condition_model(model, conditions)
            except Exception as e:
                logger.error(e)
                msg = 'Applying molecular condition failed.'
                raise InvalidMolecularConditionError(msg)
            # Run a simulation
            logger.info('Starting simulation %d' % (i+1))
            if not self.ode_mode:
                try:
                    tspan, yobs = self.simulate_kappa(model_sim, max_time,
                                                      plot_period)
                except Exception as e:
                    logger.error(e)
                    raise SimulatorError('Kappa simulation failed.')
            else:
                tspan, yobs = self.simulate_odes(model_sim, max_time,
                                                 plot_period)
            # Get and plot observable
            yobs_from_min = yobs[min_time_idx:]
            results.append(yobs_from_min)
        return tspan, results

    def discretize_obs(self, yobs, obs_name):
        # TODO: This needs to be done in a model/observable-dependent way
        for i, v in enumerate(yobs[obs_name]):
            yobs[obs_name][i] = 1 if v > 50 else 0

    def condition_model(self, model, conditions):
        # Set up simulation conditions
        if conditions:
            model_sim = deepcopy(model)
            for condition in conditions:
                apply_condition(model_sim, condition)
        else:
            model_sim = model
        return model_sim

    def simulate_kappa(self, model_sim, max_time, plot_period):
        # Export kappa model
        kappa_model = pysb_to_kappa(model_sim)
        # Start simulation
        kappa_params = {'code': kappa_model,
                        'plot_period': plot_period,
                        'max_time': max_time}
        sim_id = self.kappa.start(kappa_params)
        while True:
            sleep(0.2)
            status = self.kappa.status(sim_id)
            is_running = status.get('is_running')
            if not is_running:
                break
            else:
                if status.get('time_percentage') is not None:
                    logger.info('Sim time percentage: %d' %
                                  status.get('time_percentage'))
        tspan, yobs = get_sim_result(status.get('plot'))
        return tspan, yobs

    def simulate_odes(self, model_sim, max_time, plot_period):
        ts = numpy.linspace(0, max_time, int(1.0*max_time/plot_period))
        if self.sol is None:
            self.sol = Solver(model_sim, ts)
        self.sol.run()
        return ts, self.sol.yobs