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

364 lines
15 KiB
Python

#!/usr/bin/env python3
"""
build.py — single entry point for the multiplicator pipeline.
extract (cached) -> graph -> metrics -> signals -> founder potential -> scoring
-> local artifacts -> ES index.
Run as a module from the REPO ROOT (the modules import each other by absolute
path, so `python build.py` from inside this directory cannot resolve them), in
the `potential` conda env — `--no-founding` runs on requirements.txt alone:
python -m service.scripts.profiling.multipliers.build --institution-id I62318514
... --force-extract # refresh the ES extract and the patent join
... --no-index # local artifacts only
... --no-founding # skip the founder-potential models
Artifacts and the ES index contract: README, "M2 — pipeline + ES index".
"""
from __future__ import annotations
import argparse
import gzip
import json
import time
from pathlib import Path
from service.scripts.profiling.multipliers.extract import extract_to_cache, read_jsonl_gz
from service.scripts.profiling.multipliers.founding import (
collect_publication_features,
predict_founding,
)
from service.scripts.profiling.multipliers.graph import build_graph, short_id
from service.scripts.profiling.multipliers.index import NETWORK_MAPPING, NETWORKS_INDEX, MultiplicatorsIndexClient
from service.scripts.profiling.multipliers.metrics import compute_all_metrics, incident_edges
from service.scripts.profiling.multipliers.networks import (
build_network_docs,
collect_author_context,
)
from service.scripts.profiling.multipliers.scoring import load_config, score_rows
from service.scripts.profiling.multipliers.signals import (
cached_author_patent_profiles,
collect_signals,
merge_patent_profiles,
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.",
)
parser.add_argument(
"--no-founding", action="store_true",
help="Skip the founder-potential models (no founding.* fields in the index).",
)
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)
do_founding = not args.no_founding and (config.get("founding") or {}).get(
"enabled", True
)
# ---- load ----
t0 = time.time()
author_records = list(read_jsonl_gz(authors_path))
focal_ids = {a["id"] for a in author_records}
author_meta = {short_id(a["id"]): a for a in author_records}
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 (CORDIS join) +
# per-author institution label and ego-relative company links (network docs)
focal_short_ids = {short_id(a) for a in focal_ids}
dois_by_author, inst_by_author, company_links = collect_author_context(
works,
focal_short_ids,
max_authors_per_work=config["extraction"]["max_authors_per_work"],
doi_normalizer=normalize_doi,
)
# ---- founder-model publication/grant features (works still in memory) ----
pub_features: dict = {}
if do_founding:
t0 = time.time()
pub_features = collect_publication_features(works, focal_short_ids)
timings["founding_features_s"] = round(time.time() - t0, 1)
print(f"Founding features for {len(pub_features)} authors "
f"({timings['founding_features_s']}s)")
# ---- 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) ----
org_patent_profiles: dict = {}
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, org_patent_profiles = 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)")
# ---- founder potential (classifier + timing models) ----
founding_stats: dict[str, int] = {}
if do_founding:
t0 = time.time()
founding_cfg = config.get("founding") or {}
patent_source = founding_cfg.get("patent_source", "org_patents")
if patent_source == "api":
# ~20-65 min for a fresh cohort, cached after
api_profiles = cached_author_patent_profiles(
sorted(metric_rows),
base_url=founding_cfg.get("api_base_url", "http://localhost:8000"),
cache_path=cache_dir / f"patents_named_{short}.json.gz",
concurrency=int(founding_cfg.get("api_concurrency", 16)),
force=args.force_extract,
)
# each source finds holders the other misses — best of both
patent_profiles, merge_stats = merge_patent_profiles(
api_profiles, org_patent_profiles
)
patent_source_label = "api+org_patents"
print(f"Patent profiles for {len(patent_profiles)} authors "
f"(api {len(api_profiles)}, org_patents {len(org_patent_profiles)}, "
f"merged per-author best: {merge_stats})")
else:
patent_profiles = org_patent_profiles
patent_source_label = patent_source
if args.no_signals:
print("WARNING: --no-signals with patent_source=org_patents — the "
"founder models will see zero patents for everyone.")
print(f"Institution-linked patents for {len(patent_profiles)} authors "
f"(patent_source={patent_source}; `api` roughly triples coverage "
f"at ~20-65 min — see multipliers.yaml)")
founding_rows = predict_founding(
metric_rows,
pub_features,
author_meta,
patent_profiles,
ref_year=graph.ref_year,
config=config,
patent_source=patent_source_label,
)
for aid, row in metric_rows.items():
row.update(founding_rows[aid])
founding_stats = {
"in_population": sum(
1 for r in founding_rows.values() if r["founding"]["in_population"]
),
"timing_applicable": sum(
1 for r in founding_rows.values() if r["founding"]["timing_applicable"]
),
"percentile_ge_90": sum(
1 for r in founding_rows.values()
if (r["founding"]["percentile"] or 0) >= 90
),
"with_patents": len(patent_profiles),
}
timings["founding_s"] = round(time.time() - t0, 1)
print(f"Founder potential for {len(founding_rows)} authors "
f"({timings['founding_s']}s): {founding_stats}")
else:
print("Skipping founder-potential models (--no-founding).")
# ---- 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_links,
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]
]
def top_founders(k: int = 10):
"""Highest founder-propensity percentile among in-population authors —
out-of-population rows have no percentile and must not be ranked."""
rows = [r for r in scored if r.get("founding", {}).get("in_population")]
rows.sort(key=lambda r: r["founding"]["percentile"] or 0, reverse=True)
return [
{
"author_id": r["author_id"],
"name": r["display_name"],
"percentile": r["founding"]["percentile"],
"probability_raw": r["founding"]["probability_raw"],
"p_within_3y_percentile": r["founding"].get("p_within_3y_percentile"),
"publications": r.get("founding_features", {}).get("publications"),
"patents": r.get("founding_features", {}).get("patents"),
"bucket": r["career_bucket"],
"tags": r["tags"],
}
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,
"founding": founding_stats,
},
"timings": timings,
"top_bridgers": top("bridger"),
"top_mentors": top("mentor"),
"top_amplifiers": top("amplifier"),
"top_founder_potential": top_founders() if do_founding else [],
}
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()