Skip to main content
Version: Next

ts_shape.utils.time_accounting

Time and quantity accounting per period (shift, hour, day, ...).

KPIs such as availability, utilization or performance are ratios of durations and quantities within a period. ISO 22400-2 defines them on the time that actually falls inside the period: a stop that starts at 07:00 and lasts until 15:00 contributes 7 h of down time to the 06:00-14:00 shift and 1 h to the 14:00-22:00 shift -- not 8 h to the shift it started in.

Booking a whole interval to the period of its start reading is a common shortcut that breaks every period-level KPI on change-encoded data (one row per transition) and on any interval that crosses a boundary. This module does the accounting correctly:

  • :func:reading_intervals -- one [t_i, t_{i+1}) interval per reading, the reading's state held until the next one (over-long gaps can be marked as "no data").
  • :func:shift_periods, :func:grouper_periods, :func:floor_periods -- the period grid covering a time range: shift windows (overnight shifts and the production day included), pd.Grouper / resample bins, or floor-aligned windows. Wall-clock bounds are localized in the data's timezone, so a DST day lasts 23 h or 25 h.
  • :func:split_intervals -- each interval cut at the period boundaries.
  • :func:time_by_period -- seconds per (period, state).
  • :func:spread_increments -- a counter increment between two readings spread over (t_prev, t] in proportion to time, so the parts produced across a boundary are shared between the periods they were produced in.
Functions
NameDescription
reading_intervalsOne interval per reading: its state held until the next reading.
shift_periodsShift windows covering [t0, t1], labeled like the readings would be.
grouper_periodsThe pd.Grouper(freq=window) bins covering [t0, t1].
floor_periodsWindows labeled by floor_local(t, window) covering [t0, t1].
split_intervalsCut each interval at the period boundaries.
time_by_periodSeconds per period and state, intervals split at period boundaries.
spread_incrementsCounter increments spread over the time they were produced in.
counter_by_periodReset-aware counter quantity and resets per period.

reading_intervals​

functionsource
reading_intervals(
times: pd.Series, states: pd.Series, *, max_gap: Any = None
) -> pd.DataFrame

One interval per reading: its state held until the next reading.

Parameters
NameTypeDescriptionDefault
timesSeriesReading times of one signal, sorted.required
statesSeriesState per reading, aligned with times.required
max_gapAnyOptional cap ("15min", Timedelta). An interval longer than this is a logging gap: its state becomes :data:EXCLUDED.None
Returns
TypeDescription
DataFrameDataFrame with start, end, state. The last reading has no
DataFramesuccessor and opens no interval.

shift_periods​

functionsource
shift_periods(
t0: pd.Timestamp,
t1: pd.Timestamp,
shift_definitions: Mapping[str, tuple[str, str]],
*,
production_day: bool = True
) -> pd.DataFrame

Shift windows covering [t0, t1], labeled like the readings would be.

Each window is labeled with the shift that :func:~ts_shape.utils.shifts.assign_shift gives a reading in it ("unknown" for time no shift covers) and the date that :func:~ts_shape.utils.shifts.production_dates gives it (production_day=True: an overnight shift is one window on its start date) or the calendar date (production_day=False: an overnight shift is cut at midnight into two windows). Wall-clock bounds are localized in the timezone of t0.

Parameters
NameTypeDescriptionDefault
t0TimestampStart of the range.required
t1TimestampEnd of the range.required
shift_definitionsMapping[str, tuple[str, str]]{name: ("HH:MM", "HH:MM")}.required
production_dayboolLabel by production day (default) or calendar date.True
Returns
TypeDescription
DataFrameDataFrame with date, shift, start, end -- contiguous,
DataFramesorted windows overlapping [t0, t1].

grouper_periods​

functionsource
grouper_periods(
t0: pd.Timestamp, t1: pd.Timestamp, window: Any
) -> pd.DataFrame

The pd.Grouper(freq=window) bins covering [t0, t1].

Parameters
NameTypeDescriptionDefault
t0TimestampStart of the range.required
t1TimestampEnd of the range.required
windowAnyResample frequency ("1h", "1D", "W", ...).required
Returns
TypeDescription
DataFrameDataFrame with period (the resample label), start and end
DataFrame(the true bin bounds, calendar-correct on DST days and for
DataFrameright-labeled frequencies), sorted.

floor_periods​

functionsource
floor_periods(t0: pd.Timestamp, t1: pd.Timestamp, window: Any) -> pd.DataFrame

Windows labeled by floor_local(t, window) covering [t0, t1].

Parameters
NameTypeDescriptionDefault
t0TimestampStart of the range.required
t1TimestampEnd of the range.required
windowAnyFixed frequency ("15min", "1h", "8h", "1D").required
Returns
TypeDescription
DataFrameDataFrame with period (the floored label), start (= label)
DataFrameand end (the next label; the last window ends one window
DataFramelater, a calendar day for "D"), sorted.

split_intervals​

functionsource
split_intervals(
intervals: pd.DataFrame, periods: pd.DataFrame, *, keys: Sequence[str]
) -> pd.DataFrame

Cut each interval at the period boundaries.

Parameters
NameTypeDescriptionDefault
intervalsDataFramestart, end and any other columns (carried over).required
periodsDataFrameNon-overlapping periods with start, end and the keys columns.required
keysSequence[str]Period label columns copied to each piece.required
Returns
TypeDescription
DataFrameOne row per (interval, period) with positive overlap: the keys,
DataFramethe interval's other columns, start / end of the piece,
DataFrameseconds and fraction (piece / whole interval).

time_by_period​

functionsource
time_by_period(
intervals: pd.DataFrame,
periods: pd.DataFrame,
*,
keys: Sequence[str],
states: Sequence[str]
) -> pd.DataFrame

Seconds per period and state, intervals split at period boundaries.

Parameters
NameTypeDescriptionDefault
intervalsDataFramestart, end, state.required
periodsDataFrameNon-overlapping periods with start, end, keys.required
keysSequence[str]Period label columns.required
statesSequence[str]The state labels to report; each becomes a float column of seconds (0 when a period holds none of it). Intervals in other states are ignored.required
Returns
TypeDescription
DataFrameOne row per period that overlaps any interval, in time order, with
DataFramethe keys, start, end and one column per state.

spread_increments​

functionsource
spread_increments(
times: pd.Series,
increments: pd.Series,
periods: pd.DataFrame,
*,
keys: Sequence[str]
) -> pd.DataFrame

Counter increments spread over the time they were produced in.

The increment reported at reading t_i was produced during (t_{i-1}, t_i]. It is shared between the periods that interval overlaps, in proportion to the time in each (constant production rate between two readings). An increment with no preceding reading, or one between two readings at the same time, goes to the period holding its reading.

Parameters
NameTypeDescriptionDefault
timesSeriesReading times, sorted.required
incrementsSeriesIncrement per reading (aligned with times).required
periodsDataFrameNon-overlapping periods with start, end, keys.required
keysSequence[str]Period label columns.required
Returns
TypeDescription
DataFrameDataFrame with the keys and quantity (float), one row per
DataFrameperiod that received any share (zero shares included).

counter_by_period​

functionsource
counter_by_period(
times: pd.Series,
values: pd.Series,
periods: pd.DataFrame,
reading_keys: pd.DataFrame,
*,
keys: Sequence[str]
) -> pd.DataFrame

Reset-aware counter quantity and resets per period.

The reset-aware increments (:func:~ts_shape.utils.counters.counter_increments) are spread over the time they were produced in (:func:spread_increments); a reset is a point event and counts in the period of the reading that shows it. Missing readings are skipped.

Parameters
NameTypeDescriptionDefault
timesSeriesReading times of one counter, sorted.required
valuesSeriesCounter readings, aligned with times.required
periodsDataFrameNon-overlapping periods with start, end, keys.required
reading_keysDataFrameThe keys of each reading's own period, aligned with times; every such period is reported (with 0 when it received no production).required
keysSequence[str]Period label columns.required
Returns
TypeDescription
DataFrameDataFrame with the keys, quantity (float) and resets
DataFrame(int), one row per period that holds a reading or received a share,
DataFramesorted by the keys.