#!/usr/bin/env python3 """Check Data Set S1 of the mint paper's supplement against itself and against the paper. Rules: RULES_supplement.txt (D1-D5, A1-A3), and RULES_review_addendum_s1.txt (A4-A9), written after a fresh review of the page. The workbook is read as data: the script unzips it and parses its XML, so nothing in it runs. It reads the two data sheets and no other part of the file. The workbook is the journal's supplement (mmc1.xlsx) and is not hosted here: download it from the article's page and give its path. Needs numpy. Run with `py -3.12 -I` on this machine. Usage: py -3.12 -I recheck_dataset_s1.py """ import json import math import re import sys import xml.etree.ElementTree as ET import zipfile from decimal import Decimal from fractions import Fraction from pathlib import Path import numpy as np sys.stdout.reconfigure(encoding="utf-8") NS = "{http://schemas.openxmlformats.org/spreadsheetml/2006/main}" T_CRIT_8DF = 2.306004135 # two-sided 0.05, Student's t with 8 degrees of freedom def betacf(a, b, x): fpmin = 1e-300 qab, qap, qam = a + b, a + 1.0, a - 1.0 c, d = 1.0, 1.0 - qab * x / qap d = fpmin if abs(d) < fpmin else d d = 1.0 / d h = d for m in range(1, 500): m2 = 2 * m aa = m * (b - m) * x / ((qam + m2) * (a + m2)) d = 1.0 + aa * d d = fpmin if abs(d) < fpmin else d c = 1.0 + aa / c c = fpmin if abs(c) < fpmin else c d = 1.0 / d h *= d * c aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2)) d = 1.0 + aa * d d = fpmin if abs(d) < fpmin else d c = 1.0 + aa / c c = fpmin if abs(c) < fpmin else c d = 1.0 / d de = d * c h *= de if abs(de - 1.0) < 3e-14: break return h def betai(a, b, x): if x <= 0.0: return 0.0 if x >= 1.0: return 1.0 bt = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log(1.0 - x)) if x < (a + 1.0) / (a + b + 2.0): return bt * betacf(a, b, x) / a return 1.0 - bt * betacf(b, a, 1.0 - x) / b def p_from_t(t, df): if t == 0: return 1.0 return betai(df / 2.0, 0.5, df / (df + t * t)) def student(m1, s1, n1, m2, s2, n2): df = n1 + n2 - 2 sp2 = ((n1 - 1) * s1 ** 2 + (n2 - 1) * s2 ** 2) / df if sp2 == 0: return float("inf") if m1 != m2 else 0.0, 0.0 if m1 != m2 else 1.0 t = abs(m1 - m2) / math.sqrt(sp2 * (1 / n1 + 1 / n2)) return t, p_from_t(t, df) def welch(m1, s1, n1, m2, s2, n2): v1, v2 = s1 ** 2 / n1, s2 ** 2 / n2 if v1 + v2 == 0: return 0.0 if m1 != m2 else 1.0 t = abs(m1 - m2) / math.sqrt(v1 + v2) df = (v1 + v2) ** 2 / (v1 ** 2 / (n1 - 1) + v2 ** 2 / (n2 - 1)) return p_from_t(t, df) def bh(ps, q=0.05): order = sorted(range(len(ps)), key=lambda i: ps[i]) m, kmax = len(ps), 0 for rank, i in enumerate(order, 1): if ps[i] <= q * rank / m: kmax = rank return sorted(order[:kmax]) def holm(ps, a=0.05): order = sorted(range(len(ps)), key=lambda i: ps[i]) keep = [] for rank, i in enumerate(order): if ps[i] <= a / (len(ps) - rank): keep.append(i) else: break return sorted(keep) def read_workbook(path): """Only the two data sheets and the shared strings; also the count of formula cells in each sheet.""" z = zipfile.ZipFile(path) shared = ["".join(t.text or "" for t in si.iter(NS + "t")) for si in ET.fromstring(z.read("xl/sharedStrings.xml")).findall(NS + "si")] sheets, formulas = {}, {} for i, nm in ((1, "quant"), (2, "annot")): rows, nf = [], 0 for row in ET.fromstring(z.read(f"xl/worksheets/sheet{i}.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") nf += c.find(NS + "f") is not None cells[j] = "" if v is None else (shared[int(v.text)] if c.get("t") == "s" else v.text) rows.append(cells) sheets[nm], formulas[nm] = rows, nf return sheets, formulas def plain(o): """numpy scalars to plain Python, for JSON.""" return o.item() if hasattr(o, "item") else str(o) def stored(text): """A stored cell as an exact fraction of its shortest round-trip decimal: what the file displays.""" return Fraction(Decimal(repr(float(text)))) def sigfigs(text): d = Decimal(repr(float(text))).normalize() return len(d.as_tuple().digits) if d != 0 else 0 def round_sig(x, n=10): """Round an exact fraction to n significant figures, half up, as an exact fraction.""" if x == 0: return x sign = 1 if x > 0 else -1 x = abs(x) e = 0 while x >= Fraction(10) ** (e + 1): e += 1 while x < Fraction(10) ** e: e -= 1 unit = Fraction(10) ** (e - n + 1) return sign * math.floor(x / unit + Fraction(1, 2)) * unit def t_counts(gg, nn): """Student's t, vectorised over rows, for rule A6: how many rows have P < 0.05, among rows not all zero.""" keep = ~((gg == 0).all(axis=1) & (nn == 0).all(axis=1)) a, b = gg[keep], nn[keep] sp2 = (a.var(axis=1, ddof=1) + b.var(axis=1, ddof=1)) / 2 t = np.abs(a.mean(axis=1) - b.mean(axis=1)) / np.sqrt(sp2 * 2 / 5) return int((t > T_CRIT_8DF).sum()), int(keep.sum()) def main(): sheets, formula_cells = read_workbook(sys.argv[1]) outdir = Path(sys.argv[2]) outdir.mkdir(parents=True, exist_ok=True) res = {"rules": ["RULES_supplement.txt", "RULES_review_addendum_s1.txt"]} q = sheets["quant"] header = [q[1][j] for j in range(2, 22)] names = [re.sub(r"\s+", " ", r[1]).strip() for r in q[3:]] # some names carry stray spaces A = np.array([[float(r[j]) for j in range(2, 22)] for r in q[3:]]) raw = [[r[j] for j in range(2, 22)] for r in q[3:]] annotated = {re.sub(r"\s+", " ", r[1]).strip(): (r[2].strip(), r[4].strip()) for r in sheets["annot"][2:] if r.get(1)} # The annotation sheet lists fewer rows than the data sheet, so aglycone and conjugation are taken from each row's name. annot = {} for n in names: if " O-" in n: ag, cj = n.split(" O-", 1) annot[n] = (ag, cj[0].upper() + cj[1:]) else: annot[n] = (n, "Aglycone") disagree = [n for n in annotated if n in annot and (annotated[n][0].lower() != annot[n][0].lower() or annotated[n][1].lower() != annot[n][1].lower())] res["S1_annotation"] = {"annotated_rows": len(annotated), "data_rows": len(names), "data_rows_not_annotated": [n for n in names if n not in annotated], "annotated_not_in_data": [n for n in annotated if n not in annot], "class_from_name_disagrees_with_annotation": disagree, "not_annotated_all_zero": sum(1 for n in names if n not in annotated and (A[names.index(n)] == 0).all())} print("Annotation:", res["S1_annotation"]) groups = {"GMF_SHOOT": A[:, 0:5], "NNMF_SHOOT": A[:, 5:10], "GMF_ROOT": A[:, 10:15], "NNMF_ROOT": A[:, 15:20]} assert [h[:-2] for h in header[0:5]] == ["GMF_SHOOT"] * 5 res["S1_shape"] = {"rows": len(names), "samples": len(header), "aglycones": len({annot[n][0] for n in names}), "conjugations": len({annot[n][1] for n in names})} print("\nData Set S1:", res["S1_shape"]) # D1-D3: tests that treat the columns as independent S1 = {} allp = [] for organ, gg, nn in (("shoot", groups["GMF_SHOOT"], groups["NNMF_SHOOT"]), ("root", groups["GMF_ROOT"], groups["NNMF_ROOT"])): ps, labs, up, down, both_zero, one_group = [], [], 0, 0, 0, [] pw, plog = [], [] for i, name in enumerate(names): a, b = gg[i], nn[i] if (a == 0).all() and (b == 0).all(): both_zero += 1 continue if (a == 0).all() or (b == 0).all(): one_group.append(name) p = student(a.mean(), a.std(ddof=1), 5, b.mean(), b.std(ddof=1), 5)[1] ps.append(p) labs.append(name) if p < 0.05: up += int(b.mean() > a.mean()) down += int(b.mean() < a.mean()) pw.append(welch(a.mean(), a.std(ddof=1), 5, b.mean(), b.std(ddof=1), 5)) if (a > 0).all() and (b > 0).all(): la, lb = np.log2(a), np.log2(b) plog.append(student(la.mean(), la.std(ddof=1), 5, lb.mean(), lb.std(ddof=1), 5)[1]) keep = bh(ps) S1[organ] = {"tested": len(ps), "zero_in_all_ten": both_zero, "present_in_one_group_only": len(one_group), "one_group_rows": one_group, "P_below_05": sum(p < 0.05 for p in ps), "higher_in_NNMF": up, "lower_in_NNMF": down, "expected_by_chance": round(0.05 * len(ps), 1), "BH_survivors": len(keep), "BH_survivor_rows": [labs[i] for i in keep], "Holm_survivors": len(holm(ps)), "welch_P_below_05": sum(p < 0.05 for p in pw), "welch_BH": len(bh(pw)), "log2_rows": len(plog), "log2_P_below_05": sum(p < 0.05 for p in plog), "log2_BH": len(bh(plog))} allp += ps keep_all = bh(allp) S1["both_organs"] = {"tested": len(allp), "P_below_05": sum(p < 0.05 for p in allp), "BH_survivors": len(keep_all), "Holm_survivors": len(holm(allp)), "expected_by_chance": round(0.05 * len(allp), 1)} res["S1_tests"] = S1 print(json.dumps({k: {x: y for x, y in v.items() if x not in ("one_group_rows", "BH_survivor_rows")} for k, v in S1.items()}, indent=1, default=plain)) # D4: class shares agl_order, conj_order = [], [] for n in names: if annot[n][0] not in agl_order: agl_order.append(annot[n][0]) if annot[n][1] not in conj_order: conj_order.append(annot[n][1]) classes = {} print("\nClass shares of each sample's total, mean % by group, with Student's P (n = 5):") for organ, gg, nn in (("shoot", groups["GMF_SHOOT"], groups["NNMF_SHOOT"]), ("root", groups["GMF_ROOT"], groups["NNMF_ROOT"])): ta, tb = gg.sum(axis=0), nn.sum(axis=0) for kind, order, idx in (("aglycone", agl_order, 0), ("conjugation", conj_order, 1)): for cl in order: mask = np.array([annot[n][idx] == cl for n in names]) sa, sb = 100 * gg[mask].sum(axis=0) / ta, 100 * nn[mask].sum(axis=0) / tb p = student(sa.mean(), sa.std(ddof=1), 5, sb.mean(), sb.std(ddof=1), 5)[1] classes[f"{organ}|{kind}|{cl}"] = {"GMF_pct": round(float(sa.mean()), 2), "NNMF_pct": round(float(sb.mean()), 2), "P": round(p, 4)} print(f" {organ:<5} {kind:<11} {cl:<24} {sa.mean():7.2f} {sb.mean():7.2f} P={p:.4f}") res["S1_class_shares"] = classes # D4 and A7: the summed areas, with five columns and with the sample-1 columns alone totals = {} for organ, gg, nn in (("shoot", groups["GMF_SHOOT"], groups["NNMF_SHOOT"]), ("root", groups["GMF_ROOT"], groups["NNMF_ROOT"])): ta, tb = gg.sum(axis=0), nn.sum(axis=0) p = student(ta.mean(), ta.std(ddof=1), 5, tb.mean(), tb.std(ddof=1), 5)[1] totals[organ] = {"GMF_total_area": float(ta.mean()), "NNMF_total_area": float(tb.mean()), "change_pct": round(100 * (tb.mean() - ta.mean()) / ta.mean(), 1), "P": round(p, 4), "ratio_five_columns": round(float(tb.mean() / ta.mean()), 3), "ratio_sample_1_alone": round(float(tb[0] / ta[0]), 3)} res["S1_total_area"] = totals print("Total summed area:", totals) # D5: arithmetic between columns TOL = 1.5e-9 def share(v, b, d): m = (b != 0) & (v != 0) r = v[m] / b[m] k = 10.0 ** d return int(np.sum(np.abs(r * k - np.round(r * k)) / (np.abs(r) * k) < TOL)), int(m.sum()) arith = {} print("\nArithmetic between columns (matches / non-zero rows):") for g, X in groups.items(): c1, c2, c3, c4, c5 = [X[:, i] for i in range(5)] whole = [int(np.sum(c == np.round(c))) for c in (c1, c2, c3, c4, c5)] zero_rows = c1 == 0 rec = { "whole_numbers_by_column": whole, "rows_with_c1_zero": int(zero_rows.sum()), "others_nonzero_where_c1_zero": int((X[zero_rows, 1:] != 0).sum()), "c1_nonzero_but_another_zero": int((X[~zero_rows, 1:] == 0).any(axis=1).sum()), "c2 = c1 x (<=3 decimals)": share(c2, c1, 3), "c4 = c2 x (<=4 decimals)": share(c4, c2, 4), "c3 = c1 x (<=3 decimals)": share(c3, c1, 3), "3 x c3 = c1 x (<=3 decimals)": share(3 * c3, c1, 3), "1.5 x c3 = c1 x (<=3 decimals)": share(1.5 * c3, c1, 3), "c5 = mean(c1..c4) x (<=3 decimals)": share(c5, (c1 + c2 + c3 + c4) / 4, 3), "control: c5 = c1 x (<=3 decimals)": share(c5, c1, 3), "control: c4 = c1 x (<=4 decimals)": share(c4, c1, 4), "control: c3 = c2 x (<=3 decimals)": share(c3, c2, 3), } m = c1 != 0 rec["ranges"] = {"c2/c1": [round(float((c2[m] / c1[m]).min()), 3), round(float((c2[m] / c1[m]).max()), 3)], "c4/c2": [round(float((c4[m] / c2[m]).min()), 4), round(float((c4[m] / c2[m]).max()), 4)], "1.5c3/c1": [round(float((1.5 * c3[m] / c1[m]).min()), 3), round(float((1.5 * c3[m] / c1[m]).max()), 3)], "c5/mean": [round(float((c5[m] / ((c1 + c2 + c3 + c4)[m] / 4)).min()), 3), round(float((c5[m] / ((c1 + c2 + c3 + c4)[m] / 4)).max()), 3)]} rec["distinct_values_of_c2_over_c1"] = len({round(float(x), 3) for x in c2[m] / c1[m]}) # A9: a normalisation would give one value down a column arith[g] = rec print(" ", g, json.dumps(rec, default=plain)) tot = {} for key in ("c2 = c1 x (<=3 decimals)", "c4 = c2 x (<=4 decimals)", "3 x c3 = c1 x (<=3 decimals)", "1.5 x c3 = c1 x (<=3 decimals)", "c5 = mean(c1..c4) x (<=3 decimals)", "control: c5 = c1 x (<=3 decimals)", "control: c4 = c1 x (<=4 decimals)", "control: c3 = c2 x (<=3 decimals)"): tot[key] = [sum(arith[g][key][0] for g in groups), sum(arith[g][key][1] for g in groups)] res["S1_arithmetic"] = {"tolerance_relative": TOL, "by_group": arith, "totals": tot, "chance_per_cell_unrelated_numbers": {"3 decimals": 2 * TOL * 1e3 * 1.0, "4 decimals": 2 * TOL * 1e4 * 1.0}, "note": "Chance for a ratio near 1: twice the relative tolerance divided by the spacing of the decimals."} print("Totals:", tot) print("Chance per cell for unrelated numbers: 3 decimals %.1e, 4 decimals %.1e" % (2 * TOL * 1e3, 2 * TOL * 1e4)) # Addendum A1-A3 (see RULES_supplement.txt) keys = list(groups) a1 = {f"{a} / {b}": share(groups[a][:, 0], groups[b][:, 0], 4) for a in keys for b in keys if a != b} X = A[(A > 0).any(axis=1)].copy() for i in range(X.shape[0]): X[i][X[i] == 0] = X[i][X[i] > 0].min() / 5 L = np.log2(X / np.median(X, axis=0)) P = (L - L.mean(axis=1, keepdims=True)) / np.sqrt(L.std(axis=1, ddof=1, keepdims=True)) ev = np.linalg.svd(P.T, compute_uv=False) ** 2 ev = ev / ev.sum() def c21(X): m = X[:, 0] != 0 r = np.full(X.shape[0], np.nan) r[m] = X[m, 1] / X[m, 0] return r a3 = {} for i, a in enumerate(keys): for b in keys[i + 1:]: ra, rb = c21(groups[a]), c21(groups[b]) m = ~np.isnan(ra) & ~np.isnan(rb) a3[f"{a} vs {b}"] = {"rows": int(m.sum()), "r": round(float(np.corrcoef(ra[m], rb[m])[0, 1]), 3)} res["S1_addendum"] = {"A1_column1_across_groups_matches_at_up_to_4_decimals": a1, "A2_PCA_our_run": {"PC1_pct": round(100 * float(ev[0]), 1), "PC2_pct": round(100 * float(ev[1]), 1), "paper_Fig3F": [43.2, 18.4], "note": "Not reproduced; the paper does not give every processing step."}, "A3_multiplier_c2_over_c1_across_groups": a3} print("Addendum:", json.dumps(res["S1_addendum"], default=plain)) # A4, A5: the chain, in exact arithmetic, digit for digit at 10 significant figures chain = {"s2": 0, "s3": 0, "s4": 0, "s5": 0, "rows": 0, "s4_through_stored_s2": 0, "s5_through_stored_values": 0, "c_has_at_most_3_decimals": 0} c_values, single_matches = [], [] for row, name in zip(raw, names): for gi, g in enumerate(groups): vals = [stored(x) for x in row[gi * 5:gi * 5 + 5]] if vals[0] == 0: continue chain["rows"] += 1 s1, s2, s3, s4, s5 = vals a = Fraction(round(float(s2 / s1) * 1000), 1000) c = Fraction(round(float(Fraction(3, 2) * s3 / s1) * 1000), 1000) b = Fraction(round(float(s4 / s2) * 10000), 10000) m = Fraction(round(float(s5 / ((s1 + s2 + s3 + s4) / 4)) * 1000), 1000) c_values.append(float(c)) S2 = s1 * a S3 = s1 * c * Fraction(2, 3) S4 = S2 * b S5 = (s1 + S2 + S3 + S4) / 4 * m chain["s2"] += round_sig(S2) == s2 chain["s3"] += round_sig(S3) == s3 chain["s4"] += round_sig(S4) == s4 chain["s5"] += round_sig(S5) == s5 chain["s4_through_stored_s2"] += round_sig(s2 * b) == s4 chain["s5_through_stored_values"] += round_sig((s1 + s2 + s3 + s4) / 4 * m) == s5 chain["c_has_at_most_3_decimals"] += abs(float(Fraction(3, 2) * s3 / s1) - float(c)) / float(c) < TOL # A9: the rows behind the single matches of the checks r41 = float(s4 / s1) if abs(r41 * 1e4 - round(r41 * 1e4)) / (r41 * 1e4) < TOL: single_matches.append({"group": g, "row": name, "check": "sample 4 on sample 1", "ratio": round(r41, 4), "a": float(a), "b": float(b), "a_times_b": round(float(a * b), 7)}) r32 = float(s3 / s2) if abs(r32 * 1e3 - round(r32 * 1e3)) / (r32 * 1e3) < TOL: single_matches.append({"group": g, "row": name, "check": "sample 3 on sample 2", "ratio": round(r32, 3), "a": float(a), "c_over_1_5": round(float(c * Fraction(2, 3)), 7), "ratio_from_chain": round(float(c * Fraction(2, 3) / a), 7)}) chain["all_values_reproduced"] = chain["s2"] + chain["s3"] + chain["s4"] + chain["s5"] chain["all_values"] = 4 * chain["rows"] chain["c_range"] = [min(c_values), max(c_values)] res["S1_chain"] = chain res["S1_single_matches_in_the_checks"] = single_matches print("Chain:", chain) print("Single matches:", single_matches) # A6: keep the sample-1 columns, redraw every multiplier rng = np.random.default_rng(20261104) def redraw(s1): 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 return np.stack([s1, s2, s3, s4, s5], axis=1) obs = sum(t_counts(groups[f"GMF_{o}"], groups[f"NNMF_{o}"])[0] for o in ("SHOOT", "ROOT")) counts, tested = [], 0 for _ in range(2000): n05, tested = 0, 0 for o in ("SHOOT", "ROOT"): k, t = t_counts(redraw(groups[f"GMF_{o}"][:, 0]), redraw(groups[f"NNMF_{o}"][:, 0])) n05 += k tested += t counts.append(n05) res["S1_redrawn_multipliers"] = {"draws": 2000, "seed": 20261104, "tested": tested, "observed_count": obs, "mean": round(float(np.mean(counts)), 1), "sd": round(float(np.std(counts, ddof=1)), 1), "min": int(min(counts)), "max": int(max(counts))} print("Redrawn multipliers:", res["S1_redrawn_multipliers"]) # A8: what the workbook holds annot_rows = sheets["annot"] head_row = next(i for i, r in enumerate(annot_rows) if any("max" in str(v) for v in r.values())) uv_col = next(j for j, v in annot_rows[head_row].items() if "max" in str(v)) uv = [r[uv_col] for r in annot_rows[head_row + 1:] if r.get(uv_col)] firsts = sorted({u.split(";")[0].strip() for u in uv}) seconds = [int(u.split(";")[1]) for u in uv] all_cells = [x for row in raw for x in row] res["S1_workbook"] = {"formula_cells": formula_cells, "largest_significant_figures_stored": max(sigfigs(x) for x in all_cells), "rows": len(names), "rows_zero_in_all_20_samples": int((A == 0).all(axis=1).sum()), "rows_with_data": int((A != 0).any(axis=1).sum()), "UV_lambda_max_header": annot_rows[head_row][uv_col], "UV_rows": len(uv), "UV_first_values": firsts, "UV_second_value_first_and_last": [seconds[0], seconds[-1]], "UV_second_value_rises_by_1_every_row": all(y - x == 1 for x, y in zip(seconds, seconds[1:]))} print("Workbook:", res["S1_workbook"]) with open(outdir / "recheck_dataset_s1.json", "w", encoding="utf-8", newline="\n") as fh: json.dump(res, fh, indent=1, ensure_ascii=False, default=plain) if __name__ == "__main__": main()