Skip to main content
Version: 0.0.98

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.

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).

Classes
NameDescription
ObjectReportResult of :func:identify_objects.
Functions
NameDescription
register_identifier_typeAdd an object type to the vocabulary (and to the OCEL object types).
register_identifier_patternRegister a site-specific id format as evidence for a type.
identify_objectsScreen every signal for object identifiers and classify their type.

register_identifier_type​

functionsource
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).

Parameters
NameTypeDescriptionDefault
namestrThe new type, e.g. "coil". Lowercase, no ":".required
groupstr | NoneOptional group name; created when new. A group is reported instead of a member when the data cannot separate the members.None
Raises
TypeDescription
ValueErrorWhen name or group is empty, contains ":", or group is itself a type.

register_identifier_pattern​

functionsource
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.

Parameters
NameTypeDescriptionDefault
namestrName of the pattern, shown in the evidence.required
regex_or_callablestr | Pattern[str] | Callable[[str], bool]A regular expression (the whole value must match) or a function str -> bool.required
object_typestrA type or group of :data:IDENTIFIER_TYPES.required
weightfloatScore added to object_type (positive; 1.0 or more is a decisive format).required
Raises
TypeDescription
ValueErrorFor an unknown object_type, a non-positive weight, or an empty name.

ObjectReport​

classsource
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).

Attributes
NameTypeDescription
tableDataFrameOne 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_scoresMapping[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
Functions
NameDescription
to_frameThe per-signal table (a copy).
identifiersThe rows whose role is identifier.
to_object_specsObject specs for :func:~ts_shape.eventlog.detect_objects.
hierarchySignal-level part_of edges for
usesUsage links for :func:~ts_shape.eventlog.detect_objects
to_event_logThe objects of the report as an OCEL 2.0 event log, in one call.
explainWhy a signal got its role and type.
summaryHuman-readable overview: roles, then each identifier and its type.

to_frame​

methodsource
to_frame() -> pd.DataFrame

The per-signal table (a copy).

identifiers​

methodsource
identifiers() -> pd.DataFrame

The rows whose role is identifier.

to_object_specs​

methodsource
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.

Parameters
NameTypeDescriptionDefault
min_confidencefloatKeep identifiers whose type_confidence is at least this.0.6
include_genericboolAlso keep identifiers typed identifier (their confidence is the identifier score).False
namespaceboolRender 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
attributesboolFill :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
Returns
NameTypeDescription
Onelist [ObjectSpec ]class:~ts_shape.eventlog.ObjectSpec per kept identifier,
list [ObjectSpec ]in uuid order.

hierarchy​

methodsource
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()).

Parameters
NameTypeDescriptionDefault
min_confidencefloatAs for :meth:to_object_specs.0.6
include_genericboolAs for :meth:to_object_specs.False
Returns
TypeDescription
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​

methodsource
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).

Parameters
NameTypeDescriptionDefault
min_confidencefloatAs for :meth:to_object_specs.0.6
include_genericboolAs for :meth:to_object_specs.False
Returns
TypeDescription
dict[str, dict[str, str]]Child signal uuid -> parent signal uuid -> qualifier, in uuid
dict[str, dict[str, str]]order.

to_event_log​

methodsource
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.

Parameters
NameTypeDescriptionDefault
dataframeDataFrameThe long-format frame the report was made from (the id and attribute signals).required
eventsobjectThe 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_confidencefloatAs for :meth:to_object_specs.0.6
scopeMapping[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
namespaceboolObject ids "{type}:{value}" (default True).True
attributesboolCapture the attribute_of signals as object attributes (default True).True
include_genericboolAs for :meth:to_object_specs.False
detectorstr | None"ClassName.method_name" of the detector frames in events, for :func:~ts_shape.eventlog.to_event_log.None
**kwargsAnyPassed to detect_objects / attach_objects (hierarchy replaces :meth:hierarchy and uses replaces :meth:uses; qualifiers, fanout_threshold, infer_o2o, uuid_column, time_column, validate).{}
Returns
TypeDescription
EventLogclass:~ts_shape.eventlog.EventLog.
Raises
TypeDescription
ValueErrorWhen scope is given without events, or a detector frame without detector.
TypeErrorFor an events value of another kind.

explain​

methodsource
explain(signal_uuid: str) -> str

Why a signal got its role and type.

Parameters
NameTypeDescriptionDefault
signal_uuidstrThe signal to explain.required
Returns
TypeDescription
strA few lines of text: role, type, runner-up, the measured
strfeatures and each piece of evidence.
Raises
TypeDescription
KeyErrorWhen signal_uuid is not in the report.

summary​

methodsource
summary() -> str

Human-readable overview: roles, then each identifier and its type.

identify_objects​

functionsource
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.

Parameters
NameTypeDescriptionDefault
dataframeDataFrameLong-format frame (systime, uuid, value_*).required
signal_uuidsSequence[str] | NoneScreen only these signals; unknown ones give a :class:~ts_shape.errors.DataQualityWarning.None
hintsMapping[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_samplesintSignals with fewer rows are insufficient_data.3
shift_definitionsMapping[str, tuple[str, str]] | NoneShift name -> ("HH:MM", "HH:MM"), for the operator evidence (changes at shift boundaries). Defaults to :data:ts_shape.utils.shifts.DEFAULT_SHIFTS.None
time_columnstrTimestamp column.'systime'
uuid_columnstrSignal identifier column.'uuid'
delta_columnstr | NoneBool 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'
labelsMapping[str, str] | NoneOptional {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
Returns
TypeDescription
ObjectReportclass:ObjectReport with one row per signal; parent_uuid and
ObjectReportpacking_parent_uuid give each identifier's production and
ObjectReportpacking parent (see Nesting in the module docstring),
ObjectReportcycle_uuid a serial's cycle signal and uses the ids held
ObjectReportwhile a unit is made (see Cycles and usage links).
Raises
TypeDescription
ColumnNotFoundErrorWhen uuid_column or time_column is missing.
ValueErrorWhen a hint names an unknown type.