-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathrange.py
More file actions
577 lines (476 loc) · 18 KB
/
range.py
File metadata and controls
577 lines (476 loc) · 18 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
# -*- coding: utf-8 -*-
from __future__ import annotations
import math
from typing import TYPE_CHECKING
import guidata.io
import numpy as np
from guidata.dataset import update_dataset
from guidata.utils.misc import assert_interfaces_valid
from qtpy import QtCore as QC
from qtpy import QtGui as QG
from plotpy.config import CONF, _
from plotpy.coords import canvas_to_axes
from plotpy.items.shape.base import AbstractShape
from plotpy.styles.shape import RangeShapeParam
if TYPE_CHECKING:
import qwt.scale_map
from qtpy.QtCore import QPointF, QRectF
from qtpy.QtGui import QPainter
from qwt import QwtSymbol
from plotpy.plot import BasePlot
from plotpy.styles.base import ItemParameters
class BaseRangeSelection(AbstractShape):
"""Range selection shape
Args:
_min: Minimum value
_max: Maximum value
shapeparam: Shape parameters
"""
_icon_name = "" # This should be set in subclasses
def __init__(
self,
_min: float | None = None,
_max: float | None = None,
shapeparam: RangeShapeParam | None = None,
) -> None:
super().__init__()
self._min = _min
self._max = _max
if shapeparam is None:
self.shapeparam = RangeShapeParam(_("Range"), icon="xrange.png")
self.shapeparam.read_config(CONF, "histogram", "range")
else:
self.shapeparam: RangeShapeParam = shapeparam
self.pen = None
self.sel_pen = None
self.brush = None
self.handle = None
self.symbol = None
self.sel_symbol = None
if self._min is not None and self._max is not None:
self.shapeparam.update_item(self) # creates all the above QObjects
def set_style(self, section: str, option: str) -> None:
"""Set style for this item
Args:
section: Section
option: Option
"""
self.shapeparam.read_config(CONF, section, option)
self.shapeparam.update_item(self)
def __reduce__(self) -> tuple[type, tuple, tuple]:
"""Return state information for pickling"""
self.shapeparam.update_param(self)
state = (self.shapeparam, self._min, self._max)
return (self.__class__, (), state)
def __setstate__(self, state: tuple) -> None:
"""Restore state information from pickling"""
self.shapeparam, self._min, self._max = state
self.shapeparam.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
"""
self.shapeparam.update_param(self)
writer.write(self.shapeparam, group_name="shapeparam")
writer.write(self._min, group_name="min")
writer.write(self._max, group_name="max")
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._min = reader.read("min")
self._max = reader.read("max")
self.shapeparam = RangeShapeParam(_("Range"), icon="xrange.png")
reader.read("shapeparam", instance=self.shapeparam)
self.shapeparam.update_item(self)
def get_handles_pos(self) -> tuple[float, float, float]:
"""Return the handles position
Returns:
Tuple with three elements (x0, x1, y) or (y0, y1, x) depending on the
orientation of the range selection. The first two elements are the
positions of the handles, and the third element is the fixed position
(either y or x) depending on the orientation.
"""
raise NotImplementedError("get_handles_pos must be implemented in subclasses")
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
"""
raise NotImplementedError("draw must be implemented in subclasses")
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
"""
raise NotImplementedError("hit_test must be implemented in subclasses")
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
"""
raise NotImplementedError(
"move_local_point_to must be implemented in subclasses"
)
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
"""
raise NotImplementedError("move_point_to must be implemented in subclasses")
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
"""
raise NotImplementedError("move_shape must be implemented in subclasses")
def boundingRect(self) -> QC.QRectF:
"""Return the bounding rectangle of the shape
Returns:
Bounding rectangle of the shape
"""
raise NotImplementedError("boundingRect must be implemented in subclasses")
def get_range(self) -> tuple[float, float]:
"""Return the range
Returns:
Tuple with two elements (min, max).
"""
return self._min, self._max
def set_range(self, _min: float, _max: float, dosignal: bool = True) -> None:
"""Set the range
Args:
_min: Minimum value
_max: Maximum value
dosignal: True to emit the SIG_RANGE_CHANGED signal
"""
self._min = _min
self._max = _max
plot = self.plot()
if dosignal and plot is not None:
plot.SIG_RANGE_CHANGED.emit(self, self._min, self._max)
def update_item_parameters(self) -> None:
"""Update item parameters (dataset) from object properties"""
self.shapeparam.update_param(self)
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.update_item_parameters()
itemparams.add("ShapeParam", self, self.shapeparam)
def set_item_parameters(self, itemparams: ItemParameters) -> None:
"""
Change the appearance of this item according
to the parameter set provided
Args:
itemparams: Item parameters
"""
update_dataset(self.shapeparam, itemparams.get("ShapeParam"), visible_only=True)
self.shapeparam.update_item(self)
self.sel_brush = QG.QBrush(self.brush)
class XRangeSelection(BaseRangeSelection):
"""X range selection shape
Args:
_min: Minimum value
_max: Maximum value
shapeparam: Shape parameters
"""
_icon_name = "xrange.png"
def get_handles_pos(self) -> tuple[float, float, float]:
"""Return the handles position
Returns:
Tuple with three elements (x0, x1, y).
"""
plot = self.plot()
assert plot is not None, "Item must be attached to a plot"
rct = plot.canvas().contentsRect()
y = rct.center().y()
x0 = plot.transform(self.xAxis(), self._min)
x1 = plot.transform(self.xAxis(), self._max)
return x0, x1, y
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
"""
plot: BasePlot = self.plot()
if not plot:
return
if self.selected:
pen: QG.QPen = self.sel_pen
sym: QwtSymbol = self.sel_symbol
else:
pen: QG.QPen = self.pen
sym: QwtSymbol = self.symbol
rct = QC.QRectF(plot.canvas().contentsRect())
rct.setLeft(xMap.transform(self._min))
rct.setRight(xMap.transform(self._max))
painter.fillRect(rct, self.brush)
painter.setPen(pen)
painter.drawLine(rct.topLeft(), rct.bottomLeft())
painter.drawLine(rct.topRight(), rct.bottomRight())
dash = QG.QPen(pen)
dash.setStyle(QC.Qt.DashLine)
dash.setWidth(1)
painter.setPen(dash)
cx = rct.center().x()
painter.drawLine(QC.QPointF(cx, rct.top()), QC.QPointF(cx, rct.bottom()))
if self.can_resize() and not self.is_readonly():
painter.setPen(pen)
x0, x1, y = self.get_handles_pos()
sym.drawSymbol(painter, QC.QPointF(x0, y))
sym.drawSymbol(painter, QC.QPointF(x1, y))
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
"""
x, _y = pos.x(), pos.y()
x0, x1, _yp = self.get_handles_pos()
d0 = math.fabs(x0 - x)
d1 = math.fabs(x1 - x)
d2 = math.fabs((x0 + x1) / 2 - x)
z = np.array([d0, d1, d2])
dist = z.min()
handle = z.argmin()
inside = bool(x0 < x < x1)
return dist, handle, inside, None
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
"""
x, _y = canvas_to_axes(self, pos)
self.move_point_to(handle, (x, 0), ctrl)
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
"""
val, _ = pos
if handle == 0:
self._min = val
elif handle == 1:
self._max = val
elif handle == 2:
move = val - (self._max + self._min) / 2
self._min += move
self._max += move
self.plot().SIG_RANGE_CHANGED.emit(self, self._min, self._max)
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
"""
dx = new_pos[0] - old_pos[0]
self._min += dx
self._max += dx
self.plot().SIG_RANGE_CHANGED.emit(self, self._min, self._max)
self.plot().replot()
def boundingRect(self) -> QC.QRectF:
"""Return the bounding rectangle of the shape
Returns:
Bounding rectangle of the shape
"""
return QC.QRectF(self._min, 0, self._max - self._min, 0)
assert_interfaces_valid(XRangeSelection)
class YRangeSelection(BaseRangeSelection):
"""Y range selection shape
Args:
_min: Minimum value
_max: Maximum value
shapeparam: Shape parameters
"""
_icon_name = "yrange.png"
def get_handles_pos(self) -> tuple[float, float, float]:
"""Return the handles position
Returns:
Tuple with three elements (y0, y1, x).
"""
plot = self.plot()
assert plot is not None, "Item must be attached to a plot"
rct = plot.canvas().contentsRect()
x = rct.center().x()
y0 = plot.transform(self.yAxis(), self._min)
y1 = plot.transform(self.yAxis(), self._max)
return y0, y1, x
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
"""
plot: BasePlot = self.plot()
if not plot:
return
if self.selected:
pen: QG.QPen = self.sel_pen
sym: QwtSymbol = self.sel_symbol
else:
pen: QG.QPen = self.pen
sym: QwtSymbol = self.symbol
rct = QC.QRectF(plot.canvas().contentsRect())
rct.setTop(yMap.transform(self._max))
rct.setBottom(yMap.transform(self._min))
painter.fillRect(rct, self.brush)
painter.setPen(pen)
painter.drawLine(rct.topLeft(), rct.topRight())
painter.drawLine(rct.bottomLeft(), rct.bottomRight())
dash = QG.QPen(pen)
dash.setStyle(QC.Qt.DashLine)
dash.setWidth(1)
painter.setPen(dash)
cy = rct.center().y()
painter.drawLine(QC.QPointF(rct.left(), cy), QC.QPointF(rct.right(), cy))
if self.can_resize() and not self.is_readonly():
painter.setPen(pen)
y0, y1, x = self.get_handles_pos()
sym.drawSymbol(painter, QC.QPointF(x, y0))
sym.drawSymbol(painter, QC.QPointF(x, y1))
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
"""
_x, y = pos.x(), pos.y()
y0, y1, _xp = self.get_handles_pos()
d0 = math.fabs(y0 - y)
d1 = math.fabs(y1 - y)
d2 = math.fabs((y0 + y1) / 2 - y)
z = np.array([d0, d1, d2])
dist = z.min()
handle = z.argmin()
inside = bool(y0 < y < y1)
return dist, handle, inside, None
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
"""
_x, y = canvas_to_axes(self, pos)
self.move_point_to(handle, (0, y), ctrl)
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
"""
_, val = pos
if handle == 0:
self._min = val
elif handle == 1:
self._max = val
elif handle == 2:
move = val - (self._max + self._min) / 2
self._min += move
self._max += move
self.plot().SIG_RANGE_CHANGED.emit(self, self._min, self._max)
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
"""
dy = new_pos[1] - old_pos[1]
self._min += dy
self._max += dy
self.plot().SIG_RANGE_CHANGED.emit(self, self._min, self._max)
self.plot().replot()
def boundingRect(self) -> QC.QRectF:
"""Return the bounding rectangle of the shape
Returns:
Bounding rectangle of the shape
"""
return QC.QRectF(0, self._min, 0, self._max - self._min)
assert_interfaces_valid(YRangeSelection)