Compare commits
2 Commits
bb6e6d9b64
...
08659faea9
| Author | SHA1 | Date | |
|---|---|---|---|
| 08659faea9 | |||
| f7e3731724 |
20
README.md
20
README.md
@@ -29,8 +29,8 @@ average repeated scans, and relate results to ink mix formulas.
|
|||||||
`samples.txt`.
|
`samples.txt`.
|
||||||
5. **Updates the averages** — re-averages **all** complete scan CSVs in
|
5. **Updates the averages** — re-averages **all** complete scan CSVs in
|
||||||
the folder into `averaged.csv` (L\*, a\*, b\* mean and standard
|
the folder into `averaged.csv` (L\*, a\*, b\* mean and standard
|
||||||
deviation per sample, plus a `dE00` CIEDE2000 column against the
|
deviation per sample, plus a `dE00` CIEDE2000 column against each
|
||||||
reference sample) and a formatted `averaged.html` view, then asks
|
sample's named reference) and a formatted `averaged.html` view, then asks
|
||||||
whether to rebuild the formula table `formula.csv` (default: yes).
|
whether to rebuild the formula table `formula.csv` (default: yes).
|
||||||
|
|
||||||
### Options
|
### Options
|
||||||
@@ -87,15 +87,15 @@ cp samples.example.txt samples.txt
|
|||||||
```
|
```
|
||||||
|
|
||||||
Lines starting with `#` are ignored. Material names can be any codes.
|
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
|
Append ` > REF` to measure that sample's `dE00` against another sample; a
|
||||||
`dE00` column is measured against (if none is marked, the first sample is
|
bare name (no `>`) is itself a **reference**. Mix samples use the pattern
|
||||||
used). Mix samples use the pattern `NAME_A+NAME_B[w1 to w2 mix]`, e.g.:
|
`NAME_A+NAME_B[w1 to w2 mix]`, e.g.:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
*INK_A
|
INK_A
|
||||||
INK_B
|
INK_B > INK_A
|
||||||
INK_A+INK_B[75 to 15 mix]
|
INK_A+INK_B[75 to 15 mix] > INK_A
|
||||||
INK_A+INK_C[30 to 80 mix]
|
INK_A+INK_C[30 to 80 mix] > INK_A
|
||||||
```
|
```
|
||||||
|
|
||||||
The weights are converted to percentages in the formula table
|
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>.tsv` | Raw spotread log (Lab + XYZ + spectrum 380–730 nm) |
|
||||||
| `scan_D50_<timestamp>.csv` | Same data as CSV with `sample_id` column |
|
| `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 |
|
| `averaged.html` | Formatted view of `averaged.csv` with color swatches |
|
||||||
| `formula.csv` | Averaged Lab plus one percentage column per ink |
|
| `formula.csv` | Averaged Lab plus one percentage column per ink |
|
||||||
| `archive/` | Discarded or superseded scans |
|
| `archive/` | Discarded or superseded scans |
|
||||||
|
|||||||
@@ -128,13 +128,13 @@ wait_for_instrument() {
|
|||||||
scan_samples() {
|
scan_samples() {
|
||||||
[[ -f "$SAMPLES_FILE" ]] || fail "$SAMPLES_FILE not found"
|
[[ -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.
|
# A while-read loop is used instead of mapfile for bash 3.2 (macOS) support.
|
||||||
SAMPLES=()
|
SAMPLES=()
|
||||||
while IFS= read -r line; do
|
while IFS= read -r line; do
|
||||||
SAMPLES+=("$line")
|
SAMPLES+=("$line")
|
||||||
done < <(grep -v '^#' "$SAMPLES_FILE" | grep -v '^[[:space:]]*$' \
|
done < <(grep -v '^#' "$SAMPLES_FILE" | grep -v '^[[:space:]]*$' \
|
||||||
| sed -E 's/^[[:space:]]*\*[[:space:]]*//')
|
| sed -E 's/[[:space:]]*>.*$//')
|
||||||
local count="${#SAMPLES[@]}"
|
local count="${#SAMPLES[@]}"
|
||||||
[[ "$count" -gt 0 ]] || fail "No sample names found in $SAMPLES_FILE"
|
[[ "$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.
|
# D50 / 2 deg white point, used to render approximate sRGB swatches from Lab.
|
||||||
WHITE_POINT = (96.422, 100.0, 82.521)
|
WHITE_POINT = (96.422, 100.0, 82.521)
|
||||||
|
|
||||||
# A sample line prefixed with "*" is the Delta-E reference: every other
|
# A sample line may name its Delta-E reference as "NAME > REF". Bare names
|
||||||
# sample's Delta-E is measured against it. The marker is stripped to recover
|
# (no ">") are references themselves. The " > REF" suffix is stripped to
|
||||||
# the real sample name.
|
# recover the real sample name used as sample_id.
|
||||||
REF_MARKER = "*"
|
REF_SEP = ">"
|
||||||
NOTE_PREFIX = "# note:"
|
NOTE_PREFIX = "# note:"
|
||||||
|
|
||||||
|
|
||||||
@@ -35,11 +35,13 @@ def load_notes(path: Path) -> list[str]:
|
|||||||
return notes
|
return notes
|
||||||
|
|
||||||
|
|
||||||
def _strip_ref_marker(name: str) -> str:
|
def _parse_sample_line(line: str) -> tuple[str, str | None]:
|
||||||
"""Remove a leading Delta-E reference marker from a sample name."""
|
"""Return (sample_name, reference_or_None). Bare name = this sample is a reference."""
|
||||||
if name.startswith(REF_MARKER):
|
if REF_SEP in line:
|
||||||
return name[len(REF_MARKER):].strip()
|
name, _, ref = line.partition(REF_SEP)
|
||||||
return name
|
name, ref = name.strip(), ref.strip()
|
||||||
|
return name, ref or None
|
||||||
|
return line.strip(), None
|
||||||
|
|
||||||
|
|
||||||
def _sample_lines(path: Path) -> list[str]:
|
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]:
|
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:
|
def load_references(path: Path) -> dict[str, str]:
|
||||||
"""Return the sample marked with a leading '*', if any."""
|
"""Map sample_id -> reference_id for samples that name a reference."""
|
||||||
|
refs: dict[str, str] = {}
|
||||||
for line in _sample_lines(path):
|
for line in _sample_lines(path):
|
||||||
if line.startswith(REF_MARKER):
|
name, ref = _parse_sample_line(line)
|
||||||
return _strip_ref_marker(line)
|
if ref:
|
||||||
return None
|
refs[name] = ref
|
||||||
|
return refs
|
||||||
|
|
||||||
|
|
||||||
def de2000(lab1, lab2) -> float:
|
def de2000(lab1, lab2) -> float:
|
||||||
@@ -110,31 +114,40 @@ def de2000(lab1, lab2) -> float:
|
|||||||
+ RT * (dCp / SC) * (dHp / SH))
|
+ RT * (dCp / SC) * (dHp / SH))
|
||||||
|
|
||||||
|
|
||||||
def add_delta_e(rows: list[dict], reference: str | None) -> str | None:
|
def add_delta_e(rows: list[dict], references: dict[str, str]) -> bool:
|
||||||
"""Add a CIEDE2000 column to each averaged row, measured against `reference`.
|
"""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
|
Samples absent from `references` are references themselves (dE00 = 0).
|
||||||
added (missing/unknown reference). Never raises so the scan pipeline can
|
Returns True if the column was written (only when at least one sample
|
||||||
continue even when the reference is misconfigured.
|
names a reference). Never raises so the scan pipeline can continue even
|
||||||
|
when a named reference is missing.
|
||||||
"""
|
"""
|
||||||
if not rows:
|
if not rows or not references:
|
||||||
return None
|
return False
|
||||||
|
|
||||||
ref_id = reference or rows[0]["sample_id"]
|
by_id = {r["sample_id"]: r for r in rows}
|
||||||
ref_row = next((r for r in rows if r["sample_id"] == ref_id), None)
|
wrote = False
|
||||||
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)
|
|
||||||
for row in rows:
|
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)
|
lab = tuple(row[f"{c}_mean"] for c in LAB_COLS)
|
||||||
row[DE_COL] = de2000(ref_lab, lab)
|
row[DE_COL] = de2000(ref_lab, lab)
|
||||||
return ref_id
|
wrote = True
|
||||||
|
return wrote
|
||||||
|
|
||||||
|
|
||||||
def srgb(L: float, a: float, b: float) -> str:
|
def srgb(L: float, a: float, b: float) -> str:
|
||||||
@@ -170,10 +183,13 @@ def de_bucket(d: float) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def write_html(
|
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:
|
) -> None:
|
||||||
"""Write a self-contained HTML view of the averaged results."""
|
"""Write a self-contained HTML view of the averaged results."""
|
||||||
has_de = ref_used is not None
|
|
||||||
esc = html.escape
|
esc = html.escape
|
||||||
|
|
||||||
head_cells = [
|
head_cells = [
|
||||||
@@ -187,30 +203,39 @@ def write_html(
|
|||||||
for r in rows:
|
for r in rows:
|
||||||
lab = tuple(float(r[f"{c}_mean"]) for c in LAB_COLS)
|
lab = tuple(float(r[f"{c}_mean"]) for c in LAB_COLS)
|
||||||
std = tuple(float(r[f"{c}_std"]) 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
|
is_pred = int(float(r["n_scans"])) == 0
|
||||||
row_cls = "ref" if is_ref else ("pred" if is_pred else "")
|
row_cls = "ref" if is_ref else ("pred" if is_pred else "")
|
||||||
cls = f' class="{row_cls}"' if row_cls else ""
|
cls = f' class="{row_cls}"' if row_cls else ""
|
||||||
ref_tag = ' <span class="tag">reference</span>' if is_ref 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 ""
|
pred_tag = ' <span class="tag">predicted</span>' if is_pred else ""
|
||||||
cells = [
|
cells = [
|
||||||
f'<td><span class="patch" style="background:{srgb(*lab)}"></span></td>',
|
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>',
|
f'<td>{esc(str(r["n_scans"])) if not is_pred else "—"}</td>',
|
||||||
]
|
]
|
||||||
for m, s in zip(lab, std):
|
for m, s in zip(lab, std):
|
||||||
cells.append(f'<td>{m:.2f}<span class="std">±{s:.2f}</span></td>')
|
cells.append(f'<td>{m:.2f}<span class="std">±{s:.2f}</span></td>')
|
||||||
if has_de:
|
if has_de:
|
||||||
d = float(r[DE_COL])
|
raw = r.get(DE_COL, "")
|
||||||
de_cls = "de win" if is_ref else ("de bad" if d >= 3.5 else "de")
|
if raw == "" or raw is None:
|
||||||
cells.append(f'<td class="{de_cls}" title="{esc(de_bucket(d))}">{d:.2f}</td>')
|
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>')
|
body_rows.append(f' <tr{cls}>{"".join(cells)}</tr>')
|
||||||
|
|
||||||
ref_note = (
|
ref_note = (
|
||||||
f"ΔE00 is CIEDE2000 against <b>{esc(ref_used)}</b>; "
|
"ΔE00 is CIEDE2000 against each sample's named reference "
|
||||||
"lower is a closer match."
|
"(<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
|
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")
|
generated = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||||
notes = notes or []
|
notes = notes or []
|
||||||
@@ -341,7 +366,7 @@ def main() -> int:
|
|||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
|
|
||||||
sample_names = load_sample_names(args.samples) if args.samples.exists() else []
|
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 = []
|
sets = []
|
||||||
for path in args.csv_files:
|
for path in args.csv_files:
|
||||||
@@ -352,12 +377,12 @@ def main() -> int:
|
|||||||
|
|
||||||
averaged = average_sets(sets)
|
averaged = average_sets(sets)
|
||||||
|
|
||||||
ref_used = add_delta_e(averaged, reference)
|
has_de = add_delta_e(averaged, references)
|
||||||
|
|
||||||
fieldnames = ["sample_id", "n_scans"]
|
fieldnames = ["sample_id", "n_scans"]
|
||||||
for col in LAB_COLS:
|
for col in LAB_COLS:
|
||||||
fieldnames.extend([f"{col}_mean", f"{col}_std"])
|
fieldnames.extend([f"{col}_mean", f"{col}_std"])
|
||||||
if ref_used is not None:
|
if has_de:
|
||||||
fieldnames.append(DE_COL)
|
fieldnames.append(DE_COL)
|
||||||
|
|
||||||
with args.output.open("w", newline="", encoding="utf-8") as f:
|
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")
|
html_path = args.output.with_suffix(".html")
|
||||||
notes = load_notes(args.samples) if args.samples.exists() else []
|
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 {len(averaged)} averaged sample(s) to {args.output}")
|
||||||
print(f"Wrote HTML view to {html_path}")
|
print(f"Wrote HTML view to {html_path}")
|
||||||
if ref_used is not None:
|
if has_de:
|
||||||
note = "" if reference else " (no '*'-marked sample; using first sample)"
|
n_ref = sum(1 for r in averaged if r["sample_id"] not in references)
|
||||||
print(f"{DE_COL} computed as CIEDE2000 vs {ref_used!r}{note}")
|
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
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -17,13 +17,13 @@ RESET = "\033[0m"
|
|||||||
|
|
||||||
|
|
||||||
def load_sample_names(path: Path) -> list[str]:
|
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 = []
|
names = []
|
||||||
for line in path.read_text(encoding="utf-8").splitlines():
|
for line in path.read_text(encoding="utf-8").splitlines():
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if line and not line.startswith("#"):
|
if line and not line.startswith("#"):
|
||||||
if line.startswith("*"):
|
if ">" in line:
|
||||||
line = line[1:].strip()
|
line = line.split(">", 1)[0].strip()
|
||||||
names.append(line)
|
names.append(line)
|
||||||
return names
|
return names
|
||||||
|
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
# One sample name per line, in measurement order.
|
# One sample name per line, in measurement order.
|
||||||
# Lines starting with # are ignored.
|
# Lines starting with # are ignored.
|
||||||
#
|
#
|
||||||
# Prefix one sample with * to mark it as the Delta-E reference: every other
|
# Name a Delta-E reference with "NAME > REF": that sample's dE00 (CIEDE2000
|
||||||
# sample's Delta-E (CIEDE2000, written as the dE00 column in averaged.csv) is
|
# in averaged.csv) is measured against REF. A bare name (no ">") is itself a
|
||||||
# measured against it. If none is marked, the first sample is used. Example:
|
# reference. Example:
|
||||||
# *INK_A
|
# INK_A
|
||||||
|
# INK_B > INK_A
|
||||||
#
|
#
|
||||||
# Optional notes for averaged.html (one per line, shown above the results table):
|
# Optional notes for averaged.html (one per line, shown above the results table):
|
||||||
# note: Glaze: CPO1192
|
# note: Glaze: CPO1192
|
||||||
@@ -19,8 +20,8 @@
|
|||||||
#
|
#
|
||||||
# Copy this file to samples.txt and replace with your own materials:
|
# Copy this file to samples.txt and replace with your own materials:
|
||||||
# cp samples.example.txt samples.txt
|
# cp samples.example.txt samples.txt
|
||||||
*INK_A
|
INK_A
|
||||||
INK_B
|
INK_B > INK_A
|
||||||
INK_C
|
INK_C > INK_A
|
||||||
INK_A+INK_B[75 to 15 mix]
|
INK_A+INK_B[75 to 15 mix] > INK_A
|
||||||
INK_A+INK_C[30 to 80 mix]
|
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]:
|
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 = []
|
names = []
|
||||||
for line in path.read_text(encoding="utf-8").splitlines():
|
for line in path.read_text(encoding="utf-8").splitlines():
|
||||||
line = line.strip()
|
line = line.strip()
|
||||||
if line and not line.startswith("#"):
|
if line and not line.startswith("#"):
|
||||||
if line.startswith("*"):
|
if ">" in line:
|
||||||
line = line[1:].strip()
|
line = line.split(">", 1)[0].strip()
|
||||||
names.append(line)
|
names.append(line)
|
||||||
return names
|
return names
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user