fecpool 1.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fecpool/__init__.py ADDED
@@ -0,0 +1,11 @@
1
+ """Pooled faecal samples: how many pools, of how many animals, to find parasite eggs."""
2
+
3
+ __version__ = "1.1.0"
4
+
5
+ from .core import (ceiling, compare_pool_sizes, detection, excluded_prevalence, plan_detection,
6
+ pool_detection, pools_needed)
7
+ from .method import method_profile
8
+ from .pigs import farm_sheet, target_group
9
+
10
+ __all__ = ["ceiling", "compare_pool_sizes", "detection", "excluded_prevalence", "plan_detection",
11
+ "pool_detection", "pools_needed", "method_profile", "farm_sheet", "target_group", "__version__"]
fecpool/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
fecpool/cli.py ADDED
@@ -0,0 +1,205 @@
1
+ """Command line: fecpool plan | check | negative | farm."""
2
+
3
+ import argparse
4
+ import json
5
+ import sys
6
+
7
+ from . import __version__
8
+ from .core import (ceiling, compare_pool_sizes, excluded_prevalence, plan_detection)
9
+ from .method import SPECIES, VARIANTS, describe, method_profile
10
+ from .pigs import AGE_GROUPS, PARASITES, PASSAGE_IN_PIGLETS, SAMPLES, farm_sheet, target_group
11
+
12
+
13
+ class _Parser(argparse.ArgumentParser):
14
+ def error(self, message):
15
+ raise ValueError(message)
16
+
17
+
18
+ def _table(rows):
19
+ widths = [max(len(row[c]) for row in rows) for c in range(len(rows[0]))]
20
+ return [" ".join(cell.ljust(w) for cell, w in zip(row, widths)).rstrip() for row in rows]
21
+
22
+
23
+ def _pct(x):
24
+ return f"{100 * x:.3g}%"
25
+
26
+
27
+ def _condition(args):
28
+ return f"at least {_pct(args.prevalence)} of the animals excrete {args.threshold:g} EPG or more"
29
+
30
+
31
+ def _add_method(p, per_parasite=False):
32
+ g = p.add_argument_group("counting method")
33
+ g.add_argument("--variant", choices=VARIANTS,
34
+ help="Raynaud's modification: one_grid, two_grids, whole_chamber, flotation_slide (factors 100, 50, 15, 7)")
35
+ g.add_argument("--multiplier", type=float, help="multiplication factor of one count, for any other method")
36
+ if per_parasite:
37
+ return
38
+ g.add_argument("--species", choices=SPECIES, help="built-in validated egg type (with --variant)")
39
+ g.add_argument("--matrix", choices=("pig", "dog"), default="pig", help="faeces of the built-in profile (default pig)")
40
+ g.add_argument("--profile", help="method profile (JSON) written by mcmaster-epg calibrate or profile")
41
+ g.add_argument("--recovery", type=float, help="share of eggs recovered, entered by hand")
42
+ g.add_argument("--recovery-ci", type=float, nargs=2, metavar=("LOW", "HIGH"), help="its 95%% interval")
43
+ g.add_argument("--k", type=float, help="dispersion of counts between samples, entered by hand")
44
+ g.add_argument("--k-ci", type=float, nargs=2, metavar=("LOW", "HIGH"), help="its 95%% interval")
45
+
46
+
47
+ def _add_design(p, prevalence=True):
48
+ if prevalence:
49
+ p.add_argument("--prevalence", type=float, required=True,
50
+ help="share of animals to be found, between 0 and 1 (for example 0.1)")
51
+ p.add_argument("--threshold", type=float, required=True, help="EPG that these animals excrete at least")
52
+ p.add_argument("--conf", type=float, default=0.95, help="probability or confidence level (default 0.95)")
53
+ p.add_argument("--json", action="store_true", help="print the result as JSON")
54
+
55
+
56
+ def _model(args):
57
+ return method_profile(args.variant, args.multiplier, args.species, args.matrix, args.profile,
58
+ args.recovery, args.k, args.recovery_ci, args.k_ci)
59
+
60
+
61
+ def _plan(args):
62
+ model = _model(args)
63
+ rows = compare_pool_sizes(model, args.pool_size, args.prevalence, args.threshold, args.conf, args.group_size)
64
+ top = ceiling(model, args.prevalence, args.threshold)
65
+ result = {"command": "plan", "method": describe(model), "prevalence": args.prevalence,
66
+ "threshold": args.threshold, "conf": args.conf, "group_size": args.group_size,
67
+ "rows": rows, "ceiling": top, "ceiling_epg": args.prevalence * args.threshold}
68
+ lines = ["Method: " + describe(model),
69
+ f"Aim: eggs found with probability {args.conf:g} if {_condition(args)}"]
70
+ if args.group_size:
71
+ lines.append(f"Group of {args.group_size} animals, pools drawn without replacement")
72
+ table = [["Animals per pool", "One pool positive", "Pools needed", "Animals sampled", "Probability reached"]]
73
+ for r in rows:
74
+ none = r["pools"] is None
75
+ table.append([str(r["pool_size"]), f"{r['pool_detection']:.3f}", "not reachable" if none else str(r["pools"]),
76
+ "-" if none else str(r["animals"]), "-" if none else f"{r['detection']:.3f}"])
77
+ lines += _table(table)
78
+ lines.append(f"One pool of very many animals is positive with probability {top:.3f} at most: "
79
+ f"its EPG tends to {args.prevalence * args.threshold:g}")
80
+ return result, lines
81
+
82
+
83
+ def _check(args):
84
+ model = _model(args)
85
+ p = plan_detection(model, args.pools, args.pool_size, args.prevalence, args.threshold, args.group_size)
86
+ result = {"command": "check", "method": describe(model), "pools": args.pools, "pool_size": args.pool_size,
87
+ "prevalence": args.prevalence, "threshold": args.threshold, "group_size": args.group_size,
88
+ "detection": p}
89
+ lines = ["Method: " + describe(model),
90
+ f"{args.pools} pools of {args.pool_size}: eggs found with probability at least {p:.3f} if {_condition(args)}"]
91
+ return result, lines
92
+
93
+
94
+ def _negative(args):
95
+ model = _model(args)
96
+ limit = excluded_prevalence(model, args.pools, args.pool_size, args.threshold, args.conf, args.group_size)
97
+ result = {"command": "negative", "method": describe(model), "pools": args.pools, "pool_size": args.pool_size,
98
+ "threshold": args.threshold, "conf": args.conf, "group_size": args.group_size, "upper_limit": limit}
99
+ head = f"All {args.pools} pools of {args.pool_size} negative: "
100
+ if limit is None:
101
+ tail = (f"nothing is excluded at {args.threshold:g} EPG; even if every animal excreted that much, "
102
+ f"all pools would be negative with probability above {1 - args.conf:.3g}")
103
+ else:
104
+ tail = (f"at most {_pct(limit)} of the animals excrete {args.threshold:g} EPG or more "
105
+ f"({_pct(args.conf)} confidence)")
106
+ return result, ["Method: " + describe(model), head + tail]
107
+
108
+
109
+ def _farm(args):
110
+ sheet = farm_sheet(args.prevalence, args.threshold, args.pool_size, args.variant, args.multiplier, args.conf)
111
+ result = {"command": "farm", "prevalence": args.prevalence, "threshold": args.threshold, "conf": args.conf,
112
+ "pool_size": args.pool_size, **sheet}
113
+ lines = [f"Aim: each parasite found with probability {args.conf:g} if {_condition(args)} in the age group sampled",
114
+ f"Pools of {args.pool_size} animals", ""]
115
+ table = [["Age group", "Pools", "Animals", "Parasites looked for"]]
116
+ for g in sheet["age_groups"]:
117
+ table.append([g["age_group"], "not reachable" if g["pools"] is None else str(g["pools"]),
118
+ "-" if g["pools"] is None else str(g["animals"]), ", ".join(g["parasites"])])
119
+ lines += _table(table) + [""]
120
+ table = [["Parasite", "Age group", "Pools", "Method profile"]]
121
+ for r in sheet["parasites"]:
122
+ table.append([r["parasite"], r["age_group"], "not reachable" if r["pools"] is None else str(r["pools"]),
123
+ "validated for pig faeces" if r["validated_profile"] else "nominal (detection overstated)"])
124
+ lines += _table(table)
125
+ lines += ["", "Age groups: the group with most positive samples in Kochanowski et al. 2017 (J Vet Res 61:459)."]
126
+ return result, lines
127
+
128
+
129
+ def _targets(args):
130
+ result = {"command": "targets", "age_groups": list(AGE_GROUPS), "samples": list(SAMPLES),
131
+ "parasites": [{"parasite": name, "target": target_group(name), **values,
132
+ "passage_in_piglets": name in PASSAGE_IN_PIGLETS}
133
+ for name, values in PARASITES.items()]}
134
+ table = [["Parasite"] + [f"{g} (n={n})" for g, n in zip(AGE_GROUPS, SAMPLES)] + ["Sample"]]
135
+ for name, values in PARASITES.items():
136
+ cells = [f"{pct:g}%" + ("" if mean is None else f", {mean:g}")
137
+ for pct, mean in zip(values["positive_pct"], values["mean_count"])]
138
+ table.append([name] + cells + [target_group(name)])
139
+ lines = ["Positive samples and mean count of the positive samples (eggs or oocysts per gram), by age group",
140
+ "Kochanowski et al. 2017, J Vet Res 61:459, 70 farms in Poland", ""] + _table(table)
141
+ lines += ["", "Eggs of " + ", ".join(PASSAGE_IN_PIGLETS) + " in suckling piglets were attributed in the article",
142
+ "to passage of ingested eggs, not to infection of the piglets."]
143
+ return result, lines
144
+
145
+
146
+ def _parser():
147
+ parser = _Parser(prog="fecpool",
148
+ description="Pooled faecal samples: how many pools, of how many animals, to find parasite eggs.")
149
+ parser.add_argument("--version", action="version", version=__version__)
150
+ sub = parser.add_subparsers(dest="command", required=True, parser_class=_Parser)
151
+
152
+ p = sub.add_parser("plan", help="pools needed, for several pool sizes")
153
+ p.add_argument("--pool-size", type=int, nargs="+", default=[1, 3, 5, 10, 20], help="animals per pool (default 1 3 5 10 20)")
154
+ p.add_argument("--group-size", type=int, help="animals in the group (default: a large group)")
155
+ _add_design(p)
156
+ _add_method(p)
157
+ p.set_defaults(run=_plan)
158
+
159
+ p = sub.add_parser("check", help="probability that a given plan finds eggs")
160
+ p.add_argument("--pools", type=int, required=True, help="number of pooled samples")
161
+ p.add_argument("--pool-size", type=int, required=True, help="animals per pool")
162
+ p.add_argument("--group-size", type=int, help="animals in the group (default: a large group)")
163
+ _add_design(p)
164
+ _add_method(p)
165
+ p.set_defaults(run=_check)
166
+
167
+ p = sub.add_parser("negative", help="what all-negative pools exclude")
168
+ p.add_argument("--pools", type=int, required=True, help="number of pooled samples, all negative")
169
+ p.add_argument("--pool-size", type=int, required=True, help="animals per pool")
170
+ p.add_argument("--group-size", type=int, help="animals in the group (default: a large group)")
171
+ _add_design(p, prevalence=False)
172
+ _add_method(p)
173
+ p.set_defaults(run=_negative)
174
+
175
+ p = sub.add_parser("farm", help="sampling sheet of a pig farm: pools per age group for five parasites")
176
+ p.add_argument("--pool-size", type=int, default=5, help="animals per pool (default 5)")
177
+ _add_design(p)
178
+ _add_method(p, per_parasite=True)
179
+ p.set_defaults(run=_farm)
180
+
181
+ p = sub.add_parser("targets", help="age groups and counts by parasite in the Polish survey")
182
+ p.add_argument("--json", action="store_true", help="print the result as JSON")
183
+ p.set_defaults(run=_targets)
184
+ return parser
185
+
186
+
187
+ def run(argv):
188
+ """Run a command; returns (result dict, text). Raises ValueError on wrong input."""
189
+ args = _parser().parse_args(argv)
190
+ try:
191
+ result, lines = args.run(args)
192
+ except (OSError, TypeError, KeyError) as error:
193
+ raise ValueError(str(error)) from None
194
+ return result, "\n".join(lines)
195
+
196
+
197
+ def main(argv=None):
198
+ argv = sys.argv[1:] if argv is None else argv
199
+ try:
200
+ result, text = run(argv)
201
+ except ValueError as error:
202
+ print(f"fecpool: {error}", file=sys.stderr)
203
+ return 2
204
+ print(json.dumps(result, indent=2) if "--json" in argv else text)
205
+ return 0
fecpool/core.py ADDED
@@ -0,0 +1,180 @@
1
+ """Finding parasite eggs in pooled (composite) faecal samples.
2
+
3
+ A pooled sample is made of equal amounts of faeces from `pool_size` different
4
+ animals, mixed, and counted once. The design question is the one of a survey
5
+ for freedom from infection: if at least a share `prevalence` of the animals of
6
+ a group excretes at least `threshold` eggs per gram (EPG), how likely is it
7
+ that eggs are found?
8
+
9
+ No distribution of EPG among the animals is assumed. A pool that holds j such
10
+ animals has a true EPG of at least j * threshold / pool_size, whatever the
11
+ other animals excrete, and the probability of counting at least one egg rises
12
+ with the true EPG. The least favourable group is therefore the one in which
13
+ exactly that share of animals excretes exactly `threshold` and the others
14
+ nothing; every probability below is computed for it and is a lower limit for
15
+ any other group that meets the condition.
16
+
17
+ The counting method is a `mcmaster_epg.MethodProfile` (factor, recovery of
18
+ eggs, dispersion between samples). When the profile carries the uncertainty of
19
+ recovery and dispersion, the least favourable end of their 95% ranges is used.
20
+ """
21
+
22
+ import math
23
+
24
+ from scipy.optimize import brentq
25
+ from scipy.stats import binom, hypergeom
26
+
27
+ #: level of the parameter ranges of a profile at which detection is taken
28
+ RANGE_LEVEL = 0.95
29
+
30
+
31
+ def detection(model, epg):
32
+ """Probability that at least one egg is counted in a sample of true EPG `epg`
33
+ (lowest value over the 95% ranges of recovery and dispersion, if known)."""
34
+ if epg <= 0:
35
+ return 0.0
36
+ if model.has_ranges:
37
+ return model.tail_range(1, epg, RANGE_LEVEL)[0]
38
+ return model.tail(1, epg)
39
+
40
+
41
+ def _check(pool_size, prevalence, threshold, group_size, pools=1):
42
+ if pool_size < 1 or pools < 1:
43
+ raise ValueError("the number of pools and of animals in a pool must be at least 1")
44
+ if not 0 <= prevalence <= 1:
45
+ raise ValueError("prevalence must be between 0 and 1")
46
+ if not threshold > 0:
47
+ raise ValueError("the EPG threshold must be positive")
48
+ if group_size is not None and pools * pool_size > group_size:
49
+ raise ValueError(f"{pools} pools of {pool_size} need {pools * pool_size} animals, "
50
+ f"the group has {group_size}")
51
+
52
+
53
+ def carriers(prevalence, group_size):
54
+ """Smallest number of animals that makes up the share `prevalence` of the group."""
55
+ return math.ceil(prevalence * group_size - 1e-9)
56
+
57
+
58
+ def _miss(model, pool_size, threshold):
59
+ """P(no egg counted) for a pool with j = 0..pool_size animals at the threshold."""
60
+ return [1 - detection(model, j * threshold / pool_size) for j in range(pool_size + 1)]
61
+
62
+
63
+ def pool_detection(model, pool_size, prevalence, threshold, group_size=None):
64
+ """Probability that one pool is positive.
65
+
66
+ The number of animals at or above the threshold in the pool is binomial,
67
+ or hypergeometric when the size of the group is given.
68
+ """
69
+ _check(pool_size, prevalence, threshold, group_size)
70
+ miss = _miss(model, pool_size, threshold)
71
+ if group_size is None:
72
+ dist = binom(pool_size, prevalence)
73
+ else:
74
+ dist = hypergeom(group_size, carriers(prevalence, group_size), pool_size)
75
+ return float(sum(dist.pmf(j) * (1 - miss[j]) for j in range(1, pool_size + 1)))
76
+
77
+
78
+ def _all_negative(model, pools, pool_size, threshold, group_size, n_carriers):
79
+ """P(every pool negative) when the pools are drawn without replacement from a
80
+ group of `group_size` animals of which `n_carriers` are at the threshold."""
81
+ miss = _miss(model, pool_size, threshold)
82
+ state = {n_carriers: 1.0}
83
+ for done in range(pools):
84
+ left = group_size - done * pool_size
85
+ nxt = {}
86
+ for c, weight in state.items():
87
+ dist = hypergeom(left, c, pool_size)
88
+ for j in range(min(c, pool_size) + 1):
89
+ p = dist.pmf(j)
90
+ if p > 0:
91
+ nxt[c - j] = nxt.get(c - j, 0.0) + weight * p * miss[j]
92
+ state = nxt
93
+ return float(sum(state.values()))
94
+
95
+
96
+ def plan_detection(model, pools, pool_size, prevalence, threshold, group_size=None):
97
+ """Probability that at least one of `pools` pooled samples is positive.
98
+
99
+ Pools hold different animals. Without `group_size` the group is taken as
100
+ large; with it the pools are drawn from the group without replacement.
101
+ """
102
+ _check(pool_size, prevalence, threshold, group_size, pools)
103
+ if group_size is None:
104
+ p = pool_detection(model, pool_size, prevalence, threshold)
105
+ return 1 - (1 - p) ** pools
106
+ return 1 - _all_negative(model, pools, pool_size, threshold, group_size,
107
+ carriers(prevalence, group_size))
108
+
109
+
110
+ def pools_needed(model, pool_size, prevalence, threshold, conf=0.95, group_size=None):
111
+ """Smallest number of pools that finds eggs with probability `conf`.
112
+
113
+ None when no number of pools reaches it: nothing can be detected at this
114
+ threshold, or the whole group is used up first.
115
+ """
116
+ _check(pool_size, prevalence, threshold, group_size)
117
+ if not 0 < conf < 1:
118
+ raise ValueError("conf must be between 0 and 1")
119
+ if group_size is None:
120
+ p = pool_detection(model, pool_size, prevalence, threshold)
121
+ if p <= 0:
122
+ return None
123
+ if p >= 1:
124
+ return 1
125
+ return max(1, math.ceil(math.log(1 - conf) / math.log1p(-p) - 1e-12))
126
+ for pools in range(1, group_size // pool_size + 1):
127
+ if plan_detection(model, pools, pool_size, prevalence, threshold, group_size) >= conf:
128
+ return pools
129
+ return None
130
+
131
+
132
+ def ceiling(model, prevalence, threshold):
133
+ """Detection by one pool of very many animals: its EPG tends to prevalence x threshold,
134
+ so mixing in more animals cannot raise the detection of a single pool above this."""
135
+ return detection(model, prevalence * threshold)
136
+
137
+
138
+ def excluded_prevalence(model, pools, pool_size, threshold, conf=0.95, group_size=None):
139
+ """Upper confidence limit of the share of animals with EPG >= threshold when
140
+ every one of `pools` pooled samples was negative.
141
+
142
+ Returns the share; a larger share would have given a positive pool with
143
+ probability above `conf`. None when even a group in which every animal is
144
+ at the threshold would often be missed, so the negative result excludes
145
+ nothing.
146
+ """
147
+ _check(pool_size, 0.0, threshold, group_size, pools)
148
+ if not 0 < conf < 1:
149
+ raise ValueError("conf must be between 0 and 1")
150
+ alpha = 1 - conf
151
+ if group_size is not None:
152
+ for c in range(1, group_size + 1):
153
+ if _all_negative(model, pools, pool_size, threshold, group_size, c) < alpha:
154
+ return (c - 1) / group_size
155
+ return None
156
+
157
+ def gap(prevalence):
158
+ return (1 - pool_detection(model, pool_size, prevalence, threshold)) ** pools - alpha
159
+
160
+ if gap(1.0) >= 0:
161
+ return None
162
+ return float(brentq(gap, 0.0, 1.0, xtol=1e-10))
163
+
164
+
165
+ def compare_pool_sizes(model, pool_sizes, prevalence, threshold, conf=0.95, group_size=None):
166
+ """One row per pool size: detection of one pool, pools needed, animals sampled and counts."""
167
+ rows = []
168
+ for size in pool_sizes:
169
+ if group_size is not None and size > group_size:
170
+ continue
171
+ needed = pools_needed(model, size, prevalence, threshold, conf, group_size)
172
+ rows.append({
173
+ "pool_size": size,
174
+ "pool_detection": pool_detection(model, size, prevalence, threshold, group_size),
175
+ "pools": needed,
176
+ "animals": None if needed is None else needed * size,
177
+ "detection": None if needed is None else
178
+ plan_detection(model, needed, size, prevalence, threshold, group_size),
179
+ })
180
+ return rows
fecpool/method.py ADDED
@@ -0,0 +1,53 @@
1
+ """The counting method as a mcmaster-epg method profile."""
2
+
3
+ import math
4
+
5
+ from mcmaster_epg import builtin_profile, load_profile, manual_profile
6
+ from mcmaster_epg.factors import VARIANTS, raynaud_factor
7
+ from mcmaster_epg.profile import nominal_profile
8
+
9
+ SPECIES = ("ascaris_suum", "trichuris", "toxocara_canis")
10
+
11
+
12
+ def method_profile(variant=None, multiplier=None, species=None, matrix="pig", profile=None,
13
+ recovery=None, k=None, recovery_ci=None, k_ci=None):
14
+ """Method profile from the same choices as the mcmaster-epg command line.
15
+
16
+ The factor comes from `variant` (Raynaud's modification) or `multiplier`;
17
+ egg loss and dispersion from a profile file, a built-in validated
18
+ combination (`species` with `variant`) or values entered by hand. Without
19
+ any of these the nominal method is returned: no egg loss, Poisson counts.
20
+ """
21
+ manual = any(v is not None for v in (recovery, k, recovery_ci, k_ci))
22
+ if sum((profile is not None, species is not None, manual)) > 1:
23
+ raise ValueError("give only one of a profile file, a built-in species or recovery and k")
24
+ if variant is not None and multiplier is not None:
25
+ raise ValueError("give either the variant or the multiplication factor")
26
+ if profile is not None:
27
+ if variant is not None or multiplier is not None:
28
+ raise ValueError("a profile file holds its own factor; leave out the variant and the factor")
29
+ return load_profile(profile)
30
+ if variant is None and multiplier is None:
31
+ raise ValueError("give the variant, the multiplication factor or a profile file")
32
+ if species is not None:
33
+ if variant is None:
34
+ raise ValueError("a built-in species needs a variant")
35
+ return builtin_profile(variant, species, matrix, strict=True)
36
+ factor = raynaud_factor(variant) if variant is not None else multiplier
37
+ if manual:
38
+ return manual_profile(factor, 1.0 if recovery is None else recovery,
39
+ math.inf if k is None else k,
40
+ tuple(recovery_ci) if recovery_ci else None,
41
+ tuple(k_ci) if k_ci else None)
42
+ return nominal_profile(factor, variant=variant)
43
+
44
+
45
+ def describe(model):
46
+ """One line on the method, saying whether egg loss is accounted for."""
47
+ k = "Poisson counts" if math.isinf(model.k) else f"dispersion k {model.k:.3g}"
48
+ text = f"factor {model.factor:g}, recovery {model.recovery:.3g}, {k}"
49
+ if model.source == "nominal":
50
+ return text + " (nominal method: no egg loss assumed, detection is overstated)"
51
+ if model.has_ranges:
52
+ return text + " (least favourable end of the 95% ranges of recovery and dispersion used)"
53
+ return text + " (entered values taken as known)"
fecpool/pigs.py ADDED
@@ -0,0 +1,78 @@
1
+ """Which age group to sample for which parasite on a pig farm.
2
+
3
+ Source: Kochanowski M, Karamon J, Dabrowska J, Dors A, Czyzewska-Dors E,
4
+ Cencek T. Occurrence of intestinal parasites in pigs in Poland - the influence
5
+ of factors related to the production system. J Vet Res 2017;61(4):459-466.
6
+ https://doi.org/10.1515/jvetres-2017-0053 (70 farms, 1,119 samples; values of
7
+ the Results section).
8
+ """
9
+
10
+ from mcmaster_epg import builtin_profile
11
+ from mcmaster_epg.factors import raynaud_factor
12
+ from mcmaster_epg.profile import nominal_profile
13
+
14
+ from .core import pools_needed
15
+
16
+ AGE_GROUPS = ("suckling piglets", "weaners", "fatteners", "sows")
17
+
18
+ #: number of samples examined in each age group (litters for suckling piglets:
19
+ #: faeces of three to five piglets per litter were pooled)
20
+ SAMPLES = (367, 170, 215, 367)
21
+
22
+ #: per parasite: percentage of positive samples and mean count of the positive
23
+ #: samples (eggs or oocysts per gram) in each age group; None = not detected
24
+ PARASITES = {
25
+ "coccidia": {"positive_pct": (14.2, 3.5, 3.7, 6.0), "mean_count": (9378.6, 153.3, 723.8, 4398.0)},
26
+ "Oesophagostomum spp.": {"positive_pct": (13.1, 12.9, 18.1, 51.8), "mean_count": (1424.5, 147.0, 266.9, 957.7)},
27
+ "Ascaris suum": {"positive_pct": (0.5, 1.2, 6.5, 3.8), "mean_count": (113.6, 233.3, 1411.0, 550.5)},
28
+ "Trichuris suis": {"positive_pct": (0.5, 1.2, 1.4, 3.0), "mean_count": (52.5, 32.5, 53.3, 219.7)},
29
+ "Strongyloides spp.": {"positive_pct": (3.3, 1.8, 0.0, 2.5), "mean_count": (867.9, 500.0, None, 2418.6)},
30
+ }
31
+
32
+ #: eggs of these parasites in suckling piglets were attributed in the article to
33
+ #: passage of ingested eggs, because the piglets were younger than the prepatent period
34
+ PASSAGE_IN_PIGLETS = ("Oesophagostomum spp.", "Ascaris suum", "Trichuris suis")
35
+
36
+
37
+ def target_group(parasite):
38
+ """Age group with the highest percentage of positive samples in the article."""
39
+ pct = PARASITES[parasite]["positive_pct"]
40
+ return AGE_GROUPS[pct.index(max(pct))]
41
+
42
+
43
+ def parasite_profile(parasite, variant=None, multiplier=None):
44
+ """Method profile for a parasite in pig faeces and whether it is validated.
45
+
46
+ A validated profile exists only for Ascaris suum eggs read with one of
47
+ Raynaud's variants (Kochanowski et al. 2013); otherwise the nominal method.
48
+ """
49
+ if parasite == "Ascaris suum" and variant is not None:
50
+ return builtin_profile(variant, "ascaris_suum", "pig", strict=True), True
51
+ if variant is not None:
52
+ return nominal_profile(raynaud_factor(variant), variant=variant), False
53
+ return nominal_profile(multiplier), False
54
+
55
+
56
+ def farm_sheet(prevalence, threshold, pool_size, variant=None, multiplier=None, conf=0.95):
57
+ """Sampling sheet of a farm: pools needed per parasite and per age group.
58
+
59
+ One pooled sample is read for all parasites, so an age group needs the
60
+ largest number of pools among the parasites looked for in it.
61
+ """
62
+ if (variant is None) == (multiplier is None):
63
+ raise ValueError("give either the variant or the multiplication factor")
64
+ rows = []
65
+ for parasite in PARASITES:
66
+ model, validated = parasite_profile(parasite, variant, multiplier)
67
+ rows.append({"parasite": parasite, "age_group": target_group(parasite),
68
+ "validated_profile": validated,
69
+ "pools": pools_needed(model, pool_size, prevalence, threshold, conf)})
70
+ groups = []
71
+ for group in AGE_GROUPS:
72
+ mine = [r for r in rows if r["age_group"] == group]
73
+ if not mine:
74
+ continue
75
+ needed = None if any(r["pools"] is None for r in mine) else max(r["pools"] for r in mine)
76
+ groups.append({"age_group": group, "parasites": [r["parasite"] for r in mine], "pools": needed,
77
+ "animals": None if needed is None else needed * pool_size})
78
+ return {"parasites": rows, "age_groups": groups}
@@ -0,0 +1,233 @@
1
+ Metadata-Version: 2.5
2
+ Name: fecpool
3
+ Version: 1.1.0
4
+ Summary: Pooled faecal samples: how many pools, of how many animals, to find parasite eggs with a McMaster count, without assumptions about the distribution of egg counts among animals
5
+ Project-URL: Repository, https://github.com/maciejkochanowski/fecpool
6
+ Project-URL: Homepage, https://maciejkochanowski.github.io/fecpool/
7
+ Project-URL: DOI, https://doi.org/10.5281/zenodo.24699361
8
+ Author: Joanna Dąbrowska
9
+ Author-email: Maciej Kochanowski <maciej.kochanowski@piwet.pulawy.pl>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: McMaster,composite samples,faecal egg count,herd sensitivity,parasitology,pigs,pooled samples,survey design,veterinary
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
17
+ Requires-Python: >=3.10
18
+ Requires-Dist: mcmaster-epg>=1.1.0
19
+ Requires-Dist: scipy>=1.8
20
+ Provides-Extra: test
21
+ Requires-Dist: numpy; extra == 'test'
22
+ Requires-Dist: pytest; extra == 'test'
23
+ Provides-Extra: validation
24
+ Requires-Dist: numpy; extra == 'validation'
25
+ Provides-Extra: web
26
+ Requires-Dist: playwright; extra == 'web'
27
+ Requires-Dist: pytest; extra == 'web'
28
+ Description-Content-Type: text/markdown
29
+
30
+ # fecpool
31
+
32
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.24699361.svg)](https://doi.org/10.5281/zenodo.24699361)
33
+
34
+ Pooled (composite) faecal samples for finding parasite eggs with a McMaster
35
+ count: how many pools, of how many animals each, are needed; how likely a
36
+ given plan is to find eggs; and what all-negative pools exclude. Made for
37
+ pig farms, where faeces are usually pooled by pen or age group, and usable
38
+ for any host.
39
+
40
+ The question is put as in a survey for freedom from infection: *if at least
41
+ 10% of the animals of a group excrete at least 200 eggs per gram (EPG), with
42
+ what probability are eggs found?* No distribution of EPG among the animals is
43
+ assumed. Egg loss and the dispersion of counts come from the method profiles
44
+ of [mcmaster-epg](https://github.com/maciejkochanowski/mcmaster-epg).
45
+
46
+ The age group to sample for each parasite of pigs is taken from Kochanowski
47
+ et al. 2017 (https://doi.org/10.1515/jvetres-2017-0053), the survey of 70
48
+ Polish farms that this software accompanies.
49
+
50
+ ## Run in the browser
51
+
52
+ No installation needed: https://maciejkochanowski.github.io/fecpool/
53
+
54
+ The page runs the fecpool package itself inside the browser (Pyodide,
55
+ WebAssembly), so its results are those of the command line. It has one tab per
56
+ command (`plan`, `check`, `negative`, `farm`, `targets`), shows the result as
57
+ tables and charts with the program output, and gives the equivalent command
58
+ under each result. Nothing you enter or upload leaves your device: the page
59
+ sends no data to any server and uses no cookies or analytics. The first visit
60
+ downloads the Python runtime from cdn.jsdelivr.net (about 10 to 20 seconds;
61
+ later visits use the browser cache).
62
+
63
+ The site is built from `main` by `.github/workflows/pages.yml`, which first
64
+ runs the browser tests in `web/tests/`: every tab is calculated in the page
65
+ and its record compared with that of the command line for the same arguments.
66
+ To run them locally, `pip install .[web]`, `python -m playwright install
67
+ chromium` and `python -m pytest web/tests` (add `--pyodide-dir PATH` to use a
68
+ local copy of Pyodide instead of the CDN).
69
+
70
+ ## Installation
71
+
72
+ ```bash
73
+ pip install git+https://github.com/maciejkochanowski/fecpool
74
+ ```
75
+
76
+ Python 3.10 or later; mcmaster-epg, NumPy and SciPy are installed with it.
77
+
78
+ ## Commands
79
+
80
+ ```bash
81
+ fecpool plan --prevalence 0.1 --threshold 200 --variant whole_chamber --species ascaris_suum
82
+ # Method: factor 15, recovery 0.74, Poisson counts (least favourable end of the 95% ranges of recovery and dispersion used)
83
+ # Aim: eggs found with probability 0.95 if at least 10% of the animals excrete 200 EPG or more
84
+ # Animals per pool One pool positive Pools needed Animals sampled Probability reached
85
+ # 1 0.100 29 29 0.953
86
+ # 3 0.258 11 33 0.963
87
+ # 5 0.353 7 35 0.953
88
+ # 10 0.460 5 50 0.954
89
+ # 20 0.527 5 100 0.976
90
+ # One pool of very many animals is positive with probability 0.600 at most: its EPG tends to 20
91
+
92
+ fecpool check --pools 6 --pool-size 5 --prevalence 0.1 --threshold 200 --variant whole_chamber --species ascaris_suum
93
+ # 6 pools of 5: eggs found with probability at least 0.927 if at least 10% of the animals excrete 200 EPG or more
94
+
95
+ fecpool negative --pools 6 --pool-size 5 --threshold 200 --variant whole_chamber --species ascaris_suum
96
+ # All 6 pools of 5 negative: at most 11.4% of the animals excrete 200 EPG or more (95% confidence)
97
+
98
+ fecpool farm --prevalence 0.1 --threshold 200 --variant whole_chamber --pool-size 5
99
+ # Age group Pools Animals Parasites looked for
100
+ # suckling piglets 7 35 coccidia, Strongyloides spp.
101
+ # fatteners 7 35 Ascaris suum
102
+ # sows 7 35 Oesophagostomum spp., Trichuris suis
103
+
104
+ fecpool targets # positive samples and mean counts by age group in the Polish survey
105
+ ```
106
+
107
+ `--group-size N` (plan, check, negative) draws the pools from a group of N
108
+ animals without replacement, for a pen or a small herd. `--json` prints every
109
+ result as JSON.
110
+
111
+ The counting method is given as in mcmaster-epg: `--variant` (Raynaud's
112
+ modification: `one_grid`, `two_grids`, `whole_chamber`, `flotation_slide`,
113
+ factors 100, 50, 15, 7) or `--multiplier`; egg loss and dispersion from
114
+ `--species` (built-in validated profile; `--matrix pig` is the default),
115
+ `--profile FILE` (a profile calibrated with `mcmaster-epg calibrate`) or
116
+ `--recovery` and `--k` with their intervals. Without them the nominal method
117
+ is used (no egg loss, Poisson counts), which overstates detection; the output
118
+ says so.
119
+
120
+ ## What the numbers mean
121
+
122
+ A pooled sample holds equal amounts of faeces from `pool size` different
123
+ animals, mixed and counted once. If j of them excrete at least the threshold
124
+ T, the EPG of the pool is at least j x T / pool size, whatever the others
125
+ excrete, and the probability of counting at least one egg rises with the EPG.
126
+ The least favourable group is therefore the one in which exactly the stated
127
+ share excretes exactly T and the others nothing. Every probability is computed
128
+ for that group, so it is a lower limit for any group that meets the condition;
129
+ the number of animals at the threshold in a pool is binomial, or
130
+ hypergeometric with `--group-size`. When the method profile carries the
131
+ uncertainty of recovery and dispersion, the least favourable end of their 95%
132
+ ranges is used.
133
+
134
+ Two consequences for practice:
135
+
136
+ - Pooling saves counts, not animals: in the example 29 single samples become
137
+ 7 pools of 5 (35 animals, 7 counts).
138
+ - Larger pools stop helping. The EPG of a very large pool tends to
139
+ share x T (20 EPG in the example), so one pool cannot be positive more often
140
+ than a single sample of that EPG. When share x T is far below the limit of
141
+ detection of the method, take more pools or a more sensitive variant, not
142
+ larger pools.
143
+
144
+ `negative` gives the upper confidence limit of the share of animals with at
145
+ least T: a larger share would have given a positive pool with a probability
146
+ above the confidence level. It says nothing about animals that excrete less
147
+ than T.
148
+
149
+ ## Pig farms
150
+
151
+ `farm` lists the pools per age group for five parasites. Each parasite is
152
+ looked for in the age group with the highest percentage of positive samples
153
+ in Kochanowski et al. 2017 (Results; `fecpool targets` prints the table):
154
+ coccidia and *Strongyloides* spp. in suckling piglets, *Ascaris suum* in
155
+ fatteners, *Oesophagostomum* spp. and *Trichuris suis* in sows. One pooled
156
+ sample is read for all parasites, so an age group needs the largest number of
157
+ pools among its parasites. (The abstract of the article names fatteners for
158
+ *T. suis*; the Results give 3.0% of positive samples in sows and 1.4% in
159
+ fatteners, and the Results are used.)
160
+
161
+ A validated method profile for pig faeces exists only for *A. suum* eggs
162
+ (Kochanowski et al. 2013, https://doi.org/10.14411/fp.2013.030). For the
163
+ other parasites `farm` uses the nominal method and marks it; calibrate your
164
+ own profile with `mcmaster-epg calibrate` and use `plan --profile` for them.
165
+
166
+ ## Validation
167
+
168
+ `validation/BOUND_REPORT.md` (`python validation/run_bound_validation.py`):
169
+ 162 combinations of method, pool size, share and threshold, each with four
170
+ distributions of EPG among animals and every corner of the parameter ranges,
171
+ 40,000 simulated pools each. No simulated share of positive pools was below
172
+ the limit by more than four standard errors, and for the least favourable
173
+ group the simulation met the limit within 0.007, so the limit cannot be
174
+ raised without an assumption on the distribution. Plans in small groups
175
+ (pools drawn without replacement) agreed with the simulation within 0.002.
176
+
177
+ `validation/PIG_DATA_REPORT.md` (`python validation/run_pig_data_validation.py`):
178
+ pools of five made on the computer from the published egg counts of
179
+ individual pigs of Fischer et al. 2024 (German outdoor farms, FLOTAC; 38
180
+ combinations of group, parasite and threshold). No plan fell below the limit.
181
+ Real groups were found more easily than the limit says: one pool was positive
182
+ 1.5 times as often in the median (1.04 to 6.25 times), and where both numbers
183
+ exist the limit asked for one pool more in the median (0 to 4 more).
184
+
185
+ ## Limits
186
+
187
+ - Equal amounts of faeces from different animals and thorough mixing are
188
+ assumed. Droppings collected from a pen floor may come from the same animal,
189
+ and the mixing of faeces was not tested: in the validation the EPG of a pool
190
+ is computed from the animals' counts, not measured in a mixed sample.
191
+ - The count of a pool is assumed to follow the method profile obtained from
192
+ spiked single samples.
193
+ - The limit is cautious by construction (see the pig data above).
194
+ - Only detection is covered. The mean EPG of a group from pooled counts and
195
+ the egg count reduction test are not; for the latter see `eggCounts`,
196
+ `bayescount` or fecrt.com.
197
+ - A positive count is taken as a true finding. Low counts of *A. suum* and
198
+ other eggs can come from eggs that pass through the gut after being eaten;
199
+ Kochanowski et al. 2017 attributed the eggs of *A. suum*, *T. suis* and
200
+ *Oesophagostomum* spp. in suckling piglets to this.
201
+ - Models of composite egg counts exist for other hosts and questions
202
+ (Morgan et al. 2005 for the mean count of sheep flocks; Levecke et al. 2015
203
+ for human helminths); fecpool addresses detection with a validated count
204
+ model and without a distribution of EPG.
205
+
206
+ ## Python
207
+
208
+ ```python
209
+ from fecpool import method_profile, pools_needed, plan_detection, excluded_prevalence
210
+
211
+ pig = method_profile(variant="whole_chamber", species="ascaris_suum")
212
+ pools_needed(pig, pool_size=5, prevalence=0.1, threshold=200) # 7
213
+ plan_detection(pig, pools=6, pool_size=5, prevalence=0.1, threshold=200) # 0.927
214
+ excluded_prevalence(pig, pools=6, pool_size=5, threshold=200) # 0.114
215
+ ```
216
+
217
+ ## Citation
218
+
219
+ Kochanowski M, Dąbrowska J. fecpool, version 1.1.0. Zenodo; 2026.
220
+ https://doi.org/10.5281/zenodo.24699361 (this DOI covers all versions; each
221
+ version has its own DOI on Zenodo)
222
+
223
+ Kochanowski M, Karamon J, Dąbrowska J, Dors A, Czyżewska-Dors E, Cencek T.
224
+ Occurrence of intestinal parasites in pigs in Poland - the influence of
225
+ factors related to the production system. J Vet Res 2017;61(4):459-466.
226
+ https://doi.org/10.1515/jvetres-2017-0053
227
+
228
+ Data used in the validation: Fischer HRM et al. Porcine Health Manag
229
+ 2024;10:33. https://doi.org/10.1186/s40813-024-00384-8 (CC BY 4.0).
230
+
231
+ ## Licence
232
+
233
+ MIT.
@@ -0,0 +1,11 @@
1
+ fecpool/__init__.py,sha256=gSffSAexntvyyNjdCkdJCqAl_180wO7DPyVkb5AVV8o,543
2
+ fecpool/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
3
+ fecpool/cli.py,sha256=hP0ehqkVocCDGsXyE524QhtierPZV0HW6Y4X0pCqgsM,10716
4
+ fecpool/core.py,sha256=oKDhWrKgyH6bCbnsQDJyU8mhWj8E3LXP_Ciyyp-JhEI,7724
5
+ fecpool/method.py,sha256=vnsABSWnd0ZmKWO7qZmK0Yjzgy7kFxCitqtcSesbTR0,2773
6
+ fecpool/pigs.py,sha256=JqDnWA9Vo59lfzQk773Cz4NFSEqZ3iMTrfkz1VfTtVI,3854
7
+ fecpool-1.1.0.dist-info/METADATA,sha256=4rqfraEaZojG8D3qBcWyN68mYKDe13mizfvK7cnkYvs,11843
8
+ fecpool-1.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ fecpool-1.1.0.dist-info/entry_points.txt,sha256=45m-tN1zblSftPVgiKr_76D2ut4BnYn5KNWK5PwCZdM,45
10
+ fecpool-1.1.0.dist-info/licenses/LICENSE,sha256=rTrEdMc4p_u9ba6b_QA7y7VnUEK7EmcieZv8x6AlhPM,1075
11
+ fecpool-1.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fecpool = fecpool.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Maciej Kochanowski
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.