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:
timeseries: the raw frame of :class:~ts_shape.loader.timeseries.azure_blob_loader.AzureBlobParquetLoader(uuid,systimeas Unix nanoseconds or timestamps,value_*,is_deltaand whatever else the parquet files carry);metadata(optional): the datapoint table of a ts-shape metadata loader (:class:~ts_shape.loader.metadata.metadata_json_loader.MetadataJsonLoader.to_df(), indexed byuuid, or any frame with auuidcolumn). 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.
| Name | Description |
|---|---|
CycleProfileResult | Every table of one profile run and a summary of plain numbers. |
| Name | Description |
|---|---|
signal_labels | uuid -> label from a metadata table (labels only, no roles). |
prepare_signals | Turn a loader's raw frame into the long frame the profile reads. |
signal_inventory | Kind, encoding and sample period of every signal (kickoff check LL-1). |
cycle_events | Every event placed in its cycle, with its offset from the cycle start. |
recurring_events | The events that recur in the cycles, in their usual order. |
sequence_variants | Group the non-pause cycles by the order of their recurring events. |
process_graph | Directly-follows graph of the recurring events within the cycles. |
parts_per_cycle | How much every counter advances per cycle (parts per cycle). |
parallel_lanes | Events that repeat at the cycle rate but are not locked to the cycle. |
curve_profiles | Shape of every analog signal within the cycle, and cycles that deviate. |
cycle_time_check | Find signals that report the cycle time themselves, and compare. |
case_log | The cycles as a process-mining event log (one case per cycle). |
profile_cycles | Profile the cycle time of one PLC from a loader's two outputs. |
cycle_tables | Every table of :func:profile_cycles from a prepared frame and profile. |
load_azure_timeseries | Read one PLC's raw frame with the Azure loader as it is. |
main | Command line: load from Azure, profile, write the result. |
benchmark_profiles | Score the profile against the ground truth of simulated machines. |
signal_labels
signal_labels(metadata: pd.DataFrame | None) -> pd.Series
uuid -> label from a metadata table (labels only, no roles).
| Name | Type | Description | Default |
|---|---|---|---|
metadata | DataFrame | None | A metadata loader's table, indexed by uuid or with a uuid column; None gives no labels. | required |
| Type | Description |
|---|---|
Series | Labels 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
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.
| Name | Type | Description | Default |
|---|---|---|---|
timeseries | DataFrame | Raw frame of a ts-shape timeseries loader. | required |
metadata | DataFrame | None | Optional metadata table (see :func:signal_labels). | None |
exclude | Sequence[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 |
| Type | Description |
|---|---|
DataFrame | systime, uuid, is_delta (when present) and the |
DataFrame | value_* 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
signal_inventory(frame: pd.DataFrame) -> pd.DataFrame
Kind, encoding and sample period of every signal (kickoff check LL-1).
CycleProfileResult
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.
| Name | Type | Description |
|---|---|---|
tables | dict[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). |
summary | dict[str, Any] | Plain numbers (counts, seconds, percent), JSON-able. |
kind | str | "cycles". |
cycle_events
cycle_events(events: pd.DataFrame, records: pd.DataFrame) -> pd.DataFrame
Every event placed in its cycle, with its offset from the cycle start.
| Name | Type | Description | Default |
|---|---|---|---|
events | DataFrame | CycleProfileEvents.signal_events(). | required |
records | DataFrame | CycleProfileEvents.cycle_records(). | required |
| Type | Description |
|---|---|
DataFrame | cycle_uuid, cycle_class, variant, event, |
DataFrame | source_uuid, offset_seconds (from the cycle start) and |
DataFrame | phase_ratio (offset / cycle duration), in time order. Events |
DataFrame | outside 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
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).
| Name | Type | Description | Default |
|---|---|---|---|
events | DataFrame | The cycle_events table. | required |
records | DataFrame | The cycle_records table. | required |
anchor_event | str | None | The cycle event, left out (it is the cycle boundary). | None |
| Type | Description |
|---|---|
DataFrame | event, source_uuid, presence_ratio, events_per_cycle |
DataFrame | and median_offset_seconds (first occurrence), ordered by the |
DataFrame | median 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
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.
| Name | Type | Description | Default |
|---|---|---|---|
events | DataFrame | The cycle_events table. | required |
records | DataFrame | The cycle_records table. | required |
rows | list[str] | The recurring events (:func:recurring_events). | required |
resolution | float | Time resolution; events closer than this count as simultaneous. | 0.0 |
| Type | Description |
|---|---|
DataFrame | (variants, cycle_variant). variants: sequence_rank, |
Series | cycle_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
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).
| Type | Description |
|---|---|
DataFrame | source, target, cycle_count, share_ratio (of the |
DataFrame | non-pause cycles), median_seconds and p90_seconds (time from |
DataFrame | source to target). |
parts_per_cycle
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.
| Name | Type | Description | Default |
|---|---|---|---|
frame | DataFrame | The prepared long frame (:func:prepare_signals). | required |
records | DataFrame | The cycle_records table. | required |
inventory | DataFrame | The signals table (:func:signal_inventory). | required |
| Type | Description |
|---|---|
DataFrame | signal, cycle_count, median_parts_per_cycle, |
DataFrame | mean_parts_per_cycle (robust to polling: an update just before |
DataFrame | or after a boundary moves a step to the neighbouring cycle), |
DataFrame | p10_parts_per_cycle, p90_parts_per_cycle. |
parallel_lanes
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.
| Name | Type | Description | Default |
|---|---|---|---|
events | DataFrame | The cycle_events table. | required |
records | DataFrame | The cycle_records table. | required |
anchor_event | str | None | The cycle event, left out. | None |
| Type | Description |
|---|---|
DataFrame | event, source_uuid, events_per_cycle, |
DataFrame | phase_locking_ratio, is_independent_lane. |
curve_profiles
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_SHIFTgrid points (at least oneresolution), 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 beyondn_sigmarobust 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).
| Name | Type | Description | Default |
|---|---|---|---|
frame | DataFrame | The prepared long frame. | required |
records | DataFrame | The cycle_records table. | required |
inventory | DataFrame | The signals table. | required |
n_sigma | float | Robust sigmas for a shape anomaly. | 3.0 |
resolution | float | Time resolution (s) of polled signals; the allowed shift of a curve is at least one resolution step. | 0.0 |
| Type | Description |
|---|---|
DataFrame | (bands, scores, flagged): bands per signal and grid point |
DataFrame | (signal, offset_seconds, p10, median, p90); |
DataFrame | scores 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
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.
| Type | Description |
|---|---|
DataFrame | One row per numeric signal that matches within 10 % (median): |
DataFrame | signal, unit, cycle_count, |
DataFrame | median_abs_difference_seconds, p95_abs_difference_seconds, |
DataFrame | correlation_ratio (Pearson r, clipped at 0), sorted best first. |
case_log
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
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.
| Name | Type | Description | Default |
|---|---|---|---|
timeseries | DataFrame | Raw frame of a ts-shape timeseries loader (one PLC). | required |
metadata | DataFrame | None | Optional metadata table; labels only. | None |
exclude | Sequence[str] | Signals to drop (see :func:prepare_signals). | DEFAULT_EXCLUDE |
top_n | int | Influencers kept per comparison. | 10 |
**profile_options | Any | Passed to :class:~ts_shape.CycleProfileEvents (min_cycles, n_sigma, time_resolution, ...). | {} |
| Name | Type | Description |
|---|---|---|
The | CycleProfileResult | class: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
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.
| Name | Type | Description | Default |
|---|---|---|---|
frame | DataFrame | The output of :func:prepare_signals. | required |
profile | CycleProfileEvents | The cycle profile of frame. | required |
top_n | int | Influencers kept per comparison. | 10 |
| Name | Type | Description |
|---|---|---|
The | CycleProfileResult | class:CycleProfileResult. |
load_azure_timeseries
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.
| Name | Type | Description | Default |
|---|---|---|---|
loader | AzureBlobParquetLoader | A configured :class:AzureBlobParquetLoader. | required |
start | str | Timestamp | Start of the range. | required |
end | str | Timestamp | End of the range (inclusive). | required |
signal_uuids | Sequence[str] | None | The PLC's datapoint uuids (e.g. the metadata index); None reads every file in the hour folders. | None |
main
main(argv: Sequence[str] | None = None) -> int
Command line: load from Azure, profile, write the result.
benchmark_profiles
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).
| Name | Type | Description | Default |
|---|---|---|---|
scenarios | Mapping[str, Mapping[str, Any]] | None | {name: make_plc_cycles options}; default :data:BENCHMARK_SCENARIOS. | None |
seeds | Sequence[int] | Random seeds. | (11,) |
n_cycles | int | Cycles per run. | 300 |
| Type | Description |
|---|---|
DataFrame | One row per scenario and seed: anchor_ok, cycle_match_ratio, |
DataFrame | duration_mae_seconds, precision / recall of long, short |
DataFrame | and pause, route_ok (the alternative route is its own |
DataFrame | sequence variant), parts_ok, lane_ok, |
DataFrame | cycle_time_signal_ok, shape_precision_ratio, |
DataFrame | shape_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)