-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathplots.py
1801 lines (1584 loc) · 81.4 KB
/
plots.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
# the possible plottypes are defined here,
from __future__ import print_function
from six import iteritems
from functional import zip_, map_, drap, reduce, range_
from plotutil import *
import enumerations, jenums, ms2util, hvutil, parsers, copy, re
import inspect, math, numpy, operator, os, types, functional, functools
AX = jenums.Axes
FLAG = jenums.Flagstuff
SYMBOL = jenums.Symbol
Scaling = enumerations.Enum("auto_global", "auto_local")
FixFlex = enumerations.Enum("fixed", "flexible")
RowsCols = enumerations.Enum("rows", "columns")
CKReset = enumerations.Enum("newplot")
FU = functional
CP = copy.deepcopy
# we seem to have had a circular dependency here - plots.py (this module) imports plotiterator
# but plotiterator uses plots.YTypes ... Just 'import plots' wouldn't work unless the import of
# plotiterator was deferred until here
import plotiterator
## Sometimes a plot annotation is None ...
M = lambda x: '*' if x is None else x # M is for M(aybe)
M2 = lambda k, v: k+"="+("*" if v is None else str(v))
UNIQ = lambda x: x if x else ""
BASENAME = os.path.basename
## a real pgplot 'context', usable in 'with ...' constructions
class pgenv(object):
def __init__(self, plt):
self.plotter = plt
def __enter__(self):
self.plotter.pgsave()
def __exit__(self, tp, val, tb):
self.plotter.pgunsa()
## Keep track of the layout of a page in number-of-plots in X,Y direction
class layout(object):
def __init__(self, nx, ny):
self.nx = nx
self.ny = ny
self.rows = True
def nplots(self):
return self.nx * self.ny
def __str__(self):
return "{2} plots organized as {0} x {1}".format(self.nx, self.ny, self.nplots())
## Colorkey functions. Take a data set label and produce a
## key such that for data sets having identical "keys"
## they will be drawn in identical colors.
# the default colour index function: each key gets their
# own distinctive colour index
def ckey_builtin(label, keycoldict, **opts):
key = str(label)
ck = keycoldict.get(key, None)
if ck is not None:
return ck
if len(keycoldict)>=opts.get('ncol', 16):
return 1
# Never seen this label before - must allocate new colour!
# find values in the keycoldict and choose one that isn't there already
colours = sorted([v for (k,v) in iteritems(keycoldict)])
# skip colour 0 and 1 (black & white)
ck = 2
if colours:
# find first unused colour index
while ck<=colours[-1]:
if ck not in colours:
break
ck = ck + 1
keycoldict[key] = ck
return ck
#### A function that returns functions that remap each subband's x-axis
#### such that they are put next to each other in subband (=meta data) order
#### The original x-axes will be *remapped* for plotting purposes.
#### If you want to plot against e.g. physical x-axis values don't set 'multiSubband'
#### to true or plot against frequency (note: not implemented yet ...)
####
#### Returns tuple (dict(), new-xaxis-maximum-value)
#### 'datasets' = list of (label, data) pairs
def mk_offset(datasets, attribute):
# for each subband we must record the (max) extent of the x-axis
# (there could be data sets for the same subband from different
# sources with different number of data points)
#
# Then we sort them by subband, and update each subband with the current
# offset, increment the offset by the current subband's size and proceed
def range_per_sb(acc, ds):
(label, data) = ds
attributeval = getattr(label, attribute)
(mi, ma) = (0, 0) if data.xlims is None else data.xlims
#(mi, ma) = (min(data.xval), max(data.xval))
# if either mi/ma is None that means there is no data
(ami, ama) = acc.get(attributeval, (mi, ma))
acc.update( {attributeval: (min(mi, ami), max(ma, ama))} )
return acc
# process one entry from the {attrval1:(mi, ma), attrval2:(mi, ma), ...} dict
# the accumulator is (dict(), current_xaxis_length)
def offset_per_sb(acc, kv):
(sb, (sbMin, sbMax)) = kv
# if the indicated subband has no min/max then no data was to be plotted for that one
if sbMin is None or sbMax is None:
return acc
(offsetmap, curMax) = acc
if curMax is None:
# this is the first SB in the plot - this sets
# the xmin/xmax and the x-axis transform is the identity transform
offsetmap[sb] = lambda xarr: xarr
# now initialize the actual max x value to current SB's max x
sbOffset = 0
else:
sbOffset = (curMax - sbMin)
# generate a function which transforms the x-axis for the current subband
offsetmap[sb] = lambda xarr: xarr+sbOffset if isinstance(xarr, numpy.ndarray) \
else map_(lambda z:z+sbOffset, xarr)
# the new x-axis length is the (transformed) maximum x value of this subband
return (offsetmap, sbMax+sbOffset)
# we automatically get the new x-axis max value out of this
return reduce(offset_per_sb,
sorted(iteritems(reduce(range_per_sb, datasets, {})),
key=operator.itemgetter(0)),
({}, None))
def normalize_mask(m):
if numpy.all(m):
return True
if numpy.any(m): # note: do not use "sum(m)" - dat's wikkit sl0w
return m
# not all && not any => none at all!
return False
# After https://stackoverflow.com/questions/11731136/python-class-method-decorator-with-self-arguments
def check_attribute(attribute):
def _check_attribute(f, *brgs, **kwbrgs):
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
if getattr(self, attribute) is None:
raise RuntimeError("Called method {0} requires {1} to be not None".format(f.__name__, attribute))
return f(self, *args, **kwargs)
return wrapper
return _check_attribute
def verify_argument(verifier):
def _verify_argument(f, *brgs, **kwbrgs):
@functools.wraps(f)
def wrapper(self, *args, **kwargs):
if not verifier(*args, **kwargs):
raise RuntimeError("Called method {0} fails to verify called with {1} {2}".format(f.__name__, args, kwargs))
return f(self, *args, **kwargs)
return wrapper
return _verify_argument
# A viewport describes an area on the draw surface with xLeft, xRight, yBottom,
# yTop coordinates in Normalized Device Coordinates
# If the viewport is a subplot /then/ it can be drawn on a device, decorated
# with axes, tick marks and labels The subplot state is managed from the parent
# page; if a viewport is requested from a page, the page knows wether the
# viewport is special one (leftmost, rightmost, bottom row) and sets the
# properties accordingly. This allows the viewport to correctly draw x,y axis
# values and labels, if set.
# The parent page does the layouting, taking care of reserving space for the
# values, labels and computing the offsets at which these should happen
# The viewport infers labels and scaling properties directly from the plotter
# object (through its parent page) whose data it is meant to display
class Viewport(object):
# x=column, y=row, parent = parent _Page_
def __init__(self, x, y, parent, subplot=None):
self.viewport_= [0.0]*4 # xLeft xRight yBottom yTop
self.window = None
self.x = x
self.y = y
self.page = parent
self.xDisp = 0 # "DISP" parameter to PGMTXT for x-label
self.yDisp = 0 # id. for y-label
self.lastRow = False
self.lastCol = False
self.subPlot = subplot
@staticmethod
def _is_ok(x):
return 0<=x<=1
@staticmethod
def _is_not_ok(x):
return x<0 or x>1
def get_viewport(self):
return self.viewport_
def set_viewport(self, vp):
if len(vp)!=4:
raise RuntimeError("Viewport must be length 4")
if functional.filter_(Viewport._is_not_ok, vp):
raise RuntimeError("Attempt to set invalid viewport {0}".format(vp))
self.viewport_ = vp
viewport = property(get_viewport, set_viewport)
# transform array-of-length-4 into four named properties
def get0(self):
return self.viewport_[0]
def set0(self, v):
self[0] = v
def get1(self):
return self.viewport_[1]
def set1(self, v):
self[1] = v
def get2(self):
return self.viewport_[2]
def set2(self, v):
self[2] = v
def get3(self):
return self.viewport_[3]
def set3(self, v):
self[3] = v
xLeft = property(get0, set0)
xRight = property(get1, set1)
yBottom = property(get2, set2)
yTop = property(get3, set3)
# also allow [0..3] based indexing
def __getitem__(self, n):
return self.viewport_[n]
def __setitem__(self, n, v):
if Viewport._is_not_ok(v):
raise RuntimeError("Attempt to set invalid viewport[{0}] = {1} on ".format(n, v)+repr(self))
self.viewport_[n] = v
return self
# return x/y size in NDC
@property
@check_attribute('subPlot')
def dx(self):
return self.xRight - self.xLeft
@property
@check_attribute('subPlot')
def dy(self):
return self.yTop - self.yBottom
# return x/y-sizes in world coordinates
@property
@check_attribute('window')
def dx_world(self):
return self.window[1] - self.window[0]
@property
@check_attribute('window')
def dy_world(self):
return self.window[3] - self.window[2]
# extract a new viewport which is an indexed subsection of the parent viewport
def subplot(self, idx):
# get a new viewport as height fraction of this one
yHeights = self.page.plotter.yHeights
bot = sum(yHeights[0:idx])
top = bot + yHeights[idx]
dvpY = self.yTop - self.yBottom
# construct with valid subplot and transfer logic values
rv = Viewport(self.x, self.y, self.page, subplot=idx)
rv.xDisp = self.xDisp
rv.yDisp = self.yDisp
rv.lastRow = self.lastRow
rv.lastCol = self.lastCol
rv.viewport = [self.xLeft, self.xRight, self.yBottom + bot*dvpY, self.yBottom+top*dvpY]
return rv
@check_attribute('subPlot')
def doXLabel(self):
return self.page.plotter.xLabel and self.lastRow and self.subPlot==0
@check_attribute('subPlot')
def doYLabel(self):
return self.page.plotter.yLabel[self.subPlot] and self.x == 0
@check_attribute('subPlot')
def doXTicks(self):
return self.subPlot==0 and (self.lastRow or self.page.plotter.xScale == Scaling.auto_local)
@check_attribute('subPlot')
def doYTicks(self):
return self.x == 0 or self.lastCol or self.page.plotter.yScale[self.subPlot] == Scaling.auto_local
# Do our thang on the device!
@check_attribute('subPlot')
def svp(self, device):
device.pgsvp( *self.viewport_ )
@check_attribute('subPlot')
def drawLabels(self, device):
with pgenv(device):
# all text drawn in black with page's label character size
device.pgsci( 1 )
device.pgsch( self.page.labelCharSz )
if self.doXLabel():
device.pgmtxt('B', self.xDisp, 0.9, 1.0, self.page.plotter.xLabel)
if self.doYLabel():
device.pgmtxt('L', self.yDisp, 0.9, 1.0, self.page.plotter.yLabel[self.subPlot])
# sets window and draws boxes &cet
@check_attribute('subPlot')
def drawBox(self, device, xmi, xma, ymi, yma):
if self.window is not None:
raise RuntimeError("Can only set window once on viewport ({0.x}, {0.y}, subPlot={0.subPlot})".format(self))
self.window = [xmi, xma, ymi, yma]
with pgenv(device):
# step one: set the window in world coordinates
device.pgswin( *self.window )
# Need to draw the box always, wih thin line
device.pgsci( 1 )
device.pgslw( 1 )
device.pgsch( self.page.tickCharSz )
# Form the XOPT/YOPT strings for PGPLOT's PG(T)BOX function
xboxstr = yboxstr = "ABCTS"
yboxstr += "V"
if self.page.plotter.xAxis == jenums.Axes.TIME:
xboxstr += "ZHO"
# do we need to draw the x-axis ticks?
if self.doXTicks():
xboxstr += "N"
# y-axis values for the outermost column get drawn on the right-hand side
if self.doYTicks():
yboxstr += ("M" if self.lastCol else "N")
# y values forced to decimal
yboxstr += "1"
#device.pgsch( 0.6 )
device.pgtbox( xboxstr, 0.0, 0, yboxstr, 0.0, 0 )
# sets viewport, window, draws boxes and labels
@check_attribute('subPlot')
def setLabelledBox(self, device, xmi, xma, ymi, yma):
self.svp(device)
self.drawBox(device, xmi, xma, ymi, yma)
self.drawLabels(device)
# Help in choosing which x limit to use; data sets these days have
# flagged+unflagged data and we need to select based on which of these are
# actually available what the lowest time is.
# Key into the choice table is:
# ( <bool A>, <bool B> )
# where:
# <bool A> = '.xval is not None' ("data set has unflagged data points")
# <bool B> = '.xval_f is not None' ("data set has flagged data points")
choicetab = {
# we don't have to cover (True, True) because
# that would mean that both .xval and .xval_f are None
# and that case is filtered out; datasets with no data at all
# are not sent to the drawing function ...
(False, False): lambda x, xf: min(min(x), min(xf)),
(True , False): lambda x, xf: min(xf),
(False, True ): lambda x, xf: min(x)
}
# analyze dataset labels for unique source names
# and display the first occurrence of each, cycling
# in three heights. Use world coordinates for this
@check_attribute('subPlot')
def printSrcNameByTime(self, device, datasets, xform_x=lambda x: x):
# if parent page's parent plot [that's ancestry for you ...] indicates
# don't show source name(s) then let's not do that
if not self.page.plotter.showSource:
return
# do each source only once
seensrces = set()
# must be done in world coordinates
y_offset, y_step = (0.45 * self.dy_world, 0.1*self.dy_world)
with pgenv(device):
# in black w/ small characters
device.pgsci( 1 )
device.pgsch( 0.4 )
for (dskey,dsdata) in datasets:
# If no 'SRC' in data set identifier or already seen: do nothing
if dskey.SRC is None or dskey.SRC in seensrces:
continue
# SRC available, not seen yet, find 'earliest time'
x0 = Viewport.choicetab[(dsdata.xval is None, dsdata.xval_f is None)](dsdata.xval, dsdata.xval_f)
# stagger them in groups of 3, covers 3 source phase ref
device.pgptxt( xform_x(x0), y_offset + y_step * (len(seensrces)%3), 0.0, 0.0, dskey.SRC )
seensrces.add( dskey.SRC )
@check_attribute('subPlot')
def drawMainLabel(self, device, mainlabel):
with pgenv(device):
device.pgsci( 1 )
device.pgsch( 0.8 )
device.pgmtxt( 'T', -1.0, 0.5, 0.5, mainlabel)
# Get a nice string representation of this objects's stat
_fmt = ("Viewport(x={0.x:d},y={0.y:d} [x:{0.xLeft:.3f}-{0.xRight:.3f} y:{0.yBottom:.3f}-{0.yTop:.3f}] xDisp={0.xDisp:.3f} yDisp={0.yDisp:.3f} "+
"lastRow/Col={0.lastRow}/{0.lastCol} subPlot={0.subPlot}) id={1}").format
def __repr__(self):
return Viewport._fmt(self, id(self))
########################################################################################
#
# An object describing a page layout for a particular plotter and array of plots
# to be displayed.
#
# From the parent plotter properties the layout is copied and potentially
# altered, based on the amount of plots that are to be generated. From the
# labels and scaling options the Page class can compute the size of the plots
# and decide how the viewports (where the actual data will be plotted)'s axes
# are to be created (if x/y tick values must be drawn, if x/y labels must be
# drawn).
#
# From the parent plotter's properties it can also infer wether the metadata
# (header, legend) must be drawn or wether that space needs to be allocated to
# the plot area.
#
########################################################################################
class Page(object):
charSize = 1.0/40 # PGPLOT nominal char size in NDC [1/40th of y-height if charsize set to 1.0]
tickString = "1.00e^8" # nominal-ish format for how tick values are displayed (it's the string length that counts)
# come up with a good layout
#
# onePage:
# is AllInOne => for animation, change layout to hold nplot
# is None => unnavigable device so we may have to produce > 1 pages
# * => navigable device (window) so draw one page
# if nlot < layout, change layout to hold all
def __init__(self, plotter, device, onePage, plotar, **kwargs):
nplot = len(plotar)
# start by setting page boundaries
self.header = 0.14 if plotter.showHeader else 0.01
self.footer = 0.04 if plotter.showLegend else 0.00
self.xl_ = 0.01
self.xr_ = 0.98
self.yb_ = self.footer
self.yt_ = 1.0 - self.header
self.plotter = plotter
# the left hand side and bottom of the plot area
# may be offset (to make room for x/y axis labels
self.leftShift_ = 0
self.rightShift_ = 0
self.bottomShift_ = 0
# and the given layout
self.layout = copy.deepcopy(plotter.layout())
# depending on if it's allowed and how to re-arrange the amount of plots come up with a new layout
if onePage is AllInOne:
# we must grow or shrink the layout such that everything fits on one page, note: this is non-negotiable
if plotter.fixedLayout:
print("Warning: fixed layout overridden by AllInOne requirement")
if nplot > self.layout.nplots():
self._growLayout(nplot, **kwargs)
else:
self._shrinkLayout(nplot, **kwargs)
elif not plotter.fixedLayout:
nplot = min(nplot, self.layout.nplots()) if onePage else nplot
# shrinkage is allowed if number of plots < layout
# AND (either nx,ny==1 OR spillage > 25%)
# otherwise we leave the layout well alone I guess
if nplot<self.layout.nplots() and (self.layout.nx==1 or self.layout.ny==1 or (float(nplot)/self.layout.nplots())<=0.75):
self._shrinkLayout(nplot, **kwargs)
else:
self._updateLayout(nplot, **kwargs)
# Now we can seed dx,dy for the plot panels
# and ddx, ddy for room for the tick values, if necessary
self.dx, self.dy = (0, 0)
self.ddx, self.ddy = (0, 0)
self._updateDxy()
# page has tickCharSz and labelCharSz (in normalized character heights)
# as well as the 'offset outside viewport in character heights' in case a label needs to be drawn
# if we need to do x/y labels we just shift the xleft and ybottom accordingly
# zip the panel heights with their labels and filter those who are not empty
# set the property on the page in units of the normal character height
if self.plotter.charSize > 0:
self.labelCharSz = self.plotter.charSize
else:
self.labelCharSz = [h/n for (h,n) in
zip_(map(lambda fraction: self.dy * fraction, self.plotter.yHeights),
map(len, self.plotter.yLabel))+
[(self.dx, len(self.plotter.xLabel))] if n>0]
self.labelCharSz = min(0.8*Page.charSize, 0 if not self.labelCharSz else min(self.labelCharSz)) / Page.charSize
# already compute the tickCharSz with the same current settings for consistency
# Allow user to override the character size?
if self.plotter.charSize > 0:
self.tickCharSz = self.plotter.charSize
else:
self.tickCharSz = map_(lambda fraction: (self.dy * fraction)/len(Page.tickString),
self.plotter.yHeights) + [ self.dx/len(Page.tickString) ]
self.tickCharSz = min(0.6*Page.charSize, min(self.tickCharSz)) / Page.charSize
# the important values to keep are: tickwitdh (measured string length) and label x/y height and tick char height
with pgenv(device):
device.pgsch( self.labelCharSz )
(self.lXCH, self.lYCH) = device.pgqcs( 0 )
device.pgsch( self.tickCharSz )
(self.tXCH, self.tYCH) = device.pgqcs( 0 )
(self.tickWidth, _ ) = map_(lambda l: 1.2*l, device.pglen(Page.tickString, 0))
self.tickHeight = 2 * self.tYCH
if self.labelCharSz>0:
# if we need to do x labels, shift bottom of page up by ~2 chY units
# (xlabels are drawn with horizontal baseline)
if self.plotter.xLabel:
self.bottomShift = self.bottomShift + 1.5*self.lYCH
# if there is/are y labels, shift the left side of the page to the right
# make room for one and a bit label character-heights-with-vertical-baseline
if any(self.plotter.yLabel):
self.rightShift = self.rightShift + 1.5*self.lXCH
# Depending on x/y scaling we have to make room for x/y axis tick values on left row/bottom row
# or on all plots
if self.plotter.xScale == Scaling.auto_local:
# local x-axis scaling: bottom of each plot must be raised
self.ddy = self.tickHeight
else:
# common x-axis so we can just raise the bottom to make room
self.bottomShift = self.bottomShift + self.tickHeight
# repeat for y-axis
# tick values are drawn with horizontal baseline
if Scaling.auto_local in self.plotter.yScale:
# each plot will have own y axis so shift viewport to the right
self.ddx = self.tickWidth
else:
# common/global y-axis, just shift the left hand side of the page's view area
self.rightShift = self.rightShift + self.tickWidth
# also make a /little/ more room on the right hand side by shifting
# the left side back in case we have > 1 columns of plots because
# the right-most plots will get their global y-axis tick values
# displayed on the right. (When doing local y-axis scale, all plots
# get their y-axis values on the left hand side)
if self.layout.nx > 1:
self.leftShift = self.leftShift + 0.5*self.tickWidth
# From the parent plotter + plot array we can form the page header, but only if needed
self.pageLabel = None if not self.plotter.showHeader else self.plotter.mk_pagelabel( plotar )
def _updateDxy(self):
self.dx = (self.xr_ - self.xl_ - self.rightShift_ - self.leftShift_)/self.layout.nx
self.dy = (self.yt_ - self.yb_ - self.bottomShift_)/self.layout.ny
@verify_argument(lambda *args, **kwargs: args[0]>=0 and args[0]<=1)
def _setLeftShift(self, ls):
self.leftShift_ = ls
self._updateDxy()
def _getLeftShift(self):
return self.leftShift_
@verify_argument(lambda *args, **kwargs: args[0]>=0 and args[0]<=1)
def _setRightShift(self, rs):
self.rightShift_ = rs
self._updateDxy()
def _getRightShift(self):
return self.rightShift_
@verify_argument(lambda *args, **kwargs: args[0]>=0 and args[0]<=1)
def _setBottomShift(self, bs):
self.bottomShift_ = bs
self._updateDxy()
def _getBottomShift(self):
return self.bottomShift_
leftShift = property(_getLeftShift, _setLeftShift)
rightShift = property(_getRightShift, _setRightShift)
bottomShift = property(_getBottomShift, _setBottomShift)
# whenever xl, xr, yt, yb is updated, recompute dx, dy
@verify_argument(lambda *args, **kwargs: args[0]>=0 and args[0]<=1)
def _setxl(self, xl):
self.xl_ = xl
self._updateDxy()
@verify_argument(lambda *args, **kwargs: args[0]>=0 and args[0]<=1)
def _setxr(self, xr):
self.xr_ = xr
self._updateDxy()
@verify_argument(lambda *args, **kwargs: args[0]>=0 and args[0]<=1)
def _setyb(self, yb):
self.yb_ = yb
self._updateDxy()
@verify_argument(lambda *args, **kwargs: args[0]>=0 and args[0]<=1)
def _setyt(self, yt):
self.yt_ = yt
self._updateDxy()
def _getxl(self):
return self.xl_
def _getxr(self):
return self.xr_
def _getyb(self):
return self.yb_
def _getyt(self):
return self.yt_
xl = property(_getxl, _setxl)
xr = property(_getxr, _setxr)
yb = property(_getyb, _setyb)
yt = property(_getyt, _setyt)
def plotIndex(self, pnum):
return pnum % self.layout.nplots()
def viewport(self, pnum, nplot):
# figure out the index of the plot on the page
pidx = self.plotIndex(pnum)
# the viewport coords - take care of filling rows or columns first
if self.layout.rows:
rv = Viewport(pidx % self.layout.nx, pidx // self.layout.nx, self)
else:
rv = Viewport(pidx // self.layout.ny, pidx % self.layout.ny, self)
rv.lastRow = (rv.y+1)==self.layout.ny or (nplot - pnum)<=self.layout.nx
rv.lastCol = (self.layout.nx>1 and (rv.x+1)==self.layout.nx and not Scaling.auto_local in self.plotter.yScale) or (pnum == nplot)
xl,yt = (self.xl + self.rightShift + rv.x*self.dx, self.yt - rv.y * self.dy)
# if there's multiple columns, rows, relax the fit in those directions
x_scale = 0.98 if self.layout.nx > 1 else 1.0
y_scale = 0.98 if self.layout.ny > 1 else 1.0
# left right bottom top
# 0 1 2 3
rv.viewport = [xl + self.ddx, xl+x_scale*self.dx, yt-y_scale*self.dy+self.ddy, yt]
# we now have the basic viewport for the current plot
# set label offsts in units of the label character height
rv.xDisp = 2
rv.yDisp = (1.5*self.tickWidth / self.lYCH) if self.lYCH else 0
return rv
# if amount of plots to draw << current layout, then we automatically
# rescale to a layout which maximizes to the actual amount of plots.
# that is: if rescaling is allowed at all
def _updateLayout(self, nplots, expandx=None, expandy=None, **kwargs):
if self.layout.nplots()<nplots or not (expandx or expandy):
return
# start with an approximation
if expandx and expandy:
sqrtN = math.sqrt(nplots)
self.layout.nx = int(math.floor(sqrtN))
self.layout.ny = int(math.ceil(sqrtN))
elif expandx:
self.layout.nx = int(math.ceil(float(nplots)/self.layout.ny))
else:
self.layout.ny = int(math.ceil(float(nplots)/self.layout.nx))
# expand in allowed dimensions until fit
self._growLayout(nplots, expandx=expandx, expandy=expandy)
def _growLayout(self, nplots, expandx=None, expandy=None, **kwargs):
if nplots>self.layout.nplots() and not (expandx or expandy):
raise RuntimeError("Request to grow layout from {0} to {1} plots but not allowed to expand!".format(self.layout.nplots(), nplots))
# make sure the new layout is such that all plots will be on one page
while self.layout.nplots()<nplots:
if expandx and expandy:
if self.layout.nx<self.layout.ny:
self.layout.nx = self.layout.nx + 1
else:
self.layout.ny = self.layout.ny + 1
elif expandx:
self.layout.nx = self.layout.nx + 1
else:
self.layout.ny = self.layout.ny + 1
def _shrinkLayout(self, nplots, expandx=None, expandy=None, **kwargs):
# if people say expandy = True that means they value the y direction
# so for shrinking we're going to reverse that
expandx = not expandx
expandy = not expandy
lo = self.layout
while True:
# we want to minimize spillage
# if < 0 we must grow again
spill = lo.nplots() - nplots
# no spillage means we're /definitely/ done!
if spill==0:
break
(comp, delta) = (operator.gt, +1) if spill < 0 else (operator.lt, -1)
# if neither nor both directions are allowed to expand ...
# note: there is no 'xor' for 'objects' in Python only bitwise xor ...
if (expandx and expandy) or (not expandx and not expandy):
if lo.nx>1 and lo.ny>1:
# if both > 1 prefer a balanced shrinkage
if comp(lo.ny,lo.nx):
lo.nx += delta
else:
lo.ny += delta
elif comp(1, lo.nx):
lo.nx += delta
elif comp(1, lo.ny):
lo.ny += delta
else:
raise RuntimeError("Failed to shrink (expandx and expandy and neither nx,ny>1)")
elif expandx:
# prefer lowering x, until we can't anymore
if comp(1, lo.nx):
lo.nx += delta
else:
lo.ny += delta
else:
# prefer lowering y, until we can't anymore
if comp(1, lo.ny):
lo.ny += delta
else:
lo.nx += delta
# check new spillage?
nspill = lo.nplots() - nplots
if nspill < spill:
# less spillage is gooder
continue
# we may only terminate if spill >= 0
if spill>=0:
break
def show(self, device):
with pgenv(device):
device.pgslw( 2 )
device.pgsls( 1 )
device.pgsvp( 0, 1, 0, 1)
device.pgsci( 2 )
device.pgbox( "BC", 0, 0, "BC", 0, 0)
device.pgsvp( self.xl_, self.xr_, self.yb_, self.yt_ )
device.pgsci( 1 )
device.pgbox( "BC", 0, 0, "BC", 0, 0)
def printlegend(self, device):
# if the color code dict is empty, there isn't much we can do now, is there?
# note: we filter out the ones that do not have a label:
# sometimes, when only one data set is plotted in a plot,
# there are no labels left [either they're in the global, shared
# label section or they're in the per-plot label but none reside
# in the per-dataset section]. So there's no need to draw the legend
# because there isn't any
coldict = dict(filter(functional.compose(operator.truth, operator.itemgetter(0)),
iteritems(self.plotter.coldict())))
if not coldict or not self.plotter.showLegend:
return
with pgenv(device):
device.pgsvp( self.xl_, self.xr_, 0, self.yb_ )
device.pgswin( 0, 1, 0, 1 )
device.pgsch(0.4)
# Find the longest description and divide the space we have into an equal
# number of positions. So we need the size of the longest key in device units
(xsz, ysz) = device.pglen(max(coldict.keys(), key=len), 0)
# the values below look like NDC but they are world coordinates for PGPTXT.
# However, we'll map the footer area to world (0,1,0,1) so it's "NDC" inside the footer ;-)
(xsep, xoff, xline, xskip) = (0.01, 0.01, 0.03, 0.005)
(txt_off,) = (0.10,) # drop text baseline by this factor to align nicely with the line
nxleg = max(1, int(math.floor((1.0 - 2*xoff) / (xsz+xline+xskip+xsep))))
# for drawing a horizontal line we need 2 x-coords and only 1 y-coord
xpos = [0.0] * 2
ypos = 0.0
nyleg = int(math.ceil(float(len(coldict))/nxleg))
dy = 1.0/(nyleg+1)
for (idx, cmap) in enumerate(iteritems(coldict)):
(label, col) = cmap
(ipos, jpos) = (idx % nxleg, idx // nxleg)
xpos[0] = xoff + (xsz+xline+xskip+xsep) * ipos
xpos[1] = xpos[0] + xline
xcapt = xpos[1] + xskip
ypos = 1.0 - (jpos + 1)*dy
ycapt = ypos - txt_off*dy
device.pgsci( col )
device.pgslw( 4 )
device.pgline( numpy.asarray(xpos), numpy.asarray([ypos, ypos]) )
device.pgsci( 1 )
device.pgslw( 1 )
device.pgptxt( xcapt, ycapt, 0.0, 0.0, label )
def printPageLabel(self, device, curPlot, nPlot):
if self.pageLabel is None:
return
# Puts a label on the page, assuming a fixed record structure.
# take the data from the parent plotter
# compute the skip between lines - we should use the max of
# left/right labels to make them line up properly
nline = max(len(self.pageLabel.left), len(self.pageLabel.right))
# set current pageno based on settings
self.pageLabel.right[2] = "page: {0}/{1}".format( int(math.ceil(float(curPlot)/self.layout.nplots())) + 1,
int(math.ceil(float(nPlot)/self.layout.nplots())) )
# When using giza as PGPLOT backend, then '_' is suddenly "subscript" a-la TeX ffs
noUnderscore = functools.partial(re.sub, r"_", r"\\_") if 'giza' in device.pgqinf('VERSION').lower() else functional.identity
with pgenv(device):
# set the viewport to the header area and map to world coordinates 0,1 0,1
device.pgsvp( self.xl, self.xr, self.yt, 1 )
device.pgswin( 0, 1, 0, 1 )
device.pgsch( 0.8 )
# compute y position of succesive lines
ypos = map_(lambda lineno: 1.0 - (lineno+1.5)/(nline+1), range_(nline))
# plot the left lines
for (txt, pos) in zip(self.pageLabel.left, ypos):
device.pgptxt(0, pos, 0.0, 0.0, noUnderscore(txt))
# id. for the right ones
for (txt, pos) in zip(self.pageLabel.right, ypos):
device.pgptxt(1, pos, 0.0, 1.0, noUnderscore(txt))
# What's left is the center label, we print it LARGER than normal
device.pgsch( 1.6 );
device.pgptxt(0.5, 0.75, 0.0, 0.5, self.pageLabel.center);
def nextPage(self, device, curPlot, nPlot):
self.printlegend(device)
with pgenv(device):
device.pgpage()
device.pgsvp( 0.0, 1.0, 0.0, 1.0 )
device.pgswin( 0.0, 1.0, 0.0, 1.0 )
device.pgsci( 1 )
self.printPageLabel(device, curPlot, nPlot)
_fmt = ("Page({0.layout.nx}x{0.layout.ny} [x={0.xl:.3f}-{0.xr:.3f} y={0.yb:.3f}-{0.yt:.3f}] dx/y={0.dx:.3f} {0.dy:.3f} ddx/y={0.ddx:.3f} {0.ddy:.3f} " +
"lbl={0.labelCharSz:.3f} tick={0.tickCharSz:.3f} rs={0.rightShift_:.3f} bs={0.bottomShift_:.3f}").format
def __repr__(self):
return Page._fmt(self)
Drawers = enumerations.Enum("Lines", "Points", "Both")
AllInOne = type("AllInOne", (), {})()
##########################################################
####
#### Base class for plotter objects
####
##########################################################
noFilter = lambda x: True
# The label regex's match groups:
# non-capturing 3
# |
# 1 v
rxLabel = re.compile(r'([^ \t\v]+)\s*:\s*((?<![\\])[\'"])((?:.(?!(?<![\\])\2))*.?)\2')
# Standard x/y[n] axis description
# 1 2
rxXYAxis = re.compile(r'^(x|y([0-9]*))$').match
class Plotter(object):
#drawfuncs = { Drawers.Points: lambda dev, x, y, tp: dev.pgpt(x, y, tp),
# Drawers.Lines: lambda dev, x, y, tp: dev.pgline(x, y) }
def __init__(self, desc, xaxis, yaxis, lo, xscaling=None, yscaling=None, yheights=None, drawer=None, **kwargs):
# determine the number of subplots from the yaxis parameter we limit
# ourselves to accepting list(...) or anything else (if we would e.g.
# test wether 'yaxis' was a sequence than a yaxis of "hello" would
# result in five subplots: ['h', 'e', 'l', 'l', 'o'])
if not isinstance(yaxis, list):
yaxis = [yaxis]
self.xAxis = CP(xaxis)
self.yAxis = CP(yaxis)
self.yHeights = [0.97]*len(self.yAxis) if yheights is None else CP(yheights)
self.Description = CP(desc)
self.defaultLayout = CP(lo)
self.defaultFixedLayout = False
self.defaultDrawer = CP(Drawers.Points) if drawer is None else CP(drawer)
self.defaultxScaling = CP(xscaling) if xscaling is not None else CP(Scaling.auto_global)
self.defaultyScaling = CP(yscaling) if yscaling is not None else [Scaling.auto_global] * len(self.yAxis)
self.defaultsortOrder = lambda x: hash(x)
self.defaultsortOrderStr = "(none)"
self.defaultMarker = [None] * len(self.yAxis)
self.defaultMarkerStr = ["(none)"] * len(self.yAxis)
self.defaultCkFun = ckey_builtin
self.defaultCkFunS = "ckey_builtin"
self.defaultFilter = [noFilter] * len(self.yAxis)
self.defaultFilterS = ["(none)"] * len(self.yAxis)
self.defaultxLabel = ""
self.defaultyLabel = [""] * len(self.yAxis)
self.defaultShowHeader = True
self.defaultShowLegend = True
self.defaultShowSource = True
# Drawing attributes
self.defaultPointSize = 1
self.defaultLineWidth = 2
self.defaultMarkerSize = 1.5
self.defaultCharSize = 0 # zero = auto-scale, otherwise use this value
# Symbols for the different categories
self.defaultSymbol = {SYMBOL.Unflagged: -2, SYMBOL.Flagged: 5,
SYMBOL.Marked: 7, SYMBOL.Markedflagged: 27 }
# dict mapping a specific drawer to a method call on self
self.drawfuncs = { Drawers.Points: lambda dev, x, y, tp: self.drawPoints(dev, x, y, tp),
Drawers.Lines: lambda dev, x, y, tp: self.drawLines(dev, x, y) }
# this dict maps a specific drawer setting to list-of-functioncalls-to-self
self.drawDict = { Drawers.Points: [self.drawfuncs[Drawers.Points]],
Drawers.Lines: [self.drawfuncs[Drawers.Lines]],
Drawers.Both: [self.drawfuncs[Drawers.Points], self.drawfuncs[Drawers.Lines]] }
# we start off very clean (the following reset() will mark it dirty ofc)
self.dirtyCount = 0
# reset ourselves - go back to default plot settings
# some (if not all of these) can be modified by the user
self.reset()
# Trace "dirty" state - allow the plotter to detect if any of the plot attributes have changed since last time it used this plottype
def get_dirty(self):
return self.dirtyCount > 0
def set_dirty(self, value):
# Only accept True/False as settable arguments
if value not in (True, False):
raise RuntimeError("dirty can only be set True or False")
if value:
self.dirtyCount += 1
else:
self.dirtyCount = 0
return None
def del_dirty(self):
raise RuntimeError("tsssssk, *don't* do that!")
dirty = property(get_dirty, set_dirty, del_dirty, "Did any of the attributes change since last time this plotter was used")
## API methods
def description(self):
return self.Description
def xaxis(self):
return self.xAxis
def yaxis(self):
return self.yAxis
def nYaxes(self):
return len(self.yAxis)
def reset(self):
# There's at least three different y-scaling possibilities
# * externally given global scale
# * automatic global scale derived from the max across all plots
# * automatic scaling of each plot
# currently support two subplots in y axis. both subplots share
# the x-axis
self.dirtyCount = 1
self.layOut = CP(self.defaultLayout)
self.fixedLayout = CP(self.defaultFixedLayout)
self.xScale = CP(self.defaultxScaling)
self.yScale = CP(self.defaultyScaling)
self.sortOrder = CP(self.defaultsortOrder)
self.sortOrderStr = CP(self.defaultsortOrderStr)
self.marker = CP(self.defaultMarker)
self.markerStr = CP(self.defaultMarkerStr)
self.ck_fun = CP(self.defaultCkFun)
self.ck_fun_s = CP(self.defaultCkFunS)
self.filter_fun = CP(self.defaultFilter)
self.filter_fun_s = CP(self.defaultFilterS)
self.multiSubband = False
self.lineWidth = CP(self.defaultLineWidth)
self.pointSize = CP(self.defaultPointSize)
self.markerSize = CP(self.defaultMarkerSize)
self.charSize = CP(self.defaultCharSize)
self.symbol = CP(self.defaultSymbol)
self.drawMethod = CP([""]*len(self.yAxis))
self.drawers = CP([[]]*len(self.yAxis))
self.setDrawer(*str(self.defaultDrawer).split())
self.xLabel = CP(self.defaultxLabel)
self.yLabel = CP(self.defaultyLabel)
self.showHeader = CP(self.defaultShowHeader)
self.showLegend = CP(self.defaultShowLegend)
self.showSource = CP(self.defaultShowSource)
# self.drawers = [ [drawers-for-yaxis0], [drawers-for-yaxis1], ... ]
# self.drawMethod = "yaxis0:method yaxis1:method ...."
#
# allowed:
# 1 arg => set this drawer for all yAxes
# n arg => set the drawer for a specific yAxis
# format of argN:
# (<yAx>:)method
# if "(<yAx>:)" prefix is omitted the method will
# be set for yAxis N in stead of yAxis "<yAx>"
# n > nr-of-yaxes is not allowed
#