nod3tools.py
36.2 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
# -*- coding: utf-8 -*-
import numpy as np
from guiqwt.signals import (SIG_VALIDATE_TOOL, SIG_TOOL_JOB_FINISHED, SIG_START_TRACKING,
SIG_MOVE, SIG_STOP_NOT_MOVING, SIG_STOP_MOVING)
from guiqwt.events import (KeyEventMatch, QtDragHandler, setup_standard_tool_filter)
from guiqwt.curve import CurvePlot
from guiqwt.tools import (SelectTool, AnnotatedRectangle, RectangularShapeTool, PolygonShape,
update_image_tool_status, AnnotatedEllipse,
InteractiveTool, CommandTool, DefaultToolbarID)
from guiqwt.annotations import AnnotatedPoint
from guiqwt.shapes import EllipseShape
from guiqwt.curve import PolygonMapItem
from guiqwt.geometry import (compute_center, compute_rect_size, compute_distance, compute_angle)
from guiqwt.panels import ID_XCS, ID_YCS, ID_OCS, ID_ITEMLIST, ID_CONTRAST
from guiqwt.config import _
from guiqwt.interfaces import (IColormapImageItemType, IPlotManager, IHistDataSource,
IVoiImageItemType, IExportROIImageItemType,
IStatsImageItemType, ICurveItemType)
from guidata.configtools import get_icon
from guidata.qt.QtGui import QApplication, QAction, QPolygonF
from guidata.qt.QtCore import Qt, QT_VERSION_STR, PYQT_VERSION_STR, SIGNAL, QPointF
from socket import gethostname
RAD = np.pi/180.0
GRD = 180.0/np.pi
SHAPE_Z_OFFSET = 1000
COLORS=[(0xff000000, 0x8000ff00),
(0xff0000ff, 0x800000ff),
(0xff000000, 0x80ff0000),
(0xff00ff00, 0x80000000)]
class PolygonTool(InteractiveTool):
TITLE = _("Polyline")
ICON = "polyline.png"
CURSOR = Qt.ArrowCursor
#CURSOR = Qt.CrossCursor
def __init__(self, manager, handle_final_shape_cb=None, shape_style=None,
toolbar_id=None, title=None, icon=None, tip=None):
super(PolygonTool, self).__init__(manager, toolbar_id,
title=title, icon=icon, tip=tip)
self.handle_final_shape_cb = handle_final_shape_cb
self.shape = None
self.current_handle = None
self.init_pos = None
if shape_style is not None:
self.shape_style_sect = shape_style[0]
self.shape_style_key = shape_style[1]
else:
self.shape_style_sect = "plot"
#self.shape_style_key = "shape/drag"
self.shape_style_key = "shape/label"
#self.shape_style_key = "shape/mask"
def reset(self):
self.shape = None
self.current_handle = None
def create_shape(self, filter, pt):
self.shape = PolygonShape([], closed=False)
filter.plot.add_item_with_z_offset(self.shape, SHAPE_Z_OFFSET)
self.shape.setVisible(True)
self.shape.set_style(self.shape_style_sect, self.shape_style_key)
self.shape.add_local_point(pt)
return self.shape.add_local_point(pt)
def setup_filter(self, baseplot):
filter = baseplot.filter
start_state = filter.new_state()
handler = QtDragHandler(filter, Qt.LeftButton, start_state=start_state)
filter.add_event(start_state,
KeyEventMatch((Qt.Key_Enter, Qt.Key_Return, Qt.Key_N)),
self.next_polygon, start_state)
filter.add_event(start_state,
KeyEventMatch((Qt.Key_Space, Qt.Key_Escape)),
self.validate, start_state)
filter.add_event(start_state,
KeyEventMatch((Qt.Key_Backspace, Qt.Key_Minus, Qt.Key_Delete)),
self.cancel_point, start_state)
self.Filter = filter
self.connect(handler, SIG_START_TRACKING, self.mouse_press)
self.connect(handler, SIG_MOVE, self.move)
self.connect(handler, SIG_STOP_NOT_MOVING, self.mouse_release)
self.connect(handler, SIG_STOP_MOVING, self.mouse_release)
return setup_standard_tool_filter(filter, start_state)
def set_polygon(self):
if not hasattr(self.shape, 'get_points'): return
points = list(self.shape.get_points())
points.append(points[0])
ndim, mdim = np.shape(points)
offsets = np.zeros((ndim, 2))
colors = np.zeros((ndim, 2), np.uint32)
colors[:,0] = 0xff00ff00
colors[:,1] = 0x80000000
crv = PolygonMapItem()
crv.set_data(points, offsets, colors)
self.Filter.plot.add_item(crv)
self.Filter.plot.replot()
self.points = np.array(points)
def next_polygon(self, filter, event):
super(PolygonTool, self).validate(filter, event)
if self.Finis: return
self.set_polygon()
if self.handle_final_shape_cb is not None:
self.handle_final_shape_cb(self.shape)
self.reset()
### should we apply function all times?
##m, p = self.funct(self.obj, self.param, self.points)
self.nextpoints.append(self.points)
def validate(self, filter, event):
super(PolygonTool, self).validate(filter, event)
for itm in self.Filter.plot.get_items():
if str(itm).find("PolygonShape") > 0:
self.Filter.plot.del_item(itm)
if self.Finis: return
self.set_polygon()
if self.handle_final_shape_cb is not None:
self.handle_final_shape_cb(self.shape)
self.reset()
self.emit(SIG_VALIDATE_TOOL, filter)
self.emit(SIG_TOOL_JOB_FINISHED)
self.deactivate()
self.Finis = True
self.listwidget.selectionModel().currentIndex()
QApplication.restoreOverrideCursor()
if not hasattr(self, "points"):
return
if self.nextpoints == [] or np.all(self.nextpoints[-1] != self.points):
self.nextpoints.append(self.points)
m, p = self.funct(self.obj, self.param, self.nextpoints)
if m != []: self.handle_input_output([m], lambda m, p: (m, p), p, onein=True)
def cancel_point(self, filter, event):
if self.Finis: return
if self.shape is None:
return
points = self.shape.get_points()
if points is None:
return
elif len(points) <= 2:
filter.plot.del_item(self.shape)
self.reset()
else:
if self.current_handle:
newh = self.shape.del_point(self.current_handle)
else:
newh = self.shape.del_point(-1)
self.current_handle = newh
filter.plot.replot()
def mouse_press(self, filter, event):
"""We create a new shape if it's the first point
otherwise we add a new point
"""
if self.Finis: return
if self.shape is None:
self.init_pos = event.pos()
self.current_handle = self.create_shape(filter, event.pos())
filter.plot.replot()
else:
self.current_handle = self.shape.add_local_point(event.pos())
def move(self, filter, event):
"""moving while holding the button down lets the user
position the last created point
"""
if self.Finis: return
if self.shape is None or self.current_handle is None:
# Error ??
return
self.shape.move_local_point_to(self.current_handle, event.pos())
filter.plot.replot()
def mouse_release(self, filter, event):
"""Releasing the mouse button validate the last point position"""
if self.Finis: return
if self.current_handle is None:
return
if self.init_pos is not None and self.init_pos == event.pos():
self.shape.del_point(-1)
else:
self.shape.move_local_point_to(self.current_handle, event.pos())
self.init_pos = None
self.current_handle = None
filter.plot.replot()
class MapEllipse(AnnotatedEllipse):
ICON = "ellipse_shape.png"
def __init__(self, x1=0, y1=0, x2=0, y2=0, ratio=1.0, annotationparam=None):
super(MapEllipse, self).__init__(x1, y1, x2, y2, annotationparam)
self.image_item = None
self.ratio = ratio
if ratio < 0: self.shape.switch_to_ellipse()
if abs(ratio) == 2: self.vis = False
else: self.vis = True
def set_image_item(self, image_item):
self.image_item = image_item
self.set_label_visible(self.vis)
#self.set_label_visible(False)
#self.set_label_visible(True)
def set_label_position(self):
global positions
"""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))
if not self.is_label_visible():
self.label.set_pos((x2+x1)/2, y1)
angle = self.get_tr_angle()
positions = self.get_tr_center(), self.get_tr_size(), angle, self.get_rect()
def x_to_str(self, x):
"""Convert x (float) to a string
(with associated unit and uncertainty)"""
param = self.annotationparam
if self.plot() is None:
return ''
else:
xunit = self.plot().get_axis_unit(self.xAxis())
if xunit == None: xunit = "pixel"
fmt = param.format
if param.uncertainty:
fmt += u" ± "+(fmt % (x*param.uncertainty))
return (fmt+" "+xunit) % x
def y_to_str(self, y):
"""Convert y (float) to a string
(with associated unit and uncertainty)"""
param = self.annotationparam
if self.plot() is None:
return ''
else:
yunit = self.plot().get_axis_unit(self.yAxis())
if yunit == None: yunit = "pixel"
fmt = param.format
if param.uncertainty:
fmt += u" ± "+(fmt % (y*param.uncertainty))
return (fmt+" "+yunit) % y
def get_tr_center(self):
"""Return shape center coordinates after applying transform matrix"""
return self.shape.get_center()
#raise NotImplementedError
def get_tr_center_str(self):
"""Return center coordinates as a string (with units)"""
xc, yc = self.get_tr_center()
return "( %s ; %s )" % (self.x_to_str(xc), self.y_to_str(yc))
def get_text(self):
"""
Return text associated to current shape
(see :py:class:`guiqwt.label.ObjectInfo`)
"""
text = ""
title = self.title().text()
if title:
text += "<b>%s</b>" % title
subtitle = self.annotationparam.subtitle
if subtitle:
if text:
text += "<br>"
text += "<i>%s</i>" % subtitle
if self.area_computations_visible:
infos = self.get_infos()
if infos:
if text:
text += "<br>"
text += infos
return text
def get_tr_angle(self):
"""Return X-diameter angle with horizontal direction,
after applying transform matrix"""
x1, y1, x2, y2 = self.get_transformed_coords(0, 1)
angle = np.arctan2((y2-y1), (x2-x1))*GRD
return angle
def get_infos(self):
global positions
"""Return formatted string with informations on current shape"""
self.set_label_position()
angle = self.get_tr_angle()
positions = self.get_tr_center(), self.get_tr_size(), angle, self.get_rect()
return "<br>".join([
_("Center:") + " " + self.get_tr_center_str(),
_("Size:") + " " + self.get_tr_size_str(),
_(u"Angle:") + u" %.1f°" % angle,
])
class MapRectangle(AnnotatedRectangle):
ICON = "rectangle.png"
def __init__(self, x1=0, y1=0, x2=0, y2=0, annotationparam=None):
super(MapRectangle, self).__init__(x1, y1, x2, y2, annotationparam)
self.image_item = None
def set_image_item(self, image_item):
self.image_item = image_item
#self.set_label_visible(False)
self.set_label_visible(True)
def set_label_position(self):
global positions
"""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))
if not self.is_label_visible():
xc, yc = self.get_tr_center()
xs, ys = self.get_tr_size()
positions = (xc, yc), (xs, ys), self.get_rect()
def get_text(self):
"""
Return text associated to current shape
(see :py:class:`guiqwt.label.ObjectInfo`)
"""
text = ""
title = self.title().text()
if title:
text += "<b>%s</b>" % title
subtitle = self.annotationparam.subtitle
if subtitle:
if text:
text += "<br>"
text += "<i>%s</i>" % subtitle
if self.area_computations_visible:
infos = self.get_infos()
if infos:
if text:
text += "<br>"
text += infos
return text
def get_infos(self):
global positions
"""Return formatted string with informations on current shape"""
xc, yc = self.get_tr_center()
xs, ys = self.get_tr_size()
self.set_label_position()
positions = (xc, yc), (xs, ys), self.get_rect()
return "<br>".join([
_("Center: %.3f ; %.3f" % (xc, yc)),
_("Size: %.3f x %.3f" % (abs(xs), abs(ys))),
_("Hit [space]-key to abort"),
])
class MapSelectTool(RectangularShapeTool):
SWITCH_TO_DEFAULT_TOOL = True
TITLE = _("Box Selection")
ICON = "rectangle.png"
TIP = "press <space> key to leave program"
SHAPE_STYLE_KEY = "shape/image_stats"
#SHAPE_STYLE_KEY = "shape/segment"
def __init__(self, manager, setup_shape_cb=None, handle_final_shape_cb=None, shape_cb="box",
shape_style=None, toolbar_id=None, title=None, icon=ICON, tip=None):
super(MapSelectTool, self).__init__(manager, setup_shape_cb,
handle_final_shape_cb, shape_style, toolbar_id,
title, icon, tip)
self._last_item = None
self.shape_cb = shape_cb
def set_shape(self, x0, y0, x1, y1):
self.x0 = x0
self.y0 = y0
self.x1 = x1
self.y1 = y1
def create_shape(self):
x0 = self.x0
y0 = self.y0
x1 = self.x1
y1 = self.y1
if self.shape_cb == "Ellipse": annotate = MapEllipse(x0, y0, x1, y1, ratio=-2), 0, 1
elif self.shape_cb == "ellipse": annotate = MapEllipse(x0, y0, x1, y1, ratio=-1), 0, 1
elif self.shape_cb == "Circle": annotate = MapEllipse(x0, y0, x1, y1, ratio=2), 0, 1
elif self.shape_cb == "circle": annotate = MapEllipse(x0, y0, x1, y1, ratio=1), 0, 1
elif self.shape_cb == "box": annotate = MapRectangle(x0, y0, x1, y1), 0, 2
return annotate
def set_image_item(self, image_item):
self.image_item = image_item
def setup_shape(self, shape):
super(MapSelectTool, self).setup_shape(shape)
shape.setTitle('')
self.set_shape_style(shape)
self.register_shape(shape, final=False)
def register_shape(self, shape, final=False):
plot = shape.plot()
if plot is not None:
plot.unselect_all()
plot.set_active_item(shape)
self.sfl = plot.get_aspect_ratio()
shape.set_image_item(self._last_item)
def handle_final_shape(self, shape):
super(MapSelectTool, self).handle_final_shape(shape)
self.register_shape(shape, final=True)
def KeyEvent(self, parent):
if parent.start_state.items() != []:
baseplot, start_state = parent.start_state.items()[-1]
filter = baseplot.filter
filter.add_event(start_state,
KeyEventMatch((Qt.Key_Space, Qt.Key_Escape)),
self.validate, start_state)
if self.nextbox:
filter.add_event(start_state,
KeyEventMatch((Qt.Key_Enter, Qt.Key_Return, Qt.Key_N)),
self.next_validate, start_state)
self.Filter = filter
#print "KeyEvent setup", start_state, 'parent'
def next_validate(self, filter, event):
global positions
#print "next key event", self.Finis
if self.Finis: return
pos = [[positions[2][0], positions[2][1]], [positions[2][0], positions[2][3]],
[positions[2][0], positions[2][3]], [positions[2][2], positions[2][3]],
[positions[2][2], positions[2][3]], [positions[2][2], positions[2][1]],
[positions[2][2], positions[2][1]], [positions[2][0], positions[2][1]]]
off = [[0, 0], [0,0], [0,0], [0,0]]
color = [(0xff00ff00, 0x80000000),
(0xff00ff00, 0x80000000),
(0xff00ff00, 0x80000000),
(0xff00ff00, 0x80000000)]
crv = PolygonMapItem()
crv.set_data(pos, off, color)
self.Filter.plot.add_item(crv)
self.Filter.plot.replot()
#m, p = self.funct(self.obj, self.param, positions[0], positions[1])
#m, p = self.funct(self.obj, self.param, positions[2])
if self.onein == True:
m, p = self.funct(self.obj, self.param, positions)
else:
m, p = self.funct(self.objs, self.param, positions)
self.nextpos = pos
def validate(self, filter, event):
global positions
for itm in self.Filter.plot.get_items():
if str(itm).find("PolygonShape") > 0:
self.Filter.plot.del_item(itm)
#print "stop key event"
if self.Finis: return
self.emit(SIG_VALIDATE_TOOL, filter)
self.emit(SIG_TOOL_JOB_FINISHED)
self.deactivate()
self.Finis = True
self.listwidget.selectionModel().currentIndex()
if self.nextpos == [] or np.all(self.nextpos != positions[2]):
#m, p = self.funct(self.obj, self.param, positions[0], positions[1])
#m, p = self.funct(self.obj, self.param, positions[2])
if self.onein == True:
m, p = self.funct(self.obj, self.param, positions)
else:
m, p = self.funct(self.objs, self.param, positions)
if m != []: self.handle_input_output([m], lambda m, p: (m, p), p, onein=True)
class CrossSectionTool(CommandTool):
SWITCH_TO_DEFAULT_TOOL = False
TITLE = _("Cross section")
PANEL_IDS = (ID_XCS, ID_YCS)
def __init__(self, manager, toolbar_id=DefaultToolbarID):
super(CrossSectionTool, self).__init__(manager, _("CrossSectionPlot"),
tip=_("CrossSection creates X- and Y- profiles"), toolbar_id=toolbar_id)
self.action.setEnabled(True)
self.action.setIconText("")
self.action.setCheckable(True)
self.default_icon = get_icon('csection.png')
self.action.setIcon(self.default_icon)
self.last_final_shape = None
def create_action(self, manager):
"""Create and return tool's action"""
return manager.create_action(self.title, icon=self.icon,
tip=self.tip, triggered=self.activate)
def activate(self, checked=True):
"""Activate tool"""
plot = self.get_active_plot()
if plot is not None:
self.activate_command(plot, checked)
for panel_id in self.PANEL_IDS:
panel = self.manager.get_panel(panel_id)
panel.setVisible(checked)
def activate_command(self, plot, checked):
for panel_id in self.PANEL_IDS:
panel = self.manager.get_panel(panel_id)
class ContrastTool(CommandTool):
panel_name = _("Contrast adjustment")
panel_id = ID_CONTRAST
def __init__(self, manager, toolbar_id=DefaultToolbarID):
super(ContrastTool, self).__init__(manager, _("ContrastPanel"),
tip=_("Contrast adjustment (toggle)\nClick image few times"),
toolbar_id=toolbar_id)
self.action.setEnabled(False)
self.action.setIconText("")
self.action.setCheckable(True)
self.default_icon = get_icon('contrast.png')
self.action.setIcon(self.default_icon)
self.default_tool = manager.get_default_tool()
def get_histogram(self, nbins):
"""interface on IHistDataSource"""
if self.data is None:
return [0,], [0,1]
mask = ~np.isnan(self.data)
return np.histogram(self.data[mask], nbins)
def activate_command(self, plot, checked):
"""Activate tool"""
if not checked:
self.default_tool.activate()
panel = self.manager.get_panel(self.panel_id)
panel.setVisible(checked)
plot.Aspect = not checked
plot.lock_aspect_ratio = plot.Aspect
if plot.lock_aspect_ratio:
plot.apply_aspect_ratio(full_scale=False)
plot.replot()
item = plot.get_last_active_item(IVoiImageItemType)
if item is None:
item.selected = True
def update_status(self, plot):
super(ContrastTool, self).update_status(plot)
update_image_tool_status(self, plot)
item = plot.get_last_active_item(IVoiImageItemType)
self.action.setEnabled(item is not None)
if item is not None:
self.data = item.data
item.get_histogram = self.get_histogram
item.selected = True
#############################################################################
##
## This file was adapted from Taurus, a Tango User Interface Library
##
## http://www.tango-controls.org/static/taurus/latest/doc/html/index.html
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Taurus is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## Taurus is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with Taurus. If not, see <http://www.gnu.org/licenses/>.
##
#############################################################################
"""Extension of :mod:`guiqwt.tools`"""
__docformat__ = 'restructuredtext'
#from PyQt4 import Qt,Qwt5
from PyQt4 import Qt as QT
from PyQt4 import Qwt5
from guiqwt.tools import CommandTool, QActionGroup, add_actions
from guiqwt.signals import SIG_ITEMS_CHANGED
#from scales import DeltaTimeScaleEngine
class TimeAxisTool(CommandTool):
"""
A tool that allows the user to change the type of scales to/from time mode.
When a scale is in time mode, the values are interpreted as timestamps
(seconds since epoch)
"""
def __init__(self, manager):
super(TimeAxisTool, self).__init__(manager, "Time Scale",
tip=None, toolbar_id=None)
self.action.setEnabled(False)
self.set_scale_t_t(False)
def create_action_menu(self, manager):
"""Create and return menu for the tool's action"""
menu = QT.QMenu()
group = QActionGroup(manager.get_main())
y_x = manager.create_action("y(x)", toggled=self.set_scale_y_x)
y_t = manager.create_action("y(t)", toggled=self.set_scale_y_t)
t_x = manager.create_action("t(x)", toggled=self.set_scale_t_x)
t_t = manager.create_action("t(t)", toggled=self.set_scale_t_t)
self.scale_menu = {(False, False): y_x, (False, True): y_t,
(True, False): t_x, (True, True): t_t}
for obj in (group, menu):
add_actions(obj, (y_x, y_t, t_x, t_t))
#add_actions(obj, (y_x, t_t))
return menu
def _getAxesUseTime(self, item):
"""
Returns a tuple (xIsTime, yIsTime) where xIsTime is True if the item's x
axis uses a TimeScale. yIsTime is True if the item's y axis uses a Time
Scale. Otherwise they are False.
"""
plot = item.plot()
if plot is None:
return (False,False)
#return (True,True)
xEngine = plot.axisScaleEngine(item.xAxis())
yEngine = plot.axisScaleEngine(item.yAxis())
return isinstance(xEngine, DeltaTimeScaleEngine), isinstance(yEngine, DeltaTimeScaleEngine)
def update_status(self, plot):
item = plot.get_active_item()
active_scale = (False, False)
if item is not None:
#active_scale = self._getAxesUseTime(item)
if hasattr(plot, 'AxesUseTime'):
useTime = plot.AxesUseTime
else:
useTime = False
if hasattr(plot, 'Descript'):
des = plot.Descript
else:
des = False
active_scale = (useTime, useTime)
if hasattr(plot, 'NewPlot') and plot.NewPlot and useTime:
plot.NewPlot = False
self.set_scale_t_t(True)
for scale_type, scale_action in self.scale_menu.items():
if item is None:
scale_action.setEnabled(True)
else:
#scale_action.setEnabled(True)
if active_scale == scale_type:
scale_action.setChecked(True)
else:
scale_action.setChecked(False)
def _setPlotTimeScales(self, xIsTime, yIsTime):
plot = self.get_active_plot()
if plot is not None:
for axis,isTime in zip(plot.get_active_axes(), (xIsTime, yIsTime)):
if isTime:
if axis == 0:
DeltaTimeScaleEngine.enableInAxis(plot, axis, rotation=-90)
else:
DeltaTimeScaleEngine.enableInAxis(plot, axis, rotation=0)
else:
DeltaTimeScaleEngine.disableInAxis(plot, axis)
plot.replot()
def set_scale_y_x(self, checked):
if not checked:
return
self._setPlotTimeScales(False, False)
def set_scale_t_x(self, checked):
if not checked:
return
self._setPlotTimeScales(False, True)
def set_scale_y_t(self, checked):
if not checked:
return
self._setPlotTimeScales(True, False)
def set_scale_t_t(self, checked):
if not checked:
return
self._setPlotTimeScales(True, True)
#############################################################################
##
## This file was adapted from Taurus, a Tango User Interface Library
##
## http://www.tango-controls.org/static/taurus/latest/doc/html/index.html
##
## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain
##
## Taurus is free software: you can redistribute it and/or modify
## it under the terms of the GNU Lesser General Public License as published by
## the Free Software Foundation, either version 3 of the License, or
## (at your option) any later version.
##
## Taurus is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU Lesser General Public License for more details.
##
## You should have received a copy of the GNU Lesser General Public License
## along with Taurus. If not, see <http://www.gnu.org/licenses/>.
##
#############################################################################
"""
scales.py: Custom scales
"""
__all__=["DateTimeScaleEngine", "DeltaTimeScaleEngine", "FixedLabelsScaleEngine",
"FancyScaleDraw", "TaurusTimeScaleDraw", "DeltaTimeScaleDraw",
"FixedLabelsScaleDraw"]
import numpy
from datetime import datetime #, timedelta
from time import mktime
#from PyQt4 import Qt, Qwt5
from PyQt4 import Qt as QT
from PyQt4 import Qwt5
def TimeDelta(val, typ):
'''returns h:m:s or d:m:s for axis labels'''
h = int(val/3600)
m = int((val-3600*h)/60)
s = int((val-3600*h-60*m))
ms = int(10*abs((val-3600*h-60*m) - s))
if typ == "d":
return "".join([u"%d°" % h, "%2.2d'" % m, '%2.2d"' % s])
#return "".join([u"%d°" % h, "%2.2d'" % m, '%2.2d.' % s, '%1.1d"' % ms])
else:
return "".join([u"%d<sup>h</sup>" % h, "%2.2d<sup>m</sup>" % m, '%2.2d<sup>s</sup>' % s])
#return "".join([u"%d<sup>h</sup>" % h, "%2.2d<sup>m</sup>" % m, "%2.2d." % s, '%1.1d<sup>s</sup>' % ms])
def _getDefaultAxisLabelsAlignment(axis, rotation):
'''return a "smart" alignment for the axis labels depending on the axis
and the label rotation
:param axis: (Qwt5.QwtPlot.Axis) the axis
:param rotation: (float) The rotation (in degrees, clockwise-positive)
:return: (QT.Alignment) an alignment
'''
if axis == Qwt5.QwtPlot.xBottom:
if rotation == 0 : return QT.Qt.AlignHCenter|QT.Qt.AlignBottom
elif rotation < 0: return QT.Qt.AlignLeft|QT.Qt.AlignBottom
else: return QT.Qt.AlignRight|QT.Qt.AlignBottom
elif axis == Qwt5.QwtPlot.yLeft:
if rotation == 0 : return QT.Qt.AlignLeft|QT.Qt.AlignVCenter
#elif rotation < 0: return QT.Qt.AlignLeft|QT.Qt.AlignBottom
elif rotation < 0: return QT.Qt.AlignVCenter|QT.Qt.AlignVCenter
else: return QT.Qt.AlignLeft|Qt.QT.AlignTop
elif axis == Qwt5.QwtPlot.yRight:
if rotation == 0 : return QT.Qt.AlignRight|QT.Qt.AlignVCenter
elif rotation < 0: return QT.Qt.AlignRight|QT.Qt.AlignTop
else: return QT.Qt.AlignRight|QT.Qt.AlignBottom
elif axis == Qwt5.QwtPlot.xTop:
if rotation == 0 : return QT.Qt.AlignHCenter|QT.Qt.AlignTop
elif rotation < 0: return QT.Qt.AlignLeft|QT.QT.AlignTop
else: return QT.Qt.AlignRight|QT.Qt.AlignTop
class FancyScaleDraw(Qwt5.QwtScaleDraw):
'''This is a scaleDraw with a tuneable palette and label formats'''
def __init__(self, format = None, palette = None):
Qwt5.QwtScaleDraw.__init__(self)
self._labelFormat = format
self._palette = palette
def setPalette(self, palette):
'''pass a QPalette or None to use default'''
self._palette = palette
def getPalette(self):
return self._palette
def setLabelFormat(self, format):
'''pass a format string (e.g. "%g") or None to use default (it uses the locale)'''
self._labelFormat = format
self.invalidateCache() #to force repainting of the labels
def getLabelFormat(self):
'''pass a format string (e.g. "%g") or None to use default (it uses the locale)'''
return self._labelFormat
def label(self, val):
if str(self._labelFormat) == "": return Qwt5.QwtText()
if self._labelFormat is None:
return Qwt5.QwtScaleDraw.label(self, val)
else:
return Qwt5.QwtText(self._labelFormat%val)
def draw(self, painter, palette):
if self._palette is None:
Qwt5.QwtScaleDraw.draw(self, painter, palette)
else:
Qwt5.QwtScaleDraw.draw(self, painter, self._palette)
class DeltaTimeScaleEngine(Qwt5.QwtLinearScaleEngine):
def __init__(self, scaleDraw=None):
Qwt5.QwtLinearScaleEngine.__init__(self)
self.setScaleDraw(scaleDraw)
def setScaleDraw(self, scaleDraw):
self._scaleDraw = scaleDraw
def scaleDraw(self):
return self._scaleDraw
def divideScale(self, x1, x2, maxMajSteps, maxMinSteps, stepSize):
''' Reimplements Qwt5.QwtLinearScaleEngine.divideScale
:return: (Qwt5.QwtScaleDiv) a scale division whose ticks are aligned with
the natural delta time units '''
interval = Qwt5.QwtDoubleInterval(x1, x2).normalized()
if interval.width() <= 0:
return Qwt5.QwtScaleDiv()
d_range = interval.width()
#if d_range > 7200: f = 1
if d_range > 3*3600: f = 1
else: f = 0.5
s = 3600
#calculate a step size that respects the base step (s) and also enforces the maxMajSteps
stepSize = f * s * int(numpy.ceil(float(d_range//s)/maxMajSteps))
return Qwt5.QwtLinearScaleEngine.divideScale(self, x1, x2, maxMajSteps, maxMinSteps, stepSize)
@staticmethod
def getDefaultAxisLabelsAlignment(axis, rotation):
'''return a "smart" alignment for the axis labels depending on the axis
and the label rotation
:param axis: (Qwt5.QwtPlot.Axis) the axis
:param rotation: (float) The rotation (in degrees, clockwise-positive)
:return: (QT.Alignment) an alignment
'''
return _getDefaultAxisLabelsAlignment(axis, rotation)
@staticmethod
def enableInAxis(plot, axis, scaleDraw =None, rotation=None):
'''convenience method that will enable this engine in the given
axis. Note that it changes the ScaleDraw as well.
:param plot: (Qwt5.QwtPlot) the plot to change
:param axis: (Qwt5.QwtPlot.Axis) the id of the axis
:param scaleDraw: (Qwt5.QwtScaleDraw) Scale draw to use. If None given,
the current ScaleDraw for the plot will be used if
possible, and a :class:`TaurusTimeScaleDraw` will be set if not
:param rotation: (float or None) The rotation of the labels (in degrees, clockwise-positive)
'''
#if not hasattr(plot, 'Descript'): plot.Descript = False
if hasattr(plot, 'Descript'):
des = plot.Descript
else:
des = False
scale = 1
if hasattr(plot, 'AxisUseHour'):
if plot.AxisUseHour:
if axis == plot.xBottom:
scale = 1.0/15.0
if scaleDraw is None:
scaleDraw = plot.axisScaleDraw(axis)
#if not isinstance(scaleDraw, DeltaTimeScaleDraw):
# scaleDraw = DeltaTimeScaleDraw((scale, des))
scaleDraw = DeltaTimeScaleDraw((scale, des))
plot.setAxisScaleDraw(axis, scaleDraw)
plot.setAxisScaleEngine(axis, DeltaTimeScaleEngine(scaleDraw))
if rotation is not None:
alignment = DeltaTimeScaleEngine.getDefaultAxisLabelsAlignment(axis, rotation)
plot.setAxisLabelRotation(axis, rotation)
plot.setAxisLabelAlignment(axis, alignment)
@staticmethod
def disableInAxis(plot, axis, scaleDraw=None, scaleEngine=None):
'''convenience method that will disable this engine in the given
axis. Note that it changes the ScaleDraw as well.
:param plot: (Qwt5.QwtPlot) the plot to change
:param axis: (Qwt5.QwtPlot.Axis) the id of the axis
:param scaleDraw: (Qwt5.QwtScaleDraw) Scale draw to use. If None given,
a :class:`FancyScaleDraw` will be set
:param scaleEngine: (Qwt5.QwtScaleEngine) Scale draw to use. If None given,
a :class:`Qwt5.QwtLinearScaleEngine` will be set
'''
if scaleDraw is None:
scaleDraw=FancyScaleDraw()
if scaleEngine is None:
scaleEngine = Qwt5.QwtLinearScaleEngine()
plot.setAxisScaleEngine(axis, scaleEngine)
plot.setAxisScaleDraw(axis, scaleDraw)
class DeltaTimeScaleDraw(FancyScaleDraw):
def __init__(self, *args):
FancyScaleDraw.__init__(self, *args)
self.scale, self.des = args[0]
def label(self, Val):
val = self.scale*Val
if val >= 0:
#s = "%s"%str(timedelta(seconds=val))
if self.des:
if val == 0: s = "%s" % TimeDelta(val, 'd')
else: s = "+%s" % TimeDelta(val, 'd')
else:
if self.scale < 0.1: # scale=1./15.
s = "%s" % TimeDelta(val, 'h')
else:
s = "%s" % TimeDelta(val, 'd')
else:
#s = "-%s"%str(timedelta(seconds=-val))
if self.scale < 0.1: # scale=1./15.
s = "-%s" % TimeDelta(-val, 'h')
else:
s = "-%s" % TimeDelta(-val, 'd')
return Qwt5.QwtText(s)
from matplotlib import path
def pnpoly(x, y, xyverts):
p = path.Path(xyverts)
return p.contains_point(x, y)
def points_inside_poly(xypoints, xyverts):
p = path.Path(xyverts)
return p.contains_points(xypoints)