Beispiel #1
0
def set_panel_layout(E, fig, err_type, tbin_type='12bins'):

    # legend annotation
    if tbin_type.endswith('bins'):
        fig.text(.7, 1.1, 'gray background: Dark Cycle', fontsize=8)

    xlabel = 'Circadian Time'
    add_xylabels(fig, xlabel=xlabel, xypad=-.15, labelsize=10)

    days_string = E.get_days_to_use_text()
    fig_title = '%s Experiment\nFeatures vs CT, 12bins group avg$\pm$%s\n%s days: %s' % (
        E.short_name, err_type, E.use_days.replace('_',
                                                   '-').title(), days_string)

    add_titles_notes(E, fig, title=fig_title, typad=.1)
    plt.subplots_adjust(hspace=.6, wspace=.6)
Beispiel #2
0
def set_panel_layout(E, fig, err_type, tbin_type):
    fig.text(.6, .9, '0: %s, control, %s (grayscale)' %(E.strain_names[0], tbin_type), fontsize=8)
    fig.text(.6, .85, '1: %s, knock-out, %s (colors)' %(E.strain_names[1], tbin_type), fontsize=8)
    if tbin_type.endswith('bins'):
        fig.text(.6, .8, 'gray background: Dark Cycle', fontsize=8)

    xlabel = 'Circadian Time'
    add_xylabels(fig, xlabel=xlabel, xypad=-.02, labelsize=10)

    days_string = E.get_days_to_use_text()
    fig_title = '%s Experiment\nFeatures vs CT, 12bins, group avg$\pm$%s\n%s days: %s' %(
                    E.short_name, err_type,
                    E.use_days.replace('_', '-').title(), days_string
                    )

    add_titles_notes(E, fig, title=fig_title)   
Beispiel #3
0
def plot_features_panel_LC_DC_ratio(experiment,
                                    level='group',
                                    bin_type='3cycles',
                                    err_type='sem',
                                    plot_type='features',
                                    ADD_SOURCE=True):
    E = experiment

    print "%s, level: %s, bin_type: %s, err_type: %s, days: %s" % (
        plot_features_panel_LC_DC_ratio.__name__, level, bin_type, err_type,
        E.daysToUse)

    features = E.features_by_activity
    num_features = len(features)
    days_to_use = E.daysToUse

    dirname = E.figures_dir + '%s/vectors/panels_expdays/%s/%s_days/' % (
        plot_type, bin_type, E.use_days)
    if not os.path.isdir(dirname): os.makedirs(dirname)
    fname = dirname + '%s_panel_expdays_LC_DC_ratio' % (plot_type
                                                        )  #s, err_type)

    # using mouseday value
    # ratios = E.generate_feature_vectors_LC_DC_ratio_expdays(features, level, bin_type, err_type)

    # using group averages value
    data_ = E.generate_feature_vectors_expdays(features, level, bin_type,
                                               err_type)
    ratios_ = data_[:, :, :, 2, 0] / data_[:, :, :, 1, 0]  # LC/DC, avgs

    figsize = (14.4, 4.8)
    nrows, ncols = 4, 7
    fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True)
    xs = days_to_use

    cnt = 0
    for n in xrange(nrows):
        for m in xrange(ncols):
            ax = axes.flatten()[n * ncols + m]
            if n == 0 and m >= 3:
                ax.axis('off')
                continue

            feature = features[cnt]
            colors = get_two_group_features_colors(E, feature)
            subtitle = '%s %s' % (feature,
                                  E.plot_settings_dict[feature]['unit'])

            for g in xrange(E.num_strains):
                # # using mouseday values
                # tkw = {'fmt':'o-', 'ms':2, 'elinewidth':.5, 'capsize':1}
                # ax.errorbar(xs, ratios[g, cnt, :, 0], yerr=ratios[g, cnt, :, 1],
                #     color=colors[g], mec=colors[g], **tkw)

                # using group averages value
                tkw = {'marker': 'o', 'ms': 2, 'zorder': 0}
                ax.plot(xs,
                        ratios_[g, cnt, :],
                        color=colors[g],
                        mec=colors[g],
                        **tkw)
                # use when plotting all for comparison
                # colors_ = ['r', 'y']
                # ax.plot(xs, ratios_[g, cnt, :], color=colors_[g], mec=colors_[g], **tkw)

            if E.short_name == 'HFD2':
                d_day = E.dietChangeDayNumbers[0]
                ax.axvspan(xmin=d_day,
                           xmax=days_to_use[-1],
                           color='.9',
                           zorder=0)

            xlims = ax.get_xlim()
            ax.set_xlim((4, xlims[1]))
            ax.set_ylim((0, ax.get_ylim()[1]))
            ax_cleanup(ax)
            ax.set_title(subtitle, fontsize=10)

            cnt += 1

    fig.text(.6,
             .9,
             '0: %s, control, 24H (grayscale)' % E.strain_names[0],
             fontsize=8)
    fig.text(.6,
             .85,
             '1: %s, knock-out, 24H (colors)' % E.strain_names[1],
             fontsize=8)
    fig.text(.6, .8, 'gray background: diet change', fontsize=8)

    xlabel = 'Experiment Day'
    add_xylabels(fig, xlabel=xlabel, xypad=-.02, labelsize=10)

    days_string = E.get_days_to_use_text()
    fig_title = '%s Experiment\nFeatures vs days, LC/DC ratio %s avg$\pm$%s\nacross %s days: %s' % (
        E.short_name, level, err_type, E.use_days.replace(
            '_', '-').title(), days_string)

    add_titles_notes(E, fig, title=fig_title)

    plt.subplots_adjust(hspace=.6, wspace=.34)
    save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.02)
Beispiel #4
0
def plot_features_panel_DC_LC(experiment,
                              level='group',
                              bin_type='3cycles',
                              err_type='sem',
                              plot_type='features',
                              ADD_SOURCE=True):

    E = experiment

    print "%s, level: %s, bin_type: %s, err_type: %s, days: %s" % (
        plot_features_panel_DC_LC.__name__, level, bin_type, err_type,
        E.daysToUse)

    features = E.features_by_activity
    num_features = len(features)
    days_to_use = E.daysToUse

    dirname = E.figures_dir + '%s/vectors/panels_expdays/%s/%s_days/' % (
        plot_type, bin_type, E.use_days)
    if not os.path.isdir(dirname): os.makedirs(dirname)
    fname = dirname + '%s_panel_expdays_DC_LC_group_%s' % (plot_type, err_type)

    # groups, features, days, cycles, avg/err
    data = E.generate_feature_vectors_expdays(features, level, bin_type,
                                              err_type)
    new_data = data[:, :, :, 1:, :]

    figsize = (14.4, 4.8)
    nrows, ncols = 4, 7
    fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True)
    xs = days_to_use

    cnt = 0
    for n in xrange(nrows):
        for m in xrange(ncols):
            ax = axes.flatten()[n * ncols + m]
            if n == 0 and m >= 3:
                ax.axis('off')
                continue

            feature = features[cnt]
            # get colors
            if feature.startswith('AS'):
                color1, color2 = [E.fcolors['AS'].values()[x] for x in [1, 3]]
            elif feature.startswith('T'):
                color1, color2 = [
                    E.fcolors[feature[1:]].values()[x] for x in [1, 3]
                ]
            else:
                color1, color2 = [
                    E.fcolors[feature[:1]].values()[x] for x in [1, 3]
                ]

            colors = ['.4', '.7', color1, color2]

            subtitle = '%s %s' % (feature,
                                  E.plot_settings_dict[feature]['unit'])

            for g in xrange(E.num_strains):
                tkw = {'fmt': 'o-', 'ms': 2, 'elinewidth': .5, 'capsize': 1}
                # DC
                mec = '0' if g == 0 else colors[2 * g]
                ax.errorbar(xs,
                            new_data[g, cnt, :, 0, 0],
                            yerr=new_data[g, cnt, :, 0, 1],
                            color=colors[2 * g],
                            mec=mec,
                            **tkw)
                #LC
                mc = '0' if g == 0 else colors[2 * g + 1]
                ax.errorbar(xs,
                            new_data[g, cnt, :, 1, 0],
                            yerr=new_data[g, cnt, :, 1, 1],
                            color=colors[2 * g + 1],
                            mec=mec,
                            **tkw)

            if E.short_name == 'HFD2':
                d_day = E.dietChangeDayNumbers[0]
                ax.axvspan(xmin=d_day,
                           xmax=days_to_use[-1],
                           color='.9',
                           zorder=0)

            xlims = ax.get_xlim()
            ax.set_xlim((4, xlims[1]))
            ax.set_ylim([0, ax.get_ylim()[1]])
            ax_cleanup(ax)
            ax.set_title(subtitle, fontsize=10)

            cnt += 1

    fig.text(.6,
             .9,
             '0: %s, control (grayscale)\nDC:black, LC: gray' %
             E.strain_names[0],
             fontsize=8)
    fig.text(.6,
             .83,
             '1: %s, knock-out (colors)\nDC: dark, LC: light ' %
             E.strain_names[1],
             fontsize=8)
    fig.text(.6, .78, 'gray background: diet change', fontsize=8)

    xlabel = 'Experiment Day'
    add_xylabels(fig, xlabel=xlabel, xypad=-.02, labelsize=10)

    days_string = E.get_days_to_use_text()
    fig_title = '%s Experiment\nFeatures, DC vs. LC, %s avg and %s\nacross %s days: %s' % (
        E.short_name, level, err_type, E.use_days.replace(
            '_', '-').title(), days_string)

    add_titles_notes(E, fig, title=fig_title)

    plt.subplots_adjust(hspace=.6, wspace=.34)
    save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.02)
Beispiel #5
0
def plot_features_panel_12bins(experiment,
                               level='group',
                               bin_type='12bins',
                               err_type='sem',
                               plot_type='features',
                               ADD_SOURCE=True):

    E = experiment

    print "%s, level: %s, bin_type: %s, err_type: %s, days: %s" % (
        plot_features_panel_12bins.__name__, level, bin_type, err_type,
        E.daysToUse)

    features = E.features_by_activity
    num_features = len(features)
    days_to_use = E.daysToUse
    num_bins = int(bin_type.strip('bins'))
    tbins = my_utils.get_tbins_string(bin_type)

    dirname = E.figures_dir + '%s/vectors/panels_expdays/%s/%s_days/' % (
        plot_type, bin_type, E.use_days)
    if not os.path.isdir(dirname): os.makedirs(dirname)

    data = E.generate_feature_vectors_expdays(features, level, bin_type,
                                              err_type)
    ymaxs = get_ymaxs(data)

    # stop
    for b in xrange(num_bins):
        new_data = data[:, :, :, b, :]
        figsize = (14.4, 4.8)
        nrows, ncols = 4, 7
        fig, axes = plt.subplots(nrows, ncols, figsize=figsize, sharex=True)
        xs = days_to_use

        cnt = 0
        for n in xrange(nrows):
            for m in xrange(ncols):
                ax = axes.flatten()[n * ncols + m]
                if n == 0 and m >= 3:
                    ax.axis('off')
                    continue

                feature = features[cnt]
                colors = get_two_group_features_colors(E, feature)
                subtitle = '%s %s' % (feature,
                                      E.plot_settings_dict[feature]['unit'])

                for g in xrange(E.num_strains):
                    tkw = {
                        'fmt': 'o-',
                        'ms': 2,
                        'elinewidth': .5,
                        'capsize': 1
                    }
                    ax.errorbar(xs,
                                new_data[g, cnt, :, 0],
                                yerr=new_data[g, cnt, :, 1],
                                color=colors[g],
                                mec=colors[g],
                                **tkw)

                if E.short_name == 'HFD2':
                    d_day = E.dietChangeDayNumbers[0]
                    ax.axvspan(xmin=d_day,
                               xmax=days_to_use[-1],
                               color='.9',
                               zorder=0)

                # xmin, xmax = ax.get_xlim()
                # ax.set_xlim((xmin-.5, xmax+.5))
                # ax.set_ylim([0, ymaxs[cnt]])
                ax_cleanup(ax)
                ax.set_title(subtitle, fontsize=10)

                cnt += 1

        xmin, xmax = ax.get_xlim()
        ax.set_xlim((xmin - .5, xmax + .5))

        fig.text(.6,
                 .9,
                 '0: %s, control, %s (grayscale)' %
                 (E.strain_names[0], tbins[b]),
                 fontsize=8)
        fig.text(.6,
                 .85,
                 '1: %s, knock-out, %s (colors)' %
                 (E.strain_names[1], tbins[b]),
                 fontsize=8)
        fig.text(.6, .8, 'gray background: diet change', fontsize=8)

        xlabel = 'Experiment Day'
        add_xylabels(fig, xlabel=xlabel, xypad=-.02, labelsize=10)

        days_string = E.get_days_to_use_text()
        fig_title = '%s Experiment\nFeatures, %s %s avg$\pm$%s, %s\nacross %s days: %s' % (
            E.short_name, bin_type, level, err_type, tbins[b],
            E.use_days.replace('_', '-').title(), days_string)

        add_titles_notes(E, fig, title=fig_title)

        plt.subplots_adjust(hspace=.6, wspace=.34)
        fname = dirname + '%s_panel_expdays_%s_group_%s_bin%d' % (
            plot_type, bin_type, err_type, b)

        save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.02)
Beispiel #6
0
def draw_subplot(experiment,
                 data,
                 labels,
                 data_rescaled,
                 fname,
                 act='F',
                 level='mouse',
                 sub_type='line',
                 plot_type='ingestion',
                 ADD_SOURCE=False):

    E = experiment

    i_act = 0 if act == 'F' else 1
    units = ['mg/s', 'g', 'min']
    # var_names = [E.HCM_variables[x][i_act] for x in var_types]
    varTypes = ['coeffs', 'tots', 'durs']
    varNames = [E.HCM_derived['events'][plot_type][x][0] for x in varTypes]
    m_labels = np.unique(labels[:, 1])

    figsize, nrows, ncols, sharex, sharey = get_subplot_specs(
        num_subplots=len(m_labels))

    fig, axes = plt.subplots(nrows,
                             ncols,
                             figsize=figsize,
                             sharex=sharex,
                             sharey=sharey)

    colors = [E.fcolors[act].values()[x] for x in [1, 0, 2]]

    title, subtitles = get_figure_titles(E,
                                         labels,
                                         act=act,
                                         plot_type=plot_type)

    hls = []
    for m, mouse in enumerate(m_labels):
        try:
            ax = axes.flatten()[m]

            idx = labels[:, 1] == mouse
            arr = data_rescaled[idx]

            if sub_type == 'line':

                for k, var in enumerate(varNames):

                    ax.plot(arr[:, k], lw=.5, color=colors[k], label=var)
                    # ax.axhline(y=arr.mean()[k], c='grey', alpha='.5', label='')
                    # stop
                    make_annotation(ax, arr, data, k, idx, colors, units)

            elif sub_type == 'bar':
                pass
                # bar_width = .2
                # for k, var in enumerate(varNames):
                #     ind = np.arange(len(arr)) + k * bar_width -.1
                #     tkw = {'lw':.2, 'label':var,
                #             'color':colors[k], 'edgecolor':None,
                #             }
                #     ax.bar(ind, arr[:, k], bar_width, **tkw)

            set_layout(E, ax)

            ax.set_title(subtitles[m], fontsize=10)

            if m == 0:
                h, l = ax.get_legend_handles_labels()

        except IndexError:
            ax.axis('off')
            continue

    # legend
    tkw = {
        'ncol': 3,
        'fontsize': 8,
        'bbox_to_anchor': [0.85, .08],
        'frameon': False
    }
    legend = fig.legend(h, l, **tkw)
    for label in legend.get_lines():
        label.set_linewidth(3)  # the legend line width

    # set subplot labels
    xlabel = 'Experiment Day'
    ylabel = '%s Coefficient' % act
    add_xylabels(fig, xlabel, ylabel)  #, xypad=0, yxpad=0, labelsize=10)
    add_titles_notes(
        E,
        fig,
        title=title,
        # typad=typad,
        # tlxpad=tlxpad,
        # tlypad=typad
    )

    plt.subplots_adjust(bottom=.12, hspace=0.6, wspace=0.4)

    save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE)  #, sypad=-.05)
Beispiel #7
0
def draw_histogram_plot(E, mouse_data, arr_preFast, arr_postFast, mouseNumbers,
                        fname, plot_type, ADD_SOURCE):

    # ZeroLight is one group only
    # for m in xrange(num_mice):
    #     data = mouse_data[m]
    #     label = mouseNumbers[m]
    #     data_pre, data_post = arr_preFast[m], arr_postFast[m]

    #     stop

    # i_act = 0 if act == 'F' else 1
    units = ['mg/s', 'g', 'min']
    # var_names = [E.HCM_variables[x][i_act] for x in var_types]
    varTypes = ['coeffs', 'tots', 'durs']
    varNames = [E.HCM_derived['events'][plot_type][x][0] for x in varTypes]

    num_mice = len(mouseNumbers)
    figsize = (12.8, 3.6)
    nrows, ncols = len(varNames), num_mice

    fig, axes = plt.subplots(nrows,
                             ncols,
                             figsize=figsize,
                             sharex=True,
                             sharey=False)

    colors = [E.fcolors['F'].values()[x] for x in [1, 0, 2]]

    # title, subtitles = get_figure_titles(E, labels, act=act, plot_type=plot_type)

    hls = []
    cnt = 0
    for m in xrange(nrows):  # FC, FT, FD
        data = mouse_data[:, :, m]
        pre, post = arr_preFast[:, m], arr_postFast[:, m]

        for n in xrange(ncols):  # mouseNumbers
            ax = axes.flatten()[cnt]
            # plot quantity across days for each mouse
            ax.plot(data[n, :], lw=.5, color=colors[m])
            if m == 0:
                xmin, xmax = ax.get_xlim()
                ax.axhline(xmin=xmin,
                           xmax=xmax,
                           y=data[n].mean(0),
                           linestyle='-',
                           color=colors[m],
                           zorder=0,
                           label='average FC - up to day 35 value')
                ax.axhline(xmin=xmin,
                           xmax=xmax,
                           y=pre[n],
                           linestyle='--',
                           color='g',
                           zorder=1,
                           label='day%d, FC 4h-preFast value' %
                           E.fastDayNumbers[0])
                ax.axhline(xmin=xmin,
                           xmax=xmax,
                           y=post[n],
                           linestyle=':',
                           color='r',
                           zorder=2,
                           label='day%d FC 1h-postFast value' %
                           E.fastDayNumbers[0])

                ax.set_title('M%d' % mouseNumbers[n], fontsize=10)
                if n == 0:
                    h, l = ax.get_legend_handles_labels()

            if n == 0:
                ax.set_ylabel('%s [%s]' % (varNames[m], units[m]), fontsize=10)

            ax.set_ylim([.9 * data.min(), 1.1 * data.max()])
            set_layout2(E, ax, m, n)

            cnt += 1

    # legend
    tkw = {'fontsize': 8, 'bbox_to_anchor': [0.8, .15], 'frameon': False}
    legend = fig.legend(h, l, **tkw)
    for label in legend.get_lines():
        label.set_linewidth(3)  # the legend line width

    # set subplot labels
    xlabel = 'Experiment Day'
    add_xylabels(fig, xlabel)
    add_titles_notes(
        E,
        fig,
        title='F-Coefficient, F-Total Amounts, F-Total PhotoBeam BreakTime')

    plt.subplots_adjust(bottom=.12)  #, hspace=0.6, wspace=0.4)

    save_plot(fname, fig, ADD_SOURCE=ADD_SOURCE, sypad=-.03)