-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSegConfig.py
More file actions
1919 lines (1753 loc) · 86.3 KB
/
SegConfig.py
File metadata and controls
1919 lines (1753 loc) · 86.3 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
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
import numpy as np
import matplotlib.pyplot as plt
from collections import deque
from tqdm import tqdm
from heapq import heappush,heappop
from timeit import default_timer as timer
## A python module that holds the refactored code for behavioral trace analysis. This new code is based on the fundamental unit of a segment object, that is organized and held in a configuration object. This module should be independent of all the modules that have been written previously, but is testable using the SwitchCircle object in Social_Dataset_BB_testdata.
## The fundamental unit of our new analysis. Contains segments of behavioral traces, chunked in time such that handling by higher order functions is simple and efficient. Carries a base, working, and query configuration to handle flexible working with multiple hypothetical
invalid_int = -999999
## Helper function
## Handles indexing into numpy arrays using configuration arrays.
def c2i(data,config):
out = data[config]
out[np.where(config == -1)] = invalid_int
return out
## The same as c2i, but instead of converting to an index, converts to a float with nans as the default.
def c2f(data,config):
out = data[config]
out[np.where(config == -1)] = np.nan
return out
## Setup functions:
## Functions to get us from raw data to segments.
## Function to define rules that get us from data to segments. In the future, we will want to integrate the process of generating these segmentations to work within an optimization framework as well.
def make_blueprint():
## This can wait.
pass
## Function that takes trajectory, as well as time intervals and a mask. Returns a list of segment objects.
def data_framer(trajectory,time,mask):
## Convert the mask to a configuration representation.
conf = mask.astype(int)*np.array([[1,2]])
conf = conf-1
segs = []
for t,interval in enumerate(time):
segind = t
timeind = interval.astype(int)
trace = trajectory[slice(*timeind),:]
config = conf[t,:]
seg = Segment(trace,timeind,segind,config)
segs.append(seg)
return segs
class Segment(object):
'''
Object class to handle the low level nitty-gritty of working with behavioral trace data. Carries behavioral trace data, time and segment indices, and a local configuration set (base,working,query) to allow us to work with data flexibly.
Parameters:
trajectories: a numpy array of size (time,2*number of animals*number of parts). In reasonable cases for the forseeable future, probably will be (time,4).
timeindex: a tuple containing the start and end times occupied by the segment in the dataset of origin.
segindex: an integer, giving the ordinal index of the segment in the dataset of origin.
init_config: a two element list containing 1,0, or -1. These are codes for how to move around the trajectories to our desired initial configuration.
'''
def __init__(self,trajectories,timeindex,segindex,init_config):
## We have trajectory a and b: this is the way the trajectories are initialized. These attributes should be 100% immutable.
self.traja = trajectories[:,0:2]
self.trajb = trajectories[:,2:4]
self.trajs = np.stack((self.traja,self.trajb),axis=0)
## For indexing purposes:
self.timeindex = timeindex
self.length = self.timeindex[-1]-self.timeindex[0]
self.segindex = segindex
## Check for consistency between the attributes we have declared thus far.
assert len(self.trajs[0,:,:]) == self.timeindex[1]-self.timeindex[0],'timeindex and trajectories must match '
## Finally, initialize the configuration of the two trajectories:
self.base_config = init_config
self.barred = np.where(self.base_config==-1)[0]
self.allowed = np.where(self.base_config!=-1)[0]
self.set_work_config(self.base_config)
## Initialize distance calculations, referenced later by other methods.
self.calculate_dist()
self.calculate_tv()
self.calculate_bounds()
## Configuration functions.
## Checks if a given configuration is valid, given the base configuration that is known. If a configuration is -1 for a given segment index, another configuration cannot pull it, and it cannot be restored.
def check_config(self,config):
disallowed = np.any([bi in config for bi in self.barred])
return 1-disallowed
## Takes as input a numpy array of shape (1,number of individuals)
def set_work_config(self,config):
cond = self.check_config(config)
if cond == True:
self.work_config = config
else:
print('Given config not compatible with segment '+str(self.segindex))
## Reset to the base config.
def reset_work_config(self):
self.set_work_config(self.base_config)
## Measuring functions
def calculate_dist(self):
'''
Function to measure the distance from the point registered at the beginning and end of the trajectory. Registered to 'a' and 'b', will be handled later for specific configurations.
'''
dista = np.linalg.norm(self.traja[-1,:]-self.traja[0,:])
distb = np.linalg.norm(self.trajb[-1,:]-self.trajb[0,:])
self.dists = np.array([dista,distb])
def calculate_tv(self):
'''
Function to measure the tv norm from the point registered at the beginning and end of the trajectory. Registered to 'a' and 'b', will be handled later for specific configurations.
'''
tva = np.sum(np.linalg.norm(abs(np.diff(self.traja,axis=0)),axis = 1))
tvb = np.sum(np.linalg.norm(abs(np.diff(self.trajb,axis=0)),axis = 1))
self.tvs = np.array([tva,tvb])
def calculate_bounds(self):
'''
Function to calculate start and end points (a,b, registered).
'''
starts = np.array([self.traja[0,:],self.trajb[0,:]])
ends = np.array([self.traja[-1,:],self.trajb[-1,:]])
self.starts = starts
self.ends = ends
## Functions that return things depending on the current configuration state.
def get_dist(self, query = None,mouse = None):
'''
Function to handle configuration information and return parameters as appropriate.Can specify a query configuration, and a mouse. If not, sum across both mice for working configuration will be returned.
'''
## Organize distances according to the configuration.
if query is not None:
if self.check_config(query):
dists = c2f(self.dists,query)
else:
dists = np.array([np.nan,np.nan])
else:
dists = c2f(self.dists,self.work_config)
## Now index into the distances
if mouse is None:
dist= dists
elif mouse in [0,1]:
dist = dists[mouse]
else:
raise ValueError
return dist
def get_tv(self,query = None,mouse = None):
'''
Function to handle configuration information and return parameters as appropriate.Can specify a query configuration, and a mouse. If not, sum across both mice for working configuration will be returned.
'''
## Organize tv according to the configuration.
if query is not None:
if self.check_config(query):
tvs = c2f(self.tvs,query)
else:
tvs = np.array([np.nan,np.nan])
else:
tvs = c2f(self.tvs,self.work_config)
## Now index into the tvances
if mouse is None:
tv= tvs
elif mouse in [0,1]:
tv = tvs[mouse]
else:
raise ValueError
return tv
def get_start(self, query = None,mouse = None):
'''
Function to handle configuration information and return parameters as appropriate.Can specify a query configuration, and a mouse. If not, sum across both mice for working configuration will be returned.
'''
## Organize tv according to the configuration.
if query is not None:
if self.check_config(query):
starts = c2i(self.starts,query)
else:
starts = np.array([[invalid_int,invalid_int],[invalid_int,invalid_int]])
else:
starts = c2i(self.starts,self.work_config)
## Now index into the tvances
if mouse is None:
start = starts
elif mouse in [0,1]:
start = starts[mouse]
else:
raise ValueError
return start
def get_end(self, query = None,mouse = None):
'''
Function to handle configuration information and return parameters as appropriate.Can specify a query configuration, and a mouse. If not, sum across both mice for working configuration will be returned.
'''
## Organize tv according to the configuration.
if query is not None:
if self.check_config(query):
ends = c2i(self.ends,query)
else:
ends = np.array([[invalid_int,invalid_int],[invalid_int,invalid_int]])
else:
ends = c2i(self.ends,self.work_config)
## Now index into the tvances
if mouse is None:
end= ends
elif mouse in [0,1]:
end = ends[mouse]
else:
raise ValueError
return end
def get_traj(self, query = None,mouse = None):
'''
Function to handle configuration information and return parameters as appropriate.Can specify a query configuration, and a mouse. If not, trajectory of both mice for working configuration will be returned.
'''
## Organize according to the configuration.
if query is not None:
if self.check_config(query):
trajs = c2f(self.trajs,query)
else:
trajs = np.nan*np.ones(np.shape(self.trajs))
else:
trajs = c2f(self.trajs,self.work_config)
## Now index into the correct trajectory:
if mouse is None:
traj= trajs
elif mouse in [0,1]:
traj = trajs[mouse]
else:
raise ValueError
return traj
def plot_trace():
pass
## Trace traversal helper functions:
## Find the first valid entry and return its index
def find_first(array):
## Add one to look for zeros:
plusarray = array+1
relevant = next((i for i,x in enumerate(plusarray) if x),None)
return relevant
## We define a configuration class that holds a list of segment objects, and can test various manipulations of them, and calculate the resulting costs. As with individual segments, the configuration object has different "tiers" of configuration, starting with the base configuration (no touch) to query configuration that are just passed to the data for the sake of testing out a particular configuration. The configuration code for Configurations has one more flag compared to the Segment: -2 says, we are agnostic, reference the current underlying trajectory.
class Configuration(object):
## Lagrange multipliers are for the first and second penalty term when calculating the cost.
def __init__(self,trajectory,time,mask,lagrange1=None,lagrange2=None,mweights=None,sweights=None):
self.segs = data_framer(trajectory,time,mask)
self.nb_segs = len(self.segs)
self.length = np.sum([seg.length for seg in self.segs])
self.lengths = np.array([self.segs[i].length for i in range(self.nb_segs)])
self.base_config = np.stack([seg.base_config for seg in self.segs],axis = 0)
self.set_work_config(self.base_config)
self.calculate_timesegs()
## We need more: the starts and ends with respect to the base configuration.
self.all_starts = np.stack([self.segs[i].get_start() for i in range(self.nb_segs)],axis=1)
self.all_ends = np.stack([self.segs[i].get_end() for i in range(self.nb_segs)],axis=1)
self.all_tvs = np.stack([self.segs[i].get_tv() for i in range(self.nb_segs)],axis=0)
## If lagrange1 is not given, we can use the optimal with some default parameter:
if lagrange1 is None:
lagrange1 = self.lagrange1_fromdata(0.05)
if lagrange2 is None:
lagrange2 = 0.05
self.weights = [lagrange1,lagrange2]
if mweights is None:
self.mweights,self.sweights = self.lagrange_moving(N = int(self.length//10))
else:
self.mweights = mweights
self.sweights = sweights
def check_config(self,config,start = None,end = None):
assert len(config) == len(range(self.nb_segs)[start:end])
## Segmentwise check. First take the segment list, the relevant configs, and zip:
inputs = zip(self.segs[start:end],config)
## Now broadcast with map.
checks = list(map(lambda x: Segment.check_config(*x),inputs))
## The configuration is only valid if all the entires are individually valid.
check = np.all(checks)
return check
def return_checked(self,query,start = None,end = None):
if query is None:
config = self.work_config[start:end]
else:
assert self.check_config(query,start = start,end = end); 'Must be valid'
config = np.copy(query)
if -2 in config:
config[np.where(config ==-2)] = self.work_config[start:end][np.where(config==-2)]
return config
def set_work_config(self,config):
cond = self.check_config(config)
if cond == True:
## First take the agnostic parts, and replace with working config:
if -2 in config:
config[np.where(config ==-2)] = self.work_config[np.where(config==-2)]
self.work_config = config
## We also have to change it in the underlying segments!
inputs = zip(self.segs,config)
list(map(lambda x: Segment.set_work_config(*x),inputs))
else:
print('Given config not compatible with configuration')
def reset_work_config(self):
self.set_work_config(self.base_config)
## Now, some functions to allow for easy indexing. Let's see if we can pull out a trajectory segment by timepoints.
## First, a helper function to give the segment index of any single time point.
def calculate_timesegs(self):
indparts = []
for seg in self.segs:
indpart = np.repeat(seg.segindex,seg.length)
indparts.append(indpart)
timesegs = np.concatenate(indparts)
self.timesegs = timesegs
## Pull out the positions of the two mice at any given query point. Query in this case should just be a tuple. Useful for estimating costs.
def render_point_time(self,time,query = None):
## First get out the starting and ending segments.
segind = self.timesegs[time]
seg = self.segs[segind]
## Initialize the trajectory to be rendered as an array of nans:
## Specify the configuration we will use to generate this trajectory
if query is None:
config = self.work_config
else:
assert self.check_config(query); 'Must be valid'
config = query
## Now get the trajectory:
trajectory = seg.get_traj(query = config[segind])
## Shift the given time index to match the trajectory:
index_inseg = time-seg.timeindex[0]
point = trajectory[:,index_inseg,:]
return point
## Renders the trajectory of both animals between the given time indices. Time indices are interpreted slice-style, with the last one non-inclusive.
def render_trajectory_time(self,timeindex = None,query = None):
## Default timeindex is the whole trajectory
if timeindex is None:
timeindex = np.array([0,self.length])
s,e = timeindex[0],timeindex[-1]-1
## First get out the starting and ending segments.
start,end = self.timesegs[np.array([s,e])]
## Initialize the trajectory to be rendered as an array of nans:
trajectory = np.ones((2,timeindex[-1]-timeindex[0],2))*np.nan
## Specify the configuration we will use to generate this trajectory
if query is None:
config = self.work_config[slice(start,end+1),:]
else:
config = self.return_checked(query,start,end+1)
for sord,segind in enumerate(np.arange(start,end+1)):
## Get the trajectory as appropriate:
seg = self.segs[segind]
segtrajectory = seg.get_traj(query = config[sord])
if segind == start:
segstart = timeindex[0]-seg.timeindex[0]
else:
segstart = 0
if segind == end:
segend = timeindex[-1]-seg.timeindex[0]
else:
segend = seg.length
## Grab the time indices
segtimes = seg.timeindex
## Shift the time indices to respect the start of the trajectory and turn them into a slice. Also handle cases where the indices overlap.
shiftindex = segtimes-s
shiftindex[np.where(shiftindex<0)] = 0
segtimes_slice = slice(*shiftindex)
## Now assign.
trajectory[:,segtimes_slice,:] = segtrajectory[:,segstart:segend,:]
return trajectory
def render_trajectory_seg(self,segindex = None,query = None):
## Default timeindex is the whole trajectory
if segindex is None:
tstart,tend = 0,self.length
else:
tstart,tend = self.segs[segindex[0]].timeindex[0],self.segs[segindex[-1]].timeindex[-1]
trajectory = self.render_trajectory_time(np.array([tstart,tend]),query)
return trajectory
## TODO: Plotting functions: compare to check_plot
## Cost functions:
## In order to define cost functions, we have to have a notion of valid segments. Have a function that will return two lists of the valid segment numbers under the current configuration.
## TODO: vaildate get_valid0 against the whole trajectory.
def get_valid(self,query = None,start = None,end = None,check= True):
if check == True:
config = self.return_checked(query,start=start,end =end)
else:
if query is None:
config = self.work_config[start:end]
else:
config = query
## Start with the working configuration:
lengtharray = np.arange(self.length)[start:end]
length= len(lengtharray)# booo
indexarray = lengtharray.reshape(length,1).repeat(2,axis = 1)
valindices = []
if start is None:
startind = 0
else:
startind = start
for i in range(2):
valid = indexarray[:,i][np.where(config[:,i]!=-1)]-startind
valindices.append(valid)
return valindices
## Get the valid segment indices that flank this point.
## We have to do some low level stuff here:
def get_valid_surr(self,segindex,mouse,query = None,check = True):
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
prepoints = []
postpoints = []
mouseconfig = config[:,mouse]
mousepre,mousepost = np.flip(mouseconfig[:segindex]),mouseconfig[segindex:]
preind,postind = [find_first(m) for m in [mousepre,mousepost]]
if preind is None:
backind = None
else:
backind = segindex-(preind+1)
if postind is None:
forind = None
else:
forind = segindex+postind
return backind,forind
## The easier part is getting the inter segment intervals for all valid intervals.
## This function returns the array of all valid intra segment costs (excluding nans) under the given (or working) configuration.
def get_intra(self,query = None,check = True):
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
valids = self.get_valid(config,check = False)
mice_ids = [config[valids[i],i] for i in range(2)]
tvs = np.ones(self.all_tvs.shape)*np.nan
for i in range(2):
tvs[valids[i],i] = self.all_tvs[valids[i],mice_ids[i]]
return tvs
## Deprecated. here for reference in case of fires
#def get_intra(self,query = None,check = True):
# if check == True:
# config = self.return_checked(query)
# else:
# if query is None:
# config = self.work_config
# else:
# config = query
# inputs = zip(self.segs,config)
# tv = np.stack([self.segs[i].get_tv(config[i]) for i in range(self.nb_segs)])
# return tv
def get_intra_cut(self,query = None,start = None,end = None,check = True):
if check == True:
config = self.return_checked(query,start = start,end = end)
else:
if query is None:
config = self.work_config[start:end]
else:
config = query
## Returns aligned to the start provided for indexing into the config provided.
valids = self.get_valid(config,start = start,end = end,check = False)
tvs = np.ones(self.all_tvs[start:end].shape)*np.nan
for i in range(2):
if len(valids[i])>0:
mice_ids = config[valids[i],i]
tvs[valids[i],i] = self.all_tvs[valids[i],mice_ids]
return tvs
#def get_intra_cut(self,query = None,start = None,end = None,check = True):
# if check == True:
# config = self.return_checked(query,start = start,end = end)
# else:
# if query is None:
# config = self.work_config[start:end]
# else:
# config = query
# inputs = zip(self.segs[start:end],config)
# tv = np.stack(list(map(lambda x: Segment.get_tv(*x),inputs)))
# return tv
def get_intra_dist(self,query = None):
config = self.return_checked(query)
inputs = zip(self.segs,config)
tv = np.stack(list(map(lambda x: Segment.get_dist(*x),inputs)))
return tv
def get_intra_dist_cut(self,query = None,start = None,end = None,check = True):
if check == True:
config = self.return_checked(query,start = start,end = end)
else:
if query is None:
config = self.work_config[start:end]
else:
config = query
inputs = zip(self.segs[start:end],config)
dist = np.stack(list(map(lambda x: Segment.get_dist(*x),inputs)))
return dist
## The slightly harder part: this function returns two lists of all valid inter segment costs under the given (default working) configuration. Returns an array of shape (number_intervals-1,2). If the gap spans multiple invalid trajectories, put the actual cost in the first interval for which the whole cost applies.
## A version that does not have handling of these different cases:
def get_inter(self,query = None,check = True):
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
valid_inds = self.get_valid(config,check = False)
# Now iterate over each mouse:
dist_length = np.max([len(config)-1,1])
dists = np.zeros((dist_length,2))
## Get the mouse indices corresponding to the time indices:
mice_inds = [config[v,vi] for vi,v in enumerate(valid_inds)]
for m in range(2):
starts = self.all_starts[mice_inds[m][1:],valid_inds[m][1:]]
ends = self.all_ends[mice_inds[m][:-1],valid_inds[m][:-1]]
dist_all = np.linalg.norm(ends-starts,axis = 1)
dists[valid_inds[m][:-1],m] = dist_all
if len(valid_inds[m]) == 0:
endtime = 0
starttime = self.length
tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
tv_opt = np.sum(tvs)
dists[0,m] = tv_opt
elif valid_inds[m][0] != 0:
endtime = 0
starttime = self.segs[valid_inds[m][0]].timeindex[0]
## Query the moving average weights we collected, and be optimistic:
tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
tv_opt = np.sum(tvs)
dists[0,m] = tv_opt
elif valid_inds[m][-1] != self.nb_segs-1:
endtime = self.segs[valid_inds[m][-1]].timeindex[-1]
starttime = self.length
tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
tv_opt = np.sum(tvs)
dists[-1,m] = tv_opt
return dists
#def get_inter(self,query = None,check = True):
# if check == True:
# config = self.return_checked(query)
# else:
# if query is None:
# config = self.work_config
# else:
# config = query
# valid_inds = self.get_valid(config,check = False)
# # Now iterate over each mouse:
# dist_length = np.max([len(config)-1,1])
# dists = np.zeros((dist_length,2))
# for m in range(2):
# mouse_valid = valid_inds[m]
# ## Now we would like to identify all pairs:
# pairs = [mouse_valid[i:i+2] for i in range(len(mouse_valid)-1)]
# for pair in pairs:
# end = self.segs[pair[0]].get_end(mouse = m,query = config[pair[0]])
# start = self.segs[pair[-1]].get_start(mouse = m,query = config[pair[-1]])
# dist = np.linalg.norm(end-start)
# dists[pair[0],m] = dist
# if len(mouse_valid) == 0:
# endtime = 0
# starttime = self.length
# tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
# tv_opt = np.sum(tvs)
# dists[0,m] = tv_opt
# elif mouse_valid[0] != 0:
# endtime = 0
# starttime = self.segs[mouse_valid[0]].timeindex[0]
# ## Query the moving average weights we collected, and be optimistic:
# tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
# tv_opt = np.sum(tvs)
# dists[0,m] = tv_opt
# elif mouse_valid[-1] != self.nb_segs-1:
# endtime = self.segs[mouse_valid[-1]].timeindex[-1]
# starttime = self.length
# tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
# tv_opt = np.sum(tvs)
# dists[-1,m] = tv_opt
#
# return dists
def get_inter_cut(self,query = None,start = None,end = None,check = True):
if check == True:
config = self.return_checked(query,start,end)
else:
if query is None:
config = self.work_config[start:end]
else:
config = query
if start is None:
startp = 0
else:
startp = start
## Returns aligned to the start provided.
valid_inds = self.get_valid(config,start,end,check = False)
# Now iterate over each mouse:
dist_length = np.max([len(config)-1,1])
dists = np.zeros((dist_length,2))
## Get the mouse indices corresponding to the time indices:
for m in range(2):
if len(valid_inds[m])>0:
mice_inds = config[valid_inds[m],m]
starts = self.all_starts[mice_inds[1:],valid_inds[m][1:]+startp]
ends = self.all_ends[mice_inds[:-1],valid_inds[m][:-1]+startp]
dist_all = np.linalg.norm(ends-starts,axis = 1)
dists[valid_inds[m][:-1],m] = dist_all
return dists
#def get_inter_cut(self,query = None,start = None,end = None,check = True):
# if check == True:
# config = self.return_checked(query,start,end)
# else:
# if query is None:
# config = self.work_config[start:end]
# else:
# config = query
# if start is None:
# startp = 0
# else:
# startp = start
# valid_inds = self.get_valid(config,start,end,check = False)
# # Now iterate over each mouse:
# dist_length = np.max([len(config)-1,1])
# dists = np.zeros((dist_length,2))
# for m in range(2):
# mouse_valid = valid_inds[m]
# ## Now we would like to identify all pairs:
# pairs = [mouse_valid[i:i+2] for i in range(len(mouse_valid)-1)]
# for pair in pairs:
# endpos = self.segs[pair[0]].get_end(mouse = m,query = config[pair[0]-startp])
# startpos = self.segs[pair[-1]].get_start(mouse = m,query = config[pair[-1]-startp])
# dist = np.linalg.norm(endpos-startpos)
# dists[pair[0]-startp,m] = dist
# return dists
def get_inter_optimal(self,query = None,check = True):
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
valid_inds = self.get_valid(config,check = check)
# Now iterate over each mouse:
length_tv = np.max([len(config)-1,1])
tv_opts = np.zeros((length_tv,2))
for m in range(2):
mouse_valid = valid_inds[m]
## Now we would like to identify all pairs:
pairs = [mouse_valid[i:i+2] for i in range(len(mouse_valid)-1)]
for pair in pairs:
endtime = self.segs[pair[0]].timeindex[-1]-1
starttime = self.segs[pair[-1]].timeindex[0]
## Query the moving average weights we collected, and be optimistic:
tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
tv_opt = np.sum(tvs)
tv_opts[pair[0],m] = tv_opt
if len(mouse_valid) == 0:
endtime = 0
starttime = self.length
tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
tv_opt = np.sum(tvs)
dists[0,m] = tv_opt
elif mouse_valid[0] != 0:
endtime = 0
starttime = self.segs[mouse_valid[0]].timeindex[0]
## Query the moving average weights we collected, and be optimistic:
tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
tv_opt = np.sum(tvs)
dists[0,m] = tv_opt
elif mouse_valid[-1] != len(tv_opts):
endtime = self.segs[mouse_valid[-1]].timeindex[-1]-1
starttime = self.length
tvs = self.mweights[endtime:starttime,m]-self.sweights[endtime:starttime,m]
tv_opt = np.sum(tvs)
tv_opts[-1,m] = tv_opt
return tv_opts
## Get full cost. Takes a split argument that partitions the cost by the segment index. Splits up to the start of the indicated segment.
def full_tvcost(self,query = None,check = True):
## The intra segment cost:
tvarray = self.get_intra(query,check = check)
distarray = self.get_inter(query,check = check)
cost = np.nansum(tvarray)+np.sum(distarray)
return cost
## Test this on an extra long example
## Get the cost split at an indicated segment.
def split_tvcost(self,query = None,split=0,check = True):
## The intra segment cost:
tvarray = self.get_intra(query,check = check)
distarray = self.get_inter(query,check = check)
pretv,posttv = tvarray[:split,:],tvarray[split:,:]
predist,postdist = distarray[:split,:],distarray[split:,:]
precost = np.nansum(pretv)+np.sum(predist)
postcost = np.nansum(posttv)+np.sum(postdist)
return precost,postcost
## Culmination of efficient cost calculation functions.
def cut_tvcost(self,query = None,start = None,end = None,check = True):
## First calculate all intra costs:
## Handle corner cases:
if start == self.nb_segs or end == 0:
cost = 0
else:
intraarray = self.get_intra_cut(query,start,end,check)
interarray = self.get_inter_cut(query,start,end,check)
cost = np.nansum(intraarray)+np.nansum(interarray)
return cost
## Write pre/post split functions that will actually save time by computing only partial costs
## Get the penalty due to regularization terms:
## The cost for removing datapoints:
def full_nullcost(self,query=None,check = True):
## Find all segments that have negative ones
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
## We would like an efficient way to count lengths: have an integer count of how many individuals designate a given part as invalid.
indicator = np.zeros(np.shape(config))
indicator[np.where(config ==-1)] = 1
counts = np.sum(indicator,axis = 1)
costvec = self.lengths*counts*self.weights[0]
return np.sum(costvec)
def split_nullcost(self,query=None,split = 0,check = True):
## Find all segments that have negative ones
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
## We would like an efficient way to count lengths: have an integer count of how many individuals designate a given part as invalid.
indicator = np.zeros(np.shape(config))
indicator[np.where(config ==-1)] = 1
counts = np.sum(indicator,axis = 1)
costvec = self.lengths*counts*self.weights[0]
return np.sum(costvec[:split]),np.sum(costvec[split:])
def cut_nullcost(self,query=None,start=None,end=None,check = True):
## Find all segments that have negative ones
if check == True:
config = self.return_checked(query,start,end)
else:
if query is None:
config = self.work_config[start:end]
else:
config = query
## We would like an efficient way to count lengths: have an integer count of how many individuals designate a given part as invalid.
indicator = np.zeros(np.shape(config))
indicator[np.where(config ==-1)] = 1
counts = np.sum(indicator,axis = 1)
costvec = self.lengths[start:end]*counts*self.weights[0]
return np.sum(costvec)
def full_switchcost(self,query=None,check = True):
## Find all segments that have flipped indices relative to the base configuration we started with.
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
## We would like an efficient way to count lengths: have an integer count of how many individuals designate a given part as invalid.
## Compare against an entirely flipped array:
fliparray = np.zeros(np.shape(config))
fliparray[:,0] += 1
indicator = np.zeros(np.shape(config))
indicator[np.where(config == fliparray)] == 1
counts = np.sum(indicator,axis = 1)
costvec = self.lengths*counts*self.weights[1]
return np.sum(costvec)
def split_switchcost(self,query = None,split = 0,check = True):
## Find all segments that have flipped indices relative to the base configuration we started with.
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
## We would like an efficient way to count lengths: have an integer count of how many individuals designate a given part as invalid.
## Compare against an entirely flipped array:
fliparray = np.zeros(np.shape(config))
fliparray[:,0] += 1
indicator = np.zeros(np.shape(config))
indicator[np.where(config == fliparray)] == 1
counts = np.sum(indicator,axis = 1)
costvec = self.lengths*counts*self.weights[1]
return np.sum(costvec[:split]),np.sum(costvec[split:])
def cut_switchcost(self,query = None,start = None,end = None,check = True):
## Find all segments that have flipped indices relative to the base configuration we started with.
if check == True:
config = self.return_checked(query,start,end)
else:
if query is None:
config = self.work_config[start:end]
else:
config = query
## We would like an efficient way to count lengths: have an integer count of how many individuals designate a given part as invalid.
## Compare against an entirely flipped array:
fliparray = np.zeros(np.shape(config))
fliparray[:,0] += 1
indicator = np.zeros(np.shape(config))
indicator[np.where(config == fliparray)] = 1
counts = np.sum(indicator,axis = 1)
costvec = self.lengths[start:end]*counts*self.weights[1]
return np.sum(costvec)
def full_cost(self,query=None,check = True):
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
tvcost = self.full_tvcost(query=config,check = False)
p1cost = self.full_nullcost(query=config,check = False)
p2cost = self.full_switchcost(query=config,check = False)
return tvcost+p1cost+p2cost
def split_cost(self,query=None,split = 0,check = True):
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
tvcost0,tvcost1 = self.split_tvcost(query=config,split = split,check = False)
p1cost0,p1cost1 = self.split_nullcost(query=config,split = split,check = False)
p2cost0,p2cost1 = self.split_switchcost(query=config,split = split,check = False)
return np.sum(np.stack((tvcost0,p1cost0,p2cost0)),axis = 0),np.sum(np.stack((tvcost1,p1cost1,p2cost1)),axis = 0)
def cut_cost(self,query = None, start = None,end = None,check = True):
if check == True:
config = self.return_checked(query,start,end)
else:
if query is None:
config = self.work_config[start:end]
else:
config = query
cut_tv = self.cut_tvcost(query=config,start=start,end=end,check=False)
cut_p1 = self.cut_nullcost(query=config,start=start,end=end,check=False)
cut_p2 = self.cut_switchcost(query=config,start=start,end=end,check=False)
return cut_tv+cut_p1+cut_p2
def bridge_cost(self,query = None,split = 0,check = True,inds = [0,1]):
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
additional_cost = 0
for ind in inds:
end,start = self.get_valid_surr(split,ind,config,False)
if end is None:
endpos = self.segs[0].get_start(mouse = ind,query = config[0])
else:
endpos = self.segs[end].get_end(mouse = ind,query = config[end])
if start is None:
startpos = self.segs[-1].get_end(mouse = ind,query = config[-1])
else:
startpos = self.segs[start].get_start(mouse = ind,query = config[start])
#if start is None end is None:
# pass
#else:
dist = np.linalg.norm(startpos-endpos)
additional_cost+=dist
return additional_cost
def bridge_cost_opt(self,query = None,split = 0,check = True,inds = [0,1]):
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
additional_cost = 0
for ind in inds:
end,start = self.get_valid_surr(split,ind,config,False)
if end is None:
endtime = self.segs[0].timeindex[0]
else:
endtime= self.segs[end].timeindex[-1]
if start is None:
starttime = self.segs[-1].timeindex[-1]
else:
starttime = self.segs[start].timeindex[0]
#if start is None end is None:
# pass
#else:
tvs = self.mweights[endtime:starttime,ind]-self.sweights[endtime:starttime,ind]
tvopt = np.nansum(tvs)
additional_cost+=tvopt
return additional_cost
def bridge_adaptive(self,prolif_start,prolif_end,query = None, check = True):
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
## Now, check if the segment is valid under this query:
valcheck = config[prolif_start:prolif_end]
for i in range(2):
vals = valcheck[:,i]
if np.all(vals == -1):
bridge = self.bridge_cost_opt(query = config, split = prolif_end,inds = [i],check = check)
else:
bridgepre = self.bridge_cost(query = config, split = prolif_start,inds = [i],check = check)
## Should be beginning of estimation: use the optimal.
bridgepost = self.bridge_cost_opt(query = config, split = prolif_end,inds = [i],check = check)
bridge = bridgepre+bridgepost
return bridge
## Basically a test function to check the validity of what we're doing.
def split_efficient(self,query = None,split = 0,check = True):
## We have to specifically handle the case where the split happens across an invalid segment.
if check == True:
config = self.return_checked(query)
else:
if query is None:
config = self.work_config
else:
config = query
additional_cost = self.bridge_cost(config,split = split,check = False)
precost = self.cut_cost(config[:split],end = split,check = False)
postcost = self.cut_cost(config[split:],start = split,check = False)
return precost+additional_cost,postcost
## Purely for the convenience of not having to index:
def pre_cost(self,query=None,split = 0,check = True):
tvcost0,tvcost1 = self.split_tvcost(query,split = split,check = check)
p1cost0,p1cost1 = self.split_nullcost(query,split = split,check = False)
p2cost0,p2cost1 = self.split_switchcost(query,split = split,check = False)
return np.sum(np.stack((tvcost0,p1cost0,p2cost0)),axis = 0)
## Mini function to estimate distances:
def estimate_distance(self,nbp,config,split):
timepoints = np.sort(np.random.choice(np.arange(split,self.length),nbp,replace = False))
full_timepoints = np.concatenate([[split],timepoints])
pointgetter = lambda t: self.render_point_time(t,query = config)
points = np.stack(list(map(pointgetter,full_timepoints)))
## Add on the point given by the split position:
## Get two arrays, one for each mouse, without nans:
m1p,m2p = points[:,0,:],points[:,1,:]
m1clean,m2clean = m1p[~np.isnan(m1p)].reshape(-1,2),m2p[~np.isnan(m2p)].reshape(-1,2)
m1diff,m2diff = np.diff(m1clean,axis = 0),np.diff(m2clean,axis = 0)
m1norm,m2norm = np.linalg.norm(m1diff,axis=1),np.linalg.norm(m2diff,axis=1)
m1dist,m2dist = sum(m1norm),sum(m2norm)
return m1dist+m2dist
## Estimate the cost under the given (or current) configuration, using an estimate of the tv per time rate.
def estimate_postcost(self,nbp,query=None,split = 0,check = True):
if check == True: