Core

Core data model: SignalFrame, quality flags, stream metadata, errors, registries.

The lowest layer. It depends only on pandas, numpy, pydantic and tzlocal, and every other subpackage may import it.

SignalFrame

class flexsignal.core.SignalFrame

Values, per-sample quality flags, stream metadata and provenance.

A SignalFrame is immutable: every operation returns a new frame. The time index is always timezone-aware UTC with nanosecond resolution, sorted and unique. Values are float64; flags are a uint16 bitmask of Flag bits with the same shape as the values.

Parameters:
  • values – One float column per stream, indexed by a tz-aware DatetimeIndex.

  • flags – Flags with the same index and columns. If omitted, every NaN value is flagged MISSING and every other value is raw.

  • meta – Stream metadata keyed by stream name. Streams not listed get empty metadata.

  • history – Provenance records, oldest first (normally written by a pipeline).

Raises:

SignalDataError – If the index is not a sorted-or-sortable, unique, tz-aware DatetimeIndex, a stream is not numeric, or flags and meta don’t match the values.

__init__(values: DataFrame, flags: DataFrame | None = None, meta: Mapping[str, StreamMeta | Mapping[str, Any]] | None = None, history: Sequence[Mapping[str, Any]] = ())

Validate and store the parts (see the class docstring).

classmethod from_frame(df: DataFrame, *, units: Mapping[str, str] | None = None, meta: Mapping[str, StreamMeta | Mapping[str, Any]] | None = None, timezone: str | None = None, time_column: str | None = None) → SignalFrame

Build a SignalFrame from a plain DataFrame.

Parameters:
  • df – Values, one column per stream.

  • units – Units per stream, a shortcut for meta={name: {"units": ...}}.

  • meta – Full stream metadata per stream.

  • timezone – Time zone of a timezone-naive index (e.g. "UTC" or "America/Los_Angeles"). If it is not given, naive timestamps are taken as this machine’s local time (local_timezone()) with a NaiveTimestampWarning. Ignored if the index is already tz-aware.

  • time_column – Column to use as the time index instead of the index.

Returns:

A new SignalFrame. NaN values are flagged MISSING.

Raises:

SignalDataError – If the data can’t form a valid SignalFrame, or naive timestamps fall in a daylight-saving change.

evolve(*, values: DataFrame | None = None, flags: DataFrame | None = None, meta: Mapping[str, StreamMeta | Mapping[str, Any]] | None = None) → SignalFrame

Return a new frame with some parts replaced; history is kept.

Metadata for streams that no longer exist is dropped, and new streams get empty metadata unless meta provides it.

Parameters:
  • values – New values (default: unchanged).

  • flags – New flags (default: unchanged if values is not given; otherwise MISSING where the new values are NaN).

  • meta – New metadata (default: the current metadata, filtered).

Returns:

The new SignalFrame.

with_record(record: Mapping[str, Any]) → SignalFrame

Return a copy of this frame with one provenance record appended.

Parameters:

record – A JSON-able description of what produced the new state.

Returns:

The new SignalFrame.

property values: DataFrame

The values, one float64 column per stream (a copy-on-write copy).

property flags: DataFrame

The flags, one uint16 column per stream (a copy-on-write copy).

property meta: dict[str, StreamMeta]

Stream metadata keyed by stream name.

property history: tuple[dict[str, Any], ...]

Provenance records, oldest first.

property index: DatetimeIndex

The UTC time index.

property columns: list[str]

Stream names, in order.

property units: dict[str, str | None]

Units per stream (None when unknown).

stream(name: str) → Series

Return one stream’s values as a Series.

Raises:

SignalDataError – If the stream doesn’t exist.

select(streams: Sequence[str]) → SignalFrame

Return a frame with only the named streams, in the given order.

valid() → DataFrame

Return a boolean frame that is True where a value is present (not NaN).

has_flag(flag: Flag) → DataFrame

Return a boolean frame that is True where any bit of flag is set.

to_pandas(*, include_flags: bool = False) → DataFrame

Return the values as a plain DataFrame.

Parameters:

include_flags – Also add one <stream>__flags column per stream.

Returns:

A new DataFrame.

flag_counts() → dict[str, dict[str, Any]]

Count values and flag bits per stream.

Returns:

{stream: {"rows": n, "valid": n_valid, "flags": {FLAG_NAME: count}}}, JSON-able. Only flags that occur are listed.

describe_flags(stream: str, timestamp: Any) → list[str]

Return the flag names set on one sample.

Parameters:
  • stream – Stream name.

  • timestamp – Anything pandas.Timestamp accepts; naive means UTC.

equals(other: object) → bool

Return whether two frames have identical values, flags and metadata.

NaNs compare equal to NaNs; history is not compared.

class flexsignal.core.StreamMeta

What is known about one stream, independent of its values.

Units are kept as metadata rather than as a pandas extension dtype. Models then run on plain float64, and units are converted only at the boundaries (PLAN.md §5).

__init__(**data: Any) → None

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

classmethod __new__(*args, **kwargs)

field

type

default

description

units

str | None

None

Units as a pyomo/pint-parseable string, e.g. m^3/hr. None when unknown.

quantity_kind

str | None

None

Physical quantity, e.g. VolumeFlowRate or Pressure.

source

str | None

None

Where the stream came from: a file path or an external reference.

description

str | None

None

Free-text description.

flexsignal.core.local_timezone() → str

Return this machine’s time zone as an IANA name, e.g. "America/Los_Angeles".

Naive timestamps are taken to be in this zone. The TZ environment variable overrides it on every platform (TZ=UTC makes results the same on every machine). Falls back to "UTC" if the zone can’t be determined.

Quality flags

class flexsignal.core.Flag

Quality-flag bits; a sample’s flags are the OR of every bit that applies.

__new__(value)
__init__(*args, **kwds)

flag

bit value

meaning

set by

MISSING

1

No value: missing (NaN) in the input, or no sample existed at that time.

input data, align, resample, shift

OUT_OF_RANGE

2

The value was outside its allowed range.

range

RATE_OF_CHANGE

4

The value changed faster than physically allowed.

rate_of_change

OUTLIER

8

The value was a statistical outlier.

hampel, tukey

STUCK

16

The value was part of a flat-lined (stuck sensor) run.

stuck

MANUAL

32

A user-written rule marked the value invalid.

expression

EXCLUDED

64

Deliberately left out by a selection rule; not bad data, and never filled.

mask

CORRECTED

128

The value was corrected by a model.

calibrate (M2)

IMPUTED_SHORT

256

A short gap was filled by interpolation.

interpolate

IMPUTED_MODEL

512

A gap was filled by a model.

model imputers (M2)

FORECAST

1024

The value is a forecast, not a measurement.

forecast (M4)

DERIVED

2048

The stream was computed from other streams.

combine

RESAMPLED

4096

The value was aggregated or moved onto a new time grid.

align, resample

NO_SAMPLE

8192

The stream has no sample at this time; the row exists only because another input does. Always set with MISSING. Align, resample and interpolate skip these rows.

joining several inputs

flexsignal.core.flag_names(value: int) → list[str]

Return the names of the bits set in value, lowest bit first.

Parameters:

value – A flags bitmask.

Returns:

The flag names, e.g. ["MISSING", "RESAMPLED"]; empty for a raw value.

flexsignal.core.parse_flags(names: str | Iterable[str]) → Flag

Combine flag names into one bitmask.

Parameters:

names – A flag name such as "OUTLIER", or several names.

Returns:

The combined Flag.

Raises:

ValueError – If a name is not a flag.

Conditions

Evaluate condition expressions over a SignalFrame’s streams.

Conditions are small arithmetic and boolean expressions over stream names, for example "C == 0 and D == 0 and B > 0" or "abs(pressure - (4 + 0.01 * flow)) > 0.15". Names that aren’t Python identifiers go in backticks: `flow rate` > 5. A comparison with a missing (NaN) value is False.

A condition can only read streams, never run code. Before anything is evaluated, check_condition() parses it and accepts only:

  • stream names, numbers, True and False;

  • arithmetic + - * / // % ** (** only with a number as the exponent);

  • comparisons == != < <= > >=, and and or not & | ~;

  • the math functions in CONDITION_FUNCTIONS, e.g. abs(x).

Everything else is refused, including attribute access (x.y), indexing (x[0]), strings, keyword arguments, other function names and @ variables. So a spec from someone else can’t use a condition to reach Python internals. This check is what makes conditions safe; pandas.eval on its own is not a security boundary.

M2 adds duration and flag helpers (held(...), is_raw(...), flagged(...)) on top of this.

flexsignal.core.evaluate_condition(values: DataFrame, expression: str, *, field: str | None = None) → Series

Evaluate a boolean expression row by row.

The expression is checked with check_condition() first, so it can only read the streams in values.

Parameters:
  • values – The streams the expression may refer to, by column name.

  • expression – A condition that yields a boolean per row.

  • field – Spec field path, used in error messages.

Returns:

A boolean Series aligned to values.index. NaN results count as False.

Raises:

SignalConfigError – If the expression uses syntax that isn’t allowed, refers to an unknown stream, or doesn’t yield one boolean per row.

flexsignal.core.check_condition(expression: str, streams: Iterable[str] | None = None) → str

Check that a condition uses only the allowed syntax.

Parameters:
  • expression – The condition, e.g. "pump_on == 1 and flow > 0".

  • streams – Stream names it may refer to. If None, any name that isn’t a function is accepted (used when a spec is loaded, before the data is known).

Returns:

expression unchanged.

Raises:

ValueError – Saying what is not allowed. (evaluate_condition() and spec loading turn it into a SignalConfigError with the field.)

flexsignal.core.CONDITION_FUNCTIONS

Build an immutable unordered collection of unique elements.

Errors

exception flexsignal.core.SignalError

Base class for every error flex-signal raises.

Parameters:
  • message – What went wrong and what the user should do about it.

  • field – Dotted path of the spec field the error is about, if any.

  • value – The offending value, if useful to show.

__init__(message: str, *, field: str | None = None, value: Any = None)

Store the message, field and value (see the class docstring).

classmethod __new__(*args, **kwargs)
exception flexsignal.core.SignalConfigError

A spec, step option or argument is invalid.

__init__(message: str, *, field: str | None = None, value: Any = None)

Store the message, field and value (see the class docstring).

classmethod __new__(*args, **kwargs)
exception flexsignal.core.SignalDataError

Input data can’t be used as given (index, dtype, gaps, …).

__init__(message: str, *, field: str | None = None, value: Any = None)

Store the message, field and value (see the class docstring).

classmethod __new__(*args, **kwargs)
exception flexsignal.core.SignalBackendError

A backend key is unknown, or its optional extra is not installed.

__init__(message: str, *, field: str | None = None, value: Any = None)

Store the message, field and value (see the class docstring).

classmethod __new__(*args, **kwargs)
exception flexsignal.core.SignalWarning

Something worked, but probably not the way the user intended.

__init__(*args, **kwargs)
classmethod __new__(*args, **kwargs)
exception flexsignal.core.NaiveTimestampWarning

Timestamps had no time zone, so they were taken as this machine’s local time.

Pass timezone= to say which zone the data is in, which also silences the warning. To silence it everywhere:

warnings.filterwarnings("ignore", category=NaiveTimestampWarning)
__init__(*args, **kwargs)
classmethod __new__(*args, **kwargs)

The step registry

flexsignal.core.register_step(cls: type) → type

Register a step class under its kind; usable as a class decorator.

Parameters:

cls – A step class whose kind field has a string default.

Returns:

cls unchanged.

Raises:

SignalConfigError – If another class is already registered for the kind.

flexsignal.core.get_step_class(kind: str) → type

Return the step class registered for kind.

Raises:

SignalConfigError – If no step is registered for kind.

flexsignal.core.registered_steps() → dict[str, type]

Return every registered step class keyed by kind, sorted by kind.