In [1]:
%load_ext autoreload
%autoreload 2
In [7]:
import os
import pathlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
import seaborn as sns
import re
import shutil
import pandas as pd
import scipy.stats

import exdir
import expipe
from distutils.dir_util import copy_tree
import septum_mec
import spatial_maps as sp
import head_direction.head as head
import septum_mec.analysis.data_processing as dp
import septum_mec.analysis.registration
from septum_mec.analysis.plotting import violinplot, despine
from spatial_maps.fields import (
    find_peaks, calculate_field_centers, separate_fields_by_laplace, 
    map_pass_to_unit_circle, calculate_field_centers, distance_to_edge_function, 
    compute_crossings, which_field)
from phase_precession import cl_corr
import matplotlib.mlab as mlab
import scipy.signal as ss
from scipy.interpolate import interp1d
from septum_mec.analysis.plotting import regplot
from skimage import measure
from tqdm.notebook import tqdm_notebook as tqdm
tqdm.pandas()

from septum_mec.analysis.statistics import load_data_frames, make_paired_tables, make_statistics_table
In [ ]:
 
In [8]:
# %matplotlib notebook
%matplotlib inline
In [9]:
project_path = dp.project_path()
project = expipe.get_project(project_path)
actions = project.actions

output_path = pathlib.Path("output") / "spikes-in-field"
(output_path / "statistics").mkdir(exist_ok=True, parents=True)
(output_path / "figures").mkdir(exist_ok=True, parents=True)

Load cell statistics and shuffling quantiles

In [10]:
data, labels, colors, queries = load_data_frames()
Number of sessions above threshold 194
Number of animals 4
Number of individual gridcells 139
Number of gridcell recordings 230

divide into stim not stim

In [34]:
# remove multiple measured cells
results, labels = make_paired_tables(data, ['action', 'unit_name'], cell_types=['gridcell'])
results = results['gridcell']
In [37]:
results['action']
Out[37]:
entity unit_idnum channel_group date Baseline I 11 Hz Baseline II 30 Hz
51 1833 8 0 20719 1833-020719-1 NaN NaN NaN
85 1833 13 0 20719 NaN 1833-020719-2 1833-020719-3 1833-020719-4
86 1833 14 0 20719 NaN 1833-020719-2 1833-020719-3 NaN
58 1833 23 0 200619 1833-200619-1 NaN NaN NaN
127 1833 26 0 200619 NaN NaN 1833-200619-3 1833-200619-4
... ... ... ... ... ... ... ... ...
139 1849 835 4 150319 NaN NaN NaN 1849-150319-4
43 1849 851 5 60319 1849-060319-1 NaN NaN NaN
65 1849 932 7 280219 1849-280219-1 NaN NaN NaN
74 1849 937 7 280219 NaN 1849-280219-2 NaN NaN
105 1849 939 7 280219 NaN NaN 1849-280219-3 NaN

137 rows × 8 columns

In [84]:
def make_unique_unit_df(label):
    output = pd.DataFrame()
    for (i, action_row), (j, unit_name_row) in zip(results['action'].iterrows(), results['unit_name'].iterrows()):
        assert i==j
        if action_row[label] != action_row[label]: # ugly test for nan
            continue
        output.loc[i, 'action'] = action_row[label]
        output.loc[i, 'channel_group'] = action_row.channel_group
        output.loc[i, 'unit_idnum'] = action_row.unit_idnum
        output.loc[i, 'unit_name'] = unit_name_row[label]
        day = action_row[label].split('-')[1]
        output.loc[i, 'unit_day'] = f'{action_row.unit_idnum}_{day}'
    output.unit_name = output.unit_name.values.astype(int)
    output.channel_group = output.channel_group.values.astype(int)
    output.unit_idnum = output.unit_idnum.values.astype(int)
    return output
In [85]:
baseline_i = make_unique_unit_df('Baseline I')
stimulated_11 = make_unique_unit_df('11 Hz')

baseline_ii = make_unique_unit_df('Baseline II')
stimulated_30 = make_unique_unit_df('30 Hz')

print("Number of gridcells in baseline i sessions", len(baseline_i))
print("Number of gridcells in stimulated 11Hz ms sessions", len(stimulated_11))

print("Number of gridcells in baseline ii sessions", len(baseline_ii))
print("Number of gridcells in stimulated 30Hz ms sessions", len(stimulated_30))
Number of gridcells in baseline i sessions 63
Number of gridcells in stimulated 11Hz ms sessions 56
Number of gridcells in baseline ii sessions 46
Number of gridcells in stimulated 30Hz ms sessions 35

Plotting

In [17]:
max_speed = .5 # m/s only used for speed score
min_speed = 0.02 # m/s only used for speed score
position_sampling_rate = 100 # for interpolation
position_low_pass_frequency = 6 # for low pass filtering of position

box_size = [1.0, 1.0]
bin_size = 0.02
smoothing_low = 0.03
smoothing_high = 0.06

speed_binsize = 0.02

stim_mask = True
baseline_duration = 600
In [18]:
data_loader = dp.Data(
    position_sampling_rate=position_sampling_rate, 
    position_low_pass_frequency=position_low_pass_frequency,
    box_size=box_size, bin_size=bin_size, 
    stim_mask=stim_mask, baseline_duration=baseline_duration
)
In [19]:
def find_grid_fields(rate_map, sigma=3, seed=2.5):
    # find fields with laplace
    fields_laplace = sp.fields.separate_fields_by_dilation(rate_map, sigma=sigma, seed=seed)
    fields = fields_laplace.copy() # to be cleaned by Ismakov
    fields_areas = scipy.ndimage.measurements.sum(
        np.ones_like(fields), fields, index=np.arange(fields.max() + 1))
    fields_area = fields_areas[fields]
    fields[fields_area < 9.0] = 0

    # find fields with Ismakov-method
    fields_ismakov, radius = sp.separate_fields_by_distance(rate_map)
    fields_ismakov_real = fields_ismakov * bin_size
    approved_fields = []

    # remove fields not found by both methods
    for point in fields_ismakov:
        field_id = fields[tuple(point)]
        approved_fields.append(field_id)

    for field_id in np.arange(1, fields.max() + 1):
        if not field_id in approved_fields:
            fields[fields == field_id] = 0
            
    return fields
In [20]:
def get_data(row):
    spikes = data_loader.spike_train(row.action, row.channel_group, row.unit_name)
    rate_map = data_loader.rate_map(row.action, row.channel_group, row.unit_name, smoothing=0.04)
    pos_x, pos_y, pos_t, pos_speed = map(data_loader.tracking(row.action).get, ['x', 'y', 't', 'v'])
    stim_times = data_loader.stim_times(row.action)
    if stim_times is not None:
        stim_times = np.array(stim_times)
    spikes = np.array(spikes)
    spikes = spikes[(spikes > pos_t.min()) & (spikes < pos_t.max())]
#     sx, sy = rate_map.shape
#     dx = box_size[0] / sx
#     dy = box_size[1] / sy
#     x_bins = np.arange(0, box_size[0], dx)
#     y_bins = np.arange(0, box_size[1], dy)
#     f = interp2d(x_bins, y_bins, rate_map.T)
#     x_new = np.arange(0, box_size[0], dx / 3)
#     y_new = np.arange(0, box_size[1], dy / 3)
#     rate_map = f(x_new, y_new).T
    fields = find_grid_fields(rate_map)
    
    return spikes, pos_x, pos_y, pos_t, rate_map, fields, stim_times
In [21]:
def compute_field_spikes(row, plot=False, z1=5e-3, z2=11e-3, surrogate_fields=None):
    spikes, pos_x, pos_y, pos_t, rate_map, fields, stim_times = get_data(row)
    if surrogate_fields is not None:
        fields = surrogate_fields
#     if field_num is not None:
#         fields = np.where(fields == field_num, fields, 0)
        
    if plot:
        fig, axs = plt.subplots(1, 3, figsize=(16,9))
        axs[1].set_title(f'{row.action} {row.channel_group} {row.unit_idnum}, G={row.gridness:.3f}')
        dot_size = 10
        
    sx, sy = interp1d(pos_t, pos_x), interp1d(pos_t, pos_y)
    
    stim_spikes = []
    stim_in_field_indices = []
    # set z1 and z2 to be after the response: z1=12e3 - z2=60e3
    if stim_times is not None:
        for t in stim_times:
            idx = np.searchsorted(spikes, [t + z1, t + z2], side='right')
            tmp_spikes = spikes[idx[0]: idx[1]].tolist()
            stim_spikes.extend(tmp_spikes)
        stim_spikes_x = sx(stim_spikes)
        stim_spikes_y = sy(stim_spikes)
        stim_in_field_indices = which_field(stim_spikes_x, stim_spikes_y, fields, box_size).astype(bool)
        
#         stim_ids_ = []
#         stim_spikes_ = []
#         for i, t in enumerate(stim_times):
#             idx = np.searchsorted(spikes, [t, t + 30e-3], side='right')
#             tmp_spikes = (spikes[idx[0]: idx[1]] - t).tolist()
#             stim_ids_.extend([i] * len(tmp_spikes))
#             stim_spikes_.extend(tmp_spikes)
            
#         plt.scatter(stim_spikes_, stim_ids_, s=1)
#         plt.axvspan(z1, z2, color='r', alpha=.3)

    spikes_x = sx(spikes)
    spikes_y = sy(spikes)
    in_field_indices = which_field(spikes_x, spikes_y, fields, box_size).astype(bool)        
    
    if plot:
        axs[0].imshow(
            fields.T.astype(bool), extent=[0, box_size[0], 0, box_size[1]], 
            origin='lower', cmap=plt.cm.Greys, zorder=0)
        axs[0].scatter(
            spikes_x[in_field_indices], spikes_y[in_field_indices], 
            s=dot_size, color='r', zorder=1)
        axs[0].scatter(
            spikes_x[~in_field_indices], spikes_y[~in_field_indices], 
            s=dot_size, color='b', zorder=1)
        if stim_times is not None:
            axs[0].scatter(
                stim_spikes_x, stim_spikes_y,
                s=dot_size, color='orange', zorder=1)
        # Display the image and plot all contours found
        contours = measure.find_contours(fields, 0.0)
        axs[1].imshow(rate_map.T, extent=[0, box_size[0], 0, box_size[1]], origin='lower')

        axs[2].plot(pos_x, pos_y, color='k', alpha=.2, zorder=0)
        axs[2].scatter(
            interp1d(pos_t, pos_x)(spikes), interp1d(pos_t, pos_y)(spikes), 
            s=dot_size, zorder=1)

        for ax in axs.ravel()[1:]:
            for n, contour in enumerate(contours):
                ax.plot(
                    contour[:, 0] * bin_size, contour[:, 1] * bin_size, 
                    lw=4, color='y', zorder=3)

        for ax in axs.ravel():
            ax.axis('image')
            ax.set_xticks([])
            ax.set_yticks([])
    return fields, in_field_indices, stim_in_field_indices
In [22]:
def plot_stim_field_spikes(row, t1=0, t2=30, z1_base=0, z2_base=5, z1_stim=5, z2_stim=11, colors=['k','r']):
    spikes, pos_x, pos_y, pos_t, rate_map, fields, stim_times = get_data(row)
    spikes = np.array(spikes) * 1000
    pos_t = np.array(pos_t) * 1000
    stim_times = np.array(stim_times) * 1000
    
    fig, axs = plt.subplots(1, 2)
    dot_size = 2
        
    sx, sy = interp1d(pos_t, pos_x), interp1d(pos_t, pos_y)
    
    stim_spikes_base = []
    stim_spikes_base_plot = []
    stim_ids_base = []
    stim_spikes_stim = []
    stim_spikes_stim_plot = []
    stim_ids_stim = []
    stim_ids_all = []
    stim_spikes_all = []
    for i, t in enumerate(stim_times):
        idx = np.searchsorted(spikes, [t + z1_base, t + z2_base], side='right')
        tmp_spikes = spikes[idx[0]: idx[1]] - t
        stim_ids_base.extend([i] * len(tmp_spikes))
        stim_spikes_base_plot.extend(tmp_spikes)
        stim_spikes_base.extend(spikes[idx[0]: idx[1]].tolist())
        
        idx = np.searchsorted(spikes, [t + z1_stim, t + z2_stim], side='right')
        tmp_spikes = spikes[idx[0]: idx[1]] - t
        stim_ids_stim.extend([i] * len(tmp_spikes))
        stim_spikes_stim_plot.extend(tmp_spikes)
        stim_spikes_stim.extend(spikes[idx[0]: idx[1]].tolist())
        
        idx = np.searchsorted(spikes, [t + t1, t + t2], side='right')
        tmp_spikes = (spikes[idx[0]: idx[1]] - t).tolist()
        stim_ids_all.extend([i] * len(tmp_spikes))
        stim_spikes_all.extend(tmp_spikes)
        
        
    stim_spikes_base_x = sx(stim_spikes_base)
    stim_spikes_base_y = sy(stim_spikes_base)
#     stim_in_field_indices_base = which_field(
#         stim_spikes_base_x, stim_spikes_base_y, fields, box_size).astype(bool)
    
    stim_spikes_stim_x = sx(stim_spikes_stim)
    stim_spikes_stim_y = sy(stim_spikes_stim)
#     stim_in_field_indices_stim = which_field(
#         stim_spikes_stim_x, stim_spikes_stim_y, fields, box_size).astype(bool)


    axs[0].scatter(stim_spikes_all, stim_ids_all, s=dot_size, color='k', alpha=.5)
    axs[0].scatter(stim_spikes_base_plot, stim_ids_base, s=dot_size, color=colors[0], alpha=.8)
    axs[0].scatter(stim_spikes_stim_plot, stim_ids_stim, s=dot_size, color=colors[1], alpha=.8)
    
    times = np.arange(t1, t2, .1)
    from scipy.stats import gaussian_kde
    kernel = gaussian_kde(stim_spikes_all, 0.1)
    pdf = kernel(times)
    m = max(stim_ids_all)
    pdf = (pdf - pdf.min()) / (pdf - pdf.min()).max() * m
    axs[0].plot(times, pdf, 'k', lw=1)
    axs[0].set_xlim(t1, t2)
#     ax.plot(0, len(trials) * 1.1, ls='none', marker='v', color='k', markersize=5)
#     axs[0].axvspan(0, 5, color='#43a2ca', alpha=.3, zorder=-5)

    contours = measure.find_contours(fields, 0.0)

    axs[1].scatter(
        stim_spikes_base_x, stim_spikes_base_y,
        s=dot_size, color=colors[0], zorder=1, alpha=.8)
    
    axs[1].scatter(
        stim_spikes_stim_x, stim_spikes_stim_y,
        s=dot_size, color=colors[1], zorder=1, alpha=.8)

    axs[1].plot(pos_x, pos_y, color='k', alpha=.2, zorder=0)

    for n, contour in enumerate(contours):
        axs[1].plot(
            contour[:, 0] * bin_size, contour[:, 1] * bin_size, 
            lw=1, color='k', zorder=3)
    axs[0].set_aspect((t2 - t1) / len(stim_times))
    axs[1].axis('image')
    axs[1].set_xticks([])
    axs[1].set_yticks([])
    despine(axs[0])
    despine(axs[1], left=True, bottom=True)
In [23]:
 compute_field_spikes(baseline_i.sort_values('gridness', ascending=False).iloc[18], plot=True)
Out[23]:
(array([[9, 9, 9, ..., 6, 6, 6],
        [9, 9, 9, ..., 6, 6, 6],
        [0, 0, 0, ..., 6, 6, 6],
        ...,
        [0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0],
        [0, 0, 0, ..., 0, 0, 0]], dtype=int32),
 array([False, False, False, ..., False, False, False]),
 [])

Compare individual cells across sessions

In [12]:
baseline_ids = baseline_i.unit_day.unique()
In [13]:
baseline_ids
Out[13]:
array(['30_260619', '31_260619', '32_260619', '78_260619', '79_260619',
       '150_260619', '205_260619', '243_260619', '263_260619',
       '265_260619', '45_010719', '46_010719', '47_010719', '49_010719',
       '96_010719', '118_010719', '121_010719', '185_010719',
       '186_010719', '106_050619', '168_050619', '231_050619',
       '232_050619', '233_050619', '379_150319', '609_120619',
       '658_120619', '615_290519', '616_290519', '666_290519',
       '667_290519', '179_290519', '214_290519', '278_290519',
       '279_290519', '317_290519', '613_200619', '661_200619',
       '361_010319', '362_010319', '168_120619', '233_120619',
       '243_120619', '851_060319', '357_220319', '358_220319',
       '359_220319', '332_060319', '338_060319', '655_060619',
       '715_110319', '8_020719', '56_020719', '57_020719', '58_020719',
       '129_020719', '130_020719', '132_020719', '23_200619',
       '174_200619', '250_200619', '251_200619', '252_200619',
       '253_200619', '304_200619', '932_280219'], dtype=object)
In [14]:
stimulated_11_sub = stimulated_11[stimulated_11.unit_day.isin(baseline_ids)]
In [29]:
len(stimulated_11_sub)
Out[29]:
22
In [15]:
baseline_ids_11 = stimulated_11_sub.unit_day.unique()
In [16]:
baseline_i_sub = baseline_i[baseline_i.unit_day.isin(baseline_ids_11)]
In [207]:
iter_base = baseline_i_sub.sort_values('unit_day', ascending=False).itertuples()
iter_stim = stimulated_11_sub.sort_values('unit_day', ascending=False).itertuples()
for row_base, row_stim in zip(iter_base, iter_stim):
    fields,_,_ = compute_field_spikes(row_base, plot=True)
    compute_field_spikes(row_stim, plot=True)#, surrogate_fields=fields)
/home/mikkel/.virtualenvs/expipe/lib/python3.6/site-packages/ipykernel_launcher.py:9: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  if __name__ == '__main__':
In [186]:
iter_base = baseline_i_sub.sort_values('unit_day', ascending=False).itertuples()
iter_stim = stimulated_11_sub.sort_values('unit_day', ascending=False).itertuples()
for row_base, row_stim in zip(iter_base, iter_stim):
    fields,_,_ = compute_field_spikes(row_base, plot=True)
    compute_field_spikes(row_stim, plot=True)#, surrogate_fields=fields)
/home/mikkel/.virtualenvs/expipe/lib/python3.6/site-packages/ipykernel_launcher.py:9: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  if __name__ == '__main__':

analysis stim vs stim

In [24]:
plt.rc('axes', titlesize=12)
plt.rcParams.update({
    'font.size': 12, 
    'figure.figsize': (5, 2), 
    'figure.dpi': 150
})

plot_stim_field_spikes(
    stimulated_11.sort_values('gridness', ascending=False).iloc[18],
    colors=['#2166ac', '#b2182b']#['#1b9e77','#d95f02']
)
fig = plt.gcf()
figname = 'stim_field_spikes_example'
fig.savefig(
    output_path / 'figures' / f'{figname}.png', 
    bbox_inches='tight', transparent=True)
fig.savefig(
    output_path / 'figures' / f'{figname}.svg', 
    bbox_inches='tight', transparent=True)
In [86]:
results_stim_stim_11 = []
z1_stim=5e-3
z2_stim=11e-3
z1_base=0
z2_base=5e-3
for row_stim in stimulated_11.itertuples():
    _, _, base_in_field = compute_field_spikes(
        row_stim, z1=z1_base, z2=z2_base)
    _, _, stim_in_field = compute_field_spikes(
        row_stim, z1=z1_stim, z2=z2_stim)
    
    results_stim_stim_11.append({
        'base_in_field': 1 - base_in_field.mean(),
        'stim_in_field': 1 - stim_in_field.mean(),
        'entity': row_stim.action.split('-')[0],
        'unit_idnum': row_stim.unit_idnum
    })
#     break
In [87]:
results_stim_stim_11 = pd.DataFrame(results_stim_stim_11)
results_stim_stim_11
Out[87]:
base_in_field stim_in_field entity unit_idnum
0 0.578947 0.588235 1833 13
1 0.520950 0.532093 1833 14
2 0.355422 0.388792 1833 32
3 0.519512 0.555294 1833 35
4 0.270492 0.342569 1833 47
5 0.266667 0.441860 1833 53
6 0.283505 0.316288 1833 55
7 0.434084 0.463719 1833 58
8 0.224852 0.297101 1833 59
9 0.548822 0.580769 1833 79
10 0.793205 0.788756 1833 89
11 0.583744 0.646545 1833 91
12 0.596752 0.638956 1833 96
13 0.362745 0.332192 1833 106
14 0.221698 0.196532 1833 108
15 0.380228 0.369403 1833 117
16 0.311111 0.359195 1833 121
17 0.558739 0.601518 1833 124
18 0.552529 0.629842 1833 128
19 0.486025 0.488651 1833 130
20 0.307018 0.353147 1833 134
21 0.549242 0.541608 1833 135
22 0.509740 0.584600 1833 144
23 0.646943 0.682283 1833 150
24 0.293333 0.336066 1833 168
25 0.589450 0.633227 1833 171
26 0.302857 0.409681 1833 202
27 0.449915 0.528596 1833 206
28 0.520548 0.631447 1833 231
29 0.552017 0.578132 1833 232
30 0.492248 0.606518 1833 233
31 0.421687 0.512640 1833 243
32 0.335135 0.407634 1833 244
33 0.191011 0.323232 1833 253
34 0.520000 0.604046 1833 254
35 0.000000 0.417722 1833 257
36 0.462209 0.550383 1833 301
37 0.516517 0.583713 1833 304
38 0.545261 0.652083 1834 329
39 0.662100 0.739712 1834 357
40 0.437500 0.699267 1834 358
41 0.304348 0.391960 1834 361
42 0.759146 0.797188 1834 364
43 0.492500 0.576505 1834 381
44 0.728571 0.741722 1834 482
45 0.758725 0.782228 1834 518
46 0.591232 0.682730 1839 611
47 0.709712 0.744382 1839 617
48 0.464286 0.582278 1839 629
49 0.622912 0.691063 1839 645
50 0.615038 0.678867 1839 655
51 0.225806 0.413793 1839 671
52 0.724315 0.770170 1849 684
53 0.620690 0.727273 1849 715
54 0.588158 0.623261 1849 724
55 0.669880 0.686826 1849 937
In [89]:
results_stim_stim_30 = []
z1_stim=5e-3
z2_stim=11e-3
z1_base=0
z2_base=5e-3
for row_stim in stimulated_30.itertuples():
    _, _, base_in_field = compute_field_spikes(
        row_stim, z1=z1_base, z2=z2_base)
    _, _, stim_in_field = compute_field_spikes(
        row_stim, z1=z1_stim, z2=z2_stim)
    
    results_stim_stim_30.append({
        'base_in_field': 1 - base_in_field.mean(),
        'stim_in_field': 1 - stim_in_field.mean(),
        'entity': row_stim.action.split('-')[0],
        'unit_idnum': row_stim.unit_idnum
    })
#     break
In [90]:
results_stim_stim_30 = pd.DataFrame(results_stim_stim_30)
results_stim_stim_30
Out[90]:
base_in_field stim_in_field entity unit_idnum
0 0.509735 0.528025 1833 13
1 0.522109 0.571429 1833 26
2 0.402010 0.466478 1833 31
3 0.329670 0.273570 1833 32
4 0.455128 0.426690 1833 35
5 0.535645 0.536465 1833 61
6 0.391549 0.433108 1833 63
7 0.421053 0.421569 1833 86
8 0.555556 0.599616 1833 149
9 0.292683 0.357735 1833 168
10 0.524590 0.655920 1833 195
11 0.484375 0.461538 1833 210
12 0.537879 0.569832 1833 218
13 0.187500 0.328277 1833 234
14 0.562500 0.560521 1833 240
15 0.540453 0.692541 1833 248
16 0.612903 0.649031 1833 249
17 0.188235 0.310062 1833 253
18 0.325301 0.510780 1833 260
19 0.685393 0.736201 1833 261
20 0.736328 0.723063 1833 263
21 0.602041 0.472362 1833 274
22 0.570312 0.699342 1833 275
23 0.565046 0.621489 1833 304
24 0.485961 0.522303 1834 332
25 0.574074 0.648464 1834 360
26 0.568627 0.543882 1834 381
27 0.444444 0.400000 1839 577
28 0.220588 0.321023 1839 629
29 0.525164 0.579110 1839 655
30 0.317073 0.383289 1839 656
31 0.640244 0.636975 1839 659
32 0.370968 0.378876 1839 660
33 0.687144 0.675090 1849 724
34 0.457364 0.553879 1849 835
In [91]:
results_stim_stim_all = pd.concat([results_stim_stim_11, results_stim_stim_30])
In [93]:
plt.rc('axes', titlesize=12)
plt.rcParams.update({
    'font.size': 12, 
    'figure.figsize': (1.7, 3), 
    'figure.dpi': 150
})

fig = plt.figure()
violinplot(
    results_stim_stim_all.base_in_field, 
    results_stim_stim_all.stim_in_field, 
    colors=None,
    draw_significance=False
)
figname = 'stim_field_spikes_combined'
fig.savefig(
    output_path / 'figures' / f'{figname}.png', 
    bbox_inches='tight', transparent=True)
fig.savefig(
    output_path / 'figures' / f'{figname}.svg', 
    bbox_inches='tight', transparent=True)

# 11
fig = plt.figure()
violinplot(
    results_stim_stim_11.base_in_field, 
    results_stim_stim_11.stim_in_field, 
    colors=['#1b9e77','#d95f02'],
    draw_significance=False
)
figname = 'stim_field_spikes_11'
fig.savefig(
    output_path / 'figures' / f'{figname}.png', 
    bbox_inches='tight', transparent=True)
fig.savefig(
    output_path / 'figures' / f'{figname}.svg', 
    bbox_inches='tight', transparent=True)
    
# 30
fig = plt.figure()
violinplot(
    results_stim_stim_30.base_in_field, 
    results_stim_stim_30.stim_in_field, 
    colors=['#7570b3', '#e7298a'],
    draw_significance=False
)
figname = 'stim_field_spikes_30'
fig.savefig(
    output_path / 'figures' / f'{figname}.png', 
    bbox_inches='tight', transparent=True)
fig.savefig(
    output_path / 'figures' / f'{figname}.svg', 
    bbox_inches='tight', transparent=True)
    
In [94]:
results_all = {
    'Combined':results_stim_stim_all,
    '11 Hz': results_stim_stim_11,
    '30 Hz': results_stim_stim_30
}
In [96]:
stat, _ = make_statistics_table(results_all, ['base_in_field', 'stim_in_field'])
In [97]:
stat.to_latex(output_path / "statistics" / "statistics.tex")
stat.to_csv(output_path / "statistics" / "statistics.csv")

analysis baseline stim

In [188]:
iter_base = baseline_i_sub.sort_values('unit_day', ascending=False).itertuples()
iter_stim = stimulated_11_sub.sort_values('unit_day', ascending=False).itertuples()
results = []
z1=5e-3
z2=11e-3
# z1=0
# z2=5e-3
for row_base, row_stim in zip(iter_base, iter_stim):
    base_fields, base_in_field, _ = compute_field_spikes(
        row_base, z1=z1, z2=z2)
    stim_fields, stim_in_field, stim_stim_in_field = compute_field_spikes(
        row_stim, z1=z1, z2=z2)
    results.append({
        'base_in_field': base_in_field.mean(),
        'stim_in_field': stim_in_field.mean(), 
        'stim_stim_in_field': stim_stim_in_field.mean(),
        'gridness_base': row_base.gridness,
        'gridness_stim': row_stim.gridness,
        'action_base': row_base.action,
        'action_stim': row_stim.action
    })
#     break
In [189]:
results = pd.DataFrame(results)
results
Out[189]:
base_in_field stim_in_field stim_stim_in_field gridness_base gridness_stim action_base action_stim
0 0.414166 0.428529 0.361044 0.339934 -0.045053 1833-010719-1 1833-010719-2
1 0.404667 0.477324 0.419231 0.401503 -0.179613 1833-260619-1 1833-260619-2
2 0.280399 0.384092 0.321133 0.557819 0.917221 1839-060619-1 1839-060619-3
3 0.815385 0.745888 0.657431 0.532037 0.397104 1833-010719-1 1833-010719-2
4 0.481623 0.399033 0.300733 0.282903 0.001879 1834-220319-1 1834-220319-2
5 0.734889 0.681776 0.611208 0.776775 0.869214 1833-260619-1 1833-260619-2
6 0.280964 0.449841 0.416287 0.317565 0.344708 1833-200619-1 1833-200619-2
7 0.739768 0.729892 0.676768 1.101447 0.976654 1833-200619-1 1833-200619-2
8 0.599141 0.549244 0.487360 0.215937 -0.201297 1833-260619-1 1833-260619-2
9 0.826862 0.732639 0.663934 0.855641 0.554912 1833-120619-1 1833-120619-2
10 0.477416 0.392704 0.317717 0.298222 -0.087079 1833-260619-1 1833-260619-2
11 0.560374 0.543610 0.511349 0.977155 -0.058795 1833-020719-1 1833-020719-2
12 0.858028 0.624060 0.640805 0.941494 0.342802 1833-010719-1 1833-010719-2
13 0.767867 0.687664 0.667808 0.487981 0.199693 1833-050619-1 1833-050619-2
In [115]:
 
In [139]:
plt.rc('axes', titlesize=12)
plt.rcParams.update({
    'font.size': 12, 
    'figure.figsize': (3.5, 3), 
    'figure.dpi': 150
})
In [142]:
fig, ax = plt.subplots(1,1)
sc = ax.scatter(
    results.base_in_field, results.stim_in_field,
    c=results.gridness_base
#     c=results.gridness_stim
)
ax.plot([0, 1], [0,1], 'k--')
plt.xlabel('Baseline percentage in field')
plt.ylabel('11 Hz percentage in field')
cb = plt.colorbar(mappable=sc, cax=None, ax=ax)
cb.ax.yaxis.set_ticks_position('right')
cb.set_label('Baseline gridness')

save to expipe

In [98]:
action = project.require_action("spikes-in-field")
In [99]:
copy_tree(output_path, str(action.data_path()))
Out[99]:
['/media/storage/expipe/septum-mec/actions/spikes-in-field/data/statistics/statistics.tex',
 '/media/storage/expipe/septum-mec/actions/spikes-in-field/data/statistics/statistics.csv',
 '/media/storage/expipe/septum-mec/actions/spikes-in-field/data/figures/stim_field_spikes_30.svg',
 '/media/storage/expipe/septum-mec/actions/spikes-in-field/data/figures/stim_field_spikes_example.svg',
 '/media/storage/expipe/septum-mec/actions/spikes-in-field/data/figures/stim_field_spikes_11.svg',
 '/media/storage/expipe/septum-mec/actions/spikes-in-field/data/figures/stim_field_spikes_example.png',
 '/media/storage/expipe/septum-mec/actions/spikes-in-field/data/figures/stim_field_spikes_combined.svg',
 '/media/storage/expipe/septum-mec/actions/spikes-in-field/data/figures/stim_field_spikes_combined.png',
 '/media/storage/expipe/septum-mec/actions/spikes-in-field/data/figures/stim_field_spikes_30.png',
 '/media/storage/expipe/septum-mec/actions/spikes-in-field/data/figures/stim_field_spikes_11.png']
In [100]:
septum_mec.analysis.registration.store_notebook(action, "20_spikes_in_field.ipynb")
In [ ]: