Metadata-Version: 2.5
Name: mcmaster-epg
Version: 1.1.0
Summary: Eggs per gram for the McMaster method, for samples and herds: exact confidence limits, correction for egg loss, detection limits, herd fractions above EPG thresholds and survey size, with method profiles built in, entered by hand or calibrated from one's own spiked samples
Project-URL: Repository, https://github.com/maciejkochanowski/mcmaster-epg
Author: Joanna Dąbrowska
Author-email: Maciej Kochanowski <maciej.kochanowski@piwet.pulawy.pl>
License: MIT
License-File: LICENSE
Keywords: McMaster,calibration,eggs per gram,faecal egg count,limit of detection,method validation,parasitology,partial identification,prevalence,veterinary
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
Requires-Python: >=3.10
Requires-Dist: numpy>=1.22
Requires-Dist: scipy>=1.8
Provides-Extra: test
Requires-Dist: pytest; extra == 'test'
Provides-Extra: validation
Requires-Dist: matplotlib; extra == 'validation'
Requires-Dist: scienceplots; extra == 'validation'
Description-Content-Type: text/markdown

# mcmaster-epg

[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24662026.svg)](https://doi.org/10.5281/zenodo.24662026)

Eggs per gram (EPG) for the McMaster method, for single samples and for
herds, with the egg loss and variability of the procedure taken into account.
For a sample: exact confidence limits, EPG corrected for egg loss, and limits
of detection. For a herd examined with one count per animal: the mean EPG,
the fraction of animals at or above an EPG threshold (with and without an
aggregation model), and the number of animals to examine to find infection.

Everything the calculations need to know about a procedure is held in a
**method profile**: the multiplication factor, the recovery of eggs, the
dispersion of counts between samples, their uncertainty, and the
spiked-sample results behind the detection curve. A profile is

- **built in** for the combinations validated by Kochanowski et al. (2013):
  Raynaud's modification (2 g of faeces in 28 ml of saturated MgSO4, McMaster
  chamber or flotation slide), eggs of *Toxocara canis* and *Trichuris* in
  dog faeces and *Ascaris suum* in dog and pig faeces
  (https://doi.org/10.14411/fp.2013.030);
- **entered by hand**, for example from a published validation of another
  procedure (`--recovery`, `--k` and their intervals);
- **calibrated** from one's own spiked samples (`mcmaster-epg calibrate`),
  for any chamber, dilution, flotation solution, host and parasite.

For faecal egg count reduction tests and hierarchical models use `eggCounts`,
`bayescount` or fecrt.com; `mcmaster-epg` gives them the raw count and
correction factor they expect (see [Output](#output)).

## Installation

```bash
pip install mcmaster-epg
```

Python 3.10 or later; NumPy and SciPy are installed with it.

## Command line

```bash
mcmaster-epg epg 7 --variant whole_chamber
# EPG 105 (95% CI 42.2 to 216.3)

mcmaster-epg epg 6 --variant whole_chamber --species toxocara_canis
# EPG 90 (95% CI 33.0 to 195.9)
# Corrected EPG 276 (95% CI 80 to 1249), factor 46 (published factor)
#   interval includes between-sample dispersion k = 4.4
# LOD50 25 EPG (14 to 37), LOD95 154 EPG (111 to 240); published LOD 25 EPG

mcmaster-epg epg 0 0 0 40 --variant one_grid      # replicate readings
mcmaster-epg lod --variant one_grid --probability 0.95
mcmaster-epg lod --variant whole_chamber --species toxocara_canis
mcmaster-epg plan 150 --variant whole_chamber --cv 0.2 --species toxocara_canis
mcmaster-epg batch samples.csv > results.csv
```

Every command takes the method in the same way.

The factor: `--variant` (`one_grid`, `two_grids`, `whole_chamber`,
`flotation_slide`, Raynaud's factors 100, 50, 15, 7), `--multiplier` (any
factor), or `--counted-ml` with `--faeces-g` and `--flotation-ml` (the factor
is computed as (faeces + flotation volume) / (faeces x volume read)).

Egg loss and dispersion, from one source: `--profile FILE`, the built-in
`--species` (with `--variant`; `--matrix pig` for pig faeces), or `--recovery`
and `--k` entered by hand, optionally with `--recovery-ci LOW HIGH` and
`--k-ci LOW HIGH` (95% intervals; `inf` allowed as the upper limit of k).
Without any of them the nominal method is used: no egg loss, Poisson counts.
`epg --json` prints every field listed under [Output](#output).

The CSV for `batch` has the columns `sample_id,counts[,variant,species,matrix]`;
replicate readings of one sample are separated by `;`. Give the method either
in the file (per row) or on the command line (for all rows).

## Your own method

Spike faeces free of eggs with known numbers of eggs at several levels,
prepare and read each sample as in routine work, and record one row per
sample:

```text
sample,level,count
S01,25,0
S02,25,2
...
```

`level` is eggs per gram added, `count` the eggs counted in one reading
(comma, semicolon or tab separated; decimal comma accepted). Then

```bash
mcmaster-epg calibrate examples/spiked_example.csv --multiplier 50 \
    --name "example lab, two grids" --out lab.json --report lab.md
```

writes the profile `lab.json` (with the calibration data in it) and a report
`lab.md`: recovery, the corrected factor, the dispersion k and LOD50 and LOD95,
all with profile-likelihood intervals; a test of proportionality of the mean
count to the level; a test of overdispersion; the detection curve fitted to
the share of positive samples as an independent check, with its goodness of
fit; and observed against predicted values at every level. For the simulated
example file (true recovery 0.6, k = 6, LOD50 65 and LOD95 324 eggs/g):

```text
| Recovery | 0.621 | 0.485 to 0.798 (profile likelihood) |
| Corrected factor (factor / recovery) | 80.6 | 62.6 to 103.1 |
| Dispersion k | 2.46 | 1.27 to 4.99 (profile likelihood) |
| LOD50 (eggs/g) | 64.5 | 50.2 to 86.3 (count model, profile likelihood) |
| LOD95 (eggs/g) | 471.6 | 306.4 to 1016.8 (count model, profile likelihood) |
```

In this draw the interval of k misses the true value, as a 95% interval does
in about one study in twenty; the other intervals contain theirs.

Every command then uses the profile:

```bash
mcmaster-epg epg 3 --profile lab.json
# EPG 150 (95% CI 30.9 to 438.4)
# Corrected EPG 242 (95% CI 40 to 2218), factor 80.6 (calibrated recovery)
#   interval includes between-sample dispersion k = 2.5
# LOD50 65 EPG (50 to 86), LOD95 472 EPG (306 to 1017)

mcmaster-epg herd --file animals.csv --profile lab.json --threshold 200
mcmaster-epg survey --profile lab.json --prevalence 0.1 --threshold 200
```

Parameters from a publication can be entered directly, or saved as a profile:

```bash
mcmaster-epg epg 3 --multiplier 50 --recovery 0.6 --recovery-ci 0.5 0.7 --k 6
mcmaster-epg profile --multiplier 50 --recovery 0.6 --recovery-ci 0.5 0.7 --k 6 --out paper.json
mcmaster-epg profile --variant whole_chamber --species toxocara_canis --out builtin.json
```

Design of the spiking study: the more levels near the expected limit of
detection and the more samples per level, the narrower the limits. Eight
levels with 20 samples each, as in the built-in study, give recovery to about
plus or minus 12% (true recovery 0.4, k = 4.4); five levels with 10 samples,
about plus or minus 21% (see [Validation](#validation)). Counts must come from independently prepared
samples, not from re-reading one chamber.

## Herds

One McMaster count per animal, for a herd, farm or kennel:

```bash
mcmaster-epg herd 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 2 4 5 6 7 8 11 18 22 \
    --variant whole_chamber --species ascaris_suum --matrix pig --threshold 50 150
# 30 animals, 10 positive (33.3%, 95% CI 17.3% to 52.8%)
# Mean EPG 57 (95% CI 19 to 274), factor 20.3; aggregation between animals k 0.14
# Without assumptions about the distribution of EPG among animals:
#   infected (any eggs): at least 17.3%; McMaster counts give no upper limit
#   true EPG >= 50: 1.6% to 67.3% of animals (95% CI; detection at 50 EPG 0.92)
#   true EPG >= 150: 0.0% to 59.9% of animals (95% CI; detection at 150 EPG 1.00)
# Gamma aggregation model (negative binomial between animals; intervals calibrated by a parametric bootstrap, 200 herds):
#   infected 35.4% (17.1% to 100.0%); mean EPG of infected 160, shape 1.59
#   true EPG >= 50: 29.3% (12.8% to 51.2%)
#   true EPG >= 150: 15.1% (4.1% to 35.5%)

mcmaster-epg survey --variant whole_chamber --species toxocara_canis --prevalence 0.1 --threshold 50
# 48 animals: a positive is found with probability 0.95 if at least 10% of the herd
# has 50 EPG or more (detection at 50 EPG at least 0.62)
```

`--file` reads the counts from a text file or from the `counts` column of a CSV.

What the results mean:

- **Mean EPG** is corrected for egg loss (mean count x factor / recovery of the
  count model), with a negative binomial profile-likelihood interval.
- **Fraction of animals at or above a threshold** (for example a treatment
  threshold), first without any assumption about how EPG is distributed among
  the animals. These limits hold for every distribution, so they are wide;
  they show what the counts alone establish.
- **The same under the gamma aggregation model**, the usual negative binomial
  model of parasite burdens. Narrower, but valid only as far as the model
  holds (see [Validation](#validation)). Below 60 animals its intervals are
  calibrated by a parametric bootstrap (`--calibrate-intervals` and
  `--no-calibrate-intervals` override this; `--n-boot`, `--seed`). A
  goodness-of-fit test checks the model on every herd and prints a WARNING
  when the counts do not fit it; then rely on the limits without assumptions.
- **Prevalence of infection** (any EPG above 0) has no upper limit without
  assumptions: an animal with 1 EPG is almost always negative, so negative
  results never exclude that all animals are infected. The aggregation model
  gives an estimate, but its upper limit is often 100%.
- **`survey`** gives the number of animals to examine so that one positive is
  found if at least the given fraction of the herd has the given EPG or more.
  No distribution of EPG is assumed.

Without a profile (`--species`, `--profile` or `--recovery`) the nominal
method is used (no egg loss, Poisson counts), which overestimates detection;
the output says so. Without `--recovery-ci` and `--k-ci`, entered parameters
are treated as known and the herd intervals do not include their uncertainty.

## Sequential reading protocol

Some laboratories read a sample in stages: the two grids of the chamber
(factor 50); if they hold no eggs, the whole chamber (factor 15); if that is
empty too, a flotation slide (factor 7). The record is a stage and a count,
but most laboratories keep only `count x factor`. That number overstates low
EPG: a sample with one egg on the grids is stored as 50 EPG, while a sample
with none is read again and ends lower or negative, so the stored values lean
towards the large factor. And the protocol detects eggs much better than the
grids alone: at 25 EPG of *Ascaris suum* in pig faeces it finds eggs in 84%
of samples, the two grids alone in 38%.

The model, in plain words. The grids lie inside the chamber: they see a share
p of the eggs of the same chamber filling, so a sample empty on the grids
has a chamber count that is reduced accordingly. The flotation slide is a
separate preparation of the sample. The chamber and the slide follow the count
model of their method profile (recovery and dispersion k). By default p is
derived from the profiles (p = factor ratio x recovery ratio, 0.409 for the
built-in *A. suum* pig profiles, 0.3 for nominal ones); it can also be given
explicitly, for example to see how much a conclusion depends on it.

```python
from mcmaster_epg import (SequentialProtocol, sequential_epg, protocol_lod,
                          protocol_detection, stage_detection, stage_probabilities,
                          recorded_epg_bias, check_record, reconstruct_record)

pig = SequentialProtocol(species="ascaris_suum", matrix="pig")   # built-in profiles, p from them
pig.p, pig.factors
# (0.4087740166577692, (50.0, 15.0, 7.0))

r = sequential_epg(1, 3, pig)                   # 3 eggs on the two grids
r.epg, r.ci_low, r.ci_high, r.recorded_epg      # 149, 19.9 to 637.6 (rounded); 150 stored
r = sequential_epg("whole_chamber", 5, pig)     # grids empty, 5 eggs in the chamber
r.epg, r.ci_low, r.ci_high, r.recorded_epg      # 101, 9.4 to 396.2; 75 stored
r = sequential_epg(2, 12, pig)                  # grids empty, 12 eggs in the chamber
r.epg, r.ci_low, r.ci_high, r.recorded_epg      # 243, 48.6 to 746.3; 180 stored
r = sequential_epg(0, 0, pig)                   # negative at all three stages
r.epg, r.ci_low, r.ci_high                      # 0.0, 0.0 to 70.8

lod = protocol_lod(pig)                         # EPG found with probability 0.5 and 0.95
{k: round(v[0], 1) for k, v in lod.items()}
# {'lod50': 9.3, 'lod95': 40.8}
round(protocol_detection(25, pig), 3), round(stage_detection(25, pig)["two_grids"], 3)
# (0.843, 0.383)                                # whole protocol, grids alone
{k: round(float(v), 3) for k, v in stage_probabilities(25, pig).items()}
# {'stage_1': 0.396, 'stage_2': 0.313, 'stage_3': 0.135, 'negative': 0.157}

recorded_epg_bias([10, 25, 50, 100], SequentialProtocol()).round(2)   # nominal profiles
# array([1.09, 0.61, 0.29, 0.1 ])
recorded_epg_bias([10, 25, 50, 100], pig).round(2)    # relative bias of count x factor
# array([0.48, 0.32, 0.18, 0.07])

b = reconstruct_record(150, pig)                # 3 x 50 or 10 x 15?
b.stage, b.count, round(b.weight, 3)
# (1, 3, 0.997)
check_record(1160, pig).flags                   # no multiple of 50, 15 or 7
# ('not_a_multiple',)
c = check_record(180, pig)                      # 12 eggs in the chamber, grids empty
c.flags, round(c.best.p_grids_zero, 4)          # all 12 eggs outside the grids: 0.18%
# (('implausible',), 0.0018)
check_record(180, SequentialProtocol(species="ascaris_suum", matrix="pig", p=0.3)).flags
# ()
```

What the functions do:

- **`sequential_epg(stage, count, protocol, conf)`** gives the EPG estimate
  and its confidence interval from the record itself (stage 1, 2, 3 or a stage
  name; stage 0 or `"negative"` for no eggs). It uses the zeros of the earlier
  stages, so it is not biased by the stopping rule. The interval is described
  below.
- **`protocol_lod`** gives the EPG detected in 50% and 95% of samples by
  the whole protocol, from the count model (the grids are part of the
  chamber and do not enter). `protocol_detection`, `stage_detection` and
  `stage_probabilities` give the underlying probabilities at any true EPG.
- **`expected_recorded_epg`, `recorded_epg_bias`** show how far the stored
  `count x factor` is from the truth on average. `record_likelihood` gives
  the likelihood of a record at a given EPG, for your own analyses.
- **`reconstruct_record`, `check_record`** recover the stage and count behind
  a stored value and flag values that are no multiple of a factor, that
  disagree with the stage, or that are implausible, for example many eggs in
  the chamber while the grids were empty, which the model gives a probability
  of (1 - p)^count. A flag means a recording error or a different method; it is
  a screening threshold, not a test with a controlled error rate.

The stages need not be the Raynaud variants: pass other variant names or
`MethodProfile` objects (`SequentialProtocol([grids, chamber, slide], p=0.35)`).

**The interval.** The records of all three stages are put in one order, by
their EPG estimate (the negative record has estimate 0; records with the same
estimate, such as (1, 3) and (2, 10) of the nominal protocol, are one
outcome). For an observed record with estimate x, a true EPG belongs to the
interval when, at that EPG, both P(estimate >= x) and P(estimate <= x) exceed
(1 - conf)/2. The set of such EPG values is found on a grid of log(EPG), its
ends are refined by root finding, and the interval is its hull, so it does not
rely on these probabilities changing monotonically with the EPG.

- **Exact** means: with known parameters, the coverage is at least conf for
  every true EPG, as a probability over all records of the protocol together,
  whatever stage they reach.
- It is not a guarantee for each stage separately. At a given EPG the
  excluded records are the least likely ones, so a stage that holds only a
  small share of the samples (less than about (1 - conf)/2) can be covered
  much less often than conf, or not at all; stages that hold many samples are
  covered close to conf (numbers below). The lower limit of a stage 2 record
  rises with the count: 9.4 for (2, 5) and 48.6 for (2, 12) above.
- With parameter ranges (the built-in profiles have them), half of 1 - conf
  goes to the parameters, as in the herd mean: the tails use (1 - conf)/4 and
  the limits are the lowest and highest over the corners of the parameter
  ranges at level 1 - (1 - conf)/2. The corners are consistent: a derived p
  is computed at each corner from that corner's grid and chamber recoveries,
  so the mean grid count does not move with the chamber recovery; an explicit
  p stays fixed. The coverage is at least (1 + conf)/2 when the true
  parameters lie at a corner, and was at least conf in every case checked
  inside the ranges (not proved). The price is width: at 95% and 10 to 800
  EPG the mean width is 1.47 to 1.96 times that with known parameters for
  *A. suum* in pig faeces, 1.54 to 2.05 for *Trichuris* and *A. suum* in dog
  faeces, and 2.36 to 3.07 for *T. canis* (`validation/PROTOCOL_REPORT.md`,
  section 4); single records vary more, and the factor depends on the
  parameter ranges of the profiles.
- The construction concerns only the interval. The estimate, the stage
  probabilities, the protocol limits of detection and the bias of the stored
  value `count x factor` do not depend on it.

Validation of the intervals (`validation/PROTOCOL_REPORT.md`; the nominal
protocol and the four built-in combinations of egg type and faeces, true EPG
2 to 800, conf 0.90, 0.95 and 0.975; exact values from all records with
probability of at least 1e-13, checked against 80 000 to 200 000 simulated
samples per setting):

- with known parameters the exact coverage is at least 0.914, 0.954 and 0.977
  at conf 0.90, 0.95 and 0.975, and the simulated coverage agrees with the
  exact one within Monte Carlo error in all 852 compared cells (with and
  without parameter ranges);
- with known parameters and conditional on the stage reached, stages with at
  least 20% of the samples are covered in at least 0.9175, 0.9553 and 0.9734
  of them, and stages with 10% to 20% in at least 0.69, 0.83 and 0.92; rarer
  stages can fall much lower, down to 0 for stage 1 at 2 EPG (1.7% to 4% of
  samples) at conf 0.90;
- with the parameter ranges, the exact coverage is at least 0.982, 0.994 and
  0.997 when the true parameters are at their point values; when they are at
  a corner of the ranges it is at least (1 + conf)/2 everywhere (lowest 0.969
  at conf 0.90, bound 0.95); when they are redrawn for every sample from a new
  bootstrap of the spiking design, as in the herd study, the simulated
  coverage is at least 0.982, 0.994 and 0.997; stages with at least 10% of the
  samples are then covered in at least 0.90;
- a wrong p lowers the coverage with known parameters: at 200 EPG and conf
  0.95, 0.894 for *T. canis* analysed with the derived p (0.32) when the true
  p is 0.5, and 0.872 for *A. suum* in pig faeces analysed with p = 0.3 when
  it is 0.5 (with the parameter ranges of the built-in profiles see the study
  of p under "Validation");
- the stored value `count x factor` has a relative bias of +1.09 at 10 EPG
  with nominal profiles and +0.48 at 10 and +0.32 at 25 EPG for *A. suum* in
  pig faeces; for *T. canis* it is -0.21 at 10 to -0.58 at 800 EPG (egg loss
  is not corrected). The plain interval of the stored value
  (`estimate_epg(count, factor)`) then covers the true EPG of *T. canis* at
  800 EPG in 0.2880 of samples at conf 0.95, the protocol interval in 0.9765.

`python validation/run_protocol_validation.py` writes the report (default
`SIM_SCALE=1`); on a cluster `sbatch --export=ALL,VALIDATIONS=protocol
validation/helios.sbatch` runs it with `SIM_SCALE=4`, which is how the report
in `validation/` was made (about 20 seconds on 192 cores). `PROTOCOL_N_BOOT`
sets the bootstrap refits per profile (default 1000), `WORKERS` the number of
processes and `PROTOCOL_OUT` another output file; `SIM_SCALE=0.05
PROTOCOL_N_BOOT=60` is a quick check of about two minutes on eight cores. The
exact columns do not depend on `SIM_SCALE`.

Limits:

- The package does not estimate p from data. The derived value follows from
  the recoveries of the profiles; if the grids hold a different share of the
  chamber's eggs in your laboratory, give p explicitly. Estimates of p from
  the 2013 data and the literature, with a recommended value and range for
  each built-in combination, are summarised under "Validation".
- The protocol has exactly three stages, in the order grids, chamber, slide.
- The grid profile enters only through p. Counts on the grids follow the
  chamber's dispersion, not the grid profile's own k.
- The protocol limits of detection use the count model, not a detection
  curve fitted to the protocol.
- The coverage of the interval holds over all records, not for each stage:
  a record of a stage that is rare at the true EPG can be missed more often
  than conf (see above).
- The estimate is the maximum-likelihood EPG of the record and is biased
  upwards at low EPG: by +0.45 at 25 EPG and +0.08 at 100 EPG for *A. suum*
  in pig faeces, and by +0.76 and +0.31 for *T. canis* (report, section 8).
  Near the limit of detection read the interval, not the estimate alone.
- With parameter ranges only the levels stored in the profiles are available
  (built in: 0.90, 0.95 and 0.975 for `sequential_epg`; 0.95, 0.975 and
  0.9875 for `protocol_lod`).
- There are no herd functions for the protocol yet; `record_likelihood` is the
  building block, and there is no command line subcommand.
- With parameter ranges the coverage inside the ranges is not proved; it was
  checked by simulation with parameters drawn from the bootstrap, and in a
  study of the whole chain in which the profiles are estimated from simulated
  validation studies (see "Validation"). A p that differs from the true share
  lowers the coverage (see above).

## Python

```python
from mcmaster_epg import RAYNAUD_MULTIPLIER, epg, epg_ci, detection_limit, replicates_for_cv

factor = RAYNAUD_MULTIPLIER["whole_chamber"]      # 15
epg(7, factor)                                    # 105
epg_ci(7, factor)                                 # (42.2, 216.3), exact 95% limits
detection_limit(factor, probability=0.95)         # 44.9, Poisson counts only
replicates_for_cv(150, factor, target_cv=0.1)     # 10, Poisson counts only

from mcmaster_epg import interpret, fitted_limits
interpret(6, "whole_chamber", species="toxocara_canis", matrix="dog")   # dict, see below
fitted_limits("toxocara_canis", "dog", "whole_chamber")
# {'lod50': (25.1, 14.2, 37.2), 'lod95': (154, 111, 240)}  (rounded)

from mcmaster_epg import multiplier
multiplier(mass_g=2, suspension_ml=30, counted_ml=0.15)   # 100, for other set-ups

# method profiles
from mcmaster_epg.profile import builtin_profile, manual_profile, load_profile
from mcmaster_epg.calibrate import calibrate, read_spiked
from mcmaster_epg.report import interpret_profile
from mcmaster_epg.herd import summarise_herd

levels, counts = read_spiked("examples/spiked_example.csv")
lab = calibrate(levels, counts, factor=50, name="example lab").profile
interpret_profile([3], lab)                                  # dict, see below
summarise_herd([0, 0, 1, 5], thresholds=(200,), profile=lab)
paper = manual_profile(50, recovery=0.6, k=6, recovery_ci=(0.5, 0.7))
```

## Output

| Field | Meaning |
|---|---|
| `total_count`, `readings`, `cf_total` | eggs counted over all readings, number of readings, and the factor for the summed count (`total_count * cf_total = epg_nominal`). These are the raw count and correction factor of the WAAVP 2023 guideline and of `eggCounts` (`rawCounts = TRUE`, `preCF`); `eggCounts` needs an integer factor. |
| `epg_nominal`, `epg_nominal_ci` | count x Raynaud factor (100, 50, 15, 7) with the exact Poisson interval. Counting error only; no correction for egg loss. |
| `epg_corrected`, `epg_corrected_ci` | count x recovery-corrected factor. Whole chamber: the published factor (46, 28, 21). Other variants: nominal factor / recovery of the count model. The interval includes the between-sample variation estimated from the spiked samples (`dispersion_k`) where it was detected. |
| `correction_source` | `published factor` or `count model`. |
| `quantitative_range`, `within_quantitative_range` | range of levels on which the published whole-chamber regression was fitted, and whether the corrected EPG lies in it. |
| `published_lod` | limit of detection from Table 4 of the paper. |
| `lod50`, `lod95` and their intervals | EPG detected in 50% and 95% of single examinations, from the detection curve fitted to the spiked samples. `lod95_extrapolated` marks values above 300 eggs/g, the highest tested level. |
| `dispersion_index`, `dispersion_p` | for replicate readings: Poisson index of dispersion and its p-value (Torgerson et al. 2012). A small p means the Poisson interval is too narrow. |

## Methods

**Calibration.** Counts of the spiked samples are modelled as negative
binomial with mean recovery x level / factor and dispersion k (Poisson when k
is infinite), fitted by maximum likelihood. Recovery, k and the limits of
detection (LOD_p = factor x m_p(k) / recovery, with m_p(k) the mean count at
which P(count >= 1) = p) get profile-likelihood intervals, the other
parameter profiled out. The parameter ranges that the herd calculations use
are profile-likelihood intervals at the levels they need (90% to 98.75%),
stored in the profile with the calibration data. Proportionality is tested
against log mean = a + b log level (likelihood ratio, b = 1), overdispersion
against Poisson (likelihood ratio, half the chi-square tail at the boundary).
The detection curve below is fitted to the share of positive samples only and
is reported as an independent check, with a parametric-bootstrap
goodness-of-fit test. Entered 95% intervals are converted to other levels
assuming a normal distribution of the logarithm of the parameter.

**Factors.** `geometric_factor(counted_ml, faeces_g, flotation_ml)` gives the
factor for any dilution and counted volume; it reproduces 100 (0.15 ml) and
50 (0.30 ml).

**Whole-chamber factor.** The nominal factor 15 corresponds to 1.0 ml, while
the chamber holds 1.5 ml (geometric factor 10). The spiked samples fit 15 better
than 10: with 15 the detection data of the three chamber variants are
compatible with one recovery per species in all four groups, with 10 in two of
four. In the count data the whole chamber still recovers less than the grids
for Trichuris and Ascaris (validation report, section 4). The paper notes that
eggs gather under the grids.

**Flotation slide.** The nominal factor 7 underestimates about five- to
nine-fold in the spiked samples (effective factor 38 to 65). Use the corrected
EPG for this variant.

**Published whole-chamber factors.** They are 1/slope of regressions with a
positive intercept, so as plain multipliers they overestimate, most at low
counts (validation report, section 4).

**Intervals.** Poisson: exact (Garwood). With dispersion k (variance = mean +
mean^2/k): exact inversion of the negative binomial distribution; replicate
readings are pooled. The Poisson interval is too narrow when samples differ
more than counting error explains (validation report, section 6).

**Detection curve.** POD = 1 - exp(-ln 2 x (EPG / LOD50)^slope), fitted by
binomial maximum likelihood with profile-likelihood intervals. Slope 1 is the
complementary log-log model of Wilrich and Wilrich (2009, J AOAC Int
92:1763-1772) used in ISO 16140-2; the spiked samples require a slope below 1
in most combinations. `detection_limit` and `lod` without `--species` give the
Poisson (slope 1) limit of the nominal method, which is lower than the
observed one.

**Count model.** Negative binomial counts with mean recovery x EPG / factor,
fitted to the published mean and SD of ln(count + 1).

**Herd limits without assumptions.** For a count c, let q_c be the fraction
of animals with a count of at least c and s_c the probability of such a count
at the threshold EPG t. The probability rises with EPG, so for every
distribution of EPG among the animals the fraction at or above t lies between
(q_c - s_c)/(1 - s_c) and q_c/s_c. `fraction_above` uses several counts c
(chosen from the design, not from the data), exact binomial intervals for
their q_c with a Bonferroni split, and a linear programme over all
distributions of EPG consistent with those intervals; the limits are the
smallest and largest fraction at or above t. Uncertainty of recovery and k
from the spiked samples is included through bootstrap percentiles
(`count_model_ci`): a larger recovery rescales the EPG axis and lowers both
limits, so the lower limit uses the upper end of the recovery range and the
upper limit its lower end. Half of 1 - conf goes to the herd data, half to the
parameters. Assumes one examination per animal, independent examinations and
no false positives.

**Aggregation model.** A fraction of the animals is infected and their EPG
follows a gamma distribution (shape and mean free); counts then follow the
count model of the combination (within-sample variation by Gauss-Laguerre
quadrature). Fitted by maximum likelihood; intervals for prevalence and for
the fraction at or above t are profile-likelihood intervals, with the
parameter uncertainty handled as above. With the fraction at or above t fixed
at f, the profile is maximised over the shape and the prevalence (between f
and 1), the mean following from P(EPG >= t | infected) = f / prevalence, so
every point of the search is a valid model. Calibration: the herd is
simulated `n_boot` times from the fitted model (recovery and k at their
estimates), and the chi-square cutoff of each interval is replaced by the same
quantile of the likelihood-ratio statistic at the generating value, never
below the chi-square cutoff. Model check: deviance of the counts in classes 0,
1, 2-3, 4-7, ..., 64 and more against the fitted model, with a p-value from
the same bootstrap herds, and whether each estimate lies within the limits
without assumptions.

**Survey size.** Every animal at or above t is positive with probability at
least s_1(t), taken at the least favourable end of the 95% parameter range, so
n = ln(1 - conf) / ln(1 - fraction x s_1(t)) whatever the other animals carry.

**Replicate planning.** The CV of the mean of n independent counts is
sqrt((1/mean + 1/k) / n). With `--species` the recovery and k of the count
model are used. k describes variation between independently prepared
samples, so the replicates are separate preparations, not re-readings of one
chamber.

## Validation

`python validation/run_validation.py` writes `validation/REPORT.md` and
`validation/detection_curves.png` (needs `pip install mcmaster-epg[validation]`);
`python validation/run_herd_validation.py` writes `validation/HERD_REPORT.md`
(a few hours on a laptop; `HERD_N_BOOT` sets the bootstrap herds of the
calibration, default 200) and `python validation/run_calibration_validation.py`
writes `validation/CALIBRATION_REPORT.md` (about five minutes); both use the
available cores (`SLURM_CPUS_PER_TASK` on a cluster, otherwise up to 8). On a
cluster, `sbatch validation/helios.sbatch` runs all three with every core of
the job and `SIM_SCALE` times more simulated herds and studies (default 4
there; about eight minutes for the herd script on 192 cores), and `VALIDATIONS="calibration herd"`
selects some of them (`VALIDATIONS=protocol` runs the coverage study of the
sequential protocol, `validation/run_protocol_validation.py`, see "Sequential
reading protocol"; `chain`, `pest` and `intervals` the three studies of its
intervals at the end of this section). The calibration, herd and protocol
reports in `validation/` come from such runs with `SIM_SCALE=4`.
`pytest` runs the tests. Main results (all 16 combinations of egg type, faeces
and counting variant in the paper):

- the published tables are internally consistent: Table 4 limits are
  reproduced from Table 3 in 16 of 16 combinations;
- the two-parameter detection curve is not rejected in 16 of 16 combinations
  (parametric bootstrap of the deviance), and it predicts left-out spiking
  levels with a mean error of 6.8 percentage points, against 5.7 from
  binomial sampling error alone and 11.9 for the textbook Poisson model;
- curves fitted to Ascaris suum in dog faeces predict the independent pig
  samples with errors of 2.9 to 9.4 percentage points;
- the Poisson interval keeps its 95% coverage only if counts are Poisson; at
  the dispersion found for Toxocara canis (k = 4.4) its mean coverage falls to
  74%, while the negative binomial interval keeps 95%.

Calibration (`validation/CALIBRATION_REPORT.md`; 2000 simulated spiking
studies per row, true recovery 0.40 to 0.74, k from 1.5 to Poisson; Monte
Carlo SE 0.5% at 95%):

- with eight levels of 20 samples, the 95% intervals of recovery, k, LOD50
  and LOD95 contain the truth in 94.4% to 98.0% of studies, and the 98.75%
  ranges used by the herd calculations in 98.3% to 99.5%;
- with five levels of 10 samples, the 95% interval of recovery contains it in
  93.8% to 95.4% and its 98.75% range in 98.5% to 98.6%; the other intervals
  stay at 94.3% or more;
- LOD95 from the count model keeps 94.3% or more, while the detection curve
  fitted to positive results alone falls to 91.7%, which is why the count
  model gives the limits and the curve is only a check.

Herd results (`validation/HERD_REPORT.md`; simulated herds of 30 and 100
animals, 400 to 1200 herds per row, with recovery and k redrawn for every herd
from a bootstrap of the spiking design):

- limits without assumptions contain the true fraction in at least 99.7% of
  herds in every scenario, including the least favourable distributions; they
  are wide (mean width 0.38 to 1.00 with 100 animals), and 0 to 0.53 of that
  width remains even with unlimited animals, because a single McMaster count
  cannot place animals near the threshold on one side of it;
- under the gamma aggregation model, when the model holds, the intervals are
  narrower (mean width 0.19 to 0.58 with 100 animals) with bias below 0.05,
  and contain the true fraction in 0.975 to 0.998 of herds with 30 animals
  (0.978 to 0.998 with the bootstrap calibration) and 0.985 to 0.998 with
  100 (up to 1.0.1 a search error made them too narrow with 30 animals,
  coverage 0.909 to 0.959);
- the model check rejects 4.0% to 6.1% of herds where the model holds (target
  5%) and every bimodal herd (30% free, 50% at 45 EPG, 20% at 3000), where the
  estimate is biased by up to 0.29 and the intervals miss the truth; a herd
  with 30% of animals exactly at the threshold is not detected (rejection 4.5%
  to 6.2%), and there the coverage at the threshold falls to 0.80 to 0.92, so
  compare the model with the limits without assumptions;
- prevalence of infection under the aggregation model: coverage 0.978 to
  0.994 where the model holds, but the upper limit is 100% in 61% to 98% of
  those herds;
- the mean EPG interval covers the truth in at least 98.3% of herds, with a
  median estimate within 10% of the truth;
- planned survey sizes find a positive in at least 95.3% of least favourable
  herds (target 95%; Monte Carlo SE 0.1%).

A model limit equal to the published one is not a usable criterion: the
published limit is read from 20 replicates on a grid of eight levels, and even
an exactly true curve would match it in only about 9 of 16 combinations
(simulation). The fitted curve matches it in 10 of 16 and is within one level
in 16 of 16.

Three further studies examine the intervals of the sequential reading
protocol. They use the package without changing it (the interval of
`sequential_epg` is the same before and after) and compute coverage exactly,
from every record above a small probability (the chain study and the
comparison of intervals also by Monte Carlo, as a check); shared code is in
`validation/protocol_study_common.py`.

Full chain with estimated profiles (`validation/PROTOCOL_CHAIN_REPORT.md`,
`validation/run_protocol_chain_validation.py`; 1520 simulated spiking studies
in the 2013 design, 240 for each built-in combination, the rest for two
stress cases and grids read on separate fillings; each study fitted as the
built-in profiles are, with 1000 bootstrap refits per profile; true EPG 10 to
400, conf 0.90, 0.95 and 0.975). The spiking studies and the field samples
are simulated from the same count model that is fitted (negative binomial
counts in the chamber and on the slide, the grid count a binomial share of
the chamber count), so the results hold under that model. They cover six
true EPG values (10, 25, 50, 100, 200 and 400), the parameter values of the
four built-in combinations and two stress cases (dispersion k = 1, and
Poisson counts):

- all hard checks pass, among them the equality of the study's interval with
  `sequential_epg` and the agreement of exact and simulated coverage;
- with profiles estimated from a finite spiking study the current interval
  is conservative: coverage 0.9934 to 0.9991 at conf 0.95 for the four
  combinations (0.9830 to 0.9965 at 0.90, 0.9977 to 0.9998 at 0.975), never
  below conf - 0.01 for any case, and 0.9948 or more at 0.95 when the grids
  are read on separate fillings. At 95% its mean width is 1.44 to 1.68 times
  that with known parameters for *A. suum* in pig faeces, 1.51 to 1.75 for
  *Trichuris* and *A. suum* in dog faeces and 2.35 to 2.97 for *T. canis*;
- less conservative variants were evaluated in the study only, against a
  rule fixed before the run (mean coverage minus two standard errors at
  least conf - 0.01, conf - 0.02 at 10 EPG; stages with at least 20% of the
  samples at least conf - 0.05; mean width at most 0.90 of the current, the
  mean taken over all six cases and EPG values). Larger tails with narrower
  parameter ranges than the current split of 1 - conf (E2 to E4), the
  plug-in interval without parameter ranges (E5) and a Wilks interval with
  the current split (W0) met the rule at all three levels; a Wilks interval
  at the full level with ranges at level 1 - 2(1 - conf) did not;
- widths relative to the current interval at conf 0.95, as the mean of the
  ratios in section 6 of the report over the six EPG values and the four
  built-in combinations: E2 0.77, E3 0.73, E4 0.68, E5 0.57, W0 0.77 (E3
  0.59 for *T. canis* and 0.76 to 0.79 for the others, E5 0.37 and 0.62 to
  0.66). The report's summary over all six cases (E2 to E4 0.61 to 0.70, E5
  0.50, W0 0.69) is lower because of the stress case with k = 1, where the
  current interval is very wide and the mean ratios are 0.06 to 0.25;
- the rule ranks the plug-in interval E5 first. This ranking is a result of
  the study under its rule, not a recommendation, and the package keeps its
  interval. E5 ignores the uncertainty of the parameters and of p by
  construction; in the chain the fitted p stays close to the true one
  (standard deviation 0.0149 to 0.0202 for the four combinations), while
  with known parameters a wrong p gives a coverage of 0.872 to 0.894 at
  200 EPG in the examples under "Sequential reading protocol", and the
  lowest mean coverage of E5 is 0.9539 at conf 0.95 (*T. canis*, 400 EPG).

The chain report was made with the scripts as they were before the later
changes to the likelihood-ratio functions of the shared module; the chain
study does not use those functions, and its quick-mode report is unchanged
with the current scripts.

The share p of the chamber's eggs in the two grids
(`validation/PROTOCOL_P_REPORT.md`, `validation/run_protocol_p_validation.py`;
2000 bootstrap replicates per estimate):

- p is estimated from the recovery ratio of the built-in profiles (the
  derived p, with a bootstrap of the paired 2013 design), from the grid
  positives among the chamber-positive fillings of the 2013 data (the
  chamber refitted in each bootstrap replicate), and from the literature
  data in `validation/literature/data/` (gastrointestinal nematode eggs in
  cattle, sheep and horse faeces): the share of grid eggs among the
  chamber eggs in Amadesi et al. (2020) is 0.3156 (0.2780 to 0.3551) and
  0.3240 (0.2859 to 0.3640), the recovery ratios of Amadesi et al. (2020) and
  Bosco et al. (2018) 0.3072 to 0.3220; Grandi et al. (2025) read only the
  grids and say nothing about p;
- recommended p and range per combination (range: the bootstrap intervals of
  both 2013 estimates together):

  | Combination | Derived p | p from grid positives | Recommended p | Range |
  | --- | --- | --- | --- | --- |
  | *T. canis*, dog | 0.3203 | 0.4065 | 0.3634 | 0.2808 to 0.5032 |
  | *Trichuris*, dog | 0.3451 | 0.3193 | 0.3451 | 0.2592 to 0.4059 |
  | *A. suum*, dog | 0.4093 | 0.3774 | 0.4093 | 0.3005 to 0.4803 |
  | *A. suum*, pig | 0.4088 | 0.3779 | 0.4088 | 0.3059 to 0.4827 |

  For *T. canis* the derived p lies below the interval from the grid
  positives (0.3324 to 0.5032), so the midpoint of the two is recommended;
  elsewhere the derived p is. Two reference values, computed from the
  constants in `mcmaster_epg.factors`: nominal factors 15/50, 0.3 (the
  factor 15 implies 1.0 ml counted, the two grids 0.30 ml); geometric
  (volume), two grids 0.30 ml in a chamber of 1.5 ml with the eggs spread
  evenly, 0.2, below every range. The 2013 estimates in the table (0.3193
  to 0.4093) exceed both references; 0.3 lies inside the ranges for
  *T. canis* and *Trichuris* and below those for *A. suum*. The literature
  values (0.3072 to 0.3240) lie inside every range, but for *A. suum* they
  are below the 2013 estimates (0.3774 to 0.4093), by about 0.09 at the
  recommended p;
- the bootstrap intervals of p contain the true value in 0.9000 to 0.9625 of
  simulated studies (nominal 0.95);
- with the parameter ranges of the built-in profiles and conf 0.95, the
  coverage of `sequential_epg` with the derived p stays at 0.9831 or more
  over the recommended range of the true p (its ends and the values checked
  inside it; lowest for *T. canis* at 400 EPG, 0.9855 to 0.9914 for the
  other combinations); averaged over the bootstrap distribution of p it is
  at least 0.9934. Far outside the range it can fall further, to 0.8464 for
  *A. suum* in pig faeces at 400 EPG when the true p is 0.15.

Comparison of interval constructions (`validation/PROTOCOL_INTERVALS_REPORT.md`,
`validation/run_protocol_interval_comparison.py`; exact coverage at 128 true
EPG values from 2 to 800 for the nominal protocol and the four combinations
with known parameters, at 48 values with the built-in ranges; E is the
estimate-ordered interval of `sequential_epg`, W the Wilks profile-likelihood
interval, LR the likelihood-ratio ordered exact interval on a grid of log
EPG, and Ec, Wc and Lc their versions with one constant tuned so that the
lowest coverage is 0.95):

- with known parameters E never falls below conf (lowest coverage at 0.95:
  0.9524 to 0.9549 for the five protocols, mean 0.9803 to 0.9831); W
  undercovers (lowest 0.8351 to 0.8479, below 0.95 at 25 to 38 of the 128
  EPG values, and down to 0.6774 at conf 0.90); LR keeps conf (lowest 0.9501
  to 0.9511) and is narrower, with a geometric mean width of 0.843 to 0.908
  of that of E (W 0.710 to 0.837);
- at the same lowest coverage of 0.95 the width relative to E is 0.967 to
  0.987 for Ec, 0.840 to 0.908 for Lc and 1.057 to 1.101 for Wc;
- the narrower LR interval covers the records of a single stage less well:
  among stages with at least 20% of the samples its lowest conditional
  coverage is 0.8309 to 0.8601, that of E 0.8824 to 0.9396;
- with the built-in ranges (conf 0.95, limits over the corners of the ranges
  as in the package) E covers at least 0.9908 when the parameters are at
  their point values and at least 0.9791 at the corners (bound 0.975), LR at
  least 0.9761 at the corners, while W falls to 0.9377 at the point values
  and 0.9177 at a corner; tuned to a lowest coverage of 0.95 over the point
  values and four corners, Ec is 0.654 to 0.796 of the width of E and Wc
  0.803 to 0.895;
- the LR grid ends at 59890.2 EPG. For *T. canis* in dog faeces with ranges,
  58 stage-1 records (largest probability 7.82e-06) have no finite upper
  limit within the grid: it is censored at the grid end, so their upper
  limit and width are only lower bounds, a practical drawback of LR there.
  The coverage for true EPG up to 800 is not affected; no other protocol has
  censored limits.

`python validation/run_protocol_chain_validation.py`,
`python validation/run_protocol_p_validation.py` and
`python validation/run_protocol_interval_comparison.py` write the three
reports (default `SIM_SCALE=1`). On a cluster
`sbatch --export=ALL,VALIDATIONS=chain validation/helios.sbatch` runs the
chain study in a job of its own (16 min 43 s on 192 cores) and
`VALIDATIONS="pest intervals"` the other two together (1 min 19 s); the
reports in `validation/` come from such runs with `SIM_SCALE=4`. Quick checks
on eight cores: `SIM_SCALE=0.02 CHAIN_CONFS=0.95 CHAIN_N_BOOT=40` for the
chain (about four minutes), `SIM_SCALE=0.05` for p and
`INTERVALS_FAST=1 SIM_SCALE=0.05` for the comparison (about one and a half
minutes each). `WORKERS` sets the number of processes (the reports do not
depend on it) and `CHAIN_OUT`, `PEST_OUT` and `INTERVALS_OUT` other output
files.

## Limits

- The built-in profiles come from one laboratory, one chamber type, three egg
  types and dog and pig faeces, and are fitted to the published summary
  tables; for other procedures calibrate from your own spiked samples or enter
  published parameters.
- Detection limits above the highest spiking level (300 eggs/g for the
  built-in profiles) are extrapolations; the output marks them.
- Calibration assumes that recovery does not depend on the level (tested) and
  that each spiked sample was prepared independently (not tested).
- Herd results assume one examination per animal, independent examinations,
  no false positives, and animals whose egg loss resembles that of the spiked
  samples. The aggregation model is checked by a goodness-of-fit test, which
  detects strongly bimodal herds but not every departure from the gamma
  distribution; the limits without assumptions need no such check.

## How to cite

Kochanowski M, Dąbrowska J. mcmaster-epg, version 1.1.0. Zenodo; 2026.
https://doi.org/10.5281/zenodo.24662026 (concept DOI; resolves to the latest
version). See `CITATION.cff`.

Kochanowski M, Dąbrowska J, Karamon J, Cencek T, Osiński Z. Analysis of the
accuracy and precision of the McMaster method in detection of the eggs of
*Toxocara* and *Trichuris* species (Nematoda) in dog faeces. Folia
Parasitologica 2013; 60(3): 264-272. https://doi.org/10.14411/fp.2013.030

## Licence

MIT
