105 lines
3.3 KiB
Python
Executable File
105 lines
3.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Average colorimetric results from multiple spotread CSV exports."""
|
|
|
|
import argparse
|
|
import csv
|
|
import statistics
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
LAB_COLS = ("L*", "a*", "b*")
|
|
|
|
|
|
def load_sample_names(path: Path) -> list[str]:
|
|
return [
|
|
line.strip()
|
|
for line in path.read_text(encoding="utf-8").splitlines()
|
|
if line.strip() and not line.strip().startswith("#")
|
|
]
|
|
|
|
|
|
def read_measurements(path: Path, sample_names: list[str]) -> list[dict]:
|
|
with path.open(newline="", encoding="utf-8") as f:
|
|
rows = list(csv.DictReader(f))
|
|
|
|
measurements = []
|
|
for i, row in enumerate(rows):
|
|
sample_id = row.get("sample_id", "").strip()
|
|
if not sample_id:
|
|
reading = row.get("Reading", str(i + 1))
|
|
try:
|
|
idx = int(reading) - 1
|
|
except ValueError:
|
|
idx = i
|
|
sample_id = sample_names[idx] if idx < len(sample_names) else f"sample_{i + 1}"
|
|
|
|
values = {}
|
|
for col in LAB_COLS:
|
|
if col not in row:
|
|
raise KeyError(f"{path}: missing column {col}")
|
|
values[col] = float(row[col])
|
|
measurements.append({"sample_id": sample_id, **values})
|
|
return measurements
|
|
|
|
|
|
def average_sets(sets: list[list[dict]]) -> list[dict]:
|
|
if not sets:
|
|
return []
|
|
|
|
n_sets = len(sets)
|
|
n_samples = len(sets[0])
|
|
if any(len(s) != n_samples for s in sets):
|
|
raise ValueError("All input files must have the same number of readings")
|
|
|
|
averaged = []
|
|
for i in range(n_samples):
|
|
sample_id = sets[0][i]["sample_id"]
|
|
if any(s[i]["sample_id"] != sample_id for s in sets[1:]):
|
|
sample_id = sets[0][i]["sample_id"]
|
|
|
|
row = {"sample_id": sample_id, "n_scans": n_sets}
|
|
for col in LAB_COLS:
|
|
vals = [s[i][col] for s in sets]
|
|
row[f"{col}_mean"] = statistics.mean(vals)
|
|
row[f"{col}_std"] = statistics.stdev(vals) if len(vals) > 1 else 0.0
|
|
averaged.append(row)
|
|
return averaged
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Average multiple spotread CSV files.")
|
|
parser.add_argument("csv_files", nargs="+", type=Path, help="CSV files to average")
|
|
parser.add_argument(
|
|
"-s", "--samples", type=Path, default=Path("samples.txt"), help="Sample name list"
|
|
)
|
|
parser.add_argument(
|
|
"-o", "--output", type=Path, default=Path("averaged.csv"), help="Output CSV"
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
sample_names = load_sample_names(args.samples) if args.samples.exists() else []
|
|
|
|
sets = []
|
|
for path in args.csv_files:
|
|
if not path.exists():
|
|
print(f"Error: {path} not found", file=sys.stderr)
|
|
return 1
|
|
sets.append(read_measurements(path, sample_names))
|
|
|
|
averaged = average_sets(sets)
|
|
fieldnames = ["sample_id", "n_scans"]
|
|
for col in LAB_COLS:
|
|
fieldnames.extend([f"{col}_mean", f"{col}_std"])
|
|
|
|
with args.output.open("w", newline="", encoding="utf-8") as f:
|
|
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
|
writer.writeheader()
|
|
writer.writerows(averaged)
|
|
|
|
print(f"Wrote {len(averaged)} averaged sample(s) to {args.output}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|