-
Notifications
You must be signed in to change notification settings - Fork 0
/
Full_module.py
2543 lines (2161 loc) · 97.7 KB
/
Full_module.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 -*-
"""
Created on Thu Nov 26 15:06:52 2020
@author: Kristaps
"""
#-----------------------------------------------------------------------------
# Name: wx.lib.plot.py
# Purpose: Line, Bar and Scatter Graphs
#
# Author: Gordon Williams
#
# Created: 2003/11/03
# RCS-ID: $Id$
# Copyright: (c) 2002
# Licence: Use as you wish.
#-----------------------------------------------------------------------------
# 12/15/2003 - Jeff Grimmett ([email protected])
#
# o 2.5 compatability update.
# o Renamed to plot.py in the wx.lib directory.
# o Reworked test frame to work with wx demo framework. This saves a bit
# of tedious cut and paste, and the test app is excellent.
#
# 12/18/2003 - Jeff Grimmett ([email protected])
#
# o wxScrolledMessageDialog -> ScrolledMessageDialog
#
# Oct 6, 2004 Gordon Williams ([email protected])
# - Added bar graph demo
# - Modified line end shape from round to square.
# - Removed FloatDCWrapper for conversion to ints and ints in arguments
#
# Oct 15, 2004 Gordon Williams ([email protected])
# - Imported modules given leading underscore to name.
# - Added Cursor Line Tracking and User Point Labels.
# - Demo for Cursor Line Tracking and Point Labels.
# - Size of plot preview frame adjusted to show page better.
# - Added helper functions PositionUserToScreen and PositionScreenToUser in PlotCanvas.
# - Added functions GetClosestPoints (all curves) and GetClosestPoint (only closest curve)
# can be in either user coords or screen coords.
#
# Jun 22, 2009 Florian Hoech ([email protected])
# - Fixed exception when drawing empty plots on Mac OS X
# - Fixed exception when trying to draw point labels on Mac OS X (Mac OS X
# point label drawing code is still slow and only supports wx.COPY)
# - Moved label positions away from axis lines a bit
# - Added PolySpline class and modified demo 1 and 2 to use it
# - Added center and diagonal lines option (Set/GetEnableCenterLines,
# Set/GetEnableDiagonals)
# - Added anti-aliasing option with optional high-resolution mode
# (Set/GetEnableAntiAliasing, Set/GetEnableHiRes) and demo
# - Added option to specify exact number of tick marks to use for each axis
# (SetXSpec(<number>, SetYSpec(<number>) -- work like 'min', but with
# <number> tick marks)
# - Added support for background and foreground colours (enabled via
# SetBackgroundColour/SetForegroundColour on a PlotCanvas instance)
# - Changed PlotCanvas printing initialization from occuring in __init__ to
# occur on access. This will postpone any IPP and / or CUPS warnings
# which appear on stderr on some Linux systems until printing functionality
# is actually used.
#
#
"""
This is a simple light weight plotting module that can be used with
Boa or easily integrated into your own wxPython application. The
emphasis is on small size and fast plotting for large data sets. It
has a reasonable number of features to do line and scatter graphs
easily as well as simple bar graphs. It is not as sophisticated or
as powerful as SciPy Plt or Chaco. Both of these are great packages
but consume huge amounts of computer resources for simple plots.
They can be found at http://scipy.com
This file contains two parts; first the re-usable library stuff, then,
after a "if __name__=='__main__'" test, a simple frame and a few default
plots for examples and testing.
Based on wxPlotCanvas
Written by K.Hinsen, R. Srinivasan;
Ported to wxPython Harm van der Heijden, feb 1999
Major Additions Gordon Williams Feb. 2003 ([email protected])
-More style options
-Zooming using mouse "rubber band"
-Scroll left, right
-Grid(graticule)
-Printing, preview, and page set up (margins)
-Axis and title labels
-Cursor xy axis values
-Doc strings and lots of comments
-Optimizations for large number of points
-Legends
Did a lot of work here to speed markers up. Only a factor of 4
improvement though. Lines are much faster than markers, especially
filled markers. Stay away from circles and triangles unless you
only have a few thousand points.
Times for 25,000 points
Line - 0.078 sec
Markers
Square - 0.22 sec
dot - 0.10
circle - 0.87
cross,plus - 0.28
triangle, triangle_down - 0.90
Thanks to Chris Barker for getting this version working on Linux.
Zooming controls with mouse (when enabled):
Left mouse drag - Zoom box.
Left mouse double click - reset zoom.
Right mouse click - zoom out centred on click location.
"""
import string as _string
import time as _time
import sys
import wx
from numba import jit
# Needs NumPy
try:
import numpy as np
except:
msg = """
This module requires the NumPy module, which could not be
imported. It probably is not installed (it's not part of the
standard Python distribution). See the Numeric Python site
(http://numpy.scipy.org) for information on downloading source or
binaries."""
raise ImportError("NumPy not found.\n" + msg)
#
# Plotting classes...
#
class PolyPoints:
"""Base Class for lines and markers
- All methods are private.
"""
def __init__(self, points, attr):
self._points = np.array(points).astype(np.float64)
self._logscale = (False, False)
self._pointSize = (1.0, 1.0)
self.currentScale = (1, 1)
self.currentShift = (0, 0)
self.scaled = self.points
self.attributes = {}
self.attributes.update(self._attributes)
for name, value in attr.items():
if name not in self._attributes.keys():
raise KeyError(
"Style attribute incorrect. Should be one of %s" % self._attributes.keys())
self.attributes[name] = value
def setLogScale(self, logscale):
self._logscale = logscale
def __getattr__(self, name):
if name == 'points':
if len(self._points) > 0:
data = np.array(self._points, copy=True)
if self._logscale[0]:
data = self.log10(data, 0)
if self._logscale[1]:
data = self.log10(data, 1)
return data
else:
return self._points
else:
raise AttributeError(name)
@jit(nopython=True)
def log10(self, data, ind):
data = np.compress(data[:, ind] > 0, data, 0)
data[:, ind] = np.log10(data[:, ind])
return data
def boundingBox(self):
if len(self.points) == 0:
# no curves to draw
# defaults to (-1,-1) and (1,1) but axis can be set in Draw
minXY = np.array([-1.0, -1.0])
maxXY = np.array([1.0, 1.0])
else:
minXY = np.minimum.reduce(self.points)
maxXY = np.maximum.reduce(self.points)
return minXY, maxXY
def scaleAndShift(self, scale=(1, 1), shift=(0, 0)):
if len(self.points) == 0:
# no curves to draw
return
if (scale is not self.currentScale) or (shift is not self.currentShift):
# update point scaling
self.scaled = scale * self.points + shift
self.currentScale = scale
self.currentShift = shift
# else unchanged use the current scaling
def getLegend(self):
return self.attributes['legend']
def getClosestPoint(self, pntXY, pointScaled=True):
"""Returns the index of closest point on the curve, pointXY, scaledXY, distance
x, y in user coords
if pointScaled == True based on screen coords
if pointScaled == False based on user coords
"""
if pointScaled == True:
# Using screen coords
p = self.scaled
pxy = self.currentScale * np.array(pntXY) + self.currentShift
else:
# Using user coords
p = self.points
pxy = np.array(pntXY)
# determine distance for each point
d = np.sqrt(np.add.reduce((p - pxy) ** 2, 1)) # sqrt(dx^2+dy^2)
pntIndex = np.argmin(d)
dist = d[pntIndex]
return [pntIndex, self.points[pntIndex], self.scaled[pntIndex] / self._pointSize, dist]
class PolyLine(PolyPoints):
"""Class to define line type and style
- All methods except __init__ are private.
"""
_attributes = {'colour': 'black',
'width': 1,
'style': wx.PENSTYLE_SOLID,
'legend': ''}
def __init__(self, points, **attr):
"""
Creates PolyLine object
:param `points`: sequence (array, tuple or list) of (x,y) points making up line
:keyword `attr`: keyword attributes, default to:
========================== ================================
'colour'= 'black' wx.Pen Colour any wx.NamedColour
'width'= 1 Pen width
'style'= wx.PENSTYLE_SOLID wx.Pen style
'legend'= '' Line Legend to display
========================== ================================
"""
PolyPoints.__init__(self, points, attr)
@jit(nopython=True)
def draw(self, dc, printerScale, coord=None):
colour = self.attributes['colour']
width = self.attributes['width'] * printerScale * self._pointSize[0]
style = self.attributes['style']
if not isinstance(colour, wx.Colour):
colour = wx.NamedColour(colour)
pen = wx.Pen(colour, width, style)
pen.SetCap(wx.CAP_BUTT)
dc.SetPen(pen)
if coord == None:
if len(self.scaled): # bugfix for Mac OS X
dc.DrawLines(self.scaled)
else:
dc.DrawLines(coord) # draw legend line
def getSymExtent(self, printerScale):
"""Width and Height of Marker"""
h = self.attributes['width'] * printerScale * self._pointSize[0]
w = 5 * h
return (w, h)
class PolySpline(PolyLine):
"""Class to define line type and style
- All methods except __init__ are private.
"""
_attributes = {'colour': 'black',
'width': 1,
'style': wx.PENSTYLE_SOLID,
'legend': ''}
def __init__(self, points, **attr):
"""
Creates PolyLine object
:param `points`: sequence (array, tuple or list) of (x,y) points making up spline
:keyword `attr`: keyword attributes, default to:
========================== ================================
'colour'= 'black' wx.Pen Colour any wx.NamedColour
'width'= 1 Pen width
'style'= wx.PENSTYLE_SOLID wx.Pen style
'legend'= '' Line Legend to display
========================== ================================
"""
PolyLine.__init__(self, points, **attr)
def draw(self, dc, printerScale, coord=None):
colour = self.attributes['colour']
width = self.attributes['width'] * printerScale * self._pointSize[0]
style = self.attributes['style']
if not isinstance(colour, wx.Colour):
colour = wx.Colour(colour)
pen = wx.Pen(colour, width, style)
pen.SetCap(wx.CAP_ROUND)
dc.SetPen(pen)
if coord == None:
if len(self.scaled): # bugfix for Mac OS X
dc.DrawSpline(self.scaled)
else:
dc.DrawLines(coord) # draw legend line
class PolyMarker(PolyPoints):
"""Class to define marker type and style
- All methods except __init__ are private.
"""
_attributes = {'colour': 'black',
'width': 1,
'size': 2,
'fillcolour': None,
'fillstyle': wx.BRUSHSTYLE_SOLID,
'marker': 'circle',
'legend': ''}
def __init__(self, points, **attr):
"""
Creates PolyMarker object
:param `points`: sequence (array, tuple or list) of (x,y) points
:keyword `attr`: keyword attributes, default to:
================================ ================================
'colour'= 'black' wx.Pen Colour any wx.NamedColour
'width'= 1 Pen width
'size'= 2 Marker size
'fillcolour'= same as colour wx.Brush Colour any wx.NamedColour
'fillstyle'= wx.BRUSHSTYLE_SOLID wx.Brush fill style (use wx.BRUSHSTYLE_TRANSPARENT for no fill)
'style'= wx.FONTFAMILY_SOLID wx.Pen style
'marker'= 'circle' Marker shape
'legend'= '' Line Legend to display
================================ ================================
Marker Shapes:
- 'circle'
- 'dot'
- 'square'
- 'triangle'
- 'triangle_down'
- 'cross'
- 'plus'
"""
PolyPoints.__init__(self, points, attr)
def draw(self, dc, printerScale, coord=None):
colour = self.attributes['colour']
width = self.attributes['width'] * printerScale * self._pointSize[0]
size = self.attributes['size'] * printerScale * self._pointSize[0]
fillcolour = self.attributes['fillcolour']
fillstyle = self.attributes['fillstyle']
marker = self.attributes['marker']
if colour and not isinstance(colour, wx.Colour):
colour = wx.NamedColour(colour)
if fillcolour and not isinstance(fillcolour, wx.Colour):
fillcolour = wx.NamedColour(fillcolour)
dc.SetPen(wx.Pen(colour, width))
if fillcolour:
dc.SetBrush(wx.Brush(fillcolour, fillstyle))
else:
dc.SetBrush(wx.Brush(colour, fillstyle))
if coord == None:
if len(self.scaled): # bugfix for Mac OS X
self._drawmarkers(dc, self.scaled, marker, size)
else:
self._drawmarkers(dc, coord, marker, size) # draw legend marker
def getSymExtent(self, printerScale):
"""Width and Height of Marker"""
s = 5 * self.attributes['size'] * printerScale * self._pointSize[0]
return (s, s)
def _drawmarkers(self, dc, coords, marker, size=1):
f = eval('self._' + marker)
f(dc, coords, size)
def _circle(self, dc, coords, size=1):
fact = 2.5 * size
wh = 5.0 * size
rect = np.zeros((len(coords), 4), np.float) + [0.0, 0.0, wh, wh]
rect[:, 0:2] = coords - [fact, fact]
dc.DrawEllipseList(rect.astype(np.int32))
def _dot(self, dc, coords, size=1):
dc.DrawPointList(coords)
def _square(self, dc, coords, size=1):
fact = 2.5 * size
wh = 5.0 * size
rect = np.zeros((len(coords), 4), np.float) + [0.0, 0.0, wh, wh]
rect[:, 0:2] = coords - [fact, fact]
dc.DrawRectangleList(rect.astype(np.int32))
def _triangle(self, dc, coords, size=1):
shape = [(-2.5 * size, 1.44 * size),
(2.5 * size, 1.44 * size), (0.0, -2.88 * size)]
poly = np.repeat(coords, 3, 0)
poly.shape = (len(coords), 3, 2)
poly += shape
dc.DrawPolygonList(poly.astype(np.int32))
def _triangle_down(self, dc, coords, size=1):
shape = [(-2.5 * size, -1.44 * size),
(2.5 * size, -1.44 * size), (0.0, 2.88 * size)]
poly = np.repeat(coords, 3, 0)
poly.shape = (len(coords), 3, 2)
poly += shape
dc.DrawPolygonList(poly.astype(np.int32))
def _cross(self, dc, coords, size=1):
fact = 2.5 * size
for f in [[-fact, -fact, fact, fact], [-fact, fact, fact, -fact]]:
lines = np.concatenate((coords, coords), axis=1) + f
dc.DrawLineList(lines.astype(np.int32))
def _plus(self, dc, coords, size=1):
fact = 2.5 * size
for f in [[-fact, 0, fact, 0], [0, -fact, 0, fact]]:
lines = np.concatenate((coords, coords), axis=1) + f
dc.DrawLineList(lines.astype(np.int32))
class PlotGraphics:
"""Container to hold PolyXXX objects and graph labels
- All methods except __init__ are private.
"""
def __init__(self, objects, title='', xLabel='', yLabel=''):
"""Creates PlotGraphics object
objects - list of PolyXXX objects to make graph
title - title shown at top of graph
xLabel - label shown on x-axis
yLabel - label shown on y-axis
"""
if type(objects) not in [list, tuple]:
raise TypeError("objects argument should be list or tuple")
self.objects = objects
self.title = title
self.xLabel = xLabel
self.yLabel = yLabel
self._pointSize = (1.0, 1.0)
def setLogScale(self, logscale):
if type(logscale) != tuple:
raise TypeError(
'logscale must be a tuple of bools, e.g. (False, False)')
if len(self.objects) == 0:
return
for o in self.objects:
o.setLogScale(logscale)
def boundingBox(self):
p1, p2 = self.objects[0].boundingBox()
for o in self.objects[1:]:
p1o, p2o = o.boundingBox()
p1 = np.minimum(p1, p1o)
p2 = np.maximum(p2, p2o)
return p1, p2
def scaleAndShift(self, scale=(1, 1), shift=(0, 0)):
for o in self.objects:
o.scaleAndShift(scale, shift)
def setPrinterScale(self, scale):
"""Thickens up lines and markers only for printing"""
self.printerScale = scale
def setXLabel(self, xLabel=''):
"""Set the X axis label on the graph"""
self.xLabel = xLabel
def setYLabel(self, yLabel=''):
"""Set the Y axis label on the graph"""
self.yLabel = yLabel
def setTitle(self, title=''):
"""Set the title at the top of graph"""
self.title = title
def getXLabel(self):
"""Get x axis label string"""
return self.xLabel
def getYLabel(self):
"""Get y axis label string"""
return self.yLabel
def getTitle(self, title=''):
"""Get the title at the top of graph"""
return self.title
def draw(self, dc):
for o in self.objects:
# t=_time.clock() # profile info
o._pointSize = self._pointSize
o.draw(dc, self.printerScale)
#dt= _time.clock()-t
#print(o, "time=", dt)
def getSymExtent(self, printerScale):
"""Get max width and height of lines and markers symbols for legend"""
self.objects[0]._pointSize = self._pointSize
symExt = self.objects[0].getSymExtent(printerScale)
for o in self.objects[1:]:
o._pointSize = self._pointSize
oSymExt = o.getSymExtent(printerScale)
symExt = np.maximum(symExt, oSymExt)
return symExt
def getLegendNames(self):
"""Returns list of legend names"""
lst = [None] * len(self)
for i in range(len(self)):
lst[i] = self.objects[i].getLegend()
return lst
def __len__(self):
return len(self.objects)
def __getitem__(self, item):
return self.objects[item]
#-------------------------------------------------------------------------
# Main window that you will want to import into your application.
class PlotCanvas(wx.Panel):
"""
Subclass of a wx.Panel which holds two scrollbars and the actual
plotting canvas (self.canvas). It allows for simple general plotting
of data with zoom, labels, and automatic axis scaling."""
def __init__(self, parent, id=wx.ID_ANY, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0, name="plotCanvas"):
"""Constructs a panel, which can be a child of a frame or
any other non-control window"""
wx.Panel.__init__(self, parent, id, pos, size, style, name)
sizer = wx.FlexGridSizer(2, 2, 0, 0)
self.canvas = wx.Window(self, -1)
self.sb_vert = wx.ScrollBar(self, -1, style=wx.SB_VERTICAL)
self.sb_vert.SetScrollbar(0, 1000, 1000, 1000)
self.sb_hor = wx.ScrollBar(self, -1, style=wx.SB_HORIZONTAL)
self.sb_hor.SetScrollbar(0, 1000, 1000, 1000)
sizer.Add(self.canvas, 1, wx.EXPAND)
sizer.Add(self.sb_vert, 0, wx.EXPAND)
sizer.Add(self.sb_hor, 0, wx.EXPAND)
sizer.Add((0, 0))
sizer.AddGrowableRow(0, 1)
sizer.AddGrowableCol(0, 1)
self.sb_vert.Show(False)
self.sb_hor.Show(False)
self.SetSizer(sizer)
self.Fit()
self.border = (1, 1)
self.SetBackgroundColour("white")
# Create some mouse events for zooming
self.canvas.Bind(wx.EVT_LEFT_DOWN, self.OnMouseLeftDown)
self.canvas.Bind(wx.EVT_LEFT_UP, self.OnMouseLeftUp)
self.canvas.Bind(wx.EVT_MOTION, self.OnMotion)
self.canvas.Bind(wx.EVT_LEFT_DCLICK, self.OnMouseDoubleClick)
self.canvas.Bind(wx.EVT_RIGHT_DOWN, self.OnMouseRightDown)
# scrollbar events
self.Bind(wx.EVT_SCROLL_THUMBTRACK, self.OnScroll)
self.Bind(wx.EVT_SCROLL_PAGEUP, self.OnScroll)
self.Bind(wx.EVT_SCROLL_PAGEDOWN, self.OnScroll)
self.Bind(wx.EVT_SCROLL_LINEUP, self.OnScroll)
self.Bind(wx.EVT_SCROLL_LINEDOWN, self.OnScroll)
# set curser as cross-hairs
self.canvas.SetCursor(wx.CROSS_CURSOR)
self.HandCursor = wx.Cursor(Hand.GetImage())
self.GrabHandCursor = wx.Cursor(GrabHand.GetImage())
self.MagCursor = wx.Cursor(MagPlus.GetImage())
# Things for printing
self._print_data = None
self._pageSetupData = None
self.printerScale = 1
self.parent = parent
# scrollbar variables
self._sb_ignore = False
self._adjustingSB = False
self._sb_xfullrange = 0
self._sb_yfullrange = 0
self._sb_xunit = 0
self._sb_yunit = 0
self._dragEnabled = False
self._screenCoordinates = np.array([0.0, 0.0])
self._logscale = (False, False)
# Zooming variables
self._zoomInFactor = 0.5
self._zoomOutFactor = 2
self._zoomCorner1 = np.array([0.0, 0.0]) # left mouse down corner
self._zoomCorner2 = np.array([0.0, 0.0]) # left mouse up corner
self._zoomEnabled = False
self._hasDragged = False
# Drawing Variables
self.last_draw = None
self._pointScale = 1
self._pointShift = 0
self._xSpec = 'auto'
self._ySpec = 'auto'
self._gridEnabled = False
self._legendEnabled = False
self._titleEnabled = True
self._centerLinesEnabled = False
self._diagonalsEnabled = False
# Fonts
self._fontCache = {}
self._fontSizeAxis = 10
self._fontSizeTitle = 15
self._fontSizeLegend = 7
# pointLabels
self._pointLabelEnabled = False
self.last_PointLabel = None
self._pointLabelFunc = None
self.canvas.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
if sys.platform != "darwin":
self._logicalFunction = wx.EQUIV # (NOT src) XOR dst
else:
# wx.EQUIV not supported on Mac OS X
self._logicalFunction = wx.COPY
self._useScientificNotation = False
self._antiAliasingEnabled = False
self._hiResEnabled = False
self._pointSize = (1.0, 1.0)
self._fontScale = 1.0
self.canvas.Bind(wx.EVT_PAINT, self.OnPaint)
self.canvas.Bind(wx.EVT_SIZE, self.OnSize)
# OnSize called to make sure the buffer is initialized.
# This might result in OnSize getting called twice on some
# platforms at initialization, but little harm done.
self.OnSize(None) # sets the initial size based on client size
self._gridColour = wx.BLACK
def SetCursor(self, cursor):
self.canvas.SetCursor(cursor)
def GetGridColour(self):
return self._gridColour
def SetGridColour(self, colour):
if isinstance(colour, wx.Colour):
self._gridColour = colour
else:
self._gridColour = wx.NamedColour(colour)
# SaveFile
def SaveFile(self, fileName=''):
"""Saves the file to the type specified in the extension. If no file
name is specified a dialog box is provided. Returns True if sucessful,
otherwise False.
.bmp Save a Windows bitmap file.
.xbm Save an X bitmap file.
.xpm Save an XPM bitmap file.
.png Save a Portable Network Graphics file.
.jpg Save a Joint Photographic Experts Group file.
"""
extensions = {
"bmp": wx.BITMAP_TYPE_BMP, # Save a Windows bitmap file.
"xbm": wx.BITMAP_TYPE_XBM, # Save an X bitmap file.
"xpm": wx.BITMAP_TYPE_XPM, # Save an XPM bitmap file.
"jpg": wx.BITMAP_TYPE_JPEG, # Save a JPG file.
"png": wx.BITMAP_TYPE_PNG, # Save a PNG file.
}
fType = _string.lower(fileName[-3:])
dlg1 = None
while fType not in extensions:
if dlg1: # FileDialog exists: Check for extension
dlg2 = wx.MessageDialog(self, 'File name extension\n'
'must be one of\nbmp, xbm, xpm, png, or jpg',
'File Name Error', wx.OK | wx.ICON_ERROR)
try:
dlg2.ShowModal()
finally:
dlg2.Destroy()
# FileDialog doesn't exist: just check one
else:
dlg1 = wx.FileDialog(
self,
"Choose a file with extension bmp, gif, xbm, xpm, png, or jpg", ".", "",
"BMP files (*.bmp)|*.bmp|XBM files (*.xbm)|*.xbm|XPM file (*.xpm)|*.xpm|PNG files (*.png)|*.png|JPG files (*.jpg)|*.jpg",
wx.SAVE | wx.OVERWRITE_PROMPT
)
if dlg1.ShowModal() == wx.ID_OK:
fileName = dlg1.GetPath()
fType = _string.lower(fileName[-3:])
else: # exit without saving
dlg1.Destroy()
return False
if dlg1:
dlg1.Destroy()
# Save Bitmap
res = self._Buffer.SaveFile(fileName, extensions[fType])
return res
@property
def print_data(self):
if not self._print_data:
self._print_data = wx.PrintData()
self._print_data.SetPaperId(wx.PAPER_LETTER)
self._print_data.SetOrientation(wx.LANDSCAPE)
return self._print_data
@property
def pageSetupData(self):
if not self._pageSetupData:
self._pageSetupData = wx.PageSetupDialogData()
self._pageSetupData.SetMarginBottomRight((25, 25))
self._pageSetupData.SetMarginTopLeft((25, 25))
self._pageSetupData.SetPrintData(self.print_data)
return self._pageSetupData
def PageSetup(self):
"""Brings up the page setup dialog"""
data = self.pageSetupData
data.SetPrintData(self.print_data)
dlg = wx.PageSetupDialog(self.parent, data)
try:
if dlg.ShowModal() == wx.ID_OK:
data = dlg.GetPageSetupData() # returns wx.PageSetupDialogData
# updates page parameters from dialog
self.pageSetupData.SetMarginBottomRight(
data.GetMarginBottomRight())
self.pageSetupData.SetMarginTopLeft(data.GetMarginTopLeft())
self.pageSetupData.SetPrintData(data.GetPrintData())
self._print_data = wx.PrintData(
data.GetPrintData()) # updates print_data
finally:
dlg.Destroy()
def Printout(self, paper=None):
"""Print current plot."""
if paper != None:
self.print_data.SetPaperId(paper)
pdd = wx.PrintDialogData(self.print_data)
printer = wx.Printer(pdd)
out = PlotPrintout(self)
print_ok = printer.Print(self.parent, out)
if print_ok:
self._print_data = wx.PrintData(
printer.GetPrintDialogData().GetPrintData())
out.Destroy()
def PrintPreview(self):
"""Print-preview current plot."""
printout = PlotPrintout(self)
printout2 = PlotPrintout(self)
self.preview = wx.PrintPreview(printout, printout2, self.print_data)
if not self.preview.IsOk():
wx.MessageDialog(self, "Print Preview failed.\n"
"Check that default printer is configured\n",
"Print error", wx.OK | wx.CENTRE).ShowModal()
self.preview.SetZoom(40)
# search up tree to find frame instance
frameInst = self
while not isinstance(frameInst, wx.Frame):
frameInst = frameInst.GetParent()
frame = wx.PreviewFrame(self.preview, frameInst, "Preview")
frame.Initialize()
frame.SetPosition(self.GetPosition())
frame.SetSize((600, 550))
frame.Centre(wx.BOTH)
frame.Show(True)
def setLogScale(self, logscale):
if type(logscale) != tuple:
raise TypeError(
'logscale must be a tuple of bools, e.g. (False, False)')
if self.last_draw is not None:
graphics, xAxis, yAxis = self.last_draw
graphics.setLogScale(logscale)
self.last_draw = (graphics, None, None)
self.SetXSpec('min')
self.SetYSpec('min')
self._logscale = logscale
def getLogScale(self):
return self._logscale
def SetFontSizeAxis(self, point=10):
"""Set the tick and axis label font size (default is 10 point)"""
self._fontSizeAxis = point
def GetFontSizeAxis(self):
"""Get current tick and axis label font size in points"""
return self._fontSizeAxis
def SetFontSizeTitle(self, point=15):
"""Set Title font size (default is 15 point)"""
self._fontSizeTitle = point
def GetFontSizeTitle(self):
"""Get current Title font size in points"""
return self._fontSizeTitle
def SetFontSizeLegend(self, point=7):
"""Set Legend font size (default is 7 point)"""
self._fontSizeLegend = point
def GetFontSizeLegend(self):
"""Get current Legend font size in points"""
return self._fontSizeLegend
def SetShowScrollbars(self, value):
"""Set True to show scrollbars"""
if value not in [True, False]:
raise TypeError("Value should be True or False")
if value == self.GetShowScrollbars():
return
self.sb_vert.Show(value)
self.sb_hor.Show(value)
wx.CallAfter(self.Layout)
def GetShowScrollbars(self):
"""Set True to show scrollbars"""
return self.sb_vert.IsShown()
def SetUseScientificNotation(self, useScientificNotation):
self._useScientificNotation = useScientificNotation
def GetUseScientificNotation(self):
return self._useScientificNotation
def SetEnableAntiAliasing(self, enableAntiAliasing):
"""Set True to enable anti-aliasing."""
self._antiAliasingEnabled = enableAntiAliasing
self.Redraw()
def GetEnableAntiAliasing(self):
return self._antiAliasingEnabled
def SetEnableHiRes(self, enableHiRes):
"""Set True to enable high-resolution mode when using anti-aliasing."""
self._hiResEnabled = enableHiRes
self.Redraw()
def GetEnableHiRes(self):
return self._hiResEnabled
def SetEnableDrag(self, value):
"""Set True to enable drag."""
if value not in [True, False]:
raise TypeError("Value should be True or False")
if value:
if self.GetEnableZoom():
self.SetEnableZoom(False)
self.SetCursor(self.HandCursor)
else:
self.SetCursor(wx.CROSS_CURSOR)
self._dragEnabled = value
def GetEnableDrag(self):
return self._dragEnabled
def SetEnableZoom(self, value):
"""Set True to enable zooming."""
if value not in [True, False]:
raise TypeError("Value should be True or False")
if value:
if self.GetEnableDrag():
self.SetEnableDrag(False)
self.SetCursor(self.MagCursor)
else:
self.SetCursor(wx.CROSS_CURSOR)
self._zoomEnabled = value
def GetEnableZoom(self):
"""True if zooming enabled."""
return self._zoomEnabled
def SetEnableGrid(self, value):
"""Set True, 'Horizontal' or 'Vertical' to enable grid."""
if value not in [True, False, 'Horizontal', 'Vertical']:
raise TypeError(
"Value should be True, False, Horizontal or Vertical")
self._gridEnabled = value
self.Redraw()
def GetEnableGrid(self):
"""True if grid enabled."""
return self._gridEnabled
def SetEnableCenterLines(self, value):
"""Set True, 'Horizontal' or 'Vertical' to enable center line(s)."""
if value not in [True, False, 'Horizontal', 'Vertical']:
raise TypeError(
"Value should be True, False, Horizontal or Vertical")
self._centerLinesEnabled = value
self.Redraw()
def GetEnableCenterLines(self):
"""True if grid enabled."""
return self._centerLinesEnabled
def SetEnableDiagonals(self, value):
"""Set True, 'Bottomleft-Topright' or 'Bottomright-Topleft' to enable
center line(s)."""
if value not in [True, False, 'Bottomleft-Topright', 'Bottomright-Topleft']:
raise TypeError(
"Value should be True, False, Bottomleft-Topright or Bottomright-Topleft")
self._diagonalsEnabled = value
self.Redraw()
def GetEnableDiagonals(self):
"""True if grid enabled."""
return self._diagonalsEnabled
def SetEnableLegend(self, value):
"""Set True to enable legend."""
if value not in [True, False]:
raise TypeError("Value should be True or False")
self._legendEnabled = value
self.Redraw()
def GetEnableLegend(self):
"""True if Legend enabled."""
return self._legendEnabled
def SetEnableTitle(self, value):
"""Set True to enable title."""
if value not in [True, False]:
raise TypeError("Value should be True or False")
self._titleEnabled = value
self.Redraw()
def GetEnableTitle(self):
"""True if title enabled."""
return self._titleEnabled
def SetEnablePointLabel(self, value):
"""Set True to enable pointLabel."""
if value not in [True, False]:
raise TypeError("Value should be True or False")
self._pointLabelEnabled = value
self.Redraw() # will erase existing pointLabel if present
self.last_PointLabel = None
def GetEnablePointLabel(self):
"""True if pointLabel enabled."""
return self._pointLabelEnabled
def SetPointLabelFunc(self, func):
"""Sets the function with custom code for pointLabel drawing