CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-segyio

Simple & fast IO for SEG-Y files

Pending
Overview
Eval results
Files

file-operations.mddocs/

File Operations

Core functionality for opening existing SEG-Y files, creating new files, and managing file handles. These operations form the foundation of all segyio workflows.

Capabilities

Opening SEG-Y Files

Opens existing SEG-Y files for reading or writing with configurable geometry interpretation and endianness handling.

def open(filename, mode="r", iline=189, xline=193, strict=True, ignore_geometry=False, endian='big'):
    """
    Open a SEG-Y file for reading or writing.
    
    Parameters:
    - filename (str): Path to SEG-Y file
    - mode (str): Access mode ('r' for read-only, 'r+' for read-write)
    - iline (int or TraceField): Inline header field, default 189
    - xline (int or TraceField): Crossline header field, default 193
    - strict (bool): Abort if geometry cannot be inferred, default True
    - ignore_geometry (bool): Skip geometry building for performance, default False
    - endian (str): File endianness ('big', 'little', 'msb', 'lsb'), default 'big'
    
    Returns:
    SegyFile: File handle for operations
    
    Raises:
    IOError: File not found or invalid format
    ValueError: Invalid geometry or parameters
    """

Usage Example:

# Open file with default settings (structured 3D)
with segyio.open('seismic.sgy') as f:
    print(f.ilines, f.xlines)

# Open with custom geometry fields
with segyio.open('data.sgy', iline=segyio.TraceField.INLINE_3D, 
                 xline=segyio.TraceField.CROSSLINE_3D) as f:
    pass

# Open unstructured file (faster, no geometry)
with segyio.open('shots.sgy', ignore_geometry=True) as f:
    # Access only by trace number
    trace = f.trace[0]

Creating SEG-Y Files

Creates new SEG-Y files with specified geometry and structure using a specification template.

def create(filename, spec):
    """
    Create a new SEG-Y file with specified structure.
    
    Parameters:
    - filename (str): Path for new SEG-Y file
    - spec (segyio.spec): File structure specification
    
    Returns:
    SegyFile: File handle for writing operations
    
    Raises:
    IOError: Cannot create file
    ValueError: Invalid specification
    """

File Specification

Template class for defining the structure and geometry of new SEG-Y files.

class spec:
    """
    Specification template for creating new SEG-Y files.
    
    Attributes:
    - iline (int): Inline header field number, default 189
    - ilines (array_like): Inline numbers array
    - xline (int): Crossline header field number, default 193
    - xlines (array_like): Crossline numbers array
    - offsets (array_like): Offset numbers array, default [1]
    - samples (array_like): Sample array (time/depth values)
    - ext_headers (int): Number of extended text headers, default 0
    - format (SegySampleFormat): Sample format, default None
    - sorting (TraceSortingFormat): Trace sorting format, default None
    - endian (str): File endianness, default 'big'
    """

Usage Example:

import numpy as np

# Create specification for 3D post-stack volume
spec = segyio.spec()
spec.samples = np.arange(0, 2000, 4)  # 0-2000ms, 4ms sample rate
spec.ilines = range(100, 200)         # Inlines 100-199
spec.xlines = range(300, 400)         # Crosslines 300-399
spec.format = segyio.SegySampleFormat.IEEE_FLOAT_4_BYTE

# Create and write file
with segyio.create('output.sgy', spec) as f:
    for i, (il, xl) in enumerate(f.ilines, f.xlines):
        # Generate or read trace data
        trace_data = generate_trace(il, xl)
        f.trace[i] = trace_data
        
        # Set trace headers
        f.header[i] = {
            segyio.TraceField.INLINE_3D: il,
            segyio.TraceField.CROSSLINE_3D: xl,
            segyio.TraceField.TRACE_SAMPLE_COUNT: len(spec.samples)
        }

Pre-stack 4D Example:

# Create specification for pre-stack data with offsets
spec = segyio.spec()
spec.samples = np.arange(0, 4000, 2)  # 0-4000ms, 2ms sampling
spec.ilines = range(1000, 1100, 2)    # Every 2nd inline
spec.xlines = range(2000, 2200, 2)    # Every 2nd crossline  
spec.offsets = [100, 200, 300, 400, 500]  # Offset range

with segyio.create('prestack.sgy', spec) as f:
    trace_index = 0
    for il in spec.ilines:
        for xl in spec.xlines:
            for offset in spec.offsets:
                # Write trace data and headers
                f.trace[trace_index] = prestack_trace(il, xl, offset)
                f.header[trace_index] = {
                    segyio.TraceField.INLINE_3D: il,
                    segyio.TraceField.CROSSLINE_3D: xl,
                    segyio.TraceField.offset: offset
                }
                trace_index += 1

SegyFile Class

Main file handle providing access to all SEG-Y file operations and data access modes.

class SegyFile:
    """
    Main file handle for SEG-Y files.
    
    Properties:
    - dtype (numpy.dtype): Data type of traces
    - sorting (int): Inline or crossline sorting  
    - tracecount (int): Total number of traces
    - samples (numpy.ndarray): Array of sample indices/times
    - offsets (numpy.ndarray): Array of offset values
    - ext_headers (int): Number of extended text headers
    - unstructured (bool): True if file has no regular geometry
    - ilines (array_like or None): Inline numbers (structured files)
    - xlines (array_like or None): Crossline numbers (structured files)
    - readonly (bool): True if file opened read-only
    - format: Sample format description
    - endian: File endianness
    
    Access Modes:
    - header: Access to trace headers
    - trace: Access to trace data
    - iline: Access by inline number (3D structured)
    - xline: Access by crossline number (3D structured)
    - fast: Fast dimension access
    - slow: Slow dimension access
    - depth_slice: Access horizontal slices
    - gather: Access pre-stack gathers
    - text: Access to textual headers
    - bin: Access to binary header fields
    
    Methods:
    - flush(): Flush pending writes to disk
    - close(): Close the file handle
    - mmap(): Memory map the file, returns success status
    - attributes(field): Get file-wide attribute reading for header field
    - interpret(ilines, xlines, offsets, sorting): Re-interpret file structure
    - group(word): Group traces by header field values (experimental)
    """

Usage Example:

with segyio.open('data.sgy') as f:
    # File properties
    print(f"Traces: {f.tracecount}")
    print(f"Sample count: {len(f.samples)}")
    print(f"Data type: {f.dtype}")
    print(f"Read-only: {f.readonly}")
    
    # Check if structured or unstructured
    if f.unstructured:
        print("Unstructured file - access by trace index only")
    else:
        print(f"Structured: IL {f.ilines[0]}-{f.ilines[-1]}, "
              f"XL {f.xlines[0]}-{f.xlines[-1]}")
    
    # Memory map for large files
    if f.mmap():
        print("File memory mapped for faster access")
        
    # Group traces by CDP (experimental feature)
    cdp_groups = f.group(segyio.TraceField.CDP)
    print(f"Found {len(cdp_groups)} CDP groups")
    
    # Get file-wide attributes for a header field
    cdp_values = f.attributes(segyio.TraceField.CDP)
    print(f"CDP range: {cdp_values[0]} to {cdp_values[-1]}")

Common Patterns

Context Management

Always use context managers for proper resource cleanup:

# Correct - automatically closes file
with segyio.open('file.sgy') as f:
    data = f.trace[0]
    
# Also correct for explicit control
f = segyio.open('file.sgy')
try:
    data = f.trace[0]
finally:
    f.close()

Error Handling

try:
    with segyio.open('data.sgy') as f:
        # File operations
        pass
except IOError as e:
    print(f"File error: {e}")
except ValueError as e:
    print(f"Invalid parameters: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-segyio

docs

data-access.md

file-operations.md

header-access.md

index.md

seismic-unix.md

utilities.md

tile.json