Skip to content

Index

lambda_rules ¤

Lambda-rule subsystem — declarative, YAML-driven detectors that share all canonical-event-log plumbing with the 290 built-in detector methods.

Typical use::

from ts_shape.eventlog import register_lambda_rule, RuleSpec, TriggerSpec

spec = RuleSpec(
    id="high_torque",
    class_name="LambdaToolWear",
    method_name="high_torque",
    pack="maintenance",
    shape="point",
    archetype="threshold",
    template="maintenance.tool.high_torque",
    trigger=TriggerSpec(expression="(torque > 75) & (state == 'run')"),
    standard_attrs={
        "ts_shape:method": "lambda_threshold",
        "ts_shape:direction": "above",
        "ts_shape:threshold_high": 75.0,
    },
)
detector = register_lambda_rule(spec)
log = detector.to_event_log(df)

See :doc:/guides/lambda-rules for the full walkthrough including a threshold case and an interval-with-hysteresis case.

LambdaDetector ¤

LambdaDetector(spec: RuleSpec)

Runnable form of a :class:RuleSpec.

evaluate ¤

evaluate(dataframe: DataFrame) -> pd.DataFrame

Apply the rule to dataframe and return a detector frame.

Parameters:

Name Type Description Default
dataframe DataFrame

Input DataFrame the rule's trigger expression is evaluated on.

required

Returns:

Type Description
DataFrame

Detector frame whose layout depends on the rule's shape

DataFrame

(see :func:~ts_shape.eventlog.lambda_rules.evaluator.evaluate).

to_event_log ¤

to_event_log(
    dataframe: DataFrame,
    *,
    objects: Mapping[str, object] | None = None,
    qualifiers: Mapping[str, str] | None = None
) -> EventLog

Evaluate the rule on dataframe and normalize the result to an event log.

Parameters:

Name Type Description Default
dataframe DataFrame

Input DataFrame the rule is evaluated on.

required
objects Mapping[str, object] | None

Optional OCEL object bindings, mapping an object type to a column name, callable, Series or scalar; passed through to :func:~ts_shape.eventlog.to_event_log. None uses only the auto-extracted objects.

None
qualifiers Mapping[str, str] | None

Optional mapping of object type to the relation qualifier written for that type. None leaves qualifiers empty.

None

Returns:

Type Description
EventLog

The canonical :class:~ts_shape.eventlog.model.EventLog.

UnsafeExpression ¤

Bases: ValueError

Raised when a trigger expression contains a disallowed AST node.

RuleSpec dataclass ¤

RuleSpec(
    id: str,
    class_name: str,
    method_name: str,
    pack: str,
    shape: str,
    archetype: str,
    template: str,
    trigger: TriggerSpec,
    produces_objects: tuple[str, ...] = ("asset",),
    severity_field: str | None = None,
    value_field: str | None = None,
    standard_attrs: Mapping[str, object] = dict(),
)

A complete lambda-rule definition.

Required fields mirror the built-in REGISTRY contract — class_name is synthesized (must start with Lambda) so the rule slots into the same (class, method) -> LabelRule table as the 290 built-ins.

TriggerSpec dataclass ¤

TriggerSpec(
    expression: str,
    min_duration_s: float | None = None,
    group_by: tuple[str, ...] = (),
)

When does the rule fire?

expression is evaluated against the input DataFrame by the AST-restricted compiler in :mod:.expression. It must produce a boolean Series aligned with the input rows.

min_duration_s and group_by are only meaningful for shape="interval" rules: consecutive True rows are coalesced (per group) and the resulting interval is dropped if shorter than min_duration_s seconds.

run_backtest ¤

run_backtest(
    detector: LambdaDetector,
    dataframe: DataFrame,
    *,
    objects: Mapping[str, object] | None = None,
    qualifiers: Mapping[str, str] | None = None
) -> BacktestResult

Run detector over dataframe and summarize hit counts.

Parameters:

Name Type Description Default
detector LambdaDetector

The registered lambda rule.

required
dataframe DataFrame

Input frame the rule is evaluated on.

required
objects Mapping[str, object] | None

Object bindings passed to the event-log adapter.

None
qualifiers Mapping[str, str] | None

Relation qualifier per object type.

None

Returns:

Name Type Description
A BacktestResult

class:BacktestResult with the hit count, hits per severity and

BacktestResult

per asset, and the full event log.

compile_expression ¤

compile_expression(
    expression: str,
) -> Callable[[pd.DataFrame], pd.Series]

Compile a trigger expression to a vectorized boolean mask function.

Python's and / or / not / in, chained comparisons and min / max over columns are rejected here, with a hint to the element-wise &, |, ~ and column.isin([...]).

Parameters:

Name Type Description Default
expression str

The trigger, e.g. "(torque > 75) & (state == 'run')".

required

Returns:

Type Description
Callable[[DataFrame], Series]

A callable that takes a DataFrame and returns a boolean Series

Callable[[DataFrame], Series]

aligned with its rows (missing -> False).

Raises:

Type Description
UnsafeExpression

For disallowed or non-element-wise syntax. The callable raises :class:~ts_shape.errors.ColumnNotFoundError for a name that is not a column and ValueError when the result is not boolean.

load_dicts ¤

load_dicts(
    entries: Iterable[Mapping[str, Any]],
) -> list[LambdaDetector]

Compile and register an iterable of dict rules, all or nothing.

Every rule is validated and its trigger compiled before any is registered; if one fails, the rules registered by this call are removed again and the error is raised.

Parameters:

Name Type Description Default
entries Iterable[Mapping[str, Any]]

Rule mappings with the :class:RuleSpec fields; trigger is a mapping with expression (and optional min_duration_s, group_by -- a column name or a list of them).

required

Returns:

Name Type Description
One list[LambdaDetector]

class:LambdaDetector per rule, in input order.

Raises:

Type Description
ValueError

For a malformed rule, a duplicate registration or an expression that does not compile (:class:UnsafeExpression).

load_yaml ¤

load_yaml(path: str | Path) -> list[LambdaDetector]

Load and register every rule under a YAML file's rules: key.

YAML is imported lazily so :mod:ts_shape.eventlog does not gain a hard runtime dependency on PyYAML for users who only use built-in detectors. Install ts-shape[yaml] to enable this loader, or use :func:load_dicts with a hand-built list.

Parameters:

Name Type Description Default
path str | Path

Path to a YAML file with a top-level rules: list.

required

Returns:

Name Type Description
One list[LambdaDetector]

class:LambdaDetector per rule (see :func:load_dicts).

Raises:

Type Description
ImportError

When PyYAML is not installed.

ValueError

When the file has no rules: list or a rule is invalid.

register_lambda_rule ¤

register_lambda_rule(spec: RuleSpec) -> LambdaDetector

Register spec in REGISTRY + ARCHETYPE_BY_METHOD; return runnable detector.

The trigger expression is compiled here, so a bad expression fails at registration rather than at the first evaluation.

Parameters:

Name Type Description Default
spec RuleSpec

The rule to register.

required

Returns:

Type Description
LambdaDetector

The runnable :class:LambdaDetector.

Raises:

Type Description
ValueError

If the spec is malformed, the expression does not compile (:class:UnsafeExpression), the standard_attrs mapping uses unknown keys, the archetype's required keys are missing, or a rule with the same (class_name, method_name) is already registered.

unregister_lambda_rule ¤

unregister_lambda_rule(
    class_name: str, method_name: str
) -> None

Remove a rule previously installed by :func:register_lambda_rule.

Used by tests to keep the global REGISTRY clean between cases. No-op if the rule was not registered. Deprecated class / method names resolve to their current names, as in the registry lookup.

Parameters:

Name Type Description Default
class_name str

The rule's class name.

required
method_name str

The rule's method name.

required