| |
| """ |
| pubs_join.py — shared join logic for the CMIP6 publications corpus. |
| |
| Builds a per-paper index from the archive + join sources: |
| - canonical DOI (doi_lookup.json map; heuristic fallback, flagged) |
| - has_local_md + reused domains from pubs_rag/out/papers.jsonl |
| - domain heuristic (build_corpus classifier) for the rest |
| - registry link (orphan / linked_products) by canonical lowercase DOI |
| |
| Used by load_pubs_qdrant.py (loading) and standalone (join-quality report). |
| """ |
| import json |
| import sys |
| from collections import Counter |
| from pathlib import Path |
|
|
| ROOT = Path(__file__).resolve().parent |
| |
| ARCHIVE = ROOT / "out" / "chunks_embedded.jsonl" |
| DOI_MAP = Path("/Users/dmpantiu/cmip6/cmip6_gpt/rag/doi_lookup.json") |
| PAPERS = ROOT / "out" / "papers.jsonl" |
| REGISTRY = Path("/Users/dmpantiu/copernicus_mcp/publications/registry/publications.jsonl") |
|
|
| |
| DOMAIN_KEYWORDS = { |
| "ocean/marine": [ |
| "ocean", "marine", "sea surface", "sst", "salinity", "sea level", |
| "amoc", "overturning", "thermocline", "gyre", "enso", "el nino", |
| "el niño", "la nina", "la niña", "sea-surface", "oceanic", "coral", |
| "phytoplankton", "biogeochem", "seawater", "coastal", "estuar", |
| "upwelling", "meridional overturning", "ocean heat", "mixed layer", |
| "benthic", "fisher", "chlorophyll", "carbon uptake", "gulf stream", |
| ], |
| "atmosphere": [ |
| "atmospher", "precipitation", "rainfall", "monsoon", "aerosol", |
| "cloud", "troposphere", "stratosphere", "wind", "circulation", |
| "geopotential", "ozone", "humidity", "water vapor", "water vapour", |
| "convection", "jet stream", "storm track", "cyclone", "hurricane", |
| "typhoon", "radiative forcing", "temperature extremes", "heat wave", |
| "heatwave", "annular mode", "teleconnection", "air quality", |
| "greenhouse gas", "methane", "co2", "emission", |
| ], |
| "cryosphere": [ |
| "sea ice", "sea-ice", "ice sheet", "ice-sheet", "glacier", "snow", |
| "permafrost", "cryospher", "antarctic", "arctic", "greenland", |
| "albedo", "ice shelf", "iceberg", "melt", "frozen", "snowpack", |
| ], |
| "land": [ |
| "soil", "vegetation", "land surface", "land-surface", "terrestrial", |
| "crop", "agricultur", "forest", "drought", "runoff", "hydrolog", |
| "river", "streamflow", "evapotranspiration", "biosphere", "land use", |
| "land-use", "wildfire", "biomass", "ecosystem", "groundwater", |
| "watershed", "vegetation dynamics", |
| ], |
| "climate-modeling": [ |
| "cmip", "gcm", "esm", "earth system model", "coupled model", |
| "model intercomparison", "climate model", "simulation", "downscaling", |
| "bias correction", "parameteriz", "parameteris", "ensemble", |
| "reanalysis", "emulator", "scenariomip", "ssp", "rcp", |
| "climate projection", "hindcast", "climate sensitivity", |
| "detection and attribution", "resolution", "spin-up", "spinup", |
| ], |
| "emergency": [ |
| "disaster", "flood risk", "flooding", "emergency", "hazard", |
| "early warning", "risk assessment", "vulnerabilit", "adaptation", |
| "extreme event", "damage", "impact assessment", "resilience", |
| "mortality", "compound risk", "catastroph", |
| ], |
| } |
| DEFAULT_DOMAIN = "climate-general" |
|
|
|
|
| def classify(title: str, journal: str) -> list[str]: |
| hay = f"{title} {journal}".lower() |
| tags = [dom for dom, kws in DOMAIN_KEYWORDS.items() if any(kw in hay for kw in kws)] |
| return tags or [DEFAULT_DOMAIN] |
|
|
|
|
| def canonical_doi(paper_id: str, doi_field: str, doi_map: dict): |
| """Return (canonical_doi, source) where source in {chunk, map, local, heuristic}.""" |
| |
| if doi_field.startswith("10.") and "/" in doi_field: |
| return doi_field, "chunk" |
| key = paper_id or doi_field |
| if key in doi_map: |
| return doi_map[key], "map" |
| if doi_field in doi_map: |
| return doi_map[doi_field], "map" |
| |
| parts = key.split("_", 2) |
| if len(parts) >= 3 and parts[0] == "10": |
| return f"10.{parts[1]}/{parts[2]}", "heuristic" |
| return key.replace("_", "/"), "heuristic" |
|
|
|
|
| def load_doi_map() -> dict: |
| if not DOI_MAP.exists(): |
| return {} |
| return json.loads(DOI_MAP.read_text()) |
|
|
|
|
| def load_local_papers() -> dict: |
| """paper_id -> {domains, md_path} for the locally parsed set.""" |
| out = {} |
| if not PAPERS.exists(): |
| return out |
| with open(PAPERS, encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| r = json.loads(line) |
| out[r["paper_id"]] = r |
| return out |
|
|
|
|
| def load_registry() -> dict: |
| """canonical DOI (lowercase) -> registry record.""" |
| reg = {} |
| if not REGISTRY.exists(): |
| return reg |
| with open(REGISTRY, encoding="utf-8") as f: |
| for line in f: |
| line = line.strip() |
| if not line: |
| continue |
| try: |
| r = json.loads(line) |
| except Exception: |
| continue |
| doi = str(r.get("doi", "")).lower().strip() |
| if doi: |
| reg[doi] = r |
| return reg |
|
|
|
|
| def build_paper_index(log=print): |
| """One streaming pass over the archive header fields to build a per-paper |
| index. Returns (index, stats). index[paper_id] = { |
| doi, doi_source, domains, has_local_md, orphan, linked_products, n_chunks }. |
| """ |
| doi_map = load_doi_map() |
| local = load_local_papers() |
| reg = load_registry() |
| log(f"sources: doi_map={len(doi_map)} local_papers={len(local)} registry={len(reg)}") |
|
|
| index = {} |
| n_chunks = 0 |
| with open(ARCHIVE, encoding="utf-8") as f: |
| for line in f: |
| n_chunks += 1 |
| c = json.loads(line) |
| pid = c["paper_id"] |
| if pid in index: |
| index[pid]["n_chunks"] += 1 |
| continue |
| doi_field = str(c.get("doi", "")) |
| doi, source = canonical_doi(pid, doi_field, doi_map) |
| doi_lc = doi.lower().strip() |
| lp = local.get(pid) |
| if lp is not None: |
| domains = lp.get("domains") or classify(c.get("title", ""), c.get("journal", "")) |
| has_local = True |
| else: |
| domains = classify(c.get("title", ""), c.get("journal", "")) |
| has_local = False |
| r = reg.get(doi_lc) |
| if r is not None: |
| orphan = bool(r.get("orphan", False)) |
| linked = r.get("linked_products", []) or [] |
| else: |
| orphan = True |
| linked = [] |
| index[pid] = { |
| "doi": doi, "doi_source": source, "domains": domains, |
| "has_local_md": has_local, "orphan": orphan, |
| "linked_products": linked, "n_chunks": 1, |
| } |
| stats = compute_stats(index, n_chunks) |
| return index, stats |
|
|
|
|
| def compute_stats(index: dict, n_chunks: int) -> dict: |
| src_papers = Counter() |
| src_chunks = Counter() |
| dom_papers = Counter() |
| dom_chunks = Counter() |
| local_papers = local_chunks = 0 |
| linked_papers = linked_chunks = 0 |
| for pid, m in index.items(): |
| nc = m["n_chunks"] |
| src_papers[m["doi_source"]] += 1 |
| src_chunks[m["doi_source"]] += nc |
| for d in m["domains"]: |
| dom_papers[d] += 1 |
| dom_chunks[d] += nc |
| if m["has_local_md"]: |
| local_papers += 1 |
| local_chunks += nc |
| if not m["orphan"] or m["linked_products"]: |
| linked_papers += 1 |
| linked_chunks += nc |
| return { |
| "n_papers": len(index), "n_chunks": n_chunks, |
| "src_papers": src_papers, "src_chunks": src_chunks, |
| "dom_papers": dom_papers, "dom_chunks": dom_chunks, |
| "local_papers": local_papers, "local_chunks": local_chunks, |
| "linked_papers": linked_papers, "linked_chunks": linked_chunks, |
| } |
|
|
|
|
| def print_report(stats: dict): |
| P, C = stats["n_papers"], stats["n_chunks"] |
| print(f"\n=== JOIN QUALITY REPORT ===") |
| print(f"papers: {P:,} chunks: {C:,}") |
| print("\nDOI canonicalization source (papers / chunks):") |
| for s in ("chunk", "map", "heuristic", "local"): |
| pp, cc = stats["src_papers"].get(s, 0), stats["src_chunks"].get(s, 0) |
| print(f" {s:10s} papers {pp:5d} ({100*pp/P:5.1f}%) chunks {cc:7,d} ({100*cc/C:5.1f}%)") |
| print(" (unresolved = heuristic that produced a non-DOI-looking string — see flag below)") |
| print(f"\nlocal parsed md (has_local_md=true): papers {stats['local_papers']:,} " |
| f"chunks {stats['local_chunks']:,}") |
| print(f"registry-linked (orphan=false / linked_products): papers {stats['linked_papers']:,} " |
| f"chunks {stats['linked_chunks']:,}") |
| print("\ndomain distribution (multi-label):") |
| for d, n in stats["dom_papers"].most_common(): |
| print(f" {d:18s} papers {n:5d} chunks {stats['dom_chunks'][d]:7,d}") |
|
|
|
|
| if __name__ == "__main__": |
| idx, stats = build_paper_index() |
| print_report(stats) |
| |
| bad = [(pid, m["doi"]) for pid, m in idx.items() |
| if m["doi_source"] == "heuristic" and not m["doi"].startswith("10.")] |
| print(f"\nheuristic DOIs NOT starting with '10.': {len(bad)}") |
| for pid, doi in bad[:20]: |
| print(f" {pid} -> {doi}", file=sys.stderr) |
|
|