411 lines
14 KiB
Python
Executable File
411 lines
14 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Average colorimetric results from multiple spotread CSV exports."""
|
|
|
|
import argparse
|
|
import csv
|
|
import html
|
|
import math
|
|
import statistics
|
|
import sys
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
|
|
LAB_COLS = ("L*", "a*", "b*")
|
|
DE_COL = "dE00"
|
|
|
|
# D50 / 2 deg white point, used to render approximate sRGB swatches from Lab.
|
|
WHITE_POINT = (96.422, 100.0, 82.521)
|
|
|
|
# A sample line may name its Delta-E reference as "NAME > REF". Bare names
|
|
# (no ">") are references themselves. The " > REF" suffix is stripped to
|
|
# recover the real sample name used as sample_id.
|
|
REF_SEP = ">"
|
|
NOTE_PREFIX = "# note:"
|
|
|
|
|
|
def load_notes(path: Path) -> list[str]:
|
|
"""Read display notes from '# note: ...' comment lines in the samples file."""
|
|
if not path.exists():
|
|
return []
|
|
notes = []
|
|
for line in path.read_text(encoding="utf-8").splitlines():
|
|
stripped = line.strip()
|
|
if stripped.lower().startswith(NOTE_PREFIX):
|
|
notes.append(stripped[len(NOTE_PREFIX):].strip())
|
|
return notes
|
|
|
|
|
|
def _parse_sample_line(line: str) -> tuple[str, str | None]:
|
|
"""Return (sample_name, reference_or_None). Bare name = this sample is a reference."""
|
|
if REF_SEP in line:
|
|
name, _, ref = line.partition(REF_SEP)
|
|
name, ref = name.strip(), ref.strip()
|
|
return name, ref or None
|
|
return line.strip(), None
|
|
|
|
|
|
def _sample_lines(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 load_sample_names(path: Path) -> list[str]:
|
|
return [_parse_sample_line(line)[0] for line in _sample_lines(path)]
|
|
|
|
|
|
def load_references(path: Path) -> dict[str, str]:
|
|
"""Map sample_id -> reference_id for samples that name a reference."""
|
|
refs: dict[str, str] = {}
|
|
for line in _sample_lines(path):
|
|
name, ref = _parse_sample_line(line)
|
|
if ref:
|
|
refs[name] = ref
|
|
return refs
|
|
|
|
|
|
def de2000(lab1, lab2) -> float:
|
|
"""CIEDE2000 color difference between two (L*, a*, b*) triples."""
|
|
L1, a1, b1 = lab1
|
|
L2, a2, b2 = lab2
|
|
C1 = math.hypot(a1, b1)
|
|
C2 = math.hypot(a2, b2)
|
|
Cbar = (C1 + C2) / 2
|
|
G = 0.5 * (1 - math.sqrt(Cbar**7 / (Cbar**7 + 25**7)))
|
|
a1p, a2p = a1 * (1 + G), a2 * (1 + G)
|
|
C1p, C2p = math.hypot(a1p, b1), math.hypot(a2p, b2)
|
|
h1p = math.degrees(math.atan2(b1, a1p)) % 360
|
|
h2p = math.degrees(math.atan2(b2, a2p)) % 360
|
|
dLp = L2 - L1
|
|
dCp = C2p - C1p
|
|
dh = h2p - h1p
|
|
if C1p * C2p == 0:
|
|
dhp = 0
|
|
elif abs(dh) <= 180:
|
|
dhp = dh
|
|
elif dh > 180:
|
|
dhp = dh - 360
|
|
else:
|
|
dhp = dh + 360
|
|
dHp = 2 * math.sqrt(C1p * C2p) * math.sin(math.radians(dhp) / 2)
|
|
Lbp = (L1 + L2) / 2
|
|
Cbp = (C1p + C2p) / 2
|
|
if C1p * C2p == 0:
|
|
hbp = h1p + h2p
|
|
elif abs(h1p - h2p) <= 180:
|
|
hbp = (h1p + h2p) / 2
|
|
elif h1p + h2p < 360:
|
|
hbp = (h1p + h2p + 360) / 2
|
|
else:
|
|
hbp = (h1p + h2p - 360) / 2
|
|
T = (1 - 0.17 * math.cos(math.radians(hbp - 30))
|
|
+ 0.24 * math.cos(math.radians(2 * hbp))
|
|
+ 0.32 * math.cos(math.radians(3 * hbp + 6))
|
|
- 0.20 * math.cos(math.radians(4 * hbp - 63)))
|
|
SL = 1 + 0.015 * (Lbp - 50) ** 2 / math.sqrt(20 + (Lbp - 50) ** 2)
|
|
SC = 1 + 0.045 * Cbp
|
|
SH = 1 + 0.015 * Cbp * T
|
|
dTheta = 30 * math.exp(-(((hbp - 275) / 25) ** 2))
|
|
RC = 2 * math.sqrt(Cbp**7 / (Cbp**7 + 25**7))
|
|
RT = -RC * math.sin(math.radians(2 * dTheta))
|
|
return math.sqrt((dLp / SL) ** 2 + (dCp / SC) ** 2 + (dHp / SH) ** 2
|
|
+ RT * (dCp / SC) * (dHp / SH))
|
|
|
|
|
|
def add_delta_e(rows: list[dict], references: dict[str, str]) -> bool:
|
|
"""Add a CIEDE2000 column to each averaged row vs that sample's reference.
|
|
|
|
Samples absent from `references` are references themselves (dE00 = 0).
|
|
Returns True if the column was written (only when at least one sample
|
|
names a reference). Never raises so the scan pipeline can continue even
|
|
when a named reference is missing.
|
|
"""
|
|
if not rows or not references:
|
|
return False
|
|
|
|
by_id = {r["sample_id"]: r for r in rows}
|
|
wrote = False
|
|
for row in rows:
|
|
sid = row["sample_id"]
|
|
ref_id = references.get(sid)
|
|
if ref_id is None:
|
|
row[DE_COL] = 0.0
|
|
wrote = True
|
|
continue
|
|
ref_row = by_id.get(ref_id)
|
|
if ref_row is None:
|
|
print(
|
|
f"Warning: Delta-E reference {ref_id!r} for {sid!r} not found "
|
|
f"among samples; leaving {DE_COL} empty",
|
|
file=sys.stderr,
|
|
)
|
|
row[DE_COL] = ""
|
|
continue
|
|
ref_lab = tuple(ref_row[f"{c}_mean"] for c in LAB_COLS)
|
|
lab = tuple(row[f"{c}_mean"] for c in LAB_COLS)
|
|
row[DE_COL] = de2000(ref_lab, lab)
|
|
wrote = True
|
|
return wrote
|
|
|
|
|
|
def srgb(L: float, a: float, b: float) -> str:
|
|
"""Approximate sRGB hex for a CIELAB triple (D50), for display swatches."""
|
|
fy = (L + 16) / 116
|
|
fx = fy + a / 500
|
|
fz = fy - b / 200
|
|
|
|
def finv(f):
|
|
return f**3 if f**3 > 0.008856 else (f - 16 / 116) / 7.787
|
|
|
|
X, Y, Z = (finv(f) * w / 100 for f, w in zip((fx, fy, fz), WHITE_POINT))
|
|
r = 3.1338561 * X - 1.6168667 * Y - 0.4906146 * Z
|
|
g = -0.9787684 * X + 1.9161415 * Y + 0.0334540 * Z
|
|
bl = 0.0719453 * X - 0.2289914 * Y + 1.4052427 * Z
|
|
|
|
def enc(c):
|
|
c = max(0.0, min(1.0, c))
|
|
c = 1.055 * c ** (1 / 2.4) - 0.055 if c > 0.0031308 else 12.92 * c
|
|
return round(max(0.0, min(1.0, c)) * 255)
|
|
|
|
return "#%02x%02x%02x" % (enc(r), enc(g), enc(bl))
|
|
|
|
|
|
def de_bucket(d: float) -> str:
|
|
if d < 1:
|
|
return "not perceptible"
|
|
if d < 2:
|
|
return "perceptible on close inspection"
|
|
if d < 3.5:
|
|
return "perceptible at a glance"
|
|
return "clearly different"
|
|
|
|
|
|
def write_html(
|
|
rows: list[dict],
|
|
references: dict[str, str],
|
|
path: Path,
|
|
notes: list[str] | None = None,
|
|
has_de: bool = False,
|
|
) -> None:
|
|
"""Write a self-contained HTML view of the averaged results."""
|
|
esc = html.escape
|
|
|
|
head_cells = [
|
|
"<th></th>", "<th>Sample</th>", "<th>n</th>",
|
|
"<th>L*</th>", "<th>a*</th>", "<th>b*</th>",
|
|
]
|
|
if has_de:
|
|
head_cells.append("<th>ΔE00</th>")
|
|
|
|
body_rows = []
|
|
for r in rows:
|
|
lab = tuple(float(r[f"{c}_mean"]) for c in LAB_COLS)
|
|
std = tuple(float(r[f"{c}_std"]) for c in LAB_COLS)
|
|
vs = references.get(r["sample_id"])
|
|
is_ref = has_de and vs is None
|
|
is_pred = int(float(r["n_scans"])) == 0
|
|
row_cls = "ref" if is_ref else ("pred" if is_pred else "")
|
|
cls = f' class="{row_cls}"' if row_cls else ""
|
|
ref_tag = ' <span class="tag">reference</span>' if is_ref else ""
|
|
vs_tag = f' <span class="tag">vs {esc(vs)}</span>' if vs else ""
|
|
pred_tag = ' <span class="tag">predicted</span>' if is_pred else ""
|
|
cells = [
|
|
f'<td><span class="patch" style="background:{srgb(*lab)}"></span></td>',
|
|
f'<td class="name">{esc(r["sample_id"])}{ref_tag}{vs_tag}{pred_tag}</td>',
|
|
f'<td>{esc(str(r["n_scans"])) if not is_pred else "—"}</td>',
|
|
]
|
|
for m, s in zip(lab, std):
|
|
cells.append(f'<td>{m:.2f}<span class="std">±{s:.2f}</span></td>')
|
|
if has_de:
|
|
raw = r.get(DE_COL, "")
|
|
if raw == "" or raw is None:
|
|
cells.append('<td class="de">—</td>')
|
|
else:
|
|
d = float(raw)
|
|
de_cls = "de win" if is_ref else ("de bad" if d >= 3.5 else "de")
|
|
cells.append(
|
|
f'<td class="{de_cls}" title="{esc(de_bucket(d))}">{d:.2f}</td>'
|
|
)
|
|
body_rows.append(f' <tr{cls}>{"".join(cells)}</tr>')
|
|
|
|
ref_note = (
|
|
"ΔE00 is CIEDE2000 against each sample's named reference "
|
|
"(<code>NAME > REF</code> in samples.txt); tagged "
|
|
"<b>reference</b> rows have no external reference. Lower is a closer match."
|
|
if has_de else
|
|
"No Delta-E column (add <code>NAME > REF</code> lines in samples.txt)."
|
|
)
|
|
generated = datetime.now().strftime("%Y-%m-%d %H:%M")
|
|
notes = notes or []
|
|
notes_html = ""
|
|
if notes:
|
|
items = "".join(f"<li>{esc(n)}</li>" for n in notes)
|
|
notes_html = f' <ul class="notes">{items}</ul>\n'
|
|
|
|
html_doc = f"""<!DOCTYPE html>
|
|
<html lang="en">
|
|
<head>
|
|
<meta charset="utf-8">
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
<title>Averaged color measurements</title>
|
|
<style>
|
|
:root {{ --text:#1f2328; --text2:#57606a; --text3:#8b949e; --stroke:#d0d7de;
|
|
--bg:#fff; --fill:#f6f8fa; --good:#1a7f37; --bad:#bc4c00; }}
|
|
* {{ box-sizing:border-box; }}
|
|
body {{ margin:0; padding:32px 24px 48px; background:var(--bg); color:var(--text);
|
|
font:14px/1.5 -apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif; }}
|
|
main {{ max-width:760px; margin:0 auto; }}
|
|
h1 {{ font-size:22px; margin:0 0 4px; }}
|
|
.muted {{ color:var(--text2); margin:0 0 20px; }}
|
|
.notes {{ list-style:none; padding:0; margin:0 0 20px; color:var(--text2); font-size:13px; }}
|
|
.notes li {{ margin:2px 0; }}
|
|
table {{ border-collapse:separate; border-spacing:0; width:100%;
|
|
border:1px solid var(--stroke); border-radius:8px; overflow:hidden; }}
|
|
th,td {{ padding:7px 10px; text-align:right; font-size:13px;
|
|
font-variant-numeric:tabular-nums; }}
|
|
th:nth-child(2),td.name {{ text-align:left; }}
|
|
thead th {{ background:var(--fill); font-size:12px; color:var(--text2);
|
|
border-bottom:1px solid var(--stroke); }}
|
|
tbody tr + tr td {{ border-top:1px solid var(--stroke); }}
|
|
tr.ref td {{ background:var(--fill); }}
|
|
tr.pred td {{ background:#fff8e6; }}
|
|
tr.pred td.name {{ font-style:italic; }}
|
|
.patch {{ width:18px; height:18px; display:inline-block; vertical-align:middle;
|
|
border-radius:5px; border:1px solid var(--stroke); }}
|
|
.std {{ color:var(--text3); font-size:11px; margin-left:3px; }}
|
|
.tag {{ font-size:11px; color:var(--text3); border:1px solid var(--stroke);
|
|
border-radius:4px; padding:0 5px; margin-left:6px; }}
|
|
.de {{ font-weight:600; }}
|
|
.win {{ color:var(--good); }}
|
|
.bad {{ color:var(--bad); }}
|
|
.faint {{ color:var(--text3); font-size:12px; margin-top:14px; }}
|
|
@media print {{ body {{ padding:0; }} }}
|
|
</style>
|
|
</head>
|
|
<body>
|
|
<main>
|
|
<h1>Averaged color measurements</h1>
|
|
<p class="muted">Per-sample CIELAB means (± standard deviation) across the
|
|
averaged scans. {ref_note}</p>
|
|
{notes_html} <table>
|
|
<thead>
|
|
<tr>{"".join(head_cells)}</tr>
|
|
</thead>
|
|
<tbody>
|
|
{chr(10).join(body_rows)}
|
|
</tbody>
|
|
</table>
|
|
<p class="faint">Swatches are sRGB approximations of the measured Lab values
|
|
(D50 / 2°). Generated by average-results.py on {generated}.</p>
|
|
</main>
|
|
</body>
|
|
</html>
|
|
"""
|
|
path.write_text(html_doc, encoding="utf-8")
|
|
|
|
|
|
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 []
|
|
references = load_references(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)
|
|
|
|
has_de = add_delta_e(averaged, references)
|
|
|
|
fieldnames = ["sample_id", "n_scans"]
|
|
for col in LAB_COLS:
|
|
fieldnames.extend([f"{col}_mean", f"{col}_std"])
|
|
if has_de:
|
|
fieldnames.append(DE_COL)
|
|
|
|
with args.output.open("w", newline="", encoding="utf-8") as f:
|
|
writer = csv.DictWriter(f, fieldnames=fieldnames)
|
|
writer.writeheader()
|
|
writer.writerows(averaged)
|
|
|
|
html_path = args.output.with_suffix(".html")
|
|
notes = load_notes(args.samples) if args.samples.exists() else []
|
|
write_html(averaged, references, html_path, notes, has_de=has_de)
|
|
|
|
print(f"Wrote {len(averaged)} averaged sample(s) to {args.output}")
|
|
print(f"Wrote HTML view to {html_path}")
|
|
if has_de:
|
|
n_ref = sum(1 for r in averaged if r["sample_id"] not in references)
|
|
n_cmp = sum(1 for r in averaged if r["sample_id"] in references)
|
|
print(
|
|
f"{DE_COL} computed as CIEDE2000 vs per-sample references "
|
|
f"({n_ref} reference(s), {n_cmp} compared)"
|
|
)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|