-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplotSubfault.R
More file actions
1650 lines (1420 loc) · 69.6 KB
/
plotSubfault.R
File metadata and controls
1650 lines (1420 loc) · 69.6 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
##### plot original CSZ fault geometry data
library(graphics)
# plot all subfaults in the fault (users should use this instead of plotSubfault for simplicity)
# set plotData=FALSE to only plot the polygons in the fault with no filling
# NOTE: don't worry about the warnings, they are caused by setting par to be suitable for the legend.
plotFault = function(rows, plotVar="depth", varRange=NULL,
cols=tim.colors(), new=TRUE, lwd=1, plotData=TRUE,
legend.mar=6, logScale=FALSE, ...) {
if(!is.data.frame(rows))
rows = data.frame(rows)
# if log scale, modify data and range accordingly
if(logScale) {
plotVar = log10(plotVar)
if(!is.null(varRange))
varRange=log10(varRange)
}
# if the user supplies a variable to plot in plotVar:
if(!is.character(plotVar)) {
rows$tmp = plotVar
plotVar = "tmp"
}
# set default plotting parameters to be reasonable
if(is.null(varRange))
varRange = range(rows[,plotVar], na.rm=TRUE)
otherArgs = list(...)
if(is.null(otherArgs$xlim))
otherArgs$xlim=range(rows$longitude)
if(is.null(otherArgs$ylim))
otherArgs$ylim=range(rows$latitude)
if(!plotData)
cols = c(NA, NA)
else {
currPar = par()
newPar = currPar
newMar = newPar$mar
newMar[4] = max(newMar[4], legend.mar)
newPar$mar = newMar
if(currPar$mar[4] != newMar[4])
suppressWarnings({par(newPar)})
}
# plot the subfaults
do.call("plotSubfault", c(list(rows[1,], plotVar, varRange, cols, new, polyArgs=list(lwd=lwd)), otherArgs))
invisible(apply(rows[-1,], 1, plotSubfault, plotVar=plotVar, varRange=varRange, cols=cols, new=FALSE, polyArgs=list(lwd=lwd)))
#add legend if necessary
if(plotData) {
if(logScale) {
ticks = axisTicks(varRange, log=TRUE)
image.plot(zlim=varRange, nlevel=length(cols), legend.only=TRUE, horizontal=FALSE,
col=cols, add = TRUE, axis.args=list(at=log10(ticks), labels=ticks))
}
else {
image.plot(zlim=varRange, nlevel=length(cols), legend.only=TRUE, horizontal=FALSE,
col=cols, add = TRUE)
}
# suppressWarnings({par(currPar)})
}
}
plotSubfault = function(row, plotVar="depth", varRange=NULL,
cols=tim.colors(), new=FALSE, polyArgs=NULL, ...) {
if(!is.list(row))
row = as.list(row)
if(is.null(varRange))
varRange = range(faultGeom[,plotVar])
plotVar = row[[plotVar]]
otherArgs = list(...)
if(is.null(otherArgs$xlim))
otherArgs$xlim=range(faultGeom$longitude)
if(is.null(otherArgs$ylim))
otherArgs$ylim=range(faultGeom$latitude)
if(is.null(otherArgs$ylab))
otherArgs$ylab = "Latitude"
if(is.null(otherArgs$xlab))
otherArgs$xlab = "Longitude"
otherArgs$type="n"
geom = calcGeom(row)
coords = geom$corners[,1:2]
# generate new plot if necessary
if(new)
do.call("plot", c(list(1, 2), otherArgs))
# get color to plot
vals = c(varRange, plotVar)
vals = vals-vals[1]
vals = vals/(vals[2] - vals[1])
col = cols[round(vals[3]*(length(cols)-1))+1]
# plot subfault rectangle
ord = c(1:4, 1)
do.call("polygon", c(list(coords[ord,1], coords[ord,2], col=col), polyArgs))
}
# This function is based on the SubFault.calculate_geometry function from
# dtopotools. Note that this is written based on coordinate specification
# being "top center". The Okada model requires depth at the bottom center.
calcGeom = function(subfault) {
# Calculate the fault geometry.
#
# Routine calculates the class attributes *corners* and
# *centers* which are the corners of the fault plane and
# points along the centerline respecitvely in 3D space.
#
# **Note:** *self.coordinate_specification* specifies the location on each
# subfault that corresponds to the (longitude,latitude) and depth
# of the subfault.
# Currently must be one of these strings:
#
# - "bottom center": (longitude,latitude) and depth at bottom center
# - "top center": (longitude,latitude) and depth at top center
# - "centroid": (longitude,latitude) and depth at centroid of plane
# - "noaa sift": (longitude,latitude) at bottom center, depth at top,
# This mixed convention is used by the NOAA SIFT
# database and "unit sources", see:
# http://nctr.pmel.noaa.gov/propagation-database.html
#
# The Okada model is expressed assuming (longitude,latitude) and depth
# are at the bottom center of the fault plane, so values must be
# shifted or other specifications.
row = subfault
if(!is.list(row))
row = data.frame(row)
# Simple conversion factors
#lat2meter = util.dist_latlong2meters(0.0, 1.0)[1]
#LAT2METER = 110.574 #* 10^3
LAT2METER = 111133.84012073894 #/10^3
lat2meter = LAT2METER
DEG2RAD = 2*pi/360
# Setup coordinate arrays
# Python format:
# Top edge Bottom edge
# a ----------- b ^
# | | | ^
# | | | |
# | | | | along-strike direction
# | | | |
# 0------1------2 | length |
# | | |
# | | |
# | | |
# | | |
# d ----------- c v
# <------------->
# width
#
# <-- up dip direction
# corners = [[None, None, None], # a
# [None, None, None], # b
# [None, None, None], # c
# [None, None, None]] # d
# centers = [[None, None, None], # 1
# [None, None, None], # 2
# [None, None, None]] # 3
corners = matrix(nrow=4, ncol=3) # rows are a,b,c,d, and cols are lon,lat,depth
centers = matrix(nrow=3, ncol=3) # rows are 1,2,3 (0,1,2), and cols are lon,lat,depth
# Set depths
centers[1,3] = row$depth
centers[2,3] = row$depth + 0.5 * row$width * sin(row$dip * DEG2RAD)
centers[3,3] = row$depth + row$width * sin(row$dip * DEG2RAD)
corners[1,3] = centers[1,3]
corners[4,3] = centers[1,3]
corners[2,3] = centers[3,3]
corners[3,3] = centers[3,3]
# Locate fault plane in 3D space:
# See the class docstring for a guide to labeling of corners/centers.
# Vector *up_dip* goes from bottom edge to top edge, in meters,
# from point 2 to point 0 in the figure in the class docstring.
up_dip = c(-row$width * cos(row$dip * DEG2RAD) * cos(row$strike * DEG2RAD)
/ (LAT2METER * cos(row$latitude * DEG2RAD)),
row$width * cos(row$dip * DEG2RAD)
* sin(row$strike * DEG2RAD) / LAT2METER)
centers[1,1:2] = c(row$longitude, row$latitude)
centers[2,1:2] = c(row$longitude - 0.5 * up_dip[1],
row$latitude - 0.5 * up_dip[2])
centers[3,1:2] = c(row$longitude - up_dip[1],
row$latitude - up_dip[2])
# Calculate coordinates of corners:
# Vector *strike* goes along the top edge from point 0 to point a
# in the figure in the class docstring.
up_strike = c(0.5 * row$length * sin(row$strike * DEG2RAD)
/ (lat2meter * cos(centers[3,2] * DEG2RAD)),
0.5 * row$length * cos(row$strike * DEG2RAD) / lat2meter)
corners[1,1:2] = c(centers[1,1] + up_strike[1],
centers[1,2] + up_strike[2])
corners[2,1:2] = c(centers[3,1] + up_strike[1],
centers[3,2] + up_strike[2])
corners[3,1:2] = c(centers[3,1] - up_strike[1],
centers[3,2] - up_strike[2])
corners[4,1:2] = c(centers[1,1] - up_strike[1],
centers[1,2] - up_strike[2])
return(list(corners=corners, centers=centers))
}
# same as calcGeom, except assumes the subfault has information about the coordinates of it's corners
calcGeom2 = function(subfault) {
# Calculate the fault geometry.
#
# Routine calculates the class attributes *corners* and
# *centers* which are the corners of the fault plane and
# points along the centerline respecitvely in 3D space.
#
# **Note:** *self.coordinate_specification* specifies the location on each
# subfault that corresponds to the (longitude,latitude) and depth
# of the subfault.
# Currently must be one of these strings:
#
# - "bottom center": (longitude,latitude) and depth at bottom center
# - "top center": (longitude,latitude) and depth at top center
# - "centroid": (longitude,latitude) and depth at centroid of plane
# - "noaa sift": (longitude,latitude) at bottom center, depth at top,
# This mixed convention is used by the NOAA SIFT
# database and "unit sources", see:
# http://nctr.pmel.noaa.gov/propagation-database.html
#
# The Okada model is expressed assuming (longitude,latitude) and depth
# are at the bottom center of the fault plane, so values must be
# shifted or other specifications.
row = subfault
if(!is.list(row))
row = data.frame(row)
# Simple conversion factors
#lat2meter = util.dist_latlong2meters(0.0, 1.0)[1]
#LAT2METER = 110.574 #* 10^3
LAT2METER = 111133.84012073894 #/10^3
lat2meter = LAT2METER
DEG2RAD = 2*pi/360
# Setup coordinate arrays
# Python format:
# Top edge Bottom edge
# a ----------- b ^
# | | | ^
# | | | |
# | | | | along-strike direction
# | | | |
# 0------1------2 | length |
# | | |
# | | |
# | | |
# | | |
# d ----------- c v
# <------------->
# width
#
# <-- up dip direction
# corners = [[None, None, None], # a
# [None, None, None], # b
# [None, None, None], # c
# [None, None, None]] # d
# centers = [[None, None, None], # 1
# [None, None, None], # 2
# [None, None, None]] # 3
corners = matrix(nrow=4, ncol=3) # rows are a,b,c,d, and cols are lon,lat,depth
centers = matrix(nrow=3, ncol=3) # rows are 1,2,3 (0,1,2), and cols are lon,lat,depth
# Set depths
centers[1,3] = row$depth
centers[2,3] = row$depth + 0.5 * row$width * sin(row$dip * DEG2RAD)
centers[3,3] = row$depth + row$width * sin(row$dip * DEG2RAD)
corners[1,3] = centers[1,3]
corners[4,3] = centers[1,3]
corners[2,3] = centers[3,3]
corners[3,3] = centers[3,3]
# Locate fault plane in 3D space:
# See the class docstring for a guide to labeling of corners/centers.
# Vector *up_dip* goes from bottom edge to top edge, in meters,
# from point 2 to point 0 in the figure in the class docstring.
# up_dip = c(-row$width * cos(row$dip * DEG2RAD) * cos(row$strike * DEG2RAD)
# / (LAT2METER * cos(row$latitude * DEG2RAD)),
# row$width * cos(row$dip * DEG2RAD)
# * sin(row$strike * DEG2RAD) / LAT2METER)
up_dip = c(row$bottomLeftX - row$bottomRightX, 0)
centers[1,1:2] = c(0.5 * (row$topLeftX + row$bottomLeftX), 0.5 * (row$topLeftY + row$bottomLeftY))
centers[2,1:2] = c(centers[1,1] - 0.5 * up_dip[1],
centers[1,2] - 0.5 * up_dip[2])
centers[3,1:2] = c(centers[1,1] - up_dip[1],
centers[1,2] - up_dip[2])
# Calculate coordinates of corners:
# Vector *strike* goes along the top edge from point 0 to point a
# in the figure in the class docstring.
# up_strike = c(0.5 * row$length * sin(row$strike * DEG2RAD)
# / (lat2meter * cos(centers[3,2] * DEG2RAD)),
# 0.5 * row$length * cos(row$strike * DEG2RAD) / lat2meter)
up_strike = c(0.5 * (row$topLeftX - row$bottomLeftX),
0.5 * (row$topLeftY - row$bottomLeftY))
corners[1,1:2] = c(centers[1,1] + up_strike[1],
centers[1,2] + up_strike[2])
corners[2,1:2] = c(centers[3,1] + up_strike[1],
centers[3,2] + up_strike[2])
corners[3,1:2] = c(centers[3,1] - up_strike[1],
centers[3,2] - up_strike[2])
corners[4,1:2] = c(centers[1,1] - up_strike[1],
centers[1,2] - up_strike[2])
return(list(corners=corners, centers=centers))
}
plotSubfaultGeom = function(subfault, varRange=NULL,
cols=tim.colors(), new=FALSE, polyArgs=NULL, ...) {
plotVar = "depth"
geom = calcGeom(subfault)
coords = geom$corners
depth = geom$centers[2,3]
# set varRange if necessary
if(is.null(varRange))
varRange = range(faultGeom[,"depth"])
# generate new plot if necessary
if(new)
do.call("plot.new", list(...))
# get color to plot
vals = c(varRange, depth)
vals = vals-vals[1]
vals = vals/(vals[2] - vals[1])
col = cols[round(vals[3]*(length(cols)-1))+1]
# plot subfault rectangle
ord = c(1, 2, 3, 4, 1)
do.call("polygon", c(list(x=coords[ord,1], y=coords[ord,2], col=col), polyArgs))
}
##### function for subdividing faults and subfaults. Assumes units are in meters
divideFault = function(rows, nDown=3, nStrike=4) {
subFaults = apply(rows, 1, divideSubfault, nDown=nDown, nStrike=nStrike)
do.call("rbind", subFaults)
}
# This function subdivides the subfault into smaller subfaults, with nDown in the dip
# direction and nStrike in the strike direction. Assumes the coordinates of the
# subfaults are at the top center of each subfault (as in the CSZ fault geometry),
# the locations are in latitude and longitude, and the distance units are in meters
divideSubfault = function(row, nDown=3, nStrike=4) {
if(!is.list(row))
row = as.list(row)
geom = calcGeom(row)
corners = geom$corners
# generate set of nDown points mid strike and going down dip with the correct depths
centers = matrix(nrow=nDown, ncol=3) # rows are 1,2,...,nDown, and cols are lon,lat,depth
# Simple conversion factors
#lat2meter = util.dist_latlong2meters(0.0, 1.0)[1]
#LAT2METER = 110.574 #* 10^3
LAT2METER = 111133.84012073894 #/10^3
lat2meter = LAT2METER
DEG2RAD = 2*pi/360
# Set depths
centers[,3] = row$depth + (0:(nDown-1))/nDown * row$width * sin(row$dip * DEG2RAD)
# Vector *up_dip* goes from bottom edge to top edge, in meters,
# from point 2 to point 0 in the figure in the class docstring.
# Vector *up_strike* goes along the top edge from point d to point a
# in the figure in the class docstring. (this is different from in calcGeom)
# up_depth is the depth difference from top to bottom of fault
up_dip = c(-row$width * cos(row$dip * DEG2RAD) * cos(row$strike * DEG2RAD)
/ (LAT2METER * cos(row$latitude * DEG2RAD)),
row$width * cos(row$dip * DEG2RAD)
* sin(row$strike * DEG2RAD) / LAT2METER)
up_strike = c(row$length * sin(row$strike * DEG2RAD)
/ (lat2meter * cos(geom$centers[3,2] * DEG2RAD)),
row$length * cos(row$strike * DEG2RAD) / lat2meter)
# Set lon and lat of centers
centers[,1] = row$longitude - (0:(nDown-1))/nDown * up_dip[1]
centers[,2] = row$latitude - (0:(nDown-1))/nDown * up_dip[2]
# get points along down strike edge of subfault by moving in down strike direction
# from centers
starts = centers
starts[,1:2] = starts[,1:2] + (- 0.5 + 1/(2*nStrike))*matrix(rep(up_strike, nrow(centers)), ncol=2, byrow = TRUE)
# compute complete set of subfault coordinates by shifting starts by various vectors in
# the up strike direction
coords = cbind(rep(starts[,1], nStrike), rep(starts[,2], nStrike), rep(starts[,3], nStrike))
shifts = matrix(rep(up_strike, nStrike*nDown), ncol=2, byrow = TRUE)
mult = rep((0:(nStrike-1))/nStrike, rep(nDown, nStrike))
shifts = sweep(shifts, MARGIN=1, STATS = mult, FUN = "*")
coords[,1:2] = coords[,1:2] + shifts
# construct subfaults
rows = data.frame(matrix(unlist(rep(row, nStrike*nDown)), ncol=length(row), byrow = TRUE))
names(rows) = names(row)
rows$Fault = row$Fault
rows$length = rows$length/nStrike
rows$width = rows$width/nDown
rows$depth = coords[,3]
rows$longitude = coords[,1]
rows$latitude = coords[,2]
return(rows)
}
# same as dividFault, except takes in the polygons of the fault instead of
# the original geometry format of, e.g., faultGeom
divideFault2 = function(rows, nDown=3, nStrike=4) {
subFaults = apply(rows, 1, divideSubfault2, nDown=nDown, nStrike=nStrike)
do.call("rbind", subFaults)
}
# same as dividSubfault, except takes in the polygons of the fault instead of
# the original geometry format of, e.g., faultGeom
divideSubfault2 = function(row, nDown=3, nStrike=4) {
if(!is.list(row))
row = as.list(row)
geom = calcGeom2(row)
corners = geom$corners
# generate set of nDown points mid strike and going down dip with the correct depths
centers = matrix(nrow=nDown, ncol=3) # rows are 1,2,...,nDown, and cols are lon,lat,depth
# Simple conversion factors
#lat2meter = util.dist_latlong2meters(0.0, 1.0)[1]
#LAT2METER = 110.574 #* 10^3
LAT2METER = 111133.84012073894 #/10^3
lat2meter = LAT2METER
DEG2RAD = 2*pi/360
# Set depths
centers[,3] = row$depth + (0:(nDown-1))/nDown * row$width * sin(row$dip * DEG2RAD)
# Vector *up_dip* goes from bottom edge to top edge, in meters,
# from point 2 to point 0 in the figure in the class docstring.
# Vector *up_strike* goes along the top edge from point d to point a
# in the figure in the class docstring. (this is different from in calcGeom)
# up_depth is the depth difference from top to bottom of fault
# up_dip = c(-row$width * cos(row$dip * DEG2RAD) * cos(row$strike * DEG2RAD)
# / (LAT2METER * cos(row$latitude * DEG2RAD)),
# row$width * cos(row$dip * DEG2RAD)
# * sin(row$strike * DEG2RAD) / LAT2METER)
up_dip = c(row$topLeftX - row$topRightX,
row$topLeftY - row$topRightY)
# up_strike = c(row$length * sin(row$strike * DEG2RAD)
# / (lat2meter * cos(geom$centers[3,2] * DEG2RAD)),
# row$length * cos(row$strike * DEG2RAD) / lat2meter)
up_strike = c(row$topLeftX - row$bottomLeftX,
row$topLeftY - row$bottomLeftY)
# Set lon and lat of centers
# centers[,1] = row$longitude - (0:(nDown-1))/nDown * up_dip[1]
# centers[,2] = row$latitude - (0:(nDown-1))/nDown * up_dip[2]
centers[,1] = row$topLeftX - (1:(nDown))/nDown * up_dip[1]
centers[,2] = 0.5 * (row$topLeftY + row$bottomLeftY) - (0:(nDown-1))/nDown * up_dip[2]
# get points along down strike edge of subfault by moving in down strike direction
# from centers
starts = centers
starts[,1:2] = starts[,1:2] + (- 0.5 + 1/(2*nStrike))*matrix(rep(up_strike, nrow(centers)), ncol=2, byrow = TRUE)
# compute complete set of subfault coordinates by shifting starts by various vectors in
# the up strike direction
coords = cbind(rep(starts[,1], nStrike), rep(starts[,2], nStrike), rep(starts[,3], nStrike))
shifts = matrix(rep(up_strike, nStrike*nDown), ncol=2, byrow = TRUE)
mult = rep((0:(nStrike-1))/nStrike, rep(nDown, nStrike))
shifts = sweep(shifts, MARGIN=1, STATS = mult, FUN = "*")
coords[,1:2] = coords[,1:2] + shifts
# construct subfaults (ignore latitude longitude coordinates)
rows = data.frame(matrix(unlist(rep(row, nStrike*nDown)), ncol=length(row), byrow = TRUE))
names(rows) = names(row)
rows$Fault = row$Fault
rows$length = rows$length/nStrike
rows$width = rows$width/nDown
rows$depth = coords[,3]
# rows$longitude = coords[,1]
# rows$latitude = coords[,2]
rows$middleRightX = coords[,1]
rows$middleRightY = coords[,2]
# calculate the polygons of the sub faults (divide length by two since we start at the center of the sub fault)
subLength = 0.5 * (row$topRightY - row$bottomRightY) / nStrike
subWidth = (row$topRightX - row$topLeftX) / nDown
rows$topRightX = rows$middleRightX
rows$bottomRightX = rows$middleRightX
rows$topLeftX = rows$middleRightX - subWidth
rows$bottomLeftX = rows$middleRightX - subWidth
rows$bottomMiddleX = rows$middleRightX - 0.5 * subWidth
rows$topMiddleX = rows$middleRightX - 0.5 * subWidth
rows$topRightY = rows$middleRightY + subLength
rows$bottomRightY = rows$middleRightY - subLength
rows$topLeftY = rows$middleRightY + subLength
rows$bottomLeftY = rows$middleRightY - subLength
rows$bottomMiddleY = rows$middleRightY - subLength
rows$topMiddleY = rows$middleRightY + subLength
return(rows)
}
# compute_subfault_distances(fault):
# modified from https://github.com/rjleveque/KLslip-paper/blob/master/KL2d_figures.py
# Estimate the distance between subfaults i and j for every pair in the data frame
# fault. Distances are calculated in kilometers rather than in meters as in the python script.
# :Inputs:
# - *fault* of class dtopotools.Fault or some subclass,
#
# :Outputs:
# - *D* array of Euclidean distances based on longitudes, latitudes, and depths
# - *Dstrike* array of estimated distances along strike direction
# - *Ddip* array of estimated distances along dip direction
# with D**2 = Dstrike**2 + Ddip**2 to within roundoff.
# For each array, the [i,j] entry is distance from subfault i to j when
# ordered in the order the subfaults appear in the list fault.subfaults.
# Distance in dip direction based on differences in depth.
compute_subfault_distances = function(fault) {
rad = pi/180. # conversion factor from degrees to radians
rr = 6.378e6 # radius of earth
lat2meter = rr*rad # conversion factor from degrees latitude to meters
nsubfaults = nrow(fault)
D = matrix(nrow=nsubfaults, ncol=nsubfaults)
Dstrike2 = matrix(nrow=nsubfaults, ncol=nsubfaults)
Ddip = matrix(nrow=nsubfaults, ncol=nsubfaults)
for(i in 1:nsubfaults) {
xi = fault$longitude[i]
yi = fault$latitude[i]
zi = fault$depth[i]
for(j in 1:nsubfaults) {
xj = fault$longitude[j]
yj = fault$latitude[j]
zj = fault$depth[j]
dx = abs(xi-xj)*cos(0.5*(yi+yj)*pi/180.) * lat2meter
dy = abs(yi-yj) * lat2meter
dz = abs(zi-zj)
# Euclidean distance:
D[i,j] = sqrt(dx**2 + dy**2 + dz**2)
# estimate distance down-dip based on depths:
dip = 0.5*(fault$dip[i] + fault$dip[j])
ddip1 = dz / sin(dip*pi/180.)
Ddip[i,j] = ddip1
# compute distance in strike direction to sum up properly:
Dstrike2[i,j] = D[i,j]**2 - Ddip[i,j]**2
}
}
Dstrike2[Dstrike2 < 0] = 0
# return the results, converted from meters to kilometers
list(D=D / 1000,Dstrike=sqrt(Dstrike2) / 1000,Ddip=Ddip / 1000)
}
# same as compute_subfault_distances, but for the gps data. In order to
# estimate the distance down dip for each of these points, we project them
# onto the fall geometry
compute_dip_strike_distance_gps = function(gpsDat, fault) {
rad = pi/180. # conversion factor from degrees to radians
rr = 6.378e6 # radius of earth
lat2meter = rr*rad # conversion factor from degrees latitude to meters
# calculate gps dips
faultIndices = getFaultIndexFromGps(gpsDat, fault)
gpsDips = fault$dip[faultIndices]
npoints = nrow(gpsDat)
D = matrix(nrow=npoints, ncol=npoints)
Dstrike2 = matrix(nrow=npoints, ncol=npoints)
Ddip = matrix(nrow=npoints, ncol=npoints)
for(i in 1:npoints) {
xi = gpsDat$lon[i]
yi = gpsDat$lat[i]
zi = gpsDat$Depth[i]
for(j in 1:npoints) {
xj = gpsDat$lon[j]
yj = gpsDat$lat[j]
zj = gpsDat$Depth[j]
dx = abs(xi-xj)*cos(0.5*(yi+yj)*pi/180.) * lat2meter
dy = abs(yi-yj) * lat2meter
dz = abs(zi-zj)
# Euclidean distance:
D[i,j] = sqrt(dx**2 + dy**2 + dz**2)
# estimate distance down-dip based on depths:
dip = 0.5*(gpsDips[i] + gpsDips[j])
ddip1 = dz / sin(dip*pi/180.)
Ddip[i,j] = ddip1
# compute distance in strike direction to sum up properly:
Dstrike2[i,j] = D[i,j]**2 - Ddip[i,j]**2
}
}
Dstrike2[Dstrike2 < 0] = 0
# return the results, converted from meters to kilometers
list(D=D / 1000,Dstrike=sqrt(Dstrike2) / 1000,Ddip=Ddip / 1000)
}
# for any given point over the given fault geometry, return the index
# of the row of default data table corresponding to the part of the fault
# that the point is over.
getFaultIndexFromGps = function(gpsDat=slipDatCSZ, faultGeom=csz) {
# helper function for determining if GPS observations are within a specific subfault geometry
getSubfaultGPSDat = function(i) {
row = faultGeom[i,]
geom = calcGeom(row)
corners = geom$corners[,1:2]
in.poly(cbind(gpsDat$lon, gpsDat$lat), corners)
}
gpsInSubFault = sapply(1:nrow(faultGeom), getSubfaultGPSDat)
apply(gpsInSubFault, 1, function(x) {match(TRUE, x)})
}
# get table with lon, lat, and depth coords for each subfault
# when type == "centers":
# when index=2, this gives the center of the subfaults. index = 1
# corresponds to the top-center, and index=3 corresponds to the
# bottom center
# when type == "corners":
# index == 1, ..., 4 corresponds to the top left corner to the bottom left corner
# in the clockwise direction
getFaultCenters = function(rows, index=2, type=c("centers", "corners")) {
type = match.arg(type)
t(apply(rows, 1, getSubfaultCenter, index=index, type=type))
}
getSubfaultCenter = function(row, index=2, type=c("centers", "corners")) {
type = match.arg(type)
if(!is.list(row))
row = as.list(row)
geom = calcGeom(row)
pts = geom[[type]]
return(pts[index,])
}
getFaultPolygons = function(fault=csz, faultCornerTable=NULL) {
if(length(unique(fault$Fault)) != length(fault$Fault)) {
fault$Fault = 1:nrow(fault)
}
calcSubfaultPolygon = function(subfault) {
tmp = subfault
if(!is.list(subfault)) {
tmp = matrix(subfault, ncol=length(subfault))
colnames(tmp) = names(subfault)
tmp = data.frame(tmp)
}
subfault = tmp
if(is.null(faultCornerTable))
subFaultPoly = calcGeom(subfault)$corners[,1:2]
else
subFaultPoly = rbind(c(subfault$topLeftX, subfault$topLeftY),
c(subfault$topRightX, subfault$topRightY),
c(subfault$bottomRightX, subfault$bottomRightY),
c(subfault$bottomLeftX, subfault$bottomLeftY))
return(cbind(subfault$Fault, subFaultPoly))
}
# faultPolys = apply(fault, 1, calcSubfaultPolygon)
subfaultList = list()
for(i in 1:nrow(fault)) {
subfaultList = c(subfaultList, list(fault[i,]))
}
faultPolys = lapply(subfaultList, calcSubfaultPolygon)
faultPolys = do.call("rbind", faultPolys)
faultPolys = data.frame(list(Fault=faultPolys[,1], longitude=faultPolys[,2], latitude=faultPolys[,3]))
return(faultPolys)
}
##### now make ggplot fault plotters
# plot all subfaults in the fault using ggplot. Don't add data, returns the geom_polygon object
ggPlotFault = function(fault=csz, color="black") {
faultPolys = getFaultPolygons(fault)
geom_polygon(aes(x=longitude, y=latitude, group=factor(Fault)), data=faultPolys,
fill=rgb(1,1,1, 0), color=color)
}
ggPlotFaultDat = function(rows, plotVar="depth", varRange=NULL, plotData=TRUE,
logScale=FALSE, xlim=c(-128, -122), ylim=c(39.5, 50.5),
xlab=NULL, ylab=NULL, main="Cascadia Subduction Zone",
clab="Depth (m)", addLegend=plotData, lwd=1,
xName="longitude", yName="latitude",
projection=NULL, parameters=NULL, orientation=NULL,
scale=1, roundDigits=2, coordsAlreadyScaled=FALSE) {
if(is.null(orientation) && !is.null(projection)) {
warning("no orientation specified, so projection being set to the last used projection")
projection = ""
parameters = NULL
}
# get relevant map data
if(!is.null(projection)) {
states <- map_data("state", projection=projection, parameters=parameters, orientation=orientation)
west_coast <- subset(states, region %in% c("california", "oregon", "washington"))
canada = map_data("world", "Canada", projection=projection, parameters=parameters, orientation=orientation)
} else {
states <- map_data("state")
west_coast <- subset(states, region %in% c("california", "oregon", "washington"))
canada = map_data("world", "Canada")
}
# set some reasonable plotting parameters
if(is.null(projection)) {
xlab = "Longitude"
ylab = "Latitude"
} else {
xlab = "Easting (km)"
ylab = "Northing (km)"
}
if(!is.data.frame(rows))
rows = data.frame(rows)
# rename row$Fault so that each fault gets unique name
rows$Fault=1:nrow(rows)
# if the user supplies a variable to plot in plotVar:
if(!is.character(plotVar)) {
rows$tmp = plotVar
plotVar = "tmp"
}
#
if("topRightX" %in% names(rows))
faultCornerTable = rows[,9:ncol(rows)]
else
faultCornerTable = NULL
# make fault polygons
faultDat = getFaultPolygons(rows, faultCornerTable=faultCornerTable)
faultDat = merge(faultDat, rows[,c("Fault", plotVar)], by=c("Fault"))
faultDat$plotVar=faultDat[,plotVar]
# rescale coordinates of the faulty geometry if necessary
if(coordsAlreadyScaled) {
faultDat$longitude = faultDat$longitude / scale
faultDat$latitude = faultDat$latitude / scale
}
# set x and y limits if necessary
if(is.null(xlim) && is.null(ylim)) {
xlim=c(-128, -122)
ylim=c(39.5, 50.5)
proj<- mapproject(xlim, ylim) # if projection unspecified, last projection is used
xlim = proj$x
ylim = proj$y
xScale = scale_x_continuous(xlab, c(-.02, 0, .02, .04), labels=as.character(round(scale*c(-.02, 0, .02, .04), digits=roundDigits)), limits=c(-360, 360))
yScale = scale_y_continuous(ylab, seq(-.74, -.60, by=.02), labels=as.character(round(scale*seq(-.74, -.60, by=.02), digits=roundDigits)), limits=c(-360, 360))
} else if(is.null(xlim)) {
xlim = range(c(rows[[xName]], faultDat$longitude))
} else if(is.null(ylim)) {
ylim = range(c(rows[[yName]], faultDat$latitude))
} else {
xScale = scale_x_continuous(xlab, c(-127, -125, -123), labels=c("-127", "", "-123"), limits=c(-360, 360))
}
# grey maps plot:
if(identical(projection, "")) {
bg = ggplot(faultDat, aes(x=longitude, y=latitude)) +
geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=canada) +
geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=west_coast) +
coord_fixed(xlim = xlim, ylim = ylim, expand=FALSE) +
labs(x=xlab, y=ylab) + xScale + yScale +
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill='lightblue1'))
} else {
bg = ggplot(faultDat, aes(x=longitude, y=latitude)) +
geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=canada) +
geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=west_coast) +
coord_fixed(xlim = xlim, ylim = ylim, ratio = 1.3, expand=FALSE) +
labs(x=xlab, y=ylab) + xScale +
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill='lightblue1'))
}
# generate fault polygons portion of plot
if(!plotData) {
# faultPoly = ggPlotFault(rows, color=rgb(.2,.2,.2))
pl = bg + geom_polygon(aes(group=factor(Fault)), color="black", size=lwd, fill=NA)
}
else {
faultPoly = geom_polygon(aes(fill=plotVar, group=factor(Fault)), color="black", size=lwd)
if(is.null(varRange)) {
if(logScale)
pl = bg + faultPoly + scale_fill_distiller(clab, palette = "Spectral", direction=-1, trans="log") +
ggtitle(main)
else
pl = bg + faultPoly + scale_fill_distiller(clab, palette = "Spectral", direction=-1) +
ggtitle(main)
}
else {
if(logScale)
pl = bg + faultPoly + scale_fill_distiller(clab, palette = "Spectral", direction=-1, trans="log",
limits=varRange) +
ggtitle(main)
else
pl = bg + faultPoly + scale_fill_distiller(clab, palette = "Spectral", direction=-1,
limits=varRange) +
ggtitle(main)
}
# ii <- cut(values, breaks = seq(min(values), max(values), len = 100),
# include.lowest = TRUE)
# ## Use bin indices, ii, to select color from vector of n-1 equally spaced colors
# colors <- colorRampPalette(c("lightblue", "blue"))(99)[ii]
# if(logScale)
# faultPoly = faultPoly + scale_fill_manual("", palette = "Spectral", direction=-1, trans="log")
# else
# faultPoly = faultPoly + scale_fill_distiller("", palette = "Spectral", direction=-1)
}
if(addLegend)
pl + guides(color=FALSE)
else
pl + guides(color=FALSE, fill=FALSE)
}
##### now do the same but for the gps data
ggplotGpsData = function(gpsDat, plotVar=gpsDat$Depth, varRange=NULL, plotData=TRUE,
logScale=FALSE, xlim=NULL, ylim=NULL,
xlab="Longitude", ylab="Latitude", main="Cascadia Subduction Zone",
clab="", addLegend=TRUE, lwd=1, includeFault=TRUE,
gpsHull=NULL, xName="lon", yName="lat",
projection=NULL, parameters=NULL, orientation=NULL) {
library(ggmap)
library(ggplot2)
library(scales)
library(RColorBrewer)
library(latex2exp)
### Get a map
# https://mapstyle.withgoogle.com/
# https://console.cloud.google.com/home/dashboard?consoleReturnUrl=https:%2F%2Fcloud.google.com%2Fmaps-platform%2Fterms%2F%3Fapis%3Dmaps%26project%3Dspatialstatisticalmapping&consoleUI=CLOUD&mods=metropolis_maps&project=spatialstatisticalmapping&organizationId=657476903663
# map <- get_map(location = c(lon[1], lat[1], lon[2], lat[2]), zoom = 6,
# maptype = "terrain", source = "google")
# style1=c(feature="administrative", element="labels", visibility="off")
# style2=c("&style=", feature="road", element="geometry", visibility="off")
# style3=c("&style=", feature="poi", element="labels", visibility="off")
# style4=c("&style=", feature="landscape", element="labels", visibility="off")
# style5=c("&style=", feature="administrative", element="geometry.stroke", color="black")
# style6=c("&style=", feature="administrative", element="geometry.stroke", weight=.75)
# api_key = 'AIzaSyAA5-1cW2j6Q0_-xpuWF0YB6alAXkCBsmM' # key to my google account
# map <- get_googlemap(center=c(lon = mean(xlim), lat = mean(ylim)), zoom=5,
# style=c(style1, style2, style3, style4, style5, style6),
# key=api_key)
##### Let's try with greyed out land:
library(maps)
library(mapdata)
# choose color if necessary (lightblue1 or white)
# fields.color.picker()
# get relevant map data
if(is.null(orientation) && !is.null(projection)) {
warning("no orientation specified, so projection being set to the last used projection")
projection = ""
parameters = NULL
}
# get relevant map data
if(!is.null(projection)) {
states <- map_data("state", projection=projection, parameters=parameters, orientation=orientation)
west_coast <- subset(states, region %in% c("california", "oregon", "washington"))
canada = map_data("world", "Canada", projection=projection, parameters=parameters, orientation=orientation)
} else {
states <- map_data("state")
west_coast <- subset(states, region %in% c("california", "oregon", "washington"))
canada = map_data("world", "Canada")
}
# try plotting on an interpolated grid
library(gstat)
library(sp)
library(maptools)
library(RColorBrewer)
# set x and y limits if necessary
if(is.null(xlim) && is.null(ylim)) {
xlim=c(-128, -122)
ylim=c(39.5, 50.5)
proj<- mapproject(xlim, ylim) # if projection unspecified, last projection is used
xlim = proj$x
ylim = proj$y
xScale = scale_x_continuous("Easting", c(-.02, 0, .02, .04), labels=c("-.02", "0", ".02", ".04"), limits=c(-360, 360))
ylab = "Northing"
xlab = "Easting"
} else if(is.null(xlim)) {
xlim = range(gpsDat[[xName]])
} else if(is.null(ylim)) {
ylim = range(gpsDat[[yName]])
} else {
xScale = scale_x_continuous("Longitude", c(-127, -125, -123), labels=c("-127", "", "-123"), limits=c(-360, 360))
}
# plot it (choose background color with fields.color.picker())
# bg = ggplot() +
# geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=canada) +
# geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=west_coast) +
# coord_fixed(xlim = lon, ylim = lat, ratio = 1.3, expand=FALSE) +
# theme(panel.border = element_blank(), panel.grid.major = element_blank(),
# panel.grid.minor = element_blank(),
# panel.background = element_rect(fill='lightblue1')) +
# labs(x="Longitude", y="Latitude")
if(identical(projection, "")) {
bg = ggplot() +
geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=canada) +
geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=west_coast) +
coord_fixed(xlim = xlim, ylim = ylim, ratio = 1.3, expand=FALSE) +
labs(x=xlab, y=ylab) + xScale +
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill='lightblue1'))
} else {
bg = ggplot() +
geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=canada) +
geom_polygon(aes(x = long, y = lat, group = group), fill = "grey", color = "black", data=west_coast) +
coord_fixed(xlim = xlim, ylim = ylim, expand=FALSE) +
labs(x=xlab, y=ylab) + xScale +
theme(panel.border = element_blank(), panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill='lightblue1'))
}
# construct bounding polygon around data:
#make concave hull around prediction mask to get final prediction points
locking30km = gpsDat
if(is.null(gpsHull)) {
source("model1/seaDefAnis.r")
if(identical(projection, "")) {
gpsHull = ahull(locking30km[[xName]], locking30km[[yName]], alpha=.05)
} else {
gpsHull = ahull(locking30km[[xName]], locking30km[[yName]], alpha=2)
}
}
indx=gpsHull$arcs[,"end1"]
hullPts <- cbind(locking30km[[xName]], locking30km[[yName]])[indx,] # extract the boundary points from maskXY
#plot hull and data to make sure it works
# plotSubPoly(rbind(hullPts, hullPts[1,]), cbind(locking30km$lon, locking30km$lat))
# now subset prediction data frame to only be predictions within the polygon from alphahull
library(akima)
# interpolate between observations for maximum purdyness
predGrid = make.surface.grid(list(x=seq(xlim[1], xlim[2], l=500), lat=seq(ylim[1], ylim[2], l=500)))
preds = interpp(locking30km[[xName]], locking30km[[yName]], plotVar, predGrid[,1], predGrid[,2])
maskFinalPreds = in.poly(cbind(preds$x, preds$y), hullPts, convex.hull=FALSE)
preds = data.frame(preds)
finalPreds = preds[maskFinalPreds,]
if(identical(projection, "")) {
p1 = bg + geom_tile(data = finalPreds, aes(x = x, y = y, fill = z)) +
scale_fill_distiller(clab, palette = "Spectral", direction=-1) +
geom_point(aes(x=x, y=y), pch=20, col="black", size=.1, data=locking30km) +
ggtitle(main) +
geom_polygon(aes(x = long, y = lat, group = group), fill = rgb(0,0,0,0), color = "black", data=canada) +
geom_polygon(aes(x = long, y = lat, group = group), fill = rgb(0,0,0,0), color = "black", data=west_coast)
} else {