-
Notifications
You must be signed in to change notification settings - Fork 2
/
pp4duav.py
1758 lines (1572 loc) · 78.5 KB
/
pp4duav.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 time
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d as plt3d
from queue import PriorityQueue
from pandas import DataFrame, ExcelWriter, read_excel, read_csv, concat
from typing import Iterable, Literal, Generator, overload, final
from pathlib import Path
from argparse import ArgumentParser
__all__ = 'ID', 'PathPlanner', 'TaskAssigner'
class ID:
__slots__ = (
'src', 'dst', 'mode', 'content', 'priority', 'type', 'weight', 'mode_abbr',
'mode_resolve', 'time', 'consumption', 'turn_sum', 'height_variance'
)
src: tuple[int] | int | str
dst: tuple[int] | int | str
mode: str
content: str
priority: str
type: tuple[str]
weight : int | float
mode_abbr: dict[str, str]
mode_resolve: dict[str, str]
time: int | float
consumption: int | float
turn_sum: float
height_variance: float
def __new__(
cls,
src: tuple[int] | int | str,
dst: tuple[int] | int | str,
type: str | tuple[str] = ('empty', 'normal'),
weight: int | float = 0,
mode: Literal['efficiency', 'economy', 'balanced', 'default'] = 'default'):
self = object.__new__(cls)
self.mode_abbr = {'efficiency': 'E', 'economy': 'C', 'balanced': 'B', 'default': '0'}
self.mode_resolve = {'E': 'efficiency', 'C': 'economy', 'B': 'balanced', '0': 'default'}
self.src = src[:2] if isinstance(src, tuple) else src
self.dst = dst[:2] if isinstance(dst, tuple) else dst
self.mode = mode if mode in self.mode_abbr else self.mode_resolve.get(mode, 'default')
self.content = type[0] # empty, regular, valueable, special
self.priority = type[1] # normal, express, urgent
self.type = (self.content.upper()[0], self.priority.upper()[0])
self.weight = weight
self.time = self.consumption = self.turn_sum = self.height_variance = 0
return self
@classmethod
def from_str(cls, __str: str):
"""
Decode string id generated by PathPlanner, retrun cls
"""
content = {'E': 'empty', 'R': 'regular', 'V': 'valueable', 'S': 'special'}
priority = {'N': 'normal', 'E': 'express', 'U': 'urgent'}
tw, src, dst, mode = __str.split('-')
args = (content[tw[0]], priority[tw[1]]), int(tw[2:]) / 100, mode
if len(src) == 6 and len(dst) == 6:
src, dst = (int(src[:3]), int(src[3:])), (int(dst[:3]), int(dst[3:]))
else:
src = int(src) if src.isnumeric() else src
dst = int(dst) if dst.isnumeric() else dst
return cls.__new__(ID, src, dst, *args)
@classmethod
def reverse(cls, __id):
return cls.__new__(ID, __id.dst, __id.src, __id.t, __id.weight, __id.mode)
@property
def t(self):
return self.content, self.priority
def merge_data(self, *args):
'''merge flight data: `turn_sum`, `height_variance`, `time`, `consumption`'''
self.turn_sum, self.height_variance, self.time, self.consumption = args
return self
def __str__(self) -> str:
s = "{:03}{:03}".format(*self.src) if isinstance(self.src, tuple) else self.src
d = "{:03}{:03}".format(*self.dst) if isinstance(self.dst, tuple) else self.dst
return "{}{}{:04d}-{}-{}-{}".format(
*self.type, round(self.weight*100), s, d, self.mode_abbr[self.mode])
def __repr__(self):
return f"{self.__class__.__module__}.{self.__class__.__qualname__}({self})"
def __eq__(self, other):
return str(other) == self.__str__() \
if isinstance(other, ID) else str(other) == self.__str__()
def __lt__(self, other):
return str(other)[:-2] == self.__str__()[:-2] if isinstance(other, ID) \
else str(other)[:-2] == self.__str__()[:-2]
def __hash__(self):
return hash(repr(self).encode())
class PathPlanner(object):
'''
Parameters
----------
environment: `DataFrame`, original DEM map data
danger_area: `DataFrame`, a mapping of DEM map defining danger area with a ratio
resolution: `int`, shows the accuracy of the map
pos_map: `DataFrame`, for src and dst abbreviation lookup
session: `str`, session name for data saving or locating
'''
def __init__(
self,
environment: DataFrame,
danger_area: DataFrame | None = None,
pos_map: DataFrame | None = None,
resolution: int = 5,
session: str = time.strftime(r'%m%d%H%M%S')):
self.res = resolution
self.env = environment
self.da = {} if danger_area is None else \
dict(((int(x), int(y)), da) for x, y, da in danger_area.values)
self.session = session
self.mode_refer = 'efficiency', 'economy', 'balanced', 'default'
# pos_map = read_csv('TD.csv', index_col=0, header=0).fillna(0).astype('int')
self.pos_map = {}
if pos_map is not None:
t, d = [], []
for idx in pos_map.index:
(d if str(idx).isnumeric() else t).append(idx)
t = pos_map.loc[t, ['x', 'y']]
d = pos_map.loc[d]
self.terminal = dict((k, (x, y)) for k, x, y in t.reset_index().values)
self.distributor = dict((int(k), (x, y)) for k, x, y, _, _ in d.reset_index().values)
self.t2d = dict((k, tuple(int(v) for v in v.index)) for k, v in zip(t.index, \
[d.loc[np.any([d.iloc[:,2] == x+1, d.iloc[:,3] == x+1], axis=0)] for x in range(len(t))]))
self.d2t = dict((int(kv[0]), str().join([chr(64 + v) if isinstance(v, int) else v if \
isinstance(v, str) else '' for v in kv[1:]]) ) for kv in d.iloc[:,2:].reset_index().values)
self.pos_map.update(self.terminal)
self.pos_map.update(self.distributor)
self.__partition = {}
self.__children = {}
self.maxx, self.maxy = self.env.shape
# flight dist, cargo weight, danger ratio
gw0 = lambda w: 1 if w < 0.5 else (w - 0.5) ** 2 + 1
gw1 = lambda w: 0.1 if w < 0.125 else 0.8 * w if w < 1.5 else (w - 1.1) ** 2 + 1.04
self.g_kwargs = {
'efficiency': {'ratio': (lambda w: 1.6 / gw0(w), lambda w: 1.4 * gw1(w) + 1, 3)},
'economy': {'ratio': (lambda w: 1.2 / gw0(w), lambda w: 1.8 * gw1(w) + 1, 5)},
'balanced': {'ratio': (lambda w: 1.5 / gw0(w), lambda w: 1.5 * gw1(w) + 1, 4)}}
# horizontal ratio, vertical ratio
self.h_kwargs = {
'efficiency': {'r1': 6, 'r2': 12},
'economy': {'r1': 4, 'r2': 16},
'balanced': {'r1': 5, 'r2': 14}}
self.cost_ratio = {'efficiency': 0.5, 'economy': 0.7,'balanced': 0.6, 'default': 0.5}
self.path_analysis_refer = (
'id', 'srcX', 'srcY', 'dstX', 'dstY', 'time_start', 'time_elapse', 'program_loop',
'program_closed', 'cost_adj', 'cost_ratio', 'path_length', 'path_nodes', 'flight_turn_sum',
'flight_height_variance', 'flight_time', 'flight_consumption')
self.path_nodes_refer = ('x','y','z','dist')
self.returns = {-2: 'skipped', -1: 'unreach', 0: 'completed', 1: 'toplimit', 2: 'timeout'}
self.path_analysis = DataFrame(columns=self.path_analysis_refer[1:])
self.path_nodes = {}
self.success = []
self.failed = set()
'''lambda function predef'''
self.mid_pos = lambda x, y: (round((x[0] + y[0]) / 2), round((x[1] + y[1]) / 2), round((x[2] + y[2]) / 2))
self.not_near = lambda x, y, z_step: \
abs(x[0] - y[0]) > 1 or abs(x[1] - y[1]) > 1 or abs(x[2] - y[2]) > z_step
def __len__(self):
return len(self.path_analysis)
def save(self, save: Path | str = Path(), only_new: bool = False):
file = Path(save) / Path(f'data_{self.session}.xlsx') if Path(save).is_dir() else save
with ExcelWriter(file, engine='openpyxl', mode='w') as file:
output = self.path_analysis.reset_index()
if only_new:
index = output['id'].isin(self.success)
output.loc[index].to_excel(file, 'Summary', index=False)
for k in self.success:
self.path_nodes[k].to_excel(file, str(k), index=False)
else:
output.to_excel(file, 'Summary', index=False)
for k, v in self.path_nodes.items():
v.to_excel(file, str(k), index=False)
def load(self, load: Path | str = None, as_new: bool = False):
data = read_excel(Path(load if load else f'data_{self.session}.xlsx'), sheet_name=None)
data['Summary'].set_index('id', inplace=True)
data['Summary'].index = data['Summary'].index.map(ID.from_str)
if as_new:
self.success.extend(data['Summary'].index)
self.path_analysis = concat([data['Summary'], self.path_analysis])
self.path_nodes.update((k, data[str(k)]) for k in data['Summary'].index)
@overload
def plan(
self,
src: tuple[int],
dst: tuple[int],
*,
init_alt: int | float = 10,
max_alt: int | float = 100,
min_alt: int | float = 5,
z_step: int = 2,
danger_threshold: float | None = 0.35,
loop_limit: int = 0,
time_limit: float = 0,
skip_planned: bool = True,
reverse: bool = False,
visualize: bool = True,
view_pos: bool = True,
show_stat: bool = True,
mode: Literal['efficiency', 'economy', 'balanced', 'default'] = 'default',
**kwargs) -> tuple[int, ID]:
"""
Path Planner main function
-----
Input plan parameters by src and dst position like (x,y,z) or (x,y) in `tuple[int]`
"""
...
@overload
def plan(
self,
id: str | ID,
*,
init_alt: int | float = 10,
max_alt: int | float = 100,
min_alt: int | float = 5,
z_step: int = 2,
danger_threshold: float | None = 0.35,
loop_limit: int = 0,
time_limit: float = 60,
skip_planned: bool = True,
reverse: bool = False,
visualize: bool = False,
view_pos: bool = False,
show_stat: bool = False,
**kwargs) -> tuple[int, ID]:
"""
Path Planner main function
-----
Input plan parameters by id in `str` or `ID`:
cargo type, weight - source - destination - plannning mode
(`2 caps` `4d in 10g`-`3d`-`3d`-`1d`)
Here's an example id of a regular, normal cargo weighing 940g
from (2, 12) to (35, 95), path planned in default mode (0):
>>> example_id = r'RN0094-002012-035095-0'
>>> ID.from_str(example_id)
pp4duav.ID(RN0094-002012-035095-0)
type, weight, mode will be overwritten by kwargs if given.
"""
...
@final
def plan(self, *args, **kwargs) -> tuple[int, ID]:
#############################
# coordinate, env, id check #
#############################
init_alt = kwargs.setdefault('init_alt', 10)
max_alt = kwargs.pop('max_alt', 100)
min_alt = kwargs.pop('min_alt', 5)
z_step = kwargs.pop('z_step', 2)
dt = kwargs.pop('danger_threshold', 0.35)
loop_limit = kwargs.pop('loop_limit', 0)
if len(args) == 1 or kwargs.get('id'):
id = kwargs.pop('id') if kwargs.get('id') else args[0]
if isinstance(id, str):
id = ID.from_str(id)
elif not isinstance(id, ID):
raise TypeError
# skip planned path
src, dst = id.src, id.dst
if 'mode' in kwargs:
id.mode = kwargs.pop('mode')
if 'type' in kwargs:
id.content, id.priority = kwargs.pop('type')[:2]
id.type = (id.content.upper()[0], id.priority.upper()[0])
if 'weight' in kwargs:
id.weight = kwargs.pop('weight')
time_limit = kwargs.pop('time_limit', 300)
visualize = kwargs.pop('visualize', False)
view_pos = kwargs.pop('view_pos', False)
show_stat = kwargs.pop('show_stat', False)
elif len(args) == 2 or (kwargs.get('src') and kwargs.get('dst')):
src, dst = args if len(args) == 2 else (kwargs.pop('src'), kwargs.pop('dst'))
mode = kwargs.pop('mode', 'default')
type = kwargs.pop('type', ('regular','normal') if 'weight' in kwargs else ('empty','normal'))
weight = kwargs.pop('weight', 0)
id = ID(src, dst, type, weight, mode)
# skip planned path
time_limit = kwargs.pop('time_limit', 0)
visualize = kwargs.pop('visualize', True)
view_pos = kwargs.pop('view_pos', True)
show_stat = kwargs.pop('show_stat', True)
else:
raise ValueError('init parameter error')
reverse = kwargs.pop('reverse', False)
if kwargs.pop('skip_planned', True):
if id in self.path_nodes:
return 0, id.merge_data(*self.path_analysis.loc[id].iloc[-4:])
elif kwargs.pop('get', False):
if not isinstance(src, tuple):
try:
src = self.pos_map[src]
except KeyError:
ValueError("src pos invalid")
if not isinstance(dst, tuple):
try:
dst = self.pos_map[dst]
except KeyError:
ValueError("dst pos invalid")
group = (src[0], src[1], dst[0], dst[1]), (dst[0], dst[1], src[0], src[1])
for p in range(2):
try:
match_id = self.path_analysis.groupby(
['srcX', 'srcY', 'dstX', 'dstY']).get_group(group[p])
match_id = match_id.loc[match_id.index.map(lambda x: x.mode) == id.mode]
result = self.path_nodes[(match_id.index.to_series().map(
lambda x: x.weight) - id.weight).abs().idxmin()].to_numpy()
if p:
result = result[::-1]
t = result[-1,3]
for p in range(len(result)):
result[p,3], t = t, result[p,3]
flag = 0
match_id = True
break
except KeyError:
flag = -2
match_id = False
if flag:
self.failed.add(id.reverse(id) if reverse else id)
else:
flight_data = self.flight_analysis(result, id, **kwargs)
id.merge_data(*flight_data)
if reverse:
src, dst = dst, src
self.path_analysis.loc[id] = [
*src[:2], *dst[:2], 0, 0, 0, 0, 0, 0, result[:,3].sum(), len(result), *flight_data]
self.path_nodes[id] = DataFrame(result, columns=self.path_nodes_refer)
self.success.append(id)
return flag, id
if reverse:
if id.reverse(id) in self.failed:
return -2, id
elif id in self.failed:
return -2, id
if id.type[0] == 'E' or id.weight == 0:
if not (id.type[0] == 'E' and id.weight == 0):
raise ValueError('empty cargo weight conflict')
if not isinstance(src, tuple):
try:
src = self.pos_map[src]
except KeyError:
ValueError("src pos invalid")
if len(src) == 2:
src = (*src, round(self.env.iloc[src[0], src[1]]+init_alt))
elif len(src) == 3:
src = (*src[:2], max(round(self.env.iloc[src[0], src[1]]+init_alt), src[2]))
else:
raise ValueError("src is not an (x, y) or (x, y, z) pos")
if not isinstance(dst, tuple):
try:
dst = self.pos_map[dst]
except KeyError:
ValueError("dst pos invalid")
if len(dst) == 2:
p = round(self.env.iloc[dst[0], dst[1]]+init_alt)
elif len(dst) == 3:
p = max(round(self.env.iloc[dst[0], dst[1]]+init_alt), dst[2])
else:
raise ValueError("dst is not an (x, y) or (x, y, z) pos")
dst = (*dst[:2], p + (p - src[2]) % z_step)
if reverse:
src, dst = dst, src
###################
# init parameters #
###################
skw = {'min_alt': min_alt, 'max_alt': max_alt, 'z_step': z_step}
gkw = self.g_kwargs.get(id.mode, {'default': True}).copy()
hkw = self.h_kwargs.get(id.mode, {'default': True}).copy()
dh = gkw['dh'] = hkw['dh'] = self.dist2d(src, dst, self.res)
if not (gkw.get('default') and hkw.get('default')):
gkw['rf'] = gkw['ratio'][0](id.weight)
gkw['rw'] = gkw['ratio'][1](id.weight)
gkw['rd'] = gkw['ratio'][2]
self.__partition = {0: [1], 1: (1, 0), 'pos': [src]}
self.__partition['k'] = np.inf if (dst[0]-src[0])==0 else (dst[1]-src[1])/(dst[0]-src[0])
time_limit = float(time_limit) if time_limit > 0 else np.inf
loop_limit = int(loop_limit) if loop_limit > 0 else np.inf
g_ratio = cost_ratio = kwargs.pop('cost_ratio', self.cost_ratio[id.mode])
cost_adj = kwargs.pop('cost_adj', 0.05)
if g_ratio >= 1 or g_ratio <= 0:
raise ValueError('valid cost ratio range is (0, 1), recommend [0.5, 0.6]')
h_ratio = 1 - g_ratio
openlist = PriorityQueue()
closed = {src: (np.inf, np.inf)} # init close list (dict to store g): {pos: g(n))}
h_value = self.h(src, src, src, dst, **hkw)
openlist.put((h_ratio * h_value, 0, h_value, src)) # init open list: (f(n), g(n), h(n), pos)
g = {src: 0} #init min g(n) dict
path = {src: src} # dict for pos to find its parent of lowest cost
time_s = time_e = time.time() # timer for efficiency analysis
count = g_adj = 0 # process loop and cost adj counter
###############
## main func ##
###############
while count < loop_limit:
count += 1
try:
_, g_value, h_value, pos = openlist.get(timeout=0.01)
except:
time_e = time.time()
flag = -1
break
'''break conditions, restrictions check every 500 loop'''
if self.__partition[0][0] < 0.2:
dr, _da = self.sight(pos, dst, **skw)
if dr <= dt and 1 not in _da:
path[dst] = path[pos] if pos == dst else pos
time_e = time.time()
flag = 0
break # reach destination
if count % 500 == 0:
time_e = time.time()
t = time_e - time_s
p = self.__partition[0][0]
if show_stat:
print("\r{4} {0:03.0f}% |{1}{2}| Elapsed {3:.0f}s".format(
(1-p)*100, str().join(['>' for _ in range(10-round(p*10))]),
str().join([' ' for _ in range(round(p*10))]), t, id), end=' ')
if t >= time_limit:
flag = 2
break # timeout
'''dynamic cost ratio adjust'''
while cost_adj and t > self.__partition[1][1] + 60 * cost_ratio:
p = self.__partition[1][0] - self.__partition[0][0]
if p <= 0.01:
if g_ratio > 0.45:
g_ratio -= cost_adj
h_ratio += cost_adj
g_adj += 1
time_limit += 60 * cost_ratio
elif g_ratio != cost_ratio and p > cost_adj:
g_ratio = cost_ratio
h_ratio = 1 - g_ratio
else:
self.__partition[1] = (p, int(t))
self.__partition[0] = self.__partition[0][:1]
self.__partition['pos'] = self.__partition['pos'][:1]
break
newlist = PriorityQueue()
while True:
try:
_, _g, _h, child = openlist.get(timeout=0.01)
newlist.put((g_ratio * _g + h_ratio * _h, _g, _h, child))
except:
openlist = newlist
break
self.__partition[1] = (self.__partition[1][0], int(t))
self.__partition[0] = self.__partition[0][:1]
while self.__partition['pos']:
child = self.__partition['pos'].pop()
_g, _h = closed.get(child)
openlist.put((g_ratio * _g + h_ratio * _h, _g, _h, child))
self.__partition['pos'].append(child)
break
'''g check and add to closed list'''
if closed.get(pos, (np.inf, 0))[0] <= g_value:
continue # searched pos in open or closed list
closed[pos] = (g_value, h_value)
'''get child nodes'''
children = self.children(pos, **skw)
if children[0] > dt or children[1] == 1:
continue
'''theta-star sight check'''
dr, da = self.sight(path[pos], pos, **skw)
if dr > dt or 1 in da:
parents = PriorityQueue() # sight blocked (collison or restricted area)
# check sight between pos and parent's parent
parent, depth = path[path[pos]], 0
while parent != src and depth <= 2:
dr, da = self.sight(parent, pos, **skw)
depth += 1
if dr <= dt and 1 not in da and self.not_near(parent, pos, z_step):
parents.put((closed[parent][0] + \
self.g(src, parent, pos, dst, da, path[parent], **gkw, **skw), parent, da))
else:
parent = path[parent]
# check sight between pos and parent path mid if not near
mid = self.mid_pos(path[path[pos]], path[pos])
dr, da = self.sight(mid, pos, **skw)
if dr <= dt and 1 not in da and self.not_near(mid, pos, z_step) \
and self.not_near(mid, path[pos], z_step) and self.not_near(mid, path[path[pos]], z_step):
parent = path.setdefault(mid, path[path[pos]])
if mid in closed:
g_value = closed[mid][0]
else:
g_value = closed[parent][0] + self.g(src, parent, mid, dst, \
self.sight(parent, mid, **skw)[1], path[parent], **gkw, **skw)
closed[mid] = (g_value, self.h(src, path[mid], mid, dst, **hkw))
parents.put((g_value + self.g(src, mid, pos, dst, da, path[mid], **gkw, **skw), mid, da))
else:
da = {children[1]: {pos}} if children[1] else dict()
for child in children[2]: # Priority Queue of (g(n), pos)
if child in closed: # search closed nearby min g(n) pos as new parent
parents.put((closed[child][0] + \
self.g(src, child, pos, dst, da, path[child], **gkw, **skw), child, da))
g_value, parent, da = parents.get(timeout=0.01) # min g(n) pos
try:
while True:
p = parent
while p != src:
if p != pos:
p = path[p]
else:
break
else:
break
g_value, parent, da = parents.get(timeout=0.01)
except:
continue
g[pos] = g_value
closed[pos] = (g_value, self.h(src, path[pos], pos, dst, **hkw))
path[pos] = parent
else:
parent = path[pos] # parent remain the same if sighted
'''search progress'''
p = sum(self.partition(src, path[pos], pos, dst)) / dh
if p < self.__partition[0][0]:
self.__partition[0].insert(0, p)
if pos in self.__partition['pos']:
self.__partition['pos'].remove(pos)
self.__partition['pos'].insert(0, pos)
else:
self.__partition[0].append(p)
if pos not in self.__partition['pos']:
self.__partition['pos'].append(pos)
'''child nodes search'''
rt = self.dist(path[parent], parent, self.res)
for child in children[2]:
arg = src, parent, child, dst
g_value = closed[parent][0] + self.g(*arg, da, path[parent], rt = rt, **gkw, **skw)
if g.get(child, np.inf) < g_value:
continue
g[child] = g_value
h_value = self.h(*arg, **hkw)
openlist.put((g_ratio * g_value + h_ratio * h_value, g_value, h_value, child))
p = parent
while p != src:
if child == p:
break
p = path[p]
else:
path[child] = parent
else:
flag = 1 # search loop limit
#############
## results ##
#############
match_id = kwargs.get('match_id')
# path found, retrace
if flag == 0:
result = [(*dst, self.dist(pos, dst, self.res))]
while pos != src:
dist = self.dist(path[pos], pos, self.res)
result.append((*pos, dist))
pos = path[pos]
result.append((*pos, 0))
result = np.array(result)
if reverse:
t = result[-1,3]
for p in range(len(result)):
result[p,3], t = t, result[p,3]
else:
result = result[::-1]
# match another planned id & path as if succeed
elif match_id:
group = (src[0], src[1], dst[0], dst[1]), (dst[0], dst[1], src[0], src[1])
for p in range(2):
try:
match_id = self.path_analysis.groupby(
['srcX', 'srcY', 'dstX', 'dstY']).get_group(group[p])
match_id = match_id.loc[match_id.index.map(lambda x: x.mode) == id.mode]
result = self.path_nodes[(match_id.index.to_series().map(
lambda x: x.weight) - id.weight).abs().idxmin()].to_numpy()
if p:
result = result[::-1]
t = result[-1,3]
for p in range(len(result)):
result[p,3], t = t, result[p,3]
flag = 0
match_id = True
break
except KeyError:
match_id = False
if show_stat:
print("\r>> {} {}, plan time {:.02f}s {}".format(
id, 'matched' if match_id else self.returns[flag], time_e-time_s,
f"cost adj * {g_adj}" if g_adj else " "))
if flag:
self.failed.add(id.reverse(id) if reverse else id)
# analysis, stat & visualize
else:
flight_data = self.flight_analysis(result, id, **kwargs)
id.merge_data(*flight_data)
# id srcX srcY dstX dstY time_start time_elapse program_loop program_closed
# cost_adj cost_ratio path_length path_nodes flight_turn_sum
# flight_height_variance flight_time flight_consumption
if reverse:
src, dst = dst, src
stat = [
*src[:2], *dst[:2], time.ctime(time_s)[11:19], time_e-time_s, count,
len(closed), g_adj, cost_ratio, result[:,3].sum(), len(result), *flight_data]
self.path_analysis.loc[id] = stat
self.path_nodes[id] = DataFrame(result, columns=self.path_nodes_refer)
self.success.append(id)
if visualize:
self.visualize(result, np.array(list(closed.keys())) if view_pos else [])
return flag, id
def flight_analysis(self, path: np.array, id: ID, **kwargs):
'''
kwargs
------
speed_limit: `float`, max cruise speed in m/s
avg_climb: `float`, average climb in m/s
avg_descent: `float`, average descent in m/s
avg_acc: `float`, average accelerate in m/s^2
avg_dec: `float`, average decelerate in m/s^2
power_v: `int`, vertical power in J/m
power_h: `int`, horizontal power in J/m
returns
-------
flight_turn_sum: `float`, sum of turn rad
flight_height_variance: `float`, standard deviation of path height (z)
flight_time: `float`, time elapsed during flight including airborn and landing
flight_consumption: `float`, power consumed during flight
'''
'''flight route preprocess'''
turn = [np.pi/2]
slope = [np.pi/2]
for i in range(1, len(path)-1):
a = (path[i] - path[i-1])[:3]
b = (path[i+1] - path[i])[:3]
t = np.dot(a[:2], b[:2]) / (np.linalg.norm(a[:2]) * np.linalg.norm(b[:2])) \
if a[:2].any() and b[:2].any() else 1
turn.append(round(np.arccos(t if t < 1 else 1), 4))
slope.append(np.arctan2(b[2]-a[2], np.sqrt((b[0]-a[0])**2 + (b[1]-a[1])**2)))
turn.append(np.pi/2)
slope.append(np.pi/2)
'''mode and type modificator'''
# type[0]: empty, regular, valueable, special
# type[1]: normal, express, urgent
m1 = {'E': 1.5, 'R': 1, 'V': 0.9, 'S': 0.8}
m2 = {'N': -1, 'E': 0, 'U': 2}
a_ratio, v_offset = m1[id.type[0]], m2[id.type[1]]
'''initialize parameters'''
max_speed = kwargs.get('speed_limit', 10) + v_offset
acc = kwargs.get('avg_acc', 5 if id.weight <= 0.5 else (5 - (0.4 * (id.weight - 0.5)) ** 2)) * a_ratio
dec = kwargs.get('avg_dec', - 1.1 * acc) * a_ratio
climb = kwargs.get('avg_climb', round(3 + np.sqrt(1 / (id.weight + 0.5)), 4)) + v_offset
descent = kwargs.get('avg_descent', - climb - 0.5) + v_offset
power_v = kwargs.get('power_v', lambda v: (- 18 + 2 * id.weight) * v + 370 + 35 * id.weight)
power_h = kwargs.get('power_h', lambda v: (- 8.8 + 2 * id.weight) * v + 156 + 2 * id.weight)
'''time and consumption caculation'''
v_turn = lambda angle: np.sqrt(9.80665 * kwargs.get('turn_radius', self.res) / np.tan(angle)) \
if -np.pi / 2 < angle < np.pi / 2 else 0
v, d = [0], []
for idx in range(1, len(path)):
d.append((path[idx - 1, 3] * abs(np.cos(slope[idx])), path[idx, 2] - path[idx - 1, 2]))
vt = round(v_turn(turn[idx]) / (id.weight - 1 if id.weight > 2 else 1), 6) if turn[idx] else max_speed
v.append(max_speed if vt > max_speed else vt)
d.append((path[-1, 3] * abs(np.cos(slope[-2])), path[-2, 3] - path[-1, 3]))
v.append(0)
stat = {'acc': [], 'con': [], 'dec': [], 'total': [], 'consume': []}
idx = 1
while idx < len(v):
flag = True
dist, height = d[idx-1]
v1, v0 = v[idx], v[idx-1]
dv = v1 - v0
#vertical only
if dist < self.res:
ta = tc = td = va = vd = 0
# same speed
elif dv == 0:
va = vd = (max_speed + v1) / 2
ddv = max_speed - v1
ta = ddv / acc
td = - ddv / dec
dd = (ta + td) * (ddv / 2 + v1)
if dd <= dist:
tc = (dist - dd) / max_speed
else:
tc = 0
ddv = np.sqrt(v1**2+2*dist/(1/acc+1/-dec))
va = vd = (ddv + v1) / 2
ddv -= v1
ta = ddv / acc
td = ddv / dec
# acc
elif dv > 0:
vf = 2*acc*dist+v0**2
vf = round(np.sqrt(vf if vf > 0 else 0), 6)
vd = 0
if vf > v1:
va = (max_speed + v0) / 2
if v1 == max_speed:
ta = (max_speed - v0) / acc
tc = (dist - (max_speed**2 - v0**2) / 2 / acc) / max_speed
td = 0
else:
ta = (max_speed - v0) / acc
td = (v1 - max_speed) / dec
dd = v0 * ta + 0.5 * acc * ta**2 + v1 * td + 0.5 * dec * td**2
if dd <= dist:
vd = (v1 + max_speed) / 2
tc = (dist - dd) / max_speed
else:
tc = 0
vf = round(np.sqrt((2*acc*dec*dist-acc*v1**2+dec*v0**2)/(dec-acc)), 6)
ta = vf - v0 / acc
td = v1 - vf / dec
va = (vf + v0) / 2
vd = (v1 + vf) / 2
elif vf == v1:
va = (vf + v0) / 2
ta = vf - v0 / acc
td = tc = 0
else:
va = (vf + v0) / 2
ta = vf - v0 / acc
td = tc = 0
v[idx] = vf
# dec
else:
vf = 2*dec*dist+v0**2
vf = round(np.sqrt(vf if vf > 0 else 0), 6)
if vf < v1:
ta = (max_speed - v0) / acc
td = (v1 - max_speed) / dec
dd = v0 * ta + 0.5 * acc * ta**2 + v1 * td + 0.5 * dec * td**2
if dd <= dist:
va = (v0 + max_speed) / 2
vd = (max_speed + v1) / 2
tc = (dist - dd) / max_speed
else:
tc = 0
vf = round(np.sqrt((2*acc*dec*dist-acc*v1**2+dec*v0**2)/(dec-acc)), 6)
ta = vf - v0 / acc
td = v1 - vf / dec
va = (v0 + vf) / 2
vd = (vf + v1) / 2
elif abs(vf - v1) <= 0.01:
td = v0 - vf / dec
vd = (vf + v0) / 2
ta = tc = va = 0
else:
v[idx-1] = round(np.sqrt(v1**2-2*dec*dist), 6)
flag = False
if height > 0:
_td = 0
_tc = height / climb
elif height < 0:
_tc = 0
_td = height / descent
else:
_tc = _td = 0
if flag:
stat['acc'].append((ta, va))
stat['con'].append((tc, max_speed))
stat['dec'].append((td, vd))
stat['total'].append(max([ta + tc + td, _tc, _td]))
stat['consume'].append(-height*power_v(-descent) if _td else height*power_v(climb) if _tc else 0)
idx += 1
else:
for k in stat.keys():
stat[k].pop()
idx -= 1
for k in ['acc', 'con', 'dec']:
stat['consume'].append(sum(t*v*power_h(v) for t, v in stat[k]))
return np.sum(turn[1:-1]), np.std(path[:,2]), sum(stat['total']), sum(stat['consume'])
def partition(self, *args) -> tuple[int, int]:
'''args: src, parent, pos, dst in env coordinates `tuple[int]`'''
(x1, y1, _), _, (x0, y0, _), (x2, y2, _) = args
args = ((x1, y1), (x0, y0), (x2, y2))
if args not in self.__partition:
k = self.__partition['k']
if k == 0:
d = abs(x2 - x0) * self.res, abs(y2 - y0) * self.res
elif k == np.inf:
d = abs(y2 - y0) * self.res, abs(x2 - x0) * self.res
else:
if y0 == k * (x0 - x1) + y1:
x, y = x0, y0
else:
x = (y0 - y1 + x0 / k + k * x1) / (1 / k + k)
y = k * (x - x1) + y1
d = self.dist2d((x,y), args[2], self.res), self.dist2d((x,y), args[1], self.res)
self.__partition[args] = d
return self.__partition[args]
@staticmethod
def ray(src: tuple[int], dst: tuple[int]):
return ([src, tuple((d - s) for s, d in zip(src, dst))])
@staticmethod
def dist2d(src: tuple[int], dst: tuple[int], res):
return np.sqrt((res*(dst[0]-src[0]))**2 + (res*(dst[1]-src[1]))**2)
@staticmethod
def dist(src: tuple[int], dst: tuple[int], res):
return np.sqrt((res*(dst[0]-src[0]))**2 + (res*(dst[1]-src[1]))**2 + (dst[2]-src[2])**2)
@staticmethod
def mandist(src: tuple[int], dst: tuple[int], res):
return res * abs(src[0]-dst[0]) + res * abs(src[1]-dst[1]) + abs(src[2]-dst[2])
@staticmethod
def opt_mandist(src: tuple[int], parent: tuple[int], pos: tuple[int], dst: tuple[int], res, r1, r2):
dx = abs(src[0]-dst[0])
dy = abs(src[1]-dst[1])
x = abs(pos[0]-dst[0]) / dx if dx else abs(pos[1]-dst[1]) / dy + 0.1
y = abs(pos[1]-dst[1]) / dy if dy else abs(pos[0]-dst[0]) / dx + 0.1
xy = x+y
z1, z2 = abs(pos[2]-dst[2]), abs(pos[2]-parent[2])
z = (z1 if z1<z2 else z2) if xy>0.2 else z1
return (r1*res*(x*abs(pos[0]-dst[0]) + y*abs(pos[1]-dst[1]))/xy if xy else 0) + r2*z
def g(self, *args, **kwargs):
'''
Cost Function
-------------
*args: src, parent, pos, dst in env coordinates `tuple[int]`
**kwargs: g function parameters
'''
if kwargs.get('default'):
return self.dist(*args[1:3], self.res)
_, parent, pos, _, da, t = args
d = self.dist(parent, pos, self.res)
h = abs(parent[2] - pos[2])
rf, rw, rd = kwargs['rf'], kwargs['rw'], kwargs['rd']
a, b = (parent[0] - t[0], parent[1] - t[1]), (pos[0] - parent[0], pos[1] - parent[1])
if np.any(a) and np.any(b):
rt = kwargs.get('rt', self.dist(parent, t, self.res))
t = np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
t = round(np.arccos(t if t < 1 else 1), 4) if t >= 0 else np.inf
else:
rt = 0
return rf * d + rw * h + (kwargs['dh'] / (rt + d) * t if rt else 0) + \
(sum((k*len(v)**rd) for k, v in da.items()) if da else 0)
def h(self, *args, **kwargs):
'''
Heuristic Function
------------------
*args: src, parent, pos, dst in env coordinates `tuple[int]`
**kwargs: h function parameters
'''
if kwargs.get('default'):
return self.mandist(*args[2:4], self.res)
return self.opt_mandist(*args, self.res, kwargs['r1'], kwargs['r2'],)
def children(self, pos: tuple[int], min_alt: int | float, max_alt: int | float, z_step: int):
'''Check collision and max altitude of nearby 26 child cells'''
if pos in self.__children:
return self.__children[pos]
__children = []
dr = 0
da = [0]
for x in range(pos[0]-1, pos[0]+2):
for y in range(pos[1]-1, pos[1]+2):
if (x, y) in self.da:
da.append(self.da[x, y])
for z in range(pos[2]-z_step, pos[2]+z_step*2, z_step):
if 0 <= x < self.maxx and 0 <= y < self.maxy:
ground = self.env.iloc[x, y]
if min_alt < z - ground < max_alt:
__children.append((x, y, z))
continue
dr += 1
try:
__children.remove(pos)
self.__children[pos] = dr/26, max(da), __children
except:
self.__children[pos] = 1, max(da), []
return self.__children[pos]
def sight(self, src: tuple, dst: tuple, **kwargs) -> tuple[float, dict[set]]:
'''
A method to check collision between source and destination:
src, dst: env coordinates in `tuple[int]`
kwargs: min_alt, max_alt, z_step for self.children()
returns danger ratio and danger area
'''
if self.dist(src, dst, self.res) <= self.res/2:
pos = round(src[0]), round(src[1]), round(src[2])
dr, da = self.children(pos, **kwargs)[:2]
return dr, {da: {pos}} if da else dict()
else:
pos = ((src[0] + dst[0]) / 2, (src[1] + dst[1]) / 2, (src[2] + dst[2]) / 2)
dr1, da1 = self.sight(dst, pos, **kwargs)
dr2, da2 = self.sight(src, pos, **kwargs)
for k, v in da2.items():
da1.setdefault(k, set()).union(v)
return dr1 if dr1 > dr2 else dr2, da1
@overload
def visualize(self): ...
@overload
def visualize(self, __path: np.ndarray, __pos: np.ndarray): ...
@overload
def visualize(self, __start: int, __stop: int): ...
def visualize(self, *args):
black = (1,1,1,0)
z = self.env.to_numpy().T / self.res
maxz = z.max().max()
radius = 0, max([self.maxx, self.maxy, ])
'''empty plt initialize'''
ax = plt.subplot(111, projection='3d')
ax.view_init(elev=90., azim=0.)
ax.clear()