pycsamt.api#

Public API configuration objects, style controls, CLI parameter helpers, table/result view objects, and high-level reader functions.

Public API helpers shared across pyCSAMT packages.

class pycsamt.api.TopoConfig(enabled=False, source='sites', elev_array=None, elev_file=None, interp_method='linear', exaggeration=1.0, fill_color='#a89070', fill_alpha=0.4, line_color='#6b4e2a', line_width=1.2, show_surface_line=True, clip_below_surface=True, station_pins_at_surface=True, show_topo_strip=True, strip_height_ratio=0.18, marker_pad_fraction=0.015)#

Bases: object

Package-wide topography rendering policy for 2-D section plots.

Once configured, the settings apply to every 2-D section plot (pseudosections, inversion sections, interpretation panels) until reset() is called.

Variables:
  • enabled (bool) – Master switch. False → stations appear at a flat z = 0 datum (default). True → terrain-following geometry active.

  • source ({"sites", "file", "array"}) – Where to read elevation data from. "sites" — read .elev from each Site’s EDI HEAD (default). "file" — load from elev_file (CSV / parquet). "array" — use the elev_array ndarray directly.

  • elev_array (array-like or None) – External elevation values (m a.s.l.) when source="array". Must have one value per station in profile order.

  • elev_file (str or None) – Path to a tabular file when source="file". Expected columns: station, elevation (or lat / lon / elevation).

  • interp_method ({"linear", "cubic", "nearest"}) – Method for interpolating station elevations to intermediate x positions on the section grid.

  • exaggeration (float) – Vertical exaggeration factor applied to the elevation profile during rendering. 1.0 = true scale.

  • fill_color (str) – Matplotlib color for the above-surface terrain fill polygon.

  • fill_alpha (float) – Opacity of the terrain fill (0–1).

  • line_color (str) – Color of the terrain surface polyline.

  • line_width (float) – Line width of the terrain surface polyline.

  • show_surface_line (bool) – Draw the surface polyline on top of the terrain fill.

  • clip_below_surface (bool) – Mask model cells that lie above the terrain surface (set to NaN).

  • station_pins_at_surface (bool) – Place station marker triangles at the real terrain elevation instead of at the flat z = 0 datum.

  • show_topo_strip (bool) – For period-vs-station pseudosections: add a thin elevation profile strip above the main colour image.

  • strip_height_ratio (float) – Height of the topo strip relative to the main axes (0–1).

Parameters:
  • enabled (bool)

  • source (str)

  • elev_array (Any)

  • elev_file (str | None)

  • interp_method (str)

  • exaggeration (float)

  • fill_color (str)

  • fill_alpha (float)

  • line_color (str)

  • line_width (float)

  • show_surface_line (bool)

  • clip_below_surface (bool)

  • station_pins_at_surface (bool)

  • show_topo_strip (bool)

  • strip_height_ratio (float)

  • marker_pad_fraction (float)

enabled: bool = False#
source: str = 'sites'#
elev_array: Any = None#
elev_file: str | None = None#
interp_method: str = 'linear'#
exaggeration: float = 1.0#
fill_color: str = '#a89070'#
fill_alpha: float = 0.4#
line_color: str = '#6b4e2a'#
line_width: float = 1.2#
show_surface_line: bool = True#
clip_below_surface: bool = True#
station_pins_at_surface: bool = True#
show_topo_strip: bool = True#
strip_height_ratio: float = 0.18#
marker_pad_fraction: float = 0.015#
configure(**kw)#

Set one or more configuration attributes by keyword.

Parameters:

kw (Any)

Return type:

TopoConfig

context(**kw)#

Temporarily override config values, then restore them.

Parameters:

kw (Any)

Return type:

Generator[TopoConfig, None, None]

reset()#

Restore all attributes to package defaults.

Return type:

None

clone()#

Return a deep copy of this config.

Return type:

TopoConfig

is_active_for(y_type)#

Return True when topo rendering should fire for a given y-axis type.

Topo only makes physical sense when the y-axis represents a real spatial quantity (depth, elevation, skin depth). Period and frequency pseudosections carry no elevation information — topo rendering is silently skipped for those.

Parameters:

y_type (str) – String tag describing what the y-axis represents. Recognised depth-like values: "depth", "elevation", "elev", "skin_depth", "z". Recognised freq-like values: "period", "frequency", "freq", "per", "t", "f".

Return type:

bool

summary()#

One-line status string.

Return type:

str

pycsamt.api.configure_topo(**kw)#

Configure the global PYCSAMT_TOPO singleton.

Parameters:

**kw (Any) – Keyword arguments forwarded to TopoConfig.configure().

Return type:

None

Examples

>>> from pycsamt.topo import configure_topo
>>> configure_topo(enabled=True, exaggeration=2.0)
pycsamt.api.reset_topo()#

Reset PYCSAMT_TOPO to package defaults.

Return type:

None

class pycsamt.api.PipelineAPIConfig(output_root='pipe_results', processed_subdir='processed', plots_subdir='plots', on_step_error='warn', save_intermediate=False, show_progress=True, progress_style='bar', repr_width=80, plot_dpi=150, plot_fmt='png', report_formats=<factory>)#

Bases: object

Runtime configuration for the pyCSAMT pipeline engine.

Variables:
  • output_root (str) – Default root directory when no outdir is passed to run().

  • processed_subdir (str) – Sub-directory inside output_root that receives the processed EDI files.

  • plots_subdir (str) – Sub-directory inside output_root that receives all QC figures, organised into one sub-folder per pipeline step.

  • on_step_error (str) – Behaviour when a step raises an exception. "raise" re-raises immediately; "warn" logs a warning and continues with the previous sites; "skip" is silent.

  • save_intermediate (bool) – If True, EDI files are also written after each step (into plots_subdir/<step>/edi_snapshot/).

  • show_progress (bool) – Enable console progress output while the pipeline runs.

  • progress_style (str) – "bar" – tqdm-style progress bar (requires tqdm; falls back to "log" when unavailable). "log" – one line per step. "silent" – no output.

  • repr_width (int) – Character width used when printing the pipeline summary.

  • plot_dpi (int) – DPI for saved figures.

  • plot_fmt (str) – File extension / format for saved figures ("png", "pdf", "svg").

  • report_formats (tuple) – Sequence of report types to write. Each item must be "html" or "txt".

Parameters:
  • output_root (str)

  • processed_subdir (str)

  • plots_subdir (str)

  • on_step_error (str)

  • save_intermediate (bool)

  • show_progress (bool)

  • progress_style (str)

  • repr_width (int)

  • plot_dpi (int)

  • plot_fmt (str)

  • report_formats (tuple)

output_root: str = 'pipe_results'#
processed_subdir: str = 'processed'#
plots_subdir: str = 'plots'#
on_step_error: str = 'warn'#
save_intermediate: bool = False#
show_progress: bool = True#
progress_style: str = 'bar'#
repr_width: int = 80#
plot_dpi: int = 150#
plot_fmt: str = 'png'#
report_formats: tuple#
configure(**kw)#

Set one or more configuration attributes by keyword.

Parameters:

kw (Any)

Return type:

None

context(**kw)#

Temporarily override config values, then restore them.

Parameters:

kw (Any)

Return type:

Generator[PipelineAPIConfig, None, None]

reset()#

Restore all attributes to package defaults.

Return type:

None

clone()#

Return a deep copy of this config.

Return type:

PipelineAPIConfig

pycsamt.api.configure_pipe(**kw)#

Configure the global PYCSAMT_PIPE singleton.

Parameters:

kw (Any)

Return type:

None

pycsamt.api.reset_pipe()#

Reset PYCSAMT_PIPE to package defaults.

Return type:

None

class pycsamt.api.AgentConfig#

Bases: object

Global LLM configuration singleton for all pycsamt agents.

BaseAgent calls resolve() on every instantiation and get_rate() + _add_spend() on every LLM call, so keys, rates, and the budget cap set here apply automatically to every agent in the session.

:param (none — use configure() after construction):

Variables:
  • provider (str or None) – Currently active LLM provider.

  • model (str or None) – Resolved model (explicit override or provider default).

  • api_key (str or None) – Resolved key for the active provider (stored key → env var → None).

  • is_configured (bool) – True when a provider and a resolvable key are both present.

  • spent_usd (float) – Accumulated LLM spend this session.

  • remaining_usd (float or None) – Remaining budget, or None when no cap is set.

Examples

from pycsamt.api.agents import AGENT_CONFIG

# one-call setup
AGENT_CONFIG.configure(provider="claude", api_key="sk-ant-…")

# pricing — override a rate (USD / 1 M tokens)
AGENT_CONFIG.set_rate("claude", "claude-opus-4-8",
                      input=12.0, output=60.0)

# pricing — add a model not in the built-in table
AGENT_CONFIG.set_rate("openai", "gpt-5-turbo", input=5.0, output=20.0)

# budget cap
AGENT_CONFIG.set_budget(usd=5.0)
print(AGENT_CONFIG.remaining_usd)   # 5.0

# inspect
print(AGENT_CONFIG.info())

# reset
AGENT_CONFIG.reset()
configure(*, provider, api_key, model=None)#

Set the active provider, key, and optional model in one call.

Parameters:
  • provider ({"claude", "openai", "gemini"}) – LLM provider to activate.

  • api_key (str) – API key for provider. Stored per-provider so switching away and back does not require re-supplying the key.

  • model (str or None) – Model identifier override. None uses the provider default.

Returns:

self — allows chaining.

Return type:

AgentConfig

Examples

AGENT_CONFIG.configure(provider="claude", api_key="sk-ant-…")
AGENT_CONFIG.configure(
    provider="openai",
    api_key="sk-…",
    model="gpt-4o-mini",
)
set_key(provider, api_key)#

Store an API key for provider without changing the active provider.

Useful for pre-loading keys for multiple providers so you can switch() between them without re-supplying credentials.

Parameters:
  • provider (str)

  • api_key (str)

Returns:

self.

Return type:

AgentConfig

Examples

AGENT_CONFIG.set_key("claude", "sk-ant-…")
AGENT_CONFIG.set_key("openai", "sk-…")
AGENT_CONFIG.set_key("gemini", "AIza…")
AGENT_CONFIG.switch("claude")
switch(provider, *, model=None)#

Switch the active provider.

The key for provider must have been stored via configure() or set_key(), or be available as an environment variable.

Parameters:
  • provider (str)

  • model (str or None) – Override the model for this provider. None keeps the current model override (or uses the provider default).

Returns:

self.

Return type:

AgentConfig

Examples

AGENT_CONFIG.switch("openai")
AGENT_CONFIG.switch("gemini", model="gemini-2.0-flash")
reset(*, keys=True)#

Clear the active configuration, custom rates, and budget.

Parameters:

keys (bool) – When True (default) also wipe all stored per-provider keys. Pass False to clear only the active provider / model while keeping stored keys available for future switch() calls.

Returns:

self.

Return type:

AgentConfig

Notes

Custom rates and the budget cap/counter are always reset. Call reset_budget() to zero only the spend counter.

set_rate(provider, model, *, input, output)#

Override or add the cost rate for a specific provider + model.

Custom rates take precedence over the built-in table for every cost estimate made by agents in this session.

Parameters:
  • provider (str) – "claude" | "openai" | "gemini"

  • model (str) – Model identifier exactly as passed to the LLM client, e.g. "claude-opus-4-8" or "gpt-5-turbo".

  • input (float) – Cost per 1 000 000 input tokens in USD.

  • output (float) – Cost per 1 000 000 output tokens in USD.

Returns:

self.

Return type:

AgentConfig

Examples

# provider lowered their price
AGENT_CONFIG.set_rate("claude", "claude-opus-4-8",
                      input=12.0, output=60.0)

# a new model not yet in the built-in table
AGENT_CONFIG.set_rate("openai", "gpt-5-turbo",
                      input=5.0, output=20.0)
get_rate(provider, model)#

Return the resolved {"input": …, "output": …} rate.

Resolution order: custom override → built-in table (exact match → prefix match) → provider default.

Parameters:
Return type:

dict with keys "input" and "output" (USD / 1 M tokens).

Examples

rate = AGENT_CONFIG.get_rate("claude", "claude-sonnet-4-6")
# {"input": 3.0, "output": 15.0}
estimate_cost(provider, model, input_tokens, output_tokens)#

Compute the USD cost for one LLM call using the resolved rate.

Respects any rate overrides set via set_rate().

Parameters:
  • provider (str)

  • model (str)

  • input_tokens (int)

  • output_tokens (int)

Return type:

float — estimated cost in USD.

Examples

cost = AGENT_CONFIG.estimate_cost(
    "claude", "claude-sonnet-4-6", 500, 200
)
list_rates(provider=None)#

Return the effective rate table (custom overrides merged with built-in).

Parameters:

provider (str or None) – When given, return only that provider’s table. When None, return all providers.

Return type:

dict — same structure as the built-in table.

Examples

import pprint
pprint.pprint(AGENT_CONFIG.list_rates("claude"))
set_budget(*, usd)#

Set a session spend cap.

Once spent_usd reaches usd, any subsequent LLM call will raise BudgetExceededError before the API call is made.

Parameters:

usd (float) – Maximum spend in USD for this session.

Returns:

self.

Return type:

AgentConfig

Examples

AGENT_CONFIG.set_budget(usd=2.0)
# … after several agent calls …
print(f"${AGENT_CONFIG.spent_usd:.4f} used, "
      f"${AGENT_CONFIG.remaining_usd:.4f} left")
reset_budget(*, cap=False)#

Reset the session spend counter.

Parameters:

cap (bool) – When True also remove the budget cap (set_budget must be called again to re-enable it). Default False — zeroes the counter but keeps the existing cap.

Returns:

self.

Return type:

AgentConfig

Examples

AGENT_CONFIG.reset_budget()          # zero counter, keep cap
AGENT_CONFIG.reset_budget(cap=True)  # zero counter and remove cap
property spent_usd: float#

Accumulated LLM spend this session (USD).

property remaining_usd: float | None#

Remaining budget (USD), or None when no cap is set.

property provider: str | None#

Currently active provider, or None if unconfigured.

property api_key: str | None#

Resolved key for the active provider.

Resolution order: stored key → environment variable → None.

property model: str | None#

Active model (explicit override, or provider default).

property is_configured: bool#

True when a provider and a resolvable key are both present.

resolve(provider, api_key, model)#

Resolve the effective (provider, api_key, model) for an agent.

Called automatically by __init__. Users should not call this directly.

Resolution rules#

If api_key is explicitly given:

Use provider, api_key, and model (or provider default) exactly as supplied. The global config is ignored.

If api_key is None:
  • If provider equals the default "claude" and the global config has an active provider, inherit that provider.

  • Look up the key: stored key → env var.

  • Inherit the model from the global config when the effective provider matches the globally active provider.

Parameters:
  • provider (str)

  • api_key (str | None)

  • model (str | None)

Return type:

tuple[str, str | None, str | None]

info()#

Return a summary dict suitable for display or logging.

The API key is masked to its last four characters for safety.

Returns:

Keys: provider, model, has_key, key_source, stored_providers, custom_rate_models, budget_usd, spent_usd, remaining_usd.

Return type:

dict

using(*, provider=None, api_key=None, model=None)#

Temporarily override the global config inside a with block.

All arguments are optional; omitted values are left unchanged. The original config (including custom rates and budget) is restored on exit even if an exception occurs.

Parameters:
  • provider (str or None)

  • api_key (str or None)

  • model (str or None)

Yields:

AgentConfigself with the override applied.

Return type:

Generator[AgentConfig, None, None]

Examples

with AGENT_CONFIG.using(provider="gemini", api_key="AIza…"):
    r = DataQCAgent().execute(data)
# original provider / key / model restored here
offline()#

Context manager: force truly offline mode in the current thread.

While active, _resolve_key() will not inspect environment variables, so agents created inside the block receive api_key=None even when ANTHROPIC_API_KEY (or similar) is set in the OS environment. Uses threading.local so concurrent requests in other threads are unaffected.

Examples

with AGENT_CONFIG.offline():
    agent = DataQCAgent()  # api_key will be None
Return type:

Generator[AgentConfig, None, None]

exception pycsamt.api.BudgetExceededError(spent, budget)#

Bases: RuntimeError

Raised when an LLM call would be made after the session budget is used.

Variables:
  • spent_usd (float) – Accumulated spend so far this session.

  • budget_usd (float) – The cap that was set.

Parameters:
Return type:

None

pycsamt.api.configure_agents(*, provider, api_key, model=None)#

Configure AGENT_CONFIG in one call and return it.

Equivalent to AGENT_CONFIG.configure(...).

Parameters:
  • provider ({"claude", "openai", "gemini"})

  • api_key (str)

  • model (str or None)

Return type:

AgentConfig

Examples

from pycsamt.agents import configure_agents
configure_agents(provider="claude", api_key="sk-ant-…")
pycsamt.api.reset_agents(*, keys=True)#

Reset AGENT_CONFIG to its unconfigured state.

Equivalent to AGENT_CONFIG.reset(...).

Parameters:

keys (bool) – When True (default) also wipe stored per-provider keys.

Return type:

AgentConfig

class pycsamt.api.MetadataMixin#

Bases: object

Small mixin for attaching free-form object metadata.

The mixin is intentionally separate from PyCSAMTObject so the universal root class remains lightweight.

metadata: dict[str, Any]#
ensure_metadata()#

Return the metadata mapping, creating it when needed.

Return type:

dict[str, Any]

update_metadata(**metadata)#

Update metadata in place and return self.

Parameters:

metadata (Any)

Return type:

MetadataMixin

metadata_dict()#

Return a shallow copy of attached metadata.

Return type:

dict[str, Any]

class pycsamt.api.PyCSAMTObject#

Bases: object

Root object for lightweight pyCSAMT API behavior.

PyCSAMTObject provides a small, dependency-light base for readable object display and shallow introspection. It is not an electromagnetic numerical class and does not assume EDI, MT, TEM, ModEM, Occam, or AI semantics.

Subclasses may override __repr__ or __str__ freely. For smaller customization, define __repr_fields__ or __repr_exclude__ on the subclass.

Variables:
  • __repr_fields__ (iterable of str or None) – Explicit field order for __repr__. If None, dataclass fields, __dict__ keys, and __slots__ names are discovered automatically.

  • __repr_exclude__ (set of str) – Attribute names excluded from automatic displays.

  • __repr_max_fields__ (int) – Maximum number of fields shown in __repr__.

  • __repr_max_string__ (int) – Maximum string length before shortening.

Examples

>>> class Obj(PyCSAMTObject):
...     def __init__(self):
...         self.name = "S001"
...         self.verbose = 2
...         self.values = [1, 2, 3]
>>> repr(Obj())
"Obj(name='S001', values=list(len=3, sample=[1, 2, 3]))"
summary(*, max_fields=None)#

Return a short one-line object summary.

Parameters:

max_fields (int | None)

Return type:

str

to_dict(*, public_only=True, max_depth=1)#

Return a shallow dictionary representation.

Parameters:
  • public_only (bool)

  • max_depth (int)

Return type:

dict[str, Any]

update(**kwargs)#

Set attributes from keyword arguments and validate.

Parameters:

kwargs (Any)

Return type:

PyCSAMTObject

clone(**overrides)#

Return a shallow copy with optional attribute overrides.

Parameters:

overrides (Any)

Return type:

PyCSAMTObject

validate()#

Validate object state.

Subclasses can override this hook. The base implementation intentionally accepts all states.

Return type:

None

class pycsamt.api.PyCSAMTInterp#

Bases: object

Package-wide visual control container for hydro-geophysical plots.

Holds one InterpStyle per named preset. The default preset is what plot classes use when no explicit style= argument is given.

Examples

>>> from pycsamt.api.interp import PYCSAMT_INTERP
>>> PYCSAMT_INTERP.use("publication")
>>> # now all subsequent interp plots use the publication style
>>> with PYCSAMT_INTERP.context("dark"):
...     fig = PlotHydroSection(result).plot()
>>> # reverts
style_for(preset)#

Return the InterpStyle for preset.

Parameters:

preset (str) – One of 'default', 'publication', 'dark', 'accessible'.

Return type:

InterpStyle

use(preset)#

Copy a named preset into the default slot.

After this call, all plot classes that read from PYCSAMT_INTERP will use the chosen preset’s styles.

Parameters:

preset (str) – Name of the preset to activate.

Return type:

None

configure(**kw)#

Configure the default style using sub__field dotted paths.

Examples

>>> PYCSAMT_INTERP.configure(
...     section__cmap_K="plasma",
...     section__wt_color="white",
...     profile__color_wt="royalblue",
...     figsize_section=(10, 4),
... )
Parameters:

kw (Any)

Return type:

None

reset()#

Reset all presets to package defaults.

Return type:

None

context(preset=None, **kw)#

Temporarily override the default style, then restore it.

Parameters:
  • preset (str, optional) – Named preset to activate for the duration of the block.

  • **kw – Additional dotted-path overrides applied after the preset (same semantics as configure()).

Return type:

Generator[PyCSAMTInterp, None, None]

Examples

>>> with PYCSAMT_INTERP.context("publication",
...                             section__wt_lw=0.8):
...     fig = PlotHydroSection(result).plot()
summary()#

Return a human-readable summary of all presets.

Return type:

str

class pycsamt.api.HydroSectionStyle(cmap_K='viridis', cmap_Sw='RdYlBu', cmap_phi='YlOrRd', cmap_timelapse='RdBu_r', cmap_spread='hot_r', cmap_p50='viridis', wt_color='deepskyblue', wt_lw=2.5, wt_ls='--', station_color='k', station_alpha=0.45, station_lw=0.4, cb_fraction=0.025, cb_pad=0.01, cb_fontsize=8, nan_color='0.88', cmap_crossplot='viridis', scatter_alpha=0.6, scatter_size=12.0, hs_alpha=0.12, model_curve_color='k', model_curve_ls='--', model_curve_lw=1.6, rho_curve_color='0.15', rho_fill_color='steelblue', rho_fill_alpha=0.12, zone_boundary_color='0.55', zone_boundary_ls='--', zone_label_fontsize=7)#

Bases: object

Visual parameters for 2-D hydrogeophysical colour sections.

Governs PlotHydroSection, PlotTimeLapseSection, and both panels of PlotUncertaintySection.

Parameters:
  • cmap_K (str) – Colourmap for the hydraulic-conductivity K section (default 'viridis').

  • cmap_Sw (str) – Colourmap for the water-saturation Sw section ('RdYlBu').

  • cmap_phi (str) – Colourmap for the porosity φ section ('YlOrRd').

  • cmap_timelapse (str) – Diverging colourmap for Δlog₁₀ρ and ΔSw time-lapse sections ('RdBu_r').

  • cmap_spread (str) – Colourmap for uncertainty spread (CV or P90–P10) panels ('hot_r' — dark = high uncertainty).

  • cmap_p50 (str) – Colourmap for the P50 estimate panel of PlotUncertaintySection.

  • wt_color (str / float / str) – Water-table overlay: colour, line width, line style.

  • wt_lw (str / float / str) – Water-table overlay: colour, line width, line style.

  • wt_ls (str / float / str) – Water-table overlay: colour, line width, line style.

  • station_color (str / float / float) – Station-tick axvline appearance.

  • station_alpha (str / float / float) – Station-tick axvline appearance.

  • station_lw (str / float / float) – Station-tick axvline appearance.

  • cb_fraction (float / float / int) – Colourbar geometry and tick label size.

  • cb_pad (float / float / int) – Colourbar geometry and tick label size.

  • cb_fontsize (float / float / int) – Colourbar geometry and tick label size.

  • nan_color (str)

  • cmap_crossplot (str)

  • scatter_alpha (float)

  • scatter_size (float)

  • hs_alpha (float)

  • model_curve_color (str)

  • model_curve_ls (str)

  • model_curve_lw (float)

  • rho_curve_color (str)

  • rho_fill_color (str)

  • rho_fill_alpha (float)

  • zone_boundary_color (str)

  • zone_boundary_ls (str)

  • zone_label_fontsize (int)

cmap_K: str = 'viridis'#
cmap_Sw: str = 'RdYlBu'#
cmap_phi: str = 'YlOrRd'#
cmap_timelapse: str = 'RdBu_r'#
cmap_spread: str = 'hot_r'#
cmap_p50: str = 'viridis'#
wt_color: str = 'deepskyblue'#
wt_lw: float = 2.5#
wt_ls: str = '--'#
station_color: str = 'k'#
station_alpha: float = 0.45#
station_lw: float = 0.4#
cb_fraction: float = 0.025#
cb_pad: float = 0.01#
cb_fontsize: int = 8#
nan_color: str = '0.88'#
cmap_crossplot: str = 'viridis'#
scatter_alpha: float = 0.6#
scatter_size: float = 12.0#
hs_alpha: float = 0.12#
model_curve_color: str = 'k'#
model_curve_ls: str = '--'#
model_curve_lw: float = 1.6#
rho_curve_color: str = '0.15'#
rho_fill_color: str = 'steelblue'#
rho_fill_alpha: float = 0.12#
zone_boundary_color: str = '0.55'#
zone_boundary_ls: str = '--'#
zone_label_fontsize: int = 7#
cmap_for(quantity)#

Return the colourmap name for quantity.

Parameters:

quantity (str) – One of 'K', 'saturation', 'porosity', 'timelapse', 'spread', 'p50'.

Return type:

str

wt_kwargs(**overrides)#

Keyword arguments for the water-table ax.plot call.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

station_kwargs(**overrides)#

Keyword arguments for the station-tick ax.axvline calls.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

cb_kwargs(**overrides)#

Keyword arguments forwarded to fig.colorbar.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

crossplot_scatter_kwargs(**overrides)#

Kwargs for the ax.scatter call in a petrophysical cross-plot.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

hs_fill_kwargs(**overrides)#

Kwargs for ax.fill_between of Hashin-Shtrikman bounds.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

model_curve_kwargs(**overrides)#

Kwargs for the model-curve ax.plot call.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

rho_curve_kwargs(**overrides)#

Kwargs for the ρ(z) depth-profile curve.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

zone_boundary_kwargs(**overrides)#

Kwargs for geological zone boundary ax.axhline calls.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

copy(**kw)#

Return a shallow copy with optional field overrides.

Parameters:

kw (Any)

Return type:

HydroSectionStyle

class pycsamt.api.HydroProfileStyle(color_wt='steelblue', color_T='seagreen', envelope_alpha=0.25, p50_lw=2.0, scatter_size=14.0, ref_color='tomato', ref_ls='--', ref_lw=1.4, grid_alpha=0.3, grid_axis='y', station_color='0.6', station_alpha=0.5, station_lw=0.35, color_TR='darkorange', color_S='mediumpurple', tr_threshold=1000.0, s_threshold_moderate=1.0, s_threshold_good=5.0, hist_alpha=0.7, hist_edgecolor='white', hist_bins=30, kde_color='k', kde_lw=1.8)#

Bases: object

Visual parameters for 1-D hydrogeophysical profile plots.

Governs PlotWaterTableProfile and PlotUncertaintyProfile.

Parameters:
  • color_wt (str) – Colour for water-table bars/lines/envelopes ('steelblue').

  • color_T (str) – Colour for transmissivity bars/lines/envelopes ('seagreen').

  • envelope_alpha (float) – Fill-between transparency for P10–P90 bands (0–1).

  • p50_lw (float) – Line width for the P50 central estimate.

  • scatter_size (float) – Marker size for station-value scatter dots.

  • ref_color (str / str / float) – Reference-depth line style (axhline).

  • ref_ls (str / str / float) – Reference-depth line style (axhline).

  • ref_lw (str / str / float) – Reference-depth line style (axhline).

  • grid_alpha (float) – Background grid transparency.

  • grid_axis (str) – 'y', 'x', or 'both'.

  • station_color (str / float / float) – Station-tick axvline appearance.

  • station_alpha (str / float / float) – Station-tick axvline appearance.

  • station_lw (str / float / float) – Station-tick axvline appearance.

  • color_TR (str)

  • color_S (str)

  • tr_threshold (float)

  • s_threshold_moderate (float)

  • s_threshold_good (float)

  • hist_alpha (float)

  • hist_edgecolor (str)

  • hist_bins (int)

  • kde_color (str)

  • kde_lw (float)

color_wt: str = 'steelblue'#
color_T: str = 'seagreen'#
envelope_alpha: float = 0.25#
p50_lw: float = 2.0#
scatter_size: float = 14.0#
ref_color: str = 'tomato'#
ref_ls: str = '--'#
ref_lw: float = 1.4#
grid_alpha: float = 0.3#
grid_axis: str = 'y'#
station_color: str = '0.6'#
station_alpha: float = 0.5#
station_lw: float = 0.35#
color_TR: str = 'darkorange'#
color_S: str = 'mediumpurple'#
tr_threshold: float = 1000.0#
s_threshold_moderate: float = 1.0#
s_threshold_good: float = 5.0#
hist_alpha: float = 0.7#
hist_edgecolor: str = 'white'#
hist_bins: int = 30#
kde_color: str = 'k'#
kde_lw: float = 1.8#
envelope_kwargs(color, **overrides)#

Keyword arguments for ax.fill_between (uncertainty band).

Parameters:
Return type:

dict[str, Any]

line_kwargs(color, **overrides)#

Keyword arguments for ax.plot (P50 central line).

Parameters:
Return type:

dict[str, Any]

scatter_kwargs(color, **overrides)#

Keyword arguments for ax.scatter.

Parameters:
Return type:

dict[str, Any]

ref_kwargs(**overrides)#

Keyword arguments for the reference-depth ax.axhline call.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

station_kwargs(**overrides)#

Keyword arguments for station-tick ax.axvline calls.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

grid_kwargs()#

Keyword arguments for ax.grid.

Return type:

dict[str, Any]

bar_kwargs(color, **overrides)#

Kwargs for Dar-Zarrouk bar charts.

Parameters:
Return type:

dict[str, Any]

hist_kwargs(color, **overrides)#

Kwargs for ax.hist in uncertainty histograms.

Parameters:
Return type:

dict[str, Any]

kde_kwargs(**overrides)#

Kwargs for the KDE curve ax.plot call.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

copy(**kw)#

Return a shallow copy with optional field overrides.

Parameters:

kw (Any)

Return type:

HydroProfileStyle

class pycsamt.api.InterpStyle(section=<factory>, profile=<factory>, figsize_section=(13.0, 5.0), figsize_profile=(13.0, 6.0), figsize_uncertainty=(13.0, 8.0), figsize_crossplot=(7.0, 5.5), figsize_depth_profile=(4.5, 9.0), figsize_aquifer_char=(13.0, 9.0), figsize_tl_panel=(3.5, 4.5))#

Bases: object

Complete visual bundle for one hydrogeophysical interpretation preset.

Parameters:
  • section (HydroSectionStyle) – Controls all 2-D colour-section plots.

  • profile (HydroProfileStyle) – Controls all 1-D profile plots.

  • figsize_section (tuple) – Default figure size (width, height) for single-panel 2-D sections.

  • figsize_profile (tuple) – Default figure size for 2-panel 1-D profile plots.

  • figsize_uncertainty (tuple) – Default figure size for 2-panel uncertainty sections.

  • figsize_crossplot (tuple[float, float])

  • figsize_depth_profile (tuple[float, float])

  • figsize_aquifer_char (tuple[float, float])

  • figsize_tl_panel (tuple[float, float])

section: HydroSectionStyle#
profile: HydroProfileStyle#
figsize_section: tuple[float, float] = (13.0, 5.0)#
figsize_profile: tuple[float, float] = (13.0, 6.0)#
figsize_uncertainty: tuple[float, float] = (13.0, 8.0)#
figsize_crossplot: tuple[float, float] = (7.0, 5.5)#
figsize_depth_profile: tuple[float, float] = (4.5, 9.0)#
figsize_aquifer_char: tuple[float, float] = (13.0, 9.0)#
figsize_tl_panel: tuple[float, float] = (3.5, 4.5)#
copy(**kw)#

Return a deep copy with optional top-level field overrides.

Parameters:

kw (Any)

Return type:

InterpStyle

pycsamt.api.configure_interp(**kw)#

Configure PYCSAMT_INTERP using dotted-path keys.

Equivalent to PYCSAMT_INTERP.configure(**kw).

Parameters:

kw (Any)

Return type:

None

pycsamt.api.reset_interp()#

Reset PYCSAMT_INTERP to package defaults.

Return type:

None

pycsamt.api.use_interp(preset)#

Activate a named preset in PYCSAMT_INTERP.

Parameters:

preset (str) – One of 'default', 'publication', 'dark', 'accessible'.

Return type:

None

class pycsamt.api.FrequencyAxisControl(view='log10_period')#

Bases: object

Control the 1-D frequency/period axis.

Parameters:

view (str)

view: str = 'log10_period'#
transform(freq)#

Return x-axis values from frequency in hertz.

Parameters:

freq (Any)

Return type:

ndarray

label()#

Return the x-axis label.

Return type:

str

use_log_scale()#

Return whether Matplotlib should use log scaling.

Return type:

bool

class pycsamt.api.PhaseViewControl(range=(-180.0, 180.0), unit='degree', wrap=True)#

Bases: object

Control how phase values are wrapped and displayed.

Parameters:
range: tuple[float, float] = (-180.0, 180.0)#
unit: str = 'degree'#
wrap: bool = True#
transform(phase)#

Return phase values in the configured display interval.

Parameters:

phase (Any)

Return type:

ndarray

label()#

Return the phase-axis label.

Return type:

str

class pycsamt.api.PyCSAMTControl#

Bases: object

Package-wide plotting-view control container.

configure(**kw)#

Configure controls using section__attribute paths.

Parameters:

kw (Any)

Return type:

None

context(**kw)#

Temporarily override controls, then restore them.

Parameters:

kw (Any)

Return type:

Generator[PyCSAMTControl, None, None]

reset()#

Reset controls to package defaults.

Return type:

None

summary()#

Return a human-readable summary.

Return type:

str

class pycsamt.api.RhoViewControl(view='log10')#

Bases: object

Control apparent-resistivity display scale.

Parameters:

view (str)

view: str = 'log10'#
transform(rho)#

Return apparent resistivity in the configured display scale.

Parameters:

rho (Any)

Return type:

ndarray

error(rho, rho_err)#

Return display-scale rho errors.

Parameters:
  • rho (Any)

  • rho_err (Any | None)

Return type:

ndarray | None

label()#

Return the apparent-resistivity axis label.

Return type:

str

pycsamt.api.configure_control(**kw)#

Configure PYCSAMT_CONTROL with dotted-path arguments.

Parameters:

kw (Any)

Return type:

None

pycsamt.api.reset_control()#

Reset PYCSAMT_CONTROL to package defaults.

Return type:

None

pycsamt.api.wrap_phase(phase, phase_range=(-180.0, 180.0))#

Wrap phase values into phase_range.

Parameters:
Return type:

ndarray

class pycsamt.api.PyCSAMTSection#

Bases: object

Package-wide section-view control container.

style_for(preset='pseudosection')#

Return the section style associated with preset.

Parameters:

preset (str)

Return type:

SectionStyle

configure(**kw)#

Configure section styles using section__attribute paths.

Parameters:

kw (Any)

Return type:

None

context(preset=None, **kw)#

Temporarily override section styles, then restore them.

Parameters:
  • preset (str | None)

  • kw (Any)

Return type:

Generator[PyCSAMTSection, None, None]

use_preset(preset)#

Copy one preset into the pseudosection slot.

Parameters:

preset (str)

Return type:

None

reset()#

Reset section controls to package defaults.

Return type:

None

summary()#

Return a human-readable summary.

Return type:

str

class pycsamt.api.SectionAxisStyle(xlabel='Station', ylabel=None, y_direction='down', aspect='auto', grid=False, station_side='top', title=True, xlabel_pad=None, ylabel_pad=None, y_type='depth')#

Bases: object

Axis behavior for section-like plots.

Parameters:
xlabel: str = 'Station'#
ylabel: str | None = None#
y_direction: str = 'down'#
aspect: str | float = 'auto'#
grid: bool = False#
station_side: str = 'top'#
title: bool = True#
xlabel_pad: float | None = None#
ylabel_pad: float | None = None#
y_type: str = 'depth'#
apply(ax, *, xlabel=None, ylabel=None, title=None)#

Apply axis labels, direction, aspect, and grid state.

Parameters:
  • ax (Any)

  • xlabel (str | None)

  • ylabel (str | None)

  • title (str | None)

Return type:

None

class pycsamt.api.SectionColorbarStyle(show=True, side='right', size='3.5%', pad=0.04, max_ticks=6, tick_format=None)#

Bases: object

Colorbar geometry and tick-density controls.

Parameters:
show: bool = True#
side: str = 'right'#
size: str = '3.5%'#
pad: float = 0.04#
max_ticks: int | None = 6#
tick_format: str | None = None#
add(mappable, ax, *, label=None, **kw)#

Attach a section colorbar to ax.

Parameters:
Return type:

Any | None

class pycsamt.api.SectionFigureStyle(figsize=(9.5, 4.4), tight=True, constrained=False, title=True, min_width=7.0, max_width=14.0, min_height=3.2, max_height=7.5, station_width=0.16, y_sample_height=0.03, label_width=0.055, colorbar_width=0.55)#

Bases: object

Figure geometry for section-like plots.

Parameters:
figsize: tuple[float, float] | str = (9.5, 4.4)#
tight: bool = True#
constrained: bool = False#
title: bool = True#
min_width: float = 7.0#
max_width: float = 14.0#
min_height: float = 3.2#
max_height: float = 7.5#
station_width: float = 0.16#
y_sample_height: float = 0.03#
label_width: float = 0.055#
colorbar_width: float = 0.55#
resolve(*, n_stations=None, n_y=None, max_label_len=None, colorbar=True)#

Return a concrete figure size in inches.

Parameters:
  • n_stations (int | None)

  • n_y (int | None)

  • max_label_len (int | None)

  • colorbar (bool)

Return type:

tuple[float, float]

class pycsamt.api.SectionStyle(figure=<factory>, axis=<factory>, colorbar=<factory>, station_preset='pseudosection')#

Bases: object

Complete visual-control bundle for one section preset.

Parameters:
figure: SectionFigureStyle#
axis: SectionAxisStyle#
colorbar: SectionColorbarStyle#
station_preset: str = 'pseudosection'#
topo_active()#

Return True when the global topo config applies to this section.

Checks PYCSAMT_TOPO against self.axis.y_type. Period / frequency sections return False even when topo is globally enabled, because they carry no real elevation information.

Return type:

bool

copy(**kw)#

Return a modified deep copy of this section style.

Parameters:

kw (Any)

Return type:

SectionStyle

figsize_for(*, n_stations=None, n_y=None, labels=None, colorbar=True)#

Return a concrete figure size for this section.

Parameters:
Return type:

tuple[float, float]

apply_axis(ax, **kw)#

Apply this style’s axis policy to ax.

Parameters:
Return type:

None

add_colorbar(mappable, ax, *, label=None, **kw)#

Attach a colorbar using this style’s colorbar policy.

Parameters:
Return type:

Any | None

apply_stations(ax, positions, labels=None, *, station_style=None, xlim=None)#

Apply station rendering for this section style.

Parameters:
Return type:

Any

pycsamt.api.configure_section(**kw)#

Configure PYCSAMT_SECTION.

Parameters:

kw (Any)

Return type:

None

pycsamt.api.reset_section()#

Reset PYCSAMT_SECTION to package defaults.

Return type:

None

class pycsamt.api.PyCSAMTStationRendering#

Bases: object

Package-wide station rendering control container.

style_for(preset='pseudosection')#

Return the station-axis style associated with preset.

Parameters:

preset (str)

Return type:

StationAxisStyle

apply(ax, positions, labels=None, *, preset='pseudosection', xlim=None)#

Apply one named station-rendering preset to ax.

Parameters:
Return type:

ndarray

configure(**kw)#

Configure station rendering using section__attribute paths.

Parameters:

kw (Any)

Return type:

None

context(preset=None, **kw)#

Temporarily override station rendering, then restore it.

Parameters:
  • preset (str | None)

  • kw (Any)

Return type:

Generator[PyCSAMTStationRendering, None, None]

use_preset(preset)#

Copy one preset into the pseudosection slot.

Parameters:

preset (str)

Return type:

None

reset()#

Reset station rendering to package defaults.

Return type:

None

summary()#

Return a human-readable summary.

Return type:

str

class pycsamt.api.StationAxisStyle(side='top', xlabel='Station', every='auto', max_labels=14, rotation=90.0, fontsize=7, tick_length=3.0, label_tick_length=5.0, label_pad=8.0, xlabel_pad=6.0, show_all_ticks=True, show_labels=True, show_markers=True, marker=<factory>)#

Bases: object

Station-axis tick, label, and marker configuration.

Parameters:
side: str = 'top'#
xlabel: str = 'Station'#
every: int | str = 'auto'#
max_labels: int = 14#
rotation: float = 90.0#
fontsize: int = 7#
tick_length: float = 3.0#
label_tick_length: float = 5.0#
label_pad: float = 8.0#
xlabel_pad: float = 6.0#
show_all_ticks: bool = True#
show_labels: bool = True#
show_markers: bool = True#
marker: StationMarkerStyle#
compute_every(n, figwidth_in=10.0, max_label_len=4)#

Return the interval between visible station labels.

Parameters:
Return type:

int

label_indices(labels, figwidth_in=10.0)#

Return indices whose station labels should be visible.

Parameters:
Return type:

ndarray

apply(ax, positions, labels=None, *, xlim=None, topo_elev=None)#

Apply station ticks, labels, and markers to ax.

Parameters:
  • ax (Axes)

  • positions ((n,) station x positions)

  • labels ((n,) station name strings, optional)

  • xlim ((xmin, xmax) x-axis limits, optional)

  • topo_elev ((n,) terrain elevation in data y-units, optional) – When provided the markers are placed at the terrain surface (+ a small pad toward the viewer) instead of at the flat axis edge. Labels are drawn inline above the markers; xticklabels at the axis edge are suppressed.

Returns:

Indices of stations whose labels are visible.

Return type:

numpy.ndarray

class pycsamt.api.StationMarkerStyle(marker='v', size=34.0, facecolor='white', edgecolor='black', linewidth=0.9, alpha=1.0, offset=1.025, zorder=5)#

Bases: object

Marker style used to draw stations along a profile axis.

Parameters:
marker: str = 'v'#
size: float = 34.0#
facecolor: str = 'white'#
edgecolor: str = 'black'#
linewidth: float = 0.9#
alpha: float = 1.0#
offset: float = 1.025#
zorder: int = 5#
kwargs(**overrides)#

Return Matplotlib scatter keyword arguments.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

pycsamt.api.configure_station_rendering(**kw)#

Configure PYCSAMT_STATION_RENDERING.

Parameters:

kw (Any)

Return type:

None

pycsamt.api.reset_station_rendering()#

Reset PYCSAMT_STATION_RENDERING to package defaults.

Return type:

None

class pycsamt.api.PyCSAMTStyle(preset=None)#

Bases: object

Global visual-style container for pyCSAMT.

Holds five style sub-objects:

The module-level singleton PYCSAMT_STYLE is the recommended entry point; import it and mutate it in your script or notebook before creating figures.

Parameters:

preset (str or None) – Named preset to initialise from. None"pycsamt".

Examples

Inspect the current style:

from pycsamt.api.style import PYCSAMT_STYLE
print(PYCSAMT_STYLE)

Apply a named preset:

PYCSAMT_STYLE.use("publication")

Configure individual attributes with dotted paths:

PYCSAMT_STYLE.configure(
    rose__compass_labels="degrees",
    multiline__base_color="red",
    mt__xy__color="#003f88",
)

Temporary style change (context manager):

with PYCSAMT_STYLE.context("dark"):
    fig = plot_phase_tensor_rose(sites)
use(preset)#

Apply a named full-package style preset.

Parameters:

preset (str) – "pycsamt" — default: gradient bars, NESW compass, blue/red MT, blue-dashed / red-solid correction pair. "publication" — grayscale, degree compass, open markers. "dark" — dark-background optimised colours.

Raises:

ValueError – If preset is not registered.

Return type:

None

configure(**kw)#

Configure style attributes using double-underscore dotted paths.

Parameters:

**kw (Any) – Each key uses __ as a section separator, e.g. rose__compass_labels="degrees", mt__xy__color="#003f88", multiline__base_color="red".

Return type:

None

Examples

>>> PYCSAMT_STYLE.configure(
...     rose__compass_labels="degrees",
...     rose__show_secondary=False,
...     multiline__mode="gradient",
...     multiline__base_color="red",
...     mt__xy__color="#003f88",
...     mt__yx__lw=2.0,
... )
context(preset=None, **kw)#

Temporarily apply a preset and/or overrides, then restore.

Parameters:
  • preset (str or None) – Named preset to activate inside the context.

  • **kw – Additional dotted-path overrides (same syntax as configure()).

Yields:

PyCSAMTStyle – The (temporarily modified) style object.

Return type:

Generator[PyCSAMTStyle, None, None]

Examples

>>> with PYCSAMT_STYLE.context("publication", mt__xy__lw=2.0):
...     fig = plot_phase_tensor_rose(sites)
reset()#

Reset all style sections to package defaults ("pycsamt" preset).

Return type:

None

summary()#

Return a human-readable summary of the current style.

Return type:

str

class pycsamt.api.MultilineStyle(mode='gradient', base_color='blue', cmap=None, dark=0.85, light=0.25, reverse=False, lw=1.5, alpha=0.85, cycle_palette=<factory>)#

Bases: object

Gradient-first coloring for multi-line (multi-station / multi-profile) plots.

When mode is "gradient", the n lines returned by colors() are shades of the same hue arranged from dark (line 0) to light (line n-1) — or reversed. This preserves visual coherence while still making individual lines distinguishable.

Parameters:
  • mode ({"gradient", "cycle", "matplotlib"}) – "gradient" — sequential shades from base_color / cmap. "cycle" — rotate through a fixed palette (default: tab10). "matplotlib" — fall back to matplotlib’s default "C0", "C1", … colour cycle.

  • base_color (str) – Base hue for mode="gradient". If cmap is None, a sequential colormap is auto-selected from this colour name (e.g. "blue""Blues_r"). Any matplotlib colour spec works; unrecognised names fall back to cmap if set, else "Blues_r".

  • cmap (str or None) – Explicit colormap override. Takes precedence over base_color for cmap selection.

  • dark (float) – Fraction (0–1) of the cmap for the darkest (first) line. Default 0.85 avoids pure black.

  • light (float) – Fraction for the lightest (last) line. Default 0.25 avoids near-white.

  • reverse (bool) – If True, light lines come first and dark lines last.

  • lw (float) – Default line width for multi-line plots.

  • alpha (float) – Default line alpha.

  • cycle_palette (list of str) – Colour list used when mode is "cycle".

mode: str = 'gradient'#
base_color: str = 'blue'#
cmap: str | None = None#
dark: float = 0.85#
light: float = 0.25#
reverse: bool = False#
lw: float = 1.5#
alpha: float = 0.85#
cycle_palette: list[str]#
colors(n)#

Return n colours for a multi-line plot.

Parameters:

n (int) – Number of lines / profiles.

Returns:

RGBA tuples (for "gradient") or colour strings (for "cycle" / "matplotlib").

Return type:

list

Examples

>>> ms = MultilineStyle(mode="gradient", base_color="red")
>>> colors = ms.colors(5)   # 5 shades of red, dark → light
line_kwargs(idx, n, **overrides)#

Return ax.plot keyword arguments for line idx of n.

Parameters:
  • idx (int) – Zero-based line index.

  • n (int) – Total number of lines.

  • **overrides – Keyword arguments that win over the style defaults.

Return type:

dict[str, Any]

Examples

>>> kw = ms.line_kwargs(0, 5)
>>> ax.plot(x, y, **kw)
copy(**kw)#

Return a modified copy.

Parameters:

kw (Any)

Return type:

MultilineStyle

class pycsamt.api.MTComponentStyle(xy=<factory>, yx=<factory>, xx=<factory>, yy=<factory>, te=<factory>, tm=<factory>, det=<factory>)#

Bases: object

Consistent colours and markers for MT impedance components and modes.

Variables:
  • xy (_MTComp) – Off-diagonal XY component (TE-like). Default: solid blue circles.

  • yx (_MTComp) – Off-diagonal YX component (TM-like). Default: solid red squares.

  • xx (_MTComp) – Diagonal XX component. Default: dashed green upward triangles.

  • yy (_MTComp) – Diagonal YY component. Default: dashed purple downward triangles.

  • te (_MTComp) – TE mode (when TE/TM decomposition is used). Default: blue circles.

  • tm (_MTComp) – TM mode. Default: red squares.

  • det (_MTComp) – Determinant / rotationally invariant quantity. Default: grey circles.

Parameters:
  • xy (_MTComp)

  • yx (_MTComp)

  • xx (_MTComp)

  • yy (_MTComp)

  • te (_MTComp)

  • tm (_MTComp)

  • det (_MTComp)

Examples

Spread kwargs into a matplotlib call:

ax.errorbar(per, rho, drho, **style.mt.xy.errorbar_kwargs())

Override for one call only:

kw = style.mt.yx.plot_kwargs(lw=2.5, alpha=1.0)

Change the XY colour package-wide:

PYCSAMT_STYLE.mt.xy.color = "#003f88"
xy: _MTComp#
yx: _MTComp#
xx: _MTComp#
yy: _MTComp#
te: _MTComp#
tm: _MTComp#
det: _MTComp#
component(key)#

Return the _MTComp for key (case-insensitive).

Parameters:

key (str) – One of "xy", "yx", "xx", "yy", "te", "tm", "det".

Raises:

KeyError – If key is not a recognised component name.

Return type:

_MTComp

copy()#

Return a deep copy.

Return type:

MTComponentStyle

class pycsamt.api.CorrectionStyle(before=<factory>, after=<factory>)#

Bases: object

Consistent before/after visual pair for any 1-D correction workflow.

Every correction plot in pyCSAMT (static-shift, near-field, noise removal, …) uses the same two-curve convention so that users can read results at a glance across all figures:

  • before — blue dashed line with hollow markers

  • after — red solid line with hollow markers

The two colours deliberately mirror MTComponentStyle.xy (blue) and MTComponentStyle.yx (red) so the whole package stays visually coherent.

Variables:
  • before (_MTComp) – Style for the uncorrected / original curve.

  • after (_MTComp) – Style for the corrected curve.

Parameters:
  • before (_MTComp)

  • after (_MTComp)

Examples

Use directly in a plot function:

cs = PYCSAMT_STYLE.correction
ax.plot(period, rho_before, **cs.before.plot_kwargs())
ax.plot(period, rho_after,  **cs.after.plot_kwargs())

Override just the line-width for one call:

kw_before = cs.before.plot_kwargs(lw=2.0)

Change the before colour package-wide:

PYCSAMT_STYLE.correction.before.color = "#005a9e"

Use dotted-path configure:

configure_style(
    correction__before__color = "#005a9e",
    correction__after__color  = "#9b0000",
)
before: _MTComp#
after: _MTComp#
copy()#

Return a deep copy.

Return type:

CorrectionStyle

class pycsamt.api.PhaseTensorEllipseStyle(normalise_by='cell', scale=0.85, s1_ref=None, min_aspect=0.18, c_by='skew', cmap='RdBu_r', clim=None, clim_pct=(5.0, 95.0), symmetric_clim=True, alpha=0.92, edgecolor='k', linewidth=0.2, skew_threshold=3.0, mark_3d=True, lw_3d_factor=3.0, show_ref=True, ref_edgecolor='k', ref_lw=0.8, ref_fontsize=6.5)#

Bases: object

Visual style for phase-tensor ellipse plots (psection, map, summary).

Each plotted ellipse simultaneously encodes five physical quantities:

  1. Width ∝ φ_max (s1 eigenvalue — mean phase level)

  2. Height ∝ φ_min (s2 eigenvalue — minimum phase, ≤ φ_max)

  3. Aspect ratio = φ_min/φ_max — ellipticity (1 = isotropic / 1-D)

  4. Rotation angle = θ (CCW from E) — geoelectric-strike indicator

  5. Fill colour — any scalar mapped through cmap (default: skewness β)

The style groups these into five sections:

  • Sizing (scale, normalise_by, s1_ref) — how big each ellipse is

  • Colour/fill (c_by, cmap, clim, …) — what drives the fill

  • Edge/border (edgecolor, linewidth, alpha) — ellipse outline

  • 3-D cell marker (skew_threshold, mark_3d, lw_3d_factor) — highlight 3-D cells

  • Reference circle (show_ref, ref_edgecolor, ref_lw, ref_fontsize)

Parameters:
  • normalise_by ("cell" | "unity" | "abs") –

    Size normalisation strategy:

    "cell"

    The 90th-percentile s1 fills scale of its grid cell. Relative sizes are preserved across stations/periods.

    "unity"

    s1_ref = tan 45° = 1.0 (1-D half-space reference). A perfectly 1-D tensor plots as a circle of radius scale.

    "abs"

    Raw data units: width = scale × s1 (legacy behaviour).

  • scale (float, default 0.85) – Fraction of each grid cell occupied by the normalised ellipse. Values above 1 produce overlap between adjacent cells.

  • s1_ref (float or None) – Manual reference s1. Overrides the automatic reference computed from the data under "cell" and "unity" modes.

  • min_aspect (float, default 0.18) – Minimum height/width ratio enforced on every drawn ellipse. Real (noisy) EDI data frequently has φ_min ≈ 0 at some stations/periods, which collapses the ellipse to a near-invisible sliver. Flooring the height at min_aspect × width keeps every cell visible as a proper oval while leaving φ_max, θ and fill colour untouched. Set to 0 to recover the raw (possibly degenerate) ellipticity.

  • c_by (str, default "skew") – Quantity mapped to fill colour. Supported values: "skew", "beta", "|skew|", "|beta|", "theta", "|theta|", "ellipt", "phi_mean", "phi_max", "phi_min", "s1", "s2", "alpha".

  • cmap (str, default "RdBu_r") – Matplotlib colormap. When None, a sensible default is chosen automatically from c_by (e.g. "RdBu_r" for skewness, "viridis" for ellipticity, "hsv" for strike angle).

  • clim ((vmin, vmax) or None) – Explicit colour axis limits. None derives limits from clim_pct / skew_threshold.

  • clim_pct ((lo, hi), default (5.0, 95.0)) – Percentile limits used for automatic colour scaling.

  • symmetric_clim (bool, default True) – Force vmin = −vmax for diverging quantities (skewness, etc.). Automatically disabled when None is the appropriate default.

  • alpha (float, default 0.92) – Ellipse fill opacity.

  • edgecolor (str, default "k") – Ellipse border colour. Set to "none" to suppress borders.

  • linewidth (float, default 0.2) – Normal (non-3-D) ellipse border width in points.

  • skew_threshold (float, default 3.0) – |β| threshold (degrees) above which a cell is flagged as 3-D. 3-D cells receive a thicker border when mark_3d is True. Set to None to disable 3-D flagging.

  • mark_3d (bool, default True) – Draw a thicker border on ellipses where |β| > skew_threshold.

  • lw_3d_factor (float, default 3.0) – Multiplier applied to linewidth for 3-D flagged cells.

  • show_ref (bool, default True) – Draw a reference circle (s1 = s1_ref) in the corner of the pseudo-section as a scale indicator.

  • ref_edgecolor (str, default "k") – Border colour of the reference circle.

  • ref_lw (float, default 0.8) – Border line width of the reference circle.

  • ref_fontsize (float, default 6.5) – Font size of the reference-circle label.

Examples

Use the style in a plot call:

from pycsamt.api.style import PYCSAMT_STYLE
es = PYCSAMT_STYLE.pt_ellipse
plot_phase_tensor_psection(sites, **es.to_kwargs())

Switch colour quantity and cmap in one call:

plot_phase_tensor_psection(
    sites,
    **es.copy(c_by="theta", cmap=None).to_kwargs(),
)

Configure package-wide:

configure_style(
    pt_ellipse__c_by       = "ellipt",
    pt_ellipse__cmap       = "viridis",
    pt_ellipse__edgecolor  = "none",
    pt_ellipse__scale      = 0.80,
)
normalise_by: str = 'cell'#
scale: float = 0.85#
s1_ref: float | None = None#
min_aspect: float = 0.18#
c_by: str = 'skew'#
cmap: str | None = 'RdBu_r'#
clim: tuple[float, float] | None = None#
clim_pct: tuple[float, float] = (5.0, 95.0)#
symmetric_clim: bool = True#
alpha: float = 0.92#
edgecolor: str = 'k'#
linewidth: float = 0.2#
skew_threshold: float | None = 3.0#
mark_3d: bool = True#
lw_3d_factor: float = 3.0#
show_ref: bool = True#
ref_edgecolor: str = 'k'#
ref_lw: float = 0.8#
ref_fontsize: float = 6.5#
resolve_cmap()#

Return the effective colormap name, auto-selecting from c_by when cmap is None.

Examples

>>> es = PhaseTensorEllipseStyle(c_by="theta", cmap=None)
>>> es.resolve_cmap()
'hsv'
Return type:

str

resolve_symmetric_clim()#

Return effective symmetric_clim flag, honouring c_by natural symmetry.

Return type:

bool

to_kwargs()#

Return a dict of kwargs ready to spread into any phase-tensor plot function.

The dict covers every parameter currently accepted by plot_phase_tensor_psection() and plot_phase_tensor_summary().

Parameters that are style-only (e.g. lw_3d_factor, ref_edgecolor, ref_lw, ref_fontsize) are not included here because the plot functions do not yet accept them; they are preserved in the style for forward compatibility and will be added to the returned dict once the plot functions are updated.

Examples

>>> ax = plot_phase_tensor_psection(sites, **PYCSAMT_STYLE.pt_ellipse.to_kwargs())
Return type:

dict[str, Any]

copy(**kw)#

Return a modified shallow copy.

Examples

>>> strike_style = PYCSAMT_STYLE.pt_ellipse.copy(c_by="theta", cmap=None)
Parameters:

kw (Any)

Return type:

PhaseTensorEllipseStyle

class pycsamt.api.RawDataStyle(color='black', ls=':', lw=0.8, marker='.', ms=3.0, mfc='black', mew=0.5, alpha=0.85, capsize=1.5, elinewidth=0.6, label='raw')#

Bases: object

Visual style for raw, unprocessed EM observations.

Raw data should be visually distinct from processed or modelled data. The package convention is therefore a restrained black trace with small markers and thin connecting lines. Plot functions may use this style automatically when called with raw=True unless users explicitly pass colors or force a processed-data style.

Parameters:
color: str = 'black'#
ls: str = ':'#
lw: float = 0.8#
marker: str = '.'#
ms: float = 3.0#
mfc: str = 'black'#
mew: float = 0.5#
alpha: float = 0.85#
capsize: float = 1.5#
elinewidth: float = 0.6#
label: str = 'raw'#
plot_kwargs(**overrides)#

Return keyword arguments for raw-data line plots.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

errorbar_kwargs(**overrides)#

Return keyword arguments for raw-data error bars.

Parameters:

overrides (Any)

Return type:

dict[str, Any]

copy(**kw)#

Return a modified copy.

Parameters:

kw (Any)

Return type:

RawDataStyle

class pycsamt.api.RoseStyle(bar_style='gradient', bar_color='#e53935', bar_alpha=0.88, bar_edgecolor='none', bar_edgelw=0.4, cmap='YlOrRd', outer_ring_lw=2.5, outer_ring_color='0.12', n_rings=3, ring_color='0.75', ring_ls=':', ring_lw=0.7, ring_labels=None, ring_label_angle=22.5, ring_label_fontsize=7.0, ring_label_color='0.30', ring_label_fmt='{:.0f}', spoke_every=45.0, spoke_color='0.72', spoke_ls=':', spoke_lw=0.7, compass_labels='NESW', compass_fontsize=8.5, compass_color='0.15', compass_fontweight='bold', show_mean=True, mean_color='crimson', mean_lw=2.2, mean_ls='-', show_secondary=True, secondary_color=None, secondary_ls='--', secondary_lw=None, show_annotation=True, annotation_pos=(0.05, 0.93), annotation_fontsize=8.0, annotation_bg='white', annotation_ec='0.25', show_n=True)#

Bases: object

Visual style bundle shared by all pycsamt rose diagram functions.

Every attribute maps 1-to-1 to a keyword argument accepted by plot_strike_rose() and plot_phase_tensor_rose(). Pass an instance via the style= parameter of either function; individual kwargs still override the style.

Variables:
  • bar_style ({"gradient", "solid", "bands"}) – "gradient" — bar height mapped to cmap; "solid" — uniform bar_color; "bands" — one colour per period sub-band (stacked).

  • bar_color (str) – Bar fill colour for bar_style="solid".

  • bar_alpha (float) – Bar opacity (0–1).

  • bar_edgecolor (str) – Bar edge colour. "none" disables edges.

  • bar_edgelw (float) – Bar edge line-width.

  • cmap (str) – Matplotlib colormap name for bar_style="gradient".

  • outer_ring_lw (float) – Line-width of the bold outer bounding circle.

  • outer_ring_color (str) – Colour of the outer bounding circle.

  • n_rings (int) – Number of concentric reference rings inside the plot.

  • ring_color (str) – Colour of concentric rings.

  • ring_ls (str) – Line-style of concentric rings (":" dotted, "--" dashed, …).

  • ring_lw (float) – Line-width of concentric rings.

  • ring_labels (list[float] or None) – Explicit count values to annotate on the rings (e.g. [25, 50, 75, 100]). None → evenly auto-spaced.

  • ring_label_angle (float) – Clockwise degrees from North where count labels appear.

  • ring_label_fontsize (float) – Font size for ring count annotations.

  • ring_label_color (str) – Colour for ring count annotations.

  • ring_label_fmt (str) – Python format string for ring labels (e.g. "{:.0f}").

  • spoke_every (float) – Angular spacing (degrees) between radial spokes / tick marks.

  • spoke_color (str) – Colour of radial spokes.

  • spoke_ls (str) – Line-style of radial spokes.

  • spoke_lw (float) – Line-width of radial spokes.

  • compass_labels ({"NESW", "degrees", "none"}) – Perimeter labels. "NESW" → N/E/S/W; "degrees" → 0°/45°/…; "none" → hidden.

  • compass_fontsize (float) – Font size for compass / degree perimeter labels.

  • compass_color (str) – Colour for perimeter labels.

  • compass_fontweight (str) – Font weight for perimeter labels ("bold", "normal", …).

  • show_mean (bool) – Draw the mean direction as a diameter line through the centre.

  • mean_color (str) – Colour of the mean direction line.

  • mean_lw (float) – Line-width of the mean direction line.

  • mean_ls (str) – Line-style of the mean direction line.

  • show_secondary (bool) – Draw the 180°-conjugate (axial-symmetry) mean line.

  • secondary_color (str or None) – Colour of the conjugate line. None → same as mean_color.

  • secondary_ls (str) – Line-style of the conjugate line.

  • secondary_lw (float or None) – Line-width of the conjugate line. None → same as mean_lw.

  • show_annotation (bool) – Show the text box with mean angle and count.

  • annotation_pos ((float, float)) – Axes-fraction (x, y) position of the annotation box.

  • annotation_fontsize (float) – Font size of the annotation text.

  • annotation_bg (str) – Background colour of the annotation box.

  • annotation_ec (str) – Edge colour of the annotation box.

  • show_n (bool) – Append n = N (data-point count) to the annotation text.

Parameters:
  • bar_style (str)

  • bar_color (str)

  • bar_alpha (float)

  • bar_edgecolor (str)

  • bar_edgelw (float)

  • cmap (str)

  • outer_ring_lw (float)

  • outer_ring_color (str)

  • n_rings (int)

  • ring_color (str)

  • ring_ls (str)

  • ring_lw (float)

  • ring_labels (list[float] | None)

  • ring_label_angle (float)

  • ring_label_fontsize (float)

  • ring_label_color (str)

  • ring_label_fmt (str)

  • spoke_every (float)

  • spoke_color (str)

  • spoke_ls (str)

  • spoke_lw (float)

  • compass_labels (str)

  • compass_fontsize (float)

  • compass_color (str)

  • compass_fontweight (str)

  • show_mean (bool)

  • mean_color (str)

  • mean_lw (float)

  • mean_ls (str)

  • show_secondary (bool)

  • secondary_color (str | None)

  • secondary_ls (str)

  • secondary_lw (float | None)

  • show_annotation (bool)

  • annotation_pos (tuple)

  • annotation_fontsize (float)

  • annotation_bg (str)

  • annotation_ec (str)

  • show_n (bool)

bar_style: str = 'gradient'#
bar_color: str = '#e53935'#
bar_alpha: float = 0.88#
bar_edgecolor: str = 'none'#
bar_edgelw: float = 0.4#
cmap: str = 'YlOrRd'#
outer_ring_lw: float = 2.5#
outer_ring_color: str = '0.12'#
n_rings: int = 3#
ring_color: str = '0.75'#
ring_ls: str = ':'#
ring_lw: float = 0.7#
ring_labels: list[float] | None = None#
ring_label_angle: float = 22.5#
ring_label_fontsize: float = 7.0#
ring_label_color: str = '0.30'#
ring_label_fmt: str = '{:.0f}'#
spoke_every: float = 45.0#
spoke_color: str = '0.72'#
spoke_ls: str = ':'#
spoke_lw: float = 0.7#
compass_labels: str = 'NESW'#
compass_fontsize: float = 8.5#
compass_color: str = '0.15'#
compass_fontweight: str = 'bold'#
show_mean: bool = True#
mean_color: str = 'crimson'#
mean_lw: float = 2.2#
mean_ls: str = '-'#
show_secondary: bool = True#
secondary_color: str | None = None#
secondary_ls: str = '--'#
secondary_lw: float | None = None#
show_annotation: bool = True#
annotation_pos: tuple = (0.05, 0.93)#
annotation_fontsize: float = 8.0#
annotation_bg: str = 'white'#
annotation_ec: str = '0.25'#
show_n: bool = True#
copy(**overrides)#

Return a shallow copy with overrides applied.

Parameters:

**overrides (Any) – Any RoseStyle attribute name and its new value.

Returns:

A new RoseStyle instance.

Return type:

RoseStyle

Raises:

ValueError – If an unknown attribute name is passed.

Examples

>>> rs = RoseStyle()
>>> rs2 = rs.copy(compass_labels="degrees", show_secondary=False)
pycsamt.api.use_style(preset)#

Apply a named full-package style preset to PYCSAMT_STYLE.

Parameters:

preset (str) – One of "pycsamt", "publication", "dark".

Return type:

None

Examples

>>> from pycsamt.api.style import use_style
>>> use_style("publication")
pycsamt.api.reset_style()#

Reset PYCSAMT_STYLE to package defaults.

Examples

>>> from pycsamt.api.style import reset_style
>>> reset_style()
Return type:

None

pycsamt.api.configure_style(**kw)#

Configure PYCSAMT_STYLE with dotted-path keyword arguments.

Parameters:

**kw (Any) – Dotted-path attributes using __ as separator, e.g. rose__compass_labels="degrees", multiline__base_color="red", mt__xy__color="#003f88".

Return type:

None

Examples

>>> from pycsamt.api.style import configure_style
>>> configure_style(
...     rose__compass_labels="degrees",
...     multiline__mode="gradient",
...     multiline__base_color="teal",
...     mt__xy__color="#003f88",
...     mt__yx__color="#9b0000",
... )
class pycsamt.api.PlotConfig(*, fmt='png', base_fmt='png', dpi=150, bbox_inches='tight', transparent=False, facecolor='white', savedir=None, close_after_save=False, verbose=True)#

Bases: object

Global plot-export configuration singleton for pyCSAMT.

The module-level PLOT_CONFIG instance is the recommended entry point. Mutate it once (at the top of your script or notebook) and every subsequent save_fig() call inherits those settings.

Parameters:
  • fmt (str or list[str], default "png") – Export format token(s). See format-token-rules above.

  • base_fmt (str, default "png") – The reference format for additive + tokens.

  • dpi (int, default 150) – Raster resolution. Use 300600 for publication.

  • bbox_inches (str, default "tight") – Passed to savefig().

  • transparent (bool, default False) – Transparent background.

  • facecolor (str, default "white") – Figure background colour.

  • savedir (str or Path or None) – If set, relative path arguments passed to save_fig() are resolved under this directory.

  • close_after_save (bool, default False) – Call plt.close(fig) after saving.

  • verbose (bool, default True) – Print a line for each file written.

Examples

Configure once:

from pycsamt.api.plot import PLOT_CONFIG, save_fig
PLOT_CONFIG.fmt = ["+svg"]
PLOT_CONFIG.dpi = 300
PLOT_CONFIG.savedir = "~/paper/figures"

Use the configure() helper (dotted-style not needed — direct attribute access is cleaner for this class):

PLOT_CONFIG.configure(fmt="+svg", dpi=300)
resolve_formats(fmt=None)#

Return the resolved list of format strings for this call.

Parameters:

fmt (str, list[str], or None) – Per-call override. None → use fmt.

Returns:

Clean format strings (no +, no leading dot).

Return type:

list[str]

Examples

>>> cfg = PlotConfig(fmt="+svg")
>>> cfg.resolve_formats()
['png', 'svg']
>>> cfg.resolve_formats(fmt="pdf")
['pdf']
>>> cfg.resolve_formats(fmt=["+svg", "+pdf"])
['png', 'svg', 'pdf']
save(fig_or_ax, path, *, fmt=None, dpi=None, bbox_inches=None, transparent=None, facecolor=None, **savefig_kw)#

Save fig_or_ax to one or more format files.

Parameters:
  • fig_or_ax (Figure or Axes) – Accepts either object type — the parent figure is extracted automatically from an Axes.

  • path (str or Path) – Base output path. The file extension is replaced (or added) per format. If relative and savedir is set, the path is resolved under savedir.

  • fmt (str, list[str], or None) – Per-call format override. Nonefmt.

  • dpi (int or None) – Per-call DPI override. Nonedpi.

  • bbox_inches (str or None) – Per-call override.

  • transparent (bool or None) – Per-call override.

  • facecolor (str or None) – Per-call override.

  • **savefig_kw – Additional keyword arguments forwarded to savefig().

Returns:

Paths of every file written (one per resolved format).

Return type:

list[Path]

Examples

>>> paths = PLOT_CONFIG.save(ax, "fig_pt")
>>> paths = PLOT_CONFIG.save(fig, "fig_pt", fmt="+svg", dpi=300)
configure(**kw)#

Set multiple attributes at once.

Parameters:

**kw (Any) – Any writable PlotConfig attribute by name.

Return type:

None

Examples

>>> PLOT_CONFIG.configure(fmt="+svg", dpi=300, savedir="~/figures")
reset()#

Reset to package defaults (ignores config file and env vars).

Return type:

None

context(**kw)#

Temporarily override config attributes, then restore.

Parameters:

**kw (Any) – Any writable PlotConfig attribute by name.

Yields:

PlotConfig – The (temporarily modified) config object.

Return type:

Generator[PlotConfig, None, None]

Examples

>>> with PLOT_CONFIG.context(fmt="pdf", dpi=600):
...     save_fig(fig, "publication/fig")
>>> # config reverts here
to_dict()#

Return current config as a plain dict.

Return type:

dict

summary()#

Return a human-readable summary of the current config.

Return type:

str

pycsamt.api.save_fig(fig_or_ax, path, *, fmt=None, dpi=None, **kw)#

Save a pyCSAMT figure using the global PLOT_CONFIG settings.

Parameters:
  • fig_or_ax (Figure or Axes) – The object to save.

  • path (str or Path) – Base output path (extension auto-managed per format).

  • fmt (str, list[str], or None) – Per-call format override. NonePLOT_CONFIG.fmt.

  • dpi (int or None) – Per-call DPI override. NonePLOT_CONFIG.dpi.

  • **kw – Forwarded to PlotConfig.save().

Returns:

File paths written.

Return type:

list[Path]

Examples

Default (PNG):

save_fig(ax, "output/fig_pt")

Override format for this call:

save_fig(ax, "output/fig_pt", fmt="svg")

Two formats for this call:

save_fig(ax, "output/fig_pt", fmt=["+svg"])
pycsamt.api.set_fmt(*formats)#

Set the global export format(s) on PLOT_CONFIG.

Parameters:

*formats (str) – One or more format tokens. A single "png" or "svg" sets that format exclusively. A "+svg" token adds SVG to the base format.

Return type:

None

Examples

>>> set_fmt("svg")          # only SVG
>>> set_fmt("+svg")         # PNG + SVG
>>> set_fmt("+svg", "+pdf") # PNG + SVG + PDF
>>> set_fmt("svg", "pdf")   # SVG + PDF (no PNG)
pycsamt.api.set_dpi(dpi)#

Set the global raster DPI on PLOT_CONFIG.

Parameters:

dpi (int) – Dots per inch. Typical values: 150 (screen), 300 (print), 600 (high-res print).

Return type:

None

Examples

>>> set_dpi(300)
pycsamt.api.set_savedir(path)#

Set the global output directory on PLOT_CONFIG.

Parameters:

path (str or Path) – Directory where save_fig() writes files when a relative path is given. Tilde (~) is expanded.

Return type:

None

Examples

>>> set_savedir("~/paper/figures")
>>> save_fig(ax, "fig_pt")   # → ~/paper/figures/fig_pt.png
pycsamt.api.reset_plot_config()#

Reset PLOT_CONFIG to package defaults.

Does not re-read config files or environment variables.

Examples

>>> reset_plot_config()
Return type:

None

pycsamt.api.load_plot_config(path=None)#

(Re-)load a config file into PLOT_CONFIG.

Parameters:

path (str, Path, or None) – Path to an INI config file with a [plot] section. None searches the default locations (pycsamt_plot.cfg in CWD then ~/.pycsamt/plot.cfg).

Raises:

FileNotFoundError – If path is given explicitly and does not exist.

Return type:

None

Examples

Load a specific file:

load_plot_config("project/plot_settings.cfg")

Reload defaults:

load_plot_config()
pycsamt.api.write_default_config(path='pycsamt_plot.cfg')#

Write a template config file with the current PLOT_CONFIG values.

Useful for users who want to tweak settings without touching Python code.

Parameters:

path (str or Path) – Destination file path. Default "pycsamt_plot.cfg" writes to the current working directory.

Returns:

The file that was written.

Return type:

Path

Examples

>>> write_default_config()          # creates pycsamt_plot.cfg in CWD
>>> write_default_config("~/.pycsamt/plot.cfg")   # user-global config
class pycsamt.api.APIFrame(data=None, *, name=None, kind=None, source=None, units=None, meta=None, description=None, copy=False, **frame_kwargs)#

Bases: PyCSAMTObject

A pyCSAMT dataframe view that keeps pandas behavior intact.

APIFrame is a thin wrapper around pandas.DataFrame. The dataframe remains available as df; pyCSAMT adds compact display, metadata, units, statistics, and convenient conversion helpers.

Parameters:
classmethod from_records(records, *, columns=None, **kwargs)#

Build an APIFrame from record dictionaries.

Parameters:
Return type:

APIFrame

property df: DataFrame#

Return the underlying pandas dataframe.

property data: ndarray#

Return dataframe values as a NumPy array.

property shape: tuple[int, int]#

Return dataframe shape.

property columns: Index#

Return dataframe columns.

property stats: FrameProfile#

Return a compact dataframe profile.

property schema: dict[str, str]#

Return column dtype names keyed by column name.

summary(*, max_columns=8)#

Return a static display summary for printing.

Parameters:

max_columns (int)

Return type:

str

profile()#

Return the same object as stats.

Return type:

FrameProfile

missing()#

Return missing value counts by column.

Return type:

Series

numeric_stats(**kwargs)#

Return pandas describe for numeric columns.

Parameters:

kwargs (Any)

Return type:

DataFrame

to_pandas(*, copy=False)#

Return the underlying dataframe, optionally copied.

Parameters:

copy (bool)

Return type:

DataFrame

to_numpy(*args, **kwargs)#

Return dataframe values as a NumPy array.

Parameters:
Return type:

ndarray

to_dict(*args, **kwargs)#

Delegate to DataFrame.to_dict by default.

Parameters:
Return type:

dict

copy(*, deep=True)#

Return a copied view preserving metadata.

Parameters:

deep (bool)

Return type:

APIFrame

with_df(df, **overrides)#

Return a new APIFrame with another dataframe.

Parameters:
Return type:

APIFrame

update_meta(**kwargs)#

Update metadata in-place and return self.

Parameters:

kwargs (Any)

Return type:

APIFrame

set_units(**kwargs)#

Update column units in-place and return self.

Parameters:

kwargs (str)

Return type:

APIFrame

class pycsamt.api.APIResult(**items)#

Bases: PyCSAMTObject

Container for named result parts, including one or more tables.

Parameters:

items (Any)

property keys: tuple[str, ...]#

Return stored item names.

items()#

Return (name, value) pairs.

tables()#

Return only table-like result parts.

Return type:

dict[str, APIFrame]

update_meta(**kwargs)#

Update metadata in-place and return self.

Parameters:

kwargs (Any)

Return type:

APIResult

class pycsamt.api.APISurvey(collection=None, *, name=None, source=None, parser=None, meta=None)#

Bases: PyCSAMTObject

Friendly public facade over an EDICollection.

Parameters:
property n_sites: int#

Return number of loaded sites.

property stations: list[str]#

Return station names.

property paths: list[str]#

Return source paths for loaded stations.

property df: APIFrame#

Return the default summary table.

property data: Any#

Return the underlying EDI collection.

summary(*, fields=None)#

Return an editable APIFrame summary of loaded EDI files.

Parameters:

fields (Sequence[str] | None)

Return type:

APIFrame

errors()#

Return parser errors from the last read operation.

Return type:

list[tuple[Any, BaseException]]

get_site(site, default=None)#

Return one site by station, stem, filename, or path.

Parameters:
Return type:

Any

to_dataframe(*args, api=True, **kwargs)#

Return collection dataframe output, wrapped by default.

Parameters:
to_collection()#

Return the underlying collection.

Return type:

Any

update_meta(**kwargs)#

Update metadata in-place and return self.

Parameters:

kwargs (Any)

Return type:

APISurvey

summary_text()#

Return a compact survey display.

Return type:

str

class pycsamt.api.APIViewConfig#

Bases: object

Package-wide policy for dataframe-like public API views.

The backend controls what pycsamt.api.view.wrap_frame() returns:

  • "pycsamt" / True: return the built-in APIFrame.

  • "pandas" / False: return the original dataframe-like object.

  • callable: call wrapper(data, **metadata) and return its result.

configure(**kw)#

Configure the view policy.

Parameters:

kw (Any)

Return type:

None

context(**kw)#

Temporarily override API view settings.

Parameters:

kw (Any)

Return type:

Generator[APIViewConfig, None, None]

reset()#

Reset to defaults.

Return type:

None

wrap_frame(data, **metadata)#

Apply the configured dataframe wrapper.

Parameters:
Return type:

Any

enabled()#

Return whether API view wrapping is enabled.

Return type:

bool

summary()#

Return a compact configuration summary.

Return type:

str

class pycsamt.api.FrameProfile(rows, columns, column_names, numeric_columns, missing_cells, missing_fraction, memory_bytes)#

Bases: object

Small immutable profile describing a dataframe.

Parameters:
rows: int#
columns: int#
column_names: tuple[str, ...]#
numeric_columns: tuple[str, ...]#
missing_cells: int#
missing_fraction: float#
memory_bytes: int#
classmethod from_frame(df)#
Parameters:

df (DataFrame)

Return type:

FrameProfile

property shape: tuple[int, int]#

Return (rows, columns).

to_dict()#

Return a JSON-friendly profile dictionary.

Return type:

dict[str, Any]

class pycsamt.api.ProgressConfig(enabled='auto', desc=None, leave=False, unit='it', total=None)#

Bases: object

Configuration for terminal progress display.

Parameters:
enabled: bool | str = 'auto'#
desc: str | None = None#
leave: bool = False#
unit: str = 'it'#
total: int | None = None#
pycsamt.api.api_frame(_func=None, *, name=None, kind=None, source=None, units=None, meta=None, description=None, copy=False)#

Decorate a function so dataframe-like returns become APIFrame.

Parameters:
Return type:

Callable[[…], Any]

pycsamt.api.configure_api_view(**kw)#

Configure the global API view backend.

Parameters:

kw (Any)

Return type:

None

pycsamt.api.iter_progress(iterable, *, enabled='auto', desc=None, leave=False, unit='it', total=None)#

Yield items, optionally wrapped by tqdm.

Parameters:
Return type:

Iterator[T]

pycsamt.api.maybe_wrap_frame(data, *, api=None, name=None, kind=None, source=None, units=None, meta=None, description=None, copy=False, **frame_kwargs)#

Conditionally wrap data as an APIFrame.

When api is None (the default), the global PYCSAMT_API_VIEW configuration decides. Pass api=True to force wrapping, or api=False to always return the raw dataframe regardless of the global setting.

Parameters:
Return type:

Any

pycsamt.api.progress_enabled(value='auto')#

Return whether progress should be displayed.

Parameters:

value (bool | str)

Return type:

bool

pycsamt.api.read_edi(path, *, verbose=0, **kwargs)#

Read one EDI file and return an EDIFile.

Parameters:
Return type:

Any

pycsamt.api.read_edis(sources, *, recursive=True, strict=False, on_dup='replace', progress='auto', leave=False, verbose=0)#

Read many EDI files and return a public survey view.

Parameters:
Return type:

APISurvey

pycsamt.api.read_sites(sources, **kwargs)#

Alias for read_edis().

Parameters:
Return type:

APISurvey

pycsamt.api.reset_api_view()#

Reset the global API view backend.

Return type:

None

pycsamt.api.wrap_frame(data, *, name=None, kind=None, source=None, units=None, meta=None, description=None, copy=False, **frame_kwargs)#

Wrap dataframe-like data using the configured API view backend.

Parameters:
Return type:

Any

pycsamt.api.wrap_result(result, *, name='result', kind=None, meta=None, wrap_tables=True)#

Wrap a mapping of result parts as an APIResult.

Parameters:
Return type:

APIResult

pycsamt.api.geology_dataframe(catalog=None, *, name='geology_catalog')#

Return a public APIFrame for a geology catalog.

Parameters:
  • catalog (object, optional) – Object exposing to_dataframe(). If omitted, the package-level built-in geology catalog is used.

  • name (str, default "geology_catalog") – Display name attached to the returned APIFrame.

Return type:

Any

pycsamt.api.geology_table(catalog=None)#

Alias for geology_dataframe().

Parameters:

catalog (Any)

Return type:

Any

pycsamt.api.quality_dataframe(sites)#

Return a public APIFrame wrapper around metadata quality rows.

Parameters:

sites (Any)

Return type:

Any

pycsamt.api.quality_table(sites)#

Alias for quality_dataframe().

Parameters:

sites (Any)

Return type:

Any

pycsamt.api.sites_summary(sites, *, fields=('station', 'n_freq', 'has_tipper', 'period_min', 'period_max', 'lat', 'lon'), recursive=True, on_dup='replace', strict=False, verbose=0)#

Return a public APIFrame wrapper around emtools site summary.

Parameters:
Return type:

Any

class pycsamt.api.BuildConfig(n_jobs=1, cache=True, cache_dir=None)#

Bases: object

Build / processing execution settings.

Parameters:
n_jobs: int = 1#
cache: bool = True#
cache_dir: Path | None = None#
class pycsamt.api.LogConfig(level=0, color=True, file=None)#

Bases: object

Logging / verbosity settings.

Parameters:
level: int = 0#
color: bool = True#
file: Path | None = None#
class pycsamt.api.OutputConfig(format='text', dir=<factory>, overwrite=False)#

Bases: object

Output format and destination settings.

Parameters:
format: str = 'text'#
dir: Path#
overwrite: bool = False#
class pycsamt.api.PyCSAMTCLI#

Bases: object

Package-wide CLI configuration container.

Access the singleton via PYCSAMT_CLI. Do not instantiate directly unless you need an independent copy.

configure(**kw)#

Set attributes using section__attribute dotted paths.

Examples

>>> PYCSAMT_CLI.configure(log__level=1, output__format="json")
>>> PYCSAMT_CLI.configure(build__n_jobs=4)
Parameters:

kw (Any)

Return type:

None

context(**kw)#

Temporarily override settings, then restore on exit.

Examples

>>> with PYCSAMT_CLI.context(log__level=2):
...     run_command()
Parameters:

kw (Any)

Return type:

Generator[PyCSAMTCLI, None, None]

reset()#

Reset all settings to package defaults.

Return type:

None

load_env()#

Override settings from environment variables.

Recognised variables#

PYCSAMT_VERBOSE integer 0-2 PYCSAMT_NO_COLOR any non-empty value disables colour PYCSAMT_OUTPUT text | json | csv PYCSAMT_OUTPUT_DIR path PYCSAMT_JOBS integer >= 1

Return type:

None

summary()#

Return a human-readable summary of current settings.

Return type:

str

pycsamt.api.configure_cli(**kw)#

Configure PYCSAMT_CLI with dotted-path arguments.

Examples

>>> from pycsamt.api.cli import configure_cli
>>> configure_cli(log__level=1, output__format="json")
Parameters:

kw (Any)

Return type:

None

pycsamt.api.reset_cli()#

Reset PYCSAMT_CLI to package defaults.

Return type:

None

pycsamt.api.common_options(f)#

Attach verbose, no-color, format, and output-dir to a command.

pycsamt.api.format_option(f)#

Add the text, JSON, or CSV output-format option to a Click command.

Parameters:

f (FC)

Return type:

FC

pycsamt.api.n_jobs_option(f)#

Add the positive --jobs parallel-worker option to a Click command.

Parameters:

f (FC)

Return type:

FC

pycsamt.api.no_cache_option(f)#

Add the --no-cache processing option to a Click command.

Parameters:

f (FC)

Return type:

FC

pycsamt.api.no_color_option(f)#

Add the --no-color terminal-output option to a Click command.

Parameters:

f (FC)

Return type:

FC

pycsamt.api.output_dir_option(f)#

Add the writable --output-dir path option to a Click command.

Parameters:

f (FC)

Return type:

FC

pycsamt.api.overwrite_option(f)#

Add the --overwrite confirmation-bypass option to a Click command.

Parameters:

f (FC)

Return type:

FC

pycsamt.api.verbose_option(f)#

Add the repeatable --verbose logging option to a Click command.

Parameters:

f (FC)

Return type:

FC

class pycsamt.api.EDIDir#

Bases: Path

A Click Path type for a directory that contains EDI files.

name: str = 'EDI_DIR'#

the descriptive name of this type

convert(value, param, ctx)#

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (Any) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

Path

class pycsamt.api.EDIPath#

Bases: Path

A Click Path type that additionally requires a .edi extension.

name: str = 'EDI_FILE'#

the descriptive name of this type

convert(value, param, ctx)#

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (Any) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

Path

class pycsamt.api.FreqRange#

Bases: ParamType

Parse a fmin:fmax frequency-range string into (float, float).

Examples

--freq 0.1:1000(0.1, 1000.0)

name: str = 'FREQ_RANGE'#

the descriptive name of this type

convert(value, param, ctx)#

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (Any) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

tuple[float, float]

class pycsamt.api.StationList#

Bases: ParamType

Parse a comma-separated list of station identifiers.

Examples

--stations S01,S02,S03['S01', 'S02', 'S03']

name: str = 'STATION_LIST'#

the descriptive name of this type

convert(value, param, ctx)#

Convert the value to the correct type. This is not called if the value is None (the missing value).

This must accept string values from the command line, as well as values that are already the correct type. It may also convert other compatible types.

The param and ctx arguments may be None in certain situations, such as when converting prompt input.

If the value cannot be converted, call fail() with a descriptive message.

Parameters:
  • value (Any) – The value to convert.

  • param (Parameter | None) – The parameter that is using this type to convert its value. May be None.

  • ctx (Context | None) – The current context that arrived at this value. May be None.

Return type:

list[str]

Topography Configuration#

pycsamt.topo.config.configure_topo(**kw)[source]#

Configure the global PYCSAMT_TOPO singleton.

Parameters:

**kw (Any) – Keyword arguments forwarded to TopoConfig.configure().

Return type:

None

Examples

>>> from pycsamt.topo import configure_topo
>>> configure_topo(enabled=True, exaggeration=2.0)
pycsamt.topo.config.reset_topo()[source]#

Reset PYCSAMT_TOPO to package defaults.

Return type:

None

API Modules#

pycsamt.api.agents

pycsamt.api.agents

pycsamt.api.bunch

The structure module includes data structures such as Bunch and FlexDict that provide flexible and efficient ways to organize, store, and manipulate structured data.

pycsamt.api.cli

CLI configuration API for pyCSAMT.

pycsamt.api.cli.config

pycsamt.api.cli.config

pycsamt.api.cli.options

pycsamt.api.cli.options

pycsamt.api.cli.params

pycsamt.api.cli.params

pycsamt.api.control

Global plotting-view controls for pyCSAMT.

pycsamt.api.docs

Reusable docstring fragments for PyCSAMT APIs.

pycsamt.api.interp

Global visual controls for pycsamt.interp hydrogeophysical plots.

pycsamt.api.pipe

Pipeline API configuration for pyCSAMT.

pycsamt.api.pipe.config

Global pipeline configuration for pyCSAMT.

pycsamt.api.plot

pycsamt.api.plot

pycsamt.api.property

Common object and metadata helpers for pyCSAMT APIs.

pycsamt.api.section

Global section-view controls for pyCSAMT figures.

pycsamt.api.station

Global station-rendering controls for pyCSAMT figures.

pycsamt.api.style

pycsamt.api.style

pycsamt.api.typing

Shared typing helpers for PyCSAMT.

pycsamt.api.util

util module provides utility functions and classes to support various data manipulation and analysis tasks

pycsamt.api.view

User-facing result views for pyCSAMT public APIs.

pycsamt.api.view.config

Global configuration for pyCSAMT API view wrappers.

pycsamt.api.view.frame

Pandas-friendly dataframe result objects for public pyCSAMT APIs.

pycsamt.api.view.io

Public readers for EDI files and site collections.

pycsamt.api.view.progress

Progress helpers used by public pyCSAMT APIs.

pycsamt.api.view.result

General result container for public pyCSAMT APIs.

pycsamt.api.view.survey

Public survey view over EDI collections.

pycsamt.api.view.tables

Opt-in APIFrame table wrappers for common pyCSAMT summaries.