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 | def loop_ww3_sources(paths, dpt1, zlon, zlat, wave_type='P', date_vec=[2020, [], [], []], extent=[-180, 180, -90, 90],parameters= [1/12, 1/2], c_file = "../../data/cP.nc", prefix = "WW3-GLOB-30M", **kwargs):
"""Compute the equivalent vertical force on the seafloor for a given wave type (P or S), given a path to the ww3 p2l file, the bathymetry, the wave type, the date vector and the spatial extent.
Saves in netcdf format the equivalent vertical force for each frequency if save argument True.
Plots in PNG source maps of P/S waves at given intervals depending on plot variables.
Args:
paths (list): [file_bathy, ww3_local_path]: paths of additional files bathymetry, ww3 p2l file
dpt1 (xarray.ndarray): bathymetry grid in m (depth) with dimensions lon x lat
zlon (xarray.ndarray): longitude of bathymetry file (°)
zlat (xarray.ndarray): latitude of bathymetry file (°)
wave_type (str, optional): P or S waves.
date_vec (list, optional): 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 minimum frequency, maximum frequency.
c_file (str, optional): path to amplification coefficient file.
prefix (str, optional) : prefix of ww3 p2l file.
plot (bool, optional): default: True
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]
# Constants
radius = 6.371*1e6 # radius of the earth in meters
lg10 = log(10) # log of 10
#
f1 = parameters[0]
f2 = parameters[1]
## Initialize variables
if 'plot_type' in kwargs:
plot_type = kwargs['plot_type']
plot = True
if plot_type == 'hourly':
plot_hourly = True
F_hourly = np.zeros(dpt1.shape)
else:
plot_hourly = False
if plot_type == 'daily':
plot_daily = True
F_daily = np.zeros(dpt1.shape)
else:
plot_daily = False
if plot_type == 'monthly':
plot_monthly = True
F_monthly = np.zeros(dpt1.shape)
else:
plot_monthly = False
if plot_type == 'yearly':
plot_yearly = True
F_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 = 1e10
## Adapt latitude and longitude to values in parameters file
lon_min = extent[0]
lon_max = extent[1]
lat_min = extent[2]
lat_max = 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))
## Open Amplification Coefficient
# check for refined bathymetry
res_bathy = abs(zlon[1] - zlon[0])
if res_bathy == 0.5:
ds_ampli = xr.open_dataset('../../data/c%s.nc'%(wave_type)).astype('float64')
amplification_coeff = ds_ampli['c%s'%wave_type]
refined = False
else:
print("Refined bathymetry grid \n PLEASE RUN amplification_coefficients.ipynb before running this script")
ds_ampli = xr.open_dataset(c_file).astype('float64')
amplification_coeff = ds_ampli['c%s'%wave_type]
refined = True
## Surface Element
msin = np.array([np.sin(np.pi/2 - np.radians(zlat))]).T
ones = np.ones((1, len(zlon)))
res_mod = radians(abs(zlat[1] - zlat[0]))
dA = radius**2*res_mod**2*np.dot(msin,ones)
## 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))
Fp = Fp.where(np.isfinite(Fp))
Fp = Fp.drop('frequency')
Fp.coords['frequency'] = freq_seismic
res_p2l = abs(Fp.longitude[1]-Fp.longitude[0])
if res_bathy != res_p2l:
# interpolate Fp
Fp = Fp.interp(longitude=zlon, latitude=zlat, method='linear')
amplification_coeff = amplification_coeff.sel(frequency = freq_seismic, method='nearest', tolerance=0.01)
amplification_coeff = amplification_coeff.sel(latitude = slice(lat_min, lat_max), longitude = slice(lon_min, lon_max))
amplification_coeff = amplification_coeff.reindex_like(Fp, method='nearest', tolerance=0.01)
F_f = Fp*amplification_coeff**2
F = F_f.copy()
for ifq, fq in enumerate(freq_seismic):
F_f[ifq, :, :] *= dA
F[ifq, :, :] = F_f[ifq, :, :]*df[ifq]
F = 2*np.pi*np.sqrt(F.sum(dim = 'frequency'))
## Single frequency
elif f1 == f2:
index_freq = np.squeeze(np.argmin(abs(freq-f1)))
print('unique frequency ', f1)
return
## Exception in parametrization of frequencies
else:
print('two frequencies with f2 < f1 were given')
return
## Save F to file
if save == True:
path_out = './F/'
if not os.path.exists(path_out):
print("make directory %s"%path_out)
os.makedirs(path_out)
# Create netCDF 3-hourly file
ncfile = Dataset(path_out+"F_%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='Equivalent Vertical Force on %d-%02d-%02d-%02d'%(iyear, imonth, iday, ih)
ncfile.subtitle='Equivalent Force every 3 hours for the secondary microseismic peak'
lat = ncfile.createVariable('latitude', np.float64, ('latitude',))
lat.units = 'degrees_north'
lat.long_name = 'latitude'
lon = ncfile.createVariable('longitude', np.float64, ('longitude',))
lon.units = 'degrees_east'
lon.long_name = 'longitude'
time = ncfile.createVariable('time', np.float64, ('time',))
time.units = 'hours since 1990-01-01'
time.long_name = 'time'
freq_nc = ncfile.createVariable('frequency', np.float64, ('frequency',))
freq_nc.units = 'Hz'
freq_nc.long_name = 'frequency'
F_freq = ncfile.createVariable('F_f', np.float64, ('frequency','latitude', 'longitude'))
F_freq.units = 'N.s^{1/2}'
F_freq.long_name = 'Equivalent Vertical Force spectrum'
lat[:] = zlat
lon[:] = zlon
freq_nc[:] = freq_seismic
F_freq[:] = F_f
time[:] = date2num(datetime(iyear, imonth, iday, ih), units='hours since 1990-01-01', calendar='standard')
ncfile.close()
## Plot F
if plot_hourly == True:
plt.close('all')
F_plot = xr.DataArray(F,
coords={'latitude': zlat,'longitude': zlon},
dims=["latitude", "longitude"],
name = 'Frequency %.3f-%.3f Hz.%d-%02d-%02dT%02d\n %s waves.\n'%(f1, f2, iyear, imonth, iday, ih, wave_type))
fig = plt.figure(figsize=(9,6))
fig.suptitle('Frequency %.3f-%.3f Hz.%d-%02d-%02dT%02d\n %s waves.\n'%(f1, f2, iyear, imonth, iday, ih, wave_type))
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')
if wave_type == 'P':
F_plot.plot(ax=ax, transform=ccrs.PlateCarree(), cbar_kwargs={'label':'F (N)', 'orientation': 'horizontal'}, vmin=vmin, vmax=vmax)
else:
F_plot.plot(ax=ax, transform=ccrs.PlateCarree(), cbar_kwargs={'label':'F (N)', 'orientation': 'horizontal'}, vmin=vmin, vmax=vmax)
plt.savefig('F_%s_%d%02d%02dT%02d.png'%(wave_type, iyear, imonth, iday, ih), dpi = 300, bbox_inches='tight')
## Sum F
if plot_daily == True:
F_daily += F
if plot_monthly == True:
F_monthly += F
if plot_yearly == True:
F_yearly += F
if plot_daily == True:
plt.close('all')
F_plot = xr.DataArray(F_daily,
coords={'latitude': zlat,'longitude': zlon},
dims=["latitude", "longitude"],
name = 'Frequency %.3f-%.3f Hz.%d-%02d-%02d\n %s waves.\n'%(f1, f2, iyear, imonth, iday, wave_type))
fig = plt.figure(figsize=(9,6))
fig.suptitle('Frequency %.3f-%.3f Hz.%d-%02d-%02d.\n %s waves.\n'%(f1, f2, iyear, imonth, iday, wave_type))
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')
if wave_type == 'P':
F_plot.plot(ax=ax, transform=ccrs.PlateCarree(), cbar_kwargs={'label':'F (N)', 'orientation': 'horizontal'}, vmin=vmin, vmax=vmax),
else:
F_plot.plot(ax=ax, transform=ccrs.PlateCarree(), cbar_kwargs={'label':'F (N)', 'orientation': 'horizontal'}, vmin=vmin, vmax=vmax)
plt.savefig('F_%s_%d%02d%02d.png'%(wave_type, iyear, imonth, iday), dpi = 300, bbox_inches='tight')
F_daily = np.zeros((dpt1.shape))
if plot_monthly == True:
plt.close('all')
F_plot = xr.DataArray(F_monthly,
coords={'latitude': zlat,'longitude': zlon},
dims=["latitude", "longitude"],
name = 'Frequency %.3f-%.3f Hz.%d-%02d\n %s waves.\n'%(f1, f2, iyear, imonth, wave_type))
fig = plt.figure(figsize=(9,6))
fig.suptitle('Frequency %.3f-%.3f Hz.%d-%02d\n %s waves.\n'%(f1, f2, iyear, imonth, wave_type))
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')
if wave_type == 'P':
F_plot.plot(ax=ax, transform=ccrs.PlateCarree(), cbar_kwargs={'label':'F (N)', 'orientation': 'horizontal'}, vmin=vmin, vmax=vmax)
else:
F_plot.plot(ax=ax, transform=ccrs.PlateCarree(), cbar_kwargs={'label':'F (N)', 'orientation': 'horizontal'}, vmin=vmin, vmax=vmax)
plt.savefig('F_%s_%d%02d.png'%(wave_type, iyear, imonth), dpi = 300, bbox_inches='tight')
F_monthly = np.zeros((dpt1.shape))
if plot_yearly == True:
plt.close('all')
F_plot = xr.DataArray(F_yearly,
coords={'latitude': zlat,'longitude': zlon},
dims=["latitude", "longitude"],
name = 'Frequency %.3f-%.3f Hz.%d\n %s waves.\n'%(f1, f2, iyear, wave_type))
fig = plt.figure(figsize=(9,6))
fig.suptitle('Frequency %.3f-%.3f Hz.%d\n %s waves.\n'%(f1, f2, iyear, wave_type))
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')
if wave_type == 'P':
F_plot.plot(ax=ax, transform=ccrs.PlateCarree(), cbar_kwargs={'label':'F (N)', 'orientation': 'horizontal'}, vmin=vmin, vmax=vmax)
else:
F_plot.plot(ax=ax, transform=ccrs.PlateCarree(), cbar_kwargs={'label':'F (N)', 'orientation': 'horizontal'}, vmin=vmin, vmax=vmax)
plt.savefig('F_%s_%d.png'%(wave_type, iyear), dpi = 300, bbox_inches='tight')
F_daily = np.zeros((dpt1.shape))
F_yearly = np.zeros((dpt1.shape))
plt.close('all')
print('%s source maps done!'%wave_type)
|