forked from Open-MSS/MSS
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmpl_pathinteractor.py
1312 lines (1119 loc) · 54.8 KB
/
mpl_pathinteractor.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
# -*- coding: utf-8 -*-
"""
mslib.msui.mpl_pathinteractor
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interactive editing of Path objects on a Matplotlib canvas.
This module provides the following classes:
a) WaypointsPath and subclasses PathV, PathH and PathH-GC:
Derivatives of matplotlib.Path, provide additional methods to
insert and delete vertices and to find best insertion points for new
vertices.
b) PathInteractor and subclasses VPathInteractor and HPathInteractor:
Classes that implement a path editor by binding matplotlib mouse events
to a WaypointsPath object. Support for moving, inserting and deleting vertices.
The code in this module is inspired by the matplotlib example 'path_editor.py'
(http://matplotlib.sourceforge.net/examples/event_handling/path_editor.html).
For more information on implementing animated graphics in matplotlib, see
http://www.scipy.org/Cookbook/Matplotlib/Animations.
This file is part of MSS.
:copyright: Copyright 2008-2014 Deutsches Zentrum fuer Luft- und Raumfahrt e.V.
:copyright: Copyright 2011-2014 Marc Rautenhaus (mr)
:copyright: Copyright 2016-2023 by the MSS team, see AUTHORS.
:license: APACHE-2.0, see LICENSE for details.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import logging
import math
import numpy as np
import matplotlib.path as mpath
import matplotlib.patches as mpatches
from PyQt5 import QtCore, QtWidgets
from mslib.utils.coordinate import get_distance, find_location, latlon_points, path_points
from mslib.utils.units import units
from mslib.utils.thermolib import pressure2flightlevel
from mslib.msui import flighttrack as ft
from mslib.utils.loggerdef import configure_mpl_logger
mpl_logger = configure_mpl_logger()
def distance_point_linesegment(p, l1, l2):
"""Computes the distance between a point p and a line segment given by its
endpoints l1 and l2.
p, l1, l2 should be numpy arrays of length 2 representing [x,y].
Based on the dot product formulation from
'Subject 1.02: How do I find the distance from a point to a line?'
(from http://www.faqs.org/faqs/graphics/algorithms-faq/).
Special case: The point p projects to an extension of the line segment.
In this case, the distance between the point and the segment equals
the distance between the point and the closest segment endpoint.
"""
# Compute the parameter r in the line formulation p* = l1 + r*(l2-l1).
# p* is the point on the line at which (p-p*) and (l1-l2) form a right
# angle.
r = (np.dot(p - l1, l2 - l1) / np.linalg.norm(l2 - l1) ** 2)
# If 0 < r < 1, we return the distance p-p*. If r > 1, p* is on the
# forward extension of l1-l2, hence return the distance between
# p and l2. If r < 0, return the distance p-l1.
if r > 1:
return np.linalg.norm(p - l2)
elif r < 0:
return np.linalg.norm(p - l1)
else:
p_on_line = l1 + r * (l2 - l1)
return np.linalg.norm(p - p_on_line)
class WaypointsPath(mpath.Path):
"""Derivative of matplotlib.Path that provides methods to insert and
delete vertices.
"""
def delete_vertex(self, index):
"""Remove the vertex at the given index from the list of vertices.
"""
# TODO: Should codes (MOVETO, LINETO) be modified here? relevant for
# inserting/deleting first/last point.
# Emulate pop() for ndarray:
self.vertices = np.delete(self.vertices, index, axis=0)
self.codes = np.delete(self.codes, index, axis=0)
def insert_vertex(self, index, vertex, code):
"""Insert a new vertex (a tuple x,y) with the given code (see
matplotlib.Path) at the given index.
"""
self.vertices = np.insert(self.vertices, index,
np.asarray(vertex, np.float_), axis=0)
self.codes = np.insert(self.codes, index, code, axis=0)
def index_of_closest_segment(self, x, y, eps=5):
"""Find the index of the edge closest to the specified point at x,y.
If the point is not within eps (in the same coordinates as x,y) of
any edge in the path, the index of the closest end point is returned.
"""
# If only one point is stored in the list the best index to insert a
# new point is after this point.
if len(self.vertices) == 1:
return 1
# Compute the distance between the first point in the path and
# the given point.
point = np.array([x, y])
min_index = 0
min_distance = np.linalg.norm(point - self.vertices[0])
# Loop over all line segments. If the distance between the given
# point and the segment is smaller than a specified threshold AND
# the distance is smaller than the currently smallest distance
# then remember the current index.
for i in range(len(self.vertices) - 1):
l1 = self.vertices[i]
l2 = self.vertices[i + 1]
distance = distance_point_linesegment(point, l1, l2)
if distance < eps and distance < min_distance:
min_index = i + 1
min_distance = distance
# Compute the distance between the given point and the end point of
# the path. Is it smaller than the currently smallest distance?
distance = np.linalg.norm(point - self.vertices[-1])
if distance < min_distance:
min_index = len(self.vertices)
return min_index
def transform_waypoint(self, wps_list, index):
"""Transform the waypoint at index <index> of wps_list to plot
coordinates.
wps_list is a list of <Waypoint> objects (obtained from
WaypointsTableModel.allWaypointData()).
NEEDS TO BE IMPLEMENTED IN DERIVED CLASSES.
"""
return (0, 0)
def update_from_waypoints(self, wps):
"""
"""
Path = mpath.Path
pathdata = []
# on a expired mscolab server wps is an empty list
if len(wps) > 0:
pathdata = [(Path.MOVETO, self.transform_waypoint(wps, 0))]
for i, _ in enumerate(wps[1:]):
pathdata.append((Path.LINETO, self.transform_waypoint(wps, i + 1)))
codes, vertices = list(zip(*pathdata))
self.codes = np.array(codes, dtype=np.uint8)
self.vertices = np.array(vertices)
class PathV(WaypointsPath):
"""Class to represent a vertical flight profile path.
"""
def __init__(self, *args, **kwargs):
"""The constructor required the additional keyword 'numintpoints':
numintpoints -- number of intermediate interpolation points. The entire
flight track will be interpolated to this number of
points.
"""
self.numintpoints = kwargs.pop("numintpoints")
super().__init__(*args, **kwargs)
def update_from_waypoints(self, wps):
"""Extended version of the corresponding WaypointsPath method.
The idea is to generate a field 'intermediate_indexes' that stores
the indexes of the waypoints in the field of the intermediate
great circle points generated by the flight track model, then
to use these great circle indexes as x-coordinates for the vertical
section. This means: If ngc_points are created by
wps_model.intermediatePoints(), the waypoints are mapped to the
range 0..ngc_points.
NOTE: If wps_model only contains two equal waypoints,
intermediate_indexes will NOT span the entire vertical section
plot (this is intentional, as a flight with two equal
waypoints makes no sense).
"""
# Compute intermediate points.
lats, lons, times = path_points(
[wp.lat for wp in wps],
[wp.lon for wp in wps],
times=[wp.utc_time for wp in wps],
numpoints=self.numintpoints, connection="greatcircle")
if lats is not None:
# Determine indices of waypoints in list of intermediate points.
# Store these indices.
waypoints = [[wp.lat, wp.lon] for wp in wps]
intermediate_indexes = []
ipoint = 0
for i, (lat, lon) in enumerate(zip(lats, lons)):
if abs(lat - waypoints[ipoint][0]) < 1E-10 and abs(lon - waypoints[ipoint][1]) < 1E-10:
intermediate_indexes.append(i)
ipoint += 1
if ipoint >= len(waypoints):
break
self.intermediate_indexes = intermediate_indexes
self.ilats = lats
self.ilons = lons
self.itimes = times
# Call super method.
super().update_from_waypoints(wps)
def transform_waypoint(self, wps_list, index):
"""Returns the x-index of the waypoint and its pressure.
"""
return (self.intermediate_indexes[index], wps_list[index].pressure)
class PathH(WaypointsPath):
"""Class to represent a horizontal flight track path, waypoints connected
by great circle segments.
Provides to kinds of vertex data: (1) Waypoint vertices (wp_vertices) and
(2) intermediate great circle vertices (vertices).
"""
def __init__(self, *args, **kwargs):
"""The constructor required the additional keyword 'map' to transform
vertex cooredinates between lat/lon and projection coordinates.
"""
self.map = kwargs.pop("map")
super().__init__(*args, **kwargs)
self.wp_codes = np.array([], dtype=np.uint8)
self.wp_vertices = np.array([])
def transform_waypoint(self, wps_list, index):
"""Transform lon/lat to projection coordinates.
"""
return self.map(wps_list[index].lon, wps_list[index].lat)
def update_from_waypoints(self, wps):
"""Get waypoint coordinates from flight track model, get
intermediate great circle vertices from map instance.
"""
Path = mpath.Path
# Waypoint coordinates.
if len(wps) > 0:
pathdata = [(Path.MOVETO, self.transform_waypoint(wps, 0))]
for i in range(len(wps[1:])):
pathdata.append((Path.LINETO, self.transform_waypoint(wps, i + 1)))
wp_codes, wp_vertices = list(zip(*pathdata))
self.wp_codes = np.array(wp_codes, dtype=np.uint8)
self.wp_vertices = np.array(wp_vertices)
# Coordinates of intermediate great circle points.
lons, lats = list(zip(*[(wp.lon, wp.lat) for wp in wps]))
x, y = self.map.gcpoints_path(lons, lats)
if len(x) > 0:
pathdata = [(Path.MOVETO, (x[0], y[0]))]
for i in range(len(x[1:])):
pathdata.append((Path.LINETO, (x[i + 1], y[i + 1])))
codes, vertices = list(zip(*pathdata))
self.codes = np.array(codes, dtype=np.uint8)
self.vertices = np.array(vertices)
def index_of_closest_segment(self, x, y, eps=5):
"""Find the index of the edge closest to the specified point at x,y.
If the point is not within eps (in the same coordinates as x,y) of
any edge in the path, the index of the closest end point is returned.
"""
# Determine the index of the great circle vertex that is closest to the
# given point.
gcvertex_index = super().index_of_closest_segment(x, y, eps)
# Determine the waypoint index that corresponds to the great circle
# index. If the best index is to append the waypoint to the end of
# the flight track, directly return this index.
if gcvertex_index == len(self.vertices):
return len(self.wp_vertices)
# Otherwise iterate through the list of great circle points and remember
# the index of the last "real" waypoint that was encountered in this
# list.
i = 0 # index for great circle points
j = 0 # index for waypoints
wp_vertex = self.wp_vertices[j]
while (i < gcvertex_index):
vertex = self.vertices[i]
if vertex[0] == wp_vertex[0] and vertex[1] == wp_vertex[1]:
j += 1
wp_vertex = self.wp_vertices[j]
i += 1
return j
class PathPlotter:
"""An interactive matplotlib path editor. Allows vertices of a path patch
to be interactively picked and moved around.
Superclass for the path editors used by the top and side views of the
Mission Support System.
"""
showverts = True # show the vertices of the path patch
# picking points
def __init__(self, ax, mplpath=None,
facecolor='blue', edgecolor='yellow',
linecolor='blue', markerfacecolor='red',
marker='o', label_waypoints=True):
"""The constructor initializes the path patches, overlying line
plot and connects matplotlib signals.
Arguments:
ax -- matplotlib.Axes object into which the path should be drawn.
waypoints -- flighttrack.WaypointsModel instance.
mplpath -- matplotlib.path.Path instance
facecolor -- facecolor of the patch
edgecolor -- edgecolor of the patch
linecolor -- color of the line plotted above the patch edges
markerfacecolor -- color of the markers that represent the waypoints
marker -- symbol of the markers that represent the waypoints, see
matplotlib plot() or scatter() routines for more information.
label_waypoints -- put labels with the waypoint numbers on the waypoints.
"""
self.waypoints_model = None
self.background = None
# Create a PathPatch representing the interactively editable path
# (vertical profile or horizontal flight track in subclasses).
path = mplpath
pathpatch = mpatches.PathPatch(path, facecolor=facecolor,
edgecolor=edgecolor, alpha=0.15)
ax.add_patch(pathpatch)
self.ax = ax
self.path = path
self.pathpatch = pathpatch
self.pathpatch.set_animated(True) # ensure correct redrawing
# Draw the line representing flight track or profile (correct
# vertices handling for the line needs to be ensured in subclasses).
x, y = list(zip(*self.pathpatch.get_path().vertices))
self.line, = self.ax.plot(x, y, color=linecolor,
marker=marker, linewidth=2,
markerfacecolor=markerfacecolor,
animated=True)
# List to accomodate waypoint labels.
self.wp_labels = []
self.label_waypoints = label_waypoints
# Connect mpl events to handler routines: mouse movements and picks.
canvas = self.ax.figure.canvas
canvas.mpl_connect('draw_event', self.draw_callback)
self.canvas = canvas
def draw_callback(self, event):
"""Called when the figure is redrawn. Stores background data (for later
restoration) and draws artists.
"""
self.background = self.canvas.copy_from_bbox(self.ax.bbox)
try:
# TODO review
self.ax.draw_artist(self.pathpatch)
except ValueError as ex:
# When using Matplotlib 1.2, "ValueError: Invalid codes array."
# occurs. The error occurs in Matplotlib's backend_agg.py/draw_path()
# function. However, when I print the codes array in that function,
# it looks fine -- correct length and correct codes. I can't figure
# out why that error occurs.. (mr, 2013Feb08).
logging.error("%s %s", ex, type(ex))
self.ax.draw_artist(self.line)
for t in self.wp_labels:
self.ax.draw_artist(t)
# The blit() method makes problems (distorted figure background). However,
# I don't see why it is needed -- everything seems to work without this line.
# (see infos on http://www.scipy.org/Cookbook/Matplotlib/Animations).
# self.canvas.blit(self.ax.bbox)
def set_vertices_visible(self, showverts=True):
"""Set the visibility of path vertices (the line plot).
"""
self.showverts = showverts
self.line.set_visible(self.showverts)
for t in self.wp_labels:
t.set_visible(showverts and self.label_waypoints)
if not self.showverts:
self._ind = None
self.canvas.draw()
def set_patch_visible(self, showpatch=True):
"""Set the visibility of path patch (the area).
"""
self.pathpatch.set_visible(showpatch)
self.canvas.draw()
def set_labels_visible(self, visible=True):
"""Set the visibility of the waypoint labels.
"""
self.label_waypoints = visible
for t in self.wp_labels:
t.set_visible(self.showverts and self.label_waypoints)
self.canvas.draw()
def set_path_color(self, line_color=None, marker_facecolor=None,
patch_facecolor=None):
"""Set the color of the path patch elements.
Arguments (options):
line_color -- color of the path line
marker_facecolor -- color of the waypoints
patch_facecolor -- color of the patch covering the path area
"""
if line_color is not None:
self.line.set_color(line_color)
if marker_facecolor is not None:
self.line.set_markerfacecolor(marker_facecolor)
if patch_facecolor is not None:
self.pathpatch.set_facecolor(patch_facecolor)
def update_from_waypoints(self, wps):
self.pathpatch.get_path().update_from_waypoints(wps)
class PathH_Plotter(PathPlotter):
def __init__(self, mplmap, mplpath=None, facecolor='none', edgecolor='none',
linecolor='blue', markerfacecolor='red', show_marker=True,
label_waypoints=True):
super().__init__(mplmap.ax, mplpath=PathH([[0, 0]], map=mplmap),
facecolor='none', edgecolor='none', linecolor=linecolor,
markerfacecolor=markerfacecolor, marker='',
label_waypoints=label_waypoints)
self.map = mplmap
self.wp_scatter = None
self.markerfacecolor = markerfacecolor
self.tangent_lines = None
self.show_tangent_points = False
self.solar_lines = None
self.show_marker = show_marker
self.show_solar_angle = None
self.remote_sensing = None
def appropriate_epsilon(self, px=5):
"""Determine an epsilon value appropriate for the current projection and
figure size.
The epsilon value gives the distance required in map projection
coordinates that corresponds to approximately px Pixels in screen
coordinates. The value can be used to find the line/point that is
closest to a click while discarding clicks that are too far away
from any geometry feature.
"""
# (bounds = left, bottom, width, height)
ax_bounds = self.ax.bbox.bounds
width = int(round(ax_bounds[2]))
map_delta_x = np.hypot(self.map.llcrnry - self.map.urcrnry, self.map.llcrnrx - self.map.urcrnrx)
map_coords_per_px_x = map_delta_x / width
return map_coords_per_px_x * px
def redraw_path(self, wp_vertices=None, waypoints_model_data=None):
"""Redraw the matplotlib artists that represent the flight track
(path patch, line and waypoint scatter).
If waypoint vertices are specified, they will be applied to the
graphics output. Otherwise the vertex array obtained from the path
patch will be used.
"""
if waypoints_model_data is None:
waypoints_model_data = []
if wp_vertices is None:
wp_vertices = self.pathpatch.get_path().wp_vertices
if len(wp_vertices) == 0:
raise IOError("mscolab session expired")
vertices = self.pathpatch.get_path().vertices
else:
# If waypoints have been provided, compute the intermediate
# great circle points for the line instance.
x, y = list(zip(*wp_vertices))
lons, lats = self.map(x, y, inverse=True)
x, y = self.map.gcpoints_path(lons, lats)
vertices = list(zip(x, y))
# Set the line to disply great circle points, remove existing
# waypoints scatter instance and draw a new one. This is
# necessary as scatter() does not provide a set_data method.
self.line.set_data(list(zip(*vertices)))
if self.tangent_lines is not None:
self.tangent_lines.remove()
self.tangent_lines = None
if self.solar_lines is not None:
self.solar_lines.remove()
self.solar_lines = None
if len(waypoints_model_data) > 0:
wp_heights = [(wpd.flightlevel * 0.03048) for wpd in waypoints_model_data]
wp_times = [wpd.utc_time for wpd in waypoints_model_data]
if self.show_tangent_points:
assert self.remote_sensing is not None
self.tangent_lines = self.remote_sensing.compute_tangent_lines(
self.map, wp_vertices, wp_heights)
self.ax.add_collection(self.tangent_lines)
if self.show_solar_angle is not None:
assert self.remote_sensing is not None
self.solar_lines = self.remote_sensing.compute_solar_lines(
self.map, wp_vertices, wp_heights, wp_times, self.show_solar_angle)
self.ax.add_collection(self.solar_lines)
if self.wp_scatter is not None:
self.wp_scatter.remove()
self.wp_scatter = None
x, y = list(zip(*wp_vertices))
if self.map.projection == "cyl": # hack for wraparound
x = np.array(x)
x[x < self.map.llcrnrlon] += 360
x[x > self.map.urcrnrlon] -= 360
# (animated is important to remove the old scatter points from the map)
self.wp_scatter = self.ax.scatter(
x, y, color=self.markerfacecolor, s=20, zorder=3, animated=True, visible=self.show_marker)
# Draw waypoint labels.
label_offset = self.appropriate_epsilon(px=5)
for wp_label in self.wp_labels:
wp_label.remove()
self.wp_labels = [] # remove doesn't seem to be necessary
for i, wpd in enumerate(waypoints_model_data):
textlabel = str(i)
if wpd.location != "":
textlabel = f"{wpd.location}"
label_offset = 0
text = self.ax.text(
x[i] + label_offset, y[i] + label_offset, textlabel,
bbox={"boxstyle": "round", "facecolor": "white", "alpha": 0.6, "edgecolor": "none"},
fontweight="bold", zorder=4, animated=True, clip_on=True,
visible=self.showverts and self.label_waypoints)
self.wp_labels.append(text)
# Redraw the artists.
if self.background:
self.canvas.restore_region(self.background)
try:
self.ax.draw_artist(self.pathpatch)
except ValueError as error:
logging.debug("ValueError Exception '%s'", error)
self.ax.draw_artist(self.line)
if self.wp_scatter is not None:
self.ax.draw_artist(self.wp_scatter)
for wp_label in self.wp_labels:
self.ax.draw_artist(wp_label)
if self.show_tangent_points:
self.ax.draw_artist(self.tangent_lines)
if self.show_solar_angle is not None:
self.ax.draw_artist(self.solar_lines)
self.canvas.blit(self.ax.bbox)
def draw_callback(self, event):
"""Extends PathInteractor.draw_callback() by drawing the scatter
instance.
"""
super().draw_callback(event)
if self.wp_scatter:
self.ax.draw_artist(self.wp_scatter)
if self.show_solar_angle:
self.ax.draw_artist(self.solar_lines)
if self.show_tangent_points:
self.ax.draw_artist(self.tangent_lines)
def set_path_color(self, line_color=None, marker_facecolor=None,
patch_facecolor=None):
"""Set the color of the path patch elements.
Arguments (options):
line_color -- color of the path line
marker_facecolor -- color of the waypoints
patch_facecolor -- color of the patch covering the path area
"""
super().set_path_color(line_color, marker_facecolor,
patch_facecolor)
if marker_facecolor is not None and self.wp_scatter is not None:
self.wp_scatter.set_facecolor(marker_facecolor)
self.wp_scatter.set_edgecolor(marker_facecolor)
self.markerfacecolor = marker_facecolor
def set_vertices_visible(self, showverts=True):
"""Set the visibility of path vertices (the line plot).
"""
super().set_vertices_visible(showverts)
if self.wp_scatter is not None:
self.wp_scatter.set_visible(self.show_marker)
def set_tangent_visible(self, visible):
self.show_tangent_points = visible
def set_solar_angle_visible(self, visible):
self.show_solar_angle = visible
def set_remote_sensing(self, ref):
self.remote_sensing = ref
class PathV_Plotter(PathPlotter):
def __init__(self, ax, redraw_xaxis=None, clear_figure=None, numintpoints=101):
"""Constructor passes a PathV instance its parent.
Arguments:
ax -- matplotlib.Axes object into which the path should be drawn.
waypoints -- flighttrack.WaypointsModel instance.
numintpoints -- number of intermediate interpolation points. The entire
flight track will be interpolated to this number of
points.
redrawXAxis -- callback function to redraw the x-axis on path changes.
"""
super().__init__(
ax=ax, mplpath=PathV([[0, 0]], numintpoints=numintpoints))
self.numintpoints = numintpoints
self.redraw_xaxis = redraw_xaxis
self.clear_figure = clear_figure
def get_num_interpolation_points(self):
return self.numintpoints
def redraw_path(self, vertices=None, waypoints_model_data=None):
"""Redraw the matplotlib artists that represent the flight track
(path patch and line).
If vertices are specified, they will be applied to the graphics
output. Otherwise the vertex array obtained from the path patch
will be used.
"""
if waypoints_model_data is None:
waypoints_model_data = []
if vertices is None:
vertices = self.pathpatch.get_path().vertices
self.line.set_data(list(zip(*vertices)))
x, y = list(zip(*vertices))
# Draw waypoint labels.
for wp_label in self.wp_labels:
wp_label.remove()
self.wp_labels = [] # remove doesn't seem to be necessary
for i, wpd, in enumerate(waypoints_model_data):
textlabel = f"{str(i):} "
if wpd.location != "":
textlabel = f"{wpd.location:} "
text = self.ax.text(
x[i], y[i],
textlabel,
bbox=dict(boxstyle="round",
facecolor="white",
alpha=0.5,
edgecolor="none"),
fontweight="bold",
zorder=4,
rotation=90,
animated=True,
clip_on=True,
visible=self.showverts and self.label_waypoints)
self.wp_labels.append(text)
if self.background:
self.canvas.restore_region(self.background)
try:
self.ax.draw_artist(self.pathpatch)
except ValueError as error:
logging.error("ValueError Exception %s", error)
self.ax.draw_artist(self.line)
for wp_label in self.wp_labels:
self.ax.draw_artist(wp_label)
self.canvas.blit(self.ax.bbox)
def get_lat_lon(self, event, wpm):
x = event.xdata
vertices = self.pathpatch.get_path().vertices
best_index = 1
# if x axis has increasing coordinates
if vertices[-1, 0] > vertices[0, 0]:
for index, vertex in enumerate(vertices):
if x >= vertex[0]:
best_index = index + 1
# if x axis has decreasing coordinates
else:
for index, vertex in enumerate(vertices):
if x <= vertex[0]:
best_index = index + 1
# number of subcoordinates is determined by difference in x coordinates
number_of_intermediate_points = math.floor(vertices[best_index, 0] - vertices[best_index - 1, 0])
vert_xs, vert_ys = latlon_points(
vertices[best_index - 1, 0], vertices[best_index - 1, 1],
vertices[best_index, 0], vertices[best_index, 1],
number_of_intermediate_points, connection="linear")
lats, lons = latlon_points(
wpm[best_index - 1].lat, wpm[best_index - 1].lon,
wpm[best_index].lat, wpm[best_index].lon,
number_of_intermediate_points, connection="greatcircle")
# best_index1 is the best index among the intermediate coordinates to fit the hovered point
# if x axis has increasing coordinates
best_index1 = np.argmin(abs(vert_xs - x))
# depends if best_index1 or best_index1 - 1 on closeness to left or right neighbourhood
return (lats[best_index1], lons[best_index1]), best_index
class PathL_Plotter(PathPlotter):
def __init__(self, ax, redraw_xaxis=None, clear_figure=None, numintpoints=101):
"""Constructor passes a PathV instance its parent.
Arguments:
ax -- matplotlib.Axes object into which the path should be drawn.
waypoints -- flighttrack.WaypointsModel instance.
numintpoints -- number of intermediate interpolation points. The entire
flight track will be interpolated to this number of
points.
redrawXAxis -- callback function to redraw the x-axis on path changes.
"""
super().__init__(
ax=ax, marker="", mplpath=PathV([[0, 0]], numintpoints=numintpoints))
self.numintpoints = numintpoints
self.redraw_xaxis = redraw_xaxis
self.clear_figure = clear_figure
def get_num_interpolation_points(self):
return self.numintpoints
def get_lat_lon(self, event, wpm):
x = event.xdata
vertices = self.pathpatch.get_path().vertices
best_index = 1
# if x axis has increasing coordinates
if vertices[-1, 0] > vertices[0, 0]:
for index, vertex in enumerate(vertices):
if x >= vertex[0]:
best_index = index + 1
# if x axis has decreasing coordinates
else:
for index, vertex in enumerate(vertices):
if x <= vertex[0]:
best_index = index + 1
# number of subcoordinates is determined by difference in x coordinates
number_of_intermediate_points = int(abs(vertices[best_index, 0] - vertices[best_index - 1, 0]))
vert_xs, vert_ys = latlon_points(
vertices[best_index - 1, 0], vertices[best_index - 1, 1],
vertices[best_index, 0], vertices[best_index, 1],
number_of_intermediate_points, connection="linear")
lats, lons = latlon_points(
wpm.waypoint_data(best_index - 1).lat, wpm.waypoint_data(best_index - 1).lon,
wpm.waypoint_data(best_index).lat, wpm.waypoint_data(best_index).lon,
number_of_intermediate_points, connection="greatcircle")
alts = np.linspace(wpm.waypoint_data(best_index - 1).flightlevel,
wpm.waypoint_data(best_index).flightlevel, number_of_intermediate_points)
best_index1 = np.argmin(abs(vert_xs - x))
# depends if best_index1 or best_index1 - 1 on closeness to left or right neighbourhood
return (lats[best_index1], lons[best_index1], alts[best_index1]), best_index
class PathInteractor(QtCore.QObject):
"""An interactive matplotlib path editor. Allows vertices of a path patch
to be interactively picked and moved around.
Superclass for the path editors used by the top and side views of the
Mission Support System.
"""
showverts = True # show the vertices of the path patch
epsilon = 12
# picking points
def __init__(self, plotter, waypoints=None):
"""The constructor initializes the path patches, overlying line
plot and connects matplotlib signals.
Arguments:
ax -- matplotlib.Axes object into which the path should be drawn.
waypoints -- flighttrack.WaypointsModel instance.
mplpath -- matplotlib.path.Path instance
facecolor -- facecolor of the patch
edgecolor -- edgecolor of the patch
linecolor -- color of the line plotted above the patch edges
markerfacecolor -- color of the markers that represent the waypoints
marker -- symbol of the markers that represent the waypoints, see
matplotlib plot() or scatter() routines for more information.
label_waypoints -- put labels with the waypoint numbers on the waypoints.
"""
QtCore.QObject.__init__(self)
self._ind = None # the active vertex
self.plotter = plotter
# Set the waypoints model, connect to the change() signals of the model
# and redraw the figure.
self.waypoints_model = None
self.set_waypoints_model(waypoints)
def set_waypoints_model(self, waypoints):
"""Change the underlying waypoints data structure. Disconnect change()
signals of an already existing model and connect to the new model.
Redraw the map.
"""
# If a model exists, disconnect from the old change() signals.
wpm = self.waypoints_model
if wpm:
wpm.dataChanged.disconnect(self.qt_data_changed_listener)
wpm.rowsInserted.disconnect(self.qt_insert_remove_point_listener)
wpm.rowsRemoved.disconnect(self.qt_insert_remove_point_listener)
# Set the new waypoints model.
self.waypoints_model = waypoints
# Connect to the new model's signals.
wpm = self.waypoints_model
wpm.dataChanged.connect(self.qt_data_changed_listener)
wpm.rowsInserted.connect(self.qt_insert_remove_point_listener)
wpm.rowsRemoved.connect(self.qt_insert_remove_point_listener)
# Redraw.
self.plotter.update_from_waypoints(wpm.all_waypoint_data())
self.redraw_figure()
def qt_insert_remove_point_listener(self, index, first, last):
"""Listens to rowsInserted() and rowsRemoved() signals emitted
by the flight track data model. The view can thus react to
data changes induced by another view (table, side view).
"""
self.plotter.update_from_waypoints(self.waypoints_model.all_waypoint_data())
self.redraw_figure()
def qt_data_changed_listener(self, index1, index2):
"""Listens to dataChanged() signals emitted by the flight track
data model. The view can thus react to data changes induced
by another view (table, top view).
"""
# REIMPLEMENT IN SUBCLASSES.
pass
def get_ind_under_point(self, event):
"""Get the index of the waypoint vertex under the point
specified by event within epsilon tolerance.
Uses display coordinates.
If no waypoint vertex is found, None is returned.
"""
xy = np.asarray(self.plotter.pathpatch.get_path().vertices)
xyt = self.plotter.pathpatch.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.hypot(xt - event.x, yt - event.y)
ind = d.argmin()
if d[ind] >= self.epsilon:
ind = None
return ind
def button_press_callback(self, event):
"""Called whenever a mouse button is pressed. Determines the index of
the vertex closest to the click, as long as a vertex is within
epsilon tolerance of the click.
"""
if not self.plotter.showverts:
return
if event.inaxes is None:
return
if event.button != 1:
return
self._ind = self.get_ind_under_point(event)
def confirm_delete_waypoint(self, row):
"""Open a QMessageBox and ask the user if he really wants to
delete the waypoint at index <row>.
Returns TRUE if the user confirms the deletion.
If the flight track consists of only two points deleting a waypoint
is not possible. In this case the user is informed correspondingly.
"""
wps = self.waypoints_model.all_waypoint_data()
if len(wps) < 3:
QtWidgets.QMessageBox.warning(
None, "Remove waypoint",
"Cannot remove waypoint, the flight track needs to consist "
"of at least two points.")
return False
else:
wp = wps[row]
return QtWidgets.QMessageBox.question(
None, "Remove waypoint",
f"Remove waypoint no.{row:d} at {wp.lat:.2f}/{wp.lon:.2f}, flightlevel {wp.flightlevel:.2f}?",
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
QtWidgets.QMessageBox.Yes) == QtWidgets.QMessageBox.Yes
class VPathInteractor(PathInteractor):
"""Subclass of PathInteractor that implements an interactively editable
vertical profile of the flight track.
"""
signal_get_vsec = QtCore.pyqtSignal(name="get_vsec")
def __init__(self, ax, waypoints, redraw_xaxis=None, clear_figure=None, numintpoints=101):
"""Constructor passes a PathV instance its parent.
Arguments:
ax -- matplotlib.Axes object into which the path should be drawn.
waypoints -- flighttrack.WaypointsModel instance.
numintpoints -- number of intermediate interpolation points. The entire
flight track will be interpolated to this number of
points.
redrawXAxis -- callback function to redraw the x-axis on path changes.
"""
plotter = PathV_Plotter(ax, redraw_xaxis=redraw_xaxis, clear_figure=clear_figure, numintpoints=numintpoints)
self.redraw_xaxis = redraw_xaxis
self.clear_figure = clear_figure
super().__init__(plotter=plotter, waypoints=waypoints)
def redraw_figure(self):
"""For the side view, changes in the horizontal position of a waypoint
(including moved waypoints, new or deleted waypoints) make a complete
redraw of the figure necessary.
Calls the callback function 'redrawXAxis()'.
"""
self.plotter.redraw_path(waypoints_model_data=self.waypoints_model.all_waypoint_data())
# emit signal to redraw map
self.signal_get_vsec.emit()
if self.redraw_xaxis is not None:
try:
self.redraw_xaxis(self.plotter.path.ilats, self.plotter.path.ilons, self.plotter.path.itimes)
except AttributeError as err:
logging.debug("%s" % err)
self.plotter.ax.figure.canvas.draw()
def button_release_delete_callback(self, event):
"""Called whenever a mouse button is released.
"""
if not self.showverts or event.button != 1:
return
if self._ind is not None:
if self.confirm_delete_waypoint(self._ind):
# removeRows() will trigger a signal that will redraw the path.
self.waypoints_model.removeRows(self._ind)
self._ind = None
def button_release_insert_callback(self, event):
"""Called whenever a mouse button is released.
From the click event's coordinates, best_index is calculated as
the index of a vertex whose x coordinate > clicked x coordinate.
This is the position where the waypoint is to be inserted.
'lat' and 'lon' are calculated as an average of each of the first waypoint
in left and right neighbourhood of inserted waypoint.
The coordinates are checked against "locations" defined in msui' config.
A new waypoint with the coordinates, and name is inserted into the waypoints_model.
"""
if not self.showverts or event.button != 1 or event.inaxes is None:
return
y = event.ydata
wpm = self.waypoints_model
flightlevel = float(pressure2flightlevel(y * units.Pa).magnitude)
# round flightlevel to the nearest multiple of five (legal level)
flightlevel = 5.0 * round(flightlevel / 5)
[lat, lon], best_index = self.plotter.get_lat_lon(event, wpm.all_waypoint_data())
loc = find_location(lat, lon) # skipped tolerance which uses appropriate_epsilon_km
if loc is not None:
(lat, lon), location = loc
else:
location = ""
new_wp = ft.Waypoint(lat, lon, flightlevel, location=location)
# insertRows() will trigger a signal that will redraw the path.
wpm.insertRows(best_index, rows=1, waypoints=[new_wp])
self._ind = None
def get_lat_lon(self, event):
lat_lon, ind = self.plotter.get_lat_lon(event, self.waypoints_model.all_waypoint_data())
return lat_lon, ind