Skip to main content
Version: Next

ts_shape.events.profiling.cycles

Mapping-free cycle time profiling of one PLC.

:class:CycleProfileEvents takes the raw long-format signals of one machine controller and answers, without any configuration of signal roles:

  1. What must be optimized first to shorten the cycle time? -- :meth:~CycleProfileEvents.contribution_register ranks the segments of the learned standard cycle by their potential (median - best demonstrated).
  2. What is unstable within a cycle, and how is the variation distributed? -- the same register reports each segment's spread, skew, bimodality and share of the cycle time variance.

The pipeline (computed once, on first use, and cached):

  1. every signal becomes discrete events, by the kind :func:ts_shape.signals.infer.infer_spec infers for it: edges of a boolean (uuid↑, uuid↓), entry into a state value (uuid=v), a counter increment (uuid+1), or a hysteresis crossing of an analog level (uuid>, uuid<);
  2. the cycle anchor is the event that repeats in step with the most other signals (a heartbeat repeats regularly but alone, so it never wins); the cycles are cut at it with :class:~ts_shape.features.cycles.CycleExtractor;
  3. a product variant is a rarely changing text or state signal that explains the cycle time (eta squared of the log duration of at least 0.2);
  4. per variant, every cycle is classified robustly on its log duration: pause, long, short or normal;
  5. the standard view of a variant is the events that occur exactly once in almost every cycle, ordered by their median phase; consecutive events of it split each cycle into segments that add up to the cycle time.

Signal names are used for labels only. Spec IDs in the method docstrings (US-1 ...) refer to the cycle time profiling requirements, see docs/modules/production/cycle-profiling.md.

Classes
NameDescription
CycleProfileEventsProduction: mapping-free cycle time profiling of one PLC.

CycleProfileEvents​

classsource
CycleProfileEvents(
dataframe: pd.DataFrame,
*,
signal_uuids: list[str] | None = None,
anchor_uuid: str | None = None,
min_duration: str | float | None = None,
max_duration: str | float | None = None,
min_cycles: int = 50,
presence_ratio: float = 0.9,
n_sigma: float = 3.0,
pause_factor: float = 3.0,
time_resolution: str | float | None = None,
analog_levels: int | str = 2,
time_column: str = "systime",
uuid_column: str = "uuid",
event_uuid: str = "prod:cycle_profile"
) -> None

Bases: Base

Production: mapping-free cycle time profiling of one PLC.

Give it every signal of one machine controller. It finds the cycle by itself, learns the standard sequence of a cycle, splits each cycle into segments and reports what limits and what destabilizes the cycle time -- per product variant, without a role mapping or master data.

Methods:

  • signal_events: The discrete events every signal was turned into.
  • cycle_anchor_candidates: Ranking of the events that could cut cycles.
  • evaluation_window: Data readiness per variant (enough coherent cycles?).
  • standard_view: The learned standard sequence of a cycle per variant.
  • segment_durations: Each cycle split into segments (they add up to it).
  • contribution_register: Per segment: potential, spread, skew, bimodality, variance contribution.
  • cycle_time_statistics: Robust statistics and class counts per variant.
  • detect_cycle_influencers: Features that separate long / short cycles from normal ones.
  • cycle_records: One record per cycle, every field at the same timestamp.
  • detect_unusual_cycles: The long and short cycle records.
  • units: The classified cycles (for unit profilers).
  • events_frame: Every discrete event (for unit profilers).
  • signal_specs: Inferred spec per signal.
  • variant_limits: Classification limits per variant.
  • cycle_anchor: The anchor event and its signal.
  • variant_signal: The variant signal.
  • resolution_seconds: Time resolution of the cycle view.
  • evaluation_reason: Reason of the all-variants row.
Example
>>> import ts_shape
>>> frame, truth = ts_shape.make_plc_cycles(n_cycles=120, seed=1)
>>> profile = ts_shape.CycleProfileEvents(frame)
>>> profile.cycle_anchor_candidates().loc[0, "event"]
'plc:part_counter+1'
>>> register = profile.contribution_register()
>>> top = register.sort_values("potential_rank").iloc[0]
>>> top["variant"], top["segment"]
('A', 'plc:step=60 → plc:step=70')
Functions
NameDescription
signal_eventsThe discrete events every signal was turned into (LL-1).
cycle_anchor_candidatesRank the events that could mark the cycle (the anchor).
evaluation_windowData readiness: are there enough coherent cycles per variant?
standard_viewThe learned standard sequence of a cycle, per variant.
segment_durationsEvery cycle split into the segments of its standard view.
contribution_registerWhat to optimize first, and what varies, per variant and segment.
cycle_time_statisticsRobust cycle time statistics and class counts per variant.
detect_cycle_influencersThe signals that separate long and short cycles from normal ones.
cycle_recordsOne record per cycle; every field carries the same timestamp.
detect_unusual_cyclesThe long and short cycle records, for alerts and the event log.
unitsThe classified cycles: one row per complete cycle.
events_frameEvery discrete event of every signal (see :meth:signal_events).
signal_specsThe inferred :class:~ts_shape.signals.spec.SignalSpec per signal.
variant_limitsClassification limits per variant (lower, upper, pause, median seconds).
cycle_anchor(event label, source uuid) of the cycle anchor, or None.
variant_signalThe uuid of the signal that defines the product variant, or None.
resolution_secondsSeconds within which events cannot be ordered (as in :meth:evaluation_window).
evaluation_reasonThe reason of the all row of :meth:evaluation_window.
Parameters
NameTypeDescriptionDefault
dataframeDataFrameLong-format signals of one PLC (systime, uuid, value_*).required
signal_uuidslist[str] | NoneSignals to use; None (default) uses every signal of the frame.None
anchor_uuidstr | NoneSignal whose best-ranked event cuts the cycles; the default None discovers the anchor (US-1).None
min_durationstr | float | NoneOptional plausibility bound (offset string or seconds): a shorter cycle is short whatever its z-score. Cycle limits are derived from the data; this only adds to them (DQ-4).None
max_durationstr | float | NoneOptional plausibility bound: a longer cycle is a pause (DQ-4).None
min_cyclesintNon-pause cycles a variant needs to be evaluable (DQ-3; default 50).50
presence_ratiofloatShare of the non-pause cycles in which an event must occur exactly once to join the standard view.0.9
n_sigmafloatRobust z-score of log(duration) beyond which a cycle is long or short.3.0
pause_factorfloatA cycle of at least this many times the variant's median duration is a pause (DQ-2).3.0
time_resolutionstr | float | NoneHow far apart (offset string or seconds) two events must be to be told apart. Polled signals (an OPC UA client reading every 10 s) put events of one poll in random order; standard-view events closer than this become one milestone that counts at its earliest event. The default None uses the median sample period of the view's sampled signals (0 for change-encoded signals).None
analog_levelsint | strHow an analog signal becomes events. 2 (default): one hysteresis band between 40 % and 60 % of its P10..P90 range (uuid>, uuid<). An integer from 3 or "auto": the signal's operating levels are learned (1-D k-means; "auto" picks 2 to 4 levels by the drop of the within-level spread) and entering a level is an event (uuid≈<level>), with hysteresis of a quarter of the gap to the neighbouring level.2
time_columnstrTimestamp column.'systime'
uuid_columnstrSignal identifier column.'uuid'
event_uuidstruuid of the point and interval outputs.'prod:cycle_profile'
Raises
TypeDescription
ValueErrorIf a numeric parameter is out of range.

signal_events​

methodsource
signal_events() -> pd.DataFrame

The discrete events every signal was turned into (LL-1).

Implements: LL-1 (the kind of a signal decides its events; analog values that are really codes or counters are treated as such).

A boolean gives its edges (uuid↑, uuid↓), a text or integer state its entries into a value (uuid=v), a counter its increments (uuid+1) and an analog level its crossings of a hysteresis band between 40 % and 60 % of its P10..P90 range (uuid>, uuid<). The first sample of a signal gives no event.

Returns
TypeDescription
DataFramePoint events: systime, uuid (event_uuid),
DataFramesource_uuid (the signal), event (the label) and
DataFramesignal_kind (bool, state, text, counter or
DataFramecontinuous).
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=60, seed=1)
>>> events = ts_shape.CycleProfileEvents(frame).signal_events()
>>> events.groupby("signal_kind")["event"].nunique().to_dict()
{'bool': 10, 'continuous': 2, 'counter': 1, 'state': 8, 'text': 1}

cycle_anchor_candidates​

methodsource
cycle_anchor_candidates() -> pd.DataFrame

Rank the events that could mark the cycle (the anchor).

Implements: US-1 (find the unknown cycle signal from raw data only), DQ-1 (one start event; its recurrence is the end).

Every event that occurs at least three times is ranked by coverage first: only events whose regular intervals (gaps of at most three times their median) cover at least half as much of the recording as the best candidate compete (coverage_ratio); then

  1. support_count: the number of other signals with an event that repeats 0.8 to 1.5 times per candidate event and is phase-locked to it (its events fall at the same point of the candidate's intervals, mean resultant length >= 0.7) -- a cycle event repeats in step with the rest of the machine; a heartbeat repeats too often and an independent machine on the same controller drifts;
  2. is_counter: a part counter is the natural cycle boundary;
  3. interval_cv_factor: robust coefficient of variation of the intervals (median absolute deviation / median), ascending;
  4. the event label (a deterministic tie-break).

The first row is the anchor unless anchor_uuid names a signal, then the best-ranked event of that signal is.

Returns
TypeDescription
DataFrameStatic table: rank, event, source_uuid,
DataFramesignal_kind, event_count, support_count,
DataFrameis_counter, median_interval_seconds,
DataFrameinterval_cv_factor, coverage_ratio, is_anchor.
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=60, seed=1)
>>> table = ts_shape.CycleProfileEvents(frame).cycle_anchor_candidates()
>>> table[["event", "support_count", "is_anchor"]].head(2)
event support_count is_anchor
0 plc:part_counter+1 5 True
1 plc:pressure< 5 False
>>> table.loc[table["event"] == "plc:heartbeat↑", "support_count"].item()
0

evaluation_window​

methodsource
evaluation_window() -> pd.DataFrame

Data readiness: are there enough coherent cycles per variant?

Implements: DQ-3 (50-100 coherent cycles, otherwise optimize organizationally first; cycles may be stitched together).

Pauses break a run of coherent cycles; the non-pause cycles are stitched together, so cycle_count counts all of them and longest_coherent_cycle_count the longest uninterrupted run.

Returns
TypeDescription
DataFrameSummary, one row per variant plus all: start, end,
DataFrameduration_seconds (the cycles covered), variant,
DataFramecycle_count (non-pause), pause_count,
DataFramelongest_coherent_cycle_count, evaluable, reason
DataFrame(ok, too_few_cycles: optimize organizationally first or
DataFrameno_cycle_anchor), anchor_event, anchor_uuid,
DataFramevariant_uuid and time_resolution_seconds (events closer
DataFramethan this are not ordered; see time_resolution). Without an anchor, one all row covers the
DataFramedata.
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=120, seed=1)
>>> window = ts_shape.CycleProfileEvents(frame).evaluation_window()
>>> window[["variant", "cycle_count", "evaluable", "reason"]]
variant cycle_count evaluable reason
0 all 118 True ok
1 A 59 True ok
2 B 59 True ok

standard_view​

methodsource
standard_view() -> pd.DataFrame

The learned standard sequence of a cycle, per variant.

Implements: the "Standard View on every PLC" use case (learned, not configured).

An event joins the view when it occurs exactly once in at least presence_ratio of a variant's non-pause cycles; the view is ordered by the median phase (0 at the anchor, 1 at the next one).

Returns
TypeDescription
DataFrameStatic table: variant, position, milestone (events
DataFramewithin time_resolution of each other share one; segments run
DataFramebetween milestones), event, source_uuid,
DataFramepresence_ratio, median_phase_ratio,
DataFramemedian_offset_seconds, cycle_count.
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=120, seed=1)
>>> view = ts_shape.CycleProfileEvents(frame).standard_view()
>>> view.loc[view["variant"] == "A", "event"].head(4).tolist()
['plc:step=10', 'plc:step=20', 'plc:clamp_closed↑', 'plc:pressure>']

segment_durations​

methodsource
segment_durations() -> pd.DataFrame

Every cycle split into the segments of its standard view.

Implements: event pairing ("which pair of events has the longest time between them") for consecutive events of the standard view.

A cycle's segments run from the anchor to the first view event, between consecutive view events and from the last to the next anchor, so they add up exactly to the cycle duration. A cycle in which a view event is missing or out of order is a sequence deviation and has no segments (see sequence_deviation in :meth:cycle_records). Each view event counts at its first occurrence in the cycle; repeats (a re-inspection) stay inside their segment.

Returns
NameTypeDescription
IntervalsDataFramestart, end, duration_seconds, uuid,
DataFramesource_uuid (the anchor signal), cycle_uuid, variant,
DataFramecycle_class, position, segment, from_event,
DataFrameto_event.
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=60, seed=1)
>>> profile = ts_shape.CycleProfileEvents(frame)
>>> seg = profile.segment_durations()
>>> total = seg.groupby("cycle_uuid")["duration_seconds"].sum()
>>> rec = profile.cycle_records().set_index("cycle_uuid")
>>> bool(((total - rec.loc[total.index, "duration_seconds"]).abs() < 1e-6).all())
True

contribution_register​

methodsource
contribution_register() -> pd.DataFrame

What to optimize first, and what varies, per variant and segment.

Implements: Contribution Register and Schwankungsbreiten (spread) from the use-case notes; US-2 (statistical, transferable KPIs).

On the non-pause cycles of a variant without a sequence deviation:

  • median_seconds, p10_seconds, p90_seconds, spread_seconds (P90 - P10), mad_seconds (median absolute deviation), mean_seconds, std_seconds;
  • skewness and Sarle's bimodality_coefficient (is_bimodal above 5/9 and a spread of more than two time-resolution steps: the segment has two typical durations);
  • median_share_ratio: the segment's share of the summed medians;
  • potential_seconds = median - P10, the time the segment loses against its own best demonstrated performance, and its potential_rank within the variant (question 1: what first);
  • variance_contribution_factor = Cov(segment, cycle) / Var(cycle): the segment's share of the cycle time variance. The shares add up to exactly 1; a negative share compensates other segments (question 2: what is unstable).
Returns
TypeDescription
DataFrameStatic table, one row per variant and segment, with the columns
DataFrameabove plus variant, position, segment,
DataFramefrom_event, to_event, cycle_count and
DataFramedeviation_cycle_count (cycles left out for a sequence
DataFramedeviation).
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=120, seed=1)
>>> reg = ts_shape.CycleProfileEvents(frame).contribution_register()
>>> reg.groupby("variant")["variance_contribution_factor"].sum().round(6).to_dict()
{'A': 1.0, 'B': 1.0}

cycle_time_statistics​

methodsource
cycle_time_statistics() -> pd.DataFrame

Robust cycle time statistics and class counts per variant.

Implements: US-2 (short and long cycles found statistically, KPIs transferable across plants), VIZ-1 (target from the data: the best demonstrated cycle time, P10, instead of a master-data target).

A cycle is a pause at pause_factor times the median or more (or above max_duration); otherwise long / short beyond n_sigma robust sigmas of log(duration) (median and scaled median absolute deviation; floor 1 %, and at least one sample period of a polled cycle signal relative to the median), or below min_duration; else normal. Statistics other than the counts leave pauses out.

Returns
TypeDescription
DataFrameStatic table, one row per variant: variant, cycle_count
DataFrame(all classes), normal_count, long_count, short_count,
DataFramepause_count, median_seconds, p10_seconds,
DataFramep90_seconds, mad_seconds, mean_seconds,
DataFramestd_seconds, min_seconds, max_seconds,
DataFrametarget_seconds (P10), potential_seconds (median - P10),
DataFramelower_limit_seconds / upper_limit_seconds (short / long
DataFramebounds) and pause_threshold_seconds.
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=120, seed=1)
>>> st = ts_shape.CycleProfileEvents(frame).cycle_time_statistics()
>>> st[["variant", "long_count", "short_count", "pause_count"]]
variant long_count short_count pause_count
0 A 1 3 0
1 B 1 1 1

detect_cycle_influencers​

methodsource
detect_cycle_influencers(*, top_n: int = 10) -> pd.DataFrame

The signals that separate long and short cycles from normal ones.

Implements: US-3 (state information that explains why a cycle was long or short), OUT-1 (top-10 influencers with uuid, label and importance, as the earlier Cycle Analyser published them).

Features per cycle: the count of every event (event_count), the mean and maximum of every analog signal (mean, max) and the state of every boolean at the cycle start (start_state). For long_vs_normal and short_vs_normal each feature is scored by the Mann-Whitney AUC of the group against the normal cycles: importance_ratio = |AUC - 0.5| x 2 (0: no separation, 1: complete), direction says whether the group is higher or lower. Each comparison needs at least two cycles on both sides. p_value is the two-sided Mann-Whitney p-value, q_value the Benjamini-Hochberg adjusted value over every feature tested in the comparison, and is_significant is q_value < 0.05.

Analog means and maxima are taken over the same window in every cycle (from the cycle start for the variant's best demonstrated cycle time, P10), so a longer cycle does not lower its mean just by waiting longer.

Parameters
NameTypeDescriptionDefault
top_nintFeatures kept per comparison.10
Returns
TypeDescription
DataFrameStatic table: comparison, rank, feature,
DataFramesource_uuid, feature_kind, importance_ratio,
DataFrameauc_ratio, direction, group_median,
DataFramenormal_median, group_cycle_count, normal_cycle_count,
DataFramep_value, q_value, is_significant.
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=200, seed=3)
>>> inf = ts_shape.CycleProfileEvents(frame).detect_cycle_influencers(top_n=3)
>>> inf.loc[inf["comparison"] == "long_vs_normal", "feature"].tolist()
['event_count:plc:camera_done↑', 'event_count:plc:camera_done↓', 'event_count:plc:camera_nok↑']

cycle_records​

methodsource
cycle_records() -> pd.DataFrame

One record per cycle; every field carries the same timestamp.

Implements: OUT-1 (all outputs of a cycle share one timestamp, so they can be matched and charted, e.g. in Grafana), DQ-2 (pauses are kept, as their own class, not dropped).

systime is the cycle end. dominant_segment is the segment that exceeded its variant median by the most seconds in this cycle (dominant_excess_seconds), i.e. where the cycle lost its time; it is empty for a cycle with a sequence deviation.

Returns
TypeDescription
DataFramePoint events, one per complete cycle including pauses:
DataFramesystime, uuid, source_uuid (anchor signal),
DataFramecycle_uuid, start_ns, end_ns (Unix nanoseconds, UTC
DataFramefor tz-aware input), duration_seconds, cycle_class,
DataFramevariant, median_seconds (variant median),
DataFramedeviation_seconds (duration - median), sequence_deviation,
DataFramedominant_segment, dominant_segment_seconds,
DataFramedominant_excess_seconds, anchor_event.
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=120, seed=1)
>>> rec = ts_shape.CycleProfileEvents(frame).cycle_records()
>>> rec["cycle_class"].value_counts().sort_index().to_dict()
{'long': 2, 'normal': 112, 'pause': 1, 'short': 4}

detect_unusual_cycles​

methodsource
detect_unusual_cycles() -> pd.DataFrame

The long and short cycle records, for alerts and the event log.

Implements: US-2 (short and long cycles detected statistically and handed to staff for investigation).

Returns
TypeDescription
DataFrameThe rows of :meth:cycle_records with cycle_class long
DataFrameor short, plus direction (above / below the
DataFramerobust band).
Example
>>> import ts_shape
>>> frame, _ = ts_shape.make_plc_cycles(n_cycles=120, seed=1)
>>> unusual = ts_shape.CycleProfileEvents(frame).detect_unusual_cycles()
>>> sorted(unusual["cycle_class"].unique())
['long', 'short']

units​

methodsource
units() -> pd.DataFrame

The classified cycles: one row per complete cycle.

Columns: cycle_uuid, start_ns, end_ns, duration_seconds, variant, cycle_class (pause / long / short / normal) and z (robust z of the log duration). Used by the unit profilers (stops, changeovers, start-ups, orders ...) to cut their own units from the cycles.

Returns
TypeDescription
DataFrameA copy of the cycle table (empty without a cycle anchor).

events_frame​

methodsource
events_frame() -> pd.DataFrame

Every discrete event of every signal (see :meth:signal_events).

Columns: systime, source_uuid, event, signal_kind, ns (integer nanoseconds), sorted by time.

Returns
TypeDescription
DataFrameA copy of the event table.

signal_specs​

methodsource
signal_specs() -> dict[str, Any]

The inferred :class:~ts_shape.signals.spec.SignalSpec per signal.

Returns
TypeDescription
dict[str, Any]{uuid: SignalSpec} (a copy of the mapping).

variant_limits​

methodsource
variant_limits() -> dict[str, dict[str, float]]

Classification limits per variant (lower, upper, pause, median seconds).

Returns
TypeDescription
dict[str, dict[str, float]]{variant: {...}} (empty without cycles).

cycle_anchor​

methodsource
cycle_anchor() -> tuple[str, str] | None

(event label, source uuid) of the cycle anchor, or None.

variant_signal​

methodsource
variant_signal() -> str | None

The uuid of the signal that defines the product variant, or None.

resolution_seconds​

methodsource
resolution_seconds() -> float

Seconds within which events cannot be ordered (as in :meth:evaluation_window).

evaluation_reason​

methodsource
evaluation_reason() -> str

The reason of the all row of :meth:evaluation_window.