mth5.mth5
MTH5 deals with reading and writing an MTH5 file, which are HDF5 files developed for magnetotelluric (MT) data. The code is based on h5py and numpy. The main purpose is to provide an object-oriented interface for managing MT data in the HDF5 format.
This module implements the MTH5 class which provides a container for the hierarchical structure of MT data collection:
Version 0.1.0: Survey → Stations → Runs → Channels
Version 0.2.0: Experiment → Surveys → Stations → Runs → Channels
All timeseries data are stored as individual channels with appropriate metadata for electric, magnetic, and auxiliary data.
Created on Sun Dec 9 20:50:41 2018
- copyright:
Jared Peacock (jpeacock@usgs.gov)
- license:
MIT
Notes
For detailed information about the MTH5 format and metadata standards, see https://github.com/kujaku11/MTarchive/
Examples
Create a new MTH5 file and add a station:
>>> from mth5 import mth5
>>> mth5_obj = mth5.MTH5(file_version='0.2.0')
>>> mth5_obj.open_mth5('test.mth5', 'w')
>>> survey = mth5_obj.add_survey('survey_001')
>>> station = mth5_obj.add_station('MT001', survey='survey_001')
See also
h5pyHDF5 library used for file I/O
mt_metadataMetadata standards for MT data
Classes
MTH5 is the main container for the HDF5 file format developed for MT data |
Module Contents
- class mth5.mth5.MTH5(filename=None, compression='gzip', compression_opts=4, shuffle=True, fletcher32=True, data_level=1, file_version='0.2.0')[source]
MTH5 is the main container for the HDF5 file format developed for MT data
It uses the metadata standards developled by the IRIS PASSCAL software group and defined in the metadata documentation.
MTH5 is built with h5py and therefore numpy. The structure follows the different levels of MT data collection:
For version 0.1.0:
Survey
Reports
Standards
Filters
Stations
Run
Channel
For version 0.2.0:
Experiment
Reports
Standards
Surveys
Reports
Standards
Filters
Stations
Run
-Channel
All timeseries data are stored as individual channels with the appropriate metadata defined for the given channel, i.e. electric, magnetic, auxiliary.
Each level is represented as a mth5 group class object which has methods to add, remove, and get a group from the level below. Each group has a metadata attribute that is the approprate metadata class object. For instance the SurveyGroup has an attribute metadata that is a
mth5.metadata.Surveyobject. Metadata is stored in the HDF5 group attributes as (key, value) pairs.All groups are represented by their structure tree and can be shown at any time from the command line.
Each level has a summary array of the contents of the levels below to hopefully make searching easier.
- Parameters:
filename (string or
pathlib.Path) – name of the to be or existing filecompression –
compression type. Supported lossless compressions are
- ’lzf’ - Available with every installation of h5py
(C source code also available). Low to moderate compression, very fast. No options.
- ’gzip’ - Available with every installation of HDF5,
so it’s best where portability is required. Good compression, moderate speed. compression_opts sets the compression level and may be an integer from 0 to 9, default is 3.
- ’szip’ - Patent-encumbered filter used in the NASA
community. Not available with all installations of HDF5 due to legal reasons. Consult the HDF5 docs for filter options.
compression_opts (string or int depending on compression type) – compression options, see above
shuffle (boolean) – Block-oriented compressors like GZIP or LZF work better when presented with runs of similar values. Enabling the shuffle filter rearranges the bytes in the chunk and may improve compression ratio. No significant speed penalty, lossless.
fletcher32 (boolean) – Adds a checksum to each chunk to detect data corruption. Attempts to read corrupted chunks will fail with an error. No significant speed penalty. Obviously shouldn’t be used with lossy compression filters.
data_level (integer, defaults to 1) –
level the data are stored following levels defined by NASA ESDS
0 - Raw data
1 - Raw data with response information and full metadata
2 - Derived product, raw data has been manipulated
file_version (string, optional) – Version of the file [ ‘0.1.0’ | ‘0.2.0’ ], defaults to “0.2.0”
- Usage:
Open a new file and show initialized file
>>> from mth5 import mth5 >>> mth5_obj = mth5.MTH5(file_version='0.1.0') >>> # Have a look at the dataset options >>> mth5.dataset_options {'compression': 'gzip', 'compression_opts': 3, 'shuffle': True, 'fletcher32': True} >>> mth5_obj.open_mth5(r"/home/mtdata/mt01.mth5", 'w') >>> mth5_obj /: ==================== |- Group: Survey ---------------- |- Group: Filters ----------------- --> Dataset: summary ...................... |- Group: Reports ----------------- --> Dataset: summary ...................... |- Group: Standards ------------------- --> Dataset: summary ...................... |- Group: Stations ------------------ --> Dataset: summary ......................
Add metadata for survey from a dictionary
>>> survey_dict = {'survey':{'acquired_by': 'me', 'archive_id': 'MTCND'}} >>> survey = mth5_obj.survey_group >>> survey.metadata.from_dict(survey_dict) >>> survey.metadata { "survey": { "acquired_by.author": "me", "acquired_by.comments": null, "archive_id": "MTCND" ...} }
Add a station from the convenience function
>>> station = mth5_obj.add_station('MT001') >>> mth5_obj /: ==================== |- Group: Survey ---------------- |- Group: Filters ----------------- --> Dataset: summary ...................... |- Group: Reports ----------------- --> Dataset: summary ...................... |- Group: Standards ------------------- --> Dataset: summary ...................... |- Group: Stations ------------------ |- Group: MT001 --------------- --> Dataset: summary ...................... --> Dataset: summary ...................... >>> station /Survey/Stations/MT001: ==================== --> Dataset: summary ......................
>>> data.schedule_01.ex[0:10] = np.nan >>> data.calibration_hx[...] = np.logspace(-4, 4, 20)
Note
if replacing an entire array with a new one you need to use […] otherwise the data will not be updated.
Warning
You can only replace entire arrays with arrays of the same size. Otherwise you need to delete the existing data and make a new dataset.
See also
- property dataset_options: dict[str, str | int | bool][source]
Get HDF5 dataset compression and storage options.
- Returns:
Dictionary containing compression, compression_opts, shuffle, and fletcher32.
- Return type:
dict[str, str | int | bool]
Examples
>>> mth5_obj = MTH5() >>> opts = mth5_obj.dataset_options >>> print(opts['compression']) 'gzip'
- open_mth5(filename: str | pathlib.Path | None = None, mode: str = 'a', single_writer_multiple_reader: bool = False, **kwargs) MTH5[source]
Open an MTH5 file.
Opens an existing MTH5 file or creates a new one. Validates file structure and initializes summary datasets if needed.
- Parameters:
filename (str | Path, optional) – Path to MTH5 file. If None, uses stored filename.
mode (str, default 'a') –
File opening mode:
’r’ : Read-only
’a’ : Read/write, create if doesn’t exist
’w’ : Write, overwrite if exists
’x’ : Write, fail if exists
’w-’ : Write, fail if exists (same as ‘x’)
’r+’ : Read/write, file must exist
single_writer_multiple_reader (bool, default False) –
Enable SWMR (Single Writer Multiple Reader) mode.
Important SWMR Notes:
Writer: Use mode=’a’ or ‘r+’ on existing file. SWMR activated after opening.
Reader: Use mode=’r’ with swmr=True. Multiple readers can access simultaneously.
File must exist: Cannot create new files in SWMR mode.
Requires libver=’latest’: Automatically set when swmr=True.
Writer restrictions: Once activated, writer cannot delete/restructure, only append.
Flushing: Writer should regularly flush for readers to see updates.
Example (Writer):
mth5_writer = MTH5() mth5_writer.open_mth5('data.mth5', mode='a', single_writer_multiple_reader=True) # Add/modify data mth5_writer.close_mth5()
Example (Reader):
mth5_reader = MTH5() mth5_reader.open_mth5('data.mth5', mode='r', single_writer_multiple_reader=True) # Read data while writer is active mth5_reader.close_mth5()
**kwargs – Additional arguments passed to h5py.File(). Note that libver=’latest’ is set by default for forward compatibility and SWMR support. You can override this by explicitly passing a different libver value.
- Returns:
Returns self for method chaining.
- Return type:
- Raises:
MTH5Error – If file is invalid or mode is not understood, or if SWMR mode cannot be activated.
Examples
Open an existing file for reading:
>>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('data.mth5', 'r')
Create a new file:
>>> mth5_obj = MTH5(file_version='0.2.0') >>> mth5_obj.open_mth5('new_file.mth5', 'w')
Open as SWMR writer:
>>> mth5_writer = MTH5() >>> mth5_writer.open_mth5('existing.mth5', mode='a', single_writer_multiple_reader=True)
Open as SWMR reader:
>>> mth5_reader = MTH5() >>> mth5_reader.open_mth5('existing.mth5', mode='r', single_writer_multiple_reader=True)
See also
close_mth5Close the MTH5 file
Notes
Default File Format: As of MTH5 (with SWMR support), all files are created with libver=’latest’ by default, using HDF5 file format version 3. This ensures:
Compatibility with SWMR (Single Writer Multiple Reader) mode
Support for modern HDF5 features
Forward compatibility with future enhancements
Files created with libver=’latest’ are readable by h5py 2.10+ (2019) and HDF5 1.10.0+ (2016). To use an older format, explicitly pass libver=’earliest’.
SWMR Mode: SWMR mode allows one writer and multiple readers to access the same HDF5 file concurrently. This is useful for real-time data collection scenarios where data is being written while others need to read/process it.
The writer can append data and create new objects, but cannot delete or restructure existing objects. Readers see a consistent view of the file and can access new data as it’s flushed by the writer.
- validate_file() bool[source]
Validate an open MTH5 file.
Checks file attributes, version, data level, and group structure for compliance with MTH5 format specifications.
- Returns:
True if file is valid, False otherwise.
- Return type:
bool
Examples
>>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('test.mth5', 'r') >>> is_valid = mth5_obj.validate_file()
- close_mth5() None[source]
Close MTH5 file.
Flushes all data to disk, updates summary tables, and closes the file. Safe to call on already-closed files.
For SWMR writer mode, this ensures all pending data is flushed before closing so readers can access the complete dataset.
Examples
>>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('test.mth5', 'w') >>> mth5_obj.close_mth5()
Notes
Can be called automatically using context manager:
>>> with MTH5().open_mth5('test.mth5', 'w') as m: ... # do work ... pass # file closed automatically
- flush() None[source]
Flush data to disk without closing the file.
This is particularly important in SWMR writer mode to make new data visible to readers. The writer should call this regularly after adding or modifying data.
Examples
>>> # SWMR writer adding data incrementally >>> mth5_writer = MTH5() >>> mth5_writer.open_mth5('data.mth5', 'a', single_writer_multiple_reader=True) >>> >>> # Add some data >>> station = mth5_writer.add_station('STA001', survey='survey_01') >>> mth5_writer.flush() # Make it visible to readers >>> >>> # Add more data >>> run = station.add_run('run_001') >>> mth5_writer.flush() # Readers can now see the run
Notes
In SWMR mode, readers will not see new data until the writer flushes. It’s good practice to flush after each significant data addition.
- h5_is_write() bool[source]
Check if HDF5 file is open in write mode.
- Returns:
True if file is open and writable, False otherwise.
- Return type:
bool
Examples
>>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('test.mth5', 'w') >>> mth5_obj.h5_is_write() True
- h5_is_read() bool[source]
Check if HDF5 file is open and readable.
- Returns:
True if file is open and readable, False otherwise.
- Return type:
bool
Examples
>>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('test.mth5', 'r') >>> mth5_obj.h5_is_read() True
- is_swmr_mode() bool[source]
Check if file is currently in SWMR mode.
- Returns:
True if file is open in SWMR mode, False otherwise.
- Return type:
bool
Examples
>>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('test.mth5', 'a', single_writer_multiple_reader=True) >>> mth5_obj.is_swmr_mode() True
- get_reference_path(h5_reference)[source]
Get the HDF5 path from a reference
- Parameters:
h5_reference (TYPE) – DESCRIPTION
- Returns:
DESCRIPTION
- Return type:
TYPE
- from_reference(h5_reference)[source]
Get an HDF5 group, dataset, etc from a reference
- Parameters:
h5_reference (TYPE) – DESCRIPTION
- Returns:
DESCRIPTION
- Return type:
TYPE
- to_experiment(has_data=True)[source]
Create an
mt_metadata.timeseries.Experimentobject from the metadata contained in the MTH5 file.- Returns:
mt_metadata.timeseries.Experiment
- from_experiment(experiment, survey_index=0, update=False)[source]
Fill out an MTH5 from a
mt_metadata.timeseries.Experimentobject given a survey_id- Parameters:
experiment (
mt_metadata.timeseries.Experiment) – Experiment metadatasurvey_index (int, defaults to 0) – Index of the survey to write
- property channel_summary: mth5.tables.ChannelSummaryTable[source]
Get channel summary table.
- Returns:
Summary of all channels in the file with metadata.
- Return type:
Examples
>>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('test.mth5', 'r') >>> summary = mth5_obj.channel_summary
- property fc_summary: mth5.tables.FCSummaryTable[source]
Get Fourier coefficient summary table.
- Returns:
Summary of all Fourier coefficients in the file.
- Return type:
- property run_summary[source]
Get run summary with MTH5 file path.
- Returns:
Summary of runs with mth5_path column added.
- Return type:
pandas.DataFrame
- property tf_summary: mth5.tables.TFSummaryTable[source]
Get transfer function summary table.
- Returns:
Summary of all transfer functions in the file.
- Return type:
- add_survey(survey_name, survey_metadata=None)[source]
- Add a survey with metadata if given with the path:
/Experiment/Surveys/survey_name
If the survey already exists, will return that survey and nothing is added.
- Parameters:
survey_name (string) – Name of the survey, should be the same as metadata.id
survey_metadata (
mth5.metadata.survey, optional) – survey metadata container, defaults to None
- Returns:
A convenience class for the added survey
- Return type:
mth5_groups.SurveyGroup- Example:
>>> from mth5 import mth5 >>> mth5_obj = mth5.MTH5() >>> mth5_obj.open_mth5(r"/test.mth5", mode='a') >>> # one option >>> new_survey = mth5_obj.add_survey('MT001') >>> # another option >>> new_station = mth5_obj.experiment_group.surveys_group.add_survey('MT001')
- get_survey(survey_name)[source]
Get a survey with the same name as survey_name
- Parameters:
survey_name (string) – existing survey name
- Returns:
convenience survey class
- Return type:
mth5.mth5_groups.surveyGroup- Raises:
MTH5Error – if the survey name is not found.
- Example:
>>> from mth5 import mth5 >>> mth5_obj = mth5.MTH5() >>> mth5_obj.open_mth5(r"/test.mth5", mode='a') >>> # one option >>> existing_survey = mth5_obj.get_survey('MT001') >>> # another option >>> existing_staiton = mth5_obj.experiment_group.surveys_group.get_survey('MT001') MTH5Error: MT001 does not exist, check groups_list for existing names
- remove_survey(survey_name)[source]
Remove a survey from the file.
Note
Deleting a survey is not as simple as del(survey). In HDF5 this does not free up memory, it simply removes the reference to that survey. The common way to get around this is to copy what you want into a new file, or overwrite the survey.
- Parameters:
survey_name (string) – existing survey name
- Example:
>>> from mth5 import mth5 >>> mth5_obj = mth5.MTH5() >>> mth5_obj.open_mth5(r"/test.mth5", mode='a') >>> # one option >>> mth5_obj.remove_survey('MT001') >>> # another option >>> mth5_obj.experiment_group.surveys_group.remove_survey('MT001')
- add_station(station_name: str, station_metadata=None, survey: str | None = None) mth5.groups.StationGroup[source]
Convenience function to add a station.
Adds a new station with optional metadata. For v0.2.0 files, a survey must be specified.
- Parameters:
station_name (str) – Name of the station (should match metadata.archive_id).
station_metadata (mt_metadata.timeseries.Station, optional) – Station metadata container. Default is None.
survey (str, optional) – Survey ID. Required for file version 0.2.0. Default is None.
- Returns:
The added or existing station group object.
- Return type:
- Raises:
ValueError – If survey is required (v0.2.0) but not provided.
Examples
Add a station to v0.2.0 file:
>>> mth5_obj = MTH5(file_version='0.2.0') >>> mth5_obj.open_mth5('test.mth5', 'w') >>> station = mth5_obj.add_station('MT001', survey='survey_001')
See also
get_stationRetrieve existing station
remove_stationDelete a station
- get_station(station_name: str, survey: str | None = None) mth5.groups.StationGroup[source]
Get an existing station from the MTH5 file.
- Parameters:
station_name (str) – Name of the station to retrieve.
survey (str, optional) – Survey ID. Required for file version 0.2.0. Default is None.
- Returns:
The requested station group object.
- Return type:
- Raises:
MTH5Error – If the station cannot be found.
Examples
Get a station:
>>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('test.mth5', 'r') >>> station = mth5_obj.get_station('MT001', survey='survey_001')
See also
add_stationCreate a new station
remove_stationDelete a station
- remove_station(station_name, survey=None)[source]
Convenience function to remove a station using
Remove a station from the file.
Note
Deleting a station is not as simple as del(station). In HDF5 this does not free up memory, it simply removes the reference to that station. The common way to get around this is to copy what you want into a new file, or overwrite the station.
- Parameters:
station_name (string) – existing station name
survey (string) – existing survey name, needed for file version >= 0.2.0
- Example:
>>> mth5_obj.remove_station('MT001')
- add_run(station_name: str, run_name: str, run_metadata=None, survey: str | None = None) mth5.groups.RunGroup[source]
Add a run to a given station.
- Parameters:
station_name (str) – Existing station name.
run_name (str) – Name of the run (typically archive_id followed by a-z).
run_metadata (mt_metadata.timeseries.Run, optional) – Run metadata container. Default is None.
survey (str, optional) – Survey ID. Required for file version 0.2.0. Default is None.
- Returns:
The added or existing run group object.
- Return type:
Examples
Add a run to a station:
>>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('test.mth5', 'w') >>> run = mth5_obj.add_run('MT001', 'MT001a', survey='survey_001')
See also
get_runRetrieve existing run
remove_runDelete a run
- get_run(station_name, run_name, survey=None)[source]
Convenience function to get a run using
mth5.stations_group.get_station(station_name).get_run()get a run from run name for a given station
- Parameters:
station_name (string) – existing station name
run_name (string) – existing run name
survey (string) – existing survey name, needed for file version >= 0.2.0
- Returns:
Run object
- Return type:
mth5.mth5_groups.RunGroup- Example:
>>> existing_run = mth5_obj.get_run('MT001', 'MT001a')
- remove_run(station_name, run_name, survey=None)[source]
Remove a run from the station.
Note
Deleting a run is not as simple as del(run). In HDF5 this does not free up memory, it simply removes the reference to that station. The common way to get around this is to copy what you want into a new file, or overwrite the run.
- Parameters:
station_name (string) – existing station name
run_name (string) – existing run name
survey (string) – existing survey name, needed for file version >= 0.2.0
- Example:
>>> mth5_obj.remove_station('MT001', 'MT001a')
- add_channel(station_name: str, run_name: str, channel_name: str, channel_type: str, data, channel_dtype: str = 'int32', max_shape: tuple[int | None, Ellipsis] = (None,), chunks: bool = True, channel_metadata=None, survey: str | None = None) mth5.groups.ElectricDataset | mth5.groups.MagneticDataset | mth5.groups.AuxiliaryDataset[source]
Add a channel to a given run and station.
- Parameters:
station_name (str) – Existing station name.
run_name (str) – Existing run name.
channel_name (str) – Name of the channel (component, e.g., ‘Ex’, ‘Hy’).
channel_type (str) – Type of channel: ‘electric’, ‘magnetic’, or ‘auxiliary’.
data (ndarray) – Channel data array.
channel_dtype (str, default 'int32') – NumPy data type for storage.
max_shape (tuple[int | None, ...], default (None,)) – Maximum shape (allows resizing). None allows unlimited growth.
chunks (bool, default True) – Enable HDF5 chunking for better performance.
channel_metadata (mt_metadata.timeseries.Electric | Magnetic | Auxiliary, optional) – Channel metadata container. Default is None.
survey (str, optional) – Survey ID. Required for file version 0.2.0. Default is None.
- Returns:
The added channel dataset object.
- Return type:
groups.ElectricDataset | groups.MagneticDataset | groups.AuxiliaryDataset
- Raises:
MTH5Error – If channel type is not valid.
Examples
Add an electric field channel:
>>> import numpy as np >>> mth5_obj = MTH5() >>> mth5_obj.open_mth5('test.mth5', 'w') >>> data = np.random.random(1000) >>> ch = mth5_obj.add_channel('MT001', 'MT001a', 'Ex', 'electric', ... data, survey='survey_001')
See also
get_channelRetrieve existing channel
remove_channelDelete a channel
- get_channel(station_name, run_name, channel_name, survey=None)[source]
Convenience function to get a channel using
mth5.stations_group.get_station().get_run().get_channel()Get a channel from an existing name. Returns the appropriate container.
- Parameters:
station_name (string) – existing station name
run_name (string) – existing run name
channel_name (string) – name of the channel
survey (string) – existing survey name, needed for file version >= 0.2.0
- Returns:
Channel container
- Return type:
[
mth5.mth5_groups.ElectricDatset|mth5.mth5_groups.MagneticDatset|mth5.mth5_groups.AuxiliaryDatset]- Raises:
MTH5Error – If no channel is found
- Example:
>>> existing_channel = mth5_obj.get_channel(station_name, >>> ... run_name, >>> ... channel_name) >>> existing_channel Channel Electric: ------------------- component: Ex data type: electric data format: float32 data shape: (4096,) start: 1980-01-01T00:00:00+00:00 end: 1980-01-01T00:00:01+00:00 sample rate: 4096
- remove_channel(station_name, run_name, channel_name, survey=None)[source]
Convenience function to remove a channel using
mth5.stations_group.get_station().get_run().remove_channel()Remove a channel from a given run and station.
Note
Deleting a channel is not as simple as del(channel). In HDF5 this does not free up memory, it simply removes the reference to that channel. The common way to get around this is to copy what you want into a new file, or overwrite the channel.
- Parameters:
station_name (string) – existing station name
run_name (string) – existing run name
channel_name (string) – existing station name
survey (string) – existing survey name, needed for file version >= 0.2.0
- Example:
>>> mth5_obj.remove_channel('MT001', 'MT001a', 'Ex')
- add_transfer_function(tf_object, update_metadata=True)[source]
Add a transfer function :param tf_object: DESCRIPTION :type tf_object: TYPE :return: DESCRIPTION :rtype: TYPE