mtpy.core package

Subpackages

Submodules

mtpy.core.mt module

class mtpy.core.mt.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})

mtpy.core.mt_collection module

Collection of MT stations

Created on Mon Jan 11 15:36:38 2021

copyright:

Jared Peacock (jpeacock@usgs.gov)

license:

MIT

class mtpy.core.mt_collection.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

mtpy.core.mt_data module

Scaffold for a tree-backed MT data container.

This class is an outline for migrating from OrderedDict-based MTData to an Xarray tree representation for better scalability.

class mtpy.core.mt_data.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.

model_parameters: dict[str, Any]
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.

mtpy.core.mt_dataframe module

Created on Sun Oct 2 13:20:28 2022

@author: jpeacock

class mtpy.core.mt_dataframe.MTDataFrame(data: dict | np.ndarray | pd.DataFrame | 'MTDataFrame' | None = None, n_entries: int = 0, **kwargs: Any)[source]

Bases: object

DataFrame for a single MT station.

Parameters:
  • data (dict, np.ndarray, pd.DataFrame, MTDataFrame, or None, optional) – Initial data to populate the dataframe, by default None

  • n_entries (int, optional) – Number of empty entries to create if data is None, by default 0

  • **kwargs (dict) – Additional keyword arguments for setting attributes

dataframe

Pandas DataFrame containing MT data with standardized columns

Type:

pd.DataFrame

working_survey

Current working survey name

Type:

str or None

working_station

Current working station name

Type:

str or None

Notes

Tried subclassing pandas.DataFrame, but that turned out to not be straightforward, so went with composition instead.

property datum_epsg: str | None

Datum EPSG code.

Returns:

EPSG code string, or None if no data

Return type:

str or None

property east: float | None

Station easting coordinate in meters.

Returns:

Easting value, or None if no data

Return type:

float or None

property elevation: float | None

Station elevation in meters.

Returns:

Elevation value, or None if no data

Return type:

float or None

property for_shapefiles: DataFrame

DataFrame formatted for shapefile export.

Returns:

DataFrame with location, phase tensor, and tipper attributes

Return type:

pd.DataFrame

property frequency: ndarray | None

Array of unique frequencies in Hz.

Returns:

Array of frequency values (1/period), or None if no data

Return type:

np.ndarray or None

from_t_object(t_object: Tipper) None[source]

Fill dataframe from a Tipper object.

Parameters:

t_object (Tipper) – Tipper object containing tipper data

Notes

Populates tipper magnitude, angle, and component columns

from_z_object(z_object: Z) None[source]

Fill dataframe from a Z impedance object.

Parameters:

z_object (Z) – Z object containing impedance tensor data

Notes

Populates impedance, resistivity, phase, and phase tensor columns

get_period(period: float, tol: float | None = None) MTDataFrame[source]

Get data for a specific period or period range.

Parameters:
  • period (float) – Target period value in seconds

  • tol (float, optional) – Tolerance as a fraction (e.g., 0.05 for 5%), by default None

Returns:

New MTDataFrame containing only the requested period(s)

Return type:

MTDataFrame

get_station_df(station: str | None = None) DataFrame[source]

Get DataFrame for a single station.

Parameters:

station (str, optional) – Station name to retrieve, by default None (uses working_station)

Returns:

DataFrame filtered for the specified station

Return type:

pd.DataFrame

Raises:

ValueError – If station is not found in dataframe

get_station_distances(utm: bool = False) Series[source]

Calculate pairwise distances between stations.

Parameters:

utm (bool, optional) – If True, use UTM coordinates (east, north), otherwise use geographic coordinates (longitude, latitude), by default False

Returns:

Series of non-zero pairwise distances between stations

Return type:

pd.Series

property impedance: ndarray

Impedance tensor from dataframe.

Returns:

Impedance tensor of shape (n_periods, 2, 2)

Return type:

np.ndarray

property latitude: float | None

Station latitude in decimal degrees.

Returns:

Latitude value, or None if no data

Return type:

float or None

property longitude: float | None

Station longitude in decimal degrees.

Returns:

Longitude value, or None if no data

Return type:

float or None

property model_east: float | None

Model easting coordinate in meters.

Returns:

Model easting value, or None if no data

Return type:

float or None

property model_elevation: float | None

Model elevation in meters.

Returns:

Model elevation value, or None if no data

Return type:

float or None

property model_north: float | None

Model northing coordinate in meters.

Returns:

Model northing value, or None if no data

Return type:

float or None

property nonzero_items: int

Count number of non-zero entries in data columns.

Returns:

Number of non-zero entries excluding error columns

Return type:

int

property north: float | None

Station northing coordinate in meters.

Returns:

Northing value, or None if no data

Return type:

float or None

property period: ndarray | None

Array of unique periods in sorted order.

Returns:

Sorted array of period values, or None if no data

Return type:

np.ndarray or None

property phase_tensor: DataFrame

DataFrame with phase tensor information.

Returns:

DataFrame containing location and phase tensor attributes

Return type:

pd.DataFrame

property profile_offset: float | None

Distance along profile in meters.

Returns:

Profile offset value, or None if no data

Return type:

float or None

property size: int | None

Number of periods in the dataframe.

Returns:

Number of unique periods, or None if no data

Return type:

int or None

property station: str | None

Station name from the dataframe.

Returns:

Station name, or None if no data

Return type:

str or None

property station_locations: DataFrame

DataFrame of station location information.

Returns:

DataFrame with one row per station containing location attributes

Return type:

pd.DataFrame

property survey: str | None

Survey name from the dataframe.

Returns:

Survey name, or None if no data

Return type:

str or None

property tipper: DataFrame

DataFrame with tipper information.

Returns:

DataFrame containing location and tipper attributes

Return type:

pd.DataFrame

to_t_object() Tipper[source]

Create a Tipper object from dataframe data.

Returns:

Tipper object containing tipper data

Return type:

Tipper

to_z_object(units: str = 'mt') Z[source]

Create a Z impedance object from dataframe data.

Parameters:

units (str, optional) – Impedance units (‘mt’ or ‘ohm’), by default ‘mt’

Returns:

Z object containing impedance tensor

Return type:

Z

Notes

If impedance values are zero, attempts to reconstruct from resistivity and phase data

property utm_epsg: str | None

UTM EPSG code.

Returns:

EPSG code string, or None if no data

Return type:

str or None

mtpy.core.mt_location module

Might think about adding declination

Created on Mon Oct 3 15:04:12 2022

@author: jpeacock

class mtpy.core.mt_location.MTLocation(survey_metadata: Survey | None = None, **kwargs: Any)[source]

Bases: object

Location for a MT site or point measurement.

Parameters:
  • survey_metadata (Survey, optional) – Survey metadata object, by default None

  • **kwargs (dict) – Additional keyword arguments for location attributes

latitude

Latitude in decimal degrees

Type:

float

longitude

Longitude in decimal degrees

Type:

float

elevation

Elevation in meters

Type:

float

east

Easting coordinate in meters

Type:

float

north

Northing coordinate in meters

Type:

float

datum_crs

Datum coordinate reference system

Type:

CRS

utm_crs

UTM coordinate reference system

Type:

CRS

model_east

Model easting coordinate in meters

Type:

float

model_north

Model northing coordinate in meters

Type:

float

model_elevation

Model elevation in meters

Type:

float

profile_offset

Distance along profile in meters

Type:

float

compute_model_location(center_location: MTLocation) None[source]

Compute model coordinates relative to model center.

Parameters:

center_location (MTLocation) – Center location of the model

Notes

Sets model_east, model_north, and model_elevation relative to center

copy() MTLocation[source]

Create a deep copy of the MTLocation object.

Returns:

Deep copy of the current MTLocation object

Return type:

MTLocation

property datum_crs: CRS | None

Datum coordinate reference system.

Returns:

Datum CRS object

Return type:

CRS or None

property datum_epsg: int | None

EPSG code of the datum coordinate reference system.

Returns:

Datum EPSG code

Return type:

int or None

property datum_name: str | None

Name of the datum coordinate reference system.

Returns:

Datum CRS name

Return type:

str or None

property east: float

Easting coordinate in meters.

Returns:

Easting coordinate

Return type:

float

property elevation: float

Elevation in meters.

Returns:

Elevation above datum

Return type:

float

from_json(filename: str) None[source]

Read location information from a JSON file.

Parameters:

filename (str) – Path to input JSON file

get_elevation_from_national_map() None[source]

Get elevation from DEM data of the US National Map.

Notes

Pulls data from the USGS National Map DEM. Plan to extend this to global coverage. Updates the elevation attribute if successful.

property latitude: float

Latitude in decimal degrees.

Returns:

Latitude coordinate

Return type:

float

property longitude: float

Longitude in decimal degrees.

Returns:

Longitude coordinate

Return type:

float

property model_east: float

Model easting coordinate in meters.

Returns:

Model easting relative to model center

Return type:

float

property model_elevation: float

Model elevation in meters.

Returns:

Model elevation relative to model center

Return type:

float

property model_north: float

Model northing coordinate in meters.

Returns:

Model northing relative to model center

Return type:

float

property north: float

Northing coordinate in meters.

Returns:

Northing coordinate

Return type:

float

project_onto_profile_line(profile_slope: float, profile_intersection: float) None[source]

Project station location onto a profile line.

Parameters:
  • profile_slope (float) – Slope of the profile line

  • profile_intersection (float) – Y-intercept of the profile line

Raises:

ValueError – If utm_crs is None

Notes

Sets the profile_offset attribute with distance along profile line

to_json(filename: str) None[source]

Write location information to a JSON file.

Parameters:

filename (str) – Path to output JSON file

property utm_crs: CRS | None

UTM coordinate reference system.

Returns:

UTM CRS object

Return type:

CRS or None

property utm_epsg: int | None

EPSG code of the UTM coordinate reference system.

Returns:

UTM EPSG code

Return type:

int or None

property utm_name: str | None

Name of the UTM coordinate reference system.

Returns:

UTM CRS name

Return type:

str or None

property utm_zone: str | None

UTM zone string.

Returns:

UTM zone identifier

Return type:

str or None

mtpy.core.mt_stations module

ModEM

# Generate files for ModEM

# revised by JP 2017 # revised by AK 2017 to bring across functionality from ak branch

class mtpy.core.mt_stations.MTStations(utm_epsg: int | str | None, datum_epsg: int | str | None = None, station_locations: DataFrame | GeoDataFrame | None = None, **kwargs: Any)[source]

Bases: object

Object to deal with station location and geographic projection.

Geographic projections are done using pyproj.CRS objects.

Parameters:
  • utm_epsg (int or str) – UTM EPSG code for projection

  • datum_epsg (int or str, optional) – Datum EPSG code, by default None

  • **kwargs (dict) – Additional keyword arguments

station_locations

GeoDataFrame containing station metadata and coordinates

Type:

geopandas.GeoDataFrame

utm_crs

UTM coordinate reference system

Type:

pyproj.CRS

datum_crs

Datum coordinate reference system

Type:

pyproj.CRS

rotation_angle

Rotation angle in degrees

Type:

float

shift_east

Shift in east direction

Type:

float

shift_north

Shift in north direction

Type:

float

Notes

Takes in a list of mtpy.core.mt.MT objects which inherit mtpy.core.mt_location.MTLocation objects, which deal with transformation of point data using pyproj.

property center_point: MTLocation

Calculate the center point from the given station locations.

If _center attributes are set, that is returned as the center point.

Otherwise, looks for non-zero locations in E-N first, then Lat/Lon and estimates the center point as (max - min) / 2…

Returns:

Center point location object

Return type:

mtpy.core.MTLocation

center_stations(model_obj: Any) None[source]

Center station locations to the middle of cells.

Useful for topography as it reduces edge effects of stations close to cell edges. Recalculates rel_east, rel_north to center of model cell.

Parameters:

model_obj (mtpy.modeling.modem.Model or mtpy.modeling.Structured) – Model object

compute_relative_locations() None[source]

Calculate model station locations relative to the center point in meters.

Uses mtpy.core.MTLocation.compute_model_location to calculate the relative distance.

Notes

Computes in place.

copy() MTStations[source]

Create a deep copy of the MTStations object.

Returns:

Deep copy of MTStation object

Return type:

MTStations

Notes

At the moment this is very slow because it is making a lot of deep copies. Use sparingly.

property datum_crs: CRS | None

Datum coordinate reference system.

Returns:

Datum CRS object

Return type:

pyproj.CRS or None

property datum_epsg: int | None

Datum EPSG code.

Returns:

Datum EPSG number

Return type:

int or None

property datum_name: str | None

Datum coordinate reference system name.

Returns:

Datum well known name

Return type:

str or None

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

Estimate a profile from the data.

Parameters:

units (str, optional) – Units for coordinates (“deg” or “m”), by default “deg”

Returns:

  • x1 (float) – First x coordinate of profile line

  • y1 (float) – First y coordinate of profile line

  • x2 (float) – Second x coordinate of profile line

  • y2 (float) – Second y coordinate of profile line

  • profile_line (dict) – Dictionary with “slope” and “intercept” keys defining the profile line

Raises:

ValueError – If units is “m” but no UTM CRS is set

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

Estimate a profile line from a given geoelectric strike.

Parameters:
  • strike (float) – Geoelectric strike angle in degrees

  • units (str, optional) – Units for coordinates (“deg” or “m”), by default “deg”

Returns:

  • x1 (float) – First x coordinate of profile line

  • y1 (float) – First y coordinate of profile line

  • x2 (float) – Second x coordinate of profile line

  • y2 (float) – Second y coordinate of profile line

  • profile_line (dict) – Dictionary with “slope” and “intercept” keys defining the profile line

Raises:

ValueError – If units is “m” but no UTM CRS is set

property model_epsg: int | None

Model EPSG code.

Returns:

Model EPSG number from the model_crs object

Return type:

int or None

project_stations_on_topography(model_object: Any, air_resistivity: float = 1000000000000.0, sea_resistivity: float = 0.3, ocean_bottom: bool = False) None[source]

Project stations on topography of a given model.

Parameters:
  • model_object (mtpy.modeling.modem.Model) – Model object

  • air_resistivity (float, optional) – Resistivity value of air cells in the model, by default 1e12

  • sea_resistivity (float, optional) – Resistivity of sea water, by default 0.3

  • ocean_bottom (bool, optional) – If True places stations at bottom of sea cells, by default False

rotate_stations(rotation_angle: float) None[source]

Rotate stations model positions only.

Assumes N is 0 and east is 90.

Parameters:

rotation_angle (float) – Rotation angle in degrees assuming N=0, E=90. Positive clockwise

Notes

Computes in place and rotates according to already set rotation angle. Therefore if the station locations have already been rotated, the function will rotate the already rotated stations. For example, if you rotate the stations 15 degrees, then again by 20 degrees, the resulting station locations will be 35 degrees rotated from the original locations.

property station_locations: DataFrame | None

Station locations dataframe.

Returns:

Dataframe of station location information

Return type:

pandas.DataFrame or None

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

Write a CSV file of the station locations.

Parameters:
  • csv_fn (str or Path) – Full path to new CSV file

  • geometry (bool, optional) – Whether to include geometry column, by default False

to_geopd() GeoDataFrame[source]

Create a geopandas dataframe.

Returns:

GeoDataFrame with points from latitude and longitude

Return type:

geopandas.GeoDataFrame

to_shp(shp_fn: str | Path) str | Path[source]

Write a shapefile of the station locations.

Uses geopandas which only takes in epsg numbers.

Parameters:

shp_fn (str or Path) – Full path to new shapefile

Returns:

Path to the created shapefile

Return type:

str or Path

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 VTK file for plotting in 3D like Paraview.

Parameters:
  • vtk_fn (str or Path, optional) – Full path to VTK file to be written, by default None

  • vtk_save_path (str or Path, optional) – Directory to save VTK file to, by default None

  • vtk_fn_basename (str, optional) – Filename basename of VTK file, note that .vtr extension is added, by default “ModEM_stations”

  • geographic (bool, optional) – Use geographic coordinates, by default False

  • shift_east (float, optional) – Shift in east direction, by default 0

  • shift_north (float, optional) – Shift in north direction, by default 0

  • shift_elev (float, optional) – Shift in elevation, by default 0

  • units (str, optional) – Units for coordinates (“km”, “m”, or “ft”), by default “km”

  • coordinate_system (str, optional) – Coordinate system (“nez+” or “enz-“), by default “nez+”

Returns:

Full path to VTK file

Return type:

Path

Raises:

ValueError – If vtk_save_path is None when vtk_fn is None

property utm_crs: CRS | None

UTM coordinate reference system.

Returns:

UTM CRS object

Return type:

pyproj.CRS or None

property utm_epsg: int | None

UTM EPSG code.

Returns:

UTM EPSG number

Return type:

int or None

property utm_name: str | None

UTM coordinate reference system name.

Returns:

UTM CRS name

Return type:

str or None

property utm_zone: str | None

UTM zone.

Returns:

UTM Zone number

Return type:

str or None

Module contents

class mtpy.core.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.

model_parameters: dict[str, Any]
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.

class mtpy.core.MTDataFrame(data: dict | np.ndarray | pd.DataFrame | 'MTDataFrame' | None = None, n_entries: int = 0, **kwargs: Any)[source]

Bases: object

DataFrame for a single MT station.

Parameters:
  • data (dict, np.ndarray, pd.DataFrame, MTDataFrame, or None, optional) – Initial data to populate the dataframe, by default None

  • n_entries (int, optional) – Number of empty entries to create if data is None, by default 0

  • **kwargs (dict) – Additional keyword arguments for setting attributes

dataframe

Pandas DataFrame containing MT data with standardized columns

Type:

pd.DataFrame

working_survey

Current working survey name

Type:

str or None

working_station

Current working station name

Type:

str or None

Notes

Tried subclassing pandas.DataFrame, but that turned out to not be straightforward, so went with composition instead.

property datum_epsg: str | None

Datum EPSG code.

Returns:

EPSG code string, or None if no data

Return type:

str or None

property east: float | None

Station easting coordinate in meters.

Returns:

Easting value, or None if no data

Return type:

float or None

property elevation: float | None

Station elevation in meters.

Returns:

Elevation value, or None if no data

Return type:

float or None

property for_shapefiles: DataFrame

DataFrame formatted for shapefile export.

Returns:

DataFrame with location, phase tensor, and tipper attributes

Return type:

pd.DataFrame

property frequency: ndarray | None

Array of unique frequencies in Hz.

Returns:

Array of frequency values (1/period), or None if no data

Return type:

np.ndarray or None

from_t_object(t_object: Tipper) None[source]

Fill dataframe from a Tipper object.

Parameters:

t_object (Tipper) – Tipper object containing tipper data

Notes

Populates tipper magnitude, angle, and component columns

from_z_object(z_object: Z) None[source]

Fill dataframe from a Z impedance object.

Parameters:

z_object (Z) – Z object containing impedance tensor data

Notes

Populates impedance, resistivity, phase, and phase tensor columns

get_period(period: float, tol: float | None = None) MTDataFrame[source]

Get data for a specific period or period range.

Parameters:
  • period (float) – Target period value in seconds

  • tol (float, optional) – Tolerance as a fraction (e.g., 0.05 for 5%), by default None

Returns:

New MTDataFrame containing only the requested period(s)

Return type:

MTDataFrame

get_station_df(station: str | None = None) DataFrame[source]

Get DataFrame for a single station.

Parameters:

station (str, optional) – Station name to retrieve, by default None (uses working_station)

Returns:

DataFrame filtered for the specified station

Return type:

pd.DataFrame

Raises:

ValueError – If station is not found in dataframe

get_station_distances(utm: bool = False) Series[source]

Calculate pairwise distances between stations.

Parameters:

utm (bool, optional) – If True, use UTM coordinates (east, north), otherwise use geographic coordinates (longitude, latitude), by default False

Returns:

Series of non-zero pairwise distances between stations

Return type:

pd.Series

property impedance: ndarray

Impedance tensor from dataframe.

Returns:

Impedance tensor of shape (n_periods, 2, 2)

Return type:

np.ndarray

property latitude: float | None

Station latitude in decimal degrees.

Returns:

Latitude value, or None if no data

Return type:

float or None

property longitude: float | None

Station longitude in decimal degrees.

Returns:

Longitude value, or None if no data

Return type:

float or None

property model_east: float | None

Model easting coordinate in meters.

Returns:

Model easting value, or None if no data

Return type:

float or None

property model_elevation: float | None

Model elevation in meters.

Returns:

Model elevation value, or None if no data

Return type:

float or None

property model_north: float | None

Model northing coordinate in meters.

Returns:

Model northing value, or None if no data

Return type:

float or None

property nonzero_items: int

Count number of non-zero entries in data columns.

Returns:

Number of non-zero entries excluding error columns

Return type:

int

property north: float | None

Station northing coordinate in meters.

Returns:

Northing value, or None if no data

Return type:

float or None

property period: ndarray | None

Array of unique periods in sorted order.

Returns:

Sorted array of period values, or None if no data

Return type:

np.ndarray or None

property phase_tensor: DataFrame

DataFrame with phase tensor information.

Returns:

DataFrame containing location and phase tensor attributes

Return type:

pd.DataFrame

property profile_offset: float | None

Distance along profile in meters.

Returns:

Profile offset value, or None if no data

Return type:

float or None

property size: int | None

Number of periods in the dataframe.

Returns:

Number of unique periods, or None if no data

Return type:

int or None

property station: str | None

Station name from the dataframe.

Returns:

Station name, or None if no data

Return type:

str or None

property station_locations: DataFrame

DataFrame of station location information.

Returns:

DataFrame with one row per station containing location attributes

Return type:

pd.DataFrame

property survey: str | None

Survey name from the dataframe.

Returns:

Survey name, or None if no data

Return type:

str or None

property tipper: DataFrame

DataFrame with tipper information.

Returns:

DataFrame containing location and tipper attributes

Return type:

pd.DataFrame

to_t_object() Tipper[source]

Create a Tipper object from dataframe data.

Returns:

Tipper object containing tipper data

Return type:

Tipper

to_z_object(units: str = 'mt') Z[source]

Create a Z impedance object from dataframe data.

Parameters:

units (str, optional) – Impedance units (‘mt’ or ‘ohm’), by default ‘mt’

Returns:

Z object containing impedance tensor

Return type:

Z

Notes

If impedance values are zero, attempts to reconstruct from resistivity and phase data

property utm_epsg: str | None

UTM EPSG code.

Returns:

EPSG code string, or None if no data

Return type:

str or None

class mtpy.core.MTLocation(survey_metadata: Survey | None = None, **kwargs: Any)[source]

Bases: object

Location for a MT site or point measurement.

Parameters:
  • survey_metadata (Survey, optional) – Survey metadata object, by default None

  • **kwargs (dict) – Additional keyword arguments for location attributes

latitude

Latitude in decimal degrees

Type:

float

longitude

Longitude in decimal degrees

Type:

float

elevation

Elevation in meters

Type:

float

east

Easting coordinate in meters

Type:

float

north

Northing coordinate in meters

Type:

float

datum_crs

Datum coordinate reference system

Type:

CRS

utm_crs

UTM coordinate reference system

Type:

CRS

model_east

Model easting coordinate in meters

Type:

float

model_north

Model northing coordinate in meters

Type:

float

model_elevation

Model elevation in meters

Type:

float

profile_offset

Distance along profile in meters

Type:

float

compute_model_location(center_location: MTLocation) None[source]

Compute model coordinates relative to model center.

Parameters:

center_location (MTLocation) – Center location of the model

Notes

Sets model_east, model_north, and model_elevation relative to center

copy() MTLocation[source]

Create a deep copy of the MTLocation object.

Returns:

Deep copy of the current MTLocation object

Return type:

MTLocation

property datum_crs: CRS | None

Datum coordinate reference system.

Returns:

Datum CRS object

Return type:

CRS or None

property datum_epsg: int | None

EPSG code of the datum coordinate reference system.

Returns:

Datum EPSG code

Return type:

int or None

property datum_name: str | None

Name of the datum coordinate reference system.

Returns:

Datum CRS name

Return type:

str or None

property east: float

Easting coordinate in meters.

Returns:

Easting coordinate

Return type:

float

property elevation: float

Elevation in meters.

Returns:

Elevation above datum

Return type:

float

from_json(filename: str) None[source]

Read location information from a JSON file.

Parameters:

filename (str) – Path to input JSON file

get_elevation_from_national_map() None[source]

Get elevation from DEM data of the US National Map.

Notes

Pulls data from the USGS National Map DEM. Plan to extend this to global coverage. Updates the elevation attribute if successful.

property latitude: float

Latitude in decimal degrees.

Returns:

Latitude coordinate

Return type:

float

property longitude: float

Longitude in decimal degrees.

Returns:

Longitude coordinate

Return type:

float

property model_east: float

Model easting coordinate in meters.

Returns:

Model easting relative to model center

Return type:

float

property model_elevation: float

Model elevation in meters.

Returns:

Model elevation relative to model center

Return type:

float

property model_north: float

Model northing coordinate in meters.

Returns:

Model northing relative to model center

Return type:

float

property north: float

Northing coordinate in meters.

Returns:

Northing coordinate

Return type:

float

project_onto_profile_line(profile_slope: float, profile_intersection: float) None[source]

Project station location onto a profile line.

Parameters:
  • profile_slope (float) – Slope of the profile line

  • profile_intersection (float) – Y-intercept of the profile line

Raises:

ValueError – If utm_crs is None

Notes

Sets the profile_offset attribute with distance along profile line

to_json(filename: str) None[source]

Write location information to a JSON file.

Parameters:

filename (str) – Path to output JSON file

property utm_crs: CRS | None

UTM coordinate reference system.

Returns:

UTM CRS object

Return type:

CRS or None

property utm_epsg: int | None

EPSG code of the UTM coordinate reference system.

Returns:

UTM EPSG code

Return type:

int or None

property utm_name: str | None

Name of the UTM coordinate reference system.

Returns:

UTM CRS name

Return type:

str or None

property utm_zone: str | None

UTM zone string.

Returns:

UTM zone identifier

Return type:

str or None

class mtpy.core.MTStations(utm_epsg: int | str | None, datum_epsg: int | str | None = None, station_locations: DataFrame | GeoDataFrame | None = None, **kwargs: Any)[source]

Bases: object

Object to deal with station location and geographic projection.

Geographic projections are done using pyproj.CRS objects.

Parameters:
  • utm_epsg (int or str) – UTM EPSG code for projection

  • datum_epsg (int or str, optional) – Datum EPSG code, by default None

  • **kwargs (dict) – Additional keyword arguments

station_locations

GeoDataFrame containing station metadata and coordinates

Type:

geopandas.GeoDataFrame

utm_crs

UTM coordinate reference system

Type:

pyproj.CRS

datum_crs

Datum coordinate reference system

Type:

pyproj.CRS

rotation_angle

Rotation angle in degrees

Type:

float

shift_east

Shift in east direction

Type:

float

shift_north

Shift in north direction

Type:

float

Notes

Takes in a list of mtpy.core.mt.MT objects which inherit mtpy.core.mt_location.MTLocation objects, which deal with transformation of point data using pyproj.

property center_point: MTLocation

Calculate the center point from the given station locations.

If _center attributes are set, that is returned as the center point.

Otherwise, looks for non-zero locations in E-N first, then Lat/Lon and estimates the center point as (max - min) / 2…

Returns:

Center point location object

Return type:

mtpy.core.MTLocation

center_stations(model_obj: Any) None[source]

Center station locations to the middle of cells.

Useful for topography as it reduces edge effects of stations close to cell edges. Recalculates rel_east, rel_north to center of model cell.

Parameters:

model_obj (mtpy.modeling.modem.Model or mtpy.modeling.Structured) – Model object

compute_relative_locations() None[source]

Calculate model station locations relative to the center point in meters.

Uses mtpy.core.MTLocation.compute_model_location to calculate the relative distance.

Notes

Computes in place.

copy() MTStations[source]

Create a deep copy of the MTStations object.

Returns:

Deep copy of MTStation object

Return type:

MTStations

Notes

At the moment this is very slow because it is making a lot of deep copies. Use sparingly.

property datum_crs: CRS | None

Datum coordinate reference system.

Returns:

Datum CRS object

Return type:

pyproj.CRS or None

property datum_epsg: int | None

Datum EPSG code.

Returns:

Datum EPSG number

Return type:

int or None

property datum_name: str | None

Datum coordinate reference system name.

Returns:

Datum well known name

Return type:

str or None

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

Estimate a profile from the data.

Parameters:

units (str, optional) – Units for coordinates (“deg” or “m”), by default “deg”

Returns:

  • x1 (float) – First x coordinate of profile line

  • y1 (float) – First y coordinate of profile line

  • x2 (float) – Second x coordinate of profile line

  • y2 (float) – Second y coordinate of profile line

  • profile_line (dict) – Dictionary with “slope” and “intercept” keys defining the profile line

Raises:

ValueError – If units is “m” but no UTM CRS is set

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

Estimate a profile line from a given geoelectric strike.

Parameters:
  • strike (float) – Geoelectric strike angle in degrees

  • units (str, optional) – Units for coordinates (“deg” or “m”), by default “deg”

Returns:

  • x1 (float) – First x coordinate of profile line

  • y1 (float) – First y coordinate of profile line

  • x2 (float) – Second x coordinate of profile line

  • y2 (float) – Second y coordinate of profile line

  • profile_line (dict) – Dictionary with “slope” and “intercept” keys defining the profile line

Raises:

ValueError – If units is “m” but no UTM CRS is set

property model_epsg: int | None

Model EPSG code.

Returns:

Model EPSG number from the model_crs object

Return type:

int or None

project_stations_on_topography(model_object: Any, air_resistivity: float = 1000000000000.0, sea_resistivity: float = 0.3, ocean_bottom: bool = False) None[source]

Project stations on topography of a given model.

Parameters:
  • model_object (mtpy.modeling.modem.Model) – Model object

  • air_resistivity (float, optional) – Resistivity value of air cells in the model, by default 1e12

  • sea_resistivity (float, optional) – Resistivity of sea water, by default 0.3

  • ocean_bottom (bool, optional) – If True places stations at bottom of sea cells, by default False

rotate_stations(rotation_angle: float) None[source]

Rotate stations model positions only.

Assumes N is 0 and east is 90.

Parameters:

rotation_angle (float) – Rotation angle in degrees assuming N=0, E=90. Positive clockwise

Notes

Computes in place and rotates according to already set rotation angle. Therefore if the station locations have already been rotated, the function will rotate the already rotated stations. For example, if you rotate the stations 15 degrees, then again by 20 degrees, the resulting station locations will be 35 degrees rotated from the original locations.

property station_locations: DataFrame | None

Station locations dataframe.

Returns:

Dataframe of station location information

Return type:

pandas.DataFrame or None

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

Write a CSV file of the station locations.

Parameters:
  • csv_fn (str or Path) – Full path to new CSV file

  • geometry (bool, optional) – Whether to include geometry column, by default False

to_geopd() GeoDataFrame[source]

Create a geopandas dataframe.

Returns:

GeoDataFrame with points from latitude and longitude

Return type:

geopandas.GeoDataFrame

to_shp(shp_fn: str | Path) str | Path[source]

Write a shapefile of the station locations.

Uses geopandas which only takes in epsg numbers.

Parameters:

shp_fn (str or Path) – Full path to new shapefile

Returns:

Path to the created shapefile

Return type:

str or Path

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 VTK file for plotting in 3D like Paraview.

Parameters:
  • vtk_fn (str or Path, optional) – Full path to VTK file to be written, by default None

  • vtk_save_path (str or Path, optional) – Directory to save VTK file to, by default None

  • vtk_fn_basename (str, optional) – Filename basename of VTK file, note that .vtr extension is added, by default “ModEM_stations”

  • geographic (bool, optional) – Use geographic coordinates, by default False

  • shift_east (float, optional) – Shift in east direction, by default 0

  • shift_north (float, optional) – Shift in north direction, by default 0

  • shift_elev (float, optional) – Shift in elevation, by default 0

  • units (str, optional) – Units for coordinates (“km”, “m”, or “ft”), by default “km”

  • coordinate_system (str, optional) – Coordinate system (“nez+” or “enz-“), by default “nez+”

Returns:

Full path to VTK file

Return type:

Path

Raises:

ValueError – If vtk_save_path is None when vtk_fn is None

property utm_crs: CRS | None

UTM coordinate reference system.

Returns:

UTM CRS object

Return type:

pyproj.CRS or None

property utm_epsg: int | None

UTM EPSG code.

Returns:

UTM EPSG number

Return type:

int or None

property utm_name: str | None

UTM coordinate reference system name.

Returns:

UTM CRS name

Return type:

str or None

property utm_zone: str | None

UTM zone.

Returns:

UTM Zone number

Return type:

str or None

class mtpy.core.PhaseTensor(z: ndarray | None = None, z_error: ndarray | None = None, z_model_error: ndarray | None = None, frequency: ndarray | None = None, pt: ndarray | None = None, pt_error: ndarray | None = None, pt_model_error: ndarray | None = None)[source]

Bases: TFBase

Phase Tensor class.

Methods include reading and writing from and to edi-objects, rotations, combinations of Z instances, as well as calculation of invariants, inverse, amplitude/phase.

Phase tensor is a real array of the form (n_freq, 2, 2) with indices:
  • phase_tensor_xx: (0,0)

  • phase_tensor_xy: (0,1)

  • phase_tensor_yx: (1,0)

  • phase_tensor_yy: (1,1)

All internal methods are based on Caldwell et al. (2004) and Bibby et al. (2005), which use the canonical cartesian 2D reference (x1, x2). However, all components, coordinates, and angles for in- and outputs are given in the geographical reference frame:

  • x-axis = North

  • y-axis = East

  • z-axis = Down

Therefore, all results from using those methods are consistent (angles are referenced from North rather than x1).

Parameters:
  • z (np.ndarray, optional) – Impedance tensor array (n_frequency, 2, 2), by default None

  • z_error (np.ndarray, optional) – Impedance tensor error array (n_frequency, 2, 2), by default None

  • z_model_error (np.ndarray, optional) – Impedance tensor model error array (n_frequency, 2, 2), by default None

  • frequency (np.ndarray, optional) – Frequency array (n_frequency), by default None

  • pt (np.ndarray, optional) – Phase tensor array (n_frequency, 2, 2), by default None

  • pt_error (np.ndarray, optional) – Phase tensor error array (n_frequency, 2, 2), by default None

  • pt_model_error (np.ndarray, optional) – Phase tensor model error array (n_frequency, 2, 2), by default None

property alpha: ndarray | None

Principal axis angle (strike) of phase tensor in degrees.

property alpha_error: ndarray | None

Principal axis angle error of phase tensor in degrees.

property alpha_model_error: ndarray | None

Principal axis angle model error of phase tensor in degrees.

property azimuth: ndarray | None

Azimuth angle related to geoelectric strike in degrees.

property azimuth_error: ndarray | None

Azimuth angle error related to geoelectric strike in degrees.

property azimuth_model_error: ndarray | None

Azimuth angle model error related to geoelectric strike in degrees.

property beta: ndarray | None

3D-dimensionality angle Beta (invariant) of phase tensor in degrees.

property beta_error: ndarray | None

3D-dimensionality angle error Beta of phase tensor in degrees.

property beta_model_error: ndarray | None

3D-dimensionality angle model error Beta of phase tensor in degrees.

property det: ndarray | None

Determinant of phase tensor.

property det_error: ndarray | None

Determinant error of phase tensor.

property det_model_error: ndarray | None

Determinant model error of phase tensor.

property eccentricity: ndarray | None

Eccentricity estimation of dimensionality.

property eccentricity_error: ndarray | None

Error in eccentricity estimation.

property eccentricity_model_error: ndarray | None

Model error in eccentricity estimation.

property ellipticity: ndarray | None

Ellipticity of the phase tensor, related to dimensionality.

property ellipticity_error: ndarray | None

Ellipticity error of the phase tensor, related to dimensionality.

property ellipticity_model_error: ndarray | None

Ellipticity model error of the phase tensor, related to dimensionality.

property only1d: ndarray | None

Return phase tensor in 1D form.

If phase tensor is not 1D per se, the diagonal elements are set to zero, the off-diagonal elements keep their signs, but their absolute is set to the mean of the original phase tensor off-diagonal absolutes.

property only2d: ndarray | None

Return phase tensor in 2D form.

If phase tensor is not 2D per se, the diagonal elements are set to zero.

property phimax: ndarray | None

Maximum phase calculated according to Bibby et al. 2005.

Phi_max = Pi2 + Pi1.

property phimax_error: ndarray | None

Maximum phase error.

property phimax_model_error: ndarray | None

Maximum phase model error.

property phimin: ndarray | None

Minimum phase calculated according to Bibby et al. 2005.

Phi_min = Pi2 - Pi1.

property phimin_error: ndarray | None

Minimum phase error.

property phimin_model_error: ndarray | None

Minimum phase model error.

property pt: ndarray | None

Phase tensor array.

property pt_error: ndarray | None

Phase tensor error.

property pt_model_error: ndarray | None

Phase tensor model error.

property skew: ndarray | None

3D-dimensionality skew angle of phase tensor in degrees.

property skew_error: ndarray | None

3D-dimensionality skew angle error of phase tensor in degrees.

property skew_model_error: ndarray | None

3D-dimensionality skew angle model error of phase tensor in degrees.

property trace: ndarray | None

Trace of phase tensor.

property trace_error: ndarray | None

Trace error of phase tensor.

property trace_model_error: ndarray | None

Trace model error of phase tensor.

class mtpy.core.Tipper(tipper: ndarray | None = None, tipper_error: ndarray | None = None, frequency: ndarray | None = None, tipper_model_error: ndarray | None = None)[source]

Bases: TFBase

Tipper class.

Errors are given as standard deviations (sqrt(VAR)).

Parameters:
  • tipper (np.ndarray, optional) – Tipper array in the shape of [Tx, Ty] (nf, 1, 2), by default None

  • tipper_error (np.ndarray, optional) – Array of estimated tipper errors in the shape of [Tx, Ty] (nf, 1, 2), by default None

  • frequency (np.ndarray, optional) – Array of frequencies corresponding to the tipper elements (nf), by default None

  • tipper_model_error (np.ndarray, optional) – Array of model errors in the shape of [Tx, Ty] (nf, 1, 2), by default None

property amplitude: ndarray | None

Amplitude of tipper.

property amplitude_error: ndarray | None

Amplitude error.

property amplitude_model_error: ndarray | None

Amplitude model error.

property angle_error: ndarray | None

Angle error in degrees.

property angle_imag: ndarray | None

Angle of imaginary component in degrees.

property angle_model_error: ndarray | None

Angle model error in degrees.

property angle_real: ndarray | None

Angle of real component in degrees.

property mag_error: ndarray | None

Magnitude error.

property mag_imag: ndarray | None

Magnitude of imaginary component.

property mag_model_error: ndarray | None

Magnitude model error.

property mag_real: ndarray | None

Magnitude of real component.

property phase: ndarray | None

Phase of tipper in degrees.

property phase_error: ndarray | None

Phase error in degrees.

property phase_model_error: ndarray | None

Phase model error in degrees.

set_amp_phase(r: ndarray, phi: ndarray) None[source]

Set values for amplitude (r) and phase (phi).

Parameters:
  • r (np.ndarray) – Amplitude array

  • phi (np.ndarray) – Phase array in degrees

Notes

Updates the attributes tipper and tipper_error.

set_mag_direction(mag_real: ndarray, ang_real: ndarray, mag_imag: ndarray, ang_imag: ndarray) None[source]

Compute tipper from magnitude and direction of real and imaginary components.

Parameters:
  • mag_real (np.ndarray) – Magnitude of real component

  • ang_real (np.ndarray) – Angle of real component

  • mag_imag (np.ndarray) – Magnitude of imaginary component

  • ang_imag (np.ndarray) – Angle of imaginary component

Notes

Updates tipper. No error propagation yet.

property tipper: ndarray | None

Tipper array.

property tipper_error: ndarray | None

Tipper error.

property tipper_model_error: ndarray | None

Tipper model error.

class mtpy.core.Z(z: ndarray | None = None, z_error: ndarray | None = None, frequency: ndarray | None = None, z_model_error: ndarray | None = None, units: str = 'mt')[source]

Bases: TFBase

Impedance tensor (Z) class.

Z is a complex array of the form (n_frequency, 2, 2) with indices: - Zxx: (0,0) - Zxy: (0,1) - Zyx: (1,0) - Zyy: (1,1)

All errors are given as standard deviations (sqrt(VAR)).

Parameters:
  • z (np.ndarray, optional) – Array containing complex impedance values (n_frequency, 2, 2)

  • z_error (np.ndarray, optional) – Array containing error values (standard deviation) of impedance tensor elements (n_frequency, 2, 2)

  • frequency (np.ndarray, optional) – Array of frequency values corresponding to impedance tensor elements (n_frequency)

  • z_model_error (np.ndarray, optional) – Array containing model error values (n_frequency, 2, 2)

  • units (str, optional) – Units for impedance: ‘mt’ [mV/km/nT] or ‘ohm’ [Ohms], by default ‘mt’

property det: ndarray | None

Determinant of impedance.

property det_error: ndarray | None

Determinant of impedance error.

property det_model_error: ndarray | None

Determinant of impedance model error.

estimate_depth_of_investigation() Any[source]

Estimate depth of investigation.

Returns:

Depth of investigation results

Return type:

Any

estimate_dimensionality(skew_threshold: float = 5, eccentricity_threshold: float = 0.1) ndarray[source]

Estimate dimensionality of the impedance tensor.

Based on parameters such as strike and phase tensor eccentricity.

Parameters:
  • skew_threshold (float, optional) – Skew threshold for 3D determination, by default 5

  • eccentricity_threshold (float, optional) – Eccentricity threshold for 2D determination, by default 0.1

Returns:

Dimensionality array (1D, 2D, or 3D) for each period

Return type:

np.ndarray

estimate_distortion(n_frequencies: int | None = None, comp: str = 'det', only_2d: bool = False, clockwise: bool = True) tuple[ndarray, ndarray][source]

Estimate distortion tensor.

Parameters:
  • n_frequencies (int, optional) – Number of frequencies to use, by default None (uses all)

  • comp (str, optional) – Component to use for estimation, by default ‘det’

  • only_2d (bool, optional) – Only use 2D data, by default False

  • clockwise (bool, optional) – Clockwise rotation, by default True

Returns:

Distortion tensor and distortion error tensor

Return type:

tuple of np.ndarray

property invariants: ZInvariants

Weaver invariants.

property phase: ndarray | None

Phase of impedance.

property phase_det: ndarray | None

Phase determinant.

property phase_error: ndarray | None

Phase error of impedance.

Uncertainty in phase (in degrees) is computed by defining a circle around the z vector in the complex plane. The uncertainty is the absolute angle between the vector to (x,y) and the vector between the origin and the tangent to the circle.

property phase_error_det: ndarray | None

Phase error determinant.

property phase_error_xx: ndarray | None

Phase error of xx component.

property phase_error_xy: ndarray | None

Phase error of xy component.

property phase_error_yx: ndarray | None

Phase error of yx component.

property phase_error_yy: ndarray | None

Phase error of yy component.

property phase_model_error: ndarray | None

Phase model error of impedance.

property phase_model_error_det: ndarray | None

Phase model error determinant.

property phase_model_error_xx: ndarray | None

Phase model error of xx component.

property phase_model_error_xy: ndarray | None

Phase model error of xy component.

property phase_model_error_yx: ndarray | None

Phase model error of yx component.

property phase_model_error_yy: ndarray | None

Phase model error of yy component.

property phase_tensor: PhaseTensor

Phase tensor object based on impedance.

property phase_xx: ndarray | None

Phase of xx component.

property phase_xy: ndarray | None

Phase of xy component.

property phase_yx: ndarray | None

Phase of yx component.

property phase_yy: ndarray | None

Phase of yy component.

remove_distortion(distortion_tensor: np.ndarray | None = None, distortion_error_tensor: np.ndarray | None = None, n_frequencies: int | None = None, comp: str = 'det', only_2d: bool = False, inplace: bool = False) 'Z' | None[source]

Remove distortion D from observed impedance tensor Z.

Obtain the unperturbed “correct” Z0 from:

Z = D * Z0

Propagation of errors/uncertainties included.

Parameters:
  • distortion_tensor (np.ndarray, optional) – Real distortion tensor (2, 2), by default None

  • distortion_error_tensor (np.ndarray, optional) – Real distortion error tensor (2, 2), by default None

  • n_frequencies (int, optional) – Number of frequencies to use for estimation, by default None

  • comp (str, optional) – Component to use for estimation, by default ‘det’

  • only_2d (bool, optional) – Only use 2D data, by default False

  • inplace (bool, optional) – Update the current object or return a new impedance, by default False

Returns:

Impedance tensor with distortion removed if inplace is False, None otherwise

Return type:

Z or None

remove_ss(reduce_res_factor_x: float | list | np.ndarray = 1.0, reduce_res_factor_y: float | list | np.ndarray = 1.0, inplace: bool = False) 'Z' | None[source]

Remove static shift by providing correction factors.

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

Z = S * Z0

Therefore the correct Z will be:

Z0 = S^(-1) * Z

Parameters:
  • reduce_res_factor_x (float or array-like, optional) – Static shift factor to be applied to x components (z[:, 0, :]). Assumed to be in resistivity scale, by default 1.0

  • reduce_res_factor_y (float or array-like, optional) – Static shift factor to be applied to y components (z[:, 1, :]). Assumed to be in resistivity scale, by default 1.0

  • inplace (bool, optional) – Update the current object or return a new impedance, by default False

Returns:

Corrected Z if inplace is False, None otherwise

Return type:

Z or None

property res_det: ndarray | None

Resistivity determinant.

property res_error_det: ndarray | None

Resistivity error determinant.

property res_error_xx: ndarray | None

Resistivity error of xx component.

property res_error_xy: ndarray | None

Resistivity error of xy component.

property res_error_yx: ndarray | None

Resistivity error of yx component.

property res_error_yy: ndarray | None

Resistivity error of yy component.

property res_model_error_det: ndarray | None

Resistivity model error determinant.

property res_model_error_xx: ndarray | None

Resistivity model error of xx component.

property res_model_error_xy: ndarray | None

Resistivity model error of xy component.

property res_model_error_yx: ndarray | None

Resistivity model error of yx component.

property res_model_error_yy: ndarray | None

Resistivity model error of yy component.

property res_xx: ndarray | None

Resistivity of xx component.

property res_xy: ndarray | None

Resistivity of xy component.

property res_yx: ndarray | None

Resistivity of yx component.

property res_yy: ndarray | None

Resistivity of yy component.

property resistivity: ndarray | None

Resistivity of impedance.

property resistivity_error: ndarray | None

Resistivity error of impedance.

By standard error propagation, relative error in resistivity is 2 * relative error in z amplitude.

property resistivity_model_error: ndarray | None

Resistivity model error of impedance.

set_resistivity_phase(resistivity: ndarray, phase: ndarray, frequency: ndarray, res_error: ndarray | None = None, phase_error: ndarray | None = None, res_model_error: ndarray | None = None, phase_model_error: ndarray | None = None) None[source]

Set values for resistivity and phase with error propagation.

Parameters:
  • resistivity (np.ndarray) – Resistivity array in Ohm-m (num_frequency, 2, 2)

  • phase (np.ndarray) – Phase array in degrees (num_frequency, 2, 2)

  • frequency (np.ndarray) – Frequency array in Hz (num_frequency)

  • res_error (np.ndarray, optional) – Resistivity error array in Ohm-m (num_frequency, 2, 2), by default None

  • phase_error (np.ndarray, optional) – Phase error array in degrees (num_frequency, 2, 2), by default None

  • res_model_error (np.ndarray, optional) – Resistivity model error array in Ohm-m (num_frequency, 2, 2), by default None

  • phase_model_error (np.ndarray, optional) – Phase model error array in degrees (num_frequency, 2, 2), by default None

property units: str

Impedance units.

property z: ndarray | None

Impedance tensor array (nfrequency, 2, 2).

property z_error: ndarray | None

Error of impedance tensor array as standard deviation.

property z_model_error: ndarray | None

Model error of impedance tensor array as standard deviation.