Skip to main content
Version: 0.0.98

ts_shape.pipeline

Declarative pipeline orchestrator for ts-shape.

A :class:Pipeline is the single way to chain ts-shape processing steps -- transforms and event detectors -- into one reusable definition. It is linear single-channel:

  • an optional source step (always first, at most one) calls a ts-shape loader and produces the pipeline's first DataFrame;
  • a transform step takes the working DataFrame and returns a new one that replaces it (the signal flows on);
  • a detect step runs against the current working DataFrame, stores its event output under a name, and leaves the working DataFrame unchanged (detectors branch off).

Whether a step is a source, transform or detector is declared by the caller via .source() / .transform() / .detect() -- it is never inferred.

A pipeline with a source step is source-bound: call :meth:run with no argument and the source produces the data. A pipeline without one is DataFrame-driven: pass the input DataFrame to :meth:run, as before.

A step's target may be:

  • a plain callable df -> df;
  • a (class, "method") pair -- a classmethod / staticmethod is called on the class, an instance method instantiates the class first. Keyword arguments are routed between the constructor and the method by parameter name automatically; a name both accept goes to both. Write init__<name>= to send it to the constructor only and method__<name>= to send it to the method only (see :meth:Pipeline.detect).

Keyword-argument values may use two sentinels, resolved at run time:

  • "$input" -- the DataFrame originally passed to :meth:Pipeline.run;
  • "$prev" -- the current working DataFrame.

These wire steps that need a second DataFrame (e.g. SegmentProcessor.apply_ranges). If a kwarg names the step's own DataFrame parameter, that value is used instead of the auto-injected one. Only string values are compared with the sentinels; write "$$..." for a literal string starting with $ ("$$input" passes "$input").

Each transform and detect step works on its own copy of the working DataFrame, and every $input use is a fresh copy, so a step that changes its input in place never changes the caller's DataFrame or a later step's input. Step names are unique: they key :meth:Pipeline.run_steps and the detector results, and "input" is reserved for the input frame.

Example::

from ts_shape import Pipeline
from ts_shape.transform.calculator.numeric_calc import IntegerCalc
from ts_shape.events.quality.outlier_detection import OutlierDetectionEvents

pipe = (
Pipeline(name="sensor-quality")
.transform(IntegerCalc, "scale_column",
value_column="value_double", factor=0.1)
.detect(OutlierDetectionEvents, "detect_outliers_zscore",
name="outliers", value_column="value_double", n_sigma=3.0)
)
result = pipe.run(dataframe)
result.data # final transformed DataFrame
result.events["outliers"] # detector output
result.to_event_log() # normalized, combined EventLog

Debugging::

print(pipe.describe()) # preview steps without running
steps = pipe.run_steps(df) # dict of every intermediate DataFrame

A transform step must preserve the long systime / uuid / value_* schema that downstream detectors expect. Reshaping operations (e.g. DataHarmonizer.pivot_to_wide) are terminal and belong at the end.

Classes
NameDescription
PipelineResultOutcome of :meth:Pipeline.run.
PipelineA reusable, declarative chain of transform and detector steps.

PipelineResult​

classsource
PipelineResult(
name: str,
data: pd.DataFrame,
events: dict[str, pd.DataFrame],
_detector_ids: dict[str, str | None] = dict(),
) -> None

Outcome of :meth:Pipeline.run.

Attributes
NameTypeDescription
namestrThe pipeline's name.
dataDataFrameThe working DataFrame after the final transform step.
eventsdict[str, DataFrame]Detector outputs keyed by step name.
Functions
NameDescription
to_event_logNormalize detector outputs into an OCEL event log.

to_event_log​

methodsource
to_event_log(*, concat: bool = True) -> Any

Normalize detector outputs into an OCEL event log.

Each detect step added via the (class, method) form is run through :func:ts_shape.eventlog.to_event_log (the pipeline already knows the "ClassName.method" identifier). Plain-callable detect steps have no detector identity and are skipped.

Parameters
NameTypeDescriptionDefault
concatboolWhen True (default) merge all logs into one EventLog; when False return a dict keyed by step name.True
Raises
TypeDescription
ValueErrorIf no detector step has a known identity to normalize.

Pipeline​

classsource
Pipeline(name: str = 'pipeline') -> None

A reusable, declarative chain of transform and detector steps.

Build with the fluent :meth:transform and :meth:detect methods, then call :meth:run -- on as many DataFrames as you like.

Example
>>> import ts_shape
>>> from ts_shape import OutlierDetectionEvents, Pipeline
>>> pipe = Pipeline(name="sensor-quality").detect(
... OutlierDetectionEvents, "detect_outliers_zscore",
... name="outliers", value_column="value_double")
>>> print(pipe.describe())
Pipeline 'sensor-quality' (1 steps):
0. [detect ] outliers value_column='value_double'
>>> result = pipe.run(ts_shape.make_timeseries(["temp"], n_outliers=3))
>>> result
PipelineResult(name='sensor-quality', data=1000 rows, events=['outliers'])
>>> len(result.events["outliers"])
4
Functions
NameDescription
sourceAdd a source step -- a loader that produces the pipeline's first frame.
transformAdd a transform step -- its output replaces the working DataFrame.
detectAdd a detector step -- its output is stored, the signal is unchanged.
describeReturn a human-readable summary of the pipeline without running it.
runExecute every step.
run_stepsExecute every step and return all intermediate DataFrames.
run_streamExecute the pipeline slice by slice on data larger than memory.
Parameters
NameTypeDescriptionDefault
namestrA label for the pipeline, surfaced in repr and results.'pipeline'

source​

methodsource
source(
target: Any,
method: str | None = None,
*,
name: str | None = None,
**kwargs: Any
) -> Pipeline

Add a source step -- a loader that produces the pipeline's first frame.

A source step must be the first step, and a pipeline may have at most one. With a source step, :meth:run is called with no DataFrame; without one, :meth:run requires a DataFrame as before.

Parameters
NameTypeDescriptionDefault
targetAnyA callable returning a DataFrame, or a loader class.required
methodstr | NoneMethod name to call on target (omit for the callable form). A classmethod / staticmethod is called on the class; an instance method instantiates the class first, with kwargs routed between constructor and method by name.None
namestr | NoneOptional step label (defaults to the method/callable name).None
**kwargsAnyForwarded to the loader. The $input / $prev sentinels are not allowed -- a source has no prior data.{}
Returns
TypeDescription
Pipelineself, for chaining.
Raises
TypeDescription
ValueErrorIf the pipeline already has steps -- a source must be the first step, and only one is allowed.

transform​

methodsource
transform(
target: Any,
method: str | None = None,
*,
name: str | None = None,
**kwargs: Any
) -> Pipeline

Add a transform step -- its output replaces the working DataFrame.

Parameters
NameTypeDescriptionDefault
targetAnyA callable df -> df, or a transform class.required
methodstr | NoneMethod name to call on target (omit for the callable form).None
namestr | NoneOptional step label (defaults to the method/callable name, with a _2, _3 suffix when that name is taken).None
**kwargsAnyForwarded to the transform (routed between constructor and method for stateful classes). Values may be the $input / $prev sentinels.{}
Returns
TypeDescription
Pipelineself, for chaining.
Raises
TypeDescription
ValueErrorIf an explicit name is taken or is "input".

detect​

methodsource
detect(
target: Any,
method: str | None = None,
*,
name: str | None = None,
**kwargs: Any
) -> Pipeline

Add a detector step -- its output is stored, the signal is unchanged.

Parameters
NameTypeDescriptionDefault
targetAnyA callable df -> events_df, or a detector class.required
methodstr | NoneMethod name to call on target (omit for the callable form).None
namestr | NoneOptional result key (defaults to the method/callable name).None
**kwargsAnyForwarded to the detector (routed between constructor and method by parameter name). Values may be the $input / $prev sentinels. A name that both the constructor and the method accept is passed to both. That is a trap when the two mean different things: in LongDowntimeEvents.count_events_between_gaps the constructor's value_column is the run-state column and the method's value_column is the production counter's, and in ContinuousProcessAlignmentEvents.align_to_reference the constructor's value_column is the line-speed column while the method's is the station value carried through. Prefix the name to pick one side: init__<name>= goes to the constructor only, method__<name>= to the method only (a prefixed kwarg wins over the unprefixed one on its side). A class/static method takes method__<name>= too.{}
Returns
TypeDescription
Pipelineself, for chaining.
Raises
TypeDescription
ValueErrorIf the resolved step name collides with an existing step or is "input", or a kwarg (prefixed or not) matches no parameter of the constructor / method it is routed to.
Example

Count production between long stops: the run state is a bool column, the counter an integer one::

Pipeline("between-stops").detect(
LongDowntimeEvents, "count_events_between_gaps",
name="windows", run_state_uuid="m:run",
production_df="$input", production_uuid="m:count",
aggregation="sum",
method__value_column="value_integer",
)

steps​

propertysource
steps: list[tuple[str, str]]

The ordered (kind, name) pairs of the configured steps.

describe​

methodsource
describe() -> str

Return a human-readable summary of the pipeline without running it.

run​

methodsource
run(dataframe: pd.DataFrame | None = None) -> PipelineResult

Execute every step.

Parameters
NameTypeDescriptionDefault
dataframeDataFrame | NoneThe input timeseries DataFrame. Omit it when the pipeline has a .source() step (the source produces it); supply it otherwise.None
Returns
NameTypeDescription
APipelineResultclass:PipelineResult with the final signal and detector
PipelineResultoutputs.
Raises
TypeDescription
TypeErrorIf dataframe is passed to a source-bound pipeline, omitted from a sourceless one, is not a DataFrame, or a step returns a non-DataFrame.
RuntimeErrorIf a step raises; the message names the step.

run_steps​

methodsource
run_steps(dataframe: pd.DataFrame | None = None) -> dict[str, pd.DataFrame]

Execute every step and return all intermediate DataFrames.

Useful for debugging which step changes the data unexpectedly.

Parameters
NameTypeDescriptionDefault
dataframeDataFrame | NoneThe input timeseries DataFrame. Omit it when the pipeline has a .source() step; supply it otherwise.None
Returns
TypeDescription
dict[str, DataFrame]A dict keyed by step name. For a DataFrame-driven pipeline, key
dict[str, DataFrame]"input" holds the original DataFrame; for a source-bound
dict[str, DataFrame]pipeline the loaded frame is keyed by the source step's name.
dict[str, DataFrame]Transform steps store the transformed signal; detect steps store
dict[str, DataFrame]their event output.

run_stream​

methodsource
run_stream(
source: Any,
*,
chunk: Any = "1D",
overlap: Any = None,
time_column: str = "systime",
max_carry: Any = None,
keep_data: bool = False
) -> PipelineResult

Execute the pipeline slice by slice on data larger than memory.

Every detect step runs through :func:ts_shape.run_chunked's engine on each slice as transformed by the transform steps before it in the pipeline (as :meth:run does), so each step's events equal those of :meth:run on the concatenated data. Transforms run on each slice separately: they must be row-local (each output row depends only on its input row, as unit conversions, scaling and value mappings do). The $input / $prev sentinels refer to the current slice.

Parameters
NameTypeDescriptionDefault
sourceAnyFrames or (name, frame) pairs in time order, or a :func:ts_shape.time_range_source.required
chunkAnySlice length (default "1D"), or a calendar period ("W", "MS") as in :func:ts_shape.run_chunked.'1D'
overlapAnyHistory before each slice; default per detector.None
time_columnstrTime column of the source frames.'systime'
max_carryAnyLongest an event may stay open across slices (default 7 days).None
keep_databoolWhen True, result.data is the transformed data of every slice concatenated (it then holds all rows in memory); by default it is an empty frame with the transformed columns.False
Returns
NameTypeDescription
APipelineResultclass:PipelineResult.
Raises
TypeDescription
NotChunkableErrorIf a detect step's method cannot run chunked (see :data:ts_shape.stream.SUPPORT and :data:ts_shape.stream.CONDITIONAL), or is a plain callable.
TypeErrorIf the pipeline has a .source() step.