Files
arzani bc4193316f
LocationBasedServices/smartguide/pipeline/head This commit looks good
founder potential/mutlipliers backend added
2026-09-17 19:34:30 +02:00

278 lines
11 KiB
Python

#!/usr/bin/env python3
"""
build.py — single entry point for the multiplicator pipeline (M2).
extract (cached) -> graph -> metrics -> scoring -> local artifacts -> ES index.
python build.py --institution-id I62318514 # full run
python build.py --institution-id I62318514 --force-extract # refresh the ES extract
python build.py --institution-id I62318514 --no-index # skip the ES write
Artifacts in --cache-dir:
authors_<ID>.jsonl.gz / works_<ID>.jsonl.gz the extract (reused unless --force-extract)
scores_<ID>.jsonl.gz one scored row per focal author
build_summary_<ID>.json stage timings + tag counts + top lists
The ES write targets `multiplicators_v1` on the INSE cluster (admin-created; the API
key cannot create indices). Doc _id = <institution>_<author>; every run deletes the
institution's docs first, so re-runs are idempotent.
"""
from __future__ import annotations
import argparse
import gzip
import json
import time
from pathlib import Path
from extract import extract_to_cache, read_jsonl_gz
from graph import build_graph, short_id
from index import NETWORK_MAPPING, NETWORKS_INDEX, MultiplicatorsIndexClient
from metrics import compute_all_metrics, incident_edges
from networks import build_network_docs
from scoring import load_config, score_rows
from signals import collect_signals, normalize_doi
SCRIPT_DIR = Path(__file__).resolve().parent
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--institution-id", required=True)
parser.add_argument("--config", default=str(SCRIPT_DIR / "multipliers.yaml"))
parser.add_argument("--cache-dir", default=str(SCRIPT_DIR / "cache"))
parser.add_argument(
"--force-extract", action="store_true",
help="Re-extract from ES even if a cache exists.",
)
parser.add_argument(
"--no-index", action="store_true",
help="Compute and write local artifacts but skip the ES indexing step.",
)
parser.add_argument(
"--no-signals", action="store_true",
help="Skip the patents/news/CORDIS signal joins (amplifier falls back to "
"industry co-authorship alone).",
)
parser.add_argument(
"--no-network", action="store_true",
help="Skip materializing the per-author ego-network visualization docs.",
)
args = parser.parse_args()
short = args.institution_id.strip().rsplit("/", 1)[-1]
cache_dir = Path(args.cache_dir)
config = load_config(args.config)
timings: dict[str, float] = {}
# ---- extract (cache-aware) ----
t0 = time.time()
authors_path, works_path, insts = extract_to_cache(
args.institution_id, config, cache_dir, force=args.force_extract
)
cohort_short_ids = [i["short_id"] for i in insts]
timings["extract_s"] = round(time.time() - t0, 1)
# ---- load ----
t0 = time.time()
focal_ids = {a["id"] for a in read_jsonl_gz(authors_path)}
works = list(read_jsonl_gz(works_path))
timings["load_cache_s"] = round(time.time() - t0, 1)
print(f"Loaded {len(works)} works, {len(focal_ids)} focal authors "
f"({timings['load_cache_s']}s)")
# ---- single pass over works before they are freed: DOIs per focal author
# (CORDIS join), per-author institution counts (modal label), and per-WORK
# company affiliations (tie-level industry roles in the network docs)
focal_short_ids = {short_id(a) for a in focal_ids}
max_authors = int(config["extraction"]["max_authors_per_work"])
dois_by_author: dict[str, set[str]] = {}
inst_counts: dict[str, dict[str, int]] = {}
company_by_author_work: dict[str, dict[str, list[str]]] = {}
company_work_authors: dict[str, set[str]] = {}
for w in works:
doi = normalize_doi(w.get("doi"))
wid = short_id(w.get("id"))
work_authors: set[str] = set()
work_companies: dict[str, list[str]] = {}
for a in w.get("authorships") or []:
aid = short_id((a.get("author") or {}).get("id"))
if not aid:
continue
work_authors.add(aid)
if doi and aid in focal_short_ids:
dois_by_author.setdefault(aid, set()).add(doi)
for inst in a.get("institutions") or []:
name = inst.get("display_name")
if name:
counts = inst_counts.setdefault(aid, {})
counts[name] = counts.get(name, 0) + 1
if inst.get("type") == "company":
work_companies.setdefault(aid, []).append(name)
# company evidence only for works that also enter the graph (same cap)
if wid and work_companies and 2 <= len(work_authors) <= max_authors:
company_work_authors[wid] = work_authors
for aid, names in work_companies.items():
company_by_author_work.setdefault(aid, {})[wid] = names
inst_by_author = {
aid: max(counts, key=counts.get) for aid, counts in inst_counts.items()
}
del inst_counts
# ---- graph ----
t0 = time.time()
graph = build_graph(
works,
focal_ids,
max_authors_per_work=config["extraction"]["max_authors_per_work"],
decay=config["graph"]["decay"],
)
del works
timings["build_graph_s"] = round(time.time() - t0, 1)
print(f"Graph: {len(graph.nodes)} nodes, {len(graph.edges)} edges, "
f"{graph.n_works_used} works used, {graph.n_works_capped} capped, "
f"ref_year={graph.ref_year} ({timings['build_graph_s']}s)")
# ---- metrics ----
t0 = time.time()
metric_rows = compute_all_metrics(
graph,
junior_active_years_max=config["mentor"]["junior_active_years_max"],
senior_active_years_min=config["mentor"]["senior_active_years_min"],
progressed_active_years_min=config["mentor"]["progressed_active_years_min"],
industry_share_shrinkage_k=config.get("signals", {}).get(
"industry_share_shrinkage_k", 5
),
)
timings["metrics_s"] = round(time.time() - t0, 1)
print(f"Metrics for {len(metric_rows)} focal authors ({timings['metrics_s']}s)")
# ---- signal joins (patents / news / CORDIS) ----
if args.no_signals:
print("Skipping signal joins (--no-signals).")
timings["signals_s"] = 0.0
else:
t0 = time.time()
signals_cfg = config.get("signals") or {}
display_names = {
aid: row.get("display_name") or "" for aid, row in metric_rows.items()
}
signal_counts = collect_signals(
short,
display_names,
{a: d for a, d in dois_by_author.items() if a in metric_rows},
scored_match_types=tuple(
signals_cfg.get("patent_match_types", ["institution", "both"])
),
news_require_relevant=signals_cfg.get("news_require_relevant", True),
)
for metric, counts in signal_counts.items():
for aid, row in metric_rows.items():
row[metric] = counts.get(aid, 0)
timings["signals_s"] = round(time.time() - t0, 1)
print(f"Signal joins done ({timings['signals_s']}s)")
# ---- scoring ----
t0 = time.time()
scored = score_rows(metric_rows, config)
timings["scoring_s"] = round(time.time() - t0, 1)
scores_path = cache_dir / f"scores_{short}.jsonl.gz"
with gzip.open(scores_path, "wt", encoding="utf-8", newline="\n") as f:
for row in scored:
f.write(json.dumps(row, ensure_ascii=True) + "\n")
print(f"Scores -> {scores_path} ({timings['scoring_s']}s)")
# ---- index into ES ----
docs_written = 0
if args.no_index:
print("Skipping ES indexing (--no-index).")
else:
t0 = time.time()
es = MultiplicatorsIndexClient()
es.ensure_mapping()
docs_written = es.index_rows(short, cohort_short_ids, scored)
count = es.count_for_institution(short)
timings["index_s"] = round(time.time() - t0, 1)
print(f"Indexed {docs_written} docs into {es.index} "
f"(count for {short}: {count}) ({timings['index_s']}s)")
if count != len(scored):
raise RuntimeError(
f"Post-index count mismatch: expected {len(scored)}, index has {count}"
)
# ---- ego-network visualization docs ----
network_docs_written = 0
if args.no_index or args.no_network:
print("Skipping network materialization.")
else:
t0 = time.time()
network_cfg = config.get("network") or {}
network_docs = build_network_docs(
graph,
metric_rows,
scored,
incident_edges(graph),
inst_by_author,
company_by_author_work,
company_work_authors,
max_nodes=int(network_cfg.get("max_nodes", 42)),
max_forced_mentees=int(network_cfg.get("max_forced_mentees", 14)),
)
net_es = MultiplicatorsIndexClient(index=NETWORKS_INDEX)
net_es.ensure_mapping(NETWORK_MAPPING)
network_docs_written = net_es.index_rows(short, cohort_short_ids, network_docs)
timings["network_s"] = round(time.time() - t0, 1)
print(f"Indexed {network_docs_written} network docs into {net_es.index} "
f"({timings['network_s']}s)")
# ---- summary ----
tag_counts: dict[str, int] = {}
for row in scored:
for tag in row["tags"]:
tag_counts[tag] = tag_counts.get(tag, 0) + 1
def top(sub: str, k: int = 10):
rows = sorted(scored, key=lambda r: r["sub_scores"].get(sub, 0), reverse=True)
return [
{
"author_id": r["author_id"],
"name": r["display_name"],
"score": r["sub_scores"][sub],
"bucket": r["career_bucket"],
"active_years": r["active_years"],
"suspicious": r["suspicious_profile"],
}
for r in rows[:k]
]
summary = {
"institution": short,
"cohort": cohort_short_ids,
"config_hash": config["_config_hash"],
"counts": {
"focal_authors_scored": len(scored),
"nodes": len(graph.nodes),
"edges": len(graph.edges),
"works_used": graph.n_works_used,
"works_capped": graph.n_works_capped,
"tags": tag_counts,
"suspicious_profiles": sum(1 for r in scored if r["suspicious_profile"]),
"es_docs_written": docs_written,
"es_network_docs_written": network_docs_written,
},
"timings": timings,
"top_bridgers": top("bridger"),
"top_mentors": top("mentor"),
"top_amplifiers": top("amplifier"),
}
summary_path = cache_dir / f"build_summary_{short}.json"
with open(summary_path, "w", encoding="utf-8", newline="\n") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
print(json.dumps(summary["counts"], ensure_ascii=False, indent=2))
print(f"Summary -> {summary_path}")
if __name__ == "__main__":
main()