def parameter_signatures(par, model, tspan, type_sign='production'):
    """

    :param par: parameter file path or vector of parameters
    :param model: PySB model
    :param tspan: time span
    :return: tropical signatures of input parameters
    """

    try:
        if isinstance(par, str):
            parames = hf.read_pars(par)
        else:
            parames = par
        drivers = run_tropical(model, tspan, parameters=parames, type_sign=type_sign, sp_visualize=None)
        return drivers
    except:
        print(par)
        print("".join(traceback.format_exception(*sys.exc_info())))
        raise Exception("".join(traceback.format_exception(*sys.exc_info())))
def display_all_species(cluster_parameters):
    """Saves figures of all species for each cluster of parameters

        keyword arguments:
        cluster_parameters -- list of files, where each file contains the clustered parameters
    """
    for cl in cluster_parameters:
        directory = '/home/oscar/Documents/tropical_project/' + cl
        if not os.path.exists(directory):
            os.makedirs(directory)
        for sp in range(len(model.species)):
            plt.figure()
            for idx, par in enumerate(cluster_parameters[cl]):
                params = hf.read_pars(par)
                solver.run(params)
                y = solver.y.T
                plt.plot(solver.tspan, y[sp])
            plt.title(str(model.species[sp]))
            plt.savefig(directory + '/' + str(model.species[sp]) + '.jpg', format='jpg', bbox_inches='tight', dpi=400)
            plt.close()
    return
Example #3
0
from earm.lopez_embedded import model
from max_plus_consumption_production import run_tropical
import numpy as np
import os
import helper_functions as hf

directory = os.path.dirname(__file__)
parameters_path = os.path.join(directory, "parameters_5000")
all_parameters = hf.listdir_fullpath(parameters_path)
parameters = hf.read_pars(all_parameters[0])
t = np.linspace(0, 20000,  100)

run_tropical(model, t, parameters, diff_par=1, type_sign='consumption', sp_visualize=[6])


    def signal_signature(self, param_values, diff_par=1, type_sign='production', sp_to_visualize=None):
        if param_values is not None:
            if type(param_values) is str:
                param_values = hf.read_pars(param_values)
            # accept vector of parameter values as an argument
            if len(param_values) != len(self.model.parameters):
                print(param_values)
                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
        param_values = dict((p.name, param_values[i]) for i, p in enumerate(self.model.parameters))

        y = self.sim.run(param_values=param_values).dataframe
        # Dictionary whose keys are species and values are the monomial signatures
        all_signatures = {}

        if type_sign == 'production':
            mon_type = 'products'
        elif type_sign == 'consumption':
            mon_type = 'reactants'
        else:
            raise Exception("type sign must be 'production' or 'consumption'")

        for sp in self.eqs_for_tropicalization:

            # reaction terms
            monomials = []

            for term in self.model.reactions_bidirectional:
                if sp in term['reactants'] and term['reversible'] is True:
                    monomials.append((-1) * term['rate'])
                elif sp in term[mon_type]:
                    monomials.append(term['rate'])

            # Dictionary whose keys are the symbolic monomials and the values are the simulation results
            mons_dict = {}
            for mon_p in monomials:
                mon_p_values = mon_p.subs(param_values)
                var_prod = [atom for atom in mon_p_values.atoms(sympy.Symbol)]  # Variables of monomial
                arg_prod = [numpy.maximum(self.mach_eps, y[str(va)]) for va in var_prod]
                f_prod = sympy.lambdify(var_prod, mon_p_values)
                prod_values = f_prod(*arg_prod)
                mons_dict[mon_p] = prod_values

            # Dataframe whose rownames are the monomials and the columns contain their values at each time point
            mons_df = pd.DataFrame(mons_dict).T

            signature_species = mons_df.apply(self.choose_max2, args=(diff_par, self.all_comb[sp], type_sign))
            all_signatures[sp] = list(signature_species)

        # self.all_sp_signatures = all_signatures

        if sp_to_visualize:
            self.visualization2(y, all_signatures, param_values, sp_to_visualize)

        return all_signatures
def display_observables(params_estimated):
    """Save a figure of the observables with different parameter values and their distributions

        keyword arguments:
        params_estimated -- list of parameter sets
    """
    fig, axApop = plt.subplots(figsize=(7, 7))
    # Construct matrix of experimental data and variance columns of interest
    exp_obs_norm = exp_data[data_names].view(float).reshape(len(exp_data), -1).T
    var_norm = exp_data[var_names].view(float).reshape(len(exp_data), -1).T
    std_norm = var_norm ** 0.5
    obs_names_disp = obs_names + ['aSmac']
    totals = obs_totals + [momp_obs_total]

    cparp_info = [0] * len(params_estimated)
    cparp_info_fraction = [0] * len(params_estimated)

    # Plot experimental data and simulation on the same axes
    colors = ('r', 'b')
    obs_range = [0, 1]
    for exp, exp_err, obs, c in zip([exp_obs_norm[1]], [std_norm[1]], [obs_range[1]], [colors[1]]):



        for idx, par in enumerate(params_estimated):
            params = hf.read_pars(par)
            # params[62] -= params[62] * 0.89
            solver.run(params)
            sim_obs = solver.yobs[obs_names_disp].view(float).reshape(len(solver.yobs), -1)
            sim_obs_norm = (sim_obs / totals).T
            cparp_info[idx] = curve_fit(sig_apop, solver.tspan, sim_obs_norm[1], p0=[100, 100, 100])[0]
            cparp_info_fraction[idx] = sim_obs_norm[1][-1]
            # axApop.plot(solver.tspan, sim_obs_norm[obs], color=c, alpha=0.5)
            axApop.plot(solver.tspan, sim_obs_norm[2], color='g', alpha=0.4)

        # axApop.plot(solver.tspan, sim_obs_norm[obs], color=c, alpha=0.5, label=obs_names[obs] + ' sim')

        # axApop.plot(solver.tspan, sim_obs_norm[obs], color=c, alpha=0.5, label=obs_names[obs] + ' sim')

        axApop.plot(solver.tspan, sim_obs_norm[2], color='g',  alpha=0.4, label='aSmac' + ' sim')
        axApop.vlines(momp_data[0], -0.05, 1.05, color='k', linestyle=':', label='aSmac' + ' data')


        # axApop.plot(exp_data['Time'], exp, color='k', marker='.', linestyle=':', label=obs_names[obs]+' data')
        # axApop.errorbar(exp_data['Time'], exp, yerr=exp_err, ecolor='k',
        #                 elinewidth=0.5, capsize=0, fmt=None)

    plt.xticks(rotation=-30)
    plt.xlabel('Time')
    plt.ylabel('Fraction')
    fig.tight_layout()

    divider = make_axes_locatable(axApop)
    axHistx = divider.append_axes("top", 1.2, pad=0.3, sharex=axApop)
    axHisty = divider.append_axes("right", 1.2, pad=0.3, sharey=axApop)
    # make some labels invisible
    plt.setp(axHistx.get_xticklabels() + axHisty.get_yticklabels(),
             visible=False)
    # now determine nice limits by hand:
    binwidth = 0.11
    binwidthx = 600
    xymax = np.max([np.max(np.fabs(solver.tspan)), np.max(np.fabs(1))])
    lim = (int(xymax / binwidth) + 1) * binwidth

    weightsx = np.ones_like(column(cparp_info, 1)) / len(column(cparp_info, 1))
    weightsy = np.ones_like(cparp_info_fraction) / len(cparp_info_fraction)

    axHisty.hist(cparp_info_fraction, orientation='horizontal', bins=np.arange(0, 1.01 + binwidth, binwidth),
                 weights=weightsy)
    axHistx.hist(column(cparp_info, 1), bins=np.arange(min(solver.tspan), max(solver.tspan) + binwidthx, binwidthx),
                 weights=weightsx)

    # axHistx.axis["bottom"].major_ticklabels.set_visible(False)
    for tl in axHistx.get_xticklabels():
        tl.set_visible(False)
    axHistx.set_yticks([0, 0.5, 1])
    # axHisty.axis["left"].major_ticklabels.set_visible(False)
    for tl in axHisty.get_yticklabels():
        tl.set_visible(False)
    axHisty.set_xticks([0, 0.5, 1])
    axApop.legend(loc=0)
    fig.savefig('/home/oscar/Documents/tropical_project/all_parameters_earm.png', format='png', dpi=400)
    return
    else:
        parameter_ic.name == 'Bcl2_0'

    sd = cv
    return lognormal(mean, sd, size)

parameters_ic = {idx: p for idx, p in enumerate(model.parameters) if p in model.parameters_initial_conditions()[1:]}

samples = 100

pso_pars = hf.listdir_fullpath('/home/oscar/Documents/tropical_project/parameters_5000')

all_pars_ic = np.zeros((len(pso_pars), len(model.parameters)))

for idx, pa in enumerate(pso_pars):
    pso_pars[idx] = hf.read_pars(pa)


repeated_parameter_values = np.repeat(pso_pars, samples, axis=0)

for idx, par in parameters_ic.items():
    repeated_parameter_values[:, idx] = sample_lognormal(par, size=samples*len(pso_pars))


def parameter_signatures(par, model, tspan):
    """

    :param par: parameter file path or vector of parameters
    :param model: PySB model
    :param tspan: time span
    :return: tropical signatures of input parameters