Esempio n. 1
0
def plot_delta_xy(ds,
                  circ_pt_delts,
                  ax,
                  color_st=None,
                  line_color=(.8, .8, .8),
                  color_incr=.1):
    delta_eg = np.linspace(-.9, .9, 1000)
    dx, dy = am.dxdy_from_dsdelt(ds, delta_eg)

    gpl.plot_trace_werr(dx,
                        dy,
                        ax=ax,
                        log_y=True,
                        log_x=True,
                        color=line_color)

    color = color_st
    for i, cpd in enumerate(circ_pt_delts):
        dx, dy = am.dxdy_from_dsdelt(ds, cpd)
        l = ax.plot(dx, dy, 'o', color=color)
        color = gpl.add_color(l[0].get_color(), color_incr)
    xl = ax.get_xlim()
    yl = ax.get_ylim()
    ax.hlines(ds, *xl, color='k', linestyle='dashed')
    ax.vlines(ds, *yl, color='k', linestyle='dashed')
    ax.set_xlabel(r'$D_{X}$')
    ax.set_ylabel(r'$D_{Y}$')
Esempio n. 2
0
def plot_spatial_bias(ds,
                      conds,
                      labels=None,
                      colors=None,
                      ax=None,
                      filt_func=None,
                      left_field='left_first',
                      right_field='right_first',
                      boots=1000):
    if ax is None:
        f = plt.figure()
        ax = f.add_subplot(1, 1, 1)
    if labels is None:
        labels = ('', ) * len(ds)
    if colors is None:
        colors = (None, ) * len(ds)
    l_func = lambda x: np.sum(x[left_field])
    r_func = lambda x: np.sum(x[right_field])
    ratio_func = _make_ratio_function(l_func, r_func)
    for i, d in enumerate(ds):
        trs = u.get_only_conds(d, conds)
        if filt_func is not None:
            trs = filt_func(trs)
        v = u.bootstrap_list(trs, ratio_func, n=boots)
        v = np.array(v).reshape((-1, 1))
        gpl.plot_trace_werr(np.array([0]) + i,
                            v,
                            error_func=gpl.conf95_interval,
                            ax=ax,
                            label=labs[i],
                            fill=False,
                            color=cols[i])
    return ax
Esempio n. 3
0
def plot_load_mse(data,
                  ax=None,
                  plot_fit=True,
                  max_load=np.inf,
                  boots=None,
                  sep_subj=False,
                  data_color=(.7, .7, .7),
                  **plot_args):
    if ax is None:
        f, ax = plt.subplots(1, 1)
    ls, errs = data
    for i, err in enumerate(errs):
        if sep_subj:
            use_ax = ax[i]
        else:
            use_ax = ax
        l = ls[i]
        mask = l <= max_load
        l = l[mask]
        subj = i + 1
        mse = np.array(err)[mask]**2
        if boots is not None:
            mse = np.array(
                list(
                    u.bootstrap_list(mse_i.flatten(), np.nanmean, boots)
                    for mse_i in mse))
        gpl.plot_trace_werr(l,
                            mse,
                            ax=use_ax,
                            label='S{}'.format(subj),
                            jagged=True,
                            color=data_color,
                            **plot_args)
    return ax
Esempio n. 4
0
def plot_eg_overlap(ax1,
                    ax2,
                    n_stim=2,
                    eg_s=100,
                    color1=(.6, .6, .6),
                    color2=(.6, .6, .6)):
    ax1.set_aspect('equal')
    ax2.set_aspect('equal')

    stims = np.random.rand(n_stim, 3) * 100

    for stim in stims:
        gpl.plot_trace_werr(stim[1], stim[0], marker='o', ax=ax1, color=color1)
        gpl.plot_trace_werr(stim[1], stim[2], marker='o', ax=ax2, color=color2)

    ax1.set_xlim([0, eg_s])
    ax1.set_ylim([0, eg_s])
    _ = ax1.set_yticks([0, eg_s / 2, eg_s])
    _ = ax1.set_yticklabels(['0', 's/2', 's'])
    _ = ax2.set_yticks([0, eg_s / 2, eg_s])
    _ = ax2.set_yticklabels(['0', 's/2', 's'])
    _ = ax1.set_xticks([0, eg_s / 2, eg_s])
    _ = ax1.set_xticklabels(['0', 's/2', 's'])
    ax2.set_xlabel('position')
    ax1.set_ylabel('audition')
    ax2.set_ylabel('vision')
Esempio n. 5
0
def plot_distance_error_prob(ax,
                             distortions=(1, 10, 20),
                             color=None,
                             distance_bounds=(.1, 20),
                             n_dists=1000,
                             label=True,
                             label_num=None,
                             line_label=False,
                             ll_buff=.1,
                             color_incr=.1,
                             emp_ders=None,
                             emp_xs=None):
    distances = np.linspace(distance_bounds[0], distance_bounds[1], n_dists)
    sps = np.zeros((len(distortions), n_dists))
    for i, distort in enumerate(distortions):
        swap_prob = sts.norm(distances, np.sqrt(2 * distort)).cdf(0)
        sp = sts.norm(distances, np.sqrt(2 * distort)).cdf(0)
        swap_prob = 2 * sp - 2 * sp**2
        if label and label_num is None:
            label = r'$D_{X/Y} = ' + '{}$'.format(distort)
        elif label and label_num is not None:
            label = r'$\Delta D = ' + '{}$'.format(label_num[i])
        else:
            label = ''
        if label and line_label:
            legend_label = ''
        else:
            legend_label = label

        if i > 0:
            color = gpl.add_color(color, i * color_incr)
        gpl.plot_trace_werr(distances,
                            swap_prob,
                            ax=ax,
                            label=legend_label,
                            color=color)
        if line_label:
            ms = np.array([
                int(np.floor(n_dists / 2 - ll_buff * n_dists)),
                int(np.ceil(n_dists / 2 + ll_buff * n_dists))
            ])
            gpl.label_plot_line(distances, swap_prob, label, ax, mid_samp=ms)
        sps[i] = swap_prob
        if emp_ders is not None and emp_xs is not None:
            gpl.plot_trace_werr(emp_xs,
                                emp_ders[:, i].T,
                                color=color,
                                error_func=gpl.conf95_interval,
                                ax=ax)
    _ = ax.set_xlabel('distance between stimuli')
    _ = ax.set_ylabel('assignment error\nprobability')
    return sps, distances
Esempio n. 6
0
def plot_distance_distrib_prob(ax,
                               overlap_dims=(1, ),
                               funcs=(am.line_picking_line, ),
                               n_dists=1000):
    for i, d in enumerate(overlap_dims):
        dists = np.linspace(0, np.sqrt(d), n_dists)
        func = funcs[i]
        gpl.plot_trace_werr(dists,
                            func(dists),
                            ax=ax,
                            label='C = {}'.format(d))
    ax.set_xlabel('distance between stimuli')
    _ = ax.set_ylabel('probability density')
Esempio n. 7
0
def plot_sdmst_bias(ds,
                    condlist,
                    cond_labels=None,
                    d_labels=None,
                    d_colors=None,
                    ax=None,
                    filt_func=None,
                    boots=1000,
                    err_field='TrialError',
                    corr=0,
                    incorr=6,
                    offset_div=6,
                    rotate_labels=True):
    if cond_labels is None:
        cond_labels = ('', ) * len(condlist)
    if d_labels is None:
        d_labels = ('', ) * len(ds)
    if d_colors is None:
        d_colors = ('', ) * len(ds)
    if ax is None:
        f = plt.figure()
        ax = f.add_subplot(1, 1, 1)
    corr_func = lambda x: np.sum(x['TrialError'] == corr)
    incorr_func = lambda x: np.sum(x['TrialError'] == incorr)
    ratio_func = _make_ratio_function(corr_func, incorr_func)
    for i, d in enumerate(ds):
        for j, c in enumerate(condlist):
            trs = u.get_only_conds(d, (c, ))
            c_r = u.bootstrap_list(trs, ratio_func, n=boots)
            c_r = np.array(c_r).reshape((-1, 1))
            offset = (i - len(ds) / 2) / 10
            if j == 0:
                use_label = d_labels[i]
            else:
                use_label = ''
            gpl.plot_trace_werr(np.array([j]) + offset,
                                c_r,
                                error_func=gpl.conf95_interval,
                                ax=ax,
                                label=use_label,
                                fill=False,
                                color=d_colors[i])
    ax.set_xticks(range(len(condlist)))
    ax.set_xlabel('condition')
    ax.set_ylabel('P(correct)')
    if rotate_labels:
        ax.set_xticklabels(cond_labels, rotation=90)
    else:
        ax.set_xticklabels(cond_labels)
    return ax
Esempio n. 8
0
def plot_dist_dependence(data,
                         ax=None,
                         eps=1e-4,
                         plot_fit=True,
                         boots=None,
                         sep_subj=False,
                         n_bins=5,
                         need_trials=20,
                         data_color=None,
                         digit_percentile=95,
                         **plot_args):
    if ax is None:
        f, ax = plt.subplots(1, 1)
    ls, load_errs = data
    for j, load in enumerate(load_errs):
        if sep_subj:
            use_ax = ax[j]
        else:
            use_ax = ax
        for i, (errs, dists) in enumerate(load):
            if ls[j][i] > 1:
                l = ls[j][i]
                dists = np.min(np.abs(dists[:, 1:l]), axis=1)
                max_bin = np.percentile(dists, digit_percentile)
                bins = np.linspace(0, max_bin + eps, n_bins + 1)
                bin_inds = np.digitize(dists, bins)
                binned_errs = []
                bin_cents = []
                for bi, binbeg in enumerate(bins[:-1]):
                    mask = bin_inds == bi
                    if np.sum(mask) > need_trials:
                        be = errs[mask].flatten()**2
                        binned_errs.append(be)
                        bin_cents.append((binbeg + bins[bi + 1]) / 2)
                bin_cents = np.array(bin_cents)
                binned_errs = np.array(binned_errs, dtype=object)
                if boots is not None:
                    binned_errs = np.array(
                        list(
                            u.bootstrap_list(be_i, np.mean, boots)
                            for be_i in binned_errs))
                gpl.plot_trace_werr(bin_cents,
                                    binned_errs,
                                    ax=use_ax,
                                    jagged=True,
                                    color=data_color,
                                    **plot_args)
    return ax
Esempio n. 9
0
def plot_rdb(ax, bits_range=(0, 20), n_bits=1000, size=100):
    bits = np.linspace(bits_range[0], bits_range[1], n_bits)
    p = size

    dist = ((p**2) / (2 * np.pi)) * np.exp(-bits)

    gpl.plot_trace_werr(bits, dist, ax=ax, log_y=True, color='r')

    poly_pts = [[bits[0], dist[0]], [bits[-1], dist[-1]], [0, 0]]
    imp_region = plt.Polygon(poly_pts, color='r', alpha=.2)
    ax.add_patch(imp_region)

    ax.set_xlabel(r'information rate $I(X; \hat{X})$ (bits)')
    ax.set_ylabel('estimator variance (MSE)')
    _ = ax.set_xticks([0, 5, 10, 15, 20])
    ax.set_xlim((bits[0], bits[-1]))
    ax.set_ylim((dist[-1], dist[0]))
Esempio n. 10
0
def _plot_di(di, t_ind, xs, axs, n_boots=1000, buff=.01, avg_models=False):
    x_pts = di[:, 0, 0, t_ind]
    y_pts = di[:, 0, 1, t_ind]
    diffs = di[:, :, 1] - di[:, :, 0]
    if avg_models:
        diffs = np.mean(diffs, axis=0)
    else:
        diffs = diffs[:, 0]
    diffs_b = u.bootstrap_list(diffs,
                               u.mean_axis0,
                               n=n_boots,
                               out_shape=(diffs.shape[1], ))
    gpl.plot_trace_werr(xs, diffs_b, ax=axs[1], conf95=True)
    axs[0].plot(x_pts, y_pts, 'o')
    bound_low = min(np.min(x_pts), np.min(y_pts)) - buff
    bound_high = max(np.max(x_pts), np.max(y_pts)) + buff
    axs[0].plot([bound_low, bound_high], [bound_low, bound_high])
    return axs
Esempio n. 11
0
def plot_ae_rate(a_rate, a_approx, pr, s_counts, ax, colors=None):
    for i, s in enumerate(s_counts):
        l = gpl.plot_trace_werr(pr,
                                a_rate[i],
                                label='N = {}'.format(s),
                                ax=ax,
                                log_x=True,
                                log_y=True,
                                error_func=gpl.conf95_interval,
                                color=colors[i])
        gpl.plot_trace_werr(pr,
                            a_approx[i],
                            ax=ax,
                            linestyle='dashed',
                            color=colors[i])

    ax.set_xlabel(r'precision ratio ($s/D_{X/Y}$)')
    ax.set_ylabel('assignment error rate')
Esempio n. 12
0
def plot_fsc_bias(ds, labels=None, colors=None, ax=None, **kwargs):
    if labels is None:
        labels = ('', ) * len(ds)
    if colors is None:
        colors = (None, ) * len(ds)
    if ax is None:
        f = plt.figure()
        ax = f.add_subplot(1, 1, 1)
    for i, d in enumerate(ds):
        x_oas, err_rates = get_fsc_bias(d, **kwargs)
        gpl.plot_trace_werr(x_oas,
                            err_rates.T,
                            error_func=gpl.conf95_interval,
                            ax=ax,
                            label=labels[i],
                            color=colors[i])
    ax.set_ylabel('P(look left)')
    ax.set_xlabel('onset asynchrony (left - right)')
    return ax
Esempio n. 13
0
def plot_metrics(x_vals,
                 metrics,
                 x_label,
                 y_labels=None,
                 axs=None,
                 fwid=3,
                 theory=None,
                 eps=.1,
                 **kwargs):
    if theory is None:
        theory = {}
    if axs is None:
        fsize = (fwid * len(metrics), fwid)
        f, axs = plt.subplots(1, len(metrics), figsize=fsize)
    for i, (k, v) in enumerate(metrics.items()):
        ax = axs[i]
        if len(v.shape) == 3:
            v = np.expand_dims(v, 2)
        vs = v.shape
        col = None
        for j in range(vs[2]):
            v_plot = v[:, :, j]
            v_plot_shape = np.reshape(v_plot, (vs[0], vs[1] * vs[3]))

            l = gpl.plot_trace_werr(x_vals,
                                    v_plot_shape.T,
                                    ax=ax,
                                    color=col,
                                    **kwargs)
            col = l[0].get_color()

        v_theor = theory.get(k)
        if v_theor is not None:
            gpl.plot_trace_werr(x_vals, v_theor, linestyle='dashed', ax=ax)
        ax.set_title(k)
        ax.set_xlabel(x_label)
        if y_labels is not None:
            ax.set_ylabel(y_labels[k])
        yl = ax.get_ylim()
        if np.diff(yl) < eps:
            ax.set_ylim(yl[0] - eps, yl[1] + eps)
    return axs
Esempio n. 14
0
def plot_single_neuron_color(neur_dict,
                             xs,
                             plot_x,
                             filter_keys=None,
                             axs=None,
                             n_shuffs=100):
    x_ind = np.argmin(np.abs(xs - plot_x))
    mi_cs = []
    for i, (k, v) in enumerate(neur_dict.items()):
        if filter_keys is not None and k[-1] in filter_keys:
            if axs is None:
                f, ax = plt.subplots(1, 1)
            else:
                ax = axs[i]
            edges = np.linspace(0, 2 * np.pi, 9)
            bin_ids = np.digitize(v[1], edges)
            jag_tr = []
            jag_tr_shuff = []
            unique_ids = np.unique(bin_ids)
            for i, bi in enumerate(unique_ids):
                jag_tr.append(v[0][bi == bin_ids])
            mi_null = np.zeros(n_shuffs)
            for j in range(n_shuffs):
                bin_ids_shuff = np.random.choice(bin_ids,
                                                 len(bin_ids),
                                                 replace=False)
                for i, bi in enumerate(unique_ids):
                    jag_tr_shuff.append(v[0][bi == bin_ids_shuff])
                mi_null[j] = color_index(jag_tr_shuff)

            gpl.plot_trace_werr(unique_ids, jag_tr, ax=ax, jagged=True)
            mi_c = color_index(jag_tr)
            print(mi_null)
            print('m null', np.nanmean(mi_null))
            print('s null', np.nanstd(mi_null))
            print('unnorm', mi_c)
            mi_c = (mi_c - np.nanmean(mi_null)) / np.nanstd(mi_null)
            print('final', mi_c)
            mi_cs.append(mi_c)
            ax.set_title('MI: {}; {}'.format(mi_c, k[-1]))
    return np.array(mi_cs)
Esempio n. 15
0
def plot_asymmetric_eg(ds,
                       delt,
                       integ_ax,
                       indiv_ax,
                       colors,
                       n_pts=1000,
                       sd_mult=3):
    dx, dy = am.dxdy_from_dsdelt(ds, delt)
    pdf_pts = np.linspace(-sd_mult * np.sqrt(dy), sd_mult * np.sqrt(dy), n_pts)
    c_x, c_y, c_s = colors
    g_x = sts.norm(0, np.sqrt(dx)).pdf(pdf_pts)
    g_y = sts.norm(0, np.sqrt(dy)).pdf(pdf_pts)
    g_s = sts.norm(0, np.sqrt(ds)).pdf(pdf_pts)
    gpl.plot_trace_werr(pdf_pts,
                        g_s,
                        ax=integ_ax,
                        color=c_s,
                        label=r'$s | \hat{x}, \hat{y}$')
    gpl.plot_trace_werr(pdf_pts,
                        g_x,
                        ax=indiv_ax,
                        color=c_x,
                        label=r'$s | \hat{y}$')
    gpl.plot_trace_werr(pdf_pts,
                        g_y,
                        ax=indiv_ax,
                        color=c_y,
                        label=r'$s | \hat{x}$')
    indiv_ax.set_xlabel(r'stimulus value $s$')
    indiv_ax.set_ylabel(r'posterior')
    integ_ax.set_ylabel(r'posterior')
Esempio n. 16
0
def plot_loss_summary(loss_a, tr_corr, tr_swap, val_corr, val_swap, fwid=5):
    f, (ax_l, ax_ang, ax_val) = plt.subplots(
        1,
        3,
        figsize=(fwid * 3, fwid),
    )
    ax_l.plot(loss_a)
    xs_full = np.arange(len(tr_corr))
    xs = np.arange(len(val_corr))
    gpl.plot_trace_werr(xs_full, np.abs(np.array(tr_corr).T), ax=ax_ang)
    gpl.plot_trace_werr(xs_full, np.abs(np.array(tr_swap).T), ax=ax_ang)
    gpl.plot_trace_werr(xs, np.abs(np.array(val_corr).T), ax=ax_val)
    gpl.plot_trace_werr(xs, np.abs(np.array(val_swap).T), ax=ax_val)

    gpl.add_hlines(np.pi / 2, ax_ang)
    gpl.add_hlines(np.pi / 2, ax_val)
Esempio n. 17
0
def plot_plt_bias(ds,
                  labs=None,
                  cols=None,
                  filt_errs=True,
                  err_field='TrialError',
                  corr=0,
                  sep_field='angular_separation',
                  axs=None,
                  cond_nf=22,
                  cond_fn=19,
                  cond_nn=21,
                  cond_ff=20,
                  postthr='fixation_off',
                  sacc_vthr=.1,
                  readdpost=False,
                  lc=(-9, 0),
                  rc=(9, 0),
                  wid=3,
                  hei=3,
                  centoffset=(0, 0),
                  use_bhv_img_params=True,
                  boots=1000,
                  sep_filt=None,
                  figsize=(12, 4)):
    if labs is None:
        labs = ('', ) * len(ds)
    if cols is None:
        cols = ('', ) * len(ds)
    if axs is None:
        f = plt.figure(figsize=figsize)
        ax_fs_nl = f.add_subplot(1, 3, 1)
        ax_fs_nr = f.add_subplot(1, 3, 2)
        ax_fs_bias = f.add_subplot(1, 3, 3)
    else:
        ax_fs_nl, ax_fs_nr, ax_fs_bias = axs
    ax_fs_nl.set_title('left novelty bias')
    ax_fs_nr.set_title('right novelty bias')
    ax_fs_bias.set_title('full bias')
    ax_fs_nl.set_ylabel('P(look left| novel vs familiar) -\n'
                        'P(look left | homogeneous)')
    ax_fs_bias.set_ylabel('P(look novel)')
    ax_fs_nl.set_xlabel('session')
    ax_fs_nr.set_xlabel('session')
    ax_fs_bias.set_xlabel('session')

    conds = (cond_nn, cond_fn, cond_nf, cond_ff)
    for i, d in enumerate(ds):
        seps = np.unique(d[sep_field])
        if sep_filt is not None:
            seps = sep_filt(seps)
        for j, s in enumerate(seps):
            d_sep = d[d[sep_field] == s]

            x = es.get_fixtimes(d,
                                conds,
                                postthr=postthr,
                                thr=sacc_vthr,
                                readdpost=readdpost,
                                lc=lc,
                                rc=rc,
                                wid=wid,
                                hei=hei,
                                centoffset=centoffset,
                                use_bhv_img_params=use_bhv_img_params)
            ls, ts, begs, ends = x
            fls = es.get_first_sacc_latency_nocompute(begs,
                                                      ts,
                                                      onim=False,
                                                      first_n=1,
                                                      sidesplit=True)
            sacc_arr1 = _make_fls_arr(fls, cond_nf)
            sacc_arr_nn = _make_fls_arr(fls, cond_nn)
            sacc_arr_ff = _make_fls_arr(fls, cond_ff)
            sacc_arr_null = np.concatenate((sacc_arr_nn, sacc_arr_ff))
            # look novel when on left
            f1 = lambda x: np.sum(x == 0)
            f2 = lambda x: np.sum(x == 1)
            rf1 = _make_ratio_function(f1, f2)
            nov_left = u.bootstrap_list(sacc_arr1, rf1, n=boots)
            nov_left = nov_left.reshape((-1, 1))
            sub1 = np.mean(u.bootstrap_list(sacc_arr_null, rf1, n=boots))
            gpl.plot_trace_werr(np.array([0]) + i,
                                nov_left - sub1,
                                error_func=gpl.conf95_interval,
                                ax=ax_fs_nl,
                                label=labs[i],
                                fill=False,
                                color=cols[i])

            sacc_arr2 = _make_fls_arr(fls, cond_fn, l=1, r=0)
            # look novel when on right
            nov_right = u.bootstrap_list(sacc_arr2, rf1, n=boots)
            nov_right = nov_right.reshape((-1, 1))
            rf2 = _make_ratio_function(f2, f1)
            sub2 = np.mean(u.bootstrap_list(sacc_arr_null, rf2, n=boots))
            gpl.plot_trace_werr(np.array([0]) + i,
                                nov_right - sub2,
                                error_func=gpl.conf95_interval,
                                ax=ax_fs_nr,
                                fill=False,
                                color=cols[i])

            full_sacc_arr = np.concatenate((sacc_arr1, sacc_arr2))
            nov_full = u.bootstrap_list(full_sacc_arr, rf1, n=boots)
            nov_full = nov_full.reshape((-1, 1))
            gpl.plot_trace_werr(np.array([0]) + i,
                                nov_full,
                                error_func=gpl.conf95_interval,
                                ax=ax_fs_bias,
                                fill=False,
                                color=cols[i])
Esempio n. 18
0
def plot_stan_model(model,
                    ae_ax,
                    dist_ax,
                    uni_ax,
                    n=4,
                    spacing=np.pi / 4,
                    sz=8):
    m = model[0]
    rb_means = np.mean(m.samples['report_bits'], axis=0)
    db_means = np.mean(m.samples['dist_bits'], axis=0)
    sm_means = np.mean(m.samples['stim_mem'], axis=0)
    ae_prob, _ = da.ae_var_discrete(db_means, n, spacing=spacing, sz=sz)
    unif_prob = da.uniform_prob(sm_means, n)
    dist = da.dr_gaussian(rb_means, n)
    subj_xs = np.random.randn(len(dist))
    x_pos = np.array([0])
    ae_prob_arr = np.expand_dims(ae_prob, 1)
    p = ae_ax.violinplot(ae_prob, positions=x_pos, showextrema=False)
    gpl.plot_trace_werr(x_pos,
                        ae_prob_arr,
                        points=True,
                        ax=ae_ax,
                        error_func=gpl.conf95_interval)

    dist_arr = np.expand_dims(dist, 1)
    p = dist_ax.violinplot(dist, positions=x_pos, showextrema=False)
    gpl.plot_trace_werr(x_pos,
                        dist_arr,
                        points=True,
                        ax=dist_ax,
                        error_func=gpl.conf95_interval)

    up_arr = np.expand_dims(unif_prob, 1)
    p = uni_ax.violinplot(up_arr, positions=x_pos, showextrema=False)
    gpl.plot_trace_werr(x_pos,
                        up_arr,
                        points=True,
                        ax=uni_ax,
                        error_func=gpl.conf95_interval)

    gpl.clean_plot(ae_ax, 0)
    gpl.clean_plot_bottom(ae_ax)
    gpl.clean_plot(dist_ax, 0)
    gpl.clean_plot_bottom(dist_ax)
    gpl.clean_plot(uni_ax, 0)
    gpl.clean_plot_bottom(uni_ax)
    gpl.make_yaxis_scale_bar(ae_ax,
                             anchor=0,
                             magnitude=.2,
                             double=False,
                             label='assignment\nerror rate',
                             text_buff=.95)
    gpl.make_yaxis_scale_bar(dist_ax,
                             anchor=0,
                             magnitude=.5,
                             double=False,
                             label='local distortion\n(MSE)',
                             text_buff=.8)
    gpl.make_yaxis_scale_bar(uni_ax,
                             anchor=0,
                             magnitude=.2,
                             double=False,
                             label='guess rate',
                             text_buff=.7)
Esempio n. 19
0
def plot_stan_models(model_dict,
                     f=None,
                     fsize=(12, 4),
                     lw=10,
                     chains=4,
                     nov_param='eps.*',
                     bias_param='bias\[.*',
                     sal_param='s\[.*',
                     lil=.1,
                     sort_by_nov=True,
                     sal_pairs=1000,
                     remove_errs=True,
                     errfield=None,
                     diag_ind=2):
    if f is None:
        f = plt.figure(figsize=fsize)
    if remove_errs:
        model_dict = _remove_errs_models(model_dict,
                                         errfield,
                                         diag_ind=diag_ind)
    ax_sal = f.add_subplot(2, 1, 1)
    ax_par = f.add_subplot(2, 1, 2)
    nov_col = None
    fam_col = None
    nov_fits = np.zeros((len(model_dict), chains))
    bias_fits = np.zeros((len(model_dict), 2, chains))
    expsal_fits = np.zeros((len(model_dict), chains))
    sal_diff = np.zeros((len(model_dict), chains))
    for i, (k, v) in enumerate(model_dict.items()):
        fit, params, diags = v
        nov_sals = su.get_stan_params(fit, sal_param, params['img_cats'] == 1)
        nov_sals = np.expand_dims(np.mean(nov_sals, axis=1), axis=0).T
        fam_sals = su.get_stan_params(fit, sal_param, params['img_cats'] == 0)
        fam_sals = np.expand_dims(np.mean(fam_sals, axis=1), axis=0).T
        xs = np.array([i])
        nl = gpl.plot_trace_werr(xs - lil,
                                 nov_sals,
                                 ax=ax_sal,
                                 linewidth=lw,
                                 color=nov_col,
                                 error_func=gpl.conf95_interval)
        fl = gpl.plot_trace_werr(xs + lil,
                                 fam_sals,
                                 ax=ax_sal,
                                 linewidth=lw,
                                 color=fam_col,
                                 error_func=gpl.conf95_interval)
        nov_col = nl[0].get_color()
        fam_col = fl[0].get_color()

        nov_fits[i] = su.get_stan_params(fit, param=nov_param)
        bias_fits[i] = su.get_stan_params(fit, param=bias_param)
        expsal_fits[i] = np.mean(np.abs(np.concatenate((nov_sals, fam_sals))))
        sals = _sample_pairs(np.concatenate((nov_sals, fam_sals)), n=sal_pairs)
        sal_diff[i] = np.mean(sals)
    xs = np.arange(len(model_dict))
    nov_mag = np.abs(nov_fits)
    bias_diff = np.abs(np.diff(bias_fits, axis=1))
    norm = nov_mag + bias_diff[:, 0] + sal_diff
    if sort_by_nov:
        sort_inds = np.argsort(np.mean(nov_mag / norm, axis=1))
    norm = norm[sort_inds].T
    gpl.plot_trace_werr(xs,
                        nov_mag[sort_inds].T / norm,
                        ax=ax_par,
                        label='novel',
                        marker='o')
    gpl.plot_trace_werr(xs,
                        bias_diff[sort_inds, 0].T / norm,
                        ax=ax_par,
                        label='bias diff',
                        marker='o')
    gpl.plot_trace_werr(xs,
                        sal_diff[sort_inds].T / norm,
                        ax=ax_par,
                        marker='o',
                        label='salience')
    return f
Esempio n. 20
0
def plot_ae_error(ax1,
                  ax2,
                  aes,
                  redund,
                  ols,
                  pr,
                  cut_end=10,
                  delta_d=None,
                  aes_est=None,
                  col_mult=.1):

    redund[redund < 0] = np.nan

    if delta_d is None:
        for i, ae in enumerate(aes):
            l = gpl.plot_trace_werr(pr[:-cut_end],
                                    ae[:-cut_end],
                                    ax=ax1,
                                    log_x=True,
                                    log_y=True,
                                    label='C = {}'.format(ols[i]))
            gpl.plot_trace_werr(pr[:-cut_end],
                                redund[i, :-cut_end],
                                ax=ax2,
                                log_x=True,
                                log_y=False)
            if aes_est is not None:
                ae_est_plot = aes_est[i, 0, :-cut_end].T
                ae_col = l[0].get_color()
                gpl.plot_trace_werr(pr[:-cut_end],
                                    ae_est_plot,
                                    ax=ax1,
                                    color=ae_col,
                                    error_func=gpl.conf95_interval)

    else:
        for i, ae in enumerate(aes):
            color = None
            for j, dd in enumerate(delta_d):
                l_c = 'C = {}'.format(ols[i])
                l_d = r'$\Delta D = ' + '{}$'.format(dd)
                l = ' , '.join((l_c, l_d))
                if j > 0:
                    color = gpl.add_color(color, j * col_mult)
                l = gpl.plot_trace_werr(pr[:-cut_end],
                                        ae[j, :-cut_end],
                                        ax=ax1,
                                        log_x=True,
                                        log_y=True,
                                        label=l,
                                        color=color)
                if aes_est is not None:
                    ae_est_plot = aes_est[i, j, :-cut_end].T
                    ae_col = l[0].get_color()
                    gpl.plot_trace_werr(pr[:-cut_end],
                                        ae_est_plot,
                                        ax=ax1,
                                        color=ae_col,
                                        error_func=gpl.conf95_interval)

                if j == 0:
                    color = l[0].get_color()
                gpl.plot_trace_werr(pr[:-cut_end],
                                    redund[i, j, :-cut_end],
                                    ax=ax2,
                                    log_x=True,
                                    log_y=False,
                                    color=color)
    ax1.set_xlabel('precision ratio ($s/D_{S}$)')
    ax2.set_xlabel('precision ratio ($s/D_{S}$)')
    ax1.set_ylabel('assignment error rate')
    ax2.set_ylabel('redundancy (nats)')