-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathannotation.py
More file actions
362 lines (298 loc) · 13 KB
/
Copy pathannotation.py
File metadata and controls
362 lines (298 loc) · 13 KB
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
355
356
357
358
359
360
361
362
"""
Tools for annotation of lick bouts
df_licks = annotate_licks(nwb)
df_licks = annotate_lick_bouts(nwb)
df_licks = annotate_rewards(nwb)
df_licks = annotate_cue_response(nwb)
df_licks = annotate_intertrial_choices(nwb)
df_licks = annotate_switches(nwb)
"""
import numpy as np
# Maximum time between a lick and a reward delivery to assign that reward to the lick
LICK_TO_REWARD_TOLERANCE = 0.25
# Maximum time between licks to label them as one bout
BOUT_THRESHOLD = 0.7
# Maximum time between go cue and first lick to label the lick as cue responsive
CUE_TO_LICK_TOLERANCE = 1
# Maximum time after the last go cue for a bout to start and be considered within the session
CUE_TO_SESSION_END_TOLERANCE = CUE_TO_LICK_TOLERANCE
# Minimum time between licks to be flagged as artifacts
ARTIFACT_TOLERANCE = 0.0001
def annotate_licks(nwb):
"""
Adds all annotations
nwb is an object that has df_events as an attribute
"""
if not hasattr(nwb, "df_events"):
print("You need to compute df_events: nwb_utils.create_df_events(nwb)")
return
nwb.df_licks = annotate_lick_bouts(nwb)
nwb.df_licks = annotate_artifacts(nwb)
nwb.df_licks = annotate_rewards(nwb)
nwb.df_licks = annotate_cue_response(nwb)
nwb.df_licks = annotate_intertrial_choices(nwb)
nwb.df_licks = annotate_switches(nwb)
nwb.df_licks = annotate_within_session(nwb)
return nwb.df_licks
def annotate_lick_bouts(nwb):
"""
returns a dataframe of lick times with annotations
pre_ili, the elapsed time since the last lick (on either side)
post_ili, the time until the next lick (on either side)
bout_start (bool), whether this was the start of a lick bout
bout_end (bool), whether this was the end of a lick bout)
bout_number (int), what lick bout this was a part of
nwb, an object with attributes: df_events
"""
if not hasattr(nwb, "df_events"):
print("You need to compute df_events: nwb_utils.create_df_events(nwb)")
return
df_licks = nwb.df_events.query('event in ["right_lick_time","left_lick_time"]').copy()
df_licks.reset_index(drop=True, inplace=True)
# Computing ILI for each lick
df_licks["pre_ili"] = np.concatenate([[np.nan], np.diff(df_licks.timestamps.values)])
df_licks["post_ili"] = np.concatenate([np.diff(df_licks.timestamps.values), [np.nan]])
# Assign licks into bouts
df_licks["bout_start"] = df_licks["pre_ili"] > BOUT_THRESHOLD
df_licks["bout_end"] = df_licks["post_ili"] > BOUT_THRESHOLD
df_licks.loc[df_licks["pre_ili"].isnull(), "bout_start"] = True
df_licks.loc[df_licks["post_ili"].isnull(), "bout_end"] = True
df_licks["bout_number"] = np.cumsum(df_licks["bout_start"])
# Check that bouts start and stop
num_bout_start = df_licks["bout_start"].sum()
num_bout_end = df_licks["bout_end"].sum()
num_bouts = df_licks["bout_number"].max()
assert num_bout_start == num_bout_end, "Bout Starts and Bout Ends don't align"
assert num_bout_start == num_bouts, "Number of bouts is incorrect"
return df_licks
def annotate_artifacts(nwb):
"""
annotates df_licks with which licks could be electrical artifacts
likely_artifact (bool) was this lick likely an artifact
nwb, an object with attributes: df_licks, df_events
"""
if not hasattr(nwb, "df_events"):
print("You need to compute df_events: nwb_utils.create_df_events(nwb)")
return
if not hasattr(nwb, "df_licks"):
print("annotating lick bouts")
nwb.df_licks = annotate_lick_bouts(nwb)
# make a copy of df licks
df_licks = nwb.df_licks.copy()
# Find lick intervals less than tolerance that also switch sides
# mark the second lick as a likely artifact
df_licks["switch_lick"] = df_licks["event"] != df_licks.shift(1)["event"]
df_licks.loc[0, "switch_lick"] = False
df_licks["likely_artifact"] = [
np.all(x) for x in zip(df_licks["switch_lick"], df_licks["pre_ili"] < ARTIFACT_TOLERANCE)
]
# Clean up temporary column
df_licks = df_licks.drop(columns=["switch_lick"])
return df_licks
def annotate_rewards(nwb):
"""
Annotates df_licks with which lick triggered each reward
rewarded (bool) did this lick trigger a reward
bout_rewarded (bool) did this lick bout trigger a reward
nwb, an object with attributes: df_licks, df_events
"""
if not hasattr(nwb, "df_events"):
print("You need to compute df_events: nwb_utils.create_df_events(nwb)")
return
# ensure we have df_licks
if not hasattr(nwb, "df_licks"):
print("annotating lick bouts")
nwb.df_licks = annotate_lick_bouts(nwb)
# make a copy of df licks
df_licks = nwb.df_licks.copy()
# set default to false
df_licks["rewarded"] = False
# Iterate right rewards, and find most recent lick within tolerance
right_rewards = nwb.df_events.query('event == "right_reward_delivery_time"').copy()
for index, row in right_rewards.iterrows():
this_reward_lick_times = np.where(
(df_licks.timestamps <= row.timestamps)
& (df_licks.timestamps > (row.timestamps - LICK_TO_REWARD_TOLERANCE))
& (df_licks.event == "right_lick_time")
)[0]
if len(this_reward_lick_times) > 0:
df_licks.at[this_reward_lick_times[-1], "rewarded"] = True
# TODO, if we can't find a matching lick, should ensure this is manual or auto water
# Iterate left rewards, and find most recent lick within tolerance
left_rewards = nwb.df_events.query('event == "left_reward_delivery_time"').copy()
for index, row in left_rewards.iterrows():
this_reward_lick_times = np.where(
(df_licks.timestamps <= row.timestamps)
& (df_licks.timestamps > (row.timestamps - LICK_TO_REWARD_TOLERANCE))
& (df_licks.event == "left_lick_time")
)[0]
if len(this_reward_lick_times) > 0:
df_licks.at[this_reward_lick_times[-1], "rewarded"] = True
# Annotate lick bouts as rewarded or unrewarded
x = (
df_licks.groupby("bout_number")
.any("rewarded")
.rename(columns={"rewarded": "bout_rewarded"})["bout_rewarded"]
)
df_licks["bout_rewarded"] = False
temp = df_licks.reset_index().set_index("bout_number").copy()
temp.update(x)
temp = temp.reset_index().set_index("index")
df_licks["bout_rewarded"] = temp["bout_rewarded"]
return df_licks
def annotate_cue_response(nwb):
"""
Annotates df_licks with which lick was immediately after a go cue
cue_response (bool) was this lick immediately after a go cue
bout_cue_response (bool) was this licking bout immediately after a go cue
nwb, an object with attributes: df_licks, df_events
"""
if not hasattr(nwb, "df_events"):
print("You need to compute df_events: nwb_utils.create_df_events(nwb)")
return
# ensure we have df_licks
if not hasattr(nwb, "df_licks"):
print("annotating lick bouts")
nwb.df_licks = annotate_lick_bouts(nwb)
# make a copy of df licks
df_licks = nwb.df_licks.copy()
# set default to false
df_licks["cue_response"] = False
# Iterate go cues, and find most recent lick within tolerance
cues = nwb.df_events.query('event == "goCue_start_time"').copy()
for index, row in cues.iterrows():
this_lick_times = np.where(
(df_licks.timestamps > row.timestamps)
& (df_licks.timestamps <= (row.timestamps + CUE_TO_LICK_TOLERANCE))
& ((df_licks.event == "right_lick_time") | (df_licks.event == "left_lick_time"))
& (df_licks.bout_start)
)[0]
if len(this_lick_times) > 0:
df_licks.at[this_lick_times[0], "cue_response"] = True
# Annotate lick bouts as cue_responsive, or unresponsive
x = (
df_licks.groupby("bout_number")
.any("cue_response")
.rename(columns={"cue_response": "bout_cue_response"})["bout_cue_response"]
)
df_licks["bout_cue_response"] = False
temp = df_licks.reset_index().set_index("bout_number").copy()
temp.update(x)
temp = temp.reset_index().set_index("index")
df_licks["bout_cue_response"] = temp["bout_cue_response"]
return df_licks
def annotate_intertrial_choices(nwb):
"""
annotate licks and lick bouts as intertrial choices if they are not cue_responsive
intertrial_choice (bool) was this lick the start of a non-cue-responsive bout
bout_intertrial_choice (bool) was this bout non-cue-responsive?
"""
# Add lick_bout annotation, and cue_response if not already added
if not hasattr(nwb, "df_events"):
print("You need to compute df_events: nwb_utils.create_df_events(nwb)")
return
if not hasattr(nwb, "df_licks"):
nwb.df_licks = annotate_lick_bouts(nwb)
if "cue_response" not in nwb.df_licks:
nwb.df_licks = annotate_cue_response(nwb)
# Make a copy
df_licks = nwb.df_licks.copy()
# Define intertrial choices
df_licks["intertrial_choice"] = df_licks["bout_start"] & ~df_licks["cue_response"]
# Annotate lick bouts as intertrial_choice
x = (
df_licks.groupby("bout_number")
.any("intertrial_choice")
.rename(columns={"intertrial_choice": "bout_intertrial_choice"})["bout_intertrial_choice"]
)
df_licks["bout_intertrial_choice"] = False
temp = df_licks.reset_index().set_index("bout_number").copy()
temp.update(x)
temp = temp.reset_index().set_index("index")
df_licks["bout_intertrial_choice"] = temp["bout_intertrial_choice"]
return df_licks
def annotate_switches(nwb):
"""
cue_switch: this cue_choice differs from the previous cue_choice
iti_switch: this intertrial_choice differs from the previous choice (iti or cue)
"""
# Add lick_bout annotation, and cue_response if not already added
if not hasattr(nwb, "df_events"):
print("You need to compute df_events: nwb_utils.create_df_events(nwb)")
return
if not hasattr(nwb, "df_licks"):
nwb.df_licks = annotate_lick_bouts(nwb)
if "cue_response" not in nwb.df_licks:
nwb.df_licks = annotate_cue_response(nwb)
if "intertrial_choice" not in nwb.df_licks:
nwb.df_licks = annotate_intertrial_choices(nwb)
# Make a copy
df_licks = nwb.df_licks.copy()
# Compute cue_switch labels
df_cue_bouts = df_licks.query("bout_start").query("cue_response").copy()
if len(df_cue_bouts) > 0:
df_cue_bouts["cue_switch"] = (
df_cue_bouts["event"].shift(1, fill_value=df_cue_bouts.iloc[0]["event"])
!= df_cue_bouts["event"]
)
else:
df_cue_bouts["cue_switch"] = []
# Compute iti_switch labels
df_bouts = df_licks.query("bout_start").copy()
df_bouts["iti_switch"] = df_bouts["intertrial_choice"] & (
df_bouts["event"].shift(1, fill_value=df_bouts.iloc[0]["event"]) != df_bouts["event"]
)
# Add columns to df_licks
df_licks = df_licks.join(df_cue_bouts["cue_switch"], how="left")
df_licks = df_licks.join(df_bouts["iti_switch"], how="left")
# Fill NaNs as False
df_licks["cue_switch"] = df_licks["cue_switch"] == True # noqa: E712
df_licks["iti_switch"] = df_licks["iti_switch"] == True # noqa: E712
# Annotate lick bouts as cue_switch
x = (
df_licks.groupby("bout_number")
.any("cue_switch")
.rename(columns={"cue_switch": "bout_cue_switch"})["bout_cue_switch"]
)
df_licks["bout_cue_switch"] = False
temp = df_licks.reset_index().set_index("bout_number").copy()
temp.update(x)
temp = temp.reset_index().set_index("index")
df_licks["bout_cue_switch"] = temp["bout_cue_switch"]
# Annotate lick bouts as iti_switch
x = (
df_licks.groupby("bout_number")
.any("iti_switch")
.rename(columns={"iti_switch": "bout_iti_switch"})["bout_iti_switch"]
)
df_licks["bout_iti_switch"] = False
temp = df_licks.reset_index().set_index("bout_number").copy()
temp.update(x)
temp = temp.reset_index().set_index("index")
df_licks["bout_iti_switch"] = temp["bout_iti_switch"]
return df_licks
def annotate_within_session(nwb):
"""
within_session: this lick happened after the first go cue,
or < CUE_TO_SESSION_END_TOLERANCE after the last go cue
"""
if not hasattr(nwb, "df_events"):
print("You need to compute df_events: nwb_utils.create_df_events(nwb)")
return
# ensure we have df_licks
if not hasattr(nwb, "df_licks"):
print("annotating lick bouts")
nwb.df_licks = annotate_lick_bouts(nwb)
# make a copy of df licks
df_licks = nwb.df_licks.copy()
# Test for no go cues
goCues = nwb.df_events.query('event == "goCue_start_time"')
if len(goCues) == 0:
df_licks["within_session"] = False
else:
start_time = goCues.iloc[0]["timestamps"]
end_time = goCues.iloc[-1]["timestamps"] + CUE_TO_SESSION_END_TOLERANCE
df_licks["within_session"] = (start_time <= df_licks["timestamps"]) & (
df_licks["timestamps"] < end_time
)
return df_licks