-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathutils_types.jl
More file actions
2681 lines (2391 loc) · 135 KB
/
utils_types.jl
File metadata and controls
2681 lines (2391 loc) · 135 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
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
function text_record(data, text::Union{String, Vector{String}, Vector{Vector{String}}}, hdr=Vector{String}())
# Create a text record to send to pstext. DATA is the Mx2 coordinates array.
# TEXT is a string or a cell array
(isa(data, Vector)) && (data = data[:,:]) # Needs to be 2D
#(!isa(data, Array{Float64})) && (data = Float64.(data))
if (isa(text, String))
_hdr = isempty(hdr) ? "" : hdr[1]
T = GMTdataset(data, Float64[], Float64[], DictSvS(), String[], [text], _hdr, String[], "", "", 0, 0)
elseif (isa(text, Vector{String}))
if (text[1][1] == '>') # Alternative (but risky) way of setting the header content
T = GMTdataset(data, Float64[], Float64[], DictSvS(), String[], text[2:end], text[1], String[], "", "", 0, 0)
else
_hdr = isempty(hdr) ? "" : (isa(hdr, Vector{String}) ? hdr[1] : hdr)
T = GMTdataset(data, Float64[], Float64[], DictSvS(), String[], text, _hdr, String[], "", "", 0, 0)
end
elseif (isa(text, Array{Array}) || isa(text, Array{Vector{String}}))
nl_t = length(text); nl_d = size(data,1)
(nl_d > 0 && nl_d != nl_t) && error("Number of data points ($nl_d) is not equal to number of text strings ($nl_t).")
T = Vector{GMTdataset{Float64, 2}}(undef,nl_t)
for k = 1:nl_t
T[k] = GMTdataset((nl_d == 0 ? fill(NaN, length(text[k]) ,2) : data[k]), Float64[], Float64[], DictSvS(), String[], text[k], (isempty(hdr) ? "" : hdr[k]), Vector{String}(), "", "", 0, 0)
end
else
error("Wrong type ($(typeof(text))) for the 'text' argin")
end
(!isempty(data) && !isnan(data[1])) && set_dsBB!(T)
return T
end
text_record(text::String, hdr::String="") = text_record(fill(NaN,1,2), text, (hdr == "") ? String[] : [hdr])
text_record(text::Vector{String}, hdr::Union{String,Vector{String}}=String[]) = text_record(fill(NaN,length(text),2), text, hdr)
#text_record(text::AbstractVector, hdr::Vector{String}=String[]) = text_record(Array{Float64,2}(undef,0,0), text, hdr)
text_record(text) = text_record(Array{Float64,2}(undef,0,0), text)
# ---------------------------------------------------------------------------------------------------
"""
D = mat2ds(mat [,txt]; x=nothing, text=nothing, multi=false, geom=0, kwargs...)
Take a 2D `mat` array and convert it into a GMTdataset. `x` is an optional coordinates vector (must have the
same number of elements as rows in `mat`). Use `x=:ny` to generate a coords array 1:n_rows of `mat`.
Alternatively, if `mat` is a string or vector of strings we return a dataset with NaN's in the place of
the coordinates. This form is useful to pass to `text` when using the `region_justify` option that
does not need explicit coordinates to place the text.
- `txt`: (A POSITIONAL arg) Return a Text record which is a Dataset with data = Mx2 and text in third column. The ``text``
can be an array with same size as `mat` rows or a string (will be repeated n_rows times.). The keywords `txt` or `text`
are also accepted in alternative to this (positional) `txt` argument.
- `x`: An optional vector with the _xx_ coordinates
- `hdr`: optional String vector with either one or n_rows multi-element headers.
- `lc` or `linecolor` or `color`: optional array of strings/symbols with color names/values. Its length can be
smaller than n_cols, case in which colors will be cycled. If `color` is not an array of strings, e.g.
`color="yes"`, the colors cycle trough a pre-defined set of colors (same colors as in Matlab). If you
want the same color repeated for many lines pass color as a vector. *e.g,* `color=[color]`
- `linethick` or `lt`: for selecting different line thicknesses. Works like `color`, but should be
a vector of numbers, or just a single number that is then applied to all lines.
- `fill`: Optional string array (or a String of comma separated color names, or a Tuple of color names)
with color names or array of "patterns".
- `fillalpha` : When `fill` option is used, we can set the transparency of filled polygons with this
option that takes in an array (vec or 1-row matrix) with numeric values between [0-1] or ]1-100],
where 100 (or 1) means full transparency.
- `is3D`: If input 'mat' contains at least x,y,z (?).
- `ls` or `linestyle`: Line style. A string or an array of strings with `length = size(mat,2)` with line styles.
- `front`: Front Line style. A string or an array of strings with `length = size(mat,2)` with front line styles.
- `pen`: A full pen setting. A string or an array of strings with `length = size(mat,2)` with pen settings.
This differs from `lt` in the sense that `lt` does not directly set the line thickness.
- `multi` or `multicol`: When number of columns in `mat` > 2, or == 2 and x != nothing, make an multisegment Dataset
with first column and 2, first and 3, etc. Convenient when want to plot a matrix where each column is a line.
- `segnan` or `nanseg`: Boolean. If true make a multi-segment made out of segments separated by NaNs.
- `datatype`: Keep the original data type of `mat`. Default converts to Float64.
- `geom`: The data geometry. By default, we set `wkbUnknown` but try to do some basic guess.
- `proj` or `proj4`: A proj4 string for dataset SRS. Default is empty. To set it to lon,lat in WGS84 use ``proj=prj4WGS84``
- `wkt`: A WKT SRS string.
- `epsg`: An integer EPSG code. _e.g._ ``epsg=4326`` for lon,lat in WGS84. Default is 0.
- `colnames`: Optional string vector with names for each column of `mat`.
- `attrib`: Optional dictionary{String, String} with attributes of this dataset.
- `ref:`Pass in a reference GMTdataset from which we'll take the georeference info as well as `attrib` and `colnames`
- `txt` or `text`: Vector{String} with text to add into the .text field, but this forces the return of a Text record.
See what is said above about the `txt` positional argument.
- `txtcol` or `textcol`: Vector{String} with text to add into the .text field. Warning: no testing is done
to check if ``length(txtcol) == size(mat,1)`` as it must.
"""
mat2ds(mat::Nothing) = mat # Method to simplify life and let call mat2ds on a nothing
mat2ds(mat::GDtype) = mat # Method to simplify life and let call mat2ds on a already GMTdataset
mat2ds(text::Union{AbstractString, Vector{<:AbstractString}}) = text_record(text) # Now we can hide text_record
mat2ds(text::Vector{String}; hdr::String="", kw...) = text_record(fill(NaN,length(text),2), text, [hdr]) # The kw... is only to not error
function mat2ds(mat::AbstractMatrix{T}; hdr=String[], geom=0, kw...) where {T<:Real}
_mat2ds_dt(mat, isa(hdr, String) ? [hdr] : vec(hdr), Int(geom), KW(kw))
end
function _mat2ds_dt(@nospecialize(mat), hdr::Vector{String}, geom::Int, d::Dict{Symbol,Any})
# Here we are expecting that Any-ness results from columns with DateTime. If not returm 'mat' as is
# DateTime columns are converted to seconds and a regular GMTdatset with appropriate column names and attribs is return
c = zeros(Bool, size(mat, 2))
for k = 1:size(mat,2)
if (typeof(mat[1,k]) == DateTime)
mat[:,k] = Dates.value.(mat[:,k]) ./ 1000;
c[k] = true
end
end
D::GMTdataset = _mat2ds(convert(Matrix{Float64}, mat), String[], hdr, geom, d)
ind = findall(c)
if (!isempty(ind))
Tc = ""
for k = 1:numel(ind)
D.colnames[ind[k]] = "Time"; (k > 1) && (D.colnames[ind[k]] *= "$k")
Tc = (Tc == "") ? "$k" : Tc * ",$k" # Accept more than one time columns
end
(Tc != "") && (D.attrib["Timecol"] = Tc; D.attrib["Time_epoch"] = " --TIME_EPOCH=0000-12-31T00:00:00 --TIME_UNIT=s")
end
D
end
# Method for catching external types of data (e.g. DataFrame)
mat2ds(X; kw...) = tabletypes2ds(X, ((val = find_in_dict(KW(kw), [:interp])[1]) !== nothing) ? interp=val : interp=0)
# ---------------------------------------------------------------------------------------------------
"""
D = mat2ds(mat::Vector{<:AbstractMatrix}; hdr=String[], kwargs...)::Vector{GMTdataset}
Create a multi-segment GMTdataset (a vector of GMTdataset) from matrices passed in a vector-of-matrices `mat`.
The matrices elements of `mat` do not need to have the same number of rows. Think on this as specifying groups
of lines/points each sharing the same settings. KWarg options of this form are more limited in number than
in the general case, but can take the form of a Vector{Vector}, Vector or scalars.
In the former case (Vector{Vector}) the length of each Vector[i] must equal to the number of rows of each mat[i].
- `hdr`: optional String vector with either one or `length(mat)` multi-segment headers.
- `pen`: A full pen setting. A string or an array of strings with `length = length(mat)` with pen settings.
- `lc` or `linecolor` or `color`: optional color or array of strings/symbols with color names/values.
- `linethick` or `lt`: for selecting different line thicknesses. Works like `color`, but should be
a vector of numbers, or just a single number that is then applied to all lines.
- `ls` or `linestyle`: Line style. A string or an array of strings with `length = length(mat)` with line styles.
- `front`: Front Line style. A string or an array of strings with `length = length(mat)` with front line styles.
- `fill`: Optional string array (or a String of comma separated color names, or a Tuple of color names)
with color names or array of "patterns".
- `fillalpha`: When `fill` option is used, we can set the transparency of filled polygons or symbols with this
option that takes in an array (vec or 1-row matrix) with numeric values between [0-1] or ]1-100],
where 100 (or 1) means full transparency.
### Example:
D = mat2ds([rand(6,3), rand(4,3), rand(3,3)], fill=[[:red], [:green], [:blue]], fillalpha=[0.5,0.7,0.8])
"""
function mat2ds(mat::Vector{<:AbstractMatrix}; hdr=String[], kwargs...)
mat2ds(mat, hdr, KW(kwargs))
end
function mat2ds(mat::Vector{<:AbstractMatrix{T}}, hdr::Vector{String}, d::Dict)::Vector{GMTdataset{T,2}} where {T<:Real}
D = Vector{GMTdataset{eltype(mat[1]), 2}}(undef, length(mat))
pen = find_in_dict(d, [:pen])[1]
color = find_in_dict(d, [:lc :linecolor :color])[1]
ls = find_in_dict(d, [:ls :linestyle])[1]
lt = find_in_dict(d, [:lt :linethick :lw])[1]
front = find_in_dict(d, [:front])[1]
fill = find_in_dict(d, [:fill :fillcolor])[1]
alpha = find_in_dict(d, [:fillalpha])[1]
coln = find_in_dict(d, [:colnames])[1]
geom::Int = ((val = find_in_dict(d, [:geom])[1]) === nothing) ? 0 : val
proj4, wkt, epsg, _, _ = helper_set_crs(d) # Fish the eventual CRS options.
for k = 1:length(mat)
_hdr = length(hdr) <= 1 ? hdr : hdr[k]
_pen = (pen !== nothing) ? (isa(pen, Vector) ? (length(pen) == 1 ? pen : pen[k]) : [pen]) : pen
_ls = (ls !== nothing) ? (isa(ls, Vector) ? (length(ls) == 1 ? ls : ls[k]) : [ls]) : ls
_lt = (lt !== nothing) ? (isa(lt, Vector) ? (length(lt) == 1 ? lt : lt[k]) : [lt]) : lt
_front = (front !== nothing) ? (isa(front, Vector) ? (length(front) == 1 ? front : front[k]) : [front]) : front
_color = (color !== nothing) ? (isa(color, Vector) ? (length(color) == 1 ? color : color[k]) : [color]) : color
_fill = (fill !== nothing) ? (isa(fill, Vector) ? (length(fill) == 1 ? fill : fill[k]) : [fill]) : fill
_alpha = (alpha !== nothing) ? (isa(alpha, Vector) ? (length(alpha) == 1 ? alpha : alpha[k]) : [alpha]) : alpha
if (k == 1)
D[k] = mat2ds(mat[k], hdr=_hdr, color=_color, fill=_fill, fillalpha=_alpha, pen=_pen, lt=_lt, ls=_ls, front=_front, geom=geom, colnames=coln, proj4=proj4, wkt=wkt, epsg=epsg)
else
D[k] = mat2ds(mat[k], hdr=_hdr, color=_color, fill=_fill, fillalpha=_alpha, pen=_pen, lt=_lt, ls=_ls, front=_front, geom=geom)
end
end
set_dsBB!(D, false)
return D
end
# ---------------------------------------------------------------------------------------------------
function helper_set_crs(d)
# Return CRS info eventually passed in kwargs (converted into 'd') + attrib & colnames if :ref is used
if ((val = find_in_dict(d, [:ref])[1]) !== nothing) # ref has to be a D but we'll not test it
Dt::GMTdataset = val # To try to escape the f... Any's
prj, wkt, epsg = Dt.proj4, Dt.wkt, Dt.epsg
return prj, wkt, epsg, Dt.attrib, Dt.colnames
end
ref_attrib, ref_coln = Dict(), String[]
prj = hlp_desnany_str(d, [:proj, :proj4])
(prj == "geo" || prj == "geog") && (prj = prj4WGS84)
(prj != "" && !startswith(prj, "+proj=")) && (prj = "+proj=" * prj)
wkt = hlp_desnany_str(d, [:wkt])
(prj == "" && wkt != "") && (prj = wkt2proj(wkt))
epsg::Int = ((ep = hlp_desnany_int(d, [:epsg])) !== -999) ? ep : 0
(prj == "" && wkt == "" && epsg != 0) && (prj = epsg2proj(epsg))
return prj, wkt, epsg, ref_attrib, ref_coln
end
# ---------------------------------------------------------------------------------------------------
"""
D = mat2ds(mat::Array{T,N}, D::GMTdataset)
Take a 2D `mat` array and convert it into a GMTdataset. Pass in a reference GMTdataset from which we'll take
the georeference info as well as `attrib` and `colnames`.
"""
mat2ds(mat::Array{T,N}, ref::GMTdataset) where {T<:Real,N} = mat2ds(mat; ref=ref)
# ---------------------------------------------------------------------------------------------------
function mat2ds(mat::Array{T,N}, txt::Union{String,Vector{String}}=String[];
hdr::Union{String,VecOrMat{String}}=String[], geom=0, kwargs...)::GDtype where {T<:Real,N}
_mat2ds(mat, txt, isa(hdr, String) ? [hdr] : vec(hdr), Int(geom), KW(kwargs))
end
function _mat2ds(@nospecialize(mat::Array{<:Real}), txt::Union{String,Vector{String}}, hdr::Vector{String}, geom::Int, d::Dict)::GDtype
coln = hlp_desnany_vstr(d, [:colnames])
(!isempty(txt)) && return text_record(mat, txt, hdr)
if ((_text = find_in_dict(d, [:text :txt])[1]) !== nothing && !isempty(_text))
Dt = text_record(mat, _text, hdr); Dt.geom = geom;
!isempty(coln) && (Dt.colnames = coln)
return Dt
end
is3D = (is_in_dict(d, [:is3D]; del=true) === nothing) ? false : true # Should account for is3D == false?
isa(mat, Vector) && (mat = reshape(mat, length(mat), 1))
val = find_in_dict(d, [:multi :multicol])[1]
multi = (val === nothing) ? false : ((val) ? true : false) # Like this it will error if val is not Bool
segnan = (is_in_dict(d, [:segnan :nanseg]; del=true) !== nothing) ? true : false # A classic GMT multi-segment sep with NaNs
segnan && (multi = true)
if ((x = find_in_dict(d, [:x])[1]) !== nothing)
n_ds::Int = segnan ? 1 : ((multi) ? Int(size(mat, 2)) : 1)
xx::Vector{Float64} = (x == :ny || x == "ny") ? collect(1.0:size(mat, 1)) : vec(x)
(length(xx) != size(mat, 1)) && error("Number of X coordinates and MAT number of rows are not equal")
else
n_ds = (ndims(mat) == 3) ? size(mat,3) : ((multi) ? size(mat, 2) - segnan - (1+is3D) : 1)
xx = Vector{Float64}()
end
if (!isempty(hdr) && length(hdr) == 1) # Accept one only but expand to n_ds with the remaining as blanks
_hdr::Vector{String} = Base.fill("", n_ds); _hdr[1] = hdr[1]
elseif (!isempty(hdr) && length(hdr) != n_ds)
error("The header vector can only have length = 1 or same number of MAT Y columns")
else
_hdr = hdr
end
color_cycle = false
if ((color = find_in_dict(d, [:lc :linecolor :color])[1]) !== nothing && color != false)
_color::Vector{String} = (isa(color, VecOrMat{String}) && !isempty(color)) ? vec(string.(color)) : (!isa(color, Vector) && !isa(color, Bool) && color != :cycle) ? [string(color)] : matlab_cycle_colors
color_cycle = true
end
_fill::Vector{String} = helper_ds_fill(d)
# --- Here we deal with line colors and line thickness.
_lt = hlp_desnany_vfloat(d, [:lt, :linethick, :linethickness])
if (!isempty(_lt))
_lts::Vector{String} = Vector{String}(undef, n_ds)
n_thick::Integer = length(_lt)
for k = 1:n_ds
_lts[k] = " -W" * string(_lt[((k % n_thick) != 0) ? k % n_thick : n_thick])
end
else
theW = (color_cycle || get(d, :ls, nothing) !== nothing || get(d, :linestyle, nothing) !== nothing || get(d, :pen, nothing) !== nothing) ? " -W" : ""
_lts = fill(theW, n_ds) # If no pen setting no need to set -W
end
if (color_cycle)
n_colors::Int = length(_color)
if (isempty(_hdr))
_hdr = Vector{String}(undef, n_ds)
for k = 1:n_ds _hdr[k] = _lts[k] * string(",", _color[((k % n_colors) != 0) ? k % n_colors : n_colors]) end
else
for k = 1:n_ds _hdr[k] *= _lts[k] * string(",", _color[((k % n_colors) != 0) ? k % n_colors : n_colors]) end
end
else # Here we are overriding the GMT -W default that is too thin.
if (isempty(_hdr))
_hdr = Vector{String}(undef, n_ds)
for k = 1:n_ds _hdr[k] = _lts[k] end
else
for k = 1:n_ds _hdr[k] *= _lts[k] end
end
end
# ----------------------------------------
if ((ls = find_in_dict(d, [:ls :linestyle])[1]) !== nothing && ls != "")
(_hdr[1] == " -W") && (for k = 1:n_ds _hdr[k] *= "," end) # If here we have no color set must make it -W,,ls
if (isa(ls, AbstractString) || isa(ls, Symbol))
for k = 1:n_ds _hdr[k] = string(_hdr[k], ',', ls) end
else
for k = 1:n_ds _hdr[k] = string(_hdr[k], ',', ls[k]) end
end
elseif ((ls = find_in_dict(d, [:pen])[1]) !== nothing && ls != "")
if (isa(ls, AbstractString) || isa(ls, Symbol))
for k = 1:n_ds _hdr[k] = string(_hdr[k], ls) end
elseif (isa(ls, Tuple))
for k = 1:n_ds _hdr[k] = string(_hdr[k], parse_pen(ls)) end
else
for k = 1:n_ds _hdr[k] = string(_hdr[k], ls[k]) end
end
end
if (!isempty(_fill)) # Paint the polygons (in case of)
n_colors = length(_fill)
if (isempty(_hdr))
_hdr = Vector{String}(undef, n_ds)
for k = 1:n_ds _hdr[k] = " -G" * _fill[((k % n_colors) != 0) ? k % n_colors : n_colors] end
else
for k = 1:n_ds _hdr[k] *= " -G" * _fill[((k % n_colors) != 0) ? k % n_colors : n_colors] end
end
end
#if ((val = find_in_dict(d, [:front])[1]) !== nothing)
#_lf::Vector{String} = isa(val, Vector{String}) ? val : [string(val)] # Second case is free to error
_lf = hlp_desnany_vstr(d, [:front])
if (!isempty(_lf))
n_thick = length(_lf) # Save to reuse var since data type does not change
for k = 1:n_ds
_hdr[k] *= " -Sf" * _lf[((k % n_thick) != 0) ? k % n_thick : n_thick]
end
end
prj, wkt, epsg, ref_attrib, ref_coln = helper_set_crs(d)
is_geog::Bool = isgeog(prj)
function fill_colnames(coln::Vector{String}, nc::Int, is_geog::Bool) # Fill the column names vector
if isempty(coln)
(coln = (is_geog) ? ["Lon", "Lat"] : ["X", "Y"])
(nc == 1) ? append!(coln, ["Z"]) : append!(coln, ["Z$i" for i=1:nc])
end
return coln
end
att::DictSvS = ((v = find_in_dict(d, [:attrib])[1]) !== nothing && isa(v, Dict)) ? v : DictSvS()
!isempty(att) && !isa(att, Dict{String, Union{String, Vector{String}}}) && error("Attributs must be a Dict{String, Union{String, Vector{String}}}")
txtcol = hlp_desnany_vstr(d, [:txtcol, :textcol])
D = Vector{GMTdataset{isempty(xx) ? eltype(mat) : Float64, 2}}(undef, n_ds)
function segnan_mat(mat, coln, _hdr, is_geog, prj, _geom, xx=Float64[])
# Create a multi-segment where segments are separated by NaNs.
isempty(coln) && (coln = (is_geog) ? ["Lon", "Lat"] : ["X", "Y"])
off = isempty(xx) ? 1 : 0
n_rows, n_cols = size(mat)
segN = Matrix{Float64}(undef, n_rows * (n_cols-off) + (n_cols-off-1), 2)
_xx = isempty(xx) ? view(mat, :, 1) : xx
s = 1
for k = 1+off:n_cols
e = s + n_rows - 1
#segN[s:e, :] = [_xx mat[:,k]]
segN[s:e, :] = vcat(_xx, mat[:, k])
if (k < n_cols)
segN[e+1, :] = [NaN NaN]
s += n_rows+1
end
end
GMTdataset(segN, Float64[], Float64[], att, coln, String[], (isempty(_hdr) ? "" : _hdr[1]), String[], prj, wkt, epsg, _geom)
end
# By default convert to Doubles, except if instructed to NOT to do it.
#(find_in_dict(d, [:datatype])[1] === nothing) && (eltype(mat) != Float64) && (mat = Float64.(mat))
_geom::Int = Int((geom == 0 && (2 <= length(mat) <= 3)) ? wkbPoint : (geom == 0 ? wkbUnknown : geom)) # Guess geom
(multi && _geom == 0 && size(mat,1) == 1) && (_geom = Int(wkbPoint)) # One row with many columns and MULTI => Points
if (isempty(xx)) # No coordinates transmitted
if (ndims(mat) == 3)
coln = fill_colnames(coln, size(mat,2)-2, is_geog)
for k = 1:n_ds
D[k] = GMTdataset(mat[:,:,k], Float64[], Float64[], att, coln, txtcol, (isempty(_hdr) ? "" : _hdr[k]), String[], prj, wkt, epsg, _geom)
end
elseif (!multi)
if (size(mat,2) == 1 && length(coln) == 2 && !isempty(txtcol)) # Do nothing to 'coln'
else
coln = fill_colnames(coln, size(mat,2)-2, is_geog)
(size(mat,2) == 1) && (coln = coln[1:1]) # Because it defaulted to two.
end
D[1] = GMTdataset(mat, Float64[], Float64[], att, coln, txtcol, (isempty(_hdr) ? "" : _hdr[1]), String[], prj, wkt, epsg, _geom)
elseif (segnan)
D[1] = segnan_mat(mat, coln, _hdr, is_geog, prj, _geom)
else # 2D MULTICOL case(s)
isempty(coln) && (coln = (is_geog) ? ["Lon", "Lat"] : ["X", "Y"])
for k = 1:n_ds
# If colnames was transmitted try to assign the right names to each column
_coln = length(coln) > size(mat, 2) ? [coln[1], coln[k+1], coln[end]] : length(coln) == size(mat, 2) ? [coln[1], coln[k+1]] : coln
D[k] = GMTdataset(mat[:,[1,k+1]], Float64[], Float64[], att, _coln, txtcol, (isempty(_hdr) ? "" : _hdr[k]), String[], prj, wkt, epsg, _geom)
end
end
else # With xx coords transmitted.
if (!multi)
coln = fill_colnames(coln, size(mat,2)-1, is_geog)
D[1] = GMTdataset(hcat(xx,mat), Float64[], Float64[], att, coln, String[], (isempty(_hdr) ? "" : _hdr[1]), String[], prj, wkt, epsg, _geom)
elseif (segnan)
D[1] = segnan_mat(mat, coln, _hdr, is_geog, prj, _geom, xx)
else
isempty(coln) && (coln = (is_geog) ? ["Lon", "Lat"] : ["X", "Y"])
for k = 1:n_ds
# If colnames was transmitted try to assign the right names to each column
_coln = length(coln) > size(mat, 2) ? [coln[1], coln[k], coln[end]] : length(coln) == size(mat, 2) ? [coln[1], coln[k]] : coln
D[k] = GMTdataset(hcat(xx,mat[:,k]), Float64[], Float64[], att, _coln, String[], (isempty(_hdr) ? "" : _hdr[k]), String[], prj, wkt, epsg, _geom)
end
end
end
!isempty(ref_attrib) && (D[1].attrib = ref_attrib) # When a reference Ds was used
(length(ref_coln) >= size(D[1].data,2)) && (D[1].colnames = ref_coln[1:size(D[1].data,2)]) # This still loses Text colname
CTRL.pocket_d[1] = d # Store d that may be not empty with members to use in other functions
set_dsBB!(D) # Compute and set the global BoundingBox for this dataset
#return (find_in_kwargs(kwargs, [:letsingleton])[1] !== nothing) ? D : (length(D) == 1 && !multi) ? D[1] : D
return (is_in_dict(d, [:letsingleton]; del=true) !== nothing) ? D : (length(D) == 1 && !multi) ? D[1] : D
end
# ---------------------------------------------------------------------------------------------------
"""
D = mat2ds(D::GMTdataset, inds::Tuple) -> GMTdataset
Cut a GMTdataset D with the indices in INDS but updating the colnames and the Timecol info.
INDS is a Tuple of 2 with ranges in rows and columns. Ex: (:, 1:3) or (:, [1,4,7]), etc...
Attention, if original had attributes other than 'Timeinfo' there is no guarentie that they remain correct.
"""
function mat2ds(@nospecialize(D::GMTdataset), @nospecialize(inds))::GMTdataset
(length(inds) != ndims(D)) && error("\tNumber of GMTdataset dimensions and indices components must be the same.\n")
_coln = isempty(D.colnames) ? String[] : (inds[2] === Colon() || last(inds[2]) <= length(D.colnames) ? D.colnames[inds[2]] : String[])
(!isempty(_coln) && (typeof(inds[1]) == Colon) && length(D.colnames) > size(D,2)) && append!(_coln, [D.colnames[end]]) # Append text colname if exists
_D = mat2ds(D.data[inds...], proj4=D.proj4, wkt=D.wkt, epsg=D.epsg, geom=D.geom, colnames=_coln, attrib=D.attrib, hdr=D.header)
(!isempty(D.text)) && (_D.text = D.text[inds[1]])
(typeof(inds[2]) == Colon) && return _D # We are done here
if (size(_D,2) < 2 || inds[2][1] != 1 || inds[2][2] != 2) # If any of the first or second columns has gone we know no more about CRS
_D.proj4 = ""; _D.wkt = ""; _D.epsg = 0
end
i = findall(startswith.(_D.colnames, "Time"))
isempty(i) && return _D # No TIME columns. We are done
(length(i) == 1) ? (Tc::String = "$(i[1])") : _i = i[2:end]
#_D.attrib["Timecol"] = (length(i) == 1) ? Tc : [Tc *= ",$k" for k in _i]
(length(i) == 1) && (_D.attrib["Timeinfo"] = Tc)
if (length(i) > 1)
for k in _i Tc *= ",$k" end
end
(length(i) >= 1) && (_D.attrib["Timeinfo"] = Tc)
(get(D.attrib, "linearfit", "") != "") && ( # A linefit, keep the attribs.
_D.attrib["Goodness_of_fit"] = D.attrib["Goodness_of_fit"];
_D.attrib["sigma95_b"] = D.attrib["sigma95_b"];
_D.attrib["ci"] = D.attrib["ci"];
_D.attrib["b"] = D.attrib["b"];
_D.attrib["linearfit"] = D.attrib["linearfit"];
_D.attrib["sigma_b"] = D.attrib["sigma_b"];
_D.attrib["sigma95_a"] = D.attrib["sigma95_a"];
_D.attrib["Pearson"] = D.attrib["Pearson"];
_D.attrib["a"] = D.attrib["a"];
)
return _D
end
# ---------------------------------------------------------------------------------------------------
"""
mat2dsnan(mat::Matrix{<:Real}; is3D=false, kw...)
Break the matrix `mat` in a series of GMTdatasets using NaN as the breaking flag. By default it only
checks for NaNs in the first two columns. Use `is3D=true` to also check the third column. The `kw`
argument is the same as used in `mat2ds()`.
### Example, create a vector of 2 GMTdatasets:
mat2dsnan([0 1; 1 1; NaN 0; 2 2 3 3])
"""
function mat2dsnan(mat::Matrix{T}; is3D=false, kw...)::Vector{GMTdataset{T,2}} where {T<:Real}
ind = isnan.(view(mat, :, 1)) .| isnan.(view(mat, :, 2))
is3D && (ind = ind .| isnan.(view(mat, :, 3)))
ind2 = [1, findall(diff(ind) .!= 0) .+ 1 ..., size(mat,1)+1] # Indices of boundaries between NaNs
n_ds = length(ind2) - 1
Dm = Vector{GMTdataset{eltype(mat),2}}(undef, n_ds)
for k = 1:n_ds
Dm[k] = mat2ds(mat[ind2[k]:ind2[k+1]-1, :], kw...)
end
return Dm
end
# ---------------------------------------------------------------------------------------------------
"""
add2ds!(D::GMTdataset, mat, ind::Int=0; name::AbstractString="", names::Vector{<:AbstractString}=AbstractString[])
Add the Vector or Matrix 'mat' to columns of D where 'ind' is the column index of the insertion point.
Takes care also of updating the column names.
If 'ind=0' append 'mat' at the end of 'D'
If 'mat' is a vector optionally use the 'name' for the new inserted column
If 'mat' is a matrix optionally use a 'names' vector (must have size(mat,2) elements) of new column names.
"""
function add2ds!(D::GMTdataset, mat, ind::Int=0; name::AbstractString="", names::Vector{<:AbstractString}=AbstractString[])
_add2ds_1(D, mat, ind, name, names)
end
function _add2ds_1(@nospecialize(D), @nospecialize(mat), ind::Int, name::AbstractString, names::Vector{<:AbstractString})
(isvector(mat) && size(D,1) != length(mat)) && error("Number of rows in GMTdataset and adding vector elements do not match.")
(isa(mat, Matrix) && size(mat,1) > 1 && size(D,1) != size(mat,1)) && error("Number of rows in GMTdataset and adding matrix do not match.")
n_newCols = isvector(mat) ? 1 : size(mat,2)
_names = (n_newCols == 1 && name == "") ? ["Zadd"] :
(n_newCols == 1 ? [name] : !isempty(names) ? names : [string("Zadd_",k) for k=1:n_newCols])
if (!isempty(D.colnames))
t_col = (!isempty(D.text) && length(D.colnames) > size(D,2)) ? D.colnames[end] : ""
end
if (ind == 0)
if (!isempty(D.colnames))
(size(D,2) > length(D.colnames)) && (append!(D.colnames, ["Bug"])) # I fck cant get rid of this
D.colnames = !isempty(t_col) ? [D.colnames[1:size(D,2)]..., _names..., t_col] : [D.colnames[1:size(D,2)]..., _names...]
end
D.data = hcat(D.data, isvector(mat) ? mat[:] : mat)
elseif (ind == 1)
D.data = hcat(isvector(mat) ? mat[:] : mat, D.data)
!isempty(D.colnames) && (D.colnames = [_names..., D.colnames...])
else
D.data = isvector(mat) ? hcat(D.data[:,1:ind-1], mat[:], D.data[:,ind:end]) : hcat(D.data[:,1:ind-1], mat, D.data[:,ind:end])
!isempty(D.colnames) && (D.colnames = [D.colnames[1:ind-1]..., _names..., D.colnames[ind:end]...])
end
set_dsBB!(D)
return nothing
end
# ---------------------------------------------------------------------------------------------------
function add2ds!(D::Vector{<:GMTdataset}, mat, ind::Int=0; name::AbstractString="", names::Vector{<:AbstractString}=AbstractString[])
for k = 1:numel(D) add2ds!(D[k], mat, ind; name=name, names=names) end
return nothing
end
# ---------------------------------------------------------------------------------------------------
function add2ds!(@nospecialize(D::GMTdataset); name::AbstractString="", names::Vector{<:AbstractString}=AbstractString[])
# Method for fixing the colnames and/or the bbox in DS that had their matrix extended.
# 'name' and 'names' are only usable if 'D' already has 'colnames'
isempty(D.colnames) && (D.colnames = [string("Col.",k) for k=1:size(D,2)])
if ((n_newCols = size(D,2) - length(D.colnames)) > 0)
_names = (n_newCols == 1 && name == "") ? ["Zadd"] :
(n_newCols == 1 ? [name] : !isempty(names) ? names : [string("Zadd_",k) for k=1:n_newCols])
D.colnames = [D.colnames..., _names...]
end
(length(D.bbox) != 2 * size(D,2)) && set_dsBB!(D)
end
# ---------------------------------------------------------------------------------------------------
function set_dsBB(D, all_bbs::Bool=true)
# This method returns the modified 'D'
set_dsBB!(D, all_bbs)
return D
end
function set_dsBB!(D, all_bbs::Bool=true)
_set_dsBB!(wrapDatasets("", D), all_bbs)
end
# ---------------------------------------------------------------------------------------------------
function _set_dsBB!(w::wrapDatasets, all_bbs::Bool)
D = unwrapDatasets(w::wrapDatasets)[2]
# Compute and set the global and individual BoundingBox for a Vector{GMTdataset} + the trivial cases.
# If ALL_BBS is false then assume individual BBs are already knwon.
((D === nothing) || isempty(D)) && return nothing
if (all_bbs) # Compute all BBs
if isa(D, GMTdataset)
isempty(D.data) && return nothing # Likely a Text only DS
D.ds_bbox = D.bbox = collect(Float64, Iterators.flatten(extrema(D.data, dims=1)))
ind = findall(.!isfinite.(D.bbox)) # If we have some columns with NaNs or Infs
if (!isempty(ind))
for k = 1:2:length(ind)
D.ds_bbox[ind[k]], D.ds_bbox[ind[k+1]] = extrema_cols_nan(D.data, col=div(ind[k+1],2))
end
D.bbox = D.ds_bbox
end
return nothing
else
for k = 1:lastindex(D)
isempty(D[k].data) && continue # Likely a Text only DS
bb = Base.invokelatest(extrema, D[k].data, dims=1) # A N Tuple.
_bb = collect(Float64, Iterators.flatten(bb))
if (any(isnan.(_bb))) # Shit, we don't have a minimum_nan(A, dims)
n = 1
for kk = 1:size(D[k].data, 2)
isnan(_bb[n]) && (_bb[n:n+1] .= extrema_cols(D[k].data, col=kk))
n += 2
end
all(isnan.(_bb)) && continue # Shit, they are all still NaNs
end
D[k].bbox = _bb
end
end
end
(isa(D, GMTdataset)) && (D.ds_bbox = D.bbox; return nothing)
(length(D) == 1) && (D[1].ds_bbox = D[1].bbox; return nothing)
kk = 0
while (isempty(D[kk+=1].bbox) && kk < length(D)) continue end
bb = copy(D[kk].bbox)
for k = kk+1:lastindex(D)
for n = 1:2:length(bb)
isempty(D[k].bbox) && continue
bb[n] = min(D[k].bbox[n], bb[n])
bb[n+1] = max(D[k].bbox[n+1], bb[n+1])
end
end
D[1].ds_bbox = bb
return nothing
end
# ---------------------------------------------------------------------------------------------------
function ds2ds(D::Vector{<:GMTdataset{T,2}})::GMTdataset{T,2} where {T<:Real}
# Take a vector of DS and collapse it into a single GMTdataset DS. Some metadata, proj, colnames
# and attributes are copied from first segment. Colors in header and text are lost.
length(D) == 1 && return D[1] # Nothing to do. Happens when D is computed programmatically
tot_rows = sum(size.(D,1))
data = zeros(eltype(D[1]), tot_rows, size(D[1],2))
s, e = 1, size(D[1],1)
data[s:e, :] = D[1].data
for k = 2:numel(D)
s = e + 1
e += size(D[k],1)
data[s:e, :] = D[k].data
end
mat2ds(data, proj=D[1].proj4, wkt=D[1].wkt, epsg=D[1].epsg, geom=D[1].geom, colnames=D[1].colnames, attrib=D[1].attrib)
end
Base.:stack(D::Vector{<:GMTdataset}) = ds2ds(D)
# ---------------------------------------------------------------------------------------------------
function ds2ds(D::GMTdataset{T,2}; is3D::Bool=false, kwargs...)::Vector{<:GMTdataset{T,2}} where {T<:Real}
d = KW(kwargs)
ds2ds(D, is3D, d)
end
function ds2ds(D::GMTdataset{T,2}, is3D::Bool, d::Dict)::Vector{<:GMTdataset{T,2}} where {T<:Real}
# Take one DS and split it into an array of DS's, one for each row and optionally add -G<fill>
# Alternativelly, if [:multi :multicol] options lieve in 'd', split 'D' by columns: [1,2], [1,3], [1,4], ...
# So far only for internal use but may grow in function of needs
#multi = 'r' # Default split by rows
#if ((val = find_in_dict(d, [:multi :multicol], false)[1]) !== nothing) multi = 'c' end # Then by columns
# Split by rows or columns
multi = ((is_in_dict(d, [:multi :multicol]; del=false)) !== nothing) ? 'c' : 'r'
_fill = (multi == 'r') ? helper_ds_fill(d) : String[] # In the columns case all is dealt in mat2ds.
n_colors = length(_fill)
if ((val = hlp_desnany_int(d, [:color_wrap])) !== -999) # color_wrap is a kind of private option for bar-stack
n_colors::Int = Int(val)
end
n_ds = size(D.data, multi == 'r' ? 1 : 2)
(multi == 'c') && (n_ds -= 1+is3D)
if (!isempty(_fill)) # Paint the polygons (in case of)
_hdr::Vector{String} = Vector{String}(undef, n_ds)
for k = 1:n_ds
_hdr[k] = " -G" * _fill[((k % n_colors) != 0) ? k % n_colors : n_colors]
end
(D.header != _hdr[1]) && (_hdr[1] = D.header * _hdr[1]) # Copy eventual contents of first header
end
Dm = Vector{GMTdataset{eltype(D.data),2}}(undef, n_ds)
if (multi == 'r')
for k = 1:n_ds
Dm[k] = GMTdataset(D.data[k:k, :], Float64[], Float64[], DictSvS(), String[], String[], (isempty(_fill) ? "" : _hdr[k]), String[], "", "", 0, wkbPoint)
end
Dm[1].colnames = D.colnames
(size(D.text) == n_ds) && (for k = 1:n_ds Dm[k].text = D.text[k] end)
else
Dm = mat2ds(D.data; colnames=D.colnames, d...)
end
Dm[1].comment = D.comment; Dm[1].proj4 = D.proj4; Dm[1].wkt = D.wkt; Dm[1].epsg = D.epsg;
Dm
end
# ----------------------------------------------
function helper_ds_fill(d::Dict; del::Bool=true, symbs=[:fill :fillcolor], nc=0)::Vector{String}
# Shared by ds2ds & mat2ds & statplots
# The NC parameter is used to select the color schema: <= 8 ==> 'matlab_cycle_colors'; otherwise 'simple_distinct'
# By using a non-default SYMBS we can use this function for other than selecting fill colors.
if ((fill_val = find_in_dict(d, symbs, del)[1]) !== nothing)
if (isa(fill_val, StrSymb))
fill_val_s = string(fill_val)::String
if contains(fill_val_s, ",") _fill::Vector{String} = collect(split(fill_val_s, ","))
elseif (fill_val_s == "yes" || fill_val_s == "cycle")
_fill = (nc <= 8) ? copy(matlab_cycle_colors) : copy(simple_distinct)
elseif (fill_val_s == "none") _fill = [" "]
else _fill = [fill_val_s]
end
elseif (isa(fill_val, Tuple) && eltype(fill_val) == Symbol)
_fill = [string.(fill_val)...]
elseif (isa(fill_val, VecOrMat{String}) && !isempty(fill_val))
_fill = vec(fill_val)
elseif (isa(fill_val, VecOrMat{Symbol}))
_fill = vec(string.(fill_val))
else
_fill = (nc <= 8) ? copy(matlab_cycle_colors) : copy(simple_distinct)
end
n_colors::Int = length(_fill)
#if ((alpha_val = find_in_dict(d, [:fillalpha])[1]) !== nothing)
#(eltype(alpha_val) <: AbstractFloat && maximum(alpha_val) <= 1) && (alpha_val = collect(alpha_val) .* 100)
alpha_val = hlp_desnany_vstr_2(d, [:fillalpha])
if (!isempty(alpha_val))
_alpha::Vector{String} = Vector{String}(undef, n_colors)
na::Int = min(length(alpha_val), n_colors)
for k = 1:na _alpha[k] = join(string('@',alpha_val[k])) end
if (na < n_colors)
for k = na+1:n_colors _alpha[k] = "" end
end
for k = 1:n_colors _fill[k] *= _alpha[k] end # And finaly apply the transparency
end
(_fill[1] == " ") && (_fill = Vector{String}()) # Passing a fill=[" "] is programatically handy to say no fill
else
_fill = Vector{String}()
end
return _fill
end
const matlab_cycle_colors = ["#0072BD", "#D95319", "#EDB120", "#7E2F8E", "#77AC30", "#4DBEEE", "#A2142F", "0/255/0"]
# https://en.wikipedia.org/wiki/Help:Distinguishable_colors
const alphabet_colors = ["#2BCE48", "#4C005C", "#005C31", "#5EF1F2", "#8F7C00", "#9DCC00", "#0075DC", "#94FFB5", "#740AFF", "#993F00", "#00998F", "#003380", "#191919", "#426600", "#808080", "#990000", "#C20088", "#E0FF66", "#F0A3FF", "#FF0010", "#FF5005", "#FFA8BB", "#FFA405", "#FFCC99", "#FFE100", "#FFFF80"]
# https://sashamaps.net/docs/resources/20-colors/
const simple_distinct = ["#e6194b", "#3cb44b", "#ffe119", "#4363d8", "#f58231", "#911eb4", "#46f0f0", "#f032e6", "#bcf60c", "#fabebe", "#008080", "#e6beff", "#9a6324", "#fffac8", "#800000", "#aaffc3", "#808000", "#ffd8b1", "#000075", "#808080"]
# ---------------------------------------------------------------------------------------------------
"""
setcolors!(D::Vector{<:GMTdataset}; colorset=:auto, fill=false) -> D
Assign cycling line colors (`-W`) and optionally fill colors (`-G`) to a vector of datasets.
### Args
- `D`: Vector of GMTdataset to modify in-place.
### Kwargs
- `colorset`: Color palette to use. One of `:auto` (default: `:matlab` for ≤7 curves, `:distinct` otherwise),
`:matlab`, `:distinct`, or `:alphabet`. Can also be a `Vector{String}` of custom colors.
- `fill`: If `true`, also add `-G<color>` fill to each header.
If a `-W` option already exists in the header, the color is inserted or replaced while preserving
pen width and style. If no `-W` exists, one is added with the color only.
"""
function setcolors!(D::Vector{<:GMTdataset}; colorset::Union{Symbol,Vector{String}}=:auto, fill::Bool=false)
nc = length(D)
if isa(colorset, Vector{String})
colors = colorset
else
colors = (colorset == :matlab) ? matlab_cycle_colors :
(colorset == :distinct) ? simple_distinct :
(colorset == :alphabet) ? alphabet_colors :
(nc <= 7) ? matlab_cycle_colors : simple_distinct # :auto
end
n_colors = length(colors)
for k in 1:nc
c = colors[mod1(k, n_colors)]
hdr = D[k].header::String
m = match(r"-W([^ ]*)", hdr)
if (m !== nothing) # Parse existing -W: could be "-W1.5" or "-W1.5,red" or "-W1.5,red,dash" or "-W,blue"
parts = split(m.captures[1], ',')
if (length(parts) == 1) # No color yet, e.g. "-W1.5" → "-W1.5,<color>"
new_W = "-W" * parts[1] * "," * c
elseif (length(parts) == 2) # Has color, e.g. "-W1.5,red" → "-W1.5,<color>"
new_W = "-W" * parts[1] * "," * c
else # Has color+style, e.g. "-W1.5,red,dash" → "-W1.5,<color>,dash"
new_W = "-W" * parts[1] * "," * c * "," * join(parts[3:end], ",")
end
hdr = replace(hdr, m.match => new_W)
else
hdr = hdr * " -W," * c
end
fill && (hdr = strip(replace(hdr, r"\s?-G[^ ]+" => "")) * " -G" * c)
D[k].header = hdr
end
return D
end
# ---------------------------------------------------------------------------------------------------
"""
FV = fv2fv(F, V; proj="", proj4="", wkt="", epsg=0) -> GMTfv
Create a FacesVertices object from a matrix of faces indices and another matrix of vertices (a Mx3 matrix).
### Args
- `F`: A matrix of faces indices or a vector of matrices when defining bodies made of multiple
surfaces (cylinders for example).
- `V`: A Mx3 matrix of vertices.
### Kargs
- `proj` or `proj4`: A proj4 string for setting the Coordinate Referencing System
- `wkt`: A WKT SRS.
- `epsg`: Same as `proj` but using an EPSG code
"""
function fv2fv(F::Vector{<:AbstractMatrix{<:Integer}}, V; color_vwall::String="", zscale=1.0, bfculling=true, proj="", proj4="", wkt="", epsg=0)::GMTfv
(isempty(proj4) && !isempty(proj)) && (proj4 = proj) # Allow both proj4 or proj keywords
bbox = extrema(V, dims=1)
_bbox::Vector{Float64} = [bbox[1][1], bbox[1][2], bbox[2][1], bbox[2][2], bbox[3][1], bbox[3][2]]
isflat = zeros(Bool, length(F)) # Needs thinking
GMTfv(verts=collect(V), faces=collect.(F), bbox=_bbox, color_vwall=color_vwall, zscale=zscale, bfculling=bfculling,
isflat=isflat, proj4=proj4, wkt=wkt, epsg=epsg)
end
fv2fv(F::Matrix{<:Integer}, V; color_vwall::String="", zscale=1.0, bfculling=true, proj="", proj4="", wkt="", epsg=0) =
fv2fv([F], V; color_vwall=color_vwall, zscale=zscale, bfculling=bfculling, proj=proj, proj4=proj4, wkt=wkt, epsg=epsg)
"""
When using Meshing.jl we can use the output of the ``isosurface`` function, "verts, faces" as input to this function.
- `F`: A vector of Tuple{Int, Int, Int} with the body faces indices
- `V`: A vector of Tuple{Float64, Float64, Float64} with the body vertices
### Example
```julia
gyroid(v) = cos(v[1])*sin(v[2])+cos(v[2])*sin(v[3])+cos(v[3])*sin(v[1]);
gyroid_shell(v) = max(gyroid(v)-0.4,-gyroid(v)-0.4);
xr,yr,zr = ntuple(_ -> LinRange(0,pi*4,50), 3);
A = [gyroid_shell((x,y,z)) for x in xr, y in yr, z in zr];
A[1,:,:] .= 1e10; A[:,1,:] .= 1e10; A[:,:,1] .= 1e10; A[end,:,:] .= 1e10; A[:,end,:] .= 1e10; A[:,:,end] .= 1e10;
vts, fcs = isosurface(A, MarchingCubes());
FV = fv2fv(fcs, vts)
viz(FV, cmap=makecpt(T="0/1", cmap="darkgreen,lightgreen"))
```
"""
function fv2fv(F::Vector{Tuple{Int, Int, Int}}, V::Vector{Tuple{Float64, Float64, Float64}};
zscale=1.0, bfculling=true, proj="", proj4="", wkt="", epsg=0)::GMTfv
verts = reshape(reinterpret(Float64, V), (3,:))'
faces = [reshape(reinterpret(Int, F), (3,:))']
fv2fv(faces, verts; zscale=zscale, bfculling=bfculling, proj=proj, proj4=proj4, wkt=wkt, epsg=epsg)
end
# ---------------------------------------------------------------------------------------------------
"""
FV = surf2fv(X::Matrix{T}, Y::Matrix{T}, Z::Matrix{T}; type=:tri, bfculling=true,
proj="", proj4="", wkt="", epsg=0, top=nothing, bottom=nothing) -> GMTfv
Create a three-dimensional FacesVertices object.
This function is suitable for 3D plotting either of closed bodies or 3D surfaces.
The values in matrix Z represent the heights above a grid in the x-y plane defined by X and Y
### Args
- `X,Y,Z`: Three matrices of the same size and type float.
### Kwargs
- `type`: The face type. Either ``:tri`` (the default) or ``:quad`` for triangular or quadrangular faces.
- `bfculling`: Boolean that specifies if culling of invisible faces is wished (default is ``true``)
- `proj` or `proj4`: A proj4 string for setting the Coordinate Referencing System (optional).
- `wkt`: A WKT SRS (optional).
- `epsg`: Same as `proj` but using an EPSG code (optional).
- `top`: A Faces 1 row matrix with the top of the body (optional). Note that we have to impose that this
is an already created faces matrix because inside this function we no longer know what the order of
the ``X`` and ``Y`` matrices represent.
- `bottom`: A Faces 1 row matrix with the bottom of the body (optional).
### Example
```julia
X,Y = meshgrid(1:0.5:10,1.:20);
Z = sin.(X) .+ cos.(Y);
FV = surf2fv(X, Y, Z);
viz(FV)
```
"""
function surf2fv(X::Matrix{T}, Y::Matrix{T}, Z::Matrix{T}; type=:tri, bfculling=true, mask=BitArray(undef,0,0),
proj="", proj4="", wkt="", epsg=0, top=nothing, bottom=nothing)::GMTfv where {T <: AbstractFloat}
@assert length(X) == length(Y) == length(Z)
(type != :tri && type != :quad) && error("type must be :tri or :quad")
have_mask = !isempty(mask)
n_rows, n_cols = size(X)
n_faces = (have_mask) ? sum(mask) : (n_rows - 1) * (n_cols - 1)
(have_mask && n_faces == 0) && error("Something is wrong. The 'mask' matrix is filled with 'false' only.")
c1, c2 = (type == :tri) ? (2, 3) : (1, 4)
if (bottom === nothing && top === nothing)
F = [fill(0, c1 * n_faces, c2)]
indS = 1
elseif (bottom === nothing && top !== nothing)
F = [fill(0, c1 * n_faces, c2), top]
indS = 1
elseif (bottom !== nothing && top !== nothing)
F = [bottom, fill(0, c1 * n_faces, c2), top]
indS = 2
elseif (bottom !== nothing && top === nothing)
F = [bottom, fill(0, c1 * n_faces, c2)]
indS = 2
end
n = 0
if (type == :tri)
for col = 1:n_cols - 1
for row = 1:n_rows - 1
r = row + (col - 1) * n_rows
c = r + n_rows
n += 1
F[indS][n,1], F[indS][n,2], F[indS][n,3] = r, r+1, c
n += 1
F[indS][n,1], F[indS][n,2], F[indS][n,3] = r+1, r+1+n_rows, c
end
end
else
for col = 1:n_cols - 1
for row = 1:n_rows - 1
have_mask && !mask[row,col] && continue
r = row + (col - 1) * n_rows
c = r + n_rows
n += 1
F[indS][n,1], F[indS][n,2], F[indS][n,3], F[indS][n,4] = r, r+1, c+1, c
end
end
end
fv2fv(F, [X[:] Y[:] Z[:]]; bfculling=bfculling, proj=proj, proj4=proj4, wkt=wkt, epsg=epsg)
end
# ---------------------------------------------------------------------------------------------------
"""
v, names = splitds(D::Vector{<:GMTdataset}; groupby::String="") --> Tuple{Vector{Vector{Int}}, Vector{String}}
Compute the indices that split a vector of datasets into groups. The grouping is done either by a provided
attribute name (`groupby`) or by the Feature_ID attribute. This function is mostly used internally by `zonal_statistics`
### Args
- `D`: A vector of GMTdataset
### Kwargs
- `groupby`: If provided, it must be an attribute name, for example, `groupby="NAME"`. If not provided, we use
the `Feature_ID` attribute that is a unique identifier assigned during an OGR file reading (by the GMT6.5 C lib).
If the `Feature_ID` attribute does not exist, you must use a valid attribute name passed in `groupby`.
If neither of those exists, an error is thrown.
### Returns
- `v`: A Vector{Vector{Int}} with the indices that split the datasets into groups. The length of `v` is the
number of groups found and each element of `v` is a vector of indices that belong to that group.
- `names`: A Vector{String} with the names of the groups. These names are fetched from the attributes.
It will be the values of the attribute name provided by `groupby` or those of the first attribute value
if that option is not used.
"""
function splitds(D::Vector{<:GMTdataset{T,N}}; groupby::String="") where {T<:Real, N}
# Split a vector of datasets into groups by the Feature_ID attribute.
if (groupby != "") # Use the attribute selected by the user
att_names = vec(string.(keys(D[1].attrib)))
ind = findfirst(groupby .== att_names)
(ind === nothing) && error("Attribute '$groupby' not found in dataset!")
names = Vector{String}(undef, length(D))
for k = 1:length(D) names[k] = D[k].attrib[att_names[ind]] end
feature_names = unique(names)
nf = length(feature_names)
vv = Vector{Vector{Int}}(undef, nf)
for k = 1:nf vv[k] = findall(names .== feature_names[k]) end
else # Use the 'Feature_ID' attribute
get(D[1].attrib, "Feature_ID", "") == "" && error("Attribute 'Feature_ID' not found in dataset!")
nf = parse(Int, D[end].attrib["Feature_ID"])
vv = Vector{Vector{Int}}(undef, nf)
for k = 1:nf vv[k] = filter(D, indices=true, Feature_ID = "$k") end
att_ref = (get(D[1].attrib, "NAME", "") == "") ? "NAME" : collect(keys(D[1].attrib))[1]
feature_names = Vector{String}(undef, nf)
for k = 1:nf feature_names[k] = D[vv[k][1]].attrib[att_ref] end
end
return vv, feature_names
end
# ---------------------------------------------------------------------------------------------------
"""
Dv = groupby(D::GMTdataset, col)::Vector{GMTdataset}
Split a GMTdataset by the unique values of the column selected by `col`.
`col` can be a column name, either as a String or a Symbol, or a column number. In any case, it must point
to a column with integers (normaly a flint (Floating Point Integer)), or a string column. _i.e.,_ the last
column in a GMTdataset.
"""
function groupby(D::GMTdataset{T,2}, cols::Union{String,Symbol,Int})::Vector{GMTdataset{T,2}} where {T<:Real}
n_cols = size(D.data, 2)
colnames = !isempty(D.colnames) ? D.colnames : ["col.$i" for i=1:n_cols]
!isempty(D.text) && length(colnames) == n_cols && push!(colnames, "Text") # 'Text' is the text column generic name
colname::String = isa(cols, Real) ? colnames[cols] : (isa(cols, Symbol) ? string(cols) : cols)
((cn = findfirst(colname .== colnames)) === nothing) && error("Column '$colname' not found in dataset!")
if (cn > n_cols) # It must be the text column
feature_names = unique(D.text)
nf = length(feature_names)
vv = Vector{Vector{Int}}(undef, nf)
for k = 1:nf vv[k] = findall(D.text .== feature_names[k]) end
else
c = D.data[min(50, size(D.data, 1)), cn] # look at the first 50 elements of the picked column
!all(round.(c) .== c) && error("The selected column is not an integer (flint, in fact) column!")
ids = unique(view(D.data, :, cn))
vv = Vector{Vector{Int}}(undef, length(ids))
for k = 1:numel(ids) vv[k] = findall(view(D.data, :, cn) .== ids[k]) end
end
Dv = Vector{GMTdataset{eltype(D.data),2}}(undef, numel(vv))
for k = 1:numel(vv) # Loop over groups
Dv[k] = mat2ds(D, (vv[k], :))
end
return Dv
end
# ---------------------------------------------------------------------------------------------------
"""
D = stats(D::GMTdataset, cols=0) -> GMTdataset
Return descriptive statistics for a dataset `GMTdataset` where each row represents the statistics for each column.
If `cols` is a column name, either as a String or a Symbol, or a column number, only the statistics
for that column are returned.
"""
function stats(D::GMTdataset{T,2}, cols::Union{String,Symbol,Int}=0)::GMTdataset{Float64,2} where {T<:Real}
if (cols == 0)
nc = size(D.data, 2)
q25 = Vector{Float64}(undef, nc); q50 = similar(q25); q75 = similar(q25); m = similar(q25); s = similar(q25)
mi, ma = D.bbox[1:2:end], D.bbox[2:2:end]
for k = 1:nc
q25[k] = quantile(view(D,:,k), 0.25)
q50[k] = quantile(view(D,:,k), 0.50)
q75[k] = quantile(view(D,:,k), 0.75)