-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathfigure3cde_variability_over_labs_basic_&_suppfig3-2.py
203 lines (175 loc) · 8.76 KB
/
figure3cde_variability_over_labs_basic_&_suppfig3-2.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Quantify the variability of behavioral metrics within and between labs of mouse behavior.
This script doesn't perform any analysis but plots summary statistics over labs.
Guido Meijer
16 Jan 2020
"""
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
from os.path import join
import seaborn as sns
from paper_behavior_functions import (query_sessions_around_criterion, seaborn_style,
institution_map, group_colors, figpath, load_csv,
FIGURE_WIDTH, FIGURE_HEIGHT, QUERY,
dj2pandas, fit_psychfunc, num_star)
from ibl_pipeline import behavior, subject, reference
import scikit_posthocs as sp
from statsmodels.stats.multitest import multipletests
# Initialize
seaborn_style()
figpath = figpath()
pal = group_colors()
institution_map, col_names = institution_map()
col_names = col_names[:-1]
if QUERY is True:
use_sessions, _ = query_sessions_around_criterion(criterion='trained',
days_from_criterion=[2, 0])
session_keys = (use_sessions & 'task_protocol LIKE "%training%"').fetch('KEY')
ses = ((use_sessions & 'task_protocol LIKE "%training%"')
* subject.Subject * subject.SubjectLab * reference.Lab
* (behavior.TrialSet.Trial & session_keys))
ses = ses.proj('institution_short', 'subject_nickname', 'task_protocol', 'session_uuid',
'trial_stim_contrast_left', 'trial_stim_contrast_right',
'trial_response_choice', 'task_protocol', 'trial_stim_prob_left',
'trial_feedback_type', 'trial_response_time', 'trial_stim_on_time',
'session_end_time').fetch(
order_by='institution_short, subject_nickname,session_start_time, trial_id',
format='frame').reset_index()
behav = dj2pandas(ses)
behav['institution_code'] = behav.institution_short.map(institution_map)
else:
behav = load_csv('Fig3.csv', parse_dates=['session_start_time', 'session_end_time'])
# Create dataframe with behavioral metrics of all mice
learned = pd.DataFrame(columns=['mouse', 'lab', 'perf_easy', 'n_trials',
'threshold', 'bias', 'reaction_time',
'lapse_low', 'lapse_high', 'trials_per_minute'])
for i, nickname in enumerate(behav['subject_nickname'].unique()):
if np.mod(i+1, 10) == 0:
print('Processing data of subject %d of %d' % (i+1,
len(behav['subject_nickname'].unique())))
# Get the trials of the sessions around criterion for this subject
trials = behav[behav['subject_nickname'] == nickname]
trials = trials.reset_index()
# Fit a psychometric function to these trials and get fit results
fit_result = fit_psychfunc(trials)
# Get RT, performance and number of trials
reaction_time = trials['rt'].median()*1000
perf_easy = trials['correct_easy'].mean()*100
ntrials_perday = trials.groupby('session_uuid').count()['trial_id'].mean()
# average trials/minute to normalise by session length
trials['session_length'] = (trials.session_end_time - trials.session_start_time).astype('timedelta64[m]')
total_session_length = trials.groupby('session_uuid')['session_length'].mean().sum()
total_n_trials = trials['trial_id'].count()
# Add results to dataframe
learned.loc[i, 'mouse'] = nickname
learned.loc[i, 'lab'] = trials['institution_short'][0]
learned.loc[i, 'perf_easy'] = perf_easy
learned.loc[i, 'n_trials'] = ntrials_perday
learned.loc[i, 'reaction_time'] = reaction_time
learned.loc[i, 'trials_per_minute'] = total_n_trials / total_session_length
learned.loc[i, 'threshold'] = fit_result.loc[0, 'threshold']
learned.loc[i, 'bias'] = fit_result.loc[0, 'bias']
learned.loc[i, 'lapse_low'] = fit_result.loc[0, 'lapselow']
learned.loc[i, 'lapse_high'] = fit_result.loc[0, 'lapsehigh']
# Drop mice with faulty RT
learned = learned[learned['reaction_time'].notnull()]
# Change lab name into lab number
learned['lab_number'] = learned.lab.map(institution_map)
learned = learned.sort_values('lab_number')
# Convert to float
float_fields = ['perf_easy', 'reaction_time', 'threshold',
'n_trials', 'bias', 'lapse_low', 'lapse_high', 'trials_per_minute']
learned[float_fields] = learned[float_fields].astype(float)
# %% Stats
stats_tests = pd.DataFrame(columns=['variable', 'test_type', 'p_value'])
posthoc_tests = {}
for i, var in enumerate(['perf_easy', 'reaction_time', 'n_trials', 'threshold', 'bias', 'trials_per_minute']):
_, normal = stats.normaltest(learned[var])
if normal < 0.05:
test_type = 'kruskal'
test = stats.kruskal(*[group[var].values
for name, group in learned.groupby('lab_number')])
if test[1] < 0.05: # Proceed to posthocs
posthoc = sp.posthoc_dunn(learned, val_col=var, group_col='lab_number')
else:
posthoc = np.nan
else:
test_type = 'anova'
test = stats.f_oneway(*[group[var].values
for name, group in learned.groupby('lab_number')])
if test[1] < 0.05:
posthoc = sp.posthoc_tukey(learned, val_col=var, group_col='lab_number')
else:
posthoc = np.nan
# Test for difference in variance
_, p_var = stats.levene(*[group[var].values for name, group in learned.groupby('lab_number')])
posthoc_tests['posthoc_'+str(var)] = posthoc
stats_tests.loc[i, 'variable'] = var
stats_tests.loc[i, 'test_type'] = test_type
stats_tests.loc[i, 'p_value'] = test[1]
stats_tests.loc[i, 'p_value_variance'] = p_var
# Correct for multiple tests
stats_tests['p_value'] = multipletests(stats_tests['p_value'], method='fdr_bh')[1]
stats_tests['p_value_variance'] = multipletests(stats_tests['p_value_variance'],
method='fdr_bh')[1]
if (stats.normaltest(learned['n_trials'])[1] < 0.05 or
stats.normaltest(learned['reaction_time'])[1] < 0.05):
test_type = 'spearman'
correlation_coef, correlation_p = stats.spearmanr(learned['reaction_time'],
learned['n_trials'])
if (stats.normaltest(learned['n_trials'])[1] > 0.05 and
stats.normaltest(learned['reaction_time'])[1] > 0.05):
test_type = 'pearson'
correlation_coef, correlation_p = stats.pearsonr(learned['reaction_time'],
learned['n_trials'])
# Add all mice to dataframe seperately for plotting
learned_no_all = learned.copy()
learned_no_all.loc[learned_no_all.shape[0] + 1, 'lab_number'] = 'All'
learned_2 = learned.copy()
learned_2['lab_number'] = 'All'
learned_2 = learned.append(learned_2)
# %%
seaborn_style()
lab_colors = group_colors()
sns.set_palette(lab_colors)
# %%
vars = ['n_trials', 'perf_easy', 'threshold', 'bias', 'reaction_time', 'trials_per_minute']
ylabels =['Number of trials', 'Performance (%)\non easy trials',
'Contrast threshold (%)', 'Bias (%)', 'Trial duration (ms)', 'Trials / minute']
ylims = [[0, 1500],[70, 100], [0, 25], [-25, 25], [0, 1100], [0, 25]]
for v, ylab, ylim in zip(vars, ylabels, ylims):
f, ax = plt.subplots(1, 1, figsize=(FIGURE_WIDTH/5, FIGURE_HEIGHT))
sns.swarmplot(y=v, x='lab_number', data=learned_no_all, hue='lab_number',
palette=lab_colors, ax=ax, marker='.')
axbox = sns.boxplot(y=v, x='lab_number', data=learned_2, color='white',
showfliers=False, ax=ax)
ax.set(ylabel=ylab, ylim=ylim, xlabel='')
# [tick.set_color(lab_colors[i]) for i, tick in enumerate(ax5.get_xticklabels()[:-1])]
plt.setp(ax.xaxis.get_majorticklabels(), rotation=60)
axbox.artists[-1].set_edgecolor('black')
for j in range(5 * (len(axbox.artists) - 1), 5 * len(axbox.artists)):
axbox.lines[j].set_color('black')
ax.get_legend().set_visible(False)
# statistical annotation
pvalue = stats_tests.loc[stats_tests['variable'] == v, 'p_value']
if pvalue.to_numpy()[0] < 0.05:
ax.annotate(num_star(pvalue.to_numpy()[0]),
xy=[0.1, 0.8], xycoords='axes fraction', fontsize=5)
sns.despine(trim=True)
plt.tight_layout()
plt.savefig(join(figpath, 'figure3_metrics_%s.pdf'%v))
plt.savefig(join(figpath, 'figure3_metrics_%s.pdf'%v), dpi=300)
# %%
# Get stats for text
perf_mean = learned['perf_easy'].mean()
perf_std = learned['perf_easy'].std()
thres_mean = learned['threshold'].mean()
thres_std = learned['threshold'].std()
rt_median = learned['reaction_time'].median()
rt_std = learned['reaction_time'].std()
trials_mean = learned['n_trials'].mean()
trials_std = learned['n_trials'].std()