def merge_sudden_markov_fitness_sims(input_fnames, output_fname):
    """
    Merge all fitness simulation data into one pickle file.
    """
    print "merging fitness simulation files"
    all_sims = OrderedDict()
    for input_fname in input_fnames:
        data = simulation.load_data(input_fname)
        sim_cond = data["sim_cond"]
        all_sims["sim%d" %(sim_cond)] = data
    with open(output_fname, "w") as outfile:
        pickle.dump(all_sims, outfile)
def plot_switch_ssm_fitness_simulations(input_fname, plot_fname, label):
    """
    Plot switch SSM fitness simulations.
    """
    print "plotting fitness simulation for switch ssm"
    sim_info = simulation.load_data(input_fname)
    results = sim_info["data"]
    # make the plot here for three of the simulations
    sims_to_plot = ["switch_ssm_fitness_sim1",
                    "switch_ssm_fitness_sim2",
                    "switch_ssm_fitness_sim3",
                    "switch_ssm_fitness_sim4"]
    num_plots = len(sims_to_plot)
    fig = plt.figure(figsize=(10, 6))
    sns.set_style("ticks")
    ystep = 10
    yticks = np.arange(10, 40 + ystep, ystep)
    print yticks, "yticks"
    for n, sim_to_plot in enumerate(sims_to_plot):
        if sim_to_plot not in results:
            raise Exception, "No sim %s" %(sim_to_plot)
        params = results[sim_to_plot]["params"]
        params["policy_colors"] = \
          {"Random": sns.color_palette("Set1")[1],
           "Plastic": sns.color_palette("Set1")[2],
           "Posterior predictive": sns.color_palette("Set1")[0],
           "Glucose-only": sns.color_palette("Set1")[3]}
#           "Posterior pred. (BH)": "red",
#           "Random (BH)": "g"}
        plt.subplot(2, int(round(num_plots / 2.)), n + 1)
        gluc_val = params["nutr_labels"].index("glucose")
        galac_val = params["nutr_labels"].index("galactose")
        gluc_growth_rate = params["nutr_growth_rates"][gluc_val]
        galac_growth_rate = params["nutr_growth_rates"][galac_val]
        # title = r"$\mu_{\mathsf{Glu}} = %.2f, \mu_{\mathsf{Gal}} = %.3f$, " \
        #         r"$\mu_{\mathsf{Mis}} = %.1f$, " \
        #         r"$p_1 = %.2f, p_2 = %.2f$" \
        #         %(gluc_growth_rate,
        #           galac_growth_rate,
        #           params["mismatch_growth_rate"],
        #           params["p_switch_to_switch"],
        #           params["p_noswitch_to_switch"])
        title = r"$p_1 = %.2f, p_2 = %.2f$" \
                 %(params["p_switch_to_switch"],
                   params["p_noswitch_to_switch"])
        sim_results = results[sim_to_plot]["data"]
        model_switch_ssm.plot_fitness_sim_results(sim_results, params,
                                                  title=title,
                                                  yticks=yticks)
    fig.set_tight_layout(True)
    plt.savefig(plot_fname)
def plot_sudden_markov_popsize(data_fname, plot_fname):
    """
    Plot sudden Markov model population size for different growth
    policies.
    """
    print "plotting: %s" %(os.path.basename(plot_fname))
    print "  - data: %s" %(data_fname)
    sim_data = simulation.load_data(data_fname)
    sns.set_style("ticks")
    df = sim_data["sim_results"]
    params = sim_data["params"]
    plt.figure(figsize=(6, 4))
    model_sudden_markov.plot_popsize_by_policies(df, params)
    plt.savefig(plot_fname)
def plot_sudden_ssm_filtering(input_fname, plot_fname, label):
    """
    Plot SSM filtering predictions.
    """
    print "plotting: %s" %(os.path.basename(plot_fname))
    fig = plt.figure(figsize=(7, 5))
    sns.set_style("ticks")
    all_results = simulation.load_data(input_fname)
    all_results = all_results["model"]
    num_plots = len(all_results)
    total_plots = num_plots * 2
    gs = gridspec.GridSpec(total_plots, 1,
                           height_ratios=[1, 0.2]*num_plots)
    curr_plot_num = 0
    axes = {}
    for n, data_label in enumerate(all_results.keys()):
        data_set = all_results[data_label]
        params = data_set["params"]
        time_obj = time_unit.Time(params["t_start"],
                                  params["t_end"],
                                  step_size=params["step_size"])
        c = 0.8
        x_axis = time_obj.t[0::4]
        xlims = [time_obj.t[0] - c, time_obj.t[-1] + c]
        ax1 = plt.subplot(gs[curr_plot_num, 0])
        pred_probs = [p[0] for p in data_set["preds_with_lag"]]
        plt.plot(time_obj.t, pred_probs, "-o", color=plot_utils.red,
                 label="Prediction",
                 clip_on=False,
                 zorder=100)
        plt.xlabel(r"Time step")
        plt.ylabel(r"$P(C_{t+1} =\ \mathsf{Glu} \mid  C_{0:t})$",
                   fontsize=11)
        plt.title("lag = %d" %(params["decision_lag_time"]), fontsize=8)
        plt.legend(loc="lower right")
        plt.xticks(x_axis, fontsize=8)
        plt.xlim(xlims)
        plt.ylim([0, 1])
        plt.yticks(np.arange(0, 1 + 0.2, 0.2))
        ax2 = plt.subplot(gs[curr_plot_num + 1, 0])
        data_to_labels = {0: "Glu", 1: "Gal"}
        labels_to_colors = {"Glu": plot_utils.green, "Gal": plot_utils.blue}
        data = params["data"]
        ax2.get_yaxis().set_visible(False)
        ax2.set_yticks([])
        ax2.spines["left"].set_visible(False)
        plot_utils.plot_sudden_switches(time_obj, data,
                                        data_to_labels=data_to_labels,
                                        labels_to_colors=labels_to_colors,
                                        box_height=0.025,
                                        y_val=0.02,
                                        ax=ax2,
                                        despine=False,
                                        with_legend=True,
                                        legend_outside=(0,1))
        plt.xticks(x_axis, fontsize=8)
        plt.xlim(xlims)
        # despine axes
        sns.despine(trim=True, left=True, ax=ax2)
        sns.despine(trim=True, ax=ax1)
        # advance number of plots by two
        curr_plot_num += 2
    ax1.spines["left"].set_visible(True)
    #plt.tight_layout(h_pad=0.1)
    fig.set_tight_layout(True)
    plt.savefig(plot_fname)
示例#5
0
##
##
##
import numpy as np
import pandas
import utils
import fitness
import simulation
import scipy
from scipy.interpolate import interp1d
import matplotlib.pylab as plt

f = "../simulations_data/sudden_switch/merged_switch_ssm_fitness_sims.data"

sim_info = simulation.load_data(f)
results = sim_info["data"]
# get the simulations that should be plotted based on their
# parameter values
params_to_plot = [{"p_switch_to_switch": 0.1,
                   "p_noswitch_to_switch": 0.1},
                  {"p_switch_to_switch": 0.1,
                   "p_noswitch_to_switch": 0.95},
                  {"p_switch_to_switch": 0.95,
                   "p_noswitch_to_switch": 0.1},
                  {"p_switch_to_switch": 0.95,
                   "p_noswitch_to_switch": 0.95}]
sims_to_plot = []
for sim_name in results:
    # see if current simulation matches the parameters
    # we're looking for
    for curr_params in params_to_plot: