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:
objectPackage-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.elevfrom each Site’s EDI HEAD (default)."file"— load fromelev_file(CSV / parquet)."array"— use theelev_arrayndarray 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)
- configure(**kw)#
Set one or more configuration attributes by keyword.
- Parameters:
kw (Any)
- Return type:
- 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:
- 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.
- pycsamt.api.configure_topo(**kw)#
Configure the global
PYCSAMT_TOPOsingleton.- 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_TOPOto 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:
objectRuntime 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 (intoplots_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:
- 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:
- pycsamt.api.configure_pipe(**kw)#
Configure the global
PYCSAMT_PIPEsingleton.- Parameters:
kw (Any)
- Return type:
None
- pycsamt.api.reset_pipe()#
Reset
PYCSAMT_PIPEto package defaults.- Return type:
None
- class pycsamt.api.AgentConfig#
Bases:
objectGlobal LLM configuration singleton for all pycsamt agents.
BaseAgentcallsresolve()on every instantiation andget_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) –
Truewhen 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
Nonewhen 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:
- Returns:
self — allows chaining.
- Return type:
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:
- Returns:
self.
- Return type:
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()orset_key(), or be available as an environment variable.- Parameters:
- Returns:
self.
- Return type:
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. PassFalseto clear only the active provider / model while keeping stored keys available for futureswitch()calls.- Returns:
self.
- Return type:
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:
- Returns:
self.
- Return type:
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:
- 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_usdreaches usd, any subsequent LLM call will raiseBudgetExceededErrorbefore the API call is made.- Parameters:
usd (float) – Maximum spend in USD for this session.
- Returns:
self.
- Return type:
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
Truealso remove the budget cap (set_budgetmust be called again to re-enable it). DefaultFalse— zeroes the counter but keeps the existing cap.- Returns:
self.
- Return type:
Examples
AGENT_CONFIG.reset_budget() # zero counter, keep cap AGENT_CONFIG.reset_budget(cap=True) # zero counter and remove cap
- property api_key: str | None#
Resolved key for the active provider.
Resolution order: stored key → environment variable →
None.
- 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_keyis explicitly given: Use
provider,api_key, andmodel(or provider default) exactly as supplied. The global config is ignored.- If
api_keyisNone: If
providerequals 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.
- If
- 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:
- using(*, provider=None, api_key=None, model=None)#
Temporarily override the global config inside a
withblock.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:
- Yields:
AgentConfig – self 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 receiveapi_key=Noneeven whenANTHROPIC_API_KEY(or similar) is set in the OS environment. Usesthreading.localso 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:
RuntimeErrorRaised when an LLM call would be made after the session budget is used.
- pycsamt.api.configure_agents(*, provider, api_key, model=None)#
Configure
AGENT_CONFIGin one call and return it.Equivalent to
AGENT_CONFIG.configure(...).- Parameters:
- Return type:
Examples
from pycsamt.agents import configure_agents configure_agents(provider="claude", api_key="sk-ant-…")
- pycsamt.api.reset_agents(*, keys=True)#
Reset
AGENT_CONFIGto its unconfigured state.Equivalent to
AGENT_CONFIG.reset(...).- Parameters:
keys (bool) – When
True(default) also wipe stored per-provider keys.- Return type:
- class pycsamt.api.MetadataMixin#
Bases:
objectSmall mixin for attaching free-form object metadata.
The mixin is intentionally separate from
PyCSAMTObjectso the universal root class remains lightweight.- ensure_metadata()#
Return the metadata mapping, creating it when needed.
- class pycsamt.api.PyCSAMTObject#
Bases:
objectRoot object for lightweight pyCSAMT API behavior.
PyCSAMTObjectprovides 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__. IfNone, 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.
- to_dict(*, public_only=True, max_depth=1)#
Return a shallow dictionary representation.
- update(**kwargs)#
Set attributes from keyword arguments and validate.
- Parameters:
kwargs (Any)
- Return type:
- clone(**overrides)#
Return a shallow copy with optional attribute overrides.
- Parameters:
overrides (Any)
- Return type:
- validate()#
Validate object state.
Subclasses can override this hook. The base implementation intentionally accepts all states.
- Return type:
None
- class pycsamt.api.PyCSAMTInterp#
Bases:
objectPackage-wide visual control container for hydro-geophysical plots.
Holds one
InterpStyleper named preset. The default preset is what plot classes use when no explicitstyle=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
InterpStylefor preset.- Parameters:
preset (str) – One of
'default','publication','dark','accessible'.- Return type:
- use(preset)#
Copy a named preset into the default slot.
After this call, all plot classes that read from
PYCSAMT_INTERPwill 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__fielddotted 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()
- 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:
objectVisual parameters for 2-D hydrogeophysical colour sections.
Governs
PlotHydroSection,PlotTimeLapseSection, and both panels ofPlotUncertaintySection.- 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_for(quantity)#
Return the colourmap name for quantity.
- wt_kwargs(**overrides)#
Keyword arguments for the water-table
ax.plotcall.
- station_kwargs(**overrides)#
Keyword arguments for the station-tick
ax.axvlinecalls.
- cb_kwargs(**overrides)#
Keyword arguments forwarded to
fig.colorbar.
- crossplot_scatter_kwargs(**overrides)#
Kwargs for the
ax.scattercall in a petrophysical cross-plot.
- hs_fill_kwargs(**overrides)#
Kwargs for
ax.fill_betweenof Hashin-Shtrikman bounds.
- model_curve_kwargs(**overrides)#
Kwargs for the model-curve
ax.plotcall.
- rho_curve_kwargs(**overrides)#
Kwargs for the ρ(z) depth-profile curve.
- zone_boundary_kwargs(**overrides)#
Kwargs for geological zone boundary
ax.axhlinecalls.
- 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:
objectVisual parameters for 1-D hydrogeophysical profile plots.
Governs
PlotWaterTableProfileandPlotUncertaintyProfile.- 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)
- envelope_kwargs(color, **overrides)#
Keyword arguments for
ax.fill_between(uncertainty band).
- line_kwargs(color, **overrides)#
Keyword arguments for
ax.plot(P50 central line).
- scatter_kwargs(color, **overrides)#
Keyword arguments for
ax.scatter.
- ref_kwargs(**overrides)#
Keyword arguments for the reference-depth
ax.axhlinecall.
- station_kwargs(**overrides)#
Keyword arguments for station-tick
ax.axvlinecalls.
- bar_kwargs(color, **overrides)#
Kwargs for Dar-Zarrouk bar charts.
- hist_kwargs(color, **overrides)#
Kwargs for
ax.histin uncertainty histograms.
- kde_kwargs(**overrides)#
Kwargs for the KDE curve
ax.plotcall.
- 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:
objectComplete 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.
- section: HydroSectionStyle#
- profile: HydroProfileStyle#
- pycsamt.api.configure_interp(**kw)#
Configure
PYCSAMT_INTERPusing dotted-path keys.Equivalent to
PYCSAMT_INTERP.configure(**kw).- Parameters:
kw (Any)
- Return type:
None
- pycsamt.api.reset_interp()#
Reset
PYCSAMT_INTERPto 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:
objectControl the 1-D frequency/period axis.
- Parameters:
view (str)
- transform(freq)#
Return x-axis values from frequency in hertz.
- class pycsamt.api.PhaseViewControl(range=(-180.0, 180.0), unit='degree', wrap=True)#
Bases:
objectControl how phase values are wrapped and displayed.
- transform(phase)#
Return phase values in the configured display interval.
- class pycsamt.api.PyCSAMTControl#
Bases:
objectPackage-wide plotting-view control container.
- configure(**kw)#
Configure controls using
section__attributepaths.- 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
- class pycsamt.api.RhoViewControl(view='log10')#
Bases:
objectControl apparent-resistivity display scale.
- Parameters:
view (str)
- transform(rho)#
Return apparent resistivity in the configured display scale.
- error(rho, rho_err)#
Return display-scale rho errors.
- pycsamt.api.configure_control(**kw)#
Configure
PYCSAMT_CONTROLwith dotted-path arguments.- Parameters:
kw (Any)
- Return type:
None
- pycsamt.api.reset_control()#
Reset
PYCSAMT_CONTROLto package defaults.- Return type:
None
- pycsamt.api.wrap_phase(phase, phase_range=(-180.0, 180.0))#
Wrap phase values into
phase_range.
- class pycsamt.api.PyCSAMTSection#
Bases:
objectPackage-wide section-view control container.
- style_for(preset='pseudosection')#
Return the section style associated with
preset.- Parameters:
preset (str)
- Return type:
- configure(**kw)#
Configure section styles using
section__attributepaths.- Parameters:
kw (Any)
- Return type:
None
- context(preset=None, **kw)#
Temporarily override section styles, then restore them.
- Parameters:
- 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
- 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:
objectAxis behavior for section-like plots.
- Parameters:
- class pycsamt.api.SectionColorbarStyle(show=True, side='right', size='3.5%', pad=0.04, max_ticks=6, tick_format=None)#
Bases:
objectColorbar geometry and tick-density controls.
- Parameters:
- 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:
objectFigure geometry for section-like plots.
- Parameters:
- class pycsamt.api.SectionStyle(figure=<factory>, axis=<factory>, colorbar=<factory>, station_preset='pseudosection')#
Bases:
objectComplete visual-control bundle for one section preset.
- Parameters:
figure (SectionFigureStyle)
axis (SectionAxisStyle)
colorbar (SectionColorbarStyle)
station_preset (str)
- figure: SectionFigureStyle#
- axis: SectionAxisStyle#
- colorbar: SectionColorbarStyle#
- topo_active()#
Return True when the global topo config applies to this section.
Checks
PYCSAMT_TOPOagainstself.axis.y_type. Period / frequency sections return False even when topo is globally enabled, because they carry no real elevation information.- Return type:
- figsize_for(*, n_stations=None, n_y=None, labels=None, colorbar=True)#
Return a concrete figure size for this section.
- apply_axis(ax, **kw)#
Apply this style’s axis policy to
ax.
- add_colorbar(mappable, ax, *, label=None, **kw)#
Attach a colorbar using this style’s colorbar policy.
- pycsamt.api.configure_section(**kw)#
Configure
PYCSAMT_SECTION.- Parameters:
kw (Any)
- Return type:
None
- pycsamt.api.reset_section()#
Reset
PYCSAMT_SECTIONto package defaults.- Return type:
None
- class pycsamt.api.PyCSAMTStationRendering#
Bases:
objectPackage-wide station rendering control container.
- style_for(preset='pseudosection')#
Return the station-axis style associated with
preset.- Parameters:
preset (str)
- Return type:
- apply(ax, positions, labels=None, *, preset='pseudosection', xlim=None)#
Apply one named station-rendering preset to
ax.
- configure(**kw)#
Configure station rendering using
section__attributepaths.- Parameters:
kw (Any)
- Return type:
None
- context(preset=None, **kw)#
Temporarily override station rendering, then restore it.
- Parameters:
- 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
- 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:
objectStation-axis tick, label, and marker configuration.
- Parameters:
- marker: StationMarkerStyle#
- compute_every(n, figwidth_in=10.0, max_label_len=4)#
Return the interval between visible station labels.
- label_indices(labels, figwidth_in=10.0)#
Return indices whose station labels should be visible.
- 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:
- 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:
objectMarker style used to draw stations along a profile axis.
- Parameters:
- pycsamt.api.configure_station_rendering(**kw)#
Configure
PYCSAMT_STATION_RENDERING.- Parameters:
kw (Any)
- Return type:
None
- pycsamt.api.reset_station_rendering()#
Reset
PYCSAMT_STATION_RENDERINGto package defaults.- Return type:
None
- class pycsamt.api.PyCSAMTStyle(preset=None)#
Bases:
objectGlobal visual-style container for pyCSAMT.
Holds five style sub-objects:
rose—RoseStylemultiline—MultilineStylemt—MTComponentStylecorrection—CorrectionStyleraw—RawDataStylept_ellipse—PhaseTensorEllipseStyle
The module-level singleton
PYCSAMT_STYLEis 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
- 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:
objectGradient-first coloring for multi-line (multi-station / multi-profile) plots.
When mode is
"gradient", the n lines returned bycolors()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 isNone, 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.85avoids pure black.light (float) – Fraction for the lightest (last) line. Default
0.25avoids 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".
- 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:
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.plotkeyword arguments for line idx of n.- Parameters:
- Return type:
Examples
>>> kw = ms.line_kwargs(0, 5) >>> ax.plot(x, y, **kw)
- class pycsamt.api.MTComponentStyle(xy=<factory>, yx=<factory>, xx=<factory>, yy=<factory>, te=<factory>, tm=<factory>, det=<factory>)#
Bases:
objectConsistent 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
_MTCompfor key (case-insensitive).
- copy()#
Return a deep copy.
- Return type:
- class pycsamt.api.CorrectionStyle(before=<factory>, after=<factory>)#
Bases:
objectConsistent 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) andMTComponentStyle.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:
- 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:
objectVisual style for phase-tensor ellipse plots (psection, map, summary).
Each plotted ellipse simultaneously encodes five physical quantities:
Width ∝ φ_max (s1 eigenvalue — mean phase level)
Height ∝ φ_min (s2 eigenvalue — minimum phase, ≤ φ_max)
Aspect ratio = φ_min/φ_max — ellipticity (1 = isotropic / 1-D)
Rotation angle = θ (CCW from E) — geoelectric-strike indicator
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 atmin_aspect × widthkeeps every cell visible as a proper oval while leaving φ_max, θ and fill colour untouched. Set to0to 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. WhenNone, 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.
Nonederives 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 whenNoneis 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 isTrue. Set toNoneto 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, )
- 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:
- resolve_symmetric_clim()#
Return effective symmetric_clim flag, honouring c_by natural symmetry.
- Return type:
- 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()andplot_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())
- 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:
objectVisual 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=Trueunless users explicitly pass colors or force a processed-data style.- Parameters:
- plot_kwargs(**overrides)#
Return keyword arguments for raw-data line plots.
- errorbar_kwargs(**overrides)#
Return keyword arguments for raw-data error bars.
- 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:
objectVisual style bundle shared by all pycsamt rose diagram functions.
Every attribute maps 1-to-1 to a keyword argument accepted by
plot_strike_rose()andplot_phase_tensor_rose(). Pass an instance via thestyle=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_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)
- copy(**overrides)#
Return a shallow copy with overrides applied.
- Parameters:
**overrides (Any) – Any
RoseStyleattribute name and its new value.- Returns:
A new
RoseStyleinstance.- Return type:
- 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_STYLEto package defaults.Examples
>>> from pycsamt.api.style import reset_style >>> reset_style()
- Return type:
None
- pycsamt.api.configure_style(**kw)#
Configure
PYCSAMT_STYLEwith 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:
objectGlobal plot-export configuration singleton for pyCSAMT.
The module-level
PLOT_CONFIGinstance is the recommended entry point. Mutate it once (at the top of your script or notebook) and every subsequentsave_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. Use300–600for publication.bbox_inches (str, default
"tight") – Passed tosavefig().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) – Callplt.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→ usefmt.- Returns:
Clean format strings (no
+, no leading dot).- Return type:
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
savediris set, the path is resolved undersavedir.fmt (str, list[str], or None) – Per-call format override.
None→fmt.dpi (int or None) – Per-call DPI override.
None→dpi.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:
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
PlotConfigattribute 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
PlotConfigattribute 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
- pycsamt.api.save_fig(fig_or_ax, path, *, fmt=None, dpi=None, **kw)#
Save a pyCSAMT figure using the global
PLOT_CONFIGsettings.- 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.
None→PLOT_CONFIG.fmt.dpi (int or None) – Per-call DPI override.
None→PLOT_CONFIG.dpi.**kw – Forwarded to
PlotConfig.save().
- Returns:
File paths written.
- Return type:
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_CONFIGto 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.Nonesearches the default locations (pycsamt_plot.cfgin 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_CONFIGvalues.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:
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:
PyCSAMTObjectA pyCSAMT dataframe view that keeps pandas behavior intact.
APIFrameis a thin wrapper aroundpandas.DataFrame. The dataframe remains available asdf; pyCSAMT adds compact display, metadata, units, statistics, and convenient conversion helpers.- Parameters:
- classmethod from_records(records, *, columns=None, **kwargs)#
Build an
APIFramefrom record dictionaries.
- property stats: FrameProfile#
Return a compact dataframe profile.
- summary(*, max_columns=8)#
Return a static display summary for printing.
- numeric_stats(**kwargs)#
Return pandas
describefor numeric columns.
- to_pandas(*, copy=False)#
Return the underlying dataframe, optionally copied.
- to_numpy(*args, **kwargs)#
Return dataframe values as a NumPy array.
- to_dict(*args, **kwargs)#
Delegate to
DataFrame.to_dictby default.
- copy(*, deep=True)#
Return a copied view preserving metadata.
- with_df(df, **overrides)#
Return a new
APIFramewith another dataframe.
- update_meta(**kwargs)#
Update metadata in-place and return
self.
- class pycsamt.api.APIResult(**items)#
Bases:
PyCSAMTObjectContainer for named result parts, including one or more tables.
- Parameters:
items (Any)
- items()#
Return
(name, value)pairs.
- class pycsamt.api.APISurvey(collection=None, *, name=None, source=None, parser=None, meta=None)#
Bases:
PyCSAMTObjectFriendly public facade over an
EDICollection.- Parameters:
- summary(*, fields=None)#
Return an editable APIFrame summary of loaded EDI files.
- errors()#
Return parser errors from the last read operation.
- Return type:
- get_site(site, default=None)#
Return one site by station, stem, filename, or path.
- to_dataframe(*args, api=True, **kwargs)#
Return collection dataframe output, wrapped by default.
- update_meta(**kwargs)#
Update metadata in-place and return
self.
- class pycsamt.api.APIViewConfig#
Bases:
objectPackage-wide policy for dataframe-like public API views.
The backend controls what
pycsamt.api.view.wrap_frame()returns:"pycsamt"/True: return the built-inAPIFrame."pandas"/False: return the original dataframe-like object.callable: call
wrapper(data, **metadata)and return its result.
- 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.
- class pycsamt.api.FrameProfile(rows, columns, column_names, numeric_columns, missing_cells, missing_fraction, memory_bytes)#
Bases:
objectSmall immutable profile describing a dataframe.
- Parameters:
- class pycsamt.api.ProgressConfig(enabled='auto', desc=None, leave=False, unit='it', total=None)#
Bases:
objectConfiguration for terminal progress display.
- 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.
- 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.
- 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 globalPYCSAMT_API_VIEWconfiguration decides. Passapi=Trueto force wrapping, orapi=Falseto always return the raw dataframe regardless of the global setting.
- pycsamt.api.progress_enabled(value='auto')#
Return whether progress should be displayed.
- pycsamt.api.read_edi(path, *, verbose=0, **kwargs)#
Read one EDI file and return an
EDIFile.
- 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.
- pycsamt.api.read_sites(sources, **kwargs)#
Alias for
read_edis().
- 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.
- pycsamt.api.wrap_result(result, *, name='result', kind=None, meta=None, wrap_tables=True)#
Wrap a mapping of result parts as an
APIResult.
- pycsamt.api.geology_dataframe(catalog=None, *, name='geology_catalog')#
Return a public APIFrame for a geology catalog.
- pycsamt.api.geology_table(catalog=None)#
Alias for
geology_dataframe().
- pycsamt.api.quality_dataframe(sites)#
Return a public APIFrame wrapper around metadata quality rows.
- pycsamt.api.quality_table(sites)#
Alias for
quality_dataframe().
- 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
emtoolssite summary.
- class pycsamt.api.BuildConfig(n_jobs=1, cache=True, cache_dir=None)#
Bases:
objectBuild / processing execution settings.
- class pycsamt.api.LogConfig(level=0, color=True, file=None)#
Bases:
objectLogging / verbosity settings.
- class pycsamt.api.OutputConfig(format='text', dir=<factory>, overwrite=False)#
Bases:
objectOutput format and destination settings.
- class pycsamt.api.PyCSAMTCLI#
Bases:
objectPackage-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__attributedotted 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
- pycsamt.api.configure_cli(**kw)#
Configure
PYCSAMT_CLIwith 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_CLIto 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
--jobsparallel-worker option to a Click command.- Parameters:
f (FC)
- Return type:
FC
- pycsamt.api.no_cache_option(f)#
Add the
--no-cacheprocessing option to a Click command.- Parameters:
f (FC)
- Return type:
FC
- pycsamt.api.no_color_option(f)#
Add the
--no-colorterminal-output option to a Click command.- Parameters:
f (FC)
- Return type:
FC
- pycsamt.api.output_dir_option(f)#
Add the writable
--output-dirpath option to a Click command.- Parameters:
f (FC)
- Return type:
FC
- pycsamt.api.overwrite_option(f)#
Add the
--overwriteconfirmation-bypass option to a Click command.- Parameters:
f (FC)
- Return type:
FC
- pycsamt.api.verbose_option(f)#
Add the repeatable
--verboselogging option to a Click command.- Parameters:
f (FC)
- Return type:
FC
- class pycsamt.api.EDIDir#
Bases:
PathA Click Path type for a directory that contains EDI files.
- 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
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.
- class pycsamt.api.EDIPath#
Bases:
PathA Click Path type that additionally requires a
.ediextension.- 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
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.
- class pycsamt.api.FreqRange#
Bases:
ParamTypeParse a
fmin:fmaxfrequency-range string into(float, float).Examples
--freq 0.1:1000→(0.1, 1000.0)- 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
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.
- class pycsamt.api.StationList#
Bases:
ParamTypeParse a comma-separated list of station identifiers.
Examples
--stations S01,S02,S03→['S01', 'S02', 'S03']- 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
paramandctxarguments may beNonein certain situations, such as when converting prompt input.If the value cannot be converted, call
fail()with a descriptive message.
Topography Configuration#
API Modules#
pycsamt.api.agents |
|
The structure module includes data structures such as Bunch and FlexDict that provide flexible and efficient ways to organize, store, and manipulate structured data. |
|
CLI configuration API for pyCSAMT. |
|
pycsamt.api.cli.config |
|
pycsamt.api.cli.options |
|
pycsamt.api.cli.params |
|
Global plotting-view controls for pyCSAMT. |
|
Reusable docstring fragments for PyCSAMT APIs. |
|
Global visual controls for pycsamt.interp hydrogeophysical plots. |
|
Pipeline API configuration for pyCSAMT. |
|
Global pipeline configuration for pyCSAMT. |
|
pycsamt.api.plot |
|
Common object and metadata helpers for pyCSAMT APIs. |
|
Global section-view controls for pyCSAMT figures. |
|
Global station-rendering controls for pyCSAMT figures. |
|
pycsamt.api.style |
|
Shared typing helpers for PyCSAMT. |
|
util module provides utility functions and classes to support various data manipulation and analysis tasks |
|
User-facing result views for pyCSAMT public APIs. |
|
Global configuration for pyCSAMT API view wrappers. |
|
Pandas-friendly dataframe result objects for public pyCSAMT APIs. |
|
Public readers for EDI files and site collections. |
|
Progress helpers used by public pyCSAMT APIs. |
|
General result container for public pyCSAMT APIs. |
|
Public survey view over EDI collections. |
|
Opt-in APIFrame table wrappers for common pyCSAMT summaries. |