forked from QuentinBrissaud/RW_atmos
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRW_atmos.py
1838 lines (1500 loc) · 96.5 KB
/
RW_atmos.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 python3
import numpy as np
# import os
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from pdb import set_trace as bp
import sys
from pyrocko import moment_tensor as mtm
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
# from datetime import datetime, timedelta
from scipy import fftpack
import scipy.integrate as spi
from obspy.signal.tf_misfit import plot_tfr
from scipy import interpolate
# from sympy import symbols, solve
# from sympy.utilities.lambdify import lambdify
from multiprocessing import get_context
import multiprocessing as mp
from functools import partial
# Local modules
# import mechanisms as mod_mechanisms
import RWAtmosUtils, velocity_models
# display parameters
font = {'size': 14}
matplotlib.rc('font', **font)
# To make sure that there is no bug when saving and closing the figures
# https://stackoverflow.com/questions/27147300/matplotlib-tcl-asyncdelete-async-handler-deleted-by-the-wrong-thread
matplotlib.use('Agg')
class vertical_velocity():
def __init__(self, period, r2, cphi, cg, I1, kn, QR, directivity):
self.period = period
self.directivity = directivity
self.r2 = r2
self.cg = cg
self.cphi = cphi
self.I1 = I1
self.kn = kn
self.QR = QR
def add_attenuation(self, r):
return np.exp( -2.*np.pi*r/(2.*self.cphi*self.QR*self.period) )
def compute_veloc(self, r, phi, M, depth, unknown = 'd', dimension_seismic = 3):
comp_deriv = -np.pi*2.*1j/self.period if unknown == 'v' else 1.
comp_deriv = (-np.pi*2.*1j/self.period)*comp_deriv if unknown == 'a' else comp_deriv
# 3d
if(dimension_seismic == 3):
return comp_deriv*(self.r2/(8*self.cphi*self.cg*self.I1))*np.sqrt(2./(np.pi*self.kn*r))*np.exp( 1j*( self.kn*r + np.pi/4. ) )*self.directivity.compute_directivity(phi, M, depth) * self.add_attenuation(r)
# 2d
elif(dimension_seismic == 2):
# 1e3 is okay, because homogeneisation of the equations
return 1e3*comp_deriv*(self.r2/(4*self.cphi*self.cg*self.I1))*(1./(self.kn))*np.exp( 1j*( self.kn*r + np.pi/2. ) )*self.directivity.compute_directivity(phi, M, depth) * self.add_attenuation(r)
else:
sys.exit('Seismic dimension not recognized!')
class directivity():
def __init__(self, dep, dr1dz_source, dr2dz_source, kn, r1_source, r2_source):
self.dep = dep
self.dr1dz_source = dr1dz_source
self.dr2dz_source = dr2dz_source
self.kn = kn
self.r1_source = r1_source
self.r2_source = r2_source
def compute_directivity(self, phi, M, depth):
idz = np.argmin( abs(self.dep - depth/1000.) ) # get id of the source depth in the dep vector (which is the depths for the eigenfunctions)
dr1dz_source = self.dr1dz_source[idz]
dr2dz_source = self.dr2dz_source[idz]
r1_source = self.r1_source[idz]
r2_source = self.r2_source[idz]
phi_rot = phi
return self.kn*r1_source*( M[1]*np.cos(phi_rot)**2 + (-2.*M[5])*np.sin(phi_rot)*np.cos(phi_rot) + M[2]*np.sin(phi_rot)**2 ) \
+ 1j*dr1dz_source*(M[3]*np.cos(phi_rot) - M[4]*np.sin(phi_rot)) \
- 1j*self.kn*r2_source*(M[3]*np.cos(phi_rot) - M[4]*np.sin(phi_rot)) \
+ dr2dz_source*M[0]
class RW_forcing():
def __str__(self):
out = ''
out = out + '+-------------------------------+\n'
out = out + '| Rayleigh Wave Forcing |\n'
out = out + '| (Green Functions) |\n'
out = out + '+-------------------------------+\n'
out = out + ('| %5d modes |\n' % (self.nb_modes))
out = out + ('| %5d frequencies asked |\n' % (self.nb_freqs))
out = out + ('| %5d frequencies for mode 1 |\n' % (self.nb_freqs_actualforMode1))
out = out + '+-------------------------------+\n'
out = out + '| Frequencies asked (mode 1?): |\n'
if(self.nb_freqs>11):
for i in range(5):
out = out + ('| %.6e %s\n' % (self.f_tab[i], '(v)' if i<self.nb_freqs_actualforMode1 else ''))
out = out + '| ...\n'
for i in range(self.nb_freqs-5, self.nb_freqs):
out = out + ('| %.6e %s\n' % (self.f_tab[i], '(v)' if i<self.nb_freqs_actualforMode1 else ''))
else:
for i in range(self.nb_freqs):
out = out + ('| %.6e %s\n' % (self.f_tab[i], '(v)' if i<self.nb_freqs_actualforMode1 else ''))
out = out + '+-------------------------------+\n'
out = out + ('| uz: %d*%d array of %s\n' % (len(self.uz), len(self.uz[0]), type(self.uz[0][0])))
out = out + ('| directivity: %d*%d array of %s\n' % (len(self.directivity), len(self.directivity[0]), type(self.directivity[0][0])))
out = out + '+-------------------------------+\n'
out = out + '| Seismic model: |\n'
out = out + str(self.seismic)+'\n'
out = out + '+-------------------------------+\n'
out = out + '| Chosen storage folder: |\n'
out = out + '| '+self.global_folder+'\n'
out = out + '+-------------------------------+\n'
if(self.has_mechanism):
out = out + ('| Chosen mechanism: |\n')
out = out + ('| M0: %.3f\n' % (self.M0))
out = out + ('| depth: %.3f\n' % (self.zsource))
out = out + ('| strike: %.0f\n' % (self.strike))
out = out + ('| dip: %.0f\n' % (self.dip))
out = out + ('| rake: %.0f\n' % (self.rake))
out = out + ('| Source time function: |\n')
out = out + ('| %s\n' % (self.stf))
out = out + ('| %d points\n' % (len(self.stf_data)))
out = out + ('| f0 = %f\n' % (self.f0))
else:
out = out + ('| No associated mechanism yet. |\n')
out = out + '+-------------------------------+\n'
return(out)
def __repr__(self):
# Technically wrong, because repr should contain everything needed to build the instance again, but enough for what we want.
return(self.__str__())
def get_mode_filling(self):
# Prepare a matrix which is 1 if (period(i), mode(j)) contains a velocity, or 0 if (period(i), mode(j)) is empty.
mat = np.array([[0 if p==[] else 1 for p in m] for m in self.uz]).T
return(np.flipud(mat)) # make (freq, mode)
def print_mode_filling(self):
uz_func_mode_freq = self.get_mode_filling()
print(' ', end=' ')
for m in range(self.nb_modes):
if(m==self.nb_modes-1):
print('%2d' % (m), end='\n')
else:
print('%2d' % (m), end=' ')
for f in range(self.nb_freqs):
print('%.3e' % (self.f_tab[f]), end=' ')
for m in range(self.nb_modes):
if(m==self.nb_modes-1):
print('%2d' % (uz_func_mode_freq[f, m]), end='\n')
else:
print('%2d' % (uz_func_mode_freq[f, m]), end=' ')
# dd
def __init__(self, options):
# Inputs
self.f_tab = options['f_tab']
self.nb_freqs = len(self.f_tab)
self.nb_modes = options['nb_modes'][1]
self.set_global_folder(options['global_folder'])
# Attributes containing seismic/acoustic spectra
self.directivity = [ [ [] for aa in range(0, self.nb_freqs) ] for bb in range(0, self.nb_modes) ]
self.uz = [ [ [] for aa in range(0, self.nb_freqs) ] for bb in range(0, self.nb_modes) ]
# Extract seismic model for later plots
self.extract_seismic_parameters(options)
# Add source characteristics
#self.set_mechanism(mechanism)
self.has_mechanism = False
# MPI parameter
self.use_spawn = options['USE_SPAWN_MPI']
self.google_colab = options['GOOGLE_COLAB']
def set_global_folder(self, folder):
self.global_folder = folder # Save folder path from Green's class
def set_mechanism(self, mechanism):
self.has_mechanism = True
self.stf = mechanism['stf']
self.stf_data = mechanism['stf-data']
self.zsource = mechanism['zsource'] # m
if(self.stf == 'gaussian'):
self.f0 = mechanism['f0']
else:
self.f0 = mechanism['f0']*1.628
self.alpha = (np.pi*self.f0)**2
self.M0 = mechanism['M0']
self.M = mechanism['M']*self.M0
self.phi = mechanism['phi']
self.strike = mechanism['STRIKE'] # info only because everything is in self.M as a matrix
self.dip = mechanism['DIP'] # info only because everything is in self.M as a matrix
self.rake = mechanism['RAKE'] # info only because everything is in self.M as a matrix
self.mt = []
if 'mt' in mechanism:
self.mt = mechanism['mt']
def clear_mechanism(self):
self.has_mechanism = False
delattr(self, 'stf')
delattr(self, 'stf_data')
delattr(self, 'zsource')
delattr(self, 'f0')
delattr(self, 'alpha')
delattr(self, 'M0')
delattr(self, 'M')
delattr(self, 'phi')
delattr(self, 'strike')
delattr(self, 'dip')
delattr(self, 'rake')
delattr(self, 'mt')
def get_mechanism(self):
mechanism = {}
mechanism['stf'] = self.stf
mechanism['stf-data'] = self.stf_data
mechanism['zsource'] = self.zsource# m
mechanism['f0'] = self.f0
if(self.stf == 'gaussian'):
mechanism['f0'] = self.f0
else:
mechanism['f0'] = self.f0/1.628
mechanism['M0'] = self.M0
mechanism['M'] = self.M/self.M0
mechanism['phi'] = self.phi
mechanism['STRIKE'] = self.strike
mechanism['DIP'] = self.dip
mechanism['RAKE'] = self.rake
mechanism['mt'] = self.mt
return mechanism
def source_spectrum(self, period):
if(self.stf == 'gaussian'):
return self.M*np.sqrt(np.pi/self.alpha)*np.exp(-((np.pi/period)**2)/self.alpha)*np.exp(2*np.pi*1j*(4./self.f0)/period)
# ^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# moment source fourier transform time shift
# mag
elif(self.stf == 'gaussian_'):
return self.M*np.exp(-((np.pi/period)**2)/(self.f0**2))*np.exp(2*np.pi*1j*(4./self.f0)/period)
elif(self.stf == 'erf'):
#erf = -1j*(1./self.f0)*np.exp(-(np.pi/(period*self.f0))**2)/(np.pi/(period*self.f0))
erf = -1j*np.exp(-(np.pi/(period*self.f0))**2)/(np.pi/period)
dirac = 0.
return 0.5*(dirac + erf) * self.M * np.exp(2*np.pi*1j*(2.*2./self.f0)/period)
elif(self.stf == 'external'):
loc = np.argmin( abs(self.stf_data[0] - 1/period) )
return self.M * self.stf_data[1][loc]
else:
sys.exit('Source time function "'+self.stf+'" not recognized!')
def add_one_period(self, period, iperiod, current_struct, rho, orig_b1, orig_b2, d_b1_dz, d_b2_dz, kmode, dep):
# uz = []
# freqa = []
np.seterr(all='raise') # Force raising exceptions when encountering "RuntimeWarning: divide by zero encountered in true_divide".
for imode in range(0, min(len(current_struct),orig_b1.shape[1])):
cphi = current_struct[imode]['cphi'][iperiod]
cg = current_struct[imode]['cg'][iperiod]
r2 = orig_b2[:,imode]
r1 = orig_b1[:,imode]
kn = kmode[:,imode]
d_r2_dz = d_b2_dz[:,imode]
d_r1_dz = d_b1_dz[:,imode]
try:
I1 = 0.5*spi.simps(rho[:]*( r1**2 + r2**2 ), dep[:])
except(FloatingPointError):
(u, c) = np.unique(dep, return_counts=True)
if(np.any(c>1)):
print('[%s] Duplicate depth(s) found during integration:' % (sys._getframe().f_code.co_name))
print(u[c>1])
raise(FloatingPointError)
else:
sys.exit('what?')
kn = kn[0]
self.directivity[imode][iperiod] = directivity(dep, d_r1_dz, d_r2_dz, kn, r1, r2)
r2 = r2[0]
r1 = r1[0]
# Compute quality factor
#QR = spi.simps( (2./Qp[:])*(lamda[:] + 2*mu[:])*( kn*r1 + d_r2_dz )**2, dep[:])
#QR += spi.simps( (2.*mu[:]/Qs[:])*(( kn*r2 + d_r1_dz )**2 - 4*kn*r1*d_r2_dz ), dep[:])
#QR *= 1./(4.*(kn**2)*cg*cphi*I1)
QR = current_struct[imode]['QR'][iperiod]
# Store Green's functions for an arbitrary moment tensor
self.uz[imode][iperiod] = vertical_velocity(period, r2, cphi, cg, I1, kn, QR, self.directivity[imode][iperiod])
def update_frequencies(self):
# Compare the set of expected frequencies (self.nb_freq, self.f_tab)
# to the list of eigenmodes as generated by the calls to
# self.add_one_period in RW_dispersion.get_eigenfunctions.
# - In the case where the eigenfrequencies fill the array of
# expected frequencies, everything is fine.
# - In the case where there is less eigenfrequencies than expected
# frequencies, the creation of the RW_field will break (see
# compute_ifft > response_RW_all_modes > compute_RW_one_mode),
# and we need to store the actual frequencies that were found.
uz_func_mode_freq = self.get_mode_filling()
nfreqmode1 = np.sum(uz_func_mode_freq[:,0])
if(nfreqmode1 == self.nb_freqs):
# Easiest case, first mode contains values for all frequencies.
print('[%s] > > First mode contains eigenfrequencies for all expected frequencies, everything is fine.'
% (sys._getframe().f_code.co_name))
self.nb_freqs_actualforMode1 = self.nb_freqs
self.f_tab_actualforMode1 = self.f_tab
else:
# Somehow earthsr found less frequencies than asked for.
print('[%s] > > First mode contains less eigenfrequencies (%d) than expected frequencies (%d).'
% (sys._getframe().f_code.co_name, nfreqmode1, self.nb_freqs))
sys.exit(['[%s, ERROR] This should not happen: fundamental mode should always have all frequencies.'])
# # Check for empty frequencies in the middle of the series.
# # if mode 1 has [1 1 1 1 1 0 0] then it makes sense (no it does not, cf. error above)
# # if mode 1 has [1 1 0 0 1 1 1] then it does not make sense and is probably an error
# if(np.sum(uz_func_mode_freq[nfreqmode1:,0])>0):
# # If the last indices aren't zero, the zeros are somewhere before, and there is an issue.
# print('[%s] > > > On the first mode, some frequencies have no associated eigenfrequency:'
# % (sys._getframe().f_code.co_name),
# file=sys.stderr)
# print(self.f_tab[np.where(uz_func_mode_freq[:,0]==0)], file=sys.stderr)
# sys.exit('[%s] > > > This should not happen.' % (sys._getframe().f_code.co_name))
# else:
# # This is probably fine, store the updated frequency array.
# print('[%s] > > > Store frequency span agreeing with the first mode\'s first %d frequencies.' % (sys._getframe().f_code.co_name, nfreqmode1))
# self.nb_freqs_actualforMode1 = nfreqmode1
# self.f_tab_actualforMode1 = self.f_tab[:self.nb_freqs_actualforMode1]
# # Check parity.
# if(self.nb_freqs_actualforMode1%2==1):
# print('[%s] > > > Odd number of modes found. This will mess up the FFT routines.' % (sys._getframe().f_code.co_name))
# print('[%s] > > > > Dropping to even number below, updating "found frequencies", DELETING THE LAST FREQUENCY in UZ and DIRECTIVITY for ALL MODES.' % (sys._getframe().f_code.co_name))
# print('[%s] > > > > This will probably only impact the first mode anyway.' % (sys._getframe().f_code.co_name))
# for m in range(self.nb_modes):
# self.uz[m][self.nb_freqs_actualforMode1-1]=[]
# self.directivity[m][self.nb_freqs_actualforMode1-1]=[]
# self.nb_freqs_actualforMode1 -= 1
# self.f_tab_actualforMode1 = self.f_tab[:self.nb_freqs_actualforMode1]
def compute_RW_one_mode(self, imode, r, phi, type = 'RW', unknown = 'd', dimension_seismic = 3):
# Source depth
depth = self.zsource
uz_tab = []
f_tab = []
#print('Compute mode: ', imode)
# print(imode, len(self.uz[imode]))
for iuz in self.uz[imode]:
if(iuz):
M = self.source_spectrum(iuz.period)
f = 1./iuz.period
f_tab.append( f )
uz = iuz.compute_veloc(r, phi, M, depth, unknown, dimension_seismic)
# If 1d mesh passed we just append
if(phi.shape[0] == phi.size):
uz_tab.append( uz.reshape(r.size) )
# If 2d r/phi mesh passed
# Create a 1d array with increments in phi and then r
else:
uz_tab.append( uz.reshape(r.shape[1]*r.shape[0],) )
else:
break
response = pd.DataFrame(np.array(uz_tab)) # Transform list into dataframe
response.columns = np.arange(0, phi.size)
response['f'] = np.array(f_tab)
# print(np.array(uz_tab).shape, response.shape)
# stop
return response
def extract_seismic_parameters(self, options):
dimension = 2 if options['type_model'] == 'specfem2d' else 1
self.seismic = velocity_models.read_csv_seismic(options['models'][options['chosen_model']], dimension)
def local_mode(self, r, phi, type, unknown, dimension_seismic, modes):
for imode_num, imode in enumerate(modes):
#print('Computing mode', imode)
response_RW_temp = self.compute_RW_one_mode(imode, r, phi, type, unknown, dimension_seismic)
if(imode_num == 0):
response_RW = response_RW_temp.copy()
else:
# Concatenate dataframes with same freq.
# we can not use pd.concat since it is too slow for complex numbers
response_RW = RWAtmosUtils.concat_df_complex(response_RW, response_RW_temp, 'f')
return response_RW
def response_RW_all_modes(self, r, phi, type = 'RW', unknown = 'd', mode_max = -1, dimension_seismic = 3, ncpus = 16):
mode_max = len(self.uz) if mode_max == -1 else mode_max
if(ncpus<=1):
parallel = False
print('[%s] Get the RW response for all modes. Do the computation in serial.' % (sys._getframe().f_code.co_name))
else:
parallel = True
print('[%s] Get the RW response for all modes. Use multithreading over %d CPUs.' % (sys._getframe().f_code.co_name, ncpus))
if not parallel:
# SUGGESTION: INSTEAD OF ALL OF WHAT FOLLOWS, SIMPLY CALL "self.local_mode(r, phi, type, unknown, dimension_seismic)".
for imode in range(0, mode_max):
#print('Computing mode', imode)
response_RW_temp = self.compute_RW_one_mode(imode, r, phi, type, unknown, dimension_seismic)
if(imode == 0):
response_RW = response_RW_temp.copy()
else:
# Concatenate dataframes with same freq.
# we can not use pd.concat since it is too slow for complex numbers
response_RW = RWAtmosUtils.concat_df_complex(response_RW, response_RW_temp, 'f')
else:
modes = [key for key in range(0, mode_max)]
N = ncpus # How many subtasks should be prepared.
list_of_lists = [sublist for sublist in np.array_split(modes, N) if sublist.size>0] # Split the modes over the requested number of CPUs.
N = len(list_of_lists) # Make sure the requested N correspond to the number of prepared lists.
local_mode_partial = partial(self.local_mode, r, phi, type, unknown, dimension_seismic)
if self.use_spawn:
with get_context("spawn").Pool(processes = N) as p:
results = p.map(local_mode_partial, list_of_lists)
else:
with mp.Pool(processes = N) as p:
results = p.map(local_mode_partial, list_of_lists)
response_RW = results[0]
for imode, result in enumerate(results): response_RW = RWAtmosUtils.concat_df_complex(response_RW, result, 'f');
if(np.all(np.isnan(response_RW[0]))):
# Safeguard.
sys.exit('[%s, ERROR] All values in the Rayleigh wave response are NaNs. Something went terribly wrong.' % (sys._getframe().f_code.co_name))
return response_RW
def response_perturbed_solution(self, x, r, phi, type = 'RW', unknown = 'd', mode_max = -1, dimension_seismic = 3, type_opti='min'):
# dip, strike and rake perturbations
p_strike, p_dip, p_rake = x[0], x[1], x[2]
# Create source from perturbations
mechanism = self.get_mechanism()
mt = mechanism['mt']
strike0, dip0, rake0 = mt.both_strike_dip_rake()[0]
strike, dip, rake = strike0 + p_strike, dip0 + p_dip, rake0 + p_rake
m0 = mt.scalar_moment()
mt = mtm.MomentTensor(strike=strike, dip=dip, rake=rake, scalar_moment=m0)
mechanism_save = mechanism.copy()
mechanism['M'] = mt.m6_up_south_east()
self.set_mechanism(mechanism)
mode_max = len(self.uz) if mode_max == -1 else mode_max
for imode in range(0, mode_max):
response_RW_temp = self.compute_RW_one_mode(imode, r, phi, type, unknown, dimension_seismic)
if(imode == 0):
response_RW = response_RW_temp.copy()
else:
# Concatenate dataframes with same freq.
# we can not use pd.concat since it is too slow for complex numbers
response_RW = RWAtmosUtils.concat_df_complex(response_RW, response_RW_temp, 'f')
self.set_mechanism(mechanism_save)
coef = 1. if type_opti == 'min' else -1.
return coef * abs(response_RW.loc[:, response_RW.columns != 'f'].values).max(axis=0)[0]
def compute_ifft(self, r_in, phi_in, type, unknown = 'd', mode_max = -1, dimension_seismic = 3, ncpus=16):
# Collect the positive-frequency response of each RW mode
RW = self.response_RW_all_modes(r_in, phi_in, type, unknown, mode_max, dimension_seismic, ncpus)
RW = RW.sort_values(by=['f'], ascending=True)
# Positive frequencies
RW_first = RW.iloc[0:1].copy()
temp = pd.DataFrame(RW_first.values*0.)
temp.columns = RW_first.columns
RW_first = temp.copy()
# Negative frequencies
RW_neg = RW.iloc[:].copy()
RW_neg.loc[:,'f'] = -RW_neg.loc[:,'f']
RW = RW_first.append(RW.iloc[:-1])
RW_neg = RW_neg.sort_values(by=['f'], ascending=True)
temp = pd.DataFrame(np.real(RW_neg.iloc[:1].values))
temp.columns = RW_neg.columns
RW_neg = temp.append(RW_neg.drop([0]))
temp = pd.DataFrame(np.real(RW_neg.loc[:, RW_neg.columns != 'f']) + 1j*np.imag(RW_neg.loc[:, RW_neg.columns != 'f']))
temp['f'] = RW_neg['f']
RW_neg = temp.copy()
temp = pd.DataFrame(np.real(RW.loc[:, RW.columns != 'f']) - 1j*np.imag(RW.loc[:, RW.columns != 'f']))
temp['f'] = RW['f'].values
RW = temp.copy()
# Concatenate negative and positive frequencies
RW_tot = pd.concat([RW_neg,RW], ignore_index=True)
# Compute inverse Fourier transform
ifft_RW = fftpack.ifft(fftpack.fftshift(RW_tot.values[:,:-1], axes=0), axis=0)
nb_fft = ifft_RW.shape[0]//2
ifft_RW = ifft_RW[:nb_fft]
# # Compute corresponding time array
dt = 1./(2.*abs(RW_neg['f']).max())
t = np.arange(0, dt*nb_fft, dt)
# t = None # If using the updated frequencies in field_RW.__init__, then the time vector is not needed here.
return (t, ifft_RW)
def generate_one_timeseries(t, Mz_t, RW_Mz_t, comp, iz, iy, ix, stat, options, outputToFile=True, makePlot=True):
output_folder = options['output_folder']
# Time series asked by user.
ts_comp = pd.DataFrame()
ts_comp['t'] = t
ts_comp[comp] = np.real(Mz_t)
if(outputToFile):
name_file = 'waveform_'+comp+'_'+str(stat)+'_'+str(round(ix/1000.,1))+'_'+str(round(iy/1000.,1))+'_'+str(round(iz/1000.,1))+'.csv'
output_file = output_folder+name_file
ts_comp.to_csv(output_file, index=False)
print('[%s] Save waveform to \'%s\'.' % (sys._getframe().f_code.co_name, output_file))
# Rayleigh wave time series.
ts_rw = pd.DataFrame()
ts_rw['t'] = t
ts_rw['vz'] = np.real(RW_Mz_t)
if(outputToFile):
name_file = 'RW_waveform_z0_'+comp+'_'+str(stat)+'_'+str(round(ix/1000.,1))+'_'+str(round(iy/1000.,1))+'_'+str(round(iz/1000.,1))+'.csv'
output_file = output_folder+name_file
ts_rw.to_csv(output_file, index=False)
print('[%s] Save waveform to \'%s\'.' % (sys._getframe().f_code.co_name, output_file))
if(makePlot):
# Create frequency/time plot.
#freq_min, freq_max = Green_RW.f0/10., Green_RW.f0*2.
freq_min, freq_max = options['coef_low_freq'], options['coef_high_freq']
tr = RWAtmosUtils.generate_trace(t, np.real(Mz_t), freq_min, freq_max)
fig = plot_tfr(tr.data, dt=tr.stats.delta,
fmin=freq_min, fmax=freq_max,
w0=4., nf=64, fft_zero_pad_fac=4,
show=False, t0=0.,
left=0.16, bottom=0.12, w_2=0.5, )
fig.axes[0].grid()
fig.axes[0].set_xlabel('Time (s)')
fig.axes[2].grid()
fig.axes[2].set_ylabel('Frequency (Hz)')
fig.axes[1].text(0.1, 1.08, 'E = '+str(round(ix/1000.,1))+' S = '+str(round(iy/1000.,1))+' U = '+str(round(iz/1000.,1)) +' km',
horizontalalignment='center', verticalalignment='center',
bbox=dict(facecolor='w', edgecolor='black', pad=4.0),
transform=fig.axes[1].transAxes)
name_file = 'freq_time_'+comp+'_'+str(stat)+'_'+str(round(ix/1000.,1))+'_'+str(round(iy/1000.,1))+'_'+str(round(iz/1000.,1))+'.png'
output_file = output_folder + name_file
fig.set_size_inches(16, 8)
fig.tight_layout()
fig.savefig(output_file)
plt.close('all')
return(ts_comp, ts_rw)
class field_RW():
def __str__(self):
out = ''
out = out + '+-------------------------------+\n'
out = out + ('| %dD Rayleigh Wave Field |\n' % (self.dimension))
out = out + '+-------------------------------+\n'
out = out + '| Seismic model: |\n'
out = out + str(self.seismic)+'\n'
out = out + '+-------------------------------+\n'
out = out + ('| X-Y domain: |\n')
out = out + ('| x: [%.5e, %.5e] m, %d elements, dx = %.6f\n'
% (np.min(self.x), np.max(self.x), self.x.size, np.mean(np.diff(self.x))))
out = out + ('| y: [%.5e, %.5e] m, %d elements, dy = %.6f\n'
% (np.min(self.y), np.max(self.y), self.y.size, np.mean(np.diff(self.y))))
out = out + ('| Atmospheric model: |\n')
if(not self.atmospheric_model_is_generated):
out = out + ('| none (atmospheric model is not defined yet).\n')
else:
out = out + ('| z: [%.5e, %.5e] m, %d elements, dz = %.6f\n'
% (np.min(self.z), np.max(self.z), self.z.size, np.mean(np.diff(self.z))))
if(self.isothermal):
out = out + ('| Isothermal model. |\n')
else:
out = out + ('| User-defined model: |\n')
out = out + ('| rho: %d elements (density)\n' % (self.rho.size))
out = out + ('| cpa: %d elements (sound speed)\n' % (self.rho.size))
out = out + ('| winds_x: %d elements\n' % (self.winds[0].size))
out = out + ('| winds_y: %d elements\n' % (self.winds[1].size))
out = out + ('| bulk: %d elements\n' % (self.bulk.size))
out = out + ('| shear: %d elements\n' % (self.shear.size))
out = out + ('| kappa: %d elements\n' % (self.kappa.size))
out = out + ('| cp: %d elements (isobaric specific heat capacity)\n' % (self.rho.size))
out = out + ('| gamma: %d elements\n' % (self.gamma.size))
out = out + ('| H: %d elements (scale height)\n' % (self.H.size))
out = out + ('| Nsq: %d elements (Brunt-Väisälä frequency)\n' % (self.rho.size))
out = out + '+-------------------------------+\n'
out = out + ('| T domain (from IFFT): |\n')
out = out + ('| t: [%.3f, %.6f] s, %d elements, dt = %.6f\n'
% (np.min(self.t), np.max(self.t), self.t.size, np.mean(np.diff(self.t))))
out = out + '+-------------------------------+\n'
out = out + ('| Frequency domain: |\n')
if(self.dimension==3):
out = out + ('| Omega, KX, KY: %d*%d*%d meshgrid (frequency, x, y)\n'
% self.KX.shape)
out = out + ('| Forcing: |\n')
out = out + ('| Mo: %d*%d*%d meshgrid for bottom forcing\n'
% self.Mo.shape)
out = out + ('| TFMo: %d*%d*%d meshgrid for Fourier transform of bottom forcing\n'
% self.Mo.shape)
else:
out = out + ('| Omega, KX: %d*%d meshgrid (frequency, x)\n'
% self.KX.shape)
out = out + ('| Forcing: |\n')
out = out + ('| Mo: %d*%d meshgrid for bottom forcing\n'
% self.Mo.shape)
out = out + ('| TFMo: %d*%d meshgrid for Fourier transform of bottom forcing\n'
% self.Mo.shape)
out = out + '+-------------------------------+\n'
return(out)
def __repr__(self):
# Technically wrong, because repr should contain everything needed to build the instance again, but enough for what we want.
return(self.__str__())
default_loc = (30., 0.) # (km, degree)
def __init__(self, Green_RW, nb_freq, dimension = 2, dx_in = 100., dy_in = 100., xbounds = [100., 100000.], ybounds = [100., 100000.], mode_max = -1, dimension_seismic = 3, ncpus = 16):
def nextpow2(x):
return np.ceil(np.log2(abs(x)))
self.atmospheric_model_is_generated = False
self.global_folder = Green_RW.global_folder # Save folder path from Green's class
self.coef_low_freq = [Green_RW.f_tab[0], Green_RW.f_tab[-1]]
self.type_output = 'a'
#########################
# Initial call to Green_RW to get the time vector only.
output = Green_RW.compute_ifft(np.array([field_RW.default_loc[0]]), np.array([field_RW.default_loc[1]]), type='RW', unknown=self.type_output, dimension_seismic = dimension_seismic, ncpus = ncpus)
t = output[0]
# # Probably a good idea to simply compute it analytically using the updated frequencies:
# dt_anal = 1.0/(2.0*Green_RW.f_tab_actualforMode1.max())
# t = np.arange(0, Green_RW.nb_freqs_actualforMode1) * dt_anal
# Store seismic model
self.seismic = Green_RW.seismic
self.google_colab = Green_RW.google_colab
# Define time/spatial domain boundaries
# mult_tSpan, mult_xSpan, mult_ySpan = 1, 1, 1
mult_xSpan, mult_ySpan = 1, 1
dt_anal, dx_anal, dy_anal = abs(t[1] - t[0]), dx_in, dy_in # Using the dt computed from the updated frequencies above.
# dx_anal, dy_anal = dx_in, dy_in
xmin, xmax = xbounds[0], xbounds[1]
if(dimension > 2):
ymin, ymax = ybounds[0], ybounds[1]
# Define frequency/wavenumber boundaries
# NFFT1 = int(2**nextpow2((xmax-xmin)/dx_anal)*mult_xSpan)
NFFT1 = int(mult_xSpan * (xmax-xmin)/dx_anal)
NFFT2 = len(t)
# NFFT2 = Green_RW.nb_freqs_actualforMode1 # Using the updated frequencies.
if(dimension > 2):
# NFFT3 = int(2**nextpow2((ymax-ymin)/dy_anal)*mult_ySpan)
NFFT3 = int(mult_ySpan * (ymax-ymin)/dy_anal)
# Check if even numbers.
if(NFFT1%2==1):
raise ValueError('[%s] NFFT1 (related to the x vector) is odd. This will cause problems later. Make sure dx is such that NFFT1 is even.'
% (sys._getframe().f_code.co_name))
if(NFFT2%2==1):
raise ValueError('[%s] NFFT2 (related to the t vector) is odd. This will cause problems later. Make sure t has an even length.'
% (sys._getframe().f_code.co_name))
if(dimension > 2 and NFFT3%2==1):
raise ValueError('[%s] NFFT3 (related to the y vector) is odd. This will cause problems later. Make sure dy is such that NFFT1 is even.'
% (sys._getframe().f_code.co_name))
# Define corresponding time and spatial arrays
x = np.linspace(xmin, xmax, NFFT1)
# t = dt_anal * np.arange(0,NFFT2) # Already computed at beginning of function (either with Green_RW.compute_ifft or analytically).
if(dimension > 2):
y = np.linspace(ymin, ymax, NFFT3)
else:
y = np.array([Green_RW.phi])
# Define corresponding Frequency Wavenumber arrays
omega = 2.0*np.pi*(1.0/(dt_anal*NFFT2))*np.concatenate((np.arange(0,NFFT2/2), -np.arange(NFFT2/2,0,-1)))
kx = 2.0*np.pi*(1.0/(dx_anal*NFFT1))*np.concatenate((np.arange(0,NFFT1/2), -np.arange(NFFT1/2,0,-1)))
if(dimension > 2):
ky = 2.0*np.pi*(1.0/(dy_anal*NFFT3))*np.concatenate((np.arange(0,NFFT3/2), -np.arange(NFFT3/2,0,-1)))
if(dimension > 2):
KX, Omega, KY = np.meshgrid(kx, omega, ky)
else:
KX, Omega = np.meshgrid(kx, omega)
# Initialize bottom RW forcing.
# Mo = np.zeros(Omega.shape, dtype=complex) # No need for initialisation since it's completely replaced by a further call.
# Conversion of cartesian coordinates into cylindrical coordinates for 3d
if(dimension > 2):
Y, X = np.meshgrid(y, x)
R = np.sqrt( X**2 + Y**2 )
ind_where_yp0 = np.where(Y>0)
PHI = X*0.
PHI[ind_where_yp0] = np.arccos( X[ind_where_yp0]/R[ind_where_yp0] )
ind_where_yp0 = np.where(Y<0)
PHI[ind_where_yp0] = -np.arccos( X[ind_where_yp0]/R[ind_where_yp0] )
else:
R = abs(x)
PHI = 0. + R*0.
PHI[:len(x)//2] = np.pi
PHI += np.pi/2.
# Compute bottom RW forcing for all modes.
# Will run through all existing uz for each mode, meaning only the ones with existing frequencies will be added (see compute_ifft > response_RW_all_modes > compute_RW_one_mode).
# In short, the resulting Mo (or ifft_RW) will have self.nb_freq_filled frequencies, and NOT self.nb_freq.
temp = Green_RW.compute_ifft(R/1000., PHI, type='RW', unknown=self.type_output, mode_max = mode_max, dimension_seismic = dimension_seismic, ncpus = ncpus)
if(dimension > 2):
t, Mo = temp[0], temp[1].reshape( (temp[1].shape[0], PHI.shape[0], PHI.shape[1]) )
else:
t, Mo = temp[0], temp[1].reshape( (temp[1].shape[0], PHI.size) )
# # If using the updated frequencies above, then the time vector is not needed.
# if(dimension > 2):
# Mo = temp[1].reshape( (temp[1].shape[0], PHI.shape[0], PHI.shape[1]) )
# else:
# Mo = temp[1].reshape( (temp[1].shape[0], PHI.size) )
if(np.all(np.isnan(Mo))):
# Safeguard.
sys.exit('[%s, ERROR] All values in the Rayleigh wave forcing are NaNs. Something went terribly wrong.'
% (sys._getframe().f_code.co_name))
# Store forcing parameters
self.Mo = Mo
self.TFMo = fftpack.fftn(self.Mo)
self.Omega = Omega
self.KX = -KX
if(dimension > 2):
self.KY = -KY
# Compute vertical wavenumber
#self.compute_vertical_wavenumber(TFMo, H, Nsq, winds)
self.dimension = dimension
# Store mesh parameters
self.x = x
self.y = y
self.t = t
def generate_atmospheric_model(self, param_atmos):
self.atmospheric_model_is_generated = True
# Remove errors
np.seterr(divide='ignore', invalid='ignore')
self.isothermal = param_atmos['isothermal']
if(self.isothermal):
self.H = np.array([param_atmos['H']])
self.cpa = np.array([param_atmos['cpa']])
self.Nsq = np.array([param_atmos['Nsq']])
self.winds = []
self.winds.append( np.array([param_atmos['wind_x']]) )
self.winds.append( np.array([param_atmos['wind_y']]) )
self.bulk = np.array([param_atmos['bulk']])
self.shear = np.array([param_atmos['shear']])
self.kappa = np.array([param_atmos['kappa']])
self.gamma = np.array([param_atmos['gamma']])
self.rho = np.array([param_atmos['rho']])
self.cp = np.array([param_atmos['cp']])
else:
temp = RWAtmosUtils.loadAtmosphericModel(param_atmos['file'])
# temp['bulk'] = 2e-4
# temp['mu'] = 2e-4
if(param_atmos['subsampling']):
nb_layers = param_atmos['subsampling_layers']
temp_i = pd.DataFrame()
zi = np.linspace(temp['z'].min(), temp['z'].max(), nb_layers)
temp_i['z'] = zi
for (columnName, columnData) in temp.iteritems():
if('z' in columnName):
continue
f = interpolate.interp1d(temp['z'].values, columnData.values, kind='cubic')
unknown = f(zi)
temp_i[columnName] = unknown.copy()
temp = temp_i.copy()
self.z = temp['z'].values
zshift = -(np.roll(self.z, 1) - self.z)
pshift = np.log( np.roll(temp['p'].values, 1)/temp['p'].values )
locbad = np.where(zshift <= 0)
if(locbad[0].size > 0):
zshift[locbad] = zshift[locbad[0][-1]+1]
locbad = np.where(pshift <= 0)
if(locbad[0].size > 0):
pshift[locbad] = pshift[locbad[0][-1]+1]
self.H = zshift/pshift
self.Nsq = np.sqrt(-(temp['g'].values/temp['rho'].values[0])*np.gradient(temp['rho'].values, self.z, edge_order=2))**2
self.Nsq[0] = self.Nsq[1]
self.winds = []
self.winds.append( temp['wx'].values )
self.winds.append( temp['wy'].values )
self.cpa = temp['cpa'].values
self.rho = temp['rho'].values
self.bulk = temp['bulk'].values
self.shear = temp['mu'].values
self.kappa = temp['kappa'].values
self.cp = temp['cp'].values
self.gamma = temp['gamma'].values
def compute_vertical_wavenumber(self, id_layer, correct_wavenumber = True, exact_computation = False):
# Ignore division/invalid errors in KZ computation
np.seterr(divide='ignore', invalid='ignore')
# Get corresponding atmospheric parameters
H = self.H[id_layer]
Nsq = self.Nsq[id_layer]
wind_x = self.winds[0][id_layer]
wind_y = self.winds[1][id_layer]
cpa = self.cpa[id_layer]
bulk = self.bulk[id_layer]
shear = self.shear[id_layer]
kappa = self.kappa[id_layer]
gamma = self.gamma[id_layer]
rho = self.rho[id_layer]
cp = self.cp[id_layer]
# Compute intrinsic frequencies
Omega_intrinsic = self.Omega - wind_x*self.KX
if(self.dimension > 2):
Omega_intrinsic -= wind_y*self.KY
#
if(not exact_computation):
if(self.dimension > 2):
KZ = np.lib.scimath.sqrt( -self.KX**2 -self.KY**2 + (self.KX**2 + self.KY**2) * Nsq/(Omega_intrinsic**2) -1./(4.*H**2) \
+ (1.+1j*(bulk+(4./3.)*shear+kappa*(gamma-1.)/cp)*Omega_intrinsic/(2.*rho*cpa**2))*(Omega_intrinsic / cpa )**2 )
else:
KZ = np.lib.scimath.sqrt( -self.KX**2 + (self.KX**2) * Nsq/(Omega_intrinsic**2) -1./(4.*H**2) \
+ (1.+1j*(bulk+(4./3.)*shear+kappa*(gamma-1.)/cp)*Omega_intrinsic/(2.*rho*cpa**2))*(Omega_intrinsic / cpa )**2 )
# Exact dispersion equation from Godin, Dissipation of acoustic-gravity waves:An asymptotic approach, 2014.
# This whole section is not used anywhere, we comment it out.
# else:
# if(self.dimension > 2):
# kx, ky, kz, Omega = symbols('kx, ky, kz, Omega')
# H_, Nsq_, cpa_, rho_, shear_ = symbols('H, gz, c0, rho0, eta0')
# # From Godin, Dissipation of acoustic-gravity waves: An asymptotic approach, 2014
# # eq. (9)
# KZ_exact = solve( \
# (Omega/cpa_)**2 + (kx**2 + ky**2)*Nsq_/Omega**2 \
# + (1j/( Omega*rho_ )) * ( \
# ( ( 7*(Omega**2)/(3*cpa_**2) - kx**2 - ky**2 - kz**2 -1./(4*H_**2) )*( kx**2 + ky**2 + (kz - 1j/(2*H_))**2 ) )*shear_ \
# + ( ((Omega/cpa_)**2) * ( kx**2 + ky**2 + (kz - 1j/(2*H_))**2 ) )*bulk \
# ) - kx**2 - ky**2 - kz**2 -1./(4*H_**2) \
# , kz)
# func = lambdify([kx, ky, Omega, H_, Nsq_, cpa_, rho_, shear_], KZ_exact[1].evalf())
# KZ_ = func(0j+self.KX.reshape(Omega_intrinsic.shape[0]*Omega_intrinsic.shape[1]*Omega_intrinsic.shape[2]), \
# 0j+self.KY.reshape(Omega_intrinsic.shape[0]*Omega_intrinsic.shape[1]*Omega_intrinsic.shape[2]), \
# 0j+Omega_intrinsic.reshape(Omega_intrinsic.shape[0]*Omega_intrinsic.shape[1]*Omega_intrinsic.shape[2]), \
# H, Nsq, cpa, rho, shear).reshape(\
# Omega_intrinsic.shape[0], Omega_intrinsic.shape[1], Omega_intrinsic.shape[2])
# else:
# kx, kz, Omega = symbols('kx, kz, Omega')
# # From Godin, Dissipation of acoustic-gravity waves: An asymptotic approach, 2014
# # eq. (9)
# KZ_exact = solve( \
# (Omega/cpa)**2 + (kx**2)*Nsq/Omega**2 \
# + (1j/( Omega*rho )) * ( \
# ( ( 7*(Omega**2)/(3*cpa**2) - kx**2 - kz**2 -1./(4*H**2) )*( kx**2 + (kz - 1j/(2*H))**2 ) )*shear \
# + ( ((Omega/cpa)**2) * ( kx**2 + ky**2 + (kz - 1j/(2*H))**2 ) )*bulk \
# ) - kx**2 - kz**2 -1./(4*H**2) \
# , kz)
# func = lambdify([kx,ky,Omega], KZ_exact[1].evalf())
# KZ_ = func(0j+self.KX.reshape(Omega_intrinsic.shape[0]*Omega_intrinsic.shape[1]*Omega_intrinsic.shape[2]), \
# 0j+self.KY.reshape(Omega_intrinsic.shape[0]*Omega_intrinsic.shape[1]*Omega_intrinsic.shape[2]), \
# 0j+Omega_intrinsic.reshape(Omega_intrinsic.shape[0]*Omega_intrinsic.shape[1]*Omega_intrinsic.shape[2])).reshape(\
# Omega_intrinsic.shape[0],Omega_intrinsic.shape[1],Omega_intrinsic.shape[2])
# Remove infinite/nan numbers that correspond to zero frequencies
KZ = np.nan_to_num(KZ, 0.)
# Correct wavenumbers to remove non-physical solutions
if(correct_wavenumber):
indimag = np.where(np.imag(KZ)<0)
KZ[indimag] = np.conjugate(KZ[indimag])
KZ = 0.0 - np.real(KZ)*np.sign(Omega_intrinsic) + 1j*np.imag(KZ)
# Deallocate
Omega_intrinsic = None
return KZ
# Find all layers for which we have to compute the wavenumbers
def _find_id_layers_and_heights(self, z0, z1, zlayer):
id_layers = []
h_layers = []
id_first_layer = 0
if(z0 > zlayer[0]):
id_first_layer = np.where(zlayer<z0)[0][-1]
id_last_layer = 0
if(z1 > zlayer[0]):
id_last_layer = np.where(zlayer<z1)[0][-1]
zprev = z0
for current_id in range(id_first_layer, id_last_layer):
h = zlayer[current_id+1]-zprev
if(h > 0):
h_layers.append( h )
id_layers.append( current_id )
zprev = zlayer[current_id+1]
# Last element
if not id_first_layer == id_last_layer:
h = z1-zlayer[id_last_layer]
else:
h = z1-z0
if(h > 0):
h_layers.append( h )
id_layers.append( id_last_layer )
return h_layers, id_layers
def compute_response_at_given_z(self, z1_in, z0, TFMo_in, comp, KZ_in = [], last_layer_in = -1, return_only_KZ = False, only_TFMo_integration = False):
'''
If return_only_KZ == True, compute_response_at_given_z returns 1j * sum_i KZ_i * h_i in TFMo
'''