Lightweight wrapper exposing station-centric accessors
and utilities for a single EDIFile.
The mixin normalizes common site operations around the
underlying EDI content, including coordinate handling,
impedance arrays, tipper, derived resistivity/phase, and
convenient export to pandas.DataFrame.
Notes
The station name is resolved from EDI HEAD fields in the
following order: dataid, station, sitename,
name, STATION. If none is present, the file stem
is used. See _station_name().
The Z tensor is treated as an array of shape (n,2,2)
or flattened to (n,4) as needed. The order is:
Zxx,Zxy,Zyx,Zyy.
The method writes to EDI HEAD fields dataid,
station, sitename, name (best effort) and
also updates edi.name. Downstream containers that
derive station IDs from the file stem may be configured
to prefer edi.name to preserve the rename.
High-level wrapper for a single MT/CSAMT site backed by an
EDIFile. The class enforces a
stable, file-stem-based station identifier and exposes
convenient accessors for coordinates, impedance Z, tipper,
and derived quantities.
The constructor normalizes EDI HEAD fields so that
dataid (and, if absent, station) matches the site
stem resolved by _stem_from_edi(). If an in-memory
edi.name exists, the stem may prefer it so that a prior
rename is preserved. This normalization improves name-based
indexing, deterministic selection, and downstream joins in
collections.
Parameters:
edi (pycsamt.seg.edi.EDIFile) – Parsed SEG-EDI container holding one station. The file
may be constructed from disk or synthesized in memory.
name (str) – Normalized station identifier. By default this equals
the file stem, unless a previous explicit rename is in
effect.
coords (tuple of float) – Geographic location as (lat,lon,elev). Latitude
and longitude are in degrees; elevation is in meters.
Notes
Identity policy
The site identity is derived from header fields in the
following order: dataid, station, sitename,
name, STATION. If none are present, the file
stem is used. The constructor ensures that dataid is
set to the resolved stem to stabilize lookups.
Array conventions
The impedance tensor \(Z\) may be represented as a
3D array with shape (n,2,2) or flattened to
(n,4) in the component order
Zxx,Zxy,Zyx,Zyy. Frequencies are 1D of length
n. The tipper has two columns Tx and Ty.
Derived fields
Apparent resistivity and phase are derived from
\(Z\) and the frequency vector. When Z or frequency
slices are applied, recomputation is triggered after
arrays are aligned to avoid inconsistent shapes.
Robustness
Accessors are defensive. Missing arrays produce empty
frames or None. Coordinates are validated for range
using utility checks.
Container for multiple Site
objects with convenient indexing, selection, and bulk edit
operations.
Sites wraps each provided EDIFile
into a Site, ensuring that station
identity is normalized consistently. You can iterate, index by
integer, or look up by case-insensitive station name. Bulk
operations such as renaming, frequency slicing, and masking
are provided via edit_all().
Parameters:
edic (pycsamt.seg.collection.EDICollection or sequence of) – pycsamt.seg.edi.EDIFile
Parsed EDI collection or any sequence of EDI objects.
Items are wrapped into Site instances in the
order provided.
Variables:
_items (list of Site) – Internal sequence of sites. This is considered private.
Iterate over Sites instead of accessing it directly.
Notes
Identity and lookup
Each site inside the container uses the same naming
policy as Site. Name-based lookups with
sites["E01"] are case-insensitive and match the
normalized station name. If duplicates exist, the first
match is returned.
Order preservation
Ordering of input items is preserved. Integer indexing
with sites[i] retrieves the i-th Site.
Bulk edits
edit_all() supports three common operations:
- rename: compute a new name from the old name.
- freq_slice: apply a frequency slice (slice)
consistently across Z, freq, errors, and derived fields.
mask: apply a boolean mask to the Z tensor rows.
Use inplace=True to modify the container, otherwise a
new Sites is returned.
Geospatial helpers
closest() uses geodetic distance to find the nearest
site to a given latitude and longitude. Sites with missing
or non-finite coordinates are skipped.
Topography integration
with_topography() aligns site coordinates and
elevation with a user-provided frame, returning a new
container unless inplace=True is requested.
Profile conversion
to_profile() attempts to build a
Profile when that optional
dependency is available. Otherwise, a lightweight dict
describing a chainage-ordered sequence is returned.
Persistence
write() emits one EDI file per site into a target
directory. If an EDI object provides to_file, it is
used; otherwise a placeholder is written.
Robustness and errors
__getitem__ raises KeyError when a name is not
found. Prefer get() to obtain None instead.
Bulk operations ignore missing arrays on a best-effort
basis so that other arrays can still be processed.
>>> sl=slice(1,None)# drop the first frequency>>> out2=sites.edit_all(freq_slice=sl,inplace=False)>>> f0=sites["E01"].freq>>> f1=out2["E01"].freq>>> len(f1)==len(f0)-1True
Bulk-edit all sites with optional rename, frequency slicing,
and tensor masking.
Parameters:
rename (callable, optional) – Function rename(old_name)->new_name. If provided,
each site is renamed accordingly.
freq_slice (slice, optional) – Row-wise slice applied consistently to frequency,
impedance Z, errors, and derived arrays.
mask (callable, optional) – Function mask(df)->bool_series where df is the
output of site.to_dataframe("z"). Rows where the
mask is False are set to NaN in Z.
inplace (bool, optional) – If True, modify this container and return it. If
False, return a new Sites. Default is
False.
Returns:
The edited container (possibly the same instance).
Align site coordinates and elevation from a tabular frame.
Parameters:
frame (Any) – A table-like object (e.g., pandas.DataFrame)
with station identifiers and columns for latitude,
longitude, and elevation. Column names are resolved by
the topography utility.
inplace (bool, optional) – If True, modify this container and return it. If
False, return a new Sites. Default is
False.
Construct a container from heterogeneous inputs by using a
normalized loading session.
Parameters:
source (Any) – Input that can be understood by the loader. Supported
cases include:
- an EDICollection,
- a list of EDIFile,
- a single EDIFile,
- or an iterable that yields EDIs.
topo_src (Any, optional) – Optional topography source passed to the session for
use during loading. The default is None.
Returns:
Parsed container. Returns an empty container if the
input cannot be interpreted.
This is the inverse boundary of to_sites(). It accepts a
single Site, a Sites collection, an
EDICollection, raw EDI objects, path-like inputs, or mixed
iterables containing those forms. The returned objects are the
underlying EDI containers used by low-level writers, exporters,
and EM processing functions.
Parameters:
x (Any) – Site-like input to unwrap. Supported values include Site,
Sites, EDIFile, EDICollection, path-like inputs,
or iterables containing site/EDI-like objects.
as_collection (bool, default False) – If True, return an EDICollection.
Otherwise a single input returns one EDI object and multi-item
inputs return a list.
copy (bool, default False) – If True, return best-effort deep copies of the EDI objects.
If copying fails for an item, that item is returned unchanged.
recursive (bool, default True) – Forwarded to path-like discovery through EDICollection.
on_dup ({'replace', 'keep', 'keep_first', 'keep_last', 'raise'}, default 'replace') – Duplicate station policy. replace and keep are forwarded
to path loading. keep_first, keep_last, and raise are
enforced after collection construction.
strict (bool, default False) – If True, raise when an object cannot be unwrapped to EDI.
If False, invalid items are skipped.
verbose (int, default 0) – Verbosity forwarded to collection construction and duplicate
policy diagnostics.
progress (bool or {'auto'}, default False) – Enable progress display while unwrapping iterable inputs.
Returns:
Raw EDI object(s), depending on the input shape and
as_collection.
The operation is shallow by default. It returns the same EDI objects
wrapped by Site or Sites. Pass copy=True when the caller
should be able to mutate the returned objects independently.
Rotate impedance tensor Z (and tipper T, if present) by an
azimuthal angle in degrees.
The rotation is applied in the horizontal plane using the
similarity transform \(Z' = R Z R^{-1}\), where \(R\)
is the 2x2 rotation matrix built from angle_deg. When a
tipper is available (either on the EDI object as T /
TIP / Tip or attached to Z), the 2-component
vector is rotated consistently.
Parameters:
site (Any) – An EDI-like object (e.g., pycsamt.seg.edi.EDIFile) or
wrapper exposing a Z section compatible with a
complex 2x2 impedance array and, optionally, a tipper.
angle_deg (float) – Rotation angle in degrees. Positive values rotate the
measurement axes according to the internal convention of
this package. If your acquisition system defines the sign
oppositely, use the negative of your desired angle.
inplace (bool, optional) – If True, mutate site in place. Otherwise, work on
a shallow copy and return that copy. Default is
False.
Returns:
The rotated object. If inplace is True, this is
the same object as site; otherwise a new object.
Error arrays (z_error or aliases) are rotated with a
magnitude-only scheme (using absolute values of the
rotation matrices) as a pragmatic best-effort. This is a
common, but approximate, practice.
Only arrays with shapes consistent with MT tensors
((n,2,2) for Z, (n,2) for T) are rotated. Other
shapes are ignored silently.
The function is no-throw by design. If a section is not
present or incompatible, it is skipped.
Examples
>>> frompycsamt.seg.ediimportEDIFile>>> frompycsamt.site.editimportrotate>>> ed=EDIFile("path/to/station.edi")>>> ed_rot=rotate(ed,30.0)# copy by default>>> ed_rot2=rotate(ed,-45.0,inplace=True)
Subset the dataset along frequency by range or explicit
indices, keeping all affected arrays aligned.
This applies the selection to every frequency-indexed array
found on the object, including Z, Z errors, derived
resistivity/phase, and any tipper arrays resident on either
the root EDI object or under its Z section.
Parameters:
site (Any) – An EDI-like object (e.g., pycsamt.seg.edi.EDIFile)
with a discoverable frequency vector.
fmin (float, optional) – Keep rows with freq>=fmin. Ignored if None.
fmax (float, optional) – Keep rows with freq<=fmax. Ignored if None.
keep (Iterable[int] or numpy.ndarray, optional) – Explicit indices or a boolean mask to keep. If provided,
fmin and fmax are ignored. Use integer indices
for exact row picks, or a boolean mask of the same length
as the frequency vector.
inplace (bool, optional) – If True, mutate site in place. Otherwise, operate
on a shallow copy. Default is False.
Returns:
The object after selection. If inplace is True,
this is the same object as site; otherwise a new
object.
Rename a station using an explicit name or a policy function.
This updates common station identifiers across the EDI header
and attempts to keep them in sync so that downstream code
resolves the new name consistently.
Parameters:
site (Any) – An EDI-like object (e.g., pycsamt.seg.edi.EDIFile) or
wrapper with a modifiable HEAD section.
name (str, optional) – Explicit new station name to set. If provided, this takes
precedence over policy.
policy (Callable[[str], str], optional) – A function mapping the current station name to a new one.
Ignored when name is provided.
inplace (bool, optional) – If True, mutate site in place. Otherwise, operate
on a shallow copy. Default is False.
Returns:
The object with updated identifiers. If inplace is
True, this is the same object as site; otherwise a
new object.
The function writes multiple header fields when present
(e.g., dataid, station, and other common aliases)
and also mirrors the name to edi.name. This increases
the chance that name resolution remains stable across
different readers.
The rename operation does not touch on-disk filenames. File
paths remain unchanged unless you later write out using a
template that depends on the station name.
Only the values explicitly provided are updated. The call
delegates to the same coordinate writer used by the Site
API, so downstream tools see consistent lat, lon, and elev
fields.
Parameters:
site (Any) – An EDI-like object (e.g., pycsamt.seg.edi.EDIFile)
or wrapper exposing a mutable HEAD section.
lat (float, optional) – Latitude in degrees. If None, the field is left
unchanged.
lon (float, optional) – Longitude in degrees. If None, the field is left
unchanged.
elev (float, optional) – Elevation in meters. If None, the field is left
unchanged.
inplace (bool, optional) – If True, mutate site in place. Otherwise, work
on a shallow copy and return that copy. Default is
False.
Returns:
The updated object. If inplace is True, this is
the same object as site; otherwise a new object.
Replace missing or non-finite values in Z and/or tipper
arrays with zeros or NaNs.
The operation preserves shapes and alignment across arrays.
If an array is absent, a new one is allocated with the
correct shape inferred from the frequency vector.
Parameters:
site (Any) – An EDI-like object with a discoverable frequency vector
and optionally Z and tipper sections.
how ({"zero", "nan"}, optional) – Replacement policy. Use "zero" to fill with numeric
zeros. Use "nan" to fill with NaN for all non-finite
entries. Default is "zero".
components (Iterable[str], optional) – Which components to process. Accepts items like
"Z" or "Tip" (case-insensitive). Default is
("Z","Tip").
inplace (bool, optional) – If True, mutate in place. Otherwise, operate on a
shallow copy and return that copy. Default is False.
Returns:
The object after filling. If inplace is True,
this is the same object as site; otherwise a new
object.
Z arrays are expected as shape (n,2,2) and tipper as
(n,2). Only arrays with the expected shapes are
modified or allocated.
When Z exists, the function also fills common aliases for
errors and derived quantities, such as z_error,
rho (resistivity), and phase arrays, if present.
The frequency vector length n defines the number of
rows used for any new arrays.
This function is no-throw by design. Incompatible or absent
pieces are skipped silently.
Examples
Fill Z and tipper with zeros where values are non-finite:
Recompute apparent resistivity and phase from the impedance
tensor Z for a single site.
The function looks for a Z section and, if present, calls
its compute_resistivity_phase() method. The operation is
best-effort and suppresses exceptions.
Parameters:
site (Any) – An EDI-like object (EDIFile) or a wrapper exposing a
Z section with the expected API.
inplace (bool, optional) – If True, mutate the given object in place. Otherwise
work on a shallow copy and return it. Default is
False.
Returns:
The mutated object (in place) or a new object (copy).
Rotate every site in a collection by an azimuthal angle in
degrees.
This is the broadcast variant of rotate(). It accepts
either a Sites wrapper or any iterable of EDI-like
objects and returns a new Sites unless inplace is
requested.
Parameters:
sites (Any) – A pycsamt.site.base.Sites instance or any iterable
of EDI-like objects.
angle_deg (float) – Rotation angle in degrees, passed through to
rotate().
inplace (bool, optional) – If True, attempt to apply the rotation in place on
the given container. Otherwise, return a new Sites.
Default is False.
Returns:
A sites collection holding the rotated items, or the
original container when mutated in place.
Subset all sites in a collection along frequency, keeping
arrays aligned.
This is the broadcast variant of select_freq(). It
accepts a Sites wrapper or any iterable of EDI-like
objects and returns a new Sites unless inplace is
requested.
Parameters:
sites (Any) – A pycsamt.site.base.Sites instance or any iterable
of EDI-like objects.
fmin (float, optional) – Keep rows with freq>=fmin. Ignored if None.
fmax (float, optional) – Keep rows with freq<=fmax. Ignored if None.
keep (Iterable[int] or numpy.ndarray, optional) – Explicit indices or a boolean mask to keep. If provided,
fmin and fmax are ignored.
inplace (bool, optional) – If True, attempt to modify the given container in
place. Otherwise, return a new Sites. Default is
False.
Returns:
A sites collection with selection applied, or the
original container when mutated in place.
This is the broadcast variant of rename(). It accepts a
Sites wrapper or any iterable of EDI-like objects and
produces a new Sites (unless inplace is True).
policy (Callable[[str], str], optional) – Function mapping the current station name to a new one,
e.g. lambdan:f"X_{n}". Ignored if name_fn is
provided.
name_fn (Callable[[Any], str], optional) – Function mapping each EDI object to a new name, e.g. from
the file stem. This takes precedence over policy and
is useful to guarantee uniqueness across sites.
inplace (bool, optional) – If True, attempt to modify the given container in
place. Otherwise, return a new Sites. Default is
False.
Returns:
A collection holding the renamed items, or the original
container when mutated in place.
The rename updates common header identifiers and mirrors
the name to edi.name for robust downstream resolution.
If multiple sites share the same original name, a simple
policy like lambdan:"X_"+n may produce duplicate
outputs. Prefer name_fn that uses a unique attribute
(e.g., the file stem) to avoid collisions.
The function preserves input order and is no-throw; items
that cannot be renamed are skipped.
Set site coordinates for many EDI files from a table.
This high-level helper accepts a wide range of table-like
objects (CSV path, pandas DataFrame, numpy structured array,
or list of dicts / tuples). It normalizes column names,
optionally projects easting/northing to lon/lat, builds a
mapping {station:(lat,lon,elev)}, and delegates to
set_coords_all().
Parameters:
sites (Any) – A Sites instance, an iterable
of EDIFile objects, or anything accepted by
set_coords_all().
columns (dict, optional) – Explicit column mapping. Keys are canonical names and
values are the actual column names present in table.
Supported canonical keys are:
'station', 'lat', 'lon', 'elev',
'easting', 'northing'. Matching is case-insensitive.
crs_from (str, optional) – Source CRS used when the table provides easting and
northing instead of lat and lon. Required in
that case. Example: 'EPSG:32631' for UTM 31N.
to_crs (str, default "EPSG:4326") – Target CRS for output coordinates. The default is WGS84
lon/lat.
inplace (bool, default False) – If True, mutate the given collection and return it.
Otherwise return a new Sites
with updated EDI objects.
Returns:
The same semantics as set_coords_all(): either the
mutated input (inplace=True) or a new
Sites instance.
ValueError – If the station column cannot be resolved, or if neither
(lat, lon) nor (easting, northing) can be
resolved, or if crs_from is required but missing.
ImportError – If projection is needed (easting/northing present)
but pyproj is not installed.
Notes
Column detection is case-insensitive and understands common
aliases:
station: station, name, site, id.
lat: lat, latitude.
lon: lon, long, longitude.
elev: elev, elevation, z.
easting: easting, x.
northing: northing, y.
When both geographic and projected fields are present, the
geographic pair (lat, lon) is preferred. If only
projected fields are present, a valid crs_from must be
provided and pyproj will be used for projection.
Examples
Load from a CSV path with standard columns:
>>> frompycsamt.site.editimportset_coords_from_table>>> frompycsamt.site.baseimportSites>>> edis=Sites([...])# your EDI files>>> out=set_coords_from_table(... edis,"coords.csv",inplace=False... )>>> isinstance(out,Sites)True
Pass a DataFrame with aliases and an explicit mapping:
Project (easting, northing) to lon/lat and set a site’s coords.
This convenience wraps projection and assignment for a single
EDI site. It projects the provided easting/northing from
crs_from to to_crs (default WGS84 lon/lat), then calls
set_coords().
Parameters:
site (Any) – A single EDI-like object compatible with
set_coords().
easting (float) – Easting value in meters for the source CRS.
northing (float) – Northing value in meters for the source CRS.
crs_from (str) – The EPSG or PROJ string that identifies the source CRS,
for example 'EPSG:32631' for UTM 31N.
elev (float, optional) – Elevation in meters to store in the EDI header. If not
provided, the previous elevation is kept (if any).
to_crs (str, default "EPSG:4326") – Target CRS for output coordinates. The default is WGS84
lon/lat.
inplace (bool, default False) – If True, mutate the given object and return it.
Otherwise work on a copy and return the copy.
Returns:
The mutated site (inplace=True) or a new site object
with updated coordinates.
Exception – Any errors raised by the underlying projection engine or
by set_coords() may propagate.
Notes
Projection uses pyproj with always_xy=True so that
the axis order is interpreted as (lon, lat). Units are assumed
to be meters for the easting and northing values.
String patterns support a minimal glob syntax. * matches
any sequence (possibly empty) and ? matches any single
character. If you need full regular expressions, pass a
compiled re.Pattern.
When multiple patterns are given, the match is an OR over all
patterns. Matching uses the station name as returned by
station_name(ed) which reflects header normalization.
Select sites by zero-based numeric indices, supporting negative
indices.
Indices are normalized exactly like Python sequence indexing:
-1 addresses the last item, -2 the one before last,
and so on. Out-of-range or non-integer indices are ignored.
The resulting subset preserves the original ordering of the
selected items, not the order in which indices are provided.
Parameters:
sites (Any) – A Sites instance, an
EDICollection, a sequence of EDIFile objects,
or any iterable yielding EDI-like objects.
indices (Iterable[int] or int) – One index or an iterable of indices. Negative indices
are supported and mapped to their Python equivalents.
Returns:
A new Sites wrapper containing only items at the
requested positions. If no valid indices remain after
normalization, an empty Sites is returned.
Duplicate indices are de-duplicated in the output since the
selection is implemented as a membership test over the set
of normalized indices. The relative order of kept items is
the same as in the original sequence.
Examples
>>> frompycsamt.site.baseimportSites>>> frompycsamt.site.selectionimportby_index>>> sites=Sites([e1,e2,e3])# names: A, B, C>>> out=by_index(sites,[0,-1])# first and last>>> [s.nameforsinout]['A', 'C']
>>> out=by_index(sites,1)# single integer>>> [s.nameforsinout]['B']
>>> out=by_index(sites,[10,-10])# both invalid -> empty>>> len(out)0
Select sites whose stored chainage falls within a closed
interval.
This helper reads the chainage value first from the EDI
HEAD section (head.chainage) and, if missing, from a
top-level attribute edi.chainage. Sites for which a
numeric chainage cannot be determined are silently skipped.
Parameters:
sites (Any) – A Sites instance, an
EDICollection, a sequence of EDIFile objects, or
any iterable yielding EDI-like items.
Chainage is a linear reference commonly used along profiles
or lines, typically measured in meters from a chosen origin.
If chainage is not present on a site, that site is excluded.
The original order of sites is preserved among the kept
items.
Select sites that contain at least one data row with
frequency inside a closed interval.
A site is kept if its frequency array f contains any
finite value satisfying \(fmin \le f \le fmax\). Sites
with empty or non-finite frequency arrays are skipped.
Parameters:
sites (Any) – A Sites instance, an
EDICollection, a sequence of EDIFile objects, or
any iterable yielding EDI-like items.
Frequencies are obtained via
pycsamt.site.utils.get_freq(ed). The check is membership
based (any row in range), not a full slicing or resampling.
Use pycsamt.site.edit.select_freq() to actually subset
rows by frequency.
This is a simple axis-aligned test in lat/lon and does not
handle antimeridian wrapping. If longitudes cross the
antimeridian (for example, from 170 to -170 deg), split the
selection into two boxes and union the results. Coordinates
are retrieved via
pycsamt.site.utils.get_coords().
Select sites using a user-supplied predicate function.
The predicate is called for each EDI-like object and should
return True to keep the site. Any exception raised by the
predicate is caught and treated as a False (site is not
kept). This makes bulk filtering robust against occasional
data issues.
Parameters:
sites (Any) – A Sites instance, an
EDICollection, a sequence of EDIFile objects, or
any iterable yielding EDI-like items.
pred (Callable[[Any], bool]) – Function receiving a single EDI-like object and returning
a boolean.
Returns:
A new Sites wrapper containing only the sites for
which pred(site) returned True.
This function is intended as a coarse pre-filter to remove
empty placeholders and fully invalid sites before more costly
processing. It does not inspect errors or phases, and it does
not modify the data. If a site has a Z container but all
arrays are missing or fully non-finite, the site is dropped.
Filter out sites whose maximum phase-error exceeds a threshold.
For each site, the function inspects the phase-error array
when present (common attribute names are tried, e.g.
_phase_err or phase_err). If no phase-error array is
found, the site is conservatively kept. Otherwise, the
site is kept only when the maximum finite phase-error is less
than or equal to thresh.
Parameters:
sites (Any) – A Sites object, an
EDICollection, a sequence of EDIFile objects, or
any iterable yielding EDI-like items.
thresh (float) – Threshold on phase-error (same units as stored by the
processing pipeline, usually degrees).
Returns:
New wrapper containing only sites that pass the phase
error test.
The check uses a “best effort” attribute lookup and ignores
non-finite values during the maximum computation. If the
phase-error array is entirely missing, the site is kept.
This behavior makes the filter robust when some sites did not
store uncertainty products.
This is a coarse, fast filter that checks structural
presence and basic array availability. It does not test
for NaN-only content; for that, consider
pycsamt.site.selection.keep_finite_z().
This computes a 2D geoelectric strike angle in degrees. The
routine supports either a single site or many sites. For a
single site a scalar angle is returned. For multiple sites a
pandas.DataFrame is returned with one row per site.
Parameters:
obj (Any) – A single EDI-like object (e.g. EDIFile) or an iterable
of EDI-like objects. Each item must expose a .Z section
of shape (n_freq,2,2) or be convertible to such.
where \(Z'\) is the rotated tensor. The returned
angle is the argmin over a 1 degree grid in 0..179.
The "phase_diff" fallback returns 0 if
median \(\\lvert Z_{xy} \rvert \ge
\lvert Z_{yx} \rvert\), else 90. It is intended for
degraded or sparse data.
This function does not alter data. If you need
deterministic behavior for incomplete arrays, consider
preparing tensors with
pycsamt.site.edit.fill_missing().
Evaluate apparent resistivity at a target frequency.
Computes apparent resistivity for the \(Z_{xy}\) and
\(Z_{yx}\) components at a requested frequency. Works with a
single site or a collection. For a single site, a dict is
returned. For multiple sites, a pandas.DataFrame is returned.
Parameters:
obj (Any) – A single EDI-like object (e.g. EDIFile) or an iterable of
such objects. Each item must expose a .Z section of shape
(n_freq,2,2) and a frequency vector.
If obj is a single site, returns a dictionary with keys
"res_xy", "res_yx", "f_used". If obj is
iterable, returns a DataFrame with columns
station, res_xy, res_yx, f_used.
\[\begin{split}\rho_a = \frac{\lvert Z \rvert^2}
{\mu_0\,2\pi\\,f} ,\end{split}\]
where \(Z\) is the complex impedance for the selected
component, \(\\mu_0\) is the magnetic permeability of free
space, and \(f\) is frequency in Hz.
When how="interp", the function first computes
\(\rho_a\) at all native frequencies, then interpolates the
result to the query frequency using linear interpolation in
frequency. If the frequency vector or impedance is missing,
NaN values are returned.
For each site, this computes the least-squares slope of phase
(degrees) versus \(\log_{10}(f)\) over the requested band.
Two slopes are reported, one for \(Z_{xy}\) and one for
\(Z_{yx}\).
If a single site is provided, a dictionary is returned. If an
iterable of sites is provided, a pandas.DataFrame is
returned with one row per station.
Parameters:
obj (Any) – A single EDI-like object (e.g. EDIFile) or an iterable
of such objects.
band (tuple of float) – Inclusive frequency band as (fmin,fmax) in Hz. The
order does not matter; the function uses the numeric min and
max.
where \(T_x, T_y\) are the complex tipper components. The
result can be returned as per-frequency values or summarized
statistics.
For a single site, returns a dict. For an iterable of sites,
returns a pandas.DataFrame.
Parameters:
obj (Any) – A single EDI-like object (e.g. EDIFile) or an iterable
of such objects. The tipper may be attached as ed.Tip,
ed.T, or ed.TIP and must expose a 2-component array
shaped (n_freq,2) or (n_freq,1,2).
per_freq (bool, optional) – If False (default), return summary statistics
(mean, median, max). If True, return per-frequency
values.
If the site has no tipper section, summary statistics are
NaN and per-frequency mode yields an empty result for that
site. To initialize missing arrays, consider
pycsamt.site.edit.fill_missing() with components=("Tip",).
Frequencies are reported from the site frequency vector. The
function assumes the tipper array and frequency vector are
aligned along their first dimension.
This is a thin, best-effort adapter around several common EDI
writer spellings. The function will create parent directories
as needed and then try, in order, the following methods on
site until one succeeds:
write(new_edifn=path)
write(path)
to_file(path)
save(path)
If none of these exist or succeed, a RuntimeError is raised.
Parameters:
site (Any) – An EDI-like object. It can be a pycsamt.seg.edi.EDIFile
or any object exposing one of the writer methods listed
above.
path (str or pathlib.Path) – Destination file path. Parent directories are created
if they do not exist.
This function does not enforce overwrite policy. Whether an
existing file is replaced depends on the underlying writer
implementation of the provided site object.
Write a collection of sites to a directory using a filename
template.
The function accepts many input forms (Sites, an
EDICollection, any iterable of EDI-like objects, or a single
object) and writes each item to outdir. Filenames are
rendered from a context and the template string.
Supported template keys (filled via a safe formatter):
{station} : current station name
{index} : zero-based index in the iteration order
{lat}, {lon}, {elev} : header coordinates, or NaN
{chainage} : optional header chainage, or NaN
If the rendered name does not end with .edi, the extension
is appended automatically.
Parameters:
sites (Any) – A Sites instance, an EDICollection, any iterable of
EDI-like objects, or a single EDI-like object. EDI-like means
it implements one of: write(new_edifn=...), write(...),
to_file(...), or save(...).
outdir (str or pathlib.Path) – Output directory. It is created if it does not exist.
template (str, optional) – Filename template. Defaults to "{station}.edi".
exist_ok (bool, optional) – If False (default), raise FileExistsError on the first
name collision inside outdir. If True, allow
overwriting subject to the writer behavior.
manifest_csv (str or pathlib.Path or None, optional) – If provided, write a CSV manifest with one row per written
site. Columns are:
index,station,lat,lon,elev,chainage,filename,path.
Returns:
Paths to the files written, in the same order as the input
iteration.
The index used in templating and in the manifest is the
zero-based position in the input order. Coordinate fields come
from the EDI header when available; missing values are written
as NaN.
Examples
>>> frompathlibimportPath>>> frompycsamt.site.exportimportwrite_sites>>> classEdiToFile:... def__init__(self,name):self._n=name... defto_file(self,p):... Path(p).write_text(f"# {self._n}\\n",encoding="utf-8")... # station name is taken from header helpers when present,... # but the template can still use {index}....>>> outdir=Path("eds_out")>>> paths=write_sites(... [EdiToFile("S01"),EdiToFile("S02")],... outdir,... template="{index:03d}_{station}"... )>>> [p.exists()forpinpaths][True, True]
>>> # Write with a manifest>>> mpath=Path("eds_out")/"manifest.csv">>> _=write_sites(... [EdiToFile("S01"),EdiToFile("S02")],... outdir,... template="{station}",... exist_ok=True,... manifest_csv=mpath,... )>>> mpath.exists()True
Pack a set of sites into a zip archive using a filename template.
Each input item is written to a temporary directory first, then
added to the out_zip archive using ZIP_DEFLATED. Filenames
inside the archive are rendered from the same context as in
write_sites(). If a name lacks the .edi suffix, it is
appended automatically.
Optionally, a CSV manifest can be written alongside the archive.
Parameters:
sites (Any) – A Sites instance, an EDICollection, any iterable of
EDI-like objects, or a single EDI-like object.
out_zip (str or pathlib.Path) – Destination zip file path. Parent directories are created as
needed.
template (str, optional) – Filename template for entries stored in the archive.
Defaults to "{station}.edi".
manifest_csv (str or pathlib.Path or None, optional) – If provided, write a CSV manifest next to the zip. Columns:
index,station,lat,lon,elev,chainage,filename,path.
Files are staged in a temporary directory and then compressed
with zipfile.ZIP_DEFLATED. The index used in templating
and the manifest corresponds to the input iteration order. This
function does not delete or modify any original EDI sources.
Recompute and rewrite EDI files using pyCSAMT conventions.
This class is a workflow layer over the lower-level site
helpers. It accepts EDI objects, EDI collections, files,
line folders, or survey folders, applies a sequence of
optional normalizations, and can write pyCSAMT-generated
EDI files to a new output tree.
Parameters:
output_root (str or pathlib.Path, optional) – Root directory for recomputed EDI files. If omitted,
a recomputed_edis directory is created next to a
selected line folder, or inside a selected survey folder.
output_name (str, default "recomputed_edis") – Directory name used when output_root is not provided.
preserve_line_dirs (bool, default True) – If True, write each inferred line into its own
subdirectory under output_root. If False, write
all recomputed EDI files directly under output_root.
template (str, default "{station}.edi") – Filename template. Available keys are station,
index, line, and source_stem.
The operation is copy-returning by default. It can rotate
transfer functions, subset frequencies, fill missing values,
recompute apparent resistivity/phase, and rename station ids.
api (bool or None, default None) – True forces API view wrapping; False returns a bare pandas
dataframe; None (default) defers to the global
PYCSAMT_API_VIEW setting.
sites (Sites-like) – Any iterable of Site-like objects.
Examples
frompycsamt.site.reportimportSitesReportrep=SitesReport(sites)rep.report()# full survey panel + per-station tablerep.report(top=10)# first 10 stations onlydf=rep.to_dataframe()# one row per station