sampling/sampling_tool/reporting.py
78 lines · 2746 bytes
1"""Human-readable reporting outputs."""
2
3from __future__ import annotations
4
5from pathlib import Path
6
7from .facts import RunFacts
8
9
10class RunLogger:
11 def __init__(self) -> None:
12 self.lines: list[str] = []
13
14 def log(self, message: str) -> None:
15 self.lines.append(message)
16
17 def warning(self, message: str) -> None:
18 self.log(f"WARNING: {message}")
19
20 def error(self, message: str) -> None:
21 self.log(f"ERROR: {message}")
22
23 def write(self, path: Path) -> None:
24 path.write_text("\n".join(self.lines) + "\n")
25
26
27def build_methodology(
28 facts: RunFacts, strata_summary: list[dict[str, object]] | None
29) -> str:
30 options = facts.options
31 lines = [
32 "Audit Sampling Methodology",
33 "",
34 f"Source file: {facts.input_file}",
35 f"Source sheet: {facts.input_sheet or ''}",
36 f"Input SHA-256: {facts.input_sha256}",
37 f"Source row count: {facts.source_row_count}",
38 ]
39 if facts.id_column_omitted:
40 lines.append(
41 "ID column: omitted; _audit_row_id was generated from _source_row_number."
42 )
43 else:
44 lines.append(f"ID column: {options.id_column}")
45 lines.extend(
46 [
47 f"Effective ID column: {facts.effective_id_column or ''}",
48 f"Duplicate ID rows identified: {facts.duplicate_id_count}",
49 f"Blank ID rows identified: {facts.blank_id_count}",
50 f"Blank ID handling: {'excluded' if options.exclude_blank_id else 'retained'}",
51 f"Filters applied: {options.filters or {}}",
52 f"Sampling method: {options.method}",
53 f"Sample size requested: {options.sample_size or ''}",
54 f"Sample size selected: {facts.sample_size_actual}",
55 f"Random seed used: {facts.random_seed or ''}",
56 ]
57 )
58 if options.method == "stratified":
59 lines.append(f"Stratification column: {options.stratify_column}")
60 lines.append(f"Strata counts: {options.strata_counts or ''}")
61 lines.append(f"Strata proportions: {options.strata_proportions or ''}")
62 if strata_summary:
63 lines.append("Strata summary:")
64 for row in strata_summary:
65 lines.append(
66 " "
67 f"{row['Stratum']}: population={row['Population Count']}, "
68 f"requested={row['Requested Sample Count']}, "
69 f"actual={row['Actual Sample Count']}, "
70 f"shortfall={row['Shortfall']}"
71 )
72 lines.extend(
73 [
74 "Sampling was performed without replacement.",
75 "Selected rows retain source row numbers and original source fields.",
76 ]
77 )
78 return "\n".join(lines) + "\n"