Skip to main content
Version: Next

ts_shape.signals.primitives

Spec-driven primitives: the correct way to do the five recurring operations.

Every detector in ts-shape boils down to a few operations on a signal. Done naively, each has a classic failure on industrial data:

================= ========================================================== Operation Naive failure ================= ========================================================== intervals closes at the last sample: zero-length on change-encoded data, one period short on sampled data, bridges outages increments last - first loses production at a counter reset per_window resample().mean() weights samples, not time align merge_asof(nearest) looks ahead to future setpoints windows fixed Timedelta windows break on DST days / night shifts ================= ==========================================================

The functions here take a :class:~ts_shape.signals.spec.SignalSpec and do the right thing for that signal's kind and encoding. They are pure functions on pandas objects (no hidden state), so they can later get alternative backends without changing their contract.

Functions
NameDescription
signal_seriesThe signal's values as a time-indexed Series (sorted, NaN/NaT dropped).
intervalsConstant-value intervals of a held signal, correctly closed.
incrementsPer-reading increase of a counter, reset-aware.
per_windowThe right per-window aggregate for the signal's kind.
alignPair each sample of left with the right value in force at that time.
windowsAnalysis windows covering [start, end), laid out like resample.
shift_windowsOne row per (production day, shift) overlapping start, end).

signal_series​

functionsource
signal_series(
dataframe: pd.DataFrame,
spec: SignalSpec,
*,
time_column: str = "systime",
uuid_column: str = "uuid"
) -> pd.Series

The signal's values as a time-indexed Series (sorted, NaN/NaT dropped).

Rows of other uuids are ignored, so a multi-signal frame can be passed (uuids are compared as text). Duplicate timestamps keep the last value. Nullable and pyarrow dtypes are converted to NumPy dtypes.

Parameters
NameTypeDescriptionDefault
dataframe[DataFrameLong-format frame.required
specSignalSpecThe signal's spec (uuid and value_column).required
time_columnstrTimestamp column.'systime'
uuid_columnstrSignal identifier column. A frame without it is read as one signal (a ValueError when its timestamps repeat, i.e. it clearly holds several).'uuid'
Returns
TypeDescription
SeriesValues indexed by time, named after spec.uuid.
Raises
TypeDescription
ColumnNotFoundErrorWhen time_column or spec.value_column is missing.
ValueErrorWhen the frame has no uuid_column but clearly holds several signals.

intervals​

functionsource
intervals(
dataframe: pd.DataFrame,
spec: SignalSpec,
*,
data_end: pd.Timestamp | None = None,
time_column: str = "systime",
uuid_column: str = "uuid"
) -> pd.DataFrame

Constant-value intervals of a held signal, correctly closed.

  • A held value (state, counter, level) lasts until the next sample, for both encodings; an event signal's interval ends at its last sample.
  • A gap longer than spec.max_gap is "no data": the interval before it ends at its last sample and a new interval starts after the gap, even if the value is unchanged.
  • The final interval ends at data_end when given (e.g. "now" or the end of the analysis window), otherwise at its last sample. As in :func:per_window, the last value is not held across more than spec.max_gap: when data_end is further than that after the last sample, the final interval ends at its last sample.
Parameters
NameTypeDescriptionDefault
dataframeDataFrameLong-format frame.required
specSignalSpecThe signal's spec.required
data_endTimestamp | NoneEnd of the last interval; a naive bound on tz-aware data is read in the data's timezone.None
time_columnstrTimestamp column.'systime'
uuid_columnstrSignal identifier column; rows of other uuids are ignored. A frame without it is read as one signal (a ValueError when its timestamps repeat, i.e. it clearly holds several).'uuid'
Returns
TypeDescription
DataFrameDataFrame with start, end, state, duration_seconds,
DataFramesample_count -- one row per interval, in time order.
Raises
TypeDescription
ColumnNotFoundErrorWhen time_column or spec.value_column is missing.

increments​

functionsource
increments(
dataframe: pd.DataFrame,
spec: SignalSpec,
*,
time_column: str = "systime",
uuid_column: str = "uuid"
) -> pd.Series

Per-reading increase of a counter, reset-aware.

Each value is the quantity produced since the previous reading, booked at the reading that reports it (the first reading contributes 0). With reset_policy="reset_to_zero" a drop is a reset and the post-reset value counts as new production; with "none" decreases are kept (negative increments).

Parameters
NameTypeDescriptionDefault
dataframeDataFrameLong-format frame.required
specSignalSpecThe counter's spec.required
time_columnstrTimestamp column.'systime'
uuid_columnstrSignal identifier column; rows of other uuids are ignored. A frame without it is read as one signal (a ValueError when its timestamps repeat, i.e. it clearly holds several).'uuid'
Returns
TypeDescription
SeriesFloat increments indexed by reading time.
Raises
TypeDescription
ValueErrorIf the spec is not a counter.
ColumnNotFoundErrorWhen time_column or spec.value_column is missing.

per_window​

functionsource
per_window(
dataframe: pd.DataFrame,
spec: SignalSpec,
window: str,
*,
data_end: pd.Timestamp | None = None,
time_column: str = "systime",
uuid_column: str = "uuid"
) -> pd.Series

The right per-window aggregate for the signal's kind.

  • counter -- quantity produced in each window (reset-aware increments summed per window; no production lost at window boundaries).
  • continuous / numeric or boolean state -- time-weighted mean, holding each value until the next sample and never across a gap longer than spec.max_gap. For a boolean state this is the fraction of the known time it was True: a missing reading (NA) is "unknown" until the next reading and counts neither as True nor as False.
  • event -- number of events per window.
Parameters
NameTypeDescriptionDefault
dataframeDataFrameLong-format frame.required
specSignalSpecThe signal's spec.required
windowstrWindow length as a pandas offset ("1h", "1D").required
data_endTimestamp | NoneHold the last value until this time; a naive bound on tz-aware data is read in the data's timezone.None
time_columnstrTimestamp column.'systime'
uuid_columnstrSignal identifier column; rows of other uuids are ignored. A frame without it is read as one signal (a ValueError when its timestamps repeat, i.e. it clearly holds several).'uuid'
Returns
TypeDescription
SeriesA float Series indexed by window start and named after spec.uuid
Series(for every kind).
Raises
TypeDescription
ValueErrorFor a non-numeric (e.g. string) state; use :func:intervals to get time per state instead.
ColumnNotFoundErrorWhen time_column or spec.value_column is missing.

align​

functionsource
align(
left: pd.DataFrame,
left_spec: SignalSpec,
right: pd.DataFrame,
right_spec: SignalSpec,
*,
time_column: str = "systime",
uuid_column: str = "uuid"
) -> pd.DataFrame

Pair each sample of left with the right value in force at that time.

The right signal is held backward (the last value at or before each left sample) and never across more than right_spec.max_gap: no look-ahead to a future setpoint, no stale value after an outage. The two time columns are brought to one unit first (ns, us, s and pyarrow timestamps mix freely); tz-aware right times are converted to the left timezone.

Parameters
NameTypeDescriptionDefault
leftDataFrameFrame with the left signal.required
left_specSignalSpecSpec of the left signal.required
rightDataFrameFrame with the right signal.required
right_specSignalSpecSpec of the right signal.required
time_columnstrTimestamp column of both frames; also the name of the output time column.'systime'
uuid_columnstrSignal identifier column; rows of other uuids are ignored. A frame without it is read as one signal (a ValueError when its timestamps repeat, i.e. it clearly holds several).'uuid'
Returns
TypeDescription
DataFrameDataFrame with <time_column>, <left uuid>, <right uuid>.
DataFrameWhen both specs have the same uuid the value columns are
DataFrame<uuid>_left and <uuid>_right.
Raises
TypeDescription
ValueErrorWhen one side is tz-aware and the other naive.
ColumnNotFoundErrorWhen a frame lacks time_column or its value column.

windows​

functionsource
windows(
start: pd.Timestamp | str,
end: pd.Timestamp | str,
freq: str,
*,
tz: str | None = None
) -> pd.DataFrame

Analysis windows covering [start, end), laid out like resample.

Daily and longer frequencies ("1D", "1W", "MS" ...) follow the calendar in tz: a "1D" window on a DST day is 23 h or 25 h long, not 24 h, and every window starts at local midnight. Sub-daily frequencies ("12h", "8h", "15min") are fixed lengths counted from midnight of the first day, as resample counts them: after a DST change their wall-clock starts shift by the DST offset ("12h" starts at 13:00+02:00 after the spring change, not at 12:00). For wall-clock windows such as shifts use :func:shift_windows.

Every window is [start, end) and the first one contains start, also for frequencies resample labels by their last day: "1W" gives Monday-to-Monday weeks ("W-SUN" weeks end on Sunday), "ME" calendar months from the 1st.

Example
>>> from ts_shape.signals.primitives import windows
>>> w = windows("2024-03-30", "2024-04-01", "12h", tz="Europe/Berlin")
>>> for row in w.itertuples():
... print(row.start, row.end, row.duration_seconds)
2024-03-30 00:00:00+01:00 2024-03-30 12:00:00+01:00 43200.0
2024-03-30 12:00:00+01:00 2024-03-31 00:00:00+01:00 43200.0
2024-03-31 00:00:00+01:00 2024-03-31 13:00:00+02:00 43200.0
2024-03-31 13:00:00+02:00 2024-04-01 01:00:00+02:00 43200.0
>>> list(windows("2024-03-30", "2024-04-01", "1D", tz="Europe/Berlin")
... ["duration_seconds"])
[86400.0, 82800.0]
Parameters
NameTypeDescriptionDefault
startTimestamp | strThe first window covers this time.required
endTimestamp | strExclusive end of the range.required
freqstrWindow length as a pandas offset ("1D", "8h").required
tzstr | NoneCalendar timezone; naive bounds are localized in it, aware bounds converted. Without tz, a naive bound next to an aware one is read in the aware one's timezone.None
Returns
TypeDescription
DataFrameDataFrame with start, end, duration_seconds; empty when
DataFramestart >= end.

shift_windows​

functionsource
shift_windows(
start: pd.Timestamp | str,
end: pd.Timestamp | str,
shift_definitions: Mapping[str, tuple[str, str]] | None = None,
*,
tz: str | None = None
) -> pd.DataFrame

One row per (production day, shift) overlapping start, end).

Overnight shifts (e.g. 22:00 -> 06:00) are a single window attributed to the day they start; wall-clock shift times are localized in tz so a shift spanning a DST change has its real length (7 h or 9 h).

Parameters
NameTypeDescriptionDefault
start[Timestamp | strStart of the range.required
endTimestamp | strExclusive end of the range.required
shift_definitionsMapping[str, tuple[str, str]] | None{name: ("HH:MM", "HH:MM")}; default :data:ts_shape.utils.shifts.DEFAULT_SHIFTS.None
tzstr | NoneTimezone of the wall-clock shift times. Without it, an aware bound makes the shifts use that bound's timezone.None
Returns
TypeDescription
DataFrameDataFrame with production_day, shift, start, end,
DataFrameduration_seconds; empty when start >= end.