Skip to main content
Version: 0.0.98

ts_shape.events.profiling.runner

Cycle time profiling of one PLC from the two inputs ts-shape loads.

The inputs are exactly what the ts-shape loaders return, without any mapping or machine context:

  1. timeseries: the raw frame of :class:~ts_shape.loader.timeseries.azure_blob_loader.AzureBlobParquetLoader (uuid, systime as Unix nanoseconds or timestamps, value_*, is_delta and whatever else the parquet files carry);
  2. metadata (optional): the datapoint table of a ts-shape metadata loader (:class:~ts_shape.loader.metadata.metadata_json_loader.MetadataJsonLoader .to_df(), indexed by uuid, or any frame with a uuid column). It supplies labels only (the OPC UA node path, else the display name, else the label); no signal role is read from it.

:func:profile_cycles runs :class:~ts_shape.CycleProfileEvents on them and returns every table plus a summary of plain numbers. From the command line::

python -m ts_shape.events.profiling --container <name> --prefix <path/> \
--start 2026-11-17T00:00Z --end 2026-11-17T23:59:59Z \
--metadata-json datapoints.json --out profile/

The Azure credentials come from --sas-url or the environment (AZURE_STORAGE_CONNECTION_STRING), as for the loader itself.

Classes
NameDescription
CycleProfileResultEvery table of one profile run and a summary of plain numbers.
Functions
NameDescription
signal_labelsuuid -> label from a metadata table (labels only, no roles).
prepare_signalsTurn a loader's raw frame into the long frame the profile reads.
signal_inventoryKind, encoding and sample period of every signal (kickoff check LL-1).
cycle_eventsEvery event placed in its cycle, with its offset from the cycle start.
recurring_eventsThe events that recur in the cycles, in their usual order.
sequence_variantsGroup the non-pause cycles by the order of their recurring events.
process_graphDirectly-follows graph of the recurring events within the cycles.
parts_per_cycleHow much every counter advances per cycle (parts per cycle).
parallel_lanesEvents that repeat at the cycle rate but are not locked to the cycle.
curve_profilesShape of every analog signal within the cycle, and cycles that deviate.
cycle_time_checkFind signals that report the cycle time themselves, and compare.
case_logThe cycles as a process-mining event log (one case per cycle).
profile_cyclesProfile the cycle time of one PLC from a loader's two outputs.
cycle_tablesEvery table of :func:profile_cycles from a prepared frame and profile.
load_azure_timeseriesRead one PLC's raw frame with the Azure loader as it is.
mainCommand line: load from Azure, profile, write the result.
benchmark_profilesScore the profile against the ground truth of simulated machines.

signal_labels​

functionsource
signal_labels(metadata: pd.DataFrame | None) -> pd.Series

uuid -> label from a metadata table (labels only, no roles).

Parameters
NameTypeDescriptionDefault
metadataDataFrame | NoneA metadata loader's table, indexed by uuid or with a uuid column; None gives no labels.required
Returns
TypeDescription
SeriesLabels indexed by uuid (text); uuids without a label are left out.
Example
>>> import pandas as pd
>>> from ts_shape.events.profiling.runner import signal_labels
>>> meta = pd.DataFrame({"uuid": ["a1", "b2"], "label": ["x", None],
... "config.nodePath": ["/Press/Counter", None]})
>>> signal_labels(meta).to_dict()
{'a1': '/Press/Counter'}

prepare_signals​

functionsource
prepare_signals(
timeseries: pd.DataFrame,
metadata: pd.DataFrame | None = None,
*,
exclude: Sequence[str] = DEFAULT_EXCLUDE
) -> pd.DataFrame

Turn a loader's raw frame into the long frame the profile reads.

systime as integer Unix nanoseconds becomes a UTC timestamp, value_bool a nullable boolean, the uuid the signal's label from metadata (unlabeled uuids stay as they are), and columns the profile does not read (sequence_number, plctime, value_bytes) are dropped. Signals whose label matches a pattern in exclude are removed.

Parameters
NameTypeDescriptionDefault
timeseriesDataFrameRaw frame of a ts-shape timeseries loader.required
metadataDataFrame | NoneOptional metadata table (see :func:signal_labels).None
excludeSequence[str]Regular expressions of signals to drop, matched case-insensitively against the label (default: personal data, :data:ts_shape.utils.personal.PERSONAL_DATA_PATTERNS -- worker, operator, Bedienpersonal, Mitarbeiter, login ...). Empty keeps every signal.DEFAULT_EXCLUDE
Returns
TypeDescription
DataFramesystime, uuid, is_delta (when present) and the
DataFramevalue_* columns, sorted by time and signal.
Example
>>> import pandas as pd
>>> from ts_shape.events.profiling.runner import prepare_signals
>>> raw = pd.DataFrame({"uuid": ["a1", "a1"],
... "systime": [1794873604342112633, 1794873616342894346],
... "value_double": [1.0, 2.0], "value_bool": [None, None],
... "plctime": [0, 0]})
>>> meta = pd.DataFrame({"uuid": ["a1"], "label": ["/Press/Temp"]})
>>> out = prepare_signals(raw, meta)
>>> out["uuid"].unique().tolist(), str(out["systime"].dt.tz)
(['/Press/Temp'], 'UTC')

signal_inventory​

functionsource
signal_inventory(frame: pd.DataFrame) -> pd.DataFrame

Kind, encoding and sample period of every signal (kickoff check LL-1).

CycleProfileResult​

classsource
CycleProfileResult(
tables: dict[str, pd.DataFrame],
summary: dict[str, Any] = dict(),
kind: str = "cycles",
) -> None

Bases: ProfileResult

Every table of one profile run and a summary of plain numbers.

Attributes
NameTypeDescription
tablesdict[str, DataFrame]signals, anchors, evaluation_window, standard_view, cycle_time_statistics, contribution_register, segment_durations, influencers, cycle_records, unusual_cycles, pauses, cycle_events (every event with its cycle and its offset from the cycle start; the input of event heatmaps), recurring_events, sequence_variants, cycle_sequences, process_graph, parts_per_cycle, parallel_lanes, curve_bands, curve_scores, curve_flagged and cycle_time_check (see the functions of the same name).
summarydict[str, Any]Plain numbers (counts, seconds, percent), JSON-able.
kindstr"cycles".

cycle_events​

functionsource
cycle_events(events: pd.DataFrame, records: pd.DataFrame) -> pd.DataFrame

Every event placed in its cycle, with its offset from the cycle start.

Parameters
NameTypeDescriptionDefault
eventsDataFrameCycleProfileEvents.signal_events().required
recordsDataFrameCycleProfileEvents.cycle_records().required
Returns
TypeDescription
DataFramecycle_uuid, cycle_class, variant, event,
DataFramesource_uuid, offset_seconds (from the cycle start) and
DataFramephase_ratio (offset / cycle duration), in time order. Events
DataFrameoutside every complete cycle are left out.
Example
>>> import ts_shape
>>> from ts_shape.events.profiling.runner import profile_cycles
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=60, seed=1)
>>> ev = profile_cycles(frame).tables["cycle_events"]
>>> bool(ev["phase_ratio"].between(0, 1, inclusive="left").all())
True

recurring_events​

functionsource
recurring_events(
events: pd.DataFrame, records: pd.DataFrame, anchor_event: str | None = None
) -> pd.DataFrame

The events that recur in the cycles, in their usual order.

An event recurs when it occurs in at least 10 % of the non-pause cycles and at most twice per cycle on average (more is a clock, a heartbeat).

Parameters
NameTypeDescriptionDefault
eventsDataFrameThe cycle_events table.required
recordsDataFrameThe cycle_records table.required
anchor_eventstr | NoneThe cycle event, left out (it is the cycle boundary).None
Returns
TypeDescription
DataFrameevent, source_uuid, presence_ratio, events_per_cycle
DataFrameand median_offset_seconds (first occurrence), ordered by the
DataFramemedian offset.
Example
>>> import ts_shape
>>> from ts_shape.events.profiling.runner import profile_cycles, recurring_events
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=80, seed=1)
>>> t = profile_cycles(frame).tables
>>> recurring_events(t["cycle_events"], t["cycle_records"], "plc:part_counter+1")["event"].iloc[0]
'plc:step=10'

sequence_variants​

functionsource
sequence_variants(
events: pd.DataFrame,
records: pd.DataFrame,
rows: list[str],
*,
resolution: float = 0.0
) -> tuple[pd.DataFrame, pd.Series]

Group the non-pause cycles by the order of their recurring events.

Parameters
NameTypeDescriptionDefault
eventsDataFrameThe cycle_events table.required
recordsDataFrameThe cycle_records table.required
rowslist[str]The recurring events (:func:recurring_events).required
resolutionfloatTime resolution; events closer than this count as simultaneous.0.0
Returns
TypeDescription
DataFrame(variants, cycle_variant). variants: sequence_rank,
Seriescycle_count, share_ratio, median_seconds,
tuple[DataFrame, Series]p90_seconds, long_count, short_count, event_count,
tuple[DataFrame, Series]signature (events joined by →), example_cycle_uuid.
tuple[DataFrame, Series]cycle_variant: the sequence rank of every non-pause cycle.

process_graph​

functionsource
process_graph(
events: pd.DataFrame,
records: pd.DataFrame,
rows: list[str],
*,
resolution: float = 0.0
) -> pd.DataFrame

Directly-follows graph of the recurring events within the cycles.

Every non-pause cycle is a case: ▶ cycle start → its recurring events in order → ■ cycle end. This is the process-mining view of the cycle (edges between steps with their frequency and time).

Returns
TypeDescription
DataFramesource, target, cycle_count, share_ratio (of the
DataFramenon-pause cycles), median_seconds and p90_seconds (time from
DataFramesource to target).

parts_per_cycle​

functionsource
parts_per_cycle(
frame: pd.DataFrame, records: pd.DataFrame, inventory: pd.DataFrame
) -> pd.DataFrame

How much every counter advances per cycle (parts per cycle).

A counter that advances by 4 in every cycle makes 4 parts per cycle (a washer basket, a multi-cavity mould). Counter resets are left out.

Parameters
NameTypeDescriptionDefault
frameDataFrameThe prepared long frame (:func:prepare_signals).required
recordsDataFrameThe cycle_records table.required
inventoryDataFrameThe signals table (:func:signal_inventory).required
Returns
TypeDescription
DataFramesignal, cycle_count, median_parts_per_cycle,
DataFramemean_parts_per_cycle (robust to polling: an update just before
DataFrameor after a boundary moves a step to the neighbouring cycle),
DataFramep10_parts_per_cycle, p90_parts_per_cycle.

parallel_lanes​

functionsource
parallel_lanes(
events: pd.DataFrame, records: pd.DataFrame, anchor_event: str | None = None
) -> pd.DataFrame

Events that repeat at the cycle rate but are not locked to the cycle.

A second press on the same controller (left/right) produces events about once per cycle at a phase that drifts through the cycle. The phase locking (mean resultant length of the event phases, 1 = always at the same point of the cycle, 0 = anywhere) separates them from the cycle's own steps.

Parameters
NameTypeDescriptionDefault
eventsDataFrameThe cycle_events table.required
recordsDataFrameThe cycle_records table.required
anchor_eventstr | NoneThe cycle event, left out.None
Returns
TypeDescription
DataFrameevent, source_uuid, events_per_cycle,
DataFramephase_locking_ratio, is_independent_lane.

curve_profiles​

functionsource
curve_profiles(
frame: pd.DataFrame,
records: pd.DataFrame,
inventory: pd.DataFrame,
*,
n_sigma: float = 3.0,
resolution: float = 0.0
) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]

Shape of every analog signal within the cycle, and cycles that deviate.

Each non-pause cycle at least as long as the window (cut-short cycles are already classified short) has its analog signal read on a fixed grid of :data:CURVE_GRID_POINTS points from the cycle start over the best demonstrated cycle time (P10), so every cycle is compared over the same span. Per signal:

  • deviation_score: how far the curve leaves the P10..P90 band of all cycles, in robust sigmas, averaged over the grid; the band may shift by :data:CURVE_SHIFT grid points (at least one resolution), so an edge that moves slightly is timing, not shape;
  • discord_score: distance to the nearest other cycle's curve, with the same shift tolerance (matrix-profile discord: a shape no other cycle shares), scaled by the median nearest-neighbour distance;
  • is_shape_anomaly: either score beyond n_sigma robust sigmas of its distribution over the cycles, above twice its median and above an absolute floor (deviation 2 sigmas on average over the window, discord 3 times the usual nearest-neighbour distance).
Parameters
NameTypeDescriptionDefault
frameDataFrameThe prepared long frame.required
recordsDataFrameThe cycle_records table.required
inventoryDataFrameThe signals table.required
n_sigmafloatRobust sigmas for a shape anomaly.3.0
resolutionfloatTime resolution (s) of polled signals; the allowed shift of a curve is at least one resolution step.0.0
Returns
TypeDescription
DataFrame(bands, scores, flagged): bands per signal and grid point
DataFrame(signal, offset_seconds, p10, median, p90);
DataFramescores per cycle and signal (cycle_uuid, signal,
tuple[DataFrame, DataFrame, DataFrame]deviation_score, discord_score, is_shape_anomaly);
tuple[DataFrame, DataFrame, DataFrame]flagged the curves of the anomalous cycles (cycle_uuid,
tuple[DataFrame, DataFrame, DataFrame]signal, offset_seconds, value).

cycle_time_check​

functionsource
cycle_time_check(
frame: pd.DataFrame, records: pd.DataFrame, inventory: pd.DataFrame
) -> pd.DataFrame

Find signals that report the cycle time themselves, and compare.

Many controllers publish the duration of the last cycle. A numeric signal whose value read right after each cycle end matches the derived cycle duration (in seconds, milliseconds or minutes) is such a signal; it is found from the data, not named. Its agreement is an independent check of the cycles the profile found.

Returns
TypeDescription
DataFrameOne row per numeric signal that matches within 10 % (median):
DataFramesignal, unit, cycle_count,
DataFramemedian_abs_difference_seconds, p95_abs_difference_seconds,
DataFramecorrelation_ratio (Pearson r, clipped at 0), sorted best first.

case_log​

functionsource
case_log(
events: pd.DataFrame, records: pd.DataFrame, rows: list[str] | None = None
) -> pd.DataFrame

The cycles as a process-mining event log (one case per cycle).

Columns follow the pm4py / XES conventions, so the frame goes straight into pm4py.discover_dfg or pm4py.discover_petri_net_inductive: case:concept:name (cycle), concept:name (event), time:timestamp (UTC), plus case:cycle_class and case:variant. rows limits the log to the recurring events.

Example
>>> import ts_shape
>>> from ts_shape.events.profiling.runner import case_log, profile_cycles
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=60, seed=1)
>>> t = profile_cycles(frame).tables
>>> tuple(case_log(t["cycle_events"], t["cycle_records"]).columns[:3])
('case:concept:name', 'concept:name', 'time:timestamp')

profile_cycles​

functionsource
profile_cycles(
timeseries: pd.DataFrame,
metadata: pd.DataFrame | None = None,
*,
exclude: Sequence[str] = DEFAULT_EXCLUDE,
top_n: int = 10,
**profile_options: Any
) -> CycleProfileResult

Profile the cycle time of one PLC from a loader's two outputs.

Parameters
NameTypeDescriptionDefault
timeseriesDataFrameRaw frame of a ts-shape timeseries loader (one PLC).required
metadataDataFrame | NoneOptional metadata table; labels only.None
excludeSequence[str]Signals to drop (see :func:prepare_signals).DEFAULT_EXCLUDE
top_nintInfluencers kept per comparison.10
**profile_optionsAnyPassed to :class:~ts_shape.CycleProfileEvents (min_cycles, n_sigma, time_resolution, ...).{}
Returns
NameTypeDescription
TheCycleProfileResultclass:CycleProfileResult.
Example
>>> import ts_shape
>>> from ts_shape.events.profiling.runner import profile_cycles
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=120, seed=1)
>>> result = profile_cycles(frame)
>>> result.summary["anchor_event"], result.summary["cycle_count"]
('plc:part_counter+1', 119)

cycle_tables​

functionsource
cycle_tables(
frame: pd.DataFrame, profile: CycleProfileEvents, *, top_n: int = 10
) -> CycleProfileResult

Every table of :func:profile_cycles from a prepared frame and profile.

Lets :func:ts_shape.events.profiling.units.profile_units reuse one computed :class:~ts_shape.CycleProfileEvents for the cycle tables and the unit profilers.

Parameters
NameTypeDescriptionDefault
frameDataFrameThe output of :func:prepare_signals.required
profileCycleProfileEventsThe cycle profile of frame.required
top_nintInfluencers kept per comparison.10
Returns
NameTypeDescription
TheCycleProfileResultclass:CycleProfileResult.

load_azure_timeseries​

functionsource
load_azure_timeseries(
loader: AzureBlobParquetLoader,
start: str | pd.Timestamp,
end: str | pd.Timestamp,
signal_uuids: Sequence[str] | None = None,
) -> pd.DataFrame

Read one PLC's raw frame with the Azure loader as it is.

Parameters
NameTypeDescriptionDefault
loaderAzureBlobParquetLoaderA configured :class:AzureBlobParquetLoader.required
startstr | TimestampStart of the range.required
endstr | TimestampEnd of the range (inclusive).required
signal_uuidsSequence[str] | NoneThe PLC's datapoint uuids (e.g. the metadata index); None reads every file in the hour folders.None

main​

functionsource
main(argv: Sequence[str] | None = None) -> int

Command line: load from Azure, profile, write the result.

benchmark_profiles​

functionsource
benchmark_profiles(
scenarios: Mapping[str, Mapping[str, Any]] | None = None,
*,
seeds: Sequence[int] = (11,),
n_cycles: int = 300
) -> pd.DataFrame

Score the profile against the ground truth of simulated machines.

Every scenario (options of :func:ts_shape.make_plc_cycles) is run for every seed, profiled with :func:profile_cycles and compared with the generator's truth. Cycles are matched by start time (within 3 s when the signals are polled).

Parameters
NameTypeDescriptionDefault
scenariosMapping[str, Mapping[str, Any]] | None{name: make_plc_cycles options}; default :data:BENCHMARK_SCENARIOS.None
seedsSequence[int]Random seeds.(11,)
n_cyclesintCycles per run.300
Returns
TypeDescription
DataFrameOne row per scenario and seed: anchor_ok, cycle_match_ratio,
DataFrameduration_mae_seconds, precision / recall of long, short
DataFrameand pause, route_ok (the alternative route is its own
DataFramesequence variant), parts_ok, lane_ok,
DataFramecycle_time_signal_ok, shape_precision_ratio,
DataFrameshape_recall_ratio.
Example
>>> from ts_shape.events.profiling.runner import benchmark_profiles
>>> b = benchmark_profiles({"base": {}}, n_cycles=120)
>>> bool(b["anchor_ok"].all()), float(b["cycle_match_ratio"].min())
(True, 1.0)