diff --git a/README.md b/README.md index ff42ea0..23f9971 100644 --- a/README.md +++ b/README.md @@ -29,8 +29,8 @@ average repeated scans, and relate results to ink mix formulas. `samples.txt`. 5. **Updates the averages** — re-averages **all** complete scan CSVs in the folder into `averaged.csv` (L\*, a\*, b\* mean and standard - deviation per sample, plus a `dE00` CIEDE2000 column against the - reference sample) and a formatted `averaged.html` view, then asks + deviation per sample, plus a `dE00` CIEDE2000 column against each + sample's named reference) and a formatted `averaged.html` view, then asks whether to rebuild the formula table `formula.csv` (default: yes). ### Options @@ -87,15 +87,15 @@ cp samples.example.txt samples.txt ``` Lines starting with `#` are ignored. Material names can be any codes. -Prefix one sample with `*` to mark it as the **Delta-E reference** that the -`dE00` column is measured against (if none is marked, the first sample is -used). Mix samples use the pattern `NAME_A+NAME_B[w1 to w2 mix]`, e.g.: +Append ` > REF` to measure that sample's `dE00` against another sample; a +bare name (no `>`) is itself a **reference**. Mix samples use the pattern +`NAME_A+NAME_B[w1 to w2 mix]`, e.g.: ```text -*INK_A -INK_B -INK_A+INK_B[75 to 15 mix] -INK_A+INK_C[30 to 80 mix] +INK_A +INK_B > INK_A +INK_A+INK_B[75 to 15 mix] > INK_A +INK_A+INK_C[30 to 80 mix] > INK_A ``` The weights are converted to percentages in the formula table @@ -108,7 +108,7 @@ discovers the material names automatically from your sample list. |------|----------| | `scan_D50_.tsv` | Raw spotread log (Lab + XYZ + spectrum 380–730 nm) | | `scan_D50_.csv` | Same data as CSV with `sample_id` column | -| `averaged.csv` | Per-sample L\*, a\*, b\* mean and std, plus `dE00` vs the reference | +| `averaged.csv` | Per-sample L\*, a\*, b\* mean and std, plus `dE00` vs each sample's reference | | `averaged.html` | Formatted view of `averaged.csv` with color swatches | | `formula.csv` | Averaged Lab plus one percentage column per ink | | `archive/` | Discarded or superseded scans | diff --git a/auto-scan.sh b/auto-scan.sh index 303626e..70168a4 100755 --- a/auto-scan.sh +++ b/auto-scan.sh @@ -128,13 +128,13 @@ wait_for_instrument() { scan_samples() { [[ -f "$SAMPLES_FILE" ]] || fail "$SAMPLES_FILE not found" - # Strip a leading "*" (the Delta-E reference marker) from displayed names. + # Strip an optional " > REF" suffix from displayed names. # A while-read loop is used instead of mapfile for bash 3.2 (macOS) support. SAMPLES=() while IFS= read -r line; do SAMPLES+=("$line") done < <(grep -v '^#' "$SAMPLES_FILE" | grep -v '^[[:space:]]*$' \ - | sed -E 's/^[[:space:]]*\*[[:space:]]*//') + | sed -E 's/[[:space:]]*>.*$//') local count="${#SAMPLES[@]}" [[ "$count" -gt 0 ]] || fail "No sample names found in $SAMPLES_FILE" diff --git a/average-results.py b/average-results.py index 62ed1d7..8f33434 100755 --- a/average-results.py +++ b/average-results.py @@ -16,10 +16,10 @@ 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 prefixed with "*" is the Delta-E reference: every other -# sample's Delta-E is measured against it. The marker is stripped to recover -# the real sample name. -REF_MARKER = "*" +# 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:" @@ -35,11 +35,13 @@ def load_notes(path: Path) -> list[str]: return notes -def _strip_ref_marker(name: str) -> str: - """Remove a leading Delta-E reference marker from a sample name.""" - if name.startswith(REF_MARKER): - return name[len(REF_MARKER):].strip() - return name +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]: @@ -51,15 +53,17 @@ def _sample_lines(path: Path) -> list[str]: def load_sample_names(path: Path) -> list[str]: - return [_strip_ref_marker(line) for line in _sample_lines(path)] + return [_parse_sample_line(line)[0] for line in _sample_lines(path)] -def load_reference(path: Path) -> str | None: - """Return the sample marked with a leading '*', if any.""" +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): - if line.startswith(REF_MARKER): - return _strip_ref_marker(line) - return None + name, ref = _parse_sample_line(line) + if ref: + refs[name] = ref + return refs def de2000(lab1, lab2) -> float: @@ -110,31 +114,40 @@ def de2000(lab1, lab2) -> float: + RT * (dCp / SC) * (dHp / SH)) -def add_delta_e(rows: list[dict], reference: str | None) -> str | None: - """Add a CIEDE2000 column to each averaged row, measured against `reference`. +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. - Returns the reference sample_id actually used, or None if no column was - added (missing/unknown reference). Never raises so the scan pipeline can - continue even when the reference is misconfigured. + 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: - return None + if not rows or not references: + return False - ref_id = reference or rows[0]["sample_id"] - ref_row = next((r for r in rows if r["sample_id"] == ref_id), None) - if ref_row is None: - print( - f"Warning: Delta-E reference {ref_id!r} not found among samples; " - f"skipping {DE_COL} column", - file=sys.stderr, - ) - return None - - ref_lab = tuple(ref_row[f"{c}_mean"] for c in LAB_COLS) + 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) - return ref_id + wrote = True + return wrote def srgb(L: float, a: float, b: float) -> str: @@ -170,10 +183,13 @@ def de_bucket(d: float) -> str: def write_html( - rows: list[dict], ref_used: str | None, path: Path, notes: list[str] | None = None + 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.""" - has_de = ref_used is not None esc = html.escape head_cells = [ @@ -187,30 +203,39 @@ def write_html( 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) - is_ref = has_de and r["sample_id"] == ref_used + 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 = ' reference' if is_ref else "" + vs_tag = f' vs {esc(vs)}' if vs else "" pred_tag = ' predicted' if is_pred else "" cells = [ f'', - f'{esc(r["sample_id"])}{ref_tag}{pred_tag}', + f'{esc(r["sample_id"])}{ref_tag}{vs_tag}{pred_tag}', f'{esc(str(r["n_scans"])) if not is_pred else "—"}', ] for m, s in zip(lab, std): cells.append(f'{m:.2f}±{s:.2f}') if has_de: - d = float(r[DE_COL]) - de_cls = "de win" if is_ref else ("de bad" if d >= 3.5 else "de") - cells.append(f'{d:.2f}') + raw = r.get(DE_COL, "") + if raw == "" or raw is None: + cells.append('—') + else: + d = float(raw) + de_cls = "de win" if is_ref else ("de bad" if d >= 3.5 else "de") + cells.append( + f'{d:.2f}' + ) body_rows.append(f' {"".join(cells)}') ref_note = ( - f"ΔE00 is CIEDE2000 against {esc(ref_used)}; " - "lower is a closer match." + "ΔE00 is CIEDE2000 against each sample's named reference " + "(NAME > REF in samples.txt); tagged " + "reference rows have no external reference. Lower is a closer match." if has_de else - "No Delta-E reference was set (mark one sample with a leading '*')." + "No Delta-E column (add NAME > REF lines in samples.txt)." ) generated = datetime.now().strftime("%Y-%m-%d %H:%M") notes = notes or [] @@ -341,7 +366,7 @@ def main() -> int: args = parser.parse_args() sample_names = load_sample_names(args.samples) if args.samples.exists() else [] - reference = load_reference(args.samples) if args.samples.exists() else None + references = load_references(args.samples) if args.samples.exists() else {} sets = [] for path in args.csv_files: @@ -352,12 +377,12 @@ def main() -> int: averaged = average_sets(sets) - ref_used = add_delta_e(averaged, reference) + 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 ref_used is not None: + if has_de: fieldnames.append(DE_COL) with args.output.open("w", newline="", encoding="utf-8") as f: @@ -367,13 +392,17 @@ def main() -> int: html_path = args.output.with_suffix(".html") notes = load_notes(args.samples) if args.samples.exists() else [] - write_html(averaged, ref_used, html_path, notes) + 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 ref_used is not None: - note = "" if reference else " (no '*'-marked sample; using first sample)" - print(f"{DE_COL} computed as CIEDE2000 vs {ref_used!r}{note}") + 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 diff --git a/prompt-next-sample.py b/prompt-next-sample.py index cad7841..1a6fc41 100755 --- a/prompt-next-sample.py +++ b/prompt-next-sample.py @@ -17,13 +17,13 @@ RESET = "\033[0m" def load_sample_names(path: Path) -> list[str]: - # A leading "*" marks the Delta-E reference sample; strip it to get the name. + # Optional "NAME > REF": keep only the sample name (before ">"). names = [] for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if line and not line.startswith("#"): - if line.startswith("*"): - line = line[1:].strip() + if ">" in line: + line = line.split(">", 1)[0].strip() names.append(line) return names diff --git a/samples.example.txt b/samples.example.txt index 86e6b9b..dafc96d 100644 --- a/samples.example.txt +++ b/samples.example.txt @@ -1,10 +1,11 @@ # One sample name per line, in measurement order. # Lines starting with # are ignored. # -# Prefix one sample with * to mark it as the Delta-E reference: every other -# sample's Delta-E (CIEDE2000, written as the dE00 column in averaged.csv) is -# measured against it. If none is marked, the first sample is used. Example: -# *INK_A +# Name a Delta-E reference with "NAME > REF": that sample's dE00 (CIEDE2000 +# in averaged.csv) is measured against REF. A bare name (no ">") is itself a +# reference. Example: +# INK_A +# INK_B > INK_A # # Optional notes for averaged.html (one per line, shown above the results table): # note: Glaze: CPO1192 @@ -19,8 +20,8 @@ # # Copy this file to samples.txt and replace with your own materials: # cp samples.example.txt samples.txt -*INK_A -INK_B -INK_C -INK_A+INK_B[75 to 15 mix] -INK_A+INK_C[30 to 80 mix] +INK_A +INK_B > INK_A +INK_C > INK_A +INK_A+INK_B[75 to 15 mix] > INK_A +INK_A+INK_C[30 to 80 mix] > INK_A diff --git a/tsv-to-csv.py b/tsv-to-csv.py index eceaaca..8b9d0a5 100755 --- a/tsv-to-csv.py +++ b/tsv-to-csv.py @@ -8,13 +8,13 @@ from pathlib import Path def load_sample_names(path: Path) -> list[str]: - # A leading "*" marks the Delta-E reference sample; strip it to get the name. + # Optional "NAME > REF": keep only the sample name (before ">"). names = [] for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() if line and not line.startswith("#"): - if line.startswith("*"): - line = line[1:].strip() + if ">" in line: + line = line.split(">", 1)[0].strip() names.append(line) return names