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 -- aclassmethod/staticmethodis 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. Writeinit__<name>=to send it to the constructor only andmethod__<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.
| Name | Description |
|---|---|
PipelineResult | Outcome of :meth:Pipeline.run. |
Pipeline | A reusable, declarative chain of transform and detector steps. |
PipelineResult
PipelineResult(
name: str,
data: pd.DataFrame,
events: dict[str, pd.DataFrame],
_detector_ids: dict[str, str | None] = dict(),
) -> None
Outcome of :meth:Pipeline.run.
| Name | Type | Description |
|---|---|---|
name | str | The pipeline's name. |
data | DataFrame | The working DataFrame after the final transform step. |
events | dict[str, DataFrame] | Detector outputs keyed by step name. |
| Name | Description |
|---|---|
to_event_log | Normalize detector outputs into an OCEL event log. |
to_event_log
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.
| Name | Type | Description | Default |
|---|---|---|---|
concat | bool | When True (default) merge all logs into one EventLog; when False return a dict keyed by step name. | True |
| Type | Description |
|---|---|
ValueError | If no detector step has a known identity to normalize. |
Pipeline
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
| Name | Description |
|---|---|
source | Add a source step -- a loader that produces the pipeline's first frame. |
transform | Add a transform step -- its output replaces the working DataFrame. |
detect | Add a detector step -- its output is stored, the signal is unchanged. |
describe | Return a human-readable summary of the pipeline without running it. |
run | Execute every step. |
run_steps | Execute every step and return all intermediate DataFrames. |
run_stream | Execute the pipeline slice by slice on data larger than memory. |
| Name | Type | Description | Default |
|---|---|---|---|
name | str | A label for the pipeline, surfaced in repr and results. | 'pipeline' |
source
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.
| Name | Type | Description | Default |
|---|---|---|---|
target | Any | A callable returning a DataFrame, or a loader class. | required |
method | str | None | Method 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 |
name | str | None | Optional step label (defaults to the method/callable name). | None |
**kwargs | Any | Forwarded to the loader. The $input / $prev sentinels are not allowed -- a source has no prior data. | {} |
| Type | Description |
|---|---|
Pipeline | self, for chaining. |
| Type | Description |
|---|---|
ValueError | If the pipeline already has steps -- a source must be the first step, and only one is allowed. |
transform
transform(
target: Any,
method: str | None = None,
*,
name: str | None = None,
**kwargs: Any
) -> Pipeline
Add a transform step -- its output replaces the working DataFrame.
| Name | Type | Description | Default |
|---|---|---|---|
target | Any | A callable df -> df, or a transform class. | required |
method | str | None | Method name to call on target (omit for the callable form). | None |
name | str | None | Optional step label (defaults to the method/callable name, with a _2, _3 suffix when that name is taken). | None |
**kwargs | Any | Forwarded to the transform (routed between constructor and method for stateful classes). Values may be the $input / $prev sentinels. | {} |
| Type | Description |
|---|---|
Pipeline | self, for chaining. |
| Type | Description |
|---|---|
ValueError | If an explicit name is taken or is "input". |
detect
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.
| Name | Type | Description | Default |
|---|---|---|---|
target | Any | A callable df -> events_df, or a detector class. | required |
method | str | None | Method name to call on target (omit for the callable form). | None |
name | str | None | Optional result key (defaults to the method/callable name). | None |
**kwargs | Any | Forwarded 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. | {} |
| Type | Description |
|---|---|
Pipeline | self, for chaining. |
| Type | Description |
|---|---|
ValueError | If 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
steps: list[tuple[str, str]]
The ordered (kind, name) pairs of the configured steps.
describe
describe() -> str
Return a human-readable summary of the pipeline without running it.
run
run(dataframe: pd.DataFrame | None = None) -> PipelineResult
Execute every step.
| Name | Type | Description | Default |
|---|---|---|---|
dataframe | DataFrame | None | The input timeseries DataFrame. Omit it when the pipeline has a .source() step (the source produces it); supply it otherwise. | None |
| Name | Type | Description |
|---|---|---|
A | PipelineResult | class:PipelineResult with the final signal and detector |
PipelineResult | outputs. |
| Type | Description |
|---|---|
TypeError | If dataframe is passed to a source-bound pipeline, omitted from a sourceless one, is not a DataFrame, or a step returns a non-DataFrame. |
RuntimeError | If a step raises; the message names the step. |
run_steps
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.
| Name | Type | Description | Default |
|---|---|---|---|
dataframe | DataFrame | None | The input timeseries DataFrame. Omit it when the pipeline has a .source() step; supply it otherwise. | None |
| Type | Description |
|---|---|
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
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.
| Name | Type | Description | Default |
|---|---|---|---|
source | Any | Frames or (name, frame) pairs in time order, or a :func:ts_shape.time_range_source. | required |
chunk | Any | Slice length (default "1D"), or a calendar period ("W", "MS") as in :func:ts_shape.run_chunked. | '1D' |
overlap | Any | History before each slice; default per detector. | None |
time_column | str | Time column of the source frames. | 'systime' |
max_carry | Any | Longest an event may stay open across slices (default 7 days). | None |
keep_data | bool | When 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 |
| Name | Type | Description |
|---|---|---|
A | PipelineResult | class:PipelineResult. |
| Type | Description |
|---|---|
NotChunkableError | If 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. |
TypeError | If the pipeline has a .source() step. |