-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgmtpy.py
2273 lines (1764 loc) · 74.8 KB
/
gmtpy.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
import subprocess
import cStringIO
import re
import os
import sys
import shutil
from itertools import izip
from os.path import join as pjoin
import tempfile
import random
import logging
import math
import numpy as num
golden_ratio = 1.61803
point = 1.0/72.0
# units in points
units = { 'i':72., 'c':72./2.54, 'm':72.*100./2.54, 'p':1. }
inch = units['i']
cm = units['c']
alphabet = 'abcdefghijklmnopqrstuvwxyz'
gmt_installations = {}
gmt_installations['4.2.1'] = { 'home': '/sw/etch-ia32/gmt-4.2.1',
'bin': '/sw/etch-ia32/gmt-4.2.1/bin' }
gmt_installations['4.3.0'] = { 'home': '/sw/etch-ia32/gmt-4.3.0',
'bin': '/sw/etch-ia32/gmt-4.3.0/bin' }
#gmt_installations['4.3.1'] = { 'home': '/sw/share/gmt',
# 'bin': '/sw/bin' }
def cmp_version(a,b):
ai = [ int(x) for x in a.split('.') ]
bi = [ int(x) for x in b.split('.') ]
return cmp(ai, bi)
newest_installed_gmt_version = sorted(gmt_installations.keys(), cmp=cmp_version)[-1]
# To have consistent defaults, they are hardcoded here and should not be changed.
gmt_defaults_by_version = {}
gmt_defaults_by_version['4.2.1'] = r'''
#
# GMT-SYSTEM 4.2.1 Defaults file
#
#-------- Plot Media Parameters -------------
PAGE_COLOR = 255/255/255
PAGE_ORIENTATION = portrait
PAPER_MEDIA = a4+
#-------- Basemap Annotation Parameters ------
ANNOT_MIN_ANGLE = 20
ANNOT_MIN_SPACING = 0
ANNOT_FONT_PRIMARY = Helvetica
ANNOT_FONT_SIZE = 12p
ANNOT_OFFSET_PRIMARY = 0.075i
ANNOT_FONT_SECONDARY = Helvetica
ANNOT_FONT_SIZE_SECONDARY = 16p
ANNOT_OFFSET_SECONDARY = 0.075i
DEGREE_SYMBOL = ring
HEADER_FONT = Helvetica
HEADER_FONT_SIZE = 36p
HEADER_OFFSET = 0.1875i
LABEL_FONT = Helvetica
LABEL_FONT_SIZE = 14p
LABEL_OFFSET = 0.1125i
OBLIQUE_ANNOTATION = 1
PLOT_CLOCK_FORMAT = hh:mm:ss
PLOT_DATE_FORMAT = yyyy-mm-dd
PLOT_DEGREE_FORMAT = +ddd:mm:ss
Y_AXIS_TYPE = hor_text
#-------- Basemap Layout Parameters ---------
BASEMAP_AXES = WESN
BASEMAP_FRAME_RGB = 0/0/0
BASEMAP_TYPE = plain
FRAME_PEN = 1.25p
FRAME_WIDTH = 0.075i
GRID_CROSS_SIZE_PRIMARY = 0i
GRID_CROSS_SIZE_SECONDARY = 0i
GRID_PEN_PRIMARY = 0.25p
GRID_PEN_SECONDARY = 0.5p
MAP_SCALE_HEIGHT = 0.075i
TICK_LENGTH = 0.075i
POLAR_CAP = 85/90
TICK_PEN = 0.5p
X_AXIS_LENGTH = 9i
Y_AXIS_LENGTH = 6i
X_ORIGIN = 1i
Y_ORIGIN = 1i
UNIX_TIME = FALSE
UNIX_TIME_POS = -0.75i/-0.75i
#-------- Color System Parameters -----------
COLOR_BACKGROUND = 0/0/0
COLOR_FOREGROUND = 255/255/255
COLOR_NAN = 128/128/128
COLOR_IMAGE = adobe
COLOR_MODEL = rgb
HSV_MIN_SATURATION = 1
HSV_MAX_SATURATION = 0.1
HSV_MIN_VALUE = 0.3
HSV_MAX_VALUE = 1
#-------- PostScript Parameters -------------
CHAR_ENCODING = ISOLatin1+
DOTS_PR_INCH = 300
N_COPIES = 1
PS_COLOR = rgb
PS_IMAGE_COMPRESS = none
PS_IMAGE_FORMAT = ascii
PS_LINE_CAP = round
PS_LINE_JOIN = miter
PS_MITER_LIMIT = 0
PS_VERBOSE = FALSE
GLOBAL_X_SCALE = 1
GLOBAL_Y_SCALE = 1
#-------- I/O Format Parameters -------------
D_FORMAT = %lg
FIELD_DELIMITER = tab
GRIDFILE_SHORTHAND = FALSE
GRID_FORMAT = nf
INPUT_CLOCK_FORMAT = hh:mm:ss
INPUT_DATE_FORMAT = yyyy-mm-dd
IO_HEADER = FALSE
N_HEADER_RECS = 1
OUTPUT_CLOCK_FORMAT = hh:mm:ss
OUTPUT_DATE_FORMAT = yyyy-mm-dd
OUTPUT_DEGREE_FORMAT = +D
XY_TOGGLE = FALSE
#-------- Projection Parameters -------------
ELLIPSOID = WGS-84
MAP_SCALE_FACTOR = default
MEASURE_UNIT = inch
#-------- Calendar/Time Parameters ----------
TIME_FORMAT_PRIMARY = full
TIME_FORMAT_SECONDARY = full
TIME_EPOCH = 2000-01-01T00:00:00
TIME_IS_INTERVAL = OFF
TIME_INTERVAL_FRACTION = 0.5
TIME_LANGUAGE = us
TIME_SYSTEM = other
TIME_UNIT = d
TIME_WEEK_START = Sunday
Y2K_OFFSET_YEAR = 1950
#-------- Miscellaneous Parameters ----------
HISTORY = TRUE
INTERPOLANT = akima
LINE_STEP = 0.01i
VECTOR_SHAPE = 0
VERBOSE = FALSE'''
gmt_defaults_by_version['4.3.0'] = r'''
#
# GMT-SYSTEM 4.3.0 Defaults file
#
#-------- Plot Media Parameters -------------
PAGE_COLOR = 255/255/255
PAGE_ORIENTATION = portrait
PAPER_MEDIA = a4+
#-------- Basemap Annotation Parameters ------
ANNOT_MIN_ANGLE = 20
ANNOT_MIN_SPACING = 0
ANNOT_FONT_PRIMARY = Helvetica
ANNOT_FONT_SIZE_PRIMARY = 12p
ANNOT_OFFSET_PRIMARY = 0.075i
ANNOT_FONT_SECONDARY = Helvetica
ANNOT_FONT_SIZE_SECONDARY = 16p
ANNOT_OFFSET_SECONDARY = 0.075i
DEGREE_SYMBOL = ring
HEADER_FONT = Helvetica
HEADER_FONT_SIZE = 36p
HEADER_OFFSET = 0.1875i
LABEL_FONT = Helvetica
LABEL_FONT_SIZE = 14p
LABEL_OFFSET = 0.1125i
OBLIQUE_ANNOTATION = 1
PLOT_CLOCK_FORMAT = hh:mm:ss
PLOT_DATE_FORMAT = yyyy-mm-dd
PLOT_DEGREE_FORMAT = +ddd:mm:ss
Y_AXIS_TYPE = hor_text
#-------- Basemap Layout Parameters ---------
BASEMAP_AXES = WESN
BASEMAP_FRAME_RGB = 0/0/0
BASEMAP_TYPE = plain
FRAME_PEN = 1.25p
FRAME_WIDTH = 0.075i
GRID_CROSS_SIZE_PRIMARY = 0i
GRID_PEN_PRIMARY = 0.25p
GRID_CROSS_SIZE_SECONDARY = 0i
GRID_PEN_SECONDARY = 0.5p
MAP_SCALE_HEIGHT = 0.075i
POLAR_CAP = 85/90
TICK_LENGTH = 0.075i
TICK_PEN = 0.5p
X_AXIS_LENGTH = 9i
Y_AXIS_LENGTH = 6i
X_ORIGIN = 1i
Y_ORIGIN = 1i
UNIX_TIME = FALSE
UNIX_TIME_POS = BL/-0.75i/-0.75i
UNIX_TIME_FORMAT = %Y %b %d %H:%M:%S
#-------- Color System Parameters -----------
COLOR_BACKGROUND = 0/0/0
COLOR_FOREGROUND = 255/255/255
COLOR_NAN = 128/128/128
COLOR_IMAGE = adobe
COLOR_MODEL = rgb
HSV_MIN_SATURATION = 1
HSV_MAX_SATURATION = 0.1
HSV_MIN_VALUE = 0.3
HSV_MAX_VALUE = 1
#-------- PostScript Parameters -------------
CHAR_ENCODING = ISOLatin1+
DOTS_PR_INCH = 300
N_COPIES = 1
PS_COLOR = rgb
PS_IMAGE_COMPRESS = none
PS_IMAGE_FORMAT = ascii
PS_LINE_CAP = round
PS_LINE_JOIN = miter
PS_MITER_LIMIT = 0
PS_VERBOSE = FALSE
GLOBAL_X_SCALE = 1
GLOBAL_Y_SCALE = 1
#-------- I/O Format Parameters -------------
D_FORMAT = %lg
FIELD_DELIMITER = tab
GRIDFILE_SHORTHAND = FALSE
GRID_FORMAT = nf
INPUT_CLOCK_FORMAT = hh:mm:ss
INPUT_DATE_FORMAT = yyyy-mm-dd
IO_HEADER = FALSE
N_HEADER_RECS = 1
OUTPUT_CLOCK_FORMAT = hh:mm:ss
OUTPUT_DATE_FORMAT = yyyy-mm-dd
OUTPUT_DEGREE_FORMAT = +D
XY_TOGGLE = FALSE
#-------- Projection Parameters -------------
ELLIPSOID = WGS-84
MAP_SCALE_FACTOR = default
MEASURE_UNIT = inch
#-------- Calendar/Time Parameters ----------
TIME_FORMAT_PRIMARY = full
TIME_FORMAT_SECONDARY = full
TIME_EPOCH = 2000-01-01T00:00:00
TIME_IS_INTERVAL = OFF
TIME_INTERVAL_FRACTION = 0.5
TIME_LANGUAGE = us
TIME_UNIT = d
TIME_WEEK_START = Sunday
Y2K_OFFSET_YEAR = 1950
#-------- Miscellaneous Parameters ----------
HISTORY = TRUE
INTERPOLANT = akima
LINE_STEP = 0.01i
VECTOR_SHAPE = 0
VERBOSE = FALSE'''
gmt_defaults_by_version['4.3.1'] = r'''
#
# GMT-SYSTEM 4.3.1 Defaults file
#
#-------- Plot Media Parameters -------------
PAGE_COLOR = 255/255/255
PAGE_ORIENTATION = portrait
PAPER_MEDIA = a4+
#-------- Basemap Annotation Parameters ------
ANNOT_MIN_ANGLE = 20
ANNOT_MIN_SPACING = 0
ANNOT_FONT_PRIMARY = Helvetica
ANNOT_FONT_SIZE_PRIMARY = 12p
ANNOT_OFFSET_PRIMARY = 0.075i
ANNOT_FONT_SECONDARY = Helvetica
ANNOT_FONT_SIZE_SECONDARY = 16p
ANNOT_OFFSET_SECONDARY = 0.075i
DEGREE_SYMBOL = ring
HEADER_FONT = Helvetica
HEADER_FONT_SIZE = 36p
HEADER_OFFSET = 0.1875i
LABEL_FONT = Helvetica
LABEL_FONT_SIZE = 14p
LABEL_OFFSET = 0.1125i
OBLIQUE_ANNOTATION = 1
PLOT_CLOCK_FORMAT = hh:mm:ss
PLOT_DATE_FORMAT = yyyy-mm-dd
PLOT_DEGREE_FORMAT = +ddd:mm:ss
Y_AXIS_TYPE = hor_text
#-------- Basemap Layout Parameters ---------
BASEMAP_AXES = WESN
BASEMAP_FRAME_RGB = 0/0/0
BASEMAP_TYPE = plain
FRAME_PEN = 1.25p
FRAME_WIDTH = 0.075i
GRID_CROSS_SIZE_PRIMARY = 0i
GRID_PEN_PRIMARY = 0.25p
GRID_CROSS_SIZE_SECONDARY = 0i
GRID_PEN_SECONDARY = 0.5p
MAP_SCALE_HEIGHT = 0.075i
POLAR_CAP = 85/90
TICK_LENGTH = 0.075i
TICK_PEN = 0.5p
X_AXIS_LENGTH = 9i
Y_AXIS_LENGTH = 6i
X_ORIGIN = 1i
Y_ORIGIN = 1i
UNIX_TIME = FALSE
UNIX_TIME_POS = BL/-0.75i/-0.75i
UNIX_TIME_FORMAT = %Y %b %d %H:%M:%S
#-------- Color System Parameters -----------
COLOR_BACKGROUND = 0/0/0
COLOR_FOREGROUND = 255/255/255
COLOR_NAN = 128/128/128
COLOR_IMAGE = adobe
COLOR_MODEL = rgb
HSV_MIN_SATURATION = 1
HSV_MAX_SATURATION = 0.1
HSV_MIN_VALUE = 0.3
HSV_MAX_VALUE = 1
#-------- PostScript Parameters -------------
CHAR_ENCODING = ISOLatin1+
DOTS_PR_INCH = 300
N_COPIES = 1
PS_COLOR = rgb
PS_IMAGE_COMPRESS = none
PS_IMAGE_FORMAT = ascii
PS_LINE_CAP = round
PS_LINE_JOIN = miter
PS_MITER_LIMIT = 0
PS_VERBOSE = FALSE
GLOBAL_X_SCALE = 1
GLOBAL_Y_SCALE = 1
#-------- I/O Format Parameters -------------
D_FORMAT = %lg
FIELD_DELIMITER = tab
GRIDFILE_SHORTHAND = FALSE
GRID_FORMAT = nf
INPUT_CLOCK_FORMAT = hh:mm:ss
INPUT_DATE_FORMAT = yyyy-mm-dd
IO_HEADER = FALSE
N_HEADER_RECS = 1
OUTPUT_CLOCK_FORMAT = hh:mm:ss
OUTPUT_DATE_FORMAT = yyyy-mm-dd
OUTPUT_DEGREE_FORMAT = +D
XY_TOGGLE = FALSE
#-------- Projection Parameters -------------
ELLIPSOID = WGS-84
MAP_SCALE_FACTOR = default
MEASURE_UNIT = inch
#-------- Calendar/Time Parameters ----------
TIME_FORMAT_PRIMARY = full
TIME_FORMAT_SECONDARY = full
TIME_EPOCH = 2000-01-01T00:00:00
TIME_IS_INTERVAL = OFF
TIME_INTERVAL_FRACTION = 0.5
TIME_LANGUAGE = us
TIME_UNIT = d
TIME_WEEK_START = Sunday
Y2K_OFFSET_YEAR = 1950
#-------- Miscellaneous Parameters ----------
HISTORY = TRUE
INTERPOLANT = akima
LINE_STEP = 0.01i
VECTOR_SHAPE = 0
VERBOSE = FALSE'''
def gmt_default_config(version):
'''Get default GMT configuration dict for given version.'''
if not version in gmt_defaults_by_version:
raise Exception('No GMT defaults for version %s found' % version)
gmt_defaults = gmt_defaults_by_version[version]
d = {}
for line in gmt_defaults.splitlines():
sline = line.strip()
if not sline or sline.startswith('#'): continue
k,v = sline.split('=',1)
d[k.strip()] = v.strip()
return d
def diff_defaults(v1,v2):
d1 = gmt_default_config(v1)
d2 = gmt_default_config(v2)
for k in d1:
if k not in d2:
print '%s not in %s' % (k, v2)
else:
if d1[k] != d2[k]:
print '%s %s = %s' % (v1, k, d1[k])
print '%s %s = %s' % (v2, k, d2[k])
for k in d2:
if k not in d1:
print '%s not in %s' % (k, v1)
#diff_defaults('4.2.1', '4.3.1')
# store defaults as dicts into the gmt installations dicts
for version, installation in gmt_installations.iteritems():
installation['defaults'] = gmt_default_config(version)
installation['version'] = version
# alias for the newest installed gmt version
gmt_installations['newest'] = gmt_installations[newest_installed_gmt_version]
paper_sizes_a = '''A0 2380 3368
A1 1684 2380
A2 1190 1684
A3 842 1190
A4 595 842
A5 421 595
A6 297 421
A7 210 297
A8 148 210
A9 105 148
A10 74 105
B0 2836 4008
B1 2004 2836
B2 1418 2004
B3 1002 1418
B4 709 1002
B5 501 709
archA 648 864
archB 864 1296
archC 1296 1728
archD 1728 2592
archE 2592 3456
flsa 612 936
halfletter 396 612
note 540 720
letter 612 792
legal 612 1008
11x17 792 1224
ledger 1224 792'''
paper_sizes = {}
for line in paper_sizes_a.splitlines():
k, w, h = line.split()
paper_sizes[k.lower()] = float(w), float(h)
def make_bbox( width, height, gmt_config, margins=(0.8,0.8,0.8,0.8)):
leftmargin, topmargin, rightmargin, bottommargin = margins
portrait = gmt_config['PAGE_ORIENTATION'].lower() == 'portrait'
paper_size = paper_sizes[gmt_config['PAPER_MEDIA'].lower().rstrip('+')]
if not portrait: paper_size = paper_size[1], paper_size[0]
xoffset = (paper_size[0] - (width + leftmargin + rightmargin)) / 2.0 + leftmargin;
yoffset = (paper_size[1] - (height + topmargin + bottommargin)) / 2.0 + bottommargin;
if portrait:
bb1 = int((xoffset - leftmargin));
bb2 = int((yoffset - bottommargin));
bb3 = bb1 + int((width+leftmargin+rightmargin));
bb4 = bb2 + int((height+topmargin+bottommargin));
else:
bb1 = int((yoffset - topmargin));
bb2 = int((xoffset - leftmargin));
bb3 = bb1 + int((height+topmargin+bottommargin));
bb4 = bb2 + int((width+leftmargin+rightmargin));
return xoffset, yoffset, (bb1,bb2,bb3,bb4)
def check_gmt_installation( installation ):
home_dir = installation['home']
bin_dir = installation['bin']
version = installation['version']
for d in home_dir, bin_dir:
if not os.path.exists(d):
logging.error(('Directory does not exist: %s\n'+
'Check your GMT installation.') % d)
gmtdefaults = pjoin(bin_dir, 'gmtdefaults')
args = [ gmtdefaults ]
environ = os.environ.copy()
environ['GMTHOME'] = home_dir
p = subprocess.Popen( args, stderr=subprocess.PIPE, env=environ )
(stdout, stderr) = p.communicate()
m = re.search(r'(\d+(\.\d+)*)', stderr)
if not m:
raise Exception("Can't extract version number from output of %s" % gmtdefaults)
versionfound = m.group(1)
if versionfound != version:
raise Exception(('Expected GMT version %s but found version %s.\n'+
'(Looking at output of %s)') % (version, versionfound, gmtdefaults))
def get_gmt_installation(version):
if version not in gmt_installations:
logging.warn('GMT version %s not installed, taking version %s instead' %
(version, newest_installed_gmt_version))
version = 'newest'
installation = dict(gmt_installations[version])
check_gmt_installation( installation )
return installation
def gmtdefaults_as_text(version='newest'):
'''Get the built-in gmtdefaults.'''
if version not in gmt_installations:
logging.warn('GMT version %s not installed, taking version %s instead' %
(version, newest_installed_gmt_version))
version = 'newest'
if version == 'newest':
version = newest_installed_gmt_version
return gmt_defaults_by_version[version]
class Guru:
'''Abstract base class providing template interpolation, accessible as attributes.
Classes deriving from this one, have to implement a get_params(), which is
called to get a dict to do ordinary "%(key)x"-substitutions. The deriving class
must also provide a dict with the templates.'''
def fill(self, templates, **kwargs):
params = self.get_params(**kwargs)
strings = [ t % params for t in templates ]
return strings
# hand through templates dict
def __getitem__(self, template_name):
return self.templates[template_name]
def __setitem__(self, template_name, template):
self.templates[template_name] = template
def __contains__(self, template_name):
return template_name in self.templates
def __iter__(self):
return iter(self.templates)
def __len__(self):
return len(self.templates)
def __delitem__(self, template_name):
del(self.templates[template_name])
def _simple_fill(self, template_names, **kwargs):
templates = [ self.templates[n] for n in template_names ]
return self.fill(templates, **kwargs)
def __getattr__(self, template_names):
def f(**kwargs):
return self._simple_fill(template_names, **kwargs)
return f
class AutoScaler:
'''Tunable 1D autoscaling based on data range.
Instances of this class may be used to determine nice minima, maxima and
increments for ax annotations, as well as suitable common exponents for
notation.
The autoscaling process is guided by the following public attributes
(default values are given in parantheses):
approx_ticks (7.0):
Approximate number of increment steps (tickmarks) to generate.
mode ('auto'):
Mode of operation: one of 'auto', 'min-max', '0-max', 'min-0',
'symmetric' or 'off'.
'auto': Look at data range and choose one of the choices below.
'min-max': Output range is selected to include data range.
'0-max': Output range shall start at zero and end at data max.
'min-0': Output range shall start at data min and end at zero.
'symmetric': Output range shall by symmetric by zero.
'off': Similar to 'min-max', but snap and space are disabled,
such that the output range always exactly matches the
data range.
exp (None):
If defined, override automatically determined exponent for notation by
the given value.
snap (False):
If set to True, snap output range to multiples of increment. This
parameter has no effect, if mode is set to 'off'.
inc (None):
If defined, override automatically determined tick increment by the
given value.
space (0.0):
Add some padding to the range. The value given, is the fraction by which
the output range is increased on each side. If mode is '0-max' or 'min-0',
the end at zero is kept fixed at zero. This parameter has no effect if
mode is set to 'off'.
exp_factor (3):
Exponent of notation is chosen to be a multiple of this value.
no_exp_interval ((-3,5)):
Range of exponent, for which no exponential notation is allowed.'''
def __init__(self, approx_ticks=7.0,
mode='auto',
exp=None,
snap=False,
inc=None,
space=0.0,
exp_factor=3,
no_exp_interval=(-3,5)):
'''Create new AutoScaler instance.
The parameters are described in the AutoScaler documentation.
'''
self.approx_ticks = approx_ticks
self.mode = mode
self.exp = exp
self.snap = snap
self.inc = inc
self.space = space
self.exp_factor = exp_factor
self.no_exp_interval = no_exp_interval
def make_scale(self, data_range, override_mode=None):
'''Get nice minimum, maximum and increment for given data range.
Returns (minimum,maximum,increment) or (maximum,minimum,-increment),
depending on whether data_range is (data_min, data_max) or (data_max,
data_min). If override_mode is defined, the mode attribute is
temporarily overridden by the given value.
'''
data_min = min(data_range)
data_max = max(data_range)
is_reverse = (data_range[0] > data_range[1])
a = self.mode
if self.mode == 'auto':
a = self.guess_autoscale_mode( data_min, data_max )
if override_mode is not None:
a = override_mode
mi, ma = 0, 0
if a == 'off':
mi, ma = data_min, data_max
elif a == '0-max':
mi = 0.0
if data_max > 0.0:
ma = data_max
else:
ma = 1.0
elif a == 'min-0':
ma = 0.0
if data_min < 0.0:
mi = data_min
else:
mi = -1.0
elif a == 'min-max':
mi, ma = data_min, data_max
elif a == 'symmetric':
m = max(abs(data_min),abs(data_max))
mi = -m
ma = m
nmi = mi
if (mi != 0. or a == 'min-max') and a != 'off':
nmi = mi - self.space*(ma-mi)
nma = ma
if (ma != 0. or a == 'min-max') and a != 'off':
nma = ma + self.space*(ma-mi)
mi, ma = nmi, nma
if mi == ma and a != 'off':
mi -= 1.0
ma += 1.0
# make nice tick increment
if self.inc is not None:
inc = self.inc
else:
inc = self.nice_value( (ma-mi)/self.approx_ticks )
if inc == 0.0:
inc = 1.0
# snap min and max to ticks if this is wanted
if self.snap and a != 'off':
ma = inc * math.ceil(ma/inc)
mi = inc * math.floor(mi/inc)
if is_reverse:
return ma, mi, -inc
else:
return mi, ma, inc
def make_exp(self, x):
'''Get nice exponent for notation of x.
For ax annotations, give tick increment as x.'''
if self.exp is not None: return self.exp
x = abs(x)
if x == 0.0: return 0
if 10**self.no_exp_interval[0] <= x <= 10**self.no_exp_interval[1]: return 0
return math.floor(math.log10(x)/self.exp_factor)*self.exp_factor
def guess_autoscale_mode(self, data_min, data_max):
'''Guess mode of operation, based on data range.
Used to map 'auto' mode to '0-max', 'min-0', 'min-max' or 'symmetric'.
'''
if data_min >= 0.0:
if data_min < data_max/2.:
a = '0-max'
else:
a = 'min-max'
if data_max <= 0.0:
if data_max > data_min/2.:
a = 'min-0'
else:
a = 'min-max'
if data_min < 0.0 and data_max > 0.0:
if abs((abs(data_max)-abs(data_min))/(abs(data_max)+abs(data_min))) < 0.5:
a = 'symmetric'
else:
a = 'min-max'
return a
def nice_value(self, x):
'''Round x to nice value.'''
exp = 1.0
sign = 1
if x<0.0:
x = -x
sign = -1
while x >= 1.0:
x /= 10.0
exp *= 10.0
while x < 0.1:
x *= 10.0
exp /= 10.0
if x >= 0.75:
return sign * 1.0 * exp
if x >= 0.375:
return sign * 0.5 * exp
if x >= 0.225:
return sign * 0.25 * exp
if x >= 0.15:
return sign * 0.2 * exp
return sign * 0.1 * exp
class Ax(AutoScaler):
'''Ax description with autoscaling capabilities.
The ax is described by the AutoScaler's public attributes, plus the following
additional attributes (with default values given in paranthesis):
label (''):
Ax label (without unit).
unit (''):
Physical unit of the data attached to this ax.
scaled_unit (''),
scaled_unit_factor(1.):
Scaled physical unit and factor between unit and scaled_unit such that
unit = scaled_unit_factor x scaled_unit.
(E.g. if unit is 'm' and data is in the range of nanometers, you may
want to set the scaled_unit to 'nm' and the scaled_unit_factor to 1e9.)
limits (None):
If defined, fix range of ax to limits=(min,max).'''
def __init__(self, label='', unit='', scaled_unit_factor=1., scaled_unit='', limits=None, **kwargs):
'''Create new Ax instance.'''
AutoScaler.__init__(self, **kwargs )
self.label = label
self.unit = unit
self.scaled_unit_factor = scaled_unit_factor
self.scaled_unit = scaled_unit
self.limits = limits
def label_str(self, exp, unit):
'''Get label string including the unit and multiplier.'''
slabel, sunit, sexp = '', '', ''
if self.label:
slabel = self.label
if unit or exp != 0:
if exp != 0:
sexp = '\\327 10@+%i@+' % exp
sunit = '[ %s %s ]' % (sexp, unit)
else:
sunit = '[ %s ]' % unit
p = []
if slabel: p.append(slabel)
if sunit: p.append(sunit)
return ' '.join(p)
def make_params(self, data_range, ax_projection=False, override_mode=None):
'''Get min, max, increment and label string for ax display.'
Returns minimum, maximum, increment and label string including unit and
multiplier for given data range.
If ax_projection is True, values suitable to be displayed on the ax are
returned, e.g. min, max and inc are returned in scaled units. Otherwise
the values are returned in the original units, without any scaling.
'''
sf = self.scaled_unit_factor
dr_scaled = [ sf*x for x in data_range ]
mi,ma,inc = self.make_scale( dr_scaled, override_mode=override_mode )
if ax_projection:
exp = self.make_exp( inc )
if sf == 1.:
unit = self.unit
else:
unit = self.scaled_unit
label = self.label_str( exp, unit )
return mi/10**exp, ma/10**exp, inc/10**exp, label
else:
label = self.label_str( 0, self.unit )
return mi/sf, ma/sf, inc/sf, label
class ScaleGuru(Guru):
'''2D/3D autoscaling and ax annotation facility.
Instances of this class provide automatic determination of plot ranges, tick
increments and scaled annotations, as well as label/unit handling. It can in
particular be used to automatically generate the -R and -B option arguments,
which are required for most GMT commands.
It extends the functionality of the Ax and AutoScaler classes at the level,
where it can not be handled anymore by looking at a single dimension of the
dataset's data, e.g.:
i) The ability to impose a fixed aspect ratio between two axes.
ii) Recalculation of data range on non-limited axes, when there are
limits imposed on other axes.
'''
def __init__(self, data_tuples=None, axes=None, aspect=None):
self.templates = dict(
R='-R%(xmin)g/%(xmax)g/%(ymin)g/%(ymax)g',
B='-B%(xinc)g:%(xlabel)s:/%(yinc)g:%(ylabel)s:WSen' )
maxdim = 2
if data_tuples:
maxdim = max(maxdim,max( [ len(dt) for dt in data_tuples ] ))
if axes is not None:
self.axes = axes
else:
self.axes = [ Ax() for i in range(maxdim) ]
self.data_tuples = data_tuples
# sophisticated data-range calculation
data_ranges = [None] * maxdim
for dt in data_tuples:
in_range = True
for ax,x in zip(self.axes, dt):
if ax.limits:
in_range = num.logical_and(in_range, num.logical_and(ax.limits[0]<=x, x<=ax.limits[1]))
for i,ax,x in zip(range(maxdim),self.axes, dt):
if not ax.limits:
if in_range is not True:
xmasked = num.where(in_range, x, num.NaN)
range_this = num.nanmin(xmasked), num.nanmax(xmasked)
else:
range_this = num.nanmin(x), num.nanmax(x)
else:
range_this = ax.limits
if data_ranges[i] is None and range_this[0] <= range_this[1]:
data_ranges[i] = range_this
else:
data_ranges[i] = (min(data_ranges[i][0],range_this[0]),
max(data_ranges[i][1],range_this[1]))
for i in range(len(data_ranges)):
if data_ranges[i] is None:
data_ranges[i] = (0.,1.)
self.data_ranges = data_ranges
self.aspect = aspect
def get_params(self, ax_projection=False):
'''Get dict with output parameters.
For each data dimension, ax minimum, maximum, increment and a label
string (including unit and exponential factor) are determined. E.g. in
for the first dimension the output dict will contain the keys 'xmin',
'xmax', 'xinc', and 'xlabel'.
Normally, values corresponding to the scaling of the raw data are
produced, but if ax_projection is True, values which are suitable to be
printed on the axes are returned. This means that in the latter case,
the 'scaled_unit' and 'scaled_unit_factor' attributes as set on the axes
are respected and that a common 10^x factor is factored out and put to
the label string.
'''
xmi, xma, xinc, xlabel = self.axes[0].make_params( self.data_ranges[0], ax_projection )
ymi, yma, yinc, ylabel = self.axes[1].make_params( self.data_ranges[1], ax_projection )
if len(self.axes) > 2:
zmi, zma, zinc, zlabel = self.axes[2].make_params( self.data_ranges[2], ax_projcetion )
# enforce certain aspect, if needed
if self.aspect is not None:
xwid = xma-xmi
ywid = yma-ymi
if ywid < xwid*self.aspect:
ymi -= (xwid*self.aspect - ywid)*0.5
yma += (xwid*self.aspect - ywid)*0.5
ymi, yma, yinc, ylabel = self.axes[1].make_params( (ymi, yma), ax_projection, override_mode='off' )
elif xwid < ywid/self.aspect:
xmi -= (ywid/self.aspect - xwid)*0.5
xma += (ywid/self.aspect - xwid)*0.5
xmi, xma, xinc, xlabel = self.axes[0].make_params( (xmi, xma), ax_projection, override_mode='off' )
params = dict(xmin=xmi, xmax=xma, xinc=xinc, xlabel=xlabel,
ymin=ymi, ymax=yma, yinc=yinc, ylabel=ylabel)
if len(self.axes) > 2:
params.update( dict(zmin=zmi, zmax=zma, zinc=zinc, zlabel=zlabel) )
return params
class GumSpring:
'''Sizing policy implementing a minimal size, plus a desire to grow.'''
def __init__(self, minimal=None, grow=None):
self.minimal = minimal
if grow is None:
if minimal is None:
self.grow = 1.0