示例#1
0
                                          parameters={
                                              'IFNAR1_IC': 0,
                                              'IFNAR2_IC': 0,
                                              'IFN_alpha2_IC': 0,
                                              'IFN_beta_IC': 0
                                          },
                                          return_type='dataframe',
                                          dataframe_labels='IFNgamma')

pSTAT1_df = IfnData(name='custom', df=model_res.xs(['pSTAT1']))
pSTAT3_df = IfnData(name='custom', df=model_res.xs(['pSTAT3']))

STAT1_palette = sns.color_palette("cubehelix", 6)
STAT3_palette = sns.color_palette("cubehelix", 6)

fig = DoseresponsePlot((1, 2))
fig.axes[0].set_title('pSTAT1')
fig.axes[1].set_title('pSTAT3')
for idx, t in enumerate(times):
    fig.add_trajectory(pSTAT1_df,
                       t,
                       'plot',
                       STAT1_palette[idx], (0, 0),
                       'IFNgamma',
                       label=str(t) + ' min',
                       linewidth=2)
    fig.add_trajectory(pSTAT3_df,
                       t,
                       'plot',
                       STAT3_palette[idx], (0, 1),
                       'IFNgamma',
                               parameters={'Ia': 0}, dataframe_labels='Beta', sf=scale_factor, **DR_KWARGS)

    # ----------------------------------------
    # Finally, plot both models in comparison
    # ----------------------------------------
    fig = plt.figure(figsize=(6.4 * 2.5, 4.8))
    gs = gridspec.GridSpec(nrows=1, ncols=5)
    panelA = fig.add_subplot(gs[0, 0:2])
    panelB = fig.add_subplot(gs[0, 2:4])
    for ax in [panelA, panelB]:
        ax.set(xscale='log', yscale='linear')
        ax.set_xlabel('Dose (pM)')
        ax.set_ylabel('Response')
    legend_panel = fig.add_subplot(gs[0, 4])

    new_fit = DoseresponsePlot((1, 2))
    new_fit.fig = fig
    new_fit.axes = [panelA, panelB, legend_panel]

    alpha_palette = sns.color_palette("rocket_r", 6)
    beta_palette = sns.color_palette("rocket_r", 6)
    t_mask = [2.5, 7.5, 20.]
    # Add fits
    for idx, t in enumerate(times):
        if t not in t_mask:
            new_fit.add_trajectory(dra_s, t, 'plot', alpha_palette[idx], (0, 0), 'Alpha', linewidth=2.0)
            new_fit.add_trajectory(dra_d, t, 'plot', '--', (0, 0), 'Alpha', color=alpha_palette[idx], linewidth=2.0)
            new_fit.add_trajectory(drb_s, t, 'plot', beta_palette[idx], (0, 1), 'Beta', linewidth=2.0)
            new_fit.add_trajectory(drb_d, t, 'plot', '--', (0, 1), 'Beta', color=beta_palette[idx], linewidth=2.0)

    new_fit.show_figure(show_flag=False, save_flag=False)
示例#3
0
    newdata_2 = IfnData("20190119_pSTAT1_IFN_Bcell")
    newdata_3 = IfnData("20190121_pSTAT1_IFN_Bcell")
    newdata_4 = IfnData("20190214_pSTAT1_IFN_Bcell")

    times = [2.5, 5, 7.5, 10, 20, 60]
    alpha_doses = [0, 10, 100, 300, 1000, 3000, 10000, 100000]
    beta_doses = [0, 0.2, 6, 20, 60, 200, 600, 2000]
    #beta_doses_20181113 = [0.1, 1, 5, 10, 100, 200, 1000]
    #alpha_doses_20181113 = [5, 50, 250, 500, 5000, 25000, 50000]

    alpha_palette_new = sns.color_palette("Reds", 6)
    beta_palette_new = sns.color_palette("Greens", 6)
    alpha_palette_old = sns.color_palette("Reds", 6)
    beta_palette_old = sns.color_palette("Greens", 6)

    data_plot_dr = DoseresponsePlot((4, 2))
    alpha_mask = []
    beta_mask = []

    # Add data
    for idx, t in enumerate(times):
        if t not in alpha_mask:
            data_plot_dr.add_trajectory(newdata_4,
                                        t,
                                        'scatter',
                                        alpha_palette_new[idx], (3, 0),
                                        'Alpha',
                                        dn=1)
            data_plot_dr.add_trajectory(newdata_4,
                                        t,
                                        'plot',
示例#4
0
                                     simulation_doses,
                                     parameters={'Ia': 0},
                                     return_type='dataframe',
                                     dataframe_labels='Beta')

    for i in range(len(times)):
        dradf.loc['Alpha'].iloc[:, i] = dradf.loc['Alpha'].iloc[:, i].apply(
            scale_data)
        drbdf.loc['Beta'].iloc[:,
                               i] = drbdf.loc['Beta'].iloc[:,
                                                           i].apply(scale_data)

    dra60 = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb60 = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    new_fit = DoseresponsePlot((3, 1))
    new_fit.axes[0].set_title("{} minutes".format(times[0]))
    new_fit.axes[0].set_xlabel("")
    new_fit.axes[1].set_title("{} minutes".format(times[1]))
    new_fit.axes[1].set_xlabel("")
    new_fit.axes[2].set_title("{} minutes".format(times[2]))
    new_fit.axes[2].set_xlabel("Dose (pM)")
    new_fit.fig.set_size_inches(8.5, 25.5)
    alpha_mask = []
    beta_mask = []
    # Add fits
    for idx, t in enumerate([el for el in times]):
        if t not in alpha_mask:
            new_fit.add_trajectory(dra60,
                                   t,
                                   'plot',
示例#5
0
def check_plots():
    smooth_plot = DoseresponsePlot((1, 2))
    alpha_palette = sns.color_palette("Reds", 6)
    beta_palette = sns.color_palette("Greens", 6)

    smooth_plot.add_trajectory(a5smoothIfnData, 5, 'plot', alpha_palette[0],
                               (0, 0), 'Alpha')
    smooth_plot.add_trajectory(a15smoothIfnData, 15, 'plot', alpha_palette[1],
                               (0, 0), 'Alpha')
    smooth_plot.add_trajectory(a30smoothIfnData, 30, 'plot', alpha_palette[2],
                               (0, 0), 'Alpha')
    smooth_plot.add_trajectory(a60smoothIfnData, 60, 'plot', alpha_palette[3],
                               (0, 0), 'Alpha')

    smooth_plot.add_trajectory(b5smoothIfnData, 5, 'plot', beta_palette[0],
                               (0, 1), 'Beta')
    smooth_plot.add_trajectory(b15smoothIfnData, 15, 'plot', beta_palette[1],
                               (0, 1), 'Beta')
    smooth_plot.add_trajectory(b30smoothIfnData, 30, 'plot', beta_palette[2],
                               (0, 1), 'Beta')
    smooth_plot.add_trajectory(b60smoothIfnData, 60, 'plot', beta_palette[3],
                               (0, 1), 'Beta')

    for idx, t in enumerate([5, 15, 30, 60]):
        smooth_plot.add_trajectory(newdata,
                                   t,
                                   'scatter',
                                   alpha_palette[idx], (0, 0),
                                   'Alpha',
                                   dn=1)
        smooth_plot.add_trajectory(newdata,
                                   t,
                                   'scatter',
                                   beta_palette[idx], (0, 1),
                                   'Beta',
                                   dn=1)

    fig, axes = smooth_plot.show_figure()
示例#6
0
    ec50_20190214 = newdata_4.get_ec50s()

    # Aligned data, to get scale factors for each data set
    alignment = DataAlignment()
    alignment.add_data([newdata_4, newdata_3, newdata_2, newdata_1])
    alignment.align()
    alignment.get_scaled_data()
    mean_data = alignment.summarize_data()

    # -------------------------------
    # Plot model dose response curves
    # -------------------------------
    alpha_palette = sns.color_palette("rocket_r")
    beta_palette = sns.color_palette("rocket_r")

    new_fit = DoseresponsePlot((1, 2))
    new_fit.axes[0].set_ylabel('pSTAT1 (MFI)')
    new_fit.axes[1].set_ylabel('pSTAT1 (MFI)')

    alpha_mask = [7.5, 10.0]
    beta_mask = [7.5, 10.0]
    # Add fits
    for idx, t in enumerate([2.5, 5.0, 7.5, 10.0, 20.0, 60.0]):
        new_fit.add_trajectory(mean_data,
                               t,
                               'errorbar',
                               'o', (0, 0),
                               'Alpha',
                               color=alpha_palette[idx])
        new_fit.add_trajectory(mean_data,
                               t,
示例#7
0
    dra25df = stepfit25.model.doseresponse([5, 10, 20, 60], 'TotalpSTAT', 'Ia', list(logspace(-3, 5)),
                                  parameters={'Ib': 0}, return_type='dataframe', dataframe_labels='Alpha')
    drb25df = stepfit25.model.doseresponse([5, 10, 20, 60], 'TotalpSTAT', 'Ib', list(logspace(-3, 4)),
                                  parameters={'Ia': 0}, return_type='dataframe', dataframe_labels='Beta')

    # Scale by best fit scale factor, so comparison to data is good
    for i in range(4):
        dra25df.loc['Alpha'].iloc[:, i] = dra25df.loc['Alpha'].iloc[:, i].apply(scale_data)
        drb25df.loc['Beta'].iloc[:, i] = drb25df.loc['Beta'].iloc[:, i].apply(scale_data)

    # Make the DR curves into IfnData objects, for easy plotting
    dra25 = IfnData('custom', df=dra25df, conditions={'Alpha': {'Ib': 0}})
    drb25 = IfnData('custom', df=drb25df, conditions={'Beta': {'Ia': 0}})

    # Generate figure by adding simulations, then data
    results_plot = DoseresponsePlot((1, 2))
    for idx, t in enumerate(['5', '10', '20', '60']):
        results_plot.add_trajectory(dra25, t, 'plot', alpha_palette[idx], (0, 0), 'Alpha')
        results_plot.add_trajectory(drb25, t, 'plot', beta_palette[idx], (0,1), 'Beta')
    for idx, t in enumerate([5, 10, 20, 60]):
        results_plot.add_trajectory(newdata, t, 'scatter', alpha_palette[idx], (0, 0), 'Alpha', dn=1)
        results_plot.add_trajectory(newdata, t, 'scatter', beta_palette[idx], (0, 1), 'Beta', dn=1)

    results_plot.save_figure()

    # Now try to fit the 60 minute data starting from the 2.5 minute results
    # ----------------------------------------------------------------------
    stepfit60 = StepwiseFit(stepfit25.model, smooth60IfnData,
                            {'kSOCSon': (1E-8, 1E-7), 'kd4': (0.03, 0.1), 'k_d4': (0.03, 0.1),
                             'krec_a2': (0.0005, 0.05), 'krec_b2': (0.01, 0.0001),
                             'krec_a1': (0.00003, 0.003), 'krec_b1': (0.001, 0.00001)}, n=2)
示例#8
0
def testing_specific_values():
    volEC1 = 1 / (25E9)
    volEC2 = 1E-5
    # --------------------
    # Set up Model
    # --------------------
    # Parameters found by stepwise fitting GAB mean data
    # Note: can remove multiplicative factors on all K1, K2, K4 and still get very good fit to data (worst is 5 min beta)
    initial_parameters = {
        'k_a1': 4.98E-14 * 2,
        'k_a2': 8.30e-13 * 2,
        'k_d4': 0.006 * 3.8,
        'kpu': 0.00095,
        'ka2': 4.98e-13 * 2.45,
        'kd4': 0.3 * 2.867,
        'kint_a': 0.000124,
        'kint_b': 0.00086,
        'krec_a1': 0.0028,
        'krec_a2': 0.01,
        'krec_b1': 0.005,
        'krec_b2': 0.05
    }
    dual_parameters = {
        'kint_a': 0.00052,
        'kSOCSon': 6e-07,
        'kint_b': 0.00052,
        'krec_a1': 0.001,
        'krec_a2': 0.1,
        'krec_b1': 0.005,
        'krec_b2': 0.05
    }
    scale_factor = 1.227

    Mixed_Model = DualMixedPopulation('Mixed_IFN_ppCompatible', 0.8, 0.2)
    Mixed_Model.model_1.set_parameters(initial_parameters)
    Mixed_Model.model_1.set_parameters(dual_parameters)
    Mixed_Model.model_1.set_parameters({'R1': 12000.0, 'R2': 1511.1})
    Mixed_Model.model_2.set_parameters(initial_parameters)
    Mixed_Model.model_2.set_parameters(dual_parameters)
    Mixed_Model.model_2.set_parameters({'R1': 6755.56, 'R2': 1511.1})

    # ---------------------------------
    # Make theory dose response curves
    # ---------------------------------
    # Make predictions
    times = np.arange(0, 120, 0.5)  # [2.5, 5.0, 7.5, 10.0, 20.0, 60.0]
    alpha_doses_20190108 = [0, 10, 100, 300, 1000, 3000, 10000, 100000]
    beta_doses_20190108 = [0, 0.2, 6, 20, 60, 200, 600, 2000]

    # 1 uL
    ka1 = Mixed_Model.model_1.parameters['ka1']
    ka2 = Mixed_Model.model_1.parameters['ka2']
    k_a1 = Mixed_Model.model_1.parameters['k_a1']
    k_a2 = Mixed_Model.model_1.parameters['k_a2']
    Mixed_Model.set_global_parameters({
        'volEC': volEC1,
        'ka1': ka1 * 1E-5 / volEC1,
        'ka2': ka2 * 1E-5 / volEC1,
        'k_a1': k_a1 * 1E-5 / volEC1,
        'k_a2': k_a2 * 1E-5 / volEC1
    })
    dradf = Mixed_Model.mixed_dose_response(times,
                                            'TotalpSTAT',
                                            'Ia',
                                            list(logspace(1, 5.2)),
                                            parameters={'Ib': 0},
                                            sf=scale_factor)
    drbdf = Mixed_Model.mixed_dose_response(times,
                                            'TotalpSTAT',
                                            'Ib',
                                            list(logspace(-1, 4)),
                                            parameters={'Ia': 0},
                                            sf=scale_factor)

    dra15uL = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb15uL = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    # 1 mL
    Mixed_Model.set_global_parameters({
        'volEC': volEC2,
        'ka1': ka1 * 1E-5 / volEC2,
        'ka2': ka2 * 1E-5 / volEC2,
        'k_a1': k_a1 * 1E-5 / volEC2,
        'k_a2': k_a2 * 1E-5 / volEC2
    })
    dradf = Mixed_Model.mixed_dose_response(times,
                                            'TotalpSTAT',
                                            'Ia',
                                            list(logspace(1, 5.2)),
                                            parameters={'Ib': 0},
                                            sf=scale_factor)
    drbdf = Mixed_Model.mixed_dose_response(times,
                                            'TotalpSTAT',
                                            'Ib',
                                            list(logspace(-1, 4)),
                                            parameters={'Ia': 0},
                                            sf=scale_factor)

    dra5mL = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb5mL = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    # -------------------------------
    # Plot model dose response curves
    # -------------------------------
    alpha_palette = sns.color_palette("deep", 6)
    beta_palette = sns.color_palette("deep", 6)

    new_fit = DoseresponsePlot((2, 2))

    alpha_mask = [2.5, 5.0, 10.0, 20.0, 60.0]
    beta_mask = [2.5, 5.0, 10.0, 20.0, 60.0]
    # Add fits
    color_counter = -1
    for idx, t in enumerate(times):
        if t in alpha_mask:
            color_counter += 1
            new_fit.add_trajectory(dra15uL,
                                   t,
                                   'plot',
                                   alpha_palette[color_counter], (0, 0),
                                   'Alpha',
                                   label=str(t) + ' min',
                                   linewidth=2)
            new_fit.add_trajectory(dra5mL,
                                   t,
                                   'plot',
                                   alpha_palette[color_counter], (1, 0),
                                   'Alpha',
                                   label=str(t) + ' min',
                                   linewidth=2)

        if t in beta_mask:
            new_fit.add_trajectory(drb15uL,
                                   t,
                                   'plot',
                                   beta_palette[color_counter], (0, 1),
                                   'Beta',
                                   label=str(t) + ' min',
                                   linewidth=2)
            new_fit.add_trajectory(drb5mL,
                                   t,
                                   'plot',
                                   beta_palette[color_counter], (1, 1),
                                   'Beta',
                                   label=str(t) + ' min',
                                   linewidth=2)

    dr_fig, dr_axes = new_fit.show_figure()
    dr_axes[0][0].set_title(r'IFN$\alpha$ at {} L'.format(volEC1))
    dr_axes[0][1].set_title(r'IFN$\beta$ at {} L'.format(volEC1))
    dr_axes[1][0].set_title(r'IFN$\alpha$ at {} L'.format(volEC2))
    dr_axes[1][1].set_title(r'IFN$\beta$ at {} L'.format(volEC2))
    dr_fig.tight_layout()
    dr_fig.savefig('varying_reaction_volume_dr.pdf')

    # -------------------------------
    # Plot model dose response curves
    # -------------------------------
    tc_figure = TimecoursePlot((1, 2))

    alpha_testdose = list(logspace(1, 5.2))[24]
    beta_testdose = list(logspace(-1, 4))[17]
    print("Using {} for IFNalpha".format(alpha_testdose))
    print("Using {} for IFNbeta".format(beta_testdose))

    tc_figure.add_trajectory(dra15uL,
                             'plot',
                             '-',
                             subplot_idx=(0, 0),
                             label=r'IFN$\alpha$ at {} L'.format(volEC1),
                             doseslice=alpha_testdose,
                             dose_species='Alpha',
                             color=alpha_palette[1])
    tc_figure.add_trajectory(dra5mL,
                             'plot',
                             '-',
                             subplot_idx=(0, 0),
                             label=r'IFN$\alpha$ at {} L'.format(volEC2),
                             doseslice=alpha_testdose,
                             dose_species='Alpha',
                             color=alpha_palette[4])

    tc_figure.add_trajectory(drb15uL,
                             'plot',
                             '-',
                             subplot_idx=(0, 1),
                             label=r'IFN$\beta$ at {} L'.format(volEC1),
                             doseslice=beta_testdose,
                             dose_species='Beta',
                             color=beta_palette[0])
    tc_figure.add_trajectory(drb5mL,
                             'plot',
                             '-',
                             subplot_idx=(0, 1),
                             label=r'IFN$\beta$ at {} L'.format(volEC2),
                             doseslice=beta_testdose,
                             dose_species='Beta',
                             color=beta_palette[2])
    tc_figure.show_figure(save_flag=True,
                          save_dir='varying_reaction_volume_tc.pdf')

    # ------------------------------------
    # Now let's quickly look at IFN levels
    # ------------------------------------
    # 1 uL
    Mixed_Model.set_global_parameters({
        'volEC': volEC1,
        'ka1': ka1 * 1E-5 / volEC1,
        'ka2': ka2 * 1E-5 / volEC1,
        'k_a1': k_a1 * 1E-5 / volEC1,
        'k_a2': k_a2 * 1E-5 / volEC1
    })
    dradf = Mixed_Model.mixed_dose_response(times,
                                            'Free_Ia',
                                            'Ia',
                                            list(logspace(1, 5.2)),
                                            parameters={'Ib': 0},
                                            sf=scale_factor)
    drbdf = Mixed_Model.mixed_dose_response(times,
                                            'Free_Ib',
                                            'Ib',
                                            list(logspace(-1, 4)),
                                            parameters={'Ia': 0},
                                            sf=scale_factor)

    dra15uL = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb15uL = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    # 1 mL
    Mixed_Model.set_global_parameters({
        'volEC': volEC2,
        'ka1': ka1 * 1E-5 / volEC2,
        'ka2': ka2 * 1E-5 / volEC2,
        'k_a1': k_a1 * 1E-5 / volEC2,
        'k_a2': k_a2 * 1E-5 / volEC2
    })
    dradf = Mixed_Model.mixed_dose_response(times,
                                            'Free_Ia',
                                            'Ia',
                                            list(logspace(1, 5.2)),
                                            parameters={'Ib': 0},
                                            sf=scale_factor)
    drbdf = Mixed_Model.mixed_dose_response(times,
                                            'Free_Ib',
                                            'Ib',
                                            list(logspace(-1, 4)),
                                            parameters={'Ia': 0},
                                            sf=scale_factor)

    dra5mL = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb5mL = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    tc_figure = TimecoursePlot((1, 2))

    tc_figure.add_trajectory(dra15uL,
                             'plot',
                             '-',
                             subplot_idx=(0, 0),
                             label=r'IFN$\alpha$ at {} L'.format(volEC1),
                             doseslice=alpha_testdose,
                             dose_species='Alpha',
                             color=alpha_palette[1])
    tc_figure.add_trajectory(dra5mL,
                             'plot',
                             '-',
                             subplot_idx=(0, 0),
                             label=r'IFN$\alpha$ at {} L'.format(volEC2),
                             doseslice=alpha_testdose,
                             dose_species='Alpha',
                             color=alpha_palette[4])

    tc_figure.add_trajectory(drb15uL,
                             'plot',
                             '-',
                             subplot_idx=(0, 1),
                             label=r'IFN$\beta$ at {} L'.format(volEC1),
                             doseslice=beta_testdose,
                             dose_species='Beta',
                             color=beta_palette[0])
    tc_figure.add_trajectory(drb5mL,
                             'plot',
                             '-',
                             subplot_idx=(0, 1),
                             label=r'IFN$\beta$ at {} L'.format(volEC2),
                             doseslice=beta_testdose,
                             dose_species='Beta',
                             color=beta_palette[2])
    for ax in tc_figure.axes.flatten():
        ax.set_yscale('log')
    ifn_fig, ifn_axes = tc_figure.show_figure()
    ifn_axes[0].set_ylabel('IFN-alpha2')
    ifn_axes[1].set_ylabel('IFN-beta')
    ifn_fig.savefig('varying_reaction_volume_tc_IFN.pdf')
示例#9
0
    # Show SOCS effects
    Mixed_Model.reset_parameters()
    Mixed_Model.set_parameters({
        'kIntBasal_r1': 0,
        'kIntBasal_r2': 0,
        'kint_a': 0,
        'kint_b': 0
    })
    dra60_SOCS, drb60_SOCS = aggregate_response(Mixed_Model, DR_method,
                                                MODEL_TYPE, R_samples)

    # --------------------
    # Make Plot
    # --------------------
    dr_plot = DoseresponsePlot((1, 1))
    alpha_mask = []
    beta_mask = []
    for idx, t in enumerate([el for el in times]):
        if t not in alpha_mask:
            dr_plot.add_trajectory(dra60,
                                   t,
                                   'plot',
                                   alpha_palette[5], (0, 0),
                                   'Alpha',
                                   linewidth=2.0)
            dr_plot.add_trajectory(dra60_int,
                                   t,
                                   'plot',
                                   '--', (0, 0),
                                   'Alpha',
                                            parameters={'Ib': 0},
                                            sf=scale_factor)
    drbdf = Mixed_Model.mixed_dose_response(times,
                                            'TotalpSTAT',
                                            'Ib',
                                            list(logspace(-1, 4)),
                                            parameters={'Ia': 0},
                                            sf=scale_factor)

    dra60 = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb60 = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    # Plot primary predictions
    alpha_palette = sns.color_palette("deep", 6)
    beta_palette = sns.color_palette("deep", 6)
    new_fit = DoseresponsePlot((1, 2))
    for idx, t in enumerate(times):
        new_fit.add_trajectory(dra60,
                               t,
                               'plot',
                               alpha_palette[idx], (0, 0),
                               'Alpha',
                               label=str(t) + ' min',
                               linewidth=2)
        new_fit.add_trajectory(drb60,
                               t,
                               'plot',
                               beta_palette[idx], (0, 1),
                               'Beta',
                               label=str(t) + ' min',
                               linewidth=2)
示例#11
0
                                                             'R1': 1200,
                                                             'R2': 4920},
                                                 return_type='dataframe', dataframe_labels='Alpha',
                                                 scale_factor=scale_factor * 0.2)
    large_cells_beta = Mixed_Model.doseresponse(times, 'TotalpSTAT', 'Ib',
                                                list(np.logspace(np.log10(doses_beta[0]), np.log10(doses_beta[-1]))),
                                                parameters={'Ia': 0,
                                                            'R1': 1200,
                                                            'R2': 4920},
                                                return_type='dataframe', dataframe_labels='Beta',
                                                scale_factor=scale_factor * 0.2)
    large_cells_alpha_IFNdata = IfnData('custom', df=large_cells_alpha, conditions={'Alpha': {'Ib': 0}})
    large_cells_beta_IFNdata = IfnData('custom', df=large_cells_beta, conditions={'Beta': {'Ia': 0}})

    # Plot
    alpha_palette = sns.color_palette("Reds", 6)
    beta_palette = sns.color_palette("Greens", 6)

    dr_plot = DoseresponsePlot((1, 2))
    # Add fits
    dr_plot.add_trajectory(large_cells_alpha_IFNdata, 60.0, 'plot', alpha_palette[5], (0, 0), 'Alpha',
                           label='Large Cells at 60 minutes')
    dr_plot.add_trajectory(small_cells_alpha_IFNdata, 60.0, 'plot', alpha_palette[2], (0, 0), 'Alpha',
                           label='Small Cells at 60 minutes')

    dr_plot.add_trajectory(large_cells_beta_IFNdata, 60.0, 'plot', beta_palette[5], (0, 1), 'Beta',
                           label='Large Cells at 60 minutes')
    dr_plot.add_trajectory(small_cells_beta_IFNdata, 60.0, 'plot', beta_palette[2], (0, 1), 'Beta',
                           label='Small Cells at 60 minutes')
    dr_fig, dr_axes = dr_plot.show_figure(save_flag=False)
示例#12
0
    best_fit_model.model_1.set_parameters(best_mixed_params[0])
    best_fit_model.model_2.set_parameters(best_mixed_params[1])

    times = [5, 15, 30, 60]

    alpha_response = best_fit_model.mixed_dose_response(times, 'TotalpSTAT', 'Ia',
                                                        np.logspace(1, 3), parameters={'Ib': 0}, sf=best_sf)
    beta_response = best_fit_model.mixed_dose_response(times, 'TotalpSTAT', 'Ib',
                                                       np.logspace(np.log10(0.2), 4),
                                                       parameters={'Ia': 0}, sf=best_sf)"""
    #total_response_df = pd.concat([alpha_response, beta_response])
    total_response_df = pd.concat([dradf, drbdf])
    total_response = IfnData('custom', df=total_response_df)

    # Plot
    new_fit = DoseresponsePlot((1, 2))
    alpha_palette = sns.color_palette("deep", 6)
    beta_palette = sns.color_palette("deep", 6)
    alpha_mask = []
    beta_mask = []
    # Add fits
    for idx, t in enumerate([el for el in times]):
        if t not in alpha_mask:
            new_fit.add_trajectory(total_response,
                                   t,
                                   'plot',
                                   alpha_palette[idx], (0, 0),
                                   'Alpha',
                                   label='Alpha ' + str(t))
        if t not in beta_mask:
            new_fit.add_trajectory(total_response,
示例#13
0
                               parameters={'Ia': 0},
                               scale_factor=scale_factor,
                               return_type='dataframe',
                               dataframe_labels='Beta')

dra60 = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
drb60 = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

# ------------------------
# Plot
# ------------------------
alpha_mask = [2.5, 5.0, 7.5, 10.0]
beta_mask = [2.5, 5.0, 7.5, 10.0]
plot_original_fit = False
if plot_original_fit == True:
    DRplot = DoseresponsePlot((1, 2))
    for idx, t in enumerate(times):
        if t not in alpha_mask:
            DRplot.add_trajectory(dra60,
                                  t,
                                  'plot',
                                  alpha_palette[idx], (0, 0),
                                  'Alpha',
                                  label=str(t) + ' min',
                                  linewidth=2)
            DRplot.add_trajectory(mean_data,
                                  t,
                                  'errorbar',
                                  'o', (0, 0),
                                  'Alpha',
                                  color=alpha_palette[idx])
from ifnclass.ifnmodel import IfnModel
from ifnclass.ifnplot import DoseresponsePlot
from ifnclass.ifndata import IfnData
import numpy as np
from numpy import logspace
import matplotlib.pyplot as plt
import seaborn as sns

ImmuneCell_Model = IfnModel('Immune_Cell_model')

IFNg_doses = list(logspace(-1.5, 2, num=15))
times = [15, 30, 60]
fig = DoseresponsePlot((2, 2))
fig.axes[0][0].set_title('pSTAT1')
fig.axes[0][1].set_title('pSTAT3')

print("Dose-response 1")
IFNg_naive_res = ImmuneCell_Model.doseresponse(times, ['pSTAT1', 'pSTAT3'],
                                               'IFN_gamma_IC',
                                               IFNg_doses,
                                               parameters={
                                                   'IFNAR1_IC': 0,
                                                   'IFNAR2_IC': 0,
                                                   'IFN_alpha2_IC': 0,
                                                   'IFN_beta_IC': 0,
                                                   'SOCS2_IC': 0
                                               },
                                               return_type='dataframe',
                                               dataframe_labels='IFNgamma')
naive_IFNg_pSTAT1_df = IfnData(name='custom', df=IFNg_naive_res.xs(['pSTAT1']))
naive_IFNg_pSTAT3_df = IfnData(name='custom', df=IFNg_naive_res.xs(['pSTAT3']))
                'R2': (volPM / volPM_typical) * 4920,
                'S': (volCP / volCP_typical) * 1E4
            },
            return_type='list',
            scale_factor=scale_factor)['TotalpSTAT'][-1]
        normalized_response = response / ((volCP / volCP_typical) * 1E4)
        beta_cell_size_curve.append(normalized_response)

    # -------------------------------
    # Plot cell size panel
    # -------------------------------
    alpha_palette = sns.color_palette("Reds", 8)
    beta_palette = sns.color_palette("Greens", 8)
    matplotlib.rcParams['xtick.labelsize'] = 12
    matplotlib.rcParams['ytick.labelsize'] = 12
    dr_fig = DoseresponsePlot((1, 2))
    ax = dr_fig.axes[0]
    xlabels = np.divide(radii, 1E-6)
    ax.plot(xlabels,
            alpha_cell_size_curve,
            color=alpha_palette[-1],
            label='Alpha',
            linewidth=2)
    ax.plot(xlabels,
            beta_cell_size_curve,
            color=beta_palette[-1],
            label='Beta',
            linewidth=2)
    ax.legend()
    ax.set_xlabel(r'Cell radius ($\mu$m)', fontsize=14)
    ax.set_ylabel('pSTAT/STAT', fontsize=14)
示例#16
0
    small_alignment.get_scaled_data()
    mean_small_data = small_alignment.summarize_data()

    large_alignment = DataAlignment()
    large_alignment.add_data([large_4, large_3, large_2, large_1])
    large_alignment.align()
    large_alignment.get_scaled_data()
    mean_large_data = large_alignment.summarize_data()

    # ------------
    # Plot data
    # ------------
    alpha_palette = sns.color_palette("deep", 6)
    beta_palette = sns.color_palette("deep", 6)

    dr_plot = DoseresponsePlot((2, 2))
    for r_idx, cell_size in enumerate([mean_small_data, mean_large_data]):
        for c_idx, species in enumerate(['Alpha', 'Beta']):
            for t_idx, time in enumerate(cell_size.get_times()[species]):
                if species == 'Alpha':
                    c = alpha_palette[t_idx]
                else:
                    c = beta_palette[t_idx]
                dr_plot.add_trajectory(cell_size, time, 'errorbar', 'o--', (r_idx, c_idx), species,
                                       label=str(time)+" min", color=c)
    dr_plot.axes[0][0].set_title(r'IFN$\alpha$')
    dr_plot.axes[0][0].set_ylabel('Small cell response')
    dr_plot.axes[0][1].set_title(r'IFN$\beta$')
    dr_plot.axes[1][0].set_ylabel('Large cell response')

    for ax in [item for sublist in dr_plot.axes for item in sublist]:
示例#17
0
                                     list(logspace(-2, 4)),
                                     parameters={'Ia': 0},
                                     return_type='dataframe',
                                     dataframe_labels='Beta')

    for i in range(len(times)):
        dradf.loc['Alpha'].iloc[:, i] = dradf.loc['Alpha'].iloc[:, i].apply(
            scale_data)
        drbdf.loc['Beta'].iloc[:,
                               i] = drbdf.loc['Beta'].iloc[:,
                                                           i].apply(scale_data)

    dra = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    dose_response_plot = DoseresponsePlot((3, 2))
    alpha_mask = []
    beta_mask = []
    # Add fits
    for idx, t in enumerate([str(el) for el in times]):
        if t not in [str(el) for el in alpha_mask]:
            dose_response_plot.add_trajectory(dra,
                                              t,
                                              'plot',
                                              alpha_palette[idx], (0, 0),
                                              'Alpha',
                                              label='Alpha ' + t,
                                              linewidth=2.0)
        if t not in [str(el) for el in beta_mask]:
            dose_response_plot.add_trajectory(drb,
                                              t,
示例#18
0
from ifnclass.ifnfit import DualMixedPopulation
from numpy import linspace, logspace, transpose
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import os
from ifnclass.ifnplot import Trajectory, DoseresponsePlot
import pandas as pd
from sys import platform


if __name__ == '__main__':
    # ----------------------
    # Set up figure layout
    # ----------------------
    spec_fig = DoseresponsePlot((3, 2))
    spec_fig.fig.set_size_inches(12, 8)
    # ---------------------------
    # Set up data for comparison
    # ---------------------------
    alpha_palette = sns.color_palette("Reds", 6)
    beta_palette = sns.color_palette("Greens", 6)
    data_palette = sns.color_palette("muted", 6)
    marker_shape = ["o", "v", "s", "P", "d", "1", "x", "*"]
    dataset_names = ["20190108", "20190119", "20190121", "20190214"]

    newdata_1 = IfnData("20190108_pSTAT1_IFN_Bcell")
    newdata_2 = IfnData("20190119_pSTAT1_IFN_Bcell")
    newdata_3 = IfnData("20190121_pSTAT1_IFN_Bcell")
    newdata_4 = IfnData("20190214_pSTAT1_IFN_Bcell")
示例#19
0
    # Add equilibrium expressions
    # max_response_axes[0].plot(time_list,
    #                          [avg_pSTAT_Max_Alpha for _ in time_list],
    #                          '--', color=alpha_palette[5], linewidth=2)
    # max_response_axes[1].plot(time_list,
    #                          [avg_pSTAT_Max_Beta for _ in time_list],
    #                          '--', color=alpha_palette[5], linewidth=2)

    # -------------------------------
    # Plot model dose response curves
    # -------------------------------
    alpha_palette = sns.color_palette("rocket_r", 6)
    beta_palette = sns.color_palette("rocket_r", 6)

    new_fit = DoseresponsePlot((1, 2))
    new_fit.axes = [
        Figure_2.add_subplot(gs[0, 0:2]),
        Figure_2.add_subplot(gs[0, 2:4])
    ]
    new_fit.axes[0].set_xscale('log')
    new_fit.axes[0].set_xlabel('Dose (pM)')
    new_fit.axes[0].set_ylabel('pSTAT (MFI)')
    new_fit.axes[1].set_xscale('log')
    new_fit.axes[1].set_xlabel('Dose (pM)')
    new_fit.axes[1].set_ylabel('pSTAT (MFI)')
    new_fit.fig = Figure_2

    alpha_mask = [7.5, 10.0]
    beta_mask = [7.5, 10.0]
    # Add fits
newdata_2 = IfnData("20190119_pSTAT1_IFN_Bcell")
newdata_3 = IfnData("20190121_pSTAT1_IFN_Bcell")
newdata_4 = IfnData("20190214_pSTAT1_IFN_Bcell")

# Aligned data, to get scale factors for each data set
alignment = DataAlignment()
alignment.add_data([newdata_4, newdata_3, newdata_2, newdata_1])
alignment.align()
alignment.get_scaled_data()
mean_data = alignment.summarize_data()

# Plot posterior samples
alpha_palette = sns.color_palette("deep", 6)
beta_palette = sns.color_palette("deep", 6)

new_fit = DoseresponsePlot((1, 2))

alpha_mask = [2.5, 7.5, 10.0]  #[2.5, 5.0, 7.5, 10.0, 20.0, 60.0]
beta_mask = [2.5, 7.5, 10.0]
plot_data = True
# Add fits
for idx, t in enumerate(times):
    if t not in alpha_mask:
        new_fit.add_trajectory(mean_model,
                               t,
                               'envelope',
                               alpha_palette[idx], (0, 0),
                               'Alpha',
                               label='{} min'.format(t),
                               linewidth=2,
                               alpha=0.2)
示例#21
0
        'small_alignment', os.path.join(os.getcwd(), 'small_alignment'))
    large_alignment = DataAlignment()
    large_alignment.load_from_save_file(
        'large_alignment', os.path.join(os.getcwd(), 'large_alignment'))
    small_alignment.align()
    small_alignment.get_scaled_data()
    mean_small_data = small_alignment.summarize_data()
    large_alignment.align()
    large_alignment.get_scaled_data()
    mean_large_data = large_alignment.summarize_data()

    # ----------------------
    # Set up Figure layout
    # ----------------------
    # Set up dose response figures
    new_fit = DoseresponsePlot((1, 2), figsize=(9, 1.5 * 2.5))
    new_fit.axes[0].set_ylabel('pSTAT1 (MFI)')
    # new_fit.axes[1].set_ylabel('pSTAT1 (MFI)')

    # Plot Dose respsonse data
    times = [2.5, 5.0, 7.5, 10.0, 20.0, 60.0]
    color_palette = sns.color_palette("rocket_r",
                                      6)  # sns.color_palette("Paired", 10)
    alpha_mask = [2.5, 5.0, 7.5, 20.0]
    beta_mask = [2.5, 5.0, 7.5, 20.0]
    for idx, t in enumerate([10.0, 60.0]):
        if t == 10.0:
            new_fit.add_trajectory(mean_large_data,
                                   t,
                                   'errorbar',
                                   'v', (0, 0),
示例#22
0
            response_species,
            dose_species,
            Epo_doses,
            parameters={n: 0
                        for n in IC_names if n != dose_species},
            return_type='dataframe',
            dataframe_labels=dose_species,
            scale_factor=100.0 / model.parameters['EpoR_IC']),
        conditions={})

    # -------------------------------
    # Plot model dose response curves
    # -------------------------------
    palette = sns.color_palette("muted")

    Epo_plot = DoseresponsePlot((1, 1))
    # Add data
    Epo_plot.add_trajectory(Moraga_data,
                            60,
                            'errorbar',
                            'o', (0, 0),
                            'T_Epo',
                            label='EPO',
                            color=palette[1])
    Epo_plot.add_trajectory(Moraga_data,
                            60,
                            'errorbar',
                            'o', (0, 0),
                            'EMP_1',
                            label='EMP-1',
                            color=palette[2])
示例#23
0
def check_plots():
    smooth_plot = DoseresponsePlot((2, 2))
    alpha_palette = sns.color_palette("Reds", 6)
    beta_palette = sns.color_palette("Greens", 6)

    smooth_plot.add_trajectory(a25smoothIfnData, 2.5, 'plot', alpha_palette[4],
                               (0, 0), 'Alpha')
    smooth_plot.add_trajectory(a60smoothIfnData, 60, 'plot', alpha_palette[5],
                               (0, 0), 'Alpha')

    smooth_plot.add_trajectory(a25smoothIfnData, 2.5, 'plot', alpha_palette[0],
                               (1, 0), 'Alpha')
    smooth_plot.add_trajectory(a5smoothIfnData, 5, 'plot', alpha_palette[1],
                               (1, 0), 'Alpha')
    smooth_plot.add_trajectory(a75smoothIfnData, 7.5, 'plot', alpha_palette[2],
                               (1, 0), 'Alpha')
    smooth_plot.add_trajectory(a10smoothIfnData, 10, 'plot', alpha_palette[3],
                               (1, 0), 'Alpha')
    smooth_plot.add_trajectory(a20smoothIfnData, 20, 'plot', alpha_palette[4],
                               (1, 0), 'Alpha')
    smooth_plot.add_trajectory(a60smoothIfnData, 60, 'plot', alpha_palette[5],
                               (1, 0), 'Alpha')

    smooth_plot.add_trajectory(b25smoothIfnData, 2.5, 'plot', beta_palette[4],
                               (0, 1), 'Beta')
    smooth_plot.add_trajectory(b60smoothIfnData, 60, 'plot', beta_palette[5],
                               (0, 1), 'Beta')

    smooth_plot.add_trajectory(b25smoothIfnData, 2.5, 'plot', beta_palette[0],
                               (1, 1), 'Beta')
    smooth_plot.add_trajectory(b5smoothIfnData, 5, 'plot', beta_palette[1],
                               (1, 1), 'Beta')
    smooth_plot.add_trajectory(b75smoothIfnData, 7.5, 'plot', beta_palette[2],
                               (1, 1), 'Beta')
    smooth_plot.add_trajectory(b10smoothIfnData, 10, 'plot', beta_palette[3],
                               (1, 1), 'Beta')
    smooth_plot.add_trajectory(b20smoothIfnData, 20, 'plot', beta_palette[4],
                               (1, 1), 'Beta')
    smooth_plot.add_trajectory(b60smoothIfnData, 60, 'plot', beta_palette[5],
                               (1, 1), 'Beta')

    for idx, t in enumerate([2.5, 60]):
        smooth_plot.add_trajectory(newdata,
                                   t,
                                   'scatter',
                                   alpha_palette[idx * 2], (0, 0),
                                   'Alpha',
                                   dn=1)
        smooth_plot.add_trajectory(newdata,
                                   t,
                                   'scatter',
                                   beta_palette[idx * 2], (0, 1),
                                   'Beta',
                                   dn=1)

    fig, axes = smooth_plot.show_figure()
示例#24
0
                                     list(logspace(-2, 4)),
                                     parameters={'Ia': 0},
                                     return_type='dataframe',
                                     dataframe_labels='Beta')

    for i in range(len(times)):
        dradf.loc['Alpha'].iloc[:, i] = dradf.loc['Alpha'].iloc[:, i].apply(
            scale_data)
        drbdf.loc['Beta'].iloc[:,
                               i] = drbdf.loc['Beta'].iloc[:,
                                                           i].apply(scale_data)

    dra60 = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb60 = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    new_fit = DoseresponsePlot((1, 2))
    alpha_mask = [2.5, 7.5]
    beta_mask = [2.5, 7.5]
    # Add fits
    for idx, t in enumerate([str(el) for el in times]):
        if t not in [str(el) for el in alpha_mask]:
            new_fit.add_trajectory(dra60,
                                   t,
                                   'plot',
                                   alpha_palette[idx], (0, 0),
                                   'Alpha',
                                   label='Alpha ' + t)
        if t not in [str(el) for el in beta_mask]:
            new_fit.add_trajectory(drb60,
                                   t,
                                   'plot',
示例#25
0
    dra60 = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb60 = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})
    dra60_int = IfnData('custom',
                        df=dradf_int,
                        conditions={'Alpha': {
                            'Ib': 0
                        }})
    drb60_int = IfnData('custom', df=drbdf_int, conditions={'Beta': {'Ia': 0}})
    dra60_rec = IfnData('custom',
                        df=dradf_rec,
                        conditions={'Alpha': {
                            'Ib': 0
                        }})
    drb60_rec = IfnData('custom', df=drbdf_rec, conditions={'Beta': {'Ia': 0}})

    dr_plot = DoseresponsePlot((3, 2))
    alpha_mask = []
    beta_mask = []
    # Add fits
    for idx, t in enumerate([el for el in times]):
        if t not in alpha_mask:
            dr_plot.add_trajectory(dra60,
                                   t,
                                   'plot',
                                   alpha_palette[idx], (0, 0),
                                   'Alpha',
                                   label='Alpha ' + str(t),
                                   linewidth=2.0)
            dr_plot.add_trajectory(dra60_int,
                                   t,
                                   'plot',
示例#26
0
                                     list(logspace(1, log10(11000))),
                                     parameters={'Ia': 0},
                                     return_type='dataframe',
                                     dataframe_labels='Beta')

    for i in range(len(times)):
        dradf.loc['Alpha'].iloc[:, i] = dradf.loc['Alpha'].iloc[:, i].apply(
            scale_data)
        drbdf.loc['Beta'].iloc[:,
                               i] = drbdf.loc['Beta'].iloc[:,
                                                           i].apply(scale_data)

    dra60 = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb60 = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    new_fit = DoseresponsePlot((1, 2))
    alpha_mask = []
    beta_mask = []
    # Add fits
    for idx, t in enumerate([el for el in times]):
        if t not in alpha_mask:
            new_fit.add_trajectory(dra60,
                                   t,
                                   'plot',
                                   alpha_palette[idx], (0, 0),
                                   'Alpha',
                                   label='Alpha ' + str(t))
        if t not in beta_mask:
            new_fit.add_trajectory(drb60,
                                   t,
                                   'plot',
    #Mixed_Model.set_parameters({'kSOCS': Mixed_Model.parameters['kSOCS'] * 2.5})
    dradf_rec = Mixed_Model.doseresponse(times, 'TotalpSTAT', 'Ia', list(logspace(-2, 8)),
                                         parameters={'Ib': 0}, return_type='dataframe', dataframe_labels='Alpha',
                                         scale_factor = scale_factor)
    drbdf_rec = Mixed_Model.doseresponse(times, 'TotalpSTAT', 'Ib', list(logspace(-2, 8)),
                                         parameters={'Ia': 0}, return_type='dataframe', dataframe_labels='Beta',
                                         scale_factor=scale_factor)

    dra60 = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb60 = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})
    dra60_int = IfnData('custom', df=dradf_int, conditions={'Alpha': {'Ib': 0}})
    drb60_int = IfnData('custom', df=drbdf_int, conditions={'Beta': {'Ia': 0}})
    dra60_rec = IfnData('custom', df=dradf_rec, conditions={'Alpha': {'Ib': 0}})
    drb60_rec = IfnData('custom', df=drbdf_rec, conditions={'Beta': {'Ia': 0}})

    dr_plot = DoseresponsePlot((1, 1))
    alpha_mask = []
    beta_mask = []
    # Add fits
    for idx, t in enumerate([el for el in times]):
        if t not in alpha_mask:
            dr_plot.add_trajectory(dra60, t, 'plot', alpha_palette[5], (0, 0), 'Alpha', label='Alpha - No Feedback', linewidth=2.0)
            dr_plot.add_trajectory(dra60_int, t, 'plot', '--', (0, 0), 'Alpha', color=alpha_palette[3],
                                   label='Internalization only', linewidth=2.0, )
            dr_plot.add_trajectory(dra60_rec, t, 'plot', ':', (0, 0), 'Alpha', color=alpha_palette[1], label='SOCS only', linewidth=2.0)
        if t not in beta_mask:
            dr_plot.add_trajectory(drb60, t, 'plot', beta_palette[5], (0, 0), 'Beta', label='Beta - No Feedback', linewidth=2.0)
            dr_plot.add_trajectory(drb60_int, t, 'plot', '--', (0, 0), 'Beta', color=beta_palette[3],
                                   label='Internalization only', linewidth=2.0)
            dr_plot.add_trajectory(drb60_rec, t, 'plot', ':', (0, 0), 'Beta', color=beta_palette[1], label='SOCS only', linewidth=2.0)
    dr_plot.fig.suptitle('Internalization vs SOCS')
示例#28
0
def plot_posterior(param_file, parameter_names, num_checks, model, posterior,
                   sf, time_mask, save_dir, plot_data=True):
    """ Plot the predictions from ensemble sampling of model parameters.
    Plots the dose-response as an envelope containing 1 sigma of predictions.
    """
    # Preparation of parameter ensemble
    if type(param_file) == str:
        log10_parameters = np.load(param_file)
    elif type(param_file) == list:
        log10_parameters = np.load(param_file[0])
        for f in param_file[1:]:
            batch_params = np.load(f)
            log10_parameters = np.append(log10_parameters, batch_params,
                                         axis=0)

    parameters = np.power(10, log10_parameters)

    parameters_to_check = [parameters[i] for i in
                           list(np.random.randint(0, high=len(parameters),
                                                  size=num_checks))]

    # Compute posterior sample trajectories
    posterior_trajectories = []
    for p in parameters_to_check:
        param_dict = {key: value for key, value in zip(parameter_names, p)}
        pp = posterior_prediction(model, param_dict, parameter_names, sf)
        posterior_trajectories.append(pp)

    # Make aggregate predicitions
    mean_alpha, std_alpha, mean_beta, std_beta = \
        posterior_IFN_summary_statistics(posterior_trajectories)

    std_predictions = {'Alpha': std_alpha,
                       'Beta': std_beta}
    mean_predictions = {'Alpha': mean_alpha,
                        'Beta': mean_beta}

    mean_model = copy.deepcopy(posterior_trajectories[0])
    for s in ['Alpha', 'Beta']:
        for didx, d in enumerate(mean_model.get_doses()[s]):
            for tidx, t in enumerate(mean_model.get_times()[s]):
                mean_model.data_set.loc[s][str(t)].loc[d] =\
                    (mean_predictions[s][didx][tidx],
                     std_predictions[s][didx][tidx])

    # Get aligned data
    mean_data = posterior.experiment

    # Plot posterior samples
    alpha_palette = sns.color_palette("rocket_r", 6)
    beta_palette = sns.color_palette("rocket_r", 6)

    new_fit = DoseresponsePlot((1, 2))

    # Add fits
    for idx, t in enumerate([2.5, 5.0, 7.5, 10.0, 20.0, 60.0]):
        if t not in time_mask:
            new_fit.add_trajectory(mean_model, t, 'envelope',
                                   alpha_palette[idx], (0, 0), 'Alpha',
                                   label='{} min'.format(t),
                                   linewidth=2, alpha=0.2)
            if plot_data:
                new_fit.add_trajectory(mean_data, t, 'errorbar', 'o',
                                       (0, 0), 'Alpha',
                                       color=alpha_palette[idx])
        if t not in time_mask:
            new_fit.add_trajectory(mean_model, t, 'envelope',
                                   beta_palette[idx], (0, 1), 'Beta',
                                   label='{} min'.format(t),
                                   linewidth=2, alpha=0.2)
            if plot_data:
                new_fit.add_trajectory(mean_data, t, 'errorbar', 'o',
                                       (0, 1), 'Beta',
                                       color=beta_palette[idx])

    # Change legend transparency
    leg = new_fit.fig.legend()
    for lh in leg.legendHandles:
        lh._legmarker.set_alpha(1)

    dr_fig, dr_axes = new_fit.show_figure()
    dr_fig.set_size_inches(14, 6)
    dr_axes[0].set_title(r'IFN$\alpha$')
    dr_axes[1].set_title(r'IFN$\beta$')

    if plot_data:
        dr_fig.savefig(os.path.join(save_dir,
                       'posterior_predictions_with_data.pdf'))
    else:
        dr_fig.savefig(os.path.join(save_dir,
                       'posterior_predictions.pdf'))
示例#29
0
        drbdf.loc['Beta'].iloc[:,
                               i] = drbdf.loc['Beta'].iloc[:,
                                                           i].apply(scale_data)

    dra60 = IfnData('custom', df=dradf, conditions={'Alpha': {'Ib': 0}})
    drb60 = IfnData('custom', df=drbdf, conditions={'Beta': {'Ia': 0}})

    # -------------------------
    # Plot mean trajectory
    # -------------------------
    alpha_palette = sns.color_palette("Reds", 1)
    alpha_model_palette = sns.color_palette("Greys", 1)
    beta_palette = sns.color_palette("Greens", 1)
    beta_model_palette = sns.color_palette("Greys", 1)

    dr_plot = DoseresponsePlot((6, 2))
    for idx, t in enumerate(newdata_4.get_times('Alpha')):
        dr_plot.add_trajectory(mean_data,
                               t,
                               'errorbar',
                               'o--', (idx, 0),
                               'Alpha',
                               label='',
                               color=alpha_palette[0])
    for idx, t in enumerate(newdata_4.get_times('Beta')):
        dr_plot.add_trajectory(mean_data,
                               t,
                               'errorbar',
                               'o--', (idx, 1),
                               'Beta',
                               label='',
示例#30
0
    # -------------------------------
    # Plot alignment of Dose Response
    # -------------------------------
    species = alignment.scaled_data[0].get_dose_species()
    #   Make subtitles
    recorded_times = alignment.scaled_data[0].get_times()[species[0]]
    titles = alignment.scaled_data[0].get_dose_species()
    titles[0] += "\r\n\r\n{} min".format(recorded_times[0])
    titles[1] += "\r\n\r\n{} min".format(recorded_times[0])
    for t in recorded_times[1:]:
        for s in species:
            titles.append(str(t) + ' min')
    num_times = len(alignment.scaled_data[0].get_times()[species[0]])
    clist = ["Reds", "Greens", "Blues", "Purples", "Oranges", "Greys"]
    dr_plot = DoseresponsePlot((num_times, len(species)))
    for i in range(num_times):
        for j in range(len(species)):
            dr_plot.axes[i][j].set_title(titles[i * len(species) + j])

    # Add fits
    for d_idx, dataset in enumerate(alignment.scaled_data):
        colour_palette = sns.color_palette(clist[d_idx], 1)
        for ax_idx, spec in enumerate(dataset.get_dose_species()):
            for idx, t in enumerate(
                    alignment.scaled_data[0].get_times()[spec]):
                spec_data = pd.concat([dataset.data_set.loc[spec]],
                                      keys=[spec],
                                      names=['Dose_Species'])
                spec_IfnData = IfnData('custom',
                                       df=spec_data,