Skip to main content
Version: 0.0.98

ts_shape.stream

Chunked processing: run a detector slice by slice on data larger than memory.

:func:run_chunked cuts the data into time slices (one day by default), runs the detector on one slice at a time and stitches the slices together, so memory holds about one slice while the result equals the in-memory run::

Target(full_df, **init_kwargs).method(**method_kwargs)

(up to float rounding). It works for the methods in :data:SUPPORT, and for those in :data:CONDITIONAL when the call passes the argument named there; every other method raises :class:~ts_shape.errors.NotChunkableError.

chunk is a fixed length ("1D", "12h") or a calendar period: "W" (weeks from Monday 00:00), "W-<DAY>" (weeks ending on <DAY>) or "MS" (calendar months), cut at local midnight. Weekly and monthly summaries need the matching calendar chunk.

How the slices are stitched​

Each slice is run on a context frame: the slice's own rows, plus for every signal the last reading before the context (a held state starts where it started) and the first reading at or after the slice end (the last interval of the slice closes where the in-memory run closes it). Rolling methods also get overlap of history before the slice.

What is kept of a slice's result depends on the shape of the method's output (:data:ts_shape.eventlog.taxonomy.REGISTRY):

  • point events are kept when their systime lies in the slice;
  • interval events still open at the slice end (they touch its last sample) are not emitted: the rows from the start of the earliest open interval on are carried into the next slice, which computes the interval again with more data. Closed intervals that start in the slice are kept, so min_duration filters and merged runs come out exactly as in memory;
  • summary windows are kept when they start in the slice; a window that ends after the slice end (an overnight shift) is carried like an open interval. The chunk must be a whole multiple of the method's window.

A few outputs need the whole run and are completed at the end of the stream (see _RUNNING_COUNTS, _ZERO_FILL and _LAST_STEP): sample counts from the start / to the end of a signal, zero windows between two slices' events, and the last window of a coverage report.

Methods that need the whole signal at once (static outputs, whole-signal sigma or quantiles, model fits, baselines taken from the first window) are not chunkable.

Sources​

  • any iterable of long-format DataFrames, or of (name, DataFrame) pairs such as the loaders' stream_by_time_range. Frames must come in time order at slice granularity: once a row of a later slice has been seen, a row of an earlier slice raises ValueError;
  • :func:time_range_source, which calls load(start, end) once per slice (databases, TimescaleDB, any loader with a time-range query).
Classes
NameDescription
ConditionWhat a method of :data:CONDITIONAL needs to run chunked.
Functions
NameDescription
time_range_sourceLoad [start, end) one slice at a time.
iter_chunkedRun a detector slice by slice and yield the finished rows of each slice.
run_chunkedRun a detector slice by slice on data larger than memory.

Condition​

classsource

Bases: NamedTuple

What a method of :data:CONDITIONAL needs to run chunked.

time_range_source​

functionsource
time_range_source(
load: Callable[[pd.Timestamp, pd.Timestamp], pd.DataFrame],
start: Any,
end: Any,
chunk: Any = "1D",
*,
time_column: str = "systime"
) -> Iterator[pd.DataFrame]

Load start, end) one slice at a time.

Calls load(slice_start, slice_end) for each slice of the chunk grid (the first and last slice are clipped to start / end) and yields the frames in time order, ready for :func:run_chunked. Rows outside the half-open [slice_start, slice_end) are dropped, so a loader with an inclusive end does not deliver a row twice.

Parameters
NameTypeDescriptionDefault
load[Callable[[Timestamp, Timestamp], DataFrame](start, end) -> DataFrame, e.g. a database query or lambda s, e: loader.load_by_time_range(s, e).required
startAnyFirst instant (anything pd.Timestamp accepts).required
endAnyEnd of the range, exclusive.required
chunkAnySlice length, aligned like :func:run_chunked's chunk.'1D'
time_columnstrTime column of the loaded frames.'systime'
Yields
TypeDescription
DataFrameOne DataFrame per slice.

iter_chunked​

functionsource
iter_chunked(
source: Any,
target: Any,
method: str | None = None,
*,
chunk: Any = "1D",
overlap: Any = None,
time_column: str = "systime",
max_carry: Any = None,
**kwargs: Any
) -> Iterator[pd.DataFrame]

Run a detector slice by slice and yield the finished rows of each slice.

Same arguments as :func:run_chunked. Each result row is yielded exactly once, in slice order; slices that finish no row yield nothing. Use it to write results out as they come (e.g. one parquet file per slice).

Rows that need the whole run are yielded together at the end, after the last slice: every row of DataGapAnalysisEvents.detect_gaps (samples_after_gap counts to the end of the signal) and the last window of DataGapAnalysisEvents.coverage_by_period (its missing time after the last sample uses the whole signal's median sampling step).

Raises
TypeDescription
NotChunkableErrorIf the method is not in :data:SUPPORT, or is in :data:CONDITIONAL and the call lacks the argument named there.
ValueErrorFor a chunk that does not tile the method's windows, an out-of-order source, or an event open longer than max_carry.

run_chunked​

functionsource
run_chunked(
source: Any,
target: Any,
method: str | None = None,
*,
chunk: Any = "1D",
overlap: Any = None,
time_column: str = "systime",
max_carry: Any = None,
**kwargs: Any
) -> pd.DataFrame

Run a detector slice by slice on data larger than memory.

The result equals target(full_df, **init_kwargs).method(**method_kwargs) on the concatenated data (up to float rounding and row order) while memory holds about one slice.

Parameters
NameTypeDescriptionDefault
sourceAnyAn iterable of long-format DataFrames or of (name, DataFrame) pairs (a loader's stream_by_time_range), in time order at slice granularity, or a :func:time_range_source.required
targetAnyThe detector class, e.g. MachineStateEvents.required
methodstr | NoneThe method name, e.g. "detect_run_idle". Deprecated names resolve to their current names.None
chunkAnySlice length ("1D" default, "12h", a Timedelta), or a calendar period: "W" (Monday 00:00 to Monday 00:00; also "W-<DAY>", weeks ending on <DAY>) or "MS" (calendar months). Slices are aligned to the wall clock of the data's timezone, so a daily slice on a DST change lasts 23 or 25 hours. weekly_summary / monthly_summary need "W" / "MS".'1D'
overlapAnyHistory before each slice for rolling methods. Default: the method's window-like argument (window, baseline_window, ...), or none.None
time_columnstrTime column of the source frames (also passed to the detector when it is not "systime").'systime'
max_carryAnyLongest an event may stay open across slices, and longest the run waits for a signal's next reading (default 7 days).None
**kwargsAnyConstructor and method arguments, routed by name as in :meth:ts_shape.Pipeline.detect.{}
Returns
TypeDescription
DataFrameThe detector's result, one row per event or window, in slice order
DataFramewith a fresh index. An empty source gives the method's empty result.
Raises
TypeDescription
NotChunkableErrorIf the method is not in :data:SUPPORT, or is in :data:CONDITIONAL and the call lacks the argument named there.
ValueErrorFor a chunk that does not tile the method's windows, an out-of-order source, or an event open longer than max_carry.
Example
>>> import pandas as pd
>>> from ts_shape import MachineStateEvents, run_chunked
>>> t = pd.date_range("2024-01-01", periods=6, freq="12h")
>>> df = pd.DataFrame({"systime": t, "uuid": "run",
... "value_bool": [1, 1, 0, 1, 1, 1]})
>>> days = (g for _, g in df.groupby(df["systime"].dt.date))
>>> out = run_chunked(days, MachineStateEvents, "detect_run_idle",
... run_state_uuid="run")
>>> out[["start", "end", "state"]]
start end state
0 2024-01-01 00:00:00 2024-01-02 00:00:00 run
1 2024-01-02 00:00:00 2024-01-02 12:00:00 idle
2 2024-01-02 12:00:00 2024-01-03 12:00:00 run