Ejemplo n.º 1
0
def run_switch_ssm_fitness_simulations(input_fnames, output_fname,
                                       sim_params, sim_label):
    """
    Run switch SSM fitness simulations.
    Compare the results of different growth policies.
    """
    print "running switch ssm fitness simulations..."
    fitness_params_fname = input_fnames[0]
    ssm_params_fname = input_fnames[1]
    params = simulation.load_params(fitness_params_fname)
    model_params = simulation.load_params(ssm_params_fname)
    params.update(model_params)
    all_policies = OrderedDict()
    all_policies["Posterior predictive"] = policies.posterior_pred_policy
    all_policies["Plastic"] = policies.plastic_growth_policy
    all_policies["Random"] = policies.rand_growth_policy
    all_policies["Glucose-only"] = policies.glu_only_growth_policy
    all_policies["Posterior pred. (BH)"] = policies.bh_particle_filter_policy
    all_policies["Random (BH)"] = policies.bh_rand_growth_policy
    # fixed parameters for all simulations
    p_init_output = params["p_init_output"]
    time_obj = time_unit.Time(params["t_start"],
                              params["t_end"],
                              step_size=params["step_size"])
    # include model parameters in into simulation parameters set
    # so that the policies that need to run the model (like the
    # posterior predictive policy) can access it
    params.update(sim_params)
    # include list of policies we ran
    params["policies"] = all_policies.keys()
    # setting of probabilities for data-generating SSM model
    p_switch_to_switch = params["p_switch_to_switch"]
    p_noswitch_to_switch = params["p_noswitch_to_switch"]
    nutr_labels = params["nutr_labels"]
    nutr_growth_rates = params["nutr_growth_rates"]
    out_trans_mat1 = params["out_trans_mat1"]
    out_trans_mat2 = params["out_trans_mat2"]
    def nutrient_simulator(time_obj):
        return nutrient_simulators.ssm_nutrient_simulator(time_obj,
                                                          out_trans_mat1=out_trans_mat1,
                                                          out_trans_mat2=out_trans_mat2,
                                                          p_switch_to_switch=p_switch_to_switch,
                                                          p_noswitch_to_switch=p_noswitch_to_switch,
                                                          p_init_output=p_init_output)

    # simulate mixed sugar environment
    env_obj = \
      env.MixedDiscEnvironment(nutr_labels,
                               nutrient_simulator,
                               nutr_growth_rates=nutr_growth_rates)
    fitness_obj = fitness.FitnessSim(all_policies, env_obj, params)
    #sim_results = {}
    sim_results = fitness_obj.simulate(time_obj)
    final_results = {"sim_params": sim_params,
                     "sim_results": sim_results}
    utils.save_as_pickle(output_fname, sim_results,
                         extra={"params": params})
Ejemplo n.º 2
0
def plot_sudden_markov_fixed_decision_mat(input_fname, plot_fname, label):
    """
    Plot decision matrix for sudden switch Markov model, with
    FIXED growth rates for glucose and galactose.
    """
    print "plotting: %s" %(os.path.basename(plot_fname))
    plt.figure(figsize=(5, 4))
    params = simulation.load_params(MARKOV_PARAM_FNAME)
    params["gluc_growth_rate"] = 0.3
    params["galac_growth_rate"] = 0.075
    model_sudden_markov.plot_decision_mat(params)
    plt.tight_layout()
    plt.savefig(plot_fname)
Ejemplo n.º 3
0
def run_bet_hedge_sims_2_nutr(param_fname, output_fname, label):
    """
    Running bet hedging simulations for two nutrients.
    """
    print "running bet hedge simulations (2 nutrients)..."
    # simulate two nutrient model
    params = simulation.load_params(param_fname)
    print "params: ", params
    data = {}
    extra = {"params": params}
    # run bet hedging simulation
    ###
    ### need skeleton code here
    ###
    # save results as a pickle file
    utils.save_as_pickle(output_fname, data, extra)
Ejemplo n.º 4
0
def get_sudden_markov_fitness_params():
#    gluc_growth_rates = [0.3]
#    galac_growth_rates = [0.04, 0.15, 0.29]
    gluc_growth_rates = [0.7]
    galac_growth_rates = [0.175, 0.35, 0.68]
    gluc_to_gluc_probs = [0.1, 0.3, 0.5, 0.8]
    galac_to_gluc_probs = [0.1, 0.3, 0.5, 0.8]
    sim_cond = 1
    basename = "sudden_markov"
    for gluc_rate in gluc_growth_rates:
        for galac_rate in galac_growth_rates:
            for gluc_prob in gluc_to_gluc_probs:
                for galac_prob in galac_to_gluc_probs:
                    output_fname = os.path.join(paths.SUDDEN_DATA_DIR,
                                                "%s_sim%d.fitness.data" %(basename, sim_cond))
                    # simulate all parameter values
                    params = simulation.load_params(MARKOV_PARAM_FNAME)
                    params["gluc_growth_rate"] = gluc_rate
                    params["galac_growth_rate"] = galac_rate
                    params["true_gluc_to_gluc"] = gluc_prob
                    params["true_galac_to_gluc"] = galac_prob
                    yield (MARKOV_PARAM_FNAME, output_fname, params, sim_cond)
                    sim_cond += 1
Ejemplo n.º 5
0
def plot_sudden_markov_variable_decision_mat(input_fname, plot_fname, label):
    """
    Plot decision matrix for sudden switch Markov model, with
    VARIABLE growth rates for glucose and galactose.
    """
    print "plotting: %s" %(os.path.basename(plot_fname))
    fig = plt.figure(figsize=(6, 3.1))
    params = simulation.load_params(MARKOV_PARAM_FNAME)
    params["gluc_growth_rate"] = 0.3
    # 4-fold lower growth rate, 2-fold, nearly equal growth rates
    galac_growth_rates = [0.075, 0.15, 0.28]
    num_plots = len(galac_growth_rates)
    # set heatmap aspect equal
    plt.gca().set_aspect("equal")
    sns.set_style("white")
    for plot_num, galac_growth_rate in enumerate(galac_growth_rates):
        show_x_label = False
        show_y_label = False
        show_colorbar_label = False
        params["galac_growth_rate"] = galac_growth_rate
        plt.subplot(1, num_plots, plot_num + 1)
        if (plot_num + 1) == 1:
            show_x_label = False
            show_y_label = True
        elif (plot_num + 1) == 2:
            show_x_label = True
            show_y_label = False
        elif (plot_num + 1) == 3:
            show_x_label = False
            show_colorbar_label = True
        model_sudden_markov.plot_decision_mat(params,
                                              show_x_label=show_x_label,
                                              show_y_label=show_y_label,
                                              show_colorbar_label=show_colorbar_label)
    plt.subplots_adjust(wspace=0.5, left=0.1)
    fig.set_tight_layout(True)
    plt.savefig(plot_fname)
Ejemplo n.º 6
0
def get_switch_ssm_fitness_params():
    # parameters common to all nutrient simulations
    # (regardless of whether it's with 2 or 3 nutrients)
    all_p_switch_to_switch = [0.1, 0.95]
    all_p_noswitch_to_switch = [0.1, 0.95]
    all_p_init_switch = [0.5]
    ## 3-nutrient related variables
    # diagonal heavy: 3 sticky nutrients
    sticky_3_nutr_trans_mat = \
      np.array([[0.9, 0.05, 0.05],
                [0.05, 0.9, 0.05],
                [0.05, 0.05, 0.9]])
    # periodic glu/gal and sticky mal
    periodic_sticky_mal_trans_mat = \
      np.array([[0.05, 0.9, 0.05],
                [0.9, 0.05, 0.05],
                [0.05, 0.05, 0.9]])
    # glu predictive of gal; gal predictive of mal;
    # sticky mal state
    glu_pred_gal_pred_mal_trans_mat = \
      np.array([[0.05, 0.9, 0.05],
                [0.1, 0.6, 0.3],
                [0.05, 0.05, 0.9]])
    ### READ THESE FROM FILE
    # load 2-nutrient params file
    two_nutr_params = simulation.load_params(FITNESS_2_NUTR_SIM_PARAM_FNAME)
    two_nutr_growth_rates = two_nutr_params["nutr_growth_rates"]
    # load 3-nutrient params file
    three_nutr_params = simulation.load_params(FITNESS_3_NUTR_SIM_PARAM_FNAME)
    three_nutr_growth_rates = three_nutr_params["nutr_growth_rates"]
    # 2-nutrient parameters
    nutrient_params = \
      {"2_nutr": \
       {"fitness_params_fname": FITNESS_2_NUTR_SIM_PARAM_FNAME,
        "model_params_fname": SSM_2_NUTR_PARAM_FNAME,
        "nutr_labels": ["glucose", "galactose"],
        # list of all growth rates to consider
        # format is [[gluc_growth_rate1, galac_growth_rate1],
        #            [gluc_growth_rate2, galac_growth_rate2],
        #            ...]
        "all_nutr_growth_rates": \
        [two_nutr_growth_rates],
        "all_out_trans_mats": \
        [[np.array([[0., 1],
                    [1., 0]]),
          np.array([[1., 0.],
                    [1., 0.]])]]},
       "3_nutr": \
       {"fitness_params_fname": FITNESS_3_NUTR_SIM_PARAM_FNAME,
        "model_params_fname": SSM_3_NUTR_PARAM_FNAME,
        "nutr_labels": ["glucose", "galactose", "maltose"],
        "all_nutr_growth_rates": \
        [three_nutr_growth_rates],
        "all_out_trans_mats": \
        [[glu_pred_gal_pred_mal_trans_mat,
          periodic_sticky_mal_trans_mat]]}}
    # 3-nutrient parameters
    ### TODO: fill this in -- add matrices for 3 nutrient
    ### simulations
    fitness_params = {}
    sim_num = 1
    ### TODO: here, add 2-nutrient or 3-nutrient as a paramter
    ### so that the subsequent pipeline function can run on
    ### both 2-nutrient and 3-nutrient fitness simulations
    for sim_type in nutrient_params:
        curr_params = nutrient_params[sim_type]
        input_fnames = [curr_params["fitness_params_fname"],
                        curr_params["model_params_fname"]]
        for p_switch_to_switch in all_p_switch_to_switch:
            for p_noswitch_to_switch in all_p_noswitch_to_switch:
                for nutr_growth_rates in curr_params["all_nutr_growth_rates"]:
                    for out_trans_mats in curr_params["all_out_trans_mats"]:
                        sim_params = \
                          {"nutr_labels": curr_params["nutr_labels"],
                           "out_trans_mat1": out_trans_mats[0],
                           "out_trans_mat2": out_trans_mats[1],
                           "nutr_growth_rates": nutr_growth_rates,
                           "p_switch_to_switch": p_switch_to_switch,
                           "p_noswitch_to_switch": p_noswitch_to_switch,
                           "out_trans_mats": out_trans_mats}
                        sim_cond = "sim_%d" %(sim_num)
                        output_fname = \
                          os.path.join(paths.SUDDEN_DATA_DIR,
                                       "switch_ssm_fitness_sim%d.data" %(sim_num))
                        yield (input_fnames, output_fname, sim_params, sim_cond)
                        sim_num += 1
Ejemplo n.º 7
0
def make_sudden_ssm_model_comparison(input_fname, output_fname, label):
    """
    Run discrete switching SSM model and compare the results for
    prediction, filtering and smoothing.
    """
    print "making switching SSM model from: %s" %(input_fname)
    data_sets = OrderedDict()
#    data_sets["period_noperiod"] = \
#      np.array([0, 1] * 10 + [0, 0] * 10)
    data_sets["period_noperiod_period"] = \
      np.array([0, 1] * 10 + [0, 0] * 10 + \
               [0, 1] * 10)
    data_sets["period_noperiod_period_noperiod"] = \
      np.array([0, 1] * 10 + [0, 0] * 10 + \
               [0, 1] * 10 + \
               [0, 0] * 10)
    all_results = OrderedDict()
    for data_label in data_sets:
        params = simulation.load_params(input_fname)
        init_switch_hyperparams = np.array(params["init_switch_hyperparams"])
        init_out_hyperparams = np.array(params["init_out_hyperparams"])
        switch_trans_mat_hyperparams = \
          np.array(params["switch_trans_mat_hyperparams"])
        out_trans_mat_hyperparams = np.array(params["out_trans_mat_hyperparams"])
        sticky_switch_weight = params["sticky_switch_weight"]
        num_switch_states = params["num_switch_states"]
        num_outputs = params["num_outputs"]
        num_particles = 200
        ssm_pf = \
          particle_filter.DiscreteSwitchSSM_PF(num_switch_states,
                                               num_outputs,
                                               num_particles=num_particles,
                                               init_switch_hyperparams=init_switch_hyperparams,
                                               init_out_hyperparams=init_out_hyperparams,
                                               switch_trans_mat_hyperparams=switch_trans_mat_hyperparams,
                                               out_trans_mat_hyperparams=out_trans_mat_hyperparams,
                                               sticky_switch_weight=sticky_switch_weight)
        data = data_sets[data_label]
        # time for simulation
        params["t_step"] = 1
        params["t_start"] = 0
        params["t_end"] = len(data) - params["t_step"]
        params["data"] = data
        # get filtering predictions
        print "running filtering predictions: "
        t1 = time.time()
        ssm_pf.initialize()
        ssm_pf.process_data(data, save_steps=True)
        t2 = time.time()
        print "filtering took %.2f" %(t2 - t1)
        # get predictions with lags
        print "getting predictions with lag"
        prev_output = data[-1]
        num_preds = 10
        t1 = time.time()
        preds_with_lag = ssm_pf.prediction_with_lag(data, lag=1)
        t2 = time.time()
        print "predictions with lag took %.2f seconds" %(t2 - t1)
        model_results = {"params": params,
                         "preds_with_lag": preds_with_lag,
                         "model": ssm_pf.prior}
        all_results[data_label] = model_results
    utils.save_model_helper(output_fname, all_results)