Skip to content

Commit fa761b5

Browse files
committed
cleaned up tilt figure; saving tilt to file
1 parent 83a54dc commit fa761b5

File tree

3 files changed

+106
-28
lines changed

3 files changed

+106
-28
lines changed

obstools/atacr/plotting.py

Lines changed: 33 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727

2828
import numpy as np
2929
from matplotlib import pyplot as plt
30+
from matplotlib.gridspec import GridSpec
3031
from obstools.atacr import utils
3132
from obspy import Trace
3233

@@ -237,7 +238,7 @@ def fig_av_cross(f, field, gooddays, ftype, ncomp, key='',
237238
return plt
238239

239240

240-
def fig_coh_ph(coh, ph, direc):
241+
def fig_coh_ph(coh, ph, direc, tilt, date):
241242
"""
242243
Function to plot the coherence and phase between the rotated H and Z
243244
components, used to characterize the tilt direction.
@@ -250,21 +251,46 @@ def fig_coh_ph(coh, ph, direc):
250251
Phase between rotated H and Z components
251252
direc : :mod:`~numpy.ndarray`
252253
Directions considered in maximizing coherence between H and Z
254+
date : list
255+
List of datetime dates for plotting as function of time
256+
tilt : list
257+
List of tilt azimuths determined for each date
253258
254259
"""
255260

256261
colors = plt.cm.cividis(np.linspace(0, 1, coh.shape[0]))
257262

258263
if coh.ndim > 1:
259-
f, (ax1, ax2) = plt.subplots(1, 2)
260-
for i, (co, p) in enumerate(zip(coh, ph)):
264+
265+
meantilt = np.mean(tilt)
266+
stdetilt = np.std(tilt, ddof=1)/np.sqrt(coh.shape[0])
267+
mediantilt = np.median(tilt)
268+
269+
plt.rcParams['date.converter'] = 'concise'
270+
f = plt.figure()
271+
gs = GridSpec(3, 2, figure=f)
272+
ax1 = f.add_subplot(gs[0:-1, 0])
273+
ax2 = f.add_subplot(gs[0:-1, 1])
274+
ax3 = f.add_subplot(gs[2, :])
275+
ax3.axhline(
276+
np.mean(tilt),
277+
ls='--',
278+
label='Mean: {0:.0f} $\pm$ {1:.1f}'.format(meantilt, stdetilt))
279+
ax3.axhline(
280+
np.median(tilt),
281+
ls=':',
282+
label='Median: {0:.0f}'.format(np.median(tilt)))
283+
for i, (co, p, d, t) in enumerate(zip(coh, ph, date, tilt)):
261284
ax1.plot(direc, co, c=colors[i])
262285
ax2.plot(direc, p*180./np.pi, c=colors[i])
263-
ax1.set_ylabel('Coherence')
286+
ax3.plot(d, t, 'o', c=colors[i])
287+
ax3.legend(loc='best', fontsize=8)
288+
ax1.set_ylabel('Coherence Z-H1')
264289
ax1.set_ylim((0, 1.))
265-
ax2.set_ylabel('Phase')
266-
ax1.set_xlabel('Angle from H1')
267-
ax2.set_xlabel('Angle from H1')
290+
ax2.set_ylabel('Phase Z-H1')
291+
ax3.set_ylabel('Tilt direction (deg)')
292+
ax1.set_xlabel('Angle clockwise from H1 (deg)')
293+
ax2.set_xlabel('Angle clockwise from H1 (deg)')
268294
plt.tight_layout()
269295

270296
else:

obstools/atacr/utils.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -408,9 +408,8 @@ def calculate_tilt(ft1, ft2, ftZ, ftP, f, goodwins, tiltfreqs):
408408
phi = np.arange(0., 360., 10.)
409409
coh = np.zeros(len(phi))
410410
ph = np.zeros(len(phi))
411-
cZZ = np.abs(
412-
np.mean(ftZ[goodwins, :] * \
413-
np.conj(ftZ[goodwins, :]), axis=0))[0:len(f)]
411+
cZZ = np.abs(np.mean(ftZ[goodwins, :] *
412+
np.conj(ftZ[goodwins, :]), axis=0))[0:len(f)]
414413

415414
for i, d in enumerate(phi):
416415

@@ -486,6 +485,10 @@ def calculate_tilt(ft1, ft2, ftZ, ftP, f, goodwins, tiltfreqs):
486485
phase_value = rph[ind[0]][0]
487486
coh_value = rcoh[ind[0]][0]
488487
tilt = rphi[ind[0]][0]
488+
if tilt > 360.:
489+
tilt -= 360.
490+
elif tilt < 0:
491+
tilt += 360.
489492

490493
# Now calculate spectra at tilt direction
491494
ftH = rotate_dir(ft1, ft2, tilt)

obstools/scripts/atacr_clean_spectra.py

Lines changed: 67 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -162,11 +162,11 @@ def get_cleanspec_arguments(argv=None):
162162
help="Plot daily average figure. " +
163163
"[Default does not plot figure]")
164164
FigureGroup.add_argument(
165-
"--figCoh",
165+
"--figTilt",
166166
action="store_true",
167-
dest="fig_coh_ph",
167+
dest="fig_tilt",
168168
default=False,
169-
help="Plot Coherence and Phase figure. " +
169+
help="Plot Coherence, phase and tilt direction figure. " +
170170
"[Default does not plot figure]")
171171
FigureGroup.add_argument(
172172
"--figCross",
@@ -349,6 +349,7 @@ def main(args=None):
349349
dstart = str(tstart.year).zfill(4)+'.'+str(tstart.julday).zfill(3)+'-'
350350
dend = str(tend.year).zfill(4)+'.'+str(tend.julday).zfill(3)+'.'
351351
fileavst = avstpath / (dstart+dend+'avg_sta.pkl')
352+
filetilt = avstpath / (dstart+dend+'tilt.txt')
352353

353354
if fileavst.exists():
354355
if not args.ovr:
@@ -383,14 +384,18 @@ def main(args=None):
383384
# Initialize StaNoise object
384385
stanoise = StaNoise()
385386

387+
# Date + tilt list
388+
date_list = []
389+
tilt_list = []
390+
386391
# Loop through each day withing time range
387392
while t1 < tend:
388393

389394
year = str(t1.year).zfill(4)
390395
jday = str(t1.julday).zfill(3)
391396

392-
tstamp = year+'.'+jday+'.'
393-
filespec = specpath / (tstamp + 'spectra.pkl')
397+
tstamp = year+'.'+jday
398+
filespec = specpath / (tstamp + '.spectra.pkl')
394399

395400
# Load file if it exists
396401
if filespec.exists():
@@ -401,6 +406,8 @@ def main(args=None):
401406
file = open(filespec, 'rb')
402407
daynoise = pickle.load(file)
403408
file.close()
409+
tilt_list.append(daynoise.rotation.tilt)
410+
date_list.append(t1.date)
404411
stanoise += daynoise
405412
else:
406413
t1 += 3600.*24.
@@ -526,21 +533,31 @@ def main(args=None):
526533
ad_2Z_all, ad_2P_all, ad_ZP_all)
527534

528535
# Quality control to identify outliers
529-
stanoise.QC_sta_spectra(pd=args.pd, tol=args.tol, alpha=args.alpha,
530-
fig_QC=args.fig_QC, debug=args.debug,
531-
save=plotpath, form=args.form)
536+
stanoise.QC_sta_spectra(
537+
pd=args.pd,
538+
tol=args.tol,
539+
alpha=args.alpha,
540+
fig_QC=args.fig_QC,
541+
debug=args.debug,
542+
save=plotpath,
543+
form=args.form)
532544

533545
# Average spectra for good days
534546
stanoise.average_sta_spectra(
535547
fig_average=args.fig_average,
536-
save=plotpath, form=args.form)
548+
save=plotpath,
549+
form=args.form)
537550

538551
if args.fig_av_cross:
539552
fname = stkey + '.' + 'av_coherence'
540553
plot = plotting.fig_av_cross(
541-
stanoise.f, coh, stanoise.gooddays,
542-
'Coherence', stanoise.ncomp, key=stkey, lw=0.5)
543-
# if plotpath.is_dir():
554+
stanoise.f,
555+
coh, stanoise.gooddays,
556+
'Coherence',
557+
stanoise.ncomp,
558+
key=stkey,
559+
lw=0.5)
560+
544561
if plotpath:
545562
plot.savefig(
546563
str(plotpath / (fname + '.' + args.form)),
@@ -550,8 +567,13 @@ def main(args=None):
550567

551568
fname = stkey + '.' + 'av_admittance'
552569
plot = plotting.fig_av_cross(
553-
stanoise.f, ad, stanoise.gooddays,
554-
'Admittance', stanoise.ncomp, key=stkey, lw=0.5)
570+
stanoise.f,
571+
ad,
572+
stanoise.gooddays,
573+
'Admittance',
574+
stanoise.ncomp,
575+
key=stkey,
576+
lw=0.5)
555577

556578
if plotpath:
557579
plot.savefig(
@@ -562,8 +584,14 @@ def main(args=None):
562584

563585
fname = stkey + '.' + 'av_phase'
564586
plot = plotting.fig_av_cross(
565-
stanoise.f, ph, stanoise.gooddays,
566-
'Phase', stanoise.ncomp, key=stkey, marker=',', lw=0)
587+
stanoise.f,
588+
ph,
589+
stanoise.gooddays,
590+
'Phase',
591+
stanoise.ncomp,
592+
key=stkey,
593+
marker=',',
594+
lw=0)
567595

568596
if plotpath:
569597
plot.savefig(
@@ -572,9 +600,15 @@ def main(args=None):
572600
else:
573601
plot.show()
574602

575-
if args.fig_coh_ph and stanoise.phi is not None:
603+
if args.fig_tilt and stanoise.phi is not None:
576604
fname = stkey + '.' + 'coh_ph'
577-
plot = plotting.fig_coh_ph(coh_all, ph_all, stanoise.phi)
605+
plot = plotting.fig_coh_ph(
606+
coh_all,
607+
ph_all,
608+
stanoise.phi,
609+
tilt_list,
610+
date_list)
611+
578612
if plotpath:
579613
plot.savefig(
580614
str(plotpath / (fname + '.' + args.form)),
@@ -583,8 +617,23 @@ def main(args=None):
583617
plot.show()
584618

585619
# Save to file
620+
print()
621+
print("* Clean station spectra saved to: ")
622+
print("* "+str(fileavst))
586623
stanoise.save(fileavst)
587624

625+
# Write out events
626+
print()
627+
print("* Tilt direction as function of time saved to: ")
628+
print("* "+str(filetilt))
629+
print()
630+
fid = open(filetilt, 'w')
631+
fid.writelines("Date, Tilt azimuth (deg from H1)\n")
632+
for i in range(len(tilt_list)):
633+
line1 = "{0},{1:.0f}\n".format(date_list[i], tilt_list[i])
634+
fid.writelines(line1.replace(" ", ""))
635+
fid.close()
636+
588637

589638
if __name__ == "__main__":
590639

0 commit comments

Comments
 (0)