sampling/sampling_tool/methods.py
114 lines · 3684 bytes
1"""Sampling methods."""
2
3from __future__ import annotations
4
5import math
6import random
7
8import pandas as pd
9
10from . import engine
11from .io import AuditSamplingError
12
13
14def ensure_seed(seed: int | None) -> tuple[int, bool]:
15 if seed is not None:
16 return int(seed), False
17 return random.SystemRandom().randint(1, 2_147_483_647), True
18
19
20def parse_key_ints(value: str | None, label: str) -> dict[str, int]:
21 if not value:
22 return {}
23 parsed: dict[str, int] = {}
24 for part in value.split(","):
25 if "=" not in part:
26 raise AuditSamplingError(f"Invalid {label} entry '{part}'. Use Name=Count.")
27 key, raw_count = part.split("=", 1)
28 key = key.strip()
29 try:
30 count = int(raw_count.strip())
31 except ValueError as exc:
32 raise AuditSamplingError(
33 f"Invalid {label} count for '{key}': {raw_count}"
34 ) from exc
35 if count <= 0:
36 raise AuditSamplingError(f"{label} count for '{key}' must be positive.")
37 parsed[key] = count
38 return parsed
39
40
41def parse_key_floats(value: str | None, label: str) -> dict[str, float]:
42 if not value:
43 return {}
44 parsed: dict[str, float] = {}
45 for part in value.split(","):
46 if "=" not in part:
47 raise AuditSamplingError(
48 f"Invalid {label} entry '{part}'. Use Name=Proportion."
49 )
50 key, raw_proportion = part.split("=", 1)
51 key = key.strip()
52 try:
53 proportion = float(raw_proportion.strip())
54 except ValueError as exc:
55 raise AuditSamplingError(
56 f"Invalid {label} proportion for '{key}': {raw_proportion}"
57 ) from exc
58 if proportion <= 0:
59 raise AuditSamplingError(
60 f"{label} proportion for '{key}' must be positive."
61 )
62 parsed[key] = proportion
63 if not math.isclose(sum(parsed.values()), 1.0, rel_tol=1e-9, abs_tol=1e-9):
64 raise AuditSamplingError(f"{label} proportions must sum to 1.0.")
65 return parsed
66
67
68def largest_remainder_allocation(
69 sample_size: int, proportions: dict[str, float]
70) -> dict[str, int]:
71 raw = {
72 stratum: {
73 "floor": math.floor(sample_size * proportion),
74 "remainder": sample_size * proportion
75 - math.floor(sample_size * proportion),
76 }
77 for stratum, proportion in proportions.items()
78 }
79 allocation = {stratum: values["floor"] for stratum, values in raw.items()}
80 remaining = sample_size - sum(allocation.values())
81 ranked = sorted(
82 raw,
83 key=lambda stratum: (-raw[stratum]["remainder"], stratum),
84 )
85 for stratum in ranked[:remaining]:
86 allocation[stratum] += 1
87 return allocation
88
89
90def random_sample(
91 population: pd.DataFrame, sample_size: int, seed: int
92) -> pd.DataFrame:
93 return population.iloc[engine.select_random(len(population), sample_size, seed)]
94
95
96def systematic_sample(
97 population: pd.DataFrame, sample_size: int, seed: int
98) -> pd.DataFrame:
99 return population.iloc[engine.select_systematic(len(population), sample_size, seed)]
100
101
102def stratified_sample(
103 population: pd.DataFrame,
104 stratify_column: str,
105 counts: dict[str, int],
106 seed: int,
107 allow_shortfall: bool,
108) -> tuple[pd.DataFrame, list[dict[str, object]]]:
109 strata = population[stratify_column].astype(str).tolist()
110 try:
111 positions, summary = engine.select_stratified(strata, counts, seed, allow_shortfall)
112 except ValueError as exc:
113 raise AuditSamplingError(f"{exc} Use --allow-shortfall to continue.") from exc
114 return population.iloc[positions], summary