MS3TraceList¶
- class pymseed.MS3TraceList(file_name=None, buffer=None, *, unpack_data=False, sourceid=None, starttime=None, endtime=None, record_list=False, skip_not_data=False, validate_crc=True, split_version=False, verbose=0)[source]¶
Bases:
objectA container for a list of traces read from miniSEED
If
file_nameis specified miniSEED will be read from the file.If
unpack_datais True, the data samples will be decoded.If
sourceid,starttime, orendtimeare specified, only records matching those criteria will be included in the trace list.sourceidis a glob pattern matched against the record source ID (e.g."FDSN:IU_COLA_*"); set toNoneto match all source IDs.starttimeandendtimeare formatted date-time strings (e.g."2024-01-01T00:00:00Z"); set either toNonefor an open-ended time window, set both toNoneto match all time.If
skip_not_datais True, bytes from the input stream will be skipped until a record is found.If
validate_crcis True, the CRC will be validated if contained in the record (legacy miniSEED v2 contains no CRCs). The CRC provides an internal integrity check of the record contents.The overall structure of the trace list is a list of trace IDs, each of which contains a list of trace segments illustrated as follows:
TraceList
TraceID
Trace Segment
Trace Segment
Trace Segment
…
TraceID
Trace Segment
Trace Segment
…
…
TraceIDs can be accessed via indexing and slicing:
traces[0]returns the first TraceIDtraces[1:3]returns a slice of the TraceIDsfor traceid in traces:iterates over all TraceIDssourceid in tracestests for a source ID, seeget_traceid()
Trace Segments can be accessed via indexing and slicing:
traceid[0]returns the first Trace Segmenttraceid[1:3]returns a slice of the Trace Segmentsfor segment in traceid:iterates over all Trace Segments
Example usage iterating over the trace list:
>>> from pymseed import MS3TraceList
>>> for traceid in MS3TraceList.from_file("examples/example_data.mseed"): ... print(f"{traceid.sourceid}, {traceid.pubversion}") ... for segment in traceid: ... print( ... f" {segment.starttime_str()} - {segment.endtime_str()}, " ... f"{segment.samprate} sps, {segment.samplecnt} samples" ... ) FDSN:IU_COLA_00_L_H_1, 4 2010-02-27T06:50:00.069539Z - 2010-02-27T07:59:59.069538Z, 1.0 sps, 4200 samples FDSN:IU_COLA_00_L_H_2, 4 2010-02-27T06:50:00.069539Z - 2010-02-27T07:59:59.069538Z, 1.0 sps, 4200 samples FDSN:IU_COLA_00_L_H_Z, 4 2010-02-27T06:50:00.069539Z - 2010-02-27T07:59:59.069538Z, 1.0 sps, 4200 samples
Example using source ID and time-window selection:
>>> traces = MS3TraceList.from_file( ... "examples/example_data.mseed", ... sourceid="FDSN:IU_COLA_00_L_H_Z", ... starttime="2010-02-27T07:00:00Z", ... endtime="2010-02-27T07:30:00Z", ... ) >>> len(traces) 1 >>> traces[0].sourceid 'FDSN:IU_COLA_00_L_H_Z' >>> traces[0][0].samplecnt 1963
The trace list, its samples, and the sources held for any record lists are released when it is garbage collected. Call
close(), or use the trace list as a context manager, to release them at a known point instead:>>> with MS3TraceList.from_file("examples/example_data.mseed") as traces: ... print(len(traces)) 3
- Parameters:
- __enter__()[source]¶
Context manager entry point - returns self for use in ‘with’ statements.
- Return type:
- __exit__(exc_type, exc_value, traceback)[source]¶
Context manager exit point - ensures proper cleanup by calling close().
- close()[source]¶
Free the trace list and release the sources held for it.
Waiting for garbage collection is otherwise the only way to release the samples, the file name buffers, and the source buffers that record lists point into.
Idempotent: safe to call multiple times.
Warning
Every
MS3TraceID,MS3TraceSeg, record list, and data sample view obtained from this trace list is invalidated. Reading one after this call reads freed memory. The trace list itself reports the closure, raisingValueErrorfor any further operation on it.- Return type:
None
- __contains__(item)[source]¶
Test for a source ID, as a str or MS3TraceID, in the list
A str matches any publication version, an MS3TraceID matches only its own. Any other type is not in the list.
- get_traceid(sourceid, version=0)[source]¶
Get a specific trace ID from the list, or None if not present
- Raises:
TypeError – If sourceid is not a str
- Parameters:
- Return type:
MS3TraceID | None
- print(details=0, gaps=False, versions=False, timeformat=TimeFormat.ISOMONTHDAY_Z)[source]¶
Print a summary of the trace list, one line per segment
Each line has the source ID, start time, and end time. The summary is written to standard output by the C library, so it is not captured by redirecting
sys.stdoutand does not interleave with the output of Python’sprint().- Parameters:
details (int) – If greater than 0, add the sample rate and sample count to each line, and a total trace and segment count. Default: 0
gaps (bool) – If True, add the gap or overlap between each segment and the previous segment of the same source ID and sample rate. Default: False
versions (bool) – If True, append the publication version to each source ID as
"#<version>". Default: Falsetimeformat (TimeFormat) – Format of the start and end times, a
TimeFormatvalue. Default: TimeFormat.ISOMONTHDAY_Z
- Raises:
ValueError – If the trace list has been closed.
- Return type:
None
- add_file(file_name, *, unpack_data=False, sourceid=None, starttime=None, endtime=None, record_list=False, skip_not_data=False, validate_crc=True, split_version=False, verbose=0)[source]¶
Read miniSEED data from file and add to existing trace list
This method reads miniSEED records from a file and adds the data they contain to the current trace list. Data are organized by source ID and time, with overlapping or adjacent data automatically merged into continuous segments.
- Parameters:
file_name (str | PathLike[str]) – Path to the miniSEED file to read. Accepts
stror anyos.PathLike(e.g.pathlib.Path). Other types raiseTypeError.unpack_data (bool) – If True, decode data samples immediately. If False, data samples remain packed and must be unpacked later with
unpack_recordlist(). Default: Falsesourceid (str | None) – Source ID glob pattern to select matching records (e.g.
"FDSN:IU_COLA_*"). None matches all source IDs. Default: Nonestarttime (str | None) – Start of time window as a formatted date-time string (e.g.
"2024-01-01T00:00:00Z"). Only records containing data after this time are included. None means open start. Default: Noneendtime (str | None) – End of time window as a formatted date-time string. Only records containing data before this time are included. None means open end. Default: None
record_list (bool) – If True, maintain a list of original records for each trace segment. Required for unpack_recordlist() and allows access to individual record metadata. Default: False NOTE: the files must remain accessible to unpack data with a record list
skip_not_data (bool) – If True, skip non-data records in the file instead of raising an error. Useful for files with mixed content. Default: False
validate_crc (bool) – If True, validate CRC checksums if present in records (miniSEED v3 only). Provides integrity verification. Default: True
split_version (bool) – If True, treat different publication versions as separate trace IDs. Default: False (merge by source ID only)
verbose (int) – Verbosity level for diagnostic output (0=quiet, 1-3=increasing detail). Default: 0
- Raises:
ValueError – If starttime or endtime is not a valid date-time string
MiniSEEDError – If file cannot be read or contains invalid data
- Return type:
None
Note
This method adds data to the existing trace list. It does not replace existing data. To start fresh, create a new MS3TraceList instance.
Examples
Basic usage examples:
>>> from pymseed import MS3TraceList >>> traces = MS3TraceList() >>> traces.add_file("examples/example_data.mseed") >>> len(traces) 3
Unpacking data while reading for immediate access
>>> traces = MS3TraceList() >>> traces.add_file("examples/example_data.mseed", unpack_data=True) >>> traces[0].sourceid 'FDSN:IU_COLA_00_L_H_1' >>> segment1 = traces[0][0] >>> segment1.starttime_str() '2010-02-27T06:50:00.069539Z' >>> segment1.endtime_str() '2010-02-27T07:59:59.069538Z' >>> segment1.samprate 1.0 >>> segment1.samplecnt 4200 >>> segment1.numsamples 4200 >>> segment1.sampletype 'i'
Read with record list for later unpacking:
>>> traces = MS3TraceList() >>> traces.add_file("examples/example_data.mseed", record_list=True) >>> total_samples = 0 >>> for traceid in traces: ... for segment in traceid: ... # Unpack when desired, can unpacked to designated buffer ... samples_count = segment.unpack_recordlist() ... total_samples += samples_count >>> total_samples 12600
Add multiple files to same trace list, in this trivial example the same file is read twice, so the data are duplicated in the trace list:
>>> traces = MS3TraceList() >>> traces.add_file("examples/example_data.mseed") >>> traces.add_file("examples/example_data.mseed") # Appends to existing data >>> len(traces) 3 >>> traceid = traces[0] >>> traceid[0].samplecnt 4200 >>> len(traceid) # Two segments (duplicate in this case) 2 >>> # Compare using explicit data comparison (fast) >>> traceid[0].has_same_data(traceid[1]) True
- add_buffer(buffer, *, unpack_data=False, sourceid=None, starttime=None, endtime=None, record_list=False, skip_not_data=False, validate_crc=True, split_version=False, verbose=0)[source]¶
Read miniSEED data from a buffer and add to existing trace list
This method reads miniSEED records from a bytes-like object and adds the data they contain to the current trace list. Data are organized by source ID and time, with overlapping or adjacent data automatically merged into continuous segments.
- Parameters:
buffer (Any) – Bytes-like object containing miniSEED data
unpack_data (bool) – If True, decode data samples immediately. If False, data samples remain packed and must be unpacked later with
unpack_recordlist(). Default: Falsesourceid (str | None) – Source ID glob pattern to select matching records (e.g.
"FDSN:IU_COLA_*"). None matches all source IDs. Default: Nonestarttime (str | None) – Start of time window as a formatted date-time string (e.g.
"2024-01-01T00:00:00Z"). Only records containing data after this time are included. None means open start. Default: Noneendtime (str | None) – End of time window as a formatted date-time string. Only records containing data before this time are included. None means open end. Default: None
record_list (bool) – If True, maintain a list of original records for each trace segment. Required for unpack_recordlist() and allows access to individual record metadata. Default: False NOTE: the record list entries point into the buffer, which the trace list holds a reference to until it is discarded
skip_not_data (bool) – If True, skip non-data records in the buffer instead of raising an error. Useful for files with mixed content. Default: False
validate_crc (bool) – If True, validate CRC checksums if present in records (miniSEED v3 only). Provides integrity verification. Default: True
split_version (bool) – If True, treat different publication versions as separate trace IDs. Default: False (merge by source ID only)
verbose (int) – Verbosity level for diagnostic output (0=quiet, 1-3=increasing detail). Default: 0
- Raises:
ValueError – If buffer does not support the buffer protocol, or if starttime or endtime is not a valid date-time string
BufferError – If buffer is not C-contiguous
MiniSEEDError – If buffer cannot be read or contains invalid data
- Return type:
None
Note
This method adds data to the existing trace list. It does not replace existing data. To start fresh, create a new MS3TraceList instance. To add data from a file, use add_file().
Examples
Read miniSEED data from a file into a buffer:
>>> with open("examples/example_data.mseed", "rb") as f: ... buffer = f.read()
Basic usage examples:
>>> from pymseed import MS3TraceList >>> traces = MS3TraceList() >>> traces.add_buffer(buffer) >>> len(traces) 3
Unpacking data while reading for immediate access
>>> traces = MS3TraceList() >>> traces.add_buffer(buffer, unpack_data=True) >>> traces[0].sourceid 'FDSN:IU_COLA_00_L_H_1' >>> segment1 = traces[0][0] >>> segment1.starttime_str() '2010-02-27T06:50:00.069539Z' >>> segment1.endtime_str() '2010-02-27T07:59:59.069538Z' >>> segment1.samprate 1.0 >>> segment1.samplecnt 4200 >>> segment1.numsamples 4200 >>> segment1.sampletype 'i'
Read with record list for later unpacking:
>>> traces = MS3TraceList() >>> traces.add_buffer(buffer, record_list=True) >>> total_samples = 0 >>> for traceid in traces: ... for segment in traceid: ... # Unpack when desired, can unpacked to designated buffer ... samples_count = segment.unpack_recordlist() ... total_samples += samples_count >>> total_samples 12600
Add multiple buffers to same trace list, in this trivial example the same file is read twice, so the data are duplicated in the trace list:
>>> traces = MS3TraceList() >>> traces.add_buffer(buffer) >>> traces.add_buffer(buffer) # Appends to existing data >>> len(traces) 3 >>> traceid = traces[0] >>> traceid[0].samplecnt 4200 >>> len(traceid) # Two segments (duplicate in this case) 2
- add_filelike(fh, *, chunk_size=65536, unpack_data=False, sourceid=None, starttime=None, endtime=None, record_list=False, validate_crc=True, split_version=False, verbose=0)[source]¶
Read miniSEED data from a file-like stream and add to the trace list.
This method reads miniSEED records from any object exposing
.read(n) -> bytes(e.g.io.BytesIO,sys.stdin.buffer, an HTTP response body, a network socket file) using a chunked sliding buffer. The stream is not required to be seekable and the full contents do not need to fit in memory. The caller retains ownership offhand is responsible for closing it.- Performance note:
This method is intended for streaming sources that cannot be represented as a file path or in-memory buffer. For files on disk, prefer
add_file()(orfrom_file()). For data already resident in memory, preferadd_buffer()(orfrom_buffer()). Those routines run a tight loop inside libmseed and apply selections at parse time; this method round-trips each record through Python, which is typically much slower. Use it as a last resort when the other methods cannot be used.- Record list limitation:
record_list=Trueis supported and produces the same per-record metadata asadd_file()/add_buffer()(source ID, start/end times, record length, encoding, etc.), butunpack_recordlist()cannot be used on the resulting record list as the original source bytes do not persist. The per-record references to those bytes are cleared, soMS3Record.recordandMS3Record.record_mvalso raise for entries in this list. If you need either, read the data withadd_file()oradd_buffer()instead.
- Parameters:
fh (Any) – A file-like object with a
.read(n)method returning bytes.chunk_size (int) – Number of bytes to read per
.read()call, greater than 0 and less than 1 GiB. Default: 65536.unpack_data (bool) – If True, decode data samples immediately. Default: False.
sourceid (str | None) – Source ID glob pattern to select matching records (e.g.
"FDSN:IU_COLA_*"). None matches all source IDs. Default: None.starttime (str | None) – Start of time window as a formatted date-time string (e.g.
"2024-01-01T00:00:00Z"). Only records overlapping this window are included. None means open start. Default: None.endtime (str | None) – End of time window as a formatted date-time string. None means open end. Default: None.
record_list (bool) – If True, maintain a per-segment list of original records (source ID, times, reclen, encoding, etc.). See the “Record list limitation” note above:
unpack_recordlist()cannot be used on the resulting list because the source bytes do not persist. Default: False.validate_crc (bool) – If True, validate CRC checksums when present (miniSEED v3 only). Default: True.
split_version (bool) – If True, treat different publication versions as separate trace IDs. Default: False.
verbose (int) – Verbosity level for libmseed diagnostics. Default: 0.
- Raises:
TypeError – If
fhhas no callable.readmethod.ValueError – If
chunk_sizeis not greater than 0 and less than 1 GiB, or ifstarttimeorendtimeis not a valid date-time string.MiniSEEDError – If a record cannot be parsed or cannot be added to the trace list.
- Return type:
None
Examples
Read miniSEED from a BytesIO stream:
>>> import io >>> from pymseed import MS3TraceList >>> with open("examples/example_data.mseed", "rb") as f: ... stream = io.BytesIO(f.read()) >>> traces = MS3TraceList() >>> traces.add_filelike(stream) >>> len(traces) 3
With source ID and time-window filtering:
>>> with open("examples/example_data.mseed", "rb") as f: ... stream = io.BytesIO(f.read()) >>> traces = MS3TraceList() >>> traces.add_filelike( ... stream, ... sourceid="FDSN:IU_COLA_00_L_H_Z", ... starttime="2010-02-27T07:00:00Z", ... endtime="2010-02-27T07:30:00Z", ... ) >>> len(traces) 1 >>> traces[0].sourceid 'FDSN:IU_COLA_00_L_H_Z'
- add_data(sourceid, data_samples, sample_type, sample_rate, *, starttime_str=None, starttime=None, starttime_seconds=None, publication_version=0)[source]¶
Add data samples to the trace list
A segment of regularly sampled data values for the given source ID of the specific type and sample rate are added to the trace list.
- Parameters:
sourceid (str) – Source identifier for the trace (e.g., “FDSN:XX_STA__B_H_Z”). Should follow FDSN Source Identifier format.
data_samples (Any) – Sequence of data samples. Can be a Python list, numpy array, or any buffer-like object. Data type must match sample_type.
sample_type (str) – Data sample type code: - “i”: 32-bit signed integers (int32) - “f”: 32-bit floating point (float32) - “d”: 64-bit floating point (float64) - “t”: Text/character data (single bytes)
sample_rate (float) – Sample rate in samples per second (Hz) or period (seconds). Use positive values for samples/second, and negative values for sample period in seconds.
starttime_str (str | None) – Start time as formatted string (e.g., “2023-01-01T12:00:00.000Z”). Mutually exclusive with starttime and starttime_seconds.
starttime (int | None) – Start time as nanoseconds since Unix epoch. Mutually exclusive with starttime_str and starttime_seconds.
starttime_seconds (float | None) – Start time as seconds since Unix epoch (float). Mutually exclusive with starttime_str and starttime.
publication_version (int) – Publication version number for the trace. Default: 0
- Raises:
ValueError – If sample_type is invalid, time parameters are conflicting, or data_samples format is incompatible with sample_type
MiniSEEDError – If the data cannot be added to the trace list
- Return type:
None
Note
Data is automatically merged with existing segments based on source ID, time continuity, and sample rate similarity. Adjacent or overlapping segments are combined when possible.
- Performance:
The method attempts zero-copy optimization when data_samples is a compatible buffer (correct type and format). Otherwise, data is converted with a copy. Use arrays (or any buffer with memoryviews) with matching types for best performance.
Examples
Basic usage with integer data:
>>> from pymseed import MS3TraceList >>> traces = MS3TraceList() >>> data_series = [100, 105, 98, 102, 99, 103, 97] >>> traces.add_data( ... sourceid="FDSN:XX_STA__B_H_Z", ... data_samples=data_series, ... sample_type="i", ... sample_rate=20.0, ... starttime_str="2023-01-01T00:00:00.000Z" ... ) >>> len(traces) 1 >>> traces[0].sourceid 'FDSN:XX_STA__B_H_Z'
Multiple segments that get merged:
>>> traces = MS3TraceList() >>> traces.add_data("FDSN:XX_STA__B_H_1", [1, 2, 3], "i", 10.0, ... starttime_str="2023-01-01T00:00:00.000Z") >>> traces.add_data("FDSN:XX_STA__B_H_1", [4, 5, 6], "i", 10.0, ... starttime_str="2023-01-01T00:00:00.300Z") >>> len(traces) # One traceID 1 >>> len(traces[0]) # One trace segment 1
- generate(*, max_record_length=4096, encoding=DataEncoding.STEIM1, format_version=None, extra_headers=None, flush_data=True, flush_idle_seconds=0, remove_packed=False, verbose=0)[source]¶
Create miniSEED record(s) for data in the trace list.
This method creates, or packs, miniSEED record(s) for the time series data from all traces in the trace list using the provided parameters (encoding, record length, etc.).
- Parameters:
max_record_length (int) – Maximum length of each miniSEED record in bytes. For miniSEED format version 3, this is the maximum record length. For miniSEED format version 2, this must be a power of 2 between 128 and 65536. Common values are 512 and 4096. Default is 4096.
encoding (DataEncoding) –
Data encoding format for compression. Options include:
DataEncoding.STEIM1: Steim-1 compression (default, good general purpose for 32-bit ints)
DataEncoding.STEIM2: Steim-2 compression
DataEncoding.INT16: 16-bit integers (no compression)
DataEncoding.INT32: 32-bit integers (no compression)
DataEncoding.FLOAT32: 32-bit IEEE floats
DataEncoding.FLOAT64: 64-bit IEEE doubles
DataEncoding.TEXT: Text encoding (UTF-8)
format_version (int | None) – miniSEED format version (2 or 3). If None, uses library default. Version 2 is legacy format, version 3 is the latest standard.
extra_headers (str | None) – Optional extra header fields to include. Must be valid JSON string.
flush_data (bool) – If True, forces creation of records for all data, even if it doesn’t fill a complete record. If False, data samples at the end of traces may be held in internal buffers. Default is True.
flush_idle_seconds (int) – If > 0, forces flushing of data segments that have not been updated within the specified number of seconds. Default is 0 (disabled), which holds idle data in the trace list until a call with flush_data=True.
remove_packed (bool) – If True, data samples packed into records will be removed from the trace list. See “Rolling buffer” section below for more details. Default is False.
verbose (int) – Verbosity level for libmseed output (0=quiet, 1=info, 2=detailed). Default is 0 (quiet).
- Yields:
bytes – Each miniSEED record as it is created
- Raises:
ValueError – If format_version is not 2 or 3, or encoding is outside the range 0..255. Raised by this call, before the first record is created.
MiniSEEDError – If the underlying libmseed library encounters an error during creation of miniSEED records, such as a max_record_length the format or encoding cannot use. Raised while iterating, by the record it applies to.
- Return type:
Examples
Simple example creating miniSEED records:
>>> # Create a trace list with some data >>> traces = MS3TraceList() >>> traces.add_data("FDSN:XX_STA__H_H_Z", [1, 2, 3, 4, 5], "i", 100.0, starttime_str="2023-01-01T00:00:00.000Z") >>> traces.add_data("FDSN:XX_STA__H_H_1", [6, 7, 8, 9, 9], "i", 100.0, starttime_str="2023-01-01T00:00:00.000Z") >>> traces.add_data("FDSN:XX_STA__H_H_2", [9, 9, 8, 7, 6], "i", 100.0, starttime_str="2023-01-01T00:00:00.000Z")
>>> record_count = 0 >>> for record in traces.generate(): ... record_count += 1 >>> print(f"Created {record_count} records") Created 3 records
- Rolling buffer:
A common pattern is to use a MS3TraceList as a rolling buffer to generate miniSEED records from an arbitrary number of continuous data streams. In particular this pattern allows creating filled miniSEED records as much as possible during regular data flow, and then flushing any remaining data at the end. This is particularly useful for converting real-time data streams into miniSEED or for converting large data sets into miniSEED without loading all the source data into memory.
A few options are needed to properly configure the rolling buffer. For creating filled records during regular data flow: * flush_data=False to keep data in the trace list * flush_idle_seconds=N to flush data segments that have not been updated within N seconds * remove_packed=True to remove packed data from the trace list
To flush the all data from the buffer on termination: * flush_data=True to flush all data from the trace list * remove_packed=True to remove packed data from the trace list
With flush_data=False, a source that stops delivering data keeps its remaining samples in the trace list until flush_idle_seconds elapses, or until a later call sets flush_data=True. Set flush_idle_seconds=N whenever the set of source IDs can change over the life of the buffer: at the default of 0 those samples, and the trace ID holding them, are retained for as long as the trace list lives.
Choose N larger than the time it takes the slowest source to fill a record, otherwise idle flushing creates partial records where full ones are still possible: 1 sample/second fills a 4096-byte STEIM2 record in about 110 minutes, a 512-byte one in about 12 minutes. Choose a smaller N when bounding output latency matters more than filling records.
update_timereports the time a segment was last updated, which is the value N is compared against.
Warning
With remove_packed=True, samples are removed from the trace list only when the segment they belong to finishes packing. Abandoning this generator early — a
break, areturn, or an exception raised while handling a record — leaves the samples of the records already yielded in the trace list, and a later generate() creates records for them again. Iterate to completion to keep the buffer and the output consistent, handling per-record failures inside the loop.See also
to_file()
- to_file(filename, *, overwrite=False, max_record_length=4096, encoding=DataEncoding.STEIM1, format_version=None, verbose=0)[source]¶
Write trace list data to a miniSEED file.
This method packages the time series data from all traces in the trace list into miniSEED format and writes them directly to a file. This is a convenience method that combines packing and file writing in a single operation.
- Parameters:
filename (str | PathLike[str]) – Path to the output miniSEED file. Accepts
stror anyos.PathLike(e.g.pathlib.Path); other types raiseTypeError. The file will be created if it doesn’t exist. Directory must already exist.overwrite (bool) – If True, overwrites any existing file. If False and file exists, append data to the end of the file. Default is False for safety.
max_record_length (int) – Maximum length of each miniSEED record in bytes. For miniSEED format version 3, this is the maximum record length. For miniSEED format version 2, this must be a power of 2 between 128 and 65536. Common values are 512 and 4096. Default is 4096.
encoding (DataEncoding) –
Data encoding format for compression. Options include:
DataEncoding.STEIM1: Steim-1 compression (default, good general purpose for 32-bit ints)
DataEncoding.STEIM2: Steim-2 compression
DataEncoding.INT16: 16-bit integers (no compression)
DataEncoding.INT32: 32-bit integers (no compression)
DataEncoding.FLOAT32: 32-bit IEEE floats
DataEncoding.FLOAT64: 64-bit IEEE doubles
DataEncoding.TEXT: Text encoding (UTF-8)
format_version (int | None) – miniSEED format version (2 or 3). If None, uses library default. Version 2 is legacy format, version 3 is the latest standard.
verbose (int) – Verbosity level for libmseed output (0=quiet, 1=info, 2=detailed). Default is 0 (quiet).
- Returns:
Number of miniSEED records written to the file.
- Return type:
- Raises:
TypeError – If filename is not a str or os.PathLike.
ValueError – If format_version is not 2 or 3, or encoding is outside the range 0..255.
MiniSEEDError – If the underlying libmseed library encounters an error during file writing (e.g., permission denied, disk full, invalid data, or a max_record_length the format or encoding cannot use).
Examples
Simple file writing:
>>> # Create a trace list with some data >>> traces = MS3TraceList() >>> traces.add_data("FDSN:XX_STA__B_H_Z", [1, 2, 3, 4, 5], "i", 100.0, starttime_str="2023-01-01T00:00:00Z")
>>> # Write to file (basic usage) >>> records_written = traces.to_file("output.mseed") >>> print(f"Wrote {records_written} records to output.mseed") Wrote 1 records to output.mseed
Writing with specific options:
>>> # Write as miniSEED v2 with Steim-2 compression >>> records_written = traces.to_file( ... "output.mseed", ... overwrite=True, ... format_version=2, ... encoding=DataEncoding.STEIM2, ... max_record_length=512 ... ) >>> print(f"Wrote {records_written} records to output.mseed") Wrote 1 records to output.mseed
Note
This method is more convenient and efficient than using generate() and writing to a file with a file handler.
See also
generate(): Lower-level method to create miniSEED records
add_data(): Add time series data to the trace list
from_file(): Read miniSEED data from file
- classmethod from_file(filename, **kwargs)[source]¶
Create MS3TraceList from a specified miniSEED file
- Parameters:
- Return type:
- classmethod from_buffer(buffer, **kwargs)[source]¶
Create an MS3TraceList from miniSEED data in a memory buffer
- Parameters:
- Return type:
- classmethod from_filelike(fh, **kwargs)[source]¶
Create an MS3TraceList from a miniSEED file-like stream.
See
add_filelike()for the full parameter list, supported filters, the record-list limitation (unpack_recordlist()is not available on the resulting record list), and performance guidance (preferfrom_file()/from_buffer()when applicable).- Parameters:
- Return type: