"""Independent re-derivation of differential expression (RULES_rederive.txt). Data only. Fact-Checked Science ("Our analysis"), https://factchecked.science/planthopper-magnetic-genes/ Data: Xie, W., et al. (2026), Dryad, doi:10.5061/dryad.r4xgxd2vx (CC0); make the input folder with prepare_inputs.py, then pass /dataset (or /field for igrf_route.py) as the script's usage says. Method A: negative-binomial Wald test with a shared (DESeq2-form) dispersion trend. Method B: moderated t on log normalized counts (limma-style empirical Bayes, global prior). Usage: python3 rederive.py Writes rederive.json and rederive_genes_.csv (method A, primary) into out_folder. """ import json import math import os import sys import numpy as np import pandas as pd from scipy import special, stats sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from xlsx_reader import read_xlsx # noqa: E402 COUNTS = "Raw_data_for_RNAseq_count_matrix.csv" FIG1 = "Raw_data_for_Figure1-Complete list of differentially expressed genes in all comparisons.xlsx" GROUPS = {"GMF45": ["GMF45_1", "GMF45_2", "GMF45_3"], "GMF50": ["GMF50_1", "GMF50_2", "GMF50_3"], "NZMF": ["NZMF_1", "NZMF_2"]} COMPARISONS = [("GMF50", "GMF45"), ("NZMF", "GMF45"), ("NZMF", "GMF50")] SHEET = {("GMF50", "GMF45"): "DEG_GMF50_vs_GMF45", ("NZMF", "GMF45"): "DEG_NZMF_vs_GMF45", ("NZMF", "GMF50"): "DEG_NZMF_vs_GMF50"} AUTHORS = {("GMF50", "GMF45"): 244, ("NZMF", "GMF45"): 3258, ("NZMF", "GMF50"): 2753} # ---------------------------------------------------------------- shared pieces def size_factors(K): pos = (K > 0).all(axis=1) lk = np.log(K[pos]) return np.exp(np.median(lk - lk.mean(axis=1, keepdims=True), axis=0)) def bh(p): p = np.asarray(p, float) n = len(p) o = np.argsort(p) r = p[o] * n / np.arange(1, n + 1) q = np.minimum.accumulate(r[::-1])[::-1] out = np.empty(n) out[o] = np.minimum(q, 1) return out def mom_dispersion(K, s, labels): """Gene-wise method-of-moments dispersion pooled within groups (RULES A3).""" q = K / s N = K.shape[1] G = len(set(labels)) m_full = np.zeros_like(q) for g in set(labels): idx = [j for j, l in enumerate(labels) if l == g] m = q[:, idx].mean(axis=1) m_full[:, idx] = m[:, None] v = ((q - m_full) ** 2).sum(axis=1) / (N - G) pois = (m_full / s).mean(axis=1) den = (m_full ** 2).mean(axis=1) with np.errstate(divide="ignore", invalid="ignore"): a = (v - pois) / den return a def gamma_identity(y, x, start): X = np.column_stack([np.ones_like(x), x]) beta = np.array(start, float) for _ in range(100): mu = np.maximum(X @ beta, 1e-12) w = 1.0 / mu ** 2 WX = X * w[:, None] new = np.linalg.solve(X.T @ WX, WX.T @ y) if np.max(np.abs(new - beta)) <= 1e-12 * (np.max(np.abs(beta)) + 1e-12): beta = new break beta = new return beta def trend_fit(alpha_hat, base_mean): """DESeq2-form trend a0 + a1/mu (RULES A4); fallback to binned medians.""" ok = np.isfinite(alpha_hat) & (alpha_hat > 1e-8) & (base_mean > 0) a, m = alpha_hat[ok], base_mean[ok] coefs = np.array([0.1, 1.0]) info = {"method": "parametric", "rounds": 0, "converged": False} for rnd in range(1, 11): res = a / (coefs[0] + coefs[1] / m) good = (res > 1e-4) & (res < 15) old = coefs coefs = gamma_identity(a[good], 1.0 / m[good], old) info["rounds"] = rnd if not (coefs[0] > 0 and coefs[1] > 0): break if np.sum(np.abs(np.log(coefs / old))) < 1e-6: info["converged"] = True break if coefs[0] > 0 and coefs[1] > 0: info["a0"], info["a1"] = float(coefs[0]), float(coefs[1]) c0, c1 = coefs def f(mu): return c0 + c1 / np.maximum(mu, 1e-12) return f, info # fallback: 20 equal-count bins of baseMean, median alpha_hat, interpolation in log baseMean info = {"method": "fallback_binned", "failed_coefs": [float(coefs[0]), float(coefs[1])]} order = np.argsort(m) bins = np.array_split(order, 20) xs = np.array([np.log(np.median(m[b])) for b in bins]) ys = np.array([np.median(a[b]) for b in bins]) def f(mu): return np.interp(np.log(np.maximum(mu, 1e-12)), xs, ys) return f, info def nb_group_mean(K, s, alpha, maxit=50, tol=1e-10): """NB MLE of a group mean with size-factor offsets (Fisher scoring on log mu). K: genes x samples.""" tot = K.sum(axis=1) mu = tot / s.sum() zero = tot == 0 mu[zero] = 0.5 / s.sum() beta = np.log(mu) act = ~zero for _ in range(maxit): if not act.any(): break m = np.exp(beta[act])[:, None] sm = s[None, :] * m a = alpha[act][:, None] U = ((K[act] - sm) / (1 + a * sm)).sum(axis=1) I = (sm / (1 + a * sm)).sum(axis=1) step = U / I beta[act] += step done = np.abs(step) < tol idx = np.where(act)[0] act[idx[done]] = False mu = np.exp(beta) I = (s[None, :] * mu[:, None] / (1 + alpha[:, None] * s[None, :] * mu[:, None])).sum(axis=1) return mu, I, zero def method_a(K, s, labels, num, ref, base_mean, variant="trend"): """Returns per-gene log2FC, p for num vs ref. K/s cover the scope's samples; labels align with columns.""" ah = mom_dispersion(K, s, labels) f, info = trend_fit(ah, base_mean) tr = f(base_mean) if variant == "trend": alpha = tr else: alpha = np.where(np.isfinite(ah), np.maximum(ah, tr), tr) alpha = np.maximum(alpha, 1e-8) in_num = [j for j, l in enumerate(labels) if l == num] in_ref = [j for j, l in enumerate(labels) if l == ref] mu1, I1, z1 = nb_group_mean(K[:, in_num], s[in_num], alpha) mu2, I2, z2 = nb_group_mean(K[:, in_ref], s[in_ref], alpha) lfc = (np.log(mu1) - np.log(mu2)) / math.log(2) se = np.sqrt(1 / I1 + 1 / I2) / math.log(2) z = lfc / se p = 2 * stats.norm.sf(np.abs(z)) both0 = z1 & z2 lfc[both0] = 0.0 p[both0] = 1.0 return lfc, p, info def trigamma_inverse(x): y = 0.5 + 1.0 / x for _ in range(50): tri = special.polygamma(1, y) dif = tri * (1 - tri / x) / special.polygamma(2, y) y = y + dif if -dif / y < 1e-8: break return y def method_b(K, s, labels, num, ref): y = np.log2(K + 0.5) - np.log2(s)[None, :] in_num = [j for j, l in enumerate(labels) if l == num] in_ref = [j for j, l in enumerate(labels) if l == ref] a, b = y[:, in_num], y[:, in_ref] n1, n2 = len(in_num), len(in_ref) d = n1 + n2 - 2 diff = a.mean(axis=1) - b.mean(axis=1) s2 = (((a - a.mean(axis=1, keepdims=True)) ** 2).sum(axis=1) + ((b - b.mean(axis=1, keepdims=True)) ** 2).sum(axis=1)) / d pos = s2 > 0 e = np.log(s2[pos]) - special.digamma(d / 2) + math.log(d / 2) G = len(e) evar = np.mean((e - e.mean()) ** 2) * G / (G - 1) - special.polygamma(1, d / 2) if evar > 0: d0 = 2 * trigamma_inverse(evar) s0 = math.exp(e.mean() + special.digamma(d0 / 2) - math.log(d0 / 2)) st2 = (d0 * s0 + d * s2) / (d0 + d) t = diff / np.sqrt(st2 * (1 / n1 + 1 / n2)) p = 2 * stats.t.sf(np.abs(t), d + d0) else: d0 = float("inf") s0 = math.exp(e.mean()) t = diff / np.sqrt(s0 * (1 / n1 + 1 / n2)) p = 2 * stats.norm.sf(np.abs(t)) return diff, p, {"d0": float(d0), "s0_sq": float(s0)} def call(lfc, p, thr=0.25, alpha=0.05, base_mean=None, indep=False): if not indep: padj = bh(p) sel = (padj < alpha) & (np.abs(lfc) > thr) return sel, padj, None best = None for theta in np.arange(0, 0.951, 0.05): cut = np.quantile(base_mean, theta) if theta > 0 else -np.inf keep = base_mean >= cut if theta > 0 else np.ones_like(base_mean, bool) padj = np.full(len(p), np.nan) padj[keep] = bh(p[keep]) nrej = int(np.nansum(padj < alpha)) if best is None or nrej > best[1]: best = (round(float(theta), 2), nrej, padj) padj = best[2] sel = (np.nan_to_num(padj, nan=1.0) < alpha) & (np.abs(lfc) > thr) return sel, padj, {"theta": best[0], "rejections_no_lfc": best[1]} def load_counts(folder): cm = pd.read_csv(os.path.join(folder, COUNTS)) cm = cm.set_index(cm.columns[0]) nonint = int((~cm.map(lambda v: float(v).is_integer() and float(v) >= 0)).values.sum()) return cm.round().astype(np.int64), nonint def load_authors(folder): wb = read_xlsx(os.path.join(folder, FIG1)) out = {} for key, sh in SHEET.items(): rows = wb[sh]["rows"][1:] df = pd.DataFrame([[r[0], float(r[2]), np.nan if r[5] in (None, "NA") else float(r[5]), np.nan if r[6] in (None, "NA") else float(r[6])] for r in rows if r], columns=["gene", "lfc", "pvalue", "padj"]).set_index("gene") df["deg"] = (df["padj"] < 0.05) & (df["lfc"].abs() > 0.25) out[key] = df return out def label(ours, theirs): if theirs == 0: return "n/a" r = ours / theirs if 0.75 <= r <= 1.25: return "close" if 1 / 3 <= r <= 3: return "same order of magnitude" return "different order of magnitude" def compare(genes, lfc, p, sel, auth): a = auth.reindex(genes) ours = set(np.array(genes)[sel]) theirs = set(auth.index[auth["deg"]]) common = len(ours & theirs) both = a["lfc"].notna().values rho_l = stats.spearmanr(lfc[both], a["lfc"].values[both]).statistic okp = both & a["pvalue"].notna().values & (p > 0) rho_p = stats.spearmanr(-np.log10(p[okp]), -np.log10(a["pvalue"].values[okp])).statistic return {"ours": int(sel.sum()), "authors": int(len(theirs)), "common": common, "share_of_authors_recovered": common / len(theirs) if theirs else None, "jaccard": common / len(ours | theirs) if (ours | theirs) else None, "spearman_log2FC": float(rho_l), "spearman_minus_log10_p": float(rho_p)} def run_scope(cm, samples, labels, auth, scope_name, out_folder=None, write_genes=False): """One scope: filter >= 6 over 'samples'; size factors from 'samples'. For 'one model' the dispersion uses all samples in the scope; for per-comparison scopes the caller passes only the two groups.""" K_all = cm[samples].values.astype(float) keep = K_all.sum(axis=1) >= 6 genes = cm.index[keep].values K = K_all[keep] s = size_factors(K) base = (K / s).mean(axis=1) res = {"n_genes": int(keep.sum()), "size_factors": dict(zip(samples, [float(x) for x in s])), "comparisons": {}} comps = [c for c in COMPARISONS if c[0] in labels and c[1] in labels] for num, ref in comps: key = num + "_vs_" + ref r = {} for variant in ("trend", "conservative"): lfc, p, info = method_a(K, s, labels, num, ref, base, variant) for indep in (False, True): sel, padj, finfo = call(lfc, p, base_mean=base, indep=indep) nm = "A_" + variant + ("_indepfilter" if indep else "") c = compare(genes, lfc, p, sel, auth[(num, ref)]) c.update({"up": int((sel & (lfc > 0)).sum()), "down": int((sel & (lfc < 0)).sum()), "label_vs_authors": label(c["ours"], AUTHORS[(num, ref)]), "trend": info, "filter": finfo}) r[nm] = c if write_genes and variant == "trend" and not indep and out_folder: pd.DataFrame({"gene": genes, "baseMean": base, "log2FC": lfc, "pvalue": p, "padj": padj, "DEG": sel}).to_csv(os.path.join(out_folder, "rederive_genes_%s.csv" % key), index=False, lineterminator="\n", float_format="%.6g") lfcb, pb, binfo = method_b(K, s, labels, num, ref) selb, _, _ = call(lfcb, pb) cb = compare(genes, lfcb, pb, selb, auth[(num, ref)]) cb.update({"up": int((selb & (lfcb > 0)).sum()), "down": int((selb & (lfcb < 0)).sum()), "label_vs_authors": label(cb["ours"], AUTHORS[(num, ref)]), "prior": binfo}) r["B"] = cb res["comparisons"][key] = r return res def descriptive(cm): s9 = sum(GROUPS.values(), []) + ["NZMF_3"] lib = cm[s9].sum(axis=0) det = (cm[s9] > 0).sum(axis=0) K = cm[s9].values.astype(float) keep = K.sum(axis=1) >= 6 K = K[keep] s = size_factors(K) y = np.log2(K / s + 1) corr = np.corrcoef(y.T) var = y.var(axis=1) top = np.argsort(var)[::-1][:500] Y = y[top].T Y = Y - Y.mean(axis=0) U, S, Vt = np.linalg.svd(Y, full_matrices=False) pcs = U[:, :2] * S[:2] expl = (S ** 2 / (S ** 2).sum())[:2] return {"library_size": {k: int(v) for k, v in lib.items()}, "detected_genes": {k: int(v) for k, v in det.items()}, "size_factors_9": dict(zip(s9, [float(x) for x in s])), "pearson_corr_log2q": {a: {b: round(float(corr[i, j]), 4) for j, b in enumerate(s9)} for i, a in enumerate(s9)}, "pca_top500": {k: [round(float(pcs[i, 0]), 2), round(float(pcs[i, 1]), 2)] for i, k in enumerate(s9)}, "pca_var_explained": [float(expl[0]), float(expl[1])]} def main(): folder, out_folder = sys.argv[1], sys.argv[2] cm, nonint = load_counts(folder) auth = load_authors(folder) out = {"count_matrix": {"genes": int(len(cm)), "non_integer_or_negative_cells": nonint, "columns": list(cm.columns)}} out["descriptive"] = descriptive(cm) s8 = GROUPS["GMF45"] + GROUPS["GMF50"] + GROUPS["NZMF"] lab8 = ["GMF45"] * 3 + ["GMF50"] * 3 + ["NZMF"] * 2 out["primary_one_model"] = run_scope(cm, s8, lab8, auth, "one model", out_folder, write_genes=True) per = {} for num, ref in COMPARISONS: smp = GROUPS[num] + GROUPS[ref] lab = [num] * len(GROUPS[num]) + [ref] * len(GROUPS[ref]) per[num + "_vs_" + ref] = run_scope(cm, smp, lab, auth, "per comparison")["comparisons"][num + "_vs_" + ref] out["secondary_per_comparison"] = per s9 = s8 + ["NZMF_3"] lab9 = lab8 + ["NZMF"] out["sensitivity_NZMF3_kept_one_model"] = run_scope(cm, s9, lab9, auth, "one model, NZMF_3 kept") with open(os.path.join(out_folder, "rederive.json"), "w", encoding="utf-8", newline="\n") as f: json.dump(out, f, indent=1, default=float) # printed summary print("library sizes:", out["descriptive"]["library_size"]) print("detected genes:", out["descriptive"]["detected_genes"]) print("PCA (PC1, PC2):", out["descriptive"]["pca_top500"], "var explained", out["descriptive"]["pca_var_explained"]) for scope in ("primary_one_model", "sensitivity_NZMF3_kept_one_model"): print("==", scope, "genes", out[scope]["n_genes"]) for k, r in out[scope]["comparisons"].items(): for nm, c in r.items(): print(" %-15s %-26s ours %5d (up %4d, down %4d) authors %4d common %4d recovered %.2f jaccard %.2f rho_lfc %.2f rho_p %.2f | %s" % ( k, nm, c["ours"], c["up"], c["down"], c["authors"], c["common"], c["share_of_authors_recovered"], c["jaccard"], c["spearman_log2FC"], c["spearman_minus_log10_p"], c["label_vs_authors"])) print("== secondary_per_comparison") for k, r in per.items(): for nm, c in r.items(): print(" %-15s %-26s ours %5d (up %4d, down %4d) authors %4d common %4d recovered %.2f jaccard %.2f | %s" % ( k, nm, c["ours"], c["up"], c["down"], c["authors"], c["common"], c["share_of_authors_recovered"], c["jaccard"], c["label_vs_authors"])) if __name__ == "__main__": main()