-
Notifications
You must be signed in to change notification settings - Fork 28
/
common_options.jl
1888 lines (1728 loc) · 71.9 KB
/
common_options.jl
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
# Parse the common options that all GMT modules share, plus some others functions of also common usage
const KW = Dict{Symbol,Any}
nt2dict(nt::NamedTuple) = nt2dict(; nt...)
nt2dict(; kw...) = Dict(kw)
function find_in_dict(d::Dict, symbs, del=false)
# See if D contains any of the symbols in SYMBS. If yes, return corresponding value
for symb in symbs
if (haskey(d, symb))
val = d[symb]
if (del) delete!(d, symb) end
return val, symb
end
end
return nothing, 0
end
function parse_R(cmd::String, d::Dict, O=false, del=false)
# Build the option -R string. Make it simply -R if overlay mode (-O) and no new -R is fished here
opt_R = ""
val, symb = find_in_dict(d, [:R :region :limits])
if (val !== nothing)
opt_R = build_opt_R(val)
if (del) delete!(d, symb) end
end
if (isempty(opt_R)) # See if we got the region as tuples of xlim, ylim [zlim]
R = ""; c = 0
if (haskey(d, :xlim) && isa(d[:xlim], Tuple) && length(d[:xlim]) == 2)
R = @sprintf(" -R%.15g/%.15g", d[:xlim][1], d[:xlim][2])
c += 2
if (haskey(d, :ylim) && isa(d[:ylim], Tuple) && length(d[:ylim]) == 2)
R = @sprintf("%s/%.15g/%.15g", R, d[:ylim][1], d[:ylim][2])
c += 2
if (haskey(d, :zlim) && isa(d[:zlim], Tuple) && length(d[:zlim]) == 2)
R = @sprintf("%s/%.15g/%.15g", R, d[:zlim][1], d[:zlim][2])
end
end
end
if (!isempty(R) && c == 4) opt_R = R end
end
if (O && isempty(opt_R)) opt_R = " -R" end
cmd = cmd * opt_R
return cmd, opt_R
end
function build_opt_R(Val)
if (isa(Val, String) || isa(Val, Symbol))
return string(" -R", Val)
elseif ((isa(Val, Array{<:Number}) || isa(Val, Tuple)) && (length(Val) == 4 || length(Val) == 6))
out = join([@sprintf("%.15g/",x) for x in Val])
return " -R" * rstrip(out, '/') # Remove last '/'
elseif (isa(Val, GMTgrid) || isa(Val, GMTimage))
return @sprintf(" -R%.15g/%.15g/%.15g/%.15g", Val.range[1], Val.range[2], Val.range[3], Val.range[4])
end
return ""
end
# ---------------------------------------------------------------------------------------------------
function parse_JZ(cmd::String, d::Dict, del=false)
opt_J = ""
val, symb = find_in_dict(d, [:JZ :Jz])
if (val !== nothing)
if (symb == :JZ) opt_J = " -JZ" * arg2str(val)
else opt_J = " -Jz" * arg2str(val)
end
cmd *= opt_J
if (del) delete!(d, symb) end
end
return cmd, opt_J
end
# ---------------------------------------------------------------------------------------------------
function parse_J(cmd::String, d::Dict, default="", map=true, O=false, del=false)
# Build the option -J string. Make it simply -J if overlay mode (-O) and no new -J is fished here
# Default to 14c if no size is provided.
# If MAP == false, do not try to append a fig size
opt_J = ""
if ((val = find_in_dict(d, [:J :proj], del)[1]) !== nothing)
opt_J = build_opt_J(val)
end
if (!map && opt_J != "")
return cmd * opt_J, opt_J
end
if (O && opt_J == "") opt_J = " -J" end
if (!O)
if (opt_J == "") opt_J = " -JX" end
# If only the projection but no size, try to get it from the kwargs.
if (haskey(d, :figsize))
s = arg2str(d[:figsize])
if (haskey(d, :units)) s *= d[:units][1] end
if (isdigit(opt_J[end])) opt_J *= "/" * s
else opt_J *= s
end
elseif ((val = find_in_dict(d, [:figscale :scale])[1]) !== nothing)
val = string(val)
if (opt_J == " -JX") isletter(val[1]) ? opt_J = " -J" * val : opt_J = " -Jx" * val # FRAGILE
else opt_J *= string(val)
end
elseif (default != "" && opt_J == " -JX")
opt_J = default # -JX was a working default
elseif (length(opt_J) == 4 || (length(opt_J) >= 5 && isletter(opt_J[5])))
if !(length(opt_J) >= 6 && isnumeric(opt_J[6]))
opt_J *= def_fig_size[1:3] # If no size, default to 12 centimeters
end
end
end
cmd *= opt_J
return cmd, opt_J
end
function build_opt_J(Val)
if (isa(Val, String) || isa(Val, Symbol))
s = string(Val)
if (!isletter(s[1])) error("This (" * s * ") is a bad 'proj' argument. Must start with a char code.") end
return " -J" * s
elseif (isa(Val, Number))
if (!(typeof(Val) <: Int) || Val < 2000)
error("The only valid case to provide a number to the 'proj' option is when that number is an EPSG code, but this (" * string(Val) * ") is clearly an invalid EPSG")
end
return string(" -J", string(Val))
elseif (isempty(Val))
return " -J"
end
return ""
end
# ---------------------------------------------------------------------------------------------------
function parse_B(cmd::String, d::Dict, opt_B::String="", del=false)
# These four are aliases
extra_parse = true
if ((val = find_in_dict(d, [:B :frame :axis :axes], del)[1]) !== nothing)
if (val == :none || val == "none") # User explicitly said NO AXES
return cmd * " -B0", " -B0"
elseif (val == :same || val == "same") # User explicitly said "Same as previous -B"
return cmd * " -B", " -B"
end
if (isa(val, NamedTuple)) opt_B = axis(val); extra_parse = false
else opt_B = string(val)
end
end
# Let the :title and x|y_label be given on main kwarg list. Risky if used with NamedTuples way.
t = "" # Use the trick to replace blanks by some utf8 char and undo it in extra_parse
if (haskey(d, :title)) t *= "+t" * replace(str_with_blancs(d[:title]), ' '=>'\U00AF'); end
if (haskey(d, :xlabel)) t *= " x+l" * replace(str_with_blancs(d[:xlabel]),' '=>'\U00AF'); end
if (haskey(d, :ylabel)) t *= " y+l" * replace(str_with_blancs(d[:ylabel]),' '=>'\U00AF'); end
if (t != "")
if (opt_B == "")
opt_B = def_fig_axes
else
if !( ((ind = findlast("-B",opt_B)) !== nothing || (ind = findlast(" ",opt_B)) !== nothing) &&
(occursin(r"[WESNwesntlbu+g+o]",opt_B[ind[1]:end])) )
t = " " * t; # Do not glue, for example, -Bg with :title
end
end
#opt_B = replace(opt_B, "-B" => "") # Needed so that bellow titles with blanks don't get -B's
opt_B *= t; extra_parse = true
end
# These are not and we can have one or all of them. NamedTuples are dealt at the end
for symb in [:xaxis :yaxis :zaxis :axis2 :xaxis2 :yaxis2]
if (haskey(d, symb) && !isa(d[symb], NamedTuple))
opt_B = string(d[symb], " ", opt_B)
end
end
if (extra_parse)
# This is old code that takes care to break a string in tokens and prefix with a -B to each token
tok = Vector{String}(undef, 10)
k = 1
r = opt_B
found = false
while (r != "")
tok[k],r = GMT.strtok(r)
#=
if (occursin(r"[WESNwesntlbu+g+o]", tok[k]) && !occursin("+t", tok[k])) # If title here, forget about :title
if (haskey(d, :title) && isa(d[:title], String))
tok[k] = tok[k] * "+t\"" * d[:title] * "\""
end
elseif (occursin(r"[afgpsxyz+S+u]", tok[k]) && !occursin(r"[+l+L]", tok[k])) # If label, forget about :x|y_label
if (haskey(d, :xlabel) && isa(d[:xlabel], String)) tok[k] = tok[k] * " -Bx+l\"" * d[:xlabel] * "\"" end
if (haskey(d, :ylabel) && isa(d[:ylabel], String)) tok[k] = tok[k] * " -By+l\"" * d[:ylabel] * "\"" end
end
=#
tok[k] = replace(tok[k], '\U00AF'=>' ')
if (!occursin("-B", tok[k]))
if (!occursin('"', tok[k]))
tok[k] = " -B" * tok[k] # Simple case, no quotes to break our heads
else
if (!found) tok[k] = " -B" * tok[k] # A title in quotes with spaces
else tok[k] = " " * tok[k]
end
found = !found
end
else
tok[k] = " " * tok[k]
end
k = k + 1
end
# Rebuild the B option string
opt_B = ""
for n = 1:k-1
opt_B = opt_B * tok[n]
end
end
# We can have one or all of them. Deal separatelly here to allow way code to keep working
this_opt_B = "";
for symb in [:xaxis :yaxis :zaxis :axis2 :xaxis2 :yaxis2 :zaxis2]
if (haskey(d, symb) && isa(d[symb], NamedTuple))
if (symb == :axis2) this_opt_B = axis(d[symb], secondary=true)
elseif (symb == :xaxis) this_opt_B = axis(d[symb], x=true) * this_opt_B
elseif (symb == :xaxis2) this_opt_B = axis(d[symb], x=true, secondary=true) * this_opt_B
elseif (symb == :yaxis) this_opt_B = axis(d[symb], y=true) * this_opt_B
elseif (symb == :yaxis2) this_opt_B = axis(d[symb], y=true, secondary=true) * this_opt_B
elseif (symb == :zaxis) this_opt_B = axis(d[symb], z=true) * this_opt_B
end
end
end
if (opt_B != def_fig_axes) opt_B *= this_opt_B
elseif (this_opt_B != "") opt_B = this_opt_B
end
return cmd * opt_B, opt_B
end
# ---------------------------------------------------------------------------------------------------
function parse_BJR(d::Dict, cmd::String, caller, O, default, del=false)
# Join these three in one function. CALLER is non-empty when module is called by plot()
cmd, opt_R = parse_R(cmd, d, O, del)
cmd, opt_J = parse_J(cmd, d, default, true, O, del)
if (!O && opt_J == "") # If we have no -J use this default
opt_J = default # " -JX12c/8c" (e.g. psxy) or " -JX12c/0" (e.g. grdimage)
cmd *= opt_J
elseif (O && opt_J == "")
cmd *= " -J"
end
if (caller != "" && occursin("-JX", opt_J)) # e.g. plot() sets 'caller'
if (caller == "plot3d" || caller == "bar3" || caller == "scatter3")
cmd, opt_B = parse_B(cmd, d, (O ? "" : def_fig_axes3), del)
else
cmd, opt_B = parse_B(cmd, d, (O ? "" : def_fig_axes), del) # For overlays, default is no axes
end
else
cmd, opt_B = parse_B(cmd, d, (O ? "" : def_fig_axes), del)
end
return cmd, opt_B, opt_J, opt_R
end
# ---------------------------------------------------------------------------------------------------
function parse_UXY(cmd::String, d::Dict, aliases, opt::Char)
# Parse the global -U, -X, -Y options. Return CMD same as input if no option OPT in args
# ALIASES: [:X :x_off :x_offset] (same for Y) or [:U :time_stamp :stamp]
if ((val = find_in_dict(d, aliases)[1]) !== nothing)
cmd = string(cmd, " -", opt, val)
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function parse_V(cmd::String, d::Dict)
# Parse the global -V option. Return CMD same as input if no -V option in args
if ((val = find_in_dict(d, [:V :verbose])[1]) !== nothing)
if (isa(val, Bool) && val) cmd *= " -V"
else cmd *= " -V" * arg2str(val)
end
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function parse_V_params(cmd::String, d::Dict)
# Parse the global -V option and the --PAR=val. Return CMD same as input if no options in args
cmd = parse_V(cmd, d)
return parse_params(cmd, d)
end
# ---------------------------------------------------------------------------------------------------
function parse_UVXY(cmd::String, d::Dict)
cmd = parse_V(cmd, d)
cmd = parse_UXY(cmd, d, [:X :x_off :off_x :x_offset], 'X')
cmd = parse_UXY(cmd, d, [:Y :y_off :off_y :y_offset], 'Y')
cmd = parse_UXY(cmd, d, [:U :stamp :time_stamp], 'U')
return cmd
end
# ---------------------------------------------------------------------------------------------------
function parse_a(cmd::String, d::Dict)
# Parse the global -a option. Return CMD same as input if no -a option in args
return parse_helper(cmd, d, [:a :aspatial], " -a")
end
# ---------------------------------------------------------------------------------------------------
function parse_b(cmd::String, d::Dict)
# Parse the global -b option. Return CMD same as input if no -b option in args
return parse_helper(cmd, d, [:b :binary], " -b")
end
# ---------------------------------------------------------------------------------------------------
function parse_bi(cmd::String, d::Dict)
# Parse the global -bi option. Return CMD same as input if no -bi option in args
return parse_helper(cmd, d, [:bi :binary_in], " -bi")
end
# ---------------------------------------------------------------------------------------------------
function parse_bo(cmd::String, d::Dict)
# Parse the global -bo option. Return CMD same as input if no -bo option in args
return parse_helper(cmd, d, [:bo :binary_out], " -bo")
end
# ---------------------------------------------------------------------------------------------------
function parse_d(cmd::String, d::Dict)
# Parse the global -di option. Return CMD same as input if no -di option in args
return parse_helper(cmd, d, [:d :nodata], " -d")
end
# ---------------------------------------------------------------------------------------------------
function parse_di(cmd::String, d::Dict)
# Parse the global -di option. Return CMD same as input if no -di option in args
return parse_helper(cmd, d, [:di :nodata_in], " -di")
end
# ---------------------------------------------------------------------------------------------------
function parse_do(cmd::String, d::Dict)
# Parse the global -do option. Return CMD same as input if no -do option in args
return parse_helper(cmd, d, [:do :nodata_out], " -do")
end
# ---------------------------------------------------------------------------------------------------
function parse_e(cmd::String, d::Dict)
# Parse the global -e option. Return CMD same as input if no -e option in args
return parse_helper(cmd, d, [:e :pattern], " -e")
end
# ---------------------------------------------------------------------------------------------------
function parse_f(cmd::String, d::Dict)
# Parse the global -f option. Return CMD same as input if no -f option in args
return parse_helper(cmd, d, [:f :colinfo], " -f")
end
# ---------------------------------------------------------------------------------------------------
function parse_g(cmd::String, d::Dict)
# Parse the global -g option. Return CMD same as input if no -g option in args
return parse_helper(cmd, d, [:g :gaps], " -g")
end
# ---------------------------------------------------------------------------------------------------
function parse_h(cmd::String, d::Dict)
# Parse the global -h option. Return CMD same as input if no -h option in args
return parse_helper(cmd, d, [:h :header], " -h")
end
# ---------------------------------------------------------------------------------------------------
function parse_i(cmd::String, d::Dict)
# Parse the global -i option. Return CMD same as input if no -i option in args
return parse_helper(cmd, d, [:i :incol], " -i")
end
# ---------------------------------------------------------------------------------------------------
function parse_n(cmd::String, d::Dict)
# Parse the global -n option. Return CMD same as input if no -n option in args
return parse_helper(cmd, d, [:n :interp :interpol], " -n")
end
# ---------------------------------------------------------------------------------------------------
function parse_o(cmd::String, d::Dict)
# Parse the global -o option. Return CMD same as input if no -o option in args
return parse_helper(cmd, d, [:o :outcol], " -o")
end
# ---------------------------------------------------------------------------------------------------
function parse_p(cmd::String, d::Dict)
# Parse the global -p option. Return CMD same as input if no -p option in args
return parse_helper(cmd, d, [:p :view :perspective], " -p")
end
# ---------------------------------------------------------------------------------------------------
function parse_s(cmd::String, d::Dict)
# Parse the global -s option. Return CMD same as input if no -s option in args
return parse_helper(cmd, d, [:s :skip_col], " -s")
end
# ---------------------------------------------------------------------------------------------------
function parse_swap_xy(cmd::String, d::Dict)
# Parse the global -: option. Return CMD same as input if no -: option in args
# But because we can't have a variable called ':' we use only the 'swap_xy' alias
return parse_helper(cmd, d, [:swap_xy :xy :yx], " -:")
end
# ---------------------------------------------------------------------------------------------------
function parse_r(cmd::String, d::Dict)
# Parse the global -r option. Return CMD same as input if no -r option in args
return parse_helper(cmd, d, [:r :reg :registration], " -r")
end
# ---------------------------------------------------------------------------------------------------
function parse_x(cmd::String, d::Dict)
# Parse the global -x option. Return CMD same as input if no -x option in args
return parse_helper(cmd, d, [:x :cores :n_threads], " -x")
end
# ---------------------------------------------------------------------------------------------------
function parse_t(cmd::String, d::Dict)
# Parse the global -t option. Return CMD same as input if no -t option in args
return parse_helper(cmd, d, [:t :alpha :transparency], " -t")
end
# ---------------------------------------------------------------------------------------------------
function parse_helper(cmd::String, d::Dict, symbs, opt::String)
# Helper function to the parse_?() global options. Isolate in a fun to not repeat over and over
opt_val = ""
if ((val = find_in_dict(d, symbs)[1]) !== nothing)
opt_val = opt * arg2str(val)
cmd *= opt_val
end
return cmd, opt_val
end
# ---------------------------------------------------------------------------------------------------
function parse_common_opts(d, cmd, opts)
for opt in opts
if (opt == :a) cmd, = parse_a(cmd, d)
elseif (opt == :b) cmd, = parse_b(cmd, d)
elseif (opt == :bi) cmd, = parse_bi(cmd, d)
elseif (opt == :bo) cmd, = parse_bo(cmd, d)
elseif (opt == :d) cmd, = parse_d(cmd, d)
elseif (opt == :di) cmd, = parse_di(cmd, d)
elseif (opt == :do) cmd, = parse_do(cmd, d)
elseif (opt == :e) cmd, = parse_e(cmd, d)
elseif (opt == :f) cmd, = parse_f(cmd, d)
elseif (opt == :g) cmd, = parse_g(cmd, d)
elseif (opt == :h) cmd, = parse_h(cmd, d)
elseif (opt == :i) cmd, = parse_i(cmd, d)
elseif (opt == :n) cmd, = parse_n(cmd, d)
elseif (opt == :o) cmd, = parse_o(cmd, d)
elseif (opt == :p) cmd, = parse_p(cmd, d)
elseif (opt == :r) cmd, = parse_r(cmd, d)
elseif (opt == :s) cmd, = parse_p(cmd, d)
elseif (opt == :x) cmd, = parse_x(cmd, d)
elseif (opt == :t) cmd, = parse_t(cmd, d)
elseif (opt == :xy) cmd, = parse_swap_xy(cmd, d)
elseif (opt == :yx) cmd, = parse_swap_xy(cmd, d)
elseif (opt == :R) cmd, = parse_R(cmd, d)
elseif (opt == :J) cmd, = parse_J(cmd, d)
elseif (opt == :JZ) cmd, = parse_JZ(cmd, d)
elseif (opt == :UVXY) cmd = parse_UVXY(cmd, d)
elseif (opt == :V_params) cmd = parse_V_params(cmd, d)
elseif (opt == :params) cmd = parse_params(cmd, d)
end
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function parse_these_opts(cmd, d, opts)
# Parse a group of options that individualualy would had been parsed as (example):
# cmd = add_opt(cmd, 'A', d, [:A :horizontal])
for opt in opts
cmd = add_opt(cmd, string(opt[1]), d, opt)
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function parse_inc(cmd::String, d::Dict, symbs, opt, del=false)
# Parse the quasi-global -I option. But arguments can be strings, arrays, tuples or NamedTuples
# At the end we must recreate this syntax: xinc[unit][+e|n][/yinc[unit][+e|n]] or
if ((val = find_in_dict(d, symbs, del)[1]) !== nothing)
if (isa(val, NamedTuple))
fn = fieldnames(typeof(val))
x = ""; y = ""; u = ""; e = false
for k = 1:length(fn)
if (fn[k] == :x) x = string(val[k])
elseif (fn[k] == :y) y = string(val[k])
elseif (fn[k] == :unit) u = string(val[k])
elseif (fn[k] == :extend) e = true
end
end
if (x == "") error("Need at least the x increment") end
cmd = string(cmd, " -", opt, x)
if (u != "")
if (u == "m" || u == "minutes" || u == "s" || u == "seconds" ||
u == "f" || u == "foot" || u == "k" || u == "km" || u == "n" || u == "nautical")
cmd *= u[1]
elseif (u == "e" || u == "meter") cmd *= "e"; u = "e"
elseif (u == "M" || u == "mile") cmd *= "M"; u = "M"
elseif (u == "nodes") cmd *= "+n"; u = "+n"
elseif (u == "data") u = "u"; # For the `scatter` modules
end
end
if (e) cmd *= "+e" end
if (y != "")
cmd = string(cmd, "/", y, u)
if (e) cmd *= "+e" end # Should never have this and u != ""
end
else
if (opt != "") cmd = string(cmd, " -", opt, arg2str(val))
else cmd = string(cmd, arg2str(val))
end
end
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function parse_params(cmd::String, d::Dict)
# Parse the gmt.conf parameters when used from within the modules. Return a --PAR=val string
# The input to this kwarg can be a tuple (e.g. (PAR,val)) or a NamedTuple (P1=V1, P2=V2,...)
if ((val = find_in_dict(d, [:conf :par :params])[1]) !== nothing)
if (isa(val, NamedTuple))
fn = fieldnames(typeof(val))
for k = 1:length(fn) # Suspect that this is higly inefficient but N is small
cmd *= " --" * string(fn[k]) * "=" * string(val[k])
end
elseif (isa(val, Tuple))
cmd *= " --" * string(val[1]) * "=" * string(val[2])
end
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function add_opt_pen(d::Dict, symbs, opt="", del::Bool=false)
# Build a pen option. Input can be either a full hard core string or spread in lw, lc, lw, etc or a tuple
if (opt != "") opt = " -" * opt end # Will become -W<pen>, for example
out = ""
pen = build_pen(d, del) # Either a full pen string or empty ("") (Seeks for lw, lc, etc)
if (pen != "")
out = opt * pen
else
if ((val = find_in_dict(d, symbs, del)[1]) !== nothing)
if (isa(val, Tuple)) # Like this it can hold the pen, not extended atts
out = opt * parse_pen(val) # Should be a better function
elseif (isa(val, NamedTuple)) # Make a recursive call. Will screw if used in mix mode
d2 = nt2dict(val) # Decompose the NT and feed into this-self
return opt * add_opt_pen(d2, symbs, "")
else
out = opt * arg2str(val)
end
end
end
# Some -W take extra options to indicate that color comes from CPT
if (haskey(d, :cline)) out *= "+cl" end
if (haskey(d, :ctext) || haskey(d, :csymbol)) out *= "+cf" end
if (haskey(d, :bezier)) out *= "+s" end
if (haskey(d, :offset)) out *= "+o" * arg2str(d[:offset]) end
if (out != "") # Search for eventual vec specs, but only if something above has activated -W
r = helper_arrows(d)
if (r != "")
if (haskey(d, :vec_start)) out *= "+vb" * r[2:end] # r[1] = 'v'
elseif (haskey(d, :vec_stop)) out *= "+ve" * r[2:end]
else out *= "+" * r
end
end
end
return out
end
# ---------------------------------------------------------------------------------------------------
function opt_pen(d::Dict, opt::Char, symbs)
# Create an option string of the type -Wpen
out = ""
pen = build_pen(d) # Either a full pen string or empty ("")
if (!isempty(pen))
out = string(" -", opt, pen)
else
if ((val = find_in_dict(d, symbs)[1]) !== nothing)
if (isa(val, String) || isa(val, Number))
out = string(" -", opt, val)
elseif (isa(val, Tuple)) # Like this it can hold the pen, not extended atts
out = string(" -", opt, parse_pen(val))
else
error(string("Nonsense in ", opt, " option"))
end
end
end
return out
end
# ---------------------------------------------------------------------------------------------------
function parse_pen(pen::Tuple)
# Convert an empty to 3 args tuple containing (width[c|i|p]], [color], [style[c|i|p|])
len = length(pen)
s = arg2str(pen[1]) # First arg is different because there is no leading ','
if (length(pen) > 1)
s *= ',' * get_color(pen[2])
if (length(pen) > 2) s *= ',' * arg2str(pen[3]) end
end
return s
end
# ---------------------------------------------------------------------------------------------------
function parse_pen_color(d::Dict, symbs=nothing, del::Bool=false)
# Need this as a separate fun because it's used from modules
lc = ""
if (symbs === nothing) symbs = [:lc :linecolor] end
if ((val = find_in_dict(d, symbs, del)[1]) !== nothing)
lc = get_color(val)
end
return lc
end
# ---------------------------------------------------------------------------------------------------
function build_pen(d::Dict, del::Bool=false)
# Search for lw, lc, ls in d and create a pen string in case they exist
# If no pen specs found, return the empty string ""
lw = add_opt("", "", d, [:lw :linewidth], nothing, del) # Line width
ls = add_opt("", "", d, [:ls :linestyle], nothing, del) # Line style
lc = parse_pen_color(d, [:lc :linecolor], del)
out = ""
if (lw != "" || lc != "" || ls != "")
out = lw * "," * lc * "," * ls
while (out[end] == ',') out = rstrip(out, ',') end # Strip unneeded commas
end
return out
end
# ---------------------------------------------------------------------------------------------------
function parse_arg_and_pen(arg::Tuple)
# Parse an ARG of the type (arg, (pen)) and return a string. These may be used in pscoast -I & -N
if (isa(arg[1], String)) s = arg[1]
elseif (isa(arg[1], Number)) s = @sprintf("%d", arg[1])
else error("Nonsense first argument")
end
if (length(arg) > 1 && isa(arg[2], Tuple)) s *= "/" * parse_pen(arg[2]) end
return s
end
# ---------------------------------------------------------------------------------------------------
function arg2str(arg)
# Convert an empty, a numeric or string ARG into a string ... if it's not one to start with
# ARG can also be a Bool, in which case the TRUE value is converted to "" (empty string)
if (isa(arg, String) || isa(arg, Symbol))
out = string(arg)
elseif (isempty_(arg) || (isa(arg, Bool) && arg))
out = ""
elseif (isa(arg, Number)) # Have to do it after the Bool test above because Bool is a Number too
out = @sprintf("%.15g", arg)
elseif (isa(arg, Array{<:Number}) || isa(arg, Tuple))
out = join([@sprintf("%.15g/",x) for x in arg])
out = rstrip(out, '/') # Remove last '/'
else
error(@sprintf("arg2str: argument 'arg' can only be a String, Symbol, Number, Array or a Tuple,
but was %s", typeof(arg)))
end
end
# ---------------------------------------------------------------------------------------------------
function set_KO(first::Bool)
# Set the O K pair dance
if (first) K = true; O = false
else K = true; O = true;
end
return K, O
end
# ---------------------------------------------------------------------------------------------------
function finish_PS(d::Dict, cmd::String, output::String, K::Bool, O::Bool)
# Finish a PS creating command. All PS creating modules should use this.
if (!haskey(d, :P) && !haskey(d, :portrait)) cmd *= " -P" end
if (K && !O) opt = " -K"
elseif (K && O) opt = " -K -O"
elseif (!K && O) opt = " -O"
else opt = ""
end
if (output != "")
if (K && !O) cmd *= opt * " > " * output
elseif (!K && !O) cmd *= opt * " > " * output
elseif (O) cmd *= opt * " >> " * output
end
else
if ((K && !O) || (!K && !O) || O) cmd *= opt end
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function add_opt(cmd::String, opt, d::Dict, symbs, mapa=nothing, del::Bool=false, arg=nothing)
# Scan the D Dict for SYMBS keys and if found create the new option OPT and append it to CMD
# If DEL == true we remove the found key.
if ((val = find_in_dict(d, symbs, del)[1]) !== nothing)
if (isa(val, NamedTuple)) args = add_opt(val, mapa, arg)
else args = arg2str(val)
end
if (opt != "") cmd = string(cmd, " -", opt, args)
else cmd = string(cmd, args)
end
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function add_opt(nt::NamedTuple, mapa::NamedTuple, arg=nothing)
# Generic parser of options passed in a NT and whose last element is anther NT with the mapping
# between expanded sub-options names and the original GMT flags.
# Example:
# add_opt((a=(1,0.5),b=2), (a="+a",b="-b"))
# translates to: "+a1/0.5-b2"
key = keys(nt);
d = nt2dict(mapa) # The flags mapping as a Dict
cmd = ""
for k = 1:length(key) # Loop over the keys of option's tuple
if (haskey(d, key[k]))
if (isa(d[key[k]], Tuple)) # Complexify it
if (isa(nt[k], NamedTuple))
cmd *= d[key[k]][1] * d[key[k]][2](nt2dict(nt[k]), [])
else
cmd *= d[key[k]][1] * d[key[k]][2](Dict(key[k] => nt[k]), [key[k]])
end
elseif (d[key[k]] == "1") # Means that only first char in value is retained. Used with units
t = arg2str(nt[k])
if (t != "") cmd *= t[1]
else cmd *= "1" # "1" is itself the flag
end
elseif (d[key[k]] != "" && d[key[k]][1] == '|') # Potentialy append to the arg matrix
if (arg === nothing)
@warn(@sprintf("The key %s implies appending to input but the 'arg' variable is empty. Ignoring it.",key[k]))
continue
end
if (isa(nt[k], AbstractArray) || isa(nt[k], NTuple))
if (mod(length(arg), length(nt[k])) != 0)
@warn("The columns to be appended do not have the same number of rows as the input data. Ignoring it.")
continue
end
if (isa(nt[k], AbstractArray)) append!(arg, reshape(nt[k], :))
else append!(arg, reshape(collect(nt[k]), :))
end
end
cmd *= d[key[k]][2:end] # And now append the flag
else
cmd *= d[key[k]] * arg2str(nt[k])
end
end
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function add_opt_cpt(d::Dict, cmd::String, symbs, opt::Char, N_args=0, arg1=[], arg2=[])
# Deal with options of the form -Ccolor, where color can be a string or a GMTcpt type
# N_args only applyies to when a GMTcpt was transmitted. Than it's either 0, case in which
# the cpt is put in arg1, or 1 and the cpt goes to arg2.
if ((val = find_in_dict(d, symbs)[1]) !== nothing)
if (isa(val, GMT.GMTcpt))
cmd = string(cmd, " -", opt)
if (N_args == 0) arg1 = val; N_args += 1
elseif (N_args == 1) arg2 = val; N_args += 1
else error(string("Can't send the CPT data via ", opt, " and input array"))
end
else
cmd = string(cmd, " -", opt, get_color(val))
end
end
return cmd, arg1, arg2, N_args
end
# ---------------------------------------------------------------------------------------------------
add_opt_fill(d::Dict, symbs, opt="") = add_opt_fill("", d, symbs, opt)
function add_opt_fill(cmd::String, d::Dict, symbs, opt="")
# Deal with the area fill attributes option. Normally, -G
if ((val = find_in_dict(d, symbs)[1]) === nothing) return cmd end
if (opt != "") opt = " -" * opt end
if (isa(val, NamedTuple))
d2 = nt2dict(val)
cmd *= opt
if (haskey(d2, :pattern)) cmd *= 'p' * add_opt("", "", d2, [:pattern])
elseif (haskey(d2, :inv_pattern)) cmd *= 'P' * add_opt("", "", d2, [:inv_pattern])
else error("For 'fill' option as a NamedTuple, you MUST provide a 'patern' member")
end
if ((val2 = find_in_dict(d2, [:bg :background])[1]) !== nothing)
cmd *= "+b" * get_color(val2)
end
if ((val2 = find_in_dict(d2, [:fg :foreground])[1]) !== nothing)
cmd *= "+f" * get_color(val2)
end
if (haskey(d2, :dpi)) cmd = string(cmd, "+r", d2[:dpi]) end
else
cmd *= opt * get_color(val)
end
return cmd
end
# ---------------------------------------------------------------------------------------------------
function get_color(val)
# Parse a color input. Always return a string
# color1,color2[,color3,…] colorn can be a r/g/b triplet, a color name, or an HTML hexadecimal color (e.g. #aabbcc
if (isa(val, String) || isa(val, Symbol) || isa(val, Number)) return string(val) end
if (isa(val, Tuple) && (length(val) == 3))
if (val[1] <= 1 && val[2] <= 1 && val[3] <= 1) # Assume colors components are in [0 1]
return @sprintf("%d/%d/%d", val[1]*255, val[2]*255, val[3]*255)
else
return @sprintf("%d/%d/%d", val[1], val[2], val[3])
end
elseif (isa(val, Array) && (size(val, 2) == 3))
if (val[1,1] <= 1 && val[1,2] <= 1 && val[1,3] <= 1)
copy = val .* 255 # Do not change the original
else
copy = val
end
out = @sprintf("%d/%d/%d", copy[1], copy[2], copy[3])
for k = 2:size(copy, 1)
out = @sprintf("%s,%d/%d/%d", out, copy[k,1], copy[k,2], copy[k,3])
end
return out
else
error(@sprintf("GOT_COLOR, got and unsupported data type: %s", typeof(val)))
end
end
# ---------------------------------------------------------------------------------------------------
function font(d::Dict, symbs)
font(collect(values(d))[1]) # Don't understand why types got so complicated that must use 'collect'
end
function font(val)
# parse and create a font string.
# TODO: either add a NammedTuple option and/or guess if 2nd arg is the font name or the color
# And this: Optionally, you may append =pen to the fill value in order to draw the text outline with
# the specified pen; if used you may optionally skip the filling of the text by setting fill to -.
if (isa(val, String) || isa(val, Number)) return string(val) end
if (isa(val, Tuple))
s = parse_units(val[1])
if (length(val) > 1)
s = string(s,',',val[2])
if (length(val) > 2)
s = string(s, ',', get_color(val[3]))
end
end
end
end
# ---------------------------------------------------------------------------------------------------
function parse_units(val)
# Parse a units string in the form d|e|f|k|n|M|n|s or expanded
if (isa(val, String) || isa(val, Symbol) || isa(val, Number)) return string(val) end
if (isa(val, Tuple) && (length(val) == 2))
return string(val[1], parse_unit_unit(val[2]))
else
error(@sprintf("PARSE_UNITS, got and unsupported data type: %s", typeof(val)))
end
end
# ---------------------------
function parse_unit_unit(str)
out = ""
if (isa(str, Symbol)) str = string(str) end
if (!isa(str, String))
error(@sprintf("Argument data type must be String or Symbol but was: %s", typeof(str)))
end
if (str == "e" || str == "meter") out = "e";
elseif (str == "M" || str == "mile") out = "M";
elseif (str == "nodes") out = "+n";
elseif (str == "data") out = "u"; # For the `scatter` modules
else out = string(str[1]) # To be type-stable
end
return out
end
# ---------------------------------------------------------------------------------------------------
# ---------------------------------------------------------------------------------------------------
axis(nt::NamedTuple; x=false, y=false, z=false, secondary=false) = axis(;x=x, y=y, z=z, secondary=secondary, nt...)
function axis(;x=false, y=false, z=false, secondary=false, kwargs...)
# Build the (terrible) -B option
d = KW(kwargs)
# Before anything else
if (haskey(d, :none)) return " -B0" end
secondary ? primo = 's' : primo = 'p' # Primary or secondary axis
x ? axe = "x" : y ? axe = "y" : z ? axe = "z" : axe = "" # Are we dealing with a specific axis?
opt = " -B"
if (haskey(d, :axes)) opt *= helper0_axes(d[:axes]) end
if (haskey(d, :corners)) opt *= string(d[:corners]) end # 1234
#if (haskey(d, :fill)) opt *= "+g" * get_color(d[:fill]) end
if (haskey(d, :fill)) opt *= "+g" * add_opt_fill(d, [:fill]) end # Works, but patterns can screw
if (haskey(d, :cube)) opt *= "+b" end
if (haskey(d, :noframe)) opt *= "+n" end
if (haskey(d, :oblique_pole)) opt *= "+o" * arg2str(d[:oblique_pole]) end
if (haskey(d, :title)) opt *= "+t" * str_with_blancs(arg2str(d[:title])) end
if (opt == " -B") opt = "" end # If nothing, no -B
# axes supps
ax_sup = ""
if (haskey(d, :seclabel)) ax_sup *= "+s" * str_with_blancs(arg2str(d[:seclabel])) end
if (haskey(d, :label))
opt *= " -B" * primo * axe * "+l" * str_with_blancs(arg2str(d[:label])) * ax_sup
else
if (haskey(d, :xlabel)) opt *= " -B" * primo * "x+l" * str_with_blancs(arg2str(d[:xlabel])) * ax_sup end
if (haskey(d, :zlabel)) opt *= " -B" * primo * "z+l" * str_with_blancs(arg2str(d[:zlabel])) * ax_sup end
if (haskey(d, :ylabel))
opt *= " -B" * primo * "y+l" * str_with_blancs(arg2str(d[:ylabel])) * ax_sup
elseif (haskey(d, :Yhlabel))
axe != "y" ? opt_L = "y+L" : opt_L = "+L"
opt *= " -B" * primo * axe * opt_L * str_with_blancs(arg2str(d[:Yhlabel])) * ax_sup
end
end
# intervals
ints = ""
if (haskey(d, :annot)) ints *= "a" * helper1_axes(d[:annot]) end
if (haskey(d, :annot_unit)) ints *= helper2_axes(d[:annot_unit]) end
if (haskey(d, :ticks)) ints *= "f" * helper1_axes(d[:ticks]) end
if (haskey(d, :grid)) ints *= "g" * helper1_axes(d[:grid]) end
if (haskey(d, :prefix)) ints *= "+p" * str_with_blancs(arg2str(d[:prefix])) end
if (haskey(d, :suffix)) ints *= "+u" * str_with_blancs(arg2str(d[:suffix])) end
if (haskey(d, :custom))
if (isa(d[:custom], String)) ints *= 'c' * d[:custom]
else
if ((r = helper3_axes(d[:custom], primo, axe)) != "") ints = ints * 'c' * r end
end
# Should find a way to also accept custom=GMTdataset
elseif (haskey(d, :pi))
if (isa(d[:pi], Number))
ints = string(ints, d[:pi], "pi") # (n)pi
elseif (isa(d[:pi], Array) || isa(d[:pi], Tuple))
ints = string(ints, d[:pi][1], "pi", d[:pi][2]) # (n)pi(m)
end
elseif (haskey(d, :scale))
s = arg2str(d[:scale])
if (s == "log") ints *= 'l'
elseif (s == "10log") ints *= 'p'
elseif (s == "exp") ints *= 'p'
end
end
if (haskey(d, :phase_add))
ints *= "+" * arg2str(d[:phase_add])
elseif (haskey(d, :phase_sub))
ints *= "-" * arg2str(d[:phase_sub])
end
if (ints != "") opt *= " -B" * primo * axe * ints end
# Check if ax_sup was requested
if (opt == "" && ax_sup != "") opt = " -B" * primo * axe * ax_sup end
return opt
end
# ------------------------
function helper0_axes(arg)
# Deal with the available ways of specifying the WESN(Z),wesn(z),lbrt(u)
# The solution is very enginious and allows using "left_full", "l_full" or only "l_f"
# to mean 'W'. Same for others:
# bottom|bot|b_f(ull); right|r_f(ull); t(op)_f(ull); up_f(ull) => S, E, N, Z
# bottom|bot|b_t(icks); right|r_t(icks); t(op)_t(icks); up_t(icks) => s, e, n, z
# bottom|bot|b_b(are); right|r_b(are); t(op)_b(are); up_b(are) => b, r, t, u
if (isa(arg, String) || isa(arg, Symbol)) # Assume that a WESNwesn string was already sent in.
return string(arg)
end
if (!isa(arg, Tuple))
error(@sprintf("The 'axes' argument must be a String, Symbol or a Tuple but was (%s)", typeof(arg)))
end
opt = ""
for k = 1:length(arg)
t = string(arg[k]) # For the case it was a symbol
if (occursin("_f", t))
if (t[1] == 'l') opt *= "W"
elseif (t[1] == 'b') opt *= "S"
elseif (t[1] == 'r') opt *= "E"
elseif (t[1] == 't') opt *= "N"
elseif (t[1] == 'u') opt *= "Z"
end
elseif (occursin("_t", t))
if (t[1] == 'l') opt *= "w"
elseif (t[1] == 'b') opt *= "s"
elseif (t[1] == 'r') opt *= "e"
elseif (t[1] == 't') opt *= "n"
elseif (t[1] == 'u') opt *= "z"
end
elseif (occursin("_b", t))
if (t[1] == 'l') opt *= "l"
elseif (t[1] == 'b') opt *= "b"
elseif (t[1] == 'r') opt *= "r"
elseif (t[1] == 't') opt *= "t"
elseif (t[1] == 'u') opt *= "u"