-
Notifications
You must be signed in to change notification settings - Fork 11
/
seismicToolBox2.py
2601 lines (1962 loc) · 76.3 KB
/
seismicToolBox2.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
"""
A python module for plotting and manipulating seismic data and headers,
kirchhoff migration and more. Contains the following functions
load_header : load mat file header
load_segy : load segy dataset
sorthdr : sort seismic header
sortdata : sort seismic data
selectCMP : select a CMP gather with respect to its midpoint position
analysefold : Positions of gathers and their folds
imageseis : Interactive seismic image
wiggle : Seismic wiggle plot
plothdr : Plots header data
semblanceWiggle : Interactive semblance plot for velocity analysis
apply_nmo : Applies nmo correction
nmo_v : Applies nmo to single CMP gather for constant velocity
nmo_vlog : Applied nmo to single CMP gather for a 1D time-velocity log
nmo_stack : Generates a stacked zero-offset section
stackplot : Stacks all traces in a gather and plots the stacked trace
generatevmodel2 : Generates a 2D velocity model
kirk_mig : Kirkhoff migration
time2depth_trace : time-to-depth conversion for a single trace in time domain
time2depth_section : time-to-depth conversion for a seismic section in time domain
agc : applies automatic gain control for a given dataset.
(C) Nicolas Vinard and Musab al Hasani, 2020, v.0.0.7
- 9.9.2020 added load_header and load_segy
- 31.01.2020 added nth-percentile clipping
- 16.01.2020 Added clipping in wiggle function
- added agc functions
- Fixed semblanceWiggle sorting error
Many of the functions here were developed by CREWES and were originally written in MATLAB.
In the comments of every function we translated from CREWES we refer to its function name
and the CREWES Matlab library at www.crewes.org.
Other functions were translated from MATLAB to Python and originally written by Max Holicki
for the course "Geophyiscal methods for subsurface characterization" tought at TU Delft.
"""
import struct, sys
import numpy as np
import matplotlib
import copy
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
import sys
from typing import Tuple
#from tqdm import tnrange
from stb import segypy
from scipy.io import loadmat
### LOAD HEADER OR SEGY DATA ####
def load_header(file_path)->np.ndarray:
"""
TraceHeaders = load_header(path_to_file)
Parameters
----------
file_path: string
Path to mat file
Returns
-------
TraceHeaders: np.ndarray of shape (5, # traces)
Trace headers containing information of
trace number: TraceHeaders[0,:]
shot position: TraceHeaders[1,:],
receiver positions: TraceHeaders[2,:]
CMP positions: TraceHeaders[3,:]
Offset positions: TraceHeaders[4,:]
"""
TraceHeaders = loadmat(file_path)
return TraceHeaders['H_SHT']
def load_segy(file_path)->tuple([np.ndarray, np.ndarray, np.ndarray]):
"""
Data, TraceHeaders, FileHeader = load_segy(path_to_file)
Parameters
----------
file_path: string
Path to mat file
Returns
-------
Data: np.ndarray of shape (# time samples, # traces)
Seismic data
TraceHeaders: np.ndarray of shape (5, # traces)
Trace headers containing information of
trace number: TraceHeaders[0,:]
shot position: TraceHeaders[1,:],
receiver positions: TraceHeaders[2,:]
CMP positions: TraceHeaders[3,:]
Offset positions: TraceHeaders[4,:]
FileHeader: dictonary
File header information containing info about time sampling rate, time-array and so on
example: access time-array as: time=FileHeader["time"]
"""
segyDataset = segypy.readSegy(file_path)
Data = segyDataset[0]
TraceHeaders = segyDataset[2]
FileHeader = segyDataset[1]
return Data, TraceHeaders, FileHeader
##################################################
########## HEADER AND DATA MANIPULATION ##########
##################################################
def sorthdr(TraceHeaders: np.ndarray, sortkey1: int, sortkey2 = None)->np.ndarray:
"""
sorted_header = sorthdr(TraceHeaders, sortkey1, sortkey2 = None)
Sorts the input header according to the sortkey1 value as primary sort,
and within sortykey1 the header is sorted according to sortkey2.
Valid values for sortkey are:
1 = Common Shot
2 = Common Receiver
3 = Common Midpoint (CMP)
4 = Common Offset
Parameters
----------
TraceHeaders: np.ndarray of shape (5, # traces)
TraceHeaders containing information of shot, receiver, CMP and offset positions
sortkey1: int
Primary sort key by which to sort the header
Optional parameters
-------------------
sortkey2: int
Secondary sort key by which to sort the header
Returns
-------
sortedTraceHeaders: np.ndarray of shape (5, # traces)
Sorted header
Translated to Python from Matlab by Nicolas Vinard and Musab al Hasani, 2019
"""
if sortkey2 is None:
if sortkey1 == 4:
sortkey2 = 3
if sortkey1 == 1:
sortkey2 = 2
if sortkey1 == 2:
sortkey2 = 1
if sortkey1 == 3:
sortkey2 = 4
index_sort = np.lexsort((TraceHeaders[sortkey2, :], TraceHeaders[sortkey1, :]))
sortedTraceHeaders = TraceHeaders[:, index_sort]
return sortedTraceHeaders
def sortdata(
data: np.ndarray,
TraceHeaders: np.ndarray,
sortkey1: int,
sortkey2 = None
)->tuple([np.ndarray, np.ndarray]):
"""
sorted_data, sorted_header = sortdata(data, TraceHeaders, sortkey1, sortkey2 = None):
Sorts data using the data's header. Sorting order is defined according to the
sortkey1 value as primary sort, and within sortykey1 it is is sorted
again according to sortkey2.
Valid values for sortkey are:
1 = Common Shot
2 = Common Receiver
3 = Common Midpoint (CMP)
4 = Common Offset
Parameters
----------
data: np.ndarray of shape (# time samples, # traces)
The seismic data
TraceHeaders: np.ndarray of shape (5, # traces)
Header containing information of shot, receiver, CMP and offset positions
Optional parameters
-------------------
sortkey2: int
Secondary sort key by which to sort the header
Returns
-------
sorted_data: np.ndarray of shape (# time samples, # traces)
Sorted seismic data
sorted_header: np.ndarray of shape (5, # traces)
Sorted header
Translated to Python from Matlab by Nicolas Vinard and Musab al Hasani, 2019
"""
if sortkey2 is None:
if sortkey1 == 4:
sortkey2 = 3
if sortkey1 == 1:
sortkey2 = 2
if sortkey1 == 2:
sortkey2 = 1
if sortkey1 == 3:
sortkey2 = 4
ns, n_traces = data.shape
# Put header on top of data
headered_data = np.append(TraceHeaders, data, axis=0)
index_sort = np.lexsort((headered_data[sortkey2, :], headered_data[sortkey1, :]))
sorted_headerData = headered_data[:, index_sort]
sorted_data = sorted_headerData[len(TraceHeaders):, :]
sorted_header = sorted_headerData[:len(TraceHeaders), :]
return sorted_data, sorted_header
def selectCMP(
CMPsortedData: np.ndarray,
CMPsortedTraceHeaders: np.ndarray,
midpnt: float
)->tuple([np.ndarray, np.ndarray]):
"""
CMPGather, CMPsortedDataTraceHeadersGather = selectCMP(CMPsortedData, CMPsortedTraceHeaders, midpnt):
This function selects a CMP gather according to its midpoint position.
Midpoints can be found with the function analysefold.
Parameters
----------
CMPsortedData: np.ndarray of shape (# time samples, # traces)
CMP sorted seismic data
CMPsortedTraceHeaders: np.ndarray of shape (5, # traces)
CMP sorted header
midpnt: float
Midpoint of the CMP-gather you want to plot
Returns
-------
CMPGather: np.ndarray
Selected CMP-gather
CMPsortedTraceHeaders: np.ndarray
Header of selectred CMP gather
see also sortdata, anaylsefold
Translated to Python from Matlab by Nicolas Vinard and Musab al Hasani, 2019
"""
# Read the amount of time-samples and traces from the shape of the datamatrix
nt, ntr = CMPsortedData.shape
# initialise arrays
CMPgather = np.empty(CMPsortedData.shape)
H_CMPgather = np.empty(CMPsortedTraceHeaders.shape)
# CMP-gather trace counter initialisation:
# l is the number of traces in a CMP gather
l = 0
# Scan the CMP-sorted dataset for traces with the correct midpoint and put those traces in a cmpgather.
for i in range(0,ntr):
if CMPsortedTraceHeaders[3,i] == midpnt:
CMPgather[:,l] = CMPsortedData[:,i]
H_CMPgather[:,l] = CMPsortedTraceHeaders[:,i]
l = l + 1
return CMPgather[:,:l], H_CMPgather[:,:l]
##################################################
########## HEADER AND DATA VISUALIZATION #########
##################################################
def analysefold(TraceHeaders: np.ndarray, sortkey: int
)->tuple([np.ndarray, np.ndarray]):
"""
positions, folds = analysefold(TraceHeaders, sortkey)
This function gives the positions of the gathers, such as CMP's or
Common-Offset gathers, as well as their folds. Furthermore, a
crossplot is generated.
Analysefold analyzes the fold of a dataset according to the value of sortkey:
1 = Common Shot
2 = Common Receiver
3 = Common Midpoint (CMP)
4 = Common Offset
Parameters
----------
TraceHeaders: np.ndarray of shape (5, # traces)
Trace headers
sortkey: int
Sorting key
Returns
-------
positions: np.ndarray
Gather positions
folds: np.ndarray
Gather-folds
Translated to Python from Matlab by Musab al Hasani and Nicolas Vinard, 2019
"""
# Read the amount of time-samples and traces from the shape of the datamatrix
nt, ntr = TraceHeaders.shape
# Sort the header
sortedTraceHeaders = sorthdr(TraceHeaders, sortkey)
# Midpoint initialization, midpoint distance and fold
gather_positions = sortedTraceHeaders[1,0]
gather_positions = np.array(gather_positions)
gather_positions = np.reshape(gather_positions, (1,1))
gather_folds = 1
gather_folds = np.array(gather_folds)
gather_folds = np.reshape(gather_folds, (1,1))
# Gather trace counter initialization
# l is the amount of traces in a gather
l = 0
# Distance counter initialization
# m is the amount of distances in the sorted dataset
m = 0
for k in range(1, ntr):
if sortedTraceHeaders[sortkey, k] == gather_positions[m]:
l = l + 1
else:
if m == 0:
gather_folds[0,0] = l
else:
gather_folds = np.append(gather_folds, l)
m = m + 1
gather_positions = np.append(gather_positions, sortedTraceHeaders[sortkey, k])
l = 0
gather_folds = gather_folds+1
# Remove first superfluous entry in gather_positions
gather_positions = gather_positions[1:]
# Make a plot
fig, ax = plt.subplots(figsize=(8,6))
ax.plot(gather_positions, gather_folds, 'x')
ax.set_title('Amount of traces per gather')
ax.set_xlabel('gather-distance [m]')
ax.set_ylabel('fold')
fig.tight_layout()
return gather_positions, gather_folds
def imageseis(DataO: np.ndarray, x=None, t=None, gain=1, perc=100):
"""
imageseis(Data, x=None, t=None, maxval=-1, gain=1, perc=100):
This function generates a seismic image plot including interactive
handles to apply a gain and a clip
Parameters
----------
Data: np.ndarray of shape (# time samples, # traces)
Seismic data
Optional parameters
-------------------
gain: float
Apply simple gain
x: np.ndarray of shape Data.shape[1]
x-coordinates to Plot
t: np.ndarray of shape Data.shap[0]
t-axis to plot
perc: float
nth parcintile to be clipped
Returns
-------
Seismic image
Adapted from segypy (Thomas Mejer Hansen, https://github.com/cultpenguin/segypy/blob/master/segypy/segypy.py)
Musab and Nicolas added interactive gain and clip, 2019
"""
# Make a copy of the original, so that it won't change the original one ouside the scope of the function
Data = copy.copy(DataO)
# calculate value of nth-percentile, when perc = 100, data won't be clipped.
nth_percentile = np.abs(np.percentile(Data, perc))
# clip data to the value of nth-percintile
Data = np.clip(Data, a_min=-nth_percentile, a_max = nth_percentile)
ns, ntraces = Data.shape
maxval = -1
Dmax = np.max(Data)
maxval = -1*maxval*Dmax
if t is None:
t = np.arange(0, ns)
tLabel = 'Sample number'
else:
t = t
tc = t
tLabel = 'Time [s]'
if len(t)!=ns:
print('Error: time array not of same length as number of time samples in data \n Samples in data: {}, sample in input time array: {}'.format(ns, len(t)))
sys.exit()
if x is None:
x = np.arange(0, ntraces) +1
xLabel = 'Trace number'
else:
x = x
xLabel = 'Distance [m]'
if len(x)!=ntraces:
print('Error: x array not of same length as number of trace samples in data \n Samples in data: {}, sample in input x array: {}'.format(ns, len(t)))
plt.figure()
plt.subplots_adjust(left=0.25, bottom=0.3)
img = plt.pcolormesh(x, t, Data*gain, vmin=-1*maxval, vmax=maxval, cmap='seismic')
cb = plt.colorbar()
plt.axis('auto')
plt.xlabel(xLabel)
plt.ylabel(tLabel)
plt.gca().invert_yaxis()
# Add interactice widgets
# Defines position of the toolbars
ax_cmax = plt.axes([0.25, 0.15, 0.5, 0.03])
ax_cmin = plt.axes([0.25, 0.1, 0.5, 0.03])
ax_gain = plt.axes([0.25, 0.05, 0.5, 0.03])
s_cmax = Slider(ax_cmax, 'max clip ', 0, np.max(np.abs(Data)), valinit=np.max(np.abs(Data)))
s_cmin = Slider(ax_cmin, 'min clip', -np.max(np.abs(Data)), 0, valinit=-np.max(np.abs(Data)))
s_gain = Slider(ax_gain, 'gain', gain, 10*gain, valinit=gain)
def update(val, s=None):
_cmin = s_cmin.val/s_gain.val
_cmax = s_cmax.val/s_gain.val
img.set_clim([_cmin, _cmax])
plt.draw()
s_cmin.on_changed(update)
s_cmax.on_changed(update)
s_gain.on_changed(update)
return img
def wiggle(
DataO: np.ndarray,
x=None,
t=None,
skipt=1,
lwidth=.5,
gain=1,
typeD='VA',
color='red',
perc=100):
"""
wiggle(DataO, x=None, t=None, maxval=-1, skipt=1, lwidth=.5, gain=1, typeD='VA', color='red', perc=100)
This function generates a wiggle plot of the seismic data.
Parameters
----------
DataO: np.ndarray of shape (# time samples, # traces)
Seismic data
Optional parameters
-------------------
x: np.ndarray of shape Data.shape[1]
x-coordinates to Plot
t: np.ndarray of shape Data.shap[0]
t-axis to plot
skipt: int
Skip trace, skips every n-th trace
ldwidth: float
line width of the traces in the figure, increase or decreases the traces width
typeD: string
With or without filling positive amplitudes. Use type=None for no filling
color: string
Color of the traces
perc: float
nth parcintile to be clipped
Returns
-------
Seismic wiggle plot
Adapted from segypy (Thomas Mejer Hansen, https://github.com/cultpenguin/segypy/blob/master/segypy/segypy.py)
"""
# Make a copy of the original, so that it won't change the original one ouside the scope of the function
Data = copy.copy(DataO)
# calculate value of nth-percentile, when perc = 100, data won't be clipped.
nth_percentile = np.abs(np.percentile(Data, perc))
# clip data to the value of nth-percentile
Data = np.clip(Data, a_min=-nth_percentile, a_max = nth_percentile)
ns = Data.shape[0]
ntraces = Data.shape[1]
fig = plt.gca()
ax = plt.gca()
ntmax=1e+9 # used to be optinal
if ntmax<ntraces:
skipt=int(np.floor(ntraces/ntmax))
if skipt<1:
skipt=1
if x is not None:
x=x
ax.set_xlabel('Distance [m]')
else:
x=range(0, ntraces)
ax.set_xlabel('Trace number')
if t is not None:
t=t
yl='Time [s]'
else:
t=np.arange(0, ns)
yl='Sample number'
dx = x[1]-x[0]
Dmax = np.nanmax(Data)
maxval = np.abs(Dmax)
for i in range(0, ntraces, skipt):
# use copy to avoid truncating the data
trace = copy.copy(Data[:, i])
trace = Data[:, i]
trace[0] = 0
trace[-1] = 0
traceplt = x[i] + gain * skipt * dx * trace / maxval
traceplt = np.clip(traceplt, a_min=x[i]-dx, a_max=(dx+x[i]))
ax.plot(traceplt, t, color=color, linewidth=lwidth)
offset = x[i]
if typeD=='VA':
for a in range(len(trace)):
if (trace[a] < 0):
trace[a] = 0
ax.fill_betweenx(t, offset, traceplt, where=(traceplt>offset), interpolate='True', linewidth=0, color=color)
ax.grid(False)
ax.set_xlim([x[0]-1, x[-1]+1])
ax.invert_yaxis()
ax.set_ylim([np.max(t), np.min(t)])
ax.set_ylabel(yl)
def plothdr(TraceHeaders: np.ndarray, trmin=None, trmax=None):
"""
plothdr(Header, trmin, trmax) - plots the header data
Parameters
----------
TraceHeaders: np.ndarray
Data header
Optional parameters
-------------------
trmin: int
Start with trace trmin
trmax: int
End with trace trmax, int
Returns
-------
Figures:
four plots:
(1) shot position
(2) CMP
(3) receiver position
(4) trace offset
Translated to Python from Matlab by Musab al Hasani and Nicolas Vinard, 2019
"""
if trmin == None:
trmin = 0
if trmax == None:
trmax = np.max(np.size(TraceHeaders[0,:]))
fig, ax = plt.subplots(2,2, figsize=(10,8), sharex=True)
ind = np.array([2, 4, 3, 1])
ax[0,0].plot(np.arange(trmin, trmax, 1), TraceHeaders[1, trmin:trmax], 'x')
ax[0,1].plot(np.arange(trmin, trmax, 1), TraceHeaders[3, trmin:trmax], 'x')
ax[1,0].plot(np.arange(trmin, trmax, 1), TraceHeaders[2, trmin:trmax], 'x')
ax[1,1].plot(np.arange(trmin, trmax, 1), TraceHeaders[4, trmin:trmax], 'x')
ax[0,0].set(title = 'shot positions', xlabel = 'trace number', ylabel = 'shot position [m]')
ax[0,1].set(title = 'common midpoint positions (CMPs)', xlabel = 'trace number', ylabel = 'CMP [m]')
ax[1,0].set(title = 'receiver positions', xlabel = 'trace number', ylabel = 'receiver position [m]')
ax[1,1].set(title = 'trace offset', xlabel = 'trace number', ylabel = 'offset [m]')
ax[0,0].xaxis.set_tick_params(which='both', labelbottom=True)
ax[0,1].xaxis.set_tick_params(which='both', labelbottom=True)
fig.tight_layout(pad=1)
##################################################
######### DATA ANALYSIS PRE-PROCESSING ###########
##################################################
def semblanceWiggle(
CMPgather: np.ndarray,
CMPsortedTraceHeaders: np.ndarray,
FileHeader,
vmin:float,
vmax:float,
vstep:float
)->tuple([np.ndarray, np.ndarray]):
"""
v_picks, t_picks = semblanceWiggle(CMPgather,CMPsortedTraceHeaders,FileHeader,vmin,vmax,vstep):
This funcion generates an interactive semblance plot for the velocity analysis.
Picks are generated by left-clicking the semblance with the mouse. A red cross
indicates the location of the picks. Picks can be removed by click in the middle.
To end the picking press enter.
Parameters
----------
CMPgather: np.ndarray
CMP gather
CMPsortedTraceHeaders: np.ndarray
CMP header with postional information
FileHeader:
File header
vmin: float
Minimum velocity in semblance analysis (m/s)
vmax: float
Maximum velocity in semblance analysis (m/s)
vstep: float
Velocity step between vmin and vmax (m/s)
Returns
-------
v_picks: np.ndarray
Picked velocities
t_picks: np.ndarray
Time picks at picked velocities
Translated to Python from Matlab by Nicolas Vinard and Musab al Hasani, 2019
"""
ExpSmooth=50 # used to be optinal argument
# Create vectors
x = CMPsortedTraceHeaders[4,:]
t = np.arange(0,FileHeader['ns']*FileHeader['dt']*1e-6, FileHeader['dt']*1e-6)
t2 = np.arange(0,FileHeader['ns']*FileHeader['dt']*1e-6, FileHeader['dt']*1e-6)
v = np.arange(vmin,vmax+vstep,vstep)
# Compute the squares
xsq = np.square(x)
tsq = np.square(t)
vsq = np.square(v)
# reshape for broadcasting
xsq = xsq.reshape(1,len(xsq),1)
tsq = tsq.reshape(len(tsq),1,1)
vsq = vsq.reshape(1,1,len(vsq))
t = t.reshape((len(t),1,1))
x = x.reshape((1,len(x),1))
v = v.reshape((1,1,len(v)))
T = np.sqrt(tsq+xsq/vsq)
# Interpolate data to NMO time and stack for each velocity
tt = np.exp(-ExpSmooth*np.abs(np.subtract(t,t.T)))
tt = tt.reshape(np.size(t), np.size(t))
S = np.zeros((np.size(t),np.size(v))) # Preallocate semblance
q = np.zeros((np.size(t),np.size(x))) # Preallocate temporary container
b = np.zeros((np.size(t),1))
for vi in range(0, np.size(v)):
for j in range(0, np.size(x)):
q[:,j] = np.interp(T[:,j,vi], t[:,0,0],CMPgather[:,j], left=0,right=0)
r = np.sum(q,axis=1, keepdims=True)
C = t*np.size(x)/np.sum(x**2)*x**2 / T
C[np.isnan(C)] = 0
# Three expressions for conventional semblance
Crq = np.sum(tt*np.sum(r*q,axis=1,keepdims=True),axis=0,keepdims=True).T
Crr = np.sum(tt*np.size(x)*r**2,axis=0,keepdims=True).T
Cqq = np.sum(tt*np.sum(q**2,axis=1,keepdims=True),axis=0,keepdims=True).T
normalS = Crq**2/(Crr*Cqq)
Brq = np.sum(tt*np.sum(r*(C[:,:,vi]*q),axis=1,keepdims=True),axis=0,keepdims=True).T
Brr = np.sum(tt*np.sum(r**2*C[:,:,vi],axis=1,keepdims=True),axis=0,keepdims=True).T
Bqq = np.sum(tt*np.sum(C[:,:,vi]*(q**2),axis=1,keepdims=True),axis=0,keepdims=True).T
# Minimize b
A = Crr*Bqq+Cqq*Brr
Rrq=Crq/(Crq-Brq)
Rrr=Crr/(Crr-Brr)
Rqq=Cqq/(Cqq-Bqq)
ind = np.logical_or(
np.logical_and(
np.less(Rrr,Rrq), np.less(Rrq,Rqq)),
np.logical_and(
np.less(Rqq,Rrq), np.less(Rrq,Rrr)))
ind = ind.astype(int)
for ik in range(0, len(ind)-1):
if ind[ik,0] == 1:
b[ik] = (1-(2*Crq[ik,0]*Brr[ik,0]*Bqq[ik,0]-Brq[ik,0]*A[ik,0])/(2*Brq[ik,0]*Crr[ik,0]*Cqq[ik,0]-Crq[ik,0]*A[ik,0]))**(-1)
elif ind[ik,0] == 0:
b[ik] = Rrq[ik,0]
ind2 = np.zeros((ind.shape)).astype(int)
for ij in range(0,len(b)):
if (b[ij,0] > 1 or b[ij,0] < 0):
ind2[ij] = 1
b[ij,0] = 0
else:
ind2[ij] = 0
Wrq = (1-b)*Crq + b*Brq
Wrr = (1-b)*Crr + b*Brr;
Wqq = (1-b)*Cqq + b*Bqq;
tmp = Wrq**2 / (Wrr*Wqq)
S[:,vi] = tmp.reshape(len(tmp))
Ind = np.argwhere(ind2)[:,0]
s = Brq[Ind]**2/(Brr[Ind]*Bqq[Ind]);
IndF=np.argwhere(Ind)
IND = []
for ik in range(0, len(s)):
if S[ik,vi] > s[ik]:
IND.append(1)
else:
IND.append(0)
S[IndF[IND],vi]=s[IND]
fig, ax = plt.subplots(nrows= 1, figsize=(4,10))
ax.pcolormesh(v, t, S)
ax.invert_yaxis()
ax.set_xlabel('Velocity, m/s', fontsize=12)
ax.set_ylabel('Time, s', fontsize=12)
ax.set_title('Left-click: pick \n - Middle-click: delete pick \n - Enter: save picks ')
fig.tight_layout(pad=2.0, h_pad=1.0)
#plt.waitforbuttonpress(timeout=15)
picks = plt.ginput(n=-1,timeout=15)
plt.close()
if not picks:
sys.exit("No time-velocity picks selected. Closing.")
picks = np.asarray(picks)
v_picks = picks[:,0]
t_picks = picks[:,1]
index_sort = np.argsort(t_picks)
t_picks = t_picks[index_sort]
v_picks = v_picks[index_sort]
t_picks = np.insert(t_picks, 0, 0)
v_picks = np.insert(v_picks, 0, v_picks[0])
t_picks = np.insert(t_picks, len(t_picks), t[-1])
v_picks = np.insert(v_picks, len(v_picks), v_picks[-1])
return v_picks, t_picks
def apply_nmo(
CMPgather: np.ndarray,
CMPsortedTraceHeaders: np.ndarray,
FileHeader,
t: np.ndarray,
v: np.ndarray,
smute=0
)->np.ndarray:
"""
NMOedCMP = apply_nmo(CMPgather, CMPsortedTraceHeaders, FileHeader, t, v, smute=0)
This function applies NMO to a single CMP-gather given a 1D velocity-time log
Addtionally it outputs three plots showing the log, the CMP-gather before and after NMO
Parameters
----------
CMPgather gather: np.ndarray
CMP gather
CMPsortedTraceHeaders: np.ndarray
Header of CMP-gather
FileHeader:
File header
t: np.ndarray of shape (#picks,)
Time of velocity picks in seconds
v: np.ndarray of shape (#picks,)
Velocity picks in m/s
Optinal parameters
------------------
smute: float
Stretch-mute value (default 0)
Returns
-------
Three plots:
(1) log
(2) CMP before
(3) CMP after
NMOedCMP: np.ndarray
NMO-ed CMP gather
Translated to Python from Matlab by Musab al Hasani and Nicolas Vinard, 2019
"""
# Convert time to ms
t = 1000*t
dt = FileHeader['dt']*1e-3 # Convert H['dt'] to ms
nt = FileHeader['ns'] # Number of time samples
# append zero to first time vector if not already 0
if t[0] > 0:
t = np.append(0.0, t)
v = np.append(v[0], v)
# End of t should be the total time
if t[len(t)-1] < dt*nt:
t = np.append(t, dt*nt)
v = np.append(v, v[len(v)-1])
# Plot time-velocity log
t_plot = np.arange(0,dt*nt, dt)
v2 = np.interp(t_plot, t, v)
c = v2
dt = dt/1000
nx = np.min(CMPgather.shape)
NMOedCMP = np.zeros((nt, nx))
if smute == 0:
for ix in range(0, nx):
off = CMPsortedTraceHeaders[4,ix]
for it in range(0, nt):
off2c2 = (off*off)/(c[it]*c[it])
t0 = it * dt
t2 = t0*t0 + off2c2
tnmo = np.sqrt(t2) - t0
itnmo1 = int(np.floor(tnmo/dt))
difft = (tnmo-dt*itnmo1)/dt
if (it+itnmo1) < nt:
NMOedCMP[it,ix] = (1.-difft)*CMPgather[it+itnmo1,ix] + difft*CMPgather[it+itnmo1,ix]
if it+itnmo1 == nt:
NMOedCMP[it, ix] = CMPgather[it+itnmo1-1, ix]
else:
for ix in range(0, nx):
off = CMPsortedTraceHeaders[4,ix]
for it in range(0, nt):
off2c2 = (off*off)/(c[it]*c[it])
t0 = it * dt
t02 = t0*t0
t2 = t02*off2c2
tnmo = np.sqrt(t2)-t0
if it==1:
dtnmo = 1000.
else:
dtnmo = np.abs(np.sqrt(1+off2c2/t02)) - 1.
itnmo1 = int(np.floor(tnmo/dt))
difft = (tnmo-dt*itnmo1)/dt
if (it+itnmo1) < nt:
if dtnmo >= smute:
NMOedCMP[it,ix] = 0.
else:
NMOedCMP[it, ix] = (1.-difft)*CMPgather[it+itnmo,ix] + difft*CMPgather[it+itnmo1,ix]
if it+itnmo1 == nt:
NMOedCMP[it, ix] = CMPgather[it+itnmo1-1,ix]
return NMOedCMP
def semblance(
cmp_sorted_data: np.ndarray,
cmp_sorted_header: np.ndarray,
FileHeader,
cmp_positions: list,
vmin=1500,vmax=4000, vstep=25
)->list:
"""
tvpicks = semblance(cmp_sorted_data, cmp_sorted_header, FileHeader, cmp_positions, vmin=1500, vmax=4000, vstep=25)
Example: cmp_positions = [800, 1200, 2000, 3000]
This function calls semblance for the given list of cmp positions
Parameters
----------
cmp_sorted_data gather: np.ndarray
cmp sorted data
cmp_sorted_header: np.ndarray
cmp sorted header
FileHeader:
Seismic data header
cmp_positions: list,
list of cmp positions (see Example above)
Optinal parameters
------------------
vmin: float
minimum velocity
vmax: float
maximum velocity
vstep: float
velocity increment
Returns
-------
tvpicks: list
list of travel-time picks required for generatevmodel2