4. MTpy v2 Interoperability#
MTpy v2 [Kirkby2019] [MTpyV2] and pyCSAMT both read magnetotelluric
transfer functions, and a project often needs the two side by
side: MTpy’s station objects for its own plots, model files and
coordinate tools, pyCSAMT’s processing, QC and inversion workflows for
the rest. Exchanging data through EDI files works, but it forces a disk
round trip and depends on both packages agreeing on every corner of the
EDI format. pycsamt.transformers.mtpy_interop removes that step.
It copies the arrays and station metadata of an MTpy object straight
into a pyCSAMT Site, and back, without
writing a file.
Two functions carry the conversion. from_mtpy()
accepts a single mtpy.MT station (or a plain mt_metadata TF),
a multi-station mtpy.MTData or mtpy.MTCollection, or a list of
stations, and returns a Site or Sites.
to_mtpy() goes the other way and returns an
MT or an MTData. The same operations are available as methods:
Site.from_mtpy, Site.to_mtpy, Sites.from_mtpy and
Sites.to_mtpy.
4.1. Installation#
MTpy is optional. Install it with pyCSAMT’s mtpy extra:
pip install "pycsamt[mtpy]"
The extra installs the mtpy-v2 distribution. from_mtpy never
imports MTpy: it only reads attributes of objects the caller has already
built, so it works in any environment that can create them. to_mtpy
has to construct MTpy objects and raises an ImportError that
names the extra when MTpy is missing.
The examples on this page use the Broken Hill survey shipped in
data/MT/broken-hill/edis (21 broadband stations of
[AlQahtani2026], released under CC BY as [AlQahtani2026data]). They
were run with MTpy 2.1.4
from the repository root, as one interactive session.
4.2. Reading a Station#
MTpy reads the EDI file into an MT object that holds the
impedance tensor and the tipper:
>>> from mtpy import MT
>>> mt = MT('data/MT/broken-hill/edis/BH_1_imp.edi')
>>> mt.read()
>>> print(mt.station, mt.Z.z.shape, mt.has_tipper())
None (96, 2, 2) True
The station name is None because every Broken Hill file declares
DATAID=None. Converting the station gives a Site:
>>> from pycsamt.transformers import from_mtpy
>>> site = from_mtpy(mt)
>>> site.name, site.backend
('BH_1_imp', 'xml')
>>> site.coords
(-31.974277777777775, 141.51005555555557, 284.005)
>>> site.freq.size, site.z.shape, site.tipper.shape
(96, (96, 2, 2), (96, 1, 2))
The site carries the name pyCSAMT’s own EDI reader would give it, the
file stem BH_1_imp, so a station read through MTpy and the same
station read directly by pyCSAMT have the same identity. The site is
backed by a format-neutral EMTF
document (backend == "xml"); its EDI view is built on first access
of site.edi, and every array property (freq, z, z_err,
tipper, rho, phase) behaves exactly as it does for a site
loaded from an EDI file.
4.3. Units and Conventions#
No rescaling takes place, because both packages keep the impedance in the practical field units of the EDI convention, \(\mathrm{mV\,km^{-1}\,nT^{-1}}\), and use the same \(e^{+i\omega t}\) time dependence. The apparent resistivity and phase of a component \(Z_{ij}\) measured at frequency \(f\) (Hz) are then
with \(\rho_{a,ij}\) in \(\Omega\,\mathrm{m}\). The values computed by MTpy and by pyCSAMT agree at every measured frequency, and the formula reproduces pyCSAMT’s value by hand:
>>> import numpy as np
>>> good = np.isfinite(site.z).all(axis=(1, 2))
>>> int(good.sum()), int((~good).sum())
(94, 2)
>>> np.allclose(site.rho[good], mt.Z.resistivity[good])
True
>>> np.allclose(site.phase[good], mt.Z.phase[good])
True
>>> f0, zxy = site.freq[10], site.z[10, 0, 1]
>>> print(f'{0.2 / f0 * abs(zxy) ** 2:.6f} {site.rho[10, 0, 1]:.6f}')
132.999033 132.999033
Two of the 96 frequencies of BH_1_imp are missing from the file;
they are discussed in the next section. When an MTpy object labels its
impedance in SI units (Z.units == "ohm"), from_mtpy converts it
to field units first,
so that (1) holds for every converted site.
Figure 1 overlays the two computations for BH_1_imp. The plotting
code continues the same session:
import matplotlib.pyplot as plt
period = 1.0 / site.freq
colors = {"xy": "#0072B2", "yx": "#D55E00"}
fig, (ax_r, ax_p) = plt.subplots(
1, 2, figsize=(9.0, 3.6), constrained_layout=True
)
for comp, (i, j) in {"xy": (0, 1), "yx": (1, 0)}.items():
c = colors[comp]
# MTpy marks missing frequencies with zeros; hide them.
keep = mt.Z.resistivity[:, i, j] > 0
phi_mt = np.where(keep, mt.Z.phase[:, i, j], np.nan)
phi_pc = site.phase[:, i, j]
if comp == "yx": # fold the third-quadrant phase
phi_mt, phi_pc = phi_mt + 180.0, phi_pc + 180.0
ax_r.loglog(
period[keep], mt.Z.resistivity[keep, i, j], "-",
color=c, lw=1.2, label=f"MTpy {comp}",
)
ax_r.loglog(
period, site.rho[:, i, j], "o", mfc="none", ms=4,
color=c, label=f"pyCSAMT {comp}",
)
ax_p.semilogx(period, phi_mt, "-", color=c, lw=1.2)
ax_p.semilogx(
period, phi_pc, "o", mfc="none", ms=4, color=c
)
ax_r.set(
xlabel="Period (s)",
ylabel=r"Apparent resistivity ($\Omega\,$m)",
title="(a) BH_1_imp",
)
ax_p.set(
xlabel="Period (s)", ylabel="Phase (°)", ylim=(0, 90),
title="(b) BH_1_imp",
)
ax_r.legend(fontsize=8, ncol=2)
fig.savefig(
"docs/source/images/user_guide/mtpy/mtpy_vs_pycsamt_bh1.png",
dpi=150,
)
Apparent resistivity (a) and phase (b) of the xy (blue) and yx
(orange) components of station BH_1_imp. Lines are MTpy’s
values; open circles are pyCSAMT’s values after from_mtpy. The
yx phase is shifted by \(180^\circ\) into the first quadrant.
The gaps in the lines are the two frequencies missing from the file.#
4.4. Missing Values#
The two packages mark missing data differently. pyCSAMT uses NaN.
MTpy reads a frequency that is absent from the source file as zeros in
every impedance component, and writes an error of zero where no error
estimate exists. A measured impedance tensor is never zero in all four
components, and a zero standard error would give a datum infinite
weight in an inversion, so from_mtpy maps both markers to NaN.
Station BH_11_imp has a missing frequency at index 78:
>>> mt11 = MT('data/MT/broken-hill/edis/BH_11_imp.edi')
>>> mt11.read()
>>> print(mt11.station, mt11.Z.z[78, 0, 1], mt11.Z.z_error[78, 0, 1])
None 0j 1.0
>>> s11 = from_mtpy(mt11)
>>> print(s11.name, s11.z[78, 0, 1], s11.z_err[78, 0, 1])
BH_11_imp (nan+nanj) 1.0
>>> bool(np.all(mt11.Z.z[78] == 0))
True
The rule applies only to frequencies whose components are all
exactly zero, so a genuine zero on the diagonal of a 1-D tensor is
kept. The same rule applies to the tipper. to_mtpy reverses both
rules (NaN errors and all-NaN frequencies are written as zeros), so a
station sent from MTpy to pyCSAMT and back has MTpy’s own values. The
MTpy objects passed to from_mtpy are never modified.
4.5. Survey Containers#
A survey is usually handled in MTpy as an MTData container. Its
stations are keyed by survey and station name, which matters for files
like these: every station read from Broken Hill is named None, so
adding them unchanged to an MTData keeps a single station.
>>> import glob
>>> from mtpy.core import MTData
>>> files = sorted(glob.glob('data/MT/broken-hill/edis/BH_*.edi'))
>>> stations = []
>>> for fn in files:
... m = MT(fn)
... m.read()
... stations.append(m)
...
>>> len(stations)
21
>>> naive = MTData()
>>> _ = naive.add_station(stations)
>>> naive.n_stations
1
Naming each station after its file before building the container keeps all 21:
>>> from pathlib import Path
>>> for m in stations:
... m.station = Path(m.fn).stem
...
>>> md = MTData()
>>> _ = md.add_station(stations, survey_id='broken_hill')
>>> md.n_stations
21
Sites.from_mtpy (or from_mtpy) turns the container into
Sites in the container’s station order, and the survey identifier
travels with each site:
>>> from pycsamt.site.base import Sites
>>> sites = Sites.from_mtpy(md)
>>> len(sites)
21
>>> [s.name for s in sites][:4]
['BH_10_imp_rev', 'BH_11_imp', 'BH_12_imp_rev', 'BH_13_imp_rev']
>>> sites[0].site_meta.survey
'broken_hill'
Passing the plain list stations to from_mtpy works too, even
without names: pyCSAMT names each unnamed station after its file, and
falls back to MT001, MT002, … by position when no file is
known, so stations never merge.
4.6. MTpy Objects in Workflows#
to_sites and ensure_sites(), the entry
point of every pycsamt.emtools function, recognise MTpy objects.
An MTData, an MT or a list mixing MTpy stations with EDI paths
and Site objects can be passed wherever pyCSAMT expects sites. The
phase-tensor skew table of the whole survey, for instance, is computed
directly from the MTpy container:
>>> from pycsamt import emtools
>>> skew = emtools.skew_table(md)
>>> skew.shape
(1953, 10)
>>> print(skew[['station', 'freq', 'skew']].head(3).to_string())
station freq skew
0 BH_10_imp_rev 10000.0 2.331769
1 BH_10_imp_rev 8800.0 2.678174
2 BH_10_imp_rev 7200.0 2.912263
4.7. Writing Back to MTpy#
to_mtpy builds MTpy objects from any site, whatever reader produced
it. Here a site read by pyCSAMT’s EDI reader becomes an MT that is
identical to the one MTpy read from the same file, and the 21 Broken
Hill sites become an MTData:
>>> from pycsamt.site.base import Site
>>> edi_site = Site('data/MT/broken-hill/edis/BH_1_imp.edi')
>>> mt_back = edi_site.to_mtpy(survey='broken_hill')
>>> type(mt_back).__name__, mt_back.station, mt_back.survey
('MT', 'BH_1_imp', 'broken_hill')
>>> np.allclose(mt_back.Z.z, mt.Z.z, equal_nan=True)
True
>>> np.allclose(mt_back.Z.resistivity, mt.Z.resistivity, equal_nan=True)
True
>>> md_back = sites.to_mtpy()
>>> type(md_back).__name__, md_back.n_stations
('MTData', 21)
The optional survey argument sets the survey identifier of every
station; without it, each site’s own survey is used when one is
recorded.
4.8. Copied Quantities#
Quantity |
Handling |
|---|---|
Frequency |
Copied in Hz. A |
Impedance and its error |
Copied as |
Tipper and its error |
Copied as |
Station name and survey |
Copied; an empty name falls back to the file stem, then to a positional name. |
Latitude, longitude, elevation |
Copied in decimal degrees and metres. |
Declination |
Copied into the site location metadata (degrees). |
Rotation angle |
Stored in |
Model errors, residual covariance, inverse signal power, run and channel metadata |
Not copied. Keep the MTpy object (or its EMTF XML file) when these are needed. |
4.9. See Also#
Transformers – the other converters of
pycsamt.transformers(AVG, J, spectra and time series to EDI).Loading electromagnetic data – reading EDI and EMTF XML files directly.
pycsamt.transformers – API reference for
pycsamt.transformers.mtpy_interop.References – full citations for the software and data used on this page.