#!/usr/bin/env python3 """Was Fig. 3 of the mint paper drawn from the exact numbers in Data Set S1? Rule A11 of RULES_review_addendum_s1.txt, written after a fresh review of the page. Reads Fig. 3E's cells from the PDF's embedded image (extract_pdf_images.py gives it as a PNG) against the figure's own colour bar, and compares them with the workbook under the paper's stated steps (p. 4): median normalisation per sample, log2, row scaling; zeros at one-fifth of the row's smallest positive value; empty rows dropped. Rows are matched one to one by the Hungarian method and each group's column order is chosen to fit best, so the procedure flatters any file; that is why the same procedure is run on files that keep the sample-1 columns and redraw the multipliers, and on the file's own matrix, shuffled, with reading noise. Then PCA under variants of the processing, against the printed 43.2% and 18.4%. A reading of colours can't prove a figure came from another table. If the cells don't match, all this can say is that we couldn't confirm the match. The workbook is read as data (its two data sheets only), and is not hosted: download it from the article's page. Needs numpy, scipy and Pillow. Run with `py -3.12 -I` on this machine. Usage: py -3.12 -I fig3_compare.py """ import itertools import json import re import sys import xml.etree.ElementTree as ET import zipfile from pathlib import Path import numpy as np from PIL import Image from scipy.optimize import linear_sum_assignment sys.stdout.reconfigure(encoding="utf-8") NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}" PERMS = list(itertools.permutations(range(5))) # The figure's groups, left to right, as its header band prints them, and their first column in the workbook (0-based, after the name) FIG_GROUPS = (("SHOOT GMF", 0), ("SHOOT NNMF", 5), ("ROOT NNMF", 15), ("ROOT GMF", 10)) def read_quant(path): z = zipfile.ZipFile(path) rows = [] for row in ET.fromstring(z.read("xl/worksheets/sheet1.xml")).find(NS + "sheetData"): cells = {} for c in row: col = re.match(r"[A-Z]+", c.get("r")).group(0) j = 0 for ch in col: j = j * 26 + ord(ch) - 64 v = c.find(NS + "v") if v is not None and c.get("t") != "s": cells[j] = float(v.text) rows.append(cells) data = [r for r in rows if len(r) == 20] return np.array([[r[j] for j in range(2, 22)] for r in data]) def runs(frac, th): idx = np.where(frac > th)[0] out, start, prev = [], idx[0], idx[0] for i in idx[1:]: if i != prev + 1: out.append((int(start), int(prev))) start = i prev = i out.append((int(start), int(prev))) return out def read_figure(path): im = np.array(Image.open(path).convert("RGB")).astype(float) # The heatmap sits inside this box of the 1800 x 2334 image; its cell borders are a mid grey. x0, x1, y0, y1 = 100, 900, 960, 1900 sub = im[y0:y1, x0:x1] grey = ((sub.max(2) - sub.min(2)) < 16) & (sub.mean(2) > 90) & (sub.mean(2) < 175) cols = runs(grey.mean(0), 0.5) rows = runs(grey.mean(1), 0.5) cols = [(a + x0, b + x0) for a, b in cols] rows = [(a + y0, b + y0) for a, b in rows] col_cells = [(cols[i][1] + 1, cols[i + 1][0] - 1) for i in range(len(cols) - 1)] row_cells = [(rows[i][1] + 1, rows[i + 1][0] - 1) for i in range(len(rows) - 1)] row_cells = [r for r in row_cells if r[1] - r[0] >= 6] # the first gap is the line under the header band cells = np.zeros((len(row_cells), len(col_cells), 3)) for i, (a, b) in enumerate(row_cells): for j, (c, d) in enumerate(col_cells): cells[i, j] = np.median(im[a:b + 1, c:d + 1].reshape(-1, 3), axis=0) # The colour bar and its labels bx0, bx1 = 918, 942 bar = im[930:1370, bx0:bx1].mean(1) colored = np.where(bar.mean(1) < 245)[0] by0 = 930 + colored[0] bar = bar[colored[0]:colored[-1] + 1] # The seven labels, +3 to -3, to the right of the bar: their vertical centres fix the scale lab = im[930:1370, 948:1010].mean(2) < 120 prof = lab.mean(1) > 0 segs = runs(prof.astype(float), 0.5) centres = [930 + (a + b) / 2 for a, b in segs] if len(centres) != 7: raise SystemExit(f"expected 7 labels on the colour bar, found {len(centres)}") slope, intercept = np.polyfit(centres, [3, 2, 1, 0, -1, -2, -3], 1) bar_vals = slope * (by0 + np.arange(len(bar))) + intercept d = ((cells[:, :, None, :] - bar[None, None, :, :]) ** 2).sum(3) return bar_vals[d.argmin(2)], {"rows": len(row_cells), "columns": len(col_cells), "bar_value_range": [round(float(bar_vals.min()), 2), round(float(bar_vals.max()), 2)], "colour_bar_label_centres": centres} def pipeline(A): A = A.copy() A = A[(A > 0).any(axis=1)] for i in range(A.shape[0]): A[i][A[i] == 0] = A[i][A[i] > 0].min() / 5 L = np.log2(A / np.median(A, axis=0)) return (L - L.mean(axis=1, keepdims=True)) / L.std(axis=1, ddof=1, keepdims=True) def fig_order(A): return np.concatenate([A[:, s:s + 5] for _, s in FIG_GROUPS], axis=1) def resid(M): R = M.copy() for g in range(4): R[:, 5 * g:5 * g + 5] -= R[:, 5 * g:5 * g + 5].mean(axis=1, keepdims=True) return R def col_index(p): return sum(([5 * g + k for k in p[g]] for g in range(4)), []) def fit(V, Z, rng, starts=4, sweeps=5): """Row match and column orders. Returns r over all cells, r on within-group residuals, and the median per-row residual r.""" Rv = resid(V) best = None for s in range(starts): p = [tuple(range(5))] * 4 if s == 0 else [PERMS[rng.integers(120)] for _ in range(4)] for _ in range(sweeps): Zp = Z[:, col_index(p)] Rz = resid(Zp) C = ((Rv[:, None, :] - Rz[None, :, :]) ** 2).sum(2) + 0.5 * ((V[:, None, :] - Zp[None, :, :]) ** 2).sum(2) ri, ci = linear_sum_assignment(C) new = [] for g in range(4): a = Rv[ri][:, 5 * g:5 * g + 5] b = resid(Z)[ci][:, 5 * g:5 * g + 5] new.append(PERMS[int(np.argmax([(a * b[:, list(q)]).sum() for q in PERMS]))]) if new == p: break p = new Zp = Z[:, col_index(p)] Rz = resid(Zp) C = ((Rv[:, None, :] - Rz[None, :, :]) ** 2).sum(2) + 0.5 * ((V[:, None, :] - Zp[None, :, :]) ** 2).sum(2) ri, ci = linear_sum_assignment(C) cost = C[ri, ci].sum() if best is None or cost < best[0]: best = (cost, ri, ci, Zp, Rz) _, ri, ci, Zp, Rz = best r_all = np.corrcoef(V[ri].ravel(), Zp[ci].ravel())[0, 1] r_res = np.corrcoef(Rv[ri].ravel(), Rz[ci].ravel())[0, 1] per = [np.corrcoef(Rv[i], Rz[j])[0, 1] for i, j in zip(ri, ci)] return float(r_all), float(r_res), float(np.median(per)) def surrogate(A, rng): out = np.zeros_like(A) for s in (0, 5, 10, 15): s1 = A[:, s] n = len(s1) a = rng.integers(700, 1401, n) / 1000 c = rng.integers(1100, 1601, n) / 1000 b = rng.integers(7000, 14001, n) / 10000 m = rng.integers(900, 1101, n) / 1000 s2 = s1 * a s3 = s1 * c / 1.5 s4 = s2 * b s5 = (s1 + s2 + s3 + s4) / 4 * m out[:, s:s + 5] = np.stack([s1, s2, s3, s4, s5], axis=1) return out def pca_variants(A): res = [] for zero, norm, log, scale in itertools.product(("fifth of row minimum", "add one", "fifth of overall minimum"), ("median", "sum", "none"), ("log2", "log10", "none"), ("pareto", "auto", "none")): X = A[(A > 0).any(axis=1)].copy() if zero == "fifth of row minimum": for i in range(X.shape[0]): X[i][X[i] == 0] = X[i][X[i] > 0].min() / 5 elif zero == "add one": X = X + 1 else: X[X == 0] = X[X > 0].min() / 5 if norm == "median": X = X / np.median(X, axis=0) elif norm == "sum": X = X / X.sum(axis=0) if log == "log2": X = np.log2(X) elif log == "log10": X = np.log10(X) X = X - X.mean(axis=1, keepdims=True) sd = X.std(axis=1, ddof=1, keepdims=True) if scale == "pareto": X = X / np.sqrt(sd) elif scale == "auto": X = X / sd Y = X.T - X.T.mean(axis=0) s = np.linalg.svd(Y, compute_uv=False) ** 2 s = 100 * s / s.sum() res.append({"zeros": zero, "normalisation": norm, "log": log, "scaling": scale, "PC1": round(float(s[0]), 1), "PC2": round(float(s[1]), 1)}) return res def main(): V, grid = read_figure(sys.argv[1]) A = read_quant(sys.argv[2]) outdir = Path(sys.argv[3]) outdir.mkdir(parents=True, exist_ok=True) F = fig_order(A) Z = pipeline(F) rng = np.random.default_rng(20261105) res = {"rules": "RULES_review_addendum_s1.txt, A11", "figure_grid": grid, "file_rows_with_data": int(Z.shape[0]), "file_rows": int(A.shape[0])} r_all, r_res, per = fit(V, Z, rng) res["figure_against_file"] = {"r_all_cells": round(r_all, 3), "r_within_group_residuals": round(r_res, 3), "median_per_row_residual_r": round(per, 3)} print("figure grid", grid) print("figure against file", res["figure_against_file"], flush=True) sur = [] for _ in range(40): sur.append(fit(V, pipeline(surrogate(F, rng)), rng)) sur = np.array(sur) res["figure_against_40_files_with_multipliers_redrawn"] = {"r_all_cells_mean": round(float(sur[:, 0].mean()), 3), "r_within_group_residuals_mean": round(float(sur[:, 1].mean()), 3), "r_within_group_residuals_max": round(float(sur[:, 1].max()), 3), "median_per_row_residual_r_mean": round(float(sur[:, 2].mean()), 3), "median_per_row_residual_r_max": round(float(sur[:, 2].max()), 3)} print("surrogates", res["figure_against_40_files_with_multipliers_redrawn"], flush=True) ctrl = {} for noise in (0.05, 0.1, 0.2, 0.3, 0.4): rr = [] for _ in range(4): rows = rng.permutation(Z.shape[0]) cols = col_index([PERMS[rng.integers(120)] for _ in range(4)]) rr.append(fit(Z[rows][:, cols] + rng.normal(0, noise, Z.shape), Z, rng)) ctrl[str(noise)] = {"r_within_group_residuals": round(float(np.mean([x[1] for x in rr])), 3), "median_per_row_residual_r": round(float(np.mean([x[2] for x in rr])), 3)} res["same_data_control_by_reading_noise_sd"] = ctrl print("control", ctrl, flush=True) v = pca_variants(A) res["PCA_variants"] = {"variants": len(v), "printed_in_Fig_3F": {"PC1": 43.2, "PC2": 18.4}, "PC1_range": [min(x["PC1"] for x in v), max(x["PC1"] for x in v)], "PC2_range": [min(x["PC2"] for x in v), max(x["PC2"] for x in v)], "nearest": min(v, key=lambda x: (x["PC1"] - 43.2) ** 2 + (x["PC2"] - 18.4) ** 2)} print("PCA", res["PCA_variants"]) res["Fig_3F_points_per_group_by_eye"] = 4 with open(outdir / "fig3_compare.json", "w", encoding="utf-8", newline="\n") as fh: json.dump(res, fh, indent=1, ensure_ascii=False) if __name__ == "__main__": main()