Ejemplo n.º 1
0
def plot_RF_results(RF_res, stims, fdir, sup_title):
    """Plot receptive field results."""

    # Plot distribution of coverage values.
    putil.set_style('poster', 'white')
    fig = putil.figure()
    ax = putil.axes()
    sns.distplot(RF_res.S1_cover, bins=np.arange(0, 1.01, 0.1),
                 kde=False, rug=True, ax=ax)
    putil.set_limits(ax, [0, 1])
    fst = util.format_to_fname(sup_title)
    ffig = fdir + fst + '_S1_coverage.png'
    putil.save_fig(ffig, fig, sup_title)

    # Plot RF coverage and rate during S1 on regression plot for each
    # recording and task.
    tasks = RF_res.index.get_level_values(-1).unique()
    for vname, ylim in [('mean_rate', [0, None]), ('max_rate', [0, None]),
                        ('mDSI', [0, 1])]:
        fig, gs, axes = putil.get_gs_subplots(nrow=len(stims), ncol=len(tasks),
                                              subw=4, subh=4, ax_kws_list=None,
                                              create_axes=True)
        colors = sns.color_palette('muted', len(tasks))
        for istim, stim in enumerate(stims):
            for itask, task in enumerate(tasks):
                # Plot regression plot.
                ax = axes[istim, itask]
                scov, sval = [stim + '_' + name for name in ('cover', vname)]
                df = RF_res.xs(task, level=-1)
                sns.regplot(scov, sval, df, color=colors[itask], ax=ax)
                # Add unit labels.
                uids = df.index.droplevel(0)
                putil.add_unit_labels(ax, uids, df[scov], df[sval])
                # Add stats.
                r, p = sp.stats.pearsonr(df[sval], df[scov])
                pstr = util.format_pvalue(p)
                txt = 'r = {:.2f}, {}'.format(r, pstr)
                ax.text(0.02, 0.98, txt, va='top', ha='left',
                        transform=ax.transAxes)
                # Set labels.
                title = '{} {}'.format(task, stim)
                xlab, ylab = [sn.replace('_', ' ') for sn in (scov, sval)]
                putil.set_labels(ax, xlab, ylab, title)
                # Set limits.
                xlim = [0, 1]
                putil.set_limits(ax, xlim, ylim)

        # Save plot.
        fst = util.format_to_fname(sup_title)
        fname = '{}_cover_{}.png'.format(fst, vname)
        ffig = util.join([fdir, vname, fname])
        putil.save_fig(ffig, fig, sup_title)
Ejemplo n.º 2
0
def fig_title(res_dir, tasks, feat, nrate, ncv, Cs, n_perm, n_pshfl,
              sep_err_trs, sep_by, zscore_by, even_by, PDD_offset, n_most_DS,
              tstep):
    """Return title for decoding result figure with given parameters."""

    feat_str = util.format_to_fname(str(feat))
    tasks_str = ', '.join(tasks)
    cv_str = 'Logistic regression with {}-fold CV'.format(ncv)
    Cs_str = 'regularization: ' + (str(Cs) if Cs != [1] else 'off')
    err_str = 'error trials ' + ('excl.' if sep_err_trs else 'incl.')
    prem_str = '# permutations: {}'.format(n_perm)
    pshfl_str = '# population shuffles: {}'.format(n_pshfl)
    zscore_str = ('raw non-z-scored rates' if util.is_null(zscore_by) else
                  'z-scored by ' + util.format_feat_name(zscore_by, True))
    even_str = ('uneven trial numbers'
                if util.is_null(even_by) else 'trial numbers evened across ' +
                util.format_feat_name(even_by, True))
    PDD_str = ('using all 8 directions' if util.is_null(PDD_offset) else
               'using only PDD/PAD +- {}'.format(PDD_offset))
    nDS_str = ('using {} most DS units'.format(n_most_DS)
               if n_most_DS not in [0, 'all'] else 'all units')
    tstep_str = 'time step: {} ms'.format(int(tstep))
    title = ('Decoding {} in {}'.format(feat_str, tasks_str) +
             '\n{}, {}'.format(cv_str, Cs_str) +
             '\nFR kernel: {}, {}, {}'.format(nrate, tstep_str, err_str) +
             '\n{}, {}, {}'.format(prem_str, pshfl_str, nDS_str) +
             '\n{}, {}, {}'.format(zscore_str, even_str, PDD_str))
    return title
Ejemplo n.º 3
0
def res_fname(res_dir, subdir, tasks, feat, nrate, ncv, Cs, n_perm, n_pshfl,
              sep_err_trs, sep_by, zscore_by, even_by, PDD_offset, n_most_DS,
              tstep):
    """Return full path to decoding result with given parameters."""

    tasks_str = '_'.join(tasks)
    feat_str = util.format_to_fname(str(feat))
    ncv_str = 'ncv{}'.format(ncv)
    Cs_str = 'nregul{}'.format(len(Cs)) if Cs != [1] else 'reguloff'
    prem_str = 'nperm{}'.format(n_perm)
    pshfl_str = 'npshfl{}'.format(n_pshfl)
    err_str = 'w{}err'.format('o' if sep_err_trs else '')
    zscore_str = ('_zscoredby' + util.format_feat_name(zscore_by, True)
                  if not util.is_null(zscore_by) else '')
    even_str = ('_evenby' + util.format_feat_name(even_by, True)
                if not util.is_null(even_by) else '')
    PDD_str = ('_PDDoff{}'.format(int(PDD_offset))
               if not util.is_null(PDD_offset) else '')
    nDS_str = ('top{}u'.format(n_most_DS) if n_most_DS != 0 else 'allu')
    tstep_str = 'tstep{}ms'.format(int(tstep))
    dir_name = '{}{}/{}{}{}{}'.format(res_dir, tasks_str, feat_str, zscore_str,
                                      even_str, PDD_str)
    fname = '{}_{}_{}_{}_{}_{}_{}_{}.data'.format(nrate, ncv_str, Cs_str,
                                                  prem_str, pshfl_str, err_str,
                                                  nDS_str, tstep_str)
    fres = util.join([dir_name, subdir, fname])

    return fres
Ejemplo n.º 4
0
def aroc_fig_fname(res_dir, prefix, offsets, cmap, sort_prd=None):
    """Return full path to AROC result with given parameters."""

    sort_prd_str = ('sorted_by_' + util.format_to_fname(sort_prd)
                    if sort_prd is not None else 'unsorted')
    ostr = 'offset_' + '_'.join([str(int(d)) for d in offsets])
    fname = 'AROC_{}_{}.png'.format(prefix, sort_prd_str)
    ffig = util.join([res_dir + 'heatmap', ostr, cmap, fname])

    return ffig
Ejemplo n.º 5
0
def aroc_table_fname(res_dir, task, nrate, tstep, n_perm, offsets, sort_prd,
                     min_len, pth, vth_hi, vth_lo):
    """Return full path to AROC results table with given parameters."""

    ostr = '_'.join([str(int(d)) for d in offsets])
    ftable = ('{}_{}_tstep{}ms_nperm{}_offs{}'.format(task, nrate, int(tstep),
                                                      n_perm, ostr) +
              '_prd{}_minlen{}_pth{}'.format(sort_prd, int(min_len), pth) +
              '_vthhi{}_vthlo{}'.format(vth_hi, vth_lo))
    ftable = util.join(
        [res_dir + 'tables',
         util.format_to_fname(ftable) + '.xlsx'])
    return ftable
Ejemplo n.º 6
0
def plot_trial_type_distribution(UA, RecInfo, utids=None, tr_par=('S1', 'Dir'),
                                 save_plot=False, fname=None):
    """Plot distribution of trial types."""

    # Init.
    par_str = util.format_to_fname(str(tr_par))
    if utids is None:
        utids = UA.utids(as_series=True)
    recs = util.get_subj_date_pairs(utids)
    tasks = RecInfo.index.get_level_values('task').unique()
    tasks = [task for task in UA.tasks() if task in tasks]  # reorder tasks

    # Init plotting.
    putil.set_style('notebook', 'darkgrid')
    fig, gsp, axs = putil.get_gs_subplots(nrow=len(recs), ncol=len(tasks),
                                          subw=4, subh=3, create_axes=True)

    for ir, rec in enumerate(recs):
        for it, task in enumerate(tasks):

            ax = axs[ir, it]
            rt = rec + (task,)
            if rt not in RecInfo.index:
                ax.set_axis_off()
                continue

            # Get includecd trials and their parameters.
            inc_trs = RecInfo.loc[rt, 'trials']
            utid = utids.xs(rt, level=('subj', 'date', 'task'))[0]
            TrData = UA.get_unit(utid[:-1], utid[-1]).TrData.loc[inc_trs]

            # Create DF to plot.
            anw_df = TrData[[tr_par, 'correct']].copy()
            anw_df['answer'] = 'error'
            anw_df.loc[anw_df.correct, 'answer'] = 'correct'
            all_df = anw_df.copy()
            all_df.answer = 'all'
            comb_df = pd.concat([anw_df, all_df])

            if not TrData.size:
                ax.set_axis_off()
                continue

            # Plot as countplot.
            sns.countplot(x=tr_par, hue='answer', data=comb_df,
                          hue_order=['all', 'correct', 'error'], ax=ax)
            sns.despine(ax=ax)
            putil.hide_tick_marks(ax)
            putil.set_max_n_ticks(ax, 6, 'y')
            ax.legend(loc=[0.95, 0.7])

            # Add title.
            title = '{} {}'.format(rec, task)
            nce = anw_df.answer.value_counts()
            nc, ne = [nce[c] if c in nce else 0 for c in ('correct', 'error')]
            pnc, pne = 100*nc/nce.sum(), 100*ne/nce.sum()
            title += '\n\n# correct: {} ({:.0f}%)'.format(nc, pnc)
            title += '      # error: {} ({:.0f}%)'.format(ne, pne)
            putil.set_labels(ax, title=title, xlab=par_str)

            # Format legend.
            if (ir != 0) or (it != 0):
                ax.legend_.remove()

    # Save plot.
    if save_plot:
        title = 'Trial type distribution'
        if fname is None:
            fname = util.join(['results', 'decoding', 'prepare',
                               par_str + '_trial_type_distr.pdf'])

        putil.save_fig(fname, fig, title, w_pad=3, h_pad=3)
Ejemplo n.º 7
0
    def name_to_fname(self):
        """Return filename compatible name string."""

        fname = util.format_to_fname(self.Name)
        return fname