forked from wanggy-1/cigChannel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunctions.py
More file actions
3650 lines (3236 loc) · 179 KB
/
functions.py
File metadata and controls
3650 lines (3236 loc) · 179 KB
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
"""
Functions for generating geologic models and synthetic seismic data.
Created by Guangyu Wang @ USTC
2022.10.01
"""
import random, math, numba, sys, multiprocessing, pickle, socket, os, shutil, re
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy import ndimage, interpolate
from scipy.spatial import distance
from scipy.fft import fft, fftfreq
from scipy.signal import hilbert
from prettytable import PrettyTable
from PIL import Image, ImageDraw
from joblib import Parallel, delayed
from datetime import datetime
from mpl_toolkits.axes_grid1 import make_axes_locatable
class BiharmonicSpline2D:
"""
2D Bi-harmonic Spline Interpolation.
"""
def __init__(self, x, y):
"""
Use coordinates of the known points to calculate the weight "w" in the interpolation function.
:param x: (numpy.ndarray) - x-coordinates of the known points.
:param y: (numpy.ndarray) - y-coordinates of the known points.
"""
# x- and y-coordinates of the known points.
self.x = x
self.y = y
# Check if the array shape of x and y is identical.
if not self.x.shape == self.y.shape:
raise ValueError("The array shape of x- and y-coordinates must be identical. Get x%s and y%s instead." %
(self.x.shape, self.y.shape))
# Flatten the coordinate arrays if they are not.
if self.x.ndim != 1 and self.y.ndim != 1:
self.x = self.x.ravel(order='C')
self.y = self.y.ravel(order='C')
# Calculate the 1D Green function matrix.
green = np.zeros(shape=[len(self.x), len(self.x)], dtype=np.float32)
for i in range(len(x)):
green[i, :] = np.abs(self.x[i] - self.x) ** 3
# Calculate weights.
if np.linalg.matrix_rank(green) == green.shape[0]: # The Green matrix is invertible.
self.w = np.linalg.inv(green) @ self.y
else: # The Green matrix is non-invertible.
self.w = np.linalg.pinv(green) @ self.y # Use pseudo-inverse.
def __call__(self, x_new):
"""
Interpolate new points.
:param x_new: (numpy.ndarray) - x-coordinates of the new points.
:return y_new: (numpy.ndarray) - y-coordinates of the new points.
"""
# Get the array shape of new x-coordinates.
original_shape = x_new.shape
# Flatten the coordinate arrays if they are not.
if x_new.ndim != 1:
x_new = x_new.ravel(order='C')
# Calculate the 1D Green function matrix.
green = np.zeros(shape=[len(x_new), len(self.x)], dtype=np.float32)
for i in range(len(x_new)):
green[i, :] = np.abs(x_new[i] - self.x) ** 3
# Calculate y-coordinates of new points.
y_new = green @ self.w
y_new = y_new.reshape(original_shape, order='C')
return y_new
class BiharmonicSpline3D:
"""
3D Bi-harmonic Spline Interpolation.
"""
def __init__(self, x, y, z):
"""
Use coordinates of the known points to calculate the weight "w" in the interpolation function.
:param x: (numpy.ndarray) - x-coordinates of the known points.
:param y: (numpy.ndarray) - y-coordinates of the known points.
:param z: (numpy.ndarray) - z-coordinates of the known points.
"""
# x-, y- and z-coordinates of the known points.
self.x = x
self.y = y
self.z = z
# Check if the array shape of x, y and z is identical.
if not self.x.shape == self.y.shape == self.z.shape:
raise ValueError("The array shape of x-, y- and z-coordinates must be identical. Get x%s, y%s and z%s instead." %
(self.x.shape, self.y.shape, self.z.shape))
# Flatten the coordinate arrays if they are not.
if self.x.ndim != 1 and self.y.ndim != 1 and self.z.ndim != 1:
self.x = self.x.ravel(order='C')
self.y = self.y.ravel(order='C')
self.z = self.z.ravel(order='C')
# Calculate the 2D Green function matrix.
delta_x = np.zeros(shape=[len(self.x), len(self.x)], dtype=np.float32)
delta_y = np.zeros(shape=[len(self.y), len(self.y)], dtype=np.float32)
for i in range(len(x)):
delta_x[i, :] = self.x[i] - self.x # Calculate the x-coordinate difference between two points.
delta_y[i, :] = self.y[i] - self.y # Calculate the y-coordinate difference between two points.
mod = np.sqrt(delta_x ** 2 + delta_y ** 2) # The vector's modulus between two points.
mod = mod.ravel(order='C') # Flatten the 2D mod array to 1D.
green = np.zeros(shape=mod.shape, dtype=np.float32) # Initialize the Green function matrix.
# Calculate the Green function matrix at non-zero points.
green[mod != 0] = mod[mod != 0] ** 2 * (np.log(mod[mod != 0]) - 1)
green = green.reshape(delta_x.shape) # Reshape the matrix to 2-D array shape.
# Calculate weights.
if np.linalg.matrix_rank(green) == green.shape[0]: # The Green matrix is invertible.
self.w = np.linalg.inv(green) @ self.z
else: # The Green matrix is non-invertible.
self.w = np.linalg.pinv(green) @ self.z # Use pseudo-inverse.
def __call__(self, x_new, y_new):
"""
Interpolate new points.
:param x_new: (numpy.ndarray) - x-coordinates of the new points.
:param y_new: (numpy.ndarray) - y-coordinates of the new points.
:return znew: (numpy.ndarray) - z-coordinates of the new points.
"""
# Get the array shape of new x-coordinates.
original_shape = x_new.shape
# Check if the array shape of x and y is identical.
if not x_new.shape == y_new.shape:
raise ValueError("The array shape of x- and y-coordinates must be identical. Get x%s and y%s instead." %
(self.x.shape, self.y.shape))
# Flatten the coordinates if they are not.
if x_new.ndim != 1 and y_new.ndim != 1:
x_new = x_new.ravel(order='C')
y_new = y_new.ravel(order='C')
delta_x = np.zeros(shape=[len(x_new), len(self.x)], dtype=np.float32)
delta_y = np.zeros(shape=[len(y_new), len(self.y)], dtype=np.float32)
for i in range(len(x_new)):
delta_x[i, :] = x_new[i] - self.x
delta_y[i, :] = y_new[i] - self.y
mod = np.sqrt(delta_x ** 2 + delta_y ** 2) # The vector's modulus between two points.
mod = mod.ravel(order='C') # Flatten the 2D mod array to 1D.
green = np.zeros(shape=mod.shape, dtype=np.float32)
green[mod != 0] = mod[mod != 0] ** 2 * (np.log(mod[mod != 0]) - 1)
green = green.reshape(delta_x.shape)
# Calculate z-coordinates of new points.
z_new = green @ self.w
z_new = z_new.reshape(original_shape, order='C')
return z_new
class GeoModel:
"""
Geologic model.
"""
def __init__(self, extent, resolution, mute=False):
"""
Initialize a geologic model with hexahedral cells.
:param extent: (List of floats) - [Xmin, Xmax, Ymin, Ymax, Zmin, Zmax]. Extent of the model (unit: meter).
:param resolution: (List of floats) - [dX, dY, dZ]. Model's resolution in each dimension (unit: meter).
:param mute: (Bool) - If True, will not print anything.
Default value is False.
"""
# Coordinates.
self.Xmin, self.Xmax = extent[0], extent[1]
self.Ymin, self.Ymax = extent[2], extent[3]
self.Zmin, self.Zmax = extent[4], extent[5]
self.dX, self.dY, self.dZ = resolution[0], resolution[1], resolution[2]
X = np.arange(start=self.Xmin, stop=self.Xmax, step=self.dX, dtype=np.float32)
Y = np.arange(start=self.Ymin, stop=self.Ymax, step=self.dY, dtype=np.float32)
Z = np.arange(start=self.Zmin, stop=self.Zmax, step=self.dZ, dtype=np.float32)
self.nX, self.nY, self.nZ = len(X), len(Y), len(Z)
self.X, self.Y, self.Z = np.meshgrid(X, Y, Z)
# Attributes.
self.vp = None # P-wave velocity.
self.Ip = None # P-wave impedance.
self.rc = None # Reflection coefficient.
self.seismic = None # Synthetic seismic data.
self.seis_label = None # Seismic response marker of channels.
self.horizon = None # Horizons.
self.fault = None # Fault label (0: non-fault, 1: fault).
self.facies = None # Facies label (0: background, 1: channel fill, 2: point-bar, 3: natural levee, 4: oxbow lake).
self.channel = None # River channel label (0: non-channel, 1: channel).
self.twt = None # Two-way time of seismic wave reflection.
self.rgt = None # Relative geologic time.
self.info = {'basic':[],
'vp':[],
'rc': [],
'wavelet': [],
'dipping': [],
'folds': [],
'faults': [],
'meandering channels': [],
'submarine channels': [],
'noise': []} # Model info.
self.topo_out = None
self.channel_out = None
self.n_submarine = 0
self.n_meandering = 0
self.n_distributary = 0
# Print model's basic information.
if not mute:
print('Model extent:')
print('X range: %.2fm-%.2fm' % (self.Xmin, self.Xmax))
print('Y range: %.2fm-%.2fm' % (self.Ymin, self.Ymax))
print('Z range: %.2fm-%.2fm' % (self.Zmin, self.Zmax))
print('Model resolution (XYZ): [%.2fm x %.2fm x %.2fm]' % (self.dX, self.dY, self.dZ))
print('Model points (XYZ): [%d x %d x %d]' % (self.nX, self.nY, self.nZ))
# Record model's basic information.
self.info['basic'] = ['Model extent:\n',
'X range: %.2fm-%.2fm\n' % (self.Xmin, self.Xmax),
'Y range: %.2fm-%.2fm\n' % (self.Ymin, self.Ymax),
'Z range: %.2fm-%.2fm\n' % (self.Zmin, self.Zmax),
'Model resolution (XYZ): [%.2fm x %.2fm x %.2fm]\n' % (self.dX, self.dY, self.dZ),
'Model points (XYZ): [%d x %d x %d]\n' % (self.nX, self.nY, self.nZ)]
def add_rc(self, rc_range=None, seed=None, mute=False):
"""
Create a horizontally layered acoustic reflection coefficient (RC) model.
:param rc_range: (List of floats) - Range of RC, in the format of [min, max]
Default values are [-1, 1].
:param seed: (Integer) - The seed value needed to generate a random number.
Default value is None, which is to use the current system time.
:param mute: (Bool) - If True, will not print anything.
Default value is False.
"""
# Control the random state.
np.random.seed(seed)
# Print progress.
if not mute:
sys.stdout.write('Generating RC model...')
# Get RC range.
if rc_range is None:
rc_min, rc_max = -1, 1 # The default RC range.
else:
rc_min, rc_max = rc_range[0], rc_range[1]
# Generate random numbers in RC range.
rdm = (rc_max - rc_min) * np.random.random_sample((self.nZ,)) + rc_min
# Initialize RC model with a 3d array filled with ones.
self.rc = np.ones(shape=self.Z.shape, dtype=np.float32)
# Generate model with random RC, each z-slice of the model has uniform RC.
for i in range(self.nZ):
self.rc[:, :, i] = self.rc[:, :, i] * rdm[i]
# Set RC of the first and last z-slices to 0.
self.rc[:, :, 0] *= 0
self.rc[:, :, -1] *= 0
# Record RC information.
self.info['rc'] = ['Acoustic reflection coefficient (RC):\n',
'rc_range: %s\n' % rc_range,
'seed: %s\n' % seed]
# Print progress.
if not mute:
sys.stdout.write('Done.\n')
def add_vp(self,
h_layer_range: list[float] = None,
fm_list: list[float] = [0.3, 0.6],
vp_list: list[tuple] = [(3000, 3500),
(3500, 5000),
(5000, 6500)],
vp_diff: float = 300,
vp_disturb: float = 100,
smooth: bool = True,
sigma: float = 2.0,
seed: int = None,
mute: bool = False):
"""
Create horizontally layered seismic P-wave velocity (Vp) model.
Args:
h_layer_range (list of floats): Range of layer thickness [m].
In the format of [min, max].
The layer thickness will be randomly chosen within this range.
Defaults to [0.1 * (Zmax - Zmin), 0.2 * (Zmax - Zmin)],
where Zmax is the maxima of the model's z-coordinates and
Zmin is the minima of the model's z-coordinates.
fm_list (list of floats): Lower boundaries of the shallow and middle formations.
In the format of [shallow boundary, middle boundary].
Each element in this list is a fraction between 0 and 1,
with 0 representing the model's top and 1 representing the model's bottom.
Defaults to [0.3, 0.6].
vp_list (list of tuples): Vp ranges of the shallow, middle and deep formations [m/s].
In the format of [(min, max), (min, max), (min, max)].
The Vp of each layer in the shallow, middle and deep formations
will be randomly chosen within the respective ranges defined by those tuples.
Defaults to [(3000, 3500), (3500, 5000), (5000, 6500)].
vp_diff (float): Minimum Vp difference between two consecutive layers [m/s].
Defaults to 300 m/s.
vp_disturb (float): Standard deviation of the random Vp disturbance in each layer [m/s].
Defaults to 100 m/s.
smooth (bool): Whether to smooth the Vp model with a Gaussian filter.
Defaults to True.
sigma (float): Standard deviation of the Gaussian kernal.
Defaults to 2.0.
Only effective when smooth is True.
seed (int): Seed value to generate random numbers.
Defaults to None, which is to use the current system time.
mute (bool): Whether to mute printing.
Defaults to False.
"""
# Control the random state.
np.random.seed(seed)
random.seed(seed)
# Print progress.
if not mute:
sys.stdout.write('\rGenerating Vp model...')
# Initialization.
self.vp = np.ones(self.Z.shape, dtype=np.float32) # P-wave velocity.
self.horizon = []
depth_top = self.Zmin # The initial layer's top depth.
ind_bottom = 0 # The initial array Z-index of layer's bottom depth.
if vp_list is None:
vp_list = [(3000, 3500), (3500, 5000), (5000, 6500)]
if fm_list is None:
fm_list = [0.3, 0.6]
if h_layer_range is None:
h_layer_range = [0.1 * (self.Zmax - self.Zmin), 0.2 * (self.Zmax - self.Zmin)]
fmbt_idx = [int(fm_list[0] * (self.nZ - 1)), # Array Z-index of the bottom of shallow formation.
int(fm_list[1] * (self.nZ - 1)), # Array Z-index of the bottom of middle formation.
int(1.0 * (self.nZ - 1))] # Array Z-index of the bottom of deep formation.
# Save info.
self.info['vp'] = ['P-wave velocity:\n',
'h_layer_range: %s\n' % h_layer_range,
'fm_list: %s\n' % fm_list,
'vp_list: %s\n' % vp_list,
'vp_disturb: %s\n' % vp_disturb,
'smooth: %s\n' % smooth]
if smooth:
self.info['vp'].append('sigma: %s\n' % sigma)
self.info['vp'].append('seed: %s\n' % seed)
# Assign velocity from the top to the bottom.
vp_upper = 0
for idx, vp_param in zip(fmbt_idx, vp_list):
fmbt = self.Zmin + idx * self.dZ # Bottom depth of the formation.
vp1, vp2 = vp_param # Vp range of the formation.
while ind_bottom < idx:
# Set layer thickness randomly.
h_layer = random.uniform(h_layer_range[0], h_layer_range[1])
# Compute the layer's bottom depth.
depth_bottom = depth_top + h_layer
# Layer's bottom depth can not be greater than 125% formation bottom depth or Z_max.
if depth_bottom > 1.25 * fmbt or depth_bottom > self.Zmax:
depth_bottom = min(1.25 * fmbt, self.Zmax)
# Compute array Z-index of the layer's top and bottom depth.
ind_top = int((depth_top - self.Zmin) // self.dZ) # Layer's top depth.
ind_bottom = int((depth_bottom - self.Zmin) // self.dZ) # Layer's bottom depth.
# Assign velocity.
vp = random.uniform(vp1, vp2)
while abs(vp - vp_upper) < vp_diff:
vp = random.uniform(vp1, vp2)
vp_upper = vp
# Gaussian distributed velocity.
if vp_disturb > 0.0:
shape = self.vp[:, :, ind_top:ind_bottom+1].shape
self.vp[:, :, ind_top:ind_bottom+1] = np.random.normal(loc=vp, scale=vp_disturb, size=shape)
# Uniform velocity.
else:
self.vp[:, :, ind_top:ind_bottom+1] *= vp
# Z-coordinates of the horizon.
hz = self.Zmin + (ind_bottom+1) * self.dZ
# Store the horizon.
self.horizon.append(Horizon(z=hz,
vp=vp,
rgt=ind_bottom+1,
channel=0))
# Update layer top depth.
depth_top = hz
# Smooth Vp.
if smooth:
for k in range(self.vp.shape[-1]):
self.vp[:, :, k] = ndimage.gaussian_filter(self.vp[:, :, k], sigma=sigma)
# Print progress.
if not mute:
sys.stdout.write(' Done.\n')
def add_rgt(self,
mute: bool = False):
"""
Create a relative geologic time (RGT) model.
Args:
mute (bool): Whether to mute printing.
Defaults to False.
"""
# Print progress.
if not mute:
sys.stdout.write("\rGenerating RGT model...")
# Initialize RGT cube with ones.
self.rgt = np.ones(self.Z.shape, dtype=np.float32)
# Z-indexes.
zid = np.arange(0, self.nZ, 1, dtype=np.float32)
# RGT is 3D Z-indexes.
for k in range(self.nZ):
self.rgt[:, :, k] *= zid[k]
# Print progress.
if not mute:
sys.stdout.write(" Done.\n")
def smooth(self, param='all', sigma=1, mute=False):
"""
Smooth 3D models with Gaussian filter.
:param (String or list of strings): 3D models to be smoothed. For example, ['vp', 'channel'].
1. 'vp' - Smooth Vp model.
2. 'rgt' - Smooth RGT model.
3. 'channel' - Smooth channel label.
If you want to smooth all models, just assign param='all'.
Defaults to 'all'.
:sigma (Float): Standard deviation of the Gaussian filter.
Defaults to 1.
"""
if param == 'all' or 'vp' in param:
if not mute:
sys.stdout.write('Smoothing Vp model...')
if self.vp is None:
raise ValueError("Vp model not found. \
Use 'add_vp' function to create a Vp model.")
self.vp = ndimage.gaussian_filter(self.vp, sigma=sigma)
if not mute:
sys.stdout.write(' Done.\n')
if param == 'all' or 'rgt' in param:
if not mute:
sys.stdout.write("Smoothing RGT model...")
if self.rgt is None:
raise ValueError("RGT model not found. \
Use 'add_rgt' function to create a RGT model.")
self.rgt = ndimage.gaussian_filter(self.rgt, sigma=sigma)
if not mute:
sys.stdout.write(" Done.\n")
if param == 'all' or 'channel' in param:
if not mute:
sys.stdout.write('Smoothing channel label...')
if self.channel is None:
raise ValueError("River channel label not found. \
Use 'add_meandering_channel_from_database', 'add_distributary_channel_from_database', \
or 'add_submarine_channel' to create channel label.")
self.channel = self.channel.astype(np.float32)
self.channel = ndimage.gaussian_filter(self.channel, sigma=sigma)
if not mute:
sys.stdout.write(' Done.\n')
def compute_Ip(self, rho=2.4):
"""
Compute seismic P-wave impedance in terms of constant rock density.
:rho (float): Rock density. Defaults to 2.4.
"""
if self.vp is None:
raise ValueError("P-wave velocity (Vp) model is not exist. Use 'add_vp' function to create a Vp model.")
self.Ip = self.vp * rho
def compute_rc(self, mute=False):
"""
Compute reflection coefficients (RC) in terms of constant rock density.
RC = (Vp[i+1] - Vp[i]) / (Vp[i+1] + Vp[i])
:param mute: (Bool) - If True, will not print anything.
Default value is False.
"""
# If RC model does not exist.
if self.rc is None:
if self.vp is None:
raise ValueError("P-wave velocity (Vp) model is not exist. Use 'add_vp' function to create a Vp model.")
self.rc = np.zeros(self.vp.shape, dtype=np.float32)
for i in range(self.rc.shape[2] - 1):
if not mute:
sys.stdout.write('\rComputing reflection coefficient: %.2f%%' % ((i + 1) / (self.vp.shape[2] - 1) * 100))
self.rc[:, :, i] = (self.vp[:, :, i + 1] - self.vp[:, :, i]) / (self.vp[:, :, i + 1] + self.vp[:, :, i])
if not mute:
sys.stdout.write('\n')
# If RC model exists.
else:
s = input('A reflection coefficient model exists, do you want to overwrite it? [Y/N]')
if s.lower() == 'y':
if self.vp is None:
raise ValueError("P-wave velocity (Vp) model is not defined. Use 'add_vp' function to define Vp model.")
for i in range(self.rc.shape[2] - 1):
if not mute:
sys.stdout.write(
'\rComputing reflection coefficient: %.2f%%' % ((i + 1) / (self.vp.shape[2] - 1) * 100))
self.rc[:, :, i] = (self.vp[:, :, i + 1] - self.vp[:, :, i]) / (self.vp[:, :, i + 1] + self.vp[:, :, i])
if not mute:
sys.stdout.write('\n')
else:
print('Reflection coefficient model is unchanged.')
def make_synseis(self,
wavelet_type: str = 'ricker',
A: float = 1.0,
f_ricker: float = 30,
f_ormsby: tuple[float] = (5, 10, 40, 45),
dt: float = 0.002,
length: float = 0.1,
mark_channel: bool = True,
plot_wavelet: bool = False,
mute: bool = False):
"""
Make synthetic seismic data.
Args:
wavelet_type (str): Wavelet type.
Options: 1. 'ricker' - Ricker wavelet.
2. 'ormsby' - Ormsby wavelet.
Default value is 'ricker'.
A (float): Maximum amplitude of the wavelet.
Defaults to 1.0.
f_ricker (float): Peak frequency of the Ricker wavelet (unit: Hz).
Default value is 30Hz.
Only effective when 'type' is 'ricker'.
f_ormsby (tuple of float): Four frequencies of the Ormsby wavelet (unit: Hz),
in the format of (low-cut, low-pass, high-pass, high-pass).
Default values are (5, 10, 40, 45)Hz.
dt (float): Sampling time interval of the wavelet (unit: s).
Defaults to 0.002s.
length (float): Time duration of the wavelet (unit: s).
Defaults to 0.1s.
mark_channel (str): Mark the seismic response of channels.
plot_wavelet (bool): Whether to visualize the wavelet.
Defaults to False.
mute (bool): Whether to mute printing.
Defaults to True.
"""
# Check if RC model exists.
if self.rc is None:
raise ValueError("Reflection coefficient (RC) model is not defined. Use 'add_rc' or 'compute_rc' functions to define RC model.")
# Initialize the output.
self.seismic = np.zeros(shape=self.rc.shape, dtype=np.float32)
# Initialize seismic label (seismic response marker of channels).
if mark_channel:
if self.channel is None:
raise ValueError("Channel label not found.")
else:
if self.channel.dtype == np.int16:
label_type = 'instance'
self.seis_label = np.zeros(self.seismic.shape, dtype=np.int16)
else:
label_type = 'semantic'
self.seis_label = np.zeros(self.seismic.shape, dtype=np.uint8)
# Add padding to the channel labels, otherwise their seismic labels will be problematic.
channelp = padding3D(self.channel, pad_up=50, pad_down=50)
self.seis_label = padding3D(self.seis_label, pad_up=50, pad_down=50)
# Generate seismic wavelet.
t = np.arange(-length / 2, length / 2, dt, dtype=np.float32)
if wavelet_type == 'ricker': # Riker wavelet.
wavelet = (1 - 2 * math.pi ** 2 * f_ricker ** 2 * t ** 2) * np.exp(-math.pi ** 2 * f_ricker ** 2 * t ** 2)
wavelet *= A
if wavelet_type == 'ormsby': # Ormsby wavelet.
f1, f2, f3, f4 = f_ormsby
wavelet = (math.pi * f1 ** 2) / (f2 - f1) * np.sinc(math.pi * f1 * t) ** 2 - \
(math.pi * f2 ** 2) / (f2 - f1) * np.sinc(math.pi * f2 * t) ** 2 - \
(math.pi * f3 ** 2) / (f4 - f3) * np.sinc(math.pi * f3 * t) ** 2 + \
(math.pi * f4 ** 2) / (f4 - f3) * np.sinc(math.pi * f4 * t) ** 2
wavelet *= A
# Record wavelet info.
self.info['wavelet'] = ['Seismic Wavelet:\n',
'wavelet_type: %s\n' % wavelet_type,
'A: %s\n' % A,
'length: %s(s)\n' % length,
'dt: %s(s)\n' % dt]
if wavelet_type == 'ricker':
self.info['wavelet'].append('f_ricker: %s\n' % f_ricker)
if wavelet_type == 'ormsby':
self.info['wavelet'].append('f_ormsby: %s\n' % f_ormsby)
# Compute amplitude spectrum of the wavelet.
n = len(wavelet)
xf = fftfreq(n, dt)[:n//2]
yf = np.abs(fft(wavelet))[:n//2]
# Make synthetic seismic data.
for i in range(self.rc.shape[0]):
for j in range(self.rc.shape[1]):
# Print progress.
if not mute:
sys.stdout.write('\rGenerating synthetic seismic data: %.2f%%' %
((i*self.rc.shape[1]+j+1) / (self.rc.shape[0]*self.rc.shape[1]) * 100))
# Seismic data.
self.seismic[i, j, :] = np.convolve(self.rc[i, j, :], wavelet, mode='same')
# Mark the seismic response of channel.
# Semantic label.
# (0: non-channel, 1: channel)
if mark_channel and label_type == 'semantic':
clb = channelp[i, j, :].copy()
# Skip this trace if the labels are all zeros.
if (clb == 0).all():
continue
else:
# Convolve wavelet and channel label.
slb = np.convolve(clb, wavelet, mode='same')
# Compute envelope.
slb = np.abs(hilbert(slb))
# Ensure the channel fill has the strongest seismic response.
slb = np.maximum(slb, clb)
# Binarize.
slb[slb < 0.5] = 0
slb[slb >= 0.5] = 1
# Update seismic label.
self.seis_label[i, j, :] = slb
# Instance label.
# (101: meandering channel 1, 102: meandering channel 2, ...)
# (201: distributary channel 1, 202: distributary channel 2, ...)
# (301: submarine channel 1, 302: submarine channel 2, ...)
if mark_channel and label_type == 'instance':
# Get unique label values in this trace.
lbl = np.unique(channelp[i, j, :])
if (lbl == 0).all():
# Skip this trace if the labels are all zeros.
continue
else:
# Rule out non-channel.
lbl = lbl[lbl > 0]
for k in range(len(lbl)):
# A trace in channel label cube.
clb = channelp[i, j, :].copy()
# Convert to binary.
clb[clb != lbl[k]] = 0
clb[clb == lbl[k]] = 1
# Convolve wavelet and channel label.
slb = np.convolve(clb, wavelet, mode='same')
# Compute the envelope.
slb = np.abs(hilbert(slb))
# Ensure the channel fill has the strongest seismic response.
slb = np.maximum(slb, clb)
# Binarize.
slb[slb < 0.5] = 0
slb[slb >= 0.5] = 1
# Assign instance id.
slb *= lbl[k]
# Update.
self.seis_label[i, j, :] = np.maximum(self.seis_label[i, j, :], slb)
# Depadding the seismic label.
self.seis_label = depadding3D(self.seis_label, pad_up=50, pad_down=50)
if not mute:
sys.stdout.write('\n')
# Visualize wavelet.
if plot_wavelet:
fig, ax = plt.subplots(1, 2, figsize=(16, 4))
ax[0].plot(t, wavelet, 'k', lw=3)
ax[0].set_xlabel('Time(s)', fontsize=14)
ax[0].set_ylabel('Amplitude', fontsize=14)
ax[0].tick_params(labelsize=12)
ax[1].plot(xf, yf, 'k', lw=3)
ax[1].set_xlabel('Frequency(Hz)', fontsize=14)
ax[1].set_ylabel('Amplitude', fontsize=14)
ax[1].tick_params(labelsize=12)
fig.tight_layout()
plt.show()
def add_dipping(self,
a_range: list[float] = [0.1, 0.3],
b_range: list[float] = [0.1, 0.3],
Xc_range: list[float] = [0.4, 0.6],
Yc_range: list[float] = [0.4, 0.6],
seed: int = None,
mute: bool = False):
"""
Simulate dipping structure.
Args:
a_range (list of float): Range of 'a', which determines the dipping angle in x-direction,
in the format of [min, max].
Default range is [0.1, 0.3].
Larger value means more dipping.
b_range (list of float): Range of 'b', which determines the dipping angle in y-direction,
in the format of [min, max].
Default range is [0.1, 0.3].
Larger value means more dipping.
Xc_range (list of float): X-coordinate range of the dipping center, in the format of [min, max].
This range must be between 0 and 1, with 0 means the minimum x-coordinate and 1 means
the maximum x-coordinate.
Default range is [0.4, 0.6].
Yc_range (list of float): Y-coordinate range of the dipping center, in the format of [min, max].
This range must be between 0 and 1, with 0 means the minimum y-coordinate and 1 means
the maximum y-coordinate.
Default range is [0.4, 0.6].
seed (int): The seed value needed to generate a random number.
Defaults to None, which is to use the current system time.
mute (bool): If True, will not print anything.
Defaults to False.
"""
# Random state control.
random.seed(seed)
# Print progress.
if not mute:
sys.stdout.write('\rSimulating dipping structure...')
# Initialize the dipping parameter table.
tb = PrettyTable()
tb.field_names = ['a', 'b', 'Xc(m)', 'Yc(m)']
tb.float_format = '.2'
# Record input parameters.
self.info['dipping'] = ['Dipping:\n',
'a_range: %s\n' % a_range,
'b_range: %s\n' % b_range,
'Xc_range: %s\n' % Xc_range,
'Yc_range: %s\n' % Yc_range,
'seed: %s\n' % seed]
# Vertical shift field.
a = random.uniform(a_range[0], a_range[1]) * random.choice([-1, 1])
b = random.uniform(b_range[0], b_range[1]) * random.choice([-1, 1])
Xc = random.uniform(Xc_range[0], Xc_range[1]) * (self.Xmax - self.Xmin) + self.Xmin
Yc = random.uniform(Yc_range[0], Yc_range[1]) * (self.Ymax - self.Ymin) + self.Ymin
c0 = -a * Xc - b * Yc
dZ = a * self.X + b * self.Y + c0
# Shift Z-coordinates.
self.Z -= dZ
# Dipping parameter table.
tb.add_row([a, b, Xc, Yc])
self.info['dipping'].append(tb) # Record the table.
# Print.
if not mute:
sys.stdout.write(' Done.\n')
print(tb)
def add_fold(self,
N: int = 10,
miu_X_range: list[float] = [0, 1],
miu_Y_range: list[float] = [0, 1],
sigma_range: list[float] = [0.1, 0.2],
A_range: list[float] = [0.1, 0.2],
d_fold: float = 300,
zscale: float = 1.5,
sync: bool = False,
seed: int = None,
mute: bool = False):
"""
Simulate folds with a set of Gaussian functions.
N (int): The number of Gaussian functions.
This is also the approximate number of folds.
Defaults to 10.
miu_X_range (list of float): X-coordinate range of the fold center (i.e. mean of the Gaussian function).
This range must be between 0 and 1, with 0 means the minimum x-coordiante and
1 means the maximum x-coordinate.
The default range is [0, 1].
miu_Y_range (list of float): Y-coordinate range of the fold center (i.e. mean of the Gaussian function).
This range must be between 0 and 1, with 0 means the minimum y-coordinate and
1 means the maximum y-coordinate.
The default range is [0, 1].
sigma_range (list of float): Half-width range of the fold (i.e. standard deviation of the Gaussian function).
This range must be between 0 and 1, with 0 means the minimum horizontal coordinate
and 1 means the maximum horizontal coordinate.
The default range is [0.1, 0.2].
A_range (list of float): Amplitude range of the fold (i.e. amplitude of the Gaussian function).
This range must be between 0 and 1, with 0 means the minimum z-coordinate and 1 means
the maximum z-coordinate.
The default range is [0.1, 0.2].
d_fold (float): Minimum distance between each pair of folds [m].
Defaults to 300 m.
z_scale (float): Scaling factor of fold amplitude.
Defaults to 1.5.
sync (bool): Whether the fold bending will not increase with depth.
Defaults to False.
seed (int): The seed value needed to generate a random number.
Defaults to None, which is to use the current system time.
mute (bool): Whether to mute printing verbose info.
Defaults to False
"""
# Random state control.
random.seed(seed)
# Print progress.
if not mute:
sys.stdout.write('\rSimulating folds...')
# Initialize the fold parameter table.
fold_parameter = PrettyTable()
fold_parameter.field_names = ['Number', 'miu_X (m)', 'miu_Y (m)', 'sigma (m)', 'Amplitude (m)']
fold_parameter.float_format = '.2'
# Save info.
self.info['folds'] = ['Folds:\n',
'miu_X_range: %s\n' % miu_X_range,
'miu_Y_range: %s\n' % miu_Y_range,
'sigma_range: %s\n' % sigma_range,
'A_range: %s\n' % A_range,
'Sync: %s\n' % sync,
'seed: %s\n' % seed]
# Create folds.
Gaussian_sum = 0 # Initialize the summation of Gaussian functions.
x0y0_list = [] # A list of all fold center coordinates.
for i in range(N):
flag = 1
while(flag == 1):
miu_X = random.uniform(miu_X_range[0], miu_X_range[1]) * (self.Xmax - self.Xmin) + self.Xmin
miu_Y = random.uniform(miu_Y_range[0], miu_Y_range[1]) * (self.Ymax - self.Ymin) + self.Ymin
if len(x0y0_list) == 0:
x0y0_list.append((miu_X, miu_Y))
flag = 0
else:
for item in x0y0_list:
x0, y0 = item
d = math.sqrt((miu_X - x0)**2 + (miu_Y - y0)**2)
if d >= d_fold:
x0y0_list.append((miu_X, miu_Y))
flag = 0
sigma = random.uniform(sigma_range[0], sigma_range[1]) * min(self.Xmax - self.Xmin, self.Ymax - self.Ymin)
A = random.uniform(A_range[0], A_range[1]) * (self.Zmax - self.Zmin)
# The Gaussian function.
f_Gaussian = A * np.exp(-1 * ((self.X - miu_X) ** 2 + (self.Y - miu_Y) ** 2) / (2 * sigma ** 2))
Gaussian_sum += f_Gaussian # Combine the Gaussian functions.
fold_parameter.add_row([i + 1, miu_X, miu_Y, sigma, A]) # Visualizing parameters.
# Shift the Z-coordinates vertically.
if sync is False:
self.Z = self.Z - zscale * self.Z / self.Z.max() * Gaussian_sum
else:
self.Z = self.Z - Gaussian_sum
# Save info.
self.info['folds'].append(fold_parameter)
# Print.
if not mute:
sys.stdout.write('Done.\n')
print(fold_parameter)
def add_fault(self, N=3, reference_point_range=None, phi_range=None, theta_range=None,
d_max_range=None, lx_range=None, ly_range=None, gamma_range=None, beta_range=None,
curved_fault=False, n_perturb=20, perturb_range=None, d_fault=300.0,
computation_mode='parallel', seed=None, mute=False):
"""
Simulate faults.
:param N: (Integer) - The number of faults.
Default value is 3.
:param reference_point_range: (List of floats) - Coordinate ranges of the fault plane center (unit: m), in the format of [X0_min, X0_max, Y0_min, Y0_max, Z0_min, Z0_max].
Must be decimals between 0 and 1.
For the center of each fault plane:
The actual x-coordinate will be randomly chosen between:
'X0_min * (Xmax - Xmin)' and 'X0_max * (Xmax - Xmin)'.
The actual y-coordinate will be randomly chosen between:
'Y0_min * (Ymax - Ymin)' and 'Y0_max * (Ymax - Ymin)'.
The actual z-coordinate will be randomly chosen between:
'Z0_min * (Zmax - Zmin)' and 'Z0_max * (Zmax - Zmin)'.
Default values are [0.1, 0.9, 0.1, 0.9, 0.3, 0.9].
:param phi_range: (List of floats) - Strike angle range (unit: degree), in the format of [min, max].
The strike angle of each fault will be randomly chosen between this range.
Default values are [0, 360].
:param theta_range: (List of floats) - Dip angle range (unit: degree), in the format of [min, max].
The dip angle of each fault will be randomly chosen between this range.
Default values are [0, 90].
:param d_max_range: (List of floats) - Range of maximum displacement on the fault plane (unit: meter), in the format of [min, max].
Must be two decimals no less than zero.
For each fault, the actual displacement value will be randomly chosen between:
'min * y_range' and 'max * y_range', where y_range is the model's extent in dip direction of the fault.
Default values are [0.1, 0.3].
:param lx_range: (List of floats) - Range of axial length of the elliptical fault displacement field in strike direction (unit: meter), in the format of [min, max].
Must be two decimals no less than zero.
For each fault, the actual axial length will be randomly chosen between:
'min * x_range' and 'max * x_range', where x_range is the model's extent in strike direction of the fault.
Default values are [0.5, 1.0].
:param ly_range: (List of floats) - Range of axial length of the elliptical fault displacement field in dip direction (unit: meter), in the format of [min, max].
Must be two decimals no less than zero.
For each fault, the actual axial length will be randomly chosen between:
'min * y_range' and 'max * y_range', where y_range is the model's extent in dip direction of the fault.
Default values are [0.1, 0.5].
:param gamma_range: (List of floats) - Range of reverse drag radius (unit: m), in the format of [min, max].
Must be two decimals no less than zero.
For each fault, the actual radius will be randomly chosen between:
'min * z_range' and 'max * z_range', where z_range is the model's extent in normal direction of the fault.
Default values are [0.1, 0.5].
:param beta_range: (List of floats) - Range of 'hanging-wall displacement / d_max', in the format of [min, max].
The beta value of each fault will be randomly chosen between this range.
Default values are [0.5, 1.0].
:param curved_fault: (Bool) - Whether to create a curved fault.
Default value is False.
:param n_perturb: (Integer) - Number of perturbation points near the fault plane, which are used to create a curved fault plane.
Default value is 20.
Only effective when 'curved_fault' is True.
:param perturb_range: (List of floats) - Normal distance range from perturbation points to the fault plane (unit: meter), in the format of [min, max].
Must be two decimals between -1 and 1.
For each fault, the actual distance will be randomly chosen between:
'min * z_range' and 'max * z_range', where z_range is the model's extent in normal direction of the fault.
Default values are [-0.05, 0.05].
Only effective when 'curved_fault' is True.
:param d_fault: (Float) - Minimum distance between faults (unit: meter).
Default value is 300.0.
:param computation_mode: (String) - The computation mode.
Options are:
1. 'parallel' - which is to break down the model's coordinate arrays into
slices and simulate curved faults in parallel.
2. 'non-parallel' - takes the whole coordinate arrays as input to simulate
the curved faults.
Notice that when the model size is small (e.g. 32 x 32 x 32), taking the
whole coordinate array as input will be faster.
In addition, when the memory is not enough, using the 'parallel' mode
may solve the problem.
:param seed: (Integer) - The seed value needed to generate a random number.
Default value is None, which is to use the current system time.
:param mute: (Bool) - If True, will not print anything.
Default value is False.
"""
# Random state control.
random.seed(seed)
np.random.seed(seed)
# Print.
if curved_fault: # Curved fault.
if computation_mode != 'parallel' and computation_mode != 'non-parallel':
raise ValueError("'computation_mode' must be 'parallel' or 'non-parallel'.")
else:
if not mute:
sys.stdout.write(f'\rSimulating curved fault in {computation_mode} mode...')
else: # Planar fault.
if not mute:
sys.stdout.write('\rSimulating planar fault...')
# Initialize fault marker.
self.fault = np.zeros(self.Z.shape, dtype=np.int32)
# Initialize the fault parameter table.
fault_parameter = PrettyTable()
fault_parameter.field_names = ['Fault Number', 'X0(m)', 'Y0(m)', 'Z0(m)',
'phi(degree)', 'theta(degree)',
'dmax(m)', 'lx(m)', 'ly(m)',
'gamma', 'beta']
fault_parameter.float_format = '.2'
# Assign default parameters.