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 | def loop_SDF(paths, dpt1, zlon, zlat, date_vec=[2020, [], [], []], extent=[-180, 180, -90, 90],parameters= [2.8, 2830, 1/12, 0.2], prefix = "WW3-GLOB-30M", **kwargs):
""" Computes the power spectrum of the vertical displacement for Rayleigh waves in m.s.
Saves in netcdf format if save argument True.
Plots in PNG source maps of Rayleigh waves at given intervals depending on plot variables.
Args:
paths (list): [file_bathy, ww3_local_path, longuet_higgins_file]: paths of additional files bathymetry, ww3 p2l file and Longuet-Higgins coefficients
dpt1 (xarray.DataArray): bathymetry grid in m (depth) with dimensions lon x lat
zlon (xarray.DataArray): longitude of bathymetry file (°)
zlat (xarray.DataArray): latitude of bathymetry file (°)
date_vec (list): date vector [year, month, day, hour], with hour in [0, 3, 6, 9, 12, 15, 18, 21].
extent (list, optional): spatial extent format [lon_min, lon_max, lat_min, lat_max].
parameters (list, optional): parameters vS of the crust, density of the crust, minimum frequency, maximum frequency.
prefix (str, optional): prefix of the ww3 p2l file.
plot (bool, optional): plot maps.
plot_hourly (bool, optional): plot maps every 3-hours default = False.
plot_daily (bool, optional): plot maps every day, default = False.
plot_monthly (bool, optional): plot maps every month, default = True.
plot_yearly (bool, optional): plot map for the year average, default = False.
save (bool, optional): save 3-hourly matrix, default = False.
"""
file_bathy = paths[0]
ww3_local_path = paths[1]
path_longuet_higgins = paths[2]
# Constants
radius = 6.371*1e6 # radius of the earth in meters
lg10 = log(10) # log of 10
vs_crust = parameters[0]
rho_s = parameters[1]
f1 = parameters[2]
f2 = parameters[3]
## Initialize variables
if 'plot_type' in kwargs:
plot_type = kwargs['plot_type']
plot = True
if plot_type == 'hourly':
plot_hourly = True
SDF_hourly = np.zeros(dpt1.shape)
else:
plot_hourly = False
if plot_type == 'daily':
plot_daily = True
SDF_daily = np.zeros(dpt1.shape)
else:
plot_daily = False
if plot_type == 'monthly':
plot_monthly = True
SDF_monthly = np.zeros(dpt1.shape)
else:
plot_monthly = False
if plot_type == 'yearly':
plot_yearly = True
SDF_yearly = np.zeros(dpt1.shape)
else:
plot_yearly = False
else:
plot = True
if 'save' in kwargs:
save = kwargs['save']
else:
save = False
if 'vmin' in kwargs:
vmin = kwargs['vmin']
else:
vmin = 0
if 'vmax' in kwargs:
vmax = kwargs['vmax']
else:
vmax = 1e-16
## Adapt latitude and longitude to values in parameters file
lon_min, lon_max, lat_min, lat_max = extent[0], extent[1], extent[2], extent[3]
dpt1 = dpt1.sel(latitude = slice(lat_min, lat_max), longitude = slice(lon_min, lon_max))
zlat = zlat.sel(latitude = slice(lat_min, lat_max))
zlon = zlon.sel(longitude = slice(lon_min, lon_max))
## Loop over dates
YEAR = date_vec[0]
MONTH = date_vec[1]
DAY = date_vec[2]
HOUR = date_vec[3]
for iyear in np.array([YEAR]):
if isinstance(MONTH, int):
MONTH = np.array([MONTH])
elif not len(MONTH):
MONTH = np.arange(1, 13)
else:
MONTH = np.array(MONTH)
for imonth in MONTH:
TOTAL_month = np.zeros(dpt1.shape) # Initiate monthly source of Rayleigh wave matrix
daymax = monthrange(iyear,imonth)[1]
filename_p2l = '%s/%s_%d%02d_p2l.nc'%(ww3_local_path, prefix, iyear, imonth)
print("File WW3 ", filename_p2l)
try:
day = np.array(DAY)
if day[0] > day[-1]:
index = np.squeeze(np.argwhere(day==daymax))
if imonth == MONTH[0]:
day = day[:index+1]
elif imonth == MONTH[-1]:
index = np.squeeze(np.argwhere(day==monthrange(iyear, imonth-1)[1]))
day = day[index+1:]
else:
day = np.arange(1,daymax+1)
except:
try:
day = int(np.squeeze(day))
except:
day= np.arange(1,(monthrange(iyear,imonth)[1])+1)
for iday in day:
if isinstance(HOUR, int):
HOUR = np.array([HOUR])
elif not len(HOUR):
HOUR = np.arange(0,24,3)
else:
HOUR = np.array(HOUR)
for ih in HOUR:
## Open F_p3D
(lati, longi, freq_ocean, p2l, unit1) = read_p2l(filename_p2l, [iyear, imonth, iday, ih], [lon_min, lon_max], [lat_min, lat_max])
nf = len(freq_ocean) # number of frequencies
xfr = np.exp(np.log(freq_ocean[-1]/freq_ocean[0])/(nf-1)) # determines the xfr geometric progression factor
df = freq_ocean*0.5*(xfr-1/xfr) # frequency interval in wave model times 2
freq_seismic = 2*freq_ocean # ocean to seismic waves freq
## Check units of the model, depends on version
if unit1 == 'log10(Pa2 m2 s+1E-12':
p2l = np.exp(lg10*p2l) - (1e-12-1e-16)
elif unit1 == 'log10(m4s+0.01':
p2l = np.exp(lg10*p2l) - 0.009999
elif unit1 == 'log10(Pa2 m2 s+1E-12)':
p2l = np.exp(lg10*p2l) - (1e-12-1e-16)
## Integral over a frequency band
if f1 < f2:
index_freq = np.logical_and(f1 <= freq_seismic, freq_seismic <= f2)
df = df[index_freq]
freq_seismic = freq_seismic[index_freq]
n_freq = len(df)
Fp = p2l.sel(frequency = freq_ocean[index_freq], latitude = slice(lat_min, lat_max), longitude = slice(lon_min, lon_max))
C = site_effect(dpt1, freq_seismic, zlat, zlon,vs_crust, path_longuet_higgins) # computes Longuet-Higgins site effect given the bathymetryint(Fp.shape)
if C.shape == Fp.shape:
SDF_f = 2*np.pi/(rho_s**2*(vs_crust*1e3)**5)*C.data*Fp.data
else:
Fp = Fp.interp(latitude = zlat, longitude = zlon)
SDF_f = 2*np.pi/(rho_s**2*(vs_crust*1e3)**5)*C.data*Fp.data
if SDF_f.shape != C.shape:
print('SDF shape', SDF_f.shape)
return
## Loop over frequencies of interest
M = np.zeros((n_freq, len(dpt1), len(dpt1[0])))
for i, fq in enumerate(freq_seismic):
SDF_f[i, :, :] = fq.data*SDF_f[i, :, :]
M[i, :, :] = df.data[i]*SDF_f[i, :, :]
M = xr.DataArray(M, coords={'frequency': freq_seismic, 'latitude': zlat,'longitude': zlon}, dims=["frequency", "latitude", "longitude"])
SDF = M.sum(dim = 'frequency', skipna = True)
## Single frequency
elif f1 == f2:
index_freq = np.squeeze(np.argmin(abs(freq-f1)))
print('unique frequency ', f1)
Fp = p2l[:, :, index_freq]
C = site_effect(dpt1, f1, vs_crust, path_longuet_higgins)
SDF_f = 2*np.pi*f1/(rho_s**2*(vs_crust*1e3)**5)*Fp.data*C.data
SDF = SDF_f
## Exception in parametrization of frequencies
else:
print('two frequencies with f2 < f1 were given')
return
## Save SDF to file
if save == True:
## Save SDF to file
path_out = './SDF/'
if not os.path.exists(path_out):
print('make directory '+path_out)
os.makedirs(path_out)
# Create netCDF 3-hourly file
ncfile = Dataset(path_out+"rayleigh_SDF_%d%02d%02d%02d.nc"%(iyear, imonth, iday, ih), mode='w',format='NETCDF4_CLASSIC')
lat_dim = ncfile.createDimension('latitude', len(zlat)) # latitude axis
lon_dim = ncfile.createDimension('longitude', len(zlon)) # longitude axis
time_dim = ncfile.createDimension('time', daymax*8) # unlimited axis (can be appended to).
freq_dim = ncfile.createDimension('frequency', n_freq)
ncfile.title='Rayleigh waves power spectrum of vertical displacement on %d-%02d-%02d-%02d'%(iyear, imonth, iday, ih)
ncfile.subtitle='Equivalent Force maps every 3 hours for the secondary microseismic peak'
lat = ncfile.createVariable('latitude', np.float32, ('latitude',))
lat.units = 'degrees_north'
lat.long_name = 'latitude'
lon = ncfile.createVariable('longitude', np.float32, ('longitude',))
lon.units = 'degrees_east'
lon.long_name = 'longitude'
time = ncfile.createVariable('time', np.float32, ('time',))
time.units = 'hours since 1990-01-01'
time.long_name = 'time'
freq_nc = ncfile.createVariable('frequency', np.float32, ('frequency',))
freq_nc.units = 'Hz'
freq_nc.long_name = 'frequency'
sdf_f = ncfile.createVariable('sdf_f', np.float32, ('frequency','latitude', 'longitude'))
sdf_f.units = 'm.s'
sdf_f.long_name = 'Power spectrum of vertical displacement'
lat[:] = zlat
lon[:] = zlon
freq_nc[:] = freq_seismic
sdf_f[:] = SDF_f
time[:] = date2num(datetime(iyear, imonth, iday, ih), units='hours since 1990-01-01', calendar='standard')
ncfile.close()
## Plot SDF
if plot_hourly == True:
plt.close('all')
SDF_plot = xr.DataArray(SDF,
coords={'latitude': zlat,'longitude': zlon},
dims=["latitude", "longitude"],
name = 'Source of the power spectrum for the vertical displacement.\nRayleigh waves.\nFrequency %.3f-%.3f Hz.%d-%02d-%02dT%02d'%(f1, f2, iyear, imonth, iday, ih))
fig = plt.figure(figsize=(9,6))
fig.suptitle('Source of the power spectrum for the vertical displacement. Rayleigh waves.\nFrequency %.3f-%.3f Hz. %d-%02d-%02dT%02d'%(f1, f2, iyear, imonth, iday, ih))
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines()
gl = ax.gridlines()
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
ax.add_feature(cartopy.feature.LAND, zorder=100, edgecolor='k', facecolor='linen')
SDF_plot.plot(ax=ax, transform=ccrs.PlateCarree(), vmin=vmin, vmax=vmax, cbar_kwargs={'label':'SDF (m)', 'orientation': 'horizontal'})
plt.savefig('rayleigh_SDF_%d%02d%02dT%02d.png'%(iyear, imonth, iday, ih), dpi = 300, bbox_inches='tight')
## Sum SDF
if plot_daily == True:
SDF_daily += SDF
if plot_monthly == True:
SDF_monthly += SDF
if plot_yearly == True:
SDF_yearly += SDF
if plot_daily == True:
plt.close('all')
SDF_plot = xr.DataArray(SDF_daily,
coords={'latitude': zlat,'longitude': zlon},
dims=["latitude", "longitude"])
fig = plt.figure(figsize=(9,6))
fig.suptitle('Source of the power spectrum for the vertical displacement. Rayleigh waves.\nFrequency %.3f-%.3f Hz %d-%02d-%02d'%(f1, f2, iyear, imonth, iday))
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines()
gl = ax.gridlines()
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
ax.add_feature(cartopy.feature.LAND, zorder=100, edgecolor='k', facecolor='linen')
SDF_plot.plot(ax=ax, transform=ccrs.PlateCarree(), vmin = vmin, vmax = vmax, cbar_kwargs={'label':'SDF (m)', 'orientation': 'horizontal'})
plt.savefig('rayleigh_SDF_daily_%d%02d%02d.png'%(iyear, imonth, iday), dpi = 300, bbox_inches='tight')
plt.close('all')
SDF_daily = np.zeros((dpt1.shape))
if plot_monthly == True:
plt.close('all')
SDF_plot = xr.DataArray(SDF_monthly,
coords={'latitude': zlat,'longitude': zlon},
dims=["latitude", "longitude"])
fig = plt.figure(figsize=(9,6))
fig.suptitle('Source of the power spectrum for the vertical displacement. Rayleigh waves.\nFrequency %.3f-%.3f Hz %d-%02d'%(f1, f2, iyear, imonth))
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines()
gl = ax.gridlines()
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
ax.add_feature(cartopy.feature.LAND, zorder=100, edgecolor='k', facecolor='linen')
SDF_plot.plot(ax=ax, transform=ccrs.PlateCarree(), vmin = vmin, vmax = vmax, cbar_kwargs={'label':'SDF (m)','orientation': 'horizontal'})
plt.savefig('rayleigh_SDF_monthly_%d%02d.png'%(iyear, imonth), dpi = 300, bbox_inches='tight')
#plt.show()
plt.close('all')
SDF_monthly = np.zeros((dpt1.shape))
if plot_yearly == True:
plt.close('all')
SDF_plot = xr.DataArray(SDF_yearly,
coords={'latitude': zlat,'longitude': zlon},
dims=["latitude", "longitude"])
fig = plt.figure(figsize=(9,6))
ax = plt.axes(projection=ccrs.Robinson())
ax.coastlines()
gl = ax.gridlines()
gl.xformatter = LONGITUDE_FORMATTER
gl.yformatter = LATITUDE_FORMATTER
ax.add_feature(cartopy.feature.LAND, zorder=100, edgecolor='k', facecolor='linen')
fig.suptitle('Source of the power spectrum for the vertical displacement.Rayleigh waves.\nFrequency %.3f-%.3f Hz %d'%(f1, f2, iyear))
SDF_plot.plot(ax=ax, transform=ccrs.PlateCarree(), vmin = vmin, vmax = vmax, cbar_kwargs={'label':'SDF (m)','orientation': 'horizontal'})
plt.savefig('rayleigh_SDF_yearly_%d.png'%(iyear), dpi = 300, bbox_inches='tight')
plt.close('all')
SDF_yearly = np.zeros((dpt1.shape))
plt.close('all')
print('Rayleigh source maps done!')
|