pycsamt.jones.j#

Classes

JFile([path, verbose])

High-level J dispatcher for MT/SEG archives.

JIOMixin()

Tolerant BLOCK parser and TF/R/Tipper builder.

JMixin()

Lightweight helpers shared by J-format readers.

class pycsamt.jones.j.JMixin[source]#

Bases: object

Lightweight helpers shared by J-format readers.

The mixin groups small, allocation-friendly utilities that many parsers need. It keeps math, alignment and token-handling logic out of higher-level classes.

Notes

The helpers are intentionally tiny and avoid importing heavy libraries beyond numpy. They favor pure functions that accept and return arrays.

_complex(re, im)[source]#

Combine real and imaginary parts into a complex vector. Shapes must be broadcast-compatible.

_deg2rad(x)[source]#

Degrees to radians conversion with float return.

_hz_from_period(p)[source]#

Convert period seconds to frequency in Hz. Non- positive entries are mapped to nan.

_align_by_periods(p0, p1)[source]#

Return a tuple (p_common, i0, i1) where p_common are periods present in both sequences, ordered like p0; i0 and i1 are indices to select the matching rows in the original arrays.

Examples

>>> jm = JMixin()
>>> jm._complex([1, -2], [0.5, 3]).dtype.kind == 'c'
True
>>> jm._deg2rad(180.0)
3.141592653589793
>>> jm._hz_from_period([1.0, 0.5])
array([1., 2.])
>>> pc, i0, i1 = jm._align_by_periods([1, 2, 3], [3, 1])
>>> pc.tolist(), i0.tolist(), i1.tolist()
([1, 3], [0, 2], [1, 0])

See also

JIOMixin

Block scanning and object building helpers.

JFile

High-level reader that uses both mixins.

References

class pycsamt.jones.j.JIOMixin[source]#

Bases: JMixin

Tolerant BLOCK parser and TF/R/Tipper builder.

This mixin concentrates the I/O-oriented parts for J files: scanning blocks, aligning periods, normalizing rows, and assembling higher-level objects (Z, Tipper, and ResPhase).

It aims to be robust against non-canonical header orders and minor format quirks.

Notes

  • Data rows are normalized before assembly. Period sign conventions (negative means Hz) are corrected.

  • Missing sentinels (e.g., -999) are mapped to nan for numeric arrays, but objects are pre- allocated with zeros to keep shapes consistent.

  • When only rho/phi are present, impedance is rebuilt using \(|Z|=\sqrt{\mu_0 \,\omega\, \rho}\) and \(\phi\) for the phase. The vacuum permeability \(\mu_0\) is imported from pycsamt.constants.

_scan_blocks(path, \*, start=None, empty_val=...)[source]#

Parse the file into a component dictionary indexed by tokens like 'ZXY', 'RXX' or 'TZX'. Values include period, real/imag/error (TF) or rho/ phi (+ auxiliary columns for R blocks).

_build_from_comp(comp, \*, z_obj=None, tip_obj=None)[source]#

Assemble Z, Tipper, and ResPhase from the scanned components. Returns a triple (Z|None, Tipper|None, ResPhase|None).

Examples

>>> mix = JIOMixin()
>>> # (typically used via JFile; direct use shown here)
>>> # comp = mix._scan_blocks(Path("data/j/site.j"))
>>> # z, tip, rp = mix._build_from_comp(comp)

See also

JMixin

Mathematical utilities used by this mixin.

JFile

High-level reader/writer that calls these methods.

pycsamt.z.z.Z

Impedance tensor container.

pycsamt.z.tipper.Tipper

Tipper container.

pycsamt.z.resphase.ResPhase

R–φ container.

References

class pycsamt.jones.j.JFile(path=None, *, verbose=0)[source]#

Bases: JIOMixin

High-level J dispatcher for MT/SEG archives.

The class reads a J file, extracts headers and blocks, and builds analysis-ready objects for impedance (Z), resistivity/phase (Res), and tipper (Tip). It also writes new J files from the in-memory state.

Parameters:
  • path (str or Path, optional) – Input J file. If omitted, call read() later.

  • verbose (int, default=0) – Verbosity level. Non-zero emits informational messages during parsing and writing.

Variables:
  • path (Path or None) – Source path when set via __init__ or from_file().

  • heads (pycsamt.jones.heads.Heads or None) – Parsed banner, info and a single head triple.

  • blocks (pycsamt.jones.blocks.JBlocks or None) – Parsed data blocks (R and/or TF).

  • Z (pycsamt.z.z.Z or None) – Impedance tensor container, possibly rebuilt from rho/phi when TF are absent.

  • Tip (pycsamt.z.tipper.Tipper or None) – Tipper container if ZX/ZY are present.

  • Res (pycsamt.z.resphase.ResPhase or None) – Resistivity/phase view (direct or derived).

  • freq (ndarray or None) – Shared frequency vector inferred from available objects. Periods are available via :pyattr:`periods`.

  • periods (ndarray or None) – Convenience view of 1.0/freq when known.

  • n_freq (int) – Number of frequency samples (0 if unknown).

  • name (str or None) – Friendly site/station name. Precedence is: Z.name -> head.station -> file stem.

  • site (str or None) – Alias for the station code (if known).

  • elev (lat, lon, azimuth, az_hint,) – Geographic metadata proxied from headers.

from_file(path, \*, verbose=0)[source]#

Construct and read in one call.

Parameters:
Return type:

JFile

read(path=None, \*, start=None)[source]#

Parse headers and blocks, then build Z, Tip and Res as available.

Parameters:
Return type:

JFile

write(j_fn=None, new_jfn=None, datatype=None,

savepath=None, *, verbose=None, overwrite=True)

Serialize the current state to a J file. The datatype selector accepts combinations like 'Z', 'R', 'T', 'ZR', or 'ALL'.

compose_headers()[source]#

Render banner, head and info lines only.

Return type:

list[str]

__has_read__()[source]#

Return True once a full read() completed.

Examples

>>> jf = JFile.from_file("data/j/kb0-s001.txt", verbose=0)
>>> jf.n_freq > 0
True
>>> out = jf.write(new_jfn="out.j", datatype="ZR",
...                overwrite=True)
>>> isinstance(out, str)
True
>>> jf.lat, jf.lon  # site coordinates if present
( ... )

Notes

  • write prefers existing uncertainties; missing errors are filled with zeros. Periods are written from the active frequency vector.

  • When only R-blocks exist, Z is rebuilt so that downstream code can still compute QA metrics or plot tensor-based products.

See also

pycsamt.jones.heads.Heads

Header and metadata view.

pycsamt.jones.blocks.JBlocks

Low-level parsed blocks.

pycsamt.z.z.Z

Impedance tensor class.

pycsamt.z.tipper.Tipper

Tipper class.

pycsamt.z.resphase.ResPhase

R–φ class.

References

classmethod from_file(path, *, verbose=0)[source]#

Construct and read a J file in one call.

This convenience constructor mirrors __init__ + read(). It resolves path to a filesystem location, parses headers and data blocks, and builds analysis-ready objects (Z, Tip, Res) when present or derivable.

Parameters:
  • path (str or Path) – Path to a J-format text file (Jones v2.0 style).

  • verbose (int, default=0) – Verbosity flag. When non-zero, progress/info messages may be emitted during parsing.

Returns:

Instance with :pyattr:`heads`, :pyattr:`blocks` and objects (:pyattr:`Z`, :pyattr:`Tip`, :pyattr:`Res`) populated where possible.

Return type:

JFile

Notes

  • Headers (banner + >KEY=VALUE + the first head triple) are parsed via Heads.

  • Blocks are scanned with JBlocks, then assembled into Z/Tip/Res via JIOMixin.

Examples

>>> jf = JFile.from_file("data/j/kb0-s001.txt")
>>> jf.n_freq > 0
True

See also

JFile.read

Lower-level method if you already have an instance.

JBlocks

Low-level block parser.

Heads

Header and site metadata container.

References

read(path=None, *, start=None)[source]#

Parse a J file and build objects in memory.

The method reads the banner, info block and the first head triple, then scans all following data blocks. Transfer functions (Zxx, Zxy, …) and tipper (Tzx, Tzy) are assembled when present. If only resistivity/phase blocks exist, a synthetic impedance is rebuilt from \(\rho\) and \(\phi\).

Parameters:
  • path (str or Path, optional) – If given, set as the source and read from it. If omitted, reuse self.path set at construction.

  • start (int, optional) – Line index hint to start scanning blocks. Most users can leave this as None.

Returns:

The instance itself (for chaining).

Return type:

JFile

Notes

  • Block scanning is tolerant to minor format quirks (blank lines, non-canonical head order where the row count precedes the data-type).

  • Period sign conventions are normalized (negative values mean input was frequency in Hz).

  • Missing sentinels (e.g., -999) are mapped to nan in numeric arrays, while objects are pre- allocated with zeros to keep shapes consistent.

Examples

>>> jf = JFile(verbose=0)
>>> _ = jf.read("data/j/kb0-s001.txt")
>>> jf.Z is not None or jf.Res is not None
True

See also

JFile.from_file

Shortcut that constructs then calls this method.

JBlocks

Underlying block parser.

Z, Tipper, ResPhase

References

write(j_fn=None, new_jfn=None, datatype=None, savepath=None, *, verbose=None, overwrite=True)[source]#

Serialize the current state to a J-format file.

The writer renders a banner, info lines and one or more data blocks selected via datatype. When uncertainties are unavailable, zero-filled error columns are emitted to preserve column layout. Periods are derived from the active frequency vector.

Parameters:
  • j_fn (str, optional) – Base filename to use. If omitted, derive from :pyattr:`path` or default to 'out.j'.

  • new_jfn (str, optional) – Replacement filename. Takes precedence over j_fn when provided.

  • datatype ({'Z','R','T','ZR','RT','ZT','ZRT','ALL'}, optional) – Select families to emit. If None, the writer auto-detects from available objects on the instance.

  • savepath (str or Path, optional) – Folder where to save. Defaults to the parent of :pyattr:`path` or the current directory.

  • verbose (int, optional) – Override verbosity. If None, reuse :pyattr:`verbose`.

  • overwrite (bool, default=True) – If False and the target exists, a numeric suffix is appended to avoid clobbering.

Returns:

out_path – The filesystem path of the written file.

Return type:

str

Notes

  • The station code and optional azimuth hint are taken from the parsed head. Units for transfer functions are written as SI.

  • If only R blocks exist, they can be emitted directly; if only Z is present, synthetic R/φ can be computed for writing when the selector requests it.

  • The banner defaults to PYCSAMT when no producer is known. The original banner (if parsed) can be preserved or referenced by the caller before writing.

Examples

>>> jf = JFile.from_file("data/j/kb0-s001.txt")
>>> out = jf.write(new_jfn="site_out.j",
...                datatype="ZR", overwrite=True)
>>> isinstance(out, str)
True

See also

JFile.compose_headers

Render banner + headers only.

Z, Tipper, ResPhase

References

property freq: ndarray | None[source]#
property periods: ndarray | None[source]#
property n_freq: int[source]#
property station: str | None[source]#
property name: str | None[source]#
property lat: float | None[source]#
property lon: float | None[source]#
property azimuth: float | None[source]#
property az_hint: float | None[source]#
property elev: float | None[source]#
property site[source]#
compose_headers()[source]#
Return type:

list[str]