-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathplot_stats_gng.py
360 lines (262 loc) · 10.2 KB
/
plot_stats_gng.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
#plot_stats.py
from __future__ import division
import numpy as np
import pandas as pd
import os
import time
import sys
from bokeh.io import hplot, output_notebook, gridplot
from bokeh.client import push_session
from bokeh.driving import cosine
from bokeh.plotting import figure, curdoc, show
from bokeh.models import Span
from bokeh.charts import Bar
from bokeh.models import HoverTool, BoxSelectTool
TOOLS = [BoxSelectTool(), HoverTool()]
from scipy.stats import norm
def Z(x):
return norm.ppf(x)
usage = '''bokeh serve
plot_stats.py ID DATAPATH
'''
colors = {
'test' : 'dodgerblue',
'F2' : 'magenta',
'F3' : 'magenta',
}
def today():
import datetime
"""provides today's date as a string in the form YYMMDD"""
return datetime.date.today().strftime('%y%m%d')
df = pd.DataFrame([])
df_summary = pd.DataFrame([])
# ## 1. Read the data
ID = sys.argv[1]
bin = int(sys.argv[2])
if len(sys.argv) == 4:
DATAPATH = sys.argv[3]
else:
DATAPATH = '/'.join((r'R:\Andrew\161222_GOnoGO_Perception_III', today()))
infile = ['/'.join((DATAPATH,f)) for f in os.listdir(DATAPATH)
if ID in f
if f.endswith('.csv')][-1]
#first_loop = True
last_mod = 0
#STYLING -------------------------------------------------
# wining, living it up in the city,
total_line = {
'line_color' : colors[ID],
#'line_dash' : [4,2],
'line_width' : 2,
}
total_marker = {
'fill_color' : 'white',
'line_color' : colors[ID],
'line_width' : 2,
'size' : 7.5,
}
# --------------------------------------------------------
def read_data(df = pd.DataFrame([])):
try:
if df.empty:
df = pd.read_csv(infile)
else:
last_line = df['Unnamed: 0'].values[-1]
df = df.append(pd.read_csv(infile,
names = df.columns,
skiprows = last_line))
if df['Unnamed: 0'].values[-1] == last_line:
return df, False
df = df.drop_duplicates()
df = df.dropna(subset = ['t_stimDUR'])
df.minlickCount = df.minlickCount.fillna(method = 'ffill')
#df = df[df.minlickCount > 0]
#df.loc[df.t_stimDUR == 100, 'trialType'] = 'G'
#df.loc[df.t_stimDUR != 100, 'trialType'] = 'N'
if 'time' in df.columns:
df = df.drop_duplicates(subset = 'time')
date = infile.split('/')[3]
animal = infile.split('/')[4]
df['trial_num'] = np.arange(0, df.shape[0])
return df, True
except:
return df, False
def update():
global df
global last_mod
global changed
mod_time = time.ctime(os.path.getmtime(infile))
if (mod_time > last_mod):
last_mod = mod_time
print mod_time, '\r',
else:
#print last_mod, '\r',
time.sleep(1)
return
df, changed = read_data(df)
###############################################################################
was_operant = (df.minlickCount < 1).values
did_respond = (df['delta'] >= df.minlickCount).values
was_go_trial = (df.trialType == 'G').values
was_nogo_trial = (df.trialType == 'N').values
reward = df.Water.astype(bool)
hit = was_go_trial & did_respond
miss = was_go_trial & ~did_respond
FA = did_respond & was_nogo_trial
CR = ~did_respond & was_nogo_trial
N = { 'go' : was_go_trial.cumsum(),
'no go': was_nogo_trial.cumsum(),
}
p_hit_go = hit.cumsum() / N['go']
p_miss_go = miss.cumsum() / N['go']
p_FA_ngo = FA.cumsum() / N['no go']
p_CR_ngo = CR.cumsum() / N['no go']
p_hit_go[p_hit_go == 0] = 1 / (2*N['go'][p_hit_go == 0])
p_hit_go[p_hit_go == 1] = 1 - ( 1 / (2*N['go'][p_hit_go == 1]))
p_FA_ngo[p_FA_ngo == 0] = 1 / (2*N['no go'][p_FA_ngo == 0])
p_FA_ngo[p_FA_ngo == 1] = 1 - ( 1 / (2*N['no go'][p_FA_ngo == 1]))
d_prime = [Z(phit) - Z(pFA) for phit, pFA in zip(p_hit_go, p_FA_ngo)]
d_prime = np.array(d_prime)
correct = hit | CR
wrong = miss | FA
trial = np.arange(df.shape[0])
p_reward = pd.rolling_mean(reward, bin)
p_response = pd.rolling_mean(did_respond, bin)
p_correct = pd.rolling_mean(correct, bin)
d_prime_col = 'limegreen'# if d else 'red' for d in (d_prime>1.5)]
###############################################################################
#Rendering of the lines ---------------------------------------
p1_DPRIME['tot'].data_source.data = {'x' : trial[::bin], 'y' : d_prime}
p1_DPRIME['marker'].data_source.data = {'x' : trial[::bin], 'y' : d_prime,
'fill_color':d_prime_col,
'line_color':d_prime_col,
}
p2_CORRECT['tot'].data_source.data = {'x': trial, 'y': p_correct}
p2_CORRECT['marker'].data_source.data = {'x' : trial[::bin], 'y' : p_correct[::bin]}
p3_REWARD['tot'].data_source.data = {'x': trial, 'y' : p_response}
p3_REWARD['marker'].data_source.data = {'x': trial[::bin], 'y' : p_response[::bin]}
p4_CUMREWARD['tot'].data_source.data = {'x': trial, 'y' : reward.cumsum() * 10}
p4_CUMREWARD['marker'].data_source.data = {'x': trial[::bin], 'y' : reward.cumsum()[::bin] * 10}
p5_HITS['tot'].data_source.data = {'x': trial, 'y' : p_hit_go}
p5_HITS['marker'].data_source.data = {'x': trial[::bin], 'y' : p_hit_go[::bin]}
p6_FALSEALARMS['tot'].data_source.data = {'x': trial, 'y' : p_FA_ngo}
p6_FALSEALARMS['marker'].data_source.data = {'x': trial[::bin], 'y' : p_FA_ngo[::bin]}
print ' updated:', mod_time, '\r',
#import pdb; pdb.set_trace()
##generate_plots## ===========================================================#
#=============================================================================#
## static lines ##
dprime_cutoff = Span(location = 1.5, dimension = 'width',
line_dash = [1,1],
line_color = 'firebrick',
line_width = 4
)
water_target = Span(location = 1000, dimension = 'width')
##plot 1
# signal detection
p1 = figure(title='signal detection',
height = 200,
width = 400,
y_range = (-2, 2.0),
x_axis_label = 'trial (%d bins)' %bin,
y_axis_label = 'd`',
)
##plot 2
p2 = figure(title="fraction 'correct'",
height = 200,
width = 400,
y_range= (-.05, 1.05),
x_range = p1.x_range,
x_axis_label = 'trial (%d bins)' %bin,
y_axis_label = 'fraction',
#tools=TOOLS,
)
p3 = figure(title="fraction Responded",
height = 200,
width = 400,
y_range=(-.05,1.05),
x_range = p1.x_range,
x_axis_label = 'trial (%d bins)' %bin,
y_axis_label = 'fraction',
#tools=TOOLS,
)
p4 = figure(title="Cumulative Reward",
height = 200,
width = 400,
x_range = p1.x_range,
y_range=(-.05, 1500),
x_axis_label = 'trial (%d bins)' %bin,
y_axis_label = 'uL',
# tools=TOOLS,
)
p5 = figure(title="Hit ratio",
height = 200,
width = 400,
x_range = p1.x_range,
y_range = (0.05, 1.05),
x_axis_label = 'trial (%d bins)' %bin,
y_axis_label = 'fraction',
# tools=TOOLS,
)
p6 = figure(title="False Alarm ratio",
height = 200,
width = 400,
x_range = p1.x_range,
y_range = (0.05, 1.05),
x_axis_label = 'trial (%d bins)' %bin,
y_axis_label = 'fraction',
#tools=TOOLS,
)
p1.renderers.extend([dprime_cutoff])
p4.renderers.extend([water_target])
p4.add_tools(HoverTool())
p = gridplot([[p1, p2],
[p3, p4],
[p5, p6]],
#tools=TOOLS,
)
#-----------------------------------------------------------------------------#
#=============================================================================#
#Initialisation of the lines ---------------------------------------
p1_DPRIME = {
'tot' : p1.line([0,0], [0,0],
line_color = 'red',
line_dash = [4,4]
),
'marker' : p1.circle(x = [], y = [],
fill_color = [],
line_color = [],
size = 10,
),
}
p2_CORRECT = {
'tot' : p2.line([0,0], [0,0], **total_line),
'marker' : p2.circle([0,0], [0,0], **total_marker),
}
p3_REWARD = {
'tot' : p3.line([0,0], [0,0], **total_line),
'marker' : p3.circle([0,0], [0,0], **total_marker),
}
p4_CUMREWARD = {
'tot' : p4.line([0,0], [0,0], **total_line),
'marker' : p4.circle([0,0], [0,0], **total_marker),
}
p5_HITS = {
'tot' : p5.line([0,0], [0,0], **total_line),
'marker' : p5.circle([0,0], [0,0], **total_marker),
}
p6_FALSEALARMS = {
'tot' : p6.line([0,0], [0,0], **total_line),
'marker' : p6.circle([0,0], [0,0], **total_marker),
}
#first_loop = False
###############################################################################
df, changed = read_data(df)
update()
###############################################################################
#-----------------------------------------------------------------#
# open a session to keep our local document in sync with server
session = push_session(curdoc())
curdoc().add_periodic_callback(update, 10000)
session.show() # open the document in a browser
session.loop_until_closed() # run forever