108 lines
3.0 KiB
Python
Executable File
108 lines
3.0 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Build formula table from averaged results and sample mix definitions.
|
|
|
|
Ink/material names are discovered automatically from the sample IDs, so this
|
|
works for any material codes (not tied to a specific product line).
|
|
"""
|
|
|
|
import argparse
|
|
import csv
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
# Two-material mix, e.g. "INK_A+INK_B[75 to 15 mix]". Names may be any token
|
|
# that does not contain '+' or '['.
|
|
MIX_PATTERN = re.compile(
|
|
r"^(?P<a>[^+\[]+)\+(?P<b>[^+\[]+)\[(?P<w1>\d+)\s+to\s+(?P<w2>\d+)\s+mix\]$"
|
|
)
|
|
|
|
|
|
def parse_components(sample_id: str) -> dict[str, int]:
|
|
"""Return {material: percent} for a pure material or a two-material mix."""
|
|
mix = MIX_PATTERN.match(sample_id)
|
|
if mix:
|
|
ink_a = mix.group("a").strip()
|
|
ink_b = mix.group("b").strip()
|
|
w1 = float(mix.group("w1"))
|
|
w2 = float(mix.group("w2"))
|
|
total = w1 + w2
|
|
return {ink_a: round(100.0 * w1 / total), ink_b: round(100.0 * w2 / total)}
|
|
return {sample_id.strip(): 100}
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description="Build formula table from averaged CSV.")
|
|
parser.add_argument(
|
|
"-i",
|
|
"--input",
|
|
type=Path,
|
|
default=Path("averaged.csv"),
|
|
help="Averaged results CSV",
|
|
)
|
|
parser.add_argument(
|
|
"-o",
|
|
"--output",
|
|
type=Path,
|
|
default=Path("formula.csv"),
|
|
help="Output formula table CSV",
|
|
)
|
|
args = parser.parse_args()
|
|
|
|
if not args.input.exists():
|
|
print(f"Error: {args.input} not found", file=sys.stderr)
|
|
return 1
|
|
|
|
with args.input.open(newline="", encoding="utf-8") as f:
|
|
rows = list(csv.DictReader(f))
|
|
|
|
# Discover material columns in order of first appearance.
|
|
inks: list[str] = []
|
|
parsed: list[dict[str, int]] = []
|
|
for row in rows:
|
|
comps = parse_components(row["sample_id"])
|
|
parsed.append(comps)
|
|
for ink in comps:
|
|
if ink not in inks:
|
|
inks.append(ink)
|
|
|
|
fieldnames = [
|
|
"sample_id",
|
|
*inks,
|
|
"n_scans",
|
|
"L*_mean",
|
|
"L*_std",
|
|
"a*_mean",
|
|
"a*_std",
|
|
"b*_mean",
|
|
"b*_std",
|
|
]
|
|
|
|
out_rows = []
|
|
for row, comps in zip(rows, parsed):
|
|
out = {
|
|
"sample_id": row["sample_id"],
|
|
"n_scans": row["n_scans"],
|
|
"L*_mean": row["L*_mean"],
|
|
"L*_std": row["L*_std"],
|
|
"a*_mean": row["a*_mean"],
|
|
"a*_std": row["a*_std"],
|
|
"b*_mean": row["b*_mean"],
|
|
"b*_std": row["b*_std"],
|
|
}
|
|
for ink in inks:
|
|
out[ink] = comps.get(ink, 0)
|
|
out_rows.append(out)
|
|
|
|
with args.output.open("w", newline="", encoding="utf-8") as f:
|
|
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
|
writer.writeheader()
|
|
writer.writerows(out_rows)
|
|
|
|
print(f"Wrote {len(out_rows)} row(s) to {args.output}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|