Skip to main content

Data API

Dataset and data loading interfaces

DevitoHorizon provides a clean interface for loading and managing seismic shot data from various formats.

Module: devitohorizon.data

from devitohorizon.data import (
    Dataset,           # Main dataset container
    SeismicData,          # Single shot container
    DataManager,       # Abstract base class
    SEGYDataManager,   # SEG-Y format loader
    ZarrDataManager,   # Zarr format loader
)

from devitohorizon.config import DataConfig  # Configuration dataclass

Dataset

The main container for seismic survey data.

Factory Methods

# From SEG-Y file
dataset = Dataset.from_segy(
    data_path="shots.segy",
    preprocess=None,     # Optional preprocessing config
    creds=None,          # Optional credentials (cloud storage)
    t0=None,             # Optional override for the recording delay (s or "20ms")
    tn=None,             # Optional truncation of each shot to ≤ tn (s or "4s")
)

# From Zarr store
dataset = Dataset.from_zarr(
    data_path="shots.zarr",
    preprocess=None,
    creds=None,
    t0=None,
    tn=None,
)

# Geometry-only acquisition (no recorded data) for forward modeling
acquisition = Dataset.from_geometry(
    sources,             # (nshots, ndim) or (nshots, 1, ndim), or list of arrays
    receivers,           # shared (nrec, ndim) spread, or one array per shot
    dt=4.0,              # sampling interval in ms
    nt=2501,             # number of time samples to model per shot
)
shots = physics.simulate_shots(acquisition)  # populated SeismicData, ready to image

# From custom DataManager
from devitohorizon.config import DataConfig
config = DataConfig(data_path="data.h5")
manager = MyCustomDataManager(config)
dataset = Dataset(manager)
Tip

Dataset.from_geometry describes an acquisition with no recorded data — each shot is a SeismicData blank carrying only the geometry and nt samples. simulate_shots fills it in and returns populated SeismicData, so a synthetic dataset feeds straight into image/objective without re-wrapping by hand.

Header overrides: t0 and tn

t0 and tn exist for the case where a SEG-Y file’s timing headers are wrong and you cannot rewrite the file:

Param Effect What is not changed
t0 Replaces shot.t0_rec (recording delay). The data array, shot.dt.
tn Truncates shot.data to the samples at or before tn, using the file’s dt. shot.dt — dt is always taken from the SEG-Y header.

Either parameter accepts a number (interpreted as seconds) or a string with an explicit unit suffix ("20ms", "500us"). The two parameters are independent — set either or both. Per-shot validation runs at load time and raises if tn ≤ t0_rec, if the header dt is non-positive, or if the truncation would leave fewer than one sample.

If you only want to limit FWI’s view of otherwise correct data, set the window on DevitoPhysics instead — that does not modify shots, see the Physics API.

Properties and Methods

# Number of shots
n_shots = len(dataset)

# Available shot IDs
shot_ids = dataset.shot_ids  # List[int]

# Get single shot
shot = dataset[0]           # By index
shot = dataset.get(shot_id) # By shot ID

# Create subset
subset = dataset.subset([0, 5, 10, 15])  # By indices

# Random sample
sample = dataset.sample(n=8, seed=42)    # Random subset

# Computed surface (for datum muting)
surface = dataset.surface  # Dict with 'horizontal', 'depth'

Iteration

# Iterate over all shots
for shot in dataset:
    print(f"Shot {shot.shot_id}: {shot.data.shape}")

# Batch iteration
for i in range(0, len(dataset), batch_size):
    batch = dataset.subset(range(i, min(i + batch_size, len(dataset))))

Example

from devitohorizon.data import Dataset

# Load with preprocessing
dataset = Dataset.from_segy(
    "data/marmousi_shots.segy",
    preprocess={
        'filters': [
            {'type': 'bandpass', 'freqs': [2, 4, 18, 20]},
        ],
        'mute': {'type': 'top', 'velocity': 1500.0, 'taper': 20},
    }
)

print(f"Loaded {len(dataset)} shots")
print(f"Shot IDs: {dataset.shot_ids[:5]}...")

# Access single shot
shot = dataset[0]
print(f"Shot 0 shape: {shot.data.shape}")  # (nt, nrec)
print(f"Time sampling: {shot.dt} ms")

SeismicData

Container for a single shot record. A shot may carry recorded data or be geometry-only: a blank with just the acquisition and nt time samples, ready to be forward-modeled by simulate_shots.

Fields

Field Type Description
shot_id int Shot identifier
src_pos ndarray Source coordinates (ndim,) or (nsrc, ndim)
rec_pos ndarray Receiver coordinates (nrec, ndim)
dt float Time sampling in milliseconds
data ndarray, optional Receiver data (nt, nrec); omit for a geometry-only shot
nt int, optional Number of time samples for a geometry-only shot
surface ndarray, optional Optional surface/datum array
t0_rec float Recording start time in ms (default 0.0)

Exactly one of data or nt must be supplied. shot.num_samples returns the trace length from data when present, else nt.

Example

from devitohorizon.config import SeismicData

# Recorded shot
shot = SeismicData(
    shot_id=0,
    src_pos=np.array([500.0, 0.0, 10.0]),
    rec_pos=np.zeros((201, 3)),  # Fill with receiver positions
    dt=1.0,
    data=np.random.randn(1501, 201).astype(np.float32),
)

# Geometry-only blank (no data) for forward modeling
blank = SeismicData(
    shot_id=0,
    src_pos=np.array([500.0, 0.0, 10.0]),
    rec_pos=np.zeros((201, 3)),
    dt=1.0,
    nt=1501,
)

# Access fields
print(f"Shot ID: {shot.shot_id}")
print(f"Data shape: {shot.data.shape}")
print(f"Source position: {shot.src_pos}")
print(f"Number of receivers: {shot.rec_pos.shape[0]}")

DataConfig

Configuration for data loading.

Fields

from devitohorizon.config import DataConfig

config = DataConfig(
    data_path="data/shots.segy",     # Path to data
    preprocess={                      # Preprocessing pipeline
        'filters': [...],
        'mute': {...},
        'gain': {...},
    },
    creds={                           # Cloud credentials
        'connection_string': '...',
        'container': 'data',
    },
    units='m/s',                      # Input units for model velocities
)

Model units

The units field controls how velocity model parameters (vp, vs) are interpreted when they are read from disk. Internally DevitoHorizon always works in km/s, so any input given in different units is converted on load. Three forms are accepted:

# 1. Bare string — applied to every velocity parameter (vp, vs)
DataConfig(data_path=..., units='m/s')

# 2. Per-parameter dict, string value
DataConfig(data_path=..., units={'vp': 'm/s', 'vs': 'm/s'})

# 3. Per-parameter dict, nested form (kept for backwards compatibility)
DataConfig(data_path=..., units={'vp': {'in': 'ft/s'}})

Supported velocity unit strings: 'm/s' (alias 'mps'), 'km/s' (alias 'kmps'), 'ft/s' (alias 'fps'). Strings are case- and whitespace-insensitive.

When units is not specified, a value-based fallback is applied: if the maximum of a velocity array exceeds 30 it is assumed to be in m/s and divided by 1000. This check uses the maximum rather than the minimum so that models containing low-velocity zones (water layers, near-surface Vs around 100-300 m/s, air pockets) are still detected correctly. Pass an explicit units value whenever you want to bypass the heuristic — for example, when loading a model that is already in km/s but happens to contain values above 30.

The same conversion rules apply to model files loaded through load_model (SEG-Y, HDF5, Zarr); the units key sits in the top-level config dict alongside model, data_path, etc.

Preprocessing Options

preprocess = {
    # Frequency filtering
    'filters': [
        {'type': 'bandpass', 'freqs': [2, 4, 18, 20]},
        {'type': 'highpass', 'freq': 1.5},
        {'type': 'lowpass', 'freq': 25.0},
    ],

    # Muting
    'mute': {
        'type': 'top',           # 'top', 'linear', 'direct'
        'velocity': 1500.0,      # For direct arrival mute
        'offset': 0.0,           # Time offset
        'taper': 20,             # Taper samples
    },

    # Amplitude gain
    'gain': {
        'type': 'agc',           # 'agc', 't2', 'trace'
        'window': 500,           # AGC window samples
        'power': 2.0,            # For t^power gain
    },
}

DataManager (Abstract)

Base class for custom data loaders.

Interface

from devitohorizon.data import DataManager

class DataManager(ABC):
    def __init__(self, config: DataConfig):
        self.config = config
        self.data_path = config.data_path
        self.preprocess = config.preprocess

    @abstractmethod
    def discover_shots(self) -> List[int]:
        """Return list of available shot IDs."""
        pass

    @abstractmethod
    def load_shot_raw(self, shot_id: int) -> SeismicData:
        """Load single shot without preprocessing."""
        pass

    def get_geometry(self, shot_id: int) -> Tuple[np.ndarray, np.ndarray]:
        """Return (src_pos, rec_pos) without loading data."""
        shot = self.load_shot_raw(shot_id)
        return shot.src_pos, shot.rec_pos

    def load_shot(self, shot_id: int, **kwargs) -> SeismicData:
        """Load shot with preprocessing applied."""
        # Base implementation handles preprocessing
        ...

Custom Implementation

from devitohorizon.data import DataManager, SeismicData
from devitohorizon.config import DataConfig

class HDF5DataManager(DataManager):
    """Load shots from HDF5 file."""

    def discover_shots(self) -> list:
        import h5py
        with h5py.File(self.data_path, 'r') as f:
            return sorted([int(k) for k in f['shots'].keys()])

    def load_shot_raw(self, shot_id: int) -> SeismicData:
        import h5py
        with h5py.File(self.data_path, 'r') as f:
            grp = f['shots'][str(shot_id)]
            return SeismicData(
                shot_id=shot_id,
                data=np.array(grp['data'], dtype=np.float32),
                src_pos=np.array(grp['src_coords'], dtype=np.float32),
                rec_pos=np.array(grp['rec_coords'], dtype=np.float32),
                dt=float(grp.attrs['dt']),
            )

# Usage
config = DataConfig(data_path="survey.h5")
dataset = Dataset(HDF5DataManager(config))

See Custom Data I/O Guide for more examples.


SEGYDataManager

Built-in loader for SEG-Y format.

from devitohorizon.data import SEGYDataManager
from devitohorizon.config import DataConfig

config = DataConfig(data_path="shots.segy")
manager = SEGYDataManager(config)

# Discover shots
shot_ids = manager.discover_shots()

# Load single shot
shot = manager.load_shot_raw(shot_ids[0])

ZarrDataManager

Built-in loader for Zarr format (cloud-optimized).

from devitohorizon.data import ZarrDataManager
from devitohorizon.config import DataConfig

config = DataConfig(
    data_path="s3://bucket/shots.zarr",
    creds={'key': 'ACCESS_KEY', 'secret': 'SECRET_KEY'},
)
manager = ZarrDataManager(config)

dataset = Dataset(manager)

Preprocessing Pipeline

The preprocessing pipeline is applied automatically when loading shots.

Available Processors

Filters

preprocess = {
    'filters': [
        {'type': 'bandpass', 'freqs': [f1, f2, f3, f4]},  # Butterworth
        {'type': 'highpass', 'freq': f_low},
        {'type': 'lowpass', 'freq': f_high},
        {'type': 'notch', 'freq': 60.0, 'Q': 30.0},      # Remove noise
    ]
}

Muting

preprocess = {
    'mute': {
        'type': 'top',          # Mute above direct arrival
        'velocity': 1500.0,     # Water velocity (m/s)
        'offset': 50.0,         # Additional offset (ms)
        'taper': 20,            # Taper length (samples)
    }
}

# Or linear mute
preprocess = {
    'mute': {
        'type': 'linear',
        'slope': 0.001,         # ms per meter
        'intercept': 100.0,     # ms
        'taper': 15,
    }
}

Gain

preprocess = {
    'gain': {
        'type': 'agc',          # Automatic gain control
        'window': 500,          # Window length (samples)
    }
}

# Or power-of-t gain
preprocess = {
    'gain': {
        'type': 't2',           # t^power scaling
        'power': 2.0,
    }
}

Normalization

Not a preprocessing step: normalization belongs to the misfit, whose normalization ('trace' or 'shot') differentiates through it. A normalize section is refused.

Complete Example

dataset = Dataset.from_segy(
    "data/survey.segy",
    preprocess={
        'filters': [
            {'type': 'bandpass', 'freqs': [2, 4, 20, 25]},
        ],
        'mute': {
            'type': 'top',
            'velocity': 1500.0,
            'taper': 20,
        },
        'gain': {
            'type': 'agc',
            'window': 300,
        },
    }
)

See Also

Back to top