pycsamt.jones.xa#

Functions

build_jdataset(jfiles, *[, drop_empty])

Build a multi-site xarray Dataset from JFile objects.

Classes

JFileAcc(ds)

An xarray accessor for convenient interaction with J-format datasets.

XAJMixin()

A mixin to add xarray export capabilities to J-file collections.

class pycsamt.jones.xa.XAJMixin[source]#

Bases: object

A mixin to add xarray export capabilities to J-file collections.

This class is designed to be mixed into a collection class that is iterable and yields JFile objects, such as JCollection. It provides high-level methods to convert the entire collection into an xarray.Dataset.

to_xarray()[source]#

Converts the collection into a full xarray.Dataset.

Parameters:

drop_empty (bool)

Return type:

Dataset

meta_table()[source]#

Extracts only the site-level metadata into a compact Dataset.

Return type:

Dataset

See also

JCollection

An example of a class that can use this mixin.

build_jdataset

The underlying function that performs the conversion.

Examples

>>> from pycsamt.jones import JCollection
>>> from pycsamt.jones.xa import XAJMixin
>>>
>>> # Create a new class that inherits from JCollection and the mixin
>>> class JCollectionWithXA(JCollection, XAJMixin):
...     pass
>>>
>>> # Use the new class to load data
>>> j_collection_xa = JCollectionWithXA.from_sources("data/jc/")
>>>
>>> # Now you can directly call the .to_xarray() method
>>> ds = j_collection_xa.to_xarray()
>>> print(ds.dims)
Frozen({'site': 4, 'freq': 17, 'output_ch': 2, 'input_ch': 2, 'tcomp': 2})
to_xarray(*, drop_empty=True)[source]#

Converts the entire collection into an xarray Dataset.

This method is a convenient wrapper around the build_jdataset() function.

Parameters:

drop_empty (bool)

Return type:

Dataset

meta_table()[source]#

Extracts site-level metadata into a new Dataset.

This method provides a quick way to get a summary of all sites in the collection without loading the bulky tensor data.

Return type:

Dataset

class pycsamt.jones.xa.JFileAcc(ds)[source]#

Bases: object

An xarray accessor for convenient interaction with J-format datasets.

This accessor is registered under the .jfile namespace and provides a set of domain-specific methods and properties for xarray.Dataset objects that were created by build_jdataset(). It simplifies common tasks like selecting sites, filtering by frequency, and accessing metadata.

Properties#

stationslist[str]

A list of all station/site names in the dataset.

get(site)[source]#

Selects a single site by name and returns a new Dataset.

Parameters:

site (str)

Return type:

Dataset

components()[source]#

Lists the available impedance tensor component names.

Return type:

list[str]

band(fmin, fmax)[source]#

Filters the dataset to a specific frequency band.

Parameters:
Return type:

Dataset

Notes

The accessor pattern is a powerful feature of xarray that allows external libraries to add their own functionality to xarray objects without modifying the xarray codebase itself.

See also

build_jdataset

The function that creates compatible datasets.

xarray.register_dataset_accessor

The decorator used to create accessors.

Examples

>>> from pycsamt.jones import JCollection, build_jdataset
>>> j_collection = JCollection.from_sources("data/jc/")
>>> ds = build_jdataset(j_collection)
>>>
>>> # Use the .jfile accessor
>>> print(ds.jfile.stations)
['NIA000', 'NIA001', 'NIA002', 'NIA003']
>>>
>>> # Get data for a single site
>>> site_nia001 = ds.jfile.get("NIA001")
>>> print(site_nia001.dims)
Frozen({'freq': 17, 'output_ch': 2, 'input_ch': 2, 'tcomp': 2})
property stations: list[str][source]#
get(site)[source]#

Selects data for a single site.

This is a convenience wrapper around .sel(site=...) which also cleans up the resulting dataset by removing the now-singleton ‘site’ dimension.

Parameters:

site (str)

Return type:

Dataset

components()[source]#

Returns a list of available impedance component names.

Return type:

list[str]

band(fmin=None, fmax=None)[source]#

Filters the dataset to a specified frequency band.

Parameters:
  • fmin (float, optional) – The minimum frequency to include (inclusive).

  • fmax (float, optional) – The maximum frequency to include (inclusive).

Returns:

A new dataset containing only the data within the specified frequency range.

Return type:

xr.Dataset

plot_apparent_resistivity(site, components=None, phase_mod=None, figsize=(8, 8), show_grid=True, grid_props=None, savefig=None, **plot_kwargs)[source]#

Generates a standard plot of apparent resistivity and phase.

This method provides a flexible interface for visualizing MT (magnetotelluric) data, allowing customization of components, phase wrapping, and plot aesthetics.

Parameters:
  • site (str) – The site identifier to plot.

  • components (list of str, default=["xy", "yx"]) – A list of tensor components to plot (e.g., “xy”, “yx”, “xx”). The selection is case-insensitive.

  • phase_mod (int, optional) – If provided, wraps the phase to a specific quadrant. For example, phase_mod=90 will display phases in the [0, 90] degree range.

  • figsize (tuple[int, int], default=(8, 8)) – The figure size for the plot.

  • show_grid (bool, default=True) – Whether to display a grid on both subplots.

  • grid_props (dict, optional) – Additional properties to customize the grid lines (e.g., {'color': 'grey', 'linestyle': '--', 'linewidth': 0.5}).

  • savefig (str, optional) – If a path is provided, the plot will be saved to that file.

  • **plot_kwargs – Additional keyword arguments passed directly to xarray’s .plot.line() method for customizing the lines.

Returns:

  • fig (matplotlib.figure.Figure) – The matplotlib Figure object.

  • axes (np.ndarray of matplotlib.axes.Axes) – An array containing the two subplot Axes objects.

attrs()[source]#

Returns the global attributes of the Dataset.

Deprecated since version 2.1.0: Metadata is now primarily stored as non-dimensional coordinates. Use direct coordinate access for site-specific metadata (e.g., ds.coords[‘lat’]). This method is maintained for backward compatibility.

Return type:

dict[str, object]

Parameters:

ds (xr.Dataset)

pycsamt.jones.xa.build_jdataset(jfiles, *, drop_empty=True)[source]#

Build a multi-site xarray Dataset from JFile objects.

This function iterates through a collection of parsed JFile objects, converts each one into a single-site xarray.Dataset, and then concatenates them into a unified, multi-site dataset.

Parameters:
  • jfiles (Iterable of JFile) – An iterable (e.g., a list or a JCollection) of parsed J-file objects.

  • drop_empty (bool, default=True) – If True, any JFile object that contains no frequency data will be skipped and excluded from the final dataset.

Returns:

A single dataset containing data from all valid J-files. The dataset is indexed by a site dimension, and site-specific metadata (latitude, longitude, etc.) are stored as non-dimensional coordinates aligned with this dimension.

Return type:

xr.Dataset

Notes

The resulting dataset is structured with dimensions for sites, frequencies, and tensor components. This structure is ideal for vectorized computations and advanced plotting across multiple sites.

Data variables include impedance (z), tipper (tip), apparent resistivity (rho), phase (phi), their associated errors, and crucial data quality flags (z_rej, rho_rej).

See also

JCollection.to_xarray

A convenient wrapper around this function.

JFile

The per-item reader that provides the source data.

JFileAcc

An accessor for interacting with the created dataset.

Examples

>>> from pycsamt.jones import JCollection, build_jdataset
>>> # Create a collection of J-files from a directory
>>> j_collection = JCollection.from_sources("data/jc/*")
>>> # Build the xarray dataset
>>> ds = build_jdataset(j_collection)
>>> print(ds)
<xarray.Dataset>
Dimensions:    (site: 4, freq: 17, ...)
Coordinates:
  * site       (site) object 'NIA000' 'NIA001' ...
    ...
Data variables:
    z          (site, freq, output_ch, input_ch) complex128 ...
    z_err      (site, freq, output_ch, input_ch) float64 ...
    ...