-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathslowness_model.py
1823 lines (1628 loc) · 83.9 KB
/
slowness_model.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Slowness model class.
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
from future.builtins import * # NOQA
from copy import deepcopy
import math
import numpy as np
from . import _DEFAULT_VALUES
from .helper_classes import (CriticalDepth, DepthRange, SlownessLayer,
SlownessModelError, SplitLayerInfo, TimeDist)
from .slowness_layer import (bullen_depth_for,
bullen_radial_slowness, create_from_vlayer,
evaluate_at_bullen)
from .velocity_layer import (VelocityLayer, evaluate_velocity_at_bottom,
evaluate_velocity_at_top)
def _fix_critical_depths(critical_depths, layer_num, is_p_wave):
name = 'p_layer_num' if is_p_wave else 's_layer_num'
mask = critical_depths[name] > layer_num
critical_depths[name][mask] += 1
class SlownessModel(object):
"""
Storage and methods for generating slowness-depth pairs.
"""
def __init__(self, v_mod, min_delta_p=0.1, max_delta_p=11,
max_depth_interval=115,
max_range_interval=2.5 * math.pi / 180,
max_interp_error=0.05, allow_inner_core_s=True,
slowness_tolerance=_DEFAULT_VALUES["slowness_tolerance"],
skip_model_creation=False):
self.debug = False
# NB if the following are actually cleared (lists are mutable) every
# time create_sample is called, maybe it would be better to just put
# these initialisations into the relevant methods? They do have to be
# persistent across method calls in create_sample though, so don't.
# Stores the layer number for layers in the velocity model with a
# critical point at their top. These form the "branches" of slowness
# sampling.
self.critical_depths = None # will be list of CriticalDepth objects
# Store depth ranges that contains a high slowness zone for P/S. Stored
# as DepthRange objects, containing the top depth and bottom depth.
self.high_slowness_layer_depths_p = [] # will be list of DepthRanges
self.high_slowness_layer_depths_s = []
# Stores depth ranges that are fluid, ie S velocity is zero. Stored as
# DepthRange objects, containing the top depth and bottom depth.
self.fluid_layer_depths = []
self.p_layers = None
self.s_layers = None
# For methods that have an is_p_wave parameter
self.s_wave = False
self.p_wave = True
self.v_mod = v_mod
self.min_delta_p = min_delta_p
self.max_delta_p = max_delta_p
self.max_depth_interval = max_depth_interval
self.max_range_interval = max_range_interval
self.max_interp_error = max_interp_error
self.allow_inner_core_s = allow_inner_core_s
self.slowness_tolerance = slowness_tolerance
if skip_model_creation:
return
self.create_sample()
def __str__(self):
desc = "".join([
"radius_of_planet=", str(self.radius_of_planet), "\n max_delta_p=",
str(self.max_delta_p),
"\n min_delta_p=", str(self.min_delta_p), "\n max_depth_interval=",
str(self.max_depth_interval), "\n max_range_interval=",
str(self.max_range_interval),
"\n allow_inner_core_s=", str(self.allow_inner_core_s),
"\n slownessTolerance=", str(self.slowness_tolerance),
"\n get_num_layers('P')=", str(self.get_num_layers(self.p_wave)),
"\n get_num_layers('S')=", str(self.get_num_layers(self.s_wave)),
"\n fluid_layer_depths.size()=", str(len(self.fluid_layer_depths)),
"\n high_slowness_layer_depths_p.size()=",
str(len(self.high_slowness_layer_depths_p)),
"\n high_slowness_layer_depths_s.size()=",
str(len(self.high_slowness_layer_depths_s)),
"\n critical_depths.size()=",
(str(len(self.critical_depths))
if self.critical_depths is not None else 'N/A'),
"\n"])
desc += "**** Critical Depth Layers ************************\n"
desc += str(self.critical_depths)
desc += "\n"
desc += "\n**** Fluid Layer Depths ************************\n"
for fl in self.fluid_layer_depths:
desc += str(fl.top_depth) + "," + str(fl.bot_depth) + " "
desc += "\n"
desc += "\n**** P High Slowness Layer Depths ****************\n"
for fl in self.high_slowness_layer_depths_p:
desc += str(fl.top_depth) + "," + str(fl.bot_depth) + " "
desc += "\n"
desc += "\n**** S High Slowness Layer Depths ****************\n"
for fl in self.high_slowness_layer_depths_s:
desc += str(fl.top_depth) + "," + str(fl.bot_depth) + " "
desc += "\n"
desc += "\n**** P Layers ****************\n"
for l in self.p_layers:
desc += str(l) + "\n"
return desc
def create_sample(self):
"""
Create slowness-depth layers from a velocity model.
This method takes a velocity model and creates a vector containing
slowness-depth layers that, hopefully, adequately sample both slowness
and depth so that the travel time as a function of distance can be
reconstructed from the theta function.
"""
# Some checks on the velocity model
self.v_mod.validate()
if len(self.v_mod) == 0:
raise SlownessModelError("velModel.get_num_layers()==0")
if self.v_mod.layers[0]['top_s_velocity'] == 0:
raise SlownessModelError(
"Unable to handle zero S velocity layers at surface. "
"This should be fixed at some point, but is a limitation of "
"TauP at this point.")
if self.debug:
print("start create_sample")
self.radius_of_planet = self.v_mod.radius_of_planet
if self.debug:
print("find_critical_points")
self.find_critical_points()
if self.debug:
print("coarse_sample")
self.coarse_sample()
if self.debug:
self.validate()
if self.debug:
print("ray_paramCheck")
self.ray_param_inc_check()
if self.debug:
print("depth_inc_check")
self.depth_inc_check()
if self.debug:
print("distance_check")
self.distance_check()
if self.debug:
print("fix_critical_points")
self.fix_critical_points()
self.validate()
if self.debug:
print("create_sample seems to be done successfully.")
def find_critical_points(self):
"""
Find all critical points within a velocity model.
Critical points are first order discontinuities in velocity/slowness,
local extrema in slowness. A high slowness zone is a low velocity zone,
but it is possible to have a slightly low velocity zone within a
spherical planet that is not a high slowness zone and thus does not
exhibit any of the pathological behavior of a low velocity zone.
"""
high_slowness_zone_p = DepthRange()
high_slowness_zone_s = DepthRange()
fluid_zone = DepthRange()
in_fluid_zone = False
below_outer_core = False
in_high_slowness_zone_p = False
in_high_slowness_zone_s = False
# just some very big values (java had max possible of type,
# but these should do)
min_p_so_far = 1.1e300
min_s_so_far = 1.1e300
# First remove any critical points previously stored
# so these are effectively re-initialised... it's probably silly
self.critical_depths = np.zeros(len(self.v_mod.layers) + 1,
dtype=CriticalDepth)
cd_count = 0
self.high_slowness_layer_depths_p = [] # lists of DepthRange
self.high_slowness_layer_depths_s = []
self.fluid_layer_depths = []
# Initialize the current velocity layer
# to be zero thickness layer with values at the surface
curr_v_layer = self.v_mod.layers[0]
curr_v_layer = np.array([(
curr_v_layer['top_depth'], curr_v_layer['top_depth'],
curr_v_layer['top_p_velocity'], curr_v_layer['top_p_velocity'],
curr_v_layer['top_s_velocity'], curr_v_layer['top_s_velocity'],
curr_v_layer['top_density'], curr_v_layer['top_density'],
curr_v_layer['top_qp'], curr_v_layer['top_qp'],
curr_v_layer['top_qs'], curr_v_layer['top_qs'])],
dtype=VelocityLayer)
curr_s_layer = create_from_vlayer(
v_layer=curr_v_layer,
is_p_wave=self.s_wave,
radius_of_planet=self.v_mod.radius_of_planet,
is_spherical=self.v_mod.is_spherical)
curr_p_layer = create_from_vlayer(
v_layer=curr_v_layer,
is_p_wave=self.p_wave,
radius_of_planet=self.v_mod.radius_of_planet,
is_spherical=self.v_mod.is_spherical)
# We know that the top is always a critical slowness so add 0
self.critical_depths[cd_count] = (0, 0, 0, 0)
cd_count += 1
# Check to see if starting in fluid zone.
if in_fluid_zone is False and curr_v_layer['top_s_velocity'] == 0:
in_fluid_zone = True
fluid_zone = DepthRange(top_depth=curr_v_layer['top_depth'])
curr_s_layer = curr_p_layer
if min_s_so_far > curr_s_layer['top_p']:
min_s_so_far = curr_s_layer['top_p']
# P is not a typo, it represents slowness, not P-wave speed.
if min_p_so_far > curr_p_layer['top_p']:
min_p_so_far = curr_p_layer['top_p']
for layer_num, layer in enumerate(self.v_mod.layers):
prev_v_layer = curr_v_layer
prev_s_layer = curr_s_layer
prev_p_layer = curr_p_layer
# Could make the following a deep copy, but not necessary.
# Also don't just replace layer here and in the loop
# control with curr_v_layer, or the reference to the first
# zero thickness layer that has been initialised above
# will break.
curr_v_layer = layer
# Check again if in fluid zone
if in_fluid_zone is False and curr_v_layer['top_s_velocity'] == 0:
in_fluid_zone = True
fluid_zone = DepthRange(top_depth=curr_v_layer['top_depth'])
# If already in fluid zone, check if exited (java line 909)
if in_fluid_zone is True and curr_v_layer['top_s_velocity'] != 0:
if prev_v_layer['bot_depth'] > self.v_mod.iocb_depth:
below_outer_core = True
in_fluid_zone = False
fluid_zone.bot_depth = prev_v_layer['bot_depth']
self.fluid_layer_depths.append(fluid_zone)
curr_p_layer = create_from_vlayer(
v_layer=curr_v_layer,
is_p_wave=self.p_wave,
radius_of_planet=self.v_mod.radius_of_planet,
is_spherical=self.v_mod.is_spherical)
# If we are in a fluid zone ( S velocity = 0.0 ) or if we are below
# the outer core and allow_inner_core_s=false then use the P
# velocity structure to look for critical points.
if in_fluid_zone \
or (below_outer_core and self.allow_inner_core_s is False):
curr_s_layer = curr_p_layer
else:
curr_s_layer = create_from_vlayer(
v_layer=curr_v_layer,
is_p_wave=self.s_wave,
radius_of_planet=self.v_mod.radius_of_planet,
is_spherical=self.v_mod.is_spherical)
if prev_s_layer['bot_p'] != curr_s_layer['top_p'] \
or prev_p_layer['bot_p'] != curr_p_layer['top_p']:
# a first order discontinuity
self.critical_depths[cd_count] = (
curr_s_layer['top_depth'],
layer_num,
-1,
-1)
cd_count += 1
if self.debug:
print('First order discontinuity, depth =' +
str(curr_s_layer['top_depth']))
print('between' + str(prev_p_layer), str(curr_p_layer))
if in_high_slowness_zone_s and \
curr_s_layer['top_p'] < min_s_so_far:
if self.debug:
print("Top of current layer is the bottom"
" of a high slowness zone.")
high_slowness_zone_s.bot_depth = curr_s_layer['top_depth']
self.high_slowness_layer_depths_s.append(
high_slowness_zone_s)
in_high_slowness_zone_s = False
if in_high_slowness_zone_p and \
curr_p_layer['top_p'] < min_p_so_far:
if self.debug:
print("Top of current layer is the bottom"
" of a high slowness zone.")
high_slowness_zone_p.bot_depth = curr_s_layer['top_depth']
self.high_slowness_layer_depths_p.append(
high_slowness_zone_p)
in_high_slowness_zone_p = False
# Update min_p_so_far and min_s_so_far as all total reflections
# off of the top of the discontinuity are ok even though below
# the discontinuity could be the start of a high slowness zone.
if min_p_so_far > curr_p_layer['top_p']:
min_p_so_far = curr_p_layer['top_p']
if min_s_so_far > curr_s_layer['top_p']:
min_s_so_far = curr_s_layer['top_p']
if in_high_slowness_zone_s is False and (
prev_s_layer['bot_p'] < curr_s_layer['top_p'] or
curr_s_layer['top_p'] < curr_s_layer['bot_p']):
# start of a high slowness zone S
if self.debug:
print("Found S high slowness at first order " +
"discontinuity, layer = " + str(layer_num))
in_high_slowness_zone_s = True
high_slowness_zone_s = \
DepthRange(top_depth=curr_s_layer['top_depth'])
high_slowness_zone_s.ray_param = min_s_so_far
if in_high_slowness_zone_p is False and (
prev_p_layer['bot_p'] < curr_p_layer['top_p'] or
curr_p_layer['top_p'] < curr_p_layer['bot_p']):
# start of a high slowness zone P
if self.debug:
print("Found P high slowness at first order " +
"discontinuity, layer = " + str(layer_num))
in_high_slowness_zone_p = True
high_slowness_zone_p = \
DepthRange(top_depth=curr_p_layer['top_depth'])
high_slowness_zone_p.ray_param = min_p_so_far
elif ((prev_s_layer['top_p'] - prev_s_layer['bot_p']) *
(prev_s_layer['bot_p'] - curr_s_layer['bot_p']) < 0) or (
(prev_p_layer['top_p'] - prev_p_layer['bot_p']) *
(prev_p_layer['bot_p'] - curr_p_layer['bot_p'])) < 0:
# local slowness extrema, java l 1005
self.critical_depths[cd_count] = (
curr_s_layer['top_depth'],
layer_num,
-1,
-1)
cd_count += 1
if self.debug:
print("local slowness extrema, depth=" +
str(curr_s_layer['top_depth']))
# here is line 1014 of the java src!
if in_high_slowness_zone_p is False \
and curr_p_layer['top_p'] < curr_p_layer['bot_p']:
if self.debug:
print("start of a P high slowness zone, local "
"slowness extrema,min_p_so_far= " +
str(min_p_so_far))
in_high_slowness_zone_p = True
high_slowness_zone_p = \
DepthRange(top_depth=curr_p_layer['top_depth'])
high_slowness_zone_p.ray_param = min_p_so_far
if in_high_slowness_zone_s is False \
and curr_s_layer['top_p'] < curr_s_layer['bot_p']:
if self.debug:
print("start of a S high slowness zone, local "
"slowness extrema, min_s_so_far= " +
str(min_s_so_far))
in_high_slowness_zone_s = True
high_slowness_zone_s = \
DepthRange(top_depth=curr_s_layer['top_depth'])
high_slowness_zone_s.ray_param = min_s_so_far
if in_high_slowness_zone_p and \
curr_p_layer['bot_p'] < min_p_so_far:
# P: layer contains the bottom of a high slowness zone. java
# l 1043
if self.debug:
print("layer contains the bottom of a P " +
"high slowness zone. min_p_so_far=" +
str(min_p_so_far), curr_p_layer)
high_slowness_zone_p.bot_depth = self.find_depth_from_layers(
min_p_so_far, layer_num, layer_num, self.p_wave)
self.high_slowness_layer_depths_p.append(high_slowness_zone_p)
in_high_slowness_zone_p = False
if in_high_slowness_zone_s and \
curr_s_layer['bot_p'] < min_s_so_far:
# S: layer contains the bottom of a high slowness zone. java
# l 1043
if self.debug:
print("layer contains the bottom of a S " +
"high slowness zone. min_s_so_far=" +
str(min_s_so_far), curr_s_layer)
# in fluid layers we want to check p_wave structure
# when looking for S wave critical points
por_s = (self.p_wave
if curr_s_layer == curr_p_layer else self.s_wave)
high_slowness_zone_s.bot_depth = self.find_depth_from_layers(
min_s_so_far, layer_num, layer_num, por_s)
self.high_slowness_layer_depths_s.append(high_slowness_zone_s)
in_high_slowness_zone_s = False
if min_p_so_far > curr_p_layer['bot_p']:
min_p_so_far = curr_p_layer['bot_p']
if min_p_so_far > curr_p_layer['top_p']:
min_p_so_far = curr_p_layer['top_p']
if min_s_so_far > curr_s_layer['bot_p']:
min_s_so_far = curr_s_layer['bot_p']
if min_s_so_far > curr_s_layer['top_p']:
min_s_so_far = curr_s_layer['top_p']
if self.debug and in_high_slowness_zone_s:
print("In S high slowness zone, layer_num = " +
str(layer_num) + " min_s_so_far=" + str(min_s_so_far))
if self.debug and in_high_slowness_zone_p:
print("In P high slowness zone, layer_num = " +
str(layer_num) + " min_p_so_far=" + str(min_p_so_far))
# We know that the bottommost depth is always a critical slowness,
# so we add v_mod.get_num_layers()
# java line 1094
self.critical_depths[cd_count] = (
self.radius_of_planet, len(self.v_mod), -1, -1)
cd_count += 1
# Check if the bottommost depth is contained within a high slowness
# zone, might happen in a flat non-whole-planet model
if in_high_slowness_zone_s:
high_slowness_zone_s.bot_depth = curr_v_layer['bot_depth']
self.high_slowness_layer_depths_s.append(high_slowness_zone_s)
if in_high_slowness_zone_p:
high_slowness_zone_p.bot_depth = curr_v_layer['bot_depth']
self.high_slowness_layer_depths_p.append(high_slowness_zone_p)
# Check if the bottommost depth is contained within a fluid zone, this
# would be the case if we have a non whole planet model with the bottom
# in the outer core or if allow_inner_core_s == false and we want to
# use the P velocity structure in the inner core.
if in_fluid_zone:
fluid_zone.bot_depth = curr_v_layer['bot_depth']
self.fluid_layer_depths.append(fluid_zone)
self.critical_depths = self.critical_depths[:cd_count]
self.validate()
def get_num_layers(self, is_p_wave):
"""
Number of slowness layers.
This is meant to return the number of P or S layers.
:param is_p_wave: Return P layer count (``True``) or S layer count
(``False``).
:type is_p_wave: bool
:returns: Number of slowness layers.
:rtype: int
"""
if is_p_wave:
return len(self.p_layers)
else:
return len(self.s_layers)
def find_depth_from_depths(self, ray_param, top_depth, bot_depth,
is_p_wave):
"""
Find depth corresponding to a slowness between two given depths.
The given depths are converted to layer numbers before calling
:meth:`find_depth_from_layers`.
:param ray_param: Slowness (aka ray parameter) to find, in s/km.
:type ray_param: float
:param top_depth: Top depth to search, in km.
:type top_depth: float
:param bot_depth: Bottom depth to search, in km.
:type bot_depth: float
:param is_p_wave: ``True`` if P wave or ``False`` for S wave.
:type is_p_wave: bool
:returns: Depth (in km) corresponding to the desired slowness.
:rtype: float
:raises SlownessModelError:
If ``top_critical_layer > bot_critical_layer``
because there are no layers to search, or if there is an increase
in slowness, i.e., a negative velocity gradient, that just balances
the decrease in slowness due to the spherical planet, or if the ray
parameter ``p`` is not contained within the specified layer range.
"""
top_layer_num = self.v_mod.layer_number_below(top_depth)[0]
if self.v_mod.layers[top_layer_num]['bot_depth'] == top_depth:
top_layer_num += 1
bot_layer_num = self.v_mod.layer_number_above(bot_depth)[0]
return self.find_depth_from_layers(ray_param, top_layer_num,
bot_layer_num, is_p_wave)
def find_depth_from_layers(self, p, top_critical_layer, bot_critical_layer,
is_p_wave):
"""
Find depth corresponding to a slowness p between two velocity layers.
Here, slowness is defined as ``(radius_of_planet-depth) / velocity``,
and sometimes called ray parameter. Both the top and the bottom
velocity layers are included. We also check to see if the slowness is
less than the bottom slowness of these layers but greater than the top
slowness of the next deeper layer. This corresponds to a total
reflection. In this case a check needs to be made to see if this is an
S wave reflecting off of a fluid layer, use P velocity below in this
case. We assume that slowness is monotonic within these layers and
therefore there is only one depth with the given slowness. This means
we return the first depth that we find.
:param p: Slowness (aka ray parameter) to find, in s/km.
:type p: float
:param top_critical_layer: Top layer number to search.
:type top_critical_layer: int
:param bot_critical_layer: Bottom layer number to search.
:type bot_critical_layer: int
:param is_p_wave: ``True`` if P wave or ``False`` for S wave.
:type is_p_wave: bool
:returns: Depth (in km) corresponding to the desired slowness.
:rtype: float
:raises SlownessModelError: If
``top_critical_layer > bot_critical_layer``
because there are no layers to search, or if there is an increase
in slowness, i.e., a negative velocity gradient, that just balances
the decrease in slowness due to the spherical planet, or if the ray
parameter ``p`` is not contained within the specified layer range.
"""
# top_p = 1.1e300 # dummy numbers
# bot_p = 1.1e300
wave_type = 'P' if is_p_wave else 'S'
if top_critical_layer > bot_critical_layer:
raise SlownessModelError(
"findDepth: no layers to search (wrong layer num?)")
for layer_num in range(top_critical_layer, bot_critical_layer + 1):
vel_layer = self.v_mod.layers[layer_num]
top_velocity = evaluate_velocity_at_top(vel_layer, wave_type)
bot_velocity = evaluate_velocity_at_bottom(vel_layer, wave_type)
top_p = self.to_slowness(top_velocity, vel_layer['top_depth'])
bot_p = self.to_slowness(bot_velocity, vel_layer['bot_depth'])
# Check to see if we are within 'chatter level' (numerical
# error) of the top or bottom and if so then return that depth.
if abs(top_p - p) < self.slowness_tolerance:
return vel_layer['top_depth']
if abs(p - bot_p) < self.slowness_tolerance:
return vel_layer['bot_depth']
if (top_p - p) * (p - bot_p) >= 0:
# Found layer containing p.
# We interpolate assuming that velocity is linear within
# this interval. So slope is the slope for velocity versus
# depth.
slope = (bot_velocity - top_velocity) / (
vel_layer['bot_depth'] - vel_layer['top_depth'])
depth = self.interpolate(p, top_velocity,
vel_layer['top_depth'], slope)
return depth
elif layer_num == top_critical_layer \
and abs(p - top_p) < self.slowness_tolerance:
# Check to see if p is just outside the topmost layer. If so
# then return the top depth.
return vel_layer['top_depth']
# Is p a total reflection? bot_p is the slowness at the bottom
# of the last velocity layer from the previous loop, set top_p
# to be the slowness at the top of the next layer.
if layer_num < len(self.v_mod) - 1:
vel_layer = self.v_mod.layers[layer_num + 1]
top_velocity = evaluate_velocity_at_top(vel_layer, wave_type)
if (is_p_wave is False and
np.any(self.depth_in_fluid(vel_layer['top_depth']))):
# Special case for S waves above a fluid. If top next
# layer is in a fluid then we should set top_velocity to
# be the P velocity at the top of the layer.
top_velocity = evaluate_velocity_at_top(vel_layer, 'P')
top_p = self.to_slowness(top_velocity, vel_layer['top_depth'])
if bot_p >= p >= top_p:
return vel_layer['top_depth']
# noinspection PyUnboundLocalVariable
if abs(p - bot_p) < self.slowness_tolerance:
# java line 1275
# Check to see if p is just outside the bottommost layer. If so
# than return the bottom depth.
print(" p is just outside the bottommost layer. This probably "
"shouldn't be allowed to happen!")
# noinspection PyUnboundLocalVariable
return vel_layer.getBotDepth()
raise SlownessModelError(
"slowness p=" + str(p) +
" is not contained within the specified layers." +
" top_critical_layer=" + str(top_critical_layer) +
" bot_critical_layer=" + str(bot_critical_layer))
def to_slowness(self, velocity, depth):
"""
Convert velocity at some depth to slowness.
:param velocity: The velocity to convert, in km/s.
:type velocity: float
:param depth: The depth (in km) at which to perform the calculation.
Must be less than the radius of the planet defined in this
model, or the result is undefined.
:type depth: float
:returns: The slowness, in s/km.
:rtype: float
"""
if np.any(velocity == 0):
raise SlownessModelError(
"to_slowness: velocity can't be zero, at depth" +
str(depth),
"Maybe related to using S velocities in outer core?")
return (self.radius_of_planet - depth) / velocity
def interpolate(self, p, top_velocity, top_depth, slope):
"""
Interpolate slowness to depth within a layer.
We interpolate assuming that velocity is linear within
this interval.
All parameters must be of the same shape.
:param p: The slowness to interpolate, in s/km.
:type p: :class:`float` or :class:`~numpy.ndarray`
:param top_velocity: The velocity (in km/s) at the top of the layer.
:type top_velocity: :class:`float` or :class:`~numpy.ndarray`
:param top_depth: The depth (in km) for the top of the layer.
:type top_depth: :class:`float` or :class:`~numpy.ndarray`
:param slope: The slope (in (km/s)/km) for velocity versus depth.
:type slope: :class:`float` or :class:`~numpy.ndarray`
:returns: The depth (in km) of the slowness below the layer boundary.
:rtype: :class:`float` or :class:`~numpy.ndarray`
"""
denominator = p * slope + 1
if np.any(denominator == 0):
raise SlownessModelError(
"Negative velocity gradient that just balances the slowness "
"gradient of the spherical slowness, i.e. planet flattening. "
"Instructions unclear; explode.")
else:
depth = (self.radius_of_planet +
p * (top_depth * slope - top_velocity)) / denominator
return depth
def depth_in_fluid(self, depth):
"""
Determine if the given depth is contained within a fluid zone.
The fluid zone includes its upper boundary but not its lower boundary.
The top and bottom of the fluid zone are not returned as a DepthRange,
just like in the Java code, despite its claims to the contrary.
:param depth: The depth to check, in km.
:type depth: :class:`~numpy.ndarray`, dtype = :class:`float`
:returns: ``True`` if the depth is within a fluid zone, ``False``
otherwise.
:rtype: :class:`~numpy.ndarray` (dtype = :class:`bool`)
"""
ret = np.zeros(shape=depth.shape, dtype=np.bool_)
for elem in self.fluid_layer_depths:
ret |= (elem.top_depth <= depth) & (depth < elem.bot_depth)
return ret
def coarse_sample(self):
"""
Create a coarse slowness sampling of the velocity model (v_mod).
The resultant slowness layers will satisfy the maximum depth increments
as well as sampling each point specified within the VelocityModel. The
P and S sampling will also be compatible.
"""
self.p_layers = create_from_vlayer(
v_layer=self.v_mod.layers,
is_p_wave=self.p_wave,
radius_of_planet=self.v_mod.radius_of_planet,
is_spherical=self.v_mod.is_spherical)
with np.errstate(divide='ignore'):
self.s_layers = create_from_vlayer(
v_layer=self.v_mod.layers,
is_p_wave=self.s_wave,
radius_of_planet=self.v_mod.radius_of_planet,
is_spherical=self.v_mod.is_spherical)
mask = self.depth_in_fluid(self.v_mod.layers['top_depth'])
if not self.allow_inner_core_s:
mask |= self.v_mod.layers['top_depth'] >= self.v_mod.iocb_depth
self.s_layers[mask] = self.p_layers[mask]
# Check for first order discontinuity. However, we only consider
# S discontinuities in the inner core if allow_inner_core_s is true.
above = self.v_mod.layers[:-1]
below = self.v_mod.layers[1:]
mask = np.logical_or(
above['bot_p_velocity'] != below['top_p_velocity'],
np.logical_and(
above['bot_s_velocity'] != below['top_s_velocity'],
np.logical_or(
self.allow_inner_core_s,
below['top_depth'] < self.v_mod.iocb_depth)))
index = np.where(mask)[0] + 1
above = above[mask]
below = below[mask]
# If we are going from a fluid to a solid or solid to fluid, e.g., core
# mantle or outer core to inner core then we need to use the P velocity
# for determining the S discontinuity.
top_s_vel = np.where(above['bot_s_velocity'] == 0,
above['bot_p_velocity'],
above['bot_s_velocity'])
bot_s_vel = np.where(below['top_s_velocity'] == 0,
below['top_p_velocity'],
below['top_s_velocity'])
# Add the layer, with zero thickness but nonzero slowness step,
# corresponding to the discontinuity.
curr_v_layer = np.empty(shape=above.shape, dtype=VelocityLayer)
curr_v_layer['top_depth'] = above['bot_depth']
curr_v_layer['bot_depth'] = above['bot_depth']
curr_v_layer['top_p_velocity'] = above['bot_p_velocity']
curr_v_layer['bot_p_velocity'] = below['top_p_velocity']
curr_v_layer['top_s_velocity'] = top_s_vel
curr_v_layer['bot_s_velocity'] = bot_s_vel
curr_v_layer['top_density'].fill(_DEFAULT_VALUES["density"])
curr_v_layer['bot_density'].fill(_DEFAULT_VALUES["density"])
curr_v_layer['top_qp'].fill(_DEFAULT_VALUES["qp"])
curr_v_layer['bot_qp'].fill(_DEFAULT_VALUES["qp"])
curr_v_layer['top_qs'].fill(_DEFAULT_VALUES["qs"])
curr_v_layer['bot_qs'].fill(_DEFAULT_VALUES["qs"])
curr_p_layer = create_from_vlayer(
v_layer=curr_v_layer,
is_p_wave=self.p_wave,
radius_of_planet=self.v_mod.radius_of_planet,
is_spherical=self.v_mod.is_spherical)
self.p_layers = np.insert(self.p_layers, index, curr_p_layer)
curr_s_layer = create_from_vlayer(
v_layer=curr_v_layer,
is_p_wave=self.s_wave,
radius_of_planet=self.v_mod.radius_of_planet,
is_spherical=self.v_mod.is_spherical)
mask2 = (above['bot_s_velocity'] == 0) & (below['top_s_velocity'] == 0)
if not self.allow_inner_core_s:
mask2 |= curr_v_layer['top_depth'] >= self.v_mod.iocb_depth
curr_s_layer = np.where(mask2, curr_p_layer, curr_s_layer)
self.s_layers = np.insert(self.s_layers, index, curr_s_layer)
# Make sure that all high slowness layers are sampled exactly
# at their bottom
for high_zone in self.high_slowness_layer_depths_s:
s_layer_num = self.layer_number_above(high_zone.bot_depth,
self.s_wave)
high_s_layer = self.s_layers[s_layer_num]
while high_s_layer['top_depth'] == high_s_layer['bot_depth'] and (
(high_s_layer['top_p'] - high_zone.ray_param) *
(high_zone.ray_param - high_s_layer['bot_p']) < 0):
s_layer_num += 1
high_s_layer = self.s_layers[s_layer_num]
if high_zone.ray_param != high_s_layer['bot_p']:
self.add_slowness(high_zone.ray_param, self.s_wave)
for high_zone in self.high_slowness_layer_depths_p:
s_layer_num = self.layer_number_above(high_zone.bot_depth,
self.p_wave)
high_s_layer = self.p_layers[s_layer_num]
while high_s_layer['top_depth'] == high_s_layer['bot_depth'] and (
(high_s_layer['top_p'] - high_zone.ray_param) *
(high_zone.ray_param - high_s_layer['bot_p']) < 0):
s_layer_num += 1
high_s_layer = self.p_layers[s_layer_num]
if high_zone.ray_param != high_s_layer['bot_p']:
self.add_slowness(high_zone.ray_param, self.p_wave)
# Make sure P and S are consistent by adding discontinuities in one to
# the other.
# Numpy 1.6 compatibility
# _tb = self.p_layers[['top_p', 'bot_p']]
_tb = np.vstack([self.p_layers['top_p'],
self.p_layers['bot_p']]).T.ravel()
uniq = np.unique(_tb)
for p in uniq:
self.add_slowness(p, self.s_wave)
# Numpy 1.6 compatibility
# _tb = self.p_layers[['top_p', 'bot_p']]
_tb = np.vstack([self.s_layers['top_p'],
self.s_layers['bot_p']]).T.ravel()
uniq = np.unique(_tb)
for p in uniq:
self.add_slowness(p, self.p_wave)
def layer_number_above(self, depth, is_p_wave):
"""
Find the index of the slowness layer that contains the given depth.
Note that if the depth is a layer boundary, it returns the shallower
of the two or possibly more (since total reflections are zero
thickness layers) layers.
.. seealso:: :meth:`layer_number_below`
:param depth: The depth to find, in km.
:type depth: :class:`float` or :class:`~numpy.ndarray`
:param is_p_wave: Whether to look at P (``True``) velocity or S
(``False``) velocity.
:type is_p_wave: bool
:returns: The slowness layer containing the requested depth.
:rtype: :class:`int` or :class:`~numpy.ndarray` (dtype = :class:`int`,
shape = ``depth.shape``)
:raises SlownessModelError: If no layer in the slowness model contains
the given depth.
"""
if is_p_wave:
layers = self.p_layers
else:
layers = self.s_layers
# Check to make sure depth is within the range available
if np.any(depth < layers[0]['top_depth']) or \
np.any(depth > layers[-1]['bot_depth']):
raise SlownessModelError("No layer contains this depth")
found_layer_num = np.searchsorted(layers['top_depth'], depth)
mask = found_layer_num != 0
if np.isscalar(found_layer_num):
if mask:
found_layer_num -= 1
else:
found_layer_num[mask] -= 1
return found_layer_num
def layer_number_below(self, depth, is_p_wave):
"""
Find the index of the slowness layer that contains the given depth.
Note that if the depth is a layer boundary, it returns the deeper of
the two or possibly more (since total reflections are zero thickness
layers) layers.
.. seealso:: :meth:`layer_number_above`
:param depth: The depth to find, in km.
:type depth: :class:`float` or :class:`~numpy.ndarray`
:param is_p_wave: Whether to look at P (``True``) velocity or S
(``False``) velocity.
:type is_p_wave: bool
:returns: The slowness layer containing the requested depth.
:rtype: :class:`int` or :class:`~numpy.ndarray` (dtype = :class:`int`,
shape = ``depth.shape``)
:raises SlownessModelError: If no layer in the slowness model contains
the given depth.
"""
if is_p_wave:
layers = self.p_layers
else:
layers = self.s_layers
# Check to make sure depth is within the range available
if np.any(depth < layers[0]['top_depth']) or \
np.any(depth > layers[-1]['bot_depth']):
raise SlownessModelError("No layer contains this depth")
found_layer_num = np.searchsorted(layers['bot_depth'], depth,
side='right')
mask = found_layer_num == layers.shape[0]
if np.isscalar(found_layer_num):
if mask:
found_layer_num -= 1
else:
found_layer_num[mask] -= 1
return found_layer_num
def get_slowness_layer(self, layer, is_p_wave):
"""
Return the Slowness_layer of the requested wave type.
This is not meant to be a clone!
:param layer: The number of the layer(s) to return.
:type layer: :class:`int` or :class:`~numpy.ndarray` (dtype =
:class:`int`)
:param is_p_wave: Whether to return the P layer (``True``) or the S
layer (``False``).
:type is_p_wave: bool
:returns: The slowness layer(s).
:rtype: :class:`~numpy.ndarray` (dtype = :const:`Slowness_layer`,
shape = ``layer_num.shape``)
"""
if is_p_wave:
return self.p_layers[layer]
else:
return self.s_layers[layer]
def add_slowness(self, p, is_p_wave):
"""
Add a ray parameter to the slowness sampling for the given wave type.
Slowness layers are split as needed and P and S sampling are kept
consistent within fluid layers. Note, this makes use of the velocity
model, so all interpolation is linear in velocity, not in slowness!
:param p: The slowness value to add, in s/km.
:type p: float
:param is_p_wave: Whether to add to the P wave (``True``) or the S wave
(``False``) sampling.
:type is_p_wave: bool
"""
if is_p_wave:
# NB Unlike Java (unfortunately) these are not modified in place!
# NumPy arrays cannot have values inserted in place.
layers = self.p_layers
other_layers = self.s_layers
wave = 'P'
else:
layers = self.s_layers
other_layers = self.p_layers
wave = 'S'
# If depths are the same only need top_velocity, and just to verify we
# are not in a fluid.
nonzero = layers['top_depth'] != layers['bot_depth']
above = self.v_mod.evaluate_above(layers['bot_depth'], wave)
below = self.v_mod.evaluate_below(layers['top_depth'], wave)
top_velocity = np.where(nonzero, below, above)
bot_velocity = np.where(nonzero, above, below)
mask = ((layers['top_p'] - p) * (p - layers['bot_p'])) > 0
# Don't need to check for S waves in a fluid or in inner core if
# allow_inner_core_s is False.
if not is_p_wave:
mask &= top_velocity != 0
if not self.allow_inner_core_s:
iocb_mask = layers['bot_depth'] > self.v_mod.iocb_depth
mask &= ~iocb_mask
index = np.where(mask)[0]
bot_depth = np.copy(layers['bot_depth'])
# Not a zero thickness layer, so calculate the depth for
# the ray parameter.
slope = ((bot_velocity[nonzero] - top_velocity[nonzero]) /
(layers['bot_depth'][nonzero] - layers['top_depth'][nonzero]))
bot_depth[nonzero] = self.interpolate(p, top_velocity[nonzero],
layers['top_depth'][nonzero],
slope)
bot_layer = np.empty(shape=index.shape, dtype=SlownessLayer)
bot_layer['top_p'].fill(p)
bot_layer['top_depth'] = bot_depth[mask]
bot_layer['bot_p'] = layers['bot_p'][mask]
bot_layer['bot_depth'] = layers['bot_depth'][mask]
top_layer = np.empty(shape=index.shape, dtype=SlownessLayer)
top_layer['top_p'] = layers['top_p'][mask]
top_layer['top_depth'] = layers['top_depth'][mask]
top_layer['bot_p'].fill(p)
top_layer['bot_depth'] = bot_depth[mask]
# numpy 1.6 compatibility
other_index = np.where(other_layers.reshape(1, -1) ==
layers[mask].reshape(-1, 1))
layers[index] = bot_layer
layers = np.insert(layers, index, top_layer)
if len(other_index[0]):
other_layers[other_index[1]] = bot_layer[other_index[0]]
other_layers = np.insert(other_layers, other_index[1],
top_layer[other_index[0]])
if is_p_wave:
self.p_layers = layers
self.s_layers = other_layers
else:
self.s_layers = layers
self.p_layers = other_layers
def ray_param_inc_check(self):
"""
Check that no slowness layer's ray parameter interval is too large.
The limit is determined by ``self.max_delta_p``.
"""
for wave in [self.s_wave, self.p_wave]: