"""RT-qPCR and RNAi checks fixed in RULES_qpcr_rnai.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. Usage: python3 qpcr_rnai.py """ import json import math import os import sys import numpy as np from scipy import stats sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from xlsx_reader import read_xlsx # noqa: E402 FIG1 = "Raw_data_for_Figure1-Complete list of differentially expressed genes in all comparisons.xlsx" FIG3 = "Raw_data_for_Figure3-RT-qPCR validation of representative genes responding to different magnetic field conditions.xlsx" FIG4 = "Raw_data_for_Figure4-Cry1 knockdown disrupts diel eclosion rhythmicity in female brown planthopper.xlsx" SHEET_TO_DEG = {"Fig. 3A": "DEG_GMF50_vs_GMF45", "Fig. 3B": "DEG_NZMF_vs_GMF45", "Fig. 3C": "DEG_NZMF_vs_GMF50"} SEED = 20261120 NPERM = 100000 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 qpcr(folder): wb = read_xlsx(os.path.join(folder, FIG3)) deg = read_xlsx(os.path.join(folder, FIG1)) degmap = {} for sh in SHEET_TO_DEG.values(): degmap[sh] = {r[0]: r for r in deg[sh]["rows"][1:] if r} rows_out = [] for sh, degsheet in SHEET_TO_DEG.items(): rows = wb[sh]["rows"] hdr = [str(x) for x in rows[1][:9]] g1, g2 = hdr[1:4], hdr[4:7] for r in rows[2:]: if not r or r[0] is None or not str(r[0]).startswith("LOC"): continue a = np.array([float(x) for x in r[1:4]]) b = np.array([float(x) for x in r[4:7]]) la, lb = np.log2(a), np.log2(b) lfc = la.mean() - lb.mean() se = math.sqrt(la.var(ddof=1) / 3 + lb.var(ddof=1) / 3) t = stats.ttest_ind(la, lb, equal_var=False) d = degmap[degsheet].get(r[0]) rs_lfc = float(d[2]) if d else None rs_padj = None if (not d or d[6] in (None, "NA")) else float(d[6]) rows_out.append({"sheet": sh, "comparison": g1[0].split("_")[0] + " vs " + g2[0].split("_")[0], "gene": r[0], "file_log2FC": float(r[7]), "file_SE": float(r[8]), "our_log2FC": lfc, "our_SE": se, "abs_diff_log2FC": abs(lfc - float(r[7])), "abs_diff_SE": abs(se - float(r[8])), "welch_t": float(t.statistic), "welch_p": float(t.pvalue), "rnaseq_log2FC": rs_lfc, "rnaseq_padj": rs_padj, "rnaseq_DEG": bool(rs_padj is not None and rs_padj < 0.05 and abs(rs_lfc) > 0.25), "same_sign": (rs_lfc is not None and np.sign(rs_lfc) == np.sign(lfc))}) ps = np.array([x["welch_p"] for x in rows_out]) adj = bh(ps) for x, q in zip(rows_out, adj): x["welch_p_BH"] = float(q) pairs = [x for x in rows_out if x["rnaseq_log2FC"] is not None] q_l = np.array([x["our_log2FC"] for x in pairs]) r_l = np.array([x["rnaseq_log2FC"] for x in pairs]) summ = {"n_pairs": len(pairs), "n_genes_unmatched": len(rows_out) - len(pairs), "max_abs_diff_log2FC_vs_file": max(x["abs_diff_log2FC"] for x in rows_out), "max_abs_diff_SE_vs_file": max(x["abs_diff_SE"] for x in rows_out), "Q1_agree_within_0.01": all(x["abs_diff_log2FC"] <= 0.01 and x["abs_diff_SE"] <= 0.01 for x in rows_out), "n_welch_p_lt_0.05": int((ps < 0.05).sum()), "n_welch_BH_lt_0.05": int((adj < 0.05).sum()), "share_same_sign": float(np.mean([x["same_sign"] for x in pairs])), "pearson_r": float(stats.pearsonr(q_l, r_l)[0]), "spearman_rho": float(stats.spearmanr(q_l, r_l)[0]), "n_pairs_rnaseq_not_DEG": sum(1 for x in pairs if not x["rnaseq_DEG"]), "ratio_qpcr_to_rnaseq_log2FC_median": float(np.median(q_l / r_l))} summ["Q3_supports_validation"] = summ["share_same_sign"] >= 0.8 and summ["pearson_r"] > 0.5 return rows_out, summ def rnai(folder): wb = read_xlsx(os.path.join(folder, FIG4)) out = {} for sh in ("Fig. 4A", "Fig. 4B"): rows = wb[sh]["rows"] gfp = np.array([float(r[1]) for r in rows[1:] if r and str(r[0]).startswith("dsGFP")]) cry = np.array([float(r[1]) for r in rows[1:] if r and str(r[0]).startswith("dsCry1")]) t = stats.ttest_ind(np.log2(cry), np.log2(gfp), equal_var=False) out[sh] = {"n_dsGFP": len(gfp), "n_dsCry1": len(cry), "mean_dsGFP": float(gfp.mean()), "mean_dsCry1": float(cry.mean()), "reduction": float(1 - cry.mean() / gfp.mean()), "welch_t_log2": float(t.statistic), "welch_p_log2": float(t.pvalue)} def ecl(sh): rows = wb[sh]["rows"] title = rows[0][0] labels, counts, ratios = [], [], [] for r in rows: if r and isinstance(r[0], str) and r[0].startswith("ZT") and r[0] != "ZT": labels.append(int(r[0][2:])) counts.append(int(round(float(r[1])))) ratios.append(float(r[2])) return title, np.array(labels), np.array(counts), np.array(ratios) tc, lab_c, cnt_c, rat_c = ecl("Fig. 4C,E") tg, lab_g, cnt_g, rat_g = ecl("Fig. 4D,E") assert (lab_c == lab_g).all() out["eclosion_titles"] = [tc, tg] out["labels_ZT"] = lab_c.tolist() out["counts_dsCry1"] = cnt_c.tolist() out["counts_dsGFP"] = cnt_g.tolist() out["R2_totals"] = {"dsCry1": int(cnt_c.sum()), "dsGFP": int(cnt_g.sum())} out["R2_max_abs_diff_ratio"] = float(max(np.max(np.abs(rat_c - 100 * cnt_c / cnt_c.sum())), np.max(np.abs(rat_g - 100 * cnt_g / cnt_g.sum())))) # R3 layout (i): pooled counts -> chi-square homogeneity, Monte Carlo p with fixed margins table = np.vstack([cnt_g, cnt_c]) keep = table.sum(axis=0) > 0 table = table[:, keep] chi2_obs = stats.chi2_contingency(table, correction=False)[0] rng = np.random.default_rng(SEED) labels_ind = np.repeat(np.arange(table.shape[1]), table.sum(axis=0)) n_g = int(table[0].sum()) ge = 0 for _ in range(NPERM): perm = rng.permutation(len(labels_ind)) g_bins = np.bincount(labels_ind[perm[:n_g]], minlength=table.shape[1]) c_bins = table.sum(axis=0) - g_bins tt = np.vstack([g_bins, c_bins]) exp = tt.sum(axis=1, keepdims=True) * tt.sum(axis=0, keepdims=True) / tt.sum() chi = float(((tt - exp) ** 2 / exp).sum()) if chi >= chi2_obs - 1e-9: ge += 1 out["R3_layout"] = "(i) one pooled count per 2-h interval per treatment" out["R3_chi2"] = float(chi2_obs) out["R3_df"] = int(table.shape[1] - 1) out["R3_asymptotic_p"] = float(stats.chi2.sf(chi2_obs, table.shape[1] - 1)) out["R3_monte_carlo_p"] = (ge + 1) / (NPERM + 1) out["R3_min_expected"] = float((table.sum(axis=1, keepdims=True) * table.sum(axis=0, keepdims=True) / table.sum()).min()) # R4 circular statistics; labels read as interval starts (midpoint = label + 1 h) def circ(counts, offset): ang = 2 * np.pi * (lab_c + offset) / 24.0 w = counts C, S = (w * np.cos(ang)).sum(), (w * np.sin(ang)).sum() n = w.sum() R = math.hypot(C, S) / n mean_ang = math.atan2(S, C) % (2 * np.pi) Z = n * R * R p_ray = math.exp(math.sqrt(1 + 4 * n + 4 * (n * n - (n * R) ** 2)) - (1 + 2 * n)) return {"n": int(n), "R": R, "mean_ZT": mean_ang * 24 / (2 * np.pi), "rayleigh_Z": Z, "rayleigh_p": min(1.0, p_ray)} for name, off in (("R4_start_reading", 1.0), ("R4_end_reading_sensitivity", -1.0)): cg, cc = circ(cnt_g, off), circ(cnt_c, off) # permutation of individuals for the difference in R (100,000, seed) rng = np.random.default_rng(SEED) ind = np.concatenate([np.repeat(lab_c, cnt_g), np.repeat(lab_c, cnt_c)]) ang = 2 * np.pi * (ind + off) / 24.0 ng = int(cnt_g.sum()) obs = cg["R"] - cc["R"] ge = 0 cosv, sinv = np.cos(ang), np.sin(ang) for _ in range(NPERM): p = rng.permutation(len(ind)) a, b = p[:ng], p[ng:] Ra = math.hypot(cosv[a].sum(), sinv[a].sum()) / len(a) Rb = math.hypot(cosv[b].sum(), sinv[b].sum()) / len(b) if abs(Ra - Rb) >= abs(obs) - 1e-12: ge += 1 dmean = (cc["mean_ZT"] - cg["mean_ZT"] + 12) % 24 - 12 out[name] = {"dsGFP": cg, "dsCry1": cc, "R_diff_GFP_minus_Cry1": obs, "perm_p_two_sided": (ge + 1) / (NPERM + 1), "mean_time_shift_h_Cry1_minus_GFP": dmean} # R5 light vs dark for name, light in (("R5_start_reading", lab_c <= 12), ("R5_end_reading_sensitivity", (lab_c >= 2) & (lab_c <= 14))): tab = [[int(cnt_g[light].sum()), int(cnt_g[~light].sum())], [int(cnt_c[light].sum()), int(cnt_c[~light].sum())]] out[name] = {"table_[[GFP_light,GFP_dark],[Cry1_light,Cry1_dark]]": tab, "share_light_GFP": tab[0][0] / sum(tab[0]), "share_light_Cry1": tab[1][0] / sum(tab[1]), "fisher_p": float(stats.fisher_exact(tab)[1])} r4 = out["R4_start_reading"] out["R6_decision"] = ("supported" if (out["R3_monte_carlo_p"] < 0.05 and (r4["dsCry1"]["R"] < r4["dsGFP"]["R"] or abs(r4["mean_time_shift_h_Cry1_minus_GFP"]) >= 2)) else ("changed, not clearly disrupted" if out["R3_monte_carlo_p"] < 0.05 else "not shown at 0.05")) out["R7_field_condition_in_file"] = any("GMF" in str(c) or "NZMF" in str(c) for s in wb.values() for r in s["rows"] for c in r if c is not None) return out def main(): folder, out_path = sys.argv[1], sys.argv[2] rows, summ = qpcr(folder) r = rnai(folder) res = {"qpcr_rows": rows, "qpcr_summary": summ, "rnai": r} with open(out_path, "w", encoding="utf-8", newline="\n") as f: json.dump(res, f, indent=1, default=float) for x in rows: print("%-8s %-16s %-13s qPCR %+.3f (file %+.3f) SE %.3f (file %.3f) Welch p %.4f (BH %.3f) | RNA-seq %+.3f padj %s DEG %s same sign %s" % ( x["sheet"], x["comparison"], x["gene"], x["our_log2FC"], x["file_log2FC"], x["our_SE"], x["file_SE"], x["welch_p"], x["welch_p_BH"], x["rnaseq_log2FC"], "%.2g" % x["rnaseq_padj"] if x["rnaseq_padj"] is not None else "NA", x["rnaseq_DEG"], x["same_sign"])) print(json.dumps(summ, indent=1)) print(json.dumps(r, indent=1, default=float)) if __name__ == "__main__": main()