-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhierarchical_cluster_tracker (copy).py
2440 lines (1854 loc) · 103 KB
/
hierarchical_cluster_tracker (copy).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
import numpy as np
import _pickle as pickle
import torch
import time
from sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
import os,sys
import torch.multiprocessing as mp
import queue
import copy
from matplotlib.patches import Rectangle
colors = np.random.rand(10000,3)
#colors[:,2] = 0
mp.set_sharing_strategy('file_system')
# ok look
# here's the deal - I know this is horrible horrible practice to import shared variables this way but I'm just too lazy to pass yet another data file to each process
zones = { "WB":{
"source":{
"bell":[3300,3400,-120,-65],
"hickoryhollow":[6300,6500,-120,-65],
"p25":[13300,13500,-100,0],
"oldhickory":[18300,18700,-120,-65],
"extent":[21900,23000,-100,0]
},
"sink":{
"extent":[-1000,0,-100,0],
"bell":[4400,4600,-120,-65],
"hickoryhollow":[8000,8200,-120,-65],
"p25":[13500,13650,-100,0],
"oldhickory":[20400,21000,-120,-65],
}
},
"EB":{
"source":{
"extent":[3500,3600,0,100],
"bell":[4200,5000,65,120],
"hickoryhollow":[9000,9600,65,120],
"p25":[13450,13600,0,100],
"oldhickory":[20900,21900,65,120]
},
"sink":{
"extent":[21700,23000,0,100],
"hickoryhollow1":[6100,6600,70,120],
"hickoryhollow2":[7900,8300,65,120],
"p25":[13200,13450,0,100],
"oldhickory":[18700,19300,65,120]
}
}
}
class Timer:
def __init__(self):
self.cur_section = None
self.sections = {}
self.section_calls = {}
self.start_time= time.time()
self.split_time = None
self.synchronize = False
def split(self,section,SYNC = False):
# store split time up until now in previously active section (cur_section)
if self.split_time is not None:
if SYNC and self.synchronize:
torch.cuda.synchronize()
elapsed = time.time() - self.split_time
if self.cur_section in self.sections.keys():
self.sections[self.cur_section] += elapsed
self.section_calls[self.cur_section] += 1
else:
self.sections[self.cur_section] = elapsed
self.section_calls[self.cur_section] = 1
# start new split and activate current time
self.cur_section = section
self.split_time = time.time()
def bins(self):
self.sections["total"] = time.time() - self.start_time
return self.sections
def __repr__(self):
out = ["{}:{:2f}s/call".format(key,self.sections[key]/self.section_calls[key]) for key in self.sections.keys()]
return str(out)
#%% Phase 1 functions
# def hierarchical_tree_old(start_x,end_x,start_time,end_time,space_chunk,time_chunk,split_space = True):
# tree = {"start_time":start_time,
# "end_time": end_time,
# "start_x":start_x,
# "end_x":end_x,
# "data":None,
# "children":None}
# if end_time - start_time > time_chunk:
# middle_time = start_time + (end_time - start_time)//2
# if end_x - start_x > space_chunk:
# middle_x = start_x + (end_x - start_x)//2
# children = [
# hierarchical_tree(start_x,middle_x,start_time,middle_time,space_chunk,time_chunk),
# hierarchical_tree(start_x,middle_x,middle_time,end_time,space_chunk,time_chunk),
# hierarchical_tree(middle_x,end_x,start_time,middle_time,space_chunk,time_chunk),
# hierarchical_tree(middle_x,end_x,middle_time,end_time,space_chunk,time_chunk)
# ]
# else:
# children = [
# hierarchical_tree(start_x,end_x,start_time,middle_time,space_chunk,time_chunk),
# hierarchical_tree(start_x,end_x,middle_time,end_time,space_chunk,time_chunk)
# ]
# elif end_x - start_x > space_chunk:
# middle_x = start_x + (end_x - start_x)//2
# children = [
# hierarchical_tree(start_x,middle_x,start_time,end_time,space_chunk,time_chunk),
# hierarchical_tree(middle_x,end_x,start_time,end_time,space_chunk,time_chunk)
# ]
# else:
# children = []
# tree["children"] = children
# return tree
def hierarchical_tree(start_x,end_x,start_time,end_time,space_chunk,time_chunk,split_space = True):
tree = {"start_time":start_time,
"end_time": end_time,
"start_x":start_x,
"end_x":end_x,
"data":None,
"children":None}
"""
Balanced to split only on space or time dimension on a single split layer
"""
if (end_time - start_time > time_chunk) and (not split_space or (end_x - start_x) <= space_chunk):
middle_time = start_time + (end_time - start_time)//2
# if end_x - start_x > space_chunk:
# middle_x = start_x + (end_x - start_x)//2
# children = [
# hierarchical_tree(start_x,middle_x,start_time,middle_time,space_chunk,time_chunk),
# hierarchical_tree(start_x,middle_x,middle_time,end_time,space_chunk,time_chunk),
# hierarchical_tree(middle_x,end_x,start_time,middle_time,space_chunk,time_chunk),
# hierarchical_tree(middle_x,end_x,middle_time,end_time,space_chunk,time_chunk)
# ]
# else:
children = [
hierarchical_tree(start_x,end_x,start_time,middle_time,space_chunk,time_chunk,split_space = not(split_space)),
hierarchical_tree(start_x,end_x,middle_time,end_time,space_chunk,time_chunk,split_space = not(split_space))
]
elif end_x - start_x > space_chunk:
middle_x = start_x + (end_x - start_x)//2
children = [
hierarchical_tree(start_x,middle_x,start_time,end_time,space_chunk,time_chunk,split_space = not(split_space)),
hierarchical_tree(middle_x,end_x,start_time,end_time,space_chunk,time_chunk,split_space = not(split_space))
]
else:
children = []
tree["children"] = children
return tree
def get_tree_leaves(tree):
leaves = []
if len(tree["children"]) == 0:
leaves.append(tree)
else:
for c in tree["children"]:
leaves += get_tree_leaves(c)
return leaves
def flatten_tree(tree,data_dir):
if len(tree["children"]) > 0:
tree_list = []
for i in range(len(tree["children"])):
tree_list += flatten_tree(tree["children"][i],data_dir)
else:
tree_list = []
tree["dep"] = []
for child in tree["children"]:
path = "{}/tracklets_{}_{}_{}_{}.cpkl".format(data_dir,child["start_time"],child["end_time"],child["start_x"],child["end_x"])
tree["dep"].append(path)
# for now supress this so there are no dependencies for bottom level nodes
# if len(tree["dep"]) == 0:
# tree["dep"].append( "{}/clusters_{}_{}_{}_{}.npy".format(data_dir,tree["start_time"],tree["end_time"],tree["start_x"],tree["end_x"]))
del tree["children"]
tree["my_path"] = "{}/tracklets_{}_{}_{}_{}.cpkl".format(data_dir,tree["start_time"],tree["end_time"],tree["start_x"],tree["end_x"])
tree_list.append(tree)
return tree_list
def md_iou(a,b,epsilon = 1e-04):
"""
a,b - [batch_size ,num_anchors, 4]
"""
area_a = (a[:,:,2]-a[:,:,0]) * (a[:,:,3]-a[:,:,1])
area_b = (b[:,:,2]-b[:,:,0]) * (b[:,:,3]-b[:,:,1])
minx = torch.max(a[:,:,0], b[:,:,0])
maxx = torch.min(a[:,:,2], b[:,:,2])
miny = torch.max(a[:,:,1], b[:,:,1])
maxy = torch.min(a[:,:,3], b[:,:,3])
zeros = torch.zeros(minx.shape,dtype=float,device = a.device)
intersection = torch.max(zeros, maxx-minx) * torch.max(zeros,maxy-miny)
union = area_a + area_b - intersection + epsilon
iou = torch.div(intersection,union)
#print("MD iou: {}".format(iou.max(dim = 1)[0].mean()))
return iou
def cluster(det,start_time,end_time,start_x,end_x,direction, delta = 0.3, phi = 0.4,data_dir = "data"):
def visit(i,id = -1):
# if this node has an id, return
# else, assign id, and return list of neighbors
if ids[i] != -1:
return []
else:
ids[i] = id
return adj_list[i]
path = "{}/clusters_{}_{}_{}_{}.npy".format(data_dir,start_time,end_time,start_x,end_x)
if os.path.exists(path):
return -1
# Phase 1 tracklet prep
# select only relevant detections
if type(det) == np.ndarray:
det = torch.from_numpy(det)
print("Checkpoint 0")
time_idxs = torch.where(torch.logical_and(det[:,0] > start_time,det[:,0] < end_time),1,0)
print("Checkpoint 1")
space_idxs = torch.where(torch.logical_and(det[:,1] > start_x,det[:,1]<end_x),1,0)
direction_idxs = torch.where(torch.sign(det[:,2]) == direction,1,0)
keep_idxs = (time_idxs * space_idxs * direction_idxs).nonzero().squeeze()
det = det[keep_idxs,:]
### detections have many overlaps - the first phase groups all detections that overlap sufficiently in space, and that create continuous clusters in space (i.e. iou-based tracker)
t1 = time.time()
ids = torch.torch.tensor([i for i in range(det.shape[0])]) # to start every detection is in a distinct cluster
adj_list = [[] for i in range(det.shape[0])]
for ts in np.arange(start_time,end_time,step = 0.1):
elapsed = time.time() - t1
remaining = elapsed/(ts-start_time+0.001) * (end_time - ts)
print("\r Processing time {:.1f}/{:.1f}s {:.2f}% done, ({:.1f}s elapsed, {:.1f}s remaining.) ".format(ts,end_time,(ts-start_time)*100/(end_time-start_time),elapsed,remaining),flush = True, end = "\r")
## grab the set of detections in ts,ts+delta
ts_idxs = torch.where(torch.logical_and(det[:,0] > ts,det[:,0] < ts+delta),1,0).nonzero().squeeze()
ts_det = det[ts_idxs,:]
max_idx = torch.max(ts_idxs)
if ts_det.shape[0] == 0:
continue
first = torch.clone(ts_det)
## convert from state for to state-space box rcs box form
boxes_new = torch.zeros([first.shape[0],4],)
boxes_new[:,0] = torch.min(torch.stack((first[:,1],first[:,1]+first[:,3]*direction),dim = 1),dim = 1)[0]
boxes_new[:,2] = torch.max(torch.stack((first[:,1],first[:,1]+first[:,3]*direction),dim = 1),dim = 1)[0]
boxes_new[:,1] = torch.min(torch.stack((first[:,2]-first[:,4]/2,first[:,2]+first[:,4]/2),dim = 1),dim = 1)[0]
boxes_new[:,3] = torch.max(torch.stack((first[:,2]-first[:,4]/2,first[:,2]+first[:,4]/2),dim = 1),dim = 1)[0]
first = boxes_new
## get IOU matrix
f = first.shape[0]
first = first.unsqueeze(1).repeat(1,f,1).double()
ious = md_iou(first,first.transpose(1,0))
# zero diagonal
# diag = torch.eye(ious.shape[0])
# ious = ious - diag
## get adjacency graph
adj_graph = torch.where(ious > phi,1,0)
## assign each cluster a unique ID in the cluster ID tensor, or assign it an existing ID if there is already an ID in the cluster ID tensor
for i in range(len(ts_det)):
idx = ts_idxs[i] # index into overall det and ids tensors
# get set of ids that match with this detection
matches = adj_graph[i].nonzero().squeeze(1)
cluster_idxs = ts_idxs[matches]
adj_list[idx] += cluster_idxs.tolist()
##, now given an adjacency list for each detection, get clusters
ids = torch.torch.tensor([-1 for i in range(det.shape[0])])
next_id = 0
t2 = time.time()
print("\n")
for i in range(ids.shape[0]):
if i % 100 == 0:
elapsed = time.time() - t2
remaining = elapsed/((i+1)/ids.shape[0])* (1- i/ids.shape[0])
print("\rOn detection {} of {}, {:.2f}% done, ({:.1f}s elapsed, {:.1f}s remaining.) ".format(i,ids.shape[0],i/ids.shape[0]*100,elapsed,remaining),end = "\r",flush = True)
if ids[i] == -1: # no assigned cluster
ids[i] = next_id
visited = torch.zeros(det.shape[0])
visited[i] = 1
to_visit = list(set(adj_list[i]))
while len(to_visit) > 0:
j = to_visit.pop(0)
new = visit(j,id = next_id)
visited[j] = 1
for item in new:
if visited[item] == 0:
to_visit.append(item)
next_id += 1
## resulting will be a set of tracklet clusters (clusters of detections)
count = ids.unique().shape[0]
orig_idxs = torch.torch.tensor([i for i in range(det.shape[0])])
out = torch.cat((det,orig_idxs.unsqueeze(1),ids.unsqueeze(1)),dim = 1)
out = out.data.numpy()
np.save(path,out)
print("\nFinished clustering detections for phase 1. Before:{}, After: {}. {:.1f}s elapsed.".format(det.shape[0],count,time.time() - t1))
#%% Phase 2 functions
def compute_intersections(tracklets,t_threshold,x_threshold,y_threshold, i = None, intersection = None,intersection_other = None,seam_idx = None,j = None):
"""
if intersection and index are passed, update is performed solely on row/column i and the resulting updated intersection is returnedc
"""
if i is None or i >= (len(tracklets)): # second case covers when i was the last tracklet and was added to finished queue
# get t overlaps for all tracklets
start = time.time()
max_t = torch.tensor([torch.max(t[:,0]) for t in tracklets]).unsqueeze(0).expand(len(tracklets),len(tracklets)) + 0.5*t_threshold
min_t = torch.tensor([torch.min(t[:,0]) for t in tracklets]).unsqueeze(1).expand(len(tracklets),len(tracklets)) - 0.5*t_threshold
mint_int = torch.max(torch.stack((min_t,min_t.transpose(1,0)),dim = -1),dim = -1)[0]
maxt_int = torch.min(torch.stack((max_t,max_t.transpose(1,0)),dim = -1),dim = -1)[0]
zeros = torch.zeros(mint_int.shape,dtype=float)
t_intersection = torch.max(zeros, maxt_int-mint_int) # if 0, these two tracklets are not within x_threshold of one another (even disregarding time matching)
# ensure t1 starts before t2
t_order = torch.where(max_t.transpose(1,0) - max_t <+ 0, 1,0)
# get x overlaps for all tracklets
max_x = torch.tensor([torch.max(t[:,1]) for t in tracklets]).unsqueeze(0).expand(len(tracklets),len(tracklets)) + 0.5*x_threshold
min_x = torch.tensor([torch.min(t[:,1]) for t in tracklets]).unsqueeze(1).expand(len(tracklets),len(tracklets)) - 0.5*x_threshold
minx_int = torch.max(torch.stack((min_x,min_x.transpose(1,0)),dim = -1),dim = -1)[0]
maxx_int = torch.min(torch.stack((max_x,max_x.transpose(1,0)),dim = -1),dim = -1)[0]
zeros = torch.zeros(minx_int.shape,dtype=float)
x_intersection = torch.max(zeros, maxx_int-minx_int) # if 0, these two tracklets are not within x_threshold of one another (even disregarding time matching)
# get y overlaps for all tracklets
max_y = torch.tensor([torch.max(t[:,2]) for t in tracklets]).unsqueeze(0).expand(len(tracklets),len(tracklets)) + 0.5*y_threshold
min_y = torch.tensor([torch.min(t[:,2]) for t in tracklets]).unsqueeze(1).expand(len(tracklets),len(tracklets)) - 0.5*y_threshold
miny_int = torch.max(torch.stack((min_y,min_y.transpose(1,0)),dim = -1),dim = -1)[0]
maxy_int = torch.min(torch.stack((max_y,max_y.transpose(1,0)),dim = -1),dim = -1)[0]
zeros = torch.zeros(miny_int.shape,dtype=float)
y_intersection = torch.max(zeros, maxy_int-miny_int) # if 0, these two tracklets are not within y_threshold of one another (even disregarding time matching)
#direction
# direction = torch.tensor([torch.sign(t[0,2]) for t in tracklets]).unsqueeze(0).expand(len(tracklets),len(tracklets))
# d_intersection = torch.where(direction * direction.transpose(1,0) == 1, 1,0)
intersection = t_order * torch.where(t_intersection > 0,1,0) * torch.where(t_intersection < (t_threshold+2),1,0) * torch.where(x_intersection > 0,1,0) * torch.where(y_intersection > 0,1,0) # * d_intersection
#* torch.where(x_intersection < x_threshold,1,0)
# zero center diagonal
intersection = intersection * (1- torch.eye(intersection.shape[0]))
#print("Intersection computation took {:.2f}s".format(time.time() - start))
# only consider pre-seam -> post-seam matches
if seam_idx is not None:
# intersection[:seam_idx,:] = 0
# intersection[seam_idx:,seam_idx:] = 0
intersection[:seam_idx,:seam_idx] = 0
intersection[seam_idx:,seam_idx:] = 0
else:
# "load" parameters
max_t = intersection_other["max_t"]
min_t = intersection_other["min_t"]
maxt_int = intersection_other["maxt_int"]
mint_int = intersection_other["mint_int"]
t_intersection = intersection_other["t_intersection"]
max_x = intersection_other["max_x"]
min_x = intersection_other["min_x"]
maxx_int = intersection_other["maxx_int"]
minx_int = intersection_other["minx_int"]
x_intersection = intersection_other["x_intersection"]
max_y = intersection_other["max_y"]
min_y = intersection_other["min_y"]
maxy_int = intersection_other["maxy_int"]
miny_int = intersection_other["miny_int"]
y_intersection = intersection_other["y_intersection"]
if j is None:
# update row/column
# max_t[:,i] = torch.max(tracklets[i][:,0]) + 0.5* t_threshold
# min_t[i,:] = torch.min(tracklets[i][:,0]) - 0.5* t_threshold
max_t[:,i] = tracklets[i][-1,0] + 0.5* t_threshold
min_t[i,:] = tracklets[i][0,0] - 0.5* t_threshold
mint_int = torch.max(torch.stack((min_t,min_t.transpose(1,0)),dim = -1),dim = -1)[0]
maxt_int = torch.min(torch.stack((max_t,max_t.transpose(1,0)),dim = -1),dim = -1)[0]
zeros = torch.zeros(mint_int.shape,dtype=float)
t_intersection = torch.max(zeros, maxt_int-mint_int)
t_order = torch.where(max_t.transpose(1,0) - max_t < 0, 1,0)
max_x[:,i] = max(tracklets[i][0,1],tracklets[i][-1,1]) + 0.5* x_threshold
min_x[i,:] = min(tracklets[i][0,1],tracklets[i][-1,1]) - 0.5* x_threshold
minx_int = torch.max(torch.stack((min_x,min_x.transpose(1,0)),dim = -1),dim = -1)[0]
maxx_int = torch.min(torch.stack((max_x,max_x.transpose(1,0)),dim = -1),dim = -1)[0]
zeros = torch.zeros(minx_int.shape,dtype=float)
x_intersection = torch.max(zeros, maxx_int-minx_int)
max_y[:,i] = torch.max(tracklets[i][:,2]) + 0.5* y_threshold
min_y[i,:] = torch.min(tracklets[i][:,2]) - 0.5* y_threshold
miny_int = torch.max(torch.stack((min_y,min_y.transpose(1,0)),dim = -1),dim = -1)[0]
maxy_int = torch.min(torch.stack((max_y,max_y.transpose(1,0)),dim = -1),dim = -1)[0]
zeros = torch.zeros(miny_int.shape,dtype=float)
y_intersection = torch.max(zeros, maxy_int-miny_int)
intersection = t_order * torch.where(t_intersection > 0,1,0) * torch.where(t_intersection < t_threshold,1,0) * torch.where(x_intersection > 0,1,0) * torch.where(y_intersection > 0,1,0) # * d_intersection
#torch.where(x_intersection < x_threshold,1,0) *
# zero center diagonal
intersection = intersection * (1- torch.eye(intersection.shape[0]))
# only consider pre-seam -> post-seam matches
if seam_idx is not None:
# intersection[:seam_idx,:] = 0
# intersection[seam_idx:,seam_idx:] = 0
intersection[:seam_idx,:seam_idx] = 0
intersection[seam_idx:,seam_idx:] = 0
# intersection of new tracklet is the union of the intersections of the two old components - though I think this should probably deal with the interesections that now fall within the tracklet
elif j is not None:
intersection[i,:] = torch.clamp(intersection[i,:] + intersection[j,:],min = 0,max = 1)
intersection[:,i] = torch.clamp(intersection[:,i] + intersection[:,j],min = 0,max = 1)
intersection_other = {
"max_t":max_t,
"min_t":min_t,
"maxt_int":maxt_int,
"mint_int":mint_int,
"t_intersection":t_intersection,
"max_x":max_x,
"min_x":min_x,
"minx_int":minx_int,
"maxx_int":maxx_int,
"x_intersection":x_intersection,
"max_y":max_y,
"min_y":min_y,
"miny_int":miny_int,
"maxy_int":maxy_int,
"y_intersection":y_intersection,
}
return intersection,intersection_other
def compute_raster_pos(tracklets, start_time,end_time,start_x,end_x,hz = 0.2, i = None, raster_pos = None):
raster_times = torch.arange(start_time,end_time, step = hz)
if raster_pos is None or i is None:
raster_pos = torch.zeros([len(tracklets),raster_times.shape[0],2]) + torch.nan
i_list = list(range(len(tracklets)))
else:
i_list = [i]
for i in i_list:
#if i%100 == 0: print("Getting raster positions for tracklet {}".format(i))
t = tracklets[i]
tidx = 0
m1 = max(0,int((t[0,0] - start_time)//hz - 1))
m2 = min(raster_times.shape[0],int((t[-1,0] - start_time)//hz + 1))
for ridx in range(m1,m2):
rt = raster_times[ridx]
if rt < t[0,0]:
continue
elif rt > t[-1,0] :
continue
else:
while t[tidx,0] < rt:
tidx+= 1
t1 = t[tidx-1,0]
t2 = t[tidx ,0]
x1 = t[tidx-1,1]
x2 = t[tidx ,1]
y1 = t[tidx-1,2]
y2 = t[tidx, 2]
r2 = (rt-t1) / (t2-t1)
r1 = 1-r2
x_rt = x1*r1 + x2*r2
y_rt = y1*r1 + y2*r2
raster_pos[i,ridx,0] = x_rt
raster_pos[i,ridx,1] = y_rt
return raster_pos
# interpolate position at raster_times[ridx]
def compute_scores_linear(tracklets,
intersection,
params,
iteration,
align_x,
align_y,
align_xb,
align_yb,
i = None
):
# load params arggh what a dumb solution
t_threshold = params["t_thresholds"][iteration]
x_threshold = params["x_thresholds"][iteration]
y_threshold = params["y_thresholds"][iteration]
min_regression_length = params["min_regression_lengths"][iteration]
reg_keep = params["reg_keeps"][iteration]
cutoff_dist = params["cutoff_dists"][iteration]
big_number = params["big_number"]
SHOW = False
if i is None:
i_list = list(range(len(tracklets)))
mask1 = torch.where(align_x == big_number,1,0) # these are the only elements that have changed since last iteration
mask = (mask1*intersection).nonzero()
i_list = torch.cat((mask[:,0], mask[:,1]))
j_list = torch.cat((mask[:,1], mask[:,0]))
else:
temp_j = intersection[i,:].nonzero().squeeze(1)
temp_i = torch.tensor([i for _ in range(len(temp_j))])
i_list = torch.cat((temp_i,temp_j))
j_list = torch.cat((temp_j,temp_i))
prev_i = -1
for list_idx,i in enumerate(i_list):
if tracklets[i].shape[0] < min_regression_length: continue
if i != prev_i: #reuse regression if possible
# fit linear regressor
t1 = tracklets[i][-reg_keep:,0].unsqueeze(1)
y1 = tracklets[i][-reg_keep:,1:3]
reg = LinearRegression().fit(t1,y1)
# fit linear regressor
t1b = tracklets[i][:reg_keep,0].unsqueeze(1)
y1b = tracklets[i][:reg_keep,1:3]
regb = LinearRegression().fit(t1b,y1b)
if SHOW:
plt.scatter(tracklets[i][:,0],tracklets[i][:,1], c = "g")
#plot regression line
t_trend = np.array([[tracklets[i][-reg_keep,0]],[tracklets[i][-1,0]+t_threshold]])
y_trend = reg.predict(t_trend)
plt.plot(t_trend,y_trend[:,0],":",c = "k")
#plot backward regression line
t_trend = np.array([[tracklets[i][reg_keep,0]],[tracklets[i][0,0]-t_threshold]])
y_trend = regb.predict(t_trend)
plt.plot(t_trend,y_trend[:,0],"--",c = "k")
#if i%100 == 0: print("On tracklet {} of {}".format(i,len(tracklets)))
j = j_list[list_idx]
if intersection[i,j] == 1:
#if align_x[i,j] != big_number: continue # if we already computed a score for this pair, that score is the same
# get first bit of data
t2 = tracklets[j][:reg_keep,0].unsqueeze(1)
y2 = tracklets[j][:reg_keep,1:3]
pred = reg.predict(t2)
diff = np.abs(pred - y2.data.numpy())
mdx = diff[:,0].mean()
mdy = diff[:,1].mean()
align_x[i,j] = mdx
align_y[i,j] = mdy
if mdx > x_threshold: align_x[i,j] = big_number
if mdy > y_threshold: align_y[i,j] = big_number
if SHOW:
plt.scatter(tracklets[j][:,0],tracklets[j][:,1], c = "r")
if intersection[j,i] == 1:
t2b = tracklets[j][-reg_keep:,0].unsqueeze(1)
y2b = tracklets[j][-reg_keep:,1:3]
pred = regb.predict(t2b)
diff = np.abs(pred - y2b.data.numpy())
mdx = diff[:,0].mean()
mdy = diff[:,1].mean()
align_xb[j,i] = mdx
align_yb[j,i] = mdy
if mdx > x_threshold: align_xb[j,i] = big_number
if mdy > y_threshold: align_yb[j,i] = big_number
if SHOW:
plt.scatter(tracklets[j][:,0],tracklets[j][:,1], color = (0.8,0.8,0))
# # check for short segments which will not have accurate regression lines
# if tracklets[i].shape[0] < min_regression_length and tracklets[j].shape[0] > min_regression_length:
# align_x[i,j] = align_xb[i,j]
# elif tracklets[i].shape[0] > min_regression_length and tracklets[j].shape[0] < min_regression_length:
# align_xb[i,j] = align_x[i,j]
# elif tracklets[i].shape[0] < min_regression_length and tracklets[j].shape[0] < min_regression_length:
# align_x[i,j] = big_number
# align_xb[i,j] = big_number
# find min alignment error
if SHOW:
min_idx = torch.argmin(align_x[i]**2 + align_y[i]**2)
min_dist = torch.sqrt(align_x[i,min_idx]**2 + align_y[i,min_idx]**2)
if min_dist < cutoff_dist:
plt.scatter(tracklets[min_idx][:,0],tracklets[min_idx][:,1], c = "b")
plt.title("Minimum mean distance: {:.1f}ft".format(min_dist))
# min backwards match
min_idx = torch.argmin(align_xb[i]**2 + align_yb[i]**2)
min_dist2 = torch.sqrt(align_xb[i,min_idx]**2 + align_yb[i,min_idx]**2)
if min_dist2 < cutoff_dist:
plt.scatter(tracklets[min_idx][:,0],tracklets[min_idx][:,1], color = (0,0.7,0.7))
plt.title("Minimum mean distance: {:.1f}ft,{:.1f}ft".format(min_dist,min_dist2))
plt.show()
# mask short
if False:
for idx,i in enumerate(i_list):
duration_i = tracklets[i][-1,0] - tracklets[i][0,0]
if duration_i < min_regression_length:
j = j_list[idx]
duration_j = tracklets[j][-1,0] - tracklets[j][0,0]
if duration_j > min_regression_length:
if intersection[i,j] == 1:
align_x[i,j] = align_xb[i,j]
align_y[i,j] = align_yb[i,j]
if intersection[j,i] == 1:
align_xb[j,i] = align_x[j,i]
align_yb[j,i] = align_y[j,i]
return align_x,align_y,align_xb,align_yb
def compute_scores_msf(tracklets,
intersection,
params,
iteration,
align_x,
align_y,
msf_dict,
i = None
):
# load params arggh what a dumb solution
t_threshold = params["t_thresholds"][iteration]
x_threshold = params["x_thresholds"][iteration]
y_threshold = params["y_thresholds"][iteration]
min_regression_length = params["min_regression_lengths"][iteration]
reg_keep = params["reg_keeps"][iteration]
cutoff_dist = params["cutoff_dists"][iteration]
big_number = params["big_number"]
SHOW = False
if i is None:
i_list = list(range(len(tracklets)))
else:
i_list = [i]
for i in i_list:
if SHOW: plt.figure()
# get virtual points
virtual = get_msf_points(tracklets[i],msf_dict)
if SHOW:
plt.scatter(tracklets[i][:,0],tracklets[i][:,1], c = "g")
plt.plot(virtual[:,0],virtual[:,1],":",color = (0.2,0.2,0.2))
# linear regressor - for y-coordinates
t1 = tracklets[i][:reg_keep,0].unsqueeze(1)
y1 = tracklets[i][:reg_keep,1:3]
reg = LinearRegression().fit(t1,y1)
# compare to each candidate match
for j in range(len(tracklets)):
if intersection[i,j] == 1 and align_x[i,j] == big_number:
# nix this # for each point in tracklet [j] within some threshold of the times within virtual, find closest time point, compute x and y distance, and add to score
# lets do it incredibly crudely, find first point of tracklet j, find closest virtual trajectory point by time, compute offset
jx = tracklets[j][0,1]
jt = tracklets[j][0,0]
match_idx = torch.argmin(torch.abs(virtual[:,0] - jt))
align_x[i,j] = torch.abs(jx - virtual[match_idx,1])
# get first bit of data
t2 = tracklets[j][:reg_keep,0].unsqueeze(1)
y2 = tracklets[j][:reg_keep,1:3]
pred = reg.predict(t2)
diff = np.abs(pred - y2.data.numpy())
#assign
mdy = diff[:,1].mean()
align_y[i,j] = mdy
if SHOW:
plt.scatter(tracklets[j][:,0],tracklets[j][:,1], color = (0.8,0.8,0))
# find min alignment error
if SHOW:
min_idx = torch.argmin(align_x[i]**2 + align_y[i]**2)
min_dist = torch.sqrt(align_x[i,min_idx]**2 + align_y[i,min_idx]**2)
if min_dist < cutoff_dist:
plt.scatter(tracklets[min_idx][:,0],tracklets[min_idx][:,1], c = "b")
plt.title("Minimum mean distance: {:.1f}ft".format(min_dist))
plt.show()
return align_x,align_y
def compute_scores_msf2(tracklets,
intersection,
params,
iteration,
align_x,
align_y,
msf_dict,
i = None
):
# load params arggh what a dumb solution
t_threshold = params["t_thresholds"][iteration]
x_threshold = params["x_thresholds"][iteration]
y_threshold = params["y_thresholds"][iteration]
min_regression_length = params["min_regression_lengths"][iteration]
reg_keep = params["reg_keeps"][iteration]
cutoff_dist = params["cutoff_dists"][iteration]
big_number = params["big_number"]
SHOW = False
virtuals = None
if i is None:
i_list = list(range(len(tracklets)))
mask1 = torch.where(align_x == big_number,1,0) # these are the only elements that have changed since last iteration
mask = (mask1*intersection).nonzero()
i_list = mask[:,0]
j_list = mask[:,1]
# precompute msf for ALLL - this may be slower since we don't downselect only relevant tracklets - though we could
virtuals = get_msf_points_batched(tracklets, msf_dict)
else:
j_list = intersection[i,:].nonzero().squeeze(1)
i_list = torch.tensor([i for _ in range(len(j_list))])
prev_i = -1
for list_idx, i in enumerate(i_list):
if SHOW: plt.figure()
# get virtual points if i has changed
if virtuals is not None:
virtual = virtuals[i]
elif i != prev_i:
virtual = get_msf_points(tracklets[i],msf_dict)
if SHOW:
plt.scatter(tracklets[i][:,0],tracklets[i][:,1], c = "g")
plt.plot(virtual[:,0],virtual[:,1],":",color = (0.2,0.2,0.2))
# linear regressor - for y-coordinates
t1 = tracklets[i][:reg_keep,0].unsqueeze(1)
y1 = tracklets[i][:reg_keep,1:3]
reg = LinearRegression().fit(t1,y1)
# compare to each candidate match
#for j in range(len(tracklets)):
j = j_list[list_idx]
if intersection[i,j] == 1 and align_x[i,j] == big_number:
# nix this # for each point in tracklet [j] within some threshold of the times within virtual, find closest time point, compute x and y distance, and add to score
# lets do it incredibly crudely, find first point of tracklet j, find closest virtual trajectory point by time, compute offset
jx = tracklets[j][0,1]
jt = tracklets[j][0,0]
match_idx = torch.argmin(torch.abs(virtual[:,0] - jt))
align_x[i,j] = torch.abs(jx - virtual[match_idx,1])
# get first bit of data
t2 = tracklets[j][:reg_keep,0].unsqueeze(1)
y2 = tracklets[j][:reg_keep,1:3]
pred = reg.predict(t2)
diff = np.abs(pred - y2.data.numpy())
#assign
mdy = diff[:,1].mean()
align_y[i,j] = mdy
if SHOW:
plt.scatter(tracklets[j][:,0],tracklets[j][:,1], color = (0.8,0.8,0))
# find min alignment error
if SHOW:
min_idx = torch.argmin(align_x[i]**2 + align_y[i]**2)
min_dist = torch.sqrt(align_x[i,min_idx]**2 + align_y[i,min_idx]**2)
if min_dist < cutoff_dist:
plt.scatter(tracklets[min_idx][:,0],tracklets[min_idx][:,1], c = "b")
plt.title("Minimum mean distance: {:.1f}ft".format(min_dist))
plt.show()
return align_x,align_y
def compute_scores_overlap(tracklets,
intersection_other,
params,
iteration,
align_x,
align_y,
i = None,
hz = 0.1):
"""
Differently than the other compute_scores functions, here we consider all pairs that have a time overlap?
"""
t_intersection = intersection_other["t_intersection"]
x_intersection = intersection_other["x_intersection"]
y_intersection = intersection_other["y_intersection"]
big_number = params["big_number"]
mint_int = intersection_other["mint_int"]
maxt_int = intersection_other["maxt_int"]
# align_x = align_x*0 + big_number
# align_y = align_y*0 + big_number # overwrite old scores
# go through all pairs and compute mean distance over intersection
if i is None:
align_x = align_x*0 + big_number
align_y = align_y*0 + big_number # overwrite old scores
i_list = list(range(len(tracklets)))
else:
align_x[i,:] = big_number
align_x[:,i] = big_number
align_y[i,:] = big_number
align_y[:,i] = big_number
i_list = [i]
for i in i_list:
if i >= t_intersection.shape[0]: break
#if i %10 == 0: print("On tracklet {}".format(i))
for j in range(len(tracklets)):
if j == i: continue
if j >= t_intersection.shape[0]: continue
if t_intersection[i,j] > 0 and t_intersection[i,j] < 10 and x_intersection[i,j] > 0 and y_intersection[i,j] > 0:
tmin = mint_int[i,j]
tmax = maxt_int[i,j]
# compute mean dist over t_overlap range at X Hz
try: eval_t = torch.arange(tmin,tmax-3*hz,step = hz)
except RuntimeError:
eval_t = [tmin,tmax]
i_idxs = []
j_idxs = []
i_iter = 0
j_iter = 0
for t in eval_t:
try:
while tracklets[i][i_iter,0] < t: i_iter += 1
i_idxs.append(i_iter)
while tracklets[j][j_iter,0] < t: j_iter += 1
j_idxs.append(j_iter)
except IndexError:
break
# ensure there were some selected data points
l = min(len(j_idxs),len(i_idxs))
if l < 2: continue
j_idxs = j_idxs[:l]
i_idxs = i_idxs[:l]
# only use close comparison points to compute score
mask = torch.where(tracklets[i][i_idxs,0]- tracklets[j][j_idxs,0] < 0.1,1,0).nonzero().squeeze(1)
ix = tracklets[i][i_idxs,1][mask]
iy = tracklets[i][i_idxs,2][mask]
jx = tracklets[j][j_idxs,1][mask]
jy = tracklets[j][j_idxs,2][mask]
align_x[i,j] = torch.sqrt((ix-jx)**2).mean()
align_y[i,j] = torch.sqrt((iy-jy)**2).mean()
# if align_x[i,j] + align_y[i,j] < params["cutoff_dists"][iteration]:
# print("Tracklets {} and {} mean overlap distance {:.1f}ft and {} comparisons".format(i,j,align_x[i,j] + align_y[i,j],len(i_idxs)))
align_x = torch.nan_to_num(align_x,nan = big_number)
align_y = torch.nan_to_num(align_y,nan = big_number)
return align_x,align_y
def compute_scores_overlap2(tracklets,
raster_pos,
params,
align_x,
align_y,
i = None):
"""
Differently than the other compute_scores functions, here we consider all pairs that have a time overlap?
"""
# t_intersection = intersection_other["t_intersection"]
# x_intersection = intersection_other["x_intersection"]