-
Notifications
You must be signed in to change notification settings - Fork 236
/
metric.py
1443 lines (1166 loc) · 51 KB
/
metric.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
from time import time, gmtime, strftime
import numpy as np
import matplotlib.pyplot as plt
from math import degrees
import collections
from collections import defaultdict
import itertools as IT
import bluesky as bs
from bluesky.tools import geo
from bluesky.tools.misc import tim2txt
from bluesky.tools.aero import *
from bluesky import settings
# Register settings defaults
settings.set_variable_defaults(log_path='output')
"""
This module seems to work as follows:
It looks like this used to be a submodule of the traffic module
Now it is a full module under the sim package
Apparently the creation of this module also called into life the concept of a research area.
A research area is something which is not specific to the metrics module and could be used by different modules.
However, the area command in the stack module saves data in the metric instance.
If the area function and metric module are to be seperatly used, then they should be untangled.
Classes:
Metric, metric_Area, metric_CoCa, metric_HB
Each has a constructor
Requirements for instance creation:
Metric: -
metric_Area: -
metric_CoCa: regions
metric_HB: area
Called from:
metric_Area: Metric
metric_CoCa: Metric
metric_HB: Metric
Passed as argument to:
metric_Area: metric_CoCa, metric_HB (only the .cellArea instance)
metric_CoCa: -
metric_HB: -
Structure:
metric object created with Metric class constructor
metric.metric object is of the form (metric_CoCa, metric_HB)
So the metric instance has two sub instances,
one of type metric_CoCa and one of type metric_HB
"""
class metric_Area():
def __init__(self):
self.lat = 55.5
self.lon = 1.7
self.fll = 8500
self.flu = 41500
self.bearingS = 180
self.bearingE = 90
self.deltaFL = 3000
self.distance = 20
self.ncells = 18
self.nlevels = 12
self.regions = np.array([0,0,0])
def addbox(self,lat,lon):
lat_0 = lat
lat_00 = lat
lon_0 = lon
londiviser = 1
for i in range(1,self.ncells+1):
for j in range(1,self.ncells+1):
for k in range(self.fll,self.flu+self.deltaFL,self.deltaFL):
box = np.array([lat,lon,k])
self.regions = np.vstack([self.regions,box])
if i == 1:
lat,lon = geo.qdrpos(lat,lon,self.bearingE,self.distance)
lat = degrees(lat)
lon = degrees(lon)
londiviser = (lon - lon_0) / self.ncells
else:
lat,lon = geo.qdrpos(lat,lon,self.bearingE,self.distance)
lat = degrees(lat)
lon = lon_0 + londiviser * j
lat_0 = lat_00
lat,lon = geo.qdrpos(lat_0,lon_0,self.bearingS,self.distance*i)
lat = degrees(lat)
lon = degrees(lon)
lat_0 = lat
return
def cellArea(self):
point1 = [self.regions[0,0],self.regions[0,1]]
point2 = [self.regions[self.ncells*self.nlevels-1,0],self.regions[self.ncells*self.nlevels-1,1]]
point3 = [self.regions[(self.ncells-1)*self.ncells*self.nlevels,0],self.regions[(self.ncells-1)*self.ncells*self.nlevels,1]]
point4 = [self.regions[self.ncells*self.ncells*self.nlevels-1,0],self.regions[self.ncells*self.ncells*self.nlevels-1,1]]
self.cellarea = np.array([point4,point2,point1,point3])
#print self.cellarea
return self.cellarea
def makeRegions(self):
lat = self.lat
lon = self.lon
self.addbox(lat,lon)
self.regions = np.delete(self.regions, (0), axis=0)
return self.regions
def area_of_polygon(self,x, y):
area = 0.0
for i in range(-1, len(x) - 1):
area += x[i] * (y[i + 1] - y[i - 1])
return area / 2.0
def centroid_of_polygon(self,points):
area = self.area_of_polygon(*list(zip(*points)))
result_x = 0
result_y = 0
N = len(points)
points = IT.cycle(points)
x1, y1 = next(points)
for i in range(N):
x0, y0 = x1, y1
x1, y1 = next(points)
cross = (x0 * y1) - (x1 * y0)
result_x += (x0 + x1) * cross
result_y += (y0 + y1) * cross
result_x /= (area * 6.0)
result_y /= (area * 6.0)
return (result_x, result_y)
def FIR_circle(self, fir_number):
fir_lat = []
fir_lon = []
fir = []
fir_lat.append(bs.navdb.fir[fir_number][1])
fir_lon.append(bs.navdb.fir[fir_number][2])
fir.append((fir_lat[-1],fir_lon[-1]))
fir = fir[0]
fir = list(zip(fir[0],fir[1]))
fir_centroid = self.centroid_of_polygon(fir)
return fir_centroid
class metric_CoCa():
def __init__(self,regions):
self.region = regions
self.oldaircraft = np.zeros((1000,1), dtype = [('callsign','|S10'),('cellnumber',int), ('time',int),('totaltime',int)])
self.newaircraft = np.zeros((1000,1), dtype = [('callsign','|S10'),('cellnumber',int), ('time',int),('totaltime',int)])
# self.cells = np.zeros((self.region.nlevels*self.region.ncells*self.region.ncells,1), dtype = [('cellnumber',int),('interactions',int),('ntraf',int)])
# for i in range(0,len(self.cells)):
# self.cells['cellnumber'][i] = i + 1
# plt.close()
self.numberofcells = self.region.ncells*self.region.ncells*self.region.nlevels
names = []
for i in range(0,self.numberofcells):
names.append("cell"+str(i))
formats = []
for i in range(0,self.numberofcells):
formats.append("|S10")
ndtype = {'names':names, 'formats':formats}
self.cells = np.zeros((500,6), dtype = ndtype)
self.resettime = 5 #seconds
self.deltaresettime = self.resettime
self.iteration = 0
formats = []
for i in range(0,self.numberofcells):
formats.append(float)
ndtype = {'names':names, 'formats':formats}
oneday = 86400 # second in one day
numberofrows = oneday / self.resettime
numberofrows = 3
self.precocametric = np.zeros((numberofrows,5), dtype = ndtype)
self.cocametric = np.zeros((numberofrows,6), dtype = ndtype)
plt.ion()
self.ntraf = 0
# plt.colorbar()
# self.plotntraf,= plt.plot([], [])
# self.plotbar, = plt.bar([],[])
return
def findCell(self,cells,lat,lon,fl):
i = 0
j = 0
k = 0
for i in range(0,len(cells),self.region.ncells*self.region.nlevels):
if (cells[0,0]) <= lat < (cells[0,0]+0.6):
break
if (cells[i,0] < lat < cells[0,0] and cells[i,0] > cells[-1,0]) :
break
else:
i = -10000
if i > -1 :
for j in range(0,self.region.ncells*self.region.nlevels,self.region.nlevels):
if cells[i+j,1] > lon and lon < (cells[-1,1]+0.6) and lon > cells[0,1]:
j = j - self.region.nlevels
break
if cells[i+j,1]+0.6 > lon and lon < (cells[-1,1]+0.6) and lon > cells[0,1]:
break
else:
j = -10000
if j > - 1:
for k in range(0,self.region.nlevels,1):
if cells[i+j+k,2] > fl and fl < (cells[-1,2]+self.region.deltaFL) and fl > cells[0,2]:
k = k -1
break
else:
k = -10000
if (i+j+k) < 0:
i=-1
j=0
k=0
return i+j+k
# def update_line(self,ntraf,t):
# if t < 0.1:
# self.__init__()
# t = int(t)
# self.plotntraf.set_xdata(np.append(self.plotntraf.get_xdata(), t))
# self.plotntraf.set_ydata(np.append(self.plotntraf.get_ydata(), ntraf))
# plt.plot(t,ntraf,'b--o')
# ax = plt.gca()
# ax.relim()
# ax.autoscale_view()
# return
# def update_bar(self,trafcell,t):
# if t < 0.1:
# self.__init__
# t = int(t)
# self.plotbar.set_xdata(np.append(self.plotbar.get_xdata(), t))
# self.plotbar.set_ydata(np.append(self.plotbar.get_ydata(), trafcell))
# plt.plot(t,ntraf,'b--o')
# ax = plt.gca()
# ax.relim()
# ax.autoscale_view()
# return
# def plot_interactions(self):
# plotcells = np.sort(self.cells, axis = 0, order='interactions')[-3:]
# label = np.vstack(plotcells['cellnumber'])
# x = np.arange(len(label))
# y1 = np.vstack(plotcells['interactions'])
# colLabels=("Interactions","")
# nrows, ncols = len(x)+1, len(colLabels)
# hcell, wcell = 0.3, 0.5
# hpad, wpad = 0, 0.5
# fig1=plt.figure(num = 1, figsize=(ncols*wcell+wpad, nrows*hcell+hpad))
# ax = fig1.add_subplot(111)
# ax.axis('off')
# ax.table(cellText=y1,colLabels=colLabels, rowLabels = label ,loc='center')
# plt.bar(x,y)
# plt.xticks(x,str(label))
# plt.show()
# return
# def cell_interactions(self,cellN):
# # Interactions
# itemscount = np.array(collections.Counter(cellN).items())
# if len(itemscount) > 0:
# for number in range(0,self.region.ncells*self.region.ncells*self.region.nlevels):
# j = np.where(itemscount[:,0] == number)
# if np.size(j) == 0:
# self.cells['interactions'][number] = 0
# else:
# self.cells['interactions'][number] = itemscount[j,1]*(itemscount[j,1]-1)
# self.plot_interactions()
# return
# def celltime(self,time):
# for i in range(0,len(self.newaircraft)):
# j = np.where(self.oldaircraft['callsign'] == self.newaircraft['callsign'][i])[0]
# if np.size(j) == 1:
# if self.oldaircraft['cellnumber'][j] == self.newaircraft['cellnumber'][i]:
# self.newaircraft['time'][i] = time - self.oldaircraft['totaltime'][i]
# else:
# self.newaircraft['totaltime'][i] = time - self.oldaircraft['totaltime'][i]
# self.cells['ntraf'][i] = self.cells['ntraf'][i] + 1
# self.oldaircraft = self.newaircraft
# return self.newaircraft
def cellPlot(self):
cell = [floor(x/12) for x in bs.traf.cell]
count = collections.Counter(cell)
count = np.array(list(count.items()))
flcells = count
if np.size(count)>0:
flcells = count[:,0]
z = np.array([0])
for number in range(0,self.region.ncells*self.region.ncells):
i = np.where(flcells == (number))
if np.size(i) == 0:
z = np.append(z,0)
else:
i = i[0]
z = np.append(z,count[i,1])
z = np.delete(z, (0), axis=0)
zdata = np.reshape(z,(-1,self.region.ncells))
fig = plt.figure(1)
ax = fig.add_subplot(1, 1, 1)
ax.imshow(zdata, interpolation='nearest')
plt.show()
return
def applyMetric(self):
for i in range(0,self.numberofcells):
name = 'cell'+str(i)
l = self.iteration
times = []
headings = []
speeds = []
vspeeds = []
actimes = []
for j in range(0,len(self.cells[name])):
if self.cells[name][j][1] != "":
times.append(float(self.cells[name][j][1]))
headings.append(float(self.cells[name][j][2]))
speeds.append(float(self.cells[name][j][3]))
vspeeds.append(float(self.cells[name][j][4]))
actimes.append(float(self.cells[name][j][1]))
indices = np.argsort(times)
times.sort()
headings = [headings[z] for z in indices]
speeds = [speeds[y] for y in indices]
vspeeds = [vspeeds[x] for x in indices]
actimes = [actimes[w] for w in indices]
for w in range(0,len(vspeeds)):
if vspeeds[w] <= 500 and vspeeds[w] >= (-500):
vspeeds[w] = 0
elif vspeeds[w] > 500:
vspeeds[w] = 1
elif vspeeds[w] < (-500):
vspeeds[w] = -1
self.precocametric[name][l][0] = (sum(times)/self.deltaresettime)
acinteractions = []
spdinteractions = []
hdginteractions = []
vspdinteractions = []
if len(times) > 1:
for k in range(0,len(times)):
aircraft = len(times)
time = times[0]/self.deltaresettime
actime = actimes[0]/self.deltaresettime
acinteractions.append(aircraft*(aircraft-1)*(actime**aircraft))
counter = 0
for t in range(0,1):
for u in range(t+1,len(speeds)):
if abs(speeds[t]-speeds[u]) > 35:
counter = counter + 1
spdinteractions.append(2*counter*(time**(counter+1)))
counter = 0
for t in range(0,1):
for u in range(t+1,len(headings)):
if abs(headings[t]-headings[u]) > 20:
counter = counter + 1
hdginteractions.append(2*counter*(time**(counter+1)))
counter = 0
for t in range(0,1):
for u in range(t+1,len(vspeeds)):
if vspeeds[t] != vspeeds[u]:
counter = counter + 1
vspdinteractions.append(2*counter*(time**(counter+1)))
for x in range(1,len(actimes)):
actimes[x] = actimes[x] - actimes[0]
del actimes[0]
del times[0]
del vspeeds[0]
del speeds[0]
del headings[0]
self.precocametric[name][l][1] = sum(acinteractions)
self.precocametric[name][l][2] = sum(spdinteractions)
self.precocametric[name][l][3] = sum(hdginteractions)
self.precocametric[name][l][4] = sum(vspdinteractions)
self.cocametric[name][l][1] = self.precocametric[name][l][1] / self.precocametric[name][l][0]
self.cocametric[name][l][2] = self.precocametric[name][l][2] / self.precocametric[name][l][0]
self.cocametric[name][l][3] = self.precocametric[name][l][3] / self.precocametric[name][l][0]
self.cocametric[name][l][4] = self.precocametric[name][l][4] / self.precocametric[name][l][0]
self.cocametric[name][l][0] = self.cocametric[name][l][1] * (self.cocametric[name][l][2] + self.cocametric[name][l][3] + self.cocametric[name][l][4])
print("Iteration number: "+str(self.iteration+1))
print("Reset time = "+str(self.resettime))
return
def reset(self):
names = []
for i in range(0,self.numberofcells):
names.append("cell"+str(i))
formats = []
for i in range(0,self.numberofcells):
formats.append("|S10")
ndtype = {'names':names, 'formats':formats}
self.cells = np.zeros((500,6), dtype = ndtype)
return
def AircraftCell(self,cells,time):
if floor(time) >= self.resettime:
bs.sim.hold()
self.reset()
self.resettime = self.resettime + self.deltaresettime
self.iteration = self.iteration + 1
filedata = settings.log_path + "/coca_20120727-78am-1hour.npy"
# self.cellPlot(traf)
# np.save(filedata,self.cocametric)
bs.sim.op()
bs.traf.cell = []
for i in range(bs.traf.ntraf):
lat = bs.traf.lat[i]
lon = bs.traf.lon[i]
fl = bs.traf.alt[i]/ft
cellN = self.findCell(cells,lat,lon,fl)
if cellN > 0:
bs.traf.cell = np.append(bs.traf.cell, cellN)
name = 'cell'+str(cellN)
index = np.where(bs.traf.id[i] == self.cells[name][:,[0]])[0]
if len(index) != 1:
j = 0
for j in range(0,len(self.cells[name])):
if self.cells[name][j][0] == "":
break
self.cells[name][j][0] = bs.traf.id[i]
self.cells[name][j][1] = time
self.cells[name][j][2] = bs.traf.ahdg[i]
self.cells[name][j][3] = eas2tas(bs.traf.selspd[i],bs.traf.selalt[i])/kts
self.cells[name][j][4] = bs.traf.selvs[i]/fpm
self.cells[name][j][5] = time
if len(index) == 1:
createtime = float(self.cells[name][index[0]][5])
self.cells[name][index[0]][1] = str(time - createtime)
# self.newaircraft['callsign'][i] = bs.traf.id[i]
# self.newaircraft['cellnumber'][i] =
return
class metric_HB():
def __init__(self,area):
self.initiallat = area[3][0]
self.initiallon = area[3][1]
self.dist_range = 5.0 #nm
self.alt_range = 1000.0 #ft
self.t_cpa = 0
self.dist_cpa = 0
self.spd = np.array([])
self.lat = np.array([])
self.lon = np.array([])
self.pos = np.array([])
self.trk = 0
self.alt_dif = 0
self.alt = 0
self.id = []
self.complexity = defaultdict(lambda:defaultdict(int))
self.rel_trk = np.array([])
self.step = -1
self.id_previous = []
self.headings = []
self.headings_previous = np.array([])
self.doubleconflict = 0
self.ntraf = 0
self.compl_ac = 0
self.time_lookahead = 1800 #seconds
self.selected_area = ([area[0][0],area[0][1]],[area[1][0],area[1][1]],[area[2][0],area[2][1]],[area[3][0],area[3][1]])
return
def selectTraffic(self):
traf_selected_lat = np.array([])
traf_selected_lon = np.array([])
traf_selected_alt = np.array([])
traf_selected_tas = np.array([])
traf_selected_trk = np.array([])
traf_selected_ntraf = 0
# RECTANGLE AREA
# for i in range(0,bs.traf.ntraf):
# if nx.pnpoly(bs.traf.lat[i],bs.traf.lon[i],self.selected_area) == 1:
# traf_selected_lat = np.append(traf_selected_lat,bs.traf.lat[i])
# traf_selected_lon = np.append(traf_selected_lon,bs.traf.lon[i])
# traf_selected_alt = np.append(traf_selected_alt,bs.traf.alt[i])
# traf_selected_tas = np.append(traf_selected_tas,bs.traf.tas[i])
# traf_selected_trk = np.append( traf_selected_trk,bs.traf.trk[i])
# traf_selected_ntraf = traf_selected_ntraf + 1
# CIRCLE AREA (FIR Circle)
for i in range(0,bs.traf.ntraf):
dist = latlondist(bs.sim.metric.fir_circle_point[0],\
bs.sim.metric.fir_circle_point[1],\
bs.traf.lat[i],bs.traf.lon[i])
if dist/nm < bs.sim.metric.fir_circle_radius:
traf_selected_lat = np.append(traf_selected_lat,bs.traf.lat[i])
traf_selected_lon = np.append(traf_selected_lon,bs.traf.lon[i])
traf_selected_alt = np.append(traf_selected_alt,bs.traf.alt[i])
traf_selected_tas = np.append(traf_selected_tas,bs.traf.tas[i])
traf_selected_trk = np.append( traf_selected_trk,bs.traf.trk[i])
traf_selected_ntraf = traf_selected_ntraf + 1
return traf_selected_lat,traf_selected_lon,traf_selected_alt,traf_selected_tas,traf_selected_trk,traf_selected_ntraf
def applymetric(self):
time1 = time()
bs.sim.hold()
self.doubleconflict = 0
# relative pos x and pos y
self.step = self.step + 1
self.pos = np.array([])
self.lat = np.array([])
self.lon = np.array([])
self.id = []
self.alt_dif = 0
traf_selected_lat,traf_selected_lon,traf_selected_alt,traf_selected_tas,traf_selected_trk,traf_selected_ntraf = self.selectTraffic()
[self.rel_trk, self.pos] = geo.qdrdist_matrix(self.initiallat,self.initiallon,np.mat(traf_selected_lat),np.mat(traf_selected_lon))
# self.lat = np.append(self.lat,traf.lat)
# self.lon = np.append(self.lon,traf.lon)
self.id = bs.traf.id
# Position x and y wrt to initial position
self.pos = np.mat(self.pos)
anglex = np.cos(np.radians(90-self.rel_trk))
angley = np.sin(np.radians(90-self.rel_trk))
self.posx = np.mat(np.array(self.pos) * np.array(anglex)) #nm
self.posy = np.mat(np.array(self.pos) * np.array(angley)) #nm
self.lat = traf_selected_lat
self.lon = traf_selected_lon
self.alt = np.mat(traf_selected_alt/ft)
self.spd = traf_selected_tas/nm #nm/s
self.trk = traf_selected_trk
self.ntraf = traf_selected_ntraf
self.alt_dif = self.alt-self.alt.T
# Vectors CPA_dist and CPA_time
self.apply_twoCircleMethod()
time2 = time()
print("Time to Complete Calculation: " + str(time2-time1))
bs.sim.op()
return
def rel_matrixs(self):
self.alt_dif = self.alt-self.alt.T
# speeds
hdgx = np.cos(np.radians(90-self.trk))
hdgy = np.sin(np.radians(90-self.trk))
spdu = np.mat(self.spd * hdgx.T).T #nm/s
spdv = np.mat(self.spd * hdgy.T).T #nm/s
# distances pos and spd
distx = np.array(self.posx.T - self.posx) #nm
disty = np.array(self.posy.T - self.posy) #nm
distu = (np.array(spdu.T - spdu)) #nm/s
distv = (np.array(spdv.T - spdv)) #nm/s
# predicted time to CPA
self.t_cpa = -(distu*distx+distv*disty)/ \
(distu*distu+distv*distv+np.array(np.eye(distu[:,0].size)))
# predicted distance to CPA
relcpax = self.t_cpa*np.array(spdu.T)
relcpay = self.t_cpa*np.array(spdv.T)
cpax = self.posx.T + relcpax
cpay = self.posy.T + relcpay
distcpax = np.array(cpax-cpax.T)
distcpay = np.array(cpay-cpay.T)
self.dist_cpa = (distcpax**2+distcpay**2)**0.5
return
def apply_altfilter(self,S0):
condition = abs(self.alt_dif)<self.alt_range
# self.t_cpa = np.where(condition,self.t_cpa, np.nan)
# self.dist_cpa = np.where(condition,self.dist_cpa, np.nan)
S0 = np.where(condition,S0,np.nan)
return S0
def apply_distfilter(self,H0):
condition = self.dist_cpa<self.dist_range*3
self.dist_cpa = np.where(condition,self.dist_cpa,np.nan)
self.t_cpa = np.where(condition,self.t_cpa,np.nan)
H0 = np.where(condition,H0,np.nan)
return H0
def apply_timefilter(self):
condition = self.t_cpa>0#(self.t_cpa<(self.time_range+20) * (self.t_cpa>0))
self.t_cpa = np.where(condition,self.t_cpa,np.nan)
self.dist_cpa = np.where(condition,self.dist_cpa,np.nan)
return
def apply_before_filter(self,S0,Va):
Vb = Va.T
Va_Vb = np.add(np.abs(Va),np.abs(Vb))
condition1 = S0>0
condition2 = np.divide(S0,Va_Vb)>self.time_lookahead #seconds
condition = np.multiply(condition1,condition2)
condition = np.invert(condition)
S0 = np.where(condition,S0,np.nan)
return S0
def merge(self,times):
if len(times) > 0:
saved = list(times[0])
for st, en in sorted([(t) for t in times]):
if st <= saved[1]:
saved[1] = max(saved[1], en)
else:
yield list(saved)
saved[0] = st
saved[1] = en
yield list(saved)
else:
yield list(times)
def apply_twoCircleMethod(self):
Va = np.mat(self.spd)
Ha = np.radians(self.trk)
Vb = np.add(Va,0.0000001)
VaVa = np.multiply(Va,Va)
Hb = Ha
[H0,S0] = geo.qdrdist_matrix(np.mat(self.lat),np.mat(self.lon),np.mat(self.lat),np.mat(self.lon))
S0 = np.where(S0 > 0, S0, np.nan)
S0 = self.apply_before_filter(S0,Va)
S0 = self.apply_altfilter(S0)
H0 = np.radians(H0.T)
R_S0 = np.divide(self.dist_range,S0)
arcsin = np.arcsin(R_S0)
ha_new11,ha_new21,ha_new12,ha_new22,t1d1,t1d2,t2d1,t2d2 = self.calc_angles(Vb,Hb,VaVa,H0,arcsin,S0)
R_S0 = None
arcsin = None
ha_1 = np.degrees(ha_new11)
ha_3 = np.degrees(ha_new21)
ha_2 = np.degrees(ha_new12)
ha_4 = np.degrees(ha_new22)
t1 = t1d1
t2 = t1d2
t3 = t2d1
t4 = t2d2
ha_new11 = None
ha_new21 = None
ha_new12 = None
ha_new22 = None
t1d1 = None
t1d2 = None
t2d1 = None
t2d2 = None
ha_1,ha_2,ha_3,ha_4,t1,t2,t3,t4 = self.conditions(ha_1,ha_2,ha_3,ha_4,t1,t2,t3,t4,Va,Vb,Ha,Hb)
## Condition where S0 < self.dist_range
condition = np.multiply(S0<self.dist_range,S0>0)
ac_angles = {}
ac_score = {}
for k in range(0,self.ntraf):
ac_angles[str(k)] = []
ac_score[str(k)] = 0
for l in range(0,self.ntraf):
if not np.isnan(ha_1[l,k]) and not np.isnan(ha_2[l,k]):
ac_angles[str(k)].append((ha_1[l,k],ha_2[l,k]))
if not np.isnan(ha_3[l,k]) and not np.isnan(ha_4[l,k]):
ac_angles[str(k)].append((ha_3[l,k],ha_4[l,k]))
ac_angles[str(k)] = sorted(ac_angles[str(k)])
ac_angles[str(k)] = list(self.merge(ac_angles[str(k)]))
if len(ac_angles[str(k)][0]) > 0:
for z in range(0,len(ac_angles[str(k)])):
ac_angle180min = ((self.trk[k]+180-90)%360-180)
ac_angle180max = ((self.trk[k]+180+90)%360-180)
ac_angles_st180 = ((ac_angles[str(k)][z][0]+180)%360-180)
ac_angles_en180 = ((ac_angles[str(k)][z][-1]+180)%360-180)
ac_angle360min = (self.trk[k]+360-90)%360
ac_angle360max = (self.trk[k]+360+90)%360
ac_angles_st360 = (ac_angles_st180+360)%360
ac_angles_en360 = (ac_angles_en180+360)%360
if ac_angle180min<90 and ac_angle180min>-90:
if ac_angles_st180 < ac_angle180min:
ac_angles[str(k)][z][0] = ac_angle180min
else:
if ac_angles_st360 < ac_angle360min:
ac_angles[str(k)][z][0] = ac_angle180min
if ac_angle180max < 90 and ac_angle180max > -90:
if ac_angles_en180 > ac_angle180max:
ac_angles[str(k)][z][-1] = ac_angle180max
else:
if ac_angles_en360 > ac_angle360max:
ac_angles[str(k)][z][-1] = ac_angle180max
if (ac_angles_st180 < ac_angle180min and ac_angles_en180 < ac_angle180min) or (ac_angles_st360 < ac_angle360min and ac_angles_en360 < ac_angle360min):
ac_angles[str(k)][z] = [np.nan,np.nan]
# Complexity Score
if ac_angles[str(k)][z][-1]<90 and ac_angles[str(k)][z][-1]>-90:
ac_score[str(k)] = ac_score[str(k)] + (ac_angles[str(k)][z][-1]-ac_angles[str(k)][z][0])/180
else:
ac_score[str(k)] = ac_score[str(k)] + (ac_angles[str(k)][z][-1]+360-ac_angles[str(k)][z][0])/180
if True in condition[k]:
ac_score[str(k)] = 1
if np.isnan(ac_score[str(k)]):
ac_score[str(k)] = 0
ac_totalscore = sum(ac_score.values())
self.complexity[self.step][0] = ac_totalscore #/ self.ntraf
self.complexity[self.step][1] = ac_totalscore / max(1,self.ntraf)
print("Complexity per Aircraft: " + str(self.complexity[self.step][1]))
return
def calc_angles(self,Vb,Hb,VaVa,H0,arcsin,S0):
wx = np.multiply(Vb,np.sin(Hb))
wy = np.multiply(Vb,np.cos(Hb))
wxwx = np.multiply(wx,wx)
wywy = np.multiply(wy,wy)
wxwx_wywy = np.add(wxwx,wywy)
a = np.subtract(wxwx_wywy.T,VaVa)
H0_arcsin = np.subtract(H0,arcsin)
xc1 = np.multiply(S0,np.sin(H0_arcsin))
yc1 = np.multiply(S0,np.cos(H0_arcsin))
xc1xc1 = np.multiply(xc1,xc1)
yc1yc1 = np.multiply(yc1,yc1)
a = np.where(a!=0,a,np.nan)
a = np.add(a,0.00000000001)
b1 = np.add(2*np.multiply(xc1,wx.T),2*np.multiply(yc1,wy.T))
c1 = np.add(xc1xc1,yc1yc1)
b1b1 = np.multiply(b1,b1)
d1 = np.subtract(b1b1,4*np.multiply(a,c1))
c1 = None
b1b1 = None
xc1xc1 = None
yc1yc1 = None
H0_arcsin = None
a_2 = np.multiply(a,2)
conditiond1 = d1<0
conditiond1 = np.invert(conditiond1)
d1 = np.where(conditiond1,d1,np.nan)
t01d1 = np.divide(np.subtract(-b1,np.sqrt(d1)),a_2)
t02d1 = np.divide(np.add(-b1,np.sqrt(d1)),a_2)
t1d1 = np.minimum(t01d1,t02d1)
t2d1 = np.maximum(t01d1,t02d1)
xpt1d1 = np.add(xc1,np.multiply(wx.T,t1d1))
xpt2d1 = np.add(xc1,np.multiply(wx.T,t2d1))
ypt1d1 = np.add(yc1,np.multiply(wy.T,t1d1))
ypt2d1 = np.add(yc1,np.multiply(wy.T,t2d1))
xc1 = None
yc1 = None
H0_arcsin = np.add(H0,arcsin)
xc2 = np.multiply(S0,np.sin(H0_arcsin))
yc2 = np.multiply(S0,np.cos(H0_arcsin))
xc2xc2 = np.multiply(xc2,xc2)
yc2yc2 = np.multiply(yc2,yc2)
wxT = wx.T
wyT = wy.T
xc2_wx = np.multiply(xc2,wxT)
yc2_wy = np.multiply(yc2,wyT)
xc2_wx2 = np.multiply(xc2_wx,2)
yc2_wy2 = np.multiply(yc2_wy,2)
b2 = np.add(xc2_wx2,yc2_wy2)
c2 = np.add(xc2xc2,yc2yc2)
b2b2 = np.multiply(b2,b2)
d2 = np.subtract(b2b2,4*np.multiply(a,c2))
c2 = None
b2b2 = None
xc2xc2 = None
yc2yc2 = None
H0_arcsin = None
wxwx = None
wywy = None
wxwx_wywy = None
conditiond2 = d2<0
conditiond2 = np.invert(conditiond2)
d2 = np.where(conditiond2,d2,np.nan)
t01d2 = np.divide(np.subtract(-b2,np.sqrt(d2)),a_2)
t02d2 = np.divide(np.add(-b2,np.sqrt(d2)),a_2)
t1d2 = np.minimum(t01d2,t02d2)
t2d2 = np.maximum(t01d2,t02d2)
t01d1 = None
t02d1 = None
t01d2 = None
t02d2 = None
d1 = None
d2 = None
xpt1d2 = np.add(xc2,np.multiply(wx.T,t1d2))
xpt2d2 = np.add(xc2,np.multiply(wx.T,t2d2))
ypt1d2 = np.add(yc2,np.multiply(wy.T,t1d2))
ypt2d2 = np.add(yc2,np.multiply(wy.T,t2d2))
xc2 = None
yc2 = None
wx = None
wy = None
ha_new11 = np.arctan2(xpt1d1,ypt1d1)
ha_new21 = np.arctan2(xpt2d1,ypt2d1)
ha_new12 = np.arctan2(xpt1d2,ypt1d2)
ha_new22 = np.arctan2(xpt2d2,ypt2d2)
return ha_new11,ha_new21,ha_new12,ha_new22,t1d1,t1d2,t2d1,t2d2
def conditions(self,ha_1,ha_2,ha_3,ha_4,t1,t2,t3,t4,Va,Vb,Ha,Hb):
t1_nan = t1>0
t2_nan = t2>0
t3_nan = t3>0
t4_nan = t4>0
ha_1 = np.where(t1_nan,ha_1,np.nan)
ha_2 = np.where(t2_nan,ha_2,np.nan)
ha_3 = np.where(t3_nan,ha_3,np.nan)
ha_4 = np.where(t4_nan,ha_4,np.nan)
t1 = np.where(t1_nan,t1,np.nan)
t2 = np.where(t2_nan,t2,np.nan)
t3 = np.where(t3_nan,t3,np.nan)
t4 = np.where(t4_nan,t4,np.nan)
# condition: Va < Vb and all + t's
Va_Vb = Va < Vb
t1_t2 = np.multiply(t1_nan,t2_nan)
t3_t4 = np.multiply(t3_nan,t4_nan)
t_allplus = np.multiply(t1_t2,t3_t4)
condition = np.multiply(Va_Vb,t_allplus)
condition = np.invert(condition)
ha_3new = np.where(condition,ha_3,ha_4)
t3new = np.where(condition,t3,t4)
ha_4new = np.where(condition,ha_4,ha_3)
t4new = np.where(condition,t4,t3)
# condition Va < Vb and t1,t3 negatif
t1_neg = np.invert(t1_nan)
t3_neg = np.invert(t3_nan)
t1_t3_neg = np.multiply(t1_neg,t3_neg)
condition = np.multiply(Va_Vb,t1_t3_neg)
condition = np.invert(condition)
ha_3 = np.where(condition,ha_3new,ha_4new)
t3 = np.where(condition,t3new,t4new)
ha_4 = np.where(condition,ha_4new,ha_2)
t4 = np.where(condition,t4new,t2)
# condition Va < Vb and t2,t4 negatif
t2_neg = np.invert(t2_nan)
t4_neg = np.invert(t4_nan)
t2_t4_neg = np.multiply(t2_neg,t4_neg)
condition = np.multiply(Va_Vb,t2_t4_neg)
condition = np.invert(condition)
ha_2 = np.where(condition,ha_2,ha_3)
t2 = np.where(condition,t2,t3)
# TBD More than 90-degree turns!
Ha = np.degrees(Ha)
Hb = np.degrees(Hb)
# Lookahead time
t1_lht = t1 > self.time_lookahead
t2_lht = t2 > self.time_lookahead
t1_t2_lht = np.multiply(t1_lht,t2_lht)
t1_t2_lht = np.invert(t1_t2_lht)
t3_lht = t3 > self.time_lookahead
t4_lht = t4 > self.time_lookahead
t3_t4_lht = np.multiply(t3_lht,t4_lht)
t3_t4_lht = np.invert(t3_t4_lht)
ha_1 = np.where(t1_t2_lht,ha_1,np.nan)
ha_2 = np.where(t1_t2_lht,ha_2,np.nan)
ha_3 = np.where(t3_t4_lht,ha_3,np.nan)
ha_4 = np.where(t3_t4_lht,ha_4,np.nan)
t1 = np.where(t1_t2_lht,t1,np.nan)
t2 = np.where(t1_t2_lht,t2,np.nan)
t3 = np.where(t3_t4_lht,t3,np.nan)
t4 = np.where(t3_t4_lht,t4,np.nan)