mtpy package

Subpackages

Submodules

mtpy.mtpy_globals module

Description:

keep all the mtpy global params constants in this module.

Author: fei.zhang@ga.gov.au

FZ Last Updated: 2017-12-04 JP (2021-01-18) updated to use Path and get relative path locations.

Module contents

MTpy

class mtpy.MT(fn: str | Path | None = None, impedance_units: str = 'mt', **kwargs: Any)[source]

Bases: TF, MTLocation

Main container for MT response functions.

Impedance and Tipper element nomenclature is E/H where the first letter represents the output channels and the second letter represents the input channels. For example, for an input of Hx and an output of Ey, the impedance tensor element is Zyx.

Parameters:
  • fn (str or Path, optional) – Filename to read data from

  • impedance_units (str, optional) – Units for impedance, by default “mt”

  • **kwargs (dict) – Additional keyword arguments including period, frequency, impedance, impedance_error, tipper, tipper_error, and transfer function data

coordinate_reference_frame

Reference frame of the transfer function. Default is NED: - x = North - y = East - z = + Down

Alternative is ENU: - x = East - y = North - z = + Up

Type:

str

Notes

Coordinate reference frame options for NED:
  • “+”

  • “z+”

  • “nez+”

  • “ned”

  • “exp(+ iomega t)”

  • “exp(+iomega t)”

  • None

Coordinate reference frame options for ENU:
  • “-”

  • “z-”

  • “enz-”

  • “enu”

  • “exp(- iomega t)”

  • “exp(-iomega t)”

property Tipper: Tipper

Tipper object to hold tipper information.

Returns:

Tipper object containing tipper data

Return type:

mtpy.core.Tipper

property Z: Z

Z object to hold impedance tensor.

Returns:

Z object containing impedance tensor data

Return type:

mtpy.core.z.Z

add_model_error(comp: str | list[str] = [], z_value: float = 5, t_value: float = 0.05, periods: tuple[float, float] | None = None) None[source]

Add error to station’s components for given period range.

Parameters:
  • comp (str or list of str, optional) – List of components to add data to. Valid components are: “zxx”, “zxy”, “zyx”, “zyy”, “tzx”, “tzy”, by default []

  • z_value (float, optional) – Multiplier for impedance error, by default 5

  • t_value (float, optional) – Multiplier for tipper error, by default 0.05

  • periods (tuple of float, optional) – (min_period, max_period) to apply errors to, by default None (all periods)

Raises:

ValueError – If periods tuple doesn’t contain exactly 2 values

add_white_noise(value: float, inplace: bool = True) 'MT' | None[source]

Add white noise to the data.

Useful for synthetic tests.

Parameters:
  • value (float) – Noise level as a fraction (0-1) or percentage (0-100)

  • inplace (bool, optional) – Whether to modify in place, by default True

Returns:

If inplace is False, returns new MT object with added noise. Otherwise returns None

Return type:

MT or None

clone_empty() MT[source]

Copy metadata but not the transfer function estimates.

Returns:

New MT object with copied metadata but no transfer function data

Return type:

MT

compute_model_t_errors(error_value: float = 0.02, error_type: str = 'absolute', floor: bool = False) None[source]

Compute model errors for tipper based on the error type.

Parameters:
  • error_value (float, optional) – Error value/multiplier, by default 0.02

  • error_type (str, optional) –

    Type of error calculation, by default “absolute” Options:

    • ”percent”: error_value * t

    • ”absolute”: error_value

  • floor (bool, optional) – Whether to apply a floor to errors, by default False

Notes

Sets the tipper_model_error attribute with computed errors.

compute_model_z_errors(error_value: float = 5, error_type: str = 'geometric_mean', floor: bool = True) None[source]

Compute model errors based on the error type.

Parameters:
  • error_value (float, optional) – Error value/multiplier, by default 5

  • error_type (str, optional) –

    Type of error calculation, by default “geometric_mean” Options:

    • ”egbert” or “geometric_mean”: error_value * sqrt(Zxy * Zyx)

    • ”arithmetic_mean” or “mean_od”: error_value * (Zxy + Zyx) / 2

    • ”off_diagonals”: zxx_error == zxy_error, zyx_error == zyy_error

    • ”median”: error_value * median(z)

    • ”eigen”: error_value * mean(eigen(z))

    • ”percent”: error_value * z

    • ”absolute”: error_value

  • floor (bool, optional) – Whether to apply a floor to errors, by default True

Notes

Sets the impedance_model_error attribute with computed errors.

property coordinate_reference_frame: str

Coordinate reference frame of the transfer function.

Default is NED:
  • x = North

  • y = East

  • z = + down

Returns:

Coordinate reference frame identifier (NED or ENU)

Return type:

str

copy() MT[source]

Copy function.

Returns:

Copy of the MT object

Return type:

MT

edit_curve(method: str = 'default', tolerance: float = 0.05) None[source]

Try to remove bad points in a scientific way.

Parameters:
  • method (str, optional) – Method for curve editing, by default “default”

  • tolerance (float, optional) – Tolerance for detecting bad points, by default 0.05

Notes

This method is intended to bring up a GUI interface.

estimate_tf_quality(weights: dict[str, float] = {'bad': 0.35, 'corr': 0.2, 'diff': 0.2, 'fit': 0.05, 'std': 0.2}, round_qf: bool = False) float[source]

Estimate transfer function quality factor.

Quality factor ranges from 0-5, with 5 being the best.

Parameters:
  • weights (dict, optional) – Dictionary of weight factors for different quality metrics. Keys: “bad”, “corr”, “diff”, “std”, “fit” Default: {“bad”: 0.35, “corr”: 0.2, “diff”: 0.2, “std”: 0.2, “fit”: 0.05}

  • round_qf (bool, optional) – Whether to round the quality factor, by default False

Returns:

Quality factor value between 0 and 5

Return type:

float

property ex_metadata: Any

EX channel metadata.

Returns:

Metadata for EX channel

Return type:

Electric metadata object

property ey_metadata: Any

EY channel metadata.

Returns:

Metadata for EY channel

Return type:

Electric metadata object

find_flipped_phase() dict[str, bool][source]

Identify if off-diagonal components are flipped from traditional quadrants.

xy should be in the 1st quadrant (0-90 deg) and yx should be in the 3rd quadrant (-180 to -90 deg).

Returns:

Dictionary of components with bool values. True indicates flipped phase Keys: “zxy”, “zyx”

Return type:

dict

flip_phase(zxx: bool = False, zxy: bool = False, zyx: bool = False, zyy: bool = False, tzx: bool = False, tzy: bool = False, inplace: bool = False) 'MT' | None[source]

Flip the phase of components in case they’re plotting in the wrong quadrant.

Parameters:
  • zxx (bool, optional) – Flip Z_xx phase, by default False

  • zxy (bool, optional) – Flip Z_xy phase, by default False

  • zyx (bool, optional) – Flip Z_yx phase, by default False

  • zyy (bool, optional) – Flip Z_yy phase, by default False

  • tzx (bool, optional) – Flip T_zx phase, by default False

  • tzy (bool, optional) – Flip T_zy phase, by default False

  • inplace (bool, optional) – Whether to modify in place, by default False

Returns:

If inplace is False, returns new MT object with flipped phases. Otherwise returns None

Return type:

MT or None

Notes

Only flips the transfer function elements as the error is agnostic to sign.

from_dataframe(mt_df: MTDataFrame | Any, impedance_units: str = 'mt') None[source]

Fill transfer function attributes from a dataframe for a single station.

Parameters:
  • mt_df (MTDataFrame or DataFrame-like) – Dataframe containing MT data for a single station

  • impedance_units (str, optional) – Impedance units, “mt” [mV/km/nT] or “ohm” [Ohms], by default “mt”

Raises:
  • TypeError – If input dataframe is not an MTDataFrame or cannot be converted

  • ValueError – If dataframe is invalid

property hx_metadata: Any

HX channel metadata.

Returns:

Metadata for HX channel

Return type:

Magnetic metadata object

property hy_metadata: Any

HY channel metadata.

Returns:

Metadata for HY channel

Return type:

Magnetic metadata object

property hz_metadata: Any

HZ channel metadata.

Returns:

Metadata for HZ channel

Return type:

Magnetic metadata object

property impedance_units: str

Impedance units.

Returns:

Current impedance units (“mt” or “ohm”)

Return type:

str

interpolate(new_period: ndarray, method: str = 'slinear', bounds_error: bool = True, f_type: str = 'period', **kwargs: Any) MT[source]

Interpolate the impedance tensor onto different frequencies.

Parameters:
  • new_period (numpy.ndarray) – 1-d array of frequencies to interpolate onto. Must be within the bounds of the existing frequency range, anything outside will raise an error

  • method (str, optional) – Interpolation method, by default “slinear”

  • bounds_error (bool, optional) – Check if input frequencies are within original frequencies, by default True

  • f_type (str, optional) – Frequency type, can be “frequency” or “period”, by default “period”

  • **kwargs (dict) – Additional keyword arguments for interpolation

Returns:

New MT object with interpolated values

Return type:

MT

Raises:

ValueError – If f_type is not ‘frequency’ or ‘period’ If input frequencies are out of bounds

plot_depth_of_penetration(**kwargs: Any) PlotPenetrationDepth1D[source]

Plot depth of penetration estimated from Niblett-Bostick estimation.

Parameters:

**kwargs (dict) – Additional keyword arguments for plotting

Returns:

Penetration depth plot object

Return type:

PlotPenetrationDepth1D

plot_mt_response(**kwargs: Any) PlotMTResponse[source]

Create a PlotResponse object for plotting MT response.

Parameters:

**kwargs (dict) – Additional keyword arguments for plotting

Returns:

Plot response object

Return type:

PlotMTResponse

Examples

>>> mt_obj = MT(edi_file)
>>> pr = mt_obj.plot_mt_response()
>>> # For more info on plot_mt_response
>>> help(pr)
plot_phase_tensor(**kwargs: Any) PlotPhaseTensor[source]

Plot phase tensor.

Parameters:

**kwargs (dict) – Additional keyword arguments for plotting

Returns:

Phase tensor plot object

Return type:

PlotPhaseTensor

property pt

PhaseTensor object.

Returns:

Phase tensor object

Return type:

mtpy.analysis.pt.PhaseTensor

remove_component(zxx: bool = False, zxy: bool = False, zyy: bool = False, zyx: bool = False, tzx: bool = False, tzy: bool = False, inplace: bool = False) 'MT' | None[source]

Remove a component by setting it to NaN.

Parameters:
  • zxx (bool, optional) – Remove Z_xx, by default False

  • zxy (bool, optional) – Remove Z_xy, by default False

  • zyy (bool, optional) – Remove Z_yy, by default False

  • zyx (bool, optional) – Remove Z_yx, by default False

  • tzx (bool, optional) – Remove T_zx, by default False

  • tzy (bool, optional) – Remove T_zy, by default False

  • inplace (bool, optional) – Whether to modify in place, by default False

Returns:

If inplace is False, returns new MT object with components removed. Otherwise returns None

Return type:

MT or None

remove_distortion(n_frequencies: int | None = None, comp: str = 'det', only_2d: bool = False, inplace: bool = False) 'MT' | None[source]

Remove distortion following Bibby et al. [2005].

Parameters:
  • n_frequencies (int, optional) – Number of frequencies to look for distortion from the highest frequency, by default None

  • comp (str, optional) – Component to use, by default “det”

  • only_2d (bool, optional) – Whether to only consider 2D distortion, by default False

  • inplace (bool, optional) – Whether to modify in place, by default False

Returns:

If inplace is False, returns new MT object with distortion removed. Otherwise returns None

Return type:

MT or None

remove_static_shift(ss_x: float = 1.0, ss_y: float = 1.0, inplace: bool = False) 'MT' | None[source]

Remove static shift from the apparent resistivity.

Assumes the original observed tensor Z is built by a static shift S and an unperturbated “correct” Z0:

Z = S * Z0

Therefore the correct Z will be:

Z0 = S^(-1) * Z

Parameters:
  • ss_x (float, optional) – Correction factor for x component, by default 1.0

  • ss_y (float, optional) – Correction factor for y component, by default 1.0

  • inplace (bool, optional) – Whether to modify in place, by default False

Returns:

If inplace is False, returns new Z object with static shift removed. Otherwise returns None

Return type:

MT or None

rotate(theta_r: float | np.ndarray, inplace: bool = True) 'MT' | None[source]

Rotate the data in degrees.

Rotation assumes North is 0 measuring clockwise positive to East as 90.

Parameters:
  • theta_r (float or numpy.ndarray) – Rotation angle to rotate by in degrees

  • inplace (bool, optional) – Rotate all transfer function in place, by default True

Returns:

If inplace is False, returns a new MT object. Otherwise returns None

Return type:

MT or None

property rotation_angle: float | ndarray

Rotation angle in degrees from north.

Returns:

Rotation angle(s) in degrees from north in the coordinate reference frame

Return type:

float or numpy.ndarray

property rrhx_metadata: Any

Remote reference HX channel metadata.

Returns:

Metadata for remote reference HX channel

Return type:

Magnetic metadata object

property rrhy_metadata: Any

Remote reference HY channel metadata.

Returns:

Metadata for remote reference HY channel

Return type:

Magnetic metadata object

to_dataframe(utm_crs: Any | None = None, cols: list[str] | None = None, impedance_units: str = 'mt') MTDataFrame[source]

Create a dataframe from the transfer function.

For use with plotting and modeling.

Parameters:
  • utm_crs (str, int, or pyproj.CRS, optional) – UTM zone to project station to. Could be a name, pyproj.CRS, EPSG number, or anything that pyproj.CRS can intake, by default None

  • cols (list of str, optional) – Column names to include, by default None

  • impedance_units (str, optional) – Impedance units, “mt” [mV/km/nT] or “ohm” [Ohms], by default “mt”

Returns:

DataFrame containing MT data

Return type:

MTDataFrame

to_occam1d(data_filename: str | Path | None = None, mode: str = 'det') Occam1DData[source]

Write an Occam1D data file.

Parameters:
  • data_filename (str or Path, optional) – Path to write file. If None, returns Occam1DData object without writing, by default None

  • mode (str, optional) – Mode for inversion. Options: “te”, “tm”, “det”, “tez”, “tmz”, “detz”, by default “det”

Returns:

Occam1D data object

Return type:

Occam1DData

to_simpeg_1d(mode: str = 'det', **kwargs: Any) Simpeg1D[source]

Run a 1D inversion using SimPEG.

Default uses smooth parameters.

Parameters:
  • mode (str, optional) – Mode for inversion, by default “det”

  • **kwargs (dict) – Additional keyword arguments for inversion configuration: - p_s : Smoothness parameter (default: smooth inversion) - p_z : Depth weighting parameter - use_irls : Whether to use IRLS for sharp inversions

Returns:

SimPEG 1D inversion object with results

Return type:

Simpeg1D

Examples

To run sharp inversion:

>>> mt_object.to_simpeg_1d({"p_s": 2, "p_z": 0, "use_irls": True})

To run sharp inversion and compact:

>>> mt_object.to_simpeg_1d({"p_s": 0, "p_z": 0, "use_irls": True})
class mtpy.MTCollection(working_directory: str | Path | None = None)[source]

Bases: object

Collection of transfer functions.

The main working variable is MTCollection.dataframe which is a property that returns either the master dataframe that contains all the TF’s in the MTH5 file, or the working_dataframe which is a dataframe that has been queried in some way.

Parameters:

working_directory (str, Path, optional) – Working directory path, by default None

mth5_basename

Base name for MTH5 file

Type:

str

working_dataframe

Subset dataframe for queries

Type:

pd.DataFrame or None

mth5_collection

MTH5 object for data storage

Type:

MTH5

Examples

>>> mc = MTCollection()
>>> mc.open_collection(filename="path/to/example/mth5.h5")
>>> mc.working_dataframe = mc.master_dataframe.iloc[0:5]
add_tf(transfer_function: MT | str | Path | list | MTData, new_survey: str | None = None, tf_id_extra: str | None = None) None[source]

Add transfer function(s) to the collection.

Parameters:
  • transfer_function (MT, str, Path, list, MTData) – Transfer function object(s), file path(s), or MTData object

  • new_survey (str, optional) – New survey name, by default None

  • tf_id_extra (str, optional) – Additional text to append to ‘tf_id’, by default None

Notes

For efficiency, create list first then add using add_tf([list])

apply_bbox(lon_min: float, lon_max: float, lat_min: float, lat_max: float) None[source]

Set working dataframe to only stations within bounding box.

Parameters:
  • lon_min (float) – Minimum longitude

  • lon_max (float) – Maximum longitude

  • lat_min (float) – Minimum latitude

  • lat_max (float) – Maximum latitude

average_stations(cell_size_m: float, bounding_box: tuple[float, float, float, float] | None = None, count: int = 1, n_periods: int = 48, new_file: bool = True) None[source]

Average nearby stations to reduce data density.

Parameters:
  • cell_size_m (float) – Size of square in meters to search for nearby stations

  • bounding_box (tuple of float, optional) – Bounding box as (lon_min, lon_max, lat_min, lat_max), by default None

  • count (int, optional) – Starting count for averaged station names, by default 1

  • n_periods (int, optional) – Number of periods for interpolation, by default 48

  • new_file (bool, optional) – Whether to write averaged stations to EDI files, by default True

check_for_duplicates(locate: str = 'location', sig_figs: int = 6) DataFrame | None[source]

Check for duplicate station locations.

Parameters:
  • locate (str, optional) – Column(s) to check for duplicates, by default ‘location’

  • sig_figs (int, optional) – Significant figures for rounding, by default 6

Returns:

DataFrame of duplicates, or None if no data

Return type:

pd.DataFrame or None

Raises:

ValueError – If locate column not found

close_collection() None[source]

Close MTH5 file.

property dataframe: DataFrame | None

Working or master dataframe.

Returns:

Returns working_dataframe if set, otherwise master_dataframe

Return type:

pd.DataFrame or None

from_mt_data(mt_data: MTData, new_survey: str | None = None, tf_id_extra: str | None = None) None[source]

Add data from MTData object to collection.

Parameters:
  • mt_data (MTData) – MTData object containing transfer functions

  • new_survey (str, optional) – New survey name, by default None

  • tf_id_extra (str, optional) – Additional text to append to ‘tf_id’, by default None

Raises:

IOError – If MTH5 is not writable

Notes

Use ‘new_survey’ to create a new survey. Use ‘tf_id_extra’ to add text onto ‘tf_id’ (useful for edited/manipulated data)

get_tf(tf_id: str, survey: str | None = None) MT[source]

Get transfer function from collection.

Parameters:
  • tf_id (str) – Transfer function identifier

  • survey (str, optional) – Survey name, by default None

Returns:

MT object for the requested transfer function

Return type:

MT

Raises:

ValueError – If tf_id cannot be found

has_data() bool[source]

Check if collection has data.

Returns:

True if master_dataframe is not None

Return type:

bool

static make_file_list(mt_path: str | Path | list[str | Path] | None, file_types: list[str] | None = None) list[Path][source]

Get list of MT files from a given path.

Parameters:
  • mt_path (str, Path, list, optional) – Path(s) to MT transfer function files

  • file_types (list of str, optional) – File extensions to search for, by default [‘edi’]

Returns:

List of file paths

Return type:

list of Path

Raises:
  • IOError – If path does not exist

  • TypeError – If mt_path is not str, Path, or list

map_stations(transform, write_back: bool = False, new_survey: str | None = None, tf_id_extra: str | None = None) MTData[source]

Apply a transform to every station dataset and return the result.

The result is also stored in mt_data.

Parameters:
  • transform (callable) – Function that accepts and returns an xr.Dataset for a single station. Receives the same arguments as MTData.map_stations().

  • write_back (bool, optional) – If True the transformed data are written back to the MTH5 collection via from_mt_data(). Defaults to False.

  • new_survey (str, optional) – Passed to from_mt_data() when write_back is True.

  • tf_id_extra (str, optional) – Passed to from_mt_data() when write_back is True.

Returns:

MTData object with the transform applied (also stored as mt_data).

Return type:

MTData

Examples

>>> mc.map_stations(lambda ds: ds.tf.rotate(20), write_back=False)
>>> mc.map_stations(
...     lambda ds: ds.tf.interpolate([1.0, 10.0]),
...     write_back=True,
...     new_survey="processed",
...     tf_id_extra="interp",
... )
property master_dataframe: DataFrame | None

Full summary of all transfer functions.

Returns:

DataFrame with all transfer functions in the MTH5 file, or None if MTH5 is not open

Return type:

pd.DataFrame or None

Notes

Automatically updated when TFs are added

property mth5_filename: Path

MTH5 filename path.

Returns:

Full path to MTH5 file

Return type:

Path

open_collection(filename: str | Path | None = None, basename: str | None = None, working_directory: str | Path | None = None, mode: str = 'a', **kwargs: Any) None[source]

Initialize an MTH5 collection.

Parameters:
  • filename (str, Path, optional) – Full path to MTH5 file, by default None

  • basename (str, optional) – Base name for MTH5 file, by default None

  • working_directory (str, Path, optional) – Working directory path, by default None

  • mode (str, optional) – File open mode, by default ‘a’

  • **kwargs (dict) – Additional parameters

Notes

This method also initializes mt_data for convenience. If the collection does not yet contain readable transfer functions, mt_data is initialized as an empty MTData.

Examples

>>> mc = MTCollection()
>>> mc.open_collection("my_collection.h5", mode="a")
>>> mt_data = mc.mt_data
plot_mt_response(tf_id: str | list | tuple | ndarray | Series, survey: str | None = None, **kwargs: Any) Any[source]

Plot MT response for one or more stations.

Parameters:
  • tf_id (str or array-like) – Transfer function ID(s) to plot. Can be single ID string or array of IDs. If 2D array, each row is [tf_id, survey].

  • survey (str, optional) – Survey name, by default None

  • **kwargs (Any) – Additional keyword arguments passed to plotting function

Returns:

Plot object from MT.plot_mt_response or PlotMultipleResponses

Return type:

Any

plot_penetration_depth_1d(tf_id: str, survey: str | None = None, **kwargs: Any) Any[source]

Plot 1D penetration depth using Niblett-Bostick transformation.

Data is rotated to estimated strike prior to estimation, and strike angles are interpreted for data points that are 3D.

Parameters:
  • tf_id (str) – Transfer function ID

  • survey (str, optional) – Survey name, by default None

  • **kwargs (Any) – Additional keyword arguments passed to PlotPenetrationDepth1D

Returns:

PlotPenetrationDepth1D object

Return type:

Any

See also

mtpy.analysis.niblettbostick.calculate_depth_of_investigation

plot_penetration_depth_map(mt_data: MTData | None = None, **kwargs: Any) Any[source]

Plot penetration depth in map view for a single period.

Parameters:
  • mt_data (MTData, optional) – MTData object, by default None (uses collection data)

  • **kwargs (Any) – Additional keyword arguments passed to PlotPenetrationDepthMap

Returns:

PlotPenetrationDepthMap object

Return type:

Any

plot_phase_tensor(tf_id: str, survey: str | None = None, **kwargs: Any) Any[source]

Plot phase tensor elements for a station.

Parameters:
  • tf_id (str) – Transfer function ID

  • survey (str, optional) – Survey name, by default None

  • **kwargs (Any) – Additional keyword arguments passed to MT.plot_phase_tensor

Returns:

Plot object from MT.plot_phase_tensor

Return type:

Any

plot_phase_tensor_map(mt_data: MTData | None = None, **kwargs: Any) Any[source]

Plot phase tensor maps for transfer functions.

Parameters:
  • mt_data (MTData, optional) – MTData object, by default None (uses collection data)

  • **kwargs (Any) – Additional keyword arguments passed to PlotPhaseTensorMaps

Returns:

PlotPhaseTensorMaps object

Return type:

Any

plot_phase_tensor_pseudosection(mt_data: MTData | None = None, **kwargs: Any) Any[source]

Plot pseudosection of phase tensor ellipses and induction vectors.

Parameters:
  • mt_data (MTData, optional) – MTData object, by default None (uses collection data)

  • **kwargs (Any) – Additional keyword arguments passed to PlotPhaseTensorPseudoSection

Returns:

PlotPhaseTensorPseudoSection object

Return type:

Any

See also

mtpy.imaging.PlotPhaseTensorPseudosection

plot_residual_phase_tensor(mt_data_01: MTData, mt_data_02: MTData, plot_type: str = 'map', **kwargs: Any) Any[source]

Plot residual phase tensor between two datasets.

Parameters:
  • mt_data_01 (MTData) – First MTData object

  • mt_data_02 (MTData) – Second MTData object

  • plot_type (str, optional) – Type of plot: ‘map’ or ‘pseudosection’/’ps’, by default ‘map’

  • **kwargs (Any) – Additional keyword arguments passed to plotting function

Returns:

PlotResidualPTMaps or PlotResidualPTPseudoSection object

Return type:

Any

plot_resistivity_phase_maps(mt_data: MTData | None = None, **kwargs: Any) Any[source]

Plot apparent resistivity and impedance phase maps.

Parameters:
  • mt_data (MTData, optional) – MTData object, by default None (uses collection data)

  • **kwargs (Any) – Additional keyword arguments passed to PlotResPhaseMaps

Returns:

PlotResPhaseMaps object

Return type:

Any

plot_resistivity_phase_pseudosections(mt_data: MTData | None = None, **kwargs: Any) Any[source]

Plot resistivity and phase pseudosections along a profile.

Parameters:
  • mt_data (MTData, optional) – MTData object, by default None (uses collection data)

  • **kwargs (Any) – Additional keyword arguments passed to PlotResPhasePseudoSection

Returns:

PlotResPhasePseudoSection object

Return type:

Any

plot_stations(map_epsg: int = 4326, bounding_box: tuple[float, float, float, float] | None = None, **kwargs: Any) Any[source]

Plot station locations on a map.

Parameters:
  • map_epsg (int, optional) – EPSG code for map projection, by default 4326

  • bounding_box (tuple of float, optional) – Bounding box as (lon_min, lon_max, lat_min, lat_max), by default None

  • **kwargs (Any) – Additional keyword arguments passed to PlotStations

Returns:

PlotStations object

Return type:

Any

plot_strike(mt_data: MTData | None = None, **kwargs: Any) Any[source]

Plot strike angle.

Parameters:
  • mt_data (MTData, optional) – MTData object, by default None (uses collection data)

  • **kwargs (Any) – Additional keyword arguments passed to PlotStrike

Returns:

PlotStrike object

Return type:

Any

refresh_mt_data() MTData[source]

Reload mt_data from the collection.

Call this after adding or removing transfer functions to keep mt_data in sync with the underlying MTH5 file.

Returns:

The refreshed MTData object (also stored as mt_data).

Return type:

MTData

Examples

>>> mc.add_tf(tf_list)
>>> mt_data = mc.refresh_mt_data()
to_geo_df(bounding_box: tuple[float, float, float, float] | None = None, epsg: int = 4326) GeoDataFrame[source]

Create a geopandas GeoDataFrame for GIS manipulation.

Parameters:
  • bounding_box (tuple of float, optional) – Bounding box as (lon_min, lon_max, lat_min, lat_max), by default None

  • epsg (int, optional) – EPSG code for coordinate system, by default 4326

Returns:

GeoDataFrame with station locations and metadata

Return type:

gpd.GeoDataFrame

to_mt_data(bounding_box: tuple[float, float, float, float] | None = None, **kwargs: Any) MTData[source]

Get transfer functions as MTData object.

Parameters:
  • bounding_box (tuple of float, optional) – Bounding box (lon_min, lon_max, lat_min, lat_max), by default None

  • **kwargs (dict) – Additional parameters passed to MTData

Returns:

MTData object containing transfer functions

Return type:

MTData

to_shp(filename: str | Path, bounding_box: tuple[float, float, float, float] | None = None, epsg: int = 4326) GeoDataFrame | None[source]

Create a shapefile of station locations.

Parameters:
  • filename (str or Path) – Filename to save the shapefile to

  • bounding_box (tuple of float, optional) – Bounding box as (lon_min, lon_max, lat_min, lat_max), by default None

  • epsg (int, optional) – EPSG code for coordinate system, by default 4326

Returns:

GeoDataFrame of stations, or None if no data

Return type:

gpd.GeoDataFrame or None

property working_dataframe: DataFrame | None

Subset of the master dataframe for the current working selection.

Assigning a DataFrame filters mt_data to only the stations present in that subset. Setting to None resets the selection so that mt_data reflects the full master_dataframe.

Returns:

Current working selection, or None if unset.

Return type:

pd.DataFrame or None

Examples

>>> mc.working_dataframe = mc.master_dataframe.iloc[0:5]
>>> mc.working_dataframe = None  # reset to full collection
property working_directory: Path

Working directory path.

Returns:

Current working directory

Return type:

Path

class mtpy.MTData(tree: None | Any = None, metadata_storage: str = 'cache', dataset_copy_mode: str = 'shallow', use_index: bool = False, index_db_path: str = ':memory:', **attrs: Any)[source]

Bases: object

Tree-backed container for MT collection data.

Notes

Composition is intentionally used instead of inheriting from xarray’s tree type. This keeps the public MT API independent from xarray internals and allows controlled migration from MTData.

COORDINATE_REFERENCE_FRAME = {'+': 'ned', '-': 'enu', 'enu': 'enu', 'enz-': 'enu', 'exp(+ i\\omega t)': 'ned', 'exp(+i\\omega t)': 'ned', 'exp(- i\\omega t)': 'enu', 'exp(-i\\omega t)': 'enu', 'ned': 'ned', 'nez+': 'ned', 'z+': 'ned', 'z-': 'enu', None: 'ned'}
DATASET_COPY_MODES = {'deep', 'none', 'shallow'}
IMPEDANCE_UNITS = {'mt': 1, 'ohm': np.float64(795.7747154594769)}
METADATA_STORAGE_MODES = {'cache', 'dict', 'summary'}
ROOT_NAME = 'root'
STATIONS_NODE = 'stations'
SURVEYS_NODE = 'surveys'
add_station(mt_obj: MT | str | Path | list[MT | str | Path], overwrite: bool = True, dataset_copy_mode: str | None = None) str | list[str][source]

Add an MT object as a station node in the tree.

Node path pattern:

/surveys/{survey_id}/stations/{station_id}

Parameters:
  • mt_obj (mtpy.core.MT, str, Path, or list) – MT object, filename, pathlib.Path, or a list of mixed supported input types.

  • overwrite (bool, optional) – If False, raise if station path already exists.

  • dataset_copy_mode ({'deep', 'shallow', 'none'}, optional) – Dataset copy behavior for station transfer-function storage.

Returns:

Station node path for scalar inputs or list of paths for list inputs.

Return type:

str or list[str]

add_stations(mt_objects: list[MT | str | Path], overwrite: bool = True, dataset_copy_mode: str | None = None, precomputed_attrs: list[dict[str, Any] | None] | None = None) list[str][source]

Bulk-add MT stations with optional precomputed attrs for fast ingest.

Parameters:
  • mt_objects (list) – List of MT objects, filename strings, or Paths.

  • overwrite (bool, optional) – If False, raise if a station path already exists.

  • dataset_copy_mode ({'deep', 'shallow', 'none'}, optional) – Dataset copy behavior for station transfer-function storage.

  • precomputed_attrs (list[dict | None], optional) – Optional attrs payload aligned by index with mt_objects. When provided, these attrs are used directly and only canonical keys are enforced (survey/station and metadata refs).

Returns:

Inserted station paths.

Return type:

list[str]

add_tf(tf: MT | str | Path | list[MT | str | Path], **kwargs: Any) str | list[str][source]

Alias for add_station to mirror MTData API.

add_white_noise(value: float, inplace: bool = True) MTData | None[source]

Add white noise to the impedance and tipper of every station.

Multiplies the real and imaginary parts of the transfer function by independent random factors drawn from ``1 ± U(0, value) `` and increments the transfer-function error by value. Useful for generating synthetic test datasets.

Parameters:
  • value (float) – Noise level expressed as a decimal fraction (0–1) or as a percentage (>1). Values greater than 1 are divided by 100 automatically (e.g. 10 becomes 0.10, i.e. 10 %).

  • inplace (bool, optional) – When True (default) each station dataset is modified in place and None is returned. When False a new MTData containing noisy copies is returned and the original tree is left unchanged.

Returns:

A new tree containing noisy station data when inplace is False; None otherwise.

Return type:

MTData or None

Examples

In-place noise addition:

>>> from mtpy.core import MTData
>>> tree = MTData()
>>> # tree.add_station(...)  # populate first
>>> tree.add_white_noise(5)  # adds 5 % noise in place

Non-destructive copy with noise:

>>> noisy_tree = tree.add_white_noise(0.05, inplace=False)
apply_bounding_box(lon_min: float, lon_max: float, lat_min: float, lat_max: float) MTData[source]

Return stations that fall inside a lon/lat bounding box.

Parameters:
  • lon_min (float) – Longitude bounds.

  • lon_max (float) – Longitude bounds.

  • lat_min (float) – Latitude bounds.

  • lat_max (float) – Latitude bounds.

Returns:

Subset tree containing stations inside the bounding box.

Return type:

MTData

as_dask(chunks: dict[str, int] | str | None, station_paths: list[str] | None = None, variables: list[str] | None = None, inplace: bool = False) MTData[source]

Chunk station datasets to dask-backed arrays.

Parameters:
  • chunks (dict[str, int] or str or None) – Chunk specification passed to xarray chunk.

  • station_paths (list[str], optional) – Subset of station paths to chunk.

  • variables (list[str], optional) – Data-variable names to chunk. When None, all variables are chunked.

  • inplace (bool, optional) – If True, modify this tree in place. Otherwise return a chunked subset copy.

Returns:

Chunked tree (same instance when inplace is True).

Return type:

MTData

Raises:
  • RuntimeError – If dask is not installed.

  • KeyError – If a requested variable is missing for a selected station.

Examples

>>> tree = tree.as_dask(chunks={"period": 32})
>>> tree = tree.as_dask(chunks="auto", variables=["transfer_function"])
property center_point: Any

Return the geographic center point of the station collection.

If explicit center coordinates have been stored (e.g. after reading a ModEM data file), those values are returned directly. Otherwise the center is derived on-the-fly from all station locations via to_mt_stations().

Returns:

Center location with latitude, longitude, elevation, east, north, and utm_epsg attributes populated.

Return type:

MTLocation

Examples

>>> from mtpy.core import MTData
>>> tree = MTData()
>>> # (add stations first)
>>> cp = tree.center_point
>>> print(cp.latitude, cp.longitude)
center_stations(model_obj: Any) None[source]

Center station locations to model cell centers and sync to tree.

chunk_plan(station_paths: list[str] | None = None) dict[str, dict[str, tuple[tuple[int, ...], ...] | None]][source]

Return per-station chunk layout for each data variable.

Parameters:

station_paths (list[str], optional) – Station subset to summarize.

Returns:

Mapping from station path to variable chunk tuples (or None for NumPy-backed variables).

Return type:

dict[str, dict[str, tuple[tuple[int, …], …] or None]]

clone_empty() MTData[source]

Create a copy of MTData excluding all station datasets.

compute(station_paths: list[str] | None = None, scheduler: str | None = None) MTData[source]

Materialize deferred station transforms and refresh index state.

Parameters:
  • station_paths (list[str], optional) – Subset of station tree paths to realize. When None, all pending lazy station transforms are computed.

  • scheduler (str, optional) – Dask scheduler name passed through when delayed transforms are present.

Returns:

The current tree instance.

Return type:

MTData

compute_model_errors(z_error_value: float | None = None, z_error_type: str | None = None, z_floor: bool | None = None, t_error_value: float | None = None, t_error_type: str | None = None, t_floor: bool | None = None) None[source]

Recompute impedance and tipper model errors for all stations.

Parameters:
  • z_error_value (optional) – Overrides for impedance model-error settings.

  • z_error_type (optional) – Overrides for impedance model-error settings.

  • z_floor (optional) – Overrides for impedance model-error settings.

  • t_error_value (optional) – Overrides for tipper model-error settings.

  • t_error_type (optional) – Overrides for tipper model-error settings.

  • t_floor (optional) – Overrides for tipper model-error settings.

compute_relative_locations() None[source]

Compute model-relative station coordinates and sync to the tree.

property coordinate_reference_frame: str

Coordinate reference frame.

Returns:

Reference frame identifier (‘NED’ or ‘ENU’)

Return type:

str

copy() MTData[source]

Create a deep copy of MTData object.

property datum_crs: Any | None

Return the root datum CRS/EPSG value.

property datum_epsg: int | None

Return the root datum EPSG code when available.

estimate_spatial_static_shift(station_key: str, radius: float, period_min: float, period_max: float, radius_units: str = 'm', shift_tolerance: float = 0.15) tuple[float, float][source]

Estimate static-shift scale factors from nearby stations.

Parameters:
  • station_key (str) – Target station key.

  • radius (float) – Neighbor search radius.

  • period_min (float) – Period bounds used for comparison.

  • period_max (float) – Period bounds used for comparison.

  • radius_units (str, optional) – Radius units passed to get_nearby_stations().

  • shift_tolerance (float, optional) – Values within 1 +/- shift_tolerance are snapped to 1.0.

Returns:

Estimated (sx, sy) static-shift factors.

Return type:

tuple[float, float]

estimate_starting_rho() None[source]

Estimate starting resistivity from all station data and plot summary curves.

finalize_index() None[source]

Recompute deferred stations and rebuild the index.

from_dataframe(df: DataFrame, impedance_units: str = 'mt') None[source]

Populate the tree from a station dataframe.

Parameters:
  • df (pandas.DataFrame) – Dataframe containing MT rows, grouped by station (and survey when available).

  • impedance_units (str, optional) – Unit convention used by impedance values in df.

from_modem(data_filename: str | Path, survey: str = 'data', **kwargs: Any) None[source]

Populate the tree by reading an existing ModEM data file.

Station datasets, model-error parameters, the center point, and any top-level model parameters (those without a dot in the key) are all restored from the file.

Parameters:
  • data_filename (str or pathlib.Path) – Path to the ModEM .dat / .data file.

  • survey (str, optional) – Survey label to assign to all imported stations, by default 'data'.

  • **kwargs – Additional keyword arguments forwarded to mtpy.modeling.modem.Data.

Examples

>>> from mtpy.core import MTData
>>> tree = MTData()
>>> tree.from_modem("ModEM_data.dat", survey="line1")
>>> print(tree.survey_ids)
from_mt_dataframe(mt_df: MTDataFrame, impedance_units: str = 'mt') None[source]

Populate the tree from an MTDataFrame.

Parameters:
  • mt_df (MTDataFrame) – Input MTDataFrame.

  • impedance_units (str, optional) – Unit convention used by impedance values.

from_occam2d(data_filename: str | Path, file_type: str = 'data', **kwargs: Any) None[source]

Populate the tree by reading an existing Occam2D data file.

After reading, profile_origin, profile_angle, and model_mode are stored in model_parameters.

Parameters:
  • data_filename (str or pathlib.Path) – Path to the Occam2D data file.

  • file_type (str, optional) – 'data' (default) or 'response'/'model'. Controls the survey label ('data' or 'model') assigned to each row.

  • **kwargs – Additional keyword arguments forwarded to mtpy.modeling.occam2d.Occam2DData.

Examples

Read a data file:

>>> from mtpy.core import MTData
>>> tree = MTData()
>>> tree.from_occam2d("OccamDataFile.dat")
>>> print(tree.station_ids)

Read a response / model file:

>>> tree.from_occam2d("OccamResponse.dat", file_type="response")
generate_profile(units: str = 'deg') tuple[float, float, float, float, dict[str, float]][source]

Generate a best-fit profile line via MTStations.

generate_profile_from_strike(strike: float, units: str = 'deg') tuple[float, float, float, float, dict[str, float]][source]

Generate a profile line from strike via MTStations.

get_metadata(station_key: str, metadata_kind: str = 'station') Any | dict[str, Any] | None[source]

Return survey or station metadata for one station.

Parameters:
  • station_key (str) – Station tree path.

  • metadata_kind ({'survey', 'station'}, optional) – Metadata object to fetch.

Returns:

Cached metadata object in metadata_storage='cache' mode when present, otherwise a dictionary copy from station attrs.

Return type:

object or dict or None

Raises:

KeyError – If metadata_kind is not 'survey' or 'station'.

get_nearby_stations(station_key: str, radius: float, radius_units: str = 'm') list[str][source]

Find neighboring stations around a reference station.

Parameters:
  • station_key (str) – Reference station key as canonical tree path or survey.station.

  • radius (float) – Search radius in the units specified by radius_units.

  • radius_units ({'m', 'meters', 'metres', 'deg', 'degrees'}, optional) – Distance units for radius.

Returns:

Matching stations as survey.station keys (excluding the reference station).

Return type:

list[str]

Raises:

ValueError – If metric units are requested without UTM coordinate information, or if radius_units is unsupported.

Examples

>>> nearby = tree.get_nearby_stations("surveyA.station01", radius=5000)
>>> nearby_deg = tree.get_nearby_stations("surveyA.station01", 0.1, "deg")
get_periods() ndarray[source]

Return sorted unique periods across all stations.

Returns:

One-dimensional array of unique periods in ascending order.

Return type:

numpy.ndarray

get_profile(x1: float, y1: float, x2: float, y2: float, radius: float) MTData[source]

Extract stations within a corridor around a profile line.

Parameters:
  • x1 (float) – Profile start and end coordinates in the same coordinate system as station locations.

  • y1 (float) – Profile start and end coordinates in the same coordinate system as station locations.

  • x2 (float) – Profile start and end coordinates in the same coordinate system as station locations.

  • y2 (float) – Profile start and end coordinates in the same coordinate system as station locations.

  • radius (float) – Corridor half-width around the profile line.

Returns:

New tree containing only stations that fall within the profile corridor.

Return type:

MTData

get_station(station_key: str, as_mt: bool = False) xr.Dataset | 'MT'[source]

Return one station as a dataset or reconstructed MT object.

Parameters:
  • station_key (str) – Station identifier in canonical tree-path, survey/station, or survey.station form.

  • as_mt (bool, optional) – If True, convert the stored dataset to an MT object.

Returns:

Station dataset (default) or reconstructed MT object.

Return type:

xarray.Dataset or MT

Examples

>>> ds = tree.get_station("surveys/surveyA/stations/st01")
>>> ds = tree.get_station("surveyA/st01")
>>> mt_obj = tree.get_station("surveys/surveyA/stations/st01", as_mt=True)
get_subset(station_list: list[str]) MTData[source]

Create a tree containing only selected station paths.

Parameters:

station_list (list[str]) – Station tree paths to copy into the subset.

Returns:

New tree with copied station datasets and relevant metadata cache entries.

Return type:

MTData

get_survey(survey_id: str) MTData[source]

Return a subset tree for one survey.

Parameters:

survey_id (str) – Survey identifier.

Returns:

Tree containing all stations under the selected survey.

Return type:

MTData

property impedance_units: str

Impedance units.

Returns:

Impedance units (‘mt’ or ‘ohm’)

Return type:

str

interpolate(new_periods: np.ndarray, f_type: str = 'period', inplace: bool = True, bounds_error: bool = True, **kwargs: Any) 'MTData' | None[source]

Interpolate all stations to a shared period grid.

Parameters:
  • new_periods (ndarray) – Target period array, or frequency array when f_type is 'frequency'/'freq'.

  • f_type ({'frequency', 'freq', 'period', 'per'}, optional) – Specifies the meaning of new_periods.

  • inplace (bool, optional) – If True (default), update this tree in place.

  • bounds_error (bool, optional) – If True, clip target periods to each station’s native period range.

  • **kwargs – Forwarded to station interpolation.

Returns:

Interpolated copy when inplace is False; otherwise None.

Return type:

MTData or None

Raises:

ValueError – If f_type is unsupported.

interpolate_dask(new_periods: ndarray, f_type: str = 'period', bounds_error: bool = True, chunks: dict[str, int] | str | None = None, scheduler: str | None = None, compute: bool = True, inplace: bool = False, **kwargs: Any) MTData[source]

Interpolate stations with dask-delayed execution.

Parameters:
  • new_periods (ndarray) – Target periods or frequencies depending on f_type.

  • f_type (str, optional) – 'period' (default) or 'frequency'/'freq'.

  • bounds_error (bool, optional) – Restrict interpolation to each station’s native period range.

  • chunks (dict[str, int] or str or None, optional) – Optional chunking applied before creating delayed transforms.

  • scheduler (str, optional) – Dask scheduler used during computation when compute is True.

  • compute (bool, optional) – If True (default), execute delayed transforms immediately.

  • inplace (bool, optional) – If True, modify this tree.

  • **kwargs – Forwarded to the station interpolation routine.

Returns:

Tree with interpolated results or pending delayed transforms.

Return type:

MTData

interpolate_lazy(new_periods: ndarray, f_type: str = 'period', inplace: bool = False, bounds_error: bool = True, **kwargs: Any) MTData[source]

Register deferred interpolation transforms for all stations.

Parameters:
  • new_periods (ndarray) – Target period array, or frequency array when f_type indicates frequency input.

  • f_type ({'frequency', 'freq', 'period', 'per'}, optional) – Specifies the meaning of new_periods.

  • inplace (bool, optional) – If True, clear and replace lazy transforms on this instance. Otherwise return a new tree with lazy transforms attached.

  • bounds_error (bool, optional) – If True, clip target periods to each station’s native period range.

  • **kwargs – Forwarded to station interpolation at compute time.

Returns:

Tree with pending interpolation transforms.

Return type:

MTData

is_dask_backed(station_paths: list[str] | None = None) bool[source]

Check whether selected stations are dask-backed.

Parameters:

station_paths (list[str], optional) – Station subset to inspect. When None, all stations are checked.

Returns:

True only when each selected station has dask-backed arrays for all data variables.

Return type:

bool

property is_lazy: bool

True when one or more deferred station transforms are pending.

keys() list[str][source]

Return immediate top-level child node keys.

Returns:

Names of direct children under the tree root.

Return type:

list[str]

property lazy_station_count: int

Number of stations with pending deferred transforms.

map_stations(transform: Callable[[Dataset], Dataset], station_paths: list[str] | None = None, lazy: bool = True, inplace: bool = False) MTData[source]

Apply a dataset transform to selected stations.

Parameters:
  • transform (callable) – Function receiving one station xr.Dataset and returning an xr.Dataset.

  • station_paths (list[str], optional) – Station subset to transform.

  • lazy (bool, optional) – If True (default), register deferred transforms. If False, apply immediately.

  • inplace (bool, optional) – If True, mutate this tree. Otherwise return a transformed copy.

Returns:

Tree with registered or applied transforms.

Return type:

MTData

Raises:

TypeError – If lazy is False and transform does not return an xr.Dataset.

Examples

>>> def keep_short_periods(ds):
...     return ds.sel(period=ds.period <= 10.0)
>>> out = tree.map_stations(keep_short_periods, lazy=False, inplace=False)
property metadata_cache: dict[str, dict[str, Any]]

In-memory metadata map keyed by station path for cache mode.

property mt_stations: MTStations

Convenience accessor for station locations represented by the tree.

property n_stations: int

Total number of stations in the collection.

persist(station_paths: list[str] | None = None, scheduler: str | None = None) MTData[source]

Alias for compute().

Parameters:
  • station_paths (list[str], optional) – Station paths to realize.

  • scheduler (str, optional) – Dask scheduler name.

Returns:

The current tree instance.

Return type:

MTData

plot_mt_response(station_key: str | list[str] | None = None, station_id: str | list[str] | None = None, survey_id: str | list[str] | None = None, **kwargs: Any) PlotMultipleResponses | Any[source]

Plot MT response for one or more stations.

Parameters:
  • station_key (str, list of str, optional) – Station key(s) in canonical or accepted alternate form.

  • station_id (str, list of str, optional) – Station ID(s). When provided without survey_id, each station ID must be unique across surveys.

  • survey_id (str, list of str, optional) – Survey ID(s) used with station_id. If list-valued, must align one-to-one with station_id.

  • **kwargs (dict) – Additional plotting keyword arguments.

Returns:

Multi-station response plot for list-valued selectors, otherwise a single-station MT response plot object.

Return type:

PlotMultipleResponses or plot object

Raises:
  • ValueError – If list-valued survey_id does not match list-valued station_id, or if station selection is ambiguous.

  • KeyError – If a requested station cannot be resolved.

Examples

>>> tree.plot_mt_response(station_key="survey_a/st01")
>>> tree.plot_mt_response(station_id="st01", survey_id="survey_a")
>>> tree.plot_mt_response(
...     station_id=["st01", "st02"],
...     survey_id=["survey_a", "survey_b"],
... )
plot_penetration_depth_1d(station_key: str | None = None, station_id: str | None = None, survey_id: str | None = None, **kwargs: Any) Any[source]

Plot 1D penetration depth.

Parameters:
  • station_key (str, optional) – Station key in canonical or accepted alternate form.

  • station_id (str, optional) – Station ID.

  • survey_id (str, optional) – Survey ID used to disambiguate duplicate station IDs.

  • **kwargs (dict) – Additional plotting keyword arguments.

Returns:

Penetration depth plot object

Return type:

plot object

Raises:
  • ValueError – If station selection is ambiguous.

  • KeyError – If the station cannot be resolved.

Notes

Based on Niblett-Bostick transformation

Examples

>>> tree.plot_penetration_depth_1d(station_key="survey_a/st01")
>>> tree.plot_penetration_depth_1d(
...     station_id="st01", survey_id="survey_a", depth_units="km"
... )
plot_penetration_depth_map(**kwargs: Any) PlotPenetrationDepthMap[source]

Plot penetration depth in map view.

Parameters:

**kwargs (dict) – Additional plotting keyword arguments.

Returns:

Penetration depth map plot object

Return type:

PlotPenetrationDepthMap

Examples

>>> tree.plot_penetration_depth_map(plot_period=10)
>>> tree.plot_penetration_depth_map(depth_units="km")
plot_phase_tensor(station_key: str | None = None, station_id: str | None = None, survey_id: str | None = None, **kwargs: Any) Any[source]

Plot phase tensor elements for a station.

Parameters:
  • station_key (str, optional) – Station key in canonical or accepted alternate form.

  • station_id (str, optional) – Station ID.

  • survey_id (str, optional) – Survey ID used to disambiguate duplicate station IDs.

  • **kwargs (dict) – Additional plotting keyword arguments.

Returns:

Phase tensor plot object

Return type:

plot object

Raises:
  • ValueError – If station selection is ambiguous.

  • KeyError – If the station cannot be resolved.

Examples

>>> tree.plot_phase_tensor(station_key="survey_a/st01")
>>> tree.plot_phase_tensor(station_id="st01", survey_id="survey_a")
plot_phase_tensor_map(**kwargs: Any) PlotPhaseTensorMaps[source]

Plot phase tensor maps.

Parameters:

**kwargs (dict) – Additional plotting keyword arguments.

Returns:

Phase tensor map plot object

Return type:

PlotPhaseTensorMaps

Examples

>>> tree.plot_phase_tensor_map(plot_period=10)
>>> tree.plot_phase_tensor_map(plot_station=True)
plot_phase_tensor_pseudosection(mt_data: 'MTData' | None = None, **kwargs: Any) PlotPhaseTensorPseudoSection[source]

Plot phase tensor pseudosection.

Parameters:
  • mt_data (MTData, optional) – MTData object to plot. Defaults to self.

  • **kwargs (dict) – Additional plotting keyword arguments.

Returns:

Pseudosection plot object

Return type:

PlotPhaseTensorPseudoSection

Examples

>>> tree.plot_phase_tensor_pseudosection()
>>> subset = tree.get_survey("survey_a")
>>> tree.plot_phase_tensor_pseudosection(mt_data=subset)
plot_residual_phase_tensor_maps(survey_01: str, survey_02: str, **kwargs: Any) PlotResidualPTMaps[source]

Plot residual phase tensor maps.

Parameters:
  • survey_01 (str) – First survey ID.

  • survey_02 (str) – Second survey ID.

  • **kwargs (dict) – Additional plotting keyword arguments.

Returns:

Residual phase tensor map plot object

Return type:

PlotResidualPTMaps

Raises:

KeyError – If either survey ID is not present in the current MTData.

Examples

>>> tree.plot_residual_phase_tensor_maps("survey_a", "survey_b")
>>> tree.plot_residual_phase_tensor_maps(
...     "survey_a", "survey_b", plot_freq=1.0
... )
plot_resistivity_phase_maps(**kwargs: Any) PlotResPhaseMaps[source]

Plot apparent resistivity and/or phase maps.

Parameters:

**kwargs (dict) – Additional plotting keyword arguments.

Returns:

Resistivity/phase map plot object

Return type:

PlotResPhaseMaps

Examples

>>> tree.plot_resistivity_phase_maps(plot_period=10)
>>> tree.plot_resistivity_phase_maps(plot_xy=True, plot_yx=False)
plot_resistivity_phase_pseudosections(**kwargs: Any) PlotResPhasePseudoSection[source]

Plot resistivity and phase pseudosections.

Parameters:

**kwargs (dict) – Additional plotting keyword arguments.

Returns:

Pseudosection plot object

Return type:

PlotResPhasePseudoSection

Examples

>>> tree.plot_resistivity_phase_pseudosections()
>>> tree.plot_resistivity_phase_pseudosections(interpolation_method="nearest")
plot_stations(map_epsg: int = 4326, bounding_box: tuple[float, float, float, float] | None = None, model_locations: bool = False, **kwargs: Any) PlotStations[source]

Plot station locations on a map.

Parameters:
  • map_epsg (int, optional) – EPSG code forwarded to PlotStations as map_epsg.

  • bounding_box (tuple of float, optional) – Optional (lon_min, lon_max, lat_min, lat_max) used to subset stations before plotting.

  • model_locations (bool, optional) – Use model coordinates instead of geographic coordinates.

  • **kwargs (dict) – Additional plotting keyword arguments.

Returns:

Station plot object

Return type:

PlotStations

Raises:

ValueError – If bounding_box is provided and does not contain four values.

Examples

>>> tree.plot_stations()
>>> tree.plot_stations(map_epsg=3857)
>>> tree.plot_stations(bounding_box=(-121.5, -120.0, 36.5, 38.0))
plot_strike(**kwargs: Any) PlotStrike[source]

Plot strike angle.

Parameters:

**kwargs (dict) – Additional plotting keyword arguments.

Returns:

Strike plot object

Return type:

PlotStrike

Examples

>>> tree.plot_strike()
>>> tree.plot_strike(show_plot=False)
plot_tipper_map(**kwargs: Any) PlotPhaseTensorMaps[source]

Plot tipper (induction vector) maps.

Parameters:

**kwargs (dict) – Additional plotting keyword arguments. Defaults are plot_pt=False and plot_tipper='yri' when not explicitly provided.

Returns:

Tipper map plot object

Return type:

PlotPhaseTensorMaps

Examples

>>> tree.plot_tipper_map()
>>> tree.plot_tipper_map(plot_tipper="yri", plot_pt=False)
project_stations_on_topography(model_object: Any, air_resistivity: float = 1000000000000.0, sea_resistivity: float = 0.3, ocean_bottom: bool = False) None[source]

Project station elevations to model topography and sync to tree.

query_station_paths(survey: str | None = None, lat_min: float | None = None, lat_max: float | None = None, lon_min: float | None = None, lon_max: float | None = None, period_min: float | None = None, period_max: float | None = None) list[str][source]

Return station tree paths matching filter criteria via the index.

Requires the index to be enabled (use_index=True or after calling rebuild_index()).

Parameters:
  • survey – See MTDataTreeIndexStore.query_station_paths().

  • lat_min – See MTDataTreeIndexStore.query_station_paths().

  • lat_max – See MTDataTreeIndexStore.query_station_paths().

  • lon_min – See MTDataTreeIndexStore.query_station_paths().

  • lon_max – See MTDataTreeIndexStore.query_station_paths().

  • period_min – See MTDataTreeIndexStore.query_station_paths().

  • period_max – See MTDataTreeIndexStore.query_station_paths().

Return type:

list[str]

rebuild_index(index_db_path: str = ':memory:') None[source]

Build or replace the station index from the current tree contents.

Enables the index if it was not already active.

Parameters:

index_db_path (str) – SQLite database path. Defaults to ":memory:" (in-process).

rechunk(chunks: dict[str, int] | str | None, station_paths: list[str] | None = None, variables: list[str] | None = None, inplace: bool = True) MTData[source]

Rechunk station datasets.

Parameters:
  • chunks (dict[str, int] or str or None) – Chunk specification passed to as_dask().

  • station_paths (list[str], optional) – Subset of station paths to rechunk.

  • variables (list[str], optional) – Data variables to rechunk.

  • inplace (bool, optional) – If True (default), modify the current tree.

Returns:

Rechunked tree.

Return type:

MTData

remove_station(station_key: str) None[source]

Remove one station node and its cached/indexed metadata.

Parameters:

station_key (str) – Station identifier in canonical tree-path, survey/station, or survey.station form.

rotate(rotation_angle: float | np.ndarray, inplace: bool = True) 'MTData' | None[source]

Rotate all station transfer functions.

Parameters:
  • rotation_angle (float or ndarray) – Scalar rotation angle in degrees or per-period angle array.

  • inplace (bool, optional) – If True (default), mutate this tree and return None.

Returns:

Rotated copy when inplace is False; otherwise None.

Return type:

MTData or None

rotate_dask(rotation_angle: float | ndarray, chunks: dict[str, int] | str | None = None, scheduler: str | None = None, compute: bool = True, inplace: bool = False) MTData[source]

Rotate stations using dask-delayed execution.

Parameters:
  • rotation_angle (float or ndarray) – Rotation angle in degrees, scalar or per-period array.

  • chunks (dict[str, int] or str or None, optional) – Optional chunking applied before creating delayed transforms.

  • scheduler (str, optional) – Dask scheduler used when compute is True.

  • compute (bool, optional) – If True (default), execute delayed transforms immediately.

  • inplace (bool, optional) – If True, modify this tree.

Returns:

Tree with rotated results or pending delayed transforms.

Return type:

MTData

rotate_stations(rotation_angle: float) None[source]

Rotate station model coordinates and sync to the tree.

property short_station_paths: list[str]

Return sorted station paths in survey/station form.

property station_locations: DataFrame

Station-location table built directly from tree dataset attrs.

property station_paths: list[str]

Return sorted station paths present in the tree.

property survey_ids: list[str]

Unique survey IDs in the collection.

property survey_names: list[str]

Return sorted survey names inferred from station paths.

to_csv(csv_fn: str | Path, geometry: bool = False) None[source]

Write station locations to CSV via MTStations.

to_dataframe(utm_crs: None | Any = None, cols: list[str] | None = None, impedance_units: str = 'mt') DataFrame[source]

Convert all stations to a concatenated pandas DataFrame.

Parameters:
  • utm_crs (Any, optional) – CRS override used when exporting station locations.

  • cols (list[str], optional) – Column subset to include.

  • impedance_units (str, optional) – Impedance unit convention for exported transfer-function values.

Returns:

Concatenated station dataframe.

Return type:

pandas.DataFrame

to_geo_df(model_locations: bool = False, data_type: str = 'station_locations') Any[source]

Create a GeoDataFrame for GIS workflows.

Parameters:
  • model_locations (bool, optional) – If True, use model_east/model_north as geometry. Otherwise use longitude/latitude.

  • data_type (str, optional) – One of 'station_locations' (or 'stations'), 'pt', 'tipper', or 'both'.

Returns:

GeoDataFrame with point geometries.

Return type:

geopandas.GeoDataFrame

Raises:
  • ImportError – If geopandas is not installed.

  • ValueError – If data_type is unsupported.

to_geopd() Any[source]

Return station locations as a GeoDataFrame via MTStations.

to_modem(data_filename: str | Path | None = None, **kwargs: Any) Any[source]

Create a ModEM Data object from the station collection.

Parameters:
  • data_filename (str or pathlib.Path, optional) – Path to write the ModEM data file. When None (default) the file is not written.

  • **kwargs – Additional keyword arguments forwarded to mtpy.modeling.modem.Data (e.g. rotation_angle, inv_mode, formatting).

Returns:

Populated ModEM Data object with z_model_error and t_model_error set from the tree.

Return type:

mtpy.modeling.modem.Data

Examples

Create a data file and retrieve the Data object:

>>> from mtpy.core import MTData
>>> tree = MTData()
>>> # tree.add_station(...)  # populate with MT objects first
>>> tree.model_parameters = {"inv_mode": "1", "formatting": "1"}
>>> modem_data = tree.to_modem(data_filename="ModEM_data.dat")
>>> print(modem_data.center_point.latitude)
to_mt_dataframe(utm_crs: None | Any = None, impedance_units: str = 'mt') MTDataFrame[source]

Create an MTDataFrame from all stations.

Parameters:
  • utm_crs (Any, optional) – CRS override used during dataframe conversion.

  • impedance_units (str, optional) – Impedance unit convention for exported values.

Returns:

MTDataFrame wrapping the concatenated station dataframe.

Return type:

MTDataFrame

to_mt_stations() MTStations[source]

Build an MTStations view from current station locations.

Returns:

Station-location container backed by self.station_locations.

Return type:

MTStations

to_occam2d(data_filename: str | Path | None = None, **kwargs: Any) Any[source]

Create an Occam2D data object from the station collection.

Parameters:
  • data_filename (str or pathlib.Path, optional) – Path to write the Occam2D data file. When None (default) the file is not written.

  • **kwargs – Additional keyword arguments forwarded to mtpy.modeling.occam2d.Occam2DData (e.g. model_mode, profile_angle, res_te_err).

Returns:

Populated Occam2D data object with profile_origin set from center_point when not supplied via kwargs.

Return type:

mtpy.modeling.occam2d.Occam2DData

Notes

All information is derived from the station dataframe. The user should create the profile, interpolate, and estimate model errors from the tree before calling this method.

Examples

>>> from mtpy.core import MTData
>>> tree = MTData()
>>> # tree.add_station(...)  # populate first
>>> occam_data = tree.to_occam2d(
...     data_filename="OccamDataFile.dat", model_mode="5"
... )
to_shp(shp_fn: str | Path) str | Path[source]

Write a station-location shapefile via MTStations.

to_shp_pt_tipper(save_dir: str | Path, output_crs: None | Any = None, utm: bool = False, pt: bool = True, tipper: bool = True, periods: ndarray | None = None, period_tol: float | None = None, ellipse_size: float | None = None, arrow_size: float | None = None) dict[str, list[str]][source]

Write phase-tensor and tipper shapefiles.

Parameters:
  • save_dir (str or pathlib.Path) – Output directory for shapefiles.

  • output_crs (Any, optional) – Output coordinate reference system.

  • utm (bool, optional) – If True, export in UTM coordinates.

  • pt (bool, optional) – If True, write phase-tensor shapefiles.

  • tipper (bool, optional) – If True, write tipper shapefiles.

  • periods (numpy.ndarray, optional) – Periods to export. When None, use all available periods.

  • period_tol (float, optional) – Period matching tolerance.

  • ellipse_size (float, optional) – Phase-tensor ellipse size. When None and pt is True, the size is estimated automatically.

  • arrow_size (float, optional) – Tipper arrow size. When None and tipper is True, the size is estimated automatically.

Returns:

Mapping of output type to written shapefile paths.

Return type:

dict[str, list[str]]

Notes

For mixed station period sampling, interpolate first so all stations share a common period set.

to_simpeg_2d(**kwargs: Any) Any[source]

Create a SimPEG 2-D MT data object from the station collection.

Parameters:

**kwargs

Additional keyword arguments forwarded to mtpy.modeling.simpeg.data_2d.Simpeg2DData. Common options include:

include_elevationbool

Include station elevation in the receiver locations, by default True.

invert_tebool

Include TE-mode apparent resistivity and phase, by default True.

invert_tmbool

Include TM-mode apparent resistivity and phase, by default True.

Returns:

Populated SimPEG 2-D data object.

Return type:

mtpy.modeling.simpeg.data_2d.Simpeg2DData

Notes

The impedance units are converted to 'ohm' automatically. The user should create the profile, interpolate, and estimate model errors from the tree before calling this method.

Examples

>>> from mtpy.core import MTData
>>> tree = MTData()
>>> # tree.add_station(...)  # populate first
>>> simpeg_2d = tree.to_simpeg_2d(invert_te=True, invert_tm=False)
to_simpeg_3d(**kwargs: Any) Any[source]

Create a SimPEG 3-D MT data object from the station collection.

Parameters:

**kwargs

Additional keyword arguments forwarded to mtpy.modeling.simpeg.data_3d.Simpeg3DData. Common options include:

include_elevationbool

Include station elevation in the receiver locations, by default False.

geographic_coordinatesbool

Use geographic (UTM) coordinates instead of model-relative coordinates, by default True.

invert_z_xx, invert_z_xy, invert_z_yx, invert_z_yybool

Select which impedance tensor components to include, all default to True.

invert_t_zx, invert_t_zybool

Select which tipper components to include, both default to True.

Returns:

Populated SimPEG 3-D data object.

Return type:

mtpy.modeling.simpeg.data_3d.Simpeg3DData

Notes

The impedance units are converted to 'ohm' automatically. The user should interpolate and estimate model errors from the tree before calling this method.

Examples

>>> from mtpy.core import MTData
>>> tree = MTData()
>>> # tree.add_station(...)  # populate first
>>> simpeg_3d = tree.to_simpeg_3d(invert_z_yy=False, include_elevation=True)
to_vtk(vtk_fn: str | Path | None = None, vtk_save_path: str | Path | None = None, vtk_fn_basename: str = 'ModEM_stations', geographic: bool = False, shift_east: float = 0, shift_north: float = 0, shift_elev: float = 0, units: str = 'km', coordinate_system: str = 'nez+') Path[source]

Write a station-location VTK file via MTStations.

property utm_crs: Any | None

Return the root UTM CRS/EPSG value used for station projections.

property utm_epsg: int | None

Return the root UTM EPSG code when available.