ObsPy
ObsPy is an open-source Python framework for seismological observatories, providing tools for data acquisition, processing, and analysis. It is designed to work with various seismological data formats and interact with data centers. The current stable version is 1.5.0, with new releases typically occurring a few times per year, focusing on bug fixes, performance improvements, and new features.
Common errors
-
ModuleNotFoundError: No module named 'obspy'
cause The ObsPy library is not installed in the current Python environment.fixInstall ObsPy using `pip install obspy` or `conda install -c conda-forge obspy`. -
ImportError: No module named 'matplotlib'
cause Attempting to use plotting methods (e.g., `Stream.plot()`) without `matplotlib` installed.fixInstall `matplotlib` in your environment: `pip install matplotlib` or `conda install matplotlib`. -
IOError: [Errno 2] No such file or directory: 'myfile.mseed'
cause The `obspy.read()` function cannot find the specified file, likely due to an incorrect file path, a misspelled filename, or the file not existing at the given location.fixDouble-check the file path and filename. Ensure the file exists and the path is absolute or correct relative to your script's working directory. Use `os.path.exists('myfile.mseed')` to verify. -
TypeError: unsupported operand type(s) for +: 'str' and 'UTCDateTime'
cause Attempting to concatenate a string and an `obspy.UTCDateTime` object without explicitly converting the `UTCDateTime` to a string first.fixExplicitly convert `UTCDateTime` objects to strings using `str()` or `strftime()` before concatenating them with other strings, e.g., `print('Time: ' + str(my_datetime))`. -
AttributeError: 'Stream' object has no attribute 'some_method_from_old_version'
cause Attempting to use an API method that has been removed, renamed, or moved to a different module in a newer ObsPy version.fixConsult the ObsPy documentation (docs.obspy.org) for the version you are using to find the correct method name or its new location. This often occurs when migrating code from older ObsPy versions (pre-1.0) or when specific functions were refactored into submodules.
Warnings
- gotcha ObsPy has many underlying C/Fortran dependencies for performance and specific data formats. While `pip install obspy` works, for a robust and fully-featured installation, especially on Windows or macOS, `conda install -c conda-forge obspy` is strongly recommended by the developers to handle these compiled dependencies smoothly.
- gotcha Plotting capabilities in ObsPy (e.g., `Stream.plot()`, `Trace.plot()`) rely on `matplotlib`. If `matplotlib` is not installed, these methods will raise an `ImportError`.
- breaking ObsPy dropped support for Python 2.x starting with version 1.1.0. Current versions (1.5.0+) require Python 3.8 or newer. Attempting to use ObsPy 1.1.0+ with Python 2.x will result in syntax errors or `ModuleNotFoundError`.
- breaking Many utility functions within `obspy.signal` were reorganized or moved in ObsPy 1.1.0. For example, some functions previously in `obspy.signal.util` might now be in `obspy.signal.array_util` or `obspy.signal.filter`.
- gotcha Always use `obspy.UTCDateTime` for handling time and dates within ObsPy to avoid common pitfalls with timezones, precision, and comparisons that can arise from using Python's native `datetime` objects directly with seismic data structures.
Install
-
pip install obspy -
conda install -c conda-forge obspy
Imports
- read
from obspy import read
- Stream
from obspy import Stream
from obspy.core import Stream
- Trace
from obspy import Trace
from obspy.core import Trace
- UTCDateTime
from obspy import UTCDateTime
- filter
from obspy.signal.util import filter_function
from obspy.signal.filter import filter_function
Quickstart
from obspy import read, UTCDateTime
import os
# ObsPy often requires C-compiled dependencies for full functionality and speed.
# It is highly recommended to install via Anaconda/Miniconda:
# conda install -c conda-forge obspy
# Example: Reading a MiniSEED file from a URL
try:
# This URL provides a small example MiniSEED file.
# For local files, replace with your path: st = read("path/to/your/file.mseed")
st = read("https://examples.obspy.org/BW.KW1..EHZ.D.2010.010.mseed")
print(f"\nSuccessfully loaded stream: {st}")
# Accessing the first trace in the stream
trace = st[0]
print(f"First trace metadata: {trace.stats}")
print(f"Start time: {trace.stats.starttime}, End time: {trace.stats.endtime}")
print(f"Sampling rate: {trace.stats.sampling_rate} Hz")
print(f"Number of samples: {trace.stats.npts}")
# Accessing the data array (NumPy array)
print(f"First 5 data points: {trace.data[:5]}")
# Apply a basic filter (requires scipy)
st.filter('lowpass', freq=0.5)
print(f"\nStream after lowpass filter: {st}")
# For plotting, matplotlib is required:
# try:
# st.plot()
# print("Plot generated (if matplotlib installed).")
# except ImportError:
# print("Install 'matplotlib' (pip install matplotlib) to enable plotting.")
except Exception as e:
print(f"\nFailed to read example data. Error: {e}")
print("Please ensure you have an active internet connection or try a local file.")
# Fallback to creating a dummy stream if download fails
from obspy.core import Stream, Trace
import numpy as np
print("Creating a dummy stream for demonstration...")
UTC_DT = UTCDateTime("2023-01-01T00:00:00.000Z")
stats = {'network': 'XX', 'station': 'DUM', 'location': '00',
'channel': 'BHZ', 'starttime': UTC_DT, 'delta': 0.01,
'sampling_rate': 100.0, 'npts': 1000}
dummy_trace = Trace(data=np.random.rand(stats['npts']), header=stats)
dummy_st = Stream([dummy_trace])
print(f"Dummy stream created: {dummy_st}")