Skip to content

API reference

Auto-generated from the in-code docstrings. For task-oriented help start with the User Guide; for the maths behind a method see the other Reference pages.

Loading data

mfgqc.data.QCData dataclass

Immutable wrapper over a tidy measurement frame.

Construct via :func:load. Every transform returns a NEW QCData with a :class:Step appended to a copy of the history; the original is never mutated.

frame property

frame: DataFrame

A defensive copy of the underlying tidy frame.

lineage

lineage() -> list[dict]

The provenance chain so far, as a list of step dicts (each with its running digest), reconstructable end to end.

provenance_digest

provenance_digest() -> str

SHA-256 digest pinning the full provenance chain. The history is append-only by construction (an immutable tuple of frozen steps); this digest additionally makes the recorded content verifiable. It is a content hash, not a signature (see :func:mfgqc._result.history_digest).

verify_provenance

verify_provenance(expected_digest: str) -> bool

True iff the recorded history still matches a digest captured earlier.

values

values() -> np.ndarray

Flat measure vector (capability, normality).

subgroups

subgroups() -> Subgroups

Measure grouped by subgroup/time role, in sequence order.

If no subgroup/time role is defined, falls back to subgroup_size: size 1 yields singleton subgroups (for I-MR), size k chunks consecutive rows into groups of k. Raises if neither a role nor a usable subgroup_size is available.

crossed

crossed() -> Crossed

Part x operator x replicate structure for gage R&R.

clean

clean(
    *, drop_na: bool = True, sigma_clip: float | None = None
) -> "QCData"

Return a new QCData with light cleaning applied and logged.

Parameters:

Name Type Description Default
drop_na bool

Drop rows with a missing measure value.

True
sigma_clip float or None

If given, drop rows whose measure is more than sigma_clip overall standard deviations from the overall mean (basic outlier removal).

None

spec

spec(
    lower: float | None = None,
    upper: float | None = None,
    target: float | None = None,
) -> "QCData"

Set specification limits as QCData metadata; returns a NEW QCData.

Limits live on the QCData alongside measure/units - there is no separate spec object. Omit a bound for a one-sided spec. Each call sets the limits from its arguments (omitted = absent), and never mutates the original.

Examples:

>>> data = data.spec(lower=1.0, upper=2.0, target=1.5)
>>> data = data.spec(lower=200)          # one-sided
>>> sweep = [data.spec(lower=1.0, upper=u).capability() for u in candidates]

spec_from

spec_from(other: 'QCData') -> 'QCData'

Copy spec limits (lower/upper/target) from another QCData; returns a NEW QCData.

Plain-Python reuse for a 'named standard' without a bespoke class: wall = dict(lower=1.0, upper=2.0, target=1.5); data.spec(**wall) also works.

roles

roles(**mapping: str) -> 'QCData'

Bind role names to columns as metadata; returns a NEW QCData.

Flattened lowercase kwargs (no nested dict), parallel to :meth:spec. Known roles: part, operator, replicate, subgroup, time, quality, size. Bindings merge with any already set (e.g. a subgroup= from load).

Examples:

>>> data = data.roles(part='part', operator='operator', replicate='trial')

capability

capability(
    method: str = "normal", *, alpha: float = 0.05
) -> "CapabilityResult"

Process-capability analysis. See :func:mfgqc.capability.compute.

control_chart

control_chart(
    kind: str | None = None,
    rules: str = "nelson",
    n: "str | int | None" = None,
) -> "ControlChartResult"

Control-chart analysis. See :func:mfgqc.control_charts.compute.

n (attribute charts) is a sample-size column name, a constant int, or None (falls back to a size role, else 1).

gage_rr

gage_rr(
    method: str = "anova", *, alpha: float = 0.1
) -> "GageRRResult"

Gage R&R (MSA) analysis. See :func:mfgqc.gage_rr.compute.

bias_study

bias_study(reference: float, *, alpha: float = 0.05)

MSA bias study vs a known reference. See :func:mfgqc.msa.bias.

linearity_study

linearity_study(reference, *, alpha: float = 0.05)

MSA linearity study. reference is a column name or a {group: ref} mapping. See :func:mfgqc.msa.linearity.

stability_study

stability_study(
    *, kind: str | None = None, rules: str = "nelson"
)

MSA stability study (control chart over time). See :func:mfgqc.msa.stability.

regress

regress(
    on,
    *,
    select=None,
    criterion: str = "aic",
    model=None,
    start=None
)

OLS regression of the measure on on.

select ('forward'/'backward'/'stepwise') runs automated model selection by criterion ('aic'/'bic'/'p'); model (a callable) with start runs non-linear least squares instead. See :mod:mfgqc.regression_ext.

logistic

logistic(on)

Binary logistic regression of the measure on on. See :func:mfgqc.regression_ext.logistic.

transform

transform(method: str = 'boxcox')

Return a NEW QCData with the measure Box-Cox transformed; the fitted lambda and its CI are logged in the provenance. The transform is explicit and opt-in - mfgQC never transforms silently inside another analysis.

anova

anova(factors, interaction: bool = True)

One-/two-way ANOVA of the measure across factors (list of 1-2 column names).

interaction (two-way only): fit the interaction term (default) or pool it into error for an additive model.

life_fit

life_fit(
    dist: str = "weibull",
    method: str = "mle",
    *,
    conf: float = 0.95
)

Fit a life distribution with censoring (event role: 1=failure, 0=suspension). See :func:mfgqc.reliability.life_fit.

life_table

life_table(*, conf: float = 0.95)

Kaplan-Meier nonparametric R(t). See :func:mfgqc.reliability.kaplan_meier.

mtbf

mtbf(kind: str = 'time_terminated', conf: float = 0.9)

Constant-rate MTBF with chi-square bounds. See :func:mfgqc.reliability.mtbf.

timeseries

timeseries(*, lags: int = 20)

Exploratory time-series screen: trend (linear + Mann-Kendall) and autocorrelation (ACF), surfaced as flags. See :func:mfgqc.timeseries.compute_timeseries.

multivari

multivari(factors)

Multi-vari study decomposing variation into positional / cyclical / temporal families across the nested factors. See :func:mfgqc.multivari.compute.

precontrol

precontrol()

Pre-control (stoplight) against the attached spec limits. See :func:mfgqc.precontrol.compute.

short_run_chart

short_run_chart(
    by: str, target=None, *, rules: str = "nelson"
)

Standardized short-run control chart pooling part numbers via by. See :func:mfgqc.control_charts.compute_short_run.

attribute_capability

attribute_capability(
    defect: str | None = None,
    opportunities: int | None = None,
    kind: str | None = None,
)

Attributes capability (DPMO, yields, process sigma) from a defect or pass/fail column. defect defaults to the measure; kind is inferred (binary column -> defectives, counts -> defects). See :func:mfgqc.process_sigma.

attribute_agreement

attribute_agreement(
    rating: str,
    part: str,
    appraiser: str,
    reference=None,
    *,
    trial: str | None = None,
    ordinal: bool = False
)

Attribute MSA / kappa: within-, between-, and vs-reference agreement. See :func:mfgqc.attribute_agreement.compute.

doe

doe(
    design=None,
    factors=None,
    order=None,
    reduce: bool = False,
)

Analyze a two-level designed experiment on the measure.

Pass either design= (a :class:mfgqc.doe.Design, which also supplies the alias structure) or factors= (an external coded matrix). See :func:mfgqc.doe.doe.

ewma_chart

ewma_chart(
    lam: float = 0.1,
    L: float = 2.7,
    *,
    mu0: float | None = None,
    sigma: float | None = None
)

EWMA control chart. See :func:mfgqc.timeseries_charts.compute_ewma.

mu0/sigma default to the sample mean (or spec target) and MR-bar/d2; pass known phase-I values to use them directly.

cusum_chart

cusum_chart(
    k: float = 0.5,
    h: float = 5,
    *,
    mu0: float | None = None,
    sigma: float | None = None
)

Tabular two-sided CUSUM chart. See :func:mfgqc.timeseries_charts.compute_cusum.

mu0/sigma default as in :meth:ewma_chart; pass known phase-I values to use them directly.

test_mean

test_mean(target: float, **kwargs)

One-sample test of the measure mean vs target.

test_means

test_means(by: str | None = None, **kwargs)

Two-sample test of the measure split by a dimension (must yield 2 groups).

by defaults to the group role when omitted.

test_anova

test_anova(by: str | None = None, **kwargs)

One-way ANOVA of the measure split by a dimension (defaults to the group role).

test_variance

test_variance(by: str | None = None, **kwargs)

Variance comparison of the measure split by a dimension (defaults to the group role).

The result surface

Every analysis returns a frozen result that mixes in QCResult. These methods are available on every result object.

mfgqc._result.QCResult

Mixin providing the report and view behaviour shared by all results.

Subclasses are expected to be frozen dataclasses that define at least assumptions and history fields, plus implement _title, _summary_lines, _render_standalone and _render_axes.

report

report() -> str

Return the full text report: numbers, assumptions, recommendations.

summary

summary() -> dict[str, Any]

Return a FLAT, JSON-serializable dict of the result's scalar fields.

This base implementation auto-flattens the public scalar fields of the result dataclass (skipping arrays, nested structures, assumptions and history). Many result types override it with a curated key set; both the override and this fallback are guaranteed json.dumps-able. For the full structured form (arrays, CI tuples, assumption flags, provenance) use :meth:to_dict.

to_dict

to_dict() -> dict[str, Any]

Return the full structured, JSON-serializable form of the result.

Includes every public field (arrays and CI tuples as lists), the flat :meth:summary, the assumption checks, the provenance history, and the provenance_digest that pins that history. This is the canonical payload for a report builder or a wire transfer; callers must not parse :meth:report text.

lineage

lineage() -> list[dict[str, Any]]

The provenance chain that produced this result, as a list of step dicts (each with its running digest), reconstructable end to end.

provenance_digest

provenance_digest() -> str

SHA-256 digest pinning the full provenance chain (see :func:history_digest for the guarantee and its limit).

verify_provenance

verify_provenance(expected_digest: str) -> bool

True iff the recorded history still matches a digest captured earlier.

view

view(
    ax: "Axes | None" = None,
    kind: str | None = None,
    *,
    save: str | None = None,
    dpi: int = 150,
    **kwargs: Any
)

Render the analysis.

Parameters:

Name Type Description Default
ax matplotlib Axes or None

If None, a new Figure is created and returned (the canonical, possibly multi-panel chart). If an Axes is given, the analysis draws its primary panel into it and returns that Axes (enables composition).

None
kind str or None

None selects the canonical chart for the analysis; a string selects an explicit alternative view.

None
save str or None

If given (only when ax is None), write the figure to this path before returning it. The format is taken from the extension, so "chart.png" and "chart.svg" both work. The Figure is still returned so the caller can also embed it as bytes.

None
dpi int

Resolution for raster output when save is a raster format.

150

Returns:

Type Description
Figure or Axes
Notes

Rendering is headless-safe: it never calls plt.show and detaches the Figure from pyplot's registry, so it works under the Agg backend on a server with no display.

Assumption checks

mfgqc.assumptions.AssumptionCheck dataclass

Binary assumption verdict with practical-impact and reliability context.

Attributes:

Name Type Description
name, test str

What was checked and the direct test used.

statistic float

Test statistic.

p_value float or None

P-value of the direct test where defined.

passed bool

BINARY verdict from the direct test at alpha. The context fields below NEVER change this.

magnitude float or None

Effect-size / practical-impact CONTEXT (e.g. variance ratio, Cpk impact).

magnitude_label str or None

e.g. "variance ratio", "est. Cpk impact", "lag-1 autocorr".

reliability str

"ok" / "low_power" / "oversensitive" - a fact about the test's resolving power at this n, not a judgment about the data.

n int
recommendation str or None

Next step, populated when passed is False.

The analysis catalog

A frontend or report builder discovers every analysis and its required inputs from this catalog.

mfgqc.registry

Machine-readable catalog of mfgQC analyses and what each one needs.

A frontend builds its menu from this catalog instead of hard-coding the method list (which would drift out of sync as the package grows). ANALYSES is a tuple of :class:Analysis records; :func:list_analyses returns the same thing as a list of JSON-serializable dicts.

Requirement tokens (the requires field) use a small fixed vocabulary so a UI can map them to prompts. They line up with :attr:mfgqc.errors.MissingPrerequisiteError.missing:

  • "measure" -- a numeric measure column (set via load(measure=...))
  • "spec" -- at least one spec limit (.spec(lower=/upper=))
  • "spec:both" -- both spec limits
  • "subgroup" -- a subgroup/time role or a subgroup_size
  • "role:NAME" -- a specific role (e.g. "role:part")
  • "factors" -- one or more categorical factor columns (a call argument)
  • "predictors" -- one or more predictor columns (a call argument)
  • "reference" -- a known reference value (a call argument)
  • "params" -- scalar inputs passed directly (no table needed)
  • "data" -- raw sample arrays passed directly

ANALYSES module-attribute

ANALYSES: tuple[Analysis, ...] = _FLUENT + _FUNCTION

The full catalog of analyses, ordered fluent-first then parameter-driven.

Analysis dataclass

One catalog entry describing an analysis and its inputs.

name instance-attribute
name: str

Short identifier, e.g. "capability".

call instance-attribute
call: str

How it is invoked, e.g. "QCData.capability" or "mfgqc.process_sigma".

kind instance-attribute
kind: str

"fluent" (a :class:~mfgqc.QCData method) or "function" (module-level).

requires instance-attribute
requires: tuple[str, ...]

Required input tokens (see the module docstring vocabulary).

params instance-attribute
params: tuple[str, ...]

Names of the tunable call arguments (knobs) the analysis accepts.

result_type instance-attribute
result_type: str

The result class name returned (whose .summary()/.view() to render).

description instance-attribute
description: str

One-line human description for the menu.

list_analyses

list_analyses() -> list[dict]

Return the catalog as a list of JSON-serializable dicts (for a UI).

Errors

mfgqc.errors

Public exception types for mfgQC.

A thin frontend (or any caller) needs to distinguish "you asked for an analysis but did not supply what it needs" from a genuine programming error, so it can prompt the user for the missing input instead of crashing.

MissingPrerequisiteError is the catchable signal for that case. It subclasses both :class:PyQCError (so callers can catch every mfgQC-specific error with one clause) and the built-in :class:ValueError (so existing code that catches ValueError keeps working unchanged -- raising it is not a breaking change).

PyQCError

Bases: Exception

Base class for all mfgQC-specific exceptions.

MissingPrerequisiteError

Bases: PyQCError, ValueError

An analysis was requested without an input it requires.

Examples: capability without a spec limit, gage R&R without the part/ operator/replicate roles, a p-chart without subgroup sizes.

Attributes:

Name Type Description
analysis str or None

The analysis that was requested (e.g. "capability").

missing tuple of str

Machine-readable tokens for what is missing (e.g. ("spec",) or ("role:part", "role:operator")), so a UI can prompt for exactly those inputs.