Пример #1
0
def get_fits(y, gt, extra_vars):
    if extra_vars['figure_name'] == 'tbp':
        tcs = np.zeros((2, len(extra_vars['vals'])))
        for i in range(len(extra_vars['vals'])):
            tcs[0, i] = np.corrcoef(
                y[0, i][::iceil(extra_vars['npoints'] /
                                float(len(extra_vars['vals'])))],
                gt[0][i, 1:])[0, 1]
            tcs[1, i] = np.corrcoef(
                y[1, i][::iceil(extra_vars['npoints'] /
                                float(len(extra_vars['vals'])))],
                gt[1][i, 1:])[0, 1]
        it_score = np.mean(tcs)  # ** 2)
    elif extra_vars['figure_name'] == 'tbtcso':
        tcs = np.zeros((y.shape[0]))
        for i in range(y.shape[0]):
            tcs[i] = np.corrcoef(y[i, :], gt[0][i, :])[0, 1]
        it_score = np.mean(tcs)  # ** 2)
    elif extra_vars['figure_name'] == 'bw':
        tcs = np.zeros((y.shape[0], y.shape[1]))
        for r in range(y.shape[0]):
            for c in range(y.shape[1]):
                tcs[r, c] = np.corrcoef(np.squeeze(y[r, c, :]),
                                        np.squeeze(gt[1][r, c, :]))[0, 1]**2
        it_score = np.nanmean(tcs)
    elif extra_vars['figure_name'] == 'tbtcso':
        rs = np.zeros((gt.shape[0]))
        for i, r in enumerate(gt):
            rs[i] = np.corrcoef(y, r)
        it_score = np.mean(rs)
    else:
        it_score = np.corrcoef(y, gt)[0, 1]  # ** 2
    return it_score
Пример #2
0
def draw_ecrf(ax,
              loc=None,
              srf=_DEFAULT_PARAMETERS['srf'],
              ssn=_DEFAULT_PARAMETERS['ssn'],
              ssf=_DEFAULT_PARAMETERS['ssf'],
              off=0.5):

    xlims = ax.get_xlim()
    ylims = ax.get_ylim()

    if loc is None:
        loc = [sum(xlims) / 2., sum(ylims) / 2.]

    ul = lambda sz: [
        loc[0] - ifloor(sz / 2.0) - off, loc[1] - ifloor(sz / 2.0) - off
    ]
    ur = lambda sz: [
        loc[0] + iceil(sz / 2.0) - off, loc[1] - ifloor(sz / 2.0) - off
    ]
    lr = lambda sz: [
        loc[0] + iceil(sz / 2.0) - off, loc[1] + iceil(sz / 2.0) - off
    ]
    ll = lambda sz: [
        loc[0] - ifloor(sz / 2.0) - off, loc[1] + iceil(sz / 2.0) - off
    ]

    # draw CRF
    ax.plot(ul(srf), ur(srf), color='r')
    ax.plot(ur(srf), lr(srf), color='r')
    ax.plot(lr(srf), ll(srf), color='r')
    ax.plot(ll(srf), ul(srf), color='r')

    # draw neCRF
    ax.plot(ul(ssn), ur(ssn), color='g')
    ax.plot(ur(ssn), lr(ssn), color='g')
    ax.plot(lr(ssn), ll(ssn), color='g')
    ax.plot(ll(ssn), ul(ssn), color='g')

    # draw feCRF
    ax.plot(ul(ssf), ur(ssf), color='b')
    ax.plot(ur(ssf), lr(ssf), color='b')
    ax.plot(lr(ssf), ll(ssf), color='b')
    ax.plot(ll(ssf), ul(ssf), color='b')

    # restore plot limits
    ax.set_xlim(xlims)
    ax.set_ylim(ylims)

    return
Пример #3
0
def get_wl87_stim(size, dists, cval, sval, ch, cw, sh, sw):
    """"""
    im = sp.zeros((len(dists), 1, size, size))
    im[:] = sp.nan
    for idx, ds in enumerate(dists):
        u = size // 2 - ifloor(ch / 2.)
        v = size // 2 + iceil(ch / 2.)
        w = size // 2 - ifloor(cw / 2.)
        z = size // 2 + iceil(cw / 2.)
        a = size // 2 - ifloor(sw / 2.)
        b = size // 2 + iceil(sw / 2.)
        it = u - ds - sh
        jt = v + ds
        im[idx, 0, u:v, w:z] = cval
        im[idx, 0, it:it + sh, a:b] = sval
        im[idx, 0, jt:jt + sh, a:b] = sval

    return im
Пример #4
0
def get_population_agaussian(stimulus,
                             npoints=50,
                             fdomain=DEFAULT_FDOMAIN,
                             baseline=DEFAULT_BASELINE_AGAUSSIAN,
                             scale=DEFAULT_SCALE_AGAUSSIAN):
    """"""

    loci = np.linspace(fdomain[0], fdomain[1], npoints)
    b_min, b_max = min(baseline), max(baseline)
    s_min, s_max = min(scale), max(scale)

    bs_ = np.linspace(b_min, b_max, iceil(npoints / 2.))
    _bs = np.linspace(b_max, b_min, iceil(npoints / 2.))
    baselines = np.concatenate((_bs[:ifloor(npoints / 2.)], bs_))

    sc_ = np.linspace(s_min, s_max, iceil(npoints / 2.))
    _sc = np.linspace(s_max, s_min, iceil(npoints / 2.))
    scales = np.concatenate((_sc[:ifloor(npoints / 2.)], sc_))

    h, w = stimulus.shape
    population = np.zeros((npoints, h, w))

    for idx, (loc, bs, sc) in enumerate(zip(loci, baselines, scales)):
        if loc <= (fdomain[1] + fdomain[0]) / 2.:
            population[idx] = agaussian(stimulus,
                                        loc=loc,
                                        bl=bs,
                                        br=b_min,
                                        sl=sc,
                                        sr=s_min)
        if loc > (fdomain[1] + fdomain[0]) / 2.:
            population[idx] = agaussian(stimulus,
                                        loc=loc,
                                        bl=b_min,
                                        br=bs,
                                        sl=s_min,
                                        sr=sc)

    return population
Пример #5
0
def TB2015_plaid(size=_DEFAULT_TB2015PP_SIZE,
                 csize=_DEFAULT_TB2015PP_CSIZE,
                 npoints=_DEFAULT_TB2015PP_NPOINTS,
                 scale=_DEFAULT_TB2015PP_SCALE,
                 cval=_DEFAULT_TB2015PP_CVAL):
    """
    """

    BUFFERFILE = '/home/dmely/data/buffer_tb2015_plaid_cs5.h5'

    # map to a sine for the visualizations
    m = (lambda x: sp.sin(sp.pi * x))

    # simulate populations
    ppop = {
        'kind': 'circular',
        'npoints': npoints,
        'scale': scale,
        'fdomain': (0, 1),
    }

    vals_ang = sp.array([-90., -60., -30., 0., 30., 60.])
    vals = (vals_ang + 90.) / 180.
    imc1 = stim.get_center_surround(size=size,
                                    csize=csize,
                                    cval=cval,
                                    sval=sp.nan)
    x1 = utils.get_population(imc1, **ppop)
    x = sp.zeros((2, len(vals), npoints, size, size))

    for vdx, v in enumerate(vals):
        imc2 = stim.get_center_surround(size=size,
                                        csize=csize,
                                        cval=v,
                                        sval=sp.nan)
        ims = stim.get_center_surround(size=size,
                                       csize=csize,
                                       cval=sp.nan,
                                       sval=v)
        x2 = utils.get_population(imc2, **ppop)
        xs = utils.get_population(ims, **ppop)
        x[0, vdx] = (x1 + x2) / 2.
        x[1, vdx] = (x1 + x2) / 2. + xs
    x.shape = (2 * len(vals), npoints, size, size)

    try:
        with h5py.File(BUFFERFILE, 'r') as h5f:
            pr = h5f['pr'][:]

    except IOError:
        with ContextualCircuit(input_shape=x.shape,
                               keeptime=False,
                               i_gpu=_I_GPU) as cx:
            cx.run(x, from_gpu=False)
            pr = cx.Y[..., size // 2, size // 2].get()
            pr.shape = (2, len(vals), npoints)

        with h5py.File(BUFFERFILE) as h5f:
            h5f['pr'] = pr

    # display population responses for plaids and surrounds
    # raw_input("[Populations] Press Enter to continue.")
    xticks = sp.array([-90., -60., -30., 0., 30., 60., 90.])
    allx = sp.linspace(xticks.min(), xticks.max(), npoints)

    fig, ax = plt.subplots(2, len(vals))
    ax_dat = ax[0, :]
    ax_sim = ax[1, :]

    # plot digitized data
    _plot_TrottBorn2015_population_plaid_data(ax=ax_dat)

    d0 = utils.decode(pr[0], axis=-1, kind='circular_vote')
    d1 = utils.decode(pr[1], axis=-1, kind='circular_vote')
    d0_x = d0 * (xticks.max() - xticks.min()) + xticks.min()
    d1_x = d1 * (xticks.max() - xticks.min()) + xticks.min()

    # plot simulated
    for i in range(len(vals)):
        # population curve
        ax_sim[i].plot(allx,
                       pr[0, i],
                       color=CELL_LINECOLOR,
                       alpha=CELL_LINEALPHA,
                       markersize=0,
                       label='Plaid only',
                       linestyle='-',
                       linewidth=CELL_LINEWIDTH)

        ax_sim[i].plot(allx[::iceil(npoints / 6.)],
                       pr[0, i][::iceil(npoints / 6.)],
                       color=CELL_MARKERCOLOR,
                       alpha=CELL_MARKERALPHA,
                       linestyle='None',
                       markersize=CELL_MARKERSIZE,
                       marker='o')

        ax_sim[i].plot(allx,
                       pr[1, i],
                       color=CELL_LINECOLOR_RED,
                       alpha=CELL_LINEALPHA,
                       markersize=0,
                       label='Plaid + Surround',
                       linestyle='-',
                       linewidth=CELL_LINEWIDTH)

        ax_sim[i].plot(allx[::iceil(npoints / 6.)],
                       pr[1, i][::iceil(npoints / 6.)],
                       color=CELL_MARKERCOLOR_RED,
                       alpha=CELL_MARKERALPHA,
                       linestyle='None',
                       markersize=CELL_MARKERSIZE,
                       marker='o')
        ax_sim[i].set_ylim([0.0, pr.max()])

        # misc
        ax_sim[i].set_xticks(xticks)
        ax_sim[i].set_xticklabels('%i' % (i, ) for i in xticks)
        ax_sim[i].set_xlim((xticks.min(), xticks.max()))

        if not PUBLISH:
            if xticks[i] < 0:
                tt = 'C2 = C1 - %i deg.' % (sp.absolute(xticks[i]), )
            elif xticks[i] > 0:
                tt = 'C2 = C1 + %i deg.' % (sp.absolute(xticks[i]), )
            else:
                tt = 'C2 = C1'
            ax_dat[i].set_title(tt, fontweight='bold', fontsize=15.)
            ax_sim[i].set_xlabel('Orientation\n(relative to preferred)',
                                 fontweight='bold',
                                 fontsize=15.)

            if i == 0:
                ax_dat[i].set_ylabel('Population Response (normalized)',
                                     fontweight='bold',
                                     fontsize=15.)
                ax_sim[i].set_ylabel('Population Response (arbitrary units)',
                                     fontweight='bold',
                                     fontsize=15.)
            if i == len(vals) - 1:
                ax_dat[i].yaxis.set_label_position('right')
                ax_sim[i].yaxis.set_label_position('right')
                ax_dat[i].set_ylabel('Experimental data (neurophysiology)',
                                     fontweight='bold',
                                     fontsize=15.)
                ax_sim[i].set_ylabel('Model simulation',
                                     fontweight='bold',
                                     fontsize=15.)
            # ax_sim[i].patch.set_alpha(0.0)

    for i in range(6):
        if PUBLISH:
            ax_dat[i].set_xticklabels([])
            ax_dat[i].set_yticklabels([])
            ax_sim[i].set_xticklabels([])
            ax_sim[i].set_yticklabels([])

        ax_sim[i].set_xlim((-93, 93))
        ax_dat[i].set_xlim((-93, 93))

        # minima loci
        ax_sim[i].plot([d0_x[i]] * 2,
                       list(ax_sim[i].get_ylim()),
                       color=CELL_LINECOLOR,
                       alpha=CELL_LINEALPHA,
                       linewidth=CELL_ABSCISSA_LW,
                       linestyle='--')
        ax_sim[i].plot([d1_x[i]] * 2,
                       list(ax_sim[i].get_ylim()),
                       color=CELL_LINECOLOR_RED,
                       alpha=CELL_LINEALPHA,
                       linewidth=CELL_ABSCISSA_LW,
                       linestyle='--')

    if PUBLISH:
        CELLFIG(fig=fig, out='/home/dmely/data/cell.out/fig_tb15_pl.pdf')

    return pr
Пример #6
0
    def _prepare_tensors(self):
        """ Allocate buffer space on the GPU, etc. """

        n, k, h, w = self.input_shape
        SRF = self.parameters.srf
        SSN = self.parameters.ssn
        SSF = self.parameters.ssf
        OMEGA = self.parameters.omega
        ISCONTINUOUS = self.parameters.continuous

        # computation parameters
        ########################
        self._cudnn_tensor_format = cudnn.cudnnTensorFormat[
            'CUDNN_TENSOR_NCHW']
        self._cudnn_pooling_mode = cudnn.cudnnPoolingMode[
            'CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING']
        self._cudnn_relu_act = cudnn.cudnnActivationMode[
            'CUDNN_ACTIVATION_RELU']
        self._cudnn_data_type = cudnn.cudnnDataType[
            'CUDNN_DATA_FLOAT'] if self.floatX == 'float32' \
                else cudnn.cudnnDataType['CUDNN_DATA_DOUBLE']
        self._cudnn_conv_mode = cudnn.cudnnConvolutionMode[
            'CUDNN_CROSS_CORRELATION']
        # self._cudnn_conv_pref = cudnn.cudnnConvolutionFwdPreference[
        #     'CUDNN_CONVOLUTION_FWD_PREFER_FASTEST']
        self._cudnn_conv_pref = cudnn.cudnnConvolutionFwdPreference[
            'CUDNN_CONVOLUTION_FWD_NO_WORKSPACE']

        # constant tensors
        ##################
        self._gpu_negMU = _array2gpu([-1.0 * self.parameters.mu])
        self._gpu_negNU = _array2gpu([-1.0 * self.parameters.nu])

        # return tensors
        ################
        self.X = _empty2gpu((n, k, h, w))
        self.Y = _empty2gpu((n, k, h, w))
        self._desc_X = cudnn.cudnnCreateTensorDescriptor()
        self._desc_Y = cudnn.cudnnCreateTensorDescriptor()
        cudnn.cudnnSetTensor4dDescriptor(self._desc_X,
                                         self._cudnn_tensor_format,
                                         self._cudnn_data_type, n, k, h, w)
        cudnn.cudnnSetTensor4dDescriptor(self._desc_Y,
                                         self._cudnn_tensor_format,
                                         self._cudnn_data_type, n, k, h, w)

        if self.keeptime:
            self.X_t = sp.zeros((self.maxiter + 1, n, k, h, w))
            self.Y_t = sp.zeros((self.maxiter + 1, n, k, h, w))
        if self.keepvars:
            self.T_t = sp.zeros((self.maxiter + 1, n, k, h, w))
            self.U_t = sp.zeros((self.maxiter + 1, n, k, h, w))
            self.P_t = sp.zeros((self.maxiter + 1, n, k, h, w))
            self.Q_t = sp.zeros((self.maxiter + 1, n, k, h, w))

        # buffer tensors
        ################
        self._gpu_buf1 = _empty2gpu((n, k, h, w))
        self._gpu_buf2 = _empty2gpu((n, k, h, w))
        self._gpu_buf3 = _empty2gpu((n, k, h, w))
        self._gpu_buf4 = _empty2gpu((n, 1, h, w))
        self._desc_buf1 = cudnn.cudnnCreateTensorDescriptor()
        self._desc_buf2 = cudnn.cudnnCreateTensorDescriptor()
        self._desc_buf3 = cudnn.cudnnCreateTensorDescriptor()
        self._desc_buf4 = cudnn.cudnnCreateTensorDescriptor()
        cudnn.cudnnSetTensor4dDescriptor(self._desc_buf1,
                                         self._cudnn_tensor_format,
                                         self._cudnn_data_type, n, k, h, w)
        cudnn.cudnnSetTensor4dDescriptor(self._desc_buf2,
                                         self._cudnn_tensor_format,
                                         self._cudnn_data_type, n, k, h, w)
        cudnn.cudnnSetTensor4dDescriptor(self._desc_buf3,
                                         self._cudnn_tensor_format,
                                         self._cudnn_data_type, n, k, h, w)
        cudnn.cudnnSetTensor4dDescriptor(self._desc_buf4,
                                         self._cudnn_tensor_format,
                                         self._cudnn_data_type, n, 1, h, w)

        # broadly-tuned summation
        #########################
        if self.parameters.omega:
            weights = _sgw(k=k, s=OMEGA) \
                if ISCONTINUOUS else _sdw(k=k, s=OMEGA)
            q_array = sp.array(
                [sp.roll(weights, shift=shift) for shift in range(k)])
            q_array.shape = (k, k, 1, 1)
            self._gpu_q = _array2gpu(q_array)
            self._desc_q = cudnn.cudnnCreateFilterDescriptor()
            self._desc_Q = cudnn.cudnnCreateConvolutionDescriptor()
            cudnn.cudnnSetFilter4dDescriptor(self._desc_q,
                                             self._cudnn_data_type, k, k, 1, 1)
            cudnn.cudnnSetConvolution2dDescriptor(self._desc_Q, 0, 0, 1, 1, 1,
                                                  1, self._cudnn_conv_mode)
            self._algo_q = cudnn.cudnnGetConvolutionForwardAlgorithm(
                self.cudnnContext, self._desc_X, self._desc_q, self._desc_Q,
                self._desc_buf1, self._cudnn_conv_pref, 0)

            assert cudnn.cudnnGetConvolution2dForwardOutputDim(
                self._desc_Q, self._desc_X, self._desc_q) == (n, k, h, w)

        # untuned suppression: reduction across feature axis
        ####################################################
        self._gpu_u = _array2gpu(1.0 / k * sp.ones((1, k, 1, 1)))
        self._desc_u = cudnn.cudnnCreateFilterDescriptor()
        self._desc_U = cudnn.cudnnCreateConvolutionDescriptor()
        cudnn.cudnnSetFilter4dDescriptor(self._desc_u, self._cudnn_data_type,
                                         1, k, 1, 1)
        cudnn.cudnnSetConvolution2dDescriptor(self._desc_U, 0, 0, 1, 1, 1, 1,
                                              self._cudnn_conv_mode)
        self._algo_u = cudnn.cudnnGetConvolutionForwardAlgorithm(
            self.cudnnContext, self._desc_Y, self._desc_u, self._desc_U,
            self._desc_buf4, self._cudnn_conv_pref, 0)

        assert cudnn.cudnnGetConvolution2dForwardOutputDim(
            self._desc_U, self._desc_Y, self._desc_u) == (n, 1, h, w)

        # tuned summation: pooling in h, w dimensions
        #############################################
        SSN_ = 2 * ifloor(SSN / 2.0) + 1
        p_array = sp.zeros((k, k, SSN_, SSN_))
        # Uniform weights
        #----------------
        for pdx in range(k):
            p_array[pdx, pdx, :SSN, :SSN] = 1.0
        p_array[:, :,  # exclude classical receptive field!
                SSN // 2 - ifloor(SRF / 2.0):SSN // 2 + iceil(SRF / 2.0),
                SSN // 2 - ifloor(SRF / 2.0):SSN // 2 + iceil(SRF / 2.0)] = 0.0
        p_array /= SSN**2 - SRF**2  # normalize to get true average
        # Gaussian weights
        #-----------------
        # for pdx in range(k):
        #     p_array[pdx, pdx] = _cg2d(SSN)

        self._gpu_p = _array2gpu(p_array)
        self._desc_p = cudnn.cudnnCreateFilterDescriptor()
        self._desc_P = cudnn.cudnnCreateConvolutionDescriptor()
        cudnn.cudnnSetFilter4dDescriptor(self._desc_p, self._cudnn_data_type,
                                         k, k, SSN_, SSN_)
        cudnn.cudnnSetConvolution2dDescriptor(self._desc_P, SSN_ // 2,
                                              SSN_ // 2, 1, 1, 1, 1,
                                              self._cudnn_conv_mode)
        self._algo_p = cudnn.cudnnGetConvolutionForwardAlgorithm(
            self.cudnnContext, self._desc_X, self._desc_p, self._desc_P,
            self._desc_buf1, self._cudnn_conv_pref, 0)
        # self._algo_p = self._cudnn_conv_pref

        assert cudnn.cudnnGetConvolution2dForwardOutputDim(
            self._desc_P, self._desc_X, self._desc_p) == (n, k, h, w)

        # tuned suppression: pooling in h, w dimensions
        ###############################################
        SSF_ = 2 * ifloor(SSF / 2.0) + 1
        t_array = sp.zeros((k, k, SSF_, SSF_))
        # Uniform weights
        #----------------
        for tdx in range(k):
            t_array[tdx, tdx, :SSF, :SSF] = 1.0
        t_array[:, :,  # exclude near surround!
                SSF // 2 - ifloor(SSN / 2.0):SSF // 2 + iceil(SSN / 2.0),
                SSF // 2 - ifloor(SSN / 2.0):SSF // 2 + iceil(SSN / 2.0)] = 0.0
        t_array /= SSF**2 - SSN**2  # normalize to get true average
        # Gaussian weights
        #-----------------
        # for tdx in range(k):
        #     t_array[tdx, tdx] = _cg2d(SSF)

        self._gpu_t = _array2gpu(t_array)
        self._desc_t = cudnn.cudnnCreateFilterDescriptor()
        self._desc_T = cudnn.cudnnCreateConvolutionDescriptor()
        cudnn.cudnnSetFilter4dDescriptor(self._desc_t, self._cudnn_data_type,
                                         k, k, SSF_, SSF_)
        cudnn.cudnnSetConvolution2dDescriptor(self._desc_T, SSF_ // 2,
                                              SSF_ // 2, 1, 1, 1, 1,
                                              self._cudnn_conv_mode)
        # self._scal_T_alpha = 1.0/(SSF**2.0 - SSN**2.0)
        # self._scal_T_beta = -1.0/(SSF**2.0 - SSN**2.0)
        self._algo_t = cudnn.cudnnGetConvolutionForwardAlgorithm(
            self.cudnnContext, self._desc_Y, self._desc_t, self._desc_T,
            self._desc_buf3, self._cudnn_conv_pref, 0)
        # self._algo_t = self._cudnn_conv_pref

        assert cudnn.cudnnGetConvolution2dForwardOutputDim(
            self._desc_T, self._desc_Y, self._desc_t) == (n, k, h, w)