In this notebook, we will visualise a 3D reflection seismic dataset. This dataset is freely available from https://terranubis.com/datainfo/F3-Demo-2023¶
Additionally the modified segy data can be downloaded from https://data.utpalsingh.in/nextcloud/index.php/s/8KT6d2P4CzW9ATQ¶
To get started, we need a python package called segyio, xarray, which can be installed using pip install segyio, pip install xarray¶
In [1]:
import segyio
import numpy as np
import matplotlib.pyplot as plt
import xarray as xr
In [2]:
filename = "/Volumes/work/Work/data/seismic/Original_Seismics.sgy"
In [3]:
# Open the data
f = segyio.open(filename, "r", ignore_geometry=True)
f.mmap() # Memory-map the file for fast access
# f.close()
Out[3]:
True
Get list of all available header fields¶
In [4]:
import segyio
# List all trace header fields defined in segyio
print("Available Trace Header Fields:")
for name in dir(segyio.TraceField):
if not name.startswith("_"):
value = getattr(segyio.TraceField, name)
print(f"{name}: {value}")
Available Trace Header Fields: AliasFilterFrequency: 141 AliasFilterSlope: 143 CDP: 21 CDP_TRACE: 25 CDP_X: 181 CDP_Y: 185 CROSSLINE_3D: 193 CoordinateUnits: 89 Correlated: 125 DataUse: 35 DayOfYear: 159 DelayRecordingTime: 109 ElevationScalar: 69 EnergySourcePoint: 17 FieldRecord: 9 GainType: 119 GapSize: 177 GeophoneGroupNumberFirstTraceOrigField: 173 GeophoneGroupNumberLastTraceOrigField: 175 GeophoneGroupNumberRoll1: 171 GroupStaticCorrection: 101 GroupUpholeTime: 97 GroupWaterDepth: 65 GroupX: 81 GroupY: 85 HighCutFrequency: 151 HighCutSlope: 155 HourOfDay: 161 INLINE_3D: 189 InstrumentGainConstant: 121 InstrumentInitialGain: 123 LagTimeA: 105 LagTimeB: 107 LowCutFrequency: 149 LowCutSlope: 153 MinuteOfHour: 163 MuteTimeEND: 113 MuteTimeStart: 111 NStackedTraces: 33 NSummedTraces: 31 NotchFilterFrequency: 145 NotchFilterSlope: 147 OverTravel: 179 ReceiverDatumElevation: 53 ReceiverGroupElevation: 41 ScalarTraceHeader: 215 SecondOfMinute: 165 ShotPoint: 197 ShotPointScalar: 201 SourceDatumElevation: 57 SourceDepth: 49 SourceEnergyDirectionExponent: 223 SourceEnergyDirectionMantissa: 219 SourceGroupScalar: 71 SourceMeasurementExponent: 229 SourceMeasurementMantissa: 225 SourceMeasurementUnit: 231 SourceStaticCorrection: 99 SourceSurfaceElevation: 45 SourceType: 217 SourceUpholeTime: 95 SourceWaterDepth: 61 SourceX: 73 SourceY: 77 SubWeatheringVelocity: 93 SweepFrequencyEnd: 129 SweepFrequencyStart: 127 SweepLength: 131 SweepTraceTaperLengthEnd: 137 SweepTraceTaperLengthStart: 135 SweepType: 133 TRACE_SAMPLE_COUNT: 115 TRACE_SAMPLE_INTERVAL: 117 TRACE_SEQUENCE_FILE: 5 TRACE_SEQUENCE_LINE: 1 TaperType: 139 TimeBaseCode: 167 TotalStaticApplied: 103 TraceIdentificationCode: 29 TraceIdentifier: 213 TraceNumber: 13 TraceValueMeasurementUnit: 203 TraceWeightingFactor: 169 TransductionConstantMantissa: 205 TransductionConstantPower: 209 TransductionUnit: 211 UnassignedInt1: 233 UnassignedInt2: 237 WeatheringVelocity: 91 YearDataRecorded: 157 enums: <bound method Enum.enums of <class 'segyio.tracefield.TraceField'>> offset: 37
Get list of available inlines present in file¶
In [5]:
# Get the list of all available inlines
inlines = f.attributes(segyio.TraceField.INLINE_3D)[:]
unique_inlines = np.unique(inlines)
print(f"Available inlines: {unique_inlines}")
Available inlines: [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]
Lets plot an inline
In [6]:
# Choose the inline you want to extract
target_inline = 483
# Extract traces belonging to the inline
trace_indices = np.where(inlines == target_inline)[0]
# Read all traces for this inline
inline_traces = np.array([f.trace[i] for i in trace_indices])
# Optionally get number of samples (depth axis)
depth = f.samples
plt.imshow(inline_traces.T, aspect='auto', cmap='grey', extent=[0, inline_traces.shape[0], depth[-1], depth[0]], vmin=-8000, vmax = 8000)
plt.xlabel("Crossline Index")
plt.ylabel("Time/Depth (ms)")
plt.title(f"Inline {target_inline}")
plt.colorbar(label="Amplitude")
plt.show()
In [7]:
plt.imshow(inline_traces.T, aspect='auto', cmap='seismic', extent=[0, inline_traces.shape[0], depth[-1], depth[0]], vmin=-8000, vmax = 8000)
plt.xlabel("Crossline Index")
plt.ylabel("Time/Depth (ms)")
plt.title(f"Inline {target_inline}")
plt.colorbar(label="Amplitude")
plt.show()
Storing in ds¶
In [8]:
# Get inline and crossline numbers
inlines = np.unique(f.attributes(segyio.TraceField.INLINE_3D)[:])
crosslines = np.unique(f.attributes(segyio.TraceField.CROSSLINE_3D)[:])
# Time/depth axis
samples = f.samples # Typically in milliseconds
# Preallocate volume: shape [inline, crossline, samples]
volume = np.zeros((len(inlines), len(crosslines), len(samples)), dtype=np.float32)
# Build lookup: map inline/crossline to index
inline_to_index = {iline: i for i, iline in enumerate(inlines)}
crossline_to_index = {xline: i for i, xline in enumerate(crosslines)}
# Fill volume using trace headers
for trace_index in range(f.tracecount):
iline = f.header[trace_index][segyio.TraceField.INLINE_3D]
xline = f.header[trace_index][segyio.TraceField.CROSSLINE_3D]
i = inline_to_index.get(iline)
j = crossline_to_index.get(xline)
if i is not None and j is not None:
volume[i, j, :] = f.trace[trace_index]
# Create xarray Dataset
ds = xr.Dataset(
{
"amplitude": (["inline", "crossline", "time"], volume)
},
coords={
"inline": inlines,
"crossline": crosslines,
"time": samples
},
attrs={
"source": filename
}
)
Lets calculate spectral decomposition at frequency 10Hz, 30Hz¶
In [9]:
import numpy as np
from scipy.signal import butter, sosfiltfilt, hilbert
def butter_bandpass_sos(lowcut, highcut, fs, order=4):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
return butter(order, [low, high], btype='band', output='sos')
def spectral_decomposition_fast(amplitude, freqs=[10, 30], bandwidth=5, dt=0.004):
fs = 1.0 / dt
n_inline, n_crossline, n_samples = amplitude.shape
n_traces = n_inline * n_crossline
# Reshape to 2D: (n_traces, n_samples)
data_2d = amplitude.reshape(n_traces, n_samples)
# Output dictionary
result = {}
for f in freqs:
sos = butter_bandpass_sos(f - bandwidth / 2, f + bandwidth / 2, fs)
# Bandpass filter each trace
filtered = sosfiltfilt(sos, data_2d, axis=1)
# Hilbert envelope
envelope = np.abs(hilbert(filtered, axis=1))
# Reshape back to original volume shape
result[f] = envelope.reshape(n_inline, n_crossline, n_samples)
return result
In [10]:
spectral_decomposition = spectral_decomposition_fast(np.array(ds['amplitude']), freqs=[10, 90])
In [11]:
import matplotlib.pyplot as plt
inline_idx = 483
time_vals = ds['time'].values # 1D array, shape (n_time,)
for freq in [10, 90]:
if freq in spectral_decomposition:
data = spectral_decomposition[freq][inline_idx, :, :] # shape: (crossline, time)
n_crossline = data.shape[0]
plt.figure(figsize=(10, 6))
plt.imshow(
data.T, # Transpose to [time, crossline]
aspect='auto',
cmap='hot',
extent=[0, n_crossline, time_vals[-1], time_vals[0]] # flip y-axis for time/depth
)
plt.title(f'Spectral Decomposition – {freq} Hz (Inline {inline_idx})')
plt.xlabel('Crossline')
plt.ylabel('Time / Depth')
plt.colorbar(label='Spectral Amplitude')
plt.tight_layout()
plt.show()
else:
print(f"Frequency {freq} Hz not found in results.")
Lets calculate similarity parallely using joblib¶
In [12]:
import numpy as np
from joblib import Parallel, delayed
def normalize_traces(seismic):
mean = seismic.mean(axis=2, keepdims=True)
std = seismic.std(axis=2, keepdims=True) + 1e-8
return (seismic - mean) / std
def compute_similarity_slice(i, norm_seis):
n_crossline, n_samples = norm_seis.shape[1], norm_seis.shape[2]
slice_sim = np.ones((n_crossline, n_samples))
il_prev = norm_seis[i - 1]
il_next = norm_seis[i + 1]
center = norm_seis[i]
for j in range(1, n_crossline - 1):
xl_prev = center[j - 1]
xl_next = center[j + 1]
trace = center[j]
# Compute pointwise similarity (per sample)
sim_il = 0.5 * (trace * il_prev[j] + trace * il_next[j])
sim_xl = 0.5 * (trace * xl_prev + trace * xl_next)
slice_sim[j] = (sim_il + sim_xl) / 2
return i, slice_sim
def similarity_volume_parallel(seismic, n_jobs=-1):
n_inline, n_crossline, n_samples = seismic.shape
similarity = np.ones_like(seismic)
norm_seis = normalize_traces(seismic)
results = Parallel(n_jobs=n_jobs, backend='threading')(
delayed(compute_similarity_slice)(i, norm_seis) for i in range(1, n_inline - 1)
)
for i, slice_sim in results:
similarity[i] = slice_sim
return similarity
In [13]:
similarity = similarity_volume_parallel(np.array(ds['amplitude']))
In [14]:
import matplotlib.pyplot as plt
inline_idx = 483
# Extract time values from the dataset
time_vals = ds['time'].values
n_time = similarity.shape[2]
plt.figure(figsize=(10, 6))
im = plt.imshow(similarity[inline_idx, :, :].T, cmap='magma', aspect='auto',
vmin=0, vmax=1, extent=[0, similarity.shape[1], time_vals[-1], time_vals[0]])
plt.title(f"Similarity Attribute – Inline {inline_idx}")
plt.xlabel("Crossline")
plt.ylabel("Time / Depth")
plt.colorbar(im, label="Similarity (0–1)")
plt.tight_layout()
plt.show()
In [16]:
import matplotlib.pyplot as plt
inline_idx = 483
# Extract time values from the dataset
time_vals = ds['time'].values
n_time = similarity.shape[2]
plt.figure(figsize=(10, 6))
im = plt.imshow(similarity[inline_idx, :, :].T, cmap='grey', aspect='auto',
vmin=0, vmax=1, extent=[0, similarity.shape[1], time_vals[-1], time_vals[0]])
plt.title(f"Similarity Attribute – Inline {inline_idx}")
plt.xlabel("Crossline")
plt.ylabel("Time / Depth")
plt.colorbar(im, label="Similarity (0–1)")
plt.tight_layout()
plt.show()
In [ ]: