Files
ML-Porosity/scripts/50_ref_overlap.py
lamlvh eff975cc96 Address simulated GP referee reports: E1-E6 and A1-A9 (exploratory), theory scope, per-well field and anchor-error tables, scorer v1.1, paper_gp and response letter
Experiments declared and hashed before computing (docs/research/gp-review-*.md). The SMC-mean gain holds against a practitioner tie, all budgets and a same-target point tie, but is lost at anchor errors of 2 ms or less and reverses with per-well bulk error. No locked protocol, verdict or threshold changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 11:20:54 +00:00

86 lines
3.6 KiB
Python

#!/usr/bin/env python3
"""Offline word n-gram overlap between the manuscript prose and the reference PDFs in refs/.
Nothing leaves the machine. Prose of paper/sections/*.tex and paper_gp/main.tex (math, citation and
reference commands removed) is compared with the text of every distinct PDF in refs/ (PyMuPDF; line-end
hyphenation joined). Runs of shared word n-grams are merged into spans and written, longest first, to
outputs/ref_overlap/overlap_n<N>.json. Only near-verbatim reuse is found, and only against refs/ (PDFs
listed in refs/MISSING.md are not checked). Not a substitute for iThenticate.
python scripts/50_ref_overlap.py [N] # default N = 8
"""
import glob, hashlib, json, os, re, sys, warnings
warnings.filterwarnings("ignore")
import fitz
REPO = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
N = int(sys.argv[1]) if len(sys.argv) > 1 else 8
OUT = os.path.join(REPO, "outputs", "ref_overlap")
os.makedirs(OUT, exist_ok=True)
def tex_to_text(s):
s = re.sub(r"(?<!\\)%.*", "", s)
s = re.sub(r"\\begin\{(equation|align|gather|multline|eqnarray|displaymath)\*?\}.*?\\end\{\1\*?\}", " MATH ", s, flags=re.S)
s = re.sub(r"\\\[.*?\\\]", " MATH ", s, flags=re.S)
s = re.sub(r"(?<!\\)\$.+?(?<!\\)\$", " MATH ", s, flags=re.S)
s = re.sub(r"\\(cite[a-z]*|ref|eqref|label|Sref|includegraphics|input|url|href|todo)\*?(\[[^\]]*\])*\{[^}]*\}", " ", s)
s = re.sub(r"\\[a-zA-Z]+\*?", " ", s)
s = re.sub(r"[{}\[\]~&\\]", " ", s)
return s
def words(s):
s = s.replace("\u2010", "-").replace("\u2011", "-").replace("\ufb01", "fi").replace("\ufb02", "fl")
s = re.sub(r"(\w)-\s*\n\s*(\w)", r"\1\2", s) # de-hyphenate line breaks
return re.findall(r"[a-z0-9]+", s.lower())
# manuscript: full sections + GP article (prose); keep line numbers for reporting
docs = {}
for p in sorted(glob.glob(f"{REPO}/paper/sections/*.tex")) + [f"{REPO}/paper_gp/main.tex"]:
raw = open(p, encoding="utf-8").read()
if p.endswith("paper_gp/main.tex"):
raw = re.sub(r".*?\\begin\{document\}", "", raw, flags=re.S)
docs[os.path.relpath(p, REPO)] = words(tex_to_text(raw))
# references: dedupe by text hash
refs, seen = {}, {}
for p in sorted(glob.glob(f"{REPO}/refs/*.pdf")):
try:
t = "\n".join(pg.get_text() for pg in fitz.open(p))
except Exception as e:
print("skip", p, e); continue
w = words(t)
h = hashlib.sha1(" ".join(w[:2000]).encode()).hexdigest()
if h in seen:
continue
seen[h] = p
refs[os.path.basename(p)] = w
print(f"{len(refs)} distinct reference texts; n = {N}")
index = {}
for name, w in refs.items():
for i in range(len(w) - N + 1):
index.setdefault(tuple(w[i:i + N]), set()).add(name)
results = []
for d, w in docs.items():
hit = [index.get(tuple(w[i:i + N])) for i in range(len(w) - N + 1)]
i = 0
while i < len(hit):
if hit[i]:
j = i; src = set(hit[i])
while j + 1 < len(hit) and hit[j + 1]:
j += 1; src |= hit[j]
span = w[i:j + N]
results.append(dict(doc=d, nwords=len(span), text=" ".join(span), sources=sorted(src)))
i = j + 1
else:
i += 1
results.sort(key=lambda r: -r["nwords"])
json.dump(results, open(f"{OUT}/overlap_n{N}.json", "w"), indent=1)
tot = {d: sum(r["nwords"] for r in results if r["doc"] == d) for d in docs}
for d in docs:
print(f"{d}: {len(docs[d])} words, {tot[d]} in matched spans ({100*tot[d]/max(1,len(docs[d])):.2f}%)")
print(f"\n{len(results)} spans; longest first:")
for r in results[:60]:
print(f"[{r['nwords']}] {r['doc']} <- {', '.join(r['sources'])}\n {r['text']}")