pycsamt.pipeline#
Declarative processing pipelines, step registries, presets, output handling, and report generation.
pyCSAMT processing pipeline.
A declarative, automated MT processing engine that chains emtools operations from raw Sites to publication-ready output.
This package is the single entry point for all pipeline-related symbols.
The processing engine lives in the private sub-modules of this package
(_registry, _steps, _pipeline, …). Runtime configuration is
provided by pycsamt.api.pipe and re-exported here so users only need
one import location.
Typical usage#
Build and run from code:
from pycsamt.pipeline import Pipeline, Step
pipe = Pipeline([
("notch", Step("NR001", mains_hz=50)),
("band", Step("FREQ001")),
("align", Step("FREQ004")),
("correct_ss", Step("SS001")),
("rotate", Step("TZ001")),
])
print(pipe)
result = pipe.run(sites, outdir="willy_results/")
# shortest path — Pipeline and Step are also on pycsamt directly
from pycsamt import Pipeline, Step
Load from a config file:
pipe = Pipeline.from_yaml("config/workflow.yaml")
pipe = Pipeline.from_preset("publication_ready")
Discover available steps and presets:
from pycsamt.pipeline import list_steps, preset_catalogue
list_steps() # all 33 StepSpec objects
list_steps("noise_removal") # by category
print(preset_catalogue()) # named presets
Configure pipeline output globally:
from pycsamt.pipeline import configure_pipe
configure_pipe(plot_dpi=300, plot_fmt="pdf", output_root="results/")
# or temporarily with a context manager
from pycsamt.pipeline import PYCSAMT_PIPE
with PYCSAMT_PIPE.context(show_progress=False):
result = pipe.run(sites)
- class pycsamt.pipeline.PipelineBase#
Bases:
objectBase class for pyCSAMT pipeline objects.
Inherit from this to gain registry introspection,
to_pyexport, andscaffoldtemplate generation.Pipelineinherits this.- static available_steps(category=None)#
Return all registered
StepSpecobjects.- Parameters:
category (str | None) – When supplied, restrict to steps in that category (e.g.
"noise_removal","frequency").- Return type:
Examples
>>> Pipeline.available_steps() >>> Pipeline.available_steps("static_shift")
- static available_categories()#
Return a sorted list of step category names.
Examples
>>> Pipeline.available_categories() ['dimensionality', 'frequency', 'noise_removal', ...]
- static step_info(code_or_name)#
Return a formatted info block for a single step.
- Parameters:
code_or_name (str) – Registry code (
"NR001") or snake-case name ("notch_powerline").- Return type:
Examples
>>> print(Pipeline.step_info("NR001")) >>> print(Pipeline.step_info("correct_ss_ama"))
- classmethod catalogue(category=None)#
Return a full formatted catalogue of all available steps.
- Parameters:
category (str | None) – Restrict output to one category, or
Nonefor all.- Return type:
Examples
>>> print(Pipeline.catalogue()) >>> print(Pipeline.catalogue("tensor"))
- to_py(path=None)#
Serialize this pipeline to a Python config script.
Produces a
pipeline_configdict in a clean, readable.pyfile that can be edited and reloaded withfrom_py(). Steps are grouped by category and commented with their human-readable labels.- Parameters:
path (str | Path | None) – If given, write the output to this file path.
- Returns:
The generated Python source as a string (always returned, whether or not path is provided).
- Return type:
Examples
>>> src = pipe.to_py() >>> print(src) >>> pipe.to_py("config/my_workflow.py")
- classmethod scaffold(path=None, *, fmt='yaml', preset=None, name='my_workflow', outdir='pipe_results')#
Generate a ready-to-edit starter pipeline config.
The scaffold contains: - Active steps from preset (or a sensible default set) - All other available steps commented out with descriptions
- Parameters:
path (str | Path | None) – Write the output to this file. Extension is inferred from fmt if the path has none.
fmt (str) – Output format:
"yaml"(default),"json", or"py".preset (str | None) – Name of a built-in preset to use as the active step set (e.g.
"basic_qc","full_processing"). WhenNonea minimalbasic_qc-style set is used.name (str) – Pipeline name written into the config.
outdir (str) – Default output directory written into the config.
- Returns:
The generated config content as a string.
- Return type:
Examples
>>> print(Pipeline.scaffold()) >>> Pipeline.scaffold("config/starter.yaml", preset="full_processing") >>> Pipeline.scaffold("config/starter.py", fmt="py")
- class pycsamt.pipeline.Pipeline(steps, *, name='pipeline', _output_dir=None)#
Bases:
PipelineBaseAn ordered, configurable MT processing pipeline.
- Parameters:
Examples
>>> from pycsamt.emtools.pipe import Pipeline, Step >>> pipe = Pipeline([ ... ("notch", Step("NR001")), ... ("band", Step("FREQ001", band_hz=(0.001, 10000))), ... ("align", Step("FREQ004")), ... ]) >>> print(pipe)
- append(label, step)#
Add step to the end of the pipeline.
Returns self so calls can be chained.
- insert(idx, label, step)#
Insert step at position idx (0-based).
Returns self.
- remove(label)#
Remove the first step whose label matches label.
Returns self.
- replace(label, step)#
Replace the step labelled label with step.
Returns self.
- run(sites, *, outdir=<object object>, save_plots=True, save_edis=True, save_report=True, api=None)#
Run all steps in order and return a
PipelineResult.- Parameters:
outdir (Any) – Root output directory. Falls back first to the pipeline’s own
_output_dir(set byfrom_yaml), then tooutput_root.save_plots (bool) – Generate and save QC figures for each step.
save_edis (bool) – Write processed EDI files after the final step.
save_report (bool) – Write HTML and/or text reports to outdir.
api (Any) – Optional
PipelineAPIConfigoverride. WhenNonethe global singleton is used.
- Return type:
- classmethod from_yaml(path)#
Load a pipeline from a YAML config file.
- classmethod from_json(path)#
Load a pipeline from a JSON config file.
- classmethod from_py(path)#
Load a pipeline from a Python config file.
The file must expose a
pipeline_configdict.
- classmethod from_preset(name, pipeline_name=None)#
Build a pipeline from a named preset.
- Parameters:
- Return type:
See also
pycsamt.emtools.pipe.preset_catalogue
- to_yaml(path)#
Write this pipeline config to path as YAML.
- to_json(path)#
Write this pipeline config to path as JSON.
- describe()#
Return a
pandas.DataFramedescribing the pipeline steps.- Return type:
- class pycsamt.pipeline.PipelineResult(sites_in, sites_out, step_results, outdir, elapsed_sec, processed_paths=<factory>, pipeline_name='pipeline')#
Bases:
objectReturn value of
Pipeline.run().- Variables:
sites_in (Any) – Original Sites passed to
Pipeline.run().sites_out (Any) – Fully processed Sites after all steps.
step_results (list[pycsamt.pipeline._steps.StepResult]) – One
StepResultper pipeline step, in order.outdir (pathlib.Path | None) – Root output directory (
Nonewhen no output was requested).elapsed_sec (float) – Total wall-clock time for the run.
processed_paths (list[pathlib.Path]) – Paths of EDI files written to
<outdir>/processed/.pipeline_name (str) – Name label of the pipeline.
- Parameters:
- step_results: list[StepResult]#
- class pycsamt.pipeline.Step(code_or_name, **params)#
Bases:
objectA configured pipeline step.
- Parameters:
Examples
>>> from pycsamt.emtools.pipe import Step >>> Step("NR001", mains_hz=50) Step [NR001] Power-line Harmonic Notch (mains_hz=50, n_harm=30, tol_hz=0.08) >>> Step("notch_powerline") Step [NR001] Power-line Harmonic Notch (mains_hz=50, n_harm=30, tol_hz=0.08)
- transform(sites)#
Apply the step’s transform function to sites.
If the step has
returns_sites=False(diagnostic-only), the input sites is returned unchanged.
- generate_qc_plots(sites)#
Call QC plot functions on sites and return
(name, Figure)pairs.Return values are normalised to
matplotlib.figure.Figureso the pipeline can callsavefigregardless of whether the underlying emtools function returned aFigureor anAxesobject. Failures are silently skipped so that a broken QC plot never kills a successful processing run.
- class pycsamt.pipeline.StepResult(step_idx, step_name, step_code, step_label, params, elapsed_sec, plots=<factory>, n_sites_in=0, n_sites_out=0, error=None)#
Bases:
objectImmutable record produced after one pipeline step runs.
- Variables:
step_idx (int) – 1-based position in the pipeline.
step_name (str) – User-supplied label for this step in the pipeline.
step_code (str) – Registry code (e.g.
"NR001").step_label (str) – Human-readable label from the registry.
params (dict) – Parameters that were passed to the transform function.
elapsed_sec (float) – Wall-clock time in seconds for this step (transform + QC plots).
plots (list[pathlib.Path]) – Paths of figures saved to disk during this step.
n_sites_in (int) – Number of sites fed into this step.
n_sites_out (int) – Number of sites coming out of this step.
error (Exception | None) – If the step raised an exception and execution continued (
on_step_error != "raise"), the exception is stored here.Nonemeans the step completed without error.
- Parameters:
- class pycsamt.pipeline.StepSpec(code, name, label, category, defaults=<factory>, returns_sites=True, mod=None, fn_name=None, qc_defs=<factory>, override_fn=None)#
Bases:
objectImmutable descriptor for one pipeline step.
- Parameters:
code (str) – Short uppercase identifier, e.g.
"NR001".name (str) – Snake-case name, e.g.
"notch_powerline".label (str) – Human-readable label shown in pipeline
__repr__.category (str) – Logical group (
"frequency","noise_removal","static_shift","tensor","dimensionality","skew","source_effects","qc").defaults (dict) – Keyword arguments passed to the transform function when not overridden by the user.
returns_sites (bool) –
True– step transforms the Sites object (default).False– diagnostic-only step; the Sites pass through unchanged.mod (str | None) – Dotted module path for the primary transform function.
Nonewhen override_fn is provided.fn_name (str | None) – Name of the transform function inside mod.
Nonewhen override_fn is provided.qc_defs (list[tuple[str, str]]) – List of
(module_path, function_name)pairs. The pipeline calls these after each step to generate QC figures.override_fn (Callable | None) – Direct callable override. When set, mod / fn_name are ignored.
- pycsamt.pipeline.list_steps(category=None)#
Return all registered
StepSpecobjects, optionally filtered.
- pycsamt.pipeline.categories()#
Return a sorted list of distinct step categories.
- class pycsamt.pipeline.Preset(name, description, steps=<factory>)#
Bases:
objectA named, ordered collection of pipeline steps.
- Variables:
- Parameters:
- pycsamt.pipeline.load_yaml(path)#
Parse a YAML pipeline config file and return the raw dict.
- pycsamt.pipeline.load_json(path)#
Parse a JSON pipeline config file and return the raw dict.
- pycsamt.pipeline.load_py(path)#
Import a Python config file and return its
pipeline_configdict.
- pycsamt.pipeline.plot_pipeline_dashboard(result, *, figsize=(12.0, 8.0))#
Create a compact dashboard for a completed pipeline run.
The dashboard combines run-level cards, per-step status, timing, station-count flow, and generated-figure counts. It is the most useful single figure to place in a processing report or notebook.
- Returns:
Figure containing the dashboard.
- Return type:
- Parameters:
result (PipelineResult)
- pycsamt.pipeline.plot_pipeline_status(result, *, ax=None, ok_color='#2f9e44', error_color='#c92a2a', annotate_errors=True)#
Plot per-step success status for a pipeline run.
Failed steps are coloured red and, when available, the exception message is written below the corresponding bar. Empty results draw a neutral placeholder instead of failing.
- pycsamt.pipeline.plot_pipeline_timing(result, *, ax=None, color='#2f6f8f', slow_color='#f08c00', slow_quantile=0.8, annotate=True)#
Plot elapsed time per pipeline step.
Steps above slow_quantile are highlighted, helping users quickly spot expensive processing or plotting stages.
- pycsamt.pipeline.plot_site_count_flow(result, *, ax=None, color_in='#687582', color_out='#7c4d79', drop_color='#c92a2a', annotate=True)#
Plot station counts entering and leaving each pipeline step.
A faint red band marks steps where the output site count is lower than the input site count, which is useful for QC workflows that reject stations.
- class pycsamt.pipeline.StratagemPreset(name, description, survey_defaults=<factory>, steps=<factory>)#
Bases:
objectNamed configuration bundle for
StratagemSurvey.Used by
run_stratagem_preset(). Each preset describes an ordered sequence ofStratagemSurveymethod calls with default keyword arguments.- Variables:
- Parameters:
- class pycsamt.pipeline.StratagemPipeline(steps, *, coord_file=None, raw_dir=None, epsg=32649, utm_zone='49N', order='auto', rename_basename=None, rename_dir=None, name='stratagem_pipeline')#
Bases:
PipelineA
Pipelineextended with Stratagem pre/post-processing.Follows exactly the same
run(sites, *, outdir=...)interface as the standard pipeline. The sites argument is normalised viaensure_sites(), so it accepts:str/pathlib.Pathpointing to a directory of EDIsstr/pathlib.Pathpointing to a single EDI fileA single
EDIFileobjectA list of
EDIFileobjects
Optional pre-processing (applied before emtools steps)#
Coordinate injection — when coord_file is given, GPS coordinates from a CSV / XLS / XLSX table are written into each EDI
>HEADsection viaCoordinateInjector.Hardware SNR mask — when raw_dir is given, zero-stack frequency rows in the Stratagem raw files are masked in the impedance tensor via
FrequencyFilter.
Optional post-processing (applied after emtools steps)#
Rename — when rename_basename is given, the output EDI files in
<outdir>/processed/are copied to<outdir>/renamed/with a standardised naming convention usingEDIRenamer.
- param steps:
emtools processing steps (same format as
Pipeline).- type steps:
list of (str, Step) or list of Step
- param coord_file:
GPS coordinate table (CSV / XLS / XLSX).
- type coord_file:
path-like, optional
- param raw_dir:
Directory of raw Stratagem hardware files for hardware SNR masking.
- type raw_dir:
path-like, optional
- param epsg:
EPSG code of the projected CRS in coord_file.
- type epsg:
int, default 32649
- param utm_zone:
- type utm_zone:
str, default
'49N'- param order:
Station ordering for
StationLocator.- type order:
str, default
'auto'- param rename_basename:
When given, output EDIs are renamed
{basename}000.edi, …- type rename_basename:
str, optional
- param rename_dir:
Destination for renamed files. Defaults to
<outdir>/renamed/.- type rename_dir:
path-like, optional
- param name:
- type name:
str, default
'stratagem_pipeline'
Examples
Load a directory and inject coordinates:
from pycsamt.pipeline.stratagem import StratagemPipeline pipe = StratagemPipeline.from_preset( "stratagem_mt", coord_file="2.csv", epsg=32649, rename_basename="T2.", ) result = pipe.run("2/2EDI", outdir="2/processed") print(result.summary())
Single EDI file:
result = pipe.run("2/2EDI/Z2HX002.edi", outdir="tmp/single/")
Already-loaded Sites:
from pycsamt.emtools._core import ensure_sites S = ensure_sites("2/2EDI") result = pipe.run(S, outdir="2/processed")
Custom steps with hardware mask:
from pycsamt.pipeline import Step pipe = StratagemPipeline( [("ss", Step("SS001")), ("band", Step("FREQ001", band_hz=(10, 1e5)))], coord_file="2.csv", raw_dir="原始数据/2HX", epsg=32649, ) result = pipe.run("2/2EDI", outdir="out/")
- run(sites, *, outdir=None, save_plots=True, save_edis=True, save_report=True, api=None, rename_basename=None, rename_dir=None, overwrite=False)#
Run the pipeline on sites.
- Parameters:
sites (Sites | str | Path | EDIFile | list[EDIFile]) – Input data. Any form accepted by
ensure_sites().outdir (path-like, optional) – Root output directory (same as
Pipeline.run()).save_plots (bool, default True)
save_edis (bool, default True)
save_report (bool, default True)
api (PipelineAPIConfig, optional)
rename_basename (str, optional) – Override the rename_basename set in
__init__.rename_dir (path-like, optional) – Override the rename_dir set in
__init__.overwrite (bool, default False) – Overwrite existing renamed files.
- Return type:
- classmethod from_preset(name='stratagem_mt', *, coord_file=None, raw_dir=None, epsg=32649, utm_zone='49N', order='auto', rename_basename=None, rename_dir=None, pipeline_name=None)#
Build a
StratagemPipelinefrom a named emtools preset.- Parameters:
name (str, default
'stratagem_mt') – Any preset inPRESETS(e.g.'stratagem_mt','full_processing','publication_ready').coord_file (str | Path | None) – Forwarded to the constructor.
epsg (int) – Forwarded to the constructor.
utm_zone (str) – Forwarded to the constructor.
order (str) – Forwarded to the constructor.
rename_basename (str | None) – Forwarded to the constructor.
rename_dir (str | Path | None) – Forwarded to the constructor.
pipeline_name (str, optional) – Override the pipeline label.
- Return type:
Examples
>>> pipe = StratagemPipeline.from_preset( ... "stratagem_mt", ... coord_file="2.csv", ... epsg=32649, ... rename_basename="T2.", ... ) >>> result = pipe.run("2/2EDI", outdir="2/processed")
- pycsamt.pipeline.get_stratagem_preset(name)#
Return the
StratagemPresetfor name.- Parameters:
name (str)
- Return type:
- pycsamt.pipeline.list_stratagem_presets()#
Return all
StratagemPresetobjects.- Return type:
- pycsamt.pipeline.run_stratagem_preset(preset, edi_dir, coord_file, outdir, *, raw_dir=None, epsg=32649, utm_zone='49N', rename_basename='S', rename_dir=None, step_overrides=None, overwrite=False, verbose=0)#
Execute a named Stratagem preset in one call (convenience wrapper).
Uses
StratagemSurveyinternally for the full EDI-directory + GPS-CSV workflow. For the pipeline-style API (run(sites, outdir=...)) useStratagemPipelinedirectly.- Parameters:
preset ({'basic', 'full_processing', 'publication_ready'})
edi_dir (path-like)
coord_file (path-like)
outdir (path-like)
raw_dir (path-like, optional)
epsg (int, default 32649)
utm_zone (str, default
'49N')rename_basename (str, default
'S')rename_dir (path-like, optional)
step_overrides (dict, optional) – Per-step parameter overrides (see
StratagemPipeline).overwrite (bool, default False)
verbose (int, default 0)
- Returns:
The completed survey object.
- Return type:
StratagemSurvey
Examples
Replicate the legacy script:
sv = run_stratagem_preset( "basic", edi_dir="2/2EDI", coord_file="2.csv", outdir="2/processed", epsg=32649, rename_basename="T2.", )
With hardware files:
sv = run_stratagem_preset( "full_processing", edi_dir="2/2EDI", coord_file="2.csv", outdir="2/processed", raw_dir="原始数据/2HX", epsg=32649, rename_basename="T2.", )
- pycsamt.pipeline.stratagem_preset_catalogue()#
Return a formatted catalogue of all Stratagem presets.
- Return type:
- class pycsamt.pipeline.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.pipeline.configure_pipe(**kw)#
Configure the global
PYCSAMT_PIPEsingleton.- Parameters:
kw (Any)
- Return type:
None
- pycsamt.pipeline.reset_pipe()#
Reset
PYCSAMT_PIPEto package defaults.- Return type:
None
Pipeline Modules#
Core Pipeline class for the pyCSAMT processing engine. |
|
Step and StepResult — user-facing wrappers around StepSpec entries. |
|
Step registry for the pyCSAMT processing pipeline. |
|
Named pipeline presets for common MT processing workflows. |
|
Config-file loaders for the pyCSAMT pipeline. |
|
Output-directory management for the pyCSAMT pipeline. |
|
Pipeline report generators. |
|
Base class for pyCSAMT pipeline objects. |
|
pipeline.stratagem |
|
Plot helpers for |