/
utils.jl
1790 lines (1420 loc) · 71.6 KB
/
utils.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
# few utils that are useful
export meshgrid, cross_section, cross_section_volume, cross_section_surface, cross_section_points, extract_subvolume, subtract_horizontalmean
export parse_columns_CSV, votemap, countmap
export interpolate_datafields_2D, interpolate_datafields, interpolate_topography_plane
export rotate_translate_scale
export lithostatic_pressure!
export flatten_cross_section
export addfield, removefield
export inpoly, inpoly_fast, inpolygon!
using NearestNeighbors
"""
meshgrid(vx,vy,vz)
Computes an (x,y,z)-grid from the vectors (vx,vy,vz).
For more information, see the MATLAB documentation.
"""
function meshgrid(vx::AbstractVector{T}, vy::AbstractVector{T},
vz::AbstractVector{T}) where {T}
m, n, o = length(vy), length(vx), length(vz)
vx = reshape(vx, 1, n, 1)
vy = reshape(vy, m, 1, 1)
vz = reshape(vz, 1, 1, o)
om = ones(Int, m)
on = ones(Int, n)
oo = ones(Int, o)
(vx[om, :, oo], vy[:, on, oo], vz[om, on, :])
end
"""
V = addfield(V::AbstractGeneralGrid,field_name::String,data::Any)
Add Fields Data to GeoData or CartData
"""
function addfield(V::AbstractGeneralGrid,field_name::String,data::Any)
fields_new = V.fields; new_field = NamedTuple{(Symbol(field_name),)}((data,));
fields_new = merge(fields_new, new_field); # replace the field in fields_new
if isa(V,GeoData)
V = GeoData(V.lon.val,V.lat.val,V.depth.val,fields_new)
elseif isa(V,CartData)
V = CartData(V.x.val,V.y.val,V.z.val,fields_new)
else
error("addfield is only implemented for GeoData and CartData structures")
end
return V
end
"""
V = addfield(V::CartData,new_fields::NamedTuple)
Add `new_fields` fields to a `CartData` dataset
"""
addfield(V::CartData,new_fields::NamedTuple) = CartData(V.x.val, V.y.val, V.z.val, merge(V.fields, new_fields))
"""
V = addfield(V::GeoData,new_fields::NamedTuple)
Add `new_fields` fields to a `GeoData` dataset
"""
addfield(V::GeoData,new_fields::NamedTuple) = GeoData(V.lon.val, V.lat.val, V.depth.val, merge(V.fields, new_fields))
"""
V = addfield(V::Q1Data,new_fields::NamedTuple; cellfield=false)
Add `new_fields` fields to a `Q1Data` dataset; set `cellfield` to `true` if the field is a cell field; otherwise it is a vertex field
"""
function addfield(V::Q1Data,new_fields::NamedTuple; cellfield=false)
if cellfield
return Q1Data(V.x.val, V.y.val, V.z.val, V.fields, merge(V.cellfields, new_fields))
else
return Q1Data(V.x.val, V.y.val, V.z.val, merge(V.fields, new_fields), V.cellfields)
end
end
"""
V = addfield(V::FEData,new_fields::NamedTuple; cellfield=false)
Add `new_fields` fields to a `FEData` dataset; set `cellfield` to `true` if the field is a cell field; otherwise it is a vertex field
"""
function addfield(V::FEData,new_fields::NamedTuple; cellfield=false)
if cellfield
return FEData(V.vertices, V.connectivity, V.fields, merge(V.cellfields, new_fields))
else
return FEData(V.vertices, V.connectivity, merge(V.fields, new_fields), V.cellfields)
end
end
# this function is taken from @JeffreySarnoff
function dropnames(namedtuple::NamedTuple, names::Tuple{Vararg{Symbol}})
keepnames = Base.diff_names(Base._nt_names(namedtuple), names)
return NamedTuple{keepnames}(namedtuple)
end
"""
V = removefield(V::AbstractGeneralGrid,field_name::String)
Removes the field with name `field_name` from the GeoData or CartData dataset
"""
function removefield(V::AbstractGeneralGrid,field_name::String)
fields_new = V.fields;
fields_new = dropnames(fields_new, (Symbol(field_name),))
if isa(V,GeoData)
V = GeoData(V.lon.val,V.lat.val,V.depth.val,fields_new)
elseif isa(V,CartData)
V = CartData(V.x.val,V.y.val,V.z.val,fields_new)
else
error("removefield is only implemented for GeoData and CartData structures")
end
return V
end
"""
cross_section_volume(Volume::AbstractGeneralGrid; dims=(100,100), Interpolate=false, Depth_level=nothing; Lat_level=nothing; Lon_level=nothing; Start=nothing, End=nothing, Depth_extent=nothing )
Creates a cross-section through a volumetric (3D) `GeoData` object.
- Cross-sections can be horizontal (map view at a given depth), if `Depth_level` is specified
- They can also be vertical, either by specifying `Lon_level` or `Lat_level` (for a fixed lon/lat), or by defining both `Start=(lon,lat)` & `End=(lon,lat)` points.
- When both `Start=(lon,lat)` & `End=(lon,lat)` are given, one can also provide a the depth extent of the profile by providing Depth_extent=(depth_min,depth_max)
- `Interpolate` indicates whether we want to simply extract the data from the 3D volume (default) or whether we want to linearly interpolate it on a new grid, which has dimensions as specified in `dims`
- `Depth_extent` is an optional parameter that can indicate the depth extent over which you want to interpolate the vertical cross-section. Default is the full vertical extent of the 3D dataset
# Example:
```julia-repl
julia> Lon,Lat,Depth = lonlatdepth_grid(10:20,30:40,(-300:25:0)km);
julia> Data = Depth*2; # some data
julia> Vx,Vy,Vz = ustrip(Data*3),ustrip(Data*4),ustrip(Data*5);
julia> Data_set3D = GeoData(Lon,Lat,Depth,(Depthdata=Data,LonData=Lon, Velocity=(Vx,Vy,Vz)));
julia> Data_cross = cross_section_volume(Data_set3D, Depth_level=-100km)
GeoData
size : (11, 11, 1)
lon ϵ [ 10.0 : 20.0]
lat ϵ [ 30.0 : 40.0]
depth ϵ [ -100.0 km : -100.0 km]
fields: (:Depthdata, :LonData, :Velocity)
```
"""
function cross_section_volume(V::AbstractGeneralGrid; dims=(100,100), Interpolate=false, Depth_level=nothing, Lat_level=nothing, Lon_level=nothing, Start=nothing, End=nothing, Depth_extent=nothing )
DataSetType = check_data_set(V);
if DataSetType != 3
error("cross_section_volume: the input data set has to be a volume!")
end
# extract the coordinates
X,Y,Z = coordinate_grids(V)
if !isnothing(Depth_level) # Horizontal slice
CheckBounds(Z, Depth_level)
if Interpolate
Lon,Lat,Depth = lonlatdepth_grid( LinRange(minimum(X), maximum(X), dims[1]),
LinRange(minimum(Y), maximum(Y), dims[2]),
Depth_level)
else
ind_z = argmin(abs.(NumValue(Z[1,1,:]) .- ustrip(Depth_level)))
iDepth = ind_z:ind_z;
iLon = 1:size(NumValue(X),1);
iLat = 1:size(NumValue(Y),2);
end
end
if !isnothing(Lat_level) # vertical slice @ given latitude
CheckBounds(Y, Lat_level)
if Interpolate
Lon,Lat,Depth = lonlatdepth_grid( LinRange(minimum(X), maximum(X), dims[1]),
Lat_level,
LinRange(minimum(Z), maximum(Z), dims[2]))
else
ind_l = argmin(abs.(Y[1,:,1] .- Lat_level))
iDepth = 1:size(Z,3)
iLon = 1:size(X,1);
iLat = ind_l:ind_l
end
end
if !isnothing(Lon_level) # vertical slice @ given longitude
CheckBounds(X, Lon_level)
if Interpolate
Lon,Lat,Depth = lonlatdepth_grid( Lon_level,
LinRange(minimum(Y), maximum(Y), dims[1]),
LinRange(minimum(Z), maximum(Z), dims[2]))
else
ind_l = argmin(abs.(X[:,1,1] .- Lon_level))
iDepth = 1:size(Z,3)
iLat = 1:size(Y,2);
iLon = ind_l:ind_l
end
end
# diagonal profile defined by start and end lon/lat points
if !isnothing(Start)
if isnothing(End)
error("Also define End coordinates if you indicate starting lon/lat value")
end
Interpolate = true; # we must interpolate in this case
# if the depth extent is given, modify the Z values to take this into account
if !isnothing(Depth_extent)
if length(Depth_extent) != 2
error("Depth_extent should have length 2")
end
end
if !isnothing(Depth_extent)
Z = [Depth_extent[1] Depth_extent[2]];
end
Lon_dum,Lat_p,Depth_p = lonlatdepth_grid( Start[1],
LinRange(Start[2], End[2], dims[1]),
LinRange(minimum(Z), maximum(Z), dims[2]))
Lon_p,Lat_dum,Depth = lonlatdepth_grid( LinRange(Start[1], End[1], dims[1]),
Start[2],
LinRange(minimum(Z), maximum(Z), dims[2]))
Lon = zeros(dims[1],dims[2],1)
Lat = zeros(dims[1],dims[2],1)
Depth = zeros(dims[1],dims[2],1)*Depth_p[1]
# We need 3D matrixes for the paraview writing routine to know we are in 3D
Lon[:,:,1] = Lon_p[:,1,:]
Lat[:,:,1] = Lat_p[1,:,:]
Depth[:,:,1] = Depth_p[1,:,:]
end
if Interpolate
# Interpolate data on profile
DataProfile = interpolate_datafields(V, Lon, Lat, NumValue(Depth));
else
# extract data (no interpolation)
DataProfile = ExtractDataSets(V, iLon, iLat, iDepth);
end
return DataProfile
end
"""
cross_section_surface(Surface::GeoData; dims=(100,), Interpolate=false, Depth_level=nothing; Lat_level=nothing; Lon_level=nothing; Start=nothing, End=nothing )
Creates a cross-section through a surface (2D) `GeoData` object.
- Cross-sections can be horizontal (map view at a given depth), if `Depth_level` is specified
- They can also be vertical, either by specifying `Lon_level` or `Lat_level` (for a fixed lon/lat), or by defining both `Start=(lon,lat)` & `End=(lon,lat)` points.
- IMPORTANT: The surface to be extracted has to be given as a gridded GeoData object. It may also contain NaNs where it is not defined. Any points lying outside of the defined surface will be considered NaN.
# Example:
```julia-repl
julia> Lon,Lat,Depth = lonlatdepth_grid(10:20,30:40,-50km);
julia> Data = Depth*2; # some data
julia> Vx,Vy,Vz = ustrip(Data*3),ustrip(Data*4),ustrip(Data*5);
julia> Data_set2D = GeoData(Lon,Lat,Depth,(Depth=Depth,));
julia> Data_cross = cross_section_surface(Data_set2D, Lat_level =15)
GeoData
size : (100,)
lon ϵ [ 10.0 : 20.0]
lat ϵ [ 15.0 : 15.0]
depth ϵ [ NaN : NaN]
fields : (:Depth,)
attributes: ["note"]
```
"""
function cross_section_surface(S::AbstractGeneralGrid; dims=(100,), Interpolate=true, Depth_level=nothing, Lat_level=nothing, Lon_level=nothing, Start=nothing, End=nothing )
DataSetType = check_data_set(S);
if DataSetType != 2
error("cross_section_surface: the input data set has to be a surface!")
end
X,Y,Z = coordinate_grids(S)
Lon_vec = X[:,1,1]
Lat_vec = Y[1,:,1]
if !isnothing(Depth_level) # not working yet, as this requires the intersection of two interfaces
error(" horizontal cross sections not working yet with surface data!")
end
if !isnothing(Lat_level) # vertical slice @ given latitude
# create a vector that spans the entire dataset @ a given latitutde
Lon = LinRange(minimum(Lon_vec), maximum(Lon_vec), dims[1])
Lat = ones(size(Lon))*Lat_level;
end
if !isnothing(Lon_level) # vertical slice @ given longitude
# create a vector that spans the entire dataset @ a given longitude
Lat = LinRange(minimum(Lat_vec), maximum(Lat_vec), dims[1])
Lon = ones(size(Lat))*Lon_level
end
# diagonal profile defined by start and end lon/lat points
if !isnothing(Start)
if isnothing(End)
error("Also define End coordinates if you indicate starting lon/lat value")
end
Lon = LinRange(Start[1], End[1], dims[1])
Lat = LinRange(Start[2], End[2], dims[1]);
end
# now interpolate the depth information of the surface to the profile in question
interpol = linear_interpolation((Lon_vec, Lat_vec), Z[:,:,1],extrapolation_bc=NaN); # create interpolation object, fill with NaNs if outside
depth_intp = interpol.(Lon, Lat)*km
# also interpolate any other data that is stored in the GeoData structure on the profile
fields_new = S.fields;
field_names = keys(fields_new);
for i = 1:length(S.fields)
if typeof(S.fields[i]) <: Tuple
# vector or anything that contains more than 1 field
data_tuple = fields_new[i] # we have a tuple (likely a vector field), so we have to loop
data_array = zeros(size(Lon,1),size(Lon,2),length(data_tuple)); # create a 2D array that holds the 2D interpolated values
unit_array = zeros(size(data_array));
for j=1:length(data_tuple)
interpol = linear_interpolation((Lon_vec, Lat_vec), dropdims(ustrip.(data_tuple[j]),dims=3),extrapolation_bc = NaN); # create interpolation object
data_array[:,:,j] = interpol.(Lon, Lat);
end
data_new = tuple([data_array[:,:,c] for c in 1:size(data_array,3)]...) # transform 3D matrix to tuple, do not add unit, as this creates an error in GMG (Issue), to add the unit: *unit(S.fields[i][1][1])
else
# scalar field
interpol = linear_interpolation((Lon_vec, Lat_vec), dropdims(ustrip.(S.fields[i]),dims=3), extrapolation_bc = NaN);
data_new = interpol.(Lon, Lat)*unit(S.fields[i][1]); # interpolate data field
end
# replace the field
new_field = NamedTuple{(field_names[i],)}((data_new,)) # Create a tuple with same name and unit
fields_new = merge(fields_new, new_field); # replace the field in fields_new
end
# create GeoData structure with the interpolated points
Data_profile = GeoData(Lon, Lat, depth_intp, (fields_new));
return Data_profile
end
"""
function cross_section_points(P::GeoData; Depth_level=nothing, Lat_level=nothing, Lon_level=nothing, Start=nothing, End=nothing, section_width=50 )
Creates a projection of separate points (saved as a GeoData object) onto a chosen plane. Only points with a maximum distance of section_width are taken into account
"""
function cross_section_points(P::GeoData; Depth_level=nothing, Lat_level=nothing, Lon_level=nothing, Start=nothing, End=nothing, section_width = 10km)
DataSetType = check_data_set(P);
if DataSetType != 1
error("cross_section_points: the input data set has to be a pointwise data set!")
end
if !isnothing(Depth_level)
ind = findall(-0.5*ustrip(section_width) .< (NumValue(P.depth) .- ustrip(Depth_level)) .< 0.5*ustrip(section_width)) # find all points around the desired depth level, both units should be in km, so no unit transformation required
# create temporary variables
lon_tmp = NumValue(P.lon.val[ind])
lat_tmp = NumValue(P.lat.val[ind])
depth_tmp = NumValue(P.depth.val[ind])
depth_proj = ones(size(depth_tmp))*Depth_level
# create fields that will be stored additionally on the GeoData structure
field_tmp = (depth_proj=depth_proj,lat_proj=lat_tmp,lon_proj=lon_tmp) # these are the projected points
end
if !isnothing(Lat_level) # vertical slice @ given latitude
p_Point = ProjectionPoint(Lat=Lat_level,Lon=sum(P.lon.val)/length(P.lon.val)) # define the projection point (lat/lon) as the latitude and the mean of the longitudes of the data
P_UTM = convert2UTMzone(P, p_Point) # convert to UTM
ind = findall(-0.5*ustrip(uconvert(u"m",section_width)) .< (P_UTM.NS.val .- p_Point.NS) .< 0.5*ustrip(uconvert(u"m",section_width))) # find all points around the desired latitude level, UTM is in m, so we have to convert the section width
# create temporary variables
lon_tmp = NumValue(P.lon.val[ind])
lat_tmp = NumValue(P.lat.val[ind])
depth_tmp = NumValue(P.depth.val[ind])
lat_proj = ones(size(depth_tmp))*Lat_level
# data to be stored on the new GeoData structure
field_tmp = (depth_proj=depth_tmp,lat_proj=lat_proj,lon_proj=lon_tmp) # these are the projected points
end
if !isnothing(Lon_level) # vertical slice @ given longitude
p_Point = ProjectionPoint(Lat=sum(P.lat.val)/length(P.lat.val),Lon=Lon_level) # define the projection point (lat/lon) as the latitude and the mean of the longitudes of the data
P_UTM = convert2UTMzone(P,p_Point) # convert to UTM
ind = findall(-0.5*ustrip(uconvert(u"m",section_width)) .< (P_UTM.EW.val .- p_Point.EW) .< 0.5*ustrip(uconvert(u"m",section_width))) # find all points around the desired longitude level, UTM is in m, so we have to convert the section width
# create temporary variables
lon_tmp = NumValue(P.lon.val[ind])
lat_tmp = NumValue(P.lat.val[ind])
depth_tmp = NumValue(P.depth.val[ind])
lon_proj = ones(size(depth_tmp))*Lon_level
# create fields that will be stored on the GeoData structure
field_tmp = (depth_proj=depth_tmp,lat_proj=lat_tmp,lon_proj=lon_proj) # these are the projected points
end
# vertical profile defined by start and end lon/lat points
# here we need to compute the distance to a distance_to_plane
# also, we need to project the points on the profile plane for later plotting
if !isnothing(Start)
if isnothing(End)
error("Also define End coordinates if you indicate starting lon/lat value")
end
# choose projection point based on Start and End coordinates of the profile
p_Point = ProjectionPoint(Lat=0.5*(Start[2]+End[2]),Lon=0.5*(Start[1]+End[1]))
# convert P to UTM Data
P_UTM = convert2UTMzone(P, p_Point) # convert to UTM
# create a GeoData set containing the points that create the profile plane (we need three points to uniquely define that plane)
# here, we define the points in a way that the angle between P1-P2 and P1-P3 vectors is 90° --> useful for the cross product
Profile = GeoData([Start[1] Start[1] End[1]], [Start[2] Start[2] End[2]], [0 -200 0]*km, (depth = [0 -200 0]*km,))
Profile_UTM = convert2UTMzone(Profile,p_Point) # convert to UTM
# compute the unit normal of the profile plane using the cross product
# ATTENTION: UTM COORDINATES ARE IN M, WHILE DEPTH IS IN KM !!!
a1 = Profile_UTM.EW.val[2]-Profile_UTM.EW.val[1]
a2 = Profile_UTM.NS.val[2]-Profile_UTM.NS.val[1]
a3 = (Profile_UTM.depth.val[2]- Profile_UTM.depth.val[1]) * 1e3
b1 = Profile_UTM.EW.val[3]- Profile_UTM.EW.val[1]
b2 = Profile_UTM.NS.val[3]- Profile_UTM.NS.val[1]
b3 = (Profile_UTM.depth.val[3]- Profile_UTM.depth.val[1]) * 1e3
nx = a2*b3 - a3*b2
ny = a3*b1 - a1*b3
nz = a1*b2 - a2*b1
t = (nx*Profile_UTM.EW.val[1] .- nx*P_UTM.EW.val .+ ny*Profile_UTM.NS.val[1] .- ny*P_UTM.NS.val .+ nz*Profile_UTM.depth.val[1]*1e3 .- nz*P_UTM.depth.val*1e3)/(nx*nx+ny*ny+nz*nz)
# compute the distance to the plane
dist = sqrt.((t.*nx).^2 + (t.*ny).^2 + (t.*nz).^2)
# find the points that are within the required window around the profile
ind = findall(-0.5*ustrip(uconvert(u"m",section_width)) .< dist .< 0.5*ustrip(uconvert(u"m",section_width))) # find all points around the profile (distance is treated in m)
# project the points on the plane (only the relevant ones)
px = P_UTM.EW.val[ind] + t[ind].*nx
py = P_UTM.NS.val[ind] + t[ind].*ny
pz = P_UTM.depth.val[ind]*1e3 + t[ind].*nz # convert depth to m
# the projected points are given in UTM coordinates and not in lon/lat/depth
# therefore we have to recompute the lat/lon/depth values of the projected points
# then we will return a GeoData structure with all information included
trans = LLAfromUTM(p_Point.zone, p_Point.isnorth, wgs84) # set up transformation
plon = zeros(size(ind));
plat = zeros(size(ind));
pdepth = zeros(size(ind));
for i in eachindex(ind)
utmi = UTM(px[i],py[i],pz[i])
llai = trans(utmi)
plon[i] = llai.lon
plat[i] = llai.lat
pdepth[i] = llai.alt
end
# data to be stored in the GeoData structure
field_tmp = (depth_proj=pdepth/1e3,lat_proj=plat,lon_proj=plon) # these are the projected points
end
# also transfer any other data that is stored in the GeoData structure
fields_new = P.fields;
field_names = keys(fields_new);
for i = 1:length(P.fields)
if typeof(P.fields[i]) <: Tuple
# vector or anything that contains more than 1 field
data_tuple = fields_new[i] # we have a tuple (likely a vector field), so we have to loop
data_array = zeros(size(ind,1),length(data_tuple)); # create a 2D array that holds the chosen values
for j=1:length(data_tuple)
data_array[:,j] = ustrip.(data_tuple[i][ind])
end
data_new = tuple([data_array[:,:,c] for c in 1:size(data_array,3)]...) # transform 2D matrix to tuple, do not consider the unit as it creates an error in GMG (Issue), to add the unit: *unit.(P.fields[i][1][1]
else
# scalar field
data_new = fields_new[i][ind]; # interpolate data field
end
# replace the field
new_field = NamedTuple{(field_names[i],)}((data_new,)) # Create a tuple with same name and unit
fields_new = merge(fields_new, new_field); # replace the field in fields_new
end
# merge old and new fields
fields_new = merge(fields_new,field_tmp);
# create a GeoData structure to return
if length(ind)>0
Data_profile = GeoData(P.lon.val[ind],P.lat.val[ind],P.depth.val[ind],(fields_new))
else
Data_profile = nothing
end
return Data_profile
end
"""
cross_section(DataSet::AbstractGeneralGrid; dims=(100,100), Interpolate=false, Depth_level=nothing, Lat_level=nothing, Lon_level=nothing, Start=nothing, End=nothing, Depth_extent=nothing, section_width=50km)
Creates a cross-section through a `GeoData` object.
- Cross-sections can be horizontal (map view at a given depth), if `Depth_level` is specified
- They can also be vertical, either by specifying `Lon_level` or `Lat_level` (for a fixed lon/lat), or by defining both `Start=(lon,lat)` & `End=(lon,lat)` points.
- Depending on the type of input data (volume, surface or point data), cross sections will be created in a different manner:
1. Volume data: data will be interpolated or directly extracted from the data set.
2. Surface data: surface data will be interpolated or directly extracted from the data set
3. Point data: data will be projected to the chosen profile. Only data within a chosen distance (default is 50 km) will be used
- `Interpolate` indicates whether we want to simply extract the data from the data set (default) or whether we want to linearly interpolate it on a new grid, which has dimensions as specified in `dims` NOTE: THIS ONLY APPLIES TO VOLUMETRIC AND SURFACE DATA SETS
- 'section_width' indicates the maximal distance within which point data will be projected to the profile
# Example:
```julia-repl
julia> Lon,Lat,Depth = lonlatdepth_grid(10:20,30:40,(-300:25:0)km);
julia> Data = Depth*2; # some data
julia> Vx,Vy,Vz = ustrip(Data*3),ustrip(Data*4),ustrip(Data*5);
julia> Data_set3D = GeoData(Lon,Lat,Depth,(Depthdata=Data,LonData=Lon, Velocity=(Vx,Vy,Vz)));
julia> Data_cross = cross_section(Data_set3D, Depth_level=-100km)
GeoData
size : (11, 11, 1)
lon ϵ [ 10.0 : 20.0]
lat ϵ [ 30.0 : 40.0]
depth ϵ [ -100.0 km : -100.0 km]
fields: (:Depthdata, :LonData, :Velocity)
```
"""
function cross_section(DataSet::AbstractGeneralGrid; dims=(100,100), Interpolate=false, Depth_level=nothing, Lat_level=nothing, Lon_level=nothing, Start=nothing, End=nothing, Depth_extent=nothing, section_width=50km)
DataSetType = check_data_set(DataSet); # check which kind of data set we are dealing with
if DataSetType==1 # points
DataProfile = cross_section_points(DataSet; Depth_level, Lat_level, Lon_level, Start, End, section_width)
elseif DataSetType==2 # surface
DataProfile = cross_section_surface(DataSet; dims, Depth_level, Lat_level, Lon_level, Start, End)
elseif DataSetType==3 # volume
DataProfile = cross_section_volume(DataSet; dims, Interpolate, Depth_level, Lat_level, Lon_level, Start, End, Depth_extent)
# add field that has coordinates along the profile
DataProfile = addfield(DataProfile,"FlatCrossSection", flatten_cross_section(DataProfile))
end
return DataProfile
end
"""
flatten_cross_section(V::CartData)
Takes a diagonal 3D cross_section and flattens it to be converted to a 2D Grid by create_CartGrid
# Example
```julia
Grid = create_CartGrid(size=(100,100,100), x=(0.0km, 99.9km), y=(-10.0km, 20.0km), z=(-40km,4km));
X,Y,Z = xyz_grid(Grid.coord1D...);
DataSet = CartData(X,Y,Z,(Depthdata=Z,));
Data_Cross = cross_section(DataSet, dims=(100,100), Interpolate=true, Start=(ustrip(Grid.min[1]),ustrip(Grid.max[2])), End=(ustrip(Grid.max[1]), ustrip(Grid.min[2])))
x_new = flatten_cross_section(Data_Cross)
# This flattened cross_section can be added to original Data_Cross by addfield()
Data_Cross = addfield(Data_Cross,"FlatCrossSection", x_new)
CartData
size : (100, 100, 1)
x ϵ [ 0.0 : 99.9]
y ϵ [ -10.0 : 20.0]
z ϵ [ -40.0 : 4.0]
fields : (:Depthdata, :FlatCrossSection)
attributes: ["note"]
```
"""
function flatten_cross_section(V::CartData)
x_new = sqrt.((V.x.val.-V.x.val[1,1,1]).^2 .+ (V.y.val.-V.y.val[1,1,1]).^2) # NOTE: the result is in km, as V.x and V.y are stored in km
# Data_Cross_2D = CartData(x_new,V.y.val.*0.0, V.z.val, V.fields)
return x_new
end
"""
flatten_cross_section(V::GeoData)
This function takes a 3D cross section through a GeoData structure and computes the distance along the cross section for later 2D processing/plotting
```julia-repl
julia> Lon,Lat,Depth = lonlatdepth_grid(10:20,30:40,(-300:25:0)km);
julia> Data = Depth*2; # some data
julia> Vx,Vy,Vz = ustrip(Data*3),ustrip(Data*4),ustrip(Data*5);
julia> Data_set3D = GeoData(Lon,Lat,Depth,(Depthdata=Data,LonData=Lon, Velocity=(Vx,Vy,Vz)));
julia> Data_cross = cross_section(Data_set3D, Start=(10,30),End=(20,40))
julia> x_profile = flatten_cross_section(Data_cross)
julia> Data_cross = addfield(Data_cross,"x_profile",x_profile)
```
"""
function flatten_cross_section(V::GeoData; Start=nothing)
if isnothing(Start)
lla_start = LLA(V.lat.val[1][1][1],V.lon.val[1][1][1],0.0) # start point, at the surface
else
lla_start = LLA(Start[2],Start[1],0.0);
end
x_new = zeros(size(V.lon));
for i in eachindex(x_new)
x_new[i] = euclidean_distance(LLA(V.lat.val[i],V.lon.val[i],0.0), lla_start) /1e3 # compute distance as if points were at the surface, CONVERTED TO KM !!!
end
return x_new
end
"""
extract_subvolume(V::GeoData; Interpolate=false, Lon_level=nothing, Lat_level=nothing, Depth_level=nothing, dims=(50,50,50))
Extract or "cuts-out" a piece of a 2D or 3D GeoData set, defined by `Lon`, `Lat` and `Depth` coordinates.
This is useful if you are only interested in a part of a much bigger larger data set.
- `Lon_level`,`Lat_level` and `Depth_level` should be tuples that indicate `(minimum_value, maximum_value)` along the respective direction. If not specified we use the full range.
- By default, `Interpolate=false` and we find the closest indices within the data set (so your new data set will not go exactly from minimum to maximum).
- Alternatively, if `Interpolate=true` we interpolate the data onto a new grid that has dimensions `dims`. This can be useful to compare data sets that are originally given in different resolutions.
# 3D Example with no interpolation:
```julia-repl
julia> Lon,Lat,Depth = lonlatdepth_grid(10:20,30:40,(-300:25:0)km);
julia> Data = Depth*2; # some data
julia> Vx,Vy,Vz = ustrip(Data*3),ustrip(Data*4),ustrip(Data*5);
julia> Data_set3D = GeoData(Lon,Lat,Depth,(Depthdata=Data,LonData=Lon, Velocity=(Vx,Vy,Vz)))
GeoData
size : (11, 11, 13)
lon ϵ [ 10.0 : 20.0]
lat ϵ [ 30.0 : 40.0]
depth ϵ [ -300.0 km : 0.0 km]
fields: (:Depthdata, :LonData, :Velocity)
julia> Data_extracted = extract_subvolume(Data_set3D,Lon_level=(10,12),Lat_level=(35,40))
GeoData
size : (3, 6, 13)
lon ϵ [ 10.0 : 12.0]
lat ϵ [ 35.0 : 40.0]
depth ϵ [ -300.0 km : 0.0 km]
fields: (:Depthdata, :LonData, :Velocity)
```
By default it extracts the data points closest to the area defined by Lon_level/Lat_level/Depth_level.
# 3D Example with interpolation:
Alternatively, you can also interpolate the data onto a new grid:
```julia
julia> Data_extracted = extract_subvolume(Data_set3D,Lon_level=(10,12),Lat_level=(35,40), Interpolate=true, dims=(50,51,52))
GeoData
size : (50, 51, 52)
lon ϵ [ 10.0 : 12.0]
lat ϵ [ 35.0 : 40.0]
depth ϵ [ -300.0 km : 0.0 km]
fields: (:Depthdata, :LonData, :Velocity)
```
"""
function extract_subvolume(V::GeoData; Interpolate=false, Lon_level=nothing, Lat_level=nothing, Depth_level=nothing, dims=(50,50,50))
if isnothing(Lon_level)
Lon_level = (minimum(V.lon.val), maximum(V.lon.val))
end
if isnothing(Lat_level)
Lat_level = (minimum(V.lat.val), maximum(V.lat.val))
end
if isnothing(Depth_level)
Depth_level = (minimum(V.depth.val), maximum(V.depth.val))
end
if Interpolate
Lon,Lat,Depth = lonlatdepth_grid( LinRange(Lon_level[1], Lon_level[2], dims[1]),
LinRange(Lat_level[1], Lat_level[2], dims[2]),
LinRange(Depth_level[1], Depth_level[2], dims[3]) );
Data_extract = interpolate_datafields(V, Lon, Lat, Depth)
else
# Don't interpolate
i_s, i_e = argmin(abs.(V.lon.val[:,1,1] .- Lon_level[1])), argmin(abs.(V.lon.val[:,1,1] .- Lon_level[2]))
iLon = i_s:i_e;
i_s, i_e = argmin(abs.(V.lat.val[1,:,1] .- Lat_level[1])), argmin(abs.(V.lat.val[1,:,1] .- Lat_level[2]))
iLat = i_s:i_e;
i_s, i_e = argmin(abs.(V.depth.val[1,1,:] .- ustrip(Depth_level[1]))), argmin(abs.(V.depth.val[1,1,:] .- ustrip(Depth_level[2])))
step = 1;
if i_e<i_s
step=-1
end
iDepth = i_s:step:i_e;
Data_extract = ExtractDataSets(V, iLon, iLat, iDepth);
end
return Data_extract
end
"""
extract_subvolume(V::CartData; Interpolate=false, X_level=nothing, Y_level=nothing, Z_level=nothing, dims=(50,50,50))
Extract or "cuts-out" a piece of a 2D or 3D GeoData set, defined by `Lon`, `Lat` and `Depth` coordinates.
This is useful if you are only interested in a part of a much bigger larger data set.
- `Lon_level`,`Lat_level` and `Depth_level` should be tuples that indicate `(minimum_value, maximum_value)` along the respective direction. If not specified we use the full range.
- By default, `Interpolate=false` and we find the closest indices within the data set (so your new data set will not go exactly from minimum to maximum).
- Alternatively, if `Interpolate=true` we interpolate the data onto a new grid that has dimensions `dims`. This can be useful to compare data sets that are originally given in different resolutions.
# 3D Example with no interpolation:
```julia-repl
julia> Lon,Lat,Depth = lonlatdepth_grid(10:20,30:40,(-300:25:0)km);
julia> Data = Depth*2; # some data
julia> Vx,Vy,Vz = ustrip(Data*3),ustrip(Data*4),ustrip(Data*5);
julia> Data_set3D = GeoData(Lon,Lat,Depth,(Depthdata=Data,LonData=Lon, Velocity=(Vx,Vy,Vz)))
GeoData
size : (11, 11, 13)
lon ϵ [ 10.0 : 20.0]
lat ϵ [ 30.0 : 40.0]
depth ϵ [ -300.0 km : 0.0 km]
fields: (:Depthdata, :LonData, :Velocity)
julia> Data_extracted = extract_subvolume(Data_set3D,Lon_level=(10,12),Lat_level=(35,40))
GeoData
size : (3, 6, 13)
lon ϵ [ 10.0 : 12.0]
lat ϵ [ 35.0 : 40.0]
depth ϵ [ -300.0 km : 0.0 km]
fields: (:Depthdata, :LonData, :Velocity)
```
By default it extracts the data points closest to the area defined by Lon_level/Lat_level/Depth_level.
# 2D Example along a cross-section through 3D data:
```julia-repl
julia> X,Y,Z = xyz_grid(10:20,30:40,-300:25:0);
julia> Data = Z.*2
julia> Data_Int = Int64.(Data)
julia> DataSet_Cart = CartData(X,Y,Z,(Data=Data,Data_Int=Data_Int, Velocity=(X,Y,Z)))
julia> Data_cross = cross_section(DataSet_Cart, Start=(11.0,35), End=(19, 39.0))
CartData
size : (100, 100, 1)
x ϵ [ 11.0 : 19.0]
y ϵ [ 35.0 : 39.0]
z ϵ [ -300.0 : 0.0]
fields : (:Data, :Data_Int, :Velocity, :FlatCrossSection)
attributes: ["note"]
julia> Data_extracted = extract_subvolume(Data_cross, X_level=(1,7), Z_level=(-200,-100))
CartData
size : (50, 50, 1)
x ϵ [ 11.894427190999917 : 17.260990336999413]
y ϵ [ 35.44721359549995 : 38.130495168499706]
z ϵ [ -200.0 : -100.0]
fields : (:FlatCrossSection, :Data, :Data_Int, :Velocity)
attributes: ["note"]
julia> typeof(Data_extracted.fields.Data_Int)
Array{Int64, 3}
```
"""
function extract_subvolume(V::CartData;
Interpolate=true,
X_level=nothing,
X_cross=nothing,
Y_level=nothing,
Z_level=nothing,
dims=(50,50,50))
if isnothing(X_level)
X_level = (minimum(V.x.val), maximum(V.x.val))
end
if isnothing(Y_level)
Y_level = (minimum(V.y.val), maximum(V.y.val))
end
if isnothing(Z_level)
Z_level = (minimum(V.z.val), maximum(V.z.val))
end
if Interpolate==true && size(V.x.val)[3]>1
X,Y,Z = lonlatdepth_grid( LinRange(X_level[1], X_level[2], dims[1]),
LinRange(Y_level[1], Y_level[2], dims[2]),
LinRange(Z_level[1], Z_level[2], dims[3]) );
Data_extract = interpolate_datafields(V, X, Y, Z)
elseif size(V.x.val)[3]==1
# we are dealing with a vertical cross-section through a 3D dataset computed with cross_section(V,Start=.., End=...)
Xcross=V.fields.FlatCrossSection;
if isnothing(X_level)
X_level = extrema(Xcross)
end
dims_cross=(dims[1],dims[2],1);
# we need to interpolate the data onto a new grid given by X_level and Z_level
X_level_cross = X_level;
interpol_x = linear_interpolation(Xcross[:,1,1], V.x.val[:,1,1],extrapolation_bc = NaN); # create interpolation object
interpol_y = linear_interpolation(Xcross[:,1,1], V.y.val[:,1,1],extrapolation_bc = NaN); # create interpolation object
X_level = interpol_x.(X_level_cross)
Y_level = interpol_y.(X_level_cross)
x = LinRange(X_level_cross[1], X_level_cross[2], dims_cross[1])
z = LinRange(Z_level[1], Z_level[2], dims_cross[2])
X,Y,Z = zeros(dims[1],dims[2],1), zeros(dims[1],dims[2],1), zeros(dims[1],dims[2],1)
X_cross = zero(X)
for (i,x_val) in enumerate(x), (j,z_val) in enumerate(z)
X[i,j,1] = interpol_x(x_val)
Y[i,j,1] = interpol_y(x_val)
Z[i,j,1] = z_val
X_cross[i,j,1] = x_val
end
Data_extract = interpolate_data_fields_cross_section(V, X, Y, Z, X_cross);
else
# Don't interpolate
i_s, i_e = argmin(abs.(V.x.val[:,1,1] .- X_level[1])), argmin(abs.(V.x.val[:,1,1] .- X_level[2]))
iLon = i_s:i_e;
i_s, i_e = argmin(abs.(V.y.val[1,:,1] .- Y_level[1])), argmin(abs.(V.y.val[1,:,1] .- Y_level[2]))
iLat = i_s:i_e;
i_s, i_e = argmin(abs.(V.z.val[1,1,:] .- ustrip(Z_level[1]))), argmin(abs.(V.z.val[1,1,:] .- ustrip(Z_level[2])))
step = 1;
if i_e<i_s
step=-1
end
iDepth = i_s:step:i_e;
Data_extract = ExtractDataSets(V, iLon, iLat, iDepth);
end
return Data_extract
end
"""
interpolate_data_fields_cross_section(V::CartData, X,Y,Z,Xcross)
Interpolates data fields along a cross-section defined by `Xcross` and `Z`
"""
function interpolate_data_fields_cross_section(V::CartData, X,Y,Z, X_cross)
Data_extract = CartData(X,Y,Z, (FlatCrossSection=X_cross,))
fields_new = V.fields;
field_names = keys(fields_new);
for i = 1:length(V.fields)
if typeof(V.fields[i]) <: Tuple
# vector or anything that contains more than 1 field
data_tuple = fields_new[i] # we have a tuple (likely a vector field), so we have to loop
data_array = zeros(size(Data_extract.x)...,length(data_tuple)); # create a 3D array that holds the 2D interpolated values
unit_array = zeros(size(data_array));
for j=1:length(data_tuple)
interpol = linear_interpolation((V.fields.FlatCrossSection[:,1,1], V.z.val[1,:,1]), ustrip.(data_tuple[j][:,:,1]),extrapolation_bc = NaN); # create interpolation object
data_array[:,:,:,j] = interpol.(X_cross, Z);
end
data_new = tuple([data_array[:,:,:,c] for c in 1:size(data_array,4)]...) # transform 3D matrix to tuple
else
# scalar field
interpol = linear_interpolation((V.fields.FlatCrossSection[:,1,1], V.z.val[1,:,1]), V.fields[i][:,:,1], extrapolation_bc = NaN); # create interpolation object
data_new = interpol.(X_cross, Z); # interpolate data field
if isa( V.fields[i][1], Int64)
data_new = round.(Int64,data_new)
end
end
Data_extract = addfield(Data_extract,String(field_names[i]),data_new)
end
return Data_extract
end
function CheckBounds(Data::GeoUnit, Data_Cross)
min_Data, max_Data = NumValue(minimum(Data.val)), NumValue(maximum(Data.val));
if ustrip(Data_Cross) < min_Data || ustrip(Data_Cross)>max_Data
error("Outside bounds [$min_Data : $max_Data]; $Data_Cross")
end
end
function CheckBounds(Data::AbstractArray, Data_Cross)
min_Data, max_Data = NumValue(minimum(Data)), NumValue(maximum(Data));
if ustrip(Data_Cross) < min_Data || ustrip(Data_Cross)>max_Data
error("Outside bounds [$min_Data : $max_Data]; $Data_Cross")
end
end
# CHECKS FOR VOLUME, SURFACE OR POINTS
function check_data_set(DataSet::GeoData)
if length(size(DataSet.lon)) == 1 # scattered points
return 1
else
if any(size(DataSet.lon).==1) # surface data
return 2
else # volume data
return 3
end
end
end
function check_data_set(DataSet::CartData)
if length(size(DataSet.x)) == 1 # scattered points
return 1
else
if any(size(DataSet.x).==1) # surface data
return 2
else # volume data
return 3
end
end
end
"""
Data_interp = interpolate_datafields(V::AbstractGeneralGrid, Lon, Lat, Depth)
Interpolates a data field `V` on a grid defined by `Lon,Lat,Depth`
# Example
```julia
julia> x = 0:2:10
julia> y = -5:5
julia> z = -10:2:2
julia> X,Y,Z = xyz_grid(x, y, z);
julia> Data = Z
julia> Data_set1= CartData(X,Y,Z, (FakeData=Data,Data2=Data.+1.))
CartData
size : (6, 11, 7)
x ϵ [ 0.0 km : 10.0 km]
y ϵ [ -5.0 km : 5.0 km]
z ϵ [ -10.0 km : 2.0 km]
fields : (:FakeData, :Data2)
attributes: ["note"]
julia> X,Y,Z = xyz_grid(0:4:10, -1:.1:1, -5:.1:1 );
julia> Data_set2= interpolate_datafields(Data_set1, X,Y,Z)
```
"""
function interpolate_datafields(V::AbstractGeneralGrid, Lon, Lat, Depth)
X,Y,Z = coordinate_grids(V)
Lon_vec = NumValue(X[:,1,1]);
Lat_vec = NumValue(Y[1,:,1]);
Depth_vec = Z[1,1,:];
if Depth_vec[1]>Depth_vec[end]
ReverseData = true
else
ReverseData = false
end
fields_new = V.fields;
field_names = keys(fields_new);
for i = 1:length(V.fields)
if typeof(V.fields[i]) <: Tuple
# vector or anything that contains more than 1 field
data_tuple = fields_new[i] # we have a tuple (likely a vector field), so we have to loop
data_array = zeros(size(Lon,1),size(Lon,2),size(Lon,3),length(data_tuple)); # create a 3D array that holds the 2D interpolated values
unit_array = zeros(size(data_array));
for j=1:length(data_tuple)