-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathRW_atmos.py
1532 lines (1168 loc) · 80 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 Symbol, symbols, solve
from sympy.utilities.lambdify import lambdify
from multiprocessing import set_start_method, get_context
## Local modules
import mechanisms as mod_mechanisms
import utils, velocity_models, RW_dispersion
## 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):
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.) )
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 __init__(self, options):
## Inputs
self.f_tab = options['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, len(self.f_tab)) ] for bb in range(0, options['nb_modes'][1]) ]
self.uz = [ [ [] for aa in range(0, len(self.f_tab)) ] for bb in range(0, options['nb_modes'][1]) ]
## Extract seismic model for later plots
self.extract_seismic_parameters(options)
## Add source characteristics
#self.update_mechanism(mechanism)
## 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 update_mechanism(self, mechanism):
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.mt = []
if 'mt' in mechanism:
self.mt = mechanism['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['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 = []
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]
I1 = 0.5*spi.simps(rho[:]*( r1**2 + r2**2 ), dep[:])
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 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)
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)
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 = utils.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):
import multiprocessing as mp
from functools import partial
mode_max = len(self.uz) if mode_max == -1 else mode_max
parallel = True
if not parallel:
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 = utils.concat_df_complex(response_RW, response_RW_temp, 'f')
else:
modes = [key for key in range(0, mode_max)]
N = 16
list_of_lists = [sublist for sublist in np.array_split(modes, N) if sublist.size>0]
N = len(list_of_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 = utils.concat_df_complex(response_RW, result, 'f');
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.update_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 = utils.concat_df_complex(response_RW, response_RW_temp, 'f')
self.update_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):
## 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)
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)
return (t, ifft_RW)
def generate_one_timeseries(t, Mz_t, RW_Mz_t, comp, iz, iy, ix, stat, options):
## Save waveforms
df = pd.DataFrame()
df['t'] = t
df['vz'] = np.real(Mz_t)
name_file = 'waveform_'+comp+'_'+str(stat)+'_'+str(round(ix/1000.,1))+'_'+str(round(iy/1000.,1))+'_'+str(round(iz/1000.,1))+'.csv'
df.to_csv(options['global_folder'] + name_file, index=False)
print('save waveform to: '+options['global_folder'] + name_file)
## Deallocate
df = None
df = pd.DataFrame()
df['t'] = t
df['vz'] = np.real(RW_Mz_t)
name_file = 'RW_waveform_z0_'+comp+'_'+str(stat)+'_'+str(round(ix/1000.,1))+'_'+str(round(iy/1000.,1))+'_'+str(round(iz/1000.,1))+'.csv'
df.to_csv(options['global_folder'] + name_file, index=False)
print('save waveform to: '+options['global_folder'] + name_file)
## Deallocate
df = None
## 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 = utils.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)
if(not options['GOOGLE_COLAB']):
name_file = 'freq_time_'+comp+'_'+str(stat)+'_'+str(round(ix/1000.,1))+'_'+str(round(iy/1000.,1))+'_'+str(round(iz/1000.,1))+'.png'
plt.savefig(options['global_folder'] + name_file)
plt.close('all')
tr, fig = None, None
class field_RW():
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):
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
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)
t = output[0]
## 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
dt_anal, dx_anal, dy_anal = abs(t[1] - t[0]), 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)
NFFT2 = len(t)
if(dimension > 2):
NFFT3 = int(2**nextpow2((ymax-ymin)/dy_anal)*mult_ySpan)
## Define corresponding time and spatial arrays
x = np.linspace(xmin, xmax, NFFT1)
t = dt_anal * np.arange(0,NFFT2)
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)
## 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
temp = Green_RW.compute_ifft(R/1000., PHI, type='RW', unknown=self.type_output, mode_max = mode_max, dimension_seismic = dimension_seismic)
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) )
## 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:
try:
temp = pd.read_csv( param_atmos['file'], delim_whitespace=True, header=None )
temp.columns = ['z', 'rho', 'dummy1', 'cpa', 'p', 'dummy2', 'g', 'dummy3', 'kappa', 'mu', 'dummy4', 'dummy5', 'dummy6', 'wx', 'cp', 'cv', 'gamma']
temp['bulk'] = temp['mu']
temp['wy'] = temp['wx']
except:
temp = pd.read_csv( param_atmos['file'], delim_whitespace=True, header=None )
temp.columns = ['z', 'rho', 'cpa', 'p', 'g', 'kappa', 'mu', 'bulk', 'wx', 'wy', 'cp', 'cv', 'gamma']
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
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
'''
## Exit messages
if(only_TFMo_integration and return_only_KZ):
sys.exit('In "compute_response_at_given_z": Can not only integrate TFMo and only return KZ simultaneously!')
try:
if(only_TFMo_integration and not KZ_in):
sys.exit('In "compute_response_at_given_z": Can not only integrate TFMo without KZ provided!')
except:
pass
## If pressure amplitude decreases with altitude
coef_amplitude = 1. if comp == 'vz' else -1.
## If we return only KZ, TFMo will contain sum 1j*KZ*z1
if(not return_only_KZ):
TFMo = TFMo_in.copy()
else:
TFMo = np.zeros(self.TFMo.shape, dtype=complex)
multiple_altitudes_submitted = False
if(len(z1_in) > 1):
multiple_altitudes_submitted = True
last_layer = last_layer_in
KZ_tab, field_at_it_tab = [], []
for id_z1, z1 in enumerate(z1_in):
field_at_it = []
if(only_TFMo_integration and multiple_altitudes_submitted):
KZ = KZ_in[id_z1].copy()
else:
KZ = KZ_in.copy()
## We only compute the solution if we are not at the surface or below
if(z1 > 0):
## If isothermal model
if(self.isothermal):
## Compute the vertical response from the ground forcing
if(not KZ):
KZ = self.compute_vertical_wavenumber(0)
if(not return_only_KZ):
field_at_it = np.exp(coef_amplitude*z1/(2*self.H[0])) * fftpack.ifftn( np.exp(1j*(KZ*z1)) * TFMo)
## If layered model
else:
#local_inner_loop = partial(self.inner_loop, TFMo, there_is_vz, TFMo_p, there_is_p, x_in, y_in, z_in, comp_in, name_in, t_chosen_in, id_in)
#N = 4#mp.cpu_count()
#with mp.Pool(processes = N) as p:
# results = p.map(local_inner_loop, combinaisons)
h_layers, id_layers = self._find_id_layers_and_heights(z0, z1, self.z)
for idx, id_layer in enumerate(id_layers):
## Compute the vertical response from the forcing of the layer beneath (idz-1)
if(not last_layer == id_layer):
KZ = self.compute_vertical_wavenumber(id_layer)
if(not return_only_KZ and not only_TFMo_integration):
TFMo *= np.exp(coef_amplitude*h_layers[idx]/(2*self.H[id_layer])) * np.exp(1j*(KZ*h_layers[idx]))
elif(not return_only_KZ):
TFMo *= np.exp(coef_amplitude*h_layers[idx]/(2*self.H[id_layer])) #* np.exp(1j*(KZ*h_layers[idx]))
else:
TFMo += 1j*(KZ * h_layers[idx])
if(only_TFMo_integration):
TFMo *= np.exp(KZ)
if(not return_only_KZ):
field_at_it = fftpack.ifftn( TFMo )
if( len(z1_in) == id_z1+1 ):
last_layer = id_layer
z0 = z1
elif(not return_only_KZ):
field_at_it = fftpack.ifftn(TFMo)
if(multiple_altitudes_submitted):
if(not return_only_KZ):
field_at_it_tab.append( field_at_it.copy() )
else:
KZ_tab.append( TFMo.copy() )
if(multiple_altitudes_submitted):
return field_at_it_tab, last_layer, KZ, KZ_tab
else:
return field_at_it, last_layer, KZ, TFMo
def convert_TFMo_to_pressure(self):
## Ignore division/invalid errors in P computation
np.seterr(divide='ignore', invalid='ignore')
KZ = self.compute_vertical_wavenumber(0, correct_wavenumber = True)
indnot0 = np.where(abs(self.Omega) > 0)
P = np.zeros(self.Omega.shape, dtype=complex)
P[indnot0] = self.rho[0]*(self.cpa[0]**2)*KZ[indnot0]*self.TFMo[indnot0]/(self.Omega[indnot0])
P = np.nan_to_num(P, 0.)
#bp()
del KZ
return P
def get_index_tabs(self, t, x, y):
## Get required time index
it = np.argmin( abs(self.t - t) )
## Get required location index
ix = np.argmin( abs(self.x - x) )
iy = -1
if(self.dimension > 2):
iy = np.argmin( abs(self.y - y) )
return it, ix, iy
## Compute wavefield for a given physical domain
def compute_field_for_xz(self, t, x, y, z, zvect, type_slice, comp):
## Build a response matrix based on required slice dimensions
if(type_slice == 'z'):
d1, d2 = len(zvect), len(self.x)
Mz_xz = np.zeros((d1, d2), dtype=complex)
if(self.dimension > 2):
d1, d2 = len(zvect), len(self.y)
Mz_yz = np.zeros((d1, d2), dtype=complex)
elif(type_slice == 'xy'):
d1, d2 = len(self.x), len(self.y)
Mz_xy = np.zeros((d1, d2), dtype=complex)
zvect = [z]
else:
sys.exit('Slice "'+str(type_slice)+'" not recognized!')
## Get required time index
# modif 5/1/2020
#it = np.argmin( abs(self.t - t) )
it, ix, iy = self.get_index_tabs(t, x, y)
## setup progress bar
if(len(zvect) > 1):
cptbar = 0
toolbar_width = 40
total_length = len(zvect)
sys.stdout.write("Building wavefield: [%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '['
## Load initial surface forcing
if(comp == 'vz'):
TFMo = self.TFMo.copy()
else:
TFMo = self.convert_TFMo_to_pressure().copy()
## Find location of balloon to extract time series
zloc = np.argmin( abs(z - np.array(zvect)) )
iz_prev = 0.
last_layer_prev = -1
KZ_prev = []
## Loop over all layers
for idz, iz in enumerate(zvect):
field_at_it, last_layer, KZ, TFMo = self.compute_response_at_given_z([iz], iz_prev, TFMo, comp, KZ_prev, last_layer_prev)
## Store wavenumber if a new wavenumber has been computed
if(last_layer > -1):
last_layer_prev = last_layer
KZ_prev = KZ.copy()
iz_prev = iz
## 3d
if(self.dimension > 2):
if(type_slice == 'z'):
# modif 5/1/2020
#iy = np.argmin( abs(self.y - y) )
Mz_xz[idz, :] = field_at_it[it,:,iy]
#ix = np.argmin( abs(self.x - x) )
Mz_yz[idz, :] = field_at_it[it,ix,:]
## Save time serie
if(idz == zloc):
timeseries = field_at_it[:,ix,iy]
elif(type_slice == 'xy'):
Mz_xy[:, :] = field_at_it[it,:,:]
## Save time serie
if(idz == zloc):
# modif 5/1/2020
#iy = np.argmin( abs(self.y - y) )
#ix = np.argmin( abs(self.x - x) )
timeseries = field_at_it[:,ix,iy]
## 2d
else:
Mz_xz[idz, :] = field_at_it[it,:]
## Save time series
if(idz == zloc):
# modif 5/1/2020
#ix = np.argmin( abs(self.x - x) )
timeseries = field_at_it[:,ix]
## update the bar
if(len(zvect) > 1):
if(int(toolbar_width*idz/total_length) > cptbar):
cptbar = int(toolbar_width*idz/total_length)
sys.stdout.write("-")
sys.stdout.flush()
if(len(zvect) > 1):
sys.stdout.write("] Done\n")
if(self.dimension > 2 and type_slice == 'z'):
return Mz_xz, Mz_yz, timeseries
elif(self.dimension > 2 and type_slice == 'xy'):
return Mz_xy, timeseries
else:
return Mz_xz, timeseries
def compute_field_timeseries(self, station_in, merged_computation = False, create_timeseries_here = True):
## Extract location and component from station dict
x_in, y_in, z_in = [station_in[stat]['xs'] for stat in station_in], \
[station_in[stat]['ys'] for stat in station_in], \
[station_in[stat]['zs'] for stat in station_in]
comp_in = [station_in[stat]['comp'] for stat in station_in]
name_in = [station_in[stat]['name'] for stat in station_in]
t_chosen_in = [station_in[stat]['t_chosen'] for stat in station_in]
id_in = [station_in[stat]['id'] for stat in station_in]
## Setup progress bar
cptbar = 0
toolbar_width = 40
total_length = len(x_in)
sys.stdout.write("Building time series: [%s]" % (" " * toolbar_width))
sys.stdout.flush()
sys.stdout.write("\b" * (toolbar_width+1)) # return to start of line, after '['
if(merged_computation):
_, _, _, integrated_KZ = self.compute_response_at_given_z(np.unique(z_in).tolist(), 0., [], 'p', return_only_KZ = True) # 'p' is dummy
there_is_vz = False
if('vz' in comp_in):
there_is_vz = True
if(False):
TFMo = self.TFMo.copy()
there_is_p = False
if('p' in comp_in):
there_is_p = True
if(False):
TFMo_p = self.convert_TFMo_to_pressure().copy()