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:
- What must be optimized first to shorten the cycle time? --
:meth:
~CycleProfileEvents.contribution_registerranks the segments of the learned standard cycle by their potential (median - best demonstrated). - 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):
- every signal becomes discrete events, by the kind
:func:
ts_shape.signals.infer.infer_specinfers 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<); - 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; - 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);
- per variant, every cycle is classified robustly on its log duration:
pause,long,shortornormal; - 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.
| Name | Description |
|---|---|
CycleProfileEvents | Production: mapping-free cycle time profiling of one PLC. |
CycleProfileEvents
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')
| Name | Description |
|---|---|
signal_events | The discrete events every signal was turned into (LL-1). |
cycle_anchor_candidates | Rank the events that could mark the cycle (the anchor). |
evaluation_window | Data readiness: are there enough coherent cycles per variant? |
standard_view | The learned standard sequence of a cycle, per variant. |
segment_durations | Every cycle split into the segments of its standard view. |
contribution_register | What to optimize first, and what varies, per variant and segment. |
cycle_time_statistics | Robust cycle time statistics and class counts per variant. |
detect_cycle_influencers | The signals that separate long and short cycles from normal ones. |
cycle_records | One record per cycle; every field carries the same timestamp. |
detect_unusual_cycles | The long and short cycle records, for alerts and the event log. |
units | The classified cycles: one row per complete cycle. |
events_frame | Every discrete event of every signal (see :meth:signal_events). |
signal_specs | The inferred :class:~ts_shape.signals.spec.SignalSpec per signal. |
variant_limits | Classification limits per variant (lower, upper, pause, median seconds). |
cycle_anchor | (event label, source uuid) of the cycle anchor, or None. |
variant_signal | The uuid of the signal that defines the product variant, or None. |
resolution_seconds | Seconds within which events cannot be ordered (as in :meth:evaluation_window). |
evaluation_reason | The reason of the all row of :meth:evaluation_window. |
| Name | Type | Description | Default |
|---|---|---|---|
dataframe | DataFrame | Long-format signals of one PLC (systime, uuid, value_*). | required |
signal_uuids | list[str] | None | Signals to use; None (default) uses every signal of the frame. | None |
anchor_uuid | str | None | Signal whose best-ranked event cuts the cycles; the default None discovers the anchor (US-1). | None |
min_duration | str | float | None | Optional 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_duration | str | float | None | Optional plausibility bound: a longer cycle is a pause (DQ-4). | None |
min_cycles | int | Non-pause cycles a variant needs to be evaluable (DQ-3; default 50). | 50 |
presence_ratio | float | Share of the non-pause cycles in which an event must occur exactly once to join the standard view. | 0.9 |
n_sigma | float | Robust z-score of log(duration) beyond which a cycle is long or short. | 3.0 |
pause_factor | float | A cycle of at least this many times the variant's median duration is a pause (DQ-2). | 3.0 |
time_resolution | str | float | None | How 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_levels | int | str | How 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_column | str | Timestamp column. | 'systime' |
uuid_column | str | Signal identifier column. | 'uuid' |
event_uuid | str | uuid of the point and interval outputs. | 'prod:cycle_profile' |
| Type | Description |
|---|---|
ValueError | If a numeric parameter is out of range. |
signal_events
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.
| Type | Description |
|---|---|
DataFrame | Point events: systime, uuid (event_uuid), |
DataFrame | source_uuid (the signal), event (the label) and |
DataFrame | signal_kind (bool, state, text, counter or |
DataFrame | continuous). |
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
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
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;is_counter: a part counter is the natural cycle boundary;interval_cv_factor: robust coefficient of variation of the intervals (median absolute deviation / median), ascending;- 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.
| Type | Description |
|---|---|
DataFrame | Static table: rank, event, source_uuid, |
DataFrame | signal_kind, event_count, support_count, |
DataFrame | is_counter, median_interval_seconds, |
DataFrame | interval_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
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.
| Type | Description |
|---|---|
DataFrame | Summary, one row per variant plus all: start, end, |
DataFrame | duration_seconds (the cycles covered), variant, |
DataFrame | cycle_count (non-pause), pause_count, |
DataFrame | longest_coherent_cycle_count, evaluable, reason |
DataFrame | (ok, too_few_cycles: optimize organizationally first or |
DataFrame | no_cycle_anchor), anchor_event, anchor_uuid, |
DataFrame | variant_uuid and time_resolution_seconds (events closer |
DataFrame | than this are not ordered; see time_resolution). Without an anchor, one all row covers the |
DataFrame | data. |
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
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).
| Type | Description |
|---|---|
DataFrame | Static table: variant, position, milestone (events |
DataFrame | within time_resolution of each other share one; segments run |
DataFrame | between milestones), event, source_uuid, |
DataFrame | presence_ratio, median_phase_ratio, |
DataFrame | median_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
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.
| Name | Type | Description |
|---|---|---|
Intervals | DataFrame | start, end, duration_seconds, uuid, |
DataFrame | source_uuid (the anchor signal), cycle_uuid, variant, | |
DataFrame | cycle_class, position, segment, from_event, | |
DataFrame | to_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
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;skewnessand Sarle'sbimodality_coefficient(is_bimodalabove 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 itspotential_rankwithin 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).
| Type | Description |
|---|---|
DataFrame | Static table, one row per variant and segment, with the columns |
DataFrame | above plus variant, position, segment, |
DataFrame | from_event, to_event, cycle_count and |
DataFrame | deviation_cycle_count (cycles left out for a sequence |
DataFrame | deviation). |
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
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.
| Type | Description |
|---|---|
DataFrame | Static table, one row per variant: variant, cycle_count |
DataFrame | (all classes), normal_count, long_count, short_count, |
DataFrame | pause_count, median_seconds, p10_seconds, |
DataFrame | p90_seconds, mad_seconds, mean_seconds, |
DataFrame | std_seconds, min_seconds, max_seconds, |
DataFrame | target_seconds (P10), potential_seconds (median - P10), |
DataFrame | lower_limit_seconds / upper_limit_seconds (short / long |
DataFrame | bounds) 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
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.
| Name | Type | Description | Default |
|---|---|---|---|
top_n | int | Features kept per comparison. | 10 |
| Type | Description |
|---|---|
DataFrame | Static table: comparison, rank, feature, |
DataFrame | source_uuid, feature_kind, importance_ratio, |
DataFrame | auc_ratio, direction, group_median, |
DataFrame | normal_median, group_cycle_count, normal_cycle_count, |
DataFrame | p_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
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.
| Type | Description |
|---|---|
DataFrame | Point events, one per complete cycle including pauses: |
DataFrame | systime, uuid, source_uuid (anchor signal), |
DataFrame | cycle_uuid, start_ns, end_ns (Unix nanoseconds, UTC |
DataFrame | for tz-aware input), duration_seconds, cycle_class, |
DataFrame | variant, median_seconds (variant median), |
DataFrame | deviation_seconds (duration - median), sequence_deviation, |
DataFrame | dominant_segment, dominant_segment_seconds, |
DataFrame | dominant_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
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).
| Type | Description |
|---|---|
DataFrame | The rows of :meth:cycle_records with cycle_class long |
DataFrame | or short, plus direction (above / below the |
DataFrame | robust 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
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.
| Type | Description |
|---|---|
DataFrame | A copy of the cycle table (empty without a cycle anchor). |
events_frame
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.
| Type | Description |
|---|---|
DataFrame | A copy of the event table. |
signal_specs
signal_specs() -> dict[str, Any]
The inferred :class:~ts_shape.signals.spec.SignalSpec per signal.
| Type | Description |
|---|---|
dict[str, Any] | {uuid: SignalSpec} (a copy of the mapping). |
variant_limits
variant_limits() -> dict[str, dict[str, float]]
Classification limits per variant (lower, upper, pause, median seconds).
| Type | Description |
|---|---|
dict[str, dict[str, float]] | {variant: {...}} (empty without cycles). |
cycle_anchor
cycle_anchor() -> tuple[str, str] | None
(event label, source uuid) of the cycle anchor, or None.
variant_signal
variant_signal() -> str | None
The uuid of the signal that defines the product variant, or None.
resolution_seconds
resolution_seconds() -> float
Seconds within which events cannot be ordered (as in :meth:evaluation_window).
evaluation_reason
evaluation_reason() -> str
The reason of the all row of :meth:evaluation_window.