Support per-sample Delta-E references via NAME > REF
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
20
README.md
20
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_<timestamp>.tsv` | Raw spotread log (Lab + XYZ + spectrum 380–730 nm) |
|
||||
| `scan_D50_<timestamp>.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 |
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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 = ' <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}{pred_tag}</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:
|
||||
d = float(r[DE_COL])
|
||||
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>')
|
||||
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 = (
|
||||
f"ΔE00 is CIEDE2000 against <b>{esc(ref_used)}</b>; "
|
||||
"lower is a closer match."
|
||||
"Δ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 reference was set (mark one sample with a leading '*')."
|
||||
"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 []
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user