-
Notifications
You must be signed in to change notification settings - Fork 14
/
prs.py
2345 lines (1928 loc) · 73.5 KB
/
prs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2022 Wasja Bloch, Pascal Audet
# This file is part of PyRaysum.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import re
import numpy as np
import re
from datetime import datetime
import numpy as np
import matplotlib.pyplot as plt
from obspy import Stream
from numpy.fft import fft, ifft, fftshift
from copy import deepcopy
import fraysum
from pyraysum import plot
from pyraysum.frs import read_arrivals, read_traces, _phnames
_alignn = {0: "none", 1: "P", 2: "SV", 3: "SH"} # alignment name
_aligni = {_alignn[k]: k for k in _alignn} # alignment ID
_rotn = {0: "ZNE", 1: "RTZ", 2: "PVH"} # rotation name
_roti = {_rotn[k]: k for k in _rotn} # rotation ID
_iphase = {"P": 1, "SV": 2, "SH": 3}
_phids = {_phnames[k]: k for k in _phnames} # inverse dictionary, imported in core
_modhint = (
"################################################\n"
"#\n"
"# Model file to use with `PyRaysum` for \n"
"# modeling teleseismic body wave propagation \n"
"# through dippin anisotropic media.\n"
"#\n"
"# Lines starting with '#' are ignored. Each \n"
"# line corresponds to a unique layer. The \n"
"# bottom layer is assumed to be a half-space\n"
"# (Thickness is irrelevant).\n"
"#\n"
"# Format:\n"
"# Column Contents\n"
"# 0 Thickness (km)\n"
"# 1 Density (kg/m^3)\n"
"# 2 Layer P-wave velocity (km/s)\n"
"# 3 Layer S-wave velocity (km/s)\n"
"# 4 Layer flag \n"
"# 1: isotropic\n"
"# 0: transverse isotropy\n"
"# 5 % Transverse anisotropy (if Layer flag is set to 0)\n"
"# 0: isotropic\n"
"# +: fast symmetry axis\n"
"# -: slow symmetry axis\n"
"# 6 Trend of symmetry axis (degrees)\n"
"# 7 Plunge of symmetry axis (degrees)\n"
"# 8 Interface strike (degrees)\n"
"# 9 Interface dip (degrees)\n"
"#\n"
"################################################\n"
)
class Model(object):
"""Model of the subsurface seismic velocity structure.
.. note::
This object holds the infromation of the .mod file in classic Raysum
Parameters:
thickn (array_like):
Thickness of layers (m)
rho (float or array_like):
Density (kg/m^3)
vp (float or array_like):
P-wave velocity (m/s)
vs (float or array_like, optional):
S-wave velocity (m/s)
If None, computed from :const:`vpvs`
flag (array_like of str, optional):
:const:`1` for isotropic, :const:`0` for anisotropic
ani (float or array_like, optional):
Anisotropy (percent)
trend (float or array_like, optional):
Trend of symmetry axis (degree)
plunge (float or array_like, optional):
Plunge of symmetry axis (degree)
strike (float or array_like, optional):
azimuth of interface in RHR (degree clockwise from north)
dip (float or array_like, optional):
dip of interface in RHR (degree down from horizontal)
vpvs (float or array_like, optional):
P-to-S velocity ratio.
Defaults to 1.73. Ignored if :const:`vs` is set.
maxlay (int):
Maximum number of layers defined in params.h
Warning:
When setting `vpvs`, `vs` is adjusted to satisfy vs = vp / vpvs.
The following attributes are set upon initialization, when setting a layer property
via :meth:`Model.__setitem__()` (i.e. :attr:`model[0]` or :attr:`model[0,
"thickn"]`), and when execuding :meth:`Model.update()` after setting a single
element of the above model attributes. `f` prefixes indicate attributes used for
interaction with `fraysum.run_bare()` and `fraysum.run_full()`. Set these directly
for best performance.
nlay
Number of layers
parameters
Convenience attribute that collects the `f`-attributes in the order expected
by `fraysum.run_bare()` and `fraysum.run_full()`
fthickn
Thickness of layers (m)
frho
Density (kg/m^3)
fvp
P-wave velocity (m/s)
fvs
S-wave velocity (m/s)
fflag
Flag indicating isotropy (1) or anisotropy (0) of layer material
fani
Anisotropy (percent)
ftrend
Trend of symmetry axis (radians)
fplunge
Plunge of symmetry axis (radians)
fstrike
azimuth of interface in RHR (radians)
fdip
dip of interface in RHR (radians)
Example
-------
>>> from pyraysum import Model
>>> model = Model([10000, 0], [3000, 4500], [6000, 8000], [3500, 4600])
>>> print(model)
# thickn rho vp vs flag aniso trend plunge strike dip
10000.0 3000.0 6000.0 3500.0 1 0.0 0.0 0.0 0.0 0.0
0.0 4500.0 8000.0 4600.0 1 0.0 0.0 0.0 0.0 0.0
>>> model[0]["thickn"]
10000.0
>>> model.thickn[0]
10000.0
>>> model.thickn[0] = 15000 # model.fthickn has not yet changed
>>> model.update() # Now everything works as expected
>>> model.fthickn[0]
15000.0
>>> model[1, "vp"]
8000.0
>>> model[1, "vp"] = 9000. # Does not require model.update()
>>> model[1, "vp"]
9000.0
>>> model["vp", 1] = 7400. # Indices can be swapped
>>> model["vp", 1]
7400.0
>>> model[1] = {"vs": 4200., "rho": 4000.}
>>> model[1]["vs"]
4200.0
>>> model[1, "rho"]
4000.0
>>> model[1] = {"thickn": 5000, "vp": 8000., "vpvs": 2.}
>>> model[1]["vs"]
4000.0
>>> model += [5000, 3600, 8000, 4000] # thickn, rho, vp, vs
>>> print(model)
# thickn rho vp vs flag aniso trend plunge strike dip
15000.0 3000.0 6000.0 3500.0 1 0.0 0.0 0.0 0.0 0.0
5000.0 4000.0 8000.0 4000.0 1 0.0 0.0 0.0 0.0 0.0
5000.0 3600.0 8000.0 4000.0 1 0.0 0.0 0.0 0.0 0.0
>>> model += {"thickn": 0, "rho": 3800, "vp": 8500., "dip": 20, "strike": 90}
>>> print(model)
# thickn rho vp vs flag aniso trend plunge strike dip
15000.0 3000.0 6000.0 3500.0 1 0.0 0.0 0.0 0.0 0.0
5000.0 4000.0 8000.0 4000.0 1 0.0 0.0 0.0 0.0 0.0
5000.0 3600.0 8000.0 4000.0 1 0.0 0.0 0.0 0.0 0.0
0.0 3800.0 8500.0 4913.3 1 0.0 0.0 0.0 90.0 20.0
"""
def __init__(
self,
thickn,
rho,
vp,
vs=None,
flag=1,
ani=None,
trend=None,
plunge=None,
strike=None,
dip=None,
vpvs=1.73,
maxlay=15,
):
def _array(v):
if v is not None:
return np.array(
[v] * self.nlay if isinstance(v, (int, float)) else v, dtype=float
)
else:
return np.array([0.0] * self.nlay)
try:
self.nlay = len(thickn)
except TypeError:
self.nlay = 1
self._thickn = _array(thickn)
self._rho = _array(rho)
self._vp = _array(vp)
if vs is None:
self._vpvs = _array(vpvs)
self._vs = self._vp / self._vpvs
else:
self._vs = _array(vs)
self._vpvs = self._vp / self._vs
self._flag = np.array(
[flag] * self.nlay if isinstance(flag, int) else list(flag)
)
self._ani = _array(ani)
self._trend = _array(trend)
self._plunge = _array(plunge)
self._strike = _array(strike)
self._dip = _array(dip)
self.maxlay = maxlay
self.properties = [
"thickn",
"rho",
"vp",
"vs",
"vpvs",
"flag",
"ani",
"trend",
"plunge",
"strike",
"dip",
]
self._properties = ["_" + prop for prop in self.properties]
self._set_fattributes()
self._set_layers()
@property
def thickn(self):
return self._thickn
@thickn.setter
def thickn(self, value):
self._thickn = value
self._set_fattributes()
self._set_layers()
@property
def rho(self):
return self._rho
@rho.setter
def rho(self, value):
self._rho = value
self._set_fattributes()
self._set_layers()
@property
def vp(self):
return self._vp
@vp.setter
def vp(self, value):
self._vp = value
self._set_fattributes()
self._set_layers()
@property
def vpvs(self):
return self._vpvs
@vpvs.setter
def vpvs(self, value):
self._vpvs = value
self._set_fattributes()
self._set_layers()
self.update("vs")
@property
def vs(self):
return self._vs
@vs.setter
def vs(self, value):
self._vs = value
self._set_fattributes()
self._set_layers()
@property
def flag(self):
return self._flag
@flag.setter
def flag(self, value):
self._flag = value
self._set_fattributes()
self._set_layers()
@property
def ani(self):
return self._ani
@ani.setter
def ani(self, value):
self._ani = value
self._set_fattributes()
self._set_layers()
@property
def trend(self):
return self._trend
@trend.setter
def trend(self, value):
self._trend = value
self._set_fattributes()
self._set_layers()
@property
def plunge(self):
return self._plunge
@plunge.setter
def plunge(self, value):
self._plunge = value
self._set_fattributes()
self._set_layers()
@property
def strike(self):
return self._strike
@strike.setter
def strike(self, value):
self._strike = value
self._set_fattributes()
self._set_layers()
@property
def dip(self):
return self._dip
@dip.setter
def dip(self, value):
self._dip = value
self._set_fattributes()
self._set_layers()
def __getitem__(self, ilay):
"""Get a layer or property of the model"""
try:
if isinstance(ilay[0], int) and isinstance(ilay[1], str):
# model[0, "thickn"]
return self.layers[ilay[0]][ilay[1]]
if isinstance(ilay[1], int) and isinstance(ilay[0], str):
# model["thickn", 0]
return self.layers[ilay[1]][ilay[0]]
except TypeError:
try:
# model[0]
return self.layers[ilay]
except TypeError:
# model["thickn"]
return np.array([lay[ilay] for lay in self.layers])
def __setitem__(self, layatt, value):
"""Set a layer or property of the model"""
lays = []
atts = []
vals = []
try:
# model[0] = {"plunge": 10} syntax
# layatt is layer and value is {"att": value}
atts = value.keys()
for att in atts:
vals.append(value[att])
lays = [layatt] * len(vals)
except AttributeError:
# model[0, "plunge"] = 10 syntax
# layatt[0] is layer, layatt[1] is attribute, value is value
if isinstance(layatt[1], str) and isinstance(layatt[0], int):
lays = [layatt[0]]
atts = [layatt[1]]
elif isinstance(layatt[0], str) and isinstance(layatt[1], int):
lays = [layatt[1]]
atts = [layatt[0]]
else:
msg = "Cannot set model layer attribute: {:}".format(layatt)
raise ValueError(msg)
vals = [value]
for lay, att, val in zip(lays, atts, vals):
if att not in self.properties:
msg = f"Unknown attribute: '{att}'. Must be one of: "
msg += ", ".join(self.properties)
raise ValueError(msg)
self.__dict__["_" + att][lay] = val
if att == "ani" and val != 0:
self.__dict__["_flag"][lay] = 0
if att == "ani" and val == 0:
self.__dict__["_flag"][lay] = 1
if att == "vpvs":
self.update(change="vs")
else:
self.update()
def __len__(self):
return self.nlay
def __str__(self):
buf = "# thickn rho vp vs flag aniso trend "
buf += "plunge strike dip\n"
f = "{: 9.1f} {: 7.1f} {: 7.1f} {: 7.1f} {: 4.0f} {: 6.1f} {: 7.1f} "
f += "{: 6.1f} {: 6.1f} {: 5.1f}\n"
for th, vp, vs, r, fl, a, tr, p, s, d in zip(
self._thickn,
self._vp,
self._vs,
self._rho,
self._flag,
self._ani,
self._trend,
self._plunge,
self._strike,
self._dip,
):
buf += f.format(th, r, vp, vs, fl, a, tr, p, s, d)
return buf.strip("\n")
def __add__(self, other):
if not isinstance(other, Model):
try:
other = Model(**other)
except TypeError:
other = Model(*other)
except Exception:
msg = "Can only add Model, or valid dict or list to Model."
raise TypeError(msg)
third = deepcopy(self)
for att in third._properties:
third.__dict__[att] = np.append(self.__dict__[att], other.__dict__[att])
third.nlay += other.nlay
third._set_fattributes()
third._set_layers()
return third
def __eq__(self, other):
issame = [
slay[att] == olay[att]
for slay, olay in zip(self.layers, other.layers)
for att in self.properties
]
return all(issame)
def _set_layers(self):
self.layers = [
{
prop: self.__dict__[_prop][lay]
for prop, _prop in zip(self.properties, self._properties)
}
for lay in range(self.nlay)
]
def _set_fattributes(self):
if self.nlay > self.maxlay:
msg = f"The object is larger (nlay={self.nlay}) than the memory allocated "
msg += f"at compile time (maxlay={self.maxlay}). "
msg += (
f"Increase maxlay in params.h and when constucting this Model object."
)
raise IndexError(msg)
tail = np.zeros(self.maxlay - self.nlay)
self.fthickn = np.asfortranarray(np.append(self._thickn, tail))
self.frho = np.asfortranarray(np.append(self._rho, tail))
self.fvp = np.asfortranarray(np.append(self._vp, tail))
self.fvs = np.asfortranarray(np.append(self._vs, tail))
self.fflag = np.asfortranarray(np.append(self._flag, tail))
self.fani = np.asfortranarray(np.append(self._ani, tail))
self.ftrend = np.asfortranarray(np.append(self._trend, tail) * np.pi / 180)
self.fplunge = np.asfortranarray(np.append(self._plunge, tail) * np.pi / 180)
self.fstrike = np.asfortranarray(np.append(self._strike, tail) * np.pi / 180)
self.fdip = np.asfortranarray(np.append(self._dip, tail) * np.pi / 180)
self.parameters = [
self.fthickn,
self.frho,
self.fvp,
self.fvs,
self.fflag,
self.fani,
self.ftrend,
self.fplunge,
self.fstrike,
self.fdip,
self.nlay,
]
def _v12str(self):
"""Legacy Raysum .mod file convention"""
buf = "# thickn rho vp vs flag p-aniso s-aniso trend "
buf += "plunge strike dip\n"
f = "{: 9.1f} {: 7.1f} {: 7.1f} {: 7.1f} {: 4.0f} {: 8.1f} {: 8.1f} {: 7.1f} "
f += "{: 6.1f} {: 6.1f} {: 5.1f}\n"
for th, vp, vs, r, fl, a, tr, p, s, d in zip(
self._thickn,
self._vp,
self._vs,
self._rho,
self._flag,
self._ani,
self._trend,
self._plunge,
self._strike,
self._dip,
):
buf += f.format(th, r, vp, vs, fl, a, a, tr, p, s, d)
return buf.strip("\n")
def update(self, change="vpvs"):
"""
Update all attributes after one of them was changed.
Parameters:
change (str):
Decide which of :py:attr:`vp`, :py:attr:`vs` or :py:attr:`vpvs` should
depend on the other two:
* `'vpvs'`: Calculate :py:attr:`vpvs` from `vpvs = vp / vs`
* `'vp'`: Calculate :py:attr:`vp` from `vp = vs * vpvs`
* `'vs'`: Calculate :py:attr:`vs` from `vs = vp / vpvs`
Returns:
None
"""
if change == "vp":
self._vp = self._vs * self._vpvs
elif change == "vs":
self._vs = self._vp / self._vpvs
elif change == "vpvs":
self._vpvs = self._vp / self._vs
else:
msg = "Unknown value for keyword: " + change
raise ValueError(msg)
self._set_fattributes()
self._set_layers()
def copy(self):
"""Return a copy of the model"""
return deepcopy(self)
def change(self, command, verbose=True):
"""
Change layer properties using a command string.
Args:
command (str):
An arbitrary number of command substrings separated by ';'
verbose (bool):
Print changed parameters to screen
Returns:
list of 3*tuple:
List of changes applied of the form:
(attribute, layer, new value)
Note:
In the :data:`command` argument, each substring has the form:
KEY LAYER SIGN VAL;
where
KEY [t|vp|vs|psp|pss|s|d|a|tr|pl] is the attribute to change
* t: thickness (km)
* vp: P wave velocity (km/s)
* vs: S wave velocity (km/s)
* psp: P to S wave velocity ratio with fixed vs (changing vp)
* pss: P to S wave velocity ratio with fixed vp (changing vs)
* s: strike (degree)
* d: dip (degree)
* a: anisotropy (%)
* tr: trend of the anisotropy axis (degree)
* pl: plunge ot the anisotropy axis (degree)
LAYER (int) is the index of the layer
SIGN [=|+|-] is to set / increase / decrease the attribute
VAL (float) is the value to set / increase / decrease
Hint:
For example, ``Model.change('t0+10;psp0-0.2;d1+5;s1=45')`` does:
1. Increase the thickness of the first layer by 10 km
2. Decrease Vp/Vs of the of the first layer by 0.2, holding Vs
fixed
3. Increase the dip of the second layer by 5 degree
4. Set the strike of the second layer to 45 degree
"""
ATT = {
"t": "thickn",
"thickn": "thickn",
"vp": "vp",
"vs": "vs",
"psp": "vpvs",
"pss": "vpvs",
"s": "strike",
"strike": "strike",
"d": "dip",
"dip": "dip",
"a": "ani",
"ani": "ani",
"tr": "trend",
"trend": "trend",
"pl": "plunge",
"plunge": "plunge",
}
_ATT = {key: "_" + val for key, val in zip(ATT.keys(), ATT.values())}
changed = []
for com in command.split(";"):
com = com.strip()
if not com:
continue
# split by sign
for sign in "=+-":
ans = com.split(sign, maxsplit=1)
if len(ans) == 2:
break
(attlay, val) = ans
# Split attribute and layer
for n, char in enumerate(attlay):
if char in "0123456789":
break
att = attlay[:n]
lay = int(attlay[n:])
val = float(val)
# convert thicknes and velocities from kilometers
if att in ["t", "vp", "vs"]:
val *= 1000
# Which velocity to fix
change = "vpvs"
if att == "pss":
change = "vs"
if att == "psp":
change = "vp"
attribute = ATT[att]
_attribute = _ATT[att]
# Apply
if sign == "=":
self.__dict__[_attribute][lay] = val
sign = "" # to print nicely below
elif sign == "+":
self.__dict__[_attribute][lay] += val
elif sign == "-":
self.__dict__[_attribute][lay] -= val
# Set isotropy flag iff layer is isotropic
self._flag[lay] = 1
if self._ani[lay] != 0:
self._flag[lay] = 0
self.update(change=change)
changed.append((attribute, lay, self.__dict__[_attribute][lay]))
if verbose:
msg = "Changed: {:}[{:d}] {:}= {:}".format(attribute, lay, sign, val)
print(msg)
return changed
def split_layer(self, n):
"""
Split layer `n` into two with half the thickness each, but otherwise
identical parameters.
Args:
n : (int)
Index of the layer to split
"""
for att in self._properties:
self.__dict__[att] = np.insert(self.__dict__[att], n, self.__dict__[att][n])
self._thickn[n] /= 2
self._thickn[n + 1] /= 2
self.nlay += 1
self.update()
def remove_layer(self, n):
"""
Remove layer `n`
Args:
n (int):
Index of the layer to remove
"""
for att in self._properties:
self.__dict__[att] = np.delete(self.__dict__[att], n)
self.nlay -= 1
self.update()
def average_layers(self, top, bottom):
"""
Combine layers between top and bottom indices into one with summed
thicknesses and averaged vp, vs, and rho.
Args:
top (int):
Index before top-most layer to include in combination
bottom (int):
Index after bottom-most layer to include in combination
Raises:
IndexError: if bottom is less or equal to top
ValueError: if any layer is anisotropic
ValueError: if any layer has a difference in strike or dip
"""
if bottom <= top:
raise IndexError("bottom must be larger than top.")
if not all(self._flag[top:bottom]):
raise ValueError("Can only combine isotropic layers")
if not all(self._dip[top:bottom][0] == self._dip[top:bottom]):
raise ValueError("All layers must have the same dip")
if not all(self._strike[top:bottom][0] == self._strike[top:bottom]):
raise ValueError("All layers must have the same strike")
thickn = sum(self._thickn[top:bottom])
weights = self._thickn[top:bottom] / thickn
layer = {
"_thickn": thickn,
"_vp": sum(self._vp[top:bottom] * weights),
"_vs": sum(self._vs[top:bottom] * weights),
"_rho": sum(self._rho[top:bottom] * weights),
}
for att in self._properties:
try:
self.__dict__[att][top] = layer[att]
except KeyError:
pass
self.__dict__[att] = np.delete(self.__dict__[att], range(top + 1, bottom))
self.nlay -= bottom - top - 1
self.update()
def save(self, fname="sample.mod", comment="", hint=False, version="prs"):
"""
Alias for :class:`write()`
"""
self.write(fname=fname, comment=comment, hint=hint, version=version)
def write(self, fname="sample.mod", comment="", hint=False, version="prs"):
"""
Write seismic velocity model to disk as Raysum ASCII model file
Args:
fname (str): Name of the output file (including extension)
comment (str): String to write into file header
hint (bool): Include usage comment to model file
version ("prs" or "raysum"): Use PyRaysum or Raysum file format
"""
if not comment.startswith("#"):
comment = "# " + comment
if not comment.endswith("\n"):
comment += "\n"
if not isinstance(fname, str):
print("Warning: filename reverts to default 'sample.mod'")
fname = "sample.mod"
buf = "# Raysum velocity model created with PyRaysum\n"
buf += "# on: {:}\n".format(datetime.now().isoformat(" ", "seconds"))
if hint:
buf += _modhint
buf += comment
if version == "prs":
buf += self.__str__()
elif version == "raysum":
buf += self._v12str()
else:
msg = f"Unknown version: {version}"
raise ValueError(msg)
with open(fname, "w") as fil:
fil.write(buf)
def plot(self, zmax=75.0):
"""
Plot model as stair case, layers and labeled interfaces, and show it
Args:
zmax (float): Maximum depth of model to plot (km)
"""
# Initialize new figure
fig = plt.figure(figsize=(10, 5))
# Add subplot for profile
ax1 = fig.add_subplot(1, 4, 1)
self.plot_profile(zmax=zmax, ax=ax1)
# Add subplot for layers
ax2 = fig.add_subplot(1, 4, 2)
self.plot_layers(zmax=zmax, ax=ax2)
ax3 = fig.add_subplot(1, 4, (3, 4))
self.plot_interfaces(zmax=zmax, ax=ax3)
# Tighten the plot and show it
# TODO: tight layout does not work with colorbar.
# Do this manually.
# plt.tight_layout()
plt.show()
def plot_profile(self, zmax=75.0, ax=None):
"""
Plot model as stair case and show it
Args:
zmax (float):
Maximum depth of model to plot (km)
ax (plt.axis):
Axis handle for plotting. If ``None``, show the plot
Returns:
plt.axis:
Axis handle for plotting
"""
# Defaults to not show the plot
show = False
# Find depths of all interfaces in km
thickn = self._thickn.copy()
if thickn[-1] == 0.0:
thickn[-1] = 50000.0
depths = np.concatenate(([0.0], np.cumsum(thickn))) / 1000.0
# Get corner coordinates of staircase representation of model
depth = np.array(list(zip(depths[:-1], depths[1:]))).flatten()
vs = np.array(list(zip(self._vs, self._vs))).flatten()
vp = np.array(list(zip(self._vp, self._vp))).flatten()
rho = np.array(list(zip(self._rho, self._rho))).flatten()
ani = np.array(list(zip(self._ani, self._ani))).flatten()
# Generate new plot if an Axis is not passed
if ax is None:
fig = plt.figure(figsize=(5, 5))
ax = fig.add_subplot(111)
show = True
# Plot background model
ax.plot(vs, depth, color="C0", label=r"Vs (m s$^{-1}$)")
ax.plot(vp, depth, color="C1", label=r"Vp (m s$^{-1}$)")
ax.plot(rho, depth, color="C2", label=r"Density (kg m$^{-3}$)")
# If there is anisotropy, show variability
if np.any([flag == 0 for flag in self._flag]):
ax.plot(vs * (1.0 - ani / 100.0), depth, "--", color="C0")
ax.plot(vs * (1.0 + ani / 100.0), depth, "--", color="C0")
ax.plot(vp * (1.0 - ani / 100.0), depth, "--", color="C1")
ax.plot(vp * (1.0 + ani / 100.0), depth, "--", color="C1")
# Fix axes and add labels
ax.legend(fontsize=8)
ax.set_xlabel("Velocity or Density")
ax.set_ylabel("Depth (km)")
ax.set_ylim(0.0, zmax)
ax.invert_yaxis()
ax.grid(ls=":")
if show:
plt.show()
return ax
def plot_layers(self, zmax=75.0, ax=None):
"""
Plot model as horizontal layers and show it
Args:
zmax (float):
Maximum depth of model to plot (km)
ax (plt.axis):
Axis handle for plotting. If ``None``, show the plot
Returns:
plt.axis:
Axis handle for plotting
"""
# Defaults to not show the plot
show = False
# Find depths of all interfaces
thickn = self._thickn.copy()
if thickn[-1] == 0.0:
thickn[-1] = 50000.0
depths = np.concatenate(([0.0], np.cumsum(thickn))) / 1000.0
# Generate new plot if an Axis is not passed
if ax is None:
fig = plt.figure(figsize=(2, 5))
ax = fig.add_subplot(111)
show = True
else:
fig = ax.get_figure()
# Define color palette
norm = plt.Normalize()
colors = plt.cm.GnBu(norm(self._vs))
# Cycle through layers
for i in range(len(depths) - 1):
# If anisotropic, add texture - still broken hatch
if not self._flag[i] == 1:
cax = ax.axhspan(depths[i], depths[i + 1], color=colors[i])
cax.set_hatch("o")
# Else isotropic
else:
cax = ax.axhspan(depths[i], depths[i + 1], color=colors[i])
# Fix axes and labels
ax.set_ylim(0.0, zmax)
ax.set_xticks(())
ax.invert_yaxis()
pos = ax.get_position()
ax2 = fig.add_axes([pos.x0, pos.y0 - 0.02, pos.width, 0.015])
cmap = plt.cm.ScalarMappable(norm=norm, cmap="GnBu")
plt.colorbar(cmap, cax=ax2, orientation="horizontal", label="$V_S$ (m/s)")
if show:
ax.set_ylabel("Depth (km)")
plt.tight_layout()