-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSocial_Dataset_Class_v2.py
executable file
·2413 lines (2018 loc) · 108 KB
/
Social_Dataset_Class_v2.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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'''
Second pass at the social dataset class, reorganizing code for readability and
improved ui. Importantly, we want to package in filtering operations so that they
are only run once, and in the appropriate order.
'''
## Review the packages that should be included:
import os
import sys
import pdb
from tqdm import tqdm
import numpy as np
from scipy.interpolate import interp1d
from scipy.signal import savgol_filter
from scipy.ndimage import rotate
from scipy.ndimage.morphology import binary_dilation
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from skimage.util import img_as_ubyte
import moviepy
from moviepy.editor import VideoClip,VideoFileClip
from moviepy.video.io.bindings import mplfig_to_npimage
import tensorflow as tf
from collections import deque
from training_data.Training_Data_Class import training_dataset
'''
Some helper functions, to make geometric transformations, tensorflow dataset creation,
indexing, index transformations, and interpolations
'''
### Geometry helper functions
def unit_vector(vector):
""" Returns the unit vector of the vector. """
return vector / np.linalg.norm(vector)
def unit_vector_vec(vectorvec):
return vectorvec / np.linalg.norm(vectorvec,axis = 1,keepdims=True)
def angle_between(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
v1_u = unit_vector(v1)
v2_u = unit_vector(v2)
return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
def angle_between_vec(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
>>> angle_between((1, 0, 0), (0, 1, 0))
1.5707963267948966
>>> angle_between((1, 0, 0), (1, 0, 0))
0.0
>>> angle_between((1, 0, 0), (-1, 0, 0))
3.141592653589793
"""
v1_u = unit_vector_vec(v1)
v2_u = unit_vector_vec(v2)
dotted = np.einsum('ik,ik->i', v1_u, v2_u)
return np.arccos(np.clip(dotted, -1.0, 1.0))
def within_bb(points,bounds):
"""
Checks if the given point is within the given bounds. Written in 2-d.
Inputs:
points (array): A (-1,2) shaped array that gives the point to be queried.
bounds (dict): A four element dictionary with keys xn0, xn1, yn0, yn1 that give the bounding box for the nest.
"""
assert len(points.shape) == 2, "Accepts 2d arrays right now."
assert points.shape[1] == 2, "Accepts 2d data right now."
xcheck = np.logical_and(bounds["xn0"]<points[:,0],points[:,0]<bounds["xn1"])
ycheck = np.logical_and(bounds["yn0"]<points[:,1],points[:,1]<bounds["yn1"])
return np.logical_and(xcheck,ycheck)
#xcheck = (out[:,0]<self.bounds[0])
#ycheck = (out[:,1]<self.bounds[1])
## Tensorflow Data API helper functions:
## Designate helper function to define features for examples more easily
def _int64_feature_(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature_(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _float_feature_(value):
return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))
def _write_ex_animal_focused(videoname,i,image,mouse,pos):
features = {'video': _bytes_feature_(tf.compat.as_bytes((videoname))),
'frame': _int64_feature_(i),
'image': _bytes_feature_(tf.compat.as_bytes(image.tobytes())),
'mouse': _int64_feature_(mouse),
'position':_bytes_feature_(tf.compat.as_bytes(pos.tobytes()))
}
example = tf.train.Example(features = tf.train.Features(feature = features))
return example
## indexing helper functions:
def sorter(index,bp = 5,cent_ind = 3):
# return the center index and other body part indices given a mouse index
center = index*bp+3
all_body = np.arange(bp)+index*bp
rel = list(all_body)
rel.pop(cent_ind)
return center,rel
## helper function for segmentation:
def find_segments(indices):
differences = np.diff(indices)
all_intervals = []
## Initialize with the first element added:
interval = []
interval.append(indices[0])
for i,diff in enumerate(differences):
if diff == 1:
pass # interval not yet over
else:
# last interval ended
if interval[0] == indices[i]:
interval.append(indices[i]+1)
else:
interval.append(indices[i])
all_intervals.append(interval)
# start new interval
interval = [indices[i+1]]
if i == len(differences)-1:
interval.append(indices[-1]+1)
all_intervals.append(interval)
return all_intervals
## Helper function to return a segment given relevant information. Handles corner cases:
def segment_getter(trajectories,segs,segind,mouseind):
## If segind is negative, return the first element of the trajectory:
if segind <0:
segment = trajectories[mouseind][0:1,:]
return segment
else:
segbounds = segs[mouseind][segind]
segment = trajectories[mouseind][segbounds[0]:segbounds[1]]
return segment
def interpolate_isnans(trajectories,out_array):
vgood,mgood = np.where(~np.isnan(out_array[:,0:1]))[0],np.where(~np.isnan(out_array[:,1:2]))[0]
good_valsv,good_valsm = trajectories[0][vgood,:],trajectories[1][mgood,:]
vinterp = interp1d(vgood,good_valsv,axis = 0,bounds_error = False,fill_value = 'extrapolate',kind = 'slinear')
minterp = interp1d(mgood,good_valsm,axis = 0,bounds_error = False,fill_value = 'extrapolate',kind = 'slinear')
return vinterp,minterp
class social_dataset(object):
"""
Main dataset class to handle the outputs of deeplabcut. Takes as input an h5 file that contains the raw tracking output from deeplabcut. Has three main inds of functionality:
1) Data filtering. Implements a variety of filters to improve the quality of tracked output. This should eventually be refactored into its own object, and called internally to simplify things.
2) Data analysis. Tools to analyze the structure of the data, largely kinematics, ethograms
3) Data visualization. Tools to visualize the underlying data and make sense of what is going on.
Inputs:
filepath (str): path to the h5 file used in this analysis.
vers (int): optional: the dataframe structure to expect.
"""
def __init__(self,filepath,vers = 1):
self.dataset = pd.read_hdf(filepath)
self.dataset_name = filepath.split('/')[-1]
self.scorer = 'DeepCut' + filepath.split('DeepCut')[-1].split('.h5')[0]
self.part_list = ['vtip','vlear','vrear','vcent','vtail','mtip','mlear','mrear','mcent','mtail']
self.part_index = np.arange(len(self.part_list))
self.part_dict = {index:self.part_list[index] for index in range(len(self.part_list))}
self.time_index = np.arange(self.dataset.shape[0])
self.allowed_index = [self.time_index[:,np.newaxis] for _ in self.part_list] ## set of good indices for each part!
self.allowed_index_full = [self.simple_index_maker(part,self.allowed_index[part]) for part in self.part_index]
self.filter_check_counts = [[] for i in self.part_index]
self.vers = vers ## with multiple animal index or not
# Import the relevant movie file
def import_movie(self,moviepath):
self.movie = VideoFileClip(moviepath)
# self.movie.reader.initialize()
# Helper function: index maker. Takes naive index constructs and returns a workable set of indices for the dataset.
def simple_index_maker(self,pindex,allowed):
length_allowed = len(allowed)
# First compute the part index as appropriate:
part = np.array([[pindex]]).repeat(length_allowed,axis = 0)
full_index = np.concatenate((allowed,part),axis = 1)
return full_index
# Trajectory selector:
def select_trajectory(self,pindex):
part_name = self.part_dict[pindex]
part_okindex = self.allowed_index[pindex]
if self.vers == 0:
rawtrajectory = self.dataset[self.scorer][part_name]['0'].values[:,:2]
else:
rawtrajectory = self.dataset[self.scorer][part_name].values[:,:2]
return rawtrajectory
# if a trajectory could be influenced by other trajectories:
def render_trajectory_full(self,pindex):
rawtrajectories = self.dataset[self.scorer].values
part_okindex = self.allowed_index_full[pindex]
time = part_okindex[:,0:1]
x = part_okindex[:,1:2]*3
y = part_okindex[:,1:2]*3+1
coords = np.concatenate((x,y),axis = 1)
out = rawtrajectories[time,coords]
filtered_x,filtered_y = np.interp(self.time_index,part_okindex[:,0],out[:,0]),np.interp(self.time_index,part_okindex[:,0],out[:,1])
filtered_part = np.concatenate((filtered_x[:,np.newaxis],filtered_y[:,np.newaxis]),axis = 1)
return filtered_part
# render the trajectory with nans:
def render_trajectory_full(self,pindex):
rawtrajectories = self.dataset[self.scorer].values
part_okindex = self.allowed_index_full[pindex]
time = part_okindex[:,0:1]
x = part_okindex[:,1:2]*3
y = part_okindex[:,1:2]*3+1
coords = np.concatenate((x,y),axis = 1)
out = rawtrajectories[time,coords]
filtered_x,filtered_y = np.interp(self.time_index,part_okindex[:,0],out[:,0]),np.interp(self.time_index,part_okindex[:,0],out[:,1])
filtered_part = np.concatenate((filtered_x[:,np.newaxis],filtered_y[:,np.newaxis]),axis = 1)
return filtered_part
def render_trajectory_valid(self,pindex):
rawtrajectories = self.dataset[self.scorer].values
part_okindex = self.allowed_index_full[pindex]
time = part_okindex[:,0:1]
x = part_okindex[:,1:2]*3
y = part_okindex[:,1:2]*3+1
coords = np.concatenate((x,y),axis = 1)
out = rawtrajectories[time,coords]
return out,time
# For multiple trajectories:
def render_trajectories(self,to_render = None):
if to_render == None:
to_render = self.part_index
part_trajectories = []
for pindex in to_render:
part_traj = self.render_trajectory_full(pindex)
part_trajectories.append(part_traj)
return(part_trajectories)
# Now define a plotting function:
# Also plot a tracked frame on an image:
def plot_image(self,part_numbers,frame_nb):
allowed_indices = [frame_nb in self.allowed_index_full[part_number][:,0] for part_number in part_numbers]
colors = ['red','blue']
point_colors = [colors[allowed] for allowed in allowed_indices]
relevant_trajectories = self.render_trajectories(to_render = part_numbers)
print(relevant_trajectories[0].shape)
relevant_points = [traj[frame_nb,:] for traj in relevant_trajectories]
relevant_points = np.array(relevant_points)
assert np.all(np.shape(relevant_points) == (len(part_numbers),2))
print(self.movie.duration,self.movie.fps)
# Now load in video:
try:
frame = self.movie.get_frame(frame_nb/self.movie.fps)
fig,ax = plt.subplots()
ax.imshow(frame)
ax.axis('off')
ax.scatter(relevant_points[:,0],relevant_points[:,1],c = point_colors)
plt.show()
except OSError as error:
print(error)
# Plot a tracked frame on an image, with raw trackings for comparison:
def plot_image_compare(self,part_numbers,frame_nb,xlims = [0,-1],ylims = [0,-1],internal = False,figureparams = None):
print(frame_nb)
allowed_indices = [frame_nb in self.allowed_index_full[part_number][:,0] for part_number in part_numbers]
colors = ['blue','red']
shapes = ['o','v']
colorsequence = [colors[i >= 5] for i in part_numbers]
point_colors = [colors[allowed] for allowed in allowed_indices]
relevant_trajectories = self.render_trajectories(to_render = part_numbers)
relevant_points = [traj[frame_nb,:] for traj in relevant_trajectories]
relevant_points = np.array(relevant_points)
rawtrajectories = self.dataset[self.scorer].values[frame_nb,:]
a = rawtrajectories.reshape(10,3)
relevant_raw = np.array([part[:2] for i, part in enumerate(a) if i in part_numbers])
assert np.all(np.shape(relevant_points) == (len(part_numbers),2))
assert np.all(np.shape(relevant_raw) == (len(part_numbers),2))
# Now load in video:
try:
frame = self.movie.get_frame(frame_nb/self.movie.fps)
if figureparams is None:
fig,ax = plt.subplots()
else:
fig,ax = figureparams[0],figureparams[1]
shape = np.array(np.shape(frame[xlims[0]:xlims[1],ylims[0]:ylims[1]]))[:2].reshape((1,2))
ax.imshow(frame[xlims[0]:xlims[1],ylims[0]:ylims[1]])
ax.axis('off')
relevant_points[relevant_points == 0] += 1
relevant_points = np.minimum(relevant_points,shape-1)
ax.scatter(relevant_points[:,0],relevant_points[:,1]-xlims[0],c = colorsequence,marker = shapes[0],s = 100)
# ax.scatter(relevant_raw[:,0],relevant_raw[:,1]-xlims[0],c = colorsequence,marker = shapes[1])
if figureparams is not None:
return fig,ax
else:
if internal == False:
plt.show()
else:
return mplfig_to_npimage(fig)
except AttributeError as error:
print(error,' Plotting frames without video')
if figureparams is None:
fig,ax = plt.subplots()
else:
fig,ax = figureparams[0],figureparams[1]
ax.set_xlim([0,630-330])
ax.set_ylim([480-70,0])
ax.set_aspect('equal')
ax.scatter(relevant_points[:,0],relevant_points[:,1],c = colorsequence,marker = shapes[0])
ax.scatter(relevant_raw[:,0],relevant_raw[:,1],c = colorsequence,marker = shapes[1])
if figureparams is not None:
return fig,ax
else:
if internal == False:
plt.show()
else:
return mplfig_to_npimage(fig)
# Plot a tracked frame on an image, with raw trackings for comparison:
def plot_clip_compare(self,part_numbers,frame_sequence,fps):
## See how many frames we should worry about:
length = len(frame_sequence)
duration = length/fps
## Make function to pass to clipwriter:
framemaker = lambda t: self.plot_image_compare(part_numbers,frame_sequence[int(t*fps)],internal = True)
animation = VideoClip(framemaker,duration = duration)
return animation
def plot_clip_with_ethogram(self,part_numbers,interval,fps,title):
length = len(interval)
duration = length/fps
## Pull the ethogram we will use:
vetho = self.nest_ethogram(0)
detho = self.nest_ethogram(1)
petho = self.shepherding_ethogram()
ethox = np.arange(len(vetho))
fig = plt.figure(figsize = (15,10))
ax0 = plt.subplot2grid((5, 4), (0, 0), rowspan=5,colspan = 2)
ax1 = plt.subplot2grid((5, 4), (1, 2), colspan = 2)
ax2 = plt.subplot2grid((5, 4), (3, 2), colspan = 2)
ax = [ax0,ax1,ax2]
ax[1].plot(vetho,color ='blue',label = 'nest')
ax[2].plot(detho,color = 'red',label = 'nest')
ax[1].fill_between(ethox,0,vetho,color = 'blue')
ax[2].fill_between(ethox,0,detho,color = 'red')
ax[1].set_title('Virgin Ethogram')
ax[2].set_title('Dam Ethogram')
[ax[i].plot(petho,color = 'orange',label = 'pursuit') for i in [1,2]]
[ax[i].legend() for i in [1,2]]
## define a small function we will call as a lambda function:
def framemaker(t,vetho,detho,petho):
index = int(t*fps)
ax[0].clear()
fig0,ax0 = self.plot_image_compare(part_numbers,interval[index],figureparams=(fig,ax[0]))
## Plot markers based on ethogram too:
if vetho[interval[index]] or detho[interval[index]] or petho[interval[index]]:
ax0.tick_params(
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
left = False,
labelbottom=False,
labelleft=False) # labels along the bottom edge are off
ax0.axis('on')
if vetho[interval[index]]:
ax0.spines['left'].set_linewidth(2)
ax0.spines['left'].set_color('blue')
if detho[interval[index]]:
ax0.spines['right'].set_linewidth(2)
ax0.spines['right'].set_color('red')
if petho[interval[index]]:
ax0.scatter(270,15,color = 'orange',marker = 'o',s = 100)
ax[1].axvline(x = interval[index],color = 'black',alpha = 0.5)
ax[2].axvline(x = interval[index],color = 'black',alpha = 0.5)
return mplfig_to_npimage(fig)
make_frame = lambda t:framemaker(t,vetho,detho,petho)
clip = VideoClip(make_frame,duration=duration)
clip.write_videofile(title,fps = fps)
def plot_trajectory(self,part_numbers,start = 0,end = -1,cropx = 0,cropy = 0,axes = True,save = False,**kwargs):
"""
Inputs:
part_numbers:(list) a list of the part numbers that you want to plot. 0-4 are virgin, 5-9 are dam. Order is snout, left ear, right ear, centroid, tailbase.
"""
# First define the relevant part indices:
relevant_trajectories = self.render_trajectories(to_render = part_numbers)
names = ['Virgin','Dam']
mouse_id = part_numbers[0]//5
if axes == True:
fig,axes = plt.subplots()
for part_nb,trajectory in enumerate(relevant_trajectories):
axes.plot(trajectory[start:end,0],-trajectory[start:end,1],label = self.part_list[part_numbers[part_nb]],**kwargs)
axes.axis('equal')
plt.legend()
print(mouse_id)
plt.title(names[int(mouse_id)]+' Trajectories')
# plt.yticks(0,[])
# plt.xticks(0,[])
plt.show()
#plt.close()
if save != False:
plt.savefig(save)
else:
for part_nb,trajectory in enumerate(relevant_trajectories):
axes.plot(trajectory[start:end,0]-cropx,trajectory[start:end,1]-cropy,label = self.part_list[part_numbers[part_nb]],**kwargs)
## Closely related to the plotting function is the gif rendering function for trajectories:
def gif_trajectory(self,part_numbers,start = 0,end = -1,fps = 60.,cropx = 0,cropy = 0,save = False,**kwargs):
# First define the relevant part indices:
relevant_trajectories = self.render_trajectories(to_render = part_numbers)
names = ['Virgin','Dam']
mouse_id = part_numbers[0]/5
if end == -1:
duration = relevant_trajectories.shape[0]-start
else:
duration = end - start
clipduration = duration/fps
fig,axes = plt.subplots()
print(relevant_trajectories[0][start:start+2+int(5*fps),0].shape)
## Define a frame making function to pass to moviepy:
def gif_trajectory_mini(t):
axes.clear()
for part_nb,trajectory in enumerate(relevant_trajectories):
axes.plot(trajectory[start:start+2+int(t*fps),0],-trajectory[start:start+2+int(t*fps),1],label = self.part_list[part_numbers[part_nb]],**kwargs)
axes.plot(trajectory[start+int(t*fps),0],-trajectory[start+int(t*fps),1],'o',markersize = 3,label = self.part_list[part_numbers[part_nb]],**kwargs)
axes.axis('equal')
return mplfig_to_npimage(fig)
animation = VideoClip(gif_trajectory_mini,duration = clipduration)
# animation.ipython_display(fps=60., loop=True, autoplay=True)
return animation
####### Quantifying errors:
## Look at a patch of the underlying image:
def make_patches(self,frames,part,radius):
points = self.render_trajectory_full(part)[frames,:]
xcents,ycents = points[:,0],points[:,1]
xsize,ysize = self.movie.size
all_clipped = np.zeros((len(frames),2*radius,2*radius,3)).astype(np.uint8)
for i,frame in enumerate(frames):
image = self.movie.get_frame((frame)/self.movie.fps)
xcent,ycent = xcents[i],ycents[i]
xmin,xmax,ymin,ymax = int(xcent-radius),int(xcent+radius),int(ycent-radius),int(ycent+radius)
## do edge detection:
pads = np.array([[ymin - 0,ysize - ymax],[xmin - 0,xsize - xmax],[0,0]])
clip = image[ymin:ymax,xmin:xmax]
# print(clip,'makedocip')
if np.any(pads < 0):
topad = pads<0
padding = -1*pads*topad
clip = np.pad(clip,padding,'edge')
all_clipped[i,:,:,:] = clip.astype(np.uint8)
return all_clipped
def patch_grandhist(self,frames,part,radius):
dataarray = self.make_patches(frames,part,radius)
hists = [np.histogram(dataarray[:,:,:,i],bins = np.linspace(0,255,256)) for i in range(3)]
return hists
def patch_hist(self,frames,part,radius):
dataarray = self.make_patches(frames,part,radius)
hists = [[np.histogram(dataarray[f,:,:,i],bins = np.linspace(0,255,256)) for i in range(3)]for f in range(len(frames))]
return hists
# def patch_outliers
#######
def calculate_speed(self,pindex):
rawtrajectory = self.select_trajectory(pindex)
diff = np.diff(rawtrajectory,axis = 0)
speed = np.linalg.norm(diff,axis = 1)
return speed
def motion_detector(self,threshold = 80):
## We will assume the trajectories are raw.
indices = np.array([0,1,2,3,4])
mouse_moving = np.zeros((2,))
for mouse in range(2):
mouseindices = indices+5*mouse
trajectories = np.concatenate(self.render_trajectories(list(indices)),axis = 1)
maxes = np.max(trajectories,axis = 0)
mins = np.min(trajectories,axis = 0)
differences = maxes-mins
partwise_diffs = differences.reshape(5,2)
normed = np.linalg.norm(partwise_diffs,axis = 1)
## See if any of the body parts left
if np.any(normed <threshold):
mouse_moving[mouse] = 0
else:
mouse_moving[mouse] = 1
return mouse_moving,normed
# Now we define filtering functions:
# Filter by average speed
def filter_speed(self,pindex,threshold = 10):
rawtrajectory = self.select_trajectory(pindex)
diff = np.diff(rawtrajectory,axis = 0)
speed = np.linalg.norm(diff,axis = 1)
filterlength = 9
filterw = np.array([1.0 for i in range(filterlength)])/filterlength
filtered = np.convolve(speed,filterw,'valid')
# virg_outs = np.where(filtered > 10)[0]
outliers = np.where(filtered>threshold)[0]
okay_indices = np.array([index for index in self.allowed_index_full[pindex] if index[0] not in outliers])
self.allowed_index_full[pindex] = self.simple_index_maker(pindex,okay_indices[:,0:1])
# Filter by likelihood
def filter_likelihood(self,pindex):
part_name = self.part_dict[pindex]
part_okindex = self.allowed_index_full[pindex]
if self.vers == 0:
likelihood = self.dataset[self.scorer][part_name]['0'].values[:,2]
else:
likelihood = self.dataset[self.scorer][part_name].values[:,2]
outliers = np.where(likelihood<0.95)[0]
okay_indices = np.array([index for index in self.allowed_index_full[pindex] if index[0] not in outliers])
self.allowed_index_full[pindex] = self.simple_index_maker(pindex,okay_indices[:,0:1])
def filter_nests(self):
fixed = False
## TODO: use within_bb to reformat this.
assert fixed == True
try:
print("nest bounds are: "+str(self.bounds))
indices = np.array([0,1,2,3,4])
for mouse in range(2):
mouseindices = indices+5*mouse
## Bounds are defined as x greater than some value, y greater than some value (flipped on plot)
self.filter_speeds(mouseindices,9)
whole_traj = self.render_trajectories(list(mouseindices))
for part_nb,traj in enumerate(whole_traj):
pindex = part_nb+mouse*5
## Discover places where the animal is in its nest
bounds_check = traj-self.bounds
checkarray = bounds_check>0
in_nest = checkarray[:,0:1]*checkarray[:,1:]
nest_array = np.where(in_nest)[0]
okay_indices = np.array([index for index in self.allowed_index_full[pindex] if index[0] not in nest_array])
self.allowed_index_full[pindex] = self.simple_index_maker(pindex,okay_indices[:,0:1])
except NameError as error:
print(error)
def filter_speeds(self,indices,threshold = 10):
print('filtering by speed...')
for index in indices:
self.filter_speed(index,threshold)
def filter_likelihoods(self,indices):
print('filtering by likelihood...')
for index in indices:
self.filter_likelihood(index)
def reset_filters(self,indices):
print('resetting filters...')
for index in indices:
self.allowed_index_full[index] = self.simple_index_maker(index,self.time_index[:,np.newaxis])
self.filter_check_counts = [[] for i in self.part_index]
############# End of filtering functions. On to processing functions.
###
## Calculates the velocity of a mouse based on centroid:
def velocity(self,mouse,windowlength,polyorder,filter = False):
mouse = self.render_trajectories([mouse*5+3])[0]
diffs = np.diff(mouse,axis = 0)
if filter == True:
diffs = savgol_filter(diffs,windowlength,polyorder,axis = 0)
return diffs
## Determines when the velocities of the two mice are tracking each other.
def tracking(self,windowlength = 15,polyorder = 3,filter = True):
mice = [0,1]
vels = []
for mouse in mice:
vel = self.velocity(mouse,windowlength,polyorder,filter = True)
vels.append(vel)
# Batch dot product
similarity = np.sum(np.multiply(vels[0],vels[1]),axis = 1)
return similarity
## Not just when mice are tracking, but
def orderedtracking(self,windowlength = 15,polyorder = 3,filter = True):
mice = [0,1]
vels = []
for mouse in mice:
vel = self.velocity(mouse,windowlength,polyorder,filter = True)
vels.append(vel)
# Batch dot product
similarity = np.sum(np.multiply(vels[0],vels[1]),axis = 1)
# Find the average vector between their directions:
average = np.mean(np.stack(vels),axis = 0)
## Give the difference in positions between the two animals
relvec = self.relative_vector(0) ## Position of dam w.r.t. virgin.
## is the dam in front of the virgin or vice versa?
pose_align = np.sum(np.multiply(average,relvec[:-1,:]),axis = 1)/(np.linalg.norm(average,axis = 1)*np.linalg.norm(relvec[:-1,:],axis = 1))
return similarity,pose_align
def shepherding_ethogram(self):
similarity = self.tracking()
points = np.where(similarity>10)[0]
onehot = np.array([i in points for i in range(len(similarity)+1)])
return onehot
def nest_ethogram(self,mouse):
try:
nest_location = self.bounds
## retrieve trajectory:
out = self.render_trajectories([mouse*5+3])[0]
xcheck = (out[:,0]<self.bounds[0])
ycheck = (out[:,1]<self.bounds[1])
compound = np.logical_not(xcheck + ycheck)
except AttributeError as error:
print(error)
return compound
## Give a full ethogram that shows the activity of both mice, and shepherding
## events interspersed
def full_ethogram(self,save = False,show = True,savepath = './'):
## First get the nest ethograms of each animal:
in_nest = []
for mouse in [0,1]:
in_nest.append(self.nest_ethogram(mouse))
## Now get the shepherding ethogram:
shep = self.shepherding_ethogram()
fig,ax = plt.subplots(2,1)
names = ['Virgin','Dam']
for mouse in [0,1]:
b = in_nest[mouse]
b_x = range(len(b))
ax[mouse].plot(b_x,b,label = 'nest')
ax[mouse].fill_between(b_x,0,b)
ax[mouse].plot(b_x,shep,label = 'pursuit')
ax[mouse].set_title(names[mouse]+ ' Ethogram')
plt.legend()
plt.tight_layout()
if save == True:
plt.savefig(savepath+self.dataset_name.split('.')[0]+'Ethogram.png')
if show == True:
plt.show()
else:
plt.close()
def part_dist(self,part0,part1):
traj0,traj1 = self.render_trajectories([part0,part1])
diff = traj0-traj1
dist = np.linalg.norm(diff,axis = 1)
return dist
def proximity(self):
virg,moth = self.render_trajectories([3,8])
diff = virg-moth
dist = np.linalg.norm(diff,axis = 1)
return dist
def proximity_nonest(self):
close = np.where(self.proximity()<50)[0]
## Check where neither mouse is in the nest:
notnest = np.where((~self.nest_ethogram(0))*(~self.nest_ethogram(1)))[0]
close_good = [i for i in range(self.dataset.shape[0]) if i in close and i in notnest]
close_good_onehot = close_good = [i in close and i in notnest for i in range(self.dataset.shape[0])]
return close_good_onehot
def relative_velocity(self,mouse):
## First calculate velocity:
vel = self.velocity(mouse,5,3,False)
## Now calculate relative position of other mouse:
rel = self.relative_vector(mouse)
## calculate projection of velocity onto relative position:
# first calculate scalar projection:
print(vel.shape,rel.shape)
inner_prod = np.sum(np.multiply(vel[:self.dataset.shape[0]-1,:],rel[:self.dataset.shape[0],:]),axis = 1)
normed = inner_prod/np.linalg.norm(rel[:self.dataset.shape[0]-1,:],axis = 1)**2
projections = normed[:,np.newaxis]*rel[:self.dataset.shape[0]-1,:]
return projections
def relative_speed(self,mouse):
## First calculate velocity:
vel = self.velocity(mouse,5,3,False)
## Now calculate relative position of other mouse:
rel = self.relative_vector(mouse)
## calculate projection of velocity onto relative position:
# first calculate scalar projection:
inner_prod = np.sum(np.multiply(vel[:self.dataset.shape[0],:],rel[:self.dataset.shape[0]-1,:]),axis = 1)
normed = inner_prod/np.linalg.norm(rel[:self.dataset.shape[0]-1,:],axis = 1)
return normed
def relative_speed_normed(self,mouse):
## First calculate velocity:
vel = self.velocity(mouse,5,3,False)
## Now calculate relative position of other mouse:
rel = self.relative_vector(mouse)
## calculate projection of velocity onto relative position:
# first calculate scalar projection:
print(vel.shape,rel.shape)
inner_prod = np.sum(np.multiply(vel[:self.dataset.shape[0]-1,:],rel[:self.dataset.shape[0]-1,:]),axis = 1)
normed = inner_prod/(np.linalg.norm(rel[:self.dataset.shape[0]-1,:],axis = 1)*np.linalg.norm(vel[:self.dataset.shape[0]-1,:],axis = 1))
return normed
def interhead_position(self,mouse_id):
# Returns positions between the head for a given mouse
part_id = 5*mouse_id
lear,rear = self.render_trajectories([part_id+1,part_id+2])
stacked = np.stack((lear,rear))
centroids = np.mean(stacked,axis = 0)
return centroids
# Vector from the center of the head to the tip.
def head_vector(self,mouse_id):
# First get centroid:
head_cent = self.interhead_position(mouse_id)
vector = self.render_trajectory_full(mouse_id*5)-head_cent
return vector
## Vector from the center of the body to the center of the head.
def body_vector(self,mouse_id):
vector = self.render_trajectory_full(mouse_id*5)-self.render_trajectory_full(mouse_id*5+3)
return vector
def head_angle(self,mouse_id):
# First get centroid:
vector = self.head_vector(mouse_id)
north = np.concatenate((np.ones((len(self.time_index),1)),np.zeros((len(self.time_index),1))),axis = 1)
angles = angle_between_vec(north,vector)
return angles
def body_angle(self,mouse_id):
vector = self.body_vector(mouse_id)
north = np.concatenate((np.ones((len(self.time_index),1)),np.zeros((len(self.time_index),1))),axis = 1)
sign = np.sign(north[:,1]-vector[:,1])
angles = angle_between_vec(north,vector)*sign
return angles
# Gives the relative position of the other mouse with regard to the mouse provided in mouse_id
def relative_vector(self,mouse_id):
#First get centroid:
head_cent = self.interhead_position(mouse_id)
# Get other mouse centroid
other_mouse = abs(mouse_id-1)
other_mouse_centroid= self.render_trajectory_full(5*other_mouse)
vector = other_mouse_centroid-head_cent
return vector
def gaze_relative(self,mouse_id):
head_vector = self.head_vector(mouse_id)
rel_vector = self.relative_vector(mouse_id)
angles = angle_between_vec(head_vector,rel_vector)
return angles
############################ Filtering Primitives
def deviance_final(self,i,windowlength,reference,ref_pindex,target,target_pindex):
## We have to define all relevant index sets first. This is actually where most of the trickiness happens. We do the
## following: 1) define a starting point in the TARGET trajectory, by giving an index into the set of allowed axes.
# First define the relevant indices for interpolation: return the i+1th and the windowlength+i+1th index in the test set:
sample_indices_absolute = [i+1,windowlength+i+1]
ref_indices = ref_pindex[:,0]
target_indices = target_pindex[:,0]
test_indices_sample_start = target_indices[sample_indices_absolute[0]]
test_indices_sample_end = target_indices[sample_indices_absolute[-1]]
## We have to find the appropriate indices in the reference trajectory: those equal to or just outside the test indices
start_rel_ref,end_rel_ref = np.where(ref_indices <= test_indices_sample_start)[0][-1],np.where(ref_indices >= test_indices_sample_end)[0][0]
sample_indices_rel = ref_indices[[start_rel_ref-1,start_rel_ref,end_rel_ref-1,end_rel_ref]]
## Define the relevant indices for comparison in the test trajectory space:
comp_indices_rel_test = target_indices[sample_indices_absolute[0]:sample_indices_absolute[-1]]
## Now we should use indices to 1) interpolate the baseline trajectory, 2) evaluate the fit of the test to the
## interpolation
traj_ref = reference
traj_test = target
traj_ref_sample = traj_ref[[start_rel_ref-1,start_rel_ref,end_rel_ref,end_rel_ref+1],:]
## Create interpolation function:
f = interp1d(sample_indices_rel,traj_ref_sample,axis = 0,kind = 'cubic')
## Now evaluate this at the relevant points on the test function!
interped_points = f(comp_indices_rel_test)
sampled_points = traj_test[sample_indices_absolute[0]:sample_indices_absolute[-1],:]
return interped_points,sampled_points,comp_indices_rel_test
def deviance_final_p(self,i,windowlength,reference,ref_pindex,target,target_pindex):
## We have to define all relevant index sets first. This is actually where most of the trickiness happens. We do the
## following: 1) define a starting point in the TARGET trajectory, by giving an index into the set of allowed axes.
# First define the relevant indices for interpolation: return the i+1th and the windowlength+i+1th index in the test set:
sample_indices_absolute = [i+1,windowlength+i+1]
ref_indices = ref_pindex
target_indices = target_pindex
test_indices_sample_start = target_indices[sample_indices_absolute[0]]
test_indices_sample_end = target_indices[sample_indices_absolute[-1]]
## We have to find the appropriate indices in the reference trajectory: those equal to or just outside the test indices
start_rel_ref,end_rel_ref = np.where(ref_indices <= test_indices_sample_start)[0][-1],np.where(ref_indices >= test_indices_sample_end)[0][0]
sample_indices_rel = ref_indices[[start_rel_ref-1,start_rel_ref,end_rel_ref-1,end_rel_ref]]
## Define the relevant indices for comparison in the test trajectory space:
comp_indices_rel_test = target_indices[sample_indices_absolute[0]:sample_indices_absolute[-1]]
## Now we should use indices to 1) interpolate the baseline trajectory, 2) evaluate the fit of the test to the
## interpolation
traj_ref = reference
traj_test = target
traj_ref_sample = traj_ref[[start_rel_ref-1,start_rel_ref,end_rel_ref-1,end_rel_ref],:]
## Create interpolation function:
f = interp1d(sample_indices_rel,traj_ref_sample,axis = 0,kind = 'cubic')
## Now evaluate this at the relevant points on the test function!
interped_points = f(comp_indices_rel_test)
sampled_points = traj_test[sample_indices_absolute[0]:sample_indices_absolute[-1],:]
return interped_points,sampled_points,comp_indices_rel_test
def deviance_simple(self,i,windowlength,reference):
"""
Inputs:
i:(int) a time index representing the left edge of the window that we are using to process data.
windowlength:(int) a windowlength representing the amount of time over which to calculate votes.
reference:(array) a numpy array representing the xy positions of multiple body parts with axes as [time,part/coordinate].
"""
## We have to define all relevant index sets first. This is actually where most of the trickiness happens. We do the
## following: 1) define a starting point in the TARGET trajectory, by giving an index into the set of allowed axes.
# First define the relevant indices for interpolation: return the i+1th and the windowlength+i+1th index in the test set:
sample_start,sample_end = i+1,windowlength+i+1
# Get the sampled points from the trajectory.
sampled_points = reference[sample_start:sample_end,:]
## Now we should use indices to 1) interpolate the baseline trajectory, 2) evaluate the fit of the test to the
## interpolation
## Get the interpolated points from the trajectory:
sample_indices_rel = np.array([sample_start-1,sample_start,sample_end-1,sample_end])
## First extract relevant trajectories
traj_ref_sample = reference[[sample_start-1,sample_start,sample_end-1,sample_end],:]
## Create interpolation function around extracted trajectory:
f = interp1d(sample_indices_rel,traj_ref_sample,axis = 0,kind = 'cubic')
## Define the relevant indices for comparison in the test trajectory space:
comp_indices_rel = np.arange(sample_start,sample_end)
## Now evaluate this at the relevant points on the test function!
interped_points = f(comp_indices_rel)
return interped_points,sampled_points,comp_indices_rel
def adjacency_matrix(self,frames,vstats,mstats,thresh = [2,7]):
## Iterate through the parts of each mouse pairwise, and
## fetch the appropriate matrix with distances:
stats = [vstats,mstats]
matrix = np.zeros((len(frames),10,10))
for refmouse in range(2):
for j in range(5):
partref = refmouse*5+j
for targmouse in range(2):
threshindex = targmouse == refmouse
if threshindex == 0:
idxvec = j+1
else:
idxvec = j
for i in range(idxvec):
parttarg = targmouse*5+i
dist = self.part_dist(partref,parttarg)[frames]
## We want to ask if this is typical for what we would expect:
stats_touse = stats[refmouse]
if i == j:
mean,std = 0,15
else:
mean,std = stats_touse[(partref,refmouse*5+i)]
## Logical entries:
#threshold is generally stricter for your own animal:
## Query: is the target mouse part in line with what would be expected
## given the reference mouse's skeleton? I.e. asking if a body part
## fits better with the other skeleton is comparing columns of this
## block diagonal matrix
matrix[:,partref,parttarg] = abs(dist-mean)< thresh[threshindex]*std
matrix[:,partref-j+i,parttarg-i+j] = matrix[:,partref,parttarg]
return matrix
## Define a function to analyze the adjacency matrix by its individual blocks, and decide if
## an entry is misassigned:
def adjacency_matrix_fast(self,indices,meanfull,stdfull,thresh):
"""
Fast version of adjacency matrix code. Does all processing in parallel over a grid.
"""
traj = np.stack(self.render_trajectories(),axis = 1)[indices]
print(traj.shape)
matrix = np.zeros((1,10,10))
t0 = traj.reshape(-1,1,10,2)
t1 = traj.reshape(-1,10,1,2)
diffs = t0-t1
## remove some entries for [fast?] norm
block = np.ones((5,5))
mask = np.block([[np.tril(block,-1),np.tril(block)],[np.tril(block),np.tril(block,-1)]])
stackmask = np.stack([mask,mask],axis = 2)[None,:,:,:]
## WE don't need the matrix itself, but it's an important in between step that will help us later.
matrix = np.linalg.norm(diffs*stackmask,axis = 3)
binary = abs(matrix-meanfull) < stdfull
binary_sym = block_symmetric(binary,5)
return binary_sym
######################################################## Filtering operations.
## Parallelized version of the above. Could be up to 10x faster.
def filter_check_p(self,pindices,windowlength,varthresh,skip):
sample_indices = lambda i: [i,i+1,windowlength+i+1,windowlength+i+2]
# Define the indices you want to check: acceptable indices in both the part trajectory for this animal and
# its reference counterpoint
all_vars = []
all_outs = []
target = np.concatenate(self.render_trajectories(pindices),axis = 1)
## Make sure that no other processing has been done:
for pindex in pindices:
assert len(self.allowed_index_full[pindex]) == len(self.dataset.values), 'Must be done first'
target_indices = self.time_index
scores = np.zeros((len(target),len(pindices)))
compare_max = len(target_indices)-windowlength-1
for i in tqdm(range(compare_max)[::skip]):