-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathannotation.py
More file actions
1352 lines (1111 loc) · 43.4 KB
/
annotation.py
File metadata and controls
1352 lines (1111 loc) · 43.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Licensed under the terms of the BSD 3-Clause
# (see plotpy/LICENSE for details)
# pylint: disable=C0103
"""
Annotations
-----------
The :mod:`annotation` module provides annotated shape plot items.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Callable
import numpy as np
from guidata.dataset import update_dataset
from guidata.utils.misc import assert_interfaces_valid
from plotpy.config import CONF, _
from plotpy.coords import canvas_to_axes
from plotpy.interfaces import IBasePlotItem, ISerializableType, IShapeItemType
from plotpy.items.label import DataInfoLabel
from plotpy.items.shape.base import AbstractShape
from plotpy.items.shape.ellipse import EllipseShape
from plotpy.items.shape.point import PointShape
from plotpy.items.shape.polygon import PolygonShape
from plotpy.items.shape.range import XRangeSelection, YRangeSelection
from plotpy.items.shape.rectangle import ObliqueRectangleShape, RectangleShape
from plotpy.items.shape.segment import SegmentShape
from plotpy.mathutils.geometry import (
compute_angle,
compute_center,
compute_distance,
compute_rect_size,
)
from plotpy.styles.label import LabelParam
from plotpy.styles.shape import AnnotationParam
if TYPE_CHECKING:
import guidata.io
import qwt.scale_map
from qtpy.QtCore import QPointF, QRectF
from qtpy.QtGui import QPainter
from plotpy.interfaces import IItemType
from plotpy.styles.base import ItemParameters
class AnnotatedShape(AbstractShape):
"""
Construct an annotated shape with properties set with
*annotationparam* (see :py:class:`.styles.AnnotationParam`)
Args:
annotationparam: Annotation parameters
"""
__implements__ = (IBasePlotItem, ISerializableType)
_icon_name = "annotation.png"
SHAPE_CLASS: type[AbstractShape] = RectangleShape # to be overridden
LABEL_ANCHOR: str = ""
def __init__(
self,
annotationparam: AnnotationParam | None = None,
info_callback: Callable[[AnnotatedShape], str] | None = None,
) -> None:
super().__init__()
assert self.LABEL_ANCHOR is not None and len(self.LABEL_ANCHOR) != 0
if info_callback is None:
def info_callback(annotation: AnnotatedShape) -> str:
"""Return information on annotation"""
return annotation.get_info()
self.info_callback = info_callback
self.shape: AbstractShape = self.create_shape()
self.label = self.create_label()
self.area_computations_visible = True
self.subtitle_visible = True
if annotationparam is None:
self.annotationparam = AnnotationParam(
_("Annotation"), icon="annotation.png"
)
else:
self.annotationparam = annotationparam
self.annotationparam.update_item(self)
def types(self) -> tuple[type[IItemType], ...]:
"""Returns a group or category for this item.
This should be a tuple of class objects inheriting from IItemType
Returns:
tuple: Tuple of class objects inheriting from IItemType
"""
return (IShapeItemType, ISerializableType)
def __reduce__(self) -> tuple[type, tuple, tuple]:
"""Return a tuple for pickling"""
self.annotationparam.update_param(self)
state = (self.shape, self.label, self.annotationparam)
return (self.__class__, (), state)
def __setstate__(self, state: tuple) -> None:
"""Set state after unpickling"""
shape, label, param = state
self.shape = shape
self.label = label
self.annotationparam: AnnotationParam = param
self.annotationparam.update_item(self)
def serialize(
self,
writer: guidata.io.HDF5Writer | guidata.io.INIWriter | guidata.io.JSONWriter,
) -> None:
"""Serialize object to HDF5 writer
Args:
writer: HDF5, INI or JSON writer
"""
writer.write(self.annotationparam, group_name="annotationparam")
self.shape.serialize(writer)
self.label.serialize(writer)
def deserialize(
self,
reader: guidata.io.HDF5Reader | guidata.io.INIReader | guidata.io.JSONReader,
) -> None:
"""Deserialize object from HDF5 reader
Args:
reader: HDF5, INI or JSON reader
"""
self.annotationparam = AnnotationParam(_("Annotation"), icon="annotation.png")
reader.read("annotationparam", instance=self.annotationparam)
self.annotationparam.update_item(self)
self.shape.deserialize(reader)
self.label.deserialize(reader)
def set_style(self, section: str, option: str) -> None:
"""Set style for this item
Args:
section: Section
option: Option
"""
self.shape.set_style(section, option)
# ----QwtPlotItem API--------------------------------------------------------
def draw(
self,
painter: QPainter,
xMap: qwt.scale_map.QwtScaleMap,
yMap: qwt.scale_map.QwtScaleMap,
canvasRect: QRectF,
) -> None:
"""Draw the item
Args:
painter: Painter
xMap: X axis scale map
yMap: Y axis scale map
canvasRect: Canvas rectangle
"""
self.shape.draw(painter, xMap, yMap, canvasRect)
if self.label.isVisible():
self.label.draw(painter, xMap, yMap, canvasRect)
# ----AbstractShape API------------------------------------------------------
def set_readonly(self, state: bool) -> None:
"""Set object readonly state
Args:
state: True if object is readonly, False otherwise
"""
super().set_readonly(state)
self.shape.set_readonly(state)
# ----Public API-------------------------------------------------------------
def create_shape(self):
"""Return the shape object associated to this annotated shape object"""
shape = self.SHAPE_CLASS(0, 0, 1, 1) # pylint: disable=not-callable
return shape
def create_label(self) -> DataInfoLabel:
"""Return the label object associated to this annotated shape object
Returns:
Label object
"""
label_param = LabelParam(_("Label"), icon="label.png")
label_param.read_config(CONF, "plot", "shape/label")
label_param.anchor = self.LABEL_ANCHOR
if self.LABEL_ANCHOR == "C":
label_param.xc = label_param.yc = 0
return DataInfoLabel(label_param, [self])
def is_label_visible(self) -> bool:
"""Return True if associated label is visible
Returns:
True if associated label is visible
"""
return self.label.isVisible()
def set_label_visible(self, state: bool) -> None:
"""Set the annotated shape's label visibility
Args:
state: True if label should be visible
"""
self.label.setVisible(state)
def update_label(self) -> None:
"""Update the annotated shape's label contents"""
self.label.update_text()
def set_info_callback(self, callback: Callable[[AnnotatedShape], str]) -> None:
"""Set the callback function to get informations on current shape
Args:
callback: Callback function to get informations on current shape
"""
self.info_callback = callback
def get_text(self) -> str:
"""Return text associated to current shape
(see :py:class:`.label.ObjectInfo`)
Returns:
Text associated to current shape
"""
text = ""
title = self.title().text()
if title:
text += f"<b>{title}</b>"
subtitle = self.annotationparam.subtitle
if subtitle and self.subtitle_visible:
if text:
text += "<br>"
text += f"<i>{subtitle}</i>"
if self.area_computations_visible:
info = self.info_callback(self)
if info:
if text:
text += "<br>"
text += info
return text
def x_to_str(self, x: float) -> str:
"""Convert x to a string (with associated unit and uncertainty)
Args:
x: X value
Returns:
str: Formatted string with x value
"""
param = self.annotationparam
if self.plot() is None:
return ""
else:
xunit = self.plot().get_axis_unit(self.xAxis())
fmt = param.format
if param.uncertainty:
fmt += " ± " + (fmt % (x * param.uncertainty))
if xunit is not None:
return (fmt + " " + xunit) % x
else:
return (fmt) % x
def y_to_str(self, y):
"""Convert y to a string (with associated unit and uncertainty)
Args:
y: Y value
Returns:
str: Formatted string with x value
"""
param = self.annotationparam
if self.plot() is None:
return ""
else:
yunit = self.plot().get_axis_unit(self.yAxis())
fmt = param.format
if param.uncertainty:
fmt += " ± " + (fmt % (y * param.uncertainty))
if yunit is not None:
return (fmt + " " + yunit) % y
else:
return (fmt) % y
def get_center(self):
"""Return shape center coordinates: (xc, yc)"""
return self.shape.get_center()
def get_tr_center(self):
"""Return shape center coordinates after applying transform matrix"""
raise NotImplementedError
def get_tr_center_str(self):
"""Return center coordinates as a string (with units)"""
xc, yc = self.get_tr_center()
return f"( {self.x_to_str(xc)} ; {self.y_to_str(yc)} )"
def get_tr_size(self):
"""Return shape size after applying transform matrix"""
raise NotImplementedError
def get_tr_size_str(self):
"""Return size as a string (with units)"""
xs, ys = self.get_tr_size()
return f"{self.x_to_str(xs)} x {self.y_to_str(ys)}"
def get_info(self) -> str:
"""Get informations on current shape
Returns:
str: Formatted string with informations on current shape
"""
return ""
def set_label_position(self):
"""Set label position, for instance based on shape position"""
raise NotImplementedError
def apply_transform_matrix(self, x, y):
"""
:param x:
:param y:
:return:
"""
V = np.array([x, y, 1.0])
W = np.dot(V, self.annotationparam.transform_matrix)
return W[0], W[1]
def get_transformed_coords(self, handle1, handle2):
"""
:param handle1:
:param handle2:
:return:
"""
x1, y1 = self.apply_transform_matrix(*self.shape.points[handle1])
x2, y2 = self.apply_transform_matrix(*self.shape.points[handle2])
return x1, y1, x2, y2
# ----IBasePlotItem API------------------------------------------------------
def hit_test(self, pos: QPointF) -> tuple[float, float, bool, None]:
"""Return a tuple (distance, attach point, inside, other_object)
Args:
pos: Position
Returns:
tuple: Tuple with four elements: (distance, attach point, inside,
other_object).
Description of the returned values:
* distance: distance in pixels (canvas coordinates) to the closest
attach point
* attach point: handle of the attach point
* inside: True if the mouse button has been clicked inside the object
* other_object: if not None, reference of the object which will be
considered as hit instead of self
"""
return self.shape.poly_hit_test(self.plot(), self.xAxis(), self.yAxis(), pos)
def move_point_to(
self, handle: int, pos: tuple[float, float], ctrl: bool = False
) -> None:
"""Move a handle as returned by hit_test to the new position
Args:
handle: Handle
pos: Position
ctrl: True if <Ctrl> button is being pressed, False otherwise
"""
self.shape.move_point_to(handle, pos, ctrl)
self.set_label_position()
if self.plot():
self.plot().SIG_ANNOTATION_CHANGED.emit(self)
def move_shape(self, old_pos: QPointF, new_pos: QPointF) -> None:
"""Translate the shape such that old_pos becomes new_pos in axis coordinates
Args:
old_pos: Old position
new_pos: New position
"""
self.shape.move_shape(old_pos, new_pos)
self.label.move_local_shape(old_pos, new_pos)
def move_local_shape(self, old_pos: QPointF, new_pos: QPointF) -> None:
"""Translate the shape such that old_pos becomes new_pos in canvas coordinates
Args:
old_pos: Old position
new_pos: New position
"""
old_pt = canvas_to_axes(self, old_pos)
new_pt = canvas_to_axes(self, new_pos)
self.shape.move_shape(old_pt, new_pt)
self.set_label_position()
if self.plot():
self.plot().SIG_ITEM_MOVED.emit(self, *(old_pt + new_pt))
self.plot().SIG_ANNOTATION_CHANGED.emit(self)
def move_with_selection(self, delta_x: float, delta_y: float) -> None:
"""Translate the item together with other selected items
Args:
delta_x: Translation in plot coordinates along x-axis
delta_y: Translation in plot coordinates along y-axis
"""
self.shape.move_with_selection(delta_x, delta_y)
self.label.move_with_selection(delta_x, delta_y)
self.plot().SIG_ANNOTATION_CHANGED.emit(self)
def select(self) -> None:
"""
Select the object and eventually change its appearance to highlight the
fact that it's selected
"""
AbstractShape.select(self)
self.shape.select()
def unselect(self) -> None:
"""
Unselect the object and eventually restore its original appearance to
highlight the fact that it's not selected anymore
"""
AbstractShape.unselect(self)
self.shape.unselect()
def get_item_parameters(self, itemparams: ItemParameters) -> None:
"""
Appends datasets to the list of DataSets describing the parameters
used to customize apearance of this item
Args:
itemparams: Item parameters
"""
self.shape.get_item_parameters(itemparams)
self.label.get_item_parameters(itemparams)
self.annotationparam.update_param(self)
itemparams.add("AnnotationParam", self, self.annotationparam)
def set_item_parameters(self, itemparams: ItemParameters) -> None:
"""
Change the appearance of this item according
to the parameter set provided
Args:
itemparams: Item parameters
"""
self.shape.set_item_parameters(itemparams)
self.label.set_item_parameters(itemparams)
update_dataset(
self.annotationparam, itemparams.get("AnnotationParam"), visible_only=True
)
self.annotationparam.update_item(self)
self.plot().SIG_ANNOTATION_CHANGED.emit(self)
# Autoscalable types API
def is_empty(self) -> bool:
"""Return True if the item is empty
Returns:
True if the item is empty, False otherwise
"""
return self.shape.is_empty()
def boundingRect(self) -> QRectF:
"""Return the bounding rectangle of the shape
Returns:
Bounding rectangle of the shape
"""
return self.shape.boundingRect()
assert_interfaces_valid(AnnotatedShape)
class AnnotatedPoint(AnnotatedShape):
"""
Construct an annotated point at coordinates (x, y) with properties set with
*annotationparam* (see :py:class:`.styles.AnnotationParam`)
"""
_icon_name = "point_shape.png"
SHAPE_CLASS = PointShape
LABEL_ANCHOR = "TL"
def __init__(
self,
x=0,
y=0,
annotationparam: AnnotationParam | None = None,
info_callback: Callable[[AnnotatedShape], str] | None = None,
) -> None:
super().__init__(annotationparam, info_callback)
self.shape: PointShape
self.set_pos(x, y)
# ----Public API-------------------------------------------------------------
def set_pos(self, x, y):
"""Set the point coordinates to (x, y)"""
self.shape.set_pos(x, y)
self.set_label_position()
def get_pos(self):
"""Return the point coordinates"""
return self.shape.get_pos()
# ----AnnotatedShape API-----------------------------------------------------
def create_shape(self):
"""Return the shape object associated to this annotated shape object"""
shape = self.SHAPE_CLASS(0, 0)
return shape
def set_label_position(self):
"""Set label position, for instance based on shape position"""
x, y = self.shape.points[0]
self.label.set_pos(x, y)
# ----AnnotatedShape API-----------------------------------------------------
def get_tr_position(self):
xt, yt = self.apply_transform_matrix(*self.shape.points[0])
return xt, yt
def get_info(self) -> str:
"""Get informations on current shape
Returns:
str: Formatted string with informations on current shape
"""
xt, yt = self.apply_transform_matrix(*self.shape.points[0])
s = "{title} ( {posx} ; {posy} )"
s = s.format(
title=_("Position:"), posx=self.x_to_str(xt), posy=self.y_to_str(yt)
)
return s
class AnnotatedSegment(AnnotatedShape):
"""
Construct an annotated segment between coordinates (x1, y1) and
(x2, y2) with properties set with *annotationparam*
(see :py:class:`.styles.AnnotationParam`)
"""
_icon_name = "segment.png"
SHAPE_CLASS = SegmentShape
LABEL_ANCHOR = "C"
def __init__(
self,
x1=0,
y1=0,
x2=0,
y2=0,
annotationparam: AnnotationParam | None = None,
info_callback: Callable[[AnnotatedShape], str] | None = None,
) -> None:
super().__init__(annotationparam, info_callback)
self.shape: SegmentShape
self.set_rect(x1, y1, x2, y2)
# ----Public API-------------------------------------------------------------
def set_rect(self, x1, y1, x2, y2):
"""
Set the coordinates of the shape's top-left corner to (x1, y1),
and of its bottom-right corner to (x2, y2).
"""
self.shape.set_rect(x1, y1, x2, y2)
self.set_label_position()
def get_rect(self):
"""
Return the coordinates of the shape's top-left and bottom-right corners
"""
return self.shape.get_rect()
def get_tr_length(self):
"""Return segment length after applying transform matrix"""
return compute_distance(*self.get_transformed_coords(0, 1))
def get_tr_center(self):
"""Return segment position (middle) after applying transform matrix"""
return compute_center(*self.get_transformed_coords(0, 1))
def get_tr_angle(self):
"""Return segment angle with horizontal direction (0° to 180°),
after applying transform matrix"""
xcoords = self.get_transformed_coords(0, 1)
_x, yr1 = self.apply_transform_matrix(1.0, 1.0)
_x, yr2 = self.apply_transform_matrix(1.0, 2.0)
return (compute_angle(*xcoords, reverse=yr1 > yr2) + 180) % 180
# ----AnnotatedShape API-----------------------------------------------------
def set_label_position(self):
"""Set label position, for instance based on shape position"""
x1, y1, x2, y2 = self.get_rect()
self.label.set_pos(*compute_center(x1, y1, x2, y2))
# ----AnnotatedShape API-----------------------------------------------------
def get_info(self) -> str:
"""Get informations on current shape
Returns:
str: Formatted string with informations on current shape
"""
return "<br>".join(
[
_("Center:") + " " + self.get_tr_center_str(),
_("Distance:") + " " + self.x_to_str(self.get_tr_length()),
_("Angle:") + f" {self.get_tr_angle():.1f}°",
]
)
class BaseAnnotatedRangeSelection(AnnotatedShape):
"""
Construct an annotated range selection with properties set with
*annotationparam* (see :py:class:`.styles.AnnotationParam`)
Args:
annotationparam: Annotation parameters
info_callback: Callback to get information on the shape
"""
_icon_name = "" # to be overridden
SHAPE_CLASS: type[AbstractShape] = XRangeSelection # to be overridden
def __init__(
self,
_min: float | None = None,
_max: float | None = None,
annotationparam: AnnotationParam | None = None,
info_callback: Callable[[AnnotatedShape], str] | None = None,
) -> None:
super().__init__(annotationparam, info_callback)
self.shape: XRangeSelection | YRangeSelection
self.shape.set_private(True)
self.set_range(_min, _max)
# ----Public API-------------------------------------------------------------
def set_range(self, _min: float | None, _max: float | None) -> None:
"""Set the range selection coordinates
Args:
_min: Minimum value
_max: Maximum value
"""
self.shape.set_range(_min, _max)
self.set_label_position()
def get_range(self) -> tuple[float, float]:
"""Return the range selection coordinates
Returns:
Range selection coordinates as a tuple (min, max)
"""
return self.shape.get_range()
def get_tr_range(self) -> float:
"""Return the range selection length after applying transform matrix
Returns:
Range selection length after applying transform matrix
"""
return compute_distance(*self.get_transformed_coords(0, 1))
def get_tr_center(self) -> float:
"""Return the range selection position (middle) after applying transform matrix
Returns:
Range selection position (middle) after applying transform matrix
"""
center = compute_center(*self.get_transformed_coords(0, 1))
if isinstance(self.shape, XRangeSelection):
return center[0]
return center[1]
# pylint: disable=unused-argument
def get_transformed_coords(self, handle1, handle2):
"""
:param handle1:
:param handle2:
:return:
"""
x1, x2 = self.get_range()
y1 = y2 = 0.0
if isinstance(self.shape, YRangeSelection):
x1, x2, y1, y2 = y1, y2, x1, x2
x1, y1 = self.apply_transform_matrix(x1, y1)
x2, y2 = self.apply_transform_matrix(x2, y2)
return x1, y1, x2, y2
# ----AnnotatedShape API-----------------------------------------------------
def create_shape(self):
"""Return the shape object associated to this annotated shape object"""
shape = self.SHAPE_CLASS(0, 0)
return shape
def get_info(self) -> str:
"""Get informations on current shape
Returns:
str: Formatted string with informations on current shape
"""
coord_str = "x" if isinstance(self.shape, XRangeSelection) else "y"
c, r = self.get_tr_center(), self.get_tr_range()
center_val = self.x_to_str(c)
range_val = self.x_to_str(r)
lower_val = self.x_to_str(c - 0.5 * r)
upper_val = self.x_to_str(c + 0.5 * r)
return "<br>".join(
[
f"{coord_str}<sub>C</sub> = {center_val}",
f"{coord_str}<sub>MIN</sub> = {lower_val}",
f"{coord_str}<sub>MAX</sub> = {upper_val}",
f"Δ{coord_str} = {range_val}",
]
)
# ----IBasePlotItem API------------------------------------------------------
def hit_test(self, pos: QPointF) -> tuple[float, float, bool, None]:
"""Return a tuple (distance, attach point, inside, other_object)
Args:
pos: Position
Returns:
tuple: Tuple with four elements: (distance, attach point, inside,
other_object).
Description of the returned values:
* distance: distance in pixels (canvas coordinates) to the closest
attach point
* attach point: handle of the attach point
* inside: True if the mouse button has been clicked inside the object
* other_object: if not None, reference of the object which will be
considered as hit instead of self
"""
return self.shape.hit_test(pos)
# ----QwtPlotItem API--------------------------------------------------------
def draw(
self,
painter: QPainter,
xMap: qwt.scale_map.QwtScaleMap,
yMap: qwt.scale_map.QwtScaleMap,
canvasRect: QRectF,
) -> None:
"""Draw the item
Args:
painter: Painter
xMap: X axis scale map
yMap: Y axis scale map
canvasRect: Canvas rectangle
"""
self.set_label_position()
super().draw(painter, xMap, yMap, canvasRect)
def attach(self, plot):
"""
Attach the item to a plot.
This method will attach a `QwtPlotItem` to the `QwtPlot` argument.
It will first detach the `QwtPlotItem` from any plot from a previous
call to attach (if necessary). If a None argument is passed, it will
detach from any `QwtPlot` it was attached to.
:param qwt.plot.QwtPlot plot: Plot widget
.. seealso::
:py:meth:`detach()`
"""
super().attach(plot)
self.shape.attach(plot)
self.set_label_position()
class AnnotatedXRange(BaseAnnotatedRangeSelection):
"""
Construct an annotated X range selection with properties set with
*annotationparam* (see :py:class:`.styles.AnnotationParam`)
Args:
_min: Minimum value
_max: Maximum value
annotationparam: Annotation parameters
info_callback: Callback to get information on the shape
"""
_icon_name = "xrange.png"
SHAPE_CLASS = XRangeSelection
LABEL_ANCHOR = "C"
def __init__(
self,
_min: float | None = None,
_max: float | None = None,
annotationparam: AnnotationParam | None = None,
info_callback: Callable[[AnnotatedShape], str] | None = None,
) -> None:
super().__init__(_min, _max, annotationparam, info_callback)
# ----AnnotatedShape API-----------------------------------------------------
def set_label_position(self) -> None:
"""Set label position, for instance based on shape position"""
plot = self.plot()
if plot is not None:
x0, x1, y = self.shape.get_handles_pos()
x = 0.5 * (x0 + x1)
x = plot.invTransform(self.xAxis(), x)
y = plot.invTransform(self.yAxis(), y)
self.label.set_pos(x, y)
class AnnotatedYRange(BaseAnnotatedRangeSelection):
"""
Construct an annotated Y range selection with properties set with
*annotationparam* (see :py:class:`.styles.AnnotationParam`)
Args:
_min: Minimum value
_max: Maximum value
annotationparam: Annotation parameters
info_callback: Callback to get information on the shape
"""
_icon_name = "yrange.png"
SHAPE_CLASS = YRangeSelection
LABEL_ANCHOR = "C"
def __init__(
self,
_min: float | None = None,
_max: float | None = None,
annotationparam: AnnotationParam | None = None,
info_callback: Callable[[AnnotatedShape], str] | None = None,
) -> None:
super().__init__(_min, _max, annotationparam, info_callback)
# ----AnnotatedShape API-----------------------------------------------------
def set_label_position(self) -> None:
"""Set label position, for instance based on shape position"""
plot = self.plot()
if plot is not None:
y0, y1, x = self.shape.get_handles_pos()
y = 0.5 * (y0 + y1)
x = plot.invTransform(self.xAxis(), x)
y = plot.invTransform(self.yAxis(), y)
self.label.set_pos(x, y)
class AnnotatedPolygon(AnnotatedShape):
"""
Construct an annotated polygon with properties set with *annotationparam*
(see :py:class:`.styles.AnnotationParam`)
Args:
points: List of points
closed: True if polygon is closed
annotationparam: Annotation parameters
"""
_icon_name = "polygon.png"
SHAPE_CLASS = PolygonShape
LABEL_ANCHOR = "C"
def __init__(
self,
points: list[tuple[float, float]] | None = None,
closed: bool | None = None,
annotationparam: AnnotationParam | None = None,
info_callback: Callable[[AnnotatedShape], str] | None = None,
) -> None:
super().__init__(annotationparam, info_callback)
self.shape: PolygonShape
if points is not None:
self.set_points(points)
if closed is not None:
self.set_closed(closed)
# ----Public API-------------------------------------------------------------
def set_points(self, points: list[tuple[float, float]] | np.ndarray | None) -> None:
"""Set the polygon points
Args:
points: List of point coordinates
"""
self.shape.set_points(points)
self.set_label_position()
def get_points(self) -> np.ndarray:
"""Return polygon points
Returns:
Polygon points (array of shape (N, 2))
"""
return self.shape.get_points()
def set_closed(self, state: bool) -> None:
"""Set closed state
Args:
state: True if the polygon is closed, False otherwise
"""
self.shape.set_closed(state)
def is_closed(self) -> bool:
"""Return True if the polygon is closed, False otherwise
Returns:
True if the polygon is closed, False otherwise
"""
return self.shape.is_closed()
def is_empty(self) -> bool:
"""Return True if the item is empty
Returns:
True if the item is empty, False otherwise
"""
return self.shape.is_empty()
def add_local_point(self, pos: tuple[float, float]) -> int:
"""Add a point in canvas coordinates (local coordinates)
Args:
pos: Position
Returns:
Handle of the added point
"""
pt = canvas_to_axes(self, pos)
return self.add_point(pt)
def add_point(self, pt: tuple[float, float]) -> int:
"""Add a point in axis coordinates
Args:
pt: Position
Returns:
Handle of the added point
"""
handle = self.shape.add_point(pt)
self.set_label_position()
return handle
def del_point(self, handle: int) -> int:
"""Delete a point
Args:
handle: Handle
Returns:
Handle of the deleted point
"""
handle = self.shape.del_point(handle)
self.set_label_position()
return handle
def move_local_point_to(self, handle: int, pos: QPointF, ctrl: bool = None) -> None:
"""Move a handle as returned by hit_test to the new position
Args:
handle: Handle
pos: Position
ctrl: True if <Ctrl> button is being pressed, False otherwise
"""
pt = canvas_to_axes(self, pos)
self.move_point_to(handle, pt)
def move_shape(
self, old_pos: tuple[float, float], new_pos: tuple[float, float]
) -> None:
"""Translate the shape such that old_pos becomes new_pos in axis coordinates
Args:
old_pos: Old position
new_pos: New position