File size: 9,738 Bytes
0ec8fd6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#!/usr/bin/env python3
"""
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
# Copernicus corpus (12,411 papers / 430,066 chunks) — NOT the old cmip6 archive.
ARCHIVE = ROOT / "out" / "chunks_embedded.jsonl"
DOI_MAP = Path("/Users/dmpantiu/cmip6/cmip6_gpt/rag/doi_lookup.json")  # legacy fallback only
PAPERS = ROOT / "out" / "papers.jsonl"
REGISTRY = Path("/Users/dmpantiu/copernicus_mcp/publications/registry/publications.jsonl")

# ── Domain keyword classifier (copied from build_corpus.py) ──────────────────
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}."""
    # New corpus: chunks carry the registry-resolved DOI — trust it when canonical.
    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"
    # heuristic: first "_" -> ".", second "_" -> "/", rest of tail keep as-is
    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)
    # flag heuristic DOIs that don't look canonical
    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)