예제 #1
0
파일: modules.py 프로젝트: LBHB/nems_db
def fir(rec, i, o, ci, co, coefficients=[], compute_contrast=True):
    """
    apply fir filters of the same size in parallel. convolve in time, then
    sum across channels

    Parameters
    ----------
    rec : recording
        Recording to transform
    i : string
        Name of input signal
    o : string
        Name of output signal
    ci : string
        Name of input signal for contrast portion
    co : string
        Name of output signal for contrast portion
    coefficients : 2d array
        all coefficients matrix shape=channel X time lag, for which
        .shape[0] matched to the channel count of the input
    compute_contrast : boolean
        Skip contrast portion if False

    """
    fn = lambda x: per_channel(x, coefficients)
    new_signals = [rec[i].transform(fn, o)]
    if compute_contrast:
        gc_fn = lambda x: per_channel(x, np.abs(coefficients))
        new_signals.append(rec[ci].transform(gc_fn, co))

    return new_signals
예제 #2
0
def fir(rec, i, o, ci, co, coefficients=[]):
    """
    apply fir filters of the same size in parallel. convolve in time, then
    sum across channels

    coefficients : 2d array
        all coefficients matrix shape=channel X time lag, for which
        .shape[0] matched to the channel count of the input

    input :
        nems signal named in 'i'. must have dimensionality matched to size
        of coefficients matrix.
    output :
        nems signal in 'o' will be 1 x time singal (single channel)
    """
    fn = lambda x: per_channel(x, coefficients)
    gc_fn = lambda x: per_channel(x, np.abs(coefficients))
    return [rec[i].transform(fn, o), rec[ci].transform(gc_fn, co)]
예제 #3
0
파일: test_modules.py 프로젝트: nadoss/NEMS
def test_firbank():
    n_banks = 2
    bank_count = 3
    x = np.random.randn(2, 100)
    coefficients = np.zeros([6, 10])
    coefficients[0, 1] = 1
    coefficients[n_banks, 3] = -0.5

    # one stimulus per bank
    y = fir.per_channel(x, coefficients, bank_count)

    assert (y.shape == (3, 100))
    assert (y[0, 1] == x[0, 0])
    assert (np.sum(np.abs(y[0, :98] + 2 * y[1, 2:])) == 0)
    np.testing.assert_equal(y[2], 0)

    # one stimulus per filter
    x2 = np.repeat(x, bank_count, axis=0)
    y2 = fir.per_channel(x2, coefficients, bank_count)

    np.testing.assert_array_equal(y2, y)
예제 #4
0
파일: modules.py 프로젝트: LBHB/nems_db
def contrast_kernel(rec,
                    i,
                    o,
                    wc_coefficients=None,
                    fir_coefficients=None,
                    mean=None,
                    sd=None,
                    coefficients=None,
                    f1s=None,
                    taus=None,
                    delays=None,
                    gains=None,
                    use_phi=False,
                    offsets=None,
                    compute_contrast=False,
                    n_coefs=18,
                    auto_copy=None,
                    fixed=False,
                    offset=None):
    # auto_copy is no longer used directly, but is included in the keyword
    # arguments in order to load old versions of the model that have
    # not been re-run
    if auto_copy is not None:
        use_phi = True

    if compute_contrast:
        fs = rec[i].fs
        coeffs, _, _ = _get_ctk_coefficients(wc_coefficients, fir_coefficients,
                                             mean, sd, coefficients, f1s, taus,
                                             delays, gains, use_phi, n_coefs,
                                             offsets, offset, fs)
        fn = lambda x: per_channel(x, coeffs)
        return [rec[i].transform(fn, o)]
    else:
        # pass through vector of 0's until contrast is ready to be computed
        fn = lambda x: np.zeros((1, x.shape[-1]))
        return [rec[i].transform(fn, o)]
예제 #5
0
파일: fir.py 프로젝트: nadoss/nems_db
def basic(rec, coefficients):
    fn = lambda x: fir.per_channel(x, coefficients)
    return [
        rec['bg_pred'].transform(fn, 'bg_pred'),
        rec['fg_pred'].transform(fn, 'fg_pred'),
    ]
예제 #6
0
 def per_channel(self, signal, coefficients, bank_count=1, non_causal=False, rate=1, cross_channels=False):
     return per_channel(signal, coefficients, bank_count, non_causal, rate, cross_channels)
예제 #7
0
def dstrf_details(modelspec,
                  rec,
                  cellid,
                  rr,
                  dindex,
                  dstrf=None,
                  dpcs=None,
                  memory=20,
                  stepbins=3,
                  maxbins=1500,
                  n_pc=3):
    cellids = rec['resp'].chans
    match = [c == cellid for c in cellids]
    c = np.where(match)[0][0]

    # analyze all output channels
    out_channel = [c]
    channel_count = len(out_channel)

    if dstrf is not None:
        stimmag = dstrf.shape[0]

    rec = force_signal_silence(rec)
    stim_mag = rec['stim'].as_continuous()[:, :maxbins].sum(axis=0)
    index_range = np.arange(0, len(stim_mag), 1)
    if dstrf is None:
        log.info(
            'Calculating dstrf for %d channels, %d timepoints (%d steps), memory=%d',
            channel_count, len(index_range), stepbins, memory)
        dstrf = compute_dstrf(modelspec,
                              rec.copy(),
                              out_channel=out_channel,
                              memory=memory,
                              index_range=index_range)

    if dpcs is None:
        # don't skip silent bins

        stim_big = stim_mag > np.max(stim_mag) / 1000
        driven_index_range = index_range[(index_range > memory)
                                         & stim_big[index_range]]
        driven_index_range = driven_index_range[(driven_index_range >= memory)]

        # limit number of bins to speed up analysis
        driven_index_range = driven_index_range[:maxbins]
        #index_range = np.arange(525,725)

        pcs, pc_mag = compute_dpcs(dstrf[driven_index_range, :, :, :],
                                   pc_count=n_pc)

    c_ = 0

    ii = np.arange(rr[0], rr[1])
    rr_orig = ii

    print(pcs.shape, dstrf.shape)
    u = np.reshape(pcs[:, :, :, c_], [n_pc, -1])
    d = np.reshape(dstrf[ii, :, :, c_], [len(ii), -1])
    pc_proj = d @ u.T

    stim = rec['stim'].as_continuous()
    pred = np.zeros((pcs.shape[0], stim.shape[1]))
    for i in range(pcs.shape[0]):
        pred[i, :] = per_channel(stim, np.fliplr(pcs[i, :, :, 0]))

    n_strf = len(dindex)

    f = plt.figure(constrained_layout=True, figsize=(18, 8))
    gs = f.add_gridspec(5, n_strf)
    ax0 = f.add_subplot(gs[0, :])
    ax1 = f.add_subplot(gs[1, :])
    ax2 = f.add_subplot(gs[2, :])
    ax = np.array([f.add_subplot(gs[3, i]) for i in range(n_strf)])
    ax3 = np.array([f.add_subplot(gs[4, i]) for i in range(n_strf)])

    ax0.imshow(rec['stim'].as_continuous()[:, rr_orig],
               aspect='auto',
               origin='lower',
               cmap="gray_r")
    xl = ax0.get_xlim()

    ax1.plot(rec['resp'].as_continuous()[c, rr_orig], color='gray')
    ax1.plot(rec['pred'].as_continuous()[c, rr_orig], color='purple')
    ax1.legend(('actual', 'pred'), frameon=False)
    ax1.set_xlim(xl)
    yl1 = ax1.get_ylim()

    #ax2.plot(pc_proj);
    ax2.plot(pred[:, rr_orig].T)
    ax2.set_xlim(xl)
    ax2.set_ylabel('pc projection')
    ax2.legend(('PC1', 'PC2', 'PC3'), frameon=False)
    yl2 = ax2.get_ylim()

    dindex = np.array(dindex)
    mmd = np.max(np.abs(dstrf[np.array(dindex) + rr[0], :, :, c_]))
    stim = rec['stim'].as_continuous()[:, rr_orig]**2
    mms = np.max(stim)
    stim /= mms

    for i, d in enumerate(dindex):
        ax1.plot([d, d], yl1, '--', color='darkgray')
        ax2.plot([d, d], yl2, '--', color='darkgray')
        _dstrf = dstrf[d + rr[0], :, :, c_]
        if True:
            #_dstrf = np.concatenate((_dstrf,stim[:,(d-_dstrf.shape[1]):d]*mmd), axis=0)
            _dstrf = np.concatenate(
                (_dstrf, _dstrf * stim[:, (d - _dstrf.shape[1]):d]), axis=0)

            #_dstrf *= stim[:,(d-_dstrf.shape[1]):d]
        ds = np.fliplr(_dstrf)
        ds = zoom(ds, [2, 2])
        ax[i].imshow(ds,
                     aspect='auto',
                     origin='lower',
                     clim=[-mmd, mmd],
                     cmap=get_setting('WEIGHTS_CMAP'))
        #plot_heatmap(ds, aspect='auto', ax=ax[i], interpolation=2, clim=[-mmd, mmd], show_cbar=False, xlabel=None, ylabel=None)

        ax[i].set_title(f"Frame {d}", fontsize=8)
        if i < n_pc:
            ds = np.fliplr(pcs[i, :, :, c_])
            ds = zoom(ds, [2, 2])
            mmp = np.max(np.abs(ds))
            #ax3[i].imshow(ds, aspect='auto', origin='lower', clim=[-mmp, mmp])
            ax3[i].imshow(ds,
                          aspect='auto',
                          origin='lower',
                          clim=[-mmp, mmp],
                          cmap=get_setting('WEIGHTS_CMAP'))
        else:
            ax3[i].set_axis_off()

    ax[0].set_ylabel('example frames')
    ax3[0].set_ylabel('PCs')

    return f
예제 #8
0
파일: strf.py 프로젝트: LBHB/NEMS
def nonparametric(rec, coefficients, i='pred', o='pred'):
    fn = lambda x: per_channel(x, coefficients)
    return [rec[i].transform(fn, o)]