Metadata-Version: 2.4
Name: labqc
Version: 1.4.0
Summary: Laboratory quality calculations: GUM uncertainty budgets, method validation, proficiency-test scores, Westgard rules and flue-gas emission conversions
Author: Mantas Valantinavičius
License-Expression: MIT
Project-URL: Homepage, https://github.com/mantas123456/lab-quality-toolkit
Project-URL: Documentation, https://mantas123456.github.io/lab-quality-toolkit/
Project-URL: Source, https://github.com/mantas123456/lab-quality-toolkit
Project-URL: Issues, https://github.com/mantas123456/lab-quality-toolkit/issues
Project-URL: Changelog, https://github.com/mantas123456/lab-quality-toolkit/blob/main/CHANGELOG.md
Keywords: metrology,uncertainty,GUM,ISO 17025,quality control,Westgard,method validation,proficiency testing,emissions
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Scientific/Engineering :: Chemistry
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.26
Requires-Dist: pandas>=2.1
Requires-Dist: scipy>=1.11
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: matplotlib>=3.8; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=6; extra == "dev"
Provides-Extra: reports
Requires-Dist: reportlab>=4.0; extra == "reports"
Requires-Dist: openpyxl>=3.1; extra == "reports"
Provides-Extra: app
Requires-Dist: streamlit>=1.67; extra == "app"
Requires-Dist: plotly>=5.24; extra == "app"
Provides-Extra: docs
Requires-Dist: mkdocs<2,>=1.6; extra == "docs"
Requires-Dist: mkdocs-material>=9.5; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.26; extra == "docs"
Dynamic: license-file

# labqc: laboratory quality calculations in Python

[![CI](https://github.com/mantas123456/lab-quality-toolkit/actions/workflows/ci.yml/badge.svg)](https://github.com/mantas123456/lab-quality-toolkit/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/labqc)](https://pypi.org/project/labqc/)
[![Docs](https://img.shields.io/badge/docs-online-blue)](https://mantas123456.github.io/lab-quality-toolkit/)
[![Open in Streamlit](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app)

**Try it in the browser:** [the labqc web app](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app) runs every module with example data,
no installation needed. A second copy, [labqc in your browser](https://mantas123456.github.io/lab-quality-toolkit/app/), runs Python inside the
browser itself (stlite): it never sleeps, and your data never leaves your computer.

The calculations an ISO/IEC 17025 laboratory does every week, usually in spreadsheets,
written as small, tested Python functions:

<!-- --8<-- [start:modules] -->
| Module | What it covers | Reference |
|---|---|---|
| `uncertainty` | GUM uncertainty budgets: Type A and B components, sensitivity coefficients (analytic or numerical), correlated inputs, Welch–Satterthwaite degrees of freedom, coverage factor, relative uncertainty; Monte Carlo propagation and a check of the GUM interval against it | JCGM 100:2008 (GUM), JCGM 101:2008 (GUM S1) |
| `validation` | Calibration linearity (ordinary or weighted) with confidence intervals and lack-of-fit test, LOD/LOQ, precision (RSD), intermediate precision by ANOVA, spike recovery, trueness against a CRM | ICH Q2, Eurachem guide, ERM Application Note 1 |
| `proficiency` | z, zeta and E<sub>n</sub> scores with interpretation; robust consensus mean (Algorithm A); z-score history across rounds | ISO 13528, ISO/IEC 17043 |
| `control_charts` | Shewhart limits; Westgard rules 1<sub>2s</sub>, 1<sub>3s</sub>, 2<sub>2s</sub>, R<sub>4s</sub>, 4<sub>1s</sub>, 10<sub>x</sub>, also across two or three control levels; CUSUM and EWMA charts | Westgard multirule QC; Montgomery, *Introduction to Statistical Quality Control* |
| `emissions` | ppm ↔ mg/m³ at standard conditions, correction to reference O₂ and its uncertainty, wet ↔ dry, user-defined gases | Stack-emission practice, e.g. EN 303-5 at 10 % O₂ |
| `conformity` | Decision rules for pass/fail statements with uncertainty: simple acceptance, guarded acceptance and rejection, non-binary statements with a guard band; probability of conformance; suggested report wording | ILAC G8:09/2019, JCGM 106:2012 |
| `topdown` | Top-down uncertainty: u(Rw) from QC data (plus duplicates), u(bias) from PT rounds or a CRM, u_c and U | Nordtest TR 537 |
| `outliers` | Grubbs tests for one and two outliers, Cochran's test for the largest variance; critical values at 5 % and 1 %; ok / straggler / outlier | ISO 5725-2 |
| `comparison` | Method comparison: Bland–Altman bias and limits of agreement with confidence intervals; Deming regression (error ratio, jackknife intervals); Passing–Bablok regression with confidence intervals and linearity test | Bland & Altman 1986; Linnet 1990; Passing & Bablok 1983 |
| `equipment` | Drift from successive calibration certificates, when the error reaches the tolerance, and a stated rule to shorten, keep or lengthen the interval | ILAC-G24 / OIML D 10 (calibration history) |
| `report` | Run records (inputs, settings, result, method, labqc version, UTC time, analyst) saved as JSON and reloaded; Excel workbook and one-page PDF reports | ISO/IEC 17025 7.5 (technical records) |

Every function is tested against hand-calculated values or textbook worked examples (152 library tests, plus 122 for the web app and its browser build),
and the examples below run in CI.
<!-- --8<-- [end:modules] -->

<!-- --8<-- [start:examples] -->
## Example 1: uncertainty of a moisture determination

Oven-dry moisture of a wood-pellet sample, `M = (m2 − m3) / (m2 − m1) × 100`, with balance
calibration and resolution for each weighing plus repeatability from five test portions.
Sensitivity coefficients are found numerically from the model function
([`examples/moisture_uncertainty.py`](https://github.com/mantas123456/lab-quality-toolkit/blob/main/examples/moisture_uncertainty.py)).

```text
                      component     u_i    c_i  contribution  dof  share_of_variance
Repeatability (5 test portions)  0.0191      1        0.0191    4              0.996
                    Weighing m3 0.00104 -0.798       0.00083  inf            0.00188
                    Weighing m2 0.00104  0.742      0.000772  inf            0.00162
                    Weighing m1 0.00104 0.0556      5.79e-05  inf           9.12e-06

u_c = 0.01916, v_eff = 4.0, k = 2.77, U (95%) = 0.05306
Report: M = 6.97 % ± 0.05 % (k = 2.77, 95 %)
```

Over 99 % of the variance comes from sample repeatability. A better balance would change
nothing; more test portions would. With only four degrees of freedom the coverage factor is
2.77, not 2, which a fixed "k = 2" spreadsheet gets wrong.

## Example 2: Westgard rules on daily QC

Twenty baseline days set the limits. A +1.4 mg/kg shift is introduced from day 45
([`examples/westgard_iqc.py`](https://github.com/mantas123456/lab-quality-toolkit/blob/main/examples/westgard_iqc.py)).

![Levey-Jennings chart](https://raw.githubusercontent.com/mantas123456/lab-quality-toolkit/main/examples/westgard_chart.png)

```text
    value      z   status             rules
27  47.99 -2.817  warning              1_2s
45  52.49  4.385   reject        1_2s, 1_3s
47  52.09  3.745   reject        1_2s, 1_3s
48  51.50  2.798   reject        1_2s, 2_2s
50  53.00  5.206   reject  1_2s, 1_3s, 4_1s
```

Day 27 is a lone 1<sub>2s</sub> warning that needs no action. The shift is caught on its
first day, and the 2<sub>2s</sub> and 4<sub>1s</sub> rules confirm the error is systematic
(calibration), not random.

## Example 3: boiler test emissions at reference oxygen

```text
Measured O2 12.8 %, correction factor 1.346
CO      310.0 ppm  ->    521.3 mg/m3 at 10 % O2   (104% of example limit)
NO2     118.0 ppm  ->    325.9 mg/m3 at 10 % O2
C3H8      6.5 ppm  ->     17.2 mg/m3 at 10 % O2
```

At high excess air, a raw reading that looks comfortably low can exceed a limit once it is
corrected to 10 % O₂ ([`examples/boiler_emissions.py`](https://github.com/mantas123456/lab-quality-toolkit/blob/main/examples/boiler_emissions.py)).

## Example 4: Monte Carlo and correlated weighings

Version 0.2 adds Monte Carlo propagation (GUM Supplement 1) and correlated inputs
([`examples/monte_carlo_vs_gum.py`](https://github.com/mantas123456/lab-quality-toolkit/blob/main/examples/monte_carlo_vs_gum.py)).

```text
1. Moisture, M = (m2 - m3) / (m2 - m1) x 100 [%]
  GUM (linear):  y = 6.971, u = 0.01916, k = 2.77, 95 % interval [6.918, 7.025]
  Monte Carlo:   y = 6.971, u = 0.02704, 95 % interval [6.917, 7.024]

2. Recovery-corrected result, C = C_meas / R [mg/kg]
  GUM (linear):  y = 20, u = 3.371, k = 1.96, 95 % interval [13.39, 26.61]
  Monte Carlo:   y = 20.61, u = 3.843, 95 % interval [14.15, 28.12]

3. Weighings only (no repeatability), r = 0.92 between weighings
  treated as independent: u = 0.00114 %
  with shared calibration: u = 0.00031 % (-72%)
```

For the nearly linear moisture model the two 95 % intervals agree. Monte Carlo's u is larger
only because a 4-dof Type A input is sampled from a t-distribution; the GUM method puts the
same widening into k = 2.77. Dividing by an uncertain recovery (R = 0.60 ± 0.10) is
non-linear: the real distribution is skewed upwards, and the first-order interval is too low
at both ends. When the three weighings share one balance calibration, most of the offset
cancels, and the balance contribution falls by 72 %.

```python
from labqc.uncertainty import Component, monte_carlo, propagate

inputs = {"a": Component("a", 0.1), "b": Component("b", 0.1)}
y, r = propagate(lambda a, b: a - b, {"a": 5.0, "b": 2.0}, inputs, correlation={("a", "b"): 0.8})
print(r.summary(relative=True))  # u_c, k, U and u_c/|y|, U/|y|
print(monte_carlo(lambda a, b: a / b, {"a": 5.0, "b": 2.0}, inputs, seed=1))
```

## New in 0.3: lab methods

```python
import pandas as pd
from labqc.validation import intermediate_precision, linearity, trueness
from labqc.emissions import corrected_uncertainty

# weighted calibration with duplicate standards: lack-of-fit test included
cal = linearity(
    [1, 1, 2, 2, 5, 5, 10, 10], [0.11, 0.10, 0.21, 0.19, 0.52, 0.49, 1.08, 0.97], weights="1/x"
)
print(cal.lack_of_fit.p_value)  # 0.90: a straight line is adequate

# three days x three replicates: repeatability 0.100, intermediate precision 0.224
days = pd.DataFrame(
    {
        "day": [1, 1, 1, 2, 2, 2, 3, 3, 3],
        "value": [10.1, 10.3, 10.2, 10.6, 10.4, 10.5, 10.0, 10.2, 10.1],
    }
)
ip = intermediate_precision(days, "value", "day")

# five results on a CRM certified at 50 with u = 0.2
print(trueness([50.4, 50.7, 49.1, 49.0, 51.1], crm_value=50, crm_u=0.2).passed)  # True

# CO from Example 3 with u(C) = 8 mg/m3 and u(O2) = 0.2 %: 521 ± 34 mg/m3 (k = 2)
c_ref, r = corrected_uncertainty(387.4, 8, o2_measured=12.8, u_o2=0.2, k=2)
```

`pt_history()` reviews a lab's z-scores across PT rounds, and `westgard_levels()`, `cusum()`
and `ewma()` cover two- and three-level QC and small shifts that Westgard rules miss.
<!-- --8<-- [end:examples] -->

## Web app

A Streamlit app puts every module in the browser, for analysts who do not write Python.
It runs in two places, from the same `app/` code:

| Version | Where | Good for |
|---|---|---|
| Streamlit Community Cloud | **[lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app)** | Every feature, including PDF reports. Sleeps when unused and takes about 30 s to wake. |
| In your browser (stlite) | **[mantas123456.github.io/lab-quality-toolkit/app](https://mantas123456.github.io/lab-quality-toolkit/app/)** | Never sleeps; Python runs on your computer, so no data is uploaded anywhere. The first visit downloads Python and takes about a minute. No PDF reports (Excel and JSON work). |
Each page opens with the worked examples above already loaded, so the app and the library
can be checked against each other:

| Page | What it does |
|---|---|
| Uncertainty budget | Start from a template (weighing, volumetric dilution, oven-dry moisture, O₂ reference correction, each with where its numbers usually come from) or edit or upload (CSV) the components and optional correlations between them; result card y ± U with k and v_eff; budget table and a chart of each component's share of variance; *Check with Monte Carlo* compares the GUM interval with a JCGM 101 Monte Carlo interval; a *Top-down* tab builds U from QC data and PT rounds or a CRM (Nordtest TR 537) |
| Method validation | Tabs: calibration and precision (with a sample's concentration and its uncertainty read back from the line); outlier tests (Grubbs, Cochran); method comparison (Bland–Altman plot, Passing–Bablok or Deming line against y = x). Calibration line (ordinary or weighted) with residual plot and lack-of-fit test, LOD/LOQ, precision, recovery |
| Proficiency testing | z, zeta and E<sub>n</sub> with coloured status; robust mean and SD of a round (Algorithm A); a *PT history* tab with your z-scores over rounds and the warning signals marked |
| QC overview | One CSV with several methods and control levels: a grid coloured accept / warning / reject by the latest run, with the rule broken; click a cell for its chart or open the series in QC charts |
| QC charts | CSV of control results; tabs for Westgard (Levey-Jennings chart, or the rules across two or three control levels), CUSUM and EWMA |
| Emissions | ppm or mg/m³ (standard or actual conditions), wet or dry, corrected to reference O₂, % of the limit |
| Equipment drift | Certificates (date, error, U) and a tolerance: drift per year, when \|error\| + U reaches the tolerance, and a suggested calibration interval |
| Decision rules | Result, U and limits; simple acceptance or a guard band; the decision, the probability of conformance, a picture of the result against the limits and guard bands, and suggested report wording |
| Reports | Results added with *Add to report* on any page: one PDF per result, one Excel workbook, JSON records; reload a saved budget into the Uncertainty page |

The app contains no calculations of its own: every number comes from labqc. Bad input shows
a plain message, not a Python traceback. Every page has CSV downloads and an *Add to report*
button, and every main result has a short *What this means* box in plain English.

**Open an example directly.** Add `?example=<name>` to a page's address to open it with that
example loaded:

| Link | Opens |
|---|---|
| [`?example=moisture`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Uncertainty_budget?example=moisture) | Moisture budget (Example 1) |
| [`?example=moisture-shared-balance`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Uncertainty_budget?example=moisture-shared-balance) | The same budget with the three weighings correlated (one balance) |
| [`?example=outliers`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Method_validation?example=outliers) | Grubbs and Cochran tests |
| [`?example=method-comparison`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Method_validation?example=method-comparison) | Old and new analyser on 30 samples |
| [`?example=equipment-drift`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Equipment_drift?example=equipment-drift) | A thermometer's drift and its calibration interval |
| [`?example=calibration`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Method_validation?example=calibration) | Calibration line, LOD/LOQ, precision and recovery |
| [`?example=pt-round`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Proficiency_testing?example=pt-round) | z, zeta and E<sub>n</sub>, and a round of 15 labs |
| [`?example=pt-history`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Proficiency_testing?example=pt-history) | z-scores of 14 PT rounds with the warning signals |
| [`?example=westgard`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/QC_charts?example=westgard) | Westgard rules with a shift from day 45 (Example 2) |
| [`?example=westgard-levels`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/QC_charts?example=westgard-levels) | Westgard rules across two control levels |
| [`?example=cusum`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/QC_charts?example=cusum) | CUSUM chart of the same series |
| [`?example=ewma`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/QC_charts?example=ewma) | EWMA chart of the same series |
| [`?example=boiler`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Emissions?example=boiler) | Boiler test at 10 % O₂ (Example 3) |
| [`?example=topdown`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Uncertainty_budget?example=topdown) | Top-down uncertainty from the QC series and six PT rounds |
| [`?example=decision`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Decision_rules?example=decision) | Lead in water near its limit, simple acceptance |
| [`?example=decision-guarded`](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/Decision_rules?example=decision-guarded) | The same result with a guard band w = U |

An unknown name shows a warning and the page opens with its usual example.
(`?example=qc-overview` opens the QC overview: [link](https://lab-quality-toolkit-3go33hyzzwjhwpktn8tles.streamlit.app/QC_overview?example=qc-overview).)

**Project files.** *Save project* in the sidebar of every page downloads one `.labqc.json` file
with the inputs of every page and the report records; *Open a project* loads it back. The file
is versioned and checked before anything is loaded, so a damaged or foreign file is refused
with a plain message and the session stays as it was. Results are not stored: labqc calculates
them again from the inputs.

**Browser build.** `python -m build --wheel && python web/build.py --wheel dist/labqc-*.whl
--out site/app` writes the stlite version; the docs workflow publishes it under `/app/` on
GitHub Pages with every push to main.

Run it on your PC:

```bash
pip install -e ".[app,reports]"
streamlit run app/Home.py
```

Deploy it free on [Streamlit Community Cloud](https://share.streamlit.io): sign in with
GitHub, choose **Create app → Deploy a public app from GitHub**, pick this repository, branch
`main` and main file path `app/Home.py`, then **Deploy**. The cloud installs
`app/requirements.txt`, and the app imports labqc from `src/`, so a push to main redeploys
the app with the matching library code.

## Reports and records

```python
from labqc.report import RunRecord, record_budget, to_excel, to_pdf
from labqc.uncertainty import Component, combine

components = [Component("Certificate", 0.010, k=2), Component("Resolution", 0.005, "rectangular")]
result = combine(components, value=10.02)

record = record_budget(components, result, unit="mg", analyst="A. Analyst")
open("budget.json", "w", encoding="utf-8").write(record.to_json())  # reload with from_json
to_pdf(record, "budget.pdf")  # needs pip install "labqc[reports]"
to_excel([record], "records.xlsx")
```

Each record keeps the inputs, settings, result, method, labqc version and UTC time, so a
result can be traced and recalculated later.

## Validation

labqc 1.0 is checked against **91 reference cases** for 32 functions, each with an acceptance
tolerance and a source: published worked examples (GUM Supplement 1, Miller & Miller,
Montgomery), standard tables (GUM Table G.2), the cited formula evaluated by hand (GUM, ICH Q2,
ISO 13528, ISO 5725-2, emission formulas) or the definition of a rule (Westgard, Nelson).
Expected values never come from labqc itself.

```bash
python validation/run_validation.py   # writes validation/report.md, exit code 1 on any fail
```

- [`validation/report.md`](https://github.com/mantas123456/lab-quality-toolkit/blob/main/validation/report.md):
  every case with expected value, result, tolerance, pass/fail, labqc and Python version and
  date. CI runs it on every push, and a release is published only if every case passes.
- [`validation/cases/`](https://github.com/mantas123456/lab-quality-toolkit/tree/main/validation/cases):
  one CSV per function with inputs, reference value, tolerance, source and working.
- [`validation/TO_CHECK.md`](https://github.com/mantas123456/lab-quality-toolkit/blob/main/validation/TO_CHECK.md):
  sources still to confirm and cases still to add (for example an ISO 13528 Algorithm A
  example for `robust_mean_sd`).
- [Change control](https://mantas123456.github.io/lab-quality-toolkit/change_control/): how a
  change is made, tested, validated and released, and what was re-validated in each release.

## Use it

```bash
pip install labqc
```

Full documentation, with the API reference for every module:
[mantas123456.github.io/lab-quality-toolkit](https://mantas123456.github.io/lab-quality-toolkit/).

```python
from labqc.uncertainty import Component, combine, type_a
from labqc.proficiency import z_score, classify

budget = [
    type_a([10.02, 10.05, 9.98, 10.01, 10.03]),
    Component("Reference standard", 0.010, "normal", k=2),
    Component("Temperature effect", 0.004, "rectangular"),
]
print(combine(budget))  # u_c, v_eff, k, U

z = z_score(10.75, assigned=10.0, sigma_pt=0.3)
print(round(z, 2), classify(z))  # 2.5 questionable
```

## Develop

```bash
pip install -e ".[dev]"
pytest
ruff check .

pip install -e ".[docs]"
mkdocs serve        # documentation at http://127.0.0.1:8000

pip install -e ".[app]"
streamlit run app/Home.py   # web app at http://localhost:8501
python app/demo_data/make_demo_data.py   # after changing an example
```

Releases: push a tag `v*` (for example `v0.4.0`) that matches the version in
`pyproject.toml`; GitHub Actions builds the package and publishes it to PyPI.

## Scope and limits

- `propagate()` uses first-order sensitivity coefficients. For strongly non-linear models,
  use `monte_carlo()` (GUM Supplement 1) and compare.
- Monte Carlo handles correlation only between normal inputs with infinite degrees of
  freedom. Welch–Satterthwaite is applied as for independent inputs, even when correlations
  are given.
- Units are stored on each component but not checked.
- labqc is validated against the reference cases above. A laboratory that uses it for
  reported results must still validate it for its own intended use (ISO/IEC 17025 7.11.2)
  and record the labqc version with each result.

## How this was built

I designed the analysis and checked the results. I used Claude Code as
a coding assistant.

---
Mantas Valantinavičius · measurement scientist, 14 years in ISO/IEC 17025 testing ·
[github.com/mantas123456](https://github.com/mantas123456)
