ts_shape.signals.identify
Find the signals that identify objects, and say what kind of object.
:func:identify_objects screens every signal of a long-format frame for
values that name a physical object or a manufacturing entity -- a serial, a
batch, a work order, a carrier, a tool, an operator badge -- and then
classifies the type of each one. The result is a separate
:class:ObjectReport; it never changes a :class:~ts_shape.signals.SignalSpec
or what :func:~ts_shape.signals.infer_spec returns.
Only the data counts as evidence: the values and how they behave over time.
The uuid, descriptions and other metadata are never read. The exceptions are
an explicit hints={uuid: object_type}, which pins the type, and optional
labels={uuid: label}, which can only veto an identifier whose name says
it is a time, a quantity or a measurement (:data:LABEL_VETOES).
Shared id semantics (the same as the id-consuming detectors and
:mod:ts_shape.eventlog.objects): a value is held until the next value; a
change starts a new item; an empty reading ("", whitespace, NaN) means
"no item".
Stage 0, clean-up
Readers misread. Before anything is measured, spellings of one value that differ only in case, blanks or leading zeros are merged; misreads -- rare values that last a sample or two and do not fit the typical values (no-read tokens, truncations, PLC defaults such as 0 or 65535) -- keep the previous reading; and a single empty sample inside a hold is a dropped reading, not "no item". The report counts the misreads in the evidence.
Stage 1, screening
Every signal is reduced to its run-length encoding and its distinct values
(O(n), one signal in memory at a time). A signal first meets the negative
roles, in this order: insufficient_data (fewer than min_samples rows,
or no non-empty reading), constant, state (booleans),
measurement (non-integral floats, or decimal numbers stored as text),
timestamp (ISO and local date formats, compact dates, epoch numbers, and
any text a date parser reads as the moment it appears), counter,
measurement (a quantized analog value, or a number that changes at nearly
every sample with no format, no holding and no circulating pool), state
(few word-like values, a small dense integer enumeration such as 1/2/3, or a
phase sequence that cycles in a fixed order within seconds), free_text
(sentences, even when they embed ids). What is left gets an
identifier_score from :data:SCREEN_WEIGHTS; at
:data:IDENTIFIER_MIN_SCORE or more the role is identifier. Shares of a
format or shape are weighed by each value's runs, so a misread cannot
outvote a small pool.
Low-cardinality codes are told from states by format (letters with
digits, fixed-width numbers, sparse or large integers are codes; words and
dense small enumerations are states) and by behaviour: a code from a pool
that is present only briefly, in no fixed order and changing with no other
id, is a fault or alarm code and becomes a state after the cross-signal
stage.
Stage 2, identification
Facts about an identifier's values (formats, :data:FACT_DESCRIPTIONS) and
its behaviour (cardinality, holds, revisits, recurrence, a circulating
tour, alternation at cycle rate, shift alignment and shift-bounded holds,
the spread of holds) add the weights of :data:TYPE_RULES to the types they
point at. Cross-signal structure adds a second round of facts:
- containment -- each presence of A lies inside one presence of B and B's changes are matched by A's (a serial in its batch);
- attributes -- A changes only when B changes (a recipe or material with
its work order, a customer with its order); whether B belongs to the
production hierarchy (it nests batches or serials) tells production
attributes from business partners -- a recurring pool on a host typed as
an order is that order's partner, the customer of a sales order or the
supplier of a purchase order (:func:
_order_partners) -- and a unique id that changes with a coarser unique id is a batch under its work order; - part clocks -- a fixed count of serials (or counter increments) between changes is a package (handling unit) or its storage location; one change per counted part is a serial.
Change times are compared within :data:COCHANGE_TOLERANCE_SECONDS plus the
polling interval of the signals, and only where chance alone would not give
the match. The best type wins when it reaches :data:TYPE_MIN_SCORE;
otherwise the type is identifier and the evidence says what was missing.
When the two best types belong to one group of :data:IDENTIFIER_TYPES and
no format cue separates them, the group is reported (order,
business_partner).
Nesting
On the types the values and the relations point at, each serial, batch and
lot gets a production parent (parent_uuid): for a serial its batch or
lot, else its order, material or recipe; for a batch or lot its material or
recipe, else its order (:data:_PARENT_RANK, :data:_QUANTITY_PARENT_RANK;
a farther level only when the data has no id of the nearest one). The
parent must nest the child both ways: the parent keeps its value during the
child's presences, and the parent's changes meet the child's starts, ends
or pauses far more often than chance would give (:data:NEST_MIN_LIFT,
:data:NEST_MAX_CHANCE_P), so an id on another line or clock is never a
parent. Each change is also placed in the window its sampling leaves open
(after the sample before it; a change a delta signal pushes between
keep-alive re-sends is exact), so a material polled every half hour still
nests its batches when those windows meet batch changes far more often than
chance (:func:_censored_lift, :func:_censored_containment). A material
that changes only once or a few times in the recording (once a day in a
continuous process) nests a batch or lot when each of its changes meets a
change of the child and all of them together are that unlikely by chance
over every pair tried (:func:_few_changes_nest); an id whose every change
falls on a shift boundary or midnight (changed by the clock) nests nothing.
A batch's
material mistyped on its own values in a short recording (a tiny pool held
for days reads as a tool, one never revisited as an order) still counts when it nests the batch both ways, and of a material
and a recipe that change together the one whose values read like a
material wins; a "serial" that holds other serials is read as their batch;
a serial whose batch is polled too coarsely to show the alignment goes into
that batch when the batch nests in another id the serial verifiably lies in
(see :func:_nest). A handling unit (or any id holding a fixed count of
parts) that nests a serial is its packing parent (packing_parent_uuid),
next to the production parent. Resources and people (tools, carriers, operators,
stations, locations, partners) and messages that name an id are never
part of a nesting.
Attribute signals
A signal of any role whose value changes only at an identifier's presence
boundaries, is constant within its presences and comes back with its
values (the customer of an order, the material of a work order, a
description text) gets attribute_of, that identifier's uuid; the
identifier's own parents are not its attributes. See
:func:_attribute_hosts. :meth:ObjectReport.to_object_specs with
attributes=True turns them into :attr:ObjectSpec.attributes <ts_shape.eventlog.ObjectSpec.attributes>, :meth:ObjectReport.hierarchy
the nesting into part_of edges, and :meth:ObjectReport.to_event_log
runs the chain into an event log.
is_delta
Many historians flag each row with is_delta: True where the machine
wrote the value, False where the value held is re-sent (delta_column
of :func:identify_objects). The flag counts only on a signal whose rows
carry both values; a signal flagged the same on every row (stored on
change, or polled) is read as without it. Then a value change at a delta
row is seen when it happened (no sampling window, :func:_seen_late), and
a delta row that repeats the value is a same-value re-setup: counted in the
evidence and a write that can put an input on a line (:func:_same_line),
while the presences the nesting compares stay value presences. A signal
set as a delta at least once, re-sent at a keep-alive cadence
(:func:_delta_setup) and changed at most :data:NEST_FEW_CHANGES times
is a held setup when its values read like ids (:func:_id_like: a
number of 6+ digits, a code with a run of 3+ digits, a known format): an
identifier even when it never changes (delta_held in
:data:SCREEN_WEIGHTS), typed on its format alone -- a prefix family or
pattern names the type (named_setup), else it is the material the
process was set up with (held_setup). A setpoint, a state word or a
version text written the same way stays a constant.
Cycles and usage links
A serial's cycle signal (cycle_uuid) is a bool whose True intervals
(a door closed, a clamp closed) each hold exactly one change of the serial
-- at least :data:CYCLE_MIN_SHARE of them, holding as many of the
changes, far above what intervals as long placed at random would give
(:func:_cycles). The ids held while a unit (a serial, a batch, a
production lot) is made are its usage links (uses): a parent of a
type of :data:USAGE_QUALIFIERS present during :data:USES_MIN_SHARE of
the unit's presences, outside its production and packing chain --
made_from (material, article, lot, batch), made_with (tool,
fixture, recipe), made_by (operator), carried_by (the carrier of a
part) and contains (a component serial scanned once in each of the
part's cycles). With units on more than one line the data must put the
parent on the unit's line (:func:_uses). See :meth:ObjectReport.uses.
Confidence: best / (best + runner_up) * min(1, best / CONFIDENT_SCORE),
with runner_up the best score outside the reported type (or group).
Extend it with :func:register_identifier_type (new types and groups, also
registered as OCEL object types) and :func:register_identifier_pattern
(site-specific formats).
| Name | Description |
|---|---|
ObjectReport | Result of :func:identify_objects. |
| Name | Description |
|---|---|
register_identifier_type | Add an object type to the vocabulary (and to the OCEL object types). |
register_identifier_pattern | Register a site-specific id format as evidence for a type. |
identify_objects | Screen every signal for object identifiers and classify their type. |
register_identifier_type
register_identifier_type(name: str, *, group: str | None = None) -> None
Add an object type to the vocabulary (and to the OCEL object types).
The new type gets no type rules of its own: give it evidence with
:func:register_identifier_pattern, or a group whose rules it shares
(a rule on a group adds to each member).
| Name | Type | Description | Default |
|---|---|---|---|
name | str | The new type, e.g. "coil". Lowercase, no ":". | required |
group | str | None | Optional group name; created when new. A group is reported instead of a member when the data cannot separate the members. | None |
| Type | Description |
|---|---|
ValueError | When name or group is empty, contains ":", or group is itself a type. |
register_identifier_pattern
register_identifier_pattern(
name: str,
regex_or_callable: str | re.Pattern[str] | Callable[[str], bool],
object_type: str,
*,
weight: float
) -> None
Register a site-specific id format as evidence for a type.
When at least :data:FORMAT_MIN_SHARE of a signal's sampled values
match, the signal counts as having a known format (screening) and
object_type gains weight. Registering a name again replaces it.
| Name | Type | Description | Default |
|---|---|---|---|
name | str | Name of the pattern, shown in the evidence. | required |
regex_or_callable | str | Pattern[str] | Callable[[str], bool] | A regular expression (the whole value must match) or a function str -> bool. | required |
object_type | str | A type or group of :data:IDENTIFIER_TYPES. | required |
weight | float | Score added to object_type (positive; 1.0 or more is a decisive format). | required |
| Type | Description |
|---|---|
ValueError | For an unknown object_type, a non-positive weight, or an empty name. |
ObjectReport
ObjectReport(
table: pd.DataFrame, type_scores: Mapping[str, Mapping[str, float]] = dict()
) -> None
Bases: Mapping[str, 'str | None']
Result of :func:identify_objects.
The report is also a read-only mapping {uuid: object_type} over every
signal, with None for the signals that are not identifiers:
report["line:a"], dict(report).
| Name | Type | Description |
|---|---|---|
table | DataFrame | One row per signal (columns :data:REPORT_COLUMNS), sorted by uuid. parent_uuid is an identifier's production parent (a serial's batch, a batch's material), packing_parent_uuid the handling unit that packs it; both None when there is none. attribute_of is the identifier whose objects a signal describes (the customer of an order), else None. cycle_uuid is a serial's cycle signal (a bool whose True intervals hold one serial each), uses (last column) the (parent_uuid, qualifier) pairs of the ids held while a unit is made (made_from, made_with, made_by, carried_by, contains; see :meth:uses). |
type_scores | Mapping[str, Mapping[str, float]] | {uuid: {object_type: score}} for every identifier, before the decision (the raw evidence sums). |
Example
>>> import pandas as pd
>>> from ts_shape.signals import identify_objects
>>> t = pd.date_range("2025-03-01", periods=300, freq="1min")
>>> df = pd.DataFrame({"systime": t, "uuid": "line:id",
... "value_string": [f"SN{100000 + i // 3}" for i in range(300)]})
>>> report = identify_objects(df)
>>> report.table[["uuid", "role", "object_type"]]
uuid role object_type
0 line:id identifier serial
| Name | Description |
|---|---|
to_frame | The per-signal table (a copy). |
identifiers | The rows whose role is identifier. |
to_object_specs | Object specs for :func:~ts_shape.eventlog.detect_objects. |
hierarchy | Signal-level part_of edges for |
uses | Usage links for :func:~ts_shape.eventlog.detect_objects |
to_event_log | The objects of the report as an OCEL 2.0 event log, in one call. |
explain | Why a signal got its role and type. |
summary | Human-readable overview: roles, then each identifier and its type. |
to_frame
to_frame() -> pd.DataFrame
The per-signal table (a copy).
identifiers
identifiers() -> pd.DataFrame
The rows whose role is identifier.
to_object_specs
to_object_specs(
min_confidence: float = 0.6,
*,
include_generic: bool = False,
namespace: bool = False,
attributes: bool = False
) -> list[ObjectSpec]
Object specs for :func:~ts_shape.eventlog.detect_objects.
| Name | Type | Description | Default |
|---|---|---|---|
min_confidence | float | Keep identifiers whose type_confidence is at least this. | 0.6 |
include_generic | bool | Also keep identifiers typed identifier (their confidence is the identifier score). | False |
namespace | bool | Render object ids as "{type}:{value}" (:attr:~ts_shape.eventlog.ObjectSpec.id_template), so the same value on two types (an order and a batch both numbered 4711) gives two object ids. | False |
attributes | bool | Fill :attr:~ts_shape.eventlog.ObjectSpec.attributes with the signals whose attribute_of is the spec's signal (the customer of an order, the material of a work order). An attribute is named by its type when it is an identifier typed with at least min_confidence, else by its uuid. Such an identifier is still its own spec when it is kept. | False |
| Name | Type | Description |
|---|---|---|
One | list [ObjectSpec ] | class:~ts_shape.eventlog.ObjectSpec per kept identifier, |
list [ObjectSpec ] | in uuid order. |
hierarchy
hierarchy(
min_confidence: float = 0.6, *, include_generic: bool = False
) -> dict[str, list[str]]
Signal-level part_of edges for
:func:~ts_shape.eventlog.detect_objects.
{child_uuid: [parent_uuid, packing_parent_uuid]} from the nesting
columns, for the signals :meth:to_object_specs keeps with the same
arguments (a parent it does not keep is left out, and so is a child
left without parents). Pass it as
detect_objects(frame, specs, hierarchy=report.hierarchy()).
| Name | Type | Description | Default |
|---|---|---|---|
min_confidence | float | As for :meth:to_object_specs. | 0.6 |
include_generic | bool | As for :meth:to_object_specs. | False |
| Type | Description |
|---|---|
dict[str, list[str]] | Child signal uuid -> its production parent, then its packing |
dict[str, list[str]] | parent, in uuid order of the children. |
uses
uses(
min_confidence: float = 0.6, *, include_generic: bool = False
) -> dict[str, dict[str, str]]
Usage links for :func:~ts_shape.eventlog.detect_objects
(uses=).
{child_uuid: {parent_uuid: qualifier}} from the uses column,
for the signals :meth:to_object_specs keeps with the same arguments
(child and parent). Qualifiers: made_from (a material, article,
lot or batch used as input), made_with (a tool, fixture, recipe
or setup), made_by (an operator), carried_by (the carrier of
a part), contains (a component serial built into a part). The
production parent stays in :meth:hierarchy (part_of).
| Name | Type | Description | Default |
|---|---|---|---|
min_confidence | float | As for :meth:to_object_specs. | 0.6 |
include_generic | bool | As for :meth:to_object_specs. | False |
| Type | Description |
|---|---|
dict[str, dict[str, str]] | Child signal uuid -> parent signal uuid -> qualifier, in uuid |
dict[str, dict[str, str]] | order. |
to_event_log
to_event_log(
dataframe: pd.DataFrame,
events: object = None,
*,
min_confidence: float = 0.6,
scope: Mapping[str, object] | None = None,
namespace: bool = True,
attributes: bool = True,
include_generic: bool = False,
detector: str | None = None,
**kwargs: Any
) -> EventLog
The objects of the report as an OCEL 2.0 event log, in one call.
Runs :meth:to_object_specs, :meth:hierarchy and :meth:uses, then
:func:~ts_shape.eventlog.detect_objects (without events) or
:func:~ts_shape.eventlog.attach_objects (with events) on
dataframe.
| Name | Type | Description | Default |
|---|---|---|---|
dataframe | DataFrame | The long-format frame the report was made from (the id and attribute signals). | required |
events | object | The events to link to the objects: an :class:~ts_shape.eventlog.EventLog, a detector frame (with detector=), {detector: frame}, or a list of these. None gives an object-only log (objects, o2o, object_changes; no events or relations). | None |
min_confidence | float | As for :meth:to_object_specs. | 0.6 |
scope | Mapping[str, object] | None | {signal_uuid: label} for :func:~ts_shape.eventlog.attach_objects: an event links only to objects of its own line or station. Needs events. | None |
namespace | bool | Object ids "{type}:{value}" (default True). | True |
attributes | bool | Capture the attribute_of signals as object attributes (default True). | True |
include_generic | bool | As for :meth:to_object_specs. | False |
detector | str | None | "ClassName.method_name" of the detector frames in events, for :func:~ts_shape.eventlog.to_event_log. | None |
**kwargs | Any | Passed to detect_objects / attach_objects (hierarchy replaces :meth:hierarchy and uses replaces :meth:uses; qualifiers, fanout_threshold, infer_o2o, uuid_column, time_column, validate). | {} |
| Type | Description |
|---|---|
EventLog | class:~ts_shape.eventlog.EventLog. |
| Type | Description |
|---|---|
ValueError | When scope is given without events, or a detector frame without detector. |
TypeError | For an events value of another kind. |
explain
explain(signal_uuid: str) -> str
Why a signal got its role and type.
| Name | Type | Description | Default |
|---|---|---|---|
signal_uuid | str | The signal to explain. | required |
| Type | Description |
|---|---|
str | A few lines of text: role, type, runner-up, the measured |
str | features and each piece of evidence. |
| Type | Description |
|---|---|
KeyError | When signal_uuid is not in the report. |
summary
summary() -> str
Human-readable overview: roles, then each identifier and its type.
identify_objects
identify_objects(
dataframe: pd.DataFrame,
*,
signal_uuids: Sequence[str] | None = None,
hints: Mapping[str, str] | None = None,
min_samples: int = 3,
shift_definitions: Mapping[str, tuple[str, str]] | None = None,
time_column: str = "systime",
uuid_column: str = "uuid",
delta_column: str | None = "is_delta",
labels: Mapping[str, str] | None = None
) -> ObjectReport
Screen every signal for object identifiers and classify their type.
Only the values and their behaviour over time are evidence; the uuid,
labels and metadata are never read. See the module docstring for the
two stages, and :data:SCREEN_WEIGHTS / :data:TYPE_RULES for the
weights.
| Name | Type | Description | Default |
|---|---|---|---|
dataframe | DataFrame | Long-format frame (systime, uuid, value_*). | required |
signal_uuids | Sequence[str] | None | Screen only these signals; unknown ones give a :class:~ts_shape.errors.DataQualityWarning. | None |
hints | Mapping[str, str] | None | {uuid: object_type} pins a signal's type (and makes it an identifier). Types must be in :data:IDENTIFIER_TYPES or a group. | None |
min_samples | int | Signals with fewer rows are insufficient_data. | 3 |
shift_definitions | Mapping[str, tuple[str, str]] | None | Shift name -> ("HH:MM", "HH:MM"), for the operator evidence (changes at shift boundaries). Defaults to :data:ts_shape.utils.shifts.DEFAULT_SHIFTS. | None |
time_column | str | Timestamp column. | 'systime' |
uuid_column | str | Signal identifier column. | 'uuid' |
delta_column | str | None | Bool column that is True on the rows the machine wrote and False on rows that re-send the held value (default "is_delta"; None, or a frame without it, ignores it). It counts on signals whose rows carry both values: a delta row starts its value when it happened (no sampling window), a delta row that repeats the value is a new setup (counted, and a write that can place an input on a line), and one id-like value set as a delta and re-sent at a keep-alive cadence is an identifier held over the recording (see is_delta in the module docstring). | 'is_delta' |
labels | Mapping[str, str] | None | Optional {uuid: label} (datapoint names). Labels never make a signal an identifier; they only veto one the values suggest when the name says otherwise (:data:LABEL_VETOES): a time or clock field (Cycletime, MINUTE, WEEKDAY), a quantity (Production Quantity, Injection counter, Gutteile) or a physical measurement is not an identifier. Without labels the result depends on the values only. | None |
| Type | Description |
|---|---|
ObjectReport | class:ObjectReport with one row per signal; parent_uuid and |
ObjectReport | packing_parent_uuid give each identifier's production and |
ObjectReport | packing parent (see Nesting in the module docstring), |
ObjectReport | cycle_uuid a serial's cycle signal and uses the ids held |
ObjectReport | while a unit is made (see Cycles and usage links). |
| Type | Description |
|---|---|
ColumnNotFoundError | When uuid_column or time_column is missing. |
ValueError | When a hint names an unknown type. |