diversa-biomedical-v1 / src /derive_features.py
skyleee's picture
Upload diversa-biomedical-v1 package
7bcd860 verified
Raw History Blame Contribute Delete
8.94 kB
"""Derive reproducible analytical features from the normalized works table.
Two streaming passes over the works parts:
pass 1 build the group statistics that need the whole corpus (citation
distributions per publication_year x field, per-topic and per-field
yearly publication counts).
pass 2 attach the derived columns and rewrite each part in place.
Every derived value has a deterministic definition (see METHODOLOGY.md); no
values are invented or produced by a language model.
"""
from __future__ import annotations
import bisect
import math
from pathlib import Path
import pyarrow as pa
import pyarrow.parquet as pq
from common import ensure_dirs, get_logger, load_config, p, utc_now, write_json
from schema import TOPIC_GROWTH, TOPIC_YEAR_COUNTS, WORKS_BASE, WORKS_FULL
BATCH = 50000
def _year_counts(pairs):
d: dict[int, int] = {}
for y, n in pairs:
d[y] = d.get(y, 0) + n
return d
def _growth(series: dict[int, int], y0: int, y1: int, threshold: float, min_late: int):
span = y1 - y0
half = max(1, span // 2)
early_years = range(y0, y0 + half)
late_years = range(y1 - half + 1, y1 + 1)
early = sum(series.get(y, 0) for y in early_years)
late = sum(series.get(y, 0) for y in late_years)
ratio = (late + 1.0) / (early + 1.0)
n = len(list(late_years)) or 1
early_avg = max(early / max(len(list(early_years)), 1), 1e-9)
late_avg = late / n
cagr = (late_avg / early_avg) ** (1.0 / max(span, 1)) - 1.0 if early_avg > 0 else 0.0
ys = sorted(series)
slope = 0.0
if len(ys) >= 2:
mx = sum(ys) / len(ys)
my = sum(series[y] for y in ys) / len(ys)
num = sum((y - mx) * (series[y] - my) for y in ys)
den = sum((y - mx) ** 2 for y in ys) or 1.0
slope = num / den
emerging = bool(ratio >= threshold and late >= min_late and late > early)
return early, late, float(ratio), float(cagr), float(slope), emerging
def run(cfg: dict | None = None) -> dict:
cfg = cfg or load_config()
ensure_dirs(cfg)
logger = get_logger("diversa.derive", p(cfg, "logs") / "pipeline.log")
parts_dir = p(cfg, "parts") / "works"
out_dir = p(cfg, "parts") / "works_full"
out_dir.mkdir(parents=True, exist_ok=True)
files = sorted(parts_dir.glob("*.parquet"))
if not files:
raise SystemExit("no normalized works parts found; run normalize first")
percent_group = tuple(cfg["features"]["citation_percentile_group"])
hi_pct = cfg["features"]["high_impact_percentile"]
threshold = cfg["features"]["emerging_growth_threshold"]
halflife = cfg["features"]["recency_halflife_years"]
y0, y1 = cfg["scope"]["year_start"], cfg["scope"]["year_end"]
logger.info("derive pass 1/2: scanning %d works parts", len(files))
group_vals: dict[tuple, list[int]] = {}
topic_series: dict[str, dict[int, int]] = {}
topic_names: dict[str, str] = {}
field_series: dict[str, dict[int, int]] = {}
max_year = y0
total = 0
for f in files:
pf = pq.ParquetFile(f)
cols = [c for c in ["publication_year", "field_id", "primary_topic_id",
"primary_topic_name", "cited_by_count"] if c in pf.schema_arrow.names]
for batch in pf.iter_batches(batch_size=BATCH, columns=cols):
d = batch.to_pydict()
for i in range(len(d["publication_year"])):
total += 1
yr = d["publication_year"][i]
fld = d["field_id"][i]
tid = d["primary_topic_id"][i]
cbc = d["cited_by_count"][i] or 0
if yr is None:
continue
max_year = max(max_year, yr)
key_parts = []
for g in percent_group:
key_parts.append(yr if g == "publication_year" else fld)
group_vals.setdefault(tuple(key_parts), []).append(cbc)
if tid:
topic_series.setdefault(tid, {})[yr] = topic_series.setdefault(tid, {}).get(yr, 0) + 1
topic_names.setdefault(tid, d["primary_topic_name"][i])
if fld:
field_series.setdefault(fld, {})[yr] = field_series.setdefault(fld, {}).get(yr, 0) + 1
n_groups = sum(len(v) for v in group_vals.values())
for k in group_vals:
group_vals[k].sort()
logger.info("pass 1 complete: %s works, %d percentile groups, %d topics",
f"{total:,}", len(group_vals), len(topic_series))
field_growth = {fid: _growth(series, y0, y1, threshold, 1) for fid, series in field_series.items()}
topic_growth = {tid: _growth(series, y0, y1, threshold, 50) for tid, series in topic_series.items()}
min_late_topic = 50
trows = []
grows = []
for tid, series in topic_series.items():
for y in sorted(series):
trows.append({"topic_id": tid, "topic_name": topic_names.get(tid),
"publication_year": y, "works_count": series[y]})
early, late, ratio, cagr, slope, emerging = topic_growth[tid]
grows.append({"topic_id": tid, "topic_name": topic_names.get(tid),
"first_year": min(series), "last_year": max(series),
"early_count": early, "late_count": late, "growth_ratio": ratio,
"cagr": cagr, "trend_slope": slope, "emerging_topic_flag": emerging})
pq.write_table(pa.Table.from_pylist(trows, schema=TOPIC_YEAR_COUNTS),
p(cfg, "analytics") / "topic_year_counts.parquet", compression="zstd")
pq.write_table(pa.Table.from_pylist(grows, schema=TOPIC_GROWTH),
p(cfg, "analytics") / "topic_growth.parquet", compression="zstd")
logger.info("derive pass 2/2: writing enriched works")
written = 0
for f in files:
pf = pq.ParquetFile(f)
out_f = out_dir / f.name
writer = None
try:
for batch in pf.iter_batches(batch_size=BATCH):
rows = batch.to_pylist()
out_rows = []
for r in rows:
yr = r.get("publication_year")
fld = r.get("field_id")
tid = r.get("primary_topic_id")
cbc = r.get("cited_by_count") or 0
age = float(max_year - yr) if yr is not None else None
cpy = (cbc / age) if age and age > 0 else (float(cbc) if age == 0 else None)
rec = r.get("recent_citations_3y")
velocity = (rec / 3.0) if rec is not None else None
pct = None
if yr is not None:
key_parts = []
for g in percent_group:
key_parts.append(yr if g == "publication_year" else fld)
vals = group_vals.get(tuple(key_parts))
if vals:
pct = 100.0 * bisect.bisect_right(vals, cbc) / len(vals)
recency = math.exp(-age / halflife) if age is not None else None
fg = field_growth.get(fld)
tg = topic_growth.get(tid)
r2 = dict(r)
r2.update({
"paper_age_years": age,
"citations_per_year": cpy,
"citation_velocity": velocity,
"international_collaboration": (r.get("country_count") or 0) >= 2,
"multi_institutional": (r.get("institution_count") or 0) >= 2,
"publication_recency_score": recency,
"citation_percentile": pct,
"high_impact_flag": (pct is not None and pct >= hi_pct),
"research_growth_score": fg[2] if fg else None,
"topic_growth_score": tg[2] if tg else None,
"emerging_topic_flag": bool(tg[5]) if tg else False,
})
out_rows.append(r2)
tbl = pa.Table.from_pylist(out_rows, schema=WORKS_FULL)
if writer is None:
writer = pq.ParquetWriter(out_f, WORKS_FULL, compression="zstd")
writer.write_table(tbl)
written += len(out_rows)
finally:
if writer is not None:
writer.close()
logger.info("derive done: %s enriched rows -> %s", f"{written:,}", out_dir)
summary = {
"works_enriched": written,
"max_publication_year": max_year,
"percentile_groups": len(group_vals),
"topics": len(topic_series),
"emerging_topics": int(sum(1 for v in topic_growth.values() if v[5])),
"finished_at": utc_now(),
}
write_json(p(cfg, "checkpoints") / "derive_stats.json", summary)
return summary
if __name__ == "__main__":
run()