#!/usr/bin/env python3 """ founding.py — founder-potential enrichment for the multiplicator index (v2). Runs the symmetric (landmark-design) production models from `../founding_potential/production/classifier_symmetric` plus the founder-timing sequence models over the cohort and attaches their outputs to every scored row as flat, explicitly-mapped `founding.*` / `founding_features.*` fields. Which bundles, what each field means, why the scores are NOT a fourth sub-score, and the guard rails (`in_population`, `timing_applicable`): README, "Founder-potential enrichment" and docs/ROADMAP.md §3. The reference year is the corpus's newest publication year (graph.ref_year), not the wall clock, so a re-run on an unchanged extract is byte-identical. """ from __future__ import annotations import importlib.util import sys from dataclasses import dataclass, field from pathlib import Path from typing import Any, Iterable import numpy as np from service.scripts.profiling.multipliers.graph import short_id SCRIPT_DIR = Path(__file__).resolve().parent DEFAULT_HORIZONS = (1, 3, 5) # the v2 horizon bundles that exist # OpenAlex field id -> Dimensions FOR 2-digit division. The classifiers' # *_research_area inputs were trained on FOR codes; our corpus uses OpenAlex's # 26 fields. Per-entry rationale: docs/RESEARCH_AREA_MAPPING.md. OPENALEX_FIELD_TO_FOR = { "11": "30", # Agricultural and Biological Sciences "12": "36", # Arts and Humanities "13": "31", # Biochemistry, Genetics and Molecular Biology "14": "35", # Business, Management and Accounting "15": "40", # Chemical Engineering "16": "34", # Chemistry "17": "46", # Computer Science "18": "49", # Decision Sciences "19": "37", # Earth and Planetary Sciences "20": "38", # Economics, Econometrics and Finance "21": "40", # Energy "22": "40", # Engineering "23": "41", # Environmental Science "24": "32", # Immunology and Microbiology "25": "40", # Materials Science "26": "49", # Mathematics "27": "32", # Medicine "28": "32", # Neuroscience "29": "42", # Nursing "30": "32", # Pharmacology, Toxicology and Pharmaceutics "31": "51", # Physics and Astronomy "32": "52", # Psychology "33": "44", # Social Sciences "34": "30", # Veterinary "35": "32", # Dentistry "36": "42", # Health Professions } # The wrapper's own token for "unknown / not classified". UNKNOWN_AREA = "n." def modal_research_area(field_counts: dict[str, int]) -> str: """Most frequent FOR division across a set of OpenAlex field counts. Ties break on the FOR code, so repeated runs of one extract agree.""" totals: dict[str, int] = {} for field_id, count in field_counts.items(): for_code = OPENALEX_FIELD_TO_FOR.get(str(field_id)) if for_code: totals[for_code] = totals.get(for_code, 0) + count if not totals: return UNKNOWN_AREA return max(sorted(totals), key=lambda code: totals[code]) # --------------------------------------------------------------------- # Feature assembly from the work extract # --------------------------------------------------------------------- @dataclass class PublicationFeatures: """Per-author aggregates over the work extract, for one focal author. No citation aggregates: v2 excludes every citation-level feature as non-historicizable to an index date. """ publications: int = 0 first_publication_year: int | None = None last_publication_year: int | None = None pub_counts_by_year: dict[int, int] = field(default_factory=dict) field_counts: dict[str, int] = field(default_factory=dict) # grants, via OpenAlex `awards` on the author's works award_ids: set[str] = field(default_factory=set) award_ids_by_year: dict[int, set[str]] = field(default_factory=dict) first_grant_year: int | None = None last_grant_year: int | None = None grant_field_counts: dict[str, int] = field(default_factory=dict) @property def grants(self) -> int: return len(self.award_ids) @property def grant_counts_by_year(self) -> dict[int, int]: return {year: len(ids) for year, ids in self.award_ids_by_year.items()} def collect_publication_features( works: Iterable[dict[str, Any]], focal_short_ids: set[str] ) -> dict[str, PublicationFeatures]: """One pass over the work extract -> per-focal-author publication and grant aggregates for the founder models. Independent of graph.py on purpose: the hyperauthorship cap applies to graph edges only, and a 4,839-author paper is still a publication for the person's career profile. `grants` counts DISTINCT OpenAlex award ids and is inflated by consortium acknowledgement lists; the v2 wrapper de-inflates it internally, so the raw count is passed as-is and both values are indexed. """ features: dict[str, PublicationFeatures] = {} for work in works: year = work.get("publication_year") if not isinstance(year, int): continue field_id = short_id(((work.get("primary_topic") or {}).get("field") or {}).get("id")) award_ids = { short_id(a.get("id")) for a in (work.get("awards") or []) if a.get("id") } award_ids.discard(None) seen: set[str] = set() for authorship in work.get("authorships") or []: aid = short_id((authorship.get("author") or {}).get("id")) if not aid or aid in seen or aid not in focal_short_ids: continue seen.add(aid) f = features.get(aid) if f is None: f = features[aid] = PublicationFeatures() f.publications += 1 f.pub_counts_by_year[year] = f.pub_counts_by_year.get(year, 0) + 1 if f.first_publication_year is None or year < f.first_publication_year: f.first_publication_year = year if f.last_publication_year is None or year > f.last_publication_year: f.last_publication_year = year if field_id: f.field_counts[field_id] = f.field_counts.get(field_id, 0) + 1 if award_ids: f.award_ids |= award_ids f.award_ids_by_year.setdefault(year, set()).update(award_ids) if f.first_grant_year is None or year < f.first_grant_year: f.first_grant_year = year if f.last_grant_year is None or year > f.last_grant_year: f.last_grant_year = year if field_id: f.grant_field_counts[field_id] = ( f.grant_field_counts.get(field_id, 0) + 1 ) return features def build_model_record( pub: PublicationFeatures, patent: dict[str, Any], industry_collab_papers: int, ) -> dict[str, Any]: """One author's input record for the v2 classifiers. Contract: classifier_symmetric README, "Input contract". Lifetime totals as of the scoring year; missing signals use the documented 0/unknown defaults. `grants` is passed RAW — the wrapper applies the de-inflation cap itself. Citation fields are absent by contract. """ return { "publications": pub.publications, "patents": int(patent.get("patents") or 0), "grants": pub.grants, "first_publication_year": pub.first_publication_year, "first_patent_year": patent.get("first_patent_year"), "first_grant_year": pub.first_grant_year, "industry_collab_papers": int(industry_collab_papers or 0), # needs a patent-to-paper citation graph this corpus does not have; # 0 is the wrapper's documented default for a missing field "linked_patents_to_publications": 0, "publication_research_area": modal_research_area(pub.field_counts), # no IPC->FOR mapping exists for our patent corpus "patent_research_area": UNKNOWN_AREA, # derived from the works each grant funded "grant_research_area": modal_research_area(pub.grant_field_counts), } # --------------------------------------------------------------------- # Model loading # --------------------------------------------------------------------- def _load_module(path: Path, module_name: str): """Import a standalone wrapper by file path — the production dirs are not packages (each wrapper is meant to be copy-pasteable).""" spec = importlib.util.spec_from_file_location(module_name, path) if spec is None or spec.loader is None: raise RuntimeError(f"Cannot load {module_name} from {path}") module = importlib.util.module_from_spec(spec) # torch.load unpickles the sequence bundles against this module's classes, # so it must be in sys.modules before load() is called sys.modules[module_name] = module spec.loader.exec_module(module) return module @dataclass class FoundingModels: classifier: Any # FounderClassifierV2, founder-propensity horizons: dict[int, Any] # k -> FounderClassifierV2, "founds within k years" timing: Any # FounderTimingModel (point estimate only) timing_cross_check: Any names: dict[str, str] def load_models(config: dict[str, Any]) -> FoundingModels: founding_cfg = config.get("founding") or {} base = Path(founding_cfg.get("models_dir") or "../founding_potential/production") if not base.is_absolute(): base = (SCRIPT_DIR / base).resolve() classifier_mod = _load_module( base / "classifier_symmetric" / "founder_classifier_v2.py", "founder_classifier_v2", ) sequence_mod = _load_module( base / "sequence" / "founder_timing_model.py", "founder_timing_model" ) classifier_path = founding_cfg.get( "classifier", "classifier_symmetric/models/founder_classifier_v2.joblib" ) horizon_paths: dict[int, str] = { int(k): str(v) for k, v in (founding_cfg.get("horizon_bundles") or { 1: "classifier_symmetric/models/p_within_1y_v2.joblib", 3: "classifier_symmetric/models/p_within_3y_v2.joblib", 5: "classifier_symmetric/models/p_within_5y_v2.joblib", }).items() } classifier = classifier_mod.FounderClassifierV2.load(base / classifier_path) horizons = { k: classifier_mod.FounderClassifierV2.load(base / path) for k, path in sorted(horizon_paths.items()) } timing_names = { "timing": founding_cfg.get("timing", "transformer"), "timing_cross_check": founding_cfg.get("timing_cross_check", "lstm"), } def seq(name: str): return sequence_mod.FounderTimingModel.load( base / "sequence" / "models" / f"{name}.pt" ) return FoundingModels( classifier=classifier, horizons=horizons, timing=seq(timing_names["timing"]), timing_cross_check=seq(timing_names["timing_cross_check"]), names={ "classifier": classifier.model_name, **{f"p_within_{k}y": m.model_name for k, m in horizons.items()}, **timing_names, }, ) # --------------------------------------------------------------------- # Inference # --------------------------------------------------------------------- def _batch_founding_age(model: Any, sequences: list[Any]) -> list[float]: """Point estimates for a whole cohort in one forward pass. `_predict_point` takes the batched `(n, WINDOW, 3)` shape; `predict()` is the single-record wrapper and would mean one forward pass per author.""" if not sequences: return [] stacked = np.stack(sequences) return [float(v) for v in model._predict_point(stacked)] def predict_founding( metric_rows: dict[str, dict[str, Any]], pub_features: dict[str, PublicationFeatures], author_meta: dict[str, dict[str, Any]], patent_features: dict[str, dict[str, Any]], ref_year: int, config: dict[str, Any], patent_source: str | None = None, ) -> dict[str, dict[str, Any]]: """Run the v2 classifier, the three horizon bundles and both timing models over the cohort. Returns `{author_short_id: {"founding": {...}, "founding_features": {...}}}`. `author_meta` is unused by v2 (v1 inputs) but stays in the signature. `patent_source` is the provenance stamp for the patent features as actually assembled by the caller (e.g. "api+org_patents"), passed explicitly rather than read from config so it cannot drift from what happened. """ founding_cfg = config.get("founding") or {} max_career_age = int(founding_cfg.get("max_career_age", 20)) models = load_models(config) author_ids = sorted(metric_rows) records: list[dict[str, Any]] = [] for aid in author_ids: records.append( build_model_record( pub_features.get(aid) or PublicationFeatures(), patent_features.get(aid) or {}, metric_rows[aid].get("industry_collab_papers", 0), ) ) main = models.classifier.predict(records, scoring_year=ref_year) horizon_frames = { k: m.predict(records, scoring_year=ref_year) for k, m in models.horizons.items() } # capped grants the model effectively saw, via the wrapper's own mapping grants_raw = np.array([r["grants"] for r in records], dtype=float) pubs_arr = np.array([r["publications"] for r in records], dtype=float) grants_capped = models.classifier._capped_grants(grants_raw, pubs_arr) # One set of sequences feeds both timing models — `build_sequence` only # aligns/pads/log1p's and each applies its own scaler — which is valid only # while the two agree on window and channels. if (models.timing.window, models.timing.channels) != ( models.timing_cross_check.window, models.timing_cross_check.channels, ): raise RuntimeError( f"Timing models disagree on sequence shape: " f"{models.names['timing']} window={models.timing.window} " f"channels={models.timing.channels} vs " f"{models.names['timing_cross_check']} " f"window={models.timing_cross_check.window} " f"channels={models.timing_cross_check.channels}" ) sequences = [] for aid in author_ids: pub = pub_features.get(aid) or PublicationFeatures() sequences.append( models.timing.build_sequence( pub_counts_by_year=pub.pub_counts_by_year, pat_counts_by_year=(patent_features.get(aid) or {}).get( "counts_by_year" ) or {}, grant_counts_by_year=pub.grant_counts_by_year, as_of_year=ref_year, ) ) ages = _batch_founding_age(models.timing, sequences) ages_cross = _batch_founding_age(models.timing_cross_check, sequences) if patent_source is None: patent_source = founding_cfg.get("patent_source", "org_patents") out: dict[str, dict[str, Any]] = {} for i, aid in enumerate(author_ids): record = records[i] pub = pub_features.get(aid) or PublicationFeatures() row = metric_rows[aid] in_population = bool(main["in_population"].iloc[i]) first_year = pub.first_publication_year career_age = ref_year - first_year if first_year else None founding_age = ages[i] years_to_founding = ( founding_age - career_age if career_age is not None else None ) timing_applicable = ( career_age is not None and 1 <= career_age <= max_career_age and not row.get("suspicious_profile", False) ) founding: dict[str, Any] = { "percentile": ( round(float(main["percentile"].iloc[i]), 1) if in_population else None ), "probability_raw": round(float(main["probability_founder"].iloc[i]), 4), "in_population": in_population, **{ f"p_within_{k}y_percentile": ( round(float(frame["percentile"].iloc[i]), 1) if in_population else None ) for k, frame in horizon_frames.items() }, **{ f"p_within_{k}y_raw": round( float(frame["probability_founder"].iloc[i]), 4 ) for k, frame in horizon_frames.items() }, "predicted_founding_age": round(founding_age, 3), "predicted_founding_age_cross_check": round(ages_cross[i], 3), "current_career_age": career_age, "years_to_founding": ( round(years_to_founding, 3) if years_to_founding is not None else None ), "timing_applicable": timing_applicable, "classifier_model": models.names["classifier"], "timing_model": models.names["timing"], "timing_cross_check_model": models.names["timing_cross_check"], "as_of_year": ref_year, # stamped per doc: scores computed under different patent sources # are not comparable "patent_source": patent_source, } # the exact v2 input record as coach-facing evidence; the constant # patent_research_area ("n." corpus-wide) stays out out[aid] = { "founding": founding, "founding_features": { "publications": record["publications"], "patents": record["patents"], "grants": record["grants"], "grants_capped": round(float(grants_capped[i]), 2), "first_publication_year": record["first_publication_year"] or 0, "first_patent_year": record["first_patent_year"] or 0, "first_grant_year": record["first_grant_year"] or 0, "industry_collab_papers": record["industry_collab_papers"], "linked_patents_to_publications": record[ "linked_patents_to_publications" ], "publication_research_area": record["publication_research_area"], "grant_research_area": record["grant_research_area"], }, } return out