-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParkSeisIO.py
1843 lines (1394 loc) · 57.2 KB
/
ParkSeisIO.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
####################################
###CODE FOR ParkSEIS I/O
####################################
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
from matplotlib.ticker import (MultipleLocator, FormatStrFormatter, AutoMinorLocator)
from scipy.interpolate import griddata
import seaborn as sns
import os
from pathlib import Path
import sys
import obspy as op
from obspy import read
import warnings
warnings.filterwarnings('ignore')
def loadModelDAT(file):
'''
Takes a ParkSeis '.dat' file generated during modeling and returns an Obspy stream object and raw traces
'''
#load in raw .dat file
strm = read(file)
#generator function here to save memory for big files; basically list comprehension
trcs = np.stack(t.data for t in strm.traces)
return trcs, strm
def loadParkSeisDataTEXT(file):
'''
Takes in a seismic data file exported from ParkSEIS as a .TXT file and returns
model parameters and traces loaded into a numpy array of shape (trNum, sampNum)
'''
#load in the text file using np.genfromtext
tr, t, amp = np.genfromtxt(file, unpack=True)
#get model parameters and load into dict
nTrace = int(np.unique(tr)[-1])
npts = int(tr.size/nTrace)
dt = t[5]-t[4]
modParamsTXT = {
'numTrc' : nTrace,
'numSamps' : npts,
'dt' : dt
}
#load amplitudes into array to return as 'traces'
txtTraces = np.full((nTrace, npts), np.nan) #create empty array of proper shape and fill with np.nan values
for trace in np.unique(tr): #load into created empty array
trIdx = int(trace)-1
txtTraces[trIdx] = amp[tr==trace]
return modParamsTXT, txtTraces
def getModelParams(stream):
'''
Takes in a Obspy stream object for a ParkSeis model and returns a dictionary of useful parameters
'''
numTrc = len(stream)
numSamps = stream[0].stats.npts
dt = float(stream[0].stats.delta)
return dict(numTrc=numTrc, numSamps=numSamps, dt=dt)
def plotModelData(data, startTime, endTime, X1, dx, percentile=99.99, gain=1, traceNorm=None, title='Shot Record', ax=None):
'''
Takes either a model file or Obspy stream and plots the data
INPUT:
X1 --> Offset from source to first receiver
dx --> receiver spacing
'''
if data.endswith('.TXT'):
#case if model file is exported as TXT file
modParams, traces = loadParkSeisDataTEXT(data)
elif isinstance(data, str):
#case if data is a file path; loads stream and parameters then stacks traces into array
traces, stream = loadModelDAT(data)
modParams = getModelParams(stream)
else:
#case if data is a Obspy stream object
traces = np.stack(t.data for t in data.traces)
modParams = getModelParams(data)
#params for plotting
perc = np.percentile(traces, percentile)
gain = gain
nTrace = modParams['numTrc']
npts = modParams['numSamps']
dt = modParams['dt']
dx = dx
srcOffset = X1
start = int(startTime/dt)
end = int(endTime/dt)
xOffset = np.arange(0, (nTrace)*dx, dx)
t = np.arange(0, npts*dt, dt)
#plot
if ax != None:
ax = ax
msg = 'Master Plot'
else:
fig, ax = plt.subplots(1,1, figsize=(15,15))
msg = 'No Master Plot'
trNum = 1
for xpos, tr in zip(xOffset, traces):
#optional normalization
if traceNorm == 'Per Trace': amp = gain * tr / np.nanmax(tr) + (xpos+srcOffset)
else: amp = gain * tr / perc + (xpos+srcOffset)
ax.plot(amp[start:end], t[start:end], c='k', lw=0.5)
ax.fill_betweenx(t[start:end], amp[start:end],
(xpos+srcOffset), amp[start:end] > (xpos+srcOffset), color='r', lw=0, alpha=0.7)
ax.fill_betweenx(t[start:end], amp[start:end],
(xpos+srcOffset), amp[start:end] < (xpos+srcOffset), color='blue', lw=0, alpha=0.7)
ax.text(xpos+srcOffset, 0, str(trNum), horizontalalignment='center', fontsize=9)
trNum += 1
ax.set_ylabel('Time [s]')
ax.set_xlabel('Offset from Source [m]')
ax.set_title(title)
ax.invert_yaxis()
if msg == 'No Master Plot':
plt.show()
return
def dcModelPhaseShift(data, minVel, maxVel, minFreq, maxFreq, X1, dx, dv=0.1, padLen=None, title='Dispersion Image', overLayDC=None,
velSum=False, ax=None):
'''Takes either a gather file or an Obspy stream along with min/max velocity values to check
and min/max frequency values to check between; output is a dispersion curve.
After Park et al. 1998'''
################
#Calculate Image
################
if isinstance(data, str):
#load in file to get raw data matrix and stream then extract parameters
gather, gatherStream = loadModelDAT(data)
params = getModelParams(gatherStream)
else:
#extract traces from stream and get acquisition parameters
gather = np.stack(t.data for t in data.traces)
params = getModelParams(data)
#pad time axis if specified
if padLen != None:
gather = np.pad(gather, ((0,0),(padLen,padLen)), 'constant', constant_values=(0,0))
#calculate offset vector
xx = np.arange(X1, X1 + params['numTrc']*dx, dx)
#compute fft and associated freqs
G = np.fft.fft(gather)
freqs = np.fft.fftfreq(gather[0].size, params['dt'])
#select only positive frequencies from fft ouput; i.e. first half
Gp = G[:,:freqs.size//2]
freqsp = freqs[:freqs.size//2]
#select frequencies
df = freqs[10]-freqs[9]
fMax = int(maxFreq/df)
fMin = int(minFreq/df)
#set up velocities to test
#dv = 0.1 #velocity step to test
testVels = np.arange(minVel, maxVel, dv)
#create empty array to hold transformed data and mode picks
V = np.zeros((len(freqsp[fMin:fMax]), len(testVels)))
numF = V.shape[0]
M0 = np.zeros((len(freqsp[fMin:fMax])))
######TRANSFORM
#run through freqs first
for f in range(len(freqsp[fMin:fMax])):
#then run through each test velocity
#print(freqsp[f+fMin])
for v in range(len(testVels)):
V[f,v] = np.abs( np.sum( Gp[:,f+fMin]/np.abs(Gp[:,f+fMin]) * np.exp(1j*2*np.pi*freqsp[f+fMin]*xx /testVels[v]) ) )
#normalize by the numbre of traces in the gathre (as suggested by Olafsdottir 2018)
Vnorm = V/params['numTrc']
#calculate summation for all frequencies along single velocity value
vSum = Vnorm.sum(axis=0) / numF #normalize by number of frequency values
vSum_array = np.asarray([testVels, vSum])
###########
#PLOT
###########
if ax != None:
ax = ax
msg = 'Master Plot'
else:
fig, ax = plt.subplots(1,1, figsize=(15,8))
msg = 'No Master Plot'
majorXLocator = MultipleLocator(10) #sets the major tick interval to 10
majorXFormatter = FormatStrFormatter('%d')
minorXLocator = MultipleLocator(5) #sets the minor tick interval to every 5
majorYLocator = MultipleLocator(50) #sets the major tick interval to every 50
majorYFormatter = FormatStrFormatter('%d')
minorYLocator = MultipleLocator(25) #sets the minor tick interval to every 25
#plot theoretical dispersion curve if specified; must be first to not overide extents
if overLayDC != None:
#loop through dictionary of theor DC curves and plot
for dc in overLayDC:
if overLayDC[dc][0].size > 1: #ensures mode curve exists in file
dcF, dcC = overLayDC[dc][0,:], overLayDC[dc][1,:] #get mode frequency and phase vels
if dc == 'Experimental DC':
ax.plot(dcF, dcC, lw=3, c='m', label=dc)
elif dc == 'Inverted Model DC':
ax.plot(dcF, dcC, lw=3, label=dc, ls=':', c='k')
else:
ax.plot(dcF, dcC, lw=3, alpha=1, label=dc)
#ax.plot(dcF, dcC, lw=1, c='white', alpha=0.8)
#ax.scatter(dcF, dcC, marker='o', s=25, lw=1.5, alpha=0.5, label=dc)
#plot calculated dispersion image
dispC = ax.imshow(Vnorm.T, aspect='auto', interpolation='none', extent=[fMin*df,fMax*df,maxVel,minVel])
ax.invert_yaxis()
ax.set_xlabel('Frequency [Hz]')
ax.set_ylabel('Phase Velocity [m/s]')
ax.xaxis.set_major_locator(majorXLocator)
ax.xaxis.set_major_formatter(majorXFormatter)
ax.xaxis.set_minor_locator(minorXLocator)
ax.yaxis.set_major_locator(majorYLocator)
ax.yaxis.set_major_formatter(majorYFormatter)
ax.yaxis.set_minor_locator(minorYLocator)
ax.set_title(title)
ax.legend()
ax.grid(which='both', linestyle='--', alpha=0.75)
if msg == 'No Master Plot':
fig.colorbar(dispC, ax = ax, shrink = 0.7)
plt.show()
if velSum: return vSum_array
else: return
#######################
##THEOR. DISPERSION CURVE CODE
#######################
def getTheorDCParams(fname):
'''
Takes in a file path to a ParkSeis generate theoretical dispersion curve and extracts the number of points and mode number
'''
with open(fname, 'r') as dispFile:
lines = dispFile.readlines()
#get number of points on DC
numPts = int(lines[0][7:]) #number of points begins after the 7th character
#get the mode number
if fname.endswith('(Model).DC'):
modeNum = 0
else:
modeNum = int(fname[-5:-4]) #get mode number from provided file name
return numPts, modeNum
def loadTheorDC(fname, asDict=False, dictKey=''):
'''
Take in a file path to a ParkSeis generate theoretical dispersion curve and extracts the curve data into an array
'''
numPts, modeNum = getTheorDCParams(fname) #read file and get info
M = np.genfromtxt(fname, skip_header=1, usecols=(1,2), max_rows=numPts)
if asDict == True: #for loading singular experimental curves from inversions
mDict = {}
mDict[dictKey] = M.T
return mDict
else:
return M.T
def loadTheorDC_PATH(path):
'''
Takes a path to a folder containing all theoretical dispersion curves generated for a given model in ParkSeis and returns
a dictionary
NOTE: as of now it will not properly read in more than 10 curves - that is, M9 is the last one
'''
dcCurves = {}
for root, dirs, files in os.walk(path):
fNum = 0
for f in files:
#this method allows for more than 9 modes and also loading in AM0 curves
if f.endswith('.DC'):
key = f.split('(')[-1].split(')')[0] #this is to get the mode number label from the bracket value in file name
dcCurves[key] = loadTheorDC(os.path.join(path, f))
return dcCurves
def getModelFolderPaths(path):
'''
Loop through a specified path and return modeled DC folder paths, paths to modeled seismic files, and paths to modle .LYR files
NOTE: 'path' specified must contain a folder called 'DC' holding dispersion curves and a LYR file, as well as a 'seis' folder
containing all modeled seismic files
'''
dcModelFolders = []
seisModelFolders = []
seisFiles = []
lyrFiles = []
#get folder paths fopr DC curves and seismic files
for root, dirs, files in os.walk(path):
if root.endswith('DC'):
#print('Dispersion curves found in folder: ', root)
dcModelFolders.append(root)
if root.endswith('seis'):
#print('Seismic folder found in folder: ', root)
seisModelFolders.append(root)
#get seismic file paths
for p in seisModelFolders:
for entry in os.listdir(p):
if entry.endswith('v.dat'): #SELECT ONLY VERTICAL COMP OUTPUT
seisFiles.append(os.path.join(p,entry))
#get layer file paths
for p in dcModelFolders:
for entry in os.listdir(p):
if entry.endswith('.LYR'):
lyrFiles.append(os.path.join(p,entry))
#for debugging
# for f in dcModelFolders:
# print(f.split('\\')[-1])
# for f in seisFiles:
# print(f.split('\\')[-1])
if len(dcModelFolders) != len(seisFiles):
raise Exception('Caution! The number of model dispersion curve folders is not the same as the number of model seismic files!')
if len(dcModelFolders) != len(lyrFiles):
raise Exception('Caution! The number of model dispersion curve folders is not the same as the number of model .LYR files!')
return dcModelFolders, seisFiles, lyrFiles
#######################
##F-K PLOT CODE
#######################
def fkModelPlot(data, fMin, fMax, X1, dx, padLen=None, interp='hanning', title='f-k Domain', ax=None):
'''
Take either a gather file or Obspy stream and outputs its f-k spectrum
'''
if isinstance(data, str):
#load in file to get raw data matrix and stream then extract parameters
gather, gatherStream = loadModelDAT(data)
params = getModelParams(gatherStream)
else:
#extract traces from stream and get acquisition parameters
gather = np.stack(t.data for t in data.traces)
params = getModelParams(data)
#calculate 2D FFT and select only positive frequencies and associated unwrapped wavenumbers
if padLen != None:
gather = np.pad(gather, ((padLen,padLen),(padLen,padLen)), 'constant', constant_values=(0,0))
FK = np.fft.fft2(gather).T / gather.size #need to transpose due to shape of returned array
numPosF = FK[:,1].size//2 #number of positive frequencies; along 2nd col
fkUnwrap = FK[numPosF:,:] #select only positive frequencies;
fkUnwrap = np.flipud(fkUnwrap) #flips array to make indexing more intuitive
#calculate frequency and wavenumber axis
f_np = np.fft.fftfreq(FK[:,0].size, d=params['dt'])
k_np = np.fft.fftfreq(FK[0,:].size, d=dx)
df = f_np[1] - f_np[0] #frequency step
dk = k_np[1] - k_np[0] #wavenumber step
#Plotting extent calculations
minK, maxK = 0, 2*(1/(2*dx)) #NOTE: maxK is two times the Nyquist k
fmin, fmax = int(np.rint(fMin/df)), int(np.rint(fMax/df)) #index of desired min and max f
kmin, kmax = 0, k_np.size-1 #default to select all wavenumber values possible
#kmin, kmax = int(np.rint(minK/dk)), k_np.size-1
###PLOT####
if ax != None:
ax = ax
msg = 'Master Plot'
else:
fig, ax = plt.subplots(1,1, figsize=(12,10))
msg = 'No Master Plot'
fkPlot = ax.imshow(abs(fkUnwrap[fmin:fmax, kmin:kmax]), interpolation=interp, aspect='auto', origin='lower',
extent=[minK, maxK, fMin, fMax])
ax.set_title(title)
ax.set_ylabel('Frequency [Hz]')
ax.set_xlabel('Wavenumber [cycles/m]')
ax.grid(which='both', alpha=0.25)
ax.set_axisbelow(True)
if msg == 'No Master Plot':
fig.colorbar(fkPlot, ax = ax, shrink = 0.7)
plt.show()
return
######
#READ AND PLOT LYR MODEL FILE
######
def readLYRFile(fname):
''''
Takes a layer file and returns all parameter values for all layers
'''
#get number of layers in model; note returned value is number of distinct layers PLUS one (i.e. includes half-space)
with open(fname, 'r') as lyrFile:
lines = lyrFile.readlines()
numLayers = int(lines[2][14:]) #number of layers is on 3rd line starting after the 14 col
paramLines = lines[3:(3+numLayers)] #gets all lines containing model parameters
#load in the model parameters
z, h, vs, vp, pr, rho, qs, qp, vsU, vsL = np.genfromtxt(fname, skip_header=4, usecols=(1,2,3,4,5,6,7,8,9,10),
max_rows=numLayers, unpack=True)
#calculate parameters needed
hsADD = 1.5 #depth value to add to half-space for plotting
hsDepth = z[numLayers-2] #get depth to half-space
z[-1] = hsDepth + hsADD #sets depth of half-space base
h[-1] = z[-1] - z[-2] #sets thickness of half-space
dz = 0.0001
zProf = np.arange(0, hsDepth+hsADD, dz) #calculate depth vector
vsProf = np.full_like(zProf, np.nan)
vpProf = np.full_like(zProf, np.nan)
prProf = np.full_like(zProf, np.nan)
rhoProf = np.full_like(zProf, np.nan)
qsProf = np.full_like(zProf, np.nan)
qpProf = np.full_like(zProf, np.nan)
vsUProf = np.full_like(zProf, np.nan)
vsLProf = np.full_like(zProf, np.nan)
for layer in range(numLayers):
upper = z[layer] - h[layer]
lower = z[layer]
vsProf[(zProf >= upper) & (zProf <= lower)] = vs[layer]
vpProf[(zProf >= upper) & (zProf <= lower)] = vp[layer]
prProf[(zProf >= upper) & (zProf <= lower)] = pr[layer]
rhoProf[(zProf >= upper) & (zProf <= lower)] = rho[layer]
qsProf[(zProf >= upper) & (zProf <= lower)] = qs[layer]
qpProf[(zProf >= upper) & (zProf <= lower)] = qp[layer]
vsUProf[(zProf >= upper) & (zProf <= lower)] = vsU[layer]
vsLProf[(zProf >= upper) & (zProf <= lower)] = vsL[layer]
layerFileValues = {
'Depth':zProf,
'Vs':vsProf,
'Vp':vpProf,
'Poissons Ratio':prProf,
'Density':rhoProf,
'Qs':qsProf,
'Qp':qpProf,
'Vs Upper':vsUProf,
'Vs Lower':vsLProf
}
return layerFileValues
def plotLYRFile(fname, title='Layer Model Values', ax=None):
'''
Takes in a path to a ParkSeis layer file and outputs a visual plot of the model parameters
'''
lyrFileVals = readLYRFile(fname)
z = lyrFileVals['Depth']
vs = lyrFileVals['Vs']
vp = lyrFileVals['Vp']
rho = lyrFileVals['Density']
#PLOT
if ax != None:
ax = ax
msg = 'Master Plot'
else:
fig, ax = plt.subplots(1,3, figsize=(6,10))
msg = 'No Master Plot'
majorYLocator = MultipleLocator(1) #sets the major tick interval to every meter
majorYFormatter = FormatStrFormatter('%d')
minorYLocator = MultipleLocator(0.25) #sets the minor tick interval to every 0.25 meter
ax[0].plot(vs, z, c='r', label='Vs')
ax[0].set_xlabel('Vs [m/s]')
ax[0].set_ylabel('Depth [m]')
ax[0].locator_params(axis='x', tight=True, nbins=12)
ax[1].plot(vp, z, c='b', label='Vp')
ax[1].set_xlabel('Vp [m/s]')
ax[1].locator_params(axis='x', tight=True, nbins=8)
ax[2].plot(rho, z, c='k', label='Density')
ax[2].set_xlabel('Density [kg/m$^3$]')
ax[2].set_xlim(1,3)
ax[2].locator_params(axis='x', tight=True, nbins=4)
for i in range(len(ax)):
ax[i].invert_yaxis()
ax[i].yaxis.set_major_locator(majorYLocator)
ax[i].yaxis.set_major_formatter(majorYFormatter)
ax[i].yaxis.set_minor_locator(minorYLocator)
ax[i].grid(which='both', linestyle='--', alpha=0.75)
ax[i].tick_params(axis='x', labelrotation=90)
if i > 0:
ax[i].set_yticklabels([])
ax[i].tick_params(axis='y', which='both', left='off')
if msg == 'No Master Plot':
fig.suptitle(title, y=0.92)
plt.subplots_adjust(wspace=0.05, hspace=0)
plt.show()
return
#################
#PRINT LYR FILE TABLE
#################
def printLYRfile(fname, inv=False):
'''
Takes in a layer file from ParkSEIS and prints out the table of model parameters
'''
with open(fname, 'r') as lyrFile:
lines = lyrFile.readlines()
numLayers = int(lines[2][14:]) #number of layers is on 3rd line starting after the 14 col
paramLines = lines[1:(4+numLayers)] #gets all lines containing model parameters
#for printing inversion file parameters
if inv:
#get inv parameters
sectionLineNums = []
for i, l in enumerate(lines):
if l.startswith('------------------------------------------------------------'):
sectionLineNums.append(i)
if sectionLineNums: #if no section lines exists, still print results
invSecStart, invSecEnd = sectionLineNums[0]+1, sectionLineNums[1]-2 #gets the line range for inversion parameters
matchSecStart, matchSecEnd = sectionLineNums[1]+1, sectionLineNums[2] #same but for match info
invParams = lines[invSecStart:invSecEnd]
matchParams = lines[matchSecStart:matchSecEnd]
print('---- PARAMETERS FOR MODEL %s: \n' %fname)
for l in paramLines:
print(l)
if inv and (sectionLineNums): #again, make sure sections actually exist so can still print without error
print('----INVERSION PARAMETERS')
for l in invParams:
print(l)
print('----INVERSION MATCH')
for l in matchParams:
print(l)
return
#################
#SUPER MODEL PLOT OF AWESOMENESS
#################
def plotModelAnalysis(modPath, fmin=2, fmax=100, vmin=50, vmax=1500, dv=0.1, dx=1.5, X1=9, printParams=False, save=False):
'''
Takes a path to a model folder where results are stored in folders of:
'DC' - all dispersion curves and associated .LYR file
'seis' - all seismic model files generated (i.e. .dat files)
'''
#get DC folders, seismic paths, and LYR paths first
dcFolder, seisFiles, lyrFiles = getModelFolderPaths(modPath)
###
#MAIN LOOP THROUGH MODEL FILES
###
for dcF, seisF, lyrF in zip(dcFolder, seisFiles, lyrFiles):
if printParams: #print out the model parameters
printLYRfile(lyrF)
#LOAD SEISMIC
modTrcs, modStrm = loadModelDAT(seisF)
#LOAD IN EXPERIMENTAL DC FILES
dcDict = loadTheorDC_PATH(dcF)
###
#PLOT
###
fig = plt.figure(figsize=(17,17))
gs = gridspec.GridSpec(2,4, width_ratios=[0.5,0.5,0.5,2.5])
#get plot title
plotTitle = seisF.split('\\')[-1] #gets title for model
#LAYER PLOT
lyrAX = [plt.subplot(gs[0,0]), plt.subplot(gs[0,1]), plt.subplot(gs[0,2])] #create list of axes to pass to function
plotLYRFile(lyrF, ax=lyrAX)
#F-K PLOT
fkAX = plt.subplot(gs[0,3])
fkModelPlot(modStrm, fMin=fmin, fMax=fmax, X1=X1, dx=dx, padLen=200, ax=fkAX)
fig.colorbar(fkAX.images[0], ax=fkAX, shrink=0.7)
#DISP IMAGE PLOT
dcAX = plt.subplot(gs[1,:])
dcModelPhaseShift(modStrm, minVel=vmin, maxVel=vmax, dv=dv, minFreq=fmin, maxFreq=fmax, padLen=500,
X1=X1, dx=dx, overLayDC=dcDict, velSum=True, ax=dcAX)
fig.colorbar(dcAX.images[0], ax=dcAX, shrink=0.7)
#Set title and save
supT = fig.suptitle(plotTitle, x=0.445, y=0.92, fontsize=14)
if save:
figTitle = plotTitle.replace('.dat','')
plt.savefig(figTitle, dpi=300, bbox_inches='tight', bbox_extra_artists=[supT])
plt.show()
return
#################
#MODEL SUMMARY PLOTS FOR THESIS DOCUMENT
#################
def plotModelAnalysis_thesis(modPath, fmin=2, fmax=100, vmin=50, vmax=1500, dv=0.1, dx=1.5, X1=9, printParams=False,
fs=12, save=False):
'''
Takes a path to a model folder where results are stored in folders of:
'DC' - all dispersion curves and associated .LYR file
'seis' - all seismic model files generated (i.e. .dat files)
'''
#get DC folders, seismic paths, and LYR paths first
dcFolder, seisFiles, lyrFiles = getModelFolderPaths(modPath)
###
#MAIN LOOP THROUGH MODEL FILES
###
for dcF, seisF, lyrF in zip(dcFolder, seisFiles, lyrFiles):
if printParams: #print out the model parameters
printLYRfile(lyrF)
#LOAD SEISMIC
modTrcs, modStrm = loadModelDAT(seisF)
#LOAD IN EXPERIMENTAL DC FILES
dcDict = loadTheorDC_PATH(dcF)
###
#PLOT
###
plt.rcParams.update({'font.size': fs}) #global font size
fig = plt.figure(figsize=(15,5))
gs = gridspec.GridSpec(1,5, width_ratios=[0.4,0.4,0.4,0.3,3.25], wspace=0.05)
#get plot title
plotTitle = seisF.split('\\')[-1] #gets title for model
#LAYER PLOT
lyrAX = [plt.subplot(gs[0,0]), plt.subplot(gs[0,1]), plt.subplot(gs[0,2])] #create list of axes to pass to function
plotLYRFile(lyrF, ax=lyrAX)
lyrAX[0].set_xlim(50,350)
lyrAX[0].locator_params(axis='x', tight=True, nbins=8)
lyrAX[0].tick_params(axis='x', which='major', labelsize=fs*0.75)
lyrAX[1].tick_params(axis='x', which='major', labelsize=fs*0.75)
lyrAX[2].set_xlabel('$\\rho$ [kg/m$^3$]')
lyrAX[2].tick_params(axis='x', which='major', labelsize=fs*0.75)
#BLANK SPACER PLOT
axSPACE = plt.subplot(gs[0,3])
axSPACE.axis('off')
#DISP IMAGE PLOT
dcAX = plt.subplot(gs[0,4])
dcModelPhaseShift(modStrm, minVel=vmin, maxVel=vmax, dv=dv, minFreq=fmin, maxFreq=fmax, padLen=500,
X1=X1, dx=dx, overLayDC=dcDict, velSum=True, ax=dcAX)
dcAX.set_title('')
dcAX.get_legend().remove() #removes legend; over crowded and cant see response
#fig.colorbar(dcAX.images[0], ax=dcAX, shrink=0.7)
#Set title and save
if save == False:
supT = fig.suptitle(plotTitle, x=0.445, y=0.99, fontsize=14)
if save:
figTitle = plotTitle.replace('.dat','')
#plt.savefig(figTitle, dpi=300, bbox_inches='tight', bbox_extra_artists=[supT])
plt.savefig(figTitle, dpi=100, bbox_inches='tight')
plt.show()
return
######################
#CREATE LAYER FILES
######################
#NOTE: this code is pretty hacked together and not user friendly
def createLYRFile(h, vs, vp, rho, sigma, qs, qp, fname, directory, fMod='', makeDir=False):
'''
Takes in parameters for a layered earth model and outputs a '.LYR' for use in ParkSEIS modeling
- Earth properties are passed as lists
- Number of parameters passed for all but thickness (h) is n+1, where n is the number of distinct layers
- h is the thickness of each layer; list of length 'n'
- vs, vp, and rho are the shear, compressional, and density (g/cc) of each layer; lists of length 'n+1'
- sigma is Poissons ratio for each layer; list of length 'n+1'
- qs and qp are the attenuation coefficients for each layer; lists of length 'n+1'
- fname is the base name of the layer file being created (NOT including .LYR!!!)
- directory is the directory in which file will be saved
- fMode is a file anme modifier to be added to the base file name
'''
#if specified create sub model directories after checking they dont exist
if makeDir:
if os.path.exists(os.path.join(directory, fMod)):
print('Yo dog, directory already exists. Walk away and come back when you are paying closer attention.')
return
else:
subDir = os.path.join(directory, fMod)
os.makedirs(subDir) #creates sub model directory
directory = os.path.join(subDir, 'DC') #sets directory to save LYR file to
os.makedirs(directory) #makes DC curve directory for sub model
os.makedirs(os.path.join(subDir, 'seis')) #makes seis directory for sub model
#first check if file exists
if fMod != '':
fname = fname + fMod + '.LYR' #adds file anme modifier if given
else:
fname = fname + '.LYR'
if os.path.exists(os.path.join(directory, fname)):
print('Sorry bro, file already exists. Take a breather and come back to work when you\'re paying more attention.')
return
#create initial empty file
Path(os.path.join(directory,fname)).touch()
#write file
#######
#DEFINE STANDARD LINES
#######
#get number of layers in model
numLay = len(vs)
#first 3 lines of .LYR file
first3Lines = f'Layer Model\nThicknessModel = UserDefinedThickness\nNumberOfLayer {numLay}\n'
#parameter table header
tableHead = '{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}\n'.format(
'Layer#'.ljust(10),
'Depth(m)'.ljust(10),
'Thck(m)'.ljust(10),
'Vs(m/s)'.ljust(10),
'Vp(m/s)'.ljust(10),
'Poisson'.ljust(10),
'Density*'.ljust(10),
'Qs*'.ljust(10),
'Qp*'.ljust(10),
'Vs-Lower*'.ljust(10),
'Vs-Upper*'.ljust(10),
)
#'*Note' Section
note = '{0}{1}{2}'.format(
'\n*Note: Densities are in gram per cubic centimeters (gm/cc).\n',
'Qs and Qp: Quality (Q) factors for S and P waves, respectively (...not used for dispersion calculation)\n'.rjust(111),
'Vs-Lower and Vs-Upper, if assigned, indicate lower and upper limits of 99 percent (%) confidence in solution.\n'.rjust(117)
)
#Inofrmation Lines
infoLines = '{0}{1}{2}{3}'.format(
'\nVs Bounds (%): 0\n',
'Record Number: 0\n',
'Xcoord: 0.000\n',
'Distance Unit: meter\n'.rjust(24)
)
#history section
hist = [
'\n>>> Begin of History <<<\n',
f' Number of Layer = {numLay}\n',
f' Depth to Half Space = {sum(h)}\n',
' Depth Conversion Ratio = Automatic\n',
' Constant Poisson\'s Ratio =0.400\n',
f' Saving As {os.path.join(directory,fname)}\n'
'>>> End of History <<<\n',
'v. 2011'
]
###########
#WRITE
###########
#open file in 'append' mode
f = open(os.path.join(directory,fname), 'a')
f.write(first3Lines) #write first 3 lines
f.write(tableHead) #write the table header
#loop through parameters provided and write to table with formating
for l in range(numLay):
lay = str(l+1) #conver current layer to string
z = '%.3f' % sum(h[0:l+1]) #gets depth to layer through cumulative summation
VS, VP, PR, RHO, QS, QP = '%.3f' %vs[l], '%.3f' %vp[l], '%.3f' %sigma[l], '%.3f' %rho[l], '%.3f' %qs[l], '%.3f' %qp[l] #str con
if (l+1) == numLay: #for the final half-space layer
f.write(
'{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}\n'.format(
lay.ljust(10),
'HalfSpace'.ljust(10),
'N/A'.ljust(10),
VS.ljust(10),
VP.ljust(10),
PR.ljust(10),
RHO.ljust(10),
QS.ljust(10),
QP.ljust(10),
'0.000'.ljust(10),
'0.000'.ljust(10)
)
)
else: #for all layers except half-space
H = '%.3f' % h[l]
f.write(
'{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}\n'.format(
lay.ljust(10),
z.ljust(10),
H.ljust(10),
VS.ljust(10),
VP.ljust(10),
PR.ljust(10),
RHO.ljust(10),
QS.ljust(10),
QP.ljust(10),
'0.000'.ljust(10),
'0.000'.ljust(10)
)
)
f.write(note) #write note section
f.write(infoLines) #write history lines
for i in range(len(hist)): #loops through history lines and write
f.write(hist[i])
#close file
f.close()
return
def dcVelSum(data, minVel, maxVel, minFreq, maxFreq, X1, dx, dv=1, padLen=None, title='Summed Velocity'):
'''Takes either a gather file or an Obspy stream along with min/max velocity values to check
and min/max frequency values to check between; output is a plot showing summed DC amplitudes for all
frequencies at a given velocity value.
Shows (in theory) non-dispersive energy in the DC image
'''
################
#Calculate Image
################
if isinstance(data, str):
#load in file to get raw data matrix and stream then extract parameters
gather, gatherStream = loadModelDAT(data)
params = getModelParams(gatherStream)
else:
#extract traces from stream and get acquisition parameters
gather = np.stack(t.data for t in data.traces)
params = getModelParams(data)
#pad time axis if specified
if padLen != None:
gather = np.pad(gather, ((0,0),(padLen,padLen)), 'constant', constant_values=(0,0))
#calculate offset vector
xx = np.arange(X1, X1 + params['numTrc']*dx, dx)
#compute fft and associated freqs
G = np.fft.fft(gather)
freqs = np.fft.fftfreq(gather[0].size, params['dt'])
#select only positive frequencies from fft ouput; i.e. first half
Gp = G[:,:freqs.size//2]
freqsp = freqs[:freqs.size//2]
#select frequencies
df = freqs[10]-freqs[9]
fMax = int(maxFreq/df)
fMin = int(minFreq/df)
#set up velocities to test
testVels = np.arange(minVel, maxVel, dv)
#create empty array to hold transformed data and mode picks
V = np.zeros((len(freqsp[fMin:fMax]), len(testVels)))
numF = V.shape[0]
######TRANSFORM
#run through freqs first
for f in range(len(freqsp[fMin:fMax])):
#then run through each test velocity
#print(freqsp[f+fMin])
for v in range(len(testVels)):
V[f,v] = np.abs( np.sum( Gp[:,f+fMin]/np.abs(Gp[:,f+fMin]) * np.exp(1j*2*np.pi*freqsp[f+fMin]*xx /testVels[v]) ) )
#normalize by the numbre of traces in the gathre (as suggested by Olafsdottir 2018)
Vnorm = V/params['numTrc']
#calculate summation for all frequencies along single velocity value
vSum = Vnorm.sum(axis=0) / numF #normalize by number of frequency values
vSum_array = np.asarray([testVels, vSum])