Пример #1
0
    def regioncontrast(self, coord, window):
        """
        Returns the average contrast values for a group of coordinates.
        """
        import miscfuncs as msc

        msc.cut_around_center(self.texture)
Пример #2
0
def plotsvd(file, f_size=10, filter_size=1):

    data = np.load(file)
    filename = os.path.split(file)[-1].split('.')[0]

    sta = data['sta_unscaled']
    max_i = data['max_i']

    sta, max_i = mf.cut_around_center(sta, max_i, f_size=f_size)

    fit_frame = sta[:, :,  max_i[2]]

    # %%
    sp1, sp2, t1, t2, u, v = mf.svd(sta)

    sp1_filtered = ndi.filters.gaussian_filter(sp1,
                                               sigma=(filter_size,
                                                      filter_size))
    sp2_filtered = ndi.filters.gaussian_filter(sp2,
                                               sigma=(filter_size,
                                                      filter_size))
    ff_filtered = ndi.filters.gaussian_filter(fit_frame,
                                              sigma=(filter_size,
                                                     filter_size))

    plotthese = [fit_frame, sp1, sp2, ff_filtered, sp1_filtered, sp2_filtered]

    fig = plt.figure(dpi=130)
    plt.suptitle('{}\n frame size: {}'.format(filename, f_size))
    rows = 3
    columns = 3
    vmax = np.max(np.abs(sp1))
    vmin = -vmax

    for i in range(6):
        ax = plt.subplot(rows, columns, i+1)
        im = plt.imshow(plotthese[i], vmin=vmin, vmax=vmax, cmap=plf.RFcolormap())
        ax.set_aspect('equal')
        plt.xticks([])
        plt.yticks([])
        for child in ax.get_children():
            if isinstance(child, matplotlib.spines.Spine):
                child.set_color('C{}'.format(i % 3))
                child.set_linewidth(2)
        if i==0: plt.title('center px'); fig.colorbar(im)
        elif i==1: plt.title('SVD spatial 1')
        elif i==2: plt.title('SVD spatial 2')
        if i==0: plt.ylabel('Non-filtered')
        if i==3: plt.ylabel('Gaussian filtered')

    ax = plt.subplot(rows, 1, 3)
    plt.plot(sta[max_i[0], max_i[1], :], label='center px')
    plt.plot(t1, label='Temporal 1')
    plt.plot(t2, label='Temporal 2')
    plf.spineless(ax, 'trlb')  # Turn off spines using custom function
    return fig
def fitgaussian(sta, f_size=10):
    max_i = np.unravel_index(np.argmax(np.abs(sta)), sta.shape)
    try:
        sta, max_i_cut = msc.cut_around_center(sta, max_i, f_size)
    except ValueError as e:
        if str(e).startswith('Frame is out'):
            raise ValueError('Fit failed.')
    fit_frame = sta[..., max_i_cut[-1]]
    # Parameters are in the format:
    # (height,amplitude,center_x,center_y,width_x,width_y,rota)
    pars = gfit.gaussfit(fit_frame)
#    f = gfit.twodgaussian(pars)
    pars_out = pars
    pars_out[2:4] = pars[2:4] - [f_size, f_size] + max_i[:2]
    return pars_out
Пример #4
0
def plotcheckersurround(exp_name, stim_nr, filename=None, spikecutoff=1000,
                        ratingcutoff=4, staqualcutoff=0, inner_b=2,
                        outer_b=4):

    """
    Divides into center and surround by fitting 2D Gaussian, and plot
    temporal components.

    spikecutoff:
        Minimum number of spikes to include.

    ratingcutoff:
        Minimum spike sorting rating to include.

    staqualcutoff:
        Minimum STA quality (as measured by z-score) to include.

    inner_b:
        Defined limit between receptive field center and surround
        in units of sigma.

    outer_b:
        Defined limit of the end of receptive field surround.
    """

    exp_dir = iof.exp_dir_fixer(exp_name)
    stim_nr = str(stim_nr)
    if filename:
        filename = str(filename)

    if not filename:
        savefolder = 'surroundplots'
        label = ''
    else:
        label = filename.strip('.npz')
        savefolder = 'surroundplots_' + label

    _, metadata = asc.read_spikesheet(exp_name)
    px_size = metadata['pixel_size(um)']

    data = iof.load(exp_name, stim_nr, fname=filename)

    clusters = data['clusters']
    stas = data['stas']
    stx_h = data['stx_h']
    exp_name = data['exp_name']
    stimname = data['stimname']
    max_inds = data['max_inds']
    frame_duration = data['frame_duration']
    filter_length = data['filter_length']
    quals = data['quals'][-1, :]

    spikenrs = data['spikenrs']

    c1 = np.where(spikenrs > spikecutoff)[0]
    c2 = np.where(clusters[:, 2] <= ratingcutoff)[0]
    c3 = np.where(quals > staqualcutoff)[0]

    choose = [i for i in range(clusters.shape[0]) if ((i in c1) and
                                                      (i in c2) and
                                                      (i in c3))]
    clusters = clusters[choose]
    stas = list(np.array(stas)[choose])
    max_inds = list(np.array(max_inds)[choose])

    clusterids = plf.clusters_to_ids(clusters)

    t = np.arange(filter_length)*frame_duration*1000

    # Determine frame size so that the total frame covers
    # an area large enough i.e. 2*700um
    f_size = int(700/(stx_h*px_size))

    del data

    for i in range(clusters.shape[0]):

        sta_original = stas[i]
        max_i_original = max_inds[i]

        try:
            sta, max_i = mf.cut_around_center(sta_original,
                                              max_i_original, f_size)
        except ValueError:
            continue

        fit_frame = sta[:, :, max_i[2]]

        if np.max(fit_frame) != np.max(np.abs(fit_frame)):
            onoroff = -1
        else:
            onoroff = 1



        Y, X = np.meshgrid(np.arange(fit_frame.shape[1]),
                           np.arange(fit_frame.shape[0]))

        with warnings.catch_warnings():
            warnings.filterwarnings('ignore',
                                    '.*divide by zero*.', RuntimeWarning)
            pars = gfit.gaussfit(fit_frame*onoroff)
            f = gfit.twodgaussian(pars)
            Z = f(X, Y)

        # Correcting for Mahalonobis dist.
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore',
                                    '.*divide by zero*.', RuntimeWarning)
            Zm = np.log((Z-pars[0])/pars[1])
        Zm[np.isinf(Zm)] = np.nan
        Zm = np.sqrt(Zm*-2)

        ax = plt.subplot(1, 2, 1)

        plf.stashow(fit_frame, ax)
        ax.set_aspect('equal')

        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', category=UserWarning)
            warnings.filterwarnings('ignore', '.*invalid value encountered*.')
            ax.contour(Y, X, Zm, [inner_b, outer_b],
                       cmap=plf.RFcolormap(('C0', 'C1')))

        barsize = 100/(stx_h*px_size)
        scalebar = AnchoredSizeBar(ax.transData,
                                   barsize, '100 µm',
                                   'lower left',
                                   pad=1,
                                   color='k',
                                   frameon=False,
                                   size_vertical=.2)
        ax.add_artist(scalebar)

        with warnings.catch_warnings():
            warnings.filterwarnings('ignore',
                                    '.*invalid value encountered in*.',
                                    RuntimeWarning)
            center_mask = np.logical_not(Zm < inner_b)
            center_mask_3d = np.broadcast_arrays(sta,
                                                 center_mask[..., None])[1]
            surround_mask = np.logical_not(np.logical_and(Zm > inner_b,
                                                          Zm < outer_b))
            surround_mask_3d = np.broadcast_arrays(sta,
                                                   surround_mask[..., None])[1]

        sta_center = np.ma.array(sta, mask=center_mask_3d)
        sta_surround = np.ma.array(sta, mask=surround_mask_3d)

        sta_center_temporal = np.mean(sta_center, axis=(0, 1))
        sta_surround_temporal = np.mean(sta_surround, axis=(0, 1))

        ax1 = plt.subplot(1, 2, 2)
        l1 = ax1.plot(t, sta_center_temporal,
                      label='Center\n(<{}σ)'.format(inner_b),
                      color='C0')
        sct_max = np.max(np.abs(sta_center_temporal))
        ax1.set_ylim(-sct_max, sct_max)
        ax2 = ax1.twinx()
        l2 = ax2.plot(t, sta_surround_temporal,
                      label='Surround\n({}σ<x<{}σ)'.format(inner_b, outer_b),
                      color='C1')
        sst_max = np.max(np.abs(sta_surround_temporal))
        ax2.set_ylim(-sst_max, sst_max)
        plf.spineless(ax1)
        plf.spineless(ax2)
        ax1.tick_params('y', colors='C0')
        ax2.tick_params('y', colors='C1')
        plt.xlabel('Time[ms]')
        plt.axhline(0, linestyle='dashed', linewidth=1)

        lines = l1+l2
        labels = [line.get_label() for line in lines]
        plt.legend(lines, labels, fontsize=7)
        plt.title('Temporal components')
        plt.suptitle(f'{exp_name}\n{stimname}\n{clusterids[i]}')

        plt.subplots_adjust(wspace=.5, top=.85)

        plotpath = os.path.join(exp_dir, 'data_analysis',
                                stimname, savefolder)
        if not os.path.isdir(plotpath):
            os.makedirs(plotpath, exist_ok=True)

        plt.savefig(os.path.join(plotpath, clusterids[i])+'.svg',
                    format='svg', dpi=300)
        plt.close()
    print(f'Plotted checkerflicker surround for {stimname}')
Пример #5
0
t = np.arange(filter_length) * frame_duration * 1000

# Determine frame size so that the total frame covers
# an area large enough i.e. 2*700um
f_size = int(700 / (stx_h * px_size))

del data

for i in range(clusters.shape[0]):

    sta_original = stas[i]
    max_i_original = max_inds[i]

    try:
        sta, max_i = mf.cut_around_center(sta_original, max_i_original, f_size)
    except ValueError:
        continue

    fit_frame = sta[:, :, max_i[2]]

    if np.max(fit_frame) != np.max(np.abs(fit_frame)):
        onoroff = -1
    else:
        onoroff = 1

    Y, X = np.meshgrid(np.arange(fit_frame.shape[1]),
                       np.arange(fit_frame.shape[0]))

    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', '.*divide by zero*.', RuntimeWarning)
Пример #6
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 19 20:17:46 2017

@author: ycan
"""
import miscfuncs as msc
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar

plt.figure(figsize=(8.27, 11.69 * 2))  # A4 size
#plotind=0
for i in range(clusters.shape[0]):
    a = stas[i]
    a = msc.cut_around_center(a, max_inds[i], 25)[0]
    try:
        sta_max = np.max(np.abs([np.max(a), np.min(a)]))
#        plotind+=1
    except ValueError:
        continue
    sta_min = -sta_max
    ax = plt.subplot(17, 6, i + 1)
    ax.imshow(a[:, :, max_inds[i][2]], vmin=sta_min, vmax=sta_max, cmap='RdBu')
    ax.set_aspect('equal')
    plt.title('Cell {:0>3}{:0>2}'.format(clusters[i, 0], clusters[i, 1]),
              fontsize=9)
    ax.axis('off')

scalebar = AnchoredSizeBar(ax.transData,
                           5,
Пример #7
0
def plotcheckersvd(expname, stimnr, filename=None):
    """
    Plot the first two components of SVD analysis.
    """
    if filename:
        filename = str(filename)

    exp_dir = iof.exp_dir_fixer(expname)
    _, metadata = asc.read_spikesheet(exp_dir)
    px_size = metadata['pixel_size(um)']

    if not filename:
        savefolder = 'SVD'
        label = ''
    else:
        label = filename.strip('.npz')
        savefolder = 'SVD_' + label

    data = iof.load(expname, stimnr, filename)

    stas = data['stas']
    max_inds = data['max_inds']
    clusters = data['clusters']
    stx_h = data['stx_h']
    frame_duration = data['frame_duration']
    stimname = data['stimname']
    exp_name = data['exp_name']

    clusterids = plf.clusters_to_ids(clusters)

    # Determine frame size so that the total frame covers
    # an area large enough i.e. 2*700um
    f_size = int(700 / (stx_h * px_size))

    for i in range(clusters.shape[0]):
        sta = stas[i]
        max_i = max_inds[i]

        try:
            sta, max_i = msc.cut_around_center(sta, max_i, f_size=f_size)
        except ValueError:
            continue
        fit_frame = sta[:, :, max_i[2]]

        try:
            sp1, sp2, t1, t2, _, _ = msc.svd(sta)
        # If the STA is noisy (msc.cut_around_center produces an empty array)
        # SVD cannot be calculated, in this case we skip that cluster.
        except np.linalg.LinAlgError:
            continue

        plotthese = [fit_frame, sp1, sp2]

        plt.figure(dpi=200)
        plt.suptitle(f'{exp_name}\n{stimname}\n{clusterids[i]}')
        rows = 2
        cols = 3

        vmax = np.max(np.abs([sp1, sp2]))
        vmin = -vmax

        for j in range(len(plotthese)):
            ax = plt.subplot(rows, cols, j + 1)
            im = plt.imshow(plotthese[j],
                            vmin=vmin,
                            vmax=vmax,
                            cmap=iof.config('colormap'))
            ax.set_aspect('equal')
            plt.xticks([])
            plt.yticks([])
            for child in ax.get_children():
                if isinstance(child, matplotlib.spines.Spine):
                    child.set_color('C{}'.format(j % 3))
                    child.set_linewidth(2)
            if j == 0:
                plt.title('center px')
            elif j == 1:
                plt.title('SVD spatial 1')
            elif j == 2:
                plt.title('SVD spatial 2')
                plf.colorbar(im, ticks=[vmin, 0, vmax], format='%.2f')
                barsize = 100 / (stx_h * px_size)
                scalebar = AnchoredSizeBar(ax.transData,
                                           barsize,
                                           '100 µm',
                                           'lower left',
                                           pad=0,
                                           color='k',
                                           frameon=False,
                                           size_vertical=.3)
                ax.add_artist(scalebar)

        t = np.arange(sta.shape[-1]) * frame_duration * 1000
        plt.subplots_adjust(wspace=0.3, hspace=0)
        ax = plt.subplot(rows, 1, 2)
        plt.plot(t, sta[max_i[0], max_i[1], :], label='center px')
        plt.plot(t, t1, label='Temporal 1')
        plt.plot(t, t2, label='Temporal 2')
        plt.xlabel('Time[ms]')
        plf.spineless(ax, 'trlb')  # Turn off spines using custom function

        plotpath = os.path.join(exp_dir, 'data_analysis', stimname, savefolder)
        if not os.path.isdir(plotpath):
            os.makedirs(plotpath, exist_ok=True)
        plt.savefig(os.path.join(plotpath, clusterids[i] + '.svg'), dpi=300)
        plt.close()
    print(f'Plotted checkerflicker SVD for {stimname}')
Пример #8
0
def plotsvd(file, f_size=10, filter_size=1):

    data = np.load(file)
    filename = os.path.split(file)[-1].split('.')[0]

    sta = data['sta_unscaled']
    max_i = data['max_i']

    sta, max_i = mf.cut_around_center(sta, max_i, f_size=f_size)

    fit_frame = sta[:, :, max_i[2]]

    # %%
    sp1, sp2, t1, t2, u, v = mf.svd(sta)

    sp1_filtered = ndi.filters.gaussian_filter(sp1,
                                               sigma=(filter_size,
                                                      filter_size))
    sp2_filtered = ndi.filters.gaussian_filter(sp2,
                                               sigma=(filter_size,
                                                      filter_size))
    ff_filtered = ndi.filters.gaussian_filter(fit_frame,
                                              sigma=(filter_size, filter_size))

    plotthese = [fit_frame, sp1, sp2, ff_filtered, sp1_filtered, sp2_filtered]

    fig = plt.figure(dpi=130)
    plt.suptitle('{}\n frame size: {}'.format(filename, f_size))
    rows = 3
    columns = 3
    vmax = .7
    vmin = -vmax

    for i in range(6):
        ax = plt.subplot(rows, columns, i + 1)
        im = plt.imshow(plotthese[i],
                        vmin=vmin,
                        vmax=vmax,
                        cmap=plf.RFcolormap())
        ax.set_aspect('equal')
        plt.xticks([])
        plt.yticks([])
        for child in ax.get_children():
            if isinstance(child, matplotlib.spines.Spine):
                child.set_color('C{}'.format(i % 3))
                child.set_linewidth(2)
        if i == 0:
            plt.title('center px')
            fig.colorbar(im)
        elif i == 1:
            plt.title('SVD spatial 1')
        elif i == 2:
            plt.title('SVD spatial 2')
        if i == 0: plt.ylabel('Non-filtered')
        if i == 3:
            plt.ylabel('Gaussian filtered')
            from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar

            scalebar = AnchoredSizeBar(ax.transData,
                                       3,
                                       '180 µm',
                                       'lower right',
                                       pad=.5,
                                       color='grey',
                                       frameon=False,
                                       size_vertical=.3)
            ax.add_artist(scalebar)

    ax = plt.subplot(rows, 1, 3)
    plt.plot(sta[max_i[0], max_i[1], :], label='center px')
    plt.plot(t1, label='Temporal 1')
    plt.plot(t2, label='Temporal 2')
    plt.axis([0, 20, -.75, .5])
    plf.spineless(ax, 'trlb')  # Turn off spines using custom function
    return fig
Пример #9
0
spikenrs = np.array([a.sum() for a in data['all_spiketimes']])

clusterids = plf.clusters_to_ids(clusters)

# Determine frame size so that the total frame covers
# an area large enough i.e. 2*700um
px_size = 7.5
f_size = int(700 / (stx_h * px_size))

i = 63
#%%
sta = stas[i]
max_i = max_inds[i]
fit_frame = sta[:, :, max_i[2]]

stac, max_i = msc.cut_around_center(sta, max_i, f_size + 2)

sp1, sp2, t1, t2, _, _ = msc.svd(stac)

#%%
plt.figure(figsize=(12, 10))
vmax = np.max(np.abs([sp1, sp2]))
vmin = -vmax
plt.subplot(131)
plt.imshow(sp1, cmap=iof.config('colormap'), vmin=vmin, vmax=vmax)
plt.subplot(132)
plt.imshow(sp2, cmap=iof.config('colormap'), vmin=vmin, vmax=vmax)
plt.subplot(133)
im = plt.imshow(fit_frame, cmap=iof.config('colormap'), vmin=vmin, vmax=vmax)
plf.colorbar(im, size='2%', ticks=[vmin, vmax], format='%.2f')
plt.show()