pycsamt.seg.xa#
Functions
|
Build a multi-site xarray Dataset from an iterable of EDIFile. |
Classes
|
An xarray accessor for convenient interaction with EDI datasets. |
|
A mixin that adds convenient xarray exports to collection classes. |
- class pycsamt.seg.xa.XAMixin[source]#
Bases:
objectA mixin that adds convenient xarray exports to collection classes.
This mixin provides a bridge between collection-like objects (such as
EDICollection) and the powerful, multi-dimensional data structures offered by the xarray library. Any class that is iterable overEDIFileinstances can inherit from this mixin to gain methods for data conversion and metadata extraction.- to_xarray(drop_empty=True)[source]#
Converts the entire collection into a single, comprehensive
xarray.Dataset. This method leveragesbuild_dataset()to handle the conversion and concatenation of multiple EDI files.- Parameters:
drop_empty (bool)
- Return type:
Dataset
- meta_table()[source]#
Extracts only the site-level metadata (e.g., coordinates, filenames, data quality flags) from the collection and returns it as a clean, tabular
xarray.Dataset, omitting the bulky transfer function data.- Return type:
Dataset
Notes
This mixin is designed to be lightweight and does not impose any specific storage or indexing strategy on the host class; it only requires that the host class implements the __iter__ method to yield
EDIFileobjects.The site identifiers used in the resulting datasets follow the same robust inference rules as
build_dataset().
See also
build_datasetThe core function that performs the conversion.
EDICollectionA primary user of this mixin.
EDIAccThe accessor for interacting with the created dataset.
Examples
To use this mixin, simply inherit from it in your collection class.
>>> from pycsamt.seg.edi import EDIFile >>> class MyEDICollection(XAMixin): ... def __init__(self, items): ... self._items = list(items) ... def __iter__(self): ... return iter(self._items) ... >>> # Assume "site1.edi" and "site2.edi" exist >>> edi_files = [EDIFile("data/edis/S01.edi"), EDIFile("data/edis/S02.edi")] >>> collection = MyEDICollection(edi_files) >>> >>> # Convert the entire collection to an xarray Dataset >>> ds = collection.to_xarray() >>> print(ds.site.values) ['S01' 'S02'] >>> >>> # Get a summary table of just the metadata >>> metadata_ds = collection.meta_table() >>> print(metadata_ds[['lat', 'lon']]) <xarray.Dataset> Dimensions: (site: 2) Coordinates: * site (site) object 'S01' 'S02' Data variables: lat (site) float64 26.05 26.05 lon (site) float64 -10.33 -10.33
- class pycsamt.seg.xa.EDIAcc(ds)[source]#
Bases:
objectAn xarray accessor for convenient interaction with EDI datasets.
This accessor is registered under the
.edinamespace and provides domain-specific methods and properties for datasets created bybuild_dataset(). It simplifies common data selection and visualization tasks that are specific to MT/EM (magnetotelluric/electromagnetic) data.Properties#
- stationslist[str]
A list of all unique station or site names present in the dataset’s
sitecoordinate.
- get(site)[source]#
Selects and returns a new
xarray.Datasetcontaining data for only a single site, specified by its name. The selection is case-insensitive.- Parameters:
site (str)
- Return type:
Dataset
- band(fmin=None, fmax=None)[source]#
Filters the dataset to a specific frequency range. Returns a new dataset containing only the data within the inclusive frequency bounds.
- plot_apparent_resistivity(site, \*\*kwargs)[source]#
Generates a standard plot of apparent resistivity and phase curves for the off-diagonal tensor components (XY and YX) of a specified site.
See also
build_datasetThe function used to create datasets compatible with this accessor.
Examples
>>> from pycsamt.seg import EDICollection, build_dataset >>> edi_collection = EDICollection.from_sources("data/edis/") >>> ds = build_dataset(edi_collection) >>> >>> # Get a list of all station names >>> print(ds.edi.stations) ['S01', 'S02', 'S03', ...] >>> >>> # Select data for a single station (case-insensitive) >>> site_data = ds.edi.get('s01') >>> >>> # Filter the data to a specific frequency band (e.g., 1 to 100 Hz) >>> filtered_ds = ds.edi.band(fmin=1.0, fmax=100.0) >>> >>> # Create a standard plot for a site >>> fig, axes = ds.edi.plot_apparent_resistivity(site='S01') >>> # fig.show() # Uncomment to display plot
- get(site)[source]#
Selects data for a single site (case-insensitive).
- Parameters:
site (str)
- Return type:
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=90will display phases in the [0, 90] degree range, useful for visualizing data in a single quadrant.figsize (tuple[int, int], default=(8, 6)) – 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.
Examples
>>> # Basic plot of off-diagonal components >>> fig, axes = ds.edi.plot_apparent_resistivity(site='S01') >>> # fig.show()
>>> # Plot all components and save the figure >>> fig, axes = ds.edi.plot_apparent_resistivity( ... site='S01', ... components=['xy', 'yx', 'xx', 'yy'], ... savefig='S01_all_components.png' ... )
>>> # Plot with phase wrapped to the first quadrant and custom styling >>> fig, axes = ds.edi.plot_apparent_resistivity( ... site='S01', ... phase_mod=90, ... grid_props={'color': 'red', 'linestyle': ':'}, ... marker='o' # passed to plot.line ... )
- Parameters:
ds (xr.Dataset)
- pycsamt.seg.xa.build_dataset(edis, *, drop_empty=True)[source]#
Build a multi-site xarray Dataset from an iterable of EDIFile.
This function iterates through a collection of parsed
EDIFileobjects, converts each one into a single-sitexarray.Dataset, and then concatenates them into a unified, multi-site dataset.- Parameters:
edis (Iterable of
EDIFile) – An iterable (e.g., a list or aEDICollection) of parsed EDI objects.drop_empty (bool, default=True) – If
True, anyEDIFileobject that contains no frequency data will be skipped and excluded from the final dataset.
- Returns:
A single dataset containing data from all valid EDI files. The dataset is indexed by a
sitedimension, 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.
This function correctly handles site-specific metadata by assigning it to coordinates, preventing data loss during concatenation, which is a common pitfall when storing metadata in global attributes.
See also
EDICollection.to_xarrayA convenient wrapper around this function.
EDIFileThe per-item reader that provides the source data.
EDIAccAn accessor for interacting with the created dataset.
Examples
>>> from pycsamt.seg import EDICollection, build_dataset >>> # Create a collection of EDI files >>> edi_collection = EDICollection.from_sources("data/edis/") >>> # Build the xarray dataset >>> ds = build_dataset(edi_collection) >>> print(ds) <xarray.Dataset> Dimensions: (site: 2, freq: 60, ...) Coordinates: * site (site) object 'S01' 'S02' * freq (freq) float64 320.0 286.9 ... ... lat (site) float64 26.05 26.05 lon (site) float64 -10.33 -10.33 Data variables: z (site, freq, output_ch, input_ch) complex128 ... z_err (site, freq, output_ch, input_ch) float64 ... ...