Skip to main content
Version: 0.0.98

ts_shape.events.quality.tolerance_deviation

Classes
NameDescription
ToleranceDeviationEventsInherits from Base and processes DataFrame data for specific events, comparing tolerance and actual values.

ToleranceDeviationEvents​

classsource
ToleranceDeviationEvents(
dataframe: pd.DataFrame,
value_column_tolerance: str,
value_column_actual: str,
tolerance_uuid: str | None = None,
actual_uuid: str | None = None,
event_uuid: str | None = None,
compare_func: Callable[[pd.Series, pd.Series], pd.Series] = operator.ge,
time_threshold: str = "5min",
upper_tolerance_uuid: str | None = None,
lower_tolerance_uuid: str | None = None,
warning_threshold: float = 0.8,
tolerance_lag: str = "0s",
) -> None

Bases: Base

Inherits from Base and processes DataFrame data for specific events, comparing tolerance and actual values.

Enhanced features:

  • Upper and lower tolerances (two-sided, or one-sided with only one of them)
  • Warning zones with configurable thresholds
  • Deviation magnitude tracking (absolute and percentage)
  • Severity level classification (minor, major, critical)
  • Process capability indices (Cp, Cpk, Pp, Ppk)
  • Time-lagged tolerance application
Example
>>> import pandas as pd, ts_shape
>>> act = ts_shape.make_timeseries(["act"], n_points=60, n_outliers=3)
>>> limits = pd.DataFrame({"systime": act["systime"].min(), "uuid": ["usl", "lsl"],
... "value_double": [103.0, 97.0]})
>>> tde = ts_shape.ToleranceDeviationEvents(
... pd.concat([limits, act]), "value_double", "value_double", actual_uuid="act",
... upper_tolerance_uuid="usl", lower_tolerance_uuid="lsl")
>>> out = tde.detect_deviations()
>>> out[["systime", "value_double", "severity"]].round({"value_double": 1})
systime value_double severity
4 2025-01-01 00:02:00 110.0 major
33 2025-01-01 00:16:30 111.2 major
49 2025-01-01 00:24:30 112.1 major
Functions
NameDescription
detect_deviationsProcesses DataFrame to apply tolerance checks, group events by time, and generate an events DataFrame.
capability_indicesCalculate process capability indices (Cp, Cpk, Pp, Ppk and Cpm).
Parameters
NameTypeDescriptionDefault
dataframeDataFrameInput DataFrame with measurement datarequired
value_column_tolerancestrColumn name containing tolerance values (formerly tolerance_column)required
value_column_actualstrColumn name containing actual measurement values (formerly actual_column)required
tolerance_uuidstr | NoneDeprecated (removed in the next major release; passing it without upper_tolerance_uuid/lower_tolerance_uuid emits a DeprecationWarning). UUID of a single tolerance signal that is compared with the actual values through compare_func. Use upper_tolerance_uuid and/or lower_tolerance_uuid instead: a single upper limit is upper_tolerance_uuid alone.None
actual_uuidstr | NoneUUID for actual measurements. Required: a ValueError is raised when it is missing.None
event_uuidstr | NoneUUID for generated events (default None)None
compare_funcCallable[[Series, Series], Series]Comparison used by the deprecated single tolerance_uuid path only (default: operator.ge, so actual >= tolerance is a deviation).ge
time_thresholdstrTime window for grouping events (default: '5min')'5min'
upper_tolerance_uuidstr | NoneUUID for the upper tolerance limit. Given alone, it is a one-sided upper limit.None
lower_tolerance_uuidstr | NoneUUID for the lower tolerance limit. Given alone, it is a one-sided lower limit.None
warning_thresholdfloatThreshold ratio for warning zone (default: 0.8 = 80% of tolerance)0.8
tolerance_lagstrTime lag for tolerance application (default: '0s')'0s'

detect_deviations​

methodsource
detect_deviations() -> pd.DataFrame

Processes DataFrame to apply tolerance checks, group events by time, and generate an events DataFrame.

Enhanced with:

  • Upper/lower tolerances (two-sided or one-sided)
  • Deviation magnitude tracking (absolute and percentage)
  • Warning zones
  • Severity level classification
  • Time-lagged tolerance application

Out-of-tolerance samples of the actual signal closer than time_threshold form one event, reported as its first and last row; an event of a single sample is reported as that one row.

Every row of a limit signal sets the limit from its time on, whatever its is_delta flag (a snapshot limit is a valid limit; the column is not needed). With tolerance_lag a limit set at t takes effect at t + tolerance_lag (the previous limit stays in force until then); events keep the measured times.

deviation_abs is the distance beyond the violated limit (0 inside the band). Severity compares it with the tolerance range R (upper - lower; the magnitude of the single limit when one-sided): minor when deviation_abs <= warning_threshold * R, critical when deviation_abs > 2 * R, major in between. With limits [0, 10] a value of 11 is minor, 19 is major and 31 is critical.

Returns
NameTypeDescription
DataFramepd.DataFrame: A DataFrame of processed and grouped event data with enhanced metrics.
ColumnsDataFramesystime, uuid (the event uuid), source_uuid (the actual
DataFramemeasurement signal's uuid), the value columns (value_column_actual
DataFrameholds the measured value), is_delta, deviation_abs,
DataFramedeviation_pct and severity.

capability_indices​

methodsource
capability_indices(
target_value: float | None = None,
*,
as_frame: bool = True,
sigma_method: SigmaMethod = "moving_range"
) -> pd.DataFrame | dict[str, float]

Calculate process capability indices (Cp, Cpk, Pp, Ppk and Cpm).

Process capability indices measure how well a process meets specification limits (AIAG SPC manual; Montgomery, Introduction to Statistical Quality Control, section 8.3):

  • Cp = (USL - LSL) / 6σ_within: potential capability assuming perfect centering
  • Cpk = min(USL - mean, mean - LSL) / 3σ_within: accounts for centering
  • Pp / Ppk: the same formulas with the overall σ
  • Cpm (only when target_value is given): the Taguchi index (USL - LSL) / 6 sqrt(σ² + (mean - T)²) = Pp / sqrt(1 + ((mean - T) / σ)²) with the overall σ, which penalizes distance from the target T

The overall σ (std) is the sample standard deviation (ddof=1) of all actual measurements. The within (short-term) σ (std_within) is, with the default sigma_method="moving_range", the individuals-chart estimate MR-bar / 1.128 from consecutive measurements in time order; with sigma_method="std" it is the overall σ, so Cp/Cpk equal Pp/Ppk (the behavior before October 2026).

With a one-sided spec (only an upper or only a lower limit) Cp/Pp are NaN and Cpk/Ppk are the one-sided index (CPU or CPL); the missing limit is reported as NaN.

Without any row of the actual signal the result is the empty frame (with the full schema) and a :class:~ts_shape.errors.DataQualityWarning; the deprecated dict form still raises ValueError.

Measurements without spread (constant values, a single measurement or only missing values) give NaN indices and a :class:~ts_shape.errors.DataQualityWarning, as in :class:CapabilityTrendingEvents.

Parameters
NameTypeDescriptionDefault
target_valuefloat | NoneTarget/nominal value for the process. If None, the midpoint of the tolerances (or the single limit of a one-sided spec) is reported as target and no Cpm is computed.None
sigma_methodSigmaMethodWithin σ for Cp/Cpk: "moving_range" (default, MR-bar / 1.128) or "std" (the overall σ).'moving_range'
as_frameboolWhen True (default), return a one-row DataFrame (see below). as_frame=False returns the dictionary form; it is deprecated, emits a DeprecationWarning and will be removed in the next major release.True
Returns
TypeDescription
DataFrame | dict[str, float]With as_frame=True (default), a one-row summary DataFrame with
DataFrame | dict[str, float]columns start, end, duration_seconds (first to last actual
DataFrame | dict[str, float]measurement), uuid (event uuid), source_uuid (actual uuid), Cp,
DataFrame | dict[str, float]Cpk, Pp, Ppk, Cpm (always present; NaN unless target_value
DataFrame | dict[str, float]is given), mean, std (overall σ), std_within (the σ behind Cp /
DataFrame | dict[str, float]Cpk), usl, lsl, target, and sample_count (the
DataFrame | dict[str, float]number of measurements the indices are computed from).
DataFrame | dict[str, float]Canonical twin columns: cp, cpk, pp, ppk and
DataFrame | dict[str, float]cpm, each right after its upper-case column; each holds the same values as the deprecated column
DataFrame | dict[str, float]right before it, which is removed in the next major release.
DataFrame | dict[str, float]With as_frame=False (deprecated), a dictionary containing: - 'Cp': Process capability - 'Cpk': Process capability index - 'Pp': Process performance - 'Ppk': Process performance index - 'Cpm': Taguchi capability index; only present when target_value is given (NaN for a one-sided spec) - 'mean': Process mean - 'std': Overall process standard deviation - 'std_within': Within σ used for Cp / Cpk - 'usl': Upper specification limit - 'lsl': Lower specification limit - 'target': Target value used
Note
  • Values > 1.33 are generally considered acceptable
  • Values > 1.67 are considered good