Esempio n. 1
0
def time_budgets(experiment, obs_period, htype, bin_type, err_type, ignore):
    days = obs_period_to_days[experiment.name][obs_period]
    res_subdir = experiment.path_to_results(subdir=os.path.join('time_budget'))
    # load data
    fname = "{}_time_budget_{}.json".format(experiment.name, bin_type)
    df_all = experiment.load_json_data(days,
                                       akind='time_budget',
                                       fname=fname,
                                       subakind=bin_type,
                                       sub_index1='timebin',
                                       ignore=ignore)

    # percents
    df = df_all.apply(lambda row: 100. * row / row['total time'],
                      axis=1).drop(columns=['active state', 'total time'])

    # tidy form
    xvar = "percent"
    yvar = "timebin"
    dft = pd.melt(df.reset_index(),
                  id_vars=['group', 'mouse', 'day', 'timebin'],
                  var_name='event',
                  value_name=xvar)
    dft['obs_period'] = dft.apply(days_to_obs_period,
                                  args=(experiment, ),
                                  axis=1)
    # dft['budget type'] = dft.apply(budget_type, axis=1)
    hue = 'group'
    col = 'event'
    num_groups = len(dft.group.unique())

    height = 5 if experiment.name in ['StrainSurvey'] else 4
    fontsize = 4 if experiment.name in ['StrainSurvey'] else 6
    ci = to_seaborn_ci[err_type]
    act_types = ['F', 'D', 'L', 'O', 'IS']
    palettes = [
        get_features_palette(act_to_actlabel[x], num_groups) for x in act_types
    ]
    kws1 = dict(height=height, aspect=1, ci=ci, sharex='col', legend=False)

    if htype == 'groups':
        g = sns.catplot(kind='bar',
                        x=xvar,
                        y=yvar,
                        row='obs_period',
                        col=col,
                        hue=hue,
                        data=dft,
                        **kws1)

        set_layout(g, xvar, yvar, palettes, hue, fontsize)
        set_legends(g, palettes, hue)
        title = "{}\ntime budgets\ngroup averages$\pm${}\ndays: {}: {}" \
            .format(str(experiment), err_type, obs_period, days)
        add_figtitle(g.fig, title, y=1.15, xpad=-0.1, ypad=-0.05)
        plt.subplots_adjust(wspace=0.3)
        # save
        fname = "{}_time_budget_{}_groups_{}_days_test8" \
            .format(experiment.name, bin_type, err_type)
        save_figure(experiment, g.fig, res_subdir, fname)
Esempio n. 2
0
def facets_groups_comparison_hue_group(experiment, obs_period, bin_type, err_type, ignore):

    res_subdir = os.path.join('features', 'groups', 'days_comparison_hue_group')
    days = obs_period_to_days[experiment.name][obs_period]
    bins_label = '24H, DC and LC' if bin_type == '3cycles' else bin_type
    height = 2

    # load AS data
    feature_type = 'AS'
    dft, _ = load_tidy_data(experiment, obs_period, bin_type, feature_type=feature_type, ignore=ignore)
    dft['obs_period'] = dft.apply(days_to_obs_period, args=(experiment,), axis=1)

    row = 'feature'
    col = 'obs_period'
    hue = 'group'
    num_groups = len(dft.group.unique())
    palette = get_features_palette(ftype='active_state', num_items=num_groups)

    # draw
    g = draw_facets(dft, bin_type, err_type, palette, height, row=row, col=col, hue=hue,
                    num_items=16, add_kws=dict(sharey='row'))
    # layout
    set_as_layout(g, bin_type, lw=1)
    set_as_legend(g, palette, hue)
    # title
    title = "{}\nactive state features, {}\ngroup averages $\pm$ {}\ndays comparison:\n{}".format(
        str(experiment), bin_type, err_type, days)
    add_figtitle(g.fig, title, y=1.1, xpad=-0.05, ypad=-0.02)
    plt.subplots_adjust(wspace=0.2)  # necessary, or custom legend will screw the layout up
    # save
    fname = "{}_active_state_features_vs_CT_{}_grp_avg_{}_days_comparison".format(
        experiment.name, bin_type, err_type)
    save_figure(experiment, g.fig, res_subdir, fname)

    # load FDL data
    feature_type = 'FDL'
    dft, _ = load_tidy_data(experiment, obs_period, bin_type, feature_type=feature_type, ignore=ignore)
    # label dataframe in groups-days
    dft[col] = dft.apply(days_to_obs_period, args=(experiment,), axis=1)
    all_days = dft.obs_period.unique()

    for ftype, dfg in dft.groupby('feature_type'):
        palette = get_features_palette(ftype, num_items=len(all_days))

        # draw
        g = draw_facets(dfg, bin_type, err_type, palette, height, row=row, col=col, hue=hue, num_items=16,
                        add_kws=dict(sharey='row'))
        # layout
        set_as_layout(g, bin_type, lw=1)
        set_as_legend(g, palette, hue)

        title = "{}\n{} features, {}\ngroup averages $\pm$ {}\ndays comparison:\n{}".format(
            str(experiment), ftype, bins_label, err_type, days)
        add_figtitle(g.fig, title, y=1.1, xpad=-0.05, ypad=-0.02)
        plt.subplots_adjust(wspace=0.2)  # necessary, or custom legend will screw the layout up
        # save
        fname = "{}_{}_features_vs_CT_{}_grp_avg_{}_days_comparison_hue_group".format(
            experiment.name, ftype, bin_type, err_type)
        save_figure(experiment, g.fig, res_subdir, fname)
Esempio n. 3
0
def plot_as(md, as_num, vel=None):
    # active state data
    as_tset = md.data['preprocessing']['AS_timeset'][as_num - 1]
    vel = vel or vel_index(as_tset)
    fig = plot_active_state_zoom_in(md, as_num, vel)
    figtitle = 'Experiment: {}\ngroup: {}, {}, day: {}\nActive State #{}'.format(
        md.experiment.name, md.group.name, md.mouse.name, md.day, as_num)
    plot_utils.add_figtitle(fig, figtitle, y=1.12)
    return fig
Esempio n. 4
0
def within_as_structure_mice(experiment, num_mins):
    if experiment.name in ['HiFat2']:
        for nmins in num_mins:
            res_subdir = os.path.join('within_as_structure')
            days_dict = OrderedDict(
                (l, v) for l, v in obs_period_to_days[experiment.name].items()
                if l not in ['acclimated', 'comparison'])
            xmax = nmins if num_mins is not None else 200
            nrows = len(days_dict)

            # figure
            for group in list(experiment.groups):
                ncols = len(list(group.valid_mice))
                fig, axes = plt.subplots(nrows,
                                         ncols,
                                         figsize=(20, 5),
                                         sharex=True,
                                         sharey=True)

                for num, (frame, days) in enumerate(
                        obs_period_to_days[experiment.name].iteritems()):
                    if frame not in ['acclimated', 'comparison']:
                        m = 0
                        for mouse in list(group.mice):
                            if not mouse.is_ignored:
                                print "drawing within_as_structure for: {}, {} days".format(
                                    mouse, frame)
                                ax = axes[num][m]
                                data = mouse.create_within_as_structure(
                                    days, nmins)
                                draw_structure(ax, data)
                                set_layout(ax, xmax, num_as=len(data))
                                m += 1

                row_labels = [k for k in days_dict.keys() if k != 'acclimated']
                col_labels = [m[1] for m in group.valid_mice]
                xlabel = "AS time from onset [min]"
                ylabel = "active state counts"
                set_subplots_labels(fig,
                                    ncols,
                                    row_labels,
                                    col_labels,
                                    xlabel,
                                    ylabel,
                                    rxpad=-0.5)
                days = obs_period_to_days[experiment.name]['acclimated']
                title = "{}\nwithin active state structure\ngroup{}: {}\ndays comparison:\n{}" \
                    .format(str(experiment), group.number, group.name, days)
                add_figtitle(fig, title, ypad=-0.03)
                # plt.subplots_adjust(hspace=0.5, wspace=0.4)
                # save
                fname = '{}_within_as_structure_group{}_{}_days_comparison_{}mins'\
                    .format(experiment.name, group.number, group.name, nmins)
                save_figure(experiment, fig, res_subdir, fname)
Esempio n. 5
0
def within_as_structure_groups(experiment, num_mins):
    if experiment.name in ['HiFat2']:
        for nmins in num_mins:
            res_subdir = os.path.join('within_as_structure')
            days_dict = OrderedDict(
                (l, v) for l, v in obs_period_to_days[experiment.name].items()
                if l not in ['acclimated', 'comparison'])

            xmax = nmins if num_mins is not None else 200

            # figure
            nrows = len(days_dict)
            ncols = len(list(experiment.groups))
            fig, axes = plt.subplots(nrows,
                                     ncols,
                                     figsize=(12, 16),
                                     sharex=True,
                                     sharey=True)
            for g, group in enumerate(list(experiment.groups)):
                for num, (frame, days) in enumerate(
                        obs_period_to_days[experiment.name].iteritems()):
                    if frame not in ['acclimated', 'comparison']:
                        print "drawing within_as_structure for: {}, {} days".format(
                            group, frame)
                        ax = axes[num][g]
                        data = group.create_within_as_structure(days)
                        draw_structure(ax, data)
                        set_layout(ax, xmax, num_as=len(data))

            row_labels = [
                '{}:\n{}'.format(k, v) for k, v in days_dict.items()
                if k != 'acclimated'
            ]
            col_labels = [g.name for g in experiment.groups]
            xlabel = "AS time from onset [min]"
            ylabel = "active state counts"
            set_subplots_labels(fig,
                                ncols,
                                row_labels,
                                col_labels,
                                xlabel,
                                ylabel,
                                ylpad=-0.05)
            title = "{}\nwithin active state structure\ngroups, acclimated days comparison:\n{}"\
                .format(str(experiment), group.number, group.name, obs_period_to_days[experiment.name]['acclimated'])
            add_figtitle(fig, title, ypad=-0.03)
            # plt.subplots_adjust(wspace=0.3)
            # save
            fname = '{}_within_as_structure_groups_days_comparison_{}mins' \
                .format(experiment.name, nmins)
            save_figure(experiment, fig, res_subdir, fname)
Esempio n. 6
0
def group_rasters(experiment, obs_period=(), write_days=True, as_only=False):
    """Draws individual rasters in a panel for all individuals in a group """
    days = obs_period_to_days[experiment.name][obs_period]
    num_days = len(days)
    suffix = obs_period.replace('-', '_').replace(' ', '_')

    for group in experiment.groups:
        num_mice = len(list(group.valid_mice))
        figsize, nrows, ncols = figsubplots(num_mice)
        fig, axes = plt.subplots(nrows, ncols, figsize=figsize)

        m = 0
        for mouse in group.mice:
            ax = axes.flatten()[m]
            if not mouse.is_ignored:
                cnt = 0
                for md in mouse.mousedays(days):
                    if not md.is_ignored:
                        print "plotting {}".format(md)
                        y_offset = (num_days - cnt) * 10
                        md.load_npy_data(load_keys)
                        draw_timesets(ax, md, y_offset, as_only)
                        if write_days:
                            ax.text(3.5,
                                    y_offset - 5,
                                    'day{}'.format(md.day),
                                    ha='left',
                                    va='bottom',
                                    fontsize=4)
                    cnt += 1

                set_layout(ax, num_days)
                ax.set_title("{}".format(mouse.name), y=1.15)
                m += 1

        # turn ignored mice axis off
        for ax in axes.flatten()[len(group.valid_mice):]:
            ax.axis('off')

        figtitle = "{}\n{}\n{} days: {}".format(str(experiment), str(group),
                                                suffix, days)
        plot_utils.add_figtitle(fig, figtitle, y=0.97)
        plt.subplots_adjust(hspace=0.4)
        text = '' if not as_only else "AS_only"
        filename = "{}_raster_group{}_{}_{}_days_{}".format(
            experiment.name, group.number, group.name, suffix, text)
        plot_utils.save_figure(experiment,
                               fig,
                               subdir='rasters',
                               filename=filename)
        plt.close()
Esempio n. 7
0
def plot_entire_day(md):
    md.load_npy_data(keys=load_keys)
    md_data = md.data['preprocessing']
    fig, ax = plt.subplots(figsize=(10, 3))
    plot_md(ax, md_data, lw=0.1)
    draw_raster_labels(ax)
    draw_feeder_lickometer_position(ax, label_xpos=30)
    draw_sctive_state_durations(ax, md_data)
    #     draw_rectangle_around_active_state(ax, tstart, tend, as_num)
    figtitle = 'Experiment: {}, group{}: {}\nindv{}: {}, day: {}'.format(
        md.experiment.name, md.group.number, md.group.name, md.mouse.number,
        md.mouse.name, md.day)
    plot_utils.add_figtitle(fig, figtitle, ypad=-0.05)
    return fig
Esempio n. 8
0
def plot_manual_zoomin(md, tstart, dt, tstep, VEL=True):
    md_data = md.data['preprocessing']
    tend = tstart + dt
    ts, te = [
        utils.hcm_time_to_ct_string((x + 7) * 3600) for x in (tstart, tend)
    ]
    print "plotting manual Zoom-In: CT{} to CT{} ..".format(ts, te)
    fig, ax = plt.subplots(figsize=(10, 3))
    plot_md(ax, md_data, lw=1)
    if VEL:
        plot_velocity(ax, md_data)
    zoom_in_xaxis(ax, tstart, tend, tstep)
    show_timeset_durations(ax, md_data, tstart, tend)
    figtitle = 'Experiment: {}\ngroup: {}, {}, day: {}\nZoom-In: CT{} to CT{}'.format(
        md.experiment.name, md.group.name, md.mouse.name, md.day, ts, te)
    plot_utils.add_figtitle(fig, figtitle, y=1.12)
    return fig, ts, te
Esempio n. 9
0
def facets_group_avgs(experiment, obs_period, bin_type, err_type, ignore):
    """ plots features vs CT (bins) and 24H/DC/LC (3cycles) """
    # load data
    dft, _ = load_tidy_data(experiment,
                            obs_period,
                            bin_type,
                            feature_type='FDL',
                            ignore=ignore)

    res_subdir = os.path.join('features', 'groups')
    days = obs_period_to_days[experiment.name][obs_period]
    days_label = obs_period.replace('-', '_').replace(' ', '_')
    bins_label = '24H, DC and LC' if bin_type == '3cycles' else bin_type

    row = 'feature_type'
    col = 'feature'
    hue = 'group'
    height = 2
    groups = dft.group.unique()
    palettes = [
        get_features_palette(act_to_actlabel[x], len(groups)) for x in 'FDL'
    ]
    # draw
    g = draw_facets(dft,
                    bin_type,
                    err_type,
                    height,
                    row=row,
                    col=col,
                    hue=hue,
                    num_items=len(groups))
    # layout
    set_fdl_layout(g, bin_type, palettes)
    set_fdl_legends(g, palettes, hue='group')
    title = "{}\nfeeding, drinking and locomotion features, {}\ngroup averages $\pm$ {}\n{} days:\n{}".format(
        str(experiment), bins_label, err_type, days_label, days)
    add_figtitle(g.fig, title, y=1.1, xpad=-0.05, ypad=-0.03)
    plt.subplots_adjust(
        wspace=0.3)  # necessary, or custom legend will screw the layout up
    # save
    fname = "{}_feeding_drinking_locomotion_features_vs_CT_{}_grp_avg_{}_{}_days" \
        .format(experiment.name, bin_type, err_type, days_label)
    save_figure(experiment, g.fig, res_subdir, fname)
Esempio n. 10
0
def mouse_raster(experiment,
                 obs_period=(),
                 mouse_label=None,
                 write_days=True,
                 as_only=False):
    """Draws a raster plot for one individual. """
    days = obs_period_to_days[experiment.name][obs_period]
    num_days = len(days)
    suffix = obs_period.replace('-', '_').replace(' ', '_')
    mouse = experiment.mouse_object(('', mouse_label))
    fig, ax = plt.subplots(figsize=(12, 8))

    for cnt, md in enumerate(mouse.mousedays(days)):
        print "plotting {}".format(md)
        y_offset = (num_days - cnt) * 10
        md.load_npy_data(load_keys)
        draw_timesets(ax, md, y_offset, as_only)
        if write_days:
            ax.text(3.5,
                    y_offset - 5,
                    'day{}'.format(md.day),
                    ha='left',
                    va='bottom',
                    fontsize=8)

    set_layout(ax, num_days, labelsize=10, height=2)

    figtitle = "{}\n{}\n{} days: {}".format(str(experiment), str(mouse),
                                            suffix, days)
    plot_utils.add_figtitle(fig, figtitle, y=0.97)
    text = '' if not as_only else "_AS_only"
    filename = "{}_raster_group{}_{}_indv{}_{}_{}_days{}" \
        .format(experiment.name, mouse.group.number, mouse.group.name, mouse.number, mouse.name, suffix, text)
    plot_utils.save_figure(experiment,
                           fig,
                           subdir='rasters/mice',
                           filename=filename)
    plt.close()
Esempio n. 11
0
def within_as_structure(experiment, obs_period, num_mins=15):
    res_subdir = os.path.join('within_as_structure')
    days = obs_period_to_days[experiment.name][obs_period]
    xmax = num_mins if num_mins is not None else 200

    for group in experiment.groups:
        figsize, nrows, ncols = figsubplots(group.tot_mice)
        fig, axes = plt.subplots(nrows, ncols, figsize=figsize)

        m = 0
        for mouse in group.mice:
            if not mouse.is_ignored:
                print "drawing within_as_structure for: {}".format(mouse)
                # fig, ax = plt.subplots()
                ax = axes.flatten()[m]
                data = mouse.create_within_as_structure(days, num_mins)
                draw_structure(ax, data)
                set_layout(ax, xmax, num_as=len(data))
                m += 1

        row_labels = [
            '{}:\n{}'.format(k, v) for k, v in days_dict.items()
            if k != 'acclimated'
        ]
        col_labels = [g.name for g in experiment.groups]
        xlabel = "AS time from onset [min]"
        ylabel = "active state counts"
        set_subplots_labels(fig, ncols, row_labels, col_labels, xlabel, ylabel)
        title = "{}\nwithin active state structure\ngroup{}: {}\n{} days:\n{}"\
            .format(str(experiment), group.number, group.name, obs_period, days)
        plt.subplots_adjust(hspace=0.5, wspace=0.4)
        add_figtitle(fig, title)
        # save
        fname = '{}_within_as_structure_group{}_{}_{}_days_{}mins_test3' \
            .format(experiment.name, group.number, group.name, obs_period, num_mins)
        save_figure(experiment, fig, res_subdir, fname)
Esempio n. 12
0
def position_density(experiment,
                     obs_period,
                     htype='group',
                     bin_type='7cycles',
                     xbins=2,
                     ybins=4,
                     ignore=False,
                     csv_file=False):
    """Draws position density plots. """
    days = obs_period_to_days[experiment.name][obs_period]
    timebins = cycle_timebins[bin_type]
    res_subdir = os.path.join('position_density', htype)
    var_name = 'xy_bin'
    value_name = 'value'
    kwargs = dict(xticks=[], yticks=[], title='', xlabel='', ylabel='')
    days_label = obs_period.replace('-', '_').replace(' ', '_')

    if csv_file:
        write_to_csv(experiment, obs_period, bin_type, xbins, ybins, ignore)

    else:
        # load data
        hb = True if htype == 'mousedays' else False
        df_all = load_data(experiment,
                           days,
                           bin_type,
                           xbins=xbins,
                           ybins=ybins,
                           occupancy=True,
                           hb=hb,
                           ignore=ignore)

        if htype == 'groups':
            # figure1: group averages
            # tidy form
            id_vars = ['group', 'timebin']
            dfm = df_all.groupby(id_vars).agg(np.mean)
            dft = pd.melt(dfm.reset_index(),
                          id_vars=id_vars,
                          var_name=var_name,
                          value_name=value_name)
            # figure
            g = sns.FacetGrid(dft,
                              row='group',
                              col='timebin',
                              col_order=timebins,
                              height=2,
                              gridspec_kws={'wspace': 0.05})
            g = g.map_dataframe(draw_imshow,
                                xbins,
                                ybins,
                                hb=hb,
                                annotate=True).set(**kwargs)
            # layout
            colorbar(g)
            set_facetgrid_labels(g)  # rows and cols labels
            title = "{}\nposition density {}x{}, {}\ngroup averages\n{} days:\n{}" \
                .format(str(experiment), xbins, ybins, bin_type, obs_period, days)
            add_figtitle(g.fig, title)
            # save
            fname = "{}_position_{}_xbins{}_ybins{}_groups_{}_days" \
                .format(experiment.name, bin_type, xbins, ybins, days_label)
            save_figure(experiment, g.fig, res_subdir, filename=fname)
            plt.close()

            # figure2: group averages, day by day
            res_subdir = os.path.join(res_subdir, 'days_breakdown')
            id_vars = ['group', 'day', 'timebin']
            dfm = df_all.groupby(id_vars).agg(np.mean)
            dft = pd.melt(dfm.reset_index(),
                          id_vars=id_vars,
                          var_name=var_name,
                          value_name=value_name)
            for timebin, dfg in dft.groupby(['timebin']):
                # figure
                g = sns.FacetGrid(dfg,
                                  row='group',
                                  col='day',
                                  height=2,
                                  gridspec_kws={'wspace': 0.05})
                g = g.map_dataframe(draw_imshow,
                                    xbins,
                                    ybins,
                                    hb=hb,
                                    annotate=True).set(**kwargs)
                # layout
                colorbar(g)
                set_facetgrid_labels(g)  # rows and cols labels
                title = "{}\nposition density {}x{}, {}\ngroup averages, days\n{} days breakdown:\n{}".format(
                    str(experiment), xbins, ybins, timebin, obs_period, days)
                add_figtitle(g.fig, title)
                # save
                fname = "{}_position_{}_xbins{}_ybins{}_{}_grp_avg_{}_days_breakdown" \
                    .format(experiment.name, bin_type, xbins, ybins, timebin, days_label)
                save_figure(experiment, g.fig, res_subdir, fname)
                plt.close()

        elif htype == 'mice':
            id_vars = ['group', 'mouse', 'timebin']
            dfm = df_all.groupby(id_vars).agg(np.mean)
            dft = pd.melt(dfm.reset_index(),
                          id_vars=id_vars,
                          var_name=var_name,
                          value_name=value_name)
            for group_name, dfg in dft.groupby(['group']):
                group_number = experiment.group_number(group_name)
                # figure
                g = sns.FacetGrid(dfg,
                                  row='timebin',
                                  col='mouse',
                                  height=2,
                                  gridspec_kws={'wspace': 0.05})
                g = g.map_dataframe(draw_imshow,
                                    xbins,
                                    ybins,
                                    hb=False,
                                    annotate=True).set(**kwargs)
                # layout
                colorbar(g)
                set_facetgrid_labels(g)  # rows and cols labels
                title = "{}\nposition density {}x{}, {}\ngroup{}: {}\n{} days:\n{}" \
                    .format(str(experiment), xbins, ybins, bin_type, group_number, group_name, obs_period, days)
                add_figtitle(g.fig, title, y=0.95)
                # save
                fname = "{}_position_{}_xbins{}_ybins{}_grp{}_{}_avg_{}_days" \
                    .format(experiment.name, bin_type, xbins, ybins, group_number, group_name, days_label)
                save_figure(experiment, g.fig, res_subdir, filename=fname)
                plt.close()

        elif htype == 'mousedays':
            res_subdir = os.path.join(res_subdir,
                                      'xbins{}_ybins{}'.format(xbins, ybins))
            id_vars = [
                'group', 'mouse', 'day', 'timebin', 'detected', 'observed'
            ]
            dft = pd.melt(df_all.reset_index(),
                          id_vars=id_vars,
                          var_name=var_name,
                          value_name=value_name)
            for name, dfg in dft.groupby(['group', 'mouse']):
                group_name, mouse_name = name
                group_number = experiment.group_number(group_name)
                # figure
                g = sns.FacetGrid(dfg,
                                  row='timebin',
                                  col='day',
                                  height=2,
                                  gridspec_kws={'wspace': 0.05})
                g = g.map_dataframe(draw_imshow,
                                    xbins,
                                    ybins,
                                    hb=hb,
                                    annotate=True).set(**kwargs)
                # layout
                colorbar(g)
                set_facetgrid_labels(g)  # rows and cols labels
                title = "{}\nposition density {}x{}, {}\ngroup{}: {}, {}\n{} days:\n{}".format(
                    str(experiment), xbins, ybins, bin_type, group_number,
                    group_name, mouse_name, obs_period, days)
                add_figtitle(g.fig, title, y=0.95)
                # save
                fname = "{}_position_{}_xbins{}_ybins{}_grp{}_{}_{}_{}_days".format(
                    experiment.name, bin_type, xbins, ybins, group_number,
                    group_name, mouse_name, days_label)
                save_figure(experiment, g.fig, res_subdir, filename=fname)
                plt.close()
Esempio n. 13
0
def facets_groups_comparison_hue_day(experiment, obs_period, htype, timepoint,
                                     err_type, ignore):

    days = obs_period_to_days[experiment.name][obs_period]
    ci = to_seaborn_ci[err_type]
    # load data
    fname = '{}_breakfast_{}_binary_counts_tbinsize30s.json'.format(
        experiment.name, timepoint)
    df_all = experiment.load_json_data(days,
                                       akind='breakfast',
                                       fname=fname,
                                       subakind=timepoint,
                                       sub_index1='as_num',
                                       sub_index2='event',
                                       PROB=True,
                                       ignore=ignore)
    # tidy form
    xvar = "AS time from {} [min]".format(timepoint)
    yvar = "probability"
    dft = pd.melt(df_all.reset_index(),
                  id_vars=['group', 'mouse', 'day', 'event'],
                  var_name=xvar,
                  value_name=yvar)
    tbin_size = dft[xvar].min()
    dft[xvar] = dft[xvar] / 60.  # convert to minutes
    dft['obs_period'] = dft.apply(days_to_obs_period,
                                  args=(experiment, ),
                                  axis=1)

    row = 'event'
    col = 'group'
    hue = 'obs_period'
    num_periods = len(dft.obs_period.unique())
    height = 2
    palettes = [
        get_features_palette(act_to_actlabel[x], num_periods) for x in 'FD'
    ]
    kws1 = dict(height=height,
                aspect=1.5,
                ci=ci,
                sharey='row',
                legend=False,
                markers=[''] * len(dft[xvar].unique()))

    # draw
    if htype == 'groups':
        g = sns.catplot(kind='point',
                        data=dft,
                        x=xvar,
                        y=yvar,
                        row=row,
                        col=col,
                        hue=hue,
                        **kws1)
        # layout
        set_layout(g, xvar, yvar, palettes, hue=hue)
        set_legends(g, palettes, hue=hue)
        # title
        title = "{}\nprobability of event from AS {}\ngroup averages$\pm${}\ndays comparison:\n{}".format(
            str(experiment), timepoint, err_type, days)
        add_figtitle(g.fig, title, y=1.05, ypad=-0.05)
        plt.subplots_adjust(wspace=0.3)
        # save
        res_subdir = experiment.path_to_results(
            subdir=os.path.join('breakfast'))
        fname = "{}_breakfast_{}_tbinsize{}s_groups_{}_days_comparison_hue_day".format(
            experiment.name, timepoint, tbin_size, err_type)
        save_figure(experiment, g.fig, res_subdir, fname)
Esempio n. 14
0
def facets_groups_day_breakdown(experiment, obs_period, bin_type, err_type,
                                ignore):
    res_subdir = os.path.join('features', 'groups', 'days_breakdown')
    days = obs_period_to_days[experiment.name][obs_period]
    days_label = obs_period.replace('-', '_').replace(' ', '_')
    bins_label = '24H, DC and LC' if bin_type == '3cycles' else bin_type
    height = 2

    # load AS data
    dft, _ = load_tidy_data(experiment,
                            obs_period,
                            bin_type,
                            feature_type='AS',
                            ignore=ignore)
    groups = dft.group.unique()
    palette = get_features_palette(ftype='active state', num_items=len(groups))
    # draw
    g = draw_facets(dft,
                    bin_type,
                    err_type,
                    palette,
                    height,
                    row='feature',
                    col='day',
                    hue='group',
                    num_items=len(groups),
                    add_kws=dict(sharey='row'))
    # layout
    set_as_layout(g, bin_type)
    set_as_legend(g, palette, hue='group')
    title = "{}\nactive state features, {}\ngroup averages $\pm$ {}\n{} days breakdown:\n{}"\
        .format(str(experiment), bins_label, err_type, days_label, days)
    add_figtitle(g.fig, title, y=1.1, xpad=-0.05, ypad=-0.02)
    plt.subplots_adjust(
        wspace=0.2)  # necessary, or custom legend will screw the layout up
    # save
    fname = "{}_active_state_features_vs_CT_{}_grp_avg_{}_{}_days_breakdown"\
        .format(experiment.name, bin_type, err_type, days_label)
    save_figure(experiment, g.fig, res_subdir, fname)

    # load FDL data
    dft, _ = load_tidy_data(experiment,
                            obs_period,
                            bin_type,
                            feature_type='FDL',
                            ignore=ignore)
    row = 'feature'
    col = 'day'
    hue = 'group'
    groups = dft.group.unique()
    for ftype, dfg in dft.groupby('feature_type'):
        palette = get_features_palette(ftype, num_items=len(groups))
        # draw
        g = draw_facets(dfg,
                        bin_type,
                        err_type,
                        palette,
                        height,
                        row=row,
                        col=col,
                        hue=hue,
                        num_items=len(groups),
                        add_kws=dict(sharey='row'))
        # layout
        set_as_layout(g, bin_type)
        set_as_legend(g, palette, hue='group')
        title = "{}\n{} features, {}\ngroup averages $\pm$ {}\n{} days breakdown:\n{}" \
            .format(str(experiment), ftype, bins_label, err_type, days_label, days)
        add_figtitle(g.fig, title, y=1.1, xpad=-0.05, ypad=-0.02)
        plt.subplots_adjust(
            wspace=0.2)  # necessary, or custom legend will screw the layout up
        # save
        fname = "{}_{}_features_vs_CT_{}_grp_avg_{}_{}_days_breakdown" \
            .format(experiment.name, ftype, bin_type, err_type, days_label)
        save_figure(experiment, g.fig, res_subdir, fname)
Esempio n. 15
0
def breakfast(experiment,
              obs_period,
              htype='groups',
              timepoint='onset',
              err_type='sem',
              ignore=True):
    days = obs_period_to_days[experiment.name][obs_period]
    res_subdir = experiment.path_to_results(subdir=os.path.join('breakfast'))
    # load data
    fname = '{}_breakfast_{}_binary_counts_tbinsize30s.json'.format(
        experiment.name, timepoint)
    df_all = experiment.load_json_data(days,
                                       akind='breakfast',
                                       fname=fname,
                                       subakind=timepoint,
                                       sub_index1='as_num',
                                       sub_index2='event',
                                       PROB=True,
                                       ignore=ignore)
    # tidy form
    xvar = "AS time from {} [min]".format(timepoint)
    yvar = "probability"
    dft = pd.melt(df_all.reset_index(),
                  id_vars=['group', 'mouse', 'day', 'event'],
                  var_name=xvar,
                  value_name=yvar)
    tbin_size = dft[xvar].min()
    dft[xvar] = dft[xvar] / 60.  # convert to minutes

    col = 'group'
    hue = 'event'
    height = 2
    palette = sns.color_palette([fcolors[act_to_actlabel[x]][1] for x in 'FD'])
    ci = to_seaborn_ci[err_type]
    col_wrap = 4 if experiment.name == 'StrainSurvey' else None
    kws1 = dict(height=height,
                aspect=1.5,
                ci=ci,
                palette=palette,
                sharey='row',
                legend=False,
                col_wrap=col_wrap,
                markers=[''] * len(dft[xvar].unique()))
    if htype == 'groups':
        # draw
        g = sns.catplot(kind='point',
                        x=xvar,
                        y=yvar,
                        col=col,
                        hue=hue,
                        data=dft,
                        **kws1)

        set_layout(g, xvar, yvar)
        set_legend(g, palette, hue='event')
        title = "{}\nprobability of event from AS {}\ngroup averages$\pm${}\ndays: {}: {}" \
            .format(str(experiment), timepoint, err_type, obs_period, days)
        add_figtitle(g.fig, title, y=1.05, ypad=-0.03)
        plt.subplots_adjust(wspace=0.3)
        # save
        fname = "{}_breakfast_{}_tbinsize{}s_groups_{}_days" \
            .format(experiment.name, timepoint, tbin_size, err_type)
        save_figure(experiment, g.fig, res_subdir, fname)