diff --git a/service/scripts/profiling/founding_potential/README.md b/service/scripts/profiling/founding_potential/README.md new file mode 100644 index 00000000..d42450a0 --- /dev/null +++ b/service/scripts/profiling/founding_potential/README.md @@ -0,0 +1,556 @@ +# Founding-Potential Prediction — Experiments + +This folder contains a self-contained, reproducible pipeline that answers two +research questions using the Dimensions researcher-metadata datasets in +[`../dimensions_data`](../dimensions_data) and [`../evaluation`](../evaluation): + +- **RQ1** — *Can we classify founders vs. non-founders from full-career + researcher metadata?* +- **RQ2** — *Can we predict, from a truncated ("half") profile taken N years + before founding, whether/when a researcher will go on to found a company — + and does that signal hold up at a longer, unseen horizon and under a + time-to-event (survival) framing?* + +Both baselines ("primitive" models) and modern gradient-boosting / ensemble / +deep-learning models are trained side by side so the added value of more +sophisticated modeling can be judged directly. + +> **⚠️ 2026-08 redesign — read before using any RQ1/RQ2 numbers below.** +> A production probe showed the original RQ1 classifier is an +> *inverse-productivity score* (1 publication → P(founder)=0.996, 800 → +> 0.0002) and the RQ2 `p_within_3y/5y` outputs are degenerate (≡1.0 for every +> author). Root cause: the "pre-founding fix" truncates founders' totals at +> their founding year while non-founders keep full-career totals, so +> observation-window length itself encodes the label; the 0.918→0.976 ROC-AUC +> "improvement" from that fix is class-separability leakage, not noise +> removal. The corrected **symmetric landmark design** lives in +> `src/symmetric.py` (+ `src/yearly_counts.py`, `src/career_curves.py`), is +> trained by `run_rq1_symmetric.py` / `run_rq2_symmetric.py`, and reports +> honest numbers (RQ1 holdout ROC-AUC 0.874 / PR-AUC 0.726 after population + +> plausibility filtering; temporal-split PR-AUC ≈0.73; all RQ2 horizons +> discriminating at ROC-AUC 0.86–0.89). The rebuild also surfaced and filtered +> two further class-asymmetric dataset artifacts: a sampling-frame clash on +> thin profiles (founders from company databases vs non-founders from +> institutional researcher lists) and name-collision aggregate profiles +> concentrated in the non-founder class — see +> `production/classifier_symmetric/README.md`. The sections below describe the +> original (superseded) pipeline and are kept for the paper-trail. + +## Environment + +All work runs in a dedicated conda environment named **`potential`**. + +```bash +# Recreate from scratch +conda create -n potential -c conda-forge python=3.11 pandas numpy scikit-learn \ + matplotlib seaborn joblib tqdm -y +conda activate potential +pip install xgboost lightgbm catboost shap lifelines imbalanced-learn tabulate +conda install -n potential -c conda-forge pytorch -y # installed via conda, not pip + +# Or reproduce the exact resolved environment: +conda env create -f environment.yml +``` + +> **Why PyTorch via conda and not pip?** Pip's PyTorch wheel bundles its own +> OpenMP runtime, which crashes (`OMP: Error #15 ... libomp.dylib already +> initialized`) when mixed with the conda-forge OpenMP runtime used by numpy / +> scikit-learn / LightGBM on macOS. Installing `pytorch` from `conda-forge` +> shares a single OpenMP runtime with everything else, and it works fine. + +Run everything with: + +```bash +cd experiments +conda run -n potential python run_rq1.py +conda run -n potential python run_rq2.py +``` + +> **Known benign warning**: `run_rq1.py`'s SHAP step can print a +> `mutex lock failed` abort trace *after* the pipeline has already finished +> and all result files have been written — it happens during Python +> interpreter shutdown (a threading/OpenMP teardown race between +> SHAP/LightGBM/CatBoost), not during actual computation. Check for the +> `All RQ1 results written to ...` line and the contents of `results/rq1/` to +> confirm success; ignore the trailing stack trace if that line is present. + +## Repository layout + +``` +experiments/ + environment.yml # exported conda environment (reproducibility) + src/ + config.py # paths, constants, leakage-safe feature allow/deny lists + data.py # leakage-safe loaders + feature-matrix builders for RQ1/RQ2 + splits.py # stratified holdout + leave-one-institution-out split helper + outliers.py # two-stage IsolationForest outlier detection + models.py # baseline + advanced/SOTA model factories, stacking ensemble + # (scale-sensitive models wrapped in StandardScaler pipelines) + tuning.py # RandomizedSearchCV hyperparameter search spaces + tune_model() + nn.py # PyTorch MLP baseline (sklearn-style wrapper) + sequence_data.py # founder-only pre-founding activity sequence dataset builder + sequence_models.py # PyTorch LSTM/Transformer sequence regressors (sklearn-style) + evaluate.py # metrics, comparison tables, plots, McNemar test, CV+CI, + # bootstrap CI, calibration curves, stratified-by-group metrics + explain.py # permutation importance + SHAP + survival.py # CoxPH time-to-event modeling for RQ2 + run_rq1.py # RQ1 orchestration script + run_rq2.py # RQ2 orchestration script + run_rq1_robustness.py # ablation, CV+CI, tuning, calibration, bootstrap, area-stratified + run_sequence_founders.py # founder-only LSTM/Transformer founding-age prediction pipeline + results/ + rq1/ # RQ1 tables, plots, trained model, explainability output + rq2/ # RQ2 tables, trained model, survival summary + rq1_robustness/ # ablation/CV/tuning/calibration/bootstrap/area-stratified output + sequence_founders/ # sequence-model comparison tables + plots +``` + +`run_rq1.py` / `run_rq2.py` add `src/` to `sys.path` at runtime rather than +relying on an installed package — simplest option for a self-contained +experiments folder that isn't meant to be pip-installed elsewhere. + +## Data leakage findings (important) + +While auditing `evaluation/datasets_complete` (full-career features, 161 raw +columns) before modeling, two families of columns were found to be +**identically zero for every non-founder row**, i.e. broken/undefined outside +the founder class: + +1. `hist_{pub,pat,grant}_FN{+,-}{1..20}` and the no-suffix `hist_{pub,pat,grant}_FN` + columns (activity counts indexed relative to the *founding* year). +2. `{publications,patents,grants,activities}_{before,after}_founding`. + +A classifier trained on the raw column set would trivially "solve" RQ1 by +detecting this artifact (non-founders always have 0 there) rather than +learning genuine founder traits. Both families are explicitly excluded via +`config.RQ1_DROP_COLUMNS` (a deny-list built and empirically verified with +`.describe()` on the raw CSVs), leaving 24 legitimate full-career numeric +aggregates (h-index, publications, patents, grants, g-index, +`industry_collab_papers`, etc.) plus 3 research-area categoricals and +`institution`. + +The 3 research-area columns (`publication_research_area`, +`patent_research_area`, `grant_research_area`) originally carried 100+ specific +Dimensions codes each (e.g. `"3205 Medical Biochemistry and Metabolomics"`). +One-hot encoding them directly produced ~250 mostly-empty sparse columns, so +`data.build_rq1_matrix` first collapses each to its 2-digit broad parent code +(e.g. `"32"`) before one-hot encoding, reducing RQ1's feature matrix from 248 +columns down to **99** while keeping discipline-level signal. + +The original repository's non-founder downsampling used `df[:n]` — the first +N rows, not a random sample. This experiments pipeline instead either (a) +trains on the full class-imbalanced data with `class_weight='balanced'` / +`scale_pos_weight` / `auto_class_weights='Balanced'` (RQ1), or (b) uses a +documented, fixed-`random_state` 70/30 `train_test_split` to reserve a +non-founder holdout pool that is never touched during RQ2 training +(`data._nonfounder_pool_split`). + +## RQ1 — Founder vs. non-founder classification + +**Data**: `evaluation/datasets_complete`, 8 institutions pooled, restricted to +*pre-founding* activity only (see "Data leakage findings" above), with +multivariate outlier rows removed via a two-stage sanity-ceiling + +IsolationForest filter (`src/outliers.py`, 165/16,494 rows flagged). After +leakage-column removal: **16,494 rows, 99 features, 36.8% founders**. + +**Split**: single stratified 80/20 holdout (`random_state=42`). + +**Models**: `dummy_most_frequent`, `logistic_regression`, `gaussian_nb`, `knn`, +`decision_tree` (baselines); `random_forest`, `svm_rbf`, `xgboost`, `lightgbm`, +`catboost`, a `stacking_ensemble` (RF + XGBoost + LightGBM → logistic +meta-learner), and a PyTorch `torch_mlp` (advanced / SOTA-ish set). The +scale-sensitive models (`logistic_regression`, `gaussian_nb`, `knn`, `svm_rbf`) +are wrapped in a `StandardScaler` pipeline — raw features span very different +ranges (e.g. citation counts vs. binary flags), and without scaling these +models were being penalized relative to the (scale-invariant) tree ensembles. +Tree-based models are intentionally left unscaled. + +### Held-out test results (`results/rq1/rq1_model_comparison.csv`) + +| model | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | +|---|---|---|---|---|---|---|---| +| lightgbm | 0.930 | 0.913 | 0.894 | 0.903 | **0.976** | **0.969** | 0.848 | +| stacking_ensemble | 0.927 | 0.897 | 0.906 | 0.901 | 0.975 | 0.968 | 0.843 | +| xgboost | 0.927 | 0.907 | 0.893 | 0.900 | 0.974 | 0.967 | 0.843 | +| catboost | 0.922 | 0.903 | 0.885 | 0.894 | 0.972 | 0.963 | 0.833 | +| torch_mlp | 0.920 | 0.898 | 0.881 | 0.890 | 0.962 | 0.955 | 0.827 | +| random_forest | 0.896 | 0.873 | 0.839 | 0.856 | 0.952 | 0.935 | 0.774 | +| logistic_regression | 0.882 | 0.824 | 0.864 | 0.843 | 0.943 | 0.928 | 0.749 | +| svm_rbf | 0.875 | 0.845 | 0.810 | 0.827 | 0.937 | 0.914 | 0.730 | +| decision_tree | 0.838 | 0.738 | 0.867 | 0.797 | 0.921 | 0.883 | 0.669 | +| knn | 0.818 | 0.816 | 0.654 | 0.726 | 0.881 | 0.821 | 0.601 | +| gaussian_nb | 0.724 | 0.806 | 0.331 | 0.469 | 0.816 | 0.721 | 0.383 | +| dummy_most_frequent | 0.632 | 0.000 | 0.000 | 0.000 | 0.500 | 0.368 | 0.000 | + +Best baseline: `logistic_regression` (PR-AUC 0.928). Best overall: `lightgbm` +(PR-AUC 0.969). A McNemar test between the two +(`results/rq1/mcnemar_baseline_vs_best.csv`) gives χ²=83.8, p≈5.4e-20 — the +gain from advanced/ensembled models over the best linear baseline is +statistically significant, not noise. (These held-out numbers, and the ones +below, are corroborated by the independent 5-fold CV and bootstrap-CI results +in "Robustness & foolproofing checks" above — e.g. lightgbm's 5-fold PR-AUC +of 0.970 [0.967, 0.973] matches this single-split PR-AUC of 0.969 closely.) + +### Cross-institution generalization (leave-one-institution-out) + +Using the same 99-feature matrix but rebuilt **without** the institution +one-hot columns (`include_institution=False`), each of the 3 top tree-based +models is trained on 7 institutions and tested on the 8th, in turn +(`results/rq1/rq1_leave_one_institution_out.csv`). Mean across institutions: + +| model | roc_auc | pr_auc | mcc | +|---|---|---|---| +| xgboost | 0.953 | 0.922 | 0.779 | +| lightgbm | 0.952 | 0.922 | 0.782 | +| random_forest | 0.940 | 0.900 | 0.738 | + +Generalization to an unseen institution is nearly as strong as in-distribution +performance (compare to the ~0.97 ROC-AUC / ~0.97 PR-AUC of the pooled +holdout above) — the learned founder signal is not merely an artifact of +institution-specific quirks. `muenchen` and `toronto` are consistently the +weakest held-out institutions (ROC-AUC ~0.85), and `telaviv` the strongest +(ROC-AUC ~0.99) — see the per-institution breakdown in the CSV for the full +picture; this is likely driven by per-institution sample size and founder +rate rather than anything model-specific. + +### Explainability (`results/rq1/permutation_importance.csv`, `plots/shap_summary.png`) + +Top permutation-importance features on the best tree model (LightGBM), by +mean drop in PR-AUC when permuted: + +1. `publications` (0.444) +2. `pub_citation_sum` (0.064) +3. `last_patent_year` (0.061) +4. `i10-index` (0.053) +5. `pub_citation_mean` (0.042) +6. `g-index` (0.036) +7. `activities_total` (0.032) +8. `pat_citation_mean` (0.024) +9. `grants` (0.015) +10. `first_publication_year` (0.013) + +With the pre-founding fix applied, `publications` (pre-founding publication +count) is now overwhelmingly the dominant signal, followed by citation-impact +measures and patenting recency. This is a notably cleaner, more concentrated +importance profile than before the fix (previously the top feature accounted +for ~0.055 importance with a long, flat tail) — consistent with the ablation +finding that the pre-founding restriction sharpens rather than removes signal. + + + +## RQ2 — Time-to-founding prediction from a truncated profile + +**Data**: curated 13-column half-profile founder datasets at offsets 1/2/3 +years before founding (`evaluation/datasets_halfprofiles_offset{1,2,3}`), +paired with non-founders from `datasets_complete` using the *same* curated +columns (legitimate/non-degenerate for non-founders too). Non-founders per +institution are split 70/30 once (fixed seed) into a training pool (offsets +1-3) and a holdout pool reserved exclusively for horizon-validation, so no +individual is ever seen in both training and generalization testing. + +### Per-offset comparison (`results/rq2/rq2_offset_comparison.csv`) + +PR-AUC by model × offset (years before founding): + +| model | offset=1 | offset=2 | offset=3 | +|---|---|---|---| +| lightgbm | 0.906 | 0.908 | **0.915** | +| xgboost | 0.908 | **0.910** | 0.914 | +| random_forest | 0.905 | 0.906 | 0.910 | +| decision_tree | 0.843 | 0.844 | 0.860 | +| logistic_regression | 0.829 | 0.830 | 0.837 | +| dummy_most_frequent | 0.434 | 0.434 | 0.434 | + +Predictive power increases (modestly) the closer the profile snapshot is to +the actual founding event, as expected, and gradient-boosted trees clearly +beat the linear/dummy baselines at every horizon. + +### Pooled multi-horizon model + extrapolation validation + +A single LightGBM model is trained on offsets 1-3 pooled (with `offset` as an +explicit feature) and evaluated on: +- its own held-out test split (in-distribution): **ROC-AUC 0.954, PR-AUC 0.947** +- `datasets_halfprofiles_validation_offset3` — an **in-range** horizon never + used for training these specific rows: **ROC-AUC 0.949, PR-AUC 0.945** +- `datasets_halfprofiles_validation_offset5` — an **extrapolation** horizon + (offset=5 was never seen during training at all): **ROC-AUC 0.942, PR-AUC 0.941** + +(`results/rq2/rq2_horizon_validation.csv`.) The degradation from in-range to +extrapolation is small (ROC-AUC 0.949 → 0.942), but note the caveat: tree +ensembles cannot truly extrapolate a numeric feature (`offset`) beyond the +range seen in training, so this result should be read as "still works +reasonably at a nearby unseen horizon," not proof of extrapolation to +arbitrarily distant horizons. + +### Survival analysis (CoxPH) as a complementary framing + +Fixed-horizon classification requires picking specific offsets in advance. +As a principled alternative, `src/survival.py` fits a Cox proportional-hazards +model where the event is "founded a company" and the duration is years from +first publication to founding (or to last observed publication, censored, for +non-founders). Covariates are full-career aggregates (a simplification since +they are not truly time-varying — see the docstring in `survival.py` for this +known limitation). + +- **Concordance index (held-out): 0.715** — the model ranks who-founds-sooner + meaningfully better than chance, but well below the classifiers above. +- **P(founds within 5y) AUC on eligible held-out rows: 0.656** (landmark + analysis avoiding immortal-time bias), versus the pooled classifier's + extrapolation ROC-AUC of 0.942 at the same horizon. + +The purpose-built fixed-horizon classifier substantially outperforms CoxPH +here, most likely because: (a) the classifier gets to use the curated, +horizon-specific half-profile features directly, while CoxPH's covariates are +full-career aggregates rather than genuinely time-varying; and (b) CoxPH's +proportional-hazards assumption is a real constraint the classifiers don't +need to satisfy. The full `cph.print_summary()` (coefficients, hazard ratios, +p-values) is captured in the run log and shows `pub_citation_sum`, +`patents`/`pat_citation_sum`, and `affiliations` as the strongest positive +hazard-ratio covariates, consistent with the RQ1 permutation-importance +findings. + +## Robustness & foolproofing checks (RQ1) + +Beyond a single train/test split, `run_rq1_robustness.py` runs a battery of +checks aimed at making the RQ1 result trustworthy rather than a lucky split, +and at answering two specific questions: *does the pre-founding-leakage fix +actually help or hurt?* and *should the model be split up by research area?* +All numbers below come from actual executed runs; results are saved under +`results/rq1_robustness/`. + +### Ablation: does the pre-founding fix help or hurt? + +An earlier audit found that the raw full-career activity totals technically +include activity *after* founding (reverse causation — the model could partly +"see the future"). The fix restricts these aggregates to pre-founding +activity only. Comparing the two directly (`ablation_prefounding_fix.csv`): + +| variant | n | roc_auc | pr_auc | +|---|---|---|---| +| fix ON (pre-founding only) | 16,494 | **0.976** | **0.969** | +| fix OFF (raw lifetime totals) | 16,466 | 0.918 | 0.886 | + +~~The fix *improves* performance, which is counter to the naive expectation +that "removing a leak should hurt." The interpretation: the raw lifetime +totals aren't a source of illegitimately-helpful signal here so much as +*noise* — removing that dilution helps.~~ + +**Superseded (2026-08):** that interpretation was wrong. The +6-point jump is +the tell, not noise removal: truncating one class's observation window and not +the other's makes "small totals" a class marker, which a production probe +confirmed (P(founder) strictly decreasing in publications, at every threshold). +The honest comparison requires truncating *both* classes at a matched index +date — see the redesign note at the top and `run_rq1_symmetric.py`, which +lands at ROC-AUC ≈0.91 with a domain-plausible (hump-shaped) relationship +between output and founding probability. + +### 5-fold cross-validation with 95% confidence intervals + +(`cv_summary_mean.csv`; per-fold detail in `cv_.csv`.) + +| model | pr_auc (95% CI) | roc_auc (95% CI) | +|---|---|---| +| lightgbm | 0.970 [0.967, 0.973] | 0.978 [0.976, 0.980] | +| xgboost | 0.968 [0.965, 0.972] | 0.977 [0.974, 0.980] | +| random_forest | 0.936 [0.930, 0.942] | 0.953 [0.947, 0.958] | +| logistic_regression | 0.923 [0.917, 0.928] | 0.942 [0.936, 0.947] | +| dummy_most_frequent | 0.368 [0.368, 0.369] | 0.500 | + +Tight confidence intervals across folds confirm the held-out results above +aren't an artifact of one lucky split. + +### Hyperparameter tuning (RandomizedSearchCV) + +(`tuning_comparison.csv`, `tuning_best_params.json`.) 20-iteration randomized +search, 3-fold CV, optimizing PR-AUC: + +| model | pr_auc default → tuned | roc_auc default → tuned | +|---|---|---| +| random_forest | 0.935 → **0.953** | 0.952 → 0.965 | +| xgboost | 0.967 → **0.971** | 0.974 → 0.978 | +| lightgbm | 0.969 → **0.971** | 0.976 → 0.978 | + +Tuning gives a modest but consistent lift for every model, largest for +random_forest. The tuned LightGBM is used as the reference model for the +calibration and bootstrap analyses below. + +### Calibration (`plots/calibration.png`) + +Reliability diagrams (predicted probability vs. observed founder rate, in +quantile bins) for logistic regression and both default/tuned LightGBM all +track close to the diagonal — the model's probability outputs are +meaningfully interpretable as probabilities, not just a ranking score. +LightGBM is slightly better calibrated than logistic regression in the +low-probability region. + +### Bootstrap confidence intervals (tuned LightGBM, 1000 resamples) + +(`bootstrap_ci.csv`.) Percentile bootstrap on the held-out test set: + +| metric | estimate | 95% CI | +|---|---|---| +| accuracy | 0.937 | [0.929, 0.945] | +| precision | 0.926 | [0.911, 0.941] | +| recall | 0.900 | [0.883, 0.916] | +| f1 | 0.913 | [0.901, 0.924] | +| roc_auc | 0.978 | [0.973, 0.982] | +| pr_auc | 0.971 | [0.965, 0.976] | +| mcc | 0.863 | [0.845, 0.881] | + +### Does research area affect the results? (stratified evaluation + per-area specialists) + +This was a specific concern raised: founders in different research areas +might look systematically different, and pooling everyone together could hide +or distort area-specific effects. Two checks were run. + +**1. Stratified evaluation** — the pooled tuned model's held-out predictions +were broken out by broad (2-digit) research area (`area_stratified_pooled_model.csv`, +22 groups, N from 7 to 1,166). The model performs well **uniformly** across +areas — no area catastrophically fails. Largest groups: area "32" (N=1,166) +roc_auc=0.967/pr_auc=0.936; area "31" (N=377) roc_auc=0.973/pr_auc=0.936; area +"40" (N=244) roc_auc=0.962/pr_auc=0.964. Smaller areas (N<100) show more +variance (expected from smaller sample sizes) but generally still PR-AUC +0.91-1.0. + +**2. Per-area specialist vs. pooled model** — for each of the 7 largest +research areas (N≥500), a dedicated model trained *only* on that area's data +was compared against the pooled model evaluated on the same area's subset +(`per_area_specialist_vs_pooled.csv`): + +| area | N (specialist train) | specialist pr_auc | pooled pr_auc | +|---|---|---|---| +| 32 | 4,721 | 0.929 | **0.936** | +| 40 | 1,847 | 0.933 | **0.964** | +| 51 | 1,012 | 0.848 | **0.941** | +| 34 | 462 | 0.909 | **0.965** | + +**The pooled model beats the dedicated specialist on every single area +tested.** Splitting the model by research area hurts performance — the loss +of training data per specialist (hundreds to a few thousand rows, vs. ~13k +for the pooled model) outweighs any benefit from area-specific +specialization. **Conclusion: keep research area as a pooled feature, don't +split the model by area.** + +## Sequence modeling — can a transformer predict *when* someone will found a company? + +The activity-count aggregates used in RQ1/RQ2 discard *order* — e.g. two +founders with the same total pre-founding publication count look identical +even if one had a burst of activity right before founding and the other had +a burst 15 years earlier. To test whether sequence order carries additional +signal, `run_sequence_founders.py` builds true year-by-year sequences and +compares an LSTM and a Transformer against simpler baselines on the task of +predicting **founding_age** (years from first publication to founding) from +the preceding 20-year window of publication/patent/grant activity. + +### Data construction and a data-quality fix + +`founding_age = founded_on − first_publication_year` computed naively across +all 6,158 founders gave an absurd range (**−2,022 to +2,022**), revealing +that a meaningful subset of founders have sentinel/placeholder year values +(not just non-founders, as previously found). Fix: restrict to founders where +*both* `founded_on` and `first_publication_year` fall in a plausible +`[1950, 2024]` range (drops 1,741/6,158 implausible founders → 4,417 remain), +then further restrict to `founding_age` in `[1, 20]` since the 20-year +lookback window structurally can't resolve longer careers — this is a +deliberate, documented scoping decision, not a hidden limitation. **2,298 +founders** remain for the sequence task (`src/sequence_data.py`). + +### Results (`results/sequence_founders/`) + +| model | mae | rmse | r2 | +|---|---|---|---| +| transformer | **0.180** | 0.269 | 0.998 | +| lstm | 0.208 | **0.258** | 0.998 | +| naive_first_activity (heuristic) | 0.554 | 1.885 | 0.888 | +| aggregate_rf (summary stats, no order) | 2.571 | 3.424 | 0.630 | + +(`naive_first_activity` is a zero-parameter heuristic: founding_age is +inferred purely from how many leading zero-activity years precede the first +nonzero year. `aggregate_rf` is a random forest on 9 summary features — total, +nonzero-year count, and last-3-years sum per channel — deliberately +*discarding* order, to isolate the value of order/position information.) + +**Honest interpretation**: the task has strong structural determinism — even +the naive heuristic gets R²=0.888 just by counting leading zero years, so +this isn't a "hard AI problem" in the sense of needing deep learning to make +it tractable at all. The meaningful findings are: (1) the LSTM/Transformer +are far more **robust** than the brittle heuristic (~3x lower MAE, 0.55 → 0.18–0.21 +— the heuristic breaks badly on a single spurious early activity blip, the +sequence models don't), and (2) sequence models vastly outperform the +non-positional aggregate-stats baseline (R² 0.63 → 0.998), proving that +**order/position information, not just totals, is what the extra modeling +power is capturing.** This is reported as a robustness/precision gain over +simpler methods, not an overclaimed "novel predictive capability." + +### Why there's no founder-vs-non-founder sequence classifier + +The natural next step — building comparable sequences for non-founders too, +to train a founder-vs-non-founder *sequence* classifier (a more direct test +of the "sequential transformer" idea) — was investigated and found **not +feasible with the data available in this workspace**, for two independent, +confirmed reasons: + +1. Non-founders' `hist_{pub,pat,grant}_FN[+-]N` columns in + `evaluation/datasets_complete` are computed by + `extraction/non_founders_scripts.ipynb`'s `generate_history(..., + nonstartup=True)`, which hardcodes `founded_year = 0` for non-founders — + these columns are anchored at literal calendar year 0 and are **entirely + zero** (verified via `.sum()==0` / `.max()==0` across every non-founder row). + They were never usable for this and are correctly excluded from + `config.RQ1_NUMERIC_COLUMNS` already (no leakage risk in the existing RQ1 + model). +2. As a fallback, the raw `dimensions_data/{institution}_papers.csv` files + were checked directly for a possible reconstruction path. These files + turn out to contain **only founders' publication records** — verified on + Stanford by matching tracked researcher names against the raw file's + `author_people` column: **85.8%** of founders (1,580/1,842) match, versus + **0%** of non-founders (0/2,482). No raw non-founder paper/patent pull + files exist anywhere in the workspace (only pre-aggregated + `*_nonfounders_features_dataset.csv` summaries) — the underlying raw data + would need to be re-collected from the Dimensions API, which is out of + scope here. + +Given this, the founder-only founding-age sequence model above is the +deliverable for the "sequential transformer" investigation. Building a +founder-vs-non-founder sequence classifier would require re-querying the +Dimensions API for non-founders' raw, per-year publication/patent history. + +(Side note for any future data-collection work: `dimensions_data/*_papers.csv` +already has a pre-matched flat `author_people` name column + numeric `year` +column, exploded to one row per paper per tracked founder — reconstructing a +person's per-year totals is a simple `groupby(["author_people","year"]).size()` +away, no need to fuzzy-match the nested `authors` JSON-like list yourself. +Loading just `usecols=["author_people","year"]` is fast — about 10s even for +a 4.4GB/600K-row file — and reproduces `datasets_complete`'s `publications` +totals almost exactly, 98.1% exact match, correlation 0.99999997, for the +founders whose names do match.) + +## Answering the research questions + +- **RQ1**: Yes. LightGBM classifies founders vs. non-founders with ROC-AUC + 0.976 / PR-AUC 0.969 on held-out data, a statistically significant + improvement (McNemar p≈5.4e-20) over the best simple baseline (logistic + regression, ROC-AUC 0.943), and generalizes well to institutions unseen + during training (mean ROC-AUC 0.95 under leave-one-institution-out). +- **RQ2**: Yes, with caveats. Gradient-boosted models predict founding within + a 1-3 year horizon from truncated profiles with ROC-AUC ≈ 0.91-0.92, and a + pooled multi-horizon model still achieves ROC-AUC 0.94 at a 5-year horizon + it never trained on directly (small degradation vs. 0.95 in-distribution). + A CoxPH survival model provides a complementary, assumption-explicit + time-to-event view but underperforms the direct classifier (concordance + 0.715, 5-year AUC 0.656), which is expected given it uses less + horizon-specific information. +- **Is this robust, or a lucky split?** The RQ1 result holds up under 5-fold + CV (tight 95% CIs), bootstrap resampling, hyperparameter tuning, and + calibration checks — see "Robustness & foolproofing checks" above. The + pre-founding leakage fix specifically *improves* performance rather than + degrading it (0.976 vs 0.918 ROC-AUC), and the model performs uniformly + well across all 22 research-area groups, with a pooled model beating + every dedicated per-area specialist tested. +- **Does sequence order (not just totals) matter?** Yes. LSTM/Transformer + models predicting founding_age from ordered 20-year activity sequences + achieve R²=0.998, versus R²=0.63 for an equivalent non-positional + aggregate-stats model — see "Sequence modeling" above. A comparable + founder-vs-non-founder sequence classifier was investigated but found + infeasible with data available in this workspace (non-founders lack any + usable raw or pre-aggregated sequence data). diff --git a/service/scripts/profiling/founding_potential/catboost_info/catboost_training.json b/service/scripts/profiling/founding_potential/catboost_info/catboost_training.json new file mode 100644 index 00000000..478167e0 --- /dev/null +++ b/service/scripts/profiling/founding_potential/catboost_info/catboost_training.json @@ -0,0 +1,404 @@ +{ +"meta":{"test_sets":[],"test_metrics":[],"learn_metrics":[{"best_value":"Min","name":"Logloss"}],"launch_mode":"Train","parameters":"","iteration_count":400,"learn_sets":["learn"],"name":"experiment"}, +"iterations":[ +{"learn":[0.6752574527],"iteration":0,"passed_time":0.001151431995,"remaining_time":0.4594213658}, +{"learn":[0.6590158329],"iteration":1,"passed_time":0.002307072378,"remaining_time":0.4591074033}, +{"learn":[0.6439053461],"iteration":2,"passed_time":0.003364919794,"remaining_time":0.4452910527}, +{"learn":[0.6300318652],"iteration":3,"passed_time":0.00447839295,"remaining_time":0.443360902}, +{"learn":[0.6176080869],"iteration":4,"passed_time":0.005583615996,"remaining_time":0.4411056637}, +{"learn":[0.6072057723],"iteration":5,"passed_time":0.006660005325,"remaining_time":0.4373403497}, +{"learn":[0.5978862443],"iteration":6,"passed_time":0.007736852993,"remaining_time":0.4343690323}, +{"learn":[0.5892253742],"iteration":7,"passed_time":0.008886826635,"remaining_time":0.4354545051}, +{"learn":[0.5808671388],"iteration":8,"passed_time":0.009982507887,"remaining_time":0.4336845093}, +{"learn":[0.5732077946],"iteration":9,"passed_time":0.01101731333,"remaining_time":0.4296752199}, +{"learn":[0.5661847426],"iteration":10,"passed_time":0.01213249484,"remaining_time":0.4290491358}, +{"learn":[0.5600289293],"iteration":11,"passed_time":0.01322150934,"remaining_time":0.4274954686}, +{"learn":[0.5530962469],"iteration":12,"passed_time":0.01425406475,"remaining_time":0.424332543}, +{"learn":[0.5481010119],"iteration":13,"passed_time":0.01530245371,"remaining_time":0.4219105093}, +{"learn":[0.5434953481],"iteration":14,"passed_time":0.0164163852,"remaining_time":0.4213538869}, +{"learn":[0.5404101637],"iteration":15,"passed_time":0.01755581704,"remaining_time":0.4213396089}, +{"learn":[0.5361341938],"iteration":16,"passed_time":0.01863220637,"remaining_time":0.4197726493}, +{"learn":[0.5317763411],"iteration":17,"passed_time":0.01970834569,"remaining_time":0.4182548919}, +{"learn":[0.5268163473],"iteration":18,"passed_time":0.02082269386,"remaining_time":0.4175498084}, +{"learn":[0.5245315654],"iteration":19,"passed_time":0.02184062408,"remaining_time":0.4149718575}, +{"learn":[0.5205327316],"iteration":20,"passed_time":0.02292138846,"remaining_time":0.413676487}, +{"learn":[0.5177701576],"iteration":21,"passed_time":0.02400340287,"remaining_time":0.4124221038}, +{"learn":[0.5137445796],"iteration":22,"passed_time":0.02504066668,"remaining_time":0.4104491886}, +{"learn":[0.5105456834],"iteration":23,"passed_time":0.02616559832,"remaining_time":0.409927707}, +{"learn":[0.5080257838],"iteration":24,"passed_time":0.02732961381,"remaining_time":0.4099442072}, +{"learn":[0.5054934276],"iteration":25,"passed_time":0.02844792037,"remaining_time":0.409212393}, +{"learn":[0.503296382],"iteration":26,"passed_time":0.02956914363,"remaining_time":0.4084922434}, +{"learn":[0.5006211207],"iteration":27,"passed_time":0.03064232458,"remaining_time":0.4071051694}, +{"learn":[0.4985921934],"iteration":28,"passed_time":0.03184809063,"remaining_time":0.4074359181}, +{"learn":[0.4961473489],"iteration":29,"passed_time":0.03302202292,"remaining_time":0.4072716161}, +{"learn":[0.4946219665],"iteration":30,"passed_time":0.03417528828,"remaining_time":0.4067961733}, +{"learn":[0.4925272328],"iteration":31,"passed_time":0.03534963724,"remaining_time":0.4065208283}, +{"learn":[0.4898936852],"iteration":32,"passed_time":0.03647952728,"remaining_time":0.405696561}, +{"learn":[0.4884288887],"iteration":33,"passed_time":0.03768625168,"remaining_time":0.4056814152}, +{"learn":[0.4863838977],"iteration":34,"passed_time":0.03874026571,"remaining_time":0.4040056281}, +{"learn":[0.4845515615],"iteration":35,"passed_time":0.03985815559,"remaining_time":0.4030102399}, +{"learn":[0.4824883347],"iteration":36,"passed_time":0.04112954752,"remaining_time":0.4035142094}, +{"learn":[0.4804030524],"iteration":37,"passed_time":0.04225827088,"remaining_time":0.4025656331}, +{"learn":[0.4785388461],"iteration":38,"passed_time":0.04337724411,"remaining_time":0.4015175672}, +{"learn":[0.4770942099],"iteration":39,"passed_time":0.04458921857,"remaining_time":0.4013029672}, +{"learn":[0.4756384413],"iteration":40,"passed_time":0.04566781626,"remaining_time":0.3998718546}, +{"learn":[0.4747696424],"iteration":41,"passed_time":0.04680949813,"remaining_time":0.398995246}, +{"learn":[0.4736129814],"iteration":42,"passed_time":0.04803018105,"remaining_time":0.3987622008}, +{"learn":[0.4725400991],"iteration":43,"passed_time":0.04913252905,"remaining_time":0.397526826}, +{"learn":[0.4712424271],"iteration":44,"passed_time":0.05019441819,"remaining_time":0.3959781879}, +{"learn":[0.4701835699],"iteration":45,"passed_time":0.05135301695,"remaining_time":0.3951949565}, +{"learn":[0.4690223311],"iteration":46,"passed_time":0.05250178224,"remaining_time":0.3943218964}, +{"learn":[0.4682401998],"iteration":47,"passed_time":0.05360408858,"remaining_time":0.3930966496}, +{"learn":[0.4663252757],"iteration":48,"passed_time":0.05468322794,"remaining_time":0.3917104696}, +{"learn":[0.4651951732],"iteration":49,"passed_time":0.05579611776,"remaining_time":0.3905728243}, +{"learn":[0.4643129126],"iteration":50,"passed_time":0.05688575727,"remaining_time":0.3892770448}, +{"learn":[0.4634919617],"iteration":51,"passed_time":0.05797056337,"remaining_time":0.3879568472}, +{"learn":[0.4627711631],"iteration":52,"passed_time":0.05911424526,"remaining_time":0.387031002}, +{"learn":[0.4618109601],"iteration":53,"passed_time":0.06020113473,"remaining_time":0.3857331966}, +{"learn":[0.460959898],"iteration":54,"passed_time":0.06127473236,"remaining_time":0.3843596848}, +{"learn":[0.4594625002],"iteration":55,"passed_time":0.06230199603,"remaining_time":0.3827122613}, +{"learn":[0.4584854101],"iteration":56,"passed_time":0.06340980245,"remaining_time":0.3815712674}, +{"learn":[0.4570498581],"iteration":57,"passed_time":0.06447248326,"remaining_time":0.3801653323}, +{"learn":[0.455880592],"iteration":58,"passed_time":0.0655374141,"remaining_time":0.3787840374}, +{"learn":[0.4550663099],"iteration":59,"passed_time":0.06660280329,"remaining_time":0.3774158853}, +{"learn":[0.4542687957],"iteration":60,"passed_time":0.06766948415,"remaining_time":0.3760648382}, +{"learn":[0.4535032807],"iteration":61,"passed_time":0.06875341525,"remaining_time":0.3748170057}, +{"learn":[0.4526542794],"iteration":62,"passed_time":0.06989509711,"remaining_time":0.3738832973}, +{"learn":[0.4514785115],"iteration":63,"passed_time":0.07101169531,"remaining_time":0.3728114004}, +{"learn":[0.4507802979],"iteration":64,"passed_time":0.07211233496,"remaining_time":0.3716558802}, +{"learn":[0.4491962574],"iteration":65,"passed_time":0.07314830709,"remaining_time":0.3701747662}, +{"learn":[0.4485895185],"iteration":66,"passed_time":0.07426457195,"remaining_time":0.3691060068}, +{"learn":[0.4478692379],"iteration":67,"passed_time":0.07539092027,"remaining_time":0.3680850813}, +{"learn":[0.4463417221],"iteration":68,"passed_time":0.07652310201,"remaining_time":0.3670890836}, +{"learn":[0.4452451739],"iteration":69,"passed_time":0.07766007548,"remaining_time":0.3661117844}, +{"learn":[0.4444830618],"iteration":70,"passed_time":0.07871713122,"remaining_time":0.3647596644}, +{"learn":[0.4435724065],"iteration":71,"passed_time":0.07978656212,"remaining_time":0.3634721163}, +{"learn":[0.4420487712],"iteration":72,"passed_time":0.08081545082,"remaining_time":0.3620089372}, +{"learn":[0.441478802],"iteration":73,"passed_time":0.08198309136,"remaining_time":0.3611687538}, +{"learn":[0.4410124289],"iteration":74,"passed_time":0.08309781453,"remaining_time":0.3600905296}, +{"learn":[0.4401138277],"iteration":75,"passed_time":0.08419895419,"remaining_time":0.3589534363}, +{"learn":[0.4394535191],"iteration":76,"passed_time":0.08528813536,"remaining_time":0.3577671133}, +{"learn":[0.4388369011],"iteration":77,"passed_time":0.08643506729,"remaining_time":0.3568216881}, +{"learn":[0.4379911776],"iteration":78,"passed_time":0.08757429079,"remaining_time":0.3558398398}, +{"learn":[0.4374327656],"iteration":79,"passed_time":0.08871480597,"remaining_time":0.3548592239}, +{"learn":[0.4364149666],"iteration":80,"passed_time":0.08976015322,"remaining_time":0.3534998627}, +{"learn":[0.4358972456],"iteration":81,"passed_time":0.09086350124,"remaining_time":0.3523730902}, +{"learn":[0.4352582245],"iteration":82,"passed_time":0.09194689067,"remaining_time":0.3511706547}, +{"learn":[0.4345396736],"iteration":83,"passed_time":0.09300957148,"remaining_time":0.3498931499}, +{"learn":[0.4341003864],"iteration":84,"passed_time":0.09409496093,"remaining_time":0.3487048552}, +{"learn":[0.4332298157],"iteration":85,"passed_time":0.09523405943,"remaining_time":0.3477150542}, +{"learn":[0.43230384],"iteration":86,"passed_time":0.09630836539,"remaining_time":0.3464887169}, +{"learn":[0.4316562364],"iteration":87,"passed_time":0.09744271383,"remaining_time":0.3454787127}, +{"learn":[0.4309618622],"iteration":88,"passed_time":0.09848635272,"remaining_time":0.3441489404}, +{"learn":[0.4298558624],"iteration":89,"passed_time":0.09950936634,"remaining_time":0.3427544841}, +{"learn":[0.4291876524],"iteration":90,"passed_time":0.100633923,"remaining_time":0.3417129912}, +{"learn":[0.4282528408],"iteration":91,"passed_time":0.1017303959,"remaining_time":0.3405756732}, +{"learn":[0.4277131957],"iteration":92,"passed_time":0.10278841,"remaining_time":0.3393122781}, +{"learn":[0.4271829294],"iteration":93,"passed_time":0.1038367156,"remaining_time":0.3380216487}, +{"learn":[0.4264580876],"iteration":94,"passed_time":0.1049022298,"remaining_time":0.3367913693}, +{"learn":[0.4253379692],"iteration":95,"passed_time":0.1059805358,"remaining_time":0.3356050301}, +{"learn":[0.424511763],"iteration":96,"passed_time":0.107145843,"remaining_time":0.3346926848}, +{"learn":[0.4239388347],"iteration":97,"passed_time":0.1083300671,"remaining_time":0.3338334721}, +{"learn":[0.4232630534],"iteration":98,"passed_time":0.1094859575,"remaining_time":0.3328815475}, +{"learn":[0.4226485557],"iteration":99,"passed_time":0.1106647232,"remaining_time":0.3319941695}, +{"learn":[0.4222437514],"iteration":100,"passed_time":0.1117923632,"remaining_time":0.3309496692}, +{"learn":[0.4213299083],"iteration":101,"passed_time":0.1128746276,"remaining_time":0.3297709708}, +{"learn":[0.4208753627],"iteration":102,"passed_time":0.1139770589,"remaining_time":0.3286522961}, +{"learn":[0.420347864],"iteration":103,"passed_time":0.1151212408,"remaining_time":0.3276527624}, +{"learn":[0.4191908122],"iteration":104,"passed_time":0.1161755049,"remaining_time":0.326397847}, +{"learn":[0.4183297442],"iteration":105,"passed_time":0.1172568109,"remaining_time":0.3252217209}, +{"learn":[0.417987752],"iteration":106,"passed_time":0.1184834106,"remaining_time":0.3244452271}, +{"learn":[0.4174588649],"iteration":107,"passed_time":0.1196537595,"remaining_time":0.3235083127}, +{"learn":[0.4169787866],"iteration":108,"passed_time":0.120715107,"remaining_time":0.3222761113}, +{"learn":[0.4159189441],"iteration":109,"passed_time":0.1218433303,"remaining_time":0.3212233254}, +{"learn":[0.4153188878],"iteration":110,"passed_time":0.1229131362,"remaining_time":0.3200170844}, +{"learn":[0.4148918317],"iteration":111,"passed_time":0.1240373595,"remaining_time":0.3189532102}, +{"learn":[0.4144564688],"iteration":112,"passed_time":0.1251508743,"remaining_time":0.3178610702}, +{"learn":[0.4138592532],"iteration":113,"passed_time":0.1262253053,"remaining_time":0.3166705028}, +{"learn":[0.4133895004],"iteration":114,"passed_time":0.1273423202,"remaining_time":0.3155874892}, +{"learn":[0.4127703464],"iteration":115,"passed_time":0.1285151691,"remaining_time":0.3146405865}, +{"learn":[0.4124298162],"iteration":116,"passed_time":0.1297458938,"remaining_time":0.3138298116}, +{"learn":[0.4120395574],"iteration":117,"passed_time":0.1308234915,"remaining_time":0.3126459713}, +{"learn":[0.4107360285],"iteration":118,"passed_time":0.1318712555,"remaining_time":0.3113934688}, +{"learn":[0.4101591941],"iteration":119,"passed_time":0.1329510198,"remaining_time":0.3102190463}, +{"learn":[0.4092665733],"iteration":120,"passed_time":0.1340602013,"remaining_time":0.3091140178}, +{"learn":[0.4088576793],"iteration":121,"passed_time":0.135163341,"remaining_time":0.307995154}, +{"learn":[0.408361342],"iteration":122,"passed_time":0.1362857726,"remaining_time":0.3069199919}, +{"learn":[0.4078673303],"iteration":123,"passed_time":0.137447538,"remaining_time":0.3059316169}, +{"learn":[0.4073910152],"iteration":124,"passed_time":0.1386097202,"remaining_time":0.3049413844}, +{"learn":[0.4066843028],"iteration":125,"passed_time":0.1397284017,"remaining_time":0.303853826}, +{"learn":[0.4062068195],"iteration":126,"passed_time":0.1408698336,"remaining_time":0.3028146817}, +{"learn":[0.4054839673],"iteration":127,"passed_time":0.1420183489,"remaining_time":0.3017889914}, +{"learn":[0.4049627816],"iteration":128,"passed_time":0.1431889478,"remaining_time":0.3008077896}, +{"learn":[0.4042386686],"iteration":129,"passed_time":0.1442632954,"remaining_time":0.2996237674}, +{"learn":[0.4036896032],"iteration":130,"passed_time":0.1453401431,"remaining_time":0.2984465534}, +{"learn":[0.4030055463],"iteration":131,"passed_time":0.1463643234,"remaining_time":0.2971639293}, +{"learn":[0.4025982201],"iteration":132,"passed_time":0.1475024636,"remaining_time":0.2961139682}, +{"learn":[0.4021507256],"iteration":133,"passed_time":0.148610145,"remaining_time":0.2950022281}, +{"learn":[0.4017130107],"iteration":134,"passed_time":0.1497692437,"remaining_time":0.2939914784}, +{"learn":[0.4010693391],"iteration":135,"passed_time":0.1509060922,"remaining_time":0.2929353554}, +{"learn":[0.400549588],"iteration":136,"passed_time":0.1520051485,"remaining_time":0.2918055041}, +{"learn":[0.3999916469],"iteration":137,"passed_time":0.1530488291,"remaining_time":0.2905709653}, +{"learn":[0.3996655064],"iteration":138,"passed_time":0.1542111362,"remaining_time":0.2895619176}, +{"learn":[0.3993175997],"iteration":139,"passed_time":0.1553874019,"remaining_time":0.2885766034}, +{"learn":[0.3989923873],"iteration":140,"passed_time":0.1565616258,"remaining_time":0.2875848304}, +{"learn":[0.3985453884],"iteration":141,"passed_time":0.1576826824,"remaining_time":0.2864938878}, +{"learn":[0.3980582085],"iteration":142,"passed_time":0.1588619064,"remaining_time":0.2855070626}, +{"learn":[0.3978472172],"iteration":143,"passed_time":0.1599966715,"remaining_time":0.2844385272}, +{"learn":[0.3973697391],"iteration":144,"passed_time":0.1611236449,"remaining_time":0.2833553755}, +{"learn":[0.3970929708],"iteration":145,"passed_time":0.1622325346,"remaining_time":0.282240163}, +{"learn":[0.3966356443],"iteration":146,"passed_time":0.1633921751,"remaining_time":0.281212383}, +{"learn":[0.3962418114],"iteration":147,"passed_time":0.1644628977,"remaining_time":0.2800314204}, +{"learn":[0.3958183212],"iteration":148,"passed_time":0.1656396633,"remaining_time":0.2790305738}, +{"learn":[0.3952962072],"iteration":149,"passed_time":0.1667435114,"remaining_time":0.2779058523}, +{"learn":[0.3947786724],"iteration":150,"passed_time":0.1677856502,"remaining_time":0.2766796484}, +{"learn":[0.3942251128],"iteration":151,"passed_time":0.1688929983,"remaining_time":0.2755622604}, +{"learn":[0.393510771],"iteration":152,"passed_time":0.1706222297,"remaining_time":0.275448959}, +{"learn":[0.3931935538],"iteration":153,"passed_time":0.1716946189,"remaining_time":0.2742654303}, +{"learn":[0.3929263145],"iteration":154,"passed_time":0.1728882598,"remaining_time":0.2732749913}, +{"learn":[0.3921994504],"iteration":155,"passed_time":0.1739467323,"remaining_time":0.2720705299}, +{"learn":[0.3918641893],"iteration":156,"passed_time":0.1750668305,"remaining_time":0.2709633109}, +{"learn":[0.391568347],"iteration":157,"passed_time":0.1762223459,"remaining_time":0.2699101753}, +{"learn":[0.3907576665],"iteration":158,"passed_time":0.1772855684,"remaining_time":0.2687158615}, +{"learn":[0.3900011029],"iteration":159,"passed_time":0.1783590827,"remaining_time":0.267538624}, +{"learn":[0.3896939448],"iteration":160,"passed_time":0.1793802212,"remaining_time":0.2662849247}, +{"learn":[0.3892669751],"iteration":161,"passed_time":0.1805231531,"remaining_time":0.2652130274}, +{"learn":[0.3887156987],"iteration":162,"passed_time":0.1816665017,"remaining_time":0.2641408644}, +{"learn":[0.3882799657],"iteration":163,"passed_time":0.1828028501,"remaining_time":0.26305776}, +{"learn":[0.3878736136],"iteration":164,"passed_time":0.1839560322,"remaining_time":0.2619979852}, +{"learn":[0.3873377012],"iteration":165,"passed_time":0.1850520051,"remaining_time":0.2608564409}, +{"learn":[0.3868683205],"iteration":166,"passed_time":0.1861906452,"remaining_time":0.2597749721}, +{"learn":[0.3863639324],"iteration":167,"passed_time":0.1872421176,"remaining_time":0.2585724481}, +{"learn":[0.3856756608],"iteration":168,"passed_time":0.1883451739,"remaining_time":0.25744222}, +{"learn":[0.3851101196],"iteration":169,"passed_time":0.1894709389,"remaining_time":0.256343035}, +{"learn":[0.3845899076],"iteration":170,"passed_time":0.1905734536,"remaining_time":0.2552124028}, +{"learn":[0.3842809463],"iteration":171,"passed_time":0.1917395108,"remaining_time":0.2541663282}, +{"learn":[0.3838979772],"iteration":172,"passed_time":0.1928156501,"remaining_time":0.2530008819}, +{"learn":[0.3835421864],"iteration":173,"passed_time":0.1939655821,"remaining_time":0.2519323078}, +{"learn":[0.3831593151],"iteration":174,"passed_time":0.1951238058,"remaining_time":0.2508734646}, +{"learn":[0.3824219971],"iteration":175,"passed_time":0.1961889867,"remaining_time":0.2496950739}, +{"learn":[0.3818750513],"iteration":176,"passed_time":0.1972604593,"remaining_time":0.2485258894}, +{"learn":[0.3814587697],"iteration":177,"passed_time":0.1984253498,"remaining_time":0.2474743126}, +{"learn":[0.3811315933],"iteration":178,"passed_time":0.1995047391,"remaining_time":0.246315907}, +{"learn":[0.3806289168],"iteration":179,"passed_time":0.2005956703,"remaining_time":0.245172486}, +{"learn":[0.3801948808],"iteration":180,"passed_time":0.2016544344,"remaining_time":0.2439907245}, +{"learn":[0.3793927537],"iteration":181,"passed_time":0.2026815314,"remaining_time":0.2427723838}, +{"learn":[0.379061847],"iteration":182,"passed_time":0.2039010477,"remaining_time":0.2417843024}, +{"learn":[0.3786859738],"iteration":183,"passed_time":0.2050741883,"remaining_time":0.2407392645}, +{"learn":[0.3783497847],"iteration":184,"passed_time":0.2063676222,"remaining_time":0.239832642}, +{"learn":[0.3780392163],"iteration":185,"passed_time":0.2075032623,"remaining_time":0.2387403125}, +{"learn":[0.3773187067],"iteration":186,"passed_time":0.2086255689,"remaining_time":0.2376323325}, +{"learn":[0.3768762307],"iteration":187,"passed_time":0.2097723758,"remaining_time":0.2365518281}, +{"learn":[0.3763556852],"iteration":188,"passed_time":0.2108025562,"remaining_time":0.2353404199}, +{"learn":[0.3756938863],"iteration":189,"passed_time":0.2118649037,"remaining_time":0.2341664725}, +{"learn":[0.3752401881],"iteration":190,"passed_time":0.2130044189,"remaining_time":0.2330781337}, +{"learn":[0.3747042165],"iteration":191,"passed_time":0.2140860166,"remaining_time":0.231926518}, +{"learn":[0.3741421572],"iteration":192,"passed_time":0.2152354486,"remaining_time":0.2308483826}, +{"learn":[0.3737531083],"iteration":193,"passed_time":0.2163026711,"remaining_time":0.2296822178}, +{"learn":[0.3729714636],"iteration":194,"passed_time":0.2173279764,"remaining_time":0.2284730008}, +{"learn":[0.3723401504],"iteration":195,"passed_time":0.2184194909,"remaining_time":0.2273345722}, +{"learn":[0.3717195748],"iteration":196,"passed_time":0.2195059221,"remaining_time":0.2261913816}, +{"learn":[0.3713120882],"iteration":197,"passed_time":0.220651104,"remaining_time":0.225108702}, +{"learn":[0.3706316865],"iteration":198,"passed_time":0.2217496603,"remaining_time":0.2239783001}, +{"learn":[0.3702966116],"iteration":199,"passed_time":0.2229138841,"remaining_time":0.2229138841}, +{"learn":[0.3697721904],"iteration":200,"passed_time":0.2240036069,"remaining_time":0.2217747153}, +{"learn":[0.3690342594],"iteration":201,"passed_time":0.2250807463,"remaining_time":0.2206237018}, +{"learn":[0.3685483475],"iteration":202,"passed_time":0.2262793039,"remaining_time":0.2195912457}, +{"learn":[0.3679488892],"iteration":203,"passed_time":0.2273438597,"remaining_time":0.2184284143}, +{"learn":[0.3674652876],"iteration":204,"passed_time":0.2285949181,"remaining_time":0.2174439465}, +{"learn":[0.3661867815],"iteration":205,"passed_time":0.2296574322,"remaining_time":0.2162793294}, +{"learn":[0.3655245649],"iteration":206,"passed_time":0.2307709887,"remaining_time":0.215163289}, +{"learn":[0.3651419912],"iteration":207,"passed_time":0.2319487544,"remaining_time":0.2141065425}, +{"learn":[0.3648638467],"iteration":208,"passed_time":0.2331167699,"remaining_time":0.2130397275}, +{"learn":[0.3645890135],"iteration":209,"passed_time":0.234272952,"remaining_time":0.2119612423}, +{"learn":[0.3641188983],"iteration":210,"passed_time":0.2353604665,"remaining_time":0.2108205126}, +{"learn":[0.3636023273],"iteration":211,"passed_time":0.2365067734,"remaining_time":0.2097324217}, +{"learn":[0.3625971287],"iteration":212,"passed_time":0.237603163,"remaining_time":0.20859996}, +{"learn":[0.3620963436],"iteration":213,"passed_time":0.2387020943,"remaining_time":0.2074700446}, +{"learn":[0.3613752339],"iteration":214,"passed_time":0.239779317,"remaining_time":0.2063217378}, +{"learn":[0.3609288026],"iteration":215,"passed_time":0.2409774579,"remaining_time":0.2052770938}, +{"learn":[0.3602546044],"iteration":216,"passed_time":0.2420783892,"remaining_time":0.2041490563}, +{"learn":[0.3596176626],"iteration":217,"passed_time":0.2431287365,"remaining_time":0.2029790369}, +{"learn":[0.3591174894],"iteration":218,"passed_time":0.2443525445,"remaining_time":0.2019534728}, +{"learn":[0.3584672055],"iteration":219,"passed_time":0.2454519758,"remaining_time":0.2008243438}, +{"learn":[0.3579661615],"iteration":220,"passed_time":0.2465854492,"remaining_time":0.1997230562}, +{"learn":[0.3575125863],"iteration":221,"passed_time":0.2476947973,"remaining_time":0.1986021348}, +{"learn":[0.3570908255],"iteration":222,"passed_time":0.2488168539,"remaining_time":0.1974914042}, +{"learn":[0.3565320443],"iteration":223,"passed_time":0.2499274937,"remaining_time":0.1963716022}, +{"learn":[0.3557740348],"iteration":224,"passed_time":0.2510059664,"remaining_time":0.1952268628}, +{"learn":[0.3552039883],"iteration":225,"passed_time":0.2521369815,"remaining_time":0.1941231627}, +{"learn":[0.3546823154],"iteration":226,"passed_time":0.2532487879,"remaining_time":0.1930045829}, +{"learn":[0.3542588096],"iteration":227,"passed_time":0.2543872197,"remaining_time":0.1919061482}, +{"learn":[0.3539054745],"iteration":228,"passed_time":0.2556031526,"remaining_time":0.1908652362}, +{"learn":[0.3532278683],"iteration":229,"passed_time":0.2566931254,"remaining_time":0.1897297014}, +{"learn":[0.3529230362],"iteration":230,"passed_time":0.2578798912,"remaining_time":0.188665375}, +{"learn":[0.352381597],"iteration":231,"passed_time":0.2589980311,"remaining_time":0.1875502984}, +{"learn":[0.3518928383],"iteration":232,"passed_time":0.2601070459,"remaining_time":0.1864286552}, +{"learn":[0.3513050813],"iteration":233,"passed_time":0.2611858102,"remaining_time":0.1852856603}, +{"learn":[0.3508996451],"iteration":234,"passed_time":0.262347159,"remaining_time":0.1842011968}, +{"learn":[0.3504190546],"iteration":235,"passed_time":0.2635076745,"remaining_time":0.1831155026}, +{"learn":[0.350020568],"iteration":236,"passed_time":0.2645913556,"remaining_time":0.1819763332}, +{"learn":[0.3495522954],"iteration":237,"passed_time":0.265650578,"remaining_time":0.1808209817}, +{"learn":[0.349180171],"iteration":238,"passed_time":0.2667622178,"remaining_time":0.1797017451}, +{"learn":[0.3488403456],"iteration":239,"passed_time":0.2679780257,"remaining_time":0.1786520171}, +{"learn":[0.348326175],"iteration":240,"passed_time":0.2690999573,"remaining_time":0.177538976}, +{"learn":[0.3480609146],"iteration":241,"passed_time":0.2704532669,"remaining_time":0.1765769264}, +{"learn":[0.3474846933],"iteration":242,"passed_time":0.271532448,"remaining_time":0.1754345446}, +{"learn":[0.3470838691],"iteration":243,"passed_time":0.2727193804,"remaining_time":0.1743615711}, +{"learn":[0.3464878166],"iteration":244,"passed_time":0.2737749778,"remaining_time":0.1732045778}, +{"learn":[0.3461395179],"iteration":245,"passed_time":0.2749240348,"remaining_time":0.1721069161}, +{"learn":[0.3452807894],"iteration":246,"passed_time":0.2759993824,"remaining_time":0.1709631802}, +{"learn":[0.3449142029],"iteration":247,"passed_time":0.2772472741,"remaining_time":0.1699257486}, +{"learn":[0.3443799395],"iteration":248,"passed_time":0.2783343302,"remaining_time":0.1687890918}, +{"learn":[0.3438780899],"iteration":249,"passed_time":0.2794902206,"remaining_time":0.1676941324}, +{"learn":[0.343511803],"iteration":250,"passed_time":0.2805435263,"remaining_time":0.1665377905}, +{"learn":[0.3430115446],"iteration":251,"passed_time":0.2816808747,"remaining_time":0.1654316249}, +{"learn":[0.3424726164],"iteration":252,"passed_time":0.2828335984,"remaining_time":0.1643341461}, +{"learn":[0.3420562225],"iteration":253,"passed_time":0.2839551134,"remaining_time":0.1632182935}, +{"learn":[0.34149691],"iteration":254,"passed_time":0.285008294,"remaining_time":0.1620635397}, +{"learn":[0.3409610654],"iteration":255,"passed_time":0.2860447662,"remaining_time":0.160900181}, +{"learn":[0.3405231536],"iteration":256,"passed_time":0.2871926148,"remaining_time":0.1597997818}, +{"learn":[0.340034093],"iteration":257,"passed_time":0.2882568373,"remaining_time":0.158652988}, +{"learn":[0.3397309627],"iteration":258,"passed_time":0.2893273515,"remaining_time":0.157510257}, +{"learn":[0.339253501],"iteration":259,"passed_time":0.2904178244,"remaining_time":0.1563788285}, +{"learn":[0.3388066139],"iteration":260,"passed_time":0.2915355476,"remaining_time":0.1552622265}, +{"learn":[0.3384464664],"iteration":261,"passed_time":0.292620937,"remaining_time":0.1541285852}, +{"learn":[0.3379404375],"iteration":262,"passed_time":0.2936824928,"remaining_time":0.1529828955}, +{"learn":[0.3375414354],"iteration":263,"passed_time":0.2948104245,"remaining_time":0.1518720369}, +{"learn":[0.3370821259],"iteration":264,"passed_time":0.295924856,"remaining_time":0.1507541719}, +{"learn":[0.336602236],"iteration":265,"passed_time":0.2970121205,"remaining_time":0.1496226472}, +{"learn":[0.3362749],"iteration":266,"passed_time":0.2981132185,"remaining_time":0.1484983448}, +{"learn":[0.3356858224],"iteration":267,"passed_time":0.2991777743,"remaining_time":0.1473562172}, +{"learn":[0.3352310019],"iteration":268,"passed_time":0.3003209145,"remaining_time":0.1462529361}, +{"learn":[0.3348569493],"iteration":269,"passed_time":0.3014208042,"remaining_time":0.1451285354}, +{"learn":[0.3343571837],"iteration":270,"passed_time":0.3025719445,"remaining_time":0.1440287116}, +{"learn":[0.333972653],"iteration":271,"passed_time":0.3036274169,"remaining_time":0.1428834903}, +{"learn":[0.3334731775],"iteration":272,"passed_time":0.3047476818,"remaining_time":0.1417690681}, +{"learn":[0.3330291212],"iteration":273,"passed_time":0.3058505715,"remaining_time":0.1406466132}, +{"learn":[0.3326605023],"iteration":274,"passed_time":0.3069655863,"remaining_time":0.139529812}, +{"learn":[0.3321437127],"iteration":275,"passed_time":0.3080452674,"remaining_time":0.1383971491}, +{"learn":[0.3315365701],"iteration":276,"passed_time":0.3091012398,"remaining_time":0.1372543411}, +{"learn":[0.3310604688],"iteration":277,"passed_time":0.3101988377,"remaining_time":0.1361304252}, +{"learn":[0.3306178809],"iteration":278,"passed_time":0.3113700616,"remaining_time":0.1350386289}, +{"learn":[0.3302189522],"iteration":279,"passed_time":0.3124655346,"remaining_time":0.1339138005}, +{"learn":[0.3298908388],"iteration":280,"passed_time":0.3135639658,"remaining_time":0.1327904339}, +{"learn":[0.3296290713],"iteration":281,"passed_time":0.3147306064,"remaining_time":0.1316957856}, +{"learn":[0.3292322275],"iteration":282,"passed_time":0.3159200389,"remaining_time":0.1306100514}, +{"learn":[0.3289530144],"iteration":283,"passed_time":0.3171967225,"remaining_time":0.1295592247}, +{"learn":[0.3283868788],"iteration":284,"passed_time":0.3182564866,"remaining_time":0.1284192841}, +{"learn":[0.3279859547],"iteration":285,"passed_time":0.3193458345,"remaining_time":0.1272916963}, +{"learn":[0.3276029024],"iteration":286,"passed_time":0.3205133917,"remaining_time":0.1261951682}, +{"learn":[0.3269980903],"iteration":287,"passed_time":0.3216701571,"remaining_time":0.12509395}, +{"learn":[0.3265024345],"iteration":288,"passed_time":0.3228997151,"remaining_time":0.1240203058}, +{"learn":[0.3260926102],"iteration":289,"passed_time":0.3239976464,"remaining_time":0.122895659}, +{"learn":[0.3255902536],"iteration":290,"passed_time":0.3250561605,"remaining_time":0.1217564312}, +{"learn":[0.3253374601],"iteration":291,"passed_time":0.3262455513,"remaining_time":0.1206661628}, +{"learn":[0.3249964957],"iteration":292,"passed_time":0.3274385255,"remaining_time":0.1195765264}, +{"learn":[0.3247110169],"iteration":293,"passed_time":0.3286553334,"remaining_time":0.1184947801}, +{"learn":[0.3244365598],"iteration":294,"passed_time":0.3297882652,"remaining_time":0.1173822639}, +{"learn":[0.3236145686],"iteration":295,"passed_time":0.3309152385,"remaining_time":0.1162675162}, +{"learn":[0.3232270981],"iteration":296,"passed_time":0.332130463,"remaining_time":0.1151832919}, +{"learn":[0.3228851393],"iteration":297,"passed_time":0.3332317693,"remaining_time":0.1140591962}, +{"learn":[0.3225358685],"iteration":298,"passed_time":0.3343837013,"remaining_time":0.112952354}, +{"learn":[0.3221528653],"iteration":299,"passed_time":0.3356189678,"remaining_time":0.1118729893}, +{"learn":[0.3214501982],"iteration":300,"passed_time":0.3367013988,"remaining_time":0.1107423206}, +{"learn":[0.320997221],"iteration":301,"passed_time":0.3378206637,"remaining_time":0.109623924}, +{"learn":[0.3206101631],"iteration":302,"passed_time":0.3389297202,"remaining_time":0.1085022537}, +{"learn":[0.3201732621],"iteration":303,"passed_time":0.3399921927,"remaining_time":0.1073659556}, +{"learn":[0.3199084998],"iteration":304,"passed_time":0.3411286661,"remaining_time":0.1062531911}, +{"learn":[0.3195992788],"iteration":305,"passed_time":0.3422892649,"remaining_time":0.1051476827}, +{"learn":[0.3191488459],"iteration":306,"passed_time":0.3433914879,"remaining_time":0.1040241315}, +{"learn":[0.3187874781],"iteration":307,"passed_time":0.3444620855,"remaining_time":0.1028912723}, +{"learn":[0.3185523705],"iteration":308,"passed_time":0.3456197676,"remaining_time":0.1017844623}, +{"learn":[0.3183052639],"iteration":309,"passed_time":0.3467240323,"remaining_time":0.1006618158}, +{"learn":[0.3179523493],"iteration":310,"passed_time":0.3479116314,"remaining_time":0.09956313568}, +{"learn":[0.3173939542],"iteration":311,"passed_time":0.3490191878,"remaining_time":0.09844130939}, +{"learn":[0.3170235217],"iteration":312,"passed_time":0.3500825353,"remaining_time":0.09730728617}, +{"learn":[0.3167426475],"iteration":313,"passed_time":0.3512368007,"remaining_time":0.0961986142}, +{"learn":[0.3163718121],"iteration":314,"passed_time":0.3523208568,"remaining_time":0.09507070738}, +{"learn":[0.3158370493],"iteration":315,"passed_time":0.3534916224,"remaining_time":0.09396612746}, +{"learn":[0.3155503527],"iteration":316,"passed_time":0.3545707201,"remaining_time":0.0928371286}, +{"learn":[0.3151236337],"iteration":317,"passed_time":0.3557036935,"remaining_time":0.09172233605}, +{"learn":[0.3148689295],"iteration":318,"passed_time":0.3567603742,"remaining_time":0.0905880574}, +{"learn":[0.3146299768],"iteration":319,"passed_time":0.3578028881,"remaining_time":0.08945072202}, +{"learn":[0.3142772407],"iteration":320,"passed_time":0.3588606938,"remaining_time":0.08831774085}, +{"learn":[0.3138530784],"iteration":321,"passed_time":0.360001834,"remaining_time":0.08720541321}, +{"learn":[0.3135854205],"iteration":322,"passed_time":0.3611158489,"remaining_time":0.08608644075}, +{"learn":[0.3131214904],"iteration":323,"passed_time":0.3621631545,"remaining_time":0.08495185105}, +{"learn":[0.3127659838],"iteration":324,"passed_time":0.3632967112,"remaining_time":0.08383770259}, +{"learn":[0.3122350721],"iteration":325,"passed_time":0.3643763506,"remaining_time":0.08271119615}, +{"learn":[0.3118475636],"iteration":326,"passed_time":0.3655228659,"remaining_time":0.08159990583}, +{"learn":[0.3115344437],"iteration":327,"passed_time":0.3666650894,"remaining_time":0.08048745865}, +{"learn":[0.311237246],"iteration":328,"passed_time":0.3677735625,"remaining_time":0.07936754692}, +{"learn":[0.3109110889],"iteration":329,"passed_time":0.3688446184,"remaining_time":0.07823976754}, +{"learn":[0.310639938],"iteration":330,"passed_time":0.37009251,"remaining_time":0.07714919393}, +{"learn":[0.3103155862],"iteration":331,"passed_time":0.3711809828,"remaining_time":0.07602502058}, +{"learn":[0.3098221248],"iteration":332,"passed_time":0.3723168313,"remaining_time":0.07491059368}, +{"learn":[0.309423914],"iteration":333,"passed_time":0.3734389712,"remaining_time":0.07379332964}, +{"learn":[0.3091671621],"iteration":334,"passed_time":0.3746966546,"remaining_time":0.07270233598}, +{"learn":[0.308852111],"iteration":335,"passed_time":0.3758094611,"remaining_time":0.0715827545}, +{"learn":[0.3084452031],"iteration":336,"passed_time":0.3769338511,"remaining_time":0.07046537869}, +{"learn":[0.30805284],"iteration":337,"passed_time":0.3780220739,"remaining_time":0.06934132717}, +{"learn":[0.307790852],"iteration":338,"passed_time":0.3791067133,"remaining_time":0.06821684222}, +{"learn":[0.3075070726],"iteration":339,"passed_time":0.3801461439,"remaining_time":0.06708461362}, +{"learn":[0.3070106772],"iteration":340,"passed_time":0.3812151164,"remaining_time":0.06595804067}, +{"learn":[0.3063522606],"iteration":341,"passed_time":0.3823247145,"remaining_time":0.06483869428}, +{"learn":[0.306023137],"iteration":342,"passed_time":0.3834944384,"remaining_time":0.06372939647}, +{"learn":[0.3056081686],"iteration":343,"passed_time":0.3845728694,"remaining_time":0.06260488572}, +{"learn":[0.3052908972],"iteration":344,"passed_time":0.3857046345,"remaining_time":0.06148914463}, +{"learn":[0.3050698337],"iteration":345,"passed_time":0.3867824405,"remaining_time":0.06036488956}, +{"learn":[0.304718801],"iteration":346,"passed_time":0.3878819552,"remaining_time":0.05924421794}, +{"learn":[0.3043544625],"iteration":347,"passed_time":0.3890576375,"remaining_time":0.05813504928}, +{"learn":[0.3041033502],"iteration":348,"passed_time":0.3902497784,"remaining_time":0.05702790457}, +{"learn":[0.3037743316],"iteration":349,"passed_time":0.3913301677,"remaining_time":0.05590430968}, +{"learn":[0.3034668293],"iteration":350,"passed_time":0.392504225,"remaining_time":0.05479403711}, +{"learn":[0.3030885587],"iteration":351,"passed_time":0.3938031173,"remaining_time":0.05370042509}, +{"learn":[0.3026812327],"iteration":352,"passed_time":0.3948736316,"remaining_time":0.05257524273}, +{"learn":[0.3021014274],"iteration":353,"passed_time":0.3959924381,"remaining_time":0.0514566445}, +{"learn":[0.3018628727],"iteration":354,"passed_time":0.3971618287,"remaining_time":0.05034445716}, +{"learn":[0.3015681515],"iteration":355,"passed_time":0.398210676,"remaining_time":0.04921704984}, +{"learn":[0.3012563129],"iteration":356,"passed_time":0.3994373173,"remaining_time":0.0481114976}, +{"learn":[0.3008425713],"iteration":357,"passed_time":0.4005401653,"remaining_time":0.04699074565}, +{"learn":[0.3006504824],"iteration":358,"passed_time":0.4017283478,"remaining_time":0.04587983917}, +{"learn":[0.3002997122],"iteration":359,"passed_time":0.4028637796,"remaining_time":0.04476264218}, +{"learn":[0.29986022],"iteration":360,"passed_time":0.4039345855,"remaining_time":0.04363836243}, +{"learn":[0.2994157375],"iteration":361,"passed_time":0.4049831411,"remaining_time":0.04251204244}, +{"learn":[0.2991488897],"iteration":362,"passed_time":0.4060736973,"remaining_time":0.04139043196}, +{"learn":[0.2987604674],"iteration":363,"passed_time":0.4071648369,"remaining_time":0.0402690498}, +{"learn":[0.2984520322],"iteration":364,"passed_time":0.4083211439,"remaining_time":0.03915408229}, +{"learn":[0.2980086594],"iteration":365,"passed_time":0.4094280337,"remaining_time":0.03803429821}, +{"learn":[0.2976722806],"iteration":366,"passed_time":0.4105029646,"remaining_time":0.03691171072}, +{"learn":[0.297418779],"iteration":367,"passed_time":0.4116947305,"remaining_time":0.03579954178}, +{"learn":[0.2970540834],"iteration":368,"passed_time":0.4128054119,"remaining_time":0.03468012946}, +{"learn":[0.2968505628],"iteration":369,"passed_time":0.4138733428,"remaining_time":0.03355729807}, +{"learn":[0.2966096352],"iteration":370,"passed_time":0.4149656907,"remaining_time":0.03243667124}, +{"learn":[0.2962534879],"iteration":371,"passed_time":0.4159768292,"remaining_time":0.03131008392}, +{"learn":[0.2956966575],"iteration":372,"passed_time":0.4170019261,"remaining_time":0.03018512602}, +{"learn":[0.295467724],"iteration":373,"passed_time":0.4181140243,"remaining_time":0.02906675035}, +{"learn":[0.295198672],"iteration":374,"passed_time":0.4192409559,"remaining_time":0.02794939706}, +{"learn":[0.2948654216],"iteration":375,"passed_time":0.4202776364,"remaining_time":0.02682623211}, +{"learn":[0.2944509322],"iteration":376,"passed_time":0.4213771094,"remaining_time":0.02570735681}, +{"learn":[0.294163659],"iteration":377,"passed_time":0.4226436679,"remaining_time":0.02459830871}, +{"learn":[0.2938644764],"iteration":378,"passed_time":0.4237322241,"remaining_time":0.02347856651}, +{"learn":[0.293532816],"iteration":379,"passed_time":0.4248420722,"remaining_time":0.02236010906}, +{"learn":[0.2932769543],"iteration":380,"passed_time":0.4259474202,"remaining_time":0.0212414724}, +{"learn":[0.2930012713],"iteration":381,"passed_time":0.4270412265,"remaining_time":0.02012236146}, +{"learn":[0.2927528101],"iteration":382,"passed_time":0.4281576163,"remaining_time":0.01900438506}, +{"learn":[0.2924546703],"iteration":383,"passed_time":0.4292129637,"remaining_time":0.01788387349}, +{"learn":[0.2921348133],"iteration":384,"passed_time":0.4303516039,"remaining_time":0.0167669456}, +{"learn":[0.2918413938],"iteration":385,"passed_time":0.4314503685,"remaining_time":0.01564845896}, +{"learn":[0.2914998283],"iteration":386,"passed_time":0.4325481331,"remaining_time":0.01453004065}, +{"learn":[0.2912741093],"iteration":387,"passed_time":0.4336954817,"remaining_time":0.01341326232}, +{"learn":[0.2910467504],"iteration":388,"passed_time":0.4347749961,"remaining_time":0.01229440863}, +{"learn":[0.2908811787],"iteration":389,"passed_time":0.4359572618,"remaining_time":0.01117839133}, +{"learn":[0.29031764],"iteration":390,"passed_time":0.4370190259,"remaining_time":0.01005926147}, +{"learn":[0.2900000009],"iteration":391,"passed_time":0.4381199989,"remaining_time":0.008941224468}, +{"learn":[0.2897507124],"iteration":392,"passed_time":0.4392080968,"remaining_time":0.00782304498}, +{"learn":[0.2895248451],"iteration":393,"passed_time":0.4403091947,"remaining_time":0.006705216164}, +{"learn":[0.2892178364],"iteration":394,"passed_time":0.4414087927,"remaining_time":0.005587453072}, +{"learn":[0.2888956874],"iteration":395,"passed_time":0.442581475,"remaining_time":0.004470519949}, +{"learn":[0.2885872177],"iteration":396,"passed_time":0.443805658,"remaining_time":0.003353695148}, +{"learn":[0.2883226548],"iteration":397,"passed_time":0.4449120477,"remaining_time":0.002235738933}, +{"learn":[0.2880616544],"iteration":398,"passed_time":0.4460379793,"remaining_time":0.001117889673}, +{"learn":[0.2877225749],"iteration":399,"passed_time":0.4471239521,"remaining_time":0} +]} \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/catboost_info/learn/events.out.tfevents b/service/scripts/profiling/founding_potential/catboost_info/learn/events.out.tfevents new file mode 100644 index 00000000..2b8d6ee8 Binary files /dev/null and b/service/scripts/profiling/founding_potential/catboost_info/learn/events.out.tfevents differ diff --git a/service/scripts/profiling/founding_potential/catboost_info/learn_error.tsv b/service/scripts/profiling/founding_potential/catboost_info/learn_error.tsv new file mode 100644 index 00000000..1d10327d --- /dev/null +++ b/service/scripts/profiling/founding_potential/catboost_info/learn_error.tsv @@ -0,0 +1,401 @@ +iter Logloss +0 0.6752574527 +1 0.6590158329 +2 0.6439053461 +3 0.6300318652 +4 0.6176080869 +5 0.6072057723 +6 0.5978862443 +7 0.5892253742 +8 0.5808671388 +9 0.5732077946 +10 0.5661847426 +11 0.5600289293 +12 0.5530962469 +13 0.5481010119 +14 0.5434953481 +15 0.5404101637 +16 0.5361341938 +17 0.5317763411 +18 0.5268163473 +19 0.5245315654 +20 0.5205327316 +21 0.5177701576 +22 0.5137445796 +23 0.5105456834 +24 0.5080257838 +25 0.5054934276 +26 0.503296382 +27 0.5006211207 +28 0.4985921934 +29 0.4961473489 +30 0.4946219665 +31 0.4925272328 +32 0.4898936852 +33 0.4884288887 +34 0.4863838977 +35 0.4845515615 +36 0.4824883347 +37 0.4804030524 +38 0.4785388461 +39 0.4770942099 +40 0.4756384413 +41 0.4747696424 +42 0.4736129814 +43 0.4725400991 +44 0.4712424271 +45 0.4701835699 +46 0.4690223311 +47 0.4682401998 +48 0.4663252757 +49 0.4651951732 +50 0.4643129126 +51 0.4634919617 +52 0.4627711631 +53 0.4618109601 +54 0.460959898 +55 0.4594625002 +56 0.4584854101 +57 0.4570498581 +58 0.455880592 +59 0.4550663099 +60 0.4542687957 +61 0.4535032807 +62 0.4526542794 +63 0.4514785115 +64 0.4507802979 +65 0.4491962574 +66 0.4485895185 +67 0.4478692379 +68 0.4463417221 +69 0.4452451739 +70 0.4444830618 +71 0.4435724065 +72 0.4420487712 +73 0.441478802 +74 0.4410124289 +75 0.4401138277 +76 0.4394535191 +77 0.4388369011 +78 0.4379911776 +79 0.4374327656 +80 0.4364149666 +81 0.4358972456 +82 0.4352582245 +83 0.4345396736 +84 0.4341003864 +85 0.4332298157 +86 0.43230384 +87 0.4316562364 +88 0.4309618622 +89 0.4298558624 +90 0.4291876524 +91 0.4282528408 +92 0.4277131957 +93 0.4271829294 +94 0.4264580876 +95 0.4253379692 +96 0.424511763 +97 0.4239388347 +98 0.4232630534 +99 0.4226485557 +100 0.4222437514 +101 0.4213299083 +102 0.4208753627 +103 0.420347864 +104 0.4191908122 +105 0.4183297442 +106 0.417987752 +107 0.4174588649 +108 0.4169787866 +109 0.4159189441 +110 0.4153188878 +111 0.4148918317 +112 0.4144564688 +113 0.4138592532 +114 0.4133895004 +115 0.4127703464 +116 0.4124298162 +117 0.4120395574 +118 0.4107360285 +119 0.4101591941 +120 0.4092665733 +121 0.4088576793 +122 0.408361342 +123 0.4078673303 +124 0.4073910152 +125 0.4066843028 +126 0.4062068195 +127 0.4054839673 +128 0.4049627816 +129 0.4042386686 +130 0.4036896032 +131 0.4030055463 +132 0.4025982201 +133 0.4021507256 +134 0.4017130107 +135 0.4010693391 +136 0.400549588 +137 0.3999916469 +138 0.3996655064 +139 0.3993175997 +140 0.3989923873 +141 0.3985453884 +142 0.3980582085 +143 0.3978472172 +144 0.3973697391 +145 0.3970929708 +146 0.3966356443 +147 0.3962418114 +148 0.3958183212 +149 0.3952962072 +150 0.3947786724 +151 0.3942251128 +152 0.393510771 +153 0.3931935538 +154 0.3929263145 +155 0.3921994504 +156 0.3918641893 +157 0.391568347 +158 0.3907576665 +159 0.3900011029 +160 0.3896939448 +161 0.3892669751 +162 0.3887156987 +163 0.3882799657 +164 0.3878736136 +165 0.3873377012 +166 0.3868683205 +167 0.3863639324 +168 0.3856756608 +169 0.3851101196 +170 0.3845899076 +171 0.3842809463 +172 0.3838979772 +173 0.3835421864 +174 0.3831593151 +175 0.3824219971 +176 0.3818750513 +177 0.3814587697 +178 0.3811315933 +179 0.3806289168 +180 0.3801948808 +181 0.3793927537 +182 0.379061847 +183 0.3786859738 +184 0.3783497847 +185 0.3780392163 +186 0.3773187067 +187 0.3768762307 +188 0.3763556852 +189 0.3756938863 +190 0.3752401881 +191 0.3747042165 +192 0.3741421572 +193 0.3737531083 +194 0.3729714636 +195 0.3723401504 +196 0.3717195748 +197 0.3713120882 +198 0.3706316865 +199 0.3702966116 +200 0.3697721904 +201 0.3690342594 +202 0.3685483475 +203 0.3679488892 +204 0.3674652876 +205 0.3661867815 +206 0.3655245649 +207 0.3651419912 +208 0.3648638467 +209 0.3645890135 +210 0.3641188983 +211 0.3636023273 +212 0.3625971287 +213 0.3620963436 +214 0.3613752339 +215 0.3609288026 +216 0.3602546044 +217 0.3596176626 +218 0.3591174894 +219 0.3584672055 +220 0.3579661615 +221 0.3575125863 +222 0.3570908255 +223 0.3565320443 +224 0.3557740348 +225 0.3552039883 +226 0.3546823154 +227 0.3542588096 +228 0.3539054745 +229 0.3532278683 +230 0.3529230362 +231 0.352381597 +232 0.3518928383 +233 0.3513050813 +234 0.3508996451 +235 0.3504190546 +236 0.350020568 +237 0.3495522954 +238 0.349180171 +239 0.3488403456 +240 0.348326175 +241 0.3480609146 +242 0.3474846933 +243 0.3470838691 +244 0.3464878166 +245 0.3461395179 +246 0.3452807894 +247 0.3449142029 +248 0.3443799395 +249 0.3438780899 +250 0.343511803 +251 0.3430115446 +252 0.3424726164 +253 0.3420562225 +254 0.34149691 +255 0.3409610654 +256 0.3405231536 +257 0.340034093 +258 0.3397309627 +259 0.339253501 +260 0.3388066139 +261 0.3384464664 +262 0.3379404375 +263 0.3375414354 +264 0.3370821259 +265 0.336602236 +266 0.3362749 +267 0.3356858224 +268 0.3352310019 +269 0.3348569493 +270 0.3343571837 +271 0.333972653 +272 0.3334731775 +273 0.3330291212 +274 0.3326605023 +275 0.3321437127 +276 0.3315365701 +277 0.3310604688 +278 0.3306178809 +279 0.3302189522 +280 0.3298908388 +281 0.3296290713 +282 0.3292322275 +283 0.3289530144 +284 0.3283868788 +285 0.3279859547 +286 0.3276029024 +287 0.3269980903 +288 0.3265024345 +289 0.3260926102 +290 0.3255902536 +291 0.3253374601 +292 0.3249964957 +293 0.3247110169 +294 0.3244365598 +295 0.3236145686 +296 0.3232270981 +297 0.3228851393 +298 0.3225358685 +299 0.3221528653 +300 0.3214501982 +301 0.320997221 +302 0.3206101631 +303 0.3201732621 +304 0.3199084998 +305 0.3195992788 +306 0.3191488459 +307 0.3187874781 +308 0.3185523705 +309 0.3183052639 +310 0.3179523493 +311 0.3173939542 +312 0.3170235217 +313 0.3167426475 +314 0.3163718121 +315 0.3158370493 +316 0.3155503527 +317 0.3151236337 +318 0.3148689295 +319 0.3146299768 +320 0.3142772407 +321 0.3138530784 +322 0.3135854205 +323 0.3131214904 +324 0.3127659838 +325 0.3122350721 +326 0.3118475636 +327 0.3115344437 +328 0.311237246 +329 0.3109110889 +330 0.310639938 +331 0.3103155862 +332 0.3098221248 +333 0.309423914 +334 0.3091671621 +335 0.308852111 +336 0.3084452031 +337 0.30805284 +338 0.307790852 +339 0.3075070726 +340 0.3070106772 +341 0.3063522606 +342 0.306023137 +343 0.3056081686 +344 0.3052908972 +345 0.3050698337 +346 0.304718801 +347 0.3043544625 +348 0.3041033502 +349 0.3037743316 +350 0.3034668293 +351 0.3030885587 +352 0.3026812327 +353 0.3021014274 +354 0.3018628727 +355 0.3015681515 +356 0.3012563129 +357 0.3008425713 +358 0.3006504824 +359 0.3002997122 +360 0.29986022 +361 0.2994157375 +362 0.2991488897 +363 0.2987604674 +364 0.2984520322 +365 0.2980086594 +366 0.2976722806 +367 0.297418779 +368 0.2970540834 +369 0.2968505628 +370 0.2966096352 +371 0.2962534879 +372 0.2956966575 +373 0.295467724 +374 0.295198672 +375 0.2948654216 +376 0.2944509322 +377 0.294163659 +378 0.2938644764 +379 0.293532816 +380 0.2932769543 +381 0.2930012713 +382 0.2927528101 +383 0.2924546703 +384 0.2921348133 +385 0.2918413938 +386 0.2914998283 +387 0.2912741093 +388 0.2910467504 +389 0.2908811787 +390 0.29031764 +391 0.2900000009 +392 0.2897507124 +393 0.2895248451 +394 0.2892178364 +395 0.2888956874 +396 0.2885872177 +397 0.2883226548 +398 0.2880616544 +399 0.2877225749 diff --git a/service/scripts/profiling/founding_potential/catboost_info/time_left.tsv b/service/scripts/profiling/founding_potential/catboost_info/time_left.tsv new file mode 100644 index 00000000..300bf558 --- /dev/null +++ b/service/scripts/profiling/founding_potential/catboost_info/time_left.tsv @@ -0,0 +1,401 @@ +iter Passed Remaining +0 1 459 +1 2 459 +2 3 445 +3 4 443 +4 5 441 +5 6 437 +6 7 434 +7 8 435 +8 9 433 +9 11 429 +10 12 429 +11 13 427 +12 14 424 +13 15 421 +14 16 421 +15 17 421 +16 18 419 +17 19 418 +18 20 417 +19 21 414 +20 22 413 +21 24 412 +22 25 410 +23 26 409 +24 27 409 +25 28 409 +26 29 408 +27 30 407 +28 31 407 +29 33 407 +30 34 406 +31 35 406 +32 36 405 +33 37 405 +34 38 404 +35 39 403 +36 41 403 +37 42 402 +38 43 401 +39 44 401 +40 45 399 +41 46 398 +42 48 398 +43 49 397 +44 50 395 +45 51 395 +46 52 394 +47 53 393 +48 54 391 +49 55 390 +50 56 389 +51 57 387 +52 59 387 +53 60 385 +54 61 384 +55 62 382 +56 63 381 +57 64 380 +58 65 378 +59 66 377 +60 67 376 +61 68 374 +62 69 373 +63 71 372 +64 72 371 +65 73 370 +66 74 369 +67 75 368 +68 76 367 +69 77 366 +70 78 364 +71 79 363 +72 80 362 +73 81 361 +74 83 360 +75 84 358 +76 85 357 +77 86 356 +78 87 355 +79 88 354 +80 89 353 +81 90 352 +82 91 351 +83 93 349 +84 94 348 +85 95 347 +86 96 346 +87 97 345 +88 98 344 +89 99 342 +90 100 341 +91 101 340 +92 102 339 +93 103 338 +94 104 336 +95 105 335 +96 107 334 +97 108 333 +98 109 332 +99 110 331 +100 111 330 +101 112 329 +102 113 328 +103 115 327 +104 116 326 +105 117 325 +106 118 324 +107 119 323 +108 120 322 +109 121 321 +110 122 320 +111 124 318 +112 125 317 +113 126 316 +114 127 315 +115 128 314 +116 129 313 +117 130 312 +118 131 311 +119 132 310 +120 134 309 +121 135 307 +122 136 306 +123 137 305 +124 138 304 +125 139 303 +126 140 302 +127 142 301 +128 143 300 +129 144 299 +130 145 298 +131 146 297 +132 147 296 +133 148 295 +134 149 293 +135 150 292 +136 152 291 +137 153 290 +138 154 289 +139 155 288 +140 156 287 +141 157 286 +142 158 285 +143 159 284 +144 161 283 +145 162 282 +146 163 281 +147 164 280 +148 165 279 +149 166 277 +150 167 276 +151 168 275 +152 170 275 +153 171 274 +154 172 273 +155 173 272 +156 175 270 +157 176 269 +158 177 268 +159 178 267 +160 179 266 +161 180 265 +162 181 264 +163 182 263 +164 183 261 +165 185 260 +166 186 259 +167 187 258 +168 188 257 +169 189 256 +170 190 255 +171 191 254 +172 192 253 +173 193 251 +174 195 250 +175 196 249 +176 197 248 +177 198 247 +178 199 246 +179 200 245 +180 201 243 +181 202 242 +182 203 241 +183 205 240 +184 206 239 +185 207 238 +186 208 237 +187 209 236 +188 210 235 +189 211 234 +190 213 233 +191 214 231 +192 215 230 +193 216 229 +194 217 228 +195 218 227 +196 219 226 +197 220 225 +198 221 223 +199 222 222 +200 224 221 +201 225 220 +202 226 219 +203 227 218 +204 228 217 +205 229 216 +206 230 215 +207 231 214 +208 233 213 +209 234 211 +210 235 210 +211 236 209 +212 237 208 +213 238 207 +214 239 206 +215 240 205 +216 242 204 +217 243 202 +218 244 201 +219 245 200 +220 246 199 +221 247 198 +222 248 197 +223 249 196 +224 251 195 +225 252 194 +226 253 193 +227 254 191 +228 255 190 +229 256 189 +230 257 188 +231 258 187 +232 260 186 +233 261 185 +234 262 184 +235 263 183 +236 264 181 +237 265 180 +238 266 179 +239 267 178 +240 269 177 +241 270 176 +242 271 175 +243 272 174 +244 273 173 +245 274 172 +246 275 170 +247 277 169 +248 278 168 +249 279 167 +250 280 166 +251 281 165 +252 282 164 +253 283 163 +254 285 162 +255 286 160 +256 287 159 +257 288 158 +258 289 157 +259 290 156 +260 291 155 +261 292 154 +262 293 152 +263 294 151 +264 295 150 +265 297 149 +266 298 148 +267 299 147 +268 300 146 +269 301 145 +270 302 144 +271 303 142 +272 304 141 +273 305 140 +274 306 139 +275 308 138 +276 309 137 +277 310 136 +278 311 135 +279 312 133 +280 313 132 +281 314 131 +282 315 130 +283 317 129 +284 318 128 +285 319 127 +286 320 126 +287 321 125 +288 322 124 +289 323 122 +290 325 121 +291 326 120 +292 327 119 +293 328 118 +294 329 117 +295 330 116 +296 332 115 +297 333 114 +298 334 112 +299 335 111 +300 336 110 +301 337 109 +302 338 108 +303 339 107 +304 341 106 +305 342 105 +306 343 104 +307 344 102 +308 345 101 +309 346 100 +310 347 99 +311 349 98 +312 350 97 +313 351 96 +314 352 95 +315 353 93 +316 354 92 +317 355 91 +318 356 90 +319 357 89 +320 358 88 +321 360 87 +322 361 86 +323 362 84 +324 363 83 +325 364 82 +326 365 81 +327 366 80 +328 367 79 +329 368 78 +330 370 77 +331 371 76 +332 372 74 +333 373 73 +334 374 72 +335 375 71 +336 376 70 +337 378 69 +338 379 68 +339 380 67 +340 381 65 +341 382 64 +342 383 63 +343 384 62 +344 385 61 +345 386 60 +346 387 59 +347 389 58 +348 390 57 +349 391 55 +350 392 54 +351 393 53 +352 394 52 +353 395 51 +354 397 50 +355 398 49 +356 399 48 +357 400 46 +358 401 45 +359 402 44 +360 403 43 +361 404 42 +362 406 41 +363 407 40 +364 408 39 +365 409 38 +366 410 36 +367 411 35 +368 412 34 +369 413 33 +370 414 32 +371 415 31 +372 417 30 +373 418 29 +374 419 27 +375 420 26 +376 421 25 +377 422 24 +378 423 23 +379 424 22 +380 425 21 +381 427 20 +382 428 19 +383 429 17 +384 430 16 +385 431 15 +386 432 14 +387 433 13 +388 434 12 +389 435 11 +390 437 10 +391 438 8 +392 439 7 +393 440 6 +394 441 5 +395 442 4 +396 443 3 +397 444 2 +398 446 1 +399 447 0 diff --git a/service/scripts/profiling/founding_potential/docs/DESIGN_NOTES.md b/service/scripts/profiling/founding_potential/docs/DESIGN_NOTES.md new file mode 100644 index 00000000..786c2a8a --- /dev/null +++ b/service/scripts/profiling/founding_potential/docs/DESIGN_NOTES.md @@ -0,0 +1,181 @@ +# Design notes — why the preprocessing modules do what they do + +Reference for the methodology behind `src/`. The code carries short contract +docstrings; the reasoning lives here. Results and model performance are in the +top-level [README.md](../README.md); the production contract is in +[`production/classifier_symmetric/README.md`](../production/classifier_symmetric/README.md). + +--- + +## `config.py` — why whole column families are excluded + +The `hist_*_FN[+-]k`, `*_before_founding` and `*_after_founding` columns are +computed relative to a founding event and are **identically zero for every +non-founder row** in `datasets_complete`. In RQ1 (full-profile founder vs. +non-founder) a model would separate the classes on that artifact rather than on +signal, so they are excluded from `RQ1_FEATURE_COLUMNS`. + +`RQ1_PREFOUNDING_PAIRS` handles the opposite direction. For founders, lifetime +totals include **post**-founding activity (e.g. continuing to publish part-time +after founding) — a reverse-causation confound that lets a model key off a +downstream *effect* of founding. Non-founders have no equivalent issue: their +full total is inherently "pre-founding". For the four metrics where a validated +`_before_founding` split exists, `data._apply_prefounding_equivalent` swaps it in. + +## `data.py` — leakage-safe loading for RQ1 and RQ2 + +**RQ1** reads `evaluation/datasets_complete`, drops identifier and leaky columns +(`config.RQ1_DROP_COLUMNS`) and keeps the remaining full-career aggregates. + +**RQ2** ("founds within N years") reads the curated 13-column half-profile +datasets (`datasets_halfprofiles_offset{1,2,3}`) as the positive class at each +horizon, paired with non-founders from `datasets_complete` on the same curated +columns, which are legitimate and non-degenerate for non-founders too. + +Non-founders are split 70/30 per institution **once** (fixed `random_state`) +into a training pool (offsets 1–3) and a holdout pool reserved exclusively for +the offset-3/5 horizon-validation sets, so no individual is ever seen in both +training and horizon-generalization testing. + +## `outliers.py` — two-stage multivariate outlier detection + +Replaces the original `publications < 1000` / `patents < 1000` guard inherited +from the source notebooks. That guard does remove real rows (677 of them), but +the underlying problem is worse than a long tail: several of the most extreme +rows — "Hui Zhang" with 20,703 publications and 49,398 patents, "David Smith" +with 16,713 publications — are almost certainly **common-name collisions**. +Dimensions' name-based researcher matching merges dozens of distinct real people +who share a common name into one aggregated profile; these are not genuinely +hyper-prolific individuals. + +A single hand-picked threshold on one or two columns cannot reliably separate +"very productive but real" from "impossible amalgamation of several people", so +outlier handling is two-staged: + +1. A generous, documented **sanity ceiling** — any individual researcher with + more than 5,000 lifetime publications or patents is implausible even for + extreme large-collaboration physics — to drop flagrant collisions outright. +2. An **Isolation Forest** fit in log-space on the remaining rows across the + full numeric feature set (not just publications/patents), to catch subtler + multivariate anomalies — e.g. an internally inconsistent feature combination + that no single-column cutoff would flag. + +## `yearly_counts.py` — per-person, per-year activity from the raw exports + +The raw files in `dimensions_data/` are per-person record lists: each row is one +(record × tracked person) pair, keyed by `author_people`. They cover the +**founder cohort only** — non-founders were extracted live from the Dimensions +API, their per-record data was never saved, and the API key has since expired. + +These exact yearly counts are used two ways: + +1. Exact truncation of founder features at the founding year, replacing the + coarser `*_before_founding` splits. +2. Fitting the empirical career-trajectory curves in `career_curves.py`, which + calibrate the truncation of non-founder lifetime totals at a pseudo-founding + year — validated against the founders' exact counts, where both are known. + +**Grants cap.** The `grants` feature counts grant IDs acknowledged on a person's +publications, so a single consortium paper can contribute 100+ "grants". The +module also emits a capped variant crediting at most `GRANTS_PER_PAPER_CAP` +distinct grant IDs per publication, mirroring the hyperauthorship cap in the +production profiling module. The empirical distribution of grants per linked +paper is p50 = 3, p90 ≈ 6–14 depending on institution, with a consortium tail +reaching 409. The cap sits above ordinary multi-grant papers and below the +consortium artifacts (~100+/paper) that inflated `grants` roughly 100×. + +## `career_curves.py` — index-date truncation of lifetime totals + +The symmetric redesign needs every person's activity counts **as of an index +year** (real founding year for founders, sampled pseudo-founding year for +non-founders). Exact per-year records exist only for founders; non-founders have +lifetime totals plus first/last activity years. + +We therefore estimate, from the founders' raw trajectories, the average +cumulative-share curve + +``` +F(u) = expected fraction of lifetime output accumulated by career fraction u +u = (index_year - first_year) / (last_year + 1 - first_year) +``` + +separately per activity type (pubs / patents / grants) and career-length +stratum, and truncate totals as `total_at_index = total * F(u)`. + +**Critical symmetry rule:** this construction is applied to **both** classes. +Founders' exact counts are used only to (a) fit the curves and (b) quantify the +approximation error against ground truth (`validate_on_founders`, log-space +R² 0.89–0.94). If founders got exact counts while non-founders got smoothed +ones, the residual noise texture alone would separate the classes — the exact +artifact this redesign removes. + +## `symmetric.py` — the landmark design + +Replaces the asymmetric RQ1/RQ2 preprocessing in `data.py`, where founders' +lifetime totals were truncated at their founding year while non-founders kept +full-career totals. That made observation-window length a function of the label: +the classifier's dominant feature (`publications`) partly encoded the truncation +rather than productivity — probability of founding fell monotonically with +output, and the 0.918 → 0.976 ROC-AUC "improvement" of the asymmetric fix was a +class-separability artifact. + +1. **Index year.** Founders get their cleaned founding year; non-founders a + pseudo-founding year sampled from the founders' empirical + career-age-at-founding distribution, matched on career-start cohort + (landmark / matched index-date design, cf. immortal-time bias). +2. **Identical feature construction for both classes**, as deterministic + functions of (lifetime totals, first/last activity years, index year) via + `career_curves.py`. Founders' exact per-year records are used only to fit and + validate those curves — never as a founder-only feature pathway. +3. **Citation features excluded** (h-index, i10, g-index, citation sums/means): + citations cannot be historicized to the index year for either class, and + their full-career values are window-contaminated. +4. **`grants` de-inflated** with the per-paper cap from `yearly_counts.py`, + applied through a ratio curve so both classes go through the same mapping. + +Two further filters, both applied to **both** classes: + +- **Population definition.** The coach-facing tool scores academics, so the + modelled population requires a minimal academic record at the index date + (≥ 4 publications). Without it, a sampling-frame clash dominates the + thin-profile region: founders come from company databases (people with 1–3 + lifetime papers included), non-founders from institutional researcher lists + (thin profiles underrepresented), making "long career + tiny record" read as + 65–72% founder. Those people are out of scope for the product, not evidence. +- **Plausibility filter.** Profiles with a > 60-year publishing span or a + sustained lifetime rate above 25 papers/year are name-collision aggregates + (e.g. an "M Nakamura" spanning 1919–2023 with 28k papers). These concentrate + in the non-founder class — matched by name alone, vs company + name for + founders — so left in they asymmetrically inflate non-founder output. + +## `sequence_data.py` — founder-only sequence dataset + +Task: predict career-relative founding timing from pre-founding activity, using +the `hist_{pub,pat,grant}_FN-1..FN-20` columns (chronological yearly counts in +the 20 years strictly before founding). + +**Non-founders are not included.** Their equivalent columns are computed with +`founded_year` hardcoded to literal year 0 in +`extraction/non_founders_scripts.ipynb` (`generate_history(..., nonstartup=True)` +forces `founded_year = 0`), so they are all-zero placeholders anchored at +1 BCE/1 CE — not real "N years before some reference point" sequences. There is +no valid apples-to-apples non-founder sequence in the extracted data; see +`experiments/run_sequence_reconstruction_spike.py` for an attempt to build one +from the raw per-paper/per-patent data instead. + +**Target:** `founding_age = founded_on (year) - first_publication_year`, i.e. +how many years into their publishing career a founder started their company. +Only well-posed when `founding_age <= WINDOW` (20): the input window is a fixed +20-year lookback, so a longer real pre-founding career would look identical to a +≥ 20-year case regardless of the true value. This is a structural +right-censoring limit of the fixed window, not a modeling failure, so those rows +are excluded from the regression task by default and the excluded count is +always reported. + +## `run_rq1_robustness.py` — `scale_pos_weight` under StratifiedKFold + +StratifiedKFold keeps each fold's class ratio approximately equal to the +full-data ratio, so a single overall `scale_pos_weight` is a good per-fold +approximation for xgboost — which, unlike RF/LightGBM's +`class_weight="balanced"`, needs it set explicitly to correct for the ~37% +founder rate. diff --git a/service/scripts/profiling/founding_potential/environment.yml b/service/scripts/profiling/founding_potential/environment.yml new file mode 100644 index 00000000..77d5c94c --- /dev/null +++ b/service/scripts/profiling/founding_potential/environment.yml @@ -0,0 +1,149 @@ +name: potential +channels: + - conda-forge + - defaults + - https://repo.anaconda.com/pkgs/main + - https://repo.anaconda.com/pkgs/r +dependencies: + - _openmp_mutex=4.5 + - brotli=1.2.0 + - brotli-bin=1.2.0 + - bzip2=1.0.8 + - ca-certificates=2026.7.22 + - cairo=1.18.4 + - contourpy=1.3.3 + - cpython=3.11.15 + - cycler=0.12.1 + - filelock=3.32.2 + - fmt=12.1.0 + - font-ttf-dejavu-sans-mono=2.37 + - font-ttf-inconsolata=3.000 + - font-ttf-source-code-pro=2.038 + - font-ttf-ubuntu=0.83 + - fontconfig=2.18.2 + - fonts-conda-ecosystem=1 + - fonts-conda-forge=1 + - fonttools=4.63.0 + - freetype=2.14.3 + - fribidi=1.0.16 + - fsspec=2026.7.0 + - gmp=6.3.0 + - gmpy2=2.3.0 + - graphite2=1.3.15 + - icu=78.3 + - jinja2=3.1.6 + - joblib=1.5.3 + - kiwisolver=1.5.0 + - lcms2=2.19.1 + - lerc=4.2.0 + - libabseil=20260526.0 + - libblas=3.11.0 + - libbrotlicommon=1.2.0 + - libbrotlidec=1.2.0 + - libbrotlienc=1.2.0 + - libcblas=3.11.0 + - libcxx=22.1.8 + - libdeflate=1.25 + - libexpat=2.8.1 + - libffi=3.5.2 + - libfreetype=2.14.3 + - libfreetype6=2.14.3 + - libgcc=16.1.0 + - libgfortran=16.1.0 + - libgfortran5=16.1.0 + - libglib=2.88.3 + - libharfbuzz=14.3.0 + - libiconv=1.18 + - libintl=0.25.1 + - libjpeg-turbo=3.2.0 + - liblapack=3.11.0 + - liblzma=5.8.3 + - libopenblas=0.3.33 + - libpng=1.6.58 + - libprotobuf=7.35.1 + - libraqm=0.11.0 + - libsqlite=3.53.4 + - libtiff=4.7.2 + - libtorch=2.13.0 + - libuv=1.52.1 + - libwebp-base=1.6.0 + - libxcb=1.17.0 + - libzlib=1.3.2 + - llvm-openmp=22.1.8 + - markupsafe=3.0.3 + - matplotlib=3.11.1 + - matplotlib-base=3.11.1 + - mpc=1.4.0 + - mpfr=4.2.2 + - munkres=1.1.4 + - narwhals=2.24.0 + - ncurses=6.6 + - networkx=3.6.1 + - nomkl=1.0 + - numpy=2.4.6 + - onednn=3.12 + - openjpeg=2.5.4 + - openssl=3.6.3 + - optree=0.19.1 + - packaging=26.2 + - patsy=1.0.2 + - pcre2=10.47 + - pillow=12.3.0 + - pip=26.2 + - pixman=0.46.4 + - pthread-stubs=0.4 + - pybind11=3.0.3 + - pybind11-abi=11 + - pybind11-global=3.0.3 + - pyparsing=3.3.2 + - python=3.11.15 + - python-dateutil=2.9.0.post0 + - python_abi=3.11 + - pytorch=2.13.0 + - qhull=2020.2 + - readline=8.3 + - scikit-learn=1.9.0 + - scipy=1.17.1 + - seaborn=0.13.2 + - seaborn-base=0.13.2 + - setuptools=81.0.0 + - six=1.17.0 + - sleef=3.9.0 + - statsmodels=0.14.6 + - sympy=1.14.0 + - threadpoolctl=3.6.0 + - tk=8.6.13 + - tornado=6.5.7 + - tqdm=4.70.0 + - typing-extensions=4.16.0 + - typing_extensions=4.16.0 + - unicodedata2=17.0.1 + - wheel=0.47.0 + - xorg-libxau=1.0.12 + - xorg-libxdmcp=1.1.5 + - zlib-ng=2.3.3 + - zstd=1.5.7 + - pip: + - autograd==1.9.1 + - autograd-gamma==0.5.0 + - catboost==1.2.10 + - cloudpickle==3.1.2 + - formulaic==1.2.2 + - graphviz==0.21 + - imbalanced-learn==0.14.2 + - interface-meta==2.0.1 + - lifelines==0.30.3 + - lightgbm==4.7.0 + - llvmlite==0.48.0 + - mpmath==1.3.0 + - numba==0.66.0 + - pandas==2.3.3 + - plotly==6.9.0 + - pytz==2026.3.post1 + - shap==0.51.0 + - sklearn-compat==0.1.6 + - slicer==0.0.8 + - tabulate==0.10.0 + - tzdata==2026.3 + - wrapt==2.3.0 + - xgboost==3.2.0 diff --git a/service/scripts/profiling/founding_potential/production/classifier/README.md b/service/scripts/profiling/founding_potential/production/classifier/README.md new file mode 100644 index 00000000..b68630e8 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier/README.md @@ -0,0 +1,255 @@ +# Founder-Potential Classifier — Production Guide + +Predicts whether a researcher will found a company ("founder" vs. "non-founder") +from their **full career profile** (publications, patents, grants, affiliations). +This is the RQ1 model from the research pipeline, re-packaged and validated for +an OpenAlex + patents + grants production data source. + +## 1. Which two models, and why + +Ranked empirically on the actual production feature set (87 columns — see +§3), by PR-AUC on a held-out 20% stratified split (`validated_holdout_metrics.csv`): + +| rank | model | roc_auc | pr_auc | mcc | f1 | notes | +|------|----------------------|---------|--------|-------|-------|-------| +| 1 | **lightgbm** | 0.9764 | 0.9681 | 0.848 | 0.903 | single model, 1.3 MB, fastest | +| 2 | **stacking_ensemble**| 0.9748 | 0.9657 | 0.846 | 0.903 | RF+XGBoost+LightGBM blended by a logistic meta-learner, 29 MB, ~3x slower | +| 3 | xgboost | 0.9728 | 0.9640 | 0.843 | 0.900 | close 3rd, not shipped | +| 4 | catboost | 0.9710 | 0.9616 | 0.834 | 0.894 | not shipped | + +`lightgbm` and `stacking_ensemble` are shipped in `models/`. They are within +noise of each other (Δpr_auc = 0.002); `lightgbm` is recommended as the default +for a production system (simpler, smaller, faster, marginally best), with +`stacking_ensemble` as a fallback/cross-check if you want a second opinion or +slightly better recall (0.905 vs. 0.890). + +## 2. Files + +``` +production/classifier/ + founder_classifier.py <- self-contained wrapper (pandas/numpy/joblib only) + models/ + lightgbm.joblib <- recommended default + stacking_ensemble.joblib <- alternative / second opinion + feature_importance_lightgbm.csv + feature_importance_stacking_ensemble.csv + validated_holdout_metrics.csv <- honest held-out metrics for every candidate model + manifest.json + export_classifier.py <- reproducible export/training script +``` + +Each `.joblib` is a single self-contained bundle: `{model, feature_columns, +numeric_columns, log_columns, research_area_columns, research_area_categories, +label_meaning}`. You only need `founder_classifier.py` + one `.joblib` file to +run predictions — no dependency on the rest of this repository. + +## 3. OpenAlex / production data compatibility + +Your data comes from OpenAlex (publications + author metrics) with patents and +grants matched separately to OpenAlex author IDs. Two adjustments were made +relative to the original research pipeline, **both validated empirically, no +other change to the model was needed**: + +### 3.1 Institution one-hot dropped + +The research dataset one-hot-encodes 8 training institutions. A model trained +that way cannot be meaningfully applied to a 9th, unseen institution (its +one-hot vector would be all zeros — out of distribution). This production +model was trained **without** institution one-hot at all, so it works for any +institution, including yours. Cost: ROC-AUC drops from ~0.976 to ~0.95 in a +leave-one-institution-out test (see `experiments/README.md` §RQ1) — a modest, +worthwhile trade for portability. + +### 3.2 Four Dimensions-specific columns dropped + +| column | what it needs | why it's likely unavailable to you | +|---|---|---| +| `pat_citation_mean`, `pat_citation_sum` | citation counts **to** each patent | requires a patent source that tracks patent-citing-patent counts (e.g. USPTO/PatentsView citation graph); a simple OpenAlex-author-matched patent list usually won't have this | +| `linked_patents_to_publications` | patents that **cite the person's own papers** (non-patent-literature citations) | requires patent-to-paper citation linkage, which most patent sources don't expose | +| `grant_innovation_impact` | count of patents **linked to a specific grant** the person received | requires grant-to-patent linkage, on top of grant-to-person matching | + +These were the exact "things we don't have" flagged as a concern. An ablation +(same data, same models, same split, only these 4 of 87 columns removed) +showed the difference is within noise: + +| feature set | model | roc_auc | pr_auc | mcc | +|---|---|---|---|---| +| full (includes the 4 columns) | lightgbm | 0.9763 | 0.9685 | 0.8483 | +| **without the 4 columns** | lightgbm | 0.9765 | 0.9689 | 0.8514 | +| full (includes the 4 columns) | xgboost | 0.9744 | 0.9666 | 0.8426 | +| **without the 4 columns** | xgboost | 0.9741 | 0.9657 | 0.8437 | + +Performance doesn't degrade (if anything, it's marginally better without +them — consistent with their near-zero permutation importance, see §6). **No +architecture/feature-engineering change was made** beyond simply not including +these 4 columns — per "if the model can function without it, don't adjust the +model," this is confirmed and no further adaptation was necessary. + +### 3.3 Research-area categories + +`publication_research_area`, `patent_research_area`, `grant_research_area` were +trained on the first 2 characters of Dimensions' FOR classification codes +(e.g. `"3202 Clinical Sciences"` → `"32"`). If your OpenAlex pipeline classifies +research area using OpenAlex Topics/Fields/Domains instead, the exact string +values will differ. You have two options: + 1. **Do nothing.** Pass whatever string/code you have; unrecognized values + fall into an all-zero ("unknown") one-hot block for that column, which + tree models handle gracefully — you just lose the (modest, ~1-2% combined + importance, see §6) signal those columns carry. + 2. **Map your OpenAlex field/domain names to the 2-digit codes** this model + was trained on for full signal. The 21 broad codes used are Dimensions + FOR 2-digit divisions (30=Agriculture, 31=Biological Sciences, 32=Biomedical + and Clinical Sciences, 33=Built Environment and Design, 34=Chemical + Sciences, 35=Commerce/Management/Tourism/Services, 36=Creative Arts and + Writing, 37=Earth Sciences, 38=Economics, 39=Education, 40=Engineering, + 41=Environmental Sciences, 42=Health Sciences, 43=History/Heritage/ + Archaeology, 44=Human Society, 46=Information and Computing Sciences, + 47=Language/Communication/Culture, 48=Law and Legal Studies, + 49=Mathematical Sciences, 50=Philosophy and Religious Studies, + 51=Physical Sciences, 52=Psychology). `"n."` = unknown/not classified. + +Institution and research-area handling aside, **h-index and i10-index are +natively provided by OpenAlex** (`summary_stats.h_index` / +`summary_stats.i10_index` on the Author object) — you do not need to compute +them yourself, despite them being "calculable." + +## 4. Input schema + +Pass a plain dict (or list of dicts for batch) with any subset of these keys — +missing numeric keys default to 0, missing categorical keys default to +"unknown". **Fields with no natural zero (the year fields, and any field where +"0" would be misleading) should always be supplied from real data** — see §7 +caveats. + +| field | type | description | source | +|---|---|---|---| +| `h-index` | int | author h-index | OpenAlex `summary_stats.h_index` (native) | +| `i10-index` | int | author i10-index | OpenAlex `summary_stats.i10_index` (native) | +| `publications` | int | total publication count | OpenAlex `works_count`, or count of that author's works | +| `pub_citation_mean` | float | mean citations per publication | mean of `cited_by_count` across the author's works | +| `pub_citation_sum` | float | total citations across publications | OpenAlex Author `cited_by_count` (native), or sum of works' `cited_by_count` | +| `first_publication_year` | int | year of first publication | min `publication_year` across works | +| `last_publication_year` | int | year of most recent publication | max `publication_year` across works | +| `patents` | int | total patent count | your patent-matching pipeline | +| `first_patent_year` | int | year of first patent | your patent-matching pipeline | +| `last_patent_year` | int | year of most recent patent | your patent-matching pipeline | +| `grants` | int | total grants/awards count | your grant-matching pipeline (or OpenAlex `awards` on works) | +| `first_grant_year` | int | year of first grant | your grant-matching pipeline | +| `last_grant_year` | int | year of most recent grant | your grant-matching pipeline | +| `affiliations` | int | count of distinct institutional affiliations | OpenAlex Author `affiliations` (native) | +| `activities_total` | int | publications + patents + grants | computed (sum) | +| `g-index` | int | g-index (largest g s.t. top-g works have ≥ g² combined citations) | computed from per-work `cited_by_count` — see §5 | +| `industry_collab_papers` | int | count of publications co-authored with a company-type institution | OpenAlex works' `authorships.institutions.type == "company"` | +| `grant_research_impact` | int | count of publications linked to a grant the person received | OpenAlex works' `awards` field, or your grant-to-publication matching | +| `publication_research_area` | str | broad research-area code of publications | see §3.3 | +| `patent_research_area` | str | broad research-area code of patents | see §3.3 | +| `grant_research_area` | str | broad research-area code of grants | see §3.3 | + +Do **not** pass `institution` — it is not used by this model (see §3.1). + +### 5. Computing g-index from OpenAlex + +OpenAlex has no native g-index field. Compute it directly from a list of the +person's per-work citation counts (`cited_by_count`), sorted descending: + +```python +def g_index(citation_counts: list[int]) -> int: + counts = sorted(citation_counts, reverse=True) + g = 0 + cumulative = 0 + for i, c in enumerate(counts, start=1): + cumulative += c + if cumulative >= i * i: + g = i + else: + break + return g +``` + +## 6. Output format + +```python +clf.predict_one({...}) +# {'prediction': 1, 'probability_founder': 0.87, 'label': 'founder', 'model': 'lightgbm'} +``` + +- `prediction`: 0 (non-founder) or 1 (founder), thresholded at `probability_founder >= 0.5` +- `probability_founder`: calibrated-ish probability in [0, 1] from `predict_proba` +- `label`: human-readable string version of `prediction` + +`clf.predict([...])` (batch) returns a `pandas.DataFrame` with `prediction` and +`probability_founder` columns, one row per input record, in input order. + +## 7. Usage example + +```python +from founder_classifier import FounderClassifier + +clf = FounderClassifier.load("models/lightgbm.joblib") + +result = clf.predict_one({ + "h-index": 12, "i10-index": 15, "publications": 40, + "pub_citation_mean": 22.5, "pub_citation_sum": 900, + "first_publication_year": 2005, "last_publication_year": 2021, + "patents": 2, "first_patent_year": 2015, "last_patent_year": 2018, + "grants": 3, "first_grant_year": 2010, "last_grant_year": 2019, + "affiliations": 2, "activities_total": 45, "g-index": 10, + "industry_collab_papers": 4, "grant_research_impact": 5, + "publication_research_area": "32", "patent_research_area": "32", + "grant_research_area": "32", +}) +print(result) +# {'prediction': 1, 'probability_founder': 0.957, 'label': 'founder', 'model': 'lightgbm'} +``` + +For a second opinion, load `stacking_ensemble.joblib` the same way and compare. + +## 8. Features that affect the classification most + +Permutation importance (mean drop in PR-AUC when a feature is shuffled) on the +held-out test split, for both shipped models: + +| feature | lightgbm | stacking_ensemble | OpenAlex availability | +|---|---|---|---| +| `publications` | **0.494** (dominant) | **0.323** (dominant) | native | +| `pub_citation_sum` | 0.100 | 0.069 | computed from works | +| `last_patent_year` | 0.089 | 0.081 | your patent pipeline | +| `pub_citation_mean` | 0.058 | 0.042 | computed from works | +| `i10-index` | 0.058 | 0.035 | native | +| `g-index` | 0.039 | 0.035 | computed (§5) | +| `activities_total` | 0.023 | 0.021 | computed | +| `grants` | 0.023 | 0.019 | your grant pipeline | +| `first_publication_year` | 0.016 | 0.015 | native | +| `last_publication_year` | 0.010 | — | native | + +**`publications` alone dwarfs every other feature** — by a wide margin, the +single most important signal is simply how many papers someone has published. +Citation-based signals (`pub_citation_sum`/`mean`, `i10-index`, `g-index`) are +a clear second tier. Patent/grant *counts* matter far less than publication +volume, and the timing feature `last_patent_year` is surprisingly informative +(likely a proxy for "still recently active in applied/patentable work" close +to the founding decision). Research-area and institution-adjacent signals are +minor (each individual one-hot column contributes < 0.5% importance). Full +per-model tables: `feature_importance_lightgbm.csv`, +`feature_importance_stacking_ensemble.csv`. + +## 9. Caveats + +- **This is a full-career-profile model** (RQ1): it answers "does this + person's overall profile look like a founder's?", not "will they found a + company in the next N years?" — for the latter, see the sequence models + (`../sequence/README.md`). +- **Out-of-distribution inputs are not guarded against.** A record with almost + all fields missing/zero is nonsensical (every real researcher has *some* + publications) and can produce an unreliable, overconfident prediction — + this was observed directly (an all-empty dict predicts "founder" at 99.7% + confidence, an artifact of the model extrapolating into a region with no + real training examples, not a meaningful result). Only call this model with + real profile data for someone who has at least some publication history. +- **Retraining on your own labeled data** (once you have enough founder/ + non-founder examples from your own institution) will likely outperform this + model, especially for the research-area categorical signal (§3.3). This + model is a strong starting point / cold-start solution before you have your + own labels. +- Reproduce or retrain via `export_classifier.py` (depends on the full + `experiments/src` research package + `evaluation/datasets_complete`). diff --git a/service/scripts/profiling/founding_potential/production/classifier/export_classifier.py b/service/scripts/profiling/founding_potential/production/classifier/export_classifier.py new file mode 100644 index 00000000..705db7f1 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier/export_classifier.py @@ -0,0 +1,144 @@ +"""Export the two best RQ1 classifiers as standalone production artifacts, +adapted for an OpenAlex + patents + grants data pipeline. + +Two adaptations vs `src/data.py::build_rq1_matrix`: the `institution` one-hot is +dropped (a model trained on 8 one-hots cannot be applied to a 9th, unseen +institution), and four Dimensions-specific columns are dropped as unavailable +when patents are matched to OpenAlex authors. Measured cost of each: README.md +in this directory, "OpenAlex / production data compatibility". + +Run: conda run -n potential python production/classifier/export_classifier.py +(from the experiments/ directory) +""" +import json +import sys +from pathlib import Path + +import joblib +import numpy as np +import pandas as pd +from sklearn.inspection import permutation_importance + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from src import config, data, evaluate, models, splits # noqa: E402 + +OUT_DIR = Path(__file__).resolve().parent +MODELS_DIR = OUT_DIR / "models" +MODELS_DIR.mkdir(exist_ok=True) + +# Columns dropped for OpenAlex/production compatibility -- see module docstring. +UNAVAILABLE_COLUMNS = [ + "pat_citation_mean", + "pat_citation_sum", + "linked_patents_to_publications", + "grant_innovation_impact", +] + +RESEARCH_AREA_COLUMNS = ["publication_research_area", "patent_research_area", "grant_research_area"] + +# The two models to ship, chosen empirically (see rank_production_models below). +SHIP_MODELS = ["lightgbm", "stacking_ensemble"] + + +def build_production_matrix(df): + """Same as data.build_rq1_matrix(include_institution=False) minus the four + OpenAlex/production-unavailable columns.""" + X, y, groups = data.build_rq1_matrix(df, include_institution=False) + X = X.drop(columns=UNAVAILABLE_COLUMNS) + return X, y, groups + + +def rank_and_validate(X, y): + """Fit every candidate on a held-out split so we get honest metrics + a + permutation importance ranking for the *actual shipped* feature set.""" + X_train, X_test, y_train, y_test = splits.stratified_holdout(X, y, test_size=0.2) + spw = (y_train == 0).sum() / (y_train == 1).sum() + candidates = { + **models.advanced_models(scale_pos_weight=spw), + "stacking_ensemble": models.stacking_model(scale_pos_weight=spw), + } + rows, fitted = [], {} + for name, model in candidates.items(): + model, metrics, pred, proba = evaluate.fit_and_evaluate(model, X_train, y_train, X_test, y_test) + rows.append({"model": name, **metrics}) + fitted[name] = model + table = evaluate.results_table(rows, sort_by="pr_auc") + print("Validated performance (held-out 20% split, production feature set):") + print(table[["accuracy", "precision", "recall", "f1", "roc_auc", "pr_auc", "mcc"]]) + table.to_csv(OUT_DIR / "validated_holdout_metrics.csv") + + # Permutation importance for each shipped model on the held-out split. + importances = {} + for name in SHIP_MODELS: + result = permutation_importance( + fitted[name], X_test, y_test, n_repeats=20, random_state=config.RANDOM_STATE, scoring="average_precision" + ) + imp_df = pd.DataFrame( + {"feature": X.columns, "importance_mean": result.importances_mean, "importance_std": result.importances_std} + ).sort_values("importance_mean", ascending=False) + imp_df.to_csv(OUT_DIR / f"feature_importance_{name}.csv", index=False) + importances[name] = imp_df + print(f"\nTop 10 features for {name} (permutation importance, PR-AUC drop):") + print(imp_df.head(10).to_string(index=False)) + return table, importances + + +def fit_final_bundles(X, y): + """Refit each shipped model on ALL available labeled data (standard practice + for a deployed artifact -- validated metrics above already establish that + generalization performance holds up on unseen individuals/institutions).""" + spw = (y == 0).sum() / (y == 1).sum() + candidates = { + **models.advanced_models(scale_pos_weight=spw), + "stacking_ensemble": models.stacking_model(scale_pos_weight=spw), + } + numeric_columns = [c for c in config.RQ1_NUMERIC_COLUMNS if c not in UNAVAILABLE_COLUMNS] + # Persist the *actual* categories seen at training time for each research-area + # column (needed to reindex one-hot columns identically at inference time). + raw_df = data.load_rq1_raw() + broad_categories = { + col: sorted(data._broad_research_area(raw_df[col]).unique().tolist()) for col in RESEARCH_AREA_COLUMNS + } + + for name in SHIP_MODELS: + model = candidates[name] + model.fit(X, y) + bundle = { + "model": model, + "model_name": name, + "feature_columns": X.columns.tolist(), + "numeric_columns": numeric_columns, + "log_columns": [c for c in config.RQ1_LOG_COLUMNS if c not in UNAVAILABLE_COLUMNS], + "research_area_columns": RESEARCH_AREA_COLUMNS, + "research_area_categories": broad_categories, + "label_meaning": {0: "non-founder", 1: "founder"}, + } + out_path = MODELS_DIR / f"{name}.joblib" + joblib.dump(bundle, out_path) + print(f"Saved {out_path} ({out_path.stat().st_size / 1024:.0f} KB)") + + +def main(): + raw_df = data.load_rq1_raw() + X, y, _ = build_production_matrix(raw_df) + print(f"Production feature matrix: {X.shape[0]} rows x {X.shape[1]} columns\n") + + table, importances = rank_and_validate(X, y) + top2 = table.index[:2].tolist() + print(f"\nTop-2 by PR-AUC on production feature set: {top2}") + + fit_final_bundles(X, y) + + manifest = { + "shipped_models": SHIP_MODELS, + "feature_count": X.shape[1], + "unavailable_columns_dropped": UNAVAILABLE_COLUMNS, + "institution_onehot_dropped": True, + } + with open(OUT_DIR / "manifest.json", "w") as f: + json.dump(manifest, f, indent=2) + print("\nDone.") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/founding_potential/production/classifier/feature_importance_lightgbm.csv b/service/scripts/profiling/founding_potential/production/classifier/feature_importance_lightgbm.csv new file mode 100644 index 00000000..9b6cc2df --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier/feature_importance_lightgbm.csv @@ -0,0 +1,88 @@ +feature,importance_mean,importance_std +publications,0.49372270392208406,0.009435105555281502 +pub_citation_sum,0.10041155476971034,0.003075116147541558 +last_patent_year,0.08897556673923894,0.00369039716968687 +pub_citation_mean,0.05843840173995631,0.0035635258840383387 +i10-index,0.058276972447521766,0.0028493921400149316 +g-index,0.03926107174812248,0.002908392365462608 +activities_total,0.02269603064081724,0.0014262023325240447 +grants,0.022629143919601975,0.0018617301145260297 +first_publication_year,0.016383482397344773,0.0014781488366511484 +last_publication_year,0.01044333199563966,0.0012914478475198282 +last_grant_year,0.008814204773467744,0.0006485422255609053 +patents,0.007948968544722036,0.00072369450238458 +publication_research_area_32,0.004622593405503084,0.0005567329882739705 +industry_collab_papers,0.004127688678751134,0.0005178389595278936 +affiliations,0.0038678024032746117,0.0006972880130649415 +first_patent_year,0.003812250467041056,0.000739110083304315 +first_grant_year,0.0030673049491659722,0.0005750427084734693 +h-index,0.0026992385419333962,0.00038040011240434297 +grant_research_area_32,0.0024383846686938824,0.0006597174523401329 +grant_research_impact,0.002092380085101797,0.0009209829823855754 +patent_research_area_46,0.0015450646662926114,0.0003408238801588627 +publication_research_area_46,0.0011186842180353428,0.0003636648316547925 +publication_research_area_31,0.0007689503487253891,0.0003229045550739315 +publication_research_area_35,0.000357006395234688,0.000184261296332344 +patent_research_area_35,0.0003289822271172027,0.0002457177044892662 +grant_research_area_46,0.0003235675420170059,0.00012528589983147148 +patent_research_area_32,0.000284992232621617,9.07382535848989e-05 +publication_research_area_42,0.00017982554980572885,0.00010724763462688804 +publication_research_area_51,0.00015147606865889007,0.00017482583322384033 +publication_research_area_33,0.00014482998247801194,0.00014293663951790765 +publication_research_area_44,0.0001390054811560959,5.095898280286692e-05 +grant_research_area_42,0.00010679798913335037,0.00011517614876712806 +publication_research_area_52,7.58659457399391e-05,8.67872358194002e-05 +publication_research_area_n.,3.733479496259573e-05,8.266304276802761e-05 +publication_research_area_47,3.577968510939944e-05,3.644548262290321e-05 +grant_research_area_33,2.7053741977389746e-05,1.3158619878764252e-05 +publication_research_area_39,2.6107088659182988e-05,5.314752896673858e-05 +patent_research_area_40,2.293468269031207e-05,5.522677589407406e-05 +publication_research_area_30,2.1227363888909333e-05,4.0118754214761545e-05 +grant_research_area_52,1.86106929250307e-05,4.737938770158699e-05 +grant_research_area_31,1.7230231395626296e-05,3.303598252316633e-05 +grant_research_area_36,1.5591805886239208e-05,1.4155029297892755e-05 +grant_research_area_34,1.5538090563826935e-05,6.936899814614872e-05 +grant_research_area_51,1.516446191183185e-05,5.6983277869360076e-05 +publication_research_area_36,1.4576087392986769e-05,2.765828911048998e-05 +patent_research_area_34,1.2943329198150666e-05,3.9589156048043156e-05 +publication_research_area_40,1.0268854792233605e-05,0.00010816661742277235 +patent_research_area_31,7.878647505654702e-06,2.0077897722361337e-05 +grant_research_area_30,2.291815734967173e-06,4.65029322854696e-06 +publication_research_area_38,1.9069228478219014e-06,8.771931389052964e-05 +patent_research_area_41,6.061759097786279e-07,9.166702390722687e-06 +publication_research_area_43,2.6636266048374323e-08,1.1610479193812715e-07 +grant_research_area_37,0.0,0.0 +grant_research_area_49,0.0,0.0 +grant_research_area_50,0.0,0.0 +grant_research_area_43,0.0,0.0 +grant_research_area_44,0.0,0.0 +patent_research_area_52,0.0,0.0 +grant_research_area_47,0.0,0.0 +grant_research_area_48,0.0,0.0 +grant_research_area_38,0.0,0.0 +patent_research_area_47,0.0,0.0 +patent_research_area_39,0.0,0.0 +patent_research_area_38,0.0,0.0 +patent_research_area_50,0.0,0.0 +patent_research_area_49,0.0,0.0 +patent_research_area_48,0.0,0.0 +patent_research_area_33,0.0,0.0 +patent_research_area_44,0.0,0.0 +patent_research_area_43,0.0,0.0 +patent_research_area_42,0.0,0.0 +publication_research_area_50,0.0,0.0 +patent_research_area_36,0.0,0.0 +patent_research_area_37,0.0,0.0 +publication_research_area_48,0.0,0.0 +grant_research_area_35,-1.417609221954219e-07,6.811830057220157e-06 +patent_research_area_30,-2.1125354582318678e-07,5.786182703937211e-06 +publication_research_area_41,-3.4822477430085376e-06,5.216332045233262e-05 +grant_research_area_40,-3.6317530620000316e-06,1.3350040147139044e-05 +publication_research_area_34,-3.646016761565951e-06,7.33822378850038e-05 +grant_research_area_39,-7.1453723731962345e-06,7.890200374144198e-06 +publication_research_area_49,-1.1344775302907229e-05,8.151635605591815e-06 +patent_research_area_51,-1.6526341596556638e-05,1.1059230863873912e-05 +patent_research_area_n.,-2.1720602983060776e-05,7.506139221086442e-05 +publication_research_area_37,-2.9818072529441686e-05,1.7457265886226128e-05 +grant_research_area_n.,-4.7040468339543115e-05,0.00011100424284573038 +grant_research_area_41,-0.0001130957822619516,2.660738658933989e-05 diff --git a/service/scripts/profiling/founding_potential/production/classifier/feature_importance_stacking_ensemble.csv b/service/scripts/profiling/founding_potential/production/classifier/feature_importance_stacking_ensemble.csv new file mode 100644 index 00000000..cbecd799 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier/feature_importance_stacking_ensemble.csv @@ -0,0 +1,88 @@ +feature,importance_mean,importance_std +publications,0.3230278846487044,0.008800711081034392 +last_patent_year,0.08101404353937798,0.003480354323912183 +pub_citation_sum,0.06944573429242025,0.0023742502139718533 +pub_citation_mean,0.04195885153037786,0.002746357604547681 +i10-index,0.03509514754261644,0.002072326739488329 +g-index,0.03475697537302609,0.0027920726906895555 +activities_total,0.020832913783627394,0.0014390050076316802 +grants,0.019315451629353792,0.001705491344778238 +first_publication_year,0.01533644702358411,0.001435861122416683 +patents,0.008735459919303962,0.0008664045277148187 +last_grant_year,0.00852538114821349,0.0008305351559872533 +last_publication_year,0.008331716857098981,0.0011919353376131424 +first_patent_year,0.004574821675796192,0.0008880825668646626 +publication_research_area_32,0.004441482221912802,0.0005572418844014392 +industry_collab_papers,0.003930523472063801,0.0005518946751113055 +affiliations,0.0030599567623114943,0.0010611086743104593 +h-index,0.0022261144135681645,0.0005336009903611933 +first_grant_year,0.001877805851533959,0.0005896264410466552 +grant_research_impact,0.0016329087316583224,0.0008953253954886791 +patent_research_area_46,0.0014940981662886431,0.00037841991074793763 +publication_research_area_46,0.0011952487055542527,0.00034735364248049394 +grant_research_area_32,0.0010669398974483101,0.0005455308275487198 +publication_research_area_31,0.0007084035131517119,0.00039455107739638177 +patent_research_area_32,0.0004949758173996676,0.00013130610768396822 +publication_research_area_35,0.0003405892771618013,0.00018230752010422918 +patent_research_area_35,0.00024248321741005552,0.00020196690479766595 +grant_research_area_46,0.00023508021158918924,9.949654281666699e-05 +patent_research_area_31,0.00018850830793534779,1.8256292436730253e-05 +publication_research_area_42,0.0001534410024302102,0.00011124851671888089 +publication_research_area_51,0.00014695613247396323,0.0001875329044078893 +publication_research_area_33,0.00013417272910902777,0.00013187331917677777 +publication_research_area_44,0.00012981751828511912,5.6292634597364995e-05 +grant_research_area_42,5.536599990074165e-05,9.314538927088949e-05 +publication_research_area_52,4.569653237913584e-05,7.131642881143011e-05 +grant_research_area_31,4.1136563865012964e-05,2.3807980697386147e-05 +patent_research_area_n.,3.185352984812484e-05,0.00011635744728257203 +publication_research_area_39,2.6622233316087042e-05,5.5811212973079166e-05 +grant_research_area_51,2.4725683306386914e-05,6.600893864529117e-05 +publication_research_area_47,2.433370482673447e-05,3.423391460291853e-05 +patent_research_area_40,1.8682066021558085e-05,8.373831667931168e-05 +grant_research_area_52,1.736850855706962e-05,4.3586661490832724e-05 +grant_research_area_33,1.5434425911642348e-05,7.2096436009871756e-06 +publication_research_area_36,1.4747622070127031e-05,2.0277087228790355e-05 +grant_research_area_36,1.142451025916702e-05,6.434576027802877e-06 +patent_research_area_34,8.701666157134858e-06,5.019098976931235e-05 +grant_research_area_44,4.732059862427862e-06,7.2140691084721474e-06 +grant_research_area_37,4.64755563436281e-06,5.030937947155093e-07 +patent_research_area_41,2.4010968401655396e-06,5.567934448611626e-06 +patent_research_area_30,1.6321848824496498e-06,5.780242227170541e-06 +publication_research_area_38,9.905339116711431e-07,8.061592993393422e-05 +grant_research_area_30,9.659275313156358e-07,2.7523076304409766e-06 +publication_research_area_43,5.303685287838533e-07,1.367136262691942e-07 +patent_research_area_49,4.579606428523064e-07,0.0 +patent_research_area_37,3.063681887460756e-07,1.7298092956127215e-06 +grant_research_area_43,2.3512457243968222e-07,8.230462484551701e-07 +grant_research_area_38,2.3508913500336347e-07,8.200887763327234e-07 +grant_research_area_48,5.8234010574809145e-08,9.530097523591368e-07 +patent_research_area_33,3.072036073303863e-08,2.2691555351810873e-07 +publication_research_area_48,1.7983012212674508e-08,2.2325824775832636e-07 +patent_research_area_36,1.7241796396172405e-08,7.515524809601928e-08 +publication_research_area_50,6.931049512104437e-10,3.8784698331014374e-07 +grant_research_area_47,0.0,0.0 +patent_research_area_44,0.0,0.0 +patent_research_area_52,0.0,0.0 +patent_research_area_50,0.0,0.0 +patent_research_area_38,0.0,0.0 +patent_research_area_39,0.0,0.0 +patent_research_area_43,0.0,0.0 +patent_research_area_47,-1.1949865169613717e-08,3.48654680192657e-07 +grant_research_area_50,-2.1918295900480445e-08,3.3714424966572567e-07 +grant_research_area_49,-8.055305700249704e-08,1.891835873709255e-07 +patent_research_area_48,-4.387378193082547e-07,1.0065335879337318e-07 +grant_research_area_35,-1.4239535029381135e-06,8.577025403596155e-06 +grant_research_area_40,-2.8211226388352716e-06,5.5951614108796825e-06 +patent_research_area_42,-3.3309781069246203e-06,1.8056260442298824e-06 +patent_research_area_51,-6.034520616637895e-06,9.657390477461269e-06 +grant_research_area_34,-6.555808500358085e-06,5.834666117024457e-05 +publication_research_area_30,-6.9231426525317994e-06,2.3604223992407287e-05 +grant_research_area_39,-7.033697191549671e-06,4.692880133162641e-06 +publication_research_area_41,-1.6315314521198056e-05,3.6394138064735864e-05 +publication_research_area_49,-2.0970323580088435e-05,1.491599600665608e-05 +publication_research_area_37,-2.4155344697468494e-05,1.268437871622249e-05 +publication_research_area_40,-2.4661278046128608e-05,9.362093188879351e-05 +publication_research_area_34,-4.671501475140283e-05,6.79190773369875e-05 +grant_research_area_n.,-6.528496794626637e-05,0.00033896991853285866 +grant_research_area_41,-8.826418872341368e-05,2.1901303480798616e-05 +publication_research_area_n.,-8.850450506823205e-05,0.00012674501058303883 diff --git a/service/scripts/profiling/founding_potential/production/classifier/founder_classifier.py b/service/scripts/profiling/founding_potential/production/classifier/founder_classifier.py new file mode 100644 index 00000000..ef8b787d --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier/founder_classifier.py @@ -0,0 +1,109 @@ +"""Self-contained inference wrapper for the founder-potential classifier. + +Depends only on pandas, numpy and joblib -- no dependency on the `experiments/src` +research package, so this file + a `models/*.joblib` bundle can be copied into any +other codebase. + +Usage: + from founder_classifier import FounderClassifier + + clf = FounderClassifier.load("models/lightgbm.joblib") + result = clf.predict_one({ + "h-index": 12, "i10-index": 15, "publications": 40, + "pub_citation_mean": 22.5, "pub_citation_sum": 900, + "first_publication_year": 2005, "last_publication_year": 2021, + "patents": 2, "first_patent_year": 2015, "last_patent_year": 2018, + "grants": 3, "first_grant_year": 2010, "last_grant_year": 2019, + "affiliations": 2, "activities_total": 45, "g-index": 10, + "industry_collab_papers": 4, "grant_research_impact": 5, + "publication_research_area": "32", "patent_research_area": "32", + "grant_research_area": "32", + }) + print(result) # {'prediction': 1, 'probability_founder': 0.87, ...} + +See README.md in this directory for the full input schema and output format. +""" +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import joblib +import numpy as np +import pandas as pd + + +class FounderClassifier: + """Wraps a fitted sklearn/LightGBM classifier bundle produced by + `export_classifier.py`, handling feature preprocessing (log1p transforms + + research-area one-hot encoding) so callers can pass plain feature dicts.""" + + def __init__(self, bundle: dict[str, Any]): + self._model = bundle["model"] + self.model_name: str = bundle["model_name"] + self.feature_columns: list[str] = bundle["feature_columns"] + self.numeric_columns: list[str] = bundle["numeric_columns"] + self.log_columns: list[str] = bundle["log_columns"] + self.research_area_columns: list[str] = bundle["research_area_columns"] + self.research_area_categories: dict[str, list[str]] = bundle["research_area_categories"] + + @classmethod + def load(cls, path: str | Path) -> "FounderClassifier": + return cls(joblib.load(path)) + + # -- preprocessing ----------------------------------------------------- + @staticmethod + def _broad_research_area(value: Any) -> str: + """Collapse a research-area code to its 2-character broad category, + matching the training-time `data._broad_research_area` transform.""" + if value is None or (isinstance(value, float) and np.isnan(value)): + return "n." + return str(value).strip()[:2] + + def _to_frame(self, records: list[dict[str, Any]]) -> pd.DataFrame: + df = pd.DataFrame.from_records(records, index=range(len(records))) + + # Missing numeric/categorical columns default to 0 / "n." (matches + # training-time fillna(0) for any column that couldn't be parsed as + # numeric, and the "n.a." fallback in data._broad_research_area). + for col in self.numeric_columns: + if col not in df.columns: + df[col] = 0 + numeric = df[self.numeric_columns].apply(pd.to_numeric, errors="coerce").fillna(0) + for col in self.log_columns: + numeric[col] = np.log1p(numeric[col].clip(lower=0)) + + for col in self.research_area_columns: + if col not in df.columns: + df[col] = None + cat_df = pd.DataFrame( + {col: df[col].apply(self._broad_research_area) for col in self.research_area_columns} + ) + categorical = pd.get_dummies(cat_df, prefix=cat_df.columns.tolist()) + + X = pd.concat([numeric, categorical], axis=1) + # Reindex to the exact training-time column order; any research-area + # category not seen during training (or missing here) becomes all-zero + # for that one-hot block, which tree models handle gracefully. + X = X.reindex(columns=self.feature_columns, fill_value=0) + return X + + # -- public API ---------------------------------------------------------- + def predict(self, records: list[dict[str, Any]]) -> pd.DataFrame: + """Batch prediction. `records` is a list of raw feature dicts (see + README for the input schema). Returns a DataFrame with one row per + input record: `prediction` (0/1) and `probability_founder` (0-1).""" + X = self._to_frame(records) + proba = self._model.predict_proba(X)[:, 1] + pred = (proba >= 0.5).astype(int) + return pd.DataFrame({"prediction": pred, "probability_founder": proba}) + + def predict_one(self, record: dict[str, Any]) -> dict[str, Any]: + """Single-record convenience wrapper around `predict`.""" + row = self.predict([record]).iloc[0] + return { + "prediction": int(row["prediction"]), + "probability_founder": float(row["probability_founder"]), + "label": "founder" if row["prediction"] == 1 else "non-founder", + "model": self.model_name, + } diff --git a/service/scripts/profiling/founding_potential/production/classifier/manifest.json b/service/scripts/profiling/founding_potential/production/classifier/manifest.json new file mode 100644 index 00000000..ea168b87 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier/manifest.json @@ -0,0 +1,14 @@ +{ + "shipped_models": [ + "lightgbm", + "stacking_ensemble" + ], + "feature_count": 87, + "unavailable_columns_dropped": [ + "pat_citation_mean", + "pat_citation_sum", + "linked_patents_to_publications", + "grant_innovation_impact" + ], + "institution_onehot_dropped": true +} \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/production/classifier/models/lightgbm.joblib b/service/scripts/profiling/founding_potential/production/classifier/models/lightgbm.joblib new file mode 100644 index 00000000..be7dd286 Binary files /dev/null and b/service/scripts/profiling/founding_potential/production/classifier/models/lightgbm.joblib differ diff --git a/service/scripts/profiling/founding_potential/production/classifier/models/stacking_ensemble.joblib b/service/scripts/profiling/founding_potential/production/classifier/models/stacking_ensemble.joblib new file mode 100644 index 00000000..e8fe0bda Binary files /dev/null and b/service/scripts/profiling/founding_potential/production/classifier/models/stacking_ensemble.joblib differ diff --git a/service/scripts/profiling/founding_potential/production/classifier/validated_holdout_metrics.csv b/service/scripts/profiling/founding_potential/production/classifier/validated_holdout_metrics.csv new file mode 100644 index 00000000..5140e54e --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier/validated_holdout_metrics.csv @@ -0,0 +1,7 @@ +model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +lightgbm,0.9293725371324644,0.9161016949152543,0.8897119341563786,0.902713987473904,0.9763933319115661,0.9680867355662728,0.8475189762274824,0.05343925129722402 +stacking_ensemble,0.9284631706577751,0.9009009009009009,0.9053497942386831,0.90311986863711,0.9748029272608074,0.9657412183896399,0.8464233584967953,0.05796028500367217 +xgboost,0.927250682024856,0.9079497907949791,0.8930041152263375,0.9004149377593361,0.9728476023474957,0.9640546196916957,0.8431866284933476,0.05821008235216141 +catboost,0.9227038496514095,0.8993344425956739,0.8897119341563786,0.8944973107157633,0.9709767935988879,0.9616152397971783,0.833539926599779,0.061886894004821225 +random_forest,0.8911791451955138,0.8639455782312925,0.8362139917695474,0.849853617733166,0.9489078062921099,0.9295025250699936,0.764805465144283,0.09198073526810191 +svm_rbf,0.8742043043346469,0.8424657534246576,0.8098765432098766,0.8258497691984893,0.9312032495280522,0.8989506133295394,0.7277986141772655,0.09551038087976692 diff --git a/service/scripts/profiling/founding_potential/production/classifier_symmetric/README.md b/service/scripts/profiling/founding_potential/production/classifier_symmetric/README.md new file mode 100644 index 00000000..627d341a --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier_symmetric/README.md @@ -0,0 +1,97 @@ +# Founder classifier v2 (symmetric landmark design) + +Replaces `../classifier` (v1). **v1 must not be used for ranking or coaching:** +it was trained with asymmetric observation windows (founders truncated at +founding, non-founders full-career) and behaves as an inverse-productivity +score in production — 1 publication → P(founder)=0.996, 800 → 0.0002. Its +0.976 ROC-AUC was inflated by window-length leakage, and the companion +`p_within_3y`/`p_within_5y` outputs were degenerate (exactly 1.0 for every +author). + +## What changed + +| | v1 (asymmetric) | v2 (symmetric) | +|---|---|---| +| Observation window | founders truncated at founding; non-founders full career | every person truncated at an index year (real founding / cohort-matched pseudo-founding), identical construction for both classes | +| Citation features (h-index, i10, g-index, citation sums) | included, window-contaminated | excluded — not historicizable to an index date | +| `grants` | raw (consortium lists inflate ~100×, up to 409 grants/paper) | de-inflated via per-paper cap mapping (cap 10), applied inside the wrapper | +| Institution one-hots | included | excluded — production scores people from arbitrary institutions | +| Population | anyone matched | academics only: ≥4 publications at index (both classes), plausibility-filtered (see below) | +| Headline holdout | ROC-AUC 0.976 / PR-AUC 0.969 (artifact) | ROC-AUC 0.874 / PR-AUC 0.726 (honest); temporal-split PR-AUC ≈0.73; 5-fold OOF 0.866/0.726 | +| P(founder) vs output | strictly decreasing, incl. absurd tail (1 pub → 0.996) | plateau ~0.39–0.42 for 5–17 pubs at index, ~0.10–0.18 for 100+ (matches empirical label rates) | +| p_within_{1,3,5}y | 3y/5y ≡ 1.0 for everyone | all horizons discriminate (ROC-AUC 0.86–0.89; ≤0.1% of scores above 0.99) | +| Coach-facing number | raw probability | **percentile** vs the ~9k-academic reference cohort, with an out-of-population guard | + +Two dataset artifacts beyond the window asymmetry were found and filtered +during the rebuild, both class-asymmetric (rules applied to BOTH classes): + +- **Sampling-frame clash on thin profiles.** Founders come from company + databases (people with 1–3 lifetime papers included); non-founders from + institutional researcher lists (thin profiles underrepresented). Left in, + "long career + tiny record" reads as 65–72% founder. Hence the ≥4 + publications population rule, enforced at inference by `in_population`. +- **Name-collision aggregates.** Non-founders matched by name alone merge + multiple researchers (e.g. an "M Nakamura" spanning 1919–2023 with 28,050 + papers); 4.2% of non-founders vs 2.2% of founders had physically impossible + profiles (>60-year span or >25 papers/year sustained). These rows are + dropped. + +Training details: `experiments/docs/DESIGN_NOTES.md` (design rationale), `experiments/src/symmetric.py`, +`experiments/run_rq1_symmetric.py`, `experiments/run_rq2_symmetric.py`; +results in `experiments/results/rq1_symmetric` and `rq2_symmetric`. + +## Interpreting the outputs + +- `percentile` (0–100): rank of the person's score against out-of-fold scores + of the reference cohort (founders + non-founders from the 8 training + institutions). This is the number to surface to coaches ("higher founding + propensity than X% of comparable academics"). +- `probability_founder` (0–1): raw case-control model output. The training + cohort is ~26% founders — far above any real-world base rate — so this is + NOT a population founding probability. Do not display it as one. +- `p_within_{k}y` bundles: same construction at index−k; conditional-timing + evidence, same percentile caveat. + +## Input contract (per record) + +Lifetime totals **as of `scoring_year`** (for live profiles: the current year): +`publications`, `patents`, `grants` (raw — the wrapper de-inflates), +`first_publication_year`, `first_patent_year`, `first_grant_year`, +`industry_collab_papers`, `linked_patents_to_publications`, +`publication_research_area`, `patent_research_area`, `grant_research_area`. +Missing fields default to 0 / "n.a.". Citation fields are accepted but ignored. + +```python +from founder_classifier_v2 import FounderClassifierV2 +clf = FounderClassifierV2.load("models/founder_classifier_v2.joblib") +clf.predict_one({...}, scoring_year=2026) +``` + +## Migrating smart-guide `profiling/multipliers/founding.py` + +1. Copy this directory (wrapper + `models/*.joblib`) next to the v1 classifier. +2. Point the classifier loader at `founder_classifier_v2.joblib` and pass + `scoring_year` (extraction snapshot year). +3. Surface `percentile` as `founding.percentile`; keep `probability_founder` + internal. Replace the degenerate `p_within_3y/5y` fields with the v2 + bundles' outputs. +4. Remove the README stop-block once v1 is no longer referenced. + +## Known limitations (documented, not hidden) + +- Non-founder historical snapshots are curve-estimates (empirical career + curves fitted on founders' raw per-year records; log-space R² 0.89–0.94 vs + ground truth), because non-founders' per-record data was never saved and the + Dimensions API key is dead. Founders' snapshots use the same construction so + fidelity is class-symmetric. +- Pseudo-founding years for non-founders are sampled (seeded) from the + founders' career-age-at-founding distribution, cohort-matched by decade of + first publication. +- Reference cohort is 8 research universities, index years ≈1950–2023; scoring + profiles far outside that population extrapolates. +- Conditional on career age, the score declines with publication volume beyond + ~20–40 papers at index (hyper-prolific researchers found less in this + cohort). The empirical label rates support it after cleaning, but residual + moderate name-collisions in the non-founder class could still contribute. + Communicate to coaches as "the model favours focused mid-volume researchers", + and treat very-high-output percentiles as conservative. diff --git a/service/scripts/profiling/founding_potential/production/classifier_symmetric/export_classifier_v2.py b/service/scripts/profiling/founding_potential/production/classifier_symmetric/export_classifier_v2.py new file mode 100644 index 00000000..926ab370 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier_symmetric/export_classifier_v2.py @@ -0,0 +1,99 @@ +"""Export the symmetric founder classifier as a self-contained v2 bundle. + +Produces models/founder_classifier_v2.joblib (and p_within_{k}y bundles) with: +- the final model refit on the full symmetric dataset; +- preprocessing metadata (feature order, log columns, research-area columns); +- the grants de-inflation mapping fitted on raw founder records; +- reference score quantiles for percentile ranking, computed from 5-fold + OUT-OF-FOLD predictions (in-sample scores would shift live percentiles). + +Run with: conda run -n potential python experiments/production/classifier_symmetric/export_classifier_v2.py +""" +import json +import sys +from pathlib import Path + +import joblib +import numpy as np +import pandas as pd +from sklearn.model_selection import StratifiedKFold, cross_val_predict + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1])) + +from src import career_curves as cc +from src import config, models, symmetric + +MODELS_DIR = HERE / "models" +PRIMARY = "lightgbm" + + +def _grants_cap_table(): + """The binned r -> capped_share mapping as plain arrays for the bundle.""" + yearly = cc.load_yearly() + per_person = yearly.groupby("author_people").agg( + pubs=("pubs", "sum"), grants=("grants", "sum"), capped=("grants_capped", "sum") + ) + per_person = per_person[per_person["grants"] > 0] + r = per_person["grants"] / per_person["pubs"].clip(lower=1) + share = per_person["capped"] / per_person["grants"] + bins = np.unique(np.quantile(r, np.linspace(0, 1, 21))) + idx = np.clip(np.digitize(r, bins) - 1, 0, len(bins) - 2) + binned = pd.DataFrame({"bin": idx, "share": share}).groupby("bin")["share"].median() + centers = (bins[:-1] + bins[1:]) / 2 + return centers[binned.index.to_numpy()], binned.to_numpy() + + +def _export(feats, X, y, label, model_name): + spw = (y == 0).sum() / (y == 1).sum() + model = models.advanced_models(scale_pos_weight=spw)[model_name] + cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=config.RANDOM_STATE) + oof = cross_val_predict(model, X, y, cv=cv, method="predict_proba", n_jobs=-1)[:, 1] + model.fit(X, y) + + cap_r, cap_share = _grants_cap_table() + bundle = { + "model": model, + "model_name": f"{model_name}_symmetric_{label}", + "feature_columns": X.columns.tolist(), + "numeric_columns": symmetric.SYMMETRIC_NUMERIC_COLUMNS, + "log_columns": symmetric.SYMMETRIC_LOG_COLUMNS, + "research_area_columns": [ + "publication_research_area", "patent_research_area", "grant_research_area"], + "grants_cap_r": cap_r, + "grants_cap_share": cap_share, + "reference_score_quantiles": np.quantile(oof, np.linspace(0, 1, 1001)), + } + out = MODELS_DIR / f"{label}.joblib" + joblib.dump(bundle, out) + from sklearn.metrics import average_precision_score, roc_auc_score + stats = { + "rows": int(len(X)), "founders": int(y.sum()), + "oof_roc_auc": round(float(roc_auc_score(y, oof)), 4), + "oof_pr_auc": round(float(average_precision_score(y, oof)), 4), + } + print(f"{label}: {stats}") + return {"file": out.name, "model": bundle["model_name"], **stats} + + +def main(): + MODELS_DIR.mkdir(exist_ok=True) + manifest = {"design": "symmetric landmark (see experiments/src/symmetric.py)", "bundles": []} + + feats, attrition = symmetric.build_symmetric_dataset() + X, y, _ = symmetric.build_matrix(feats, include_institution=False) + manifest["attrition"] = {k: int(v) for k, v in attrition.items()} + manifest["bundles"].append(_export(feats, X, y, "founder_classifier_v2", PRIMARY)) + + for k in [1, 3, 5]: + feats_k, _ = symmetric.build_symmetric_dataset(offset=k) + feats_k = feats_k[feats_k["pubs_at_index"] > 0].reset_index(drop=True) + Xk, yk, _ = symmetric.build_matrix(feats_k, include_institution=False) + manifest["bundles"].append(_export(feats_k, Xk, yk, f"p_within_{k}y_v2", PRIMARY)) + + (HERE / "manifest.json").write_text(json.dumps(manifest, indent=2)) + print(f"Manifest written to {HERE / 'manifest.json'}") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/founding_potential/production/classifier_symmetric/founder_classifier_v2.py b/service/scripts/profiling/founding_potential/production/classifier_symmetric/founder_classifier_v2.py new file mode 100644 index 00000000..36d73429 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier_symmetric/founder_classifier_v2.py @@ -0,0 +1,150 @@ +"""Self-contained inference wrapper for the SYMMETRIC founder-potential classifier. + +Depends only on pandas, numpy and joblib. Replaces v1 (../classifier), which +must not be used for ranking — see README.md in this directory for what changed, +the input contract and how to read the outputs. + +Three contract points the caller must get right: + - `predict` requires `scoring_year`, the year the profile snapshot was taken. + - `percentile` is the coach-facing output; `probability_founder` is a raw + case-control score (~26% training base rate) and is NOT a population + founding probability. + - Pass `grants` RAW — the wrapper applies the training per-paper cap itself. + +Usage: + from founder_classifier_v2 import FounderClassifierV2 + + clf = FounderClassifierV2.load("models/founder_classifier_v2.joblib") + result = clf.predict_one({ + "publications": 40, "patents": 2, "grants": 3, + "first_publication_year": 2005, + "first_patent_year": 2015, "first_grant_year": 2010, + "industry_collab_papers": 4, "linked_patents_to_publications": 1, + "publication_research_area": "32 Biomedical and Clinical Sciences", + "patent_research_area": "32", "grant_research_area": "32", + }, scoring_year=2026) + # {'percentile': 71.4, 'probability_founder': 0.38, ...} +""" +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import joblib +import numpy as np +import pandas as pd + + +class FounderClassifierV2: + def __init__(self, bundle: dict[str, Any]): + self._model = bundle["model"] + self.model_name: str = bundle["model_name"] + self.feature_columns: list[str] = bundle["feature_columns"] + self.numeric_columns: list[str] = bundle["numeric_columns"] + self.log_columns: list[str] = bundle["log_columns"] + self.research_area_columns: list[str] = bundle["research_area_columns"] + # Grants de-inflation: interpolation table r -> capped_share, r = grants/pubs. + self.grants_cap_r: np.ndarray = np.asarray(bundle["grants_cap_r"]) + self.grants_cap_share: np.ndarray = np.asarray(bundle["grants_cap_share"]) + # Reference score quantiles for percentile ranking (1001 points on [0,1]). + self.reference_scores: np.ndarray = np.asarray(bundle["reference_score_quantiles"]) + + @classmethod + def load(cls, path: str | Path) -> "FounderClassifierV2": + return cls(joblib.load(path)) + + # -- preprocessing ------------------------------------------------------- + @staticmethod + def _broad_research_area(value: Any) -> str: + if value is None or (isinstance(value, float) and np.isnan(value)): + return "n." + return str(value).strip()[:2] + + def _capped_grants(self, grants: np.ndarray, pubs: np.ndarray) -> np.ndarray: + r = grants / np.clip(pubs, 1, None) + share = np.interp(r, self.grants_cap_r, self.grants_cap_share) + return grants * np.clip(share, 0.0, 1.0) + + def _to_frame(self, records: list[dict[str, Any]], scoring_year: int) -> pd.DataFrame: + df = pd.DataFrame.from_records(records, index=range(len(records))) + for col in ["publications", "patents", "grants", "first_publication_year", + "first_patent_year", "first_grant_year", + "industry_collab_papers", "linked_patents_to_publications"]: + if col not in df.columns: + df[col] = np.nan + df[col] = pd.to_numeric(df[col], errors="coerce") + + pubs = df["publications"].fillna(0).to_numpy(dtype=float) + pats = df["patents"].fillna(0).to_numpy(dtype=float) + grants = self._capped_grants(df["grants"].fillna(0).to_numpy(dtype=float), pubs) + first_pub = df["first_publication_year"].to_numpy(dtype=float) + career_age = np.clip(scoring_year - first_pub, 1, None) + has_pat = (df["first_patent_year"].notna() & (df["first_patent_year"] <= scoring_year) + & (pats > 0)).to_numpy() + has_grant = (df["first_grant_year"].notna() & (df["first_grant_year"] <= scoring_year) + & (grants > 0)).to_numpy() + + numeric = pd.DataFrame({ + "pubs_at_index": pubs, + "patents_at_index": pats, + "grants_at_index": grants, + "activities_at_index": pubs + pats + grants, + "industry_collab_at_index": df["industry_collab_papers"].fillna(0), + "linked_pat_pub_at_index": df["linked_patents_to_publications"].fillna(0), + "career_age_at_index": career_age, + "first_publication_year": first_pub, + "pub_rate": pubs / career_age, + "patent_rate": pats / career_age, + "grant_rate": grants / career_age, + "has_patents_at_index": has_pat.astype(int), + "has_grants_at_index": has_grant.astype(int), + "years_since_first_patent": np.where( + has_pat, np.clip(scoring_year - df["first_patent_year"].fillna(scoring_year), 0, None), 0), + "years_since_first_grant": np.where( + has_grant, np.clip(scoring_year - df["first_grant_year"].fillna(scoring_year), 0, None), 0), + }) + numeric = numeric[self.numeric_columns].fillna(0) + for col in self.log_columns: + numeric[col] = np.log1p(numeric[col].clip(lower=0)) + + cat_df = pd.DataFrame({ + col: df.get(col, pd.Series([None] * len(df))).apply(self._broad_research_area) + for col in self.research_area_columns + }) + categorical = pd.get_dummies(cat_df, prefix=cat_df.columns.tolist()) + X = pd.concat([numeric, categorical], axis=1) + return X.reindex(columns=self.feature_columns, fill_value=0) + + # -- public API ---------------------------------------------------------- + # The model's population is academics with a minimal record (see + # experiments/src/symmetric.py::MIN_PUBS_AT_INDEX): below this, the training + # classes come from clashing sampling frames (company databases vs + # institutional researcher lists) and scores are not evidence. + MIN_PUBLICATIONS = 4 + + def predict(self, records: list[dict[str, Any]], scoring_year: int) -> pd.DataFrame: + """`records`: raw profile dicts (lifetime totals as of `scoring_year`). + Returns probability_founder (raw case-control score), percentile (rank + vs the reference cohort, 0-100; the coach-facing number), and + in_population. When in_population is False (fewer than + MIN_PUBLICATIONS publications) percentile is NaN: the person is outside + the modelled population and must not be ranked.""" + X = self._to_frame(records, scoring_year) + proba = self._model.predict_proba(X)[:, 1] + pct = np.interp(proba, self.reference_scores, np.linspace(0, 100, len(self.reference_scores))) + pubs = pd.DataFrame.from_records(records).get("publications", pd.Series([0] * len(records))) + in_pop = pd.to_numeric(pubs, errors="coerce").fillna(0).to_numpy() >= self.MIN_PUBLICATIONS + return pd.DataFrame({ + "probability_founder": proba, + "percentile": np.where(in_pop, np.round(pct, 1), np.nan), + "in_population": in_pop, + }) + + def predict_one(self, record: dict[str, Any], scoring_year: int) -> dict[str, Any]: + row = self.predict([record], scoring_year).iloc[0] + return { + "percentile": None if not row["in_population"] else float(row["percentile"]), + "probability_founder": float(row["probability_founder"]), + "in_population": bool(row["in_population"]), + "model": self.model_name, + } diff --git a/service/scripts/profiling/founding_potential/production/classifier_symmetric/manifest.json b/service/scripts/profiling/founding_potential/production/classifier_symmetric/manifest.json new file mode 100644 index 00000000..74e95179 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/classifier_symmetric/manifest.json @@ -0,0 +1,48 @@ +{ + "design": "symmetric landmark (see experiments/src/symmetric.py)", + "bundles": [ + { + "file": "founder_classifier_v2.joblib", + "model": "lightgbm_symmetric_founder_classifier_v2", + "rows": 9017, + "founders": 2349, + "oof_roc_auc": 0.8659, + "oof_pr_auc": 0.7257 + }, + { + "file": "p_within_1y_v2.joblib", + "model": "lightgbm_symmetric_p_within_1y_v2", + "rows": 8515, + "founders": 2238, + "oof_roc_auc": 0.8614, + "oof_pr_auc": 0.7154 + }, + { + "file": "p_within_3y_v2.joblib", + "model": "lightgbm_symmetric_p_within_3y_v2", + "rows": 7706, + "founders": 2010, + "oof_roc_auc": 0.861, + "oof_pr_auc": 0.7176 + }, + { + "file": "p_within_5y_v2.joblib", + "model": "lightgbm_symmetric_p_within_5y_v2", + "rows": 6995, + "founders": 1833, + "oof_roc_auc": 0.8535, + "oof_pr_auc": 0.7038 + } + ], + "attrition": { + "initial": 16822, + "no_publication_anchor": 1430, + "implausible_profile_founders": 425, + "implausible_profile_nonfounders": 770, + "founder_bad_founding_year": 340, + "founder_bad_career_age": 723, + "duplicates": 0, + "below_min_pubs_at_index_founders": 1112, + "below_min_pubs_at_index_nonfounders": 3005 + } +} \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/founder_classifier_v2.joblib b/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/founder_classifier_v2.joblib new file mode 100644 index 00000000..f616024c Binary files /dev/null and b/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/founder_classifier_v2.joblib differ diff --git a/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/p_within_1y_v2.joblib b/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/p_within_1y_v2.joblib new file mode 100644 index 00000000..170f8586 Binary files /dev/null and b/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/p_within_1y_v2.joblib differ diff --git a/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/p_within_3y_v2.joblib b/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/p_within_3y_v2.joblib new file mode 100644 index 00000000..83d9ac51 Binary files /dev/null and b/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/p_within_3y_v2.joblib differ diff --git a/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/p_within_5y_v2.joblib b/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/p_within_5y_v2.joblib new file mode 100644 index 00000000..142db324 Binary files /dev/null and b/service/scripts/profiling/founding_potential/production/classifier_symmetric/models/p_within_5y_v2.joblib differ diff --git a/service/scripts/profiling/founding_potential/production/sequence/README.md b/service/scripts/profiling/founding_potential/production/sequence/README.md new file mode 100644 index 00000000..77d81c83 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/sequence/README.md @@ -0,0 +1,188 @@ +# Founder-Timing Sequence Model — Production Guide + +Given a researcher's **year-by-year publication/patent/grant activity**, +predicts how many years into their career a "founding-like" moment falls, and +derives a probability of founding within the next 1/2/3/5 years. This is the +RQ-sequence model from the research pipeline (LSTM + Transformer), re-packaged +for a production app. + +## 1. Which two models, and why + +The two model architectures evaluated (`experiments/results/sequence_founders/sequence_founders_comparison.csv`), +ranked by held-out MAE, both far ahead of the naive heuristic (MAE=0.554) and +an aggregate-feature Random Forest (MAE=2.571) baseline: + +| rank | model | MAE | RMSE | R2 | +|---|---|---|---|---| +| 1 | **transformer** | 0.180 | 0.269 | 0.998 | +| 2 | **lstm** | 0.208 | 0.258 | 0.998 | + +Both are shipped (`models/transformer.pt`, `models/lstm.pt`) — they are close +enough (Δmae=0.028 years, i.e. ~10 days) that using both as a cross-check is +worthwhile. `transformer` is marginally better on MAE, `lstm` marginally better +on RMSE (fewer large errors); either is a reasonable default. + +**Important scope note:** these predict `founding_age` only for the regime the +models were trained and validated on: founders whose company started **within +20 years of their first publication**. Founders/candidates outside that range +were excluded from training (see `experiments/README.md` "Sequence modeling" +section) — treat predictions for very long, established careers (> 20 years +of activity with no founding yet) with more caution; the model has not seen +that regime. + +## 2. Files + +``` +production/sequence/ + founder_timing_model.py <- self-contained wrapper (torch/numpy only) + models/ + transformer.pt <- recommended default + lstm.pt <- alternative / second opinion + export_sequence_models.py <- reproducible export/training script +``` + +Each `.pt` is a single bundle: `{model_key, net_kwargs, state_dict, scaler_mean, +scaler_std, window, channels, held_out_metrics, held_out_residuals, +channel_ablation_mae_delta}`. You only need `founder_timing_model.py` + one +`.pt` file to run predictions. + +## 3. Input schema + +The model consumes a **20-year rolling window** (`WINDOW = 20`) of yearly +activity counts, ending at a reference year of your choice (typically "now"). +You provide plain `{year: count}` dictionaries — the wrapper handles +alignment, left-zero-padding (for researchers with < 20 years of history) and +the log1p transform used at training time: + +```python +model.build_sequence( + pub_counts_by_year={2015: 2, 2016: 3, 2018: 1, 2020: 4, 2022: 2}, + pat_counts_by_year={2021: 1}, + grant_counts_by_year={2019: 1}, + as_of_year=2023, +) +``` + +| argument | type | description | source | +|---|---|---|---| +| `pub_counts_by_year` | dict[int, int] | publications per calendar year | OpenAlex works' `publication_year`, grouped/counted per author | +| `pat_counts_by_year` | dict[int, int] | patents per calendar year | your patent-matching pipeline | +| `grant_counts_by_year` | dict[int, int] | grants/awards per calendar year | your grant-matching pipeline | +| `as_of_year` | int | the "reference now" the 20-year window ends at (defaults to the latest year with any activity) | e.g. current year | +| `first_publication_year` | int | year of the researcher's first publication (needed only for `years_to_founding` / probability output, not for the raw point estimate) | OpenAlex, min `publication_year` | + +Years outside `[as_of_year - 19, as_of_year]` are ignored; years inside that +range with no entry default to a count of 0. + +## 4. Output format + +```python +model.predict( + pub_counts_by_year=..., pat_counts_by_year=..., grant_counts_by_year=..., + first_publication_year=2015, as_of_year=2023, +) +# { +# 'model': 'transformer', +# 'predicted_founding_age': 8.4, +# 'current_career_age': 8, +# 'years_to_founding': 0.4, +# 'probability_founds_within': {1: 0.62, 2: 0.87, 3: 0.95, 5: 0.99} +# } +``` + +- `predicted_founding_age`: point estimate — "how many years into a career + does this activity pattern, taken as of `as_of_year`, look like a founding + moment." +- `current_career_age` = `as_of_year - first_publication_year` (only returned + if `first_publication_year` is given). +- `years_to_founding` = `predicted_founding_age - current_career_age`. Positive + means the model expects founding is still that many years away (given the + current trajectory); **zero or negative means the current profile already + looks like a typical founding-moment profile** — founding could plausibly + happen any time now (the model can't distinguish "already overdue" from + "right now" — see §6 caveats). +- `probability_founds_within`: `{k: P(founds within k years)}` for k in + (1, 2, 3, 5) by default (pass `horizons=(...)` to customize) — see §5. + +If you omit `first_publication_year`, you get only `predicted_founding_age` +(no probability/timing-to-now fields, since those require knowing the current +career age). + +## 5. Probability design (why a residual-based approach, not a retrained model) + +The underlying LSTM/Transformer are **point-estimate regressors** (trained +with MSE loss) — they were not retrained with a probabilistic loss for this +deliverable, since the existing point predictions are already extremely +accurate (R²=0.998, MAE ≈ 2-2.5 months) and retraining risks losing that +accuracy for a marginal gain in "native" probability calibration. + +Instead, probability is derived **post-hoc** from the held-out test set's +residual distribution (`held_out_residuals` in the bundle, ~460 examples per +model): `P(founds within k years) = P(residual <= k - years_to_founding)`, +i.e. the empirical fraction of held-out errors small enough that the true +founding time would fall within `k` years given the current point estimate. +This is non-parametric (no Gaussian assumption) and directly reflects the +model's actual observed error spread, at the cost of being a global (not +per-input) uncertainty estimate — every prediction uses the same residual +pool, it doesn't widen for "harder" inputs specifically. + +## 6. Features that affect the prediction most + +Channel ablation (zero out one channel, re-predict on the held-out test set, +measure the MAE increase) — `channel_ablation_mae_delta` in each bundle: + +| channel | lstm MAE increase | transformer MAE increase | +|---|---|---| +| **pub** (publications) | **+8.29** | **+8.92** | +| pat (patents) | -0.003 (noise) | -0.020 (noise) | +| grant (grants) | -0.004 (noise) | -0.020 (noise) | + +**The publication timeline completely dominates.** Removing it destroys the +model (MAE jumps from ~0.2 to ~8.5 years — essentially random). Removing +patents or grants changes nothing (the tiny negative deltas are noise, not a +real effect) — for *this specific task* (predicting how far into a career a +founding-like moment falls), patent/grant timing carries no additional signal +beyond what publication timing already provides. Practically: if your +production pipeline is missing patent/grant year-by-year data for some +researchers, this model will still work essentially as well using publication +history alone — you do not need to block on having complete patent/grant +histories for this specific model (unlike the classifier, where patent/grant +*counts* do matter — see `../classifier/README.md` §8). + +## 7. Usage example + +```python +from founder_timing_model import FounderTimingModel + +model = FounderTimingModel.load("models/transformer.pt") + +result = model.predict( + pub_counts_by_year={2016: 1, 2017: 2, 2018: 3, 2019: 2, 2020: 4, 2021: 3, 2022: 5}, + pat_counts_by_year={2021: 1}, + grant_counts_by_year={2020: 1}, + first_publication_year=2016, + as_of_year=2022, +) +print(result) +``` + +## 8. Caveats + +- **Founders-only training data.** These models were trained exclusively on + people who eventually founded a company, predicting *when in their career* + that happened. There is no matched non-founder sequence in the source data + (see `experiments/README.md` "Sequence modeling" for why), so this model + cannot tell you whether someone will found at all — only, conditional on a + founding-like pattern existing, how far into the career it falls. Combine + with the classifier (`../classifier/README.md`) for the "will they found at + all" question, and this model for "when." +- **Retrospective training, prospective use.** Training examples anchor the + 20-year window at a *real, already-known* founding event. Using the window + ending at "now" for someone who hasn't founded yet is a reasonable, + intended extrapolation but was not directly validated against real + future-unknown outcomes (no ground truth exists yet for currently-active + non-founders). Treat `years_to_founding` as a useful signal/ranking tool + more than a precise calendar forecast. +- **Fixed 20-year window, [1, 20] founding-age range.** See §1. +- Reproduce or retrain via `export_sequence_models.py` (depends on the full + `experiments/src` research package + `evaluation/datasets_complete`). diff --git a/service/scripts/profiling/founding_potential/production/sequence/export_sequence_models.py b/service/scripts/profiling/founding_potential/production/sequence/export_sequence_models.py new file mode 100644 index 00000000..6358c883 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/sequence/export_sequence_models.py @@ -0,0 +1,100 @@ +"""Export the two best founder-timing sequence models (LSTM + Transformer) as +standalone production artifacts, with a post-hoc probability layer derived from +held-out residuals (see README.md "Probability design" section for rationale). + +Run: conda run -n potential python production/sequence/export_sequence_models.py +(from the experiments/ directory) +""" +import sys +from pathlib import Path + +import numpy as np +import torch +from sklearn.model_selection import train_test_split + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +from src import config, evaluate, sequence_data, sequence_models # noqa: E402 + +OUT_DIR = Path(__file__).resolve().parent +MODELS_DIR = OUT_DIR / "models" +MODELS_DIR.mkdir(exist_ok=True) + +LSTM_KWARGS = {"hidden_size": 64, "num_layers": 1, "dropout": 0.2} +TRANSFORMER_KWARGS = {"d_model": 32, "n_heads": 4, "n_layers": 2, "dropout": 0.2} + + +def channel_ablation(model, X_test, y_test, base_mae): + """Zero out one channel at a time (post-hoc, on the already-fitted model) + and measure the MAE increase -- a cheap proxy for channel importance.""" + rows = {} + for c, name in enumerate(sequence_data.CHANNELS): + X_ablated = X_test.copy() + X_ablated[:, :, c] = 0.0 + pred = model.predict(X_ablated) + metrics = evaluate.regression_metrics(y_test, pred) + rows[name] = metrics["mae"] - base_mae + return rows + + +def build_and_export(model_key, model_cls, net_kwargs, X_train, y_train, X_test, y_test, X_all, y_all): + print(f"\n=== {model_key} ===") + # 1) Fit on train only -> honest held-out metrics + residuals + channel ablation. + model = model_cls(**net_kwargs) + model.fit(X_train, y_train) + pred_test = model.predict(X_test) + metrics = evaluate.regression_metrics(y_test, pred_test) + residuals = (y_test - pred_test).astype(np.float32) + print(f" held-out: MAE={metrics['mae']:.3f} RMSE={metrics['rmse']:.3f} R2={metrics['r2']:.3f}") + + ablation = channel_ablation(model, X_test, y_test, metrics["mae"]) + print(" channel ablation (MAE increase when channel is zeroed out):") + for ch, delta in sorted(ablation.items(), key=lambda kv: -kv[1]): + print(f" {ch:6s} +{delta:.4f} MAE") + + # 2) Refit on ALL data for the final shipped artifact (standard practice; + # generalization already validated above). + final_model = model_cls(**net_kwargs) + final_model.fit(X_all, y_all) + + bundle = { + "model_key": model_key, + "net_kwargs": net_kwargs, + "state_dict": final_model.model_.state_dict(), + "scaler_mean": final_model.scaler_.mean_, + "scaler_std": final_model.scaler_.std_, + "window": sequence_data.WINDOW, + "channels": sequence_data.CHANNELS, + "held_out_metrics": metrics, + "held_out_residuals": residuals, + "channel_ablation_mae_delta": ablation, + } + out_path = MODELS_DIR / f"{model_key}.pt" + torch.save(bundle, out_path) + print(f" saved {out_path} ({out_path.stat().st_size / 1024:.0f} KB)") + return metrics, residuals, ablation + + +def main(): + print("Building founder-only sequence dataset...") + sequences, founding_age, meta = sequence_data.build_founder_sequence_dataset() + + idx = np.arange(len(sequences)) + idx_train, idx_test = train_test_split(idx, test_size=0.2, random_state=config.RANDOM_STATE) + X_train, X_test = sequences[idx_train], sequences[idx_test] + y_train, y_test = founding_age[idx_train], founding_age[idx_test] + + results = {} + results["lstm"] = build_and_export( + "lstm", sequence_models.LSTMRegressor, LSTM_KWARGS, + X_train, y_train, X_test, y_test, sequences, founding_age, + ) + results["transformer"] = build_and_export( + "transformer", sequence_models.TransformerRegressor, TRANSFORMER_KWARGS, + X_train, y_train, X_test, y_test, sequences, founding_age, + ) + + print("\nDone. Shipped: lstm.pt, transformer.pt") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/founding_potential/production/sequence/founder_timing_model.py b/service/scripts/profiling/founding_potential/production/sequence/founder_timing_model.py new file mode 100644 index 00000000..0caced38 --- /dev/null +++ b/service/scripts/profiling/founding_potential/production/sequence/founder_timing_model.py @@ -0,0 +1,192 @@ +"""Self-contained inference wrapper for the founder-timing sequence models +(LSTM / Transformer). Depends only on torch/numpy -- no dependency on the +`experiments/src` research package. + +These models predict `founding_age`: how many years into a researcher's +publishing career a founding event falls, given their chronological +publication/patent/grant activity in the WINDOW (20) years up to and including +the reference point of interest ("now", if you're asking "how founding-ready +does this person look today"). + +Usage: + from founder_timing_model import FounderTimingModel + + model = FounderTimingModel.load("models/transformer.pt") + result = model.predict( + pub_counts_by_year={2015: 2, 2016: 3, 2017: 1, 2020: 4, 2022: 2}, + pat_counts_by_year={2021: 1}, + grant_counts_by_year={2019: 1}, + first_publication_year=2015, + as_of_year=2023, + ) + print(result) + +See README.md in this directory for the full input schema, output format and +the "probability" design rationale. +""" +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch import nn + +CHANNELS = ["pub", "pat", "grant"] +WINDOW = 20 +DEFAULT_HORIZONS = (1, 2, 3, 5) + + +class _LSTMNet(nn.Module): + """Must stay structurally identical to src/sequence_models.py::_LSTMNet -- + state_dict keys are loaded directly from the exported bundle.""" + + def __init__(self, n_channels, hidden_size=64, num_layers=1, dropout=0.2): + super().__init__() + self.lstm = nn.LSTM( + input_size=n_channels, hidden_size=hidden_size, num_layers=num_layers, + batch_first=True, dropout=dropout if num_layers > 1 else 0.0, + ) + self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(hidden_size, 1)) + + def forward(self, x): + _, (h_n, _) = self.lstm(x) + return self.head(h_n[-1]).squeeze(-1) + + +class _TransformerNet(nn.Module): + """Must stay structurally identical to src/sequence_models.py::_TransformerNet.""" + + def __init__(self, n_channels, seq_len, d_model=32, n_heads=4, n_layers=2, dropout=0.2): + super().__init__() + self.input_proj = nn.Linear(n_channels, d_model) + self.pos_embedding = nn.Parameter(torch.zeros(1, seq_len, d_model)) + encoder_layer = nn.TransformerEncoderLayer( + d_model=d_model, nhead=n_heads, dim_feedforward=d_model * 4, + dropout=dropout, batch_first=True, + ) + self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=n_layers) + self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(d_model, 1)) + + def forward(self, x): + h = self.input_proj(x) + self.pos_embedding + h = self.encoder(h) + pooled = h.mean(dim=1) + return self.head(pooled).squeeze(-1) + + +class FounderTimingModel: + def __init__(self, bundle: dict[str, Any]): + self.model_key: str = bundle["model_key"] + self.window: int = bundle["window"] + self.channels: list[str] = bundle["channels"] + self.scaler_mean = bundle["scaler_mean"] + self.scaler_std = bundle["scaler_std"] + self.held_out_metrics: dict = bundle["held_out_metrics"] + self.held_out_residuals: np.ndarray = bundle["held_out_residuals"] + self.channel_ablation_mae_delta: dict = bundle["channel_ablation_mae_delta"] + + n_channels = len(self.channels) + if self.model_key == "lstm": + self._net = _LSTMNet(n_channels, **bundle["net_kwargs"]) + elif self.model_key == "transformer": + self._net = _TransformerNet(n_channels, self.window, **bundle["net_kwargs"]) + else: + raise ValueError(f"unknown model_key {self.model_key!r}") + self._net.load_state_dict(bundle["state_dict"]) + self._net.eval() + + @classmethod + def load(cls, path: str | Path) -> "FounderTimingModel": + return cls(torch.load(path, map_location="cpu", weights_only=False)) + + # -- building the input sequence ---------------------------------------- + def build_sequence( + self, + pub_counts_by_year: dict[int, int] | None = None, + pat_counts_by_year: dict[int, int] | None = None, + grant_counts_by_year: dict[int, int] | None = None, + as_of_year: int | None = None, + ) -> np.ndarray: + """Turn per-year activity counts into the (WINDOW, 3) chronological, + log1p-transformed array the model expects (oldest year first, ending + at `as_of_year`). Years with no recorded activity default to 0; years + before the start of the available history are zero-padded on the left + (identical in spirit to how a founder with < WINDOW years of real + pre-founding history looks in the training data).""" + pub_counts_by_year = pub_counts_by_year or {} + pat_counts_by_year = pat_counts_by_year or {} + grant_counts_by_year = grant_counts_by_year or {} + if as_of_year is None: + all_years = list(pub_counts_by_year) + list(pat_counts_by_year) + list(grant_counts_by_year) + if not all_years: + raise ValueError("as_of_year must be given if no activity years are provided") + as_of_year = max(all_years) + + years = range(as_of_year - self.window + 1, as_of_year + 1) # oldest -> newest, length WINDOW + channel_dicts = [pub_counts_by_year, pat_counts_by_year, grant_counts_by_year] + seq = np.zeros((self.window, len(self.channels)), dtype=np.float32) + for c, counts in enumerate(channel_dicts): + for t, year in enumerate(years): + seq[t, c] = max(0.0, float(counts.get(year, 0))) + return np.log1p(seq) + + # -- prediction ----------------------------------------------------------- + def _predict_point(self, sequence: np.ndarray) -> np.ndarray: + """`sequence`: (WINDOW, 3) or (n, WINDOW, 3) raw (log1p'd) array.""" + X = np.asarray(sequence, dtype=np.float32) + if X.ndim == 2: + X = X[None, ...] + X = (X - self.scaler_mean) / self.scaler_std + with torch.no_grad(): + pred = self._net(torch.tensor(X, dtype=torch.float32)).numpy() + return pred + + def residual_cdf(self, x: float) -> float: + """Empirical P(residual <= x) from the held-out test set -- the + nonparametric basis for every probability this class reports.""" + return float(np.mean(self.held_out_residuals <= x)) + + def predict( + self, + pub_counts_by_year: dict[int, int] | None = None, + pat_counts_by_year: dict[int, int] | None = None, + grant_counts_by_year: dict[int, int] | None = None, + first_publication_year: int | None = None, + as_of_year: int | None = None, + horizons: tuple[int, ...] = DEFAULT_HORIZONS, + ) -> dict[str, Any]: + """Full prediction for one researcher's history ending at `as_of_year` + (defaults to the latest year with any recorded activity). + + Returns: + predicted_founding_age: point estimate of "years into career at the + hypothetical founding moment defined by `as_of_year`". + current_career_age: as_of_year - first_publication_year (if given). + years_to_founding: predicted_founding_age - current_career_age; <=0 + means the current activity profile already looks like a typical + founding-moment profile (founding could happen any time now). + probability_founds_within: {k: P(founds within k years)} for each + horizon in `horizons`, derived from held-out residuals (see README). + """ + seq = self.build_sequence(pub_counts_by_year, pat_counts_by_year, grant_counts_by_year, as_of_year) + founding_age_hat = float(self._predict_point(seq)[0]) + + result: dict[str, Any] = { + "model": self.model_key, + "predicted_founding_age": founding_age_hat, + } + + if first_publication_year is not None: + if as_of_year is None: + all_years = list((pub_counts_by_year or {})) + list((pat_counts_by_year or {})) + list((grant_counts_by_year or {})) + as_of_year = max(all_years) if all_years else first_publication_year + current_career_age = as_of_year - first_publication_year + years_to_founding = founding_age_hat - current_career_age + result["current_career_age"] = current_career_age + result["years_to_founding"] = years_to_founding + result["probability_founds_within"] = { + k: round(self.residual_cdf(k - years_to_founding), 4) for k in horizons + } + return result diff --git a/service/scripts/profiling/founding_potential/production/sequence/models/lstm.pt b/service/scripts/profiling/founding_potential/production/sequence/models/lstm.pt new file mode 100644 index 00000000..956c80ac Binary files /dev/null and b/service/scripts/profiling/founding_potential/production/sequence/models/lstm.pt differ diff --git a/service/scripts/profiling/founding_potential/production/sequence/models/transformer.pt b/service/scripts/profiling/founding_potential/production/sequence/models/transformer.pt new file mode 100644 index 00000000..0d32019b Binary files /dev/null and b/service/scripts/profiling/founding_potential/production/sequence/models/transformer.pt differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/mcnemar_baseline_vs_best.csv b/service/scripts/profiling/founding_potential/results/rq1/mcnemar_baseline_vs_best.csv new file mode 100644 index 00000000..62b320dd --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1/mcnemar_baseline_vs_best.csv @@ -0,0 +1,3 @@ +,0 +statistic,83.84013605442176 +p_value,5.3644585148746496e-20 diff --git a/service/scripts/profiling/founding_potential/results/rq1/models/lightgbm.joblib b/service/scripts/profiling/founding_potential/results/rq1/models/lightgbm.joblib new file mode 100644 index 00000000..cf1fef5b Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1/models/lightgbm.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/models/stacking_ensemble.joblib b/service/scripts/profiling/founding_potential/results/rq1/models/stacking_ensemble.joblib new file mode 100644 index 00000000..58b94673 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1/models/stacking_ensemble.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/permutation_importance.csv b/service/scripts/profiling/founding_potential/results/rq1/permutation_importance.csv new file mode 100644 index 00000000..d987d184 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1/permutation_importance.csv @@ -0,0 +1,100 @@ +feature,importance_mean,importance_std +publications,0.4440974603875724,0.009511785737132612 +pub_citation_sum,0.0641745019900897,0.0023847457046495867 +last_patent_year,0.061419305752316286,0.0032168477466114997 +i10-index,0.052808315628195955,0.002509050818671705 +pub_citation_mean,0.042499292031831906,0.002523272278649042 +g-index,0.036249565551782555,0.002265360125324732 +activities_total,0.03186015042559469,0.001859142044274061 +pat_citation_mean,0.023747584504377334,0.0018054623744417433 +grants,0.014545800960367655,0.001636080338818295 +first_publication_year,0.01341695838784518,0.0011208069436919059 +last_publication_year,0.010105477585606454,0.001265829119215705 +patents,0.009386919235293584,0.000828161224172823 +last_grant_year,0.0061119416876279035,0.0006396038493956664 +publication_research_area_32,0.005199808047404142,0.0006411887411683997 +h-index,0.004761111131916573,0.0006185755476381059 +pat_citation_sum,0.004029264901793272,0.0006407043313268342 +affiliations,0.003924122102600141,0.0006734435898464144 +industry_collab_papers,0.002771785899856466,0.000458393950826596 +first_grant_year,0.0024780107524362215,0.00045174085545348724 +linked_patents_to_publications,0.0017714854471442888,0.00038735536489506483 +grant_research_impact,0.0017419551968919865,0.0007783860555244073 +publication_research_area_31,0.0010347728515872068,0.0004380600676750018 +publication_research_area_46,0.0010296404274699467,0.00027494253110439427 +institution_stanford,0.0009637600715686423,0.00023666778366864807 +patent_research_area_46,0.0007991644733361059,0.0003005059902911959 +grant_research_area_32,0.0006102226280733592,0.0003698845134606399 +institution_berkeley,0.00045373766528075123,0.00021951745011740962 +institution_muenchen,0.0004130569816417906,7.580252297057787e-05 +patent_research_area_32,0.00036940421614752863,0.00011610246817244868 +publication_research_area_35,0.0003162362804154439,0.00017402147914398575 +publication_research_area_42,0.00029062839366878477,0.00015928133313129265 +institution_oxford,0.0002602274221759626,0.000185358155946732 +first_patent_year,0.0002299601664907669,0.00015372021880899557 +institution_telaviv,0.00022185659229883025,0.0002808557319380741 +institution_harvard,0.00022091161950384407,0.00018883040518073856 +patent_research_area_35,0.00017105334272454753,0.00013583506288295137 +publication_research_area_51,0.0001581465869737786,0.00013922623521323216 +grant_innovation_impact,0.00013702479636796828,0.0001422675814029339 +institution_ude,0.00013034268850643517,5.51579297443134e-05 +publication_research_area_33,0.00011963406695062462,9.734481095501337e-05 +publication_research_area_40,6.163246509007791e-05,8.342838939511106e-05 +grant_research_area_46,5.6425844484753186e-05,6.057990043771272e-05 +grant_research_area_42,5.4768959582357504e-05,0.0001321879842622329 +publication_research_area_44,4.6328393106159774e-05,4.109464765116167e-05 +institution_toronto,4.203267111526077e-05,0.00013829259973950555 +grant_research_area_34,3.648946572037404e-05,9.856576928560712e-05 +publication_research_area_49,3.523595518664657e-05,1.0020003875083567e-05 +publication_research_area_52,2.8243411024614362e-05,6.365046136625705e-05 +grant_research_area_52,2.4976831800399558e-05,6.0461267957791294e-05 +publication_research_area_39,2.2444089520501364e-05,5.4003334909501585e-05 +publication_research_area_47,2.080080050642641e-05,2.1829610866522595e-05 +patent_research_area_34,1.2265010515000175e-05,3.4309040012788196e-06 +publication_research_area_34,1.0963870610469772e-05,5.079619737042506e-05 +publication_research_area_37,9.739396381164278e-06,1.5473891954426686e-05 +grant_research_area_31,9.05566937272062e-06,1.2355287634925927e-05 +grant_research_area_33,7.176496559663237e-06,1.1600418122926559e-05 +publication_research_area_36,6.871129506863527e-06,1.8889049455628318e-05 +publication_research_area_50,6.313148147923942e-06,8.093717579945578e-06 +patent_research_area_41,5.268894264148782e-06,1.4185767546691009e-05 +grant_research_area_36,3.979969424106055e-06,8.741862922562177e-06 +grant_research_area_51,2.6849918500770897e-06,7.727353969929902e-05 +grant_research_area_39,2.6844415874804907e-06,4.9698681231697676e-06 +patent_research_area_42,2.018322524721672e-06,4.003947557053808e-06 +patent_research_area_n.,1.5509887295039881e-06,2.7724586593788047e-05 +grant_research_area_35,2.794525058302799e-07,2.2550590120034133e-06 +patent_research_area_30,1.1961448171393662e-07,6.938865295073371e-07 +grant_research_area_47,0.0,0.0 +publication_research_area_43,0.0,0.0 +grant_research_area_43,0.0,0.0 +patent_research_area_33,0.0,0.0 +grant_research_area_38,0.0,0.0 +grant_research_area_37,0.0,0.0 +patent_research_area_37,0.0,0.0 +patent_research_area_36,0.0,0.0 +grant_research_area_49,0.0,0.0 +patent_research_area_38,0.0,0.0 +grant_research_area_30,0.0,0.0 +patent_research_area_52,0.0,0.0 +patent_research_area_50,0.0,0.0 +patent_research_area_49,0.0,0.0 +patent_research_area_48,0.0,0.0 +patent_research_area_47,0.0,0.0 +patent_research_area_39,0.0,0.0 +patent_research_area_44,0.0,0.0 +patent_research_area_43,0.0,0.0 +grant_research_area_48,0.0,0.0 +publication_research_area_48,-4.777574768688453e-07,2.5399584991121672e-06 +grant_research_area_44,-2.6545860416726797e-06,8.853044030928573e-07 +grant_research_area_40,-3.5805367832819624e-06,1.3088192634427606e-05 +publication_research_area_41,-4.670934500378143e-06,1.529003843001235e-05 +patent_research_area_51,-5.39510398220866e-06,6.7771380831518544e-06 +grant_research_area_50,-6.018075757896479e-06,3.415361829511047e-06 +publication_research_area_n.,-1.6678560361260698e-05,4.85699334820089e-05 +patent_research_area_40,-2.2966722354866854e-05,2.624449457092434e-05 +publication_research_area_30,-2.759677706088981e-05,4.2392146152842375e-05 +grant_research_area_41,-7.746870943114436e-05,4.853083326762734e-05 +patent_research_area_31,-7.858662076178912e-05,2.6338982228252595e-05 +publication_research_area_38,-0.00010061127127826141,6.048638875532882e-05 +grant_research_area_n.,-0.00018513837033415915,0.00010988699811737849 diff --git a/service/scripts/profiling/founding_potential/results/rq1/plots/confusion_lightgbm.png b/service/scripts/profiling/founding_potential/results/rq1/plots/confusion_lightgbm.png new file mode 100644 index 00000000..813d5b01 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1/plots/confusion_lightgbm.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/plots/confusion_logistic_regression.png b/service/scripts/profiling/founding_potential/results/rq1/plots/confusion_logistic_regression.png new file mode 100644 index 00000000..50739d2c Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1/plots/confusion_logistic_regression.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/plots/confusion_stacking_ensemble.png b/service/scripts/profiling/founding_potential/results/rq1/plots/confusion_stacking_ensemble.png new file mode 100644 index 00000000..4bd9dc9c Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1/plots/confusion_stacking_ensemble.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/plots/permutation_importance.png b/service/scripts/profiling/founding_potential/results/rq1/plots/permutation_importance.png new file mode 100644 index 00000000..9354ea66 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1/plots/permutation_importance.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/plots/shap_summary.png b/service/scripts/profiling/founding_potential/results/rq1/plots/shap_summary.png new file mode 100644 index 00000000..ae429080 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1/plots/shap_summary.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/plots/top5_pr.png b/service/scripts/profiling/founding_potential/results/rq1/plots/top5_pr.png new file mode 100644 index 00000000..560f7aab Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1/plots/top5_pr.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/plots/top5_roc.png b/service/scripts/profiling/founding_potential/results/rq1/plots/top5_roc.png new file mode 100644 index 00000000..cc52a422 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1/plots/top5_roc.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1/rq1_leave_one_institution_out.csv b/service/scripts/profiling/founding_potential/results/rq1/rq1_leave_one_institution_out.csv new file mode 100644 index 00000000..51ebaf73 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1/rq1_leave_one_institution_out.csv @@ -0,0 +1,25 @@ +held_out_institution,model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +berkeley,random_forest,0.8938080495356037,0.8561034761519806,0.8651960784313726,0.8606257618854124,0.9508687988322615,0.9352701725889087,0.7748863967212042,0.0916010325285079 +berkeley,xgboost,0.9352941176470588,0.9163248564397046,0.9125816993464052,0.9144494474007367,0.9782380798780129,0.9728371029060612,0.8624255919906876,0.05184710770845413 +berkeley,lightgbm,0.9402476780185759,0.9242798353909465,0.9174836601307189,0.9208692086920869,0.981150910015053,0.9755184511242864,0.8728875867367218,0.04690752230798288 +harvard,random_forest,0.8987654320987655,0.9052183173588925,0.7805325987144169,0.8382642998027613,0.9526397485697599,0.9290937209525628,0.7696254787865199,0.08178858160630093 +harvard,xgboost,0.9395061728395062,0.9425173439048563,0.8732782369146006,0.9065776930409915,0.9807783681880297,0.9706333807958668,0.8633170529628762,0.04677882418036461 +harvard,lightgbm,0.9398148148148148,0.9461077844311377,0.8705234159779615,0.9067431850789096,0.9826362607521476,0.9734330946079244,0.8640565194125395,0.043685045783186834 +muenchen,random_forest,0.7953757225433526,0.6064139941690962,0.832,0.7015177065767285,0.8767349593495936,0.7765094185861298,0.5675742666446973,0.15746290406976293 +muenchen,xgboost,0.7884393063583816,0.6012084592145015,0.796,0.685025817555938,0.8628682926829269,0.763287320123835,0.542216159841516,0.1559271514415741 +muenchen,lightgbm,0.7722543352601156,0.581039755351682,0.76,0.658578856152513,0.853691056910569,0.7517422512407861,0.5022355737952905,0.15695599279447855 +oxford,random_forest,0.911386593204775,0.8539898132427843,0.8245901639344262,0.8390325271059216,0.959453412512546,0.9238390784736245,0.7781516198820395,0.07865284747427456 +oxford,xgboost,0.9504132231404959,0.9183333333333333,0.9032786885245901,0.9107438016528926,0.984900886584142,0.9722281536725682,0.8764751247733411,0.042194340378046036 +oxford,lightgbm,0.9554637281910009,0.9253731343283582,0.9147540983606557,0.920032976092333,0.9877645115423219,0.976680741461625,0.8892006068129127,0.03689864957054344 +stanford,random_forest,0.9001419782300047,0.912889935256033,0.8498630136986302,0.880249716231555,0.9613942820628392,0.9572731678928575,0.7963001054601905,0.08187944047855213 +stanford,xgboost,0.9245149077141505,0.9096844396082698,0.9161643835616439,0.9129129129129129,0.9797777181881978,0.9772211505881503,0.846320011438327,0.05441083386540413 +stanford,lightgbm,0.927117841930904,0.9138025095471904,0.9178082191780822,0.9158009841443412,0.9798291807637229,0.9769930836860543,0.8515608804568686,0.053898616481872476 +telaviv,random_forest,0.9329221279876638,0.9143730886850153,0.9507154213036566,0.9321901792673422,0.9814694934455415,0.9840855248253557,0.8665222579580186,0.06278409820550628 +telaviv,xgboost,0.9498843484965305,0.9338461538461539,0.9650238473767886,0.9491790461297889,0.9915843987700276,0.9928955188919398,0.9002477352802948,0.035886093974113464 +telaviv,lightgbm,0.9568234387047032,0.9428129829984544,0.9697933227344993,0.9561128526645768,0.992805327342136,0.9938473761123844,0.9139930650897162,0.03212358373132753 +toronto,random_forest,0.8310708898944194,0.7942857142857143,0.6465116279069767,0.7128205128205128,0.8714571220930232,0.8089004180527387,0.6012626875361187,0.13535280288698756 +toronto,xgboost,0.8144796380090498,0.8006535947712419,0.5697674418604651,0.6657608695652174,0.8658689784053156,0.8011683092591997,0.5573915163186545,0.13123539090156555 +toronto,lightgbm,0.8076923076923077,0.7986348122866894,0.5441860465116279,0.6473029045643154,0.8486399501661129,0.7789467464984129,0.5396833164956024,0.14120805997827313 +ude,random_forest,0.9242424242424242,0.6923076923076923,0.9,0.782608695652174,0.9624999999999999,0.8845213408920609,0.7469892572492464,0.08766724613880275 +ude,xgboost,0.9318181818181818,0.7037037037037037,0.95,0.8085106382978723,0.978125,0.9280225174865269,0.780952380952381,0.05495387688279152 +ude,lightgbm,0.946969696969697,0.76,0.95,0.8444444444444444,0.9870535714285714,0.9470631781805057,0.8203096227459236,0.04920439998805263 diff --git a/service/scripts/profiling/founding_potential/results/rq1/rq1_leave_one_institution_out.md b/service/scripts/profiling/founding_potential/results/rq1/rq1_leave_one_institution_out.md new file mode 100644 index 00000000..93a9f895 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1/rq1_leave_one_institution_out.md @@ -0,0 +1,26 @@ +| | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:------------------------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|----------:| +| ('berkeley', 'random_forest') | 0.893808 | 0.856103 | 0.865196 | 0.860626 | 0.950869 | 0.93527 | 0.774886 | 0.091601 | +| ('berkeley', 'xgboost') | 0.935294 | 0.916325 | 0.912582 | 0.914449 | 0.978238 | 0.972837 | 0.862426 | 0.0518471 | +| ('berkeley', 'lightgbm') | 0.940248 | 0.92428 | 0.917484 | 0.920869 | 0.981151 | 0.975518 | 0.872888 | 0.0469075 | +| ('harvard', 'random_forest') | 0.898765 | 0.905218 | 0.780533 | 0.838264 | 0.95264 | 0.929094 | 0.769625 | 0.0817886 | +| ('harvard', 'xgboost') | 0.939506 | 0.942517 | 0.873278 | 0.906578 | 0.980778 | 0.970633 | 0.863317 | 0.0467788 | +| ('harvard', 'lightgbm') | 0.939815 | 0.946108 | 0.870523 | 0.906743 | 0.982636 | 0.973433 | 0.864057 | 0.043685 | +| ('muenchen', 'random_forest') | 0.795376 | 0.606414 | 0.832 | 0.701518 | 0.876735 | 0.776509 | 0.567574 | 0.157463 | +| ('muenchen', 'xgboost') | 0.788439 | 0.601208 | 0.796 | 0.685026 | 0.862868 | 0.763287 | 0.542216 | 0.155927 | +| ('muenchen', 'lightgbm') | 0.772254 | 0.58104 | 0.76 | 0.658579 | 0.853691 | 0.751742 | 0.502236 | 0.156956 | +| ('oxford', 'random_forest') | 0.911387 | 0.85399 | 0.82459 | 0.839033 | 0.959453 | 0.923839 | 0.778152 | 0.0786528 | +| ('oxford', 'xgboost') | 0.950413 | 0.918333 | 0.903279 | 0.910744 | 0.984901 | 0.972228 | 0.876475 | 0.0421943 | +| ('oxford', 'lightgbm') | 0.955464 | 0.925373 | 0.914754 | 0.920033 | 0.987765 | 0.976681 | 0.889201 | 0.0368986 | +| ('stanford', 'random_forest') | 0.900142 | 0.91289 | 0.849863 | 0.88025 | 0.961394 | 0.957273 | 0.7963 | 0.0818794 | +| ('stanford', 'xgboost') | 0.924515 | 0.909684 | 0.916164 | 0.912913 | 0.979778 | 0.977221 | 0.84632 | 0.0544108 | +| ('stanford', 'lightgbm') | 0.927118 | 0.913803 | 0.917808 | 0.915801 | 0.979829 | 0.976993 | 0.851561 | 0.0538986 | +| ('telaviv', 'random_forest') | 0.932922 | 0.914373 | 0.950715 | 0.93219 | 0.981469 | 0.984086 | 0.866522 | 0.0627841 | +| ('telaviv', 'xgboost') | 0.949884 | 0.933846 | 0.965024 | 0.949179 | 0.991584 | 0.992896 | 0.900248 | 0.0358861 | +| ('telaviv', 'lightgbm') | 0.956823 | 0.942813 | 0.969793 | 0.956113 | 0.992805 | 0.993847 | 0.913993 | 0.0321236 | +| ('toronto', 'random_forest') | 0.831071 | 0.794286 | 0.646512 | 0.712821 | 0.871457 | 0.8089 | 0.601263 | 0.135353 | +| ('toronto', 'xgboost') | 0.81448 | 0.800654 | 0.569767 | 0.665761 | 0.865869 | 0.801168 | 0.557392 | 0.131235 | +| ('toronto', 'lightgbm') | 0.807692 | 0.798635 | 0.544186 | 0.647303 | 0.84864 | 0.778947 | 0.539683 | 0.141208 | +| ('ude', 'random_forest') | 0.924242 | 0.692308 | 0.9 | 0.782609 | 0.9625 | 0.884521 | 0.746989 | 0.0876672 | +| ('ude', 'xgboost') | 0.931818 | 0.703704 | 0.95 | 0.808511 | 0.978125 | 0.928023 | 0.780952 | 0.0549539 | +| ('ude', 'lightgbm') | 0.94697 | 0.76 | 0.95 | 0.844444 | 0.987054 | 0.947063 | 0.82031 | 0.0492044 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1/rq1_model_comparison.csv b/service/scripts/profiling/founding_potential/results/rq1/rq1_model_comparison.csv new file mode 100644 index 00000000..71ef6004 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1/rq1_model_comparison.csv @@ -0,0 +1,13 @@ +model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +lightgbm,0.9296756592906942,0.913372582001682,0.8938271604938272,0.9034941763727121,0.976269322211954,0.9685049361518786,0.8483100198135644,0.053432731044197566 +stacking_ensemble,0.9269475598666262,0.8965798045602605,0.9061728395061729,0.9013507981989357,0.9754794515137872,0.9675765397034317,0.8433811094467112,0.05719178794634457 +xgboost,0.9269475598666262,0.907190635451505,0.8930041152263375,0.9000414765657404,0.9744139159419603,0.9665730556966816,0.8425529635211692,0.05556803196668625 +catboost,0.9224007274931798,0.9026028547439127,0.8847736625514403,0.8935993349958438,0.971654897593264,0.9632567246873249,0.8326428131667227,0.059948209000983244 +torch_mlp,0.9196726280691119,0.8984899328859061,0.8814814814814815,0.8899044453676777,0.9622309502934369,0.955302995455666,0.8267763485833509,0.06462439894676208 +random_forest,0.8957259775689603,0.8731790916880892,0.8386831275720165,0.855583543240974,0.951964210958666,0.9349680824025975,0.7744264740411075,0.08763717778689288 +logistic_regression,0.881782358290391,0.8235294117647058,0.8641975308641975,0.8433734939759037,0.9434869236905918,0.9275477315216814,0.7490861135477721,0.08788246377799803 +svm_rbf,0.8754167929675659,0.845360824742268,0.8098765432098766,0.8272383354350568,0.9373219828914007,0.9143562404019991,0.7303022058858781,0.09180799832693237 +decision_tree,0.8375265231888451,0.7379117028731604,0.8666666666666667,0.7971233913701741,0.9210842160138386,0.8829334748606221,0.6690488462111767,0.10435262951516595 +knn,0.8184298272203698,0.8162217659137577,0.654320987654321,0.7263590680676107,0.880971619945815,0.8208621350700424,0.6010655862759007,0.13055538715435655 +gaussian_nb,0.7241588360109124,0.8056112224448898,0.3308641975308642,0.4690781796966161,0.8162221669312734,0.7211454455622044,0.3827487061238318,0.2730256049045907 +dummy_most_frequent,0.6317065777508336,0.0,0.0,0.0,0.5,0.3682934222491664,0.0,0.3682934222491664 diff --git a/service/scripts/profiling/founding_potential/results/rq1/rq1_model_comparison.md b/service/scripts/profiling/founding_potential/results/rq1/rq1_model_comparison.md new file mode 100644 index 00000000..5316b1a5 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1/rq1_model_comparison.md @@ -0,0 +1,14 @@ +| model | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:--------------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|----------:| +| lightgbm | 0.929676 | 0.913373 | 0.893827 | 0.903494 | 0.976269 | 0.968505 | 0.84831 | 0.0534327 | +| stacking_ensemble | 0.926948 | 0.89658 | 0.906173 | 0.901351 | 0.975479 | 0.967577 | 0.843381 | 0.0571918 | +| xgboost | 0.926948 | 0.907191 | 0.893004 | 0.900041 | 0.974414 | 0.966573 | 0.842553 | 0.055568 | +| catboost | 0.922401 | 0.902603 | 0.884774 | 0.893599 | 0.971655 | 0.963257 | 0.832643 | 0.0599482 | +| torch_mlp | 0.919673 | 0.89849 | 0.881481 | 0.889904 | 0.962231 | 0.955303 | 0.826776 | 0.0646244 | +| random_forest | 0.895726 | 0.873179 | 0.838683 | 0.855584 | 0.951964 | 0.934968 | 0.774426 | 0.0876372 | +| logistic_regression | 0.881782 | 0.823529 | 0.864198 | 0.843373 | 0.943487 | 0.927548 | 0.749086 | 0.0878825 | +| svm_rbf | 0.875417 | 0.845361 | 0.809877 | 0.827238 | 0.937322 | 0.914356 | 0.730302 | 0.091808 | +| decision_tree | 0.837527 | 0.737912 | 0.866667 | 0.797123 | 0.921084 | 0.882933 | 0.669049 | 0.104353 | +| knn | 0.81843 | 0.816222 | 0.654321 | 0.726359 | 0.880972 | 0.820862 | 0.601066 | 0.130555 | +| gaussian_nb | 0.724159 | 0.805611 | 0.330864 | 0.469078 | 0.816222 | 0.721145 | 0.382749 | 0.273026 | +| dummy_most_frequent | 0.631707 | 0 | 0 | 0 | 0.5 | 0.368293 | 0 | 0.368293 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/ablation_prefounding_fix.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/ablation_prefounding_fix.csv new file mode 100644 index 00000000..1261d0eb --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/ablation_prefounding_fix.csv @@ -0,0 +1,3 @@ +pipeline,n_rows,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +fix_on,16494,0.9296756592906942,0.913372582001682,0.8938271604938272,0.9034941763727121,0.976269322211954,0.9685049361518786,0.8483100198135644,0.053432731044197566 +fix_off,16466,0.8466909532483303,0.7813248204309656,0.8090909090909091,0.7949654892407633,0.9180388556653607,0.8864221631506207,0.672862341314094,0.10965134265264417 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/ablation_prefounding_fix.md b/service/scripts/profiling/founding_potential/results/rq1_robustness/ablation_prefounding_fix.md new file mode 100644 index 00000000..6bfa1cb0 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/ablation_prefounding_fix.md @@ -0,0 +1,4 @@ +| pipeline | n_rows | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:-----------|---------:|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|----------:| +| fix_on | 16494 | 0.929676 | 0.913373 | 0.893827 | 0.903494 | 0.976269 | 0.968505 | 0.84831 | 0.0534327 | +| fix_off | 16466 | 0.846691 | 0.781325 | 0.809091 | 0.794965 | 0.918039 | 0.886422 | 0.672862 | 0.109651 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/area_stratified_pooled_model.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/area_stratified_pooled_model.csv new file mode 100644 index 00000000..fb38b7c4 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/area_stratified_pooled_model.csv @@ -0,0 +1,23 @@ +group,n,founder_rate,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +32,1166,0.22384219554030874,0.9493996569468267,0.9316239316239316,0.8352490421455939,0.8808080808080808,0.9666920683304757,0.9364408340780385,0.8508506430002786,0.04368896580612041 +n.,429,0.662004662004662,0.9230769230769231,0.9225589225589226,0.9647887323943662,0.9432013769363167,0.9841185041282177,0.9924822312137267,0.8262349450003642,0.05463661429743082 +31,377,0.21750663129973474,0.946949602122016,0.918918918918919,0.8292682926829268,0.8717948717948718,0.9728813559322034,0.9356866199037027,0.8402167428448224,0.04536923541973955 +40,244,0.47540983606557374,0.9098360655737705,0.8983050847457628,0.9137931034482759,0.905982905982906,0.9617456896551724,0.9642595097786962,0.8194913688077033,0.07957434518007606 +42,203,0.31527093596059114,0.9261083743842364,0.9016393442622951,0.859375,0.88,0.9769559352517986,0.9637751383174913,0.8271608292650046,0.048779758321450296 +46,157,0.6942675159235668,0.9171974522292994,0.9528301886792453,0.926605504587156,0.9395348837209302,0.9682721712538226,0.9840532918333846,0.8090948889478105,0.05626512209498496 +51,133,0.23308270676691728,0.9548872180451128,0.9310344827586207,0.8709677419354839,0.9,0.970271979759646,0.9409363609392009,0.8717228983609421,0.04478101537130266 +34,120,0.3416666666666667,0.925,0.9210526315789473,0.8536585365853658,0.8860759493670886,0.9771534424205001,0.9650667269791089,0.8316270648620494,0.05246369285584714 +52,95,0.30526315789473685,0.9578947368421052,0.9310344827586207,0.9310344827586207,0.9310344827586207,0.9937304075235109,0.9883026531846857,0.9007314524555904,0.027603964117175042 +30,56,0.32142857142857145,0.9821428571428571,1.0,0.9444444444444444,0.9714285714285714,0.9809941520467838,0.9767025089605734,0.9592851089368167,0.0369718805280747 +37,43,0.5348837209302325,0.8372093023255814,0.9444444444444444,0.7391304347826086,0.8292682926829268,0.9,0.9136438168932886,0.696745366888215,0.15414824132263785 +35,38,0.7631578947368421,0.8947368421052632,0.9032258064516129,0.9655172413793104,0.9333333333333333,0.9693486590038315,0.9921059585149952,0.6933201520991935,0.07486361338542762 +41,36,0.4722222222222222,0.9722222222222222,1.0,0.9411764705882353,0.9696969696969697,0.9938080495356038,0.9938080495356038,0.945577943407535,0.032185687482793046 +44,36,0.5,0.9166666666666666,0.9411764705882353,0.8888888888888888,0.9142857142857143,0.9876543209876543,0.9872494075602952,0.8346223261119858,0.04977443231283995 +49,32,0.34375,0.96875,0.9166666666666666,1.0,0.9565217391304348,0.9956709956709956,0.9924242424242424,0.9343531843023135,0.03103818954401077 +39,32,0.5625,0.96875,0.9473684210526315,1.0,0.972972972972973,1.0,1.0,0.9379228369755696,0.02519009805802744 +38,27,0.6666666666666666,0.7777777777777778,0.8,0.8888888888888888,0.8421052631578947,0.888888888888889,0.9502100840336136,0.4780914437337575,0.1384746732914565 +50,21,0.38095238095238093,0.9523809523809523,1.0,0.875,0.9333333333333333,1.0,1.0,0.9013878188659973,0.03054786135988341 +33,16,0.9375,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.015340673169459336 +47,16,0.625,0.875,0.9,0.9,0.9,0.9666666666666667,0.980909090909091,0.7333333333333333,0.08370998701642743 +43,10,0.5,0.9,1.0,0.8,0.8888888888888888,0.9600000000000001,0.9666666666666666,0.816496580927726,0.08761755190466188 +48,7,0.42857142857142855,1.0,1.0,1.0,1.0,1.0,1.0,1.0,0.0035793736676227616 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/area_stratified_pooled_model.md b/service/scripts/profiling/founding_potential/results/rq1_robustness/area_stratified_pooled_model.md new file mode 100644 index 00000000..660a8d4e --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/area_stratified_pooled_model.md @@ -0,0 +1,24 @@ +| group | n | founder_rate | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:--------|-----:|---------------:|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|-----------:| +| 32 | 1166 | 0.223842 | 0.9494 | 0.931624 | 0.835249 | 0.880808 | 0.966692 | 0.936441 | 0.850851 | 0.043689 | +| n. | 429 | 0.662005 | 0.923077 | 0.922559 | 0.964789 | 0.943201 | 0.984119 | 0.992482 | 0.826235 | 0.0546366 | +| 31 | 377 | 0.217507 | 0.94695 | 0.918919 | 0.829268 | 0.871795 | 0.972881 | 0.935687 | 0.840217 | 0.0453692 | +| 40 | 244 | 0.47541 | 0.909836 | 0.898305 | 0.913793 | 0.905983 | 0.961746 | 0.96426 | 0.819491 | 0.0795743 | +| 42 | 203 | 0.315271 | 0.926108 | 0.901639 | 0.859375 | 0.88 | 0.976956 | 0.963775 | 0.827161 | 0.0487798 | +| 46 | 157 | 0.694268 | 0.917197 | 0.95283 | 0.926606 | 0.939535 | 0.968272 | 0.984053 | 0.809095 | 0.0562651 | +| 51 | 133 | 0.233083 | 0.954887 | 0.931034 | 0.870968 | 0.9 | 0.970272 | 0.940936 | 0.871723 | 0.044781 | +| 34 | 120 | 0.341667 | 0.925 | 0.921053 | 0.853659 | 0.886076 | 0.977153 | 0.965067 | 0.831627 | 0.0524637 | +| 52 | 95 | 0.305263 | 0.957895 | 0.931034 | 0.931034 | 0.931034 | 0.99373 | 0.988303 | 0.900731 | 0.027604 | +| 30 | 56 | 0.321429 | 0.982143 | 1 | 0.944444 | 0.971429 | 0.980994 | 0.976703 | 0.959285 | 0.0369719 | +| 37 | 43 | 0.534884 | 0.837209 | 0.944444 | 0.73913 | 0.829268 | 0.9 | 0.913644 | 0.696745 | 0.154148 | +| 35 | 38 | 0.763158 | 0.894737 | 0.903226 | 0.965517 | 0.933333 | 0.969349 | 0.992106 | 0.69332 | 0.0748636 | +| 41 | 36 | 0.472222 | 0.972222 | 1 | 0.941176 | 0.969697 | 0.993808 | 0.993808 | 0.945578 | 0.0321857 | +| 44 | 36 | 0.5 | 0.916667 | 0.941176 | 0.888889 | 0.914286 | 0.987654 | 0.987249 | 0.834622 | 0.0497744 | +| 49 | 32 | 0.34375 | 0.96875 | 0.916667 | 1 | 0.956522 | 0.995671 | 0.992424 | 0.934353 | 0.0310382 | +| 39 | 32 | 0.5625 | 0.96875 | 0.947368 | 1 | 0.972973 | 1 | 1 | 0.937923 | 0.0251901 | +| 38 | 27 | 0.666667 | 0.777778 | 0.8 | 0.888889 | 0.842105 | 0.888889 | 0.95021 | 0.478091 | 0.138475 | +| 50 | 21 | 0.380952 | 0.952381 | 1 | 0.875 | 0.933333 | 1 | 1 | 0.901388 | 0.0305479 | +| 33 | 16 | 0.9375 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0.0153407 | +| 47 | 16 | 0.625 | 0.875 | 0.9 | 0.9 | 0.9 | 0.966667 | 0.980909 | 0.733333 | 0.08371 | +| 43 | 10 | 0.5 | 0.9 | 1 | 0.8 | 0.888889 | 0.96 | 0.966667 | 0.816497 | 0.0876176 | +| 48 | 7 | 0.428571 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0.00357937 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/bootstrap_ci.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/bootstrap_ci.csv new file mode 100644 index 00000000..d6d11811 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/bootstrap_ci.csv @@ -0,0 +1,9 @@ +,point_estimate,ci95_low,ci95_high +accuracy,0.9366474689299787,0.9284555926038193,0.9451348893604122 +precision,0.926271186440678,0.9112063996289643,0.9408187198226067 +recall,0.8995884773662551,0.8825876445799337,0.9156638830280204 +f1,0.9127348643006263,0.9005372458914456,0.9239454361275332 +roc_auc,0.9776117074634882,0.9730446608169061,0.9819179575346694 +pr_auc,0.9705838681584741,0.9647752214620384,0.975897387247084 +mcc,0.8632522856286617,0.8448324894247283,0.8805182738534791 +brier,0.05082471982015067,0.045421652957712146,0.05632171601136752 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/bootstrap_ci.md b/service/scripts/profiling/founding_potential/results/rq1_robustness/bootstrap_ci.md new file mode 100644 index 00000000..47d8b598 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/bootstrap_ci.md @@ -0,0 +1,10 @@ +| | point_estimate | ci95_low | ci95_high | +|:----------|-----------------:|-----------:|------------:| +| accuracy | 0.936647 | 0.928456 | 0.945135 | +| precision | 0.926271 | 0.911206 | 0.940819 | +| recall | 0.899588 | 0.882588 | 0.915664 | +| f1 | 0.912735 | 0.900537 | 0.923945 | +| roc_auc | 0.977612 | 0.973045 | 0.981918 | +| pr_auc | 0.970584 | 0.964775 | 0.975897 | +| mcc | 0.863252 | 0.844832 | 0.880518 | +| brier | 0.0508247 | 0.0454217 | 0.0563217 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_dummy_most_frequent.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_dummy_most_frequent.csv new file mode 100644 index 00000000..ee4bc58f --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_dummy_most_frequent.csv @@ -0,0 +1,9 @@ +,mean,std,ci95_low,ci95_high +accuracy,0.6315629945381027,0.000152607314577894,0.6314292283290328,0.6316967607471726 +precision,0.0,0.0,0.0,0.0 +recall,0.0,0.0,0.0,0.0 +f1,0.0,0.0,0.0,0.0 +roc_auc,0.5,0.0,0.5,0.5 +pr_auc,0.3684370054618973,0.000152607314577894,0.36830323925282743,0.36857077167096713 +mcc,0.0,0.0,0.0,0.0 +brier,0.3684370054618973,0.000152607314577894,0.36830323925282743,0.36857077167096713 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_lightgbm.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_lightgbm.csv new file mode 100644 index 00000000..57c7332e --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_lightgbm.csv @@ -0,0 +1,9 @@ +,mean,std,ci95_low,ci95_high +accuracy,0.9301560040521679,0.004832569968831805,0.9259200697092858,0.9343919383950501 +precision,0.9210205005213952,0.005363091113689678,0.916319543891899,0.9257214571508914 +recall,0.8864569796404591,0.011327284656886847,0.8765281768710896,0.8963857824098286 +f1,0.9033804575410747,0.007077308370071776,0.8971769232366968,0.9095839918454525 +roc_auc,0.9778044083998637,0.002580893205000624,0.9755421557614367,0.9800666610382908 +pr_auc,0.969958390900661,0.0030785333991232323,0.9672599373996954,0.9726568444016267 +mcc,0.8491361246489078,0.01056040568851125,0.839879520933029,0.8583927283647865 +brier,0.05229056699624248,0.002611979994158263,0.05000106558570199,0.05458006840678297 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_logistic_regression.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_logistic_regression.csv new file mode 100644 index 00000000..7ff62904 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_logistic_regression.csv @@ -0,0 +1,9 @@ +,mean,std,ci95_low,ci95_high +accuracy,0.877833994571007,0.005709536471229038,0.8728293651964915,0.8828386239455225 +precision,0.8241154301590724,0.008895746233050398,0.8163179647902986,0.8319128955278462 +recall,0.849927442061945,0.015153152825682954,0.8366451179836104,0.8632097661402797 +f1,0.8367420177360618,0.008288518311350008,0.8294768111083051,0.8440072243638186 +roc_auc,0.941702178253095,0.006210328162763004,0.9362585856067633,0.9471457708994266 +pr_auc,0.922607131065136,0.0063617129672597535,0.9170308437870672,0.9281834183432048 +mcc,0.7395022800023918,0.012603583626827284,0.7284547518605137,0.75054980814427 +brier,0.0913441224489286,0.003520196889471585,0.08825853382962423,0.09442971106823297 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_random_forest.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_random_forest.csv new file mode 100644 index 00000000..415a85d4 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_random_forest.csv @@ -0,0 +1,9 @@ +,mean,std,ci95_low,ci95_high +accuracy,0.8924456590572405,0.00651487700889904,0.8867351175773166,0.8981562005371644 +precision,0.8727333377136273,0.007422272623764793,0.866227428908992,0.8792392465182626 +recall,0.829030079055664,0.01844236050077116,0.8128646373315136,0.8451955207798143 +f1,0.850223748276734,0.010349709747713121,0.8411518276957687,0.8592956688576993 +roc_auc,0.9527710767910506,0.006542740503664845,0.9470361118811189,0.9585060417009822 +pr_auc,0.9358309508430764,0.00643481567167842,0.9301905862193713,0.9414713154667815 +mcc,0.7671314169694046,0.014522057546517971,0.7544022722933108,0.7798605616454983 +brier,0.08755658794676884,0.0029756638450860926,0.08494830358553487,0.0901648723080028 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_summary_mean.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_summary_mean.csv new file mode 100644 index 00000000..7a3e0872 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_summary_mean.csv @@ -0,0 +1,6 @@ +,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +dummy_most_frequent,0.6315629945381027,0.0,0.0,0.0,0.5,0.3684370054618973,0.0,0.3684370054618973 +logistic_regression,0.877833994571007,0.8241154301590724,0.849927442061945,0.8367420177360618,0.941702178253095,0.922607131065136,0.7395022800023918,0.0913441224489286 +random_forest,0.8924456590572405,0.8727333377136273,0.829030079055664,0.850223748276734,0.9527710767910506,0.9358309508430764,0.7671314169694046,0.08755658794676884 +xgboost,0.9277916328357951,0.9135406959068092,0.8881029348061512,0.9005883623006266,0.9767097128228892,0.9683117817597591,0.8441820066940338,0.05477161929011345 +lightgbm,0.9301560040521679,0.9210205005213952,0.8864569796404591,0.9033804575410747,0.9778044083998637,0.969958390900661,0.8491361246489078,0.05229056699624248 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_summary_mean.md b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_summary_mean.md new file mode 100644 index 00000000..6aa04ddc --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_summary_mean.md @@ -0,0 +1,7 @@ +| | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:--------------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|----------:| +| dummy_most_frequent | 0.631563 | 0 | 0 | 0 | 0.5 | 0.368437 | 0 | 0.368437 | +| logistic_regression | 0.877834 | 0.824115 | 0.849927 | 0.836742 | 0.941702 | 0.922607 | 0.739502 | 0.0913441 | +| random_forest | 0.892446 | 0.872733 | 0.82903 | 0.850224 | 0.952771 | 0.935831 | 0.767131 | 0.0875566 | +| xgboost | 0.927792 | 0.913541 | 0.888103 | 0.900588 | 0.97671 | 0.968312 | 0.844182 | 0.0547716 | +| lightgbm | 0.930156 | 0.921021 | 0.886457 | 0.90338 | 0.977804 | 0.969958 | 0.849136 | 0.0522906 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_xgboost.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_xgboost.csv new file mode 100644 index 00000000..4be5a477 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/cv_xgboost.csv @@ -0,0 +1,9 @@ +,mean,std,ci95_low,ci95_high +accuracy,0.9277916328357951,0.003551960767446554,0.9246782019498614,0.9309050637217289 +precision,0.9135406959068092,0.0028831677666106537,0.9110134879330716,0.9160679038805468 +recall,0.8881029348061512,0.01305781968580872,0.8766572512036331,0.8995486184086693 +f1,0.9005883623006266,0.005702534790830589,0.8955898701695755,0.9055868544316776 +roc_auc,0.9767097128228892,0.0033082724285164174,0.9738098841838948,0.9796095414618836 +pr_auc,0.9683117817597591,0.003612163522900202,0.9651455808320035,0.9714779826875146 +mcc,0.8441820066940338,0.00794620970622261,0.8372168467879335,0.851147166600134 +brier,0.05477161929011345,0.0026008881508963405,0.05249184030886049,0.057051398271366405 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/per_area_specialist_vs_pooled.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/per_area_specialist_vs_pooled.csv new file mode 100644 index 00000000..018cf39b --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/per_area_specialist_vs_pooled.csv @@ -0,0 +1,15 @@ +area,model,n_train,n_test,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +32,specialist,4721.0,1181,0.930567315834039,0.8629032258064516,0.816793893129771,0.8392156862745098,0.9673267491215974,0.9292015553816835,0.7954692332100317,0.0519155166539892 +32,pooled_on_subset,,1166,0.9493996569468267,0.9316239316239316,0.8352490421455939,0.8808080808080808,0.9666920683304757,0.9364408340780385,0.8508506430002786,0.04368896580612041 +31,specialist,1500.0,375,0.9253333333333333,0.8767123287671232,0.7710843373493976,0.8205128205128205,0.952962535071794,0.8952200307899209,0.776160027639481,0.06495098958516522 +31,pooled_on_subset,,377,0.946949602122016,0.918918918918919,0.8292682926829268,0.8717948717948718,0.9728813559322034,0.9356866199037027,0.8402167428448224,0.04536923541973955 +40,specialist,1022.0,256,0.83984375,0.8571428571428571,0.8095238095238095,0.8326530612244898,0.9236263736263736,0.9331645942069452,0.6803555888841176,0.12703101416739418 +40,pooled_on_subset,,244,0.9098360655737705,0.8983050847457628,0.9137931034482759,0.905982905982906,0.9617456896551724,0.9642595097786962,0.8194913688077033,0.07957434518007606 +42,specialist,775.0,194,0.8969072164948454,0.88,0.7586206896551724,0.8148148148148148,0.9349645030425964,0.8994204511987712,0.7478616876796342,0.08982080462945383 +42,pooled_on_subset,,203,0.9261083743842364,0.9016393442622951,0.859375,0.88,0.9769559352517986,0.9637751383174913,0.8271608292650046,0.048779758321450296 +46,specialist,658.0,165,0.9090909090909091,0.9454545454545454,0.9203539823008849,0.9327354260089686,0.9406058543226685,0.9674811594039668,0.7933093260902778,0.08051958369056347 +46,pooled_on_subset,,157,0.9171974522292994,0.9528301886792453,0.926605504587156,0.9395348837209302,0.9682721712538226,0.9840532918333846,0.8090948889478105,0.05626512209498496 +51,specialist,513.0,129,0.875968992248062,0.7272727272727273,0.7741935483870968,0.75,0.9186965108624096,0.8476593718423702,0.6682097848250941,0.100902416618966 +51,pooled_on_subset,,133,0.9548872180451128,0.9310344827586207,0.8709677419354839,0.9,0.970271979759646,0.9409363609392009,0.8717228983609421,0.04478101537130266 +34,specialist,462.0,116,0.9051724137931034,0.896551724137931,0.7647058823529411,0.8253968253968254,0.9540889526542324,0.9090455749994415,0.765404529471217,0.07917537304289644 +34,pooled_on_subset,,120,0.925,0.9210526315789473,0.8536585365853658,0.8860759493670886,0.9771534424205001,0.9650667269791089,0.8316270648620494,0.05246369285584714 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/per_area_specialist_vs_pooled.md b/service/scripts/profiling/founding_potential/results/rq1_robustness/per_area_specialist_vs_pooled.md new file mode 100644 index 00000000..da15cdff --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/per_area_specialist_vs_pooled.md @@ -0,0 +1,16 @@ +| | n_train | n_test | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:---------------------------|----------:|---------:|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|----------:| +| ('32', 'specialist') | 4721 | 1181 | 0.930567 | 0.862903 | 0.816794 | 0.839216 | 0.967327 | 0.929202 | 0.795469 | 0.0519155 | +| ('32', 'pooled_on_subset') | nan | 1166 | 0.9494 | 0.931624 | 0.835249 | 0.880808 | 0.966692 | 0.936441 | 0.850851 | 0.043689 | +| ('31', 'specialist') | 1500 | 375 | 0.925333 | 0.876712 | 0.771084 | 0.820513 | 0.952963 | 0.89522 | 0.77616 | 0.064951 | +| ('31', 'pooled_on_subset') | nan | 377 | 0.94695 | 0.918919 | 0.829268 | 0.871795 | 0.972881 | 0.935687 | 0.840217 | 0.0453692 | +| ('40', 'specialist') | 1022 | 256 | 0.839844 | 0.857143 | 0.809524 | 0.832653 | 0.923626 | 0.933165 | 0.680356 | 0.127031 | +| ('40', 'pooled_on_subset') | nan | 244 | 0.909836 | 0.898305 | 0.913793 | 0.905983 | 0.961746 | 0.96426 | 0.819491 | 0.0795743 | +| ('42', 'specialist') | 775 | 194 | 0.896907 | 0.88 | 0.758621 | 0.814815 | 0.934965 | 0.89942 | 0.747862 | 0.0898208 | +| ('42', 'pooled_on_subset') | nan | 203 | 0.926108 | 0.901639 | 0.859375 | 0.88 | 0.976956 | 0.963775 | 0.827161 | 0.0487798 | +| ('46', 'specialist') | 658 | 165 | 0.909091 | 0.945455 | 0.920354 | 0.932735 | 0.940606 | 0.967481 | 0.793309 | 0.0805196 | +| ('46', 'pooled_on_subset') | nan | 157 | 0.917197 | 0.95283 | 0.926606 | 0.939535 | 0.968272 | 0.984053 | 0.809095 | 0.0562651 | +| ('51', 'specialist') | 513 | 129 | 0.875969 | 0.727273 | 0.774194 | 0.75 | 0.918697 | 0.847659 | 0.66821 | 0.100902 | +| ('51', 'pooled_on_subset') | nan | 133 | 0.954887 | 0.931034 | 0.870968 | 0.9 | 0.970272 | 0.940936 | 0.871723 | 0.044781 | +| ('34', 'specialist') | 462 | 116 | 0.905172 | 0.896552 | 0.764706 | 0.825397 | 0.954089 | 0.909046 | 0.765405 | 0.0791754 | +| ('34', 'pooled_on_subset') | nan | 120 | 0.925 | 0.921053 | 0.853659 | 0.886076 | 0.977153 | 0.965067 | 0.831627 | 0.0524637 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/plots/calibration.png b/service/scripts/profiling/founding_potential/results/rq1_robustness/plots/calibration.png new file mode 100644 index 00000000..a610a4f1 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1_robustness/plots/calibration.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/plots/smoketest_calibration.png b/service/scripts/profiling/founding_potential/results/rq1_robustness/plots/smoketest_calibration.png new file mode 100644 index 00000000..a96a3ebe Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1_robustness/plots/smoketest_calibration.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/tuning_best_params.json b/service/scripts/profiling/founding_potential/results/rq1_robustness/tuning_best_params.json new file mode 100644 index 00000000..de3c488b --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/tuning_best_params.json @@ -0,0 +1,24 @@ +{ + "random_forest": { + "max_depth": 15, + "max_features": 0.4931994274157803, + "min_samples_leaf": 1, + "n_estimators": 720 + }, + "xgboost": { + "colsample_bytree": 0.8608647605824367, + "learning_rate": 0.05483713475230159, + "max_depth": 8, + "min_child_weight": 7, + "n_estimators": 542, + "subsample": 0.8842651558743149 + }, + "lightgbm": { + "colsample_bytree": 0.9436063712881633, + "learning_rate": 0.09972083578077036, + "min_child_samples": 41, + "n_estimators": 611, + "num_leaves": 17, + "subsample": 0.9043140194467589 + } +} \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/tuning_comparison.csv b/service/scripts/profiling/founding_potential/results/rq1_robustness/tuning_comparison.csv new file mode 100644 index 00000000..1da9f835 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/tuning_comparison.csv @@ -0,0 +1,7 @@ +model,variant,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +random_forest,default,0.8957259775689603,0.8731790916880892,0.8386831275720165,0.855583543240974,0.951964210958666,0.9349680824025975,0.7744264740411075,0.08763717778689288 +random_forest,tuned,0.9151257956956653,0.8905597326649958,0.8773662551440329,0.8839137645107794,0.9648383134680854,0.9532390244050343,0.8170865290519,0.06774435426181988 +xgboost,default,0.9269475598666262,0.907190635451505,0.8930041152263375,0.9000414765657404,0.9744139159419603,0.9665730556966816,0.8425529635211692,0.05556803196668625 +xgboost,tuned,0.9305850257653835,0.9163851351351351,0.8930041152263375,0.9045435598165903,0.9780860248177374,0.971164830473292,0.8501963188015546,0.05061671882867813 +lightgbm,default,0.9296756592906942,0.913372582001682,0.8938271604938272,0.9034941763727121,0.976269322211954,0.9685049361518786,0.8483100198135644,0.053432731044197566 +lightgbm,tuned,0.9366474689299787,0.926271186440678,0.8995884773662551,0.9127348643006263,0.9776117074634882,0.9705838681584741,0.8632522856286617,0.05082471982015067 diff --git a/service/scripts/profiling/founding_potential/results/rq1_robustness/tuning_comparison.md b/service/scripts/profiling/founding_potential/results/rq1_robustness/tuning_comparison.md new file mode 100644 index 00000000..2d1ff617 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_robustness/tuning_comparison.md @@ -0,0 +1,8 @@ +| | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:-----------------------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|----------:| +| ('random_forest', 'default') | 0.895726 | 0.873179 | 0.838683 | 0.855584 | 0.951964 | 0.934968 | 0.774426 | 0.0876372 | +| ('random_forest', 'tuned') | 0.915126 | 0.89056 | 0.877366 | 0.883914 | 0.964838 | 0.953239 | 0.817087 | 0.0677444 | +| ('xgboost', 'default') | 0.926948 | 0.907191 | 0.893004 | 0.900041 | 0.974414 | 0.966573 | 0.842553 | 0.055568 | +| ('xgboost', 'tuned') | 0.930585 | 0.916385 | 0.893004 | 0.904544 | 0.978086 | 0.971165 | 0.850196 | 0.0506167 | +| ('lightgbm', 'default') | 0.929676 | 0.913373 | 0.893827 | 0.903494 | 0.976269 | 0.968505 | 0.84831 | 0.0534327 | +| ('lightgbm', 'tuned') | 0.936647 | 0.926271 | 0.899588 | 0.912735 | 0.977612 | 0.970584 | 0.863252 | 0.0508247 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/attrition.csv b/service/scripts/profiling/founding_potential/results/rq1_symmetric/attrition.csv new file mode 100644 index 00000000..f248f550 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/attrition.csv @@ -0,0 +1,10 @@ +,0 +initial,16822 +no_publication_anchor,1430 +implausible_profile_founders,425 +implausible_profile_nonfounders,770 +founder_bad_founding_year,340 +founder_bad_career_age,723 +duplicates,0 +below_min_pubs_at_index_founders,1112 +below_min_pubs_at_index_nonfounders,3005 diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/leave_one_institution_out.csv b/service/scripts/profiling/founding_potential/results/rq1_symmetric/leave_one_institution_out.csv new file mode 100644 index 00000000..8651c0c4 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/leave_one_institution_out.csv @@ -0,0 +1,25 @@ +held_out_institution,model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +berkeley,random_forest,0.7659914712153518,0.5685019206145967,0.8131868131868132,0.6691785983421251,0.8547619047619047,0.7330881372592069,0.5158519325545086,0.16281251622327844 +berkeley,xgboost,0.7915778251599147,0.6086956521739131,0.7948717948717948,0.6894360603653693,0.8576069294114407,0.741586799531578,0.5475397548573835,0.15189167857170105 +berkeley,lightgbm,0.7814498933901919,0.603030303030303,0.7289377289377289,0.6600331674958541,0.8499407860310114,0.7350659292472954,0.5059997706165712,0.149555122726439 +harvard,random_forest,0.8015873015873016,0.5753968253968254,0.6430155210643016,0.6073298429319371,0.8438771689504753,0.6573849413778056,0.4764456796429979,0.13855781340944884 +harvard,xgboost,0.8317460317460318,0.639412997903564,0.6762749445676275,0.6573275862068966,0.8633058495598539,0.7000843424710989,0.5463194583057209,0.12460028380155563 +harvard,lightgbm,0.8232804232804233,0.6297117516629712,0.6297117516629712,0.6297117516629712,0.8558049520099724,0.6972393890872501,0.5136589372084889,0.12547720520401978 +muenchen,random_forest,0.7048832271762208,0.3446327683615819,0.7261904761904762,0.4674329501915709,0.8093392395717978,0.5006448114650062,0.33705579573522043,0.18923399440055652 +muenchen,xgboost,0.7537154989384289,0.3987341772151899,0.75,0.5206611570247934,0.815983757844223,0.5242557891617051,0.40904820462844466,0.17195990681648254 +muenchen,lightgbm,0.7515923566878981,0.3877551020408163,0.6785714285714286,0.4935064935064935,0.8122615971453181,0.5315550160005521,0.36847815988949306,0.16975197463720118 +oxford,random_forest,0.810580204778157,0.5217391304347826,0.6638297872340425,0.5842696629213483,0.842834760099003,0.6280461770360506,0.46953140892760215,0.14220733689789294 +oxford,xgboost,0.8071672354948806,0.5143769968051118,0.6851063829787234,0.5875912408759124,0.8486750380344694,0.6214727528224875,0.47319748971740944,0.13802118599414825 +oxford,lightgbm,0.8097269624573379,0.5204081632653061,0.6510638297872341,0.5784499054820416,0.8384114080701197,0.6202413328309154,0.46233779542365877,0.13681269230308113 +stanford,random_forest,0.7999124343257443,0.6654676258992805,0.757162346521146,0.7083599234205488,0.8740450864336963,0.7770736844626708,0.559726885687933,0.1423877302619292 +stanford,xgboost,0.8161120840630472,0.6968553459119496,0.7557980900409277,0.725130890052356,0.8832241312430565,0.7934283229232462,0.5884073929950523,0.1302448958158493 +stanford,lightgbm,0.8174255691768827,0.7101063829787234,0.7285129604365621,0.7191919191919192,0.8779553392917301,0.7934392862498869,0.5840718041855218,0.12889088179596303 +telaviv,random_forest,0.8055045871559633,0.5268817204301075,0.8448275862068966,0.6490066225165563,0.8872076199662406,0.7267052998356232,0.5522425615484207,0.1500184971892688 +telaviv,xgboost,0.818348623853211,0.5485714285714286,0.8275862068965517,0.6597938144329897,0.8876095169198617,0.7248530755500643,0.5640840249079071,0.13506236672401428 +telaviv,lightgbm,0.8330275229357799,0.5786163522012578,0.7931034482758621,0.6690909090909091,0.8872679045092838,0.71419228864805,0.5735279705588365,0.1302984120003824 +toronto,random_forest,0.8146067415730337,0.6116504854368932,0.7078651685393258,0.65625,0.8560998190464166,0.6936734754252618,0.5329012857891868,0.13855628609953433 +toronto,xgboost,0.827247191011236,0.6424870466321243,0.6966292134831461,0.6684636118598383,0.8769936455834701,0.7440046539927276,0.5527384390144401,0.12293894588947296 +toronto,lightgbm,0.8300561797752809,0.6557377049180327,0.6741573033707865,0.6648199445983379,0.8650422926398182,0.7332005081345564,0.5511152657981175,0.12259775056412968 +ude,random_forest,0.7611940298507462,0.2222222222222222,0.6666666666666666,0.3333333333333333,0.8497267759562841,0.46781609195402296,0.28160810322078966,0.15533642564799244 +ude,xgboost,0.7313432835820896,0.2,0.6666666666666666,0.3076923076923077,0.896174863387978,0.6018037518037518,0.25232323607491686,0.13626053929328918 +ude,lightgbm,0.835820895522388,0.3333333333333333,0.8333333333333334,0.47619047619047616,0.9262295081967212,0.6456682206682207,0.4585410702748071,0.1221060265372392 diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/leave_one_institution_out.md b/service/scripts/profiling/founding_potential/results/rq1_symmetric/leave_one_institution_out.md new file mode 100644 index 00000000..89688aa7 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/leave_one_institution_out.md @@ -0,0 +1,26 @@ +| | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:------------------------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|---------:| +| ('berkeley', 'random_forest') | 0.765991 | 0.568502 | 0.813187 | 0.669179 | 0.854762 | 0.733088 | 0.515852 | 0.162813 | +| ('berkeley', 'xgboost') | 0.791578 | 0.608696 | 0.794872 | 0.689436 | 0.857607 | 0.741587 | 0.54754 | 0.151892 | +| ('berkeley', 'lightgbm') | 0.78145 | 0.60303 | 0.728938 | 0.660033 | 0.849941 | 0.735066 | 0.506 | 0.149555 | +| ('harvard', 'random_forest') | 0.801587 | 0.575397 | 0.643016 | 0.60733 | 0.843877 | 0.657385 | 0.476446 | 0.138558 | +| ('harvard', 'xgboost') | 0.831746 | 0.639413 | 0.676275 | 0.657328 | 0.863306 | 0.700084 | 0.546319 | 0.1246 | +| ('harvard', 'lightgbm') | 0.82328 | 0.629712 | 0.629712 | 0.629712 | 0.855805 | 0.697239 | 0.513659 | 0.125477 | +| ('muenchen', 'random_forest') | 0.704883 | 0.344633 | 0.72619 | 0.467433 | 0.809339 | 0.500645 | 0.337056 | 0.189234 | +| ('muenchen', 'xgboost') | 0.753715 | 0.398734 | 0.75 | 0.520661 | 0.815984 | 0.524256 | 0.409048 | 0.17196 | +| ('muenchen', 'lightgbm') | 0.751592 | 0.387755 | 0.678571 | 0.493506 | 0.812262 | 0.531555 | 0.368478 | 0.169752 | +| ('oxford', 'random_forest') | 0.81058 | 0.521739 | 0.66383 | 0.58427 | 0.842835 | 0.628046 | 0.469531 | 0.142207 | +| ('oxford', 'xgboost') | 0.807167 | 0.514377 | 0.685106 | 0.587591 | 0.848675 | 0.621473 | 0.473197 | 0.138021 | +| ('oxford', 'lightgbm') | 0.809727 | 0.520408 | 0.651064 | 0.57845 | 0.838411 | 0.620241 | 0.462338 | 0.136813 | +| ('stanford', 'random_forest') | 0.799912 | 0.665468 | 0.757162 | 0.70836 | 0.874045 | 0.777074 | 0.559727 | 0.142388 | +| ('stanford', 'xgboost') | 0.816112 | 0.696855 | 0.755798 | 0.725131 | 0.883224 | 0.793428 | 0.588407 | 0.130245 | +| ('stanford', 'lightgbm') | 0.817426 | 0.710106 | 0.728513 | 0.719192 | 0.877955 | 0.793439 | 0.584072 | 0.128891 | +| ('telaviv', 'random_forest') | 0.805505 | 0.526882 | 0.844828 | 0.649007 | 0.887208 | 0.726705 | 0.552243 | 0.150018 | +| ('telaviv', 'xgboost') | 0.818349 | 0.548571 | 0.827586 | 0.659794 | 0.88761 | 0.724853 | 0.564084 | 0.135062 | +| ('telaviv', 'lightgbm') | 0.833028 | 0.578616 | 0.793103 | 0.669091 | 0.887268 | 0.714192 | 0.573528 | 0.130298 | +| ('toronto', 'random_forest') | 0.814607 | 0.61165 | 0.707865 | 0.65625 | 0.8561 | 0.693673 | 0.532901 | 0.138556 | +| ('toronto', 'xgboost') | 0.827247 | 0.642487 | 0.696629 | 0.668464 | 0.876994 | 0.744005 | 0.552738 | 0.122939 | +| ('toronto', 'lightgbm') | 0.830056 | 0.655738 | 0.674157 | 0.66482 | 0.865042 | 0.733201 | 0.551115 | 0.122598 | +| ('ude', 'random_forest') | 0.761194 | 0.222222 | 0.666667 | 0.333333 | 0.849727 | 0.467816 | 0.281608 | 0.155336 | +| ('ude', 'xgboost') | 0.731343 | 0.2 | 0.666667 | 0.307692 | 0.896175 | 0.601804 | 0.252323 | 0.136261 | +| ('ude', 'lightgbm') | 0.835821 | 0.333333 | 0.833333 | 0.47619 | 0.92623 | 0.645668 | 0.458541 | 0.122106 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/model_comparison.csv b/service/scripts/profiling/founding_potential/results/rq1_symmetric/model_comparison.csv new file mode 100644 index 00000000..117c8687 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/model_comparison.csv @@ -0,0 +1,12 @@ +model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +xgboost,0.8109756097560976,0.6187845303867403,0.7148936170212766,0.6633761105626851,0.8744266164789946,0.7255112168344391,0.535600710851566,0.13085858523845673 +catboost,0.815410199556541,0.6280373831775701,0.7148936170212766,0.6686567164179105,0.871187278701075,0.7229265033400272,0.5436498796133824,0.13308676740102443 +stacking_ensemble,0.8037694013303769,0.5966666666666667,0.7617021276595745,0.6691588785046729,0.8746578838240453,0.7221343045005837,0.5406113773836111,0.142284840741808 +lightgbm,0.8131929046563193,0.631163708086785,0.6808510638297872,0.6550665301944729,0.8649303008070434,0.7109401478953907,0.5279418324593667,0.13163652604161835 +random_forest,0.8004434589800443,0.5964912280701754,0.723404255319149,0.6538461538461539,0.8562202941082651,0.6943350744935747,0.5202066710761617,0.14630692947159313 +logistic_regression,0.791019955654102,0.5800344234079173,0.7170212765957447,0.6412940057088488,0.8414096143417653,0.6700032178346078,0.5017166095581281,0.15290085408182966 +svm_rbf,0.8143015521064302,0.6890756302521008,0.5234042553191489,0.5949214026602176,0.8371830042425596,0.6614524901098019,0.4849583299023803,0.13297057050989966 +decision_tree,0.7677383592017738,0.5432937181663837,0.6808510638297872,0.6043437204910292,0.8050360458068837,0.6053416508022843,0.44853834701792206,0.1718711633992893 +knn,0.7854767184035477,0.6627450980392157,0.3595744680851064,0.46620689655172415,0.7970429678777633,0.5621734577170925,0.3718006264996696,0.1496230598669623 +gaussian_nb,0.75,0.5664335664335665,0.1723404255319149,0.2642740619902121,0.778106957159718,0.5088246146088554,0.20449108478440964,0.24867163360596548 +dummy_most_frequent,0.7394678492239468,0.0,0.0,0.0,0.5,0.26053215077605324,0.0,0.26053215077605324 diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/model_comparison.md b/service/scripts/profiling/founding_potential/results/rq1_symmetric/model_comparison.md new file mode 100644 index 00000000..85fea510 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/model_comparison.md @@ -0,0 +1,13 @@ +| model | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:--------------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|---------:| +| xgboost | 0.810976 | 0.618785 | 0.714894 | 0.663376 | 0.874427 | 0.725511 | 0.535601 | 0.130859 | +| catboost | 0.81541 | 0.628037 | 0.714894 | 0.668657 | 0.871187 | 0.722927 | 0.54365 | 0.133087 | +| stacking_ensemble | 0.803769 | 0.596667 | 0.761702 | 0.669159 | 0.874658 | 0.722134 | 0.540611 | 0.142285 | +| lightgbm | 0.813193 | 0.631164 | 0.680851 | 0.655067 | 0.86493 | 0.71094 | 0.527942 | 0.131637 | +| random_forest | 0.800443 | 0.596491 | 0.723404 | 0.653846 | 0.85622 | 0.694335 | 0.520207 | 0.146307 | +| logistic_regression | 0.79102 | 0.580034 | 0.717021 | 0.641294 | 0.84141 | 0.670003 | 0.501717 | 0.152901 | +| svm_rbf | 0.814302 | 0.689076 | 0.523404 | 0.594921 | 0.837183 | 0.661452 | 0.484958 | 0.132971 | +| decision_tree | 0.767738 | 0.543294 | 0.680851 | 0.604344 | 0.805036 | 0.605342 | 0.448538 | 0.171871 | +| knn | 0.785477 | 0.662745 | 0.359574 | 0.466207 | 0.797043 | 0.562173 | 0.371801 | 0.149623 | +| gaussian_nb | 0.75 | 0.566434 | 0.17234 | 0.264274 | 0.778107 | 0.508825 | 0.204491 | 0.248672 | +| dummy_most_frequent | 0.739468 | 0 | 0 | 0 | 0.5 | 0.260532 | 0 | 0.260532 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/models/reference_score_quantiles.csv b/service/scripts/profiling/founding_potential/results/rq1_symmetric/models/reference_score_quantiles.csv new file mode 100644 index 00000000..d11f17d9 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/models/reference_score_quantiles.csv @@ -0,0 +1,1002 @@ +quantile,score +0.0,0.001799774239771068 +0.001,0.0037632015310227872 +0.002,0.004952380336821079 +0.003,0.005867551300674677 +0.004,0.006545982118695975 +0.005,0.007157282643020153 +0.006,0.007377700336277485 +0.007,0.007953032940626145 +0.008,0.008392722778022289 +0.009000000000000001,0.008771535620093345 +0.01,0.009130241088569165 +0.011,0.009676615118980405 +0.012,0.010122963160276414 +0.013000000000000001,0.01044721794873476 +0.014,0.010709293216466903 +0.015,0.011032252497971058 +0.016,0.011484382875263691 +0.017,0.01174390633404255 +0.018000000000000002,0.012157029360532761 +0.019,0.012537506878376008 +0.02,0.013113726116716861 +0.021,0.01346417072415352 +0.022,0.013826141901314258 +0.023,0.01403572330623865 +0.024,0.014331898123025894 +0.025,0.014568334631621837 +0.026000000000000002,0.014730283252894879 +0.027,0.014977157287299633 +0.028,0.01542920358479023 +0.029,0.015658036336302757 +0.03,0.0160920799523592 +0.031,0.016468267634510994 +0.032,0.01692380814254284 +0.033,0.0172864638119936 +0.034,0.01748241350054741 +0.035,0.01772677905857563 +0.036000000000000004,0.01799752199649811 +0.037,0.018203632965683936 +0.038,0.01847769160568714 +0.039,0.018807970002293586 +0.04,0.019110214486718177 +0.041,0.019433548465371132 +0.042,0.01960417187213898 +0.043000000000000003,0.019891394898295403 +0.044,0.020149678230285645 +0.045,0.02037010096013546 +0.046,0.020537120923399925 +0.047,0.020694837421178818 +0.048,0.020880491688847543 +0.049,0.02103546704351902 +0.05,0.021228662878274917 +0.051000000000000004,0.021361384451389312 +0.052000000000000005,0.02158778004348278 +0.053,0.021768898531794548 +0.054,0.021965895354747772 +0.055,0.022184690088033678 +0.056,0.022568271070718765 +0.057,0.022845994845032695 +0.058,0.02307553055882454 +0.059000000000000004,0.02328108750283718 +0.06,0.0235644493997097 +0.061,0.023780523762106896 +0.062,0.024006491526961327 +0.063,0.024251287996768955 +0.064,0.024502543240785598 +0.065,0.024897176548838613 +0.066,0.025093491032719614 +0.067,0.02540058986842632 +0.068,0.025806276559829713 +0.069,0.026113471910357476 +0.07,0.026457807794213296 +0.07100000000000001,0.026752364501357078 +0.07200000000000001,0.02699142335355282 +0.073,0.027269881308078767 +0.074,0.027585648894309995 +0.075,0.0277952317148447 +0.076,0.028084583446383475 +0.077,0.028348408862948416 +0.078,0.028570656061172487 +0.079,0.02878624477982521 +0.08,0.028965909630060196 +0.081,0.02915022283792496 +0.082,0.02947177504003048 +0.083,0.02963654287159443 +0.084,0.029749847292900086 +0.085,0.030092677772045134 +0.08600000000000001,0.03024582676589489 +0.08700000000000001,0.03049208001792431 +0.088,0.030768383026123048 +0.089,0.030941577598452567 +0.09,0.03135098725557327 +0.091,0.03169582626223564 +0.092,0.031826734334230423 +0.093,0.0320123915374279 +0.094,0.03234054717421532 +0.095,0.032648768126964565 +0.096,0.03285433998703957 +0.097,0.03318222919106484 +0.098,0.033458974361419674 +0.099,0.03368625104427338 +0.1,0.03381631970405578 +0.101,0.034190950989723204 +0.10200000000000001,0.034432792991399765 +0.10300000000000001,0.034580241203308104 +0.10400000000000001,0.03478427591919899 +0.105,0.034913765043020246 +0.106,0.03503820750117302 +0.107,0.03524049457907677 +0.108,0.03537014743685722 +0.109,0.03569643300771713 +0.11,0.035877271592617034 +0.111,0.036078438937664034 +0.112,0.03618953463435173 +0.113,0.036397378355264666 +0.114,0.036597126305103304 +0.115,0.03678628191351891 +0.116,0.03699827417731285 +0.117,0.03720176878571511 +0.11800000000000001,0.03739843383431435 +0.11900000000000001,0.03764648774266243 +0.12,0.037882559746503834 +0.121,0.0380337353348732 +0.122,0.038359600752592087 +0.123,0.03877588424086571 +0.124,0.03890495365858078 +0.125,0.03924155980348587 +0.126,0.03952528405189514 +0.127,0.03966293403506279 +0.128,0.040054906904697415 +0.129,0.04030952769517899 +0.13,0.04067708283662796 +0.131,0.04089003029465675 +0.132,0.041119325071573266 +0.133,0.04147288927435876 +0.134,0.041721326261758805 +0.135,0.04202549830079079 +0.136,0.042322816252708444 +0.137,0.042554852932691574 +0.138,0.042770673334598545 +0.139,0.04300505447387695 +0.14,0.043252265751361846 +0.14100000000000001,0.043425149589776994 +0.14200000000000002,0.04368921858072281 +0.14300000000000002,0.04388861361145974 +0.14400000000000002,0.044045136064291 +0.145,0.0442833212018013 +0.146,0.044782417327165605 +0.147,0.045063872009515754 +0.148,0.0453217701613903 +0.149,0.0454915968477726 +0.15,0.04571421667933464 +0.151,0.04599049147963523 +0.152,0.04623621851205826 +0.153,0.046478530704975124 +0.154,0.04671492674946785 +0.155,0.0468931744992733 +0.156,0.04710728642344475 +0.157,0.04728644987940788 +0.158,0.04755470862984657 +0.159,0.04789931705594063 +0.16,0.04834123939275741 +0.161,0.0486644016802311 +0.162,0.049033038228750235 +0.163,0.04941255083680152 +0.164,0.049783708095550536 +0.165,0.05000649318099022 +0.166,0.050428809911012666 +0.167,0.050800343722105026 +0.168,0.05117288133502008 +0.169,0.05139155167341233 +0.17,0.05175404116511345 +0.171,0.05204714211821557 +0.17200000000000001,0.05264578142762185 +0.17300000000000001,0.05289514508843422 +0.17400000000000002,0.05324107870459557 +0.17500000000000002,0.05340349972248078 +0.176,0.053702236682176586 +0.177,0.05412084484100341 +0.178,0.05439290323853493 +0.179,0.05462264683842659 +0.18,0.05500235110521316 +0.181,0.055233252257108685 +0.182,0.05559154903888702 +0.183,0.0558575102686882 +0.184,0.056089143723249434 +0.185,0.056454131305217745 +0.186,0.056873185664415356 +0.187,0.057242512166500094 +0.188,0.057488087356090546 +0.189,0.0578707187473774 +0.19,0.05821270272135735 +0.191,0.05862997648119927 +0.192,0.05883529642224312 +0.193,0.05926912990212441 +0.194,0.05952774372696877 +0.195,0.060024325251579295 +0.196,0.060182039588689805 +0.197,0.06042983645200729 +0.198,0.060646534860134126 +0.199,0.06084814700484277 +0.2,0.06099446192383766 +0.201,0.06115688592195511 +0.202,0.061484630912542346 +0.203,0.06174753358960152 +0.20400000000000001,0.062123492002487186 +0.20500000000000002,0.06239884823560716 +0.20600000000000002,0.06291717624664307 +0.20700000000000002,0.06318496900796892 +0.20800000000000002,0.06366013622283936 +0.209,0.06385855281352996 +0.21,0.06408542454242706 +0.211,0.06448701453208923 +0.212,0.0650018401145935 +0.213,0.06526755279302597 +0.214,0.06554229432344437 +0.215,0.06585395961999893 +0.216,0.06602701151371002 +0.217,0.06639979809522628 +0.218,0.06668967038393021 +0.219,0.06711302024126052 +0.22,0.0674582514166832 +0.221,0.06766676712036133 +0.222,0.06797932857275009 +0.223,0.06832166302204132 +0.224,0.0685513150691986 +0.225,0.06885247677564621 +0.226,0.06907792681455611 +0.227,0.06929552841186523 +0.228,0.06960715490579605 +0.229,0.06985372692346574 +0.23,0.07018462657928468 +0.231,0.07031684410572052 +0.232,0.0706936417222023 +0.233,0.07096380466222764 +0.234,0.07133973670005798 +0.23500000000000001,0.07160522401332856 +0.23600000000000002,0.07217914521694187 +0.23700000000000002,0.0726053109765053 +0.23800000000000002,0.07301280444860458 +0.23900000000000002,0.0732806180715561 +0.24,0.07351550102233886 +0.241,0.07379595106840132 +0.242,0.0741586244702339 +0.243,0.07445318394899368 +0.244,0.07490208142995834 +0.245,0.07537737339735032 +0.246,0.07563357716798783 +0.247,0.0758810641169548 +0.248,0.0761787348985672 +0.249,0.07648081809282303 +0.25,0.07686466723680496 +0.251,0.07726196575164795 +0.252,0.07751740115880966 +0.253,0.07790815007686615 +0.254,0.07833272069692612 +0.255,0.0786768940091133 +0.256,0.07904902285337448 +0.257,0.07916450589895249 +0.258,0.07944245547056199 +0.259,0.079689213514328 +0.26,0.07992075532674789 +0.261,0.08036710864305496 +0.262,0.0805756521821022 +0.263,0.08081779897212983 +0.264,0.08119877249002456 +0.265,0.08143749594688417 +0.266,0.08169604361057282 +0.267,0.0820016952753067 +0.268,0.08226227641105652 +0.269,0.08260408425331116 +0.27,0.08299875974655152 +0.271,0.08331803184747696 +0.272,0.0835688933134079 +0.273,0.08375201517343521 +0.274,0.08425226747989654 +0.275,0.08452305942773819 +0.276,0.08498697161674502 +0.277,0.08547771841287614 +0.278,0.08588391870260241 +0.279,0.08647921091318132 +0.28,0.08699423044919968 +0.281,0.08738167250156403 +0.28200000000000003,0.08766297364234926 +0.28300000000000003,0.08808381438255311 +0.28400000000000003,0.08834704554080967 +0.28500000000000003,0.08876580208539964 +0.28600000000000003,0.08914970391988757 +0.28700000000000003,0.08973953211307525 +0.28800000000000003,0.09016423755884172 +0.289,0.09044839543104172 +0.29,0.09068292379379272 +0.291,0.09093183100223541 +0.292,0.09128260791301727 +0.293,0.0917651475071907 +0.294,0.09220754694938658 +0.295,0.09271188884973526 +0.296,0.09308301031589508 +0.297,0.0934659612774849 +0.298,0.0937750015258789 +0.299,0.09413550490140915 +0.3,0.09447748810052871 +0.301,0.09472993582487105 +0.302,0.09554637509584424 +0.303,0.09615149873495102 +0.304,0.09643551796674728 +0.305,0.09674799829721452 +0.306,0.09718062919378279 +0.307,0.0977475511431694 +0.308,0.0980932623744011 +0.309,0.09845113724470138 +0.31,0.09885391712188721 +0.311,0.09951518267393113 +0.312,0.0999727665781975 +0.313,0.10044030743837357 +0.314,0.10078232258558273 +0.315,0.10114142686128616 +0.316,0.10142449378967285 +0.317,0.10155276155471801 +0.318,0.10207809031009674 +0.319,0.10259801673889163 +0.32,0.10338513910770417 +0.321,0.10375369817018508 +0.322,0.10429433315992356 +0.323,0.10474775671958923 +0.324,0.10517772769927979 +0.325,0.10565383136272431 +0.326,0.10615046876668931 +0.327,0.10660185366868973 +0.328,0.10728581184148789 +0.329,0.10792540019750596 +0.33,0.1081860238313675 +0.331,0.10849075543880464 +0.332,0.1088348265886307 +0.333,0.1091965481042862 +0.334,0.10958396917581559 +0.335,0.11017757892608644 +0.336,0.11055395060777665 +0.337,0.11099629789590837 +0.338,0.11129853975772858 +0.339,0.11170507735013964 +0.34,0.11217942953109741 +0.341,0.11231146782636643 +0.342,0.11275149816274643 +0.343,0.11316320002079017 +0.34400000000000003,0.11372063404321672 +0.34500000000000003,0.11420049339532853 +0.34600000000000003,0.11463563185930252 +0.34700000000000003,0.11521612560749056 +0.34800000000000003,0.11566848504543309 +0.34900000000000003,0.11639913254976272 +0.35000000000000003,0.11673985421657564 +0.35100000000000003,0.11735353088378907 +0.352,0.11766212177276611 +0.353,0.11850125759840012 +0.354,0.11884594368934631 +0.355,0.1192354279756546 +0.356,0.11973401689529418 +0.357,0.12031056505441666 +0.358,0.12064218485355377 +0.359,0.12086324018239972 +0.36,0.12115374535322189 +0.361,0.12183283805847168 +0.362,0.12229803383350372 +0.363,0.12302167677879333 +0.364,0.12353749239444733 +0.365,0.12430457442998886 +0.366,0.12470423686504363 +0.367,0.1251824686527252 +0.368,0.12591587495803833 +0.369,0.12632443416118622 +0.37,0.1267957031726837 +0.371,0.12733459877967834 +0.372,0.1276288584470749 +0.373,0.12818530011177062 +0.374,0.1291196981668472 +0.375,0.13003666698932648 +0.376,0.13020419442653655 +0.377,0.13043101894855502 +0.378,0.13088234555721284 +0.379,0.1313499215841293 +0.38,0.13183582901954652 +0.381,0.13241949677467346 +0.382,0.13292780244350433 +0.383,0.13362332689762116 +0.384,0.13404658889770507 +0.385,0.1347536289691925 +0.386,0.13547331619262695 +0.387,0.1359217972755432 +0.388,0.13640882778167726 +0.389,0.13662023496627806 +0.39,0.13699132978916173 +0.391,0.13760390317440038 +0.392,0.1380639338493347 +0.393,0.13884880018234252 +0.394,0.13961022019386293 +0.395,0.14011015415191652 +0.396,0.1406136281490326 +0.397,0.14113734424114233 +0.398,0.14167319762706765 +0.399,0.14219543516635894 +0.4,0.1429309844970703 +0.401,0.14331359684467315 +0.402,0.14388016438484194 +0.403,0.14480386340618134 +0.404,0.1451521753072739 +0.405,0.14555225908756256 +0.406,0.14583022665977477 +0.40700000000000003,0.1465195733308792 +0.40800000000000003,0.147320338845253 +0.40900000000000003,0.14799887013435364 +0.41000000000000003,0.1485118961334229 +0.41100000000000003,0.1491770845651627 +0.41200000000000003,0.1497563878297806 +0.41300000000000003,0.15064161586761474 +0.41400000000000003,0.15115555608272555 +0.41500000000000004,0.15216745078563695 +0.41600000000000004,0.15317100846767426 +0.417,0.1539721863269806 +0.418,0.1547320176362991 +0.419,0.15548824918270107 +0.42,0.15609226882457727 +0.421,0.1565253657102585 +0.422,0.15695716226100923 +0.423,0.15790259444713592 +0.424,0.15891353285312654 +0.425,0.15964799225330353 +0.426,0.15986077332496643 +0.427,0.16053585851192473 +0.428,0.16109719455242158 +0.429,0.16171161925792693 +0.43,0.1624261271953583 +0.431,0.1633135231733322 +0.432,0.16408455574512482 +0.433,0.1647427443265915 +0.434,0.1655306648015976 +0.435,0.16606545090675354 +0.436,0.16692753350734713 +0.437,0.16783679556846617 +0.438,0.16840672349929806 +0.439,0.16913328087329865 +0.44,0.1698775029182434 +0.441,0.1704632284641266 +0.442,0.17086516654491424 +0.443,0.17149311590194705 +0.444,0.17205322635173798 +0.445,0.172508847117424 +0.446,0.17316225707530974 +0.447,0.17408261263370514 +0.448,0.174701060295105 +0.449,0.1756818853616715 +0.45,0.17641972303390505 +0.451,0.17694791054725645 +0.452,0.17759574961662292 +0.453,0.17810420501232146 +0.454,0.17864355742931365 +0.455,0.1792915016412735 +0.456,0.179875301361084 +0.457,0.18075512480735778 +0.458,0.18159740662574783 +0.459,0.18244325518608093 +0.46,0.183116489648819 +0.461,0.18366208255290986 +0.462,0.18428684329986572 +0.463,0.1849155013561249 +0.464,0.1859894403219223 +0.465,0.1868182998895646 +0.466,0.18779022943973542 +0.467,0.18881652200222016 +0.468,0.18915651094913488 +0.46900000000000003,0.1897625983953476 +0.47000000000000003,0.1904253649711609 +0.47100000000000003,0.19091252303123477 +0.47200000000000003,0.191473042011261 +0.47300000000000003,0.19203483259677886 +0.47400000000000003,0.1926094788312912 +0.47500000000000003,0.19313776791095738 +0.47600000000000003,0.19444547510147095 +0.47700000000000004,0.19499113917350772 +0.47800000000000004,0.19600676703453068 +0.47900000000000004,0.19657825887203226 +0.48,0.1980361592769623 +0.481,0.19841951072216032 +0.482,0.19924309933185572 +0.483,0.20076051700115205 +0.484,0.20153660285472866 +0.485,0.2019729369878769 +0.486,0.2029159389734268 +0.487,0.2037711935043334 +0.488,0.20453194034099578 +0.489,0.20537151288986202 +0.49,0.20562949955463408 +0.491,0.20667454767227167 +0.492,0.20772718620300293 +0.493,0.20938274228572845 +0.494,0.21053302919864644 +0.495,0.2115868848562241 +0.496,0.21252997505664825 +0.497,0.21364262449741364 +0.498,0.21518010532855986 +0.499,0.21581983053684242 +0.5,0.21672573685646057 +0.501,0.2175786962509155 +0.502,0.21871820235252382 +0.503,0.21985201239585872 +0.504,0.22105611109733583 +0.505,0.2218460911512375 +0.506,0.22319555759429938 +0.507,0.2245520728826523 +0.508,0.2254376320838928 +0.509,0.22604082763195038 +0.51,0.2269846475124359 +0.511,0.22817751061916355 +0.512,0.22931234061717987 +0.513,0.23122588741779332 +0.514,0.23197479844093324 +0.515,0.23321748495101927 +0.516,0.23478210639953617 +0.517,0.23555755043029783 +0.518,0.2361634615659714 +0.519,0.23663234770298006 +0.52,0.2373918622732162 +0.521,0.23918447625637063 +0.522,0.24002657115459441 +0.523,0.2415082498788834 +0.524,0.242151904463768 +0.525,0.24316020011901857 +0.526,0.24401438784599308 +0.527,0.2453734210729599 +0.528,0.24645932376384738 +0.529,0.24717170202732086 +0.53,0.24844852626323702 +0.531,0.24969915282726288 +0.532,0.25050547504425075 +0.533,0.25201622319221495 +0.534,0.2531842563152313 +0.535,0.25414603114128126 +0.536,0.25508574962615965 +0.537,0.2567922923564911 +0.538,0.25790478801727296 +0.539,0.25877068305015577 +0.54,0.26013925671577454 +0.541,0.26132658815383913 +0.542,0.2628916771411896 +0.543,0.26344603204727174 +0.544,0.2640575754642487 +0.545,0.2647346985340118 +0.546,0.2658089475631714 +0.547,0.26665416312217716 +0.548,0.2676047470569611 +0.549,0.2688252766132355 +0.55,0.2700542569160462 +0.551,0.27156748604774483 +0.552,0.2722435824871064 +0.553,0.2730508170127869 +0.554,0.2745917372703553 +0.555,0.2756621563434601 +0.556,0.2766513459682465 +0.557,0.2771991498470307 +0.558,0.27822002267837526 +0.559,0.27936146712303167 +0.56,0.28084784984588623 +0.561,0.28218865418434164 +0.562,0.2832820916175843 +0.5630000000000001,0.28425156998634343 +0.5640000000000001,0.28554831838607786 +0.5650000000000001,0.2861643397808077 +0.5660000000000001,0.2867591910362244 +0.5670000000000001,0.28768497371673585 +0.5680000000000001,0.28863020992279065 +0.5690000000000001,0.29006679058074963 +0.5700000000000001,0.2913927781581881 +0.5710000000000001,0.2931470699310303 +0.5720000000000001,0.2946028594970708 +0.5730000000000001,0.29565213418006897 +0.5740000000000001,0.29677004408836366 +0.5750000000000001,0.2974316477775574 +0.5760000000000001,0.2988474183082582 +0.577,0.30008471131324765 +0.578,0.3016707212924957 +0.579,0.3026848566532135 +0.58,0.30478312849998473 +0.581,0.30558824992179856 +0.582,0.3077060241699219 +0.583,0.3090547485351562 +0.584,0.31081695675849913 +0.585,0.31140840053558344 +0.586,0.3130031421184539 +0.587,0.31407409596443175 +0.588,0.3150710313320159 +0.589,0.3168192784786224 +0.59,0.3180905878543854 +0.591,0.3194848527908325 +0.592,0.32002861857414244 +0.593,0.32117611694335935 +0.594,0.3228161997795105 +0.595,0.3239805793762206 +0.596,0.3248808357715607 +0.597,0.3260601608753204 +0.598,0.32715838408470155 +0.599,0.32828224587440485 +0.6,0.3292904675006866 +0.601,0.3308603525161743 +0.602,0.33195218253135683 +0.603,0.3331107621192932 +0.604,0.3338675284385681 +0.605,0.33452977776527404 +0.606,0.33560163140296934 +0.607,0.33675021648406983 +0.608,0.33781955432891847 +0.609,0.3405651381015777 +0.61,0.34206925272941596 +0.611,0.3433950757980347 +0.612,0.3449025204181671 +0.613,0.3468970329761505 +0.614,0.3483715529441833 +0.615,0.3507713532447815 +0.616,0.3513868060111999 +0.617,0.35219931459426884 +0.618,0.3537859859466553 +0.619,0.35466416907310483 +0.62,0.3556048142910004 +0.621,0.3576563012599945 +0.622,0.35994247651100164 +0.623,0.3610582466125488 +0.624,0.3623529901504517 +0.625,0.3633379638195038 +0.626,0.364760734796524 +0.627,0.367347946882248 +0.628,0.36956126284599294 +0.629,0.3712077219486237 +0.63,0.3729068279266357 +0.631,0.3747991518974305 +0.632,0.37640384125709536 +0.633,0.3777896862030029 +0.634,0.38004341006278997 +0.635,0.38152033805847163 +0.636,0.3832169976234436 +0.637,0.3846406662464142 +0.638,0.38654884052276617 +0.639,0.3894650237560272 +0.64,0.39180234432220457 +0.641,0.39322062754631043 +0.642,0.393999050617218 +0.643,0.39496607112884524 +0.644,0.3963148491382599 +0.645,0.397739245891571 +0.646,0.3997951874732972 +0.647,0.4016137900352477 +0.648,0.4035925948619843 +0.649,0.4049594974517822 +0.65,0.4062568724155426 +0.651,0.4090126905441285 +0.652,0.4110257773399352 +0.653,0.41210247969627384 +0.654,0.41418996834754945 +0.655,0.4162669384479523 +0.656,0.41797527551651004 +0.657,0.41914984273910527 +0.658,0.42055929017066956 +0.659,0.4219137287139892 +0.66,0.4231648337841034 +0.661,0.42448048877716066 +0.662,0.42557619571685806 +0.663,0.4262071008682251 +0.664,0.42852194929122944 +0.665,0.4309162986278534 +0.666,0.43300671768188476 +0.667,0.43433733129501345 +0.668,0.43559387683868406 +0.669,0.4377051091194153 +0.67,0.43926147699356083 +0.671,0.44071412658691417 +0.672,0.44216327786445636 +0.673,0.44413558864593505 +0.674,0.4450944979190828 +0.675,0.4470278561115265 +0.676,0.4501760702133183 +0.677,0.4522967069149018 +0.678,0.45419734191894584 +0.679,0.45564090156555187 +0.68,0.458388513326645 +0.681,0.46107772898674027 +0.682,0.4631531457901002 +0.683,0.4646178777217866 +0.684,0.46699235653877275 +0.685,0.46942047715187074 +0.686,0.4710460722446442 +0.687,0.4722603964805603 +0.6880000000000001,0.4748403420448304 +0.6890000000000001,0.47704819679260263 +0.6900000000000001,0.4787851560115815 +0.6910000000000001,0.4811604156494143 +0.6920000000000001,0.48359354758262635 +0.6930000000000001,0.4861211380958558 +0.6940000000000001,0.4876606223583222 +0.6950000000000001,0.48936103940010084 +0.6960000000000001,0.491091595888138 +0.6970000000000001,0.49230277109146126 +0.6980000000000001,0.4932593896389008 +0.6990000000000001,0.49435115742683416 +0.7000000000000001,0.49701787233352673 +0.7010000000000001,0.4989797868728638 +0.7020000000000001,0.5015483875274659 +0.7030000000000001,0.503209454536438 +0.704,0.5052170486450194 +0.705,0.5077142286300658 +0.706,0.5100656490325927 +0.707,0.5141044416427611 +0.708,0.5164363188743591 +0.709,0.519519163608551 +0.71,0.5215561914443969 +0.711,0.5228765521049498 +0.712,0.5246801681518555 +0.713,0.5262903299331658 +0.714,0.5292955532073974 +0.715,0.531598172187805 +0.716,0.5345912790298463 +0.717,0.5370034799575806 +0.718,0.5391108818054199 +0.719,0.5411532263755798 +0.72,0.5435596084594723 +0.721,0.546427152633667 +0.722,0.5495200953483581 +0.723,0.5518301258087159 +0.724,0.5552060322761535 +0.725,0.5562607526779174 +0.726,0.5581630320549011 +0.727,0.5604809155464171 +0.728,0.5631462955474854 +0.729,0.5664891710281371 +0.73,0.5695884203910828 +0.731,0.572594114780426 +0.732,0.5751643414497374 +0.733,0.579055645942688 +0.734,0.5811746497154234 +0.735,0.5834240436553957 +0.736,0.5851604099273681 +0.737,0.5875289330482479 +0.738,0.589304578781128 +0.739,0.5917584257125853 +0.74,0.5936129188537598 +0.741,0.5952727551460266 +0.742,0.5979466142654419 +0.743,0.6006524610519408 +0.744,0.602877411365509 +0.745,0.6048942303657532 +0.746,0.6068326692581175 +0.747,0.6092836647033693 +0.748,0.6122042956352234 +0.749,0.6139799165725709 +0.75,0.6167864203453064 +0.751,0.6198794775009155 +0.752,0.6233054900169374 +0.753,0.6247160305976868 +0.754,0.6272774991989136 +0.755,0.6312460994720459 +0.756,0.6333284811973573 +0.757,0.6353945846557617 +0.758,0.6379212822914123 +0.759,0.6396336307525635 +0.76,0.6424299907684325 +0.761,0.6435285568237304 +0.762,0.6446393556594848 +0.763,0.6469294843673707 +0.764,0.6495313234329224 +0.765,0.6525556492805481 +0.766,0.6562538957595826 +0.767,0.6584739785194397 +0.768,0.6599500741958618 +0.769,0.6633379888534546 +0.77,0.6649552106857299 +0.771,0.6666517553329468 +0.772,0.6696835498809814 +0.773,0.6722199306488038 +0.774,0.6750766687393188 +0.775,0.6778345227241517 +0.776,0.6804808549880982 +0.777,0.6827274684906006 +0.778,0.6855482964515687 +0.779,0.6884293208122253 +0.78,0.6912018561363223 +0.781,0.6928482160568238 +0.782,0.6945925288200383 +0.783,0.6976005382537843 +0.784,0.6995016055107116 +0.785,0.7015361976623535 +0.786,0.7055580191612244 +0.787,0.7078130025863648 +0.788,0.7096692981719971 +0.789,0.7141593947410584 +0.79,0.7166039824485779 +0.791,0.7199370312690735 +0.792,0.7221396021842957 +0.793,0.7238198552131653 +0.794,0.7256511697769166 +0.795,0.7273496651649476 +0.796,0.7287024660110474 +0.797,0.7301183547973634 +0.798,0.7312086853981018 +0.799,0.7336254096031192 +0.8,0.7378913402557374 +0.801,0.7390609560012819 +0.802,0.7413886003494263 +0.803,0.7442582187652589 +0.804,0.7457595643997192 +0.805,0.7487076735496521 +0.806,0.7513037314414979 +0.807,0.7537516617774964 +0.808,0.7558289241790772 +0.809,0.7579646811485291 +0.81,0.760122139453888 +0.811,0.7624723095893862 +0.812,0.7652060437202455 +0.8130000000000001,0.768627751350403 +0.8140000000000001,0.7704240002632142 +0.8150000000000001,0.7727911520004279 +0.8160000000000001,0.7756262598037721 +0.8170000000000001,0.7779930200576782 +0.8180000000000001,0.7792447452545168 +0.8190000000000001,0.7821139793395997 +0.8200000000000001,0.7848197984695439 +0.8210000000000001,0.7878133149147034 +0.8220000000000001,0.7894205975532534 +0.8230000000000001,0.7914696254730229 +0.8240000000000001,0.794208010196686 +0.8250000000000001,0.7980401992797854 +0.8260000000000001,0.8003686666488649 +0.8270000000000001,0.8017429127693176 +0.8280000000000001,0.8037899770736694 +0.8290000000000001,0.8061359634399415 +0.8300000000000001,0.8074638533592224 +0.8310000000000001,0.8089885425567628 +0.8320000000000001,0.8104319944381714 +0.833,0.8119312100410461 +0.834,0.8133427176475525 +0.835,0.8147295093536376 +0.836,0.8165421204566954 +0.837,0.8178741507530212 +0.838,0.8200593056678771 +0.839,0.8223081617355347 +0.84,0.8235005187988281 +0.841,0.8250714197158814 +0.842,0.8267041726112365 +0.843,0.828235424518585 +0.844,0.8300668678283691 +0.845,0.8335037064552305 +0.846,0.8348938794136047 +0.847,0.8361546907424926 +0.848,0.8376440830230714 +0.849,0.8390999097824097 +0.85,0.8401537060737608 +0.851,0.8413313694000244 +0.852,0.8428126468658447 +0.853,0.8439638833999634 +0.854,0.84551034784317 +0.855,0.8477019047737122 +0.856,0.849078444480896 +0.857,0.8508299469947814 +0.858,0.8521421542167663 +0.859,0.854283676624298 +0.86,0.8553964304924012 +0.861,0.8570736298561096 +0.862,0.8595676064491272 +0.863,0.861366729259491 +0.864,0.8628567285537719 +0.865,0.8637067222595215 +0.866,0.8648108735084533 +0.867,0.8667233924865723 +0.868,0.8680850524902344 +0.869,0.8693304338455199 +0.87,0.8708895802497864 +0.871,0.8719159803390502 +0.872,0.8728275051116944 +0.873,0.8740247650146484 +0.874,0.8746823616027832 +0.875,0.8762440085411072 +0.876,0.8774668879508971 +0.877,0.8793546710014344 +0.878,0.8800536594390869 +0.879,0.8813861413002014 +0.88,0.8821483969688415 +0.881,0.8842260141372681 +0.882,0.8849015936851502 +0.883,0.8859527988433837 +0.884,0.8867904462814331 +0.885,0.887486081123352 +0.886,0.8883855323791504 +0.887,0.8892057757377625 +0.888,0.8911232800483704 +0.889,0.8921237287521363 +0.89,0.8932707595825196 +0.891,0.8942793154716492 +0.892,0.8954495372772217 +0.893,0.8966759386062624 +0.894,0.8979583988189698 +0.895,0.8991547918319701 +0.896,0.9005982747077943 +0.897,0.9019417443275451 +0.898,0.9035397138595581 +0.899,0.9043721523284912 +0.9,0.9061365008354187 +0.901,0.9070912137031555 +0.902,0.9084761090278626 +0.903,0.9088140873908996 +0.904,0.9110051450729371 +0.905,0.9121242308616638 +0.906,0.9132118544578552 +0.907,0.914048767566681 +0.908,0.9154756035804749 +0.909,0.9165413084030151 +0.91,0.917555649280548 +0.911,0.9184043488502504 +0.912,0.9201592545509338 +0.913,0.9213558864593506 +0.914,0.9222108068466186 +0.915,0.9235749340057373 +0.916,0.9247118844985963 +0.917,0.9253981008529664 +0.918,0.92733549451828 +0.919,0.9280046472549438 +0.92,0.9286361622810365 +0.921,0.9297371454238892 +0.922,0.9306485476493837 +0.923,0.9319283595085144 +0.924,0.9327587547302245 +0.925,0.9337125897407536 +0.926,0.9347635154724121 +0.927,0.9356032304763795 +0.928,0.936365517616272 +0.929,0.9372246809005738 +0.93,0.938027358055115 +0.931,0.9386350135803223 +0.932,0.9393597273826599 +0.933,0.9400746884346008 +0.934,0.9405010867118836 +0.935,0.9409511041641236 +0.936,0.9415023317337037 +0.937,0.9420221900939941 +0.9380000000000001,0.9426584181785583 +0.9390000000000001,0.9437042894363403 +0.9400000000000001,0.9441058969497681 +0.9410000000000001,0.9453687057495117 +0.9420000000000001,0.9460503454208374 +0.9430000000000001,0.9473216133117676 +0.9440000000000001,0.9482107429504395 +0.9450000000000001,0.948664915561676 +0.9460000000000001,0.9491276588439942 +0.9470000000000001,0.950085120677948 +0.9480000000000001,0.9507388820648194 +0.9490000000000001,0.9515065894126893 +0.9500000000000001,0.9520249605178833 +0.9510000000000001,0.952864094734192 +0.9520000000000001,0.9535072164535523 +0.9530000000000001,0.9542113809585572 +0.9540000000000001,0.9552147641181946 +0.9550000000000001,0.9565998983383179 +0.9560000000000001,0.9574157347679139 +0.9570000000000001,0.9577681655883789 +0.9580000000000001,0.9586380872726441 +0.9590000000000001,0.9591634531021118 +0.96,0.959640429019928 +0.961,0.9604152369499207 +0.962,0.9614295425415039 +0.963,0.9618373155593871 +0.964,0.9625929718017578 +0.965,0.9632611250877381 +0.966,0.9637582778930665 +0.967,0.9641529331207276 +0.968,0.9645504240989685 +0.969,0.965079176902771 +0.97,0.9657490825653077 +0.971,0.9668205518722535 +0.972,0.9676790843009948 +0.973,0.9685314168930054 +0.974,0.9692204146385192 +0.975,0.9699972152709962 +0.976,0.9703809666633606 +0.977,0.9710133419036865 +0.978,0.9719177060127258 +0.979,0.9724355454444885 +0.98,0.9730843520164489 +0.981,0.9739625239372254 +0.982,0.9744145770072937 +0.983,0.9751618342399597 +0.984,0.9757989559173584 +0.985,0.9764883494377137 +0.986,0.9774243936538696 +0.987,0.9791995120048523 +0.988,0.980203695297241 +0.989,0.9809187788963318 +0.99,0.9814411735534668 +0.991,0.9828508825302124 +0.992,0.9837556133270263 +0.993,0.9849095578193665 +0.994,0.9856612262725831 +0.995,0.9867323517799378 +0.996,0.9873756999969482 +0.997,0.9892905364036559 +0.998,0.9906478109359742 +0.999,0.992839243888855 +1.0,0.9987688660621643 diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/models/stacking_ensemble.joblib b/service/scripts/profiling/founding_potential/results/rq1_symmetric/models/stacking_ensemble.joblib new file mode 100644 index 00000000..3c1be373 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1_symmetric/models/stacking_ensemble.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/models/xgboost.joblib b/service/scripts/profiling/founding_potential/results/rq1_symmetric/models/xgboost.joblib new file mode 100644 index 00000000..d21f7b0c Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1_symmetric/models/xgboost.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/permutation_importance.csv b/service/scripts/profiling/founding_potential/results/rq1_symmetric/permutation_importance.csv new file mode 100644 index 00000000..096da6da --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/permutation_importance.csv @@ -0,0 +1,93 @@ +feature,importance_mean,importance_std +patent_research_area_n.,0.10444260921031703,0.01000291629874731 +pub_rate,0.08201736179505467,0.010285677786261209 +first_publication_year,0.0547564807378144,0.006026166591504968 +industry_collab_at_index,0.0454906367927285,0.004749368941899651 +career_age_at_index,0.030337435596206636,0.0061091803388714306 +patents_at_index,0.027915583825288897,0.003703699002366671 +patent_rate,0.02257319938334216,0.0028412477089575 +patent_research_area_46,0.020719020561163842,0.004705278553964332 +publication_research_area_32,0.015048499383005075,0.002711540575849488 +years_since_first_grant,0.009081401276953966,0.002810918250730077 +grant_research_area_51,0.008390616865516776,0.001806267261854904 +institution_berkeley,0.007077813918881587,0.0020744773908402407 +pubs_at_index,0.006698549835378387,0.0027466650677884677 +grants_at_index,0.00599503440126114,0.001980142298622219 +linked_pat_pub_at_index,0.005507226827832795,0.0031018962561504865 +years_since_first_patent,0.004659123586806957,0.0022112365909527864 +grant_rate,0.004485274174139342,0.002214912214326525 +publication_research_area_31,0.0044331001338714145,0.0030081377740826198 +activities_at_index,0.004305284216529736,0.0014782296452033978 +grant_research_area_46,0.004091858156144962,0.0011631444373894524 +institution_muenchen,0.003659848471299282,0.002803323314333376 +grant_research_area_32,0.0035364026460315556,0.001234692789094628 +institution_harvard,0.0030399598700210583,0.0010328665345558197 +institution_oxford,0.002425090347126174,0.0012716207135969424 +grant_research_area_n.,0.00225639772892266,0.0010747339941249506 +publication_research_area_35,0.0020549314854987734,0.0009371249153349768 +institution_ude,0.001162683833843925,0.0006841053498902781 +institution_toronto,0.001156583492787261,0.0007606506950016298 +publication_research_area_46,0.0011120620784481894,0.0005477141022425093 +publication_research_area_51,0.0011031559479410646,0.0007678826095928305 +publication_research_area_n.,0.0010664235558135837,0.0014260233229656733 +grant_research_area_31,0.0010364325218291948,0.0004560203605407486 +grant_research_area_33,0.001024820172770624,0.0008293070226958775 +institution_stanford,0.0009809714058171327,0.0024170143165917917 +has_grants_at_index,0.0009652551908011509,0.0005840689937446477 +patent_research_area_32,0.0008854501671646586,0.0008795227637767272 +patent_research_area_37,0.0007922846156994346,0.0003202768842191713 +patent_research_area_34,0.0007533382280581757,0.0006179414386520229 +grant_research_area_40,0.0006506331487920125,0.00024905292234651626 +publication_research_area_40,0.0006333794139779525,0.0005119740114490612 +grant_research_area_44,0.0006075402293343856,0.0009861276315923473 +publication_research_area_44,0.0005199043034394668,0.00027784478444705133 +grant_research_area_52,0.0005165759383172375,0.0006805695935962879 +patent_research_area_35,0.0005135954428669542,0.0004909736821470622 +grant_research_area_35,0.0005100934296669246,0.00042419921649439104 +has_patents_at_index,0.0004675935068726766,0.0002043361710744472 +publication_research_area_36,0.000464118746512987,0.00019912666321521497 +publication_research_area_41,0.0004548894864885633,0.00047544771839497186 +publication_research_area_38,0.00041117653710123216,0.00038916428122990254 +patent_research_area_30,0.00040721947959039274,0.0002405194434829914 +grant_research_area_42,0.0003586989558202858,0.0006275379824004101 +publication_research_area_42,0.00032694798696689673,0.0004053897544270012 +patent_research_area_36,0.0003203928510275733,0.00021304776451355032 +institution_telaviv,0.00030826243735263545,0.001992324302329092 +grant_research_area_39,0.0002725435728411885,0.00022673759381254337 +publication_research_area_39,0.00026036344846201985,0.00015391601315424035 +grant_research_area_47,0.0002447153523418621,0.00028311124502635815 +publication_research_area_49,0.00023995063333196454,0.0004296785577625752 +publication_research_area_30,0.0002088399681934361,0.00020777950125951507 +patent_research_area_31,0.00019864516127749977,0.000380279221169651 +publication_research_area_37,0.00018668751279878325,0.0003857466547111577 +grant_research_area_41,0.0001861237461911358,0.00020270170413414225 +grant_research_area_34,0.000178172364924839,0.0005065287456772773 +publication_research_area_34,0.00016605431326274233,0.0012642739104362067 +patent_research_area_41,0.00016333760195231807,0.0001247795859965852 +patent_research_area_40,0.00016073261327945176,0.0006151752824866421 +publication_research_area_47,0.00010905356177434155,0.00011443403044224373 +grant_research_area_36,6.014396964046376e-05,7.141717095673809e-05 +grant_research_area_49,1.7251931083628323e-05,2.7492307340890443e-05 +grant_research_area_30,1.4864167816464047e-05,2.0438806913546228e-05 +patent_research_area_47,8.931937467215879e-06,2.6996384585526762e-05 +grant_research_area_48,0.0,0.0 +patent_research_area_52,0.0,0.0 +patent_research_area_44,0.0,0.0 +patent_research_area_48,0.0,0.0 +patent_research_area_33,0.0,0.0 +patent_research_area_39,0.0,0.0 +patent_research_area_42,0.0,0.0 +patent_research_area_43,0.0,0.0 +patent_research_area_38,0.0,0.0 +patent_research_area_49,0.0,0.0 +patent_research_area_50,0.0,0.0 +publication_research_area_43,0.0,0.0 +grant_research_area_37,-1.690891772265779e-07,6.788074255353668e-05 +grant_research_area_38,-8.25084822601574e-06,3.097726332911861e-05 +grant_research_area_50,-2.8781924222920364e-05,4.0867346872770755e-05 +grant_research_area_43,-8.555855220965803e-05,2.3804626607015977e-05 +publication_research_area_48,-8.756024432305388e-05,0.0001333723730635551 +publication_research_area_33,-0.0001731751809484261,0.0005742303072148211 +patent_research_area_51,-0.0002463145708732517,0.0001826665200607186 +publication_research_area_50,-0.000452251215090077,0.00015294072202135244 +publication_research_area_52,-0.0007332997092399818,0.0004020032943703248 diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/plots/permutation_importance.png b/service/scripts/profiling/founding_potential/results/rq1_symmetric/plots/permutation_importance.png new file mode 100644 index 00000000..14fe0477 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq1_symmetric/plots/permutation_importance.png differ diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/probability_by_pubs_decile.csv b/service/scripts/profiling/founding_potential/results/rq1_symmetric/probability_by_pubs_decile.csv new file mode 100644 index 00000000..786437af --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/probability_by_pubs_decile.csv @@ -0,0 +1,11 @@ +pubs_decile,pubs_median,p_founder_median,n +0,4.980496919642443,0.3915597,181 +1,7.265509705598422,0.34831706,180 +2,10.829857249335916,0.41633904,180 +3,17.074329250273248,0.39508438,181 +4,25.61426887916668,0.1680935,180 +5,39.18466019195309,0.1698496,180 +6,58.63514863439843,0.14302556,181 +7,83.22335062107854,0.17652148,180 +8,136.44852188347846,0.09957586,180 +9,254.4977651893464,0.10607539,181 diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/temporal_split.csv b/service/scripts/profiling/founding_potential/results/rq1_symmetric/temporal_split.csv new file mode 100644 index 00000000..d58d3896 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/temporal_split.csv @@ -0,0 +1,5 @@ +model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +catboost,0.7919157415314546,0.6121112929623568,0.7442786069651741,0.6717557251908397,0.8607147674704626,0.732969623731087,0.5268819654885002,0.14595411793192087 +random_forest,0.7947623114147452,0.6219931271477663,0.7203980099502487,0.6675887505763024,0.8526728399469955,0.7221834188868932,0.5232303860768714,0.1465061594100234 +xgboost,0.7839453458582408,0.5979299363057324,0.7472636815920398,0.6643078283945157,0.854764851976164,0.7197777187580949,0.5147610429350759,0.15043815970420837 +lightgbm,0.7873612297181896,0.6123693379790941,0.699502487562189,0.6530422666047375,0.8487121807231783,0.7101883805026368,0.5030246219789863,0.1495069027701116 diff --git a/service/scripts/profiling/founding_potential/results/rq1_symmetric/temporal_split.md b/service/scripts/profiling/founding_potential/results/rq1_symmetric/temporal_split.md new file mode 100644 index 00000000..4f890c64 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq1_symmetric/temporal_split.md @@ -0,0 +1,6 @@ +| model | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:--------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|---------:| +| catboost | 0.791916 | 0.612111 | 0.744279 | 0.671756 | 0.860715 | 0.73297 | 0.526882 | 0.145954 | +| random_forest | 0.794762 | 0.621993 | 0.720398 | 0.667589 | 0.852673 | 0.722183 | 0.52323 | 0.146506 | +| xgboost | 0.783945 | 0.59793 | 0.747264 | 0.664308 | 0.854765 | 0.719778 | 0.514761 | 0.150438 | +| lightgbm | 0.787361 | 0.612369 | 0.699502 | 0.653042 | 0.848712 | 0.710188 | 0.503025 | 0.149507 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq2/models/pooled_lightgbm.joblib b/service/scripts/profiling/founding_potential/results/rq2/models/pooled_lightgbm.joblib new file mode 100644 index 00000000..19c01405 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq2/models/pooled_lightgbm.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq2/rq2_horizon_validation.csv b/service/scripts/profiling/founding_potential/results/rq2/rq2_horizon_validation.csv new file mode 100644 index 00000000..85edfdc6 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2/rq2_horizon_validation.csv @@ -0,0 +1,3 @@ +offset_years,regime,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +3,in-range,0.8631807550952222,0.8465067043048694,0.8620194035213798,0.854192629517536,0.9490754322242588,0.9447569234280719,0.7254438560295196,0.09512312424031473 +5,extrapolation,0.8536585365853658,0.8433561397191214,0.8415379087315846,0.8424460431654677,0.9423212988990626,0.9406816480806482,0.7058289332875681,0.09915583394631641 diff --git a/service/scripts/profiling/founding_potential/results/rq2/rq2_horizon_validation.md b/service/scripts/profiling/founding_potential/results/rq2/rq2_horizon_validation.md new file mode 100644 index 00000000..78c0ff3a --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2/rq2_horizon_validation.md @@ -0,0 +1,4 @@ +| offset_years | regime | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|---------------:|:--------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|----------:| +| 3 | in-range | 0.863181 | 0.846507 | 0.862019 | 0.854193 | 0.949075 | 0.944757 | 0.725444 | 0.0951231 | +| 5 | extrapolation | 0.853659 | 0.843356 | 0.841538 | 0.842446 | 0.942321 | 0.940682 | 0.705829 | 0.0991558 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq2/rq2_offset_comparison.csv b/service/scripts/profiling/founding_potential/results/rq2/rq2_offset_comparison.csv new file mode 100644 index 00000000..f5c19013 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2/rq2_offset_comparison.csv @@ -0,0 +1,19 @@ +offset_years,model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +1,dummy_most_frequent,0.5661736822146378,0.0,0.0,0.0,0.5,0.4338263177853622,0.0,0.4338263177853622 +1,logistic_regression,0.7591960561243838,0.7040898155573376,0.7674825174825175,0.7344207444583856,0.8572581136211411,0.8293360222290606,0.5165120209574257,0.1551183472652962 +1,decision_tree,0.800910125142207,0.8788249694002448,0.6276223776223776,0.7322794492605813,0.8770102553173551,0.8433125359476892,0.601590878883977,0.13526520115889215 +1,random_forest,0.8168373151308305,0.8001816530426885,0.7701048951048951,0.7848552338530067,0.9117091883334347,0.9049847240390165,0.6258464396286001,0.11935927951910208 +1,xgboost,0.819491846795601,0.7929824561403509,0.7902097902097902,0.7915936952714536,0.9160142436264339,0.9076603816788962,0.6324002494681569,0.11532440036535263 +1,lightgbm,0.8164580963215775,0.791005291005291,0.7840909090909091,0.7875329236172081,0.9134082595234638,0.9058031727382153,0.6260083630935187,0.11756659954499901 +2,dummy_most_frequent,0.5661736822146378,0.0,0.0,0.0,0.5,0.4338263177853622,0.0,0.4338263177853622 +2,logistic_regression,0.7629882442169131,0.7071029529130087,0.7744755244755245,0.7392574050896955,0.858364968922571,0.8302205046607707,0.5246590948773446,0.15435887151342015 +2,decision_tree,0.7937049677664012,0.8658536585365854,0.6206293706293706,0.7230142566191446,0.8733225916749024,0.843959142280009,0.5856092232229861,0.1367376966357669 +2,random_forest,0.8210087220326128,0.8105360443622921,0.7666083916083916,0.7879604672057502,0.9139316811788345,0.9062550237995185,0.6340485024896209,0.11826627106757638 +2,xgboost,0.8229048160788776,0.8052299368800722,0.7805944055944056,0.7927208166888593,0.9183023105494639,0.9099229716095572,0.638436107410398,0.11364441365003586 +2,lightgbm,0.819871065604854,0.8005390835579514,0.7788461538461539,0.7895436420026584,0.9159375453749199,0.9082849372502848,0.6323366309042239,0.11539552583472808 +3,dummy_most_frequent,0.5661736822146378,0.0,0.0,0.0,0.5,0.4338263177853622,0.0,0.4338263177853622 +3,logistic_regression,0.7675388699279484,0.7098814229249012,0.784965034965035,0.7455375674553757,0.8644332057761395,0.8370762949302815,0.5348490192949841,0.15176601514477916 +3,decision_tree,0.801668562760713,0.8736462093862816,0.6346153846153846,0.7351898734177216,0.888387650527637,0.8599692227771747,0.6019822969962042,0.12890424209230303 +3,random_forest,0.8293515358361775,0.8224907063197026,0.7736013986013986,0.7972972972972973,0.9176079279059854,0.9104691376235128,0.6510984297410125,0.11569634159878014 +3,xgboost,0.8312476298824422,0.8168631006346329,0.7875874125874126,0.8019581664441477,0.9220262741277476,0.91385110761046,0.6553642864918443,0.11131781339645386 +3,lightgbm,0.8297307546454304,0.8099910793933988,0.7937062937062938,0.801766004415011,0.9226975301992046,0.9153645143313508,0.6526773305456256,0.1104552740805854 diff --git a/service/scripts/profiling/founding_potential/results/rq2/rq2_offset_comparison.md b/service/scripts/profiling/founding_potential/results/rq2/rq2_offset_comparison.md new file mode 100644 index 00000000..ff9b0f0e --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2/rq2_offset_comparison.md @@ -0,0 +1,20 @@ +| | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:---------------------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|---------:| +| (1, 'dummy_most_frequent') | 0.566174 | 0 | 0 | 0 | 0.5 | 0.433826 | 0 | 0.433826 | +| (1, 'logistic_regression') | 0.759196 | 0.70409 | 0.767483 | 0.734421 | 0.857258 | 0.829336 | 0.516512 | 0.155118 | +| (1, 'decision_tree') | 0.80091 | 0.878825 | 0.627622 | 0.732279 | 0.87701 | 0.843313 | 0.601591 | 0.135265 | +| (1, 'random_forest') | 0.816837 | 0.800182 | 0.770105 | 0.784855 | 0.911709 | 0.904985 | 0.625846 | 0.119359 | +| (1, 'xgboost') | 0.819492 | 0.792982 | 0.79021 | 0.791594 | 0.916014 | 0.90766 | 0.6324 | 0.115324 | +| (1, 'lightgbm') | 0.816458 | 0.791005 | 0.784091 | 0.787533 | 0.913408 | 0.905803 | 0.626008 | 0.117567 | +| (2, 'dummy_most_frequent') | 0.566174 | 0 | 0 | 0 | 0.5 | 0.433826 | 0 | 0.433826 | +| (2, 'logistic_regression') | 0.762988 | 0.707103 | 0.774476 | 0.739257 | 0.858365 | 0.830221 | 0.524659 | 0.154359 | +| (2, 'decision_tree') | 0.793705 | 0.865854 | 0.620629 | 0.723014 | 0.873323 | 0.843959 | 0.585609 | 0.136738 | +| (2, 'random_forest') | 0.821009 | 0.810536 | 0.766608 | 0.78796 | 0.913932 | 0.906255 | 0.634049 | 0.118266 | +| (2, 'xgboost') | 0.822905 | 0.80523 | 0.780594 | 0.792721 | 0.918302 | 0.909923 | 0.638436 | 0.113644 | +| (2, 'lightgbm') | 0.819871 | 0.800539 | 0.778846 | 0.789544 | 0.915938 | 0.908285 | 0.632337 | 0.115396 | +| (3, 'dummy_most_frequent') | 0.566174 | 0 | 0 | 0 | 0.5 | 0.433826 | 0 | 0.433826 | +| (3, 'logistic_regression') | 0.767539 | 0.709881 | 0.784965 | 0.745538 | 0.864433 | 0.837076 | 0.534849 | 0.151766 | +| (3, 'decision_tree') | 0.801669 | 0.873646 | 0.634615 | 0.73519 | 0.888388 | 0.859969 | 0.601982 | 0.128904 | +| (3, 'random_forest') | 0.829352 | 0.822491 | 0.773601 | 0.797297 | 0.917608 | 0.910469 | 0.651098 | 0.115696 | +| (3, 'xgboost') | 0.831248 | 0.816863 | 0.787587 | 0.801958 | 0.922026 | 0.913851 | 0.655364 | 0.111318 | +| (3, 'lightgbm') | 0.829731 | 0.809991 | 0.793706 | 0.801766 | 0.922698 | 0.915365 | 0.652677 | 0.110455 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq2/rq2_survival_vs_classifier.csv b/service/scripts/profiling/founding_potential/results/rq2/rq2_survival_vs_classifier.csv new file mode 100644 index 00000000..c5f6dc67 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2/rq2_survival_vs_classifier.csv @@ -0,0 +1,4 @@ +method,metric,value +CoxPH survival model,concordance_index,0.7151927275906578 +CoxPH survival model,auc_within_5y,0.6564548365605725 +"Pooled classifier (offset=5, extrapolation)",roc_auc,0.9423212988990626 diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon1_model_comparison.csv b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon1_model_comparison.csv new file mode 100644 index 00000000..b7982997 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon1_model_comparison.csv @@ -0,0 +1,5 @@ +model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +catboost,0.819142689371697,0.631578947368421,0.75,0.6857142857142857,0.8871371656232214,0.7459898973822718,0.5641373642594485,0.12782820408114018 +xgboost,0.819142689371697,0.6335877862595419,0.7410714285714286,0.6831275720164609,0.8834350099601596,0.7387567608520373,0.561018561498113,0.12772762775421143 +lightgbm,0.8244274809160306,0.6536082474226804,0.7075892857142857,0.6795284030010718,0.8750373505976096,0.7230143748644478,0.5597188552207917,0.12730823172401026 +random_forest,0.8038755137991779,0.6025179856115108,0.7477678571428571,0.6673306772908366,0.8657868525896414,0.7177200688341212,0.5367707828363867,0.1435378844440591 diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon1_model_comparison.md b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon1_model_comparison.md new file mode 100644 index 00000000..11018f57 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon1_model_comparison.md @@ -0,0 +1,6 @@ +| model | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:--------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|---------:| +| catboost | 0.819143 | 0.631579 | 0.75 | 0.685714 | 0.887137 | 0.74599 | 0.564137 | 0.127828 | +| xgboost | 0.819143 | 0.633588 | 0.741071 | 0.683128 | 0.883435 | 0.738757 | 0.561019 | 0.127728 | +| lightgbm | 0.824427 | 0.653608 | 0.707589 | 0.679528 | 0.875037 | 0.723014 | 0.559719 | 0.127308 | +| random_forest | 0.803876 | 0.602518 | 0.747768 | 0.667331 | 0.865787 | 0.71772 | 0.536771 | 0.143538 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon3_model_comparison.csv b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon3_model_comparison.csv new file mode 100644 index 00000000..964c489c --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon3_model_comparison.csv @@ -0,0 +1,5 @@ +model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +catboost,0.8346303501945526,0.6553911205073996,0.7711442786069652,0.7085714285714285,0.8906367286375141,0.7634969713091347,0.5980225591719542,0.12229772332672098 +xgboost,0.8398184176394293,0.6718403547671841,0.753731343283582,0.7104337631887456,0.8867700968840011,0.7611053473416477,0.602122023452243,0.1199701577425003 +lightgbm,0.8385214007782101,0.6758620689655173,0.7313432835820896,0.7025089605734767,0.8788426289604608,0.7437444338883753,0.5927983690393407,0.12103568709376403 +random_forest,0.8151750972762646,0.6158415841584158,0.7736318407960199,0.6857772877618522,0.8684952430828314,0.7320503621484618,0.564516037107257,0.14083228658815045 diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon3_model_comparison.md b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon3_model_comparison.md new file mode 100644 index 00000000..46349874 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon3_model_comparison.md @@ -0,0 +1,6 @@ +| model | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:--------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|---------:| +| catboost | 0.83463 | 0.655391 | 0.771144 | 0.708571 | 0.890637 | 0.763497 | 0.598023 | 0.122298 | +| xgboost | 0.839818 | 0.67184 | 0.753731 | 0.710434 | 0.88677 | 0.761105 | 0.602122 | 0.11997 | +| lightgbm | 0.838521 | 0.675862 | 0.731343 | 0.702509 | 0.878843 | 0.743744 | 0.592798 | 0.121036 | +| random_forest | 0.815175 | 0.615842 | 0.773632 | 0.685777 | 0.868495 | 0.73205 | 0.564516 | 0.140832 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon5_model_comparison.csv b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon5_model_comparison.csv new file mode 100644 index 00000000..113dcc12 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon5_model_comparison.csv @@ -0,0 +1,5 @@ +model,accuracy,precision,recall,f1,roc_auc,pr_auc,mcc,brier +catboost,0.8034310221586848,0.6059907834101382,0.7166212534059946,0.6566791510611736,0.8593641087383562,0.707239461549715,0.5239088316271747,0.13865644793831455 +xgboost,0.7912794853466762,0.585812356979405,0.6975476839237057,0.6368159203980099,0.8497005893162665,0.6813391025362026,0.49561940084087247,0.142731174826622 +lightgbm,0.8020014295925662,0.6136363636363636,0.662125340599455,0.6369593709043251,0.8483381914961029,0.6763455997712132,0.5017965664602344,0.13799904854148842 +random_forest,0.779842744817727,0.565121412803532,0.6975476839237057,0.624390243902439,0.8345769173901105,0.6598007560262796,0.47631206524064795,0.15507155075027862 diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon5_model_comparison.md b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon5_model_comparison.md new file mode 100644 index 00000000..244977b6 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon5_model_comparison.md @@ -0,0 +1,6 @@ +| model | accuracy | precision | recall | f1 | roc_auc | pr_auc | mcc | brier | +|:--------------|-----------:|------------:|---------:|---------:|----------:|---------:|---------:|---------:| +| catboost | 0.803431 | 0.605991 | 0.716621 | 0.656679 | 0.859364 | 0.707239 | 0.523909 | 0.138656 | +| xgboost | 0.791279 | 0.585812 | 0.697548 | 0.636816 | 0.849701 | 0.681339 | 0.495619 | 0.142731 | +| lightgbm | 0.802001 | 0.613636 | 0.662125 | 0.636959 | 0.848338 | 0.676346 | 0.501797 | 0.137999 | +| random_forest | 0.779843 | 0.565121 | 0.697548 | 0.62439 | 0.834577 | 0.659801 | 0.476312 | 0.155072 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon_summary.csv b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon_summary.csv new file mode 100644 index 00000000..314800b3 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon_summary.csv @@ -0,0 +1,4 @@ +horizon,best_model,rows,roc_auc,pr_auc,p5,p50,p95,frac_above_0.99 +1,catboost,8515,0.8871371656232214,0.7459898973822718,0.03493804467170691,0.26622871711017937,0.9246592350318289,0.0005871990604815032 +3,catboost,7706,0.8906367286375141,0.7634969713091347,0.03336760292181948,0.2667223860442706,0.9250154424871225,0.0012970168612191958 +5,catboost,6995,0.8593641087383562,0.707239461549715,0.03104572461935311,0.2758446380655407,0.9042286946468086,0.0 diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon_summary.md b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon_summary.md new file mode 100644 index 00000000..1b48c5b3 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/horizon_summary.md @@ -0,0 +1,5 @@ +| horizon | best_model | rows | roc_auc | pr_auc | p5 | p50 | p95 | frac_above_0.99 | +|----------:|:-------------|-------:|----------:|---------:|----------:|---------:|---------:|------------------:| +| 1 | catboost | 8515 | 0.887137 | 0.74599 | 0.034938 | 0.266229 | 0.924659 | 0.000587199 | +| 3 | catboost | 7706 | 0.890637 | 0.763497 | 0.0333676 | 0.266722 | 0.925015 | 0.00129702 | +| 5 | catboost | 6995 | 0.859364 | 0.707239 | 0.0310457 | 0.275845 | 0.904229 | 0 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_1y_catboost.joblib b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_1y_catboost.joblib new file mode 100644 index 00000000..8bd61333 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_1y_catboost.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_1y_reference_quantiles.csv b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_1y_reference_quantiles.csv new file mode 100644 index 00000000..56b6a018 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_1y_reference_quantiles.csv @@ -0,0 +1,1002 @@ +quantile,score +0.0,0.004326960868036728 +0.001,0.007301762262249395 +0.002,0.008353619121197581 +0.003,0.009821251612496017 +0.004,0.010565936672610183 +0.005,0.011120836609435076 +0.006,0.012163733642530586 +0.007,0.01258001818741625 +0.008,0.013200751243066465 +0.009000000000000001,0.014035937230936704 +0.01,0.014735881214086541 +0.011,0.01564392465102663 +0.012,0.01673343906983445 +0.013000000000000001,0.017396055287687586 +0.014,0.018281458481034032 +0.015,0.01891646886444421 +0.016,0.019182525443036978 +0.017,0.019623476706913567 +0.018000000000000002,0.020035597497692553 +0.019,0.020607889872186636 +0.02,0.021112561176099175 +0.021,0.02187431919710493 +0.022,0.02242928072859588 +0.023,0.02295889183028134 +0.024,0.023476793818608975 +0.025,0.023919844596663357 +0.026000000000000002,0.024412196541624662 +0.027,0.024875309493158786 +0.028,0.025467460444051262 +0.029,0.0257365818900545 +0.03,0.02617510806996798 +0.031,0.026630157307084807 +0.032,0.02709878527361433 +0.033,0.02738684084017181 +0.034,0.027840684769027083 +0.035,0.028378928992720837 +0.036000000000000004,0.02879792596326483 +0.037,0.029647592673534617 +0.038,0.03043258487155982 +0.039,0.030752424519024914 +0.04,0.03095199346998265 +0.041,0.031192024002206643 +0.042,0.03149612634496082 +0.043000000000000003,0.03184159882135561 +0.044,0.032286112616130284 +0.045,0.032448297186049434 +0.046,0.03272392358710546 +0.047,0.03322960853963445 +0.048,0.03360881161400196 +0.049,0.03404883140070991 +0.05,0.034314745237255986 +0.051000000000000004,0.034709067007831246 +0.052000000000000005,0.03505729757797706 +0.053,0.035352748772250996 +0.054,0.03587795887093789 +0.055,0.03612731920812441 +0.056,0.03674468069433265 +0.057,0.03701637895759633 +0.058,0.037152653760570684 +0.059000000000000004,0.03743548109035933 +0.06,0.03764255299096665 +0.061,0.03816307952180727 +0.062,0.03839013488119408 +0.063,0.03884351978591592 +0.064,0.03921023781832204 +0.065,0.039572458510687684 +0.066,0.03996685647707092 +0.067,0.04042631064817118 +0.068,0.04083209860812445 +0.069,0.041171274251916246 +0.07,0.04141933420492161 +0.07100000000000001,0.04169844765635453 +0.07200000000000001,0.04192119007666893 +0.073,0.04249587055427048 +0.074,0.042726742891087834 +0.075,0.04327389477804813 +0.076,0.04350825771570267 +0.077,0.04369075212314486 +0.078,0.044045520591169306 +0.079,0.04444362552229992 +0.08,0.044690341735702147 +0.081,0.045001824754585536 +0.082,0.045266578304822135 +0.083,0.045830674560051604 +0.084,0.04601573496233744 +0.085,0.04623833633485489 +0.08600000000000001,0.046499228258927265 +0.08700000000000001,0.04671024649750481 +0.088,0.047149544960957336 +0.089,0.04745025459033846 +0.09,0.047732225790616034 +0.091,0.04802545952500089 +0.092,0.04834312543934235 +0.093,0.048587117963540954 +0.094,0.04872342404666175 +0.095,0.04889607053563138 +0.096,0.049196265609555784 +0.097,0.04952430537459122 +0.098,0.050056197199861104 +0.099,0.05045464613391934 +0.1,0.05098060462068178 +0.101,0.05146286886329935 +0.10200000000000001,0.0516568298616653 +0.10300000000000001,0.05211285196827683 +0.10400000000000001,0.052255945944629324 +0.105,0.0525030042524201 +0.106,0.05288966284992523 +0.107,0.05317634258378183 +0.108,0.053422989172994644 +0.109,0.05367703198324982 +0.11,0.054076496732333335 +0.111,0.05442781260346271 +0.112,0.054860375564994554 +0.113,0.05522444898353922 +0.114,0.05553478618347416 +0.115,0.055991657553014336 +0.116,0.056515975076880366 +0.117,0.05679281823576199 +0.11800000000000001,0.057125312518013345 +0.11900000000000001,0.057351272505794804 +0.12,0.057718250589282476 +0.121,0.05802925873450793 +0.122,0.058383701519908425 +0.123,0.05877593300637689 +0.124,0.05893771120511132 +0.125,0.05938939949974201 +0.126,0.059558950441245116 +0.127,0.059897380350408064 +0.128,0.060260652863360124 +0.129,0.060655356992371116 +0.13,0.0608259875597373 +0.131,0.061358515987345895 +0.132,0.0617858067516716 +0.133,0.0623261137679284 +0.134,0.0625703654453098 +0.135,0.0631304210460871 +0.136,0.06335525113269337 +0.137,0.06373251051372907 +0.138,0.06398588537139217 +0.139,0.06435858754291919 +0.14,0.06466121726680962 +0.14100000000000001,0.06489783892620979 +0.14200000000000002,0.06520150708839664 +0.14300000000000002,0.06563526556606455 +0.14400000000000002,0.06606109737903662 +0.145,0.06648173226589744 +0.146,0.06672574149314808 +0.147,0.06696959860349615 +0.148,0.06727217104450298 +0.149,0.06793310208016032 +0.15,0.06853228877132221 +0.151,0.06882935846809171 +0.152,0.06934549577098158 +0.153,0.06959617801613344 +0.154,0.06976276966695014 +0.155,0.07008140852815742 +0.156,0.07086534716943498 +0.157,0.07115094283947133 +0.158,0.07150825594691991 +0.159,0.07174530788950768 +0.16,0.07217150148088451 +0.161,0.07240583665367574 +0.162,0.07263781897877516 +0.163,0.072975543296852 +0.164,0.07344764560703095 +0.165,0.0737704583329478 +0.166,0.07407811589078163 +0.167,0.07443902553383377 +0.168,0.074775399598245 +0.169,0.07538624157644067 +0.17,0.0759553210633203 +0.171,0.07636820955013683 +0.17200000000000001,0.07678134532480312 +0.17300000000000001,0.07711130723851604 +0.17400000000000002,0.07749392522739647 +0.17500000000000002,0.0778531570593911 +0.176,0.07810854723215852 +0.177,0.07834643122196765 +0.178,0.07861289168957357 +0.179,0.07890236625607858 +0.18,0.07938375441247814 +0.181,0.07963915239314213 +0.182,0.08001986582574828 +0.183,0.08027007564523152 +0.184,0.08086812923325443 +0.185,0.08120340718713631 +0.186,0.08145985281003841 +0.187,0.08191749888008812 +0.188,0.08220634566479672 +0.189,0.08239711949909825 +0.19,0.08275973958582285 +0.191,0.08328606043492175 +0.192,0.08366061281081469 +0.193,0.08401013065058943 +0.194,0.08451027630151811 +0.195,0.08512016405863619 +0.196,0.08546543553551302 +0.197,0.08577356235070119 +0.198,0.08606589716347485 +0.199,0.08647846131729395 +0.2,0.087226377577999 +0.201,0.08766654861327237 +0.202,0.08792288117874641 +0.203,0.08823312646436696 +0.20400000000000001,0.08861524253613182 +0.20500000000000002,0.08906559551078384 +0.20600000000000002,0.08926633264608307 +0.20700000000000002,0.08963976970951039 +0.20800000000000002,0.0901876575812819 +0.209,0.09057449001879725 +0.21,0.09099653475085515 +0.211,0.09124807941569259 +0.212,0.09159761051310746 +0.213,0.09187366393451254 +0.214,0.09242406801165219 +0.215,0.09280600568259832 +0.216,0.0931082334619101 +0.217,0.09372300504514054 +0.218,0.09385327028901987 +0.219,0.09424129954139261 +0.22,0.09465784390148285 +0.221,0.09509020340688083 +0.222,0.09557362297163413 +0.223,0.09595767681284696 +0.224,0.09658376972664601 +0.225,0.09693648540160035 +0.226,0.09722273250550813 +0.227,0.0977994451362888 +0.228,0.09821601533824711 +0.229,0.09860378328664103 +0.23,0.09891704048710014 +0.231,0.09917385558741545 +0.232,0.09945312590903188 +0.233,0.09973780900740618 +0.234,0.10016382966088297 +0.23500000000000001,0.10077539416569178 +0.23600000000000002,0.10112467345486663 +0.23700000000000002,0.101523314434892 +0.23800000000000002,0.10190109109193476 +0.23900000000000002,0.10214748858779445 +0.24,0.10238697318128127 +0.241,0.10277530893036509 +0.242,0.10320292651488894 +0.243,0.10364223116289908 +0.244,0.10417248268560544 +0.245,0.1046302985330386 +0.246,0.10497037606304084 +0.247,0.10520828985866702 +0.248,0.10539954680640468 +0.249,0.10580686630623622 +0.25,0.10626055426897005 +0.251,0.10684196363846839 +0.252,0.10707587908019969 +0.253,0.10783131718646083 +0.254,0.1084081716727126 +0.255,0.10876881772306424 +0.256,0.10924222924712641 +0.257,0.10950902784018993 +0.258,0.11001049139058097 +0.259,0.11057694869727443 +0.26,0.11116625052981523 +0.261,0.11180587290688197 +0.262,0.11227927642999785 +0.263,0.11272889598889602 +0.264,0.11308642573646718 +0.265,0.11383024843795325 +0.266,0.11421650281414684 +0.267,0.11499159049837372 +0.268,0.11545895592286289 +0.269,0.11603231610037389 +0.27,0.11679464997911457 +0.271,0.11708648840099911 +0.272,0.11744345732789081 +0.273,0.11784592370042944 +0.274,0.1184482281613487 +0.275,0.11871113199487582 +0.276,0.11888632109079457 +0.277,0.11928293549088052 +0.278,0.11983859150951899 +0.279,0.1202050100582724 +0.28,0.1205502910968778 +0.281,0.12105974336903907 +0.28200000000000003,0.12144278938456624 +0.28300000000000003,0.12187145811952961 +0.28400000000000003,0.12228426353779863 +0.28500000000000003,0.12252069478073752 +0.28600000000000003,0.12325737997530897 +0.28700000000000003,0.12360622261526069 +0.28800000000000003,0.124003745948362 +0.289,0.12436899587384609 +0.29,0.1246624174244418 +0.291,0.12490144893981447 +0.292,0.1254012834739967 +0.293,0.12568459201666227 +0.294,0.12615999237928816 +0.295,0.12675388840149066 +0.296,0.1272439203654099 +0.297,0.12754794513279621 +0.298,0.12801078714690986 +0.299,0.12860749897836016 +0.3,0.12926328166751325 +0.301,0.1295529930592883 +0.302,0.1301656625151197 +0.303,0.13041609690640626 +0.304,0.13069874743768975 +0.305,0.13131494662090168 +0.306,0.13175266184149328 +0.307,0.13211541876494792 +0.308,0.13255931423773482 +0.309,0.13311930958882467 +0.31,0.13364097443052667 +0.311,0.13397535290682616 +0.312,0.13446822967934197 +0.313,0.13475493525485285 +0.314,0.13532916415147167 +0.315,0.13588547696920908 +0.316,0.1362195844913053 +0.317,0.13676433084332199 +0.318,0.13703118064355863 +0.319,0.1378201119282114 +0.32,0.13831059573697468 +0.321,0.1388664446464554 +0.322,0.1394750614643045 +0.323,0.13990386657006718 +0.324,0.1401448571280558 +0.325,0.14063138442612183 +0.326,0.14087148367907076 +0.327,0.14126621776217155 +0.328,0.14177214493946738 +0.329,0.1420510237423646 +0.33,0.14248396327321247 +0.331,0.14298873166972415 +0.332,0.143433987995409 +0.333,0.1442104937495483 +0.334,0.14469523046127067 +0.335,0.1455078532293627 +0.336,0.1461508964301294 +0.337,0.14647826284259224 +0.338,0.14731676253526743 +0.339,0.1478069417041267 +0.34,0.1481855622261322 +0.341,0.14856682711414387 +0.342,0.14911892748175104 +0.343,0.14943034543526573 +0.34400000000000003,0.1500999650808431 +0.34500000000000003,0.1505048551758251 +0.34600000000000003,0.15099157328140678 +0.34700000000000003,0.15146831422231027 +0.34800000000000003,0.15199311178051592 +0.34900000000000003,0.1523675328965801 +0.35000000000000003,0.15292185709577286 +0.35100000000000003,0.15341886986448405 +0.352,0.15394147840202516 +0.353,0.15500015338002573 +0.354,0.15609208777167802 +0.355,0.15679694297950425 +0.356,0.15717369952453636 +0.357,0.15763637094234734 +0.358,0.15795630473177566 +0.359,0.15833656624719084 +0.36,0.15884822151145025 +0.361,0.1598663016770999 +0.362,0.16056311846505958 +0.363,0.16120740381089868 +0.364,0.16176852680670017 +0.365,0.1621095461843518 +0.366,0.16273657695076857 +0.367,0.1632566702525362 +0.368,0.16398843755137626 +0.369,0.16439891324883185 +0.37,0.16529765344633943 +0.371,0.1657656923089615 +0.372,0.16609157210611253 +0.373,0.1671001041190215 +0.374,0.16796910058822778 +0.375,0.16882059636484723 +0.376,0.16938416723009095 +0.377,0.16974944555532495 +0.378,0.1706362660509982 +0.379,0.17130387818521073 +0.38,0.17234229032053308 +0.381,0.1728554966211062 +0.382,0.1737327056658039 +0.383,0.17434064420026293 +0.384,0.175109442145866 +0.385,0.17559972379814356 +0.386,0.17607783367503946 +0.387,0.1764357683892163 +0.388,0.17675109228861957 +0.389,0.1773504243929517 +0.39,0.1779356244302332 +0.391,0.1787038616503578 +0.392,0.17963884254534015 +0.393,0.18037198611276037 +0.394,0.1810672782464319 +0.395,0.1813772069765228 +0.396,0.18199069235378423 +0.397,0.18286786494854002 +0.398,0.18322597495265006 +0.399,0.18356187409717015 +0.4,0.18464339865501778 +0.401,0.185390188634119 +0.402,0.18629311440262228 +0.403,0.18698016410479829 +0.404,0.18750858920177652 +0.405,0.18797559313797216 +0.406,0.1890225696575043 +0.40700000000000003,0.18936773500711548 +0.40800000000000003,0.19005320037784143 +0.40900000000000003,0.19096320564591618 +0.41000000000000003,0.191694315164994 +0.41100000000000003,0.1923501796965902 +0.41200000000000003,0.19297463094719763 +0.41300000000000003,0.19339974319632097 +0.41400000000000003,0.19391991801864525 +0.41500000000000004,0.19475444616212328 +0.41600000000000004,0.19546482675030807 +0.417,0.1958239309925363 +0.418,0.19630119851902778 +0.419,0.19696698406003374 +0.42,0.19760601493417737 +0.421,0.19872250264850064 +0.422,0.19915605512385776 +0.423,0.19991918054301072 +0.424,0.20064473095878563 +0.425,0.20122994739597752 +0.426,0.20169365259950453 +0.427,0.20234872349256217 +0.428,0.2030211301356804 +0.429,0.20394378169809768 +0.43,0.20424343845729478 +0.431,0.20497639993513597 +0.432,0.20619736357633178 +0.433,0.20676167308810856 +0.434,0.20732664708930415 +0.435,0.20816705960188533 +0.436,0.20921817172592602 +0.437,0.20990485430924516 +0.438,0.21052111939614784 +0.439,0.21151238090111607 +0.44,0.211922074406409 +0.441,0.21291146998051663 +0.442,0.21376424535230582 +0.443,0.21460411419118472 +0.444,0.21541715658599783 +0.445,0.21580793751413407 +0.446,0.2163973009942535 +0.447,0.21696709694130573 +0.448,0.21743998853165059 +0.449,0.2178842202440209 +0.45,0.2184718247469101 +0.451,0.21992179165906117 +0.452,0.2209842305938885 +0.453,0.22141899580127977 +0.454,0.22193816224268662 +0.455,0.22263267671437198 +0.456,0.22355541037217597 +0.457,0.22378227675556614 +0.458,0.22444531582917734 +0.459,0.2258703794453651 +0.46,0.22669411819295981 +0.461,0.22804557033388562 +0.462,0.22972621709673605 +0.463,0.23061081064316724 +0.464,0.23113023787533188 +0.465,0.23232172967636863 +0.466,0.23304603851080805 +0.467,0.2339267874810159 +0.468,0.23574028921725865 +0.46900000000000003,0.23671123353077747 +0.47000000000000003,0.23759007040118166 +0.47100000000000003,0.23822723204581447 +0.47200000000000003,0.2395366323455467 +0.47300000000000003,0.24048956197868673 +0.47400000000000003,0.24096286348016369 +0.47500000000000003,0.24191606910714092 +0.47600000000000003,0.24280837627420923 +0.47700000000000004,0.24363317107972782 +0.47800000000000004,0.24452451100389444 +0.47900000000000004,0.2451500004889598 +0.48,0.24623568961290365 +0.481,0.24680074793683052 +0.482,0.24773350535899602 +0.483,0.2485471014383961 +0.484,0.24922981151866294 +0.485,0.2500600387736115 +0.486,0.25122296408493333 +0.487,0.25169358846071144 +0.488,0.2529886421453687 +0.489,0.25373274031503545 +0.49,0.25462456629721786 +0.491,0.2551779123901099 +0.492,0.25616532761303706 +0.493,0.2568232112610203 +0.494,0.25778232267031365 +0.495,0.25851747023772836 +0.496,0.25946079480026724 +0.497,0.2600954076174713 +0.498,0.2609527356264362 +0.499,0.2617634609279954 +0.5,0.26239666001747486 +0.501,0.26367424084696295 +0.502,0.2652711510671486 +0.503,0.2659205803708442 +0.504,0.26674530834529525 +0.505,0.26732341649210417 +0.506,0.26823253367284267 +0.507,0.2688390610942584 +0.508,0.26987510977311646 +0.509,0.270765247068826 +0.51,0.27180344913353094 +0.511,0.2727722507310409 +0.512,0.2736401841583317 +0.513,0.2744759619404677 +0.514,0.2757654659019817 +0.515,0.27663416273468644 +0.516,0.27772896214144815 +0.517,0.2787380666213008 +0.518,0.2803440990047268 +0.519,0.28153073973444387 +0.52,0.2822406015632924 +0.521,0.28305655333253993 +0.522,0.2835838062866005 +0.523,0.2845091621370312 +0.524,0.28523160153341665 +0.525,0.28594891910972 +0.526,0.28780137470071887 +0.527,0.28874486874106414 +0.528,0.2899918484058142 +0.529,0.2912467031950302 +0.53,0.2923127404127939 +0.531,0.29333813816182003 +0.532,0.2940066335405979 +0.533,0.2952344228676742 +0.534,0.29672755720554345 +0.535,0.2983690002359541 +0.536,0.29957951844850583 +0.537,0.2999519956306758 +0.538,0.30136600882156755 +0.539,0.3023303056182912 +0.54,0.3030839368577132 +0.541,0.305309366679622 +0.542,0.30726863172114643 +0.543,0.30828262906894116 +0.544,0.3098706165794925 +0.545,0.31059562617417563 +0.546,0.3115528265105245 +0.547,0.3125141430460405 +0.548,0.3133821394245965 +0.549,0.3143795145481611 +0.55,0.31567277905349667 +0.551,0.31692613500388694 +0.552,0.3189274867190026 +0.553,0.319907012384735 +0.554,0.3211540087372924 +0.555,0.32235446780708454 +0.556,0.3235586451752667 +0.557,0.32488262879409163 +0.558,0.32571684103894233 +0.559,0.3262094543479087 +0.56,0.3268086092667386 +0.561,0.3286734732723596 +0.562,0.3295095073082167 +0.5630000000000001,0.33037496217018447 +0.5640000000000001,0.33135532539745155 +0.5650000000000001,0.33256822573664974 +0.5660000000000001,0.3337117927350759 +0.5670000000000001,0.33501555962844837 +0.5680000000000001,0.3357291014354101 +0.5690000000000001,0.336765986937461 +0.5700000000000001,0.33810999544902265 +0.5710000000000001,0.3386266237221218 +0.5720000000000001,0.3397795712650209 +0.5730000000000001,0.34075913285533327 +0.5740000000000001,0.3419054382037216 +0.5750000000000001,0.34281025652894465 +0.5760000000000001,0.34376090174792934 +0.577,0.34484096595098507 +0.578,0.3456893326658739 +0.579,0.3465833127085544 +0.58,0.3480361312809451 +0.581,0.34915190183787004 +0.582,0.35002615719470886 +0.583,0.35227417491598756 +0.584,0.3530643107173271 +0.585,0.35382860953236467 +0.586,0.3551619854846873 +0.587,0.3568406141960664 +0.588,0.3580937389621918 +0.589,0.3587579191729053 +0.59,0.3600138266749855 +0.591,0.36089923303376464 +0.592,0.3615957931127899 +0.593,0.36254008661087644 +0.594,0.364526784157752 +0.595,0.36576593926252204 +0.596,0.3670761182141618 +0.597,0.36906256573941376 +0.598,0.3699503676797926 +0.599,0.37124822221033826 +0.6,0.3721782895924814 +0.601,0.37317278895475 +0.602,0.37392256348435143 +0.603,0.3746331668107033 +0.604,0.37525524213954026 +0.605,0.37632133012806523 +0.606,0.3782583981569518 +0.607,0.3793794547849599 +0.608,0.3804256284378429 +0.609,0.38181099736477453 +0.61,0.3832551354840523 +0.611,0.38501997626459333 +0.612,0.38681140095995903 +0.613,0.38783550364712754 +0.614,0.3889384051826466 +0.615,0.3899073266167489 +0.616,0.39116149364784925 +0.617,0.3931131647803561 +0.618,0.3945329688577255 +0.619,0.3956061149718965 +0.62,0.3971462209514959 +0.621,0.39857381096064165 +0.622,0.3995576406666334 +0.623,0.4009735868220902 +0.624,0.4025337893149332 +0.625,0.40402157605245204 +0.626,0.4058270045892078 +0.627,0.40755050677154314 +0.628,0.4095198981076194 +0.629,0.4106120059626796 +0.63,0.41153037668328135 +0.631,0.4127300482394073 +0.632,0.41399824747758274 +0.633,0.4151880356282308 +0.634,0.41612290768032284 +0.635,0.41735421163649594 +0.636,0.41833711847422145 +0.637,0.4193995455397714 +0.638,0.4206999102274566 +0.639,0.42189687896530187 +0.64,0.4230148424353934 +0.641,0.4241840703536028 +0.642,0.426605448351409 +0.643,0.42785595190786635 +0.644,0.4290879730548654 +0.645,0.43091597866339715 +0.646,0.4319256684993305 +0.647,0.43428390720854243 +0.648,0.43560192762170535 +0.649,0.43726213646525747 +0.65,0.4390581491335075 +0.651,0.44088754774275307 +0.652,0.4425358990462157 +0.653,0.4437599956238195 +0.654,0.4446649322233345 +0.655,0.4463344455352927 +0.656,0.4486915189030668 +0.657,0.44994626647794816 +0.658,0.4520864342310405 +0.659,0.45389274545569447 +0.66,0.4560653228836498 +0.661,0.4585872145961324 +0.662,0.4609453999190111 +0.663,0.4631203023977345 +0.664,0.464999451442492 +0.665,0.4669602373281889 +0.666,0.46875873944777213 +0.667,0.47065921107397274 +0.668,0.47243484948580494 +0.669,0.47372200791397756 +0.67,0.47554856127139955 +0.671,0.47686369024947367 +0.672,0.47778432588423886 +0.673,0.4787011257029193 +0.674,0.48009788355882316 +0.675,0.4810374973712469 +0.676,0.4816118563065304 +0.677,0.4833580053005656 +0.678,0.4843627032249839 +0.679,0.4861649225964126 +0.68,0.4874514438400093 +0.681,0.4889763450462367 +0.682,0.4918313788097039 +0.683,0.4935155493349159 +0.684,0.49571581226142214 +0.685,0.49688859871030144 +0.686,0.49949318289557476 +0.687,0.5019243556558282 +0.6880000000000001,0.5039414035353005 +0.6890000000000001,0.5048408276713957 +0.6900000000000001,0.506383099956064 +0.6910000000000001,0.5078900045939962 +0.6920000000000001,0.50923204217972 +0.6930000000000001,0.5120740680911813 +0.6940000000000001,0.5138704767203914 +0.6950000000000001,0.5155939498394886 +0.6960000000000001,0.517605168782439 +0.6970000000000001,0.5199539913610361 +0.6980000000000001,0.5214134040217545 +0.6990000000000001,0.5221490963284675 +0.7000000000000001,0.5236093749845807 +0.7010000000000001,0.5262569040003054 +0.7020000000000001,0.5282315806000868 +0.7030000000000001,0.5297342066566673 +0.704,0.5317117174864503 +0.705,0.5332814705269826 +0.706,0.5347242436232474 +0.707,0.5370581384400775 +0.708,0.5390847950889521 +0.709,0.540022438523288 +0.71,0.541879839240609 +0.711,0.5435665184258802 +0.712,0.5449955591492208 +0.713,0.5470594796329321 +0.714,0.5484752010740013 +0.715,0.5509422778404285 +0.716,0.5527296455867768 +0.717,0.5548744245859484 +0.718,0.556613108437334 +0.719,0.5588011694150209 +0.72,0.5613291283353862 +0.721,0.5626447945309488 +0.722,0.5639333753468505 +0.723,0.5660171667818028 +0.724,0.5673239487179572 +0.725,0.5705702347032452 +0.726,0.5723680645417144 +0.727,0.5742602251960677 +0.728,0.5764274851335837 +0.729,0.5784991402209116 +0.73,0.5811745751947706 +0.731,0.5828717809490588 +0.732,0.5850362165967766 +0.733,0.5871808036352404 +0.734,0.5894454036350872 +0.735,0.590775400611203 +0.736,0.5938432387489202 +0.737,0.5964982792468944 +0.738,0.5993264846258711 +0.739,0.6016572333638422 +0.74,0.6051441549351455 +0.741,0.6074082127161494 +0.742,0.6099115691214748 +0.743,0.6119654622043816 +0.744,0.6127630256680875 +0.745,0.6140421841296052 +0.746,0.6152646452512612 +0.747,0.618469134731225 +0.748,0.6209126354370497 +0.749,0.622308990125873 +0.75,0.6254343958095098 +0.751,0.6275234111247541 +0.752,0.6287661862937602 +0.753,0.631890667855491 +0.754,0.6337928971124126 +0.755,0.6349891877418926 +0.756,0.6360972592096976 +0.757,0.6385226537050277 +0.758,0.6396161726737385 +0.759,0.6422127954443082 +0.76,0.643004180882892 +0.761,0.6449935596447683 +0.762,0.6462064620020029 +0.763,0.6489859769112132 +0.764,0.6514841928739464 +0.765,0.6536821580726178 +0.766,0.6558610519197491 +0.767,0.6601202121990236 +0.768,0.663218643352196 +0.769,0.6645342390017394 +0.77,0.6664645151167595 +0.771,0.6680505402063451 +0.772,0.6703272516496964 +0.773,0.6716385351111803 +0.774,0.6734915709034703 +0.775,0.6751464203576714 +0.776,0.6766802855018096 +0.777,0.6793713573138735 +0.778,0.6812495099960773 +0.779,0.6834521627792981 +0.78,0.6851893029992744 +0.781,0.6867276656214742 +0.782,0.688557784170827 +0.783,0.690011331115477 +0.784,0.692347105029656 +0.785,0.6937124674140915 +0.786,0.6959815501680346 +0.787,0.6978951998685058 +0.788,0.7004310313611753 +0.789,0.7031933061888818 +0.79,0.7051154269060812 +0.791,0.7068469139440745 +0.792,0.7091885441961796 +0.793,0.7110912902370834 +0.794,0.7118485502501172 +0.795,0.7143577858684232 +0.796,0.7153709425807482 +0.797,0.7174648893062957 +0.798,0.7188975424212518 +0.799,0.7214007047896814 +0.8,0.7230351579484816 +0.801,0.7248091588150484 +0.802,0.7271246459375852 +0.803,0.7292464988263413 +0.804,0.7306859975957831 +0.805,0.7327689588958399 +0.806,0.7345704353727714 +0.807,0.7357110291764819 +0.808,0.7387377875850143 +0.809,0.7412957238825566 +0.81,0.7430800770980391 +0.811,0.74506187096627 +0.812,0.747338076377908 +0.8130000000000001,0.7499450657538282 +0.8140000000000001,0.7519487380748409 +0.8150000000000001,0.7541093828628174 +0.8160000000000001,0.7550157881350563 +0.8170000000000001,0.7573939451090962 +0.8180000000000001,0.759160031111152 +0.8190000000000001,0.761822175667429 +0.8200000000000001,0.7642646758475168 +0.8210000000000001,0.7661257203848039 +0.8220000000000001,0.7678166362446789 +0.8230000000000001,0.7697718454118145 +0.8240000000000001,0.7721694932411722 +0.8250000000000001,0.7740636709127633 +0.8260000000000001,0.776492496425307 +0.8270000000000001,0.7782297121126059 +0.8280000000000001,0.7794370245716783 +0.8290000000000001,0.7806469830675882 +0.8300000000000001,0.7829073541354873 +0.8310000000000001,0.7844655301378907 +0.8320000000000001,0.7861803970626448 +0.833,0.7866046869458447 +0.834,0.7889267619278035 +0.835,0.7907646298147514 +0.836,0.7931028276782597 +0.837,0.7946208595346086 +0.838,0.7957474100558128 +0.839,0.7973660802283654 +0.84,0.7989277010800163 +0.841,0.8014088816019702 +0.842,0.802747963443687 +0.843,0.8036604712884335 +0.844,0.8052589712868781 +0.845,0.8063913041032987 +0.846,0.8080065948595849 +0.847,0.8090407477250895 +0.848,0.8099193877908486 +0.849,0.8118431538619316 +0.85,0.8133438236220896 +0.851,0.8149790540405345 +0.852,0.8162540865520347 +0.853,0.8190527738341675 +0.854,0.8206738645783158 +0.855,0.8223629479395566 +0.856,0.8241055335989235 +0.857,0.8249412760649677 +0.858,0.8261951072601064 +0.859,0.8272664309431931 +0.86,0.828211596285352 +0.861,0.8294866757101428 +0.862,0.8308280209658643 +0.863,0.8319330972518754 +0.864,0.8337000288742241 +0.865,0.836138856529228 +0.866,0.8383658334952854 +0.867,0.8395690661631146 +0.868,0.841266602407655 +0.869,0.8423230920475696 +0.87,0.8430591973614966 +0.871,0.8443624881234754 +0.872,0.8458198781491374 +0.873,0.848054936407816 +0.874,0.8488776228921577 +0.875,0.8504371995178965 +0.876,0.8513471102161023 +0.877,0.8521963331575724 +0.878,0.8532481176551447 +0.879,0.8543104474366866 +0.88,0.8552638625848662 +0.881,0.8565721623861683 +0.882,0.8578913068020552 +0.883,0.8596285553049987 +0.884,0.8606476464047346 +0.885,0.8622422128121681 +0.886,0.8632291979337968 +0.887,0.8644942744415496 +0.888,0.8653288083777844 +0.889,0.8669620948644716 +0.89,0.8678060428138831 +0.891,0.8693288899508957 +0.892,0.8713439718922912 +0.893,0.8728185983276374 +0.894,0.8743113974770872 +0.895,0.8757792299127577 +0.896,0.8782899659615621 +0.897,0.8792424083681071 +0.898,0.8800040581166769 +0.899,0.881195332029655 +0.9,0.8824636505811341 +0.901,0.8842550690122815 +0.902,0.8855822509828477 +0.903,0.8864380193897694 +0.904,0.8878131899556673 +0.905,0.8888024501788908 +0.906,0.8894779670422639 +0.907,0.8906990216402623 +0.908,0.891848472824758 +0.909,0.8929114413018936 +0.91,0.8940600894245653 +0.911,0.894945181501919 +0.912,0.8956868503142953 +0.913,0.8971306002369466 +0.914,0.8985833877511452 +0.915,0.899868669606195 +0.916,0.9005613701241005 +0.917,0.9018424386277369 +0.918,0.9028574595051614 +0.919,0.9045287715732561 +0.92,0.905583469272654 +0.921,0.9067402268057864 +0.922,0.907825975864095 +0.923,0.909009251264887 +0.924,0.9095864187587489 +0.925,0.9107304352022053 +0.926,0.911814237511663 +0.927,0.9129926864006435 +0.928,0.9141924497854875 +0.929,0.9153607350606668 +0.93,0.916615279257852 +0.931,0.9172508327086905 +0.932,0.9188164982797872 +0.933,0.9201621813553532 +0.934,0.9209399237897957 +0.935,0.9217908147648769 +0.936,0.9230945125682886 +0.937,0.9239126531293322 +0.9380000000000001,0.9246212077923079 +0.9390000000000001,0.9252651921984776 +0.9400000000000001,0.9265493625507769 +0.9410000000000001,0.9282330072417716 +0.9420000000000001,0.9290772374051356 +0.9430000000000001,0.9301564866689174 +0.9440000000000001,0.9309348153592459 +0.9450000000000001,0.9315249563043705 +0.9460000000000001,0.9331163269848178 +0.9470000000000001,0.9342221061633097 +0.9480000000000001,0.9350507620983836 +0.9490000000000001,0.9359984898748261 +0.9500000000000001,0.9364406914540373 +0.9510000000000001,0.9378603730723831 +0.9520000000000001,0.9386124750914927 +0.9530000000000001,0.9394405572454265 +0.9540000000000001,0.940599306334937 +0.9550000000000001,0.9418361496190994 +0.9560000000000001,0.943205958001646 +0.9570000000000001,0.9438551965564381 +0.9580000000000001,0.9447095458643616 +0.9590000000000001,0.945782727889325 +0.96,0.9467243072406518 +0.961,0.9476513666316594 +0.962,0.9484004084667901 +0.963,0.9493212200440948 +0.964,0.9503369160958689 +0.965,0.9509573535291973 +0.966,0.9519383719808774 +0.967,0.9527905053729677 +0.968,0.9539311242322966 +0.969,0.9543475162597191 +0.97,0.9555253321289058 +0.971,0.9564484792744875 +0.972,0.9570132679686254 +0.973,0.9580953281761142 +0.974,0.9590861092778451 +0.975,0.9596183514632001 +0.976,0.9601705964609771 +0.977,0.9617868353669167 +0.978,0.9628993913636452 +0.979,0.9642809851418357 +0.98,0.965334757015424 +0.981,0.966552807624351 +0.982,0.967050322606846 +0.983,0.9683410894059646 +0.984,0.9690034641811202 +0.985,0.9696615320556976 +0.986,0.9702247623908706 +0.987,0.9711476345302531 +0.988,0.9728091218937606 +0.989,0.9744828307665236 +0.99,0.9758565409115065 +0.991,0.976941124654224 +0.992,0.9778691670254446 +0.993,0.9791517817442605 +0.994,0.9797960743409172 +0.995,0.9815673123216156 +0.996,0.9835332623429155 +0.997,0.9849948150437549 +0.998,0.9868333460213282 +0.999,0.9876185183554548 +1.0,0.9977031602755205 diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_1y_xgboost.joblib b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_1y_xgboost.joblib new file mode 100644 index 00000000..b5718cab Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_1y_xgboost.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_3y_catboost.joblib b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_3y_catboost.joblib new file mode 100644 index 00000000..6b3810aa Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_3y_catboost.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_3y_lightgbm.joblib b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_3y_lightgbm.joblib new file mode 100644 index 00000000..3b7a8edc Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_3y_lightgbm.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_3y_reference_quantiles.csv b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_3y_reference_quantiles.csv new file mode 100644 index 00000000..ce9016a2 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_3y_reference_quantiles.csv @@ -0,0 +1,1002 @@ +quantile,score +0.0,0.0018081292553091444 +0.001,0.005012424260844976 +0.002,0.006526496527735387 +0.003,0.007532316628990469 +0.004,0.008541144195073474 +0.005,0.009371455441460369 +0.006,0.010070046070973098 +0.007,0.011023905034820036 +0.008,0.011773390739810175 +0.009000000000000001,0.012447840918967468 +0.01,0.013438095455096789 +0.011,0.014262215452732641 +0.012,0.014849785188490644 +0.013000000000000001,0.01538639777502633 +0.014,0.01645783202780307 +0.015,0.016912116567821493 +0.016,0.017644928029824716 +0.017,0.018417470973185013 +0.018000000000000002,0.018963730158421722 +0.019,0.0194095766915256 +0.02,0.019863439631739085 +0.021,0.020205856093507755 +0.022,0.021230865016946633 +0.023,0.02203604969692626 +0.024,0.02243647839175729 +0.025,0.023267068983819195 +0.026000000000000002,0.02366354681574128 +0.027,0.02432230576816416 +0.028,0.024824507315289606 +0.029,0.025492989587105663 +0.03,0.025974781399530158 +0.031,0.026262318431572944 +0.032,0.026911170985933694 +0.033,0.027313969775472517 +0.034,0.027758867257089898 +0.035,0.02819006469250437 +0.036000000000000004,0.028637972512232133 +0.037,0.028921782775366566 +0.038,0.029379390421163713 +0.039,0.02957499955104269 +0.04,0.029937175138603053 +0.041,0.030253026399476964 +0.042,0.03073753820195446 +0.043000000000000003,0.03113791477894917 +0.044,0.031619233394917554 +0.045,0.03180702368340952 +0.046,0.03248418660959981 +0.047,0.03278612413491676 +0.048,0.03302399318278363 +0.049,0.033409467619890394 +0.05,0.03380077903398372 +0.051000000000000004,0.03401365593848096 +0.052000000000000005,0.03423986184475763 +0.053,0.034468840500964916 +0.054,0.034752409618669655 +0.055,0.03525568639110507 +0.056,0.035584641763565905 +0.057,0.035805656787311874 +0.058,0.03602114815690658 +0.059000000000000004,0.036203964378520255 +0.06,0.036589226225539964 +0.061,0.036709715345040014 +0.062,0.03718363758965182 +0.063,0.0376374487808794 +0.064,0.037941332439900666 +0.065,0.03806326656349376 +0.066,0.03835273859769419 +0.067,0.038916477583201915 +0.068,0.03913781014851379 +0.069,0.03934410964511788 +0.07,0.03965355529644629 +0.07100000000000001,0.040062008120955825 +0.07200000000000001,0.04022213919622792 +0.073,0.04056808268540455 +0.074,0.040810940798992314 +0.075,0.040994094155403775 +0.076,0.041405215954945375 +0.077,0.04161860378308956 +0.078,0.04197008716774734 +0.079,0.04232275568624757 +0.08,0.04252576753027907 +0.081,0.0429488069854397 +0.082,0.043314200170803535 +0.083,0.043706938344182406 +0.084,0.044127353579103724 +0.085,0.04432372704086 +0.08600000000000001,0.04462466578932793 +0.08700000000000001,0.04504983785119751 +0.088,0.04531450179401039 +0.089,0.04558752508769685 +0.09,0.04593241364283953 +0.091,0.046367210847820445 +0.092,0.046619925356828115 +0.093,0.04702741475429597 +0.094,0.0471402761513746 +0.095,0.04755323015423657 +0.096,0.04778538972519019 +0.097,0.048276918940902316 +0.098,0.04869043486246865 +0.099,0.04897344244594413 +0.1,0.049232447181932225 +0.101,0.04950542540901037 +0.10200000000000001,0.04982509619146095 +0.10300000000000001,0.050208851948217004 +0.10400000000000001,0.05055326112607322 +0.105,0.05087038295236726 +0.106,0.05101770392974393 +0.107,0.05119206022094689 +0.108,0.05148709536221577 +0.109,0.05174456999480586 +0.11,0.05209592448137722 +0.111,0.05255872200371336 +0.112,0.053076185777896245 +0.113,0.0534826332041097 +0.114,0.05365985596643056 +0.115,0.054035348621269595 +0.116,0.05444761468981994 +0.117,0.05470606131957403 +0.11800000000000001,0.05500261864618377 +0.11900000000000001,0.055342087246928295 +0.12,0.055642101557370274 +0.121,0.055937568800188596 +0.122,0.056314811596828794 +0.123,0.056828311838298354 +0.124,0.057226785523510584 +0.125,0.057927118571936435 +0.126,0.058164038503952145 +0.127,0.05847428881092836 +0.128,0.0587371926886875 +0.129,0.059189306755755865 +0.13,0.059334603792498594 +0.131,0.0596579192519378 +0.132,0.059898739234645 +0.133,0.060175639997342795 +0.134,0.06046517811051858 +0.135,0.060827891071350136 +0.136,0.06124773545457779 +0.137,0.06155926428705422 +0.138,0.0617380136514258 +0.139,0.06201741288041299 +0.14,0.06219196712276044 +0.14100000000000001,0.0623875454902671 +0.14200000000000002,0.06270546739330449 +0.14300000000000002,0.06297689553832052 +0.14400000000000002,0.06326718526443384 +0.145,0.06378010842436838 +0.146,0.06427657179352421 +0.147,0.06467433347140279 +0.148,0.06499060586633636 +0.149,0.06522291648884747 +0.15,0.06557110396611239 +0.151,0.06590161840188069 +0.152,0.066371451366791 +0.153,0.0666348619338074 +0.154,0.0669443957357432 +0.155,0.06733704625771675 +0.156,0.06758273917186819 +0.157,0.06800032279628515 +0.158,0.06829200266849775 +0.159,0.06860825288398467 +0.16,0.0688926240605606 +0.161,0.06899763562344365 +0.162,0.06930004069740289 +0.163,0.06960022021908409 +0.164,0.06993644012122464 +0.165,0.07007114549143707 +0.166,0.0704708059257209 +0.167,0.07071496709441702 +0.168,0.07106059259346235 +0.169,0.07135945264841695 +0.17,0.0715275392576466 +0.171,0.07178164343084521 +0.17200000000000001,0.07231454485337609 +0.17300000000000001,0.07248920439609007 +0.17400000000000002,0.07270896147904883 +0.17500000000000002,0.07311668340343515 +0.176,0.0736007206345128 +0.177,0.07390391621893444 +0.178,0.07421843405936754 +0.179,0.07435805268603007 +0.18,0.07478972506100896 +0.181,0.07500494008522232 +0.182,0.07525509452531155 +0.183,0.07596058317394669 +0.184,0.07617453234589906 +0.185,0.07642202147339315 +0.186,0.07675203013705799 +0.187,0.07710274257884957 +0.188,0.07733877251269106 +0.189,0.07769320078663464 +0.19,0.07791801040334012 +0.191,0.0782266170136186 +0.192,0.07886588203650682 +0.193,0.07921148776777814 +0.194,0.07948331088160804 +0.195,0.07971959008322634 +0.196,0.07999713863567336 +0.197,0.08057202175871665 +0.198,0.08121178003954638 +0.199,0.08151944989193714 +0.2,0.08179961149723797 +0.201,0.08233533706861006 +0.202,0.08250423439261549 +0.203,0.08294128838388776 +0.20400000000000001,0.08326521601603436 +0.20500000000000002,0.08362974779919279 +0.20600000000000002,0.08406401859049838 +0.20700000000000002,0.08460162915542942 +0.20800000000000002,0.08478029280252168 +0.209,0.08535253259042924 +0.21,0.08578408223140561 +0.211,0.08617580289427788 +0.212,0.08640920209349402 +0.213,0.08701820076527486 +0.214,0.0873154090337353 +0.215,0.08772012425499089 +0.216,0.08819376941197589 +0.217,0.08839580228231614 +0.218,0.08864888563001273 +0.219,0.08900769940528266 +0.22,0.08953518094363222 +0.221,0.08994169940005092 +0.222,0.09034949423235249 +0.223,0.09080084285478522 +0.224,0.09134780670148201 +0.225,0.09192330773722412 +0.226,0.09222037412459647 +0.227,0.09277875511512068 +0.228,0.09320717165849819 +0.229,0.09342321387891836 +0.23,0.09370259959382128 +0.231,0.09387347161675653 +0.232,0.09416574619499458 +0.233,0.09458018486349624 +0.234,0.09519028969200034 +0.23500000000000001,0.09559613245471989 +0.23600000000000002,0.09598308107703099 +0.23700000000000002,0.09632144118483973 +0.23800000000000002,0.09676176880689959 +0.23900000000000002,0.09704808396495472 +0.24,0.09752826826871631 +0.241,0.09786564286458047 +0.242,0.09820385630864832 +0.243,0.09853704799934966 +0.244,0.09898949604816742 +0.245,0.09952436251362827 +0.246,0.10012826348769392 +0.247,0.1002507444498188 +0.248,0.1006258173581487 +0.249,0.1011596792025032 +0.25,0.10162034576643841 +0.251,0.10192005181575131 +0.252,0.10236930100487034 +0.253,0.1025823257271019 +0.254,0.10288807487446504 +0.255,0.10327977954773995 +0.256,0.10385485053710124 +0.257,0.10434795686956577 +0.258,0.10483103848517711 +0.259,0.10529583566086649 +0.26,0.1057601405173516 +0.261,0.1063557443081735 +0.262,0.1066687871234243 +0.263,0.1071175546486887 +0.264,0.10760368200549368 +0.265,0.10851986816415608 +0.266,0.10886319664586348 +0.267,0.10922522177298162 +0.268,0.10972982952773994 +0.269,0.11035749294130866 +0.27,0.1108642677332508 +0.271,0.11110628892972021 +0.272,0.11167932979865261 +0.273,0.11195709156140046 +0.274,0.11244298802278017 +0.275,0.11297599041870893 +0.276,0.11377136572073245 +0.277,0.11420116804184335 +0.278,0.11449044482347726 +0.279,0.11470469755567873 +0.28,0.11496080984007946 +0.281,0.11548959248784657 +0.28200000000000003,0.11596241852213539 +0.28300000000000003,0.11651014282129354 +0.28400000000000003,0.1169489254754789 +0.28500000000000003,0.11751222493907962 +0.28600000000000003,0.11790974064672058 +0.28700000000000003,0.11829791280744148 +0.28800000000000003,0.11921337444570589 +0.289,0.1196317548628482 +0.29,0.12048660901612289 +0.291,0.12090137093108512 +0.292,0.12155190376464531 +0.293,0.12191094336762189 +0.294,0.12234261401900781 +0.295,0.12272961853800077 +0.296,0.1232345884809822 +0.297,0.12402342970917939 +0.298,0.12448110177861263 +0.299,0.12494100819167704 +0.3,0.1254775953245757 +0.301,0.12589944864643757 +0.302,0.1264052941996955 +0.303,0.1269278009454374 +0.304,0.12748711628940765 +0.305,0.12799365550630043 +0.306,0.12877875712587747 +0.307,0.12960298965779352 +0.308,0.13019322590813232 +0.309,0.13066742002295162 +0.31,0.13104096929365897 +0.311,0.13146481274818506 +0.312,0.13166858392431283 +0.313,0.1320240279194002 +0.314,0.13251955333946103 +0.315,0.13307919214180414 +0.316,0.13359163963725898 +0.317,0.13396471356600184 +0.318,0.13454465528858656 +0.319,0.13477067696259615 +0.32,0.1350874629978815 +0.321,0.13536217584045962 +0.322,0.13598272552236723 +0.323,0.13638231590910208 +0.324,0.1368263869976715 +0.325,0.13733547429236775 +0.326,0.13759903418677782 +0.327,0.1388412081990711 +0.328,0.13950753277918773 +0.329,0.13983643126653528 +0.33,0.1404846169647862 +0.331,0.1410776108313101 +0.332,0.14144393106348377 +0.333,0.1417553280401326 +0.334,0.1420875480311959 +0.335,0.14253499280754886 +0.336,0.14281740375327842 +0.337,0.14348132471169622 +0.338,0.14394488125086866 +0.339,0.14445655547571434 +0.34,0.1453442613842397 +0.341,0.1457177872177323 +0.342,0.14630126712490704 +0.343,0.14674311722652292 +0.34400000000000003,0.1473778544881199 +0.34500000000000003,0.1479311797705662 +0.34600000000000003,0.14846800099090116 +0.34700000000000003,0.14902547087559878 +0.34800000000000003,0.14954851711032396 +0.34900000000000003,0.15003908187292173 +0.35000000000000003,0.15050048900492038 +0.35100000000000003,0.15112280802675854 +0.352,0.15190250772430852 +0.353,0.15224062128876512 +0.354,0.15286567338946705 +0.355,0.1532751732355769 +0.356,0.1538175058993245 +0.357,0.15424370015019667 +0.358,0.15488481122282527 +0.359,0.15553221890697094 +0.36,0.15586462256216702 +0.361,0.1566099269352091 +0.362,0.15718381925033034 +0.363,0.15805791956454204 +0.364,0.15857045602227585 +0.365,0.15916037365339036 +0.366,0.15963546022171018 +0.367,0.1601169974421132 +0.368,0.16076857784322904 +0.369,0.16127944838334157 +0.37,0.1620492671887799 +0.371,0.16268870036580044 +0.372,0.16339148215979218 +0.373,0.1637686655757493 +0.374,0.16418885221039706 +0.375,0.16487334250736096 +0.376,0.1651629060535258 +0.377,0.1654992349684434 +0.378,0.1658399488077625 +0.379,0.1664520552428461 +0.38,0.16697584720463576 +0.381,0.16797215531764031 +0.382,0.16868673708570786 +0.383,0.16990313288901523 +0.384,0.1705357239071186 +0.385,0.1711850629569353 +0.386,0.17167574989077516 +0.387,0.17243702277753978 +0.388,0.17332813264321018 +0.389,0.17393161885245542 +0.39,0.17422461624215688 +0.391,0.17501330122489386 +0.392,0.17590750207064085 +0.393,0.17636997443402486 +0.394,0.17649928146529967 +0.395,0.17683928463608117 +0.396,0.17732048094162353 +0.397,0.17794559539208613 +0.398,0.17837519077697844 +0.399,0.17889587885718986 +0.4,0.17954689896467663 +0.401,0.18016449452352432 +0.402,0.18069899553775096 +0.403,0.1814083240670981 +0.404,0.18267534745362318 +0.405,0.18295759257312347 +0.406,0.18367700792354003 +0.40700000000000003,0.18444168688747214 +0.40800000000000003,0.18558623075035527 +0.40900000000000003,0.18639747298995601 +0.41000000000000003,0.1869468303510861 +0.41100000000000003,0.1876343493015639 +0.41200000000000003,0.18801322244382623 +0.41300000000000003,0.18849265576303081 +0.41400000000000003,0.18890375727547887 +0.41500000000000004,0.18966681221168225 +0.41600000000000004,0.19048694993326148 +0.417,0.19114439035921635 +0.418,0.19182116316878473 +0.419,0.19251695027278445 +0.42,0.1936425985136706 +0.421,0.19415490670218577 +0.422,0.19466866391412063 +0.423,0.19580367714217742 +0.424,0.19675073869894233 +0.425,0.19767352567868515 +0.426,0.1989689069769348 +0.427,0.19943599795041192 +0.428,0.2001719628509083 +0.429,0.20087164722768783 +0.43,0.20158001539458317 +0.431,0.20235504630969864 +0.432,0.20310501647768844 +0.433,0.20342185664524087 +0.434,0.20414881636692248 +0.435,0.20506415139131617 +0.436,0.20602922132753462 +0.437,0.20662066654081576 +0.438,0.2072285716756124 +0.439,0.2078673071287307 +0.44,0.2089539815221067 +0.441,0.21010950426506347 +0.442,0.2105436179337032 +0.443,0.2111586142558887 +0.444,0.21183953896449856 +0.445,0.212893701737321 +0.446,0.21346406101816673 +0.447,0.214683136530799 +0.448,0.21550834508918787 +0.449,0.21629792295149647 +0.45,0.21710675737668805 +0.451,0.21763127013970796 +0.452,0.21875209377608665 +0.453,0.21970951316106097 +0.454,0.2204174802757858 +0.455,0.2211505179152599 +0.456,0.2217972668359212 +0.457,0.22235969918828352 +0.458,0.22314211770695225 +0.459,0.22395038965073116 +0.46,0.22441573848695412 +0.461,0.22487442348725967 +0.462,0.2255705285798663 +0.463,0.2261742534551913 +0.464,0.22724889941339996 +0.465,0.22827920909152982 +0.466,0.22881115608404443 +0.467,0.22985342555373406 +0.468,0.23121715783797062 +0.46900000000000003,0.23183486559262628 +0.47000000000000003,0.23267881290785558 +0.47100000000000003,0.23388022369185632 +0.47200000000000003,0.23449568584812017 +0.47300000000000003,0.23532261613608083 +0.47400000000000003,0.23574513255342305 +0.47500000000000003,0.23697779275679587 +0.47600000000000003,0.238151887190108 +0.47700000000000004,0.23913619067624556 +0.47800000000000004,0.23993051918678882 +0.47900000000000004,0.24089019049020807 +0.48,0.24137229035497515 +0.481,0.24344212641999927 +0.482,0.24381035799102174 +0.483,0.24504597525848745 +0.484,0.24587030397808438 +0.485,0.24627139458492414 +0.486,0.2472740547386053 +0.487,0.2477258070523823 +0.488,0.24925028003708044 +0.489,0.25104268396585233 +0.49,0.25166057562742294 +0.491,0.2529046833638506 +0.492,0.2537928561100953 +0.493,0.25492285935323866 +0.494,0.2561052550353078 +0.495,0.2571302471990116 +0.496,0.25871626985831225 +0.497,0.25936283999546045 +0.498,0.25963144706084146 +0.499,0.2607209503665094 +0.5,0.26127615849888836 +0.501,0.2620830950649381 +0.502,0.2625996584574552 +0.503,0.2630747214877341 +0.504,0.2642258737085895 +0.505,0.264882594628589 +0.506,0.2658790395477744 +0.507,0.2676150368518542 +0.508,0.26853989760176267 +0.509,0.27010334153143695 +0.51,0.2710823609836021 +0.511,0.27206696594414276 +0.512,0.2734011827489865 +0.513,0.2741634180839462 +0.514,0.2756675019798719 +0.515,0.27685258365355914 +0.516,0.2776791814568026 +0.517,0.2793352983112118 +0.518,0.2809940938264612 +0.519,0.28194959550184656 +0.52,0.282973746387732 +0.521,0.28399863275327475 +0.522,0.2849499730002096 +0.523,0.28585776602434515 +0.524,0.28656934476116386 +0.525,0.2881771941296923 +0.526,0.28946509570650003 +0.527,0.290862433081476 +0.528,0.29276795070661277 +0.529,0.2937807065004854 +0.53,0.2947264440664687 +0.531,0.29545113851033966 +0.532,0.2966194790757283 +0.533,0.29721673125611653 +0.534,0.29770550782833366 +0.535,0.2983818796455594 +0.536,0.2997438645822567 +0.537,0.3003828195190214 +0.538,0.30120419937910337 +0.539,0.3018105731010341 +0.54,0.30266403731922054 +0.541,0.3039480719311367 +0.542,0.3052196481897245 +0.543,0.30655086991593045 +0.544,0.30725554573032926 +0.545,0.3083310361625233 +0.546,0.309708153124795 +0.547,0.3104546531536481 +0.548,0.3113007952589983 +0.549,0.3119164304088987 +0.55,0.31295831656338413 +0.551,0.3142538683857384 +0.552,0.31470417696149283 +0.553,0.31603978928674314 +0.554,0.3167226297269539 +0.555,0.317816619474629 +0.556,0.3186958998765829 +0.557,0.31937712423527914 +0.558,0.31967508235354036 +0.559,0.3217063939347861 +0.56,0.32315965563743804 +0.561,0.3244699642564666 +0.562,0.3257157136988716 +0.5630000000000001,0.32690990214895477 +0.5640000000000001,0.32749282559936826 +0.5650000000000001,0.3282086110323134 +0.5660000000000001,0.3296837375227391 +0.5670000000000001,0.3311100906724772 +0.5680000000000001,0.3319519656966597 +0.5690000000000001,0.33269405049269113 +0.5700000000000001,0.3338183276077892 +0.5710000000000001,0.334655480231736 +0.5720000000000001,0.3358784940280478 +0.5730000000000001,0.3371928222452209 +0.5740000000000001,0.3385801662890193 +0.5750000000000001,0.3394976539553968 +0.5760000000000001,0.3408904728267326 +0.577,0.3419604060835877 +0.578,0.344085758050046 +0.579,0.3457646623011133 +0.58,0.34688099615145523 +0.581,0.34811577745779787 +0.582,0.3499818862717822 +0.583,0.35279205502411665 +0.584,0.3536522429107379 +0.585,0.35467157489542356 +0.586,0.3556576029673469 +0.587,0.356848458126325 +0.588,0.3581468523975275 +0.589,0.3591252079702072 +0.59,0.360941551475833 +0.591,0.36210598427748786 +0.592,0.3630088939841163 +0.593,0.36443483402087695 +0.594,0.36533837186185514 +0.595,0.3674188183201586 +0.596,0.36884382329459797 +0.597,0.3704314901297317 +0.598,0.37130840529271103 +0.599,0.37291826870605826 +0.6,0.3741257720734445 +0.601,0.3752520910577219 +0.602,0.37619012445202826 +0.603,0.37762816814642763 +0.604,0.37935738062751456 +0.605,0.38087852557839996 +0.606,0.3819782294394115 +0.607,0.38300640138660436 +0.608,0.3841305381272736 +0.609,0.38479160616574104 +0.61,0.38599074311276144 +0.611,0.38749379752455915 +0.612,0.38918486393471613 +0.613,0.3900980544322923 +0.614,0.39128548220132114 +0.615,0.3919229798592384 +0.616,0.39302303919615905 +0.617,0.3945355501770116 +0.618,0.39615448459376046 +0.619,0.3976990324222821 +0.62,0.3998023113668896 +0.621,0.4018463781245365 +0.622,0.402570794754075 +0.623,0.40507872964334024 +0.624,0.40640813148057353 +0.625,0.4071938895843278 +0.626,0.4082850011535036 +0.627,0.4100519881750813 +0.628,0.4113411078276697 +0.629,0.41225035453746506 +0.63,0.413199926016004 +0.631,0.41434497475628873 +0.632,0.4160044587426765 +0.633,0.4172878043825571 +0.634,0.41822806504761056 +0.635,0.4201338944634379 +0.636,0.42146162536268894 +0.637,0.42369352909077374 +0.638,0.42484354120120793 +0.639,0.42610812798089376 +0.64,0.4276845345639752 +0.641,0.42840553916939256 +0.642,0.42955922953121006 +0.643,0.43075744977824404 +0.644,0.4324388372735788 +0.645,0.4335185271525451 +0.646,0.4343789633990618 +0.647,0.43560872144264334 +0.648,0.43670680290212005 +0.649,0.4377978240844983 +0.65,0.43893292688110513 +0.651,0.4400517119467251 +0.652,0.4418128426094966 +0.653,0.4431307875517416 +0.654,0.4439570734632809 +0.655,0.44537587993578287 +0.656,0.4461910776445101 +0.657,0.44745517640594773 +0.658,0.44927395265572184 +0.659,0.452074127810906 +0.66,0.45299596007887827 +0.661,0.454579088437843 +0.662,0.4564840489379453 +0.663,0.457886026258889 +0.664,0.45935160544567105 +0.665,0.46101010488403044 +0.666,0.46265375734811603 +0.667,0.4656492434341952 +0.668,0.4675973039472089 +0.669,0.46932625617645213 +0.67,0.4700865897876632 +0.671,0.4712435267674761 +0.672,0.472150492618794 +0.673,0.47400581068279457 +0.674,0.4749324287167894 +0.675,0.4773535010634481 +0.676,0.478327392536903 +0.677,0.4800953470664572 +0.678,0.482592472275364 +0.679,0.4842301325920801 +0.68,0.4855665751374596 +0.681,0.48637412616584336 +0.682,0.4878375224234776 +0.683,0.4893994313684418 +0.684,0.4907660378883872 +0.685,0.4918622081537909 +0.686,0.49332733911242865 +0.687,0.49432392998781943 +0.6880000000000001,0.4955092417726559 +0.6890000000000001,0.4970214340290136 +0.6900000000000001,0.4986608815515541 +0.6910000000000001,0.5020104815255636 +0.6920000000000001,0.503001898452572 +0.6930000000000001,0.5044285951697806 +0.6940000000000001,0.506663558451791 +0.6950000000000001,0.5089967998156683 +0.6960000000000001,0.5109811827146877 +0.6970000000000001,0.5133164732831876 +0.6980000000000001,0.5149068565710746 +0.6990000000000001,0.5156781587509619 +0.7000000000000001,0.5169032542224099 +0.7010000000000001,0.5188465605674054 +0.7020000000000001,0.5205934477878558 +0.7030000000000001,0.5222107937299404 +0.704,0.5240653763530427 +0.705,0.5259824971643772 +0.706,0.527050724417791 +0.707,0.528723428470174 +0.708,0.5305776750876862 +0.709,0.5318628312744105 +0.71,0.5341800268187678 +0.711,0.5358588643958906 +0.712,0.5378985903638057 +0.713,0.5419514211658697 +0.714,0.5442230012781111 +0.715,0.546017269685919 +0.716,0.5475768529604376 +0.717,0.5504329212661042 +0.718,0.5539432750938068 +0.719,0.5563853872157204 +0.72,0.5586043795711586 +0.721,0.560122232748415 +0.722,0.5618059902865732 +0.723,0.5656040578146304 +0.724,0.5675560810743105 +0.725,0.5695606319072284 +0.726,0.5714548751688577 +0.727,0.5745370181942784 +0.728,0.5772211855440016 +0.729,0.5786869397839434 +0.73,0.5803053777241455 +0.731,0.5812795948091375 +0.732,0.5841347379072895 +0.733,0.5865179967939093 +0.734,0.5888092705351712 +0.735,0.5900730298205299 +0.736,0.5935409313939758 +0.737,0.5949075013065783 +0.738,0.5959136878822942 +0.739,0.5980894225306742 +0.74,0.599858789078057 +0.741,0.6013680598182348 +0.742,0.6037056852549426 +0.743,0.6054216603852403 +0.744,0.606950167642821 +0.745,0.6097922064678027 +0.746,0.6105314123202249 +0.747,0.6119833601696184 +0.748,0.6147910802019562 +0.749,0.6178931752218569 +0.75,0.619440646100409 +0.751,0.6217045308029807 +0.752,0.6241379266776056 +0.753,0.6274730411225738 +0.754,0.629127194761085 +0.755,0.6313738200180657 +0.756,0.6333296419977356 +0.757,0.634767735455638 +0.758,0.6372703308717449 +0.759,0.640103538306123 +0.76,0.6430391524922099 +0.761,0.6445319747868109 +0.762,0.6452289552037959 +0.763,0.6469050813223053 +0.764,0.6498239784339775 +0.765,0.6519326639366152 +0.766,0.6542956268699414 +0.767,0.6562115952851928 +0.768,0.6581734878494808 +0.769,0.6610177432288835 +0.77,0.661954082837615 +0.771,0.6633590926987586 +0.772,0.6654725712073735 +0.773,0.6666044254394766 +0.774,0.6690103247694599 +0.775,0.6709571080976569 +0.776,0.6734529207652752 +0.777,0.6747037628241875 +0.778,0.6773307361574372 +0.779,0.6789156762945192 +0.78,0.6805250688410208 +0.781,0.6823757731624354 +0.782,0.6856225482701258 +0.783,0.687075237192991 +0.784,0.6894707929983918 +0.785,0.6913999513339457 +0.786,0.6947407913583431 +0.787,0.6966999463417459 +0.788,0.6993293525292745 +0.789,0.7014844430013948 +0.79,0.7037487030565426 +0.791,0.7045978627348003 +0.792,0.7067221896631954 +0.793,0.7092689303365869 +0.794,0.7123566122093117 +0.795,0.714304554336962 +0.796,0.7161793584058063 +0.797,0.7186598875997848 +0.798,0.7209776370769255 +0.799,0.7228274678761636 +0.8,0.7238885740161051 +0.801,0.7253987937204041 +0.802,0.7263167570074066 +0.803,0.7273844463856278 +0.804,0.7299898392781282 +0.805,0.7319492167355209 +0.806,0.732975435587824 +0.807,0.734523318827165 +0.808,0.7367602641421113 +0.809,0.7386579909242326 +0.81,0.7412936041794448 +0.811,0.7424787596565096 +0.812,0.7440525787116198 +0.8130000000000001,0.7452855434153376 +0.8140000000000001,0.7456902723226889 +0.8150000000000001,0.7468695315617189 +0.8160000000000001,0.7477020765981806 +0.8170000000000001,0.7495889944909013 +0.8180000000000001,0.7504015130310318 +0.8190000000000001,0.7513822102090202 +0.8200000000000001,0.7528082322884613 +0.8210000000000001,0.7550016055646783 +0.8220000000000001,0.75650055796764 +0.8230000000000001,0.7582098304906609 +0.8240000000000001,0.7603242033577491 +0.8250000000000001,0.7610512854225535 +0.8260000000000001,0.7626879130928911 +0.8270000000000001,0.7646754949285486 +0.8280000000000001,0.7682122347529414 +0.8290000000000001,0.7693219857107746 +0.8300000000000001,0.7706574519750278 +0.8310000000000001,0.7730938895564875 +0.8320000000000001,0.7748697869863634 +0.833,0.7762908427197807 +0.834,0.7775831778848032 +0.835,0.7793095672983776 +0.836,0.7811327005303247 +0.837,0.784031668460753 +0.838,0.7864715540568326 +0.839,0.7893131578533129 +0.84,0.7903036630218174 +0.841,0.7914806282178419 +0.842,0.7933673995673614 +0.843,0.79539915822679 +0.844,0.7973615270128543 +0.845,0.798853191654793 +0.846,0.8009482138078644 +0.847,0.8019573647391525 +0.848,0.803475903046565 +0.849,0.8051396760591332 +0.85,0.8059548784584429 +0.851,0.8087867990951564 +0.852,0.8107363212115474 +0.853,0.8117436329452491 +0.854,0.812724549375101 +0.855,0.8139769546099459 +0.856,0.8154570620286693 +0.857,0.8176392394836608 +0.858,0.8189491792956015 +0.859,0.8212043916838866 +0.86,0.822354908117 +0.861,0.8239247040954369 +0.862,0.8255860806974631 +0.863,0.8281241227025837 +0.864,0.8296322652255105 +0.865,0.830581850201642 +0.866,0.8314921864067331 +0.867,0.832956132811265 +0.868,0.8348958389161627 +0.869,0.8360623882726657 +0.87,0.8374744800497009 +0.871,0.838450849808612 +0.872,0.8400178723296273 +0.873,0.8411717788205904 +0.874,0.8422227653968739 +0.875,0.8449045597884359 +0.876,0.8461261711681557 +0.877,0.8483429112696309 +0.878,0.849754657964562 +0.879,0.8511132798073181 +0.88,0.8521365888771484 +0.881,0.8540498052824838 +0.882,0.8548141722296926 +0.883,0.8560049403532541 +0.884,0.8570344619592334 +0.885,0.8580751455523313 +0.886,0.8593601514813766 +0.887,0.8606535349779598 +0.888,0.8627428087599693 +0.889,0.8643199452411131 +0.89,0.865590059221387 +0.891,0.8674489831416083 +0.892,0.8686751086262017 +0.893,0.869723843685014 +0.894,0.8719852211843503 +0.895,0.8735432683730682 +0.896,0.8749757252762066 +0.897,0.8767788162821385 +0.898,0.8784899292938158 +0.899,0.8795375845259918 +0.9,0.8805704319424897 +0.901,0.8811406992164448 +0.902,0.8828646808108312 +0.903,0.8836425618919174 +0.904,0.8849936232735077 +0.905,0.8857295987565695 +0.906,0.8865077014590319 +0.907,0.8874112371050057 +0.908,0.8882499126781839 +0.909,0.8890256813796589 +0.91,0.8905623134556468 +0.911,0.8915434314293454 +0.912,0.8925419064499556 +0.913,0.8940823308844946 +0.914,0.8949074990611874 +0.915,0.8965117032934682 +0.916,0.8983410778375825 +0.917,0.8997801111414278 +0.918,0.9009873923207232 +0.919,0.901666700372023 +0.92,0.9035821061961687 +0.921,0.9044371961992599 +0.922,0.9056595749808785 +0.923,0.9064416976983567 +0.924,0.9078772383387808 +0.925,0.9090768374513722 +0.926,0.9098666026856611 +0.927,0.9112299041867447 +0.928,0.9129395962216044 +0.929,0.9141499292843006 +0.93,0.9148768816149685 +0.931,0.9153609159827544 +0.932,0.9160592292617674 +0.933,0.9168021855838856 +0.934,0.918205976766667 +0.935,0.9190307991367997 +0.936,0.91988880309196 +0.937,0.9214039088258431 +0.9380000000000001,0.922277352217475 +0.9390000000000001,0.9232062513700299 +0.9400000000000001,0.9237827923122235 +0.9410000000000001,0.9248443870076098 +0.9420000000000001,0.9256323610022223 +0.9430000000000001,0.9266237084960162 +0.9440000000000001,0.9276949832278402 +0.9450000000000001,0.929340682823716 +0.9460000000000001,0.9304496916697943 +0.9470000000000001,0.93123044778716 +0.9480000000000001,0.9320889901119613 +0.9490000000000001,0.9328513666420583 +0.9500000000000001,0.9341112928029003 +0.9510000000000001,0.9349655101478773 +0.9520000000000001,0.9360878463787075 +0.9530000000000001,0.9368519243154454 +0.9540000000000001,0.9380551456186363 +0.9550000000000001,0.9388418024713768 +0.9560000000000001,0.9400601965841415 +0.9570000000000001,0.9413615904229791 +0.9580000000000001,0.9424876894153946 +0.9590000000000001,0.9429382483298901 +0.96,0.9437654644905092 +0.961,0.9446842583901877 +0.962,0.9458649180034623 +0.963,0.9465949245448836 +0.964,0.9478884116129852 +0.965,0.9490235579887125 +0.966,0.9501053088475332 +0.967,0.951760426071554 +0.968,0.9525193180259665 +0.969,0.9531826479882384 +0.97,0.9539742633530522 +0.971,0.9548157123144725 +0.972,0.9555827129692414 +0.973,0.9564131530433126 +0.974,0.9572987849793597 +0.975,0.9584106522300437 +0.976,0.9591509803531554 +0.977,0.9607748049450429 +0.978,0.9615673690936637 +0.979,0.9628208874745406 +0.98,0.9634579110206625 +0.981,0.9641399131124136 +0.982,0.9655573150820872 +0.983,0.9665908173228642 +0.984,0.9680952304435319 +0.985,0.9693143884935033 +0.986,0.9705378769649174 +0.987,0.9713899542100553 +0.988,0.972439690053074 +0.989,0.9736080900619567 +0.99,0.9752106586108641 +0.991,0.9760174361645096 +0.992,0.9772948072456846 +0.993,0.9783012970836982 +0.994,0.9803494956933375 +0.995,0.9814706629903779 +0.996,0.9824428535207566 +0.997,0.9846375902330458 +0.998,0.9870946476195143 +0.999,0.990711088280987 +1.0,0.9977677145329227 diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_5y_catboost.joblib b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_5y_catboost.joblib new file mode 100644 index 00000000..1cbca025 Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_5y_catboost.joblib differ diff --git a/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_5y_reference_quantiles.csv b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_5y_reference_quantiles.csv new file mode 100644 index 00000000..04436ea4 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/rq2_symmetric/models/p_within_5y_reference_quantiles.csv @@ -0,0 +1,1002 @@ +quantile,score +0.0,0.0011980627929556854 +0.001,0.0037797075149255993 +0.002,0.005103387303008757 +0.003,0.005937470803643555 +0.004,0.006882263567400242 +0.005,0.007819874652126297 +0.006,0.008712588792394317 +0.007,0.009787031356546872 +0.008,0.010446725402290063 +0.009000000000000001,0.011220316684400808 +0.01,0.011991544212246347 +0.011,0.012330633045222639 +0.012,0.013018190368061008 +0.013000000000000001,0.013569813766078909 +0.014,0.014036069696585166 +0.015,0.014510361930108061 +0.016,0.014881099761464808 +0.017,0.015372668154098839 +0.018000000000000002,0.015780142628571255 +0.019,0.016464322188224693 +0.02,0.017067750356321406 +0.021,0.017374165837342286 +0.022,0.01755913717939345 +0.023,0.017938865614023723 +0.024,0.018477276616269068 +0.025,0.01916216065989972 +0.026000000000000002,0.01947290570700322 +0.027,0.019923772270850047 +0.028,0.020228397690633507 +0.029,0.020695842348777155 +0.03,0.021011586220561748 +0.031,0.021298159706750565 +0.032,0.02144911462314064 +0.033,0.021689103823561956 +0.034,0.022035646542930703 +0.035,0.02225311920074592 +0.036000000000000004,0.0226188433305182 +0.037,0.023036001260823166 +0.038,0.023269266569586382 +0.039,0.0233763281626279 +0.04,0.023899449550106398 +0.041,0.024240908248074546 +0.042,0.02453222938892674 +0.043000000000000003,0.024940563991181944 +0.044,0.025270580960751243 +0.045,0.025585331231350025 +0.046,0.02590817148996968 +0.047,0.02628586541544735 +0.048,0.026610299063772214 +0.049,0.026829570331788885 +0.05,0.027351297772841794 +0.051000000000000004,0.028180149522695108 +0.052000000000000005,0.02839505831681735 +0.053,0.02883671572024297 +0.054,0.02928938073511024 +0.055,0.02953223654336287 +0.056,0.030030437804182034 +0.057,0.030398234020045885 +0.058,0.030932213413518664 +0.059000000000000004,0.031181064279022785 +0.06,0.03150524526091004 +0.061,0.03177028508177252 +0.062,0.032179525545331544 +0.063,0.032641928537406134 +0.064,0.032969210027164214 +0.065,0.03315464775241206 +0.066,0.033582871545148635 +0.067,0.03387157429131166 +0.068,0.03415404122294346 +0.069,0.034637545464609086 +0.07,0.03499218378195417 +0.07100000000000001,0.03521372520964284 +0.07200000000000001,0.03540130132667237 +0.073,0.03563691263581004 +0.074,0.0360394987379461 +0.075,0.03630035708305608 +0.076,0.03660850179990728 +0.077,0.036932092589517046 +0.078,0.037262879604338474 +0.079,0.03777028443561159 +0.08,0.03793987311107952 +0.081,0.03838850117548556 +0.082,0.03864957132146356 +0.083,0.039025674977690154 +0.084,0.03938546643089146 +0.085,0.039673554096204766 +0.08600000000000001,0.03981994479397566 +0.08700000000000001,0.040039874362711614 +0.088,0.040319880211148885 +0.089,0.04080229939470171 +0.09,0.04116931937815652 +0.091,0.041371164885912325 +0.092,0.04165133160884724 +0.093,0.04191475009140757 +0.094,0.042048237459168636 +0.095,0.042290313300541456 +0.096,0.042566623874849815 +0.097,0.04292437424548844 +0.098,0.04317502954444755 +0.099,0.043509363882976174 +0.1,0.043719872356673926 +0.101,0.04410000926228744 +0.10200000000000001,0.04429751818292577 +0.10300000000000001,0.04472371931863105 +0.10400000000000001,0.04510365731173672 +0.105,0.045237794850296276 +0.106,0.045459982312312415 +0.107,0.04574529894733589 +0.108,0.0461697459427001 +0.109,0.046469429982810374 +0.11,0.04673721776829268 +0.111,0.04715036050103196 +0.112,0.047637963072757715 +0.113,0.04785919960685908 +0.114,0.0482031933302679 +0.115,0.04842137306905714 +0.116,0.04865188627541844 +0.117,0.04891290764231245 +0.11800000000000001,0.04917215977077146 +0.11900000000000001,0.04955587270686711 +0.12,0.04987810227514396 +0.121,0.05018259179585666 +0.122,0.05044465268915764 +0.123,0.05068561148342568 +0.124,0.0509633166738001 +0.125,0.051200529698313686 +0.126,0.05175538016732117 +0.127,0.05199991756755949 +0.128,0.05233227551786299 +0.129,0.05260280117178076 +0.13,0.053031439378119494 +0.131,0.0532153996971165 +0.132,0.0538983465381692 +0.133,0.05412308146754421 +0.134,0.054422716915347905 +0.135,0.05489847034549532 +0.136,0.05517329417752938 +0.137,0.055542421910748256 +0.138,0.055977428011061446 +0.139,0.05627924841554745 +0.14,0.05650204677814945 +0.14100000000000001,0.056955079025175916 +0.14200000000000002,0.0572631702176903 +0.14300000000000002,0.05797597220771839 +0.14400000000000002,0.058460765025574575 +0.145,0.058839106449738596 +0.146,0.059255266895146874 +0.147,0.05948742423116464 +0.148,0.05977487114972082 +0.149,0.06025334913579735 +0.15,0.06070559360275828 +0.151,0.06130190954197491 +0.152,0.061918183167558795 +0.153,0.06234580564554992 +0.154,0.06256306315136523 +0.155,0.06272573991028386 +0.156,0.06332885455047663 +0.157,0.06357775133948798 +0.158,0.06393768894559985 +0.159,0.06412663602698113 +0.16,0.06445626761241612 +0.161,0.06481142568109519 +0.162,0.06499898467285685 +0.163,0.06533602064423945 +0.164,0.06564031014897792 +0.165,0.06614027743268046 +0.166,0.06649794448165773 +0.167,0.06662339887474805 +0.168,0.06693895178588151 +0.169,0.06706660831481913 +0.17,0.06755128630491478 +0.171,0.06781102005378432 +0.17200000000000001,0.06818248515074264 +0.17300000000000001,0.06842235288248356 +0.17400000000000002,0.06872432874745225 +0.17500000000000002,0.06910705064095927 +0.176,0.06969510034967596 +0.177,0.07033858214248188 +0.178,0.07058512191586239 +0.179,0.07086622264532451 +0.18,0.07123071626655587 +0.181,0.07154840257117412 +0.182,0.07187231967884182 +0.183,0.07242214939405621 +0.184,0.07265020950246277 +0.185,0.07274137237012579 +0.186,0.0732739823938373 +0.187,0.07368320323927806 +0.188,0.07404390250764482 +0.189,0.0743490945371209 +0.19,0.07490464203341526 +0.191,0.07512842223389249 +0.192,0.07571733368948655 +0.193,0.07609676772950348 +0.194,0.07647411525185722 +0.195,0.07687676369621312 +0.196,0.07710101101190796 +0.197,0.07767357064944554 +0.198,0.0782548689127061 +0.199,0.07849326703474098 +0.2,0.07879489644057208 +0.201,0.07914999443401675 +0.202,0.07951660024307024 +0.203,0.07987254348358659 +0.20400000000000001,0.08021794887845421 +0.20500000000000002,0.08078523863017546 +0.20600000000000002,0.08129737464962275 +0.20700000000000002,0.08189837039550803 +0.20800000000000002,0.08227687239768072 +0.209,0.08252980156308083 +0.21,0.08309560977240295 +0.211,0.08339028223073502 +0.212,0.08395961732260065 +0.213,0.08425502865914863 +0.214,0.08464908910010181 +0.215,0.08496454426106444 +0.216,0.08520155856644854 +0.217,0.08563885342678265 +0.218,0.08632927154862734 +0.219,0.0865982084565979 +0.22,0.08678046864670516 +0.221,0.08707913237501792 +0.222,0.08739011734542237 +0.223,0.08810534143995372 +0.224,0.08831156490227866 +0.225,0.08869847237524549 +0.226,0.08920599012578917 +0.227,0.08961139363868298 +0.228,0.09003636801066678 +0.229,0.09046496319729574 +0.23,0.09102761994799528 +0.231,0.09146186365466814 +0.232,0.09191879083339095 +0.233,0.09225579597226911 +0.234,0.09270349488607404 +0.23500000000000001,0.09320191824560013 +0.23600000000000002,0.09353867188660485 +0.23700000000000002,0.09378753291148512 +0.23800000000000002,0.0941499680429295 +0.23900000000000002,0.0944254343270722 +0.24,0.09461228874249428 +0.241,0.09525259473861837 +0.242,0.0958116001299517 +0.243,0.09644829211910053 +0.244,0.0967886188920259 +0.245,0.0975395185685522 +0.246,0.09793330745089583 +0.247,0.09847124719519408 +0.248,0.09886774873573324 +0.249,0.09930146424649001 +0.25,0.09960609499407401 +0.251,0.10034353171119638 +0.252,0.10072309076022196 +0.253,0.10112327275239398 +0.254,0.10153973690766534 +0.255,0.10179940927194508 +0.256,0.10244756025721184 +0.257,0.10283799145654149 +0.258,0.10300783307259476 +0.259,0.10341186641838496 +0.26,0.10381357853898258 +0.261,0.10420154875863452 +0.262,0.10443780134762018 +0.263,0.10480616617334376 +0.264,0.10509341192072534 +0.265,0.10539012769172483 +0.266,0.10594421127110062 +0.267,0.10660672519258839 +0.268,0.1069695483104004 +0.269,0.10747608586530451 +0.27,0.10783977410946796 +0.271,0.1082683057385295 +0.272,0.10865137963726586 +0.273,0.10897309827212102 +0.274,0.10949441646177474 +0.275,0.10983802658982887 +0.276,0.11016366638122382 +0.277,0.1108313410189427 +0.278,0.11145035789903313 +0.279,0.11214684084914407 +0.28,0.11244698044319008 +0.281,0.11282511378353036 +0.28200000000000003,0.11311334350663134 +0.28300000000000003,0.11352585279905221 +0.28400000000000003,0.11396729637116602 +0.28500000000000003,0.1143425401070227 +0.28600000000000003,0.11483398350673829 +0.28700000000000003,0.11529181088917867 +0.28800000000000003,0.1157434395772263 +0.289,0.11606264123955885 +0.29,0.11675968560598479 +0.291,0.11732882429538848 +0.292,0.11779238576098354 +0.293,0.11823363340063227 +0.294,0.11871841370570453 +0.295,0.11918721182962752 +0.296,0.11968110509367953 +0.297,0.11993581843008044 +0.298,0.12026803052474999 +0.299,0.12091915437951715 +0.3,0.12140259965465021 +0.301,0.12174651254466581 +0.302,0.1220472205584656 +0.303,0.12260796449011949 +0.304,0.12312655731627795 +0.305,0.12351686615396788 +0.306,0.12406703088877143 +0.307,0.12430110979968878 +0.308,0.12467428087301058 +0.309,0.12498667765548813 +0.31,0.12531078704559379 +0.311,0.12595485625360436 +0.312,0.12632365242520335 +0.313,0.12660850442800778 +0.314,0.12694023558906606 +0.315,0.12753844534224834 +0.316,0.12783390665682554 +0.317,0.128356336534171 +0.318,0.12862628443384475 +0.319,0.1291817539093291 +0.32,0.12955080442735747 +0.321,0.12996340564317632 +0.322,0.1305310065298015 +0.323,0.13089085213375878 +0.324,0.1312669366700456 +0.325,0.13166784213891186 +0.326,0.1325006529423855 +0.327,0.13286264576411827 +0.328,0.13327211410289666 +0.329,0.13363583133874735 +0.33,0.13433634215634963 +0.331,0.134939215812228 +0.332,0.13531914147480043 +0.333,0.1358108141501808 +0.334,0.1363268597993483 +0.335,0.13677241773963714 +0.336,0.1375096401889096 +0.337,0.13803754776539387 +0.338,0.13820166061004857 +0.339,0.13887705915034126 +0.34,0.13941368035289187 +0.341,0.13982414350768566 +0.342,0.14007516829955016 +0.343,0.14036552633266225 +0.34400000000000003,0.14079521811456508 +0.34500000000000003,0.14106122130311283 +0.34600000000000003,0.1417485360126891 +0.34700000000000003,0.1421806090717916 +0.34800000000000003,0.14284338582673115 +0.34900000000000003,0.14331094486544424 +0.35000000000000003,0.14365977432097873 +0.35100000000000003,0.14472797403246304 +0.352,0.14518960983737253 +0.353,0.1457585105441371 +0.354,0.14623136201352668 +0.355,0.1465435812463313 +0.356,0.1471180735501967 +0.357,0.14743831425212506 +0.358,0.14786433199799381 +0.359,0.14888089675350338 +0.36,0.14938649044348914 +0.361,0.15005384532485752 +0.362,0.15054013026859953 +0.363,0.1511679167553019 +0.364,0.15173081196686872 +0.365,0.15248520538654795 +0.366,0.1528877193617377 +0.367,0.15360073956599235 +0.368,0.1538946128423448 +0.369,0.15464237713930395 +0.37,0.1551408931140287 +0.371,0.1560982373389304 +0.372,0.15667744270408865 +0.373,0.15725472246259137 +0.374,0.15764158105631834 +0.375,0.15811966270668795 +0.376,0.15846361074694226 +0.377,0.15910016040761665 +0.378,0.1601391572067879 +0.379,0.16061733741429698 +0.38,0.1612434234584507 +0.381,0.1615487359787665 +0.382,0.16197648215688998 +0.383,0.16261023753101578 +0.384,0.16339012095310348 +0.385,0.16420820266723513 +0.386,0.1646802243878879 +0.387,0.16513488784942668 +0.388,0.16589549478792792 +0.389,0.16664543315560348 +0.39,0.1671656760585159 +0.391,0.16772591531652448 +0.392,0.16867259243811053 +0.393,0.16919252522072342 +0.394,0.16953216105496927 +0.395,0.17040870858112717 +0.396,0.1708520310074895 +0.397,0.17121639831304383 +0.398,0.17225952792519986 +0.399,0.1726440479385196 +0.4,0.1731679906504757 +0.401,0.1737546794105848 +0.402,0.17431268921299028 +0.403,0.17544588904730327 +0.404,0.17607015833040168 +0.405,0.17701625627378229 +0.406,0.17767509812166438 +0.40700000000000003,0.17806113532061574 +0.40800000000000003,0.1788715158168348 +0.40900000000000003,0.17942775901629884 +0.41000000000000003,0.18018668444809768 +0.41100000000000003,0.18072787538197987 +0.41200000000000003,0.18116609330285743 +0.41300000000000003,0.18161209425909866 +0.41400000000000003,0.18216411668951596 +0.41500000000000004,0.18279149288838695 +0.41600000000000004,0.18324499130422628 +0.417,0.18417253735754777 +0.418,0.18480069456478204 +0.419,0.18569435021665473 +0.42,0.18617588250228875 +0.421,0.18681702820927293 +0.422,0.18723440655943602 +0.423,0.18767570464291125 +0.424,0.18886609863220674 +0.425,0.1896641061905852 +0.426,0.1903090789773731 +0.427,0.19122876506594733 +0.428,0.19182946041828017 +0.429,0.19227832879170156 +0.43,0.19303946188265148 +0.431,0.1938140383017995 +0.432,0.1944325578407115 +0.433,0.1950484041496222 +0.434,0.19596643151688212 +0.435,0.196640393974917 +0.436,0.1973196932584517 +0.437,0.1982685067951448 +0.438,0.19874458934514397 +0.439,0.19926665611200484 +0.44,0.19974979094696585 +0.441,0.20023771438911628 +0.442,0.20078079554859604 +0.443,0.20137258722410137 +0.444,0.20213407405550596 +0.445,0.2028890447824141 +0.446,0.20387384737992187 +0.447,0.20444796762846745 +0.448,0.20530918515081215 +0.449,0.20607207590824902 +0.45,0.20713852752602824 +0.451,0.20749884477968325 +0.452,0.20799620669094682 +0.453,0.20855196733502648 +0.454,0.20896181025610597 +0.455,0.20948470783222128 +0.456,0.21044604659919477 +0.457,0.21139944860276605 +0.458,0.21216209238216943 +0.459,0.21293514575293077 +0.46,0.21366107907863824 +0.461,0.21509194361084463 +0.462,0.2161129805105155 +0.463,0.21672330234147003 +0.464,0.21781141171360707 +0.465,0.2182101712734701 +0.466,0.21923678440458125 +0.467,0.22025389057656353 +0.468,0.22148006962833494 +0.46900000000000003,0.22219592022876838 +0.47000000000000003,0.22307096161790957 +0.47100000000000003,0.22368668362262265 +0.47200000000000003,0.22438909487225023 +0.47300000000000003,0.2247919900429404 +0.47400000000000003,0.22521228358536874 +0.47500000000000003,0.22572078307395382 +0.47600000000000003,0.22628169539577295 +0.47700000000000004,0.2278855831265052 +0.47800000000000004,0.2283593799428599 +0.47900000000000004,0.22999486504984828 +0.48,0.230738732689404 +0.481,0.23158422184877384 +0.482,0.2329252766721289 +0.483,0.23396044110621939 +0.484,0.2344724755006095 +0.485,0.23551786582665604 +0.486,0.23663819522129104 +0.487,0.2377429976632073 +0.488,0.23845334509277838 +0.489,0.23975391789485892 +0.49,0.24043331112353883 +0.491,0.24111959844225153 +0.492,0.24249395716148733 +0.493,0.24302133425695527 +0.494,0.2440980241237395 +0.495,0.24534055764812507 +0.496,0.24589171026954895 +0.497,0.24710873886431414 +0.498,0.2479834673341457 +0.499,0.24863325870476113 +0.5,0.24996124533103825 +0.501,0.2507816282860748 +0.502,0.25241884514837426 +0.503,0.25322416968014644 +0.504,0.25388322468349517 +0.505,0.25568803239220417 +0.506,0.2574602650210227 +0.507,0.25841869853952376 +0.508,0.259596549781945 +0.509,0.260431156580068 +0.51,0.26147759537534737 +0.511,0.2621849603545849 +0.512,0.26420868367077693 +0.513,0.2650459459635044 +0.514,0.2653396024302023 +0.515,0.2675974037160525 +0.516,0.26848522654107476 +0.517,0.26940927621792893 +0.518,0.26992665183642234 +0.519,0.2708324244056577 +0.52,0.2719470530262638 +0.521,0.27254152562000766 +0.522,0.27347244890662886 +0.523,0.2740717275855827 +0.524,0.27466006905772533 +0.525,0.2756281523696864 +0.526,0.276346717477553 +0.527,0.2769259928337457 +0.528,0.2782499084746332 +0.529,0.27870979613674673 +0.53,0.27918758074497113 +0.531,0.2797043930286108 +0.532,0.2805832320595787 +0.533,0.28167260686109236 +0.534,0.2826881943407585 +0.535,0.2833496660204215 +0.536,0.2841447882864177 +0.537,0.28565933336451 +0.538,0.2868293450916912 +0.539,0.28816443222094573 +0.54,0.28909664427469434 +0.541,0.2899678898346889 +0.542,0.2910922880075445 +0.543,0.29243641496251377 +0.544,0.29348896126735013 +0.545,0.2947124953488303 +0.546,0.29581543366308904 +0.547,0.29742620833414773 +0.548,0.29816635077796555 +0.549,0.2999649814914746 +0.55,0.3011536213454752 +0.551,0.30249071345022105 +0.552,0.3037073781306353 +0.553,0.30423718779257736 +0.554,0.3054982920564777 +0.555,0.30682519158496835 +0.556,0.30796588030566424 +0.557,0.30927316053552767 +0.558,0.31088105382168496 +0.559,0.3124570130291004 +0.56,0.3139057044614903 +0.561,0.31458963007552887 +0.562,0.3159471254088875 +0.5630000000000001,0.3183040555913116 +0.5640000000000001,0.3189860741287205 +0.5650000000000001,0.3203248535133954 +0.5660000000000001,0.3214998428047138 +0.5670000000000001,0.322322779578368 +0.5680000000000001,0.3234129027431938 +0.5690000000000001,0.3252131037484991 +0.5700000000000001,0.3265601154686058 +0.5710000000000001,0.32772282182152496 +0.5720000000000001,0.329094604316202 +0.5730000000000001,0.3295650524507554 +0.5740000000000001,0.33076362130834064 +0.5750000000000001,0.331393781525617 +0.5760000000000001,0.3323310379127894 +0.577,0.3335780081531007 +0.578,0.3352260802832671 +0.579,0.3366275071465227 +0.58,0.33761347063246167 +0.581,0.3391829558056189 +0.582,0.3399384908722788 +0.583,0.3407290947894517 +0.584,0.34147077742264076 +0.585,0.3432994454657611 +0.586,0.3443583167987984 +0.587,0.3452938141979852 +0.588,0.3469084824864382 +0.589,0.3479790977609104 +0.59,0.3487543040303682 +0.591,0.34966863130038167 +0.592,0.3502782496603959 +0.593,0.3513645541932991 +0.594,0.35244318156265664 +0.595,0.35320692926744524 +0.596,0.3542799172124041 +0.597,0.35493926460160724 +0.598,0.3560286768165866 +0.599,0.35714834995261424 +0.6,0.3598721460587032 +0.601,0.3614686337224468 +0.602,0.36281013208482926 +0.603,0.36437449530920973 +0.604,0.36589747440438153 +0.605,0.36837096949066256 +0.606,0.36980455641308 +0.607,0.37086865729419743 +0.608,0.3726686154627568 +0.609,0.3748887031723714 +0.61,0.3772765299968702 +0.611,0.37882363300098804 +0.612,0.3804936820628148 +0.613,0.38264739589161095 +0.614,0.3837422147133152 +0.615,0.3848784922573346 +0.616,0.38659111824397613 +0.617,0.38739630725007956 +0.618,0.3882643801619453 +0.619,0.38932551888014333 +0.62,0.39007234699168464 +0.621,0.3906507615170504 +0.622,0.39143716833749637 +0.623,0.3923755154353358 +0.624,0.3939607150217326 +0.625,0.39585563962960646 +0.626,0.3965102524136849 +0.627,0.3973559516959612 +0.628,0.39859021508449466 +0.629,0.3991481698354029 +0.63,0.3999289616081354 +0.631,0.4015902707600617 +0.632,0.4036714992517918 +0.633,0.4054896654823553 +0.634,0.40849668276499185 +0.635,0.41067302181744725 +0.636,0.41166960415954373 +0.637,0.41303956496571126 +0.638,0.41477170797608026 +0.639,0.4167150775187936 +0.64,0.418373438241578 +0.641,0.4210833312283727 +0.642,0.422929038492798 +0.643,0.4260730242662612 +0.644,0.4287646949517123 +0.645,0.43031834617602716 +0.646,0.4316502842263877 +0.647,0.43315080649528603 +0.648,0.43485260544685317 +0.649,0.43589746495296233 +0.65,0.4364627696807609 +0.651,0.43802427311215314 +0.652,0.4392169311522322 +0.653,0.4400174848278027 +0.654,0.44226799486745894 +0.655,0.4443717363598302 +0.656,0.44639619351689586 +0.657,0.4485196142004243 +0.658,0.45025049464675 +0.659,0.4513490797711283 +0.66,0.45289126751413533 +0.661,0.45502593041054373 +0.662,0.45638618770343686 +0.663,0.4579102684792186 +0.664,0.45944271665703035 +0.665,0.4609198333185049 +0.666,0.4623115365787327 +0.667,0.4635071584956809 +0.668,0.4644084789373762 +0.669,0.46537921824620765 +0.67,0.4666400491669886 +0.671,0.46879684175596237 +0.672,0.47163969553677487 +0.673,0.47321272497209355 +0.674,0.47500643269411125 +0.675,0.47675540941883215 +0.676,0.4784862734105347 +0.677,0.4800062758764405 +0.678,0.4817016137598272 +0.679,0.48283353937893353 +0.68,0.4853590420324332 +0.681,0.4877521578894085 +0.682,0.4887558011790699 +0.683,0.4912026127571736 +0.684,0.4932390649775282 +0.685,0.49453543190862326 +0.686,0.49597901398341826 +0.687,0.4998819331846366 +0.6880000000000001,0.501317011256499 +0.6890000000000001,0.5033376813443697 +0.6900000000000001,0.505062768574308 +0.6910000000000001,0.506284922341918 +0.6920000000000001,0.5081984694489625 +0.6930000000000001,0.5093866353178489 +0.6940000000000001,0.5116578584436212 +0.6950000000000001,0.5131119303647365 +0.6960000000000001,0.5148437895677432 +0.6970000000000001,0.5163038146710378 +0.6980000000000001,0.5171800201862028 +0.6990000000000001,0.519819470244347 +0.7000000000000001,0.5223358174138488 +0.7010000000000001,0.5244825487044656 +0.7020000000000001,0.5264554589870959 +0.7030000000000001,0.5276203121304215 +0.704,0.5295498856902366 +0.705,0.5312850220789949 +0.706,0.5335686660852782 +0.707,0.5350695394406606 +0.708,0.536177556526681 +0.709,0.5379318331563394 +0.71,0.5395736848920841 +0.711,0.5406121144506997 +0.712,0.5420455544293954 +0.713,0.543841130098193 +0.714,0.5469106141132752 +0.715,0.5492807280591765 +0.716,0.5509208321968749 +0.717,0.5540007093621486 +0.718,0.5558791941588498 +0.719,0.5590026390824284 +0.72,0.560880413904021 +0.721,0.5617871730602774 +0.722,0.5645713675433623 +0.723,0.5655011632520683 +0.724,0.567847876755465 +0.725,0.5690624338842036 +0.726,0.570921672868359 +0.727,0.5732567796073428 +0.728,0.5745502522700852 +0.729,0.5779459357684296 +0.73,0.5797429784471794 +0.731,0.5815570095759035 +0.732,0.5844273103353028 +0.733,0.5875981073494501 +0.734,0.590198506920222 +0.735,0.5922812284423599 +0.736,0.5961165208827701 +0.737,0.599393908431313 +0.738,0.6014133955718053 +0.739,0.6052378959588556 +0.74,0.6080582673167819 +0.741,0.6101819406782203 +0.742,0.6118823242364254 +0.743,0.6168089893956546 +0.744,0.6182859688364172 +0.745,0.6203192248917001 +0.746,0.6214683890549322 +0.747,0.6243301329038635 +0.748,0.6259047095036843 +0.749,0.6273158048934225 +0.75,0.6285309450296591 +0.751,0.6301302979970824 +0.752,0.6314176379120154 +0.753,0.6331304127442994 +0.754,0.6339510547754978 +0.755,0.6352534196369674 +0.756,0.636547259245932 +0.757,0.6381557241686903 +0.758,0.6403746710366298 +0.759,0.6423258784718398 +0.76,0.6444360324189599 +0.761,0.6465409595150843 +0.762,0.6482531488202841 +0.763,0.6497826178153676 +0.764,0.6527669957814302 +0.765,0.6544481555032932 +0.766,0.6572742206540977 +0.767,0.6611473036429513 +0.768,0.664043561935125 +0.769,0.6651260352454267 +0.77,0.6666235085679483 +0.771,0.6687619869371491 +0.772,0.6711155067958973 +0.773,0.6734232957314764 +0.774,0.675230431978638 +0.775,0.676798870819111 +0.776,0.6778102093576914 +0.777,0.6810120771205962 +0.778,0.6824301751252188 +0.779,0.684306450234064 +0.78,0.6855159499737978 +0.781,0.687782162344529 +0.782,0.6885660531194441 +0.783,0.6905309111643076 +0.784,0.6930774180715704 +0.785,0.6956480574285167 +0.786,0.6981795524573139 +0.787,0.6996671160902639 +0.788,0.7032652200419128 +0.789,0.7036851772412699 +0.79,0.7063057135120113 +0.791,0.7077077226795679 +0.792,0.7111264021656013 +0.793,0.7131732699588984 +0.794,0.7143631133670328 +0.795,0.7151630941913654 +0.796,0.7172349836740501 +0.797,0.7194835525152398 +0.798,0.7218825750613462 +0.799,0.7233997340424767 +0.8,0.7258435042931047 +0.801,0.7279855170493823 +0.802,0.7304726140483709 +0.803,0.7336210313718688 +0.804,0.7345876883037915 +0.805,0.737110432910829 +0.806,0.7387918814958968 +0.807,0.7405459424620771 +0.808,0.7423027841222187 +0.809,0.7444729731949881 +0.81,0.7453036040603118 +0.811,0.7468358167798826 +0.812,0.7483198084457068 +0.8130000000000001,0.7495468087922313 +0.8140000000000001,0.7501777094306364 +0.8150000000000001,0.7513201954902143 +0.8160000000000001,0.7531911989501531 +0.8170000000000001,0.7558373776373183 +0.8180000000000001,0.757231168218212 +0.8190000000000001,0.7592886495707016 +0.8200000000000001,0.7619935427500174 +0.8210000000000001,0.7638812566766878 +0.8220000000000001,0.7657885130415554 +0.8230000000000001,0.766898016440394 +0.8240000000000001,0.7693320430257257 +0.8250000000000001,0.7703475167624061 +0.8260000000000001,0.7718370872758612 +0.8270000000000001,0.7731224982774905 +0.8280000000000001,0.7760755098328536 +0.8290000000000001,0.7791016328136352 +0.8300000000000001,0.7801713329830586 +0.8310000000000001,0.781645581755017 +0.8320000000000001,0.7841188726975937 +0.833,0.7858686309619951 +0.834,0.7875904499198999 +0.835,0.7891344438705183 +0.836,0.7925377419392323 +0.837,0.7932731183234029 +0.838,0.7955207649659382 +0.839,0.7968493341836687 +0.84,0.7982966837267264 +0.841,0.8000430967943913 +0.842,0.8011049697175305 +0.843,0.8033007477071072 +0.844,0.8063325951316784 +0.845,0.8077676574203526 +0.846,0.8094323621932727 +0.847,0.8112224448973373 +0.848,0.8129050197078973 +0.849,0.8136721592716375 +0.85,0.8155729946670617 +0.851,0.8170545616404994 +0.852,0.8178248712823145 +0.853,0.8189602454491497 +0.854,0.8212020793901265 +0.855,0.8219856240946373 +0.856,0.8228508862404386 +0.857,0.8238610987318131 +0.858,0.82560861589605 +0.859,0.8267225723036277 +0.86,0.8279756210203914 +0.861,0.8292317335986948 +0.862,0.8309443055581907 +0.863,0.8321604279147511 +0.864,0.8331931815004304 +0.865,0.8348702204172531 +0.866,0.8355008701761438 +0.867,0.8374997004455426 +0.868,0.8390205749525603 +0.869,0.8404911318254462 +0.87,0.8421717235896448 +0.871,0.8438155133819668 +0.872,0.8451937978653274 +0.873,0.8473142505149287 +0.874,0.8493348104315313 +0.875,0.8500921003401266 +0.876,0.8512149640831143 +0.877,0.8520419347654816 +0.878,0.8540706720965576 +0.879,0.8552600117322084 +0.88,0.8574902538205593 +0.881,0.8592276710578894 +0.882,0.8606244884329701 +0.883,0.8614743317522576 +0.884,0.8629810813642349 +0.885,0.8643233269335144 +0.886,0.8651164720022221 +0.887,0.8665364701128104 +0.888,0.8677118414185678 +0.889,0.8694071475932799 +0.89,0.8704639563417581 +0.891,0.8712427521294808 +0.892,0.8724964327146276 +0.893,0.8738725556874115 +0.894,0.8753432257429071 +0.895,0.8759266729101978 +0.896,0.8765902040172849 +0.897,0.8776993747990521 +0.898,0.8787198819713946 +0.899,0.8795658087166881 +0.9,0.8802349568021824 +0.901,0.8814289015122527 +0.902,0.882675247473914 +0.903,0.8835979204443071 +0.904,0.8843371213709692 +0.905,0.8849101070674011 +0.906,0.8859712525723654 +0.907,0.8867559867205788 +0.908,0.8884487229993372 +0.909,0.8896263494908736 +0.91,0.8905744685914239 +0.911,0.8914035116560728 +0.912,0.8920500991291609 +0.913,0.892709168692431 +0.914,0.8942308971125636 +0.915,0.8952330805933911 +0.916,0.896254745936607 +0.917,0.8969566562096285 +0.918,0.8977550005767381 +0.919,0.8988576218570963 +0.92,0.9001580245252396 +0.921,0.9018677586455239 +0.922,0.9030095937798814 +0.923,0.9039921131633913 +0.924,0.9051189454438844 +0.925,0.9061061783482243 +0.926,0.907000942446544 +0.927,0.9079912362480473 +0.928,0.909461944298994 +0.929,0.9106006662880433 +0.93,0.9119268927467409 +0.931,0.9132621155376915 +0.932,0.9142169866619498 +0.933,0.9153608307127082 +0.934,0.9167469841180714 +0.935,0.918610189538422 +0.936,0.9202557035708284 +0.937,0.9218378100566139 +0.9380000000000001,0.9224910017875555 +0.9390000000000001,0.9241059699666094 +0.9400000000000001,0.9250091807701697 +0.9410000000000001,0.9257657098776058 +0.9420000000000001,0.9264488606066655 +0.9430000000000001,0.9272852042555217 +0.9440000000000001,0.9284446208176286 +0.9450000000000001,0.929003253554135 +0.9460000000000001,0.9298744205860292 +0.9470000000000001,0.9310913599828171 +0.9480000000000001,0.932178189977024 +0.9490000000000001,0.9326492931568057 +0.9500000000000001,0.9339078456409762 +0.9510000000000001,0.9346482048966774 +0.9520000000000001,0.9355405346559275 +0.9530000000000001,0.9367383864623728 +0.9540000000000001,0.9376928668921315 +0.9550000000000001,0.9380703710619535 +0.9560000000000001,0.9394140567096567 +0.9570000000000001,0.9405046126908414 +0.9580000000000001,0.9420647392916559 +0.9590000000000001,0.9431225822350192 +0.96,0.9446744423634685 +0.961,0.9457200975688339 +0.962,0.9467901298760809 +0.963,0.947367192790973 +0.964,0.9486468899397595 +0.965,0.9496837204829053 +0.966,0.9511784237356303 +0.967,0.9518586082627088 +0.968,0.9528886420872215 +0.969,0.9539040778924156 +0.97,0.9548768195135587 +0.971,0.95558356367191 +0.972,0.9566785067305117 +0.973,0.9572589266096196 +0.974,0.9578750612060117 +0.975,0.9585686091741119 +0.976,0.9597413211957363 +0.977,0.960817223622322 +0.978,0.9616523013148639 +0.979,0.963178989530648 +0.98,0.964121819549196 +0.981,0.9651627297508396 +0.982,0.9658785239037542 +0.983,0.9667649439753726 +0.984,0.9678487918660454 +0.985,0.9696740596691722 +0.986,0.9704829507455188 +0.987,0.9716782507064722 +0.988,0.9727670846707898 +0.989,0.9737401374836939 +0.99,0.9742057377277695 +0.991,0.9759648157949941 +0.992,0.9765038195474827 +0.993,0.9775814868781152 +0.994,0.979768113085751 +0.995,0.9810933531435388 +0.996,0.9829039239608474 +0.997,0.9843668814605491 +0.998,0.9861021149679724 +0.999,0.9891335673994617 +1.0,0.9958057993494279 diff --git a/service/scripts/profiling/founding_potential/results/sequence_founders/plots/predicted_vs_actual.png b/service/scripts/profiling/founding_potential/results/sequence_founders/plots/predicted_vs_actual.png new file mode 100644 index 00000000..357ccb3f Binary files /dev/null and b/service/scripts/profiling/founding_potential/results/sequence_founders/plots/predicted_vs_actual.png differ diff --git a/service/scripts/profiling/founding_potential/results/sequence_founders/sequence_founders_comparison.csv b/service/scripts/profiling/founding_potential/results/sequence_founders/sequence_founders_comparison.csv new file mode 100644 index 00000000..51c20da9 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/sequence_founders/sequence_founders_comparison.csv @@ -0,0 +1,5 @@ +model,mae,rmse,r2 +transformer,0.17962484061717987,0.26887768507003784,0.9977186918258667 +lstm,0.20817223191261292,0.25809192657470703,0.9978980422019958 +naive_first_activity,0.554347813129425,1.8852977752685547,0.8878419399261475 +aggregate_rf,2.5710210526120405,3.423502154229539,0.6301618414494403 diff --git a/service/scripts/profiling/founding_potential/results/sequence_founders/sequence_founders_comparison.md b/service/scripts/profiling/founding_potential/results/sequence_founders/sequence_founders_comparison.md new file mode 100644 index 00000000..97b24b19 --- /dev/null +++ b/service/scripts/profiling/founding_potential/results/sequence_founders/sequence_founders_comparison.md @@ -0,0 +1,6 @@ +| model | mae | rmse | r2 | +|:---------------------|---------:|---------:|---------:| +| transformer | 0.179625 | 0.268878 | 0.997719 | +| lstm | 0.208172 | 0.258092 | 0.997898 | +| naive_first_activity | 0.554348 | 1.8853 | 0.887842 | +| aggregate_rf | 2.57102 | 3.4235 | 0.630162 | \ No newline at end of file diff --git a/service/scripts/profiling/founding_potential/run_rq1.py b/service/scripts/profiling/founding_potential/run_rq1.py new file mode 100644 index 00000000..7dfef78f --- /dev/null +++ b/service/scripts/profiling/founding_potential/run_rq1.py @@ -0,0 +1,131 @@ +"""RQ1: build a classifier that identifies founders from non-founders. + +Pipeline: +1. Load the leakage-safe full-profile dataset (all 8 institutions). +2. Primary stratified 80/20 split -> train & evaluate primitive baselines and + stronger/state-of-the-art models (+ a stacked ensemble + a PyTorch MLP). +3. McNemar's test between the best baseline and the best overall model. +4. Leave-one-institution-out cross-validation with the top tree models, to + check whether "founder signal" generalizes across universities rather than + just memorizing institution-specific quirks. +5. Permutation importance + SHAP on the best model. + +Run with: conda run -n potential python experiments/run_rq1.py +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import joblib +import numpy as np +import pandas as pd + +from src import config, data, evaluate, explain, models, splits + +RESULTS_DIR = config.RESULTS_DIR / "rq1" +MODELS_DIR = RESULTS_DIR / "models" +MAX_SVM_TRAIN = 6000 + + +def main(): + print("Loading RQ1 dataset (datasets_complete, leakage columns dropped)...") + df_raw = data.load_rq1_raw() + X, y, groups = data.build_rq1_matrix(df_raw, include_institution=True) + print(f" rows={len(X)} features={X.shape[1]} founders={int(y.sum())} non-founders={int((1 - y).sum())}") + + X_train, X_test, y_train, y_test = splits.stratified_holdout(X, y, test_size=0.2) + scale_pos_weight = (y_train == 0).sum() / (y_train == 1).sum() + + all_models = { + **models.baseline_models(), + **models.advanced_models(scale_pos_weight=scale_pos_weight), + "stacking_ensemble": models.stacking_model(scale_pos_weight=scale_pos_weight), + } + try: + from src.nn import TorchMLPClassifier + + all_models["torch_mlp"] = TorchMLPClassifier() + except ImportError: + print(" torch not available, skipping the MLP baseline") + + rows = [] + fitted = {} + curves = {} + for name, model in all_models.items(): + print(f"Training {name} ...") + max_train = MAX_SVM_TRAIN if name == "svm_rbf" else None + model, metrics, pred, proba = evaluate.fit_and_evaluate( + model, X_train, y_train, X_test, y_test, max_train_size=max_train + ) + rows.append({"model": name, **metrics}) + fitted[name] = (model, pred, proba) + curves[name] = (y_test.values, proba) + + table = evaluate.results_table(rows, sort_by="pr_auc") + print(table) + evaluate.save_table(table, RESULTS_DIR / "rq1_model_comparison.csv", RESULTS_DIR / "rq1_model_comparison.md") + + best_baseline = evaluate.results_table( + [r for r in rows if r["model"] in models.baseline_models()], sort_by="pr_auc" + ).index[0] + best_overall = table.index[0] + print(f"Best baseline: {best_baseline} | Best overall: {best_overall}") + + _, pred_baseline, _ = fitted[best_baseline] + _, pred_best, _ = fitted[best_overall] + mcnemar_result = evaluate.mcnemar_test(y_test.values, pred_baseline, pred_best) + print(f"McNemar's test ({best_baseline} vs {best_overall}): {mcnemar_result}") + pd.Series(mcnemar_result).to_csv(RESULTS_DIR / "mcnemar_baseline_vs_best.csv") + + evaluate.plot_confusion(y_test, fitted[best_baseline][1], f"Confusion matrix - {best_baseline}", RESULTS_DIR / "plots" / f"confusion_{best_baseline}.png") + evaluate.plot_confusion(y_test, fitted[best_overall][1], f"Confusion matrix - {best_overall}", RESULTS_DIR / "plots" / f"confusion_{best_overall}.png") + top_curve_models = table.head(5).index.tolist() + evaluate.plot_roc_pr({k: curves[k] for k in top_curve_models}, RESULTS_DIR / "plots" / "top5") + + MODELS_DIR.mkdir(parents=True, exist_ok=True) + joblib.dump(fitted[best_overall][0], MODELS_DIR / f"{best_overall}.joblib") + + # --- Leave-one-institution-out generalization test --- + print("\nLeave-one-institution-out generalization test...") + X_logo, y_logo, groups_logo = data.build_rq1_matrix(df_raw, include_institution=False) + logo_rows = [] + logo_model_names = ["random_forest", "xgboost", "lightgbm"] + for held_out, train_idx, test_idx in splits.leave_one_institution_out(X_logo, y_logo, groups_logo): + spw = (y_logo.iloc[train_idx] == 0).sum() / (y_logo.iloc[train_idx] == 1).sum() + candidates = models.advanced_models(scale_pos_weight=spw) + for name in logo_model_names: + model = candidates[name] + model.fit(X_logo.iloc[train_idx], y_logo.iloc[train_idx]) + proba = model.predict_proba(X_logo.iloc[test_idx])[:, 1] + pred = (proba >= 0.5).astype(int) + metrics = evaluate.compute_metrics(y_logo.iloc[test_idx], pred, proba) + logo_rows.append({"held_out_institution": held_out, "model": name, **metrics}) + print(f" held out {held_out}: done") + + logo_df = pd.DataFrame(logo_rows) + evaluate.save_table(logo_df.set_index(["held_out_institution", "model"]), RESULTS_DIR / "rq1_leave_one_institution_out.csv", RESULTS_DIR / "rq1_leave_one_institution_out.md") + print(logo_df.groupby("model")[["roc_auc", "pr_auc", "mcc"]].mean()) + + # --- Explainability; falls back to a tree model since SHAP TreeExplainer + # needs one --- + tree_models = {"random_forest", "xgboost", "lightgbm", "catboost"} + explain_target = best_overall if best_overall in tree_models else next((m for m in table.index if m in tree_models), None) + if explain_target is not None: + print(f"\nExplainability on {explain_target} ...") + explain_model = fitted[explain_target][0] + explain.permutation_importance_report( + explain_model, X_test, y_test, + RESULTS_DIR / "permutation_importance.csv", RESULTS_DIR / "plots" / "permutation_importance.png", + ) + sample = X_test.sample(min(500, len(X_test)), random_state=config.RANDOM_STATE) + try: + explain.shap_summary(explain_model, sample, RESULTS_DIR / "plots" / "shap_summary.png") + except Exception as exc: # SHAP TreeExplainer support varies by model internals + print(f" SHAP summary skipped: {exc}") + + print(f"\nAll RQ1 results written to {RESULTS_DIR}") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/founding_potential/run_rq1_robustness.py b/service/scripts/profiling/founding_potential/run_rq1_robustness.py new file mode 100644 index 00000000..00c53b4e --- /dev/null +++ b/service/scripts/profiling/founding_potential/run_rq1_robustness.py @@ -0,0 +1,209 @@ +"""RQ1 robustness / foolproofing pass: cross-validation with confidence +intervals, hyperparameter tuning, calibration, bootstrap CIs, and analysis of +how research-area field differences affect the model -- all requested as +follow-ups after the initial RQ1/RQ2 results. + +Sections (each independent, run in order): +1. Ablation: pre-founding-equivalent fix ON vs OFF (quantifies the + reverse-causation confound found while investigating the "n.a. research + area" group -- see README for the full writeup). +2. 5-fold stratified CV with 95% CIs for the headline models (replaces relying + on a single 80/20 split for the topline numbers). +3. Hyperparameter tuning (RandomizedSearchCV) for random_forest/xgboost/lightgbm. +4. Calibration curves (reliability diagrams) for logistic_regression vs default + vs tuned LightGBM. +5. Bootstrap 95% CIs for the tuned model's held-out metrics. +6. Stratified evaluation of the tuned pooled model, broken out by broad + research area, to check whether it works uniformly or is riding field + base-rates. +7. Per-area specialist models vs. the pooled generalist model, on the same + per-area test subsets, for the largest research areas. + +Run with: conda run -n potential python experiments/run_rq1_robustness.py +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import json + +import pandas as pd + +from src import config, data, evaluate, models, splits, tuning + +RESULTS_DIR = config.RESULTS_DIR / "rq1_robustness" + + +def section_ablation(): + print("=== 1. Pre-founding-equivalent fix: ablation ===") + rows = [] + for label, kwargs in [("fix_on", {}), ("fix_off", {"apply_prefounding_fix": False})]: + df_raw = data.load_rq1_raw(**kwargs) + X, y, _ = data.build_rq1_matrix(df_raw, include_institution=True) + X_train, X_test, y_train, y_test = splits.stratified_holdout(X, y, test_size=0.2) + spw = (y_train == 0).sum() / (y_train == 1).sum() + model = models.advanced_models(scale_pos_weight=spw)["lightgbm"] + _, metrics, _, _ = evaluate.fit_and_evaluate(model, X_train, y_train, X_test, y_test) + rows.append({"pipeline": label, "n_rows": len(X), **metrics}) + print(f" {label}: n={len(X)} roc_auc={metrics['roc_auc']:.4f} pr_auc={metrics['pr_auc']:.4f}") + table = pd.DataFrame(rows).set_index("pipeline") + evaluate.save_table(table, RESULTS_DIR / "ablation_prefounding_fix.csv", RESULTS_DIR / "ablation_prefounding_fix.md") + print(" (fix_on = corrected pipeline used everywhere else; fix_off = original\n" + " lifetime-total features, kept only for this comparison)\n") + + +def load_clean(): + df_raw = data.load_rq1_raw() + X, y, groups = data.build_rq1_matrix(df_raw, include_institution=True) + return df_raw, X, y, groups + + +def section_cross_validation(X, y): + print("=== 2. 5-fold stratified CV with 95% CIs ===") + # StratifiedKFold preserves the class ratio per fold, so one overall + # scale_pos_weight approximates the per-fold value for xgboost. + spw = (y == 0).sum() / (y == 1).sum() + factories = { + "dummy_most_frequent": lambda: models.baseline_models()["dummy_most_frequent"], + "logistic_regression": lambda: models.baseline_models()["logistic_regression"], + "random_forest": lambda: models.advanced_models()["random_forest"], + "xgboost": lambda: models.advanced_models(scale_pos_weight=spw)["xgboost"], + "lightgbm": lambda: models.advanced_models()["lightgbm"], + } + summaries = {} + for name, factory in factories.items(): + _, summary = evaluate.cross_validate_model(factory, X, y, cv=5) + summaries[name] = summary["mean"] + print(f" {name}: pr_auc={summary.loc['pr_auc','mean']:.4f} " + f"[{summary.loc['pr_auc','ci95_low']:.4f}, {summary.loc['pr_auc','ci95_high']:.4f}] " + f"roc_auc={summary.loc['roc_auc','mean']:.4f} " + f"[{summary.loc['roc_auc','ci95_low']:.4f}, {summary.loc['roc_auc','ci95_high']:.4f}]") + summary.to_csv(RESULTS_DIR / f"cv_{name}.csv") + table = pd.DataFrame(summaries).T + evaluate.save_table(table, RESULTS_DIR / "cv_summary_mean.csv", RESULTS_DIR / "cv_summary_mean.md") + print() + + +def section_tuning(X_train, y_train, X_test, y_test): + print("=== 3. Hyperparameter tuning (RandomizedSearchCV) ===") + spw = (y_train == 0).sum() / (y_train == 1).sum() + rows = [] + tuned_models = {} + best_params = {} + for name in ["random_forest", "xgboost", "lightgbm"]: + default_model = models.advanced_models(scale_pos_weight=spw)[name] + _, default_metrics, _, default_proba = evaluate.fit_and_evaluate(default_model, X_train, y_train, X_test, y_test) + rows.append({"model": name, "variant": "default", **default_metrics}) + + print(f" tuning {name} (n_iter=20, cv=3, scoring=average_precision) ...") + best_est, params, _ = tuning.tune_model(name, X_train, y_train, n_iter=20, cv=3, scale_pos_weight=spw) + proba = best_est.predict_proba(X_test)[:, 1] + pred = (proba >= 0.5).astype(int) + tuned_metrics = evaluate.compute_metrics(y_test, pred, proba) + rows.append({"model": name, "variant": "tuned", **tuned_metrics}) + tuned_models[name] = (best_est, pred, proba) + best_params[name] = params + print(f" default pr_auc={default_metrics['pr_auc']:.4f} -> tuned pr_auc={tuned_metrics['pr_auc']:.4f}") + + table = pd.DataFrame(rows).set_index(["model", "variant"]) + evaluate.save_table(table, RESULTS_DIR / "tuning_comparison.csv", RESULTS_DIR / "tuning_comparison.md") + (RESULTS_DIR / "tuning_best_params.json").write_text(json.dumps(best_params, indent=2, default=str)) + print() + return tuned_models + + +def section_calibration(X_train, y_train, X_test, y_test, tuned_models): + print("=== 4. Calibration curves ===") + logistic = models.baseline_models()["logistic_regression"] + logistic.fit(X_train, y_train) + logistic_proba = logistic.predict_proba(X_test)[:, 1] + + default_lgbm = models.advanced_models()["lightgbm"] + default_lgbm.fit(X_train, y_train) + default_proba = default_lgbm.predict_proba(X_test)[:, 1] + + tuned_proba = tuned_models["lightgbm"][2] + + curves = { + "logistic_regression": (y_test.values, logistic_proba), + "lightgbm_default": (y_test.values, default_proba), + "lightgbm_tuned": (y_test.values, tuned_proba), + } + evaluate.plot_calibration(curves, RESULTS_DIR / "plots" / "calibration.png") + print(f" saved to {RESULTS_DIR / 'plots' / 'calibration.png'}\n") + + +def section_bootstrap(y_test, tuned_models, best_model_name="lightgbm"): + print("=== 5. Bootstrap 95% CIs (tuned model, 1000 resamples) ===") + _, _, proba = tuned_models[best_model_name] + summary = evaluate.bootstrap_metric_ci(y_test.values, proba, n_boot=1000) + print(summary) + evaluate.save_table(summary, RESULTS_DIR / "bootstrap_ci.csv", RESULTS_DIR / "bootstrap_ci.md") + print() + + +def section_area_stratified(df_raw, X_test, y_test, tuned_models, best_model_name="lightgbm"): + print("=== 6. Stratified evaluation by broad research area (tuned pooled model) ===") + _, pred, proba = tuned_models[best_model_name] + broad_area = data._broad_research_area(df_raw["publication_research_area"]).loc[X_test.index] + table = evaluate.stratified_metrics(y_test, pred, proba, broad_area) + print(table[["n", "founder_rate", "roc_auc", "pr_auc", "mcc"]]) + evaluate.save_table(table, RESULTS_DIR / "area_stratified_pooled_model.csv", RESULTS_DIR / "area_stratified_pooled_model.md") + print() + return broad_area + + +def section_per_area_specialists(df_raw, X, y, X_test, y_test, tuned_models, broad_area_all, best_model_name="lightgbm", min_n=500): + print("=== 7. Per-area specialist models vs. pooled generalist ===") + broad_area_full = data._broad_research_area(df_raw["publication_research_area"]) + counts = broad_area_full.value_counts() + areas = [a for a in counts[counts >= min_n].index if a != "n."] + + _, pooled_pred, pooled_proba = tuned_models[best_model_name] + rows = [] + for area in areas: + area_idx_all = broad_area_full[broad_area_full == area].index + X_area, y_area = X.loc[area_idx_all], y.loc[area_idx_all] + X_tr, X_te, y_tr, y_te = splits.stratified_holdout(X_area, y_area, test_size=0.2) + spw = (y_tr == 0).sum() / max((y_tr == 1).sum(), 1) + specialist = models.advanced_models(scale_pos_weight=spw)["lightgbm"] + _, spec_metrics, _, _ = evaluate.fit_and_evaluate(specialist, X_tr, y_tr, X_te, y_te) + rows.append({"area": area, "model": "specialist", "n_train": len(X_tr), "n_test": len(X_te), **spec_metrics}) + + pooled_area_test_idx = broad_area_all[broad_area_all == area].index + if len(pooled_area_test_idx) >= 20: + yt = y_test.loc[pooled_area_test_idx] + ypred = pd.Series(pooled_pred, index=X_test.index).loc[pooled_area_test_idx] + yproba = pd.Series(pooled_proba, index=X_test.index).loc[pooled_area_test_idx] + if yt.nunique() == 2: + pooled_metrics = evaluate.compute_metrics(yt, ypred, yproba) + rows.append({"area": area, "model": "pooled_on_subset", "n_train": None, "n_test": len(pooled_area_test_idx), **pooled_metrics}) + print(f" area {area}: specialist pr_auc={spec_metrics['pr_auc']:.4f} (n_train={len(X_tr)})") + + table = pd.DataFrame(rows).set_index(["area", "model"]) + evaluate.save_table(table, RESULTS_DIR / "per_area_specialist_vs_pooled.csv", RESULTS_DIR / "per_area_specialist_vs_pooled.md") + print() + + +def main(): + section_ablation() + + print("Loading clean RQ1 dataset for CV/tuning/calibration/bootstrap/stratification...") + df_raw, X, y, groups = load_clean() + print(f" rows={len(X)} features={X.shape[1]}\n") + + section_cross_validation(X, y) + + X_train, X_test, y_train, y_test = splits.stratified_holdout(X, y, test_size=0.2) + tuned_models = section_tuning(X_train, y_train, X_test, y_test) + section_calibration(X_train, y_train, X_test, y_test, tuned_models) + section_bootstrap(y_test, tuned_models) + broad_area_test = section_area_stratified(df_raw, X_test, y_test, tuned_models) + section_per_area_specialists(df_raw, X, y, X_test, y_test, tuned_models, broad_area_test) + + print(f"All RQ1 robustness results written to {RESULTS_DIR}") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/founding_potential/run_rq1_symmetric.py b/service/scripts/profiling/founding_potential/run_rq1_symmetric.py new file mode 100644 index 00000000..5cc8b1ad --- /dev/null +++ b/service/scripts/profiling/founding_potential/run_rq1_symmetric.py @@ -0,0 +1,157 @@ +"""RQ1 retrained on the symmetric (landmark-design) dataset -- see src/symmetric.py. + +Compared to run_rq1.py (asymmetric preprocessing) this answers: how well can +founders be distinguished from non-founders when BOTH classes are observed over +comparable windows and features are constructed identically? Expect honest +(lower) numbers than the 0.976 ROC-AUC of the asymmetric design, which was +inflated by window-length leakage. + +Adds production-relevant checks the original run lacked: +- temporal split (train on pre-2016 index years, test on 2016+): the prospective + deployment setting; +- monotonicity probe of P(founder) vs. publications-at-index (the shipped + asymmetric model was an inverse-productivity score: 1 pub -> 0.996, 800 -> 0.0002); +- reference score distribution saved for percentile-ranking in production. + +Run with: conda run -n potential python experiments/run_rq1_symmetric.py +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import joblib +import numpy as np +import pandas as pd + +from src import config, evaluate, models, splits, symmetric + +RESULTS_DIR = config.RESULTS_DIR / "rq1_symmetric" +MODELS_DIR = RESULTS_DIR / "models" +TEMPORAL_SPLIT_YEAR = 2016 # train index_year < this, test >= this + + +def probability_by_pubs_decile(model, X_test, feats_test): + """Median predicted P(founder) per pubs-at-index decile -- the check that + caught the inverse-productivity artifact in the shipped model.""" + proba = model.predict_proba(X_test)[:, 1] + pubs = feats_test["pubs_at_index"].reset_index(drop=True) + dec = pd.qcut(pubs, 10, labels=False, duplicates="drop") + return pd.DataFrame({ + "pubs_decile": dec, "pubs_at_index": pubs, "p_founder": proba + }).groupby("pubs_decile").agg( + pubs_median=("pubs_at_index", "median"), p_founder_median=("p_founder", "median"), n=("p_founder", "size") + ) + + +def main(): + RESULTS_DIR.mkdir(parents=True, exist_ok=True) + MODELS_DIR.mkdir(parents=True, exist_ok=True) + (RESULTS_DIR / "plots").mkdir(exist_ok=True) + + print("Building symmetric RQ1 dataset ...") + feats, attrition = symmetric.build_symmetric_dataset() + pd.Series(attrition).to_csv(RESULTS_DIR / "attrition.csv") + X, y, groups = symmetric.build_matrix(feats, include_institution=True) + print(f" rows={len(X)} features={X.shape[1]} founders={int(y.sum())} non-founders={int((1 - y).sum())}") + + idx_train, idx_test, _, _ = splits.stratified_holdout(X.index.to_series(), y, test_size=0.2) + idx_train, idx_test = idx_train.values, idx_test.values + X_train, X_test = X.loc[idx_train], X.loc[idx_test] + y_train, y_test = y.loc[idx_train], y.loc[idx_test] + feats_test = feats.loc[idx_test] + scale_pos_weight = (y_train == 0).sum() / (y_train == 1).sum() + + all_models = { + **models.baseline_models(), + **models.advanced_models(scale_pos_weight=scale_pos_weight), + "stacking_ensemble": models.stacking_model(scale_pos_weight=scale_pos_weight), + } + + rows, fitted, curves = [], {}, {} + for name, model in all_models.items(): + print(f"Training {name} ...") + max_train = 6000 if name == "svm_rbf" else None + model, metrics, pred, proba = evaluate.fit_and_evaluate( + model, X_train, y_train, X_test, y_test, max_train_size=max_train + ) + rows.append({"model": name, **metrics}) + fitted[name] = (model, pred, proba) + curves[name] = (y_test.values, proba) + + table = evaluate.results_table(rows, sort_by="pr_auc") + print(table) + evaluate.save_table(table, RESULTS_DIR / "model_comparison.csv", RESULTS_DIR / "model_comparison.md") + best_overall = table.index[0] + best_model = fitted[best_overall][0] + print(f"Best overall: {best_overall}") + joblib.dump(best_model, MODELS_DIR / f"{best_overall}.joblib") + + # --- Monotonicity probe ------------------------------------------------- + probe = probability_by_pubs_decile(best_model, X_test, feats_test) + print("\nP(founder) by pubs-at-index decile (was strictly decreasing in the shipped model):") + print(probe) + probe.to_csv(RESULTS_DIR / "probability_by_pubs_decile.csv") + + # --- Temporal (prospective) split -------------------------------------- + print(f"\nTemporal split: train index_year < {TEMPORAL_SPLIT_YEAR}, test >= {TEMPORAL_SPLIT_YEAR} ...") + is_late = feats["index_year"] >= TEMPORAL_SPLIT_YEAR + Xtr, ytr = X[~is_late.values], y[~is_late.values] + Xte, yte = X[is_late.values], y[is_late.values] + print(f" train: {len(Xtr)} rows ({int(ytr.sum())} founders) | test: {len(Xte)} rows ({int(yte.sum())} founders)") + spw = (ytr == 0).sum() / (ytr == 1).sum() + temporal_rows = [] + for name, model in models.advanced_models(scale_pos_weight=spw).items(): + if name == "svm_rbf": + continue + model.fit(Xtr, ytr) + proba = model.predict_proba(Xte)[:, 1] + pred = (proba >= 0.5).astype(int) + temporal_rows.append({"model": name, **evaluate.compute_metrics(yte, pred, proba)}) + temporal_table = evaluate.results_table(temporal_rows, sort_by="pr_auc") + print(temporal_table) + evaluate.save_table(temporal_table, RESULTS_DIR / "temporal_split.csv", RESULTS_DIR / "temporal_split.md") + + # --- Leave-one-institution-out ------------------------------------------ + print("\nLeave-one-institution-out ...") + X_logo, y_logo, groups_logo = symmetric.build_matrix(feats, include_institution=False) + logo_rows = [] + for held_out, train_idx, test_idx in splits.leave_one_institution_out(X_logo, y_logo, groups_logo): + spw = (y_logo.iloc[train_idx] == 0).sum() / (y_logo.iloc[train_idx] == 1).sum() + for name in ["random_forest", "xgboost", "lightgbm"]: + model = models.advanced_models(scale_pos_weight=spw)[name] + model.fit(X_logo.iloc[train_idx], y_logo.iloc[train_idx]) + proba = model.predict_proba(X_logo.iloc[test_idx])[:, 1] + pred = (proba >= 0.5).astype(int) + logo_rows.append({"held_out_institution": held_out, "model": name, + **evaluate.compute_metrics(y_logo.iloc[test_idx], pred, proba)}) + print(f" held out {held_out}: done") + logo_df = pd.DataFrame(logo_rows) + evaluate.save_table(logo_df.set_index(["held_out_institution", "model"]), + RESULTS_DIR / "leave_one_institution_out.csv", + RESULTS_DIR / "leave_one_institution_out.md") + print(logo_df.groupby("model")[["roc_auc", "pr_auc", "mcc"]].mean()) + + # --- Permutation importance --------------------------------------------- + from src import explain + tree_models = {"random_forest", "xgboost", "lightgbm", "catboost"} + target = best_overall if best_overall in tree_models else next((m for m in table.index if m in tree_models), None) + if target: + explain.permutation_importance_report( + fitted[target][0], X_test, y_test, + RESULTS_DIR / "permutation_importance.csv", + RESULTS_DIR / "plots" / "permutation_importance.png", + ) + + # --- Reference score distribution for production percentile ranking ----- + ref_scores = best_model.predict_proba(X)[:, 1] + ref = pd.DataFrame({ + "quantile": np.linspace(0, 1, 1001), + "score": np.quantile(ref_scores, np.linspace(0, 1, 1001)), + }) + ref.to_csv(MODELS_DIR / "reference_score_quantiles.csv", index=False) + print(f"\nAll results written to {RESULTS_DIR}") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/founding_potential/run_rq2.py b/service/scripts/profiling/founding_potential/run_rq2.py new file mode 100644 index 00000000..5bba8ddf --- /dev/null +++ b/service/scripts/profiling/founding_potential/run_rq2.py @@ -0,0 +1,143 @@ +"""RQ2: how far in advance can we tell that a researcher will found a company +within N years, using only information available at that point in time? + +Pipeline: +1. Per-offset comparison: baselines vs. advanced models trained/evaluated + separately at offsets 1, 2 and 3 years before founding (half-profiles). +2. Pooled multi-horizon model: one model trained across offsets 1-3 with + `offset` as an explicit feature, then evaluated on genuinely unseen + founders/non-founders at offset 3 (in-range) and offset 5 (extrapolation + beyond anything seen in training) -- the direct answer to "up to how many + years out can we predict founding". +3. Survival analysis (CoxPH): a principled alternative to picking a fixed + horizon -- gives P(founds within k years) for any k and treats still-active + non-founders as censored rather than as permanent negatives. + +Run with: conda run -n potential python experiments/run_rq2.py +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import joblib +import pandas as pd +from sklearn.metrics import roc_auc_score + +from src import config, data, evaluate, models, splits, survival + +RESULTS_DIR = config.RESULTS_DIR / "rq2" +MODELS_DIR = RESULTS_DIR / "models" + + +def run_single_offset_comparison(): + all_rows = [] + for offset in config.RQ2_TRAIN_OFFSETS: + print(f"\n=== offset={offset} year(s) before founding ===") + df = data.load_rq2_train_dataset(offset) + X, y, _ = data.build_rq2_matrix(df, include_offset=False) + X_train, X_test, y_train, y_test = splits.stratified_holdout(X, y, test_size=0.2) + spw = (y_train == 0).sum() / (y_train == 1).sum() + + baselines = models.baseline_models() + advanced = models.advanced_models(scale_pos_weight=spw) + candidates = { + "dummy_most_frequent": baselines["dummy_most_frequent"], + "logistic_regression": baselines["logistic_regression"], + "decision_tree": baselines["decision_tree"], + "random_forest": advanced["random_forest"], + "xgboost": advanced["xgboost"], + "lightgbm": advanced["lightgbm"], + } + for name, model in candidates.items(): + _, metrics, _, _ = evaluate.fit_and_evaluate(model, X_train, y_train, X_test, y_test) + all_rows.append({"offset_years": offset, "model": name, **metrics}) + + df_results = pd.DataFrame(all_rows) + evaluate.save_table( + df_results.set_index(["offset_years", "model"]), + RESULTS_DIR / "rq2_offset_comparison.csv", + RESULTS_DIR / "rq2_offset_comparison.md", + ) + print(df_results.pivot_table(index="model", columns="offset_years", values="pr_auc")) + return df_results + + +def run_pooled_horizon_model(): + print("\n=== Pooled multi-horizon model (offsets 1-3 train) ===") + train_frames = [data.load_rq2_train_dataset(o) for o in config.RQ2_TRAIN_OFFSETS] + df_train_all = pd.concat(train_frames, ignore_index=True) + X, y, _ = data.build_rq2_matrix(df_train_all, include_offset=True) + X_train, X_test, y_train, y_test = splits.stratified_holdout(X, y, test_size=0.2) + spw = (y_train == 0).sum() / (y_train == 1).sum() + + pooled_model_name = "lightgbm" + pooled_model = models.advanced_models(scale_pos_weight=spw)[pooled_model_name] + pooled_model, metrics, _, _ = evaluate.fit_and_evaluate(pooled_model, X_train, y_train, X_test, y_test) + print(f"Pooled {pooled_model_name} held-out metrics: {metrics}") + + MODELS_DIR.mkdir(parents=True, exist_ok=True) + joblib.dump(pooled_model, MODELS_DIR / f"pooled_{pooled_model_name}.joblib") + + validation_rows = [] + for offset in config.RQ2_VALIDATION_OFFSETS: + df_val = data.load_rq2_validation_dataset(offset) + X_val, y_val, _ = data.build_rq2_matrix(df_val, include_offset=True) + X_val = X_val.reindex(columns=X_train.columns, fill_value=0) + proba_val = pooled_model.predict_proba(X_val)[:, 1] + pred_val = (proba_val >= 0.5).astype(int) + val_metrics = evaluate.compute_metrics(y_val, pred_val, proba_val) + regime = "in-range" if offset in config.RQ2_TRAIN_OFFSETS else "extrapolation" + validation_rows.append({"offset_years": offset, "regime": regime, **val_metrics}) + print(f" offset={offset} ({regime}) held-out validation: {val_metrics}") + + val_df = pd.DataFrame(validation_rows).set_index("offset_years") + evaluate.save_table(val_df, RESULTS_DIR / "rq2_horizon_validation.csv", RESULTS_DIR / "rq2_horizon_validation.md") + return pooled_model, X_train.columns, val_df + + +def run_survival_analysis(pooled_val_df): + print("\n=== Survival analysis (CoxPH) ===") + df_raw = data.load_survival_raw() + frame = survival.build_survival_frame(df_raw) + train_frame, test_frame, _, _ = splits.stratified_holdout(frame, frame["event"], test_size=0.2) + + cph = survival.fit_coxph(train_frame) + c_index = survival.evaluate_concordance(cph, test_frame) + print(f"CoxPH concordance index (held-out): {c_index:.3f}") + + eligible, label_5y = survival.landmark_labels(test_frame, years=5) + eligible_frame = test_frame[eligible] + eligible_label = label_5y[eligible] + proba_5y = survival.probability_of_founding_within(cph, eligible_frame, years=5) + survival_auc = roc_auc_score(eligible_label, proba_5y) + print(f"CoxPH P(founds within 5y) AUC on eligible held-out rows: {survival_auc:.3f} (n={len(eligible_frame)})") + + summary_rows = [ + {"method": "CoxPH survival model", "metric": "concordance_index", "value": c_index}, + {"method": "CoxPH survival model", "metric": "auc_within_5y", "value": survival_auc}, + ] + if pooled_val_df is not None and 5 in pooled_val_df.index: + summary_rows.append( + { + "method": "Pooled classifier (offset=5, extrapolation)", + "metric": "roc_auc", + "value": pooled_val_df.loc[5, "roc_auc"], + } + ) + summary = pd.DataFrame(summary_rows) + evaluate.save_table(summary.set_index(["method", "metric"]), RESULTS_DIR / "rq2_survival_vs_classifier.csv") + cph.print_summary() + return cph + + +def main(): + RESULTS_DIR.mkdir(parents=True, exist_ok=True) + run_single_offset_comparison() + _, _, val_df = run_pooled_horizon_model() + run_survival_analysis(val_df) + print(f"\nAll RQ2 results written to {RESULTS_DIR}") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/founding_potential/run_rq2_symmetric.py b/service/scripts/profiling/founding_potential/run_rq2_symmetric.py new file mode 100644 index 00000000..e79461c1 --- /dev/null +++ b/service/scripts/profiling/founding_potential/run_rq2_symmetric.py @@ -0,0 +1,100 @@ +"""RQ2 (founds within N years) retrained on the symmetric landmark design. + +The shipped RQ2 stack was degenerate in production: p_within_3y and p_within_5y +were exactly 1.0 for every scored author. Root cause is the same window +asymmetry as RQ1: offset-truncated founders were paired with FULL-career +non-founder profiles (data.load_rq2_train_dataset), so "profile smaller than a +full career" itself separated the classes -- saturating the longer horizons. + +Here, for each horizon k the profile of EVERY person is truncated at +(index_year - k): founding year for founders (label 1 = founds within k years), +sampled pseudo-founding year for non-founders (label 0). Construction is +identical across classes (src/symmetric.py). Rows whose truncated profile has +no publications are dropped SYMMETRICALLY: they do not correspond to scoreable +academics at prediction time, and one-sided empties were the original leak. + +The degeneracy check at the end verifies the predicted p_within_k distribution +actually discriminates (the shipped model's failure mode). + +Run with: conda run -n potential python experiments/run_rq2_symmetric.py +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import joblib +import numpy as np +import pandas as pd + +from src import config, evaluate, models, splits, symmetric + +RESULTS_DIR = config.RESULTS_DIR / "rq2_symmetric" +MODELS_DIR = RESULTS_DIR / "models" +HORIZONS = [1, 3, 5] + + +def main(): + RESULTS_DIR.mkdir(parents=True, exist_ok=True) + MODELS_DIR.mkdir(parents=True, exist_ok=True) + + summary_rows = [] + for k in HORIZONS: + print(f"\n=== Horizon: founds within {k} years ===") + feats, _ = symmetric.build_symmetric_dataset(offset=k) + nonempty = feats["pubs_at_index"] > 0 + dropped = (~nonempty).groupby(feats[config.LABEL_COLUMN]).sum() + print(f" empty-profile rows dropped: founders={int(dropped.get(1, 0))} " + f"non-founders={int(dropped.get(0, 0))}") + feats = feats[nonempty].reset_index(drop=True) + + X, y, groups = symmetric.build_matrix(feats, include_institution=True) + print(f" rows={len(X)} founders={int(y.sum())}") + + idx_train, idx_test, _, _ = splits.stratified_holdout(X.index.to_series(), y, test_size=0.2) + idx_train, idx_test = idx_train.values, idx_test.values + X_train, X_test = X.loc[idx_train], X.loc[idx_test] + y_train, y_test = y.loc[idx_train], y.loc[idx_test] + spw = (y_train == 0).sum() / (y_train == 1).sum() + + rows, fitted = [], {} + for name, model in models.advanced_models(scale_pos_weight=spw).items(): + if name == "svm_rbf": + continue + model, metrics, pred, proba = evaluate.fit_and_evaluate(model, X_train, y_train, X_test, y_test) + rows.append({"model": name, **metrics}) + fitted[name] = (model, proba) + table = evaluate.results_table(rows, sort_by="pr_auc") + print(table) + evaluate.save_table(table, RESULTS_DIR / f"horizon{k}_model_comparison.csv", + RESULTS_DIR / f"horizon{k}_model_comparison.md") + + best = table.index[0] + best_model, best_proba = fitted[best] + joblib.dump(best_model, MODELS_DIR / f"p_within_{k}y_{best}.joblib") + + # Degeneracy check: the shipped model returned 1.0 for everyone at k=3,5. + q = np.quantile(best_proba, [0.05, 0.25, 0.5, 0.75, 0.95]) + frac_saturated = float((best_proba > 0.99).mean()) + print(f" p_within_{k}y test-set quantiles p5..p95: {np.round(q, 3)} | frac >0.99: {frac_saturated:.3f}") + summary_rows.append({ + "horizon": k, "best_model": best, "rows": len(X), + "roc_auc": table.iloc[0]["roc_auc"], "pr_auc": table.iloc[0]["pr_auc"], + "p5": q[0], "p50": q[2], "p95": q[4], "frac_above_0.99": frac_saturated, + }) + + ref = pd.DataFrame({ + "quantile": np.linspace(0, 1, 1001), + "score": np.quantile(best_model.predict_proba(X)[:, 1], np.linspace(0, 1, 1001)), + }) + ref.to_csv(MODELS_DIR / f"p_within_{k}y_reference_quantiles.csv", index=False) + + summary = pd.DataFrame(summary_rows).set_index("horizon") + print("\n=== Horizon summary ===") + print(summary) + evaluate.save_table(summary, RESULTS_DIR / "horizon_summary.csv", RESULTS_DIR / "horizon_summary.md") + print(f"\nAll results written to {RESULTS_DIR}") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/founding_potential/run_sequence_founders.py b/service/scripts/profiling/founding_potential/run_sequence_founders.py new file mode 100644 index 00000000..bc1038af --- /dev/null +++ b/service/scripts/profiling/founding_potential/run_sequence_founders.py @@ -0,0 +1,95 @@ +"""Founder-only sequence modeling: can the *shape* of pre-founding academic/ +patent/grant activity (not just career totals) predict how early or late in a +founder's career they started their company? + +Task: predict `founding_age = founded_on (year) - first_publication_year` from +the chronological pre-founding window `hist_{pub,pat,grant}_FN-20..FN-1`, +restricted to founders where founding_age <= 20 (see `sequence_data.py` for why +that restriction is necessary -- the window can't resolve longer careers). + +Compared approaches (weakest to strongest, to see whether the extra sequence- +modeling complexity actually earns its keep over simpler baselines): +1. naive_first_activity: deterministic "20 - (leading zero years)" heuristic, + no fitting at all. +2. aggregate_rf: RandomForestRegressor on hand-crafted summary stats (total + activity / nonzero-year count / last-3-years activity per channel). +3. lstm: sequence model over the raw chronological window. +4. transformer: small Transformer encoder over the same window. + +Run with: conda run -n potential python experiments/run_sequence_founders.py +""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import numpy as np +import pandas as pd +from sklearn.ensemble import RandomForestRegressor +from sklearn.model_selection import train_test_split + +from src import config, evaluate, sequence_data, sequence_models + +RESULTS_DIR = config.RESULTS_DIR / "sequence_founders" + + +def main(): + print("Building founder-only sequence dataset...") + sequences, founding_age, meta = sequence_data.build_founder_sequence_dataset() + print(f" final dataset: n={len(sequences)} founding_age range " + f"[{founding_age.min():.0f}, {founding_age.max():.0f}] mean={founding_age.mean():.2f}\n") + + idx = np.arange(len(sequences)) + idx_train, idx_test = train_test_split(idx, test_size=0.2, random_state=config.RANDOM_STATE) + X_train, X_test = sequences[idx_train], sequences[idx_test] + y_train, y_test = founding_age[idx_train], founding_age[idx_test] + + rows = [] + curves = {} + + print("1. Naive first-activity heuristic (no fitting)...") + pred = sequence_data.naive_first_activity_baseline(X_test) + metrics = evaluate.regression_metrics(y_test, pred) + rows.append({"model": "naive_first_activity", **metrics}) + curves["naive_first_activity"] = (y_test, pred) + print(f" MAE={metrics['mae']:.3f} RMSE={metrics['rmse']:.3f} R2={metrics['r2']:.3f}") + + print("2. Aggregate-feature RandomForestRegressor...") + agg_train = sequence_data.aggregate_features(X_train) + agg_test = sequence_data.aggregate_features(X_test) + rf = RandomForestRegressor(n_estimators=400, max_depth=8, random_state=config.RANDOM_STATE, n_jobs=-1) + rf.fit(agg_train, y_train) + pred = rf.predict(agg_test) + metrics = evaluate.regression_metrics(y_test, pred) + rows.append({"model": "aggregate_rf", **metrics}) + curves["aggregate_rf"] = (y_test, pred) + print(f" MAE={metrics['mae']:.3f} RMSE={metrics['rmse']:.3f} R2={metrics['r2']:.3f}") + + print("3. LSTM sequence regressor...") + lstm = sequence_models.LSTMRegressor(hidden_size=64, num_layers=1, dropout=0.2) + lstm.fit(X_train, y_train) + pred = lstm.predict(X_test) + metrics = evaluate.regression_metrics(y_test, pred) + rows.append({"model": "lstm", **metrics}) + curves["lstm"] = (y_test, pred) + print(f" MAE={metrics['mae']:.3f} RMSE={metrics['rmse']:.3f} R2={metrics['r2']:.3f}") + + print("4. Transformer sequence regressor...") + transformer = sequence_models.TransformerRegressor(d_model=32, n_heads=4, n_layers=2, dropout=0.2) + transformer.fit(X_train, y_train) + pred = transformer.predict(X_test) + metrics = evaluate.regression_metrics(y_test, pred) + rows.append({"model": "transformer", **metrics}) + curves["transformer"] = (y_test, pred) + print(f" MAE={metrics['mae']:.3f} RMSE={metrics['rmse']:.3f} R2={metrics['r2']:.3f}") + + table = pd.DataFrame(rows).set_index("model").sort_values("mae") + print("\n", table) + evaluate.save_table(table, RESULTS_DIR / "sequence_founders_comparison.csv", RESULTS_DIR / "sequence_founders_comparison.md") + evaluate.plot_predicted_vs_actual(curves, RESULTS_DIR / "plots" / "predicted_vs_actual.png") + + print(f"\nAll sequence-founders results written to {RESULTS_DIR}") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/founding_potential/src/__init__.py b/service/scripts/profiling/founding_potential/src/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/service/scripts/profiling/founding_potential/src/career_curves.py b/service/scripts/profiling/founding_potential/src/career_curves.py new file mode 100644 index 00000000..bf3e86d1 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/career_curves.py @@ -0,0 +1,147 @@ +"""Empirical career-trajectory curves for index-date truncation of totals. + +Estimates, from the founders' raw trajectories, the average cumulative-share +curve F(u) = fraction of lifetime output accumulated by career fraction +u = (index_year - first_year) / (last_year + 1 - first_year), per activity type +and career-length stratum, so totals truncate as `total * F(u)`. + +The construction is applied to BOTH classes: founders' exact counts only fit and +validate the curves. Giving founders exact counts and non-founders smoothed ones +would let the residual noise texture separate the classes on its own — the exact +artifact the symmetric redesign removes. See docs/DESIGN_NOTES.md. +""" +import numpy as np +import pandas as pd + +from . import config + +GRID = np.linspace(0.0, 1.0, 101) +MIN_TOTAL_FOR_FIT = 5 # people with fewer records give degenerate share curves +MIN_CAREER_YEARS = 5 +CAREER_LENGTH_BINS = [0, 12, 25, np.inf] # short / medium / long careers +CAREER_LENGTH_LABELS = ["short", "medium", "long"] + + +def load_yearly(insts=None): + from .yearly_counts import YEARLY_DIR + + insts = insts or config.INSTITUTIONS + frames = [] + for inst in insts: + df = pd.read_csv(YEARLY_DIR / f"{inst}_person_year.csv") + df["institution"] = inst + frames.append(df) + return pd.concat(frames, ignore_index=True) + + +def _person_curves(yearly, value_col): + """Per-person (career_fraction, cumulative_share) trajectories.""" + df = yearly[yearly[value_col] > 0][["author_people", "year", value_col]].copy() + g = df.groupby("author_people") + stats = g.agg(first=("year", "min"), last=("year", "max"), total=(value_col, "sum")) + stats["length"] = stats["last"] + 1 - stats["first"] + keep = stats[(stats["total"] >= MIN_TOTAL_FOR_FIT) & (stats["length"] >= MIN_CAREER_YEARS)] + df = df[df["author_people"].isin(keep.index)] + df = df.merge(keep, left_on="author_people", right_index=True) + df = df.sort_values(["author_people", "year"]) + df["cum"] = df.groupby("author_people")[value_col].cumsum() + # share accumulated by the END of that year; career fraction of that year-end + df["u"] = (df["year"] + 1 - df["first"]) / df["length"] + df["share"] = df["cum"] / df["total"] + df["stratum"] = pd.cut(df["length"], CAREER_LENGTH_BINS, labels=CAREER_LENGTH_LABELS) + return df + + +def fit_curves(yearly): + """Mean cumulative-share curve on GRID, per activity type and career-length + stratum. Returns {metric: {stratum: np.array over GRID}}.""" + curves = {} + for metric in ["pubs", "patents", "grants_capped"]: + pc = _person_curves(yearly, metric) + curves[metric] = {} + for stratum in CAREER_LENGTH_LABELS: + sub = pc[pc["stratum"] == stratum] + if len(sub) < 100: # too few trajectories: fall back to all strata pooled + sub = pc + # interpolate each person's step curve onto GRID, then average + per_person = [] + for _, grp in sub.groupby("author_people"): + per_person.append(np.interp(GRID, grp["u"], grp["share"], left=0.0, right=1.0)) + mean_curve = np.mean(per_person, axis=0) + mean_curve = np.clip(np.maximum.accumulate(mean_curve), 0.0, 1.0) + mean_curve[0], mean_curve[-1] = 0.0, 1.0 + curves[metric][stratum] = mean_curve + return curves + + +def curve_fraction(curves, metric, career_length, u): + """F(u) lookup with career-length stratification. Vectorized over u.""" + stratum = pd.cut(pd.Series([career_length]), CAREER_LENGTH_BINS, labels=CAREER_LENGTH_LABELS).iloc[0] + return np.interp(np.clip(u, 0.0, 1.0), GRID, curves[metric][str(stratum)]) + + +def truncate_total(curves, metric, total, first_year, last_year, index_year): + """`total * F(u)` truncation used identically for both classes. + + Index at/before career start -> 0; index beyond last active year -> total. + """ + if pd.isna(total) or total <= 0 or pd.isna(first_year) or pd.isna(last_year): + return 0.0 + length = last_year + 1 - first_year + if length <= 0: + return 0.0 + u = (index_year - first_year) / length + return float(total) * float(curve_fraction(curves, metric, length, u)) + + +def validate_on_founders(yearly, curves, index_years): + """Exact vs curve-predicted pre-index counts, on founders' raw trajectories. + + `index_years`: Series of index year per author_people (their founding year). + Returns a tidy frame with exact, predicted, and naive-uniform predictions, + for error reporting per metric. + """ + rows = [] + for metric in ["pubs", "patents", "grants_capped"]: + df = yearly[yearly[metric] > 0] + g = df.groupby("author_people") + stats = g.agg(first=("year", "min"), last=("year", "max"), total=(metric, "sum")) + stats = stats.join(index_years.rename("index_year"), how="inner") + stats = stats[(stats["total"] >= MIN_TOTAL_FOR_FIT)] + exact = ( + df[df["author_people"].isin(stats.index)] + .merge(stats[["index_year"]], left_on="author_people", right_index=True) + .query("year < index_year") + .groupby("author_people")[metric] + .sum() + ) + for person, s in stats.iterrows(): + length = s["last"] + 1 - s["first"] + u = np.clip((s["index_year"] - s["first"]) / length, 0.0, 1.0) + pred = s["total"] * curve_fraction(curves, metric, length, u) + rows.append({ + "metric": metric, + "author_people": person, + "total": s["total"], + "exact_before": float(exact.get(person, 0.0)), + "curve_pred": float(pred), + "uniform_pred": float(s["total"] * u), + }) + return pd.DataFrame(rows) + + +def save_curves(curves, path): + rows = [] + for metric, strata in curves.items(): + for stratum, arr in strata.items(): + for u, f in zip(GRID, arr): + rows.append({"metric": metric, "stratum": stratum, "u": u, "F": f}) + pd.DataFrame(rows).to_csv(path, index=False) + + +def load_curves(path): + df = pd.read_csv(path) + curves = {} + for (metric, stratum), grp in df.groupby(["metric", "stratum"]): + curves.setdefault(metric, {})[stratum] = grp.sort_values("u")["F"].to_numpy() + return curves diff --git a/service/scripts/profiling/founding_potential/src/config.py b/service/scripts/profiling/founding_potential/src/config.py new file mode 100644 index 00000000..8ba2f026 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/config.py @@ -0,0 +1,135 @@ +"""Shared paths, constants and column allow-lists for the founder-potential experiments. + +Whole column families are excluded from RQ1 because they are computed relative +to a founding event and are identically zero for non-founders — see +docs/DESIGN_NOTES.md, "config.py". +""" +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +EVAL_DIR = ROOT / "evaluation" +EXPERIMENTS_DIR = ROOT / "experiments" +RESULTS_DIR = EXPERIMENTS_DIR / "results" + +COMPLETE_DIR = EVAL_DIR / "datasets_complete" +HALFPROFILE_DIRS = { + 1: EVAL_DIR / "datasets_halfprofiles_offset1", + 2: EVAL_DIR / "datasets_halfprofiles_offset2", + 3: EVAL_DIR / "datasets_halfprofiles_offset3", +} +VALIDATION_HALFPROFILE_DIRS = { + 3: EVAL_DIR / "datasets_halfprofiles_validation_offset3", + 5: EVAL_DIR / "datasets_halfprofiles_validation_offset5", +} + +INSTITUTIONS = [ + "berkeley", + "harvard", + "muenchen", + "oxford", + "stanford", + "telaviv", + "toronto", + "ude", +] + +RANDOM_STATE = 42 +LABEL_COLUMN = "Company_founded" + +# Identifier / non-feature columns present in every raw file. +ID_COLUMNS = ["name", "company", "company_details", "founded_on"] + +# Degenerate/leaky for RQ1: all zero for non-founders. +_HIST_LEAK_COLUMNS = [ + f"hist_{kind}_FN{sign}{k}" + for kind in ("pub", "pat", "grant") + for sign in ("+", "-") + for k in range(1, 21) +] + [f"hist_{kind}_FN" for kind in ("pub", "pat", "grant")] + +_BEFORE_AFTER_LEAK_COLUMNS = [ + f"{metric}_{when}_founding" + for metric in ("publications", "patents", "grants", "activities") + for when in ("before", "after") +] + +RQ1_DROP_COLUMNS = ( + ID_COLUMNS + [LABEL_COLUMN] + _HIST_LEAK_COLUMNS + _BEFORE_AFTER_LEAK_COLUMNS +) + +RQ1_CATEGORICAL_COLUMNS = [ + "publication_research_area", + "patent_research_area", + "grant_research_area", + "institution", +] + +# Everything else numeric in datasets_complete that is NOT dropped/categorical. +RQ1_NUMERIC_COLUMNS = [ + "h-index", + "i10-index", + "publications", + "pub_citation_mean", + "pub_citation_sum", + "first_publication_year", + "last_publication_year", + "linked_patents_to_publications", + "patents", + "pat_citation_mean", + "pat_citation_sum", + "first_patent_year", + "last_patent_year", + "grants", + "first_grant_year", + "last_grant_year", + "affiliations", + "activities_total", + "g-index", + "industry_collab_papers", + "grant_research_impact", + "grant_innovation_impact", +] + +# Skewed count-like columns worth a log1p transform. +RQ1_LOG_COLUMNS = [ + "publications", + "pub_citation_sum", + "patents", + "pat_citation_sum", + "grants", + "affiliations", + "activities_total", + "linked_patents_to_publications", +] + +# Curated feature set already used for the half-profile (RQ2) datasets. +RQ2_NUMERIC_COLUMNS = [ + "pub_citation_mean", + "publications", + "h-index", + "i10-index", + "g-index", + "industry_collab_papers", + "linked_patents_to_publications", + "patents", + "pat_citation_mean", + "grants", + "grant_research_impact", + "grant_innovation_impact", + "affiliations", +] +RQ2_CATEGORICAL_COLUMNS = ["institution"] +RQ2_LOG_COLUMNS = ["publications", "patents", "grants", "affiliations"] + +RQ2_TRAIN_OFFSETS = [1, 2, 3] +RQ2_VALIDATION_OFFSETS = [3, 5] +RQ2_NONFOUNDER_TRAIN_FRACTION = 0.7 # rest reserved for horizon-validation, see data.py + +# Founders' lifetime totals include post-founding activity (reverse-causation +# confound); for these 4 metrics a validated `_before_founding` split exists. +RQ1_PREFOUNDING_PAIRS = { + "publications": "publications_before_founding", + "patents": "patents_before_founding", + "grants": "grants_before_founding", + "activities_total": "activities_before_founding", +} diff --git a/service/scripts/profiling/founding_potential/src/data.py b/service/scripts/profiling/founding_potential/src/data.py new file mode 100644 index 00000000..6e56fc7d --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/data.py @@ -0,0 +1,177 @@ +"""Leakage-safe loading of the founder / non-founder datasets for RQ1 and RQ2. + +RQ1 reads `evaluation/datasets_complete` minus identifier and leaky columns; +RQ2 pairs the curated half-profile datasets with non-founders split 70/30 per +institution once, so no individual appears in both training and +horizon-generalization testing. Rationale: docs/DESIGN_NOTES.md, "data.py". +""" +from functools import lru_cache + +import numpy as np +import pandas as pd +from sklearn.model_selection import train_test_split + +from . import config, outliers + + +def _read_csv(path, usecols=None): + return pd.read_csv(path, usecols=usecols) + + +def _broad_research_area(series): + """Collapse the ~100+ specific Dimensions research-area codes (e.g. '3205 + Medical Biochemistry and Metabolomics') down to their ~25 broad parent + categories (e.g. '32') so one-hot encoding doesn't explode into hundreds of + sparse, mostly-empty columns.""" + return series.fillna("n.a.").astype(str).str.strip().str.slice(0, 2) + + +def _apply_prefounding_equivalent(df): + """Make lifetime-total columns comparable across classes (see config.RQ1_PREFOUNDING_PAIRS). + + For founders, replace each lifetime total with its validated `_before_founding` + split (falling back to the lifetime total when that split is missing, e.g. due + to an unparseable `founded_on` date). Non-founders are left untouched: with no + founding event, their full lifetime total is already "pre-founding". + """ + df = df.copy() + is_founder = df[config.LABEL_COLUMN] == 1 + for total_col, before_col in config.RQ1_PREFOUNDING_PAIRS.items(): + corrected = df[total_col].copy() + before = pd.to_numeric(df[before_col], errors="coerce") + use_before = is_founder & before.notna() + corrected.loc[use_before] = before.loc[use_before] + df[total_col] = corrected + return df + + +# --------------------------------------------------------------------------- +# RQ1: full-profile founder vs. non-founder +# --------------------------------------------------------------------------- + +def load_rq1_raw(drop_outliers=True, apply_prefounding_fix=True): + """Concatenate founders + non-founders across all institutions, tagged with + an `institution` column and the `Company_founded` label. + + Applies the pre-founding-equivalent correction (see + `_apply_prefounding_equivalent`) and, by default, drops rows flagged as + multivariate outliers by `outliers.flag_outliers` (Isolation Forest in + log-space -- see `src/outliers.py` for why this replaced a hard `< 1000` cutoff). + `apply_prefounding_fix=False` is only for the before/after ablation comparison + in `run_rq1_robustness.py`; leave it True otherwise. + """ + frames = [] + for inst in config.INSTITUTIONS: + founders = _read_csv(config.COMPLETE_DIR / f"{inst}_features_dataset.csv") + nonfounders = _read_csv(config.COMPLETE_DIR / f"{inst}_nonfounders_features_dataset.csv") + founders["institution"] = inst + nonfounders["institution"] = inst + frames.append(founders) + frames.append(nonfounders) + df = pd.concat(frames, ignore_index=True) + if apply_prefounding_fix: + df = _apply_prefounding_equivalent(df) + if drop_outliers: + df = df[~outliers.flag_outliers(df)] + return df.reset_index(drop=True) + + +def build_rq1_matrix(df, include_institution=True): + """Turn the raw RQ1 dataframe into a model-ready (X, y) pair. + + `include_institution=False` drops the institution one-hot columns, used for + the leave-one-institution-out generalization test so the model cannot key + off an institution indicator it never saw during that fold. + """ + y = df[config.LABEL_COLUMN].astype(int) + + numeric = df[config.RQ1_NUMERIC_COLUMNS].apply(pd.to_numeric, errors="coerce").fillna(0) + for col in config.RQ1_LOG_COLUMNS: + numeric[col] = np.log1p(numeric[col].clip(lower=0)) + + research_area_cols = ["publication_research_area", "patent_research_area", "grant_research_area"] + cat_df = pd.DataFrame({col: _broad_research_area(df[col]) for col in research_area_cols}) + if include_institution: + cat_df["institution"] = df["institution"] + categorical = pd.get_dummies(cat_df, prefix=cat_df.columns.tolist()) + + X = pd.concat([numeric, categorical], axis=1) + groups = df["institution"] + return X, y, groups + + +# --------------------------------------------------------------------------- +# RQ2: founds-within-N-years (half-profile / multi-horizon) +# --------------------------------------------------------------------------- + +_RQ2_USECOLS = ["name", config.LABEL_COLUMN] + config.RQ2_NUMERIC_COLUMNS + + +@lru_cache(maxsize=None) +def _nonfounder_pool_split(institution): + """Deterministic 70/30 split of an institution's non-founders into a + training pool (offsets 1-3) and a horizon-validation holdout (offsets 3/5).""" + df = _read_csv(config.COMPLETE_DIR / f"{institution}_nonfounders_features_dataset.csv", usecols=_RQ2_USECOLS) + train_pool, holdout_pool = train_test_split( + df, train_size=config.RQ2_NONFOUNDER_TRAIN_FRACTION, random_state=config.RANDOM_STATE + ) + return train_pool.reset_index(drop=True), holdout_pool.reset_index(drop=True) + + +def load_rq2_train_dataset(offset): + """Founders truncated at `offset` years pre-founding + the non-founder training pool.""" + assert offset in config.RQ2_TRAIN_OFFSETS + frames = [] + for inst in config.INSTITUTIONS: + founders = _read_csv(config.HALFPROFILE_DIRS[offset] / f"{inst}_features_dataset.csv") + founders = founders[["name", config.LABEL_COLUMN] + config.RQ2_NUMERIC_COLUMNS] + founders["institution"] = inst + nonfounders, _ = _nonfounder_pool_split(inst) + nonfounders = nonfounders.copy() + nonfounders["institution"] = inst + frames.append(founders) + frames.append(nonfounders) + df = pd.concat(frames, ignore_index=True) + df["offset"] = offset + return df.reset_index(drop=True) + + +def load_rq2_validation_dataset(offset): + """Held-out horizon-generalization set: unseen founders truncated at `offset` + years pre-founding + the reserved (never-trained-on) non-founder holdout pool.""" + assert offset in config.RQ2_VALIDATION_OFFSETS + frames = [] + for inst in config.INSTITUTIONS: + founders = _read_csv(config.VALIDATION_HALFPROFILE_DIRS[offset] / f"{inst}_features_dataset.csv") + founders = founders[["name", config.LABEL_COLUMN] + config.RQ2_NUMERIC_COLUMNS] + founders["institution"] = inst + _, holdout = _nonfounder_pool_split(inst) + holdout = holdout.copy() + holdout["institution"] = inst + frames.append(founders) + frames.append(holdout) + df = pd.concat(frames, ignore_index=True) + df["offset"] = offset + return df.reset_index(drop=True) + + +def build_rq2_matrix(df, include_offset=False): + y = df[config.LABEL_COLUMN].astype(int) + + numeric = df[config.RQ2_NUMERIC_COLUMNS].apply(pd.to_numeric, errors="coerce").fillna(0) + for col in config.RQ2_LOG_COLUMNS: + numeric[col] = np.log1p(numeric[col].clip(lower=0)) + if include_offset and "offset" in df.columns: + numeric["offset"] = df["offset"] + + institution = pd.Categorical(df["institution"], categories=config.INSTITUTIONS) + categorical = pd.get_dummies(institution, prefix="institution") + + X = pd.concat([numeric.reset_index(drop=True), categorical.reset_index(drop=True)], axis=1) + groups = df["institution"].reset_index(drop=True) + return X, y, groups + + +def load_survival_raw(): + """Raw RQ1 dataframe, reused by src/survival.py to build durations/events.""" + return load_rq1_raw() diff --git a/service/scripts/profiling/founding_potential/src/evaluate.py b/service/scripts/profiling/founding_potential/src/evaluate.py new file mode 100644 index 00000000..1c0d6f4a --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/evaluate.py @@ -0,0 +1,245 @@ +"""Metrics, plots and statistical model-comparison utilities.""" +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import numpy as np +import pandas as pd +from sklearn.calibration import calibration_curve +from sklearn.metrics import ( + accuracy_score, + average_precision_score, + brier_score_loss, + confusion_matrix, + f1_score, + matthews_corrcoef, + mean_absolute_error, + precision_recall_curve, + precision_score, + r2_score, + recall_score, + roc_auc_score, + roc_curve, + root_mean_squared_error, +) +from sklearn.model_selection import StratifiedKFold +from statsmodels.stats.contingency_tables import mcnemar + + +def compute_metrics(y_true, y_pred, y_proba): + return { + "accuracy": accuracy_score(y_true, y_pred), + "precision": precision_score(y_true, y_pred, zero_division=0), + "recall": recall_score(y_true, y_pred, zero_division=0), + "f1": f1_score(y_true, y_pred, zero_division=0), + "roc_auc": roc_auc_score(y_true, y_proba), + "pr_auc": average_precision_score(y_true, y_proba), + "mcc": matthews_corrcoef(y_true, y_pred), + "brier": brier_score_loss(y_true, y_proba), + } + + +def fit_and_evaluate(model, X_train, y_train, X_test, y_test, max_train_size=None, random_state=42): + if max_train_size is not None and len(X_train) > max_train_size: + rng = np.random.RandomState(random_state) + idx = rng.choice(len(X_train), size=max_train_size, replace=False) + X_train = X_train.iloc[idx] if hasattr(X_train, "iloc") else X_train[idx] + y_train = y_train.iloc[idx] if hasattr(y_train, "iloc") else y_train[idx] + + model.fit(X_train, y_train) + proba = model.predict_proba(X_test)[:, 1] + pred = (proba >= 0.5).astype(int) + metrics = compute_metrics(y_test, pred, proba) + return model, metrics, pred, proba + + +def results_table(rows, sort_by="pr_auc"): + """`rows`: list of dicts, each with a 'model' key plus metric keys.""" + df = pd.DataFrame(rows).set_index("model") + return df.sort_values(sort_by, ascending=False) + + +def save_table(df, csv_path, md_path=None): + csv_path.parent.mkdir(parents=True, exist_ok=True) + df.to_csv(csv_path) + if md_path is not None: + md_path.write_text(df.to_markdown()) + + +def plot_confusion(y_true, y_pred, title, save_path): + cm = confusion_matrix(y_true, y_pred) + fig, ax = plt.subplots(figsize=(4, 4)) + ax.imshow(cm, cmap="Blues") + for (i, j), v in np.ndenumerate(cm): + ax.text(j, i, str(v), ha="center", va="center") + ax.set_xticks([0, 1]) + ax.set_xticklabels(["non-founder", "founder"]) + ax.set_yticks([0, 1]) + ax.set_yticklabels(["non-founder", "founder"]) + ax.set_xlabel("Predicted") + ax.set_ylabel("Actual") + ax.set_title(title) + save_path.parent.mkdir(parents=True, exist_ok=True) + fig.tight_layout() + fig.savefig(save_path, dpi=150) + plt.close(fig) + + +def plot_roc_pr(curves, save_path_prefix): + """`curves`: dict[model_name] -> (y_true, y_proba).""" + save_path_prefix.parent.mkdir(parents=True, exist_ok=True) + + fig, ax = plt.subplots(figsize=(5, 5)) + for name, (y_true, y_proba) in curves.items(): + fpr, tpr, _ = roc_curve(y_true, y_proba) + ax.plot(fpr, tpr, label=f"{name} (AUC={roc_auc_score(y_true, y_proba):.3f})") + ax.plot([0, 1], [0, 1], "--", color="grey") + ax.set_xlabel("False positive rate") + ax.set_ylabel("True positive rate") + ax.set_title("ROC curves") + ax.legend(fontsize=8) + fig.tight_layout() + fig.savefig(f"{save_path_prefix}_roc.png", dpi=150) + plt.close(fig) + + fig, ax = plt.subplots(figsize=(5, 5)) + for name, (y_true, y_proba) in curves.items(): + precision, recall, _ = precision_recall_curve(y_true, y_proba) + ax.plot(recall, precision, label=f"{name} (AP={average_precision_score(y_true, y_proba):.3f})") + ax.set_xlabel("Recall") + ax.set_ylabel("Precision") + ax.set_title("Precision-Recall curves") + ax.legend(fontsize=8) + fig.tight_layout() + fig.savefig(f"{save_path_prefix}_pr.png", dpi=150) + plt.close(fig) + + +def mcnemar_test(y_true, pred_a, pred_b): + y_true, pred_a, pred_b = np.asarray(y_true), np.asarray(pred_a), np.asarray(pred_b) + a_correct = pred_a == y_true + b_correct = pred_b == y_true + table = [ + [np.sum(a_correct & b_correct), np.sum(a_correct & ~b_correct)], + [np.sum(~a_correct & b_correct), np.sum(~a_correct & ~b_correct)], + ] + result = mcnemar(table, exact=False, correction=True) + return {"statistic": float(result.statistic), "p_value": float(result.pvalue)} + + +def cross_validate_model(model_factory, X, y, cv=5, random_state=42): + """K-fold stratified CV, refitting a fresh model each fold via `model_factory()` + (a zero-arg callable returning an unfitted estimator). Returns a DataFrame with + one row per fold plus a final 'mean' row and a 95% CI (normal approximation + across fold scores) for each metric.""" + skf = StratifiedKFold(n_splits=cv, shuffle=True, random_state=random_state) + X_arr = X.reset_index(drop=True) if hasattr(X, "reset_index") else X + y_arr = y.reset_index(drop=True) if hasattr(y, "reset_index") else y + + fold_rows = [] + for fold, (train_idx, test_idx) in enumerate(skf.split(X_arr, y_arr)): + model = model_factory() + model.fit(X_arr.iloc[train_idx], y_arr.iloc[train_idx]) + proba = model.predict_proba(X_arr.iloc[test_idx])[:, 1] + pred = (proba >= 0.5).astype(int) + metrics = compute_metrics(y_arr.iloc[test_idx], pred, proba) + fold_rows.append({"fold": fold, **metrics}) + + fold_df = pd.DataFrame(fold_rows).set_index("fold") + n = len(fold_df) + mean = fold_df.mean() + std = fold_df.std(ddof=1) + ci95 = 1.96 * std / np.sqrt(n) + summary = pd.DataFrame({"mean": mean, "std": std, "ci95_low": mean - ci95, "ci95_high": mean + ci95}) + return fold_df, summary + + +def bootstrap_metric_ci(y_true, y_proba, n_boot=1000, random_state=42, threshold=0.5): + """Percentile bootstrap CI (2.5/97.5%) for roc_auc/pr_auc/mcc/f1, resampling + the held-out test set with replacement `n_boot` times.""" + y_true = np.asarray(y_true) + y_proba = np.asarray(y_proba) + rng = np.random.RandomState(random_state) + n = len(y_true) + boot_rows = [] + for _ in range(n_boot): + idx = rng.randint(0, n, size=n) + yt, yp = y_true[idx], y_proba[idx] + if yt.sum() == 0 or yt.sum() == n: + continue # a resample with only one class breaks roc_auc/pr_auc + pred = (yp >= threshold).astype(int) + boot_rows.append(compute_metrics(yt, pred, yp)) + + boot_df = pd.DataFrame(boot_rows) + point = pd.Series(compute_metrics(y_true, (y_proba >= threshold).astype(int), y_proba)) + summary = pd.DataFrame( + { + "point_estimate": point, + "ci95_low": boot_df.quantile(0.025), + "ci95_high": boot_df.quantile(0.975), + } + ) + return summary + + +def stratified_metrics(y_true, y_pred, y_proba, group): + """Break down `compute_metrics` by the values of `group`. All four arguments + must be positionally aligned (same row order) -- pandas Index labels are + ignored on purpose since y_pred/y_proba are typically plain numpy arrays + with no meaningful index of their own.""" + y_true = np.asarray(y_true) + y_pred = np.asarray(y_pred) + y_proba = np.asarray(y_proba) + group = np.asarray(group) + + rows = [] + for value in pd.unique(group): + mask = group == value + yt, yp, ypr = y_true[mask], y_pred[mask], y_proba[mask] + if len(np.unique(yt)) < 2: + continue # AUC undefined with a single class present + rows.append({"group": value, "n": int(mask.sum()), "founder_rate": float(yt.mean()), **compute_metrics(yt, yp, ypr)}) + return pd.DataFrame(rows).set_index("group").sort_values("n", ascending=False) + + +def regression_metrics(y_true, y_pred): + return { + "mae": mean_absolute_error(y_true, y_pred), + "rmse": root_mean_squared_error(y_true, y_pred), + "r2": r2_score(y_true, y_pred), + } + + +def plot_predicted_vs_actual(curves, save_path): + """`curves`: dict[model_name] -> (y_true, y_pred), one scatter subplot each.""" + save_path.parent.mkdir(parents=True, exist_ok=True) + n = len(curves) + fig, axes = plt.subplots(1, n, figsize=(4 * n, 4), sharex=True, sharey=True) + axes = np.atleast_1d(axes) + for ax, (name, (y_true, y_pred)) in zip(axes, curves.items()): + ax.scatter(y_true, y_pred, alpha=0.3, s=10) + lims = [min(np.min(y_true), np.min(y_pred)), max(np.max(y_true), np.max(y_pred))] + ax.plot(lims, lims, "--", color="grey") + ax.set_xlabel("Actual founding_age") + ax.set_ylabel("Predicted founding_age") + ax.set_title(name) + fig.tight_layout() + fig.savefig(save_path, dpi=150) + plt.close(fig) + + +def plot_calibration(curves, save_path, n_bins=10): + """`curves`: dict[model_name] -> (y_true, y_proba). Reliability diagram.""" + save_path.parent.mkdir(parents=True, exist_ok=True) + fig, ax = plt.subplots(figsize=(5, 5)) + ax.plot([0, 1], [0, 1], "--", color="grey", label="perfectly calibrated") + for name, (y_true, y_proba) in curves.items(): + frac_pos, mean_pred = calibration_curve(y_true, y_proba, n_bins=n_bins, strategy="quantile") + ax.plot(mean_pred, frac_pos, marker="o", label=name) + ax.set_xlabel("Mean predicted probability") + ax.set_ylabel("Fraction of positives") + ax.set_title("Calibration (reliability diagram)") + ax.legend(fontsize=8) + fig.tight_layout() + fig.savefig(save_path, dpi=150) + plt.close(fig) diff --git a/service/scripts/profiling/founding_potential/src/explain.py b/service/scripts/profiling/founding_potential/src/explain.py new file mode 100644 index 00000000..137d5df2 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/explain.py @@ -0,0 +1,43 @@ +"""Permutation importance and SHAP explainability for the best-performing model.""" +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import pandas as pd +import shap +from sklearn.inspection import permutation_importance + + +def permutation_importance_report(model, X_test, y_test, save_csv, save_plot, n_repeats=20, random_state=42): + result = permutation_importance( + model, X_test, y_test, n_repeats=n_repeats, random_state=random_state, scoring="average_precision", n_jobs=-1 + ) + df = pd.DataFrame( + { + "feature": X_test.columns, + "importance_mean": result.importances_mean, + "importance_std": result.importances_std, + } + ).sort_values("importance_mean", ascending=False) + + save_csv.parent.mkdir(parents=True, exist_ok=True) + df.to_csv(save_csv, index=False) + + top = df.head(20).iloc[::-1] + fig, ax = plt.subplots(figsize=(6, 8)) + ax.barh(top["feature"], top["importance_mean"], xerr=top["importance_std"]) + ax.set_xlabel("Permutation importance (avg. precision drop)") + fig.tight_layout() + fig.savefig(save_plot, dpi=150) + plt.close(fig) + return df + + +def shap_summary(model, X_sample, save_plot, max_display=20): + explainer = shap.TreeExplainer(model) + shap_values = explainer.shap_values(X_sample) + fig = plt.figure() + shap.summary_plot(shap_values, X_sample, max_display=max_display, show=False) + save_plot.parent.mkdir(parents=True, exist_ok=True) + fig.savefig(save_plot, dpi=150, bbox_inches="tight") + plt.close(fig) diff --git a/service/scripts/profiling/founding_potential/src/models.py b/service/scripts/profiling/founding_potential/src/models.py new file mode 100644 index 00000000..55dedc57 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/models.py @@ -0,0 +1,102 @@ +"""Model registries: primitive baselines and stronger/state-of-the-art models.""" +from catboost import CatBoostClassifier +from lightgbm import LGBMClassifier +from sklearn.dummy import DummyClassifier +from sklearn.ensemble import RandomForestClassifier, StackingClassifier +from sklearn.linear_model import LogisticRegression +from sklearn.naive_bayes import GaussianNB +from sklearn.neighbors import KNeighborsClassifier +from sklearn.pipeline import make_pipeline +from sklearn.preprocessing import StandardScaler +from sklearn.svm import SVC +from sklearn.tree import DecisionTreeClassifier +from xgboost import XGBClassifier + +from . import config + + +def baseline_models(random_state=config.RANDOM_STATE): + """Primitive models used as the accuracy floor. + + The feature matrix mixes raw year values (~2000), log1p-scaled counts and + 0/1 dummies, so the scale-sensitive models (logistic regression, Naive + Bayes, kNN) are wrapped in a `StandardScaler` pipeline -- otherwise a + feature like `first_publication_year` (~2000) would dominate distance/ + gradient computations over e.g. a 0-1 dummy or a log1p count in [0, 8]. + Tree-based models are scale-invariant and stay unscaled. + """ + return { + "dummy_most_frequent": DummyClassifier(strategy="most_frequent"), + "logistic_regression": make_pipeline( + StandardScaler(), + LogisticRegression(max_iter=2000, class_weight="balanced", random_state=random_state), + ), + "gaussian_nb": make_pipeline(StandardScaler(), GaussianNB()), + "knn": make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=15)), + "decision_tree": DecisionTreeClassifier( + max_depth=6, min_samples_leaf=5, class_weight="balanced", random_state=random_state + ), + } + + +def advanced_models(random_state=config.RANDOM_STATE, scale_pos_weight=1.0): + """Stronger / state-of-the-art tabular models.""" + return { + "random_forest": RandomForestClassifier( + n_estimators=400, + max_depth=12, + min_samples_leaf=2, + class_weight="balanced", + random_state=random_state, + n_jobs=-1, + ), + "svm_rbf": make_pipeline( + StandardScaler(), + SVC(kernel="rbf", C=2.0, class_weight="balanced", probability=True, random_state=random_state), + ), + "xgboost": XGBClassifier( + n_estimators=400, + max_depth=5, + learning_rate=0.05, + subsample=0.8, + colsample_bytree=0.8, + objective="binary:logistic", + eval_metric="logloss", + scale_pos_weight=scale_pos_weight, + random_state=random_state, + n_jobs=-1, + ), + "lightgbm": LGBMClassifier( + n_estimators=400, + num_leaves=31, + learning_rate=0.05, + class_weight="balanced", + random_state=random_state, + n_jobs=-1, + verbose=-1, + ), + "catboost": CatBoostClassifier( + iterations=400, + depth=6, + learning_rate=0.05, + auto_class_weights="Balanced", + random_seed=random_state, + verbose=False, + ), + } + + +def stacking_model(random_state=config.RANDOM_STATE, scale_pos_weight=1.0): + """Stacked ensemble of the three tree-based models with a logistic meta-learner.""" + base = advanced_models(random_state=random_state, scale_pos_weight=scale_pos_weight) + estimators = [ + ("random_forest", base["random_forest"]), + ("xgboost", base["xgboost"]), + ("lightgbm", base["lightgbm"]), + ] + return StackingClassifier( + estimators=estimators, + final_estimator=LogisticRegression(max_iter=2000, class_weight="balanced", random_state=random_state), + stack_method="predict_proba", + n_jobs=-1, + ) diff --git a/service/scripts/profiling/founding_potential/src/nn.py b/service/scripts/profiling/founding_potential/src/nn.py new file mode 100644 index 00000000..ff69a1e3 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/nn.py @@ -0,0 +1,106 @@ +"""A minimal sklearn-style PyTorch MLP, used as the deep-learning baseline.""" +import numpy as np +import torch +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import StandardScaler +from torch import nn + +from . import config + + +class _Net(nn.Module): + def __init__(self, n_features, hidden_sizes, dropout): + super().__init__() + layers = [] + prev = n_features + for h in hidden_sizes: + layers += [nn.Linear(prev, h), nn.ReLU(), nn.Dropout(dropout)] + prev = h + layers.append(nn.Linear(prev, 1)) + self.net = nn.Sequential(*layers) + + def forward(self, x): + return self.net(x).squeeze(-1) + + +class TorchMLPClassifier: + """Feed-forward MLP with class-weighted BCE loss and early stopping on a validation split.""" + + def __init__( + self, + hidden_sizes=(128, 64), + dropout=0.3, + lr=1e-3, + max_epochs=300, + batch_size=64, + patience=20, + random_state=config.RANDOM_STATE, + ): + self.hidden_sizes = hidden_sizes + self.dropout = dropout + self.lr = lr + self.max_epochs = max_epochs + self.batch_size = batch_size + self.patience = patience + self.random_state = random_state + + def fit(self, X, y): + torch.manual_seed(self.random_state) + X = np.asarray(X, dtype=np.float32) + y = np.asarray(y, dtype=np.float32) + + self.scaler_ = StandardScaler().fit(X) + X = self.scaler_.transform(X) + + X_tr, X_val, y_tr, y_val = train_test_split( + X, y, test_size=0.15, stratify=y, random_state=self.random_state + ) + X_tr, y_tr = torch.tensor(X_tr), torch.tensor(y_tr) + X_val, y_val = torch.tensor(X_val), torch.tensor(y_val) + + pos_weight = torch.tensor([(y_tr == 0).sum() / max((y_tr == 1).sum().item(), 1)]) + self.model_ = _Net(X.shape[1], self.hidden_sizes, self.dropout) + optimizer = torch.optim.Adam(self.model_.parameters(), lr=self.lr, weight_decay=1e-4) + loss_fn = nn.BCEWithLogitsLoss(pos_weight=pos_weight) + + best_val_loss = float("inf") + best_state = None + epochs_since_improvement = 0 + n = X_tr.shape[0] + + for _ in range(self.max_epochs): + self.model_.train() + perm = torch.randperm(n) + for start in range(0, n, self.batch_size): + idx = perm[start : start + self.batch_size] + optimizer.zero_grad() + loss = loss_fn(self.model_(X_tr[idx]), y_tr[idx]) + loss.backward() + optimizer.step() + + self.model_.eval() + with torch.no_grad(): + val_loss = loss_fn(self.model_(X_val), y_val).item() + if val_loss < best_val_loss - 1e-4: + best_val_loss = val_loss + best_state = {k: v.clone() for k, v in self.model_.state_dict().items()} + epochs_since_improvement = 0 + else: + epochs_since_improvement += 1 + if epochs_since_improvement >= self.patience: + break + + if best_state is not None: + self.model_.load_state_dict(best_state) + return self + + def predict_proba(self, X): + X = np.asarray(X, dtype=np.float32) + X = self.scaler_.transform(X) + self.model_.eval() + with torch.no_grad(): + p1 = torch.sigmoid(self.model_(torch.tensor(X))).numpy() + return np.column_stack([1 - p1, p1]) + + def predict(self, X): + return (self.predict_proba(X)[:, 1] >= 0.5).astype(int) diff --git a/service/scripts/profiling/founding_potential/src/outliers.py b/service/scripts/profiling/founding_potential/src/outliers.py new file mode 100644 index 00000000..fb13bb05 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/outliers.py @@ -0,0 +1,38 @@ +"""Multivariate outlier detection for the RQ1 feature set. + +Two stages: a sanity ceiling (>5,000 lifetime publications or patents) to drop +flagrant name-collision aggregates, then an Isolation Forest in log-space over +the full numeric feature set. Why not a single threshold: +docs/DESIGN_NOTES.md, "outliers.py". +""" +import numpy as np +import pandas as pd +from sklearn.ensemble import IsolationForest + +from . import config + +SANITY_CEILING = 5000 # any one individual having more than this is implausible +OUTLIER_CONTAMINATION = 0.01 # drop the ~1% most anomalous *remaining* rows + +_OUTLIER_COLUMNS = [c for c in config.RQ1_NUMERIC_COLUMNS if "_year" not in c] + + +def flag_outliers(df, contamination=OUTLIER_CONTAMINATION, random_state=config.RANDOM_STATE): + """Return a boolean Series (True = flagged as an outlier), combining the + sanity-ceiling and Isolation Forest stages described in the module docstring.""" + sanity_flagged = ( + pd.to_numeric(df["publications"], errors="coerce").fillna(0) > SANITY_CEILING + ) | (pd.to_numeric(df["patents"], errors="coerce").fillna(0) > SANITY_CEILING) + + remaining = df.loc[~sanity_flagged] + X = remaining[_OUTLIER_COLUMNS].apply(pd.to_numeric, errors="coerce").fillna(0) + X = np.log1p(X.clip(lower=0)) + model = IsolationForest( + n_estimators=300, contamination=contamination, random_state=random_state + ) + labels = model.fit_predict(X) # -1 = outlier, 1 = inlier + iforest_flagged = pd.Series(labels == -1, index=remaining.index) + + flagged = sanity_flagged.copy() + flagged.loc[iforest_flagged.index] = flagged.loc[iforest_flagged.index] | iforest_flagged + return flagged diff --git a/service/scripts/profiling/founding_potential/src/sequence_data.py b/service/scripts/profiling/founding_potential/src/sequence_data.py new file mode 100644 index 00000000..deb1bb79 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/sequence_data.py @@ -0,0 +1,102 @@ +"""Founder-only sequence dataset for career-relative founding-timing prediction. + +Inputs are the `hist_{pub,pat,grant}_FN-1..FN-20` yearly counts; the target is +`founding_age = founded_on - first_publication_year`. Non-founders have no valid +equivalent sequence in the extracted data, and rows with +`founding_age > WINDOW` are excluded as structurally right-censored (the +excluded count is always reported). Both points are explained in +docs/DESIGN_NOTES.md, "sequence_data.py". +""" +import numpy as np +import pandas as pd + +from . import config + +CHANNELS = ["pub", "pat", "grant"] +WINDOW = 20 +MIN_PLAUSIBLE_YEAR = 1950 +MAX_PLAUSIBLE_YEAR = 2024 + + +def _hist_columns(kind): + """Chronological order: FN-20 (earliest) ... FN-1 (year right before founding).""" + return [f"hist_{kind}_FN-{k}" for k in range(WINDOW, 0, -1)] + + +def build_founder_sequence_dataset(min_founding_age=1, max_founding_age=WINDOW, verbose=True): + """Returns (sequences, founding_age, meta). + + sequences: float32 array (n, WINDOW, len(CHANNELS)), log1p-transformed + chronological pre-founding yearly counts. + founding_age: float32 array (n,), the regression target. + meta: DataFrame (name, institution, founding_age) for bookkeeping/inspection. + """ + frames = [] + for inst in config.INSTITUTIONS: + df = pd.read_csv(config.COMPLETE_DIR / f"{inst}_features_dataset.csv") + df["institution"] = inst + frames.append(df) + df = pd.concat(frames, ignore_index=True) + n_total = len(df) + + founded_on = pd.to_numeric(df["founded_on"], errors="coerce") + fpy = pd.to_numeric(df["first_publication_year"], errors="coerce") + plausible_years = founded_on.between(MIN_PLAUSIBLE_YEAR, MAX_PLAUSIBLE_YEAR) & fpy.between( + MIN_PLAUSIBLE_YEAR, MAX_PLAUSIBLE_YEAR + ) + founding_age = founded_on - fpy + in_window = founding_age.between(min_founding_age, max_founding_age) + keep = plausible_years & in_window + + if verbose: + print(f" sequence dataset scoping: {n_total} founders total") + print(f" dropped {int((~plausible_years).sum())} with an implausible founded_on/first_publication_year " + f"(e.g. sentinel 0 from an unparseable founding date)") + print(f" dropped {int((plausible_years & ~in_window).sum())} more outside " + f"[{min_founding_age}, {max_founding_age}] founding_age (mostly founding_age > {max_founding_age}: " + "the 20-year window can't distinguish these from the >=20 case)") + print(f" kept {int(keep.sum())} founders for the sequence task") + + df = df.loc[keep].reset_index(drop=True) + founding_age = founding_age.loc[keep].reset_index(drop=True) + + channel_arrays = [] + for kind in CHANNELS: + cols = _hist_columns(kind) + arr = df[cols].apply(pd.to_numeric, errors="coerce").fillna(0).clip(lower=0).to_numpy(dtype=np.float32) + arr = np.log1p(arr) + channel_arrays.append(arr) + sequences = np.stack(channel_arrays, axis=-1) # (n, WINDOW, 3) + + meta = df[["name", "institution"]].copy() + meta["founding_age"] = founding_age.values + return sequences, founding_age.values.astype(np.float32), meta + + +def naive_first_activity_baseline(sequences): + """Deterministic, non-fitted heuristic: founding_age := WINDOW - (number of + leading all-zero years across all 3 channels). If activity starts at + position `WINDOW - founding_age` (0-indexed) that is exactly `founding_age` + -- this is the "structural" floor the learned models should be compared + against, since counting leading zeros is trivial for a sequence model too.""" + any_activity = sequences.sum(axis=-1) > 0 # (n, WINDOW) bool, any channel nonzero that year + n = sequences.shape[0] + preds = np.full(n, float(WINDOW), dtype=np.float32) + for i in range(n): + nonzero_idx = np.flatnonzero(any_activity[i]) + if len(nonzero_idx) > 0: + preds[i] = WINDOW - nonzero_idx[0] + return preds + + +def aggregate_features(sequences): + """Simple hand-crafted summary stats per sequence (for a non-sequential + fitted baseline): total activity, nonzero-year count, and activity in the + most recent 3 years, per channel.""" + feats = [] + for c in range(sequences.shape[-1]): + chan = sequences[:, :, c] + feats.append(chan.sum(axis=1)) + feats.append((chan > 0).sum(axis=1)) + feats.append(chan[:, -3:].sum(axis=1)) + return np.column_stack(feats) diff --git a/service/scripts/profiling/founding_potential/src/sequence_models.py b/service/scripts/profiling/founding_potential/src/sequence_models.py new file mode 100644 index 00000000..240ccbaf --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/sequence_models.py @@ -0,0 +1,139 @@ +"""Sequence regressors for the founder-only "predict founding_age from +pre-founding activity" task: an LSTM and a small Transformer encoder, both +sklearn-style (fit/predict) like `nn.py`'s `TorchMLPClassifier`. + +Input: float array (n, WINDOW, n_channels) -- see `sequence_data.py`. +Output: continuous `founding_age` prediction. +""" +import numpy as np +import torch +from sklearn.model_selection import train_test_split +from torch import nn + +from . import config + + +class _SequenceScaler: + """Per-channel standardization (mean/std computed over all rows x timesteps).""" + + def fit(self, X): + self.mean_ = X.mean(axis=(0, 1), keepdims=True) + self.std_ = X.std(axis=(0, 1), keepdims=True) + 1e-6 + return self + + def transform(self, X): + return (X - self.mean_) / self.std_ + + +class _LSTMNet(nn.Module): + def __init__(self, n_channels, hidden_size=64, num_layers=1, dropout=0.2): + super().__init__() + self.lstm = nn.LSTM( + input_size=n_channels, hidden_size=hidden_size, num_layers=num_layers, + batch_first=True, dropout=dropout if num_layers > 1 else 0.0, + ) + self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(hidden_size, 1)) + + def forward(self, x): + _, (h_n, _) = self.lstm(x) + return self.head(h_n[-1]).squeeze(-1) + + +class _TransformerNet(nn.Module): + def __init__(self, n_channels, seq_len, d_model=32, n_heads=4, n_layers=2, dropout=0.2): + super().__init__() + self.input_proj = nn.Linear(n_channels, d_model) + self.pos_embedding = nn.Parameter(torch.zeros(1, seq_len, d_model)) + encoder_layer = nn.TransformerEncoderLayer( + d_model=d_model, nhead=n_heads, dim_feedforward=d_model * 4, + dropout=dropout, batch_first=True, + ) + self.encoder = nn.TransformerEncoder(encoder_layer, num_layers=n_layers) + self.head = nn.Sequential(nn.Dropout(dropout), nn.Linear(d_model, 1)) + + def forward(self, x): + h = self.input_proj(x) + self.pos_embedding + h = self.encoder(h) + pooled = h.mean(dim=1) # mean-pool over the time dimension + return self.head(pooled).squeeze(-1) + + +class _BaseSequenceRegressor: + """Shared fit/predict scaffolding (train loop, early stopping, scaling).""" + + net_cls = None + + def __init__(self, lr=1e-3, max_epochs=300, batch_size=64, patience=25, random_state=config.RANDOM_STATE, **net_kwargs): + self.lr = lr + self.max_epochs = max_epochs + self.batch_size = batch_size + self.patience = patience + self.random_state = random_state + self.net_kwargs = net_kwargs + + def _build_net(self, n_channels, seq_len): + raise NotImplementedError + + def fit(self, X, y): + torch.manual_seed(self.random_state) + X = np.asarray(X, dtype=np.float32) + y = np.asarray(y, dtype=np.float32) + + self.scaler_ = _SequenceScaler().fit(X) + X = self.scaler_.transform(X).astype(np.float32) + + X_tr, X_val, y_tr, y_val = train_test_split(X, y, test_size=0.15, random_state=self.random_state) + X_tr, y_tr = torch.tensor(X_tr), torch.tensor(y_tr) + X_val, y_val = torch.tensor(X_val), torch.tensor(y_val) + + self.model_ = self._build_net(n_channels=X.shape[2], seq_len=X.shape[1]) + optimizer = torch.optim.Adam(self.model_.parameters(), lr=self.lr, weight_decay=1e-4) + loss_fn = nn.MSELoss() + + best_val_loss = float("inf") + best_state = None + epochs_since_improvement = 0 + n = X_tr.shape[0] + + for _ in range(self.max_epochs): + self.model_.train() + perm = torch.randperm(n) + for start in range(0, n, self.batch_size): + idx = perm[start : start + self.batch_size] + optimizer.zero_grad() + loss = loss_fn(self.model_(X_tr[idx]), y_tr[idx]) + loss.backward() + optimizer.step() + + self.model_.eval() + with torch.no_grad(): + val_loss = loss_fn(self.model_(X_val), y_val).item() + if val_loss < best_val_loss - 1e-4: + best_val_loss = val_loss + best_state = {k: v.clone() for k, v in self.model_.state_dict().items()} + epochs_since_improvement = 0 + else: + epochs_since_improvement += 1 + if epochs_since_improvement >= self.patience: + break + + if best_state is not None: + self.model_.load_state_dict(best_state) + return self + + def predict(self, X): + X = np.asarray(X, dtype=np.float32) + X = self.scaler_.transform(X).astype(np.float32) + self.model_.eval() + with torch.no_grad(): + return self.model_(torch.tensor(X)).numpy() + + +class LSTMRegressor(_BaseSequenceRegressor): + def _build_net(self, n_channels, seq_len): + return _LSTMNet(n_channels, **self.net_kwargs) + + +class TransformerRegressor(_BaseSequenceRegressor): + def _build_net(self, n_channels, seq_len): + return _TransformerNet(n_channels, seq_len, **self.net_kwargs) diff --git a/service/scripts/profiling/founding_potential/src/splits.py b/service/scripts/profiling/founding_potential/src/splits.py new file mode 100644 index 00000000..00c1726b --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/splits.py @@ -0,0 +1,17 @@ +"""Generic train/test and cross-institution split helpers.""" +from sklearn.model_selection import LeaveOneGroupOut, train_test_split + +from . import config + + +def stratified_holdout(X, y, test_size=0.2, random_state=config.RANDOM_STATE): + return train_test_split(X, y, test_size=test_size, stratify=y, random_state=random_state) + + +def leave_one_institution_out(X, y, groups): + """Yields (institution_name, train_idx, test_idx) for each held-out institution.""" + logo = LeaveOneGroupOut() + group_codes, group_names = groups.factorize() + for train_idx, test_idx in logo.split(X, y, groups=group_codes): + held_out = group_names[group_codes[test_idx[0]]] + yield held_out, train_idx, test_idx diff --git a/service/scripts/profiling/founding_potential/src/survival.py b/service/scripts/profiling/founding_potential/src/survival.py new file mode 100644 index 00000000..2b8f0cc4 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/survival.py @@ -0,0 +1,69 @@ +"""Cox proportional hazards survival analysis for RQ2 (time-to-founding). + +Complements the fixed-horizon classifiers in run_rq2.py: instead of one yes/no +label at a chosen cutoff, this fits a single time-to-event model and reads off +P(founds within k years | features) for any k, correctly treating non-founders +still under observation as censored rather than as permanent negatives. + +Simplification: covariates are the same full-career aggregates used for RQ1 +(observed up to the founding year for founders, up to the last observed year for +non-founders) rather than a fully time-varying design. A stricter version would +use a counting-process (start, stop, event) long format with the half-profile +snapshots as time-varying covariates; noted as future work in the README. +""" +import numpy as np +import pandas as pd +from lifelines import CoxPHFitter +from lifelines.utils import concordance_index + +from . import config + + +def build_survival_frame(df_raw): + df = df_raw.copy() + is_founder = df[config.LABEL_COLUMN] == 1 + + duration = np.where( + is_founder, + df["founded_on"] - df["first_publication_year"], + df["last_publication_year"] - df["first_publication_year"], + ) + event = is_founder.astype(int) + frame = pd.DataFrame({"duration": duration, "event": event}) + + numeric_cols = [c for c in config.RQ1_NUMERIC_COLUMNS if not c.endswith("_year")] + numeric = df[numeric_cols].apply(pd.to_numeric, errors="coerce").fillna(0) + for col in config.RQ1_LOG_COLUMNS: + if col in numeric.columns: + numeric[col] = np.log1p(numeric[col].clip(lower=0)) + + institution = pd.get_dummies(df["institution"], prefix="institution", drop_first=True) + + frame = pd.concat([frame, numeric.reset_index(drop=True), institution.reset_index(drop=True)], axis=1) + frame = frame[frame["duration"] > 0] + frame = frame.replace([np.inf, -np.inf], np.nan).dropna() + return frame.reset_index(drop=True) + + +def fit_coxph(train_frame, penalizer=0.1): + cph = CoxPHFitter(penalizer=penalizer) + cph.fit(train_frame, duration_col="duration", event_col="event") + return cph + + +def evaluate_concordance(cph, test_frame): + partial_hazard = cph.predict_partial_hazard(test_frame) + return concordance_index(test_frame["duration"], -partial_hazard, test_frame["event"]) + + +def probability_of_founding_within(cph, frame, years): + survival = cph.predict_survival_function(frame, times=[years]) + return 1 - survival.loc[years].values + + +def landmark_labels(frame, years): + """Rows with enough follow-up to know the true within-`years` outcome, plus + the corresponding binary label, avoiding immortal-time bias.""" + eligible = ((frame["event"] == 1) & (frame["duration"] <= years)) | (frame["duration"] >= years) + label = ((frame["event"] == 1) & (frame["duration"] <= years)).astype(int) + return eligible, label diff --git a/service/scripts/profiling/founding_potential/src/symmetric.py b/service/scripts/profiling/founding_potential/src/symmetric.py new file mode 100644 index 00000000..2c2cf6e3 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/symmetric.py @@ -0,0 +1,264 @@ +"""Symmetric (landmark-design) founder / non-founder datasets. + +Replaces the asymmetric RQ1/RQ2 preprocessing in `data.py`, where observation +window length was a function of the label. Here every person gets an index year +(real founding year, or a cohort-matched pseudo-founding year), features are +built identically for both classes via `career_curves.py`, citation features are +excluded as non-historicizable, and `grants` is de-inflated through the per-paper +cap from `yearly_counts.py`. + +Two filters apply to BOTH classes: a >=4-publication population rule and a +plausibility filter for name-collision aggregates. Why each of these exists: +docs/DESIGN_NOTES.md, "symmetric.py". +""" +import numpy as np +import pandas as pd + +from . import career_curves as cc +from . import config + +SYMMETRIC_DIR = config.EVAL_DIR / "datasets_symmetric" +CURVES_PATH = config.EVAL_DIR / "yearly_counts" / "career_curves.csv" + +# Minimal academic record at the index date, applied to BOTH classes: without +# it a sampling-frame clash dominates the thin-profile region. +MIN_PUBS_AT_INDEX = 4 + +VALID_FOUNDING = (1950, 2026) +VALID_FIRST_YEAR = (1930, 2025) +MAX_CAREER_AGE_AT_FOUNDING = 60 +COHORT_BIN_YEARS = 10 + +SYMMETRIC_NUMERIC_COLUMNS = [ + "pubs_at_index", + "patents_at_index", + "grants_at_index", + "activities_at_index", + "industry_collab_at_index", + "linked_pat_pub_at_index", + "career_age_at_index", + "first_publication_year", + "pub_rate", + "patent_rate", + "grant_rate", + "has_patents_at_index", + "has_grants_at_index", + "years_since_first_patent", + "years_since_first_grant", +] +SYMMETRIC_LOG_COLUMNS = [ + "pubs_at_index", + "patents_at_index", + "grants_at_index", + "activities_at_index", + "industry_collab_at_index", + "linked_pat_pub_at_index", +] +SYMMETRIC_CATEGORICAL_COLUMNS = [ + "publication_research_area", + "patent_research_area", + "grant_research_area", + "institution", +] + +_RAW_USECOLS = [ + "name", "founded_on", "publications", "patents", "grants", + "first_publication_year", "last_publication_year", + "first_patent_year", "last_patent_year", + "first_grant_year", "last_grant_year", + "industry_collab_papers", "linked_patents_to_publications", + "publication_research_area", "patent_research_area", "grant_research_area", + config.LABEL_COLUMN, +] + + +def load_people(): + """All founders + non-founders with cleaned year fields. Returns the frame + plus a per-step attrition log (how many rows each cleaning rule removed).""" + frames = [] + for inst in config.INSTITUTIONS: + for kind in ["features", "nonfounders_features"]: + df = pd.read_csv(config.COMPLETE_DIR / f"{inst}_{kind}_dataset.csv") + df = df[[c for c in _RAW_USECOLS if c in df.columns]].copy() + df["institution"] = inst + frames.append(df) + df = pd.concat(frames, ignore_index=True) + attrition = {"initial": len(df)} + + for col in ["founded_on", "publications", "patents", "grants", + "industry_collab_papers", "linked_patents_to_publications"]: + df[col] = pd.to_numeric(df.get(col), errors="coerce") + for col in ["first_publication_year", "last_publication_year", "first_patent_year", + "last_patent_year", "first_grant_year", "last_grant_year"]: + y = pd.to_numeric(df.get(col), errors="coerce") + df[col] = y.where((y >= VALID_FIRST_YEAR[0]) & (y <= VALID_FIRST_YEAR[1])) + df["name"] = df["name"].astype(str).str.strip() + + df = df[df["first_publication_year"].notna() & (df["publications"] > 0)] + attrition["no_publication_anchor"] = attrition["initial"] - len(df) + + # Plausibility filter (BOTH classes): a >60-year span or >25 papers/year + # sustained marks a name-collision aggregate, not one researcher. + career = df["last_publication_year"] - df["first_publication_year"] + 1 + rate = df["publications"] / career.clip(lower=1) + implausible = (career > 60) | (rate > 25) + by_class = implausible.groupby(df[config.LABEL_COLUMN]).sum() + attrition["implausible_profile_founders"] = int(by_class.get(1, 0)) + attrition["implausible_profile_nonfounders"] = int(by_class.get(0, 0)) + df = df[~implausible] + + is_founder = df[config.LABEL_COLUMN] == 1 + bad_year = is_founder & ~df["founded_on"].between(*VALID_FOUNDING) + df = df[~bad_year] + attrition["founder_bad_founding_year"] = int(bad_year.sum()) + + ca = df["founded_on"] - df["first_publication_year"] + is_founder = df[config.LABEL_COLUMN] == 1 + bad_ca = is_founder & ~ca.between(1, MAX_CAREER_AGE_AT_FOUNDING) + df = df[~bad_ca] + attrition["founder_bad_career_age"] = int(bad_ca.sum()) + + df = df.drop_duplicates(subset=["name", "institution", config.LABEL_COLUMN]) + attrition["duplicates"] = attrition["initial"] - sum( + v for k, v in attrition.items() if k != "initial" + ) - len(df) + return df.reset_index(drop=True), attrition + + +def assign_index_years(df, random_state=config.RANDOM_STATE): + """Founders: real founding year. Non-founders: career-age-at-founding sampled + from founders in the same career-start cohort (decade of first publication), + clipped to the person's observed active span.""" + df = df.copy() + is_founder = df[config.LABEL_COLUMN] == 1 + df.loc[is_founder, "index_year"] = df.loc[is_founder, "founded_on"] + + founders = df[is_founder] + founder_ca = (founders["founded_on"] - founders["first_publication_year"]).astype(float) + cohort = (founders["first_publication_year"] // COHORT_BIN_YEARS) * COHORT_BIN_YEARS + ca_by_cohort = {c: founder_ca[cohort == c].to_numpy() for c in cohort.unique()} + all_ca = founder_ca.to_numpy() + + rng = np.random.default_rng(random_state) + nonf = df[~is_founder] + sampled = [] + for first, last in zip(nonf["first_publication_year"], nonf["last_publication_year"]): + c = (first // COHORT_BIN_YEARS) * COHORT_BIN_YEARS + pool = ca_by_cohort.get(c) + if pool is None or len(pool) < 20: + pool = all_ca + ca = float(rng.choice(pool)) + span = (last - first) if pd.notna(last) else ca + sampled.append(first + min(max(ca, 1.0), max(span, 1.0))) + df.loc[~is_founder, "index_year"] = sampled + return df + + +def _fit_grants_cap_ratio(yearly): + """Monotone binned mapping r -> capped_share, where r = grants per publication + and capped_share = grants_capped / grants, fitted on the raw founder records. + Applied identically to both classes (non-founders lack raw records).""" + per_person = yearly.groupby("author_people").agg( + pubs=("pubs", "sum"), grants=("grants", "sum"), capped=("grants_capped", "sum") + ) + per_person = per_person[per_person["grants"] > 0] + r = per_person["grants"] / per_person["pubs"].clip(lower=1) + share = per_person["capped"] / per_person["grants"] + bins = np.quantile(r, np.linspace(0, 1, 21)) + bins = np.unique(bins) + idx = np.clip(np.digitize(r, bins) - 1, 0, len(bins) - 2) + binned = pd.DataFrame({"bin": idx, "share": share}).groupby("bin")["share"].median() + centers = (bins[:-1] + bins[1:]) / 2 + + def apply(grants_total, pubs_total): + rr = np.asarray(grants_total, dtype=float) / np.clip(np.asarray(pubs_total, dtype=float), 1, None) + shares = np.interp(rr, centers[binned.index], binned.to_numpy()) + return np.asarray(grants_total, dtype=float) * np.clip(shares, 0.0, 1.0) + + return apply + + +def build_features(df, curves, grants_cap_fn, offset=0): + """Feature table with every person's profile truncated at (index_year - offset). + Identical construction for both classes -- see module docstring.""" + out = df[["name", "institution", config.LABEL_COLUMN, "index_year", + "publication_research_area", "patent_research_area", "grant_research_area"]].copy() + idx = df["index_year"] - offset + out["index_year_effective"] = idx + + grants_capped_total = grants_cap_fn(df["grants"].fillna(0), df["publications"].fillna(0)) + + def trunc(metric, total, first, last): + return np.array([ + cc.truncate_total(curves, metric, t, f, l, i) + for t, f, l, i in zip(total, first, last, idx) + ]) + + pubs = trunc("pubs", df["publications"], df["first_publication_year"], df["last_publication_year"]) + pats = trunc("patents", df["patents"], df["first_patent_year"], df["last_patent_year"]) + grants = trunc("grants_capped", grants_capped_total, df["first_grant_year"], df["last_grant_year"]) + + pub_frac = np.divide(pubs, df["publications"].to_numpy(dtype=float), + out=np.zeros(len(df)), where=df["publications"].to_numpy(dtype=float) > 0) + pat_frac = np.divide(pats, df["patents"].to_numpy(dtype=float), + out=np.zeros(len(df)), where=df["patents"].to_numpy(dtype=float) > 0) + + out["pubs_at_index"] = pubs + out["patents_at_index"] = pats + out["grants_at_index"] = grants + out["activities_at_index"] = pubs + pats + grants + out["industry_collab_at_index"] = df["industry_collab_papers"].fillna(0).to_numpy() * pub_frac + out["linked_pat_pub_at_index"] = df["linked_patents_to_publications"].fillna(0).to_numpy() * pat_frac + + career_age = (idx - df["first_publication_year"]).clip(lower=1) + out["career_age_at_index"] = career_age + out["first_publication_year"] = df["first_publication_year"] + out["pub_rate"] = pubs / career_age + out["patent_rate"] = pats / career_age + out["grant_rate"] = grants / career_age + out["has_patents_at_index"] = ((df["first_patent_year"].notna()) & (df["first_patent_year"] <= idx)).astype(int) + out["has_grants_at_index"] = ((df["first_grant_year"].notna()) & (df["first_grant_year"] <= idx)).astype(int) + out["years_since_first_patent"] = np.where( + out["has_patents_at_index"] == 1, (idx - df["first_patent_year"]).clip(lower=0), 0) + out["years_since_first_grant"] = np.where( + out["has_grants_at_index"] == 1, (idx - df["first_grant_year"]).clip(lower=0), 0) + return out + + +def build_matrix(feat_df, include_institution=True): + """(X, y, groups) from a symmetric feature table, mirroring data.build_rq1_matrix.""" + from .data import _broad_research_area + + y = feat_df[config.LABEL_COLUMN].astype(int) + numeric = feat_df[SYMMETRIC_NUMERIC_COLUMNS].apply(pd.to_numeric, errors="coerce").fillna(0) + for col in SYMMETRIC_LOG_COLUMNS: + numeric[col] = np.log1p(numeric[col].clip(lower=0)) + + cat_cols = ["publication_research_area", "patent_research_area", "grant_research_area"] + cat_df = pd.DataFrame({c: _broad_research_area(feat_df[c]) for c in cat_cols}) + if include_institution: + cat_df["institution"] = feat_df["institution"] + categorical = pd.get_dummies(cat_df, prefix=cat_df.columns.tolist()) + + X = pd.concat([numeric.reset_index(drop=True), categorical.reset_index(drop=True)], axis=1) + return X, y.reset_index(drop=True), feat_df["institution"].reset_index(drop=True) + + +def build_symmetric_dataset(offset=0, random_state=config.RANDOM_STATE, + min_pubs_at_index=MIN_PUBS_AT_INDEX): + """End-to-end: load, clean, assign index years, build features, apply the + population filter (see MIN_PUBS_AT_INDEX). Returns (feature_table, + attrition_dict).""" + people, attrition = load_people() + people = assign_index_years(people, random_state=random_state) + yearly = cc.load_yearly() + curves = cc.load_curves(CURVES_PATH) + grants_cap_fn = _fit_grants_cap_ratio(yearly) + feats = build_features(people, curves, grants_cap_fn, offset=offset) + if min_pubs_at_index: + in_pop = feats["pubs_at_index"] >= min_pubs_at_index + by_class = (~in_pop).groupby(feats[config.LABEL_COLUMN]).sum() + attrition["below_min_pubs_at_index_founders"] = int(by_class.get(1, 0)) + attrition["below_min_pubs_at_index_nonfounders"] = int(by_class.get(0, 0)) + feats = feats[in_pop].reset_index(drop=True) + return feats, attrition diff --git a/service/scripts/profiling/founding_potential/src/tuning.py b/service/scripts/profiling/founding_potential/src/tuning.py new file mode 100644 index 00000000..d1ffeedd --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/tuning.py @@ -0,0 +1,68 @@ +"""Hyperparameter search spaces + a thin RandomizedSearchCV wrapper for the top +tree-based models. Kept separate from `models.py` so the default (untuned) +model factories used for the main comparison stay simple and fast.""" +import pandas as pd +from scipy.stats import randint, uniform +from sklearn.ensemble import RandomForestClassifier +from sklearn.model_selection import RandomizedSearchCV +from xgboost import XGBClassifier +from lightgbm import LGBMClassifier + +from . import config + +PARAM_DISTRIBUTIONS = { + "random_forest": { + "n_estimators": randint(200, 800), + "max_depth": randint(4, 20), + "min_samples_leaf": randint(1, 10), + "max_features": uniform(0.3, 0.7), + }, + "xgboost": { + "n_estimators": randint(150, 700), + "max_depth": randint(3, 9), + "learning_rate": uniform(0.01, 0.19), + "subsample": uniform(0.6, 0.4), + "colsample_bytree": uniform(0.5, 0.5), + "min_child_weight": randint(1, 10), + }, + "lightgbm": { + "n_estimators": randint(150, 700), + "num_leaves": randint(15, 127), + "learning_rate": uniform(0.01, 0.19), + "subsample": uniform(0.6, 0.4), + "colsample_bytree": uniform(0.5, 0.5), + "min_child_samples": randint(5, 60), + }, +} + + +def _base_estimator(name, random_state, scale_pos_weight): + if name == "random_forest": + return RandomForestClassifier(class_weight="balanced", random_state=random_state, n_jobs=1) + if name == "xgboost": + return XGBClassifier( + objective="binary:logistic", eval_metric="logloss", + scale_pos_weight=scale_pos_weight, random_state=random_state, n_jobs=1, + ) + if name == "lightgbm": + return LGBMClassifier(class_weight="balanced", random_state=random_state, n_jobs=1, verbose=-1) + raise ValueError(f"No tuning search space registered for '{name}'") + + +def tune_model(name, X_train, y_train, n_iter=20, cv=3, scoring="average_precision", + random_state=config.RANDOM_STATE, scale_pos_weight=1.0): + """Randomized hyperparameter search for `name` in {random_forest, xgboost, lightgbm}. + Returns (best_estimator, best_params, cv_results_dataframe).""" + estimator = _base_estimator(name, random_state, scale_pos_weight) + search = RandomizedSearchCV( + estimator, + PARAM_DISTRIBUTIONS[name], + n_iter=n_iter, + cv=cv, + scoring=scoring, + random_state=random_state, + n_jobs=-1, + refit=True, + ) + search.fit(X_train, y_train) + return search.best_estimator_, search.best_params_, pd.DataFrame(search.cv_results_) diff --git a/service/scripts/profiling/founding_potential/src/yearly_counts.py b/service/scripts/profiling/founding_potential/src/yearly_counts.py new file mode 100644 index 00000000..ba717446 --- /dev/null +++ b/service/scripts/profiling/founding_potential/src/yearly_counts.py @@ -0,0 +1,113 @@ +"""Per-person, per-year activity counts rebuilt from the raw Dimensions exports. + +Founder cohort only — non-founders were extracted live and their per-record data +was never saved. Used to truncate founder features exactly at the founding year +and to fit the career curves in `career_curves.py`. Also emits a grants variant +capped at GRANTS_PER_PAPER_CAP distinct grant ids per publication, since a single +consortium paper can otherwise contribute 100+ "grants". +Details: docs/DESIGN_NOTES.md, "yearly_counts.py". +""" +import ast +import sys +from pathlib import Path + +import pandas as pd + +from . import config + +YEARLY_DIR = config.EVAL_DIR / "yearly_counts" +# Distinct grant IDs credited per publication, at most. Sits above ordinary +# multi-grant papers (p90 ~6-14) and below the consortium tail (up to 409). +GRANTS_PER_PAPER_CAP = 10 + +VALID_YEARS = (1900, 2026) + + +def _clean_year(series): + y = pd.to_numeric(series, errors="coerce") + return y.where((y >= VALID_YEARS[0]) & (y <= VALID_YEARS[1])) + + +def _person_year_counts(path, id_col, kind, chunksize=200_000): + """Distinct-record counts per (person, year) from one raw CSV.""" + frames = [] + usecols = [id_col, "year", "author_people"] + for chunk in pd.read_csv(path, usecols=usecols, chunksize=chunksize, low_memory=False): + chunk["year"] = _clean_year(chunk["year"]) + chunk = chunk.dropna(subset=["year", "author_people", id_col]) + chunk = chunk.drop_duplicates(subset=["author_people", id_col]) + frames.append(chunk) + df = pd.concat(frames, ignore_index=True) + df = df.drop_duplicates(subset=["author_people", id_col]) + out = ( + df.groupby(["author_people", "year"])[id_col] + .nunique() + .rename(kind) + .reset_index() + ) + return out + + +def _grant_year_counts(path, chunksize=200_000): + """Grant credit per (person, year): distinct grant IDs acknowledged on that + year's linked publications, both raw and capped per publication.""" + rows = [] + usecols = ["doi", "supporting_grant_ids", "year", "author_people"] + for chunk in pd.read_csv(path, usecols=usecols, chunksize=chunksize, low_memory=False): + chunk["year"] = _clean_year(chunk["year"]) + chunk = chunk.dropna(subset=["year", "author_people", "supporting_grant_ids"]) + for person, year, doi, raw in zip( + chunk["author_people"], chunk["year"], chunk["doi"], chunk["supporting_grant_ids"] + ): + try: + ids = ast.literal_eval(raw) + except (ValueError, SyntaxError): + continue + if isinstance(ids, list) and ids: + rows.append((person, year, doi, tuple(ids))) + if not rows: + return pd.DataFrame(columns=["author_people", "year", "grants", "grants_capped"]) + df = pd.DataFrame(rows, columns=["author_people", "year", "doi", "grant_ids"]) + df = df.drop_duplicates(subset=["author_people", "doi"]) + + def _agg(group): + seen, seen_capped = set(), set() + for ids in group["grant_ids"]: + new = [g for g in ids if g not in seen] + seen.update(new) + seen_capped.update(new[:GRANTS_PER_PAPER_CAP]) + return pd.Series({"grants": len(seen), "grants_capped": len(seen_capped)}) + + return df.groupby(["author_people", "year"]).apply(_agg, include_groups=False).reset_index() + + +def build_institution(inst): + data_dir = config.ROOT / "dimensions_data" + pubs = _person_year_counts(data_dir / f"{inst}_papers.csv", "id", "pubs") + pats = _person_year_counts(data_dir / f"{inst}_patents.csv", "id", "patents") + grants = _grant_year_counts(data_dir / f"{inst}_publications_linked_grants.csv") + + merged = pubs.merge(pats, on=["author_people", "year"], how="outer") + merged = merged.merge(grants, on=["author_people", "year"], how="outer") + merged = merged.fillna(0) + for col in ["pubs", "patents", "grants", "grants_capped"]: + merged[col] = merged[col].astype(int) + merged["year"] = merged["year"].astype(int) + return merged.sort_values(["author_people", "year"]).reset_index(drop=True) + + +def main(): + YEARLY_DIR.mkdir(exist_ok=True) + insts = sys.argv[1:] or config.INSTITUTIONS + for inst in insts: + out_path = YEARLY_DIR / f"{inst}_person_year.csv" + if out_path.exists(): + print(f"{inst}: exists, skipping", flush=True) + continue + df = build_institution(inst) + df.to_csv(out_path, index=False) + print(f"{inst}: {df['author_people'].nunique()} people, {len(df)} person-years", flush=True) + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/multipliers/.gitignore b/service/scripts/profiling/multipliers/.gitignore new file mode 100644 index 00000000..cf7c1dee --- /dev/null +++ b/service/scripts/profiling/multipliers/.gitignore @@ -0,0 +1,5 @@ +# extracted person-level data + generated artifacts — never commit +cache/ +reports/ +*.log +__pycache__/ diff --git a/service/scripts/profiling/multipliers/README.md b/service/scripts/profiling/multipliers/README.md new file mode 100644 index 00000000..98f67d0d --- /dev/null +++ b/service/scripts/profiling/multipliers/README.md @@ -0,0 +1,798 @@ +# Multiplicator detection — offline pipeline + +Detects **multiplicators** among an institution's researchers — *bridgers* (connect +disconnected research communities), *mentors* (bring up junior/debutant co-authors), and +*amplifiers* (patents, industry co-authorship, news visibility) — from OpenAlex plus the +patent/project/news sources, and writes per-author scores + tags + evidence to a derived +Elasticsearch index. + +Each person additionally carries a **founder-potential** block: the output of the four +pre-trained models in [`../founding_potential/production`](../founding_potential/production), +run over the same profile data and stored as flat, explicitly-typed fields so a +backend can answer "which mentors have a founding potential above X within Y years" +in one query. See [Founder-potential enrichment](#founder-potential-enrichment) below. + +Follows the repo's offline pattern (`scripts/patents/index_org_patents.py`): all analysis +and joining happen **offline**, the result lands in a **separate, institution-parameterised +ES index**, and a thin read-only backend router is added only once the UI needs it. + +**New here? Read [ROADMAP.md](docs/ROADMAP.md) first** — a ground-up explanation of the +concept, every index field, the related work behind the metrics, and what's next. + +## Status + +**M0 — spike: done. M1 — metrics core: done** (exit check PASS). **M2 — pipeline + +`multiplicators_v1` index: done** (idempotency verified). **M3 — amplifier signal +joins: wired and indexed** (patents / news / CORDIS; results below) — remaining: +the coach calibration session. **M3b — founder-potential enrichment: wired and +indexed.** **M4 — read router:** pending, once the UI needs it. +All results per milestone are documented in the sections below. + +## Setup + +The pipeline's own dependencies are light, but the founder-potential stage +(`founding.py`) runs the LightGBM/PyTorch models from +[`../founding_potential/production`](../founding_potential/production), so the +simplest setup is the `potential` conda env those models already document, plus +this module's four packages: + +```bash +conda run -n potential pip install -r service/scripts/profiling/multipliers/requirements.txt +``` + +Without the models, a plain venv on `requirements.txt` plus `--no-founding` +works. + +**Every command below runs from the repository root as a module.** The modules +import each other by absolute path (`service.scripts.profiling.multipliers.*`), +so `python build.py` from inside this directory raises `ModuleNotFoundError`. + +Credentials are read from `service/src/main/inse/.env`: +- `ELASTICSEARCH_URL` / `ELASTICSEARCH_API_KEY` — NES cluster (OpenAlex). +- `ELASTICSEARCH_INSE_URL` / `ELASTICSEARCH_INSE_API_KEY` — INSE cluster (patents, news). + +The founder stage also needs the backend FastAPI service reachable at +`founding.api_base_url` (default `http://localhost:8000`) for its patent join. + +## Run the spike + +```bash +# Extract + audit for University of Duisburg-Essen (writes cache/ + report json) +python -m service.scripts.profiling.multipliers.spike_audit --institution-id I62318514 + +# Re-audit from the cache without re-hitting ES +python -m service.scripts.profiling.multipliers.spike_audit --institution-id I62318514 --skip-extract + +# Also test write/delete permissions on the INSE cluster (throwaway index) +python -m service.scripts.profiling.multipliers.spike_audit --institution-id I62318514 --probe-writes +``` + +Outputs land in `cache/`: +- `authors_.jsonl.gz` — the two-group author union. +- `works_.jsonl.gz` — full-authorship works (external co-authors + institutions). +- `spike_report_.json` — the audit report. + +The report answers: reproduction (author/work counts), field coverage +(`author_position` / `is_corresponding` / institution `type`), scale (authors-per-work +histogram, pair counts at caps 20/50/100), career quality (suspicious-profile %, +`active_years` distribution), signal reachability (`org_patents` match-type breakdown), +and write permissions. + +`cache/` is disposable and should not be committed (it can be hundreds of MB and contains +extracted person data). + +--- + +## M0 spike results (I62318514, run 2026-07-15) + +The spike existed to answer six questions the whole design was betting on. Full raw +numbers in `cache/spike_report_I62318514.json`; this section explains each stat, why it +was measured, and which downstream metric it feeds. + +### 1. Reproduction — is the extraction correct? + +| Stat | Value | Meaning | +|---|---|---| +| Author count | **4,921** | Exactly reproduces the audited seed extraction (`llm_evaluations/basic_applied_experimental/ude_audit_report.json`). Our port of the query is faithful. | +| — `backend_compatible` group | 4,740 | Authors with `last_known_institutions == UDE` **and** a recent UDE affiliation. | +| — `empty_last_known_recent` group | 181 | Authors with a recent UDE affiliation but **no** `last_known_institutions` at all. Without this second query group, 3.7% of the cohort would silently vanish — this is why the author set is a *union of two queries*, not one. | +| Work count | **183,661** | All works by those 4,921 authors, globally, unrestricted by institution or year. Matches the seed audit. | + +**Contributes to:** everything. This is the corpus. The "all works globally" property is +load-bearing for the career metrics: it means `active_years` is *exact* for in-set +authors (we see their complete history), while for external co-authors we only see works +shared with UDE — which is why mentor metrics are restricted to UDE-internal pairs. + +### 2. Field coverage — are the fields the metrics need actually populated? + +The OpenAlex Pydantic models declare these fields, but that says nothing about whether +the ES index actually populates them. Two sub-scores would have died silently. + +| Stat | Value | Feeds | Verdict | +|---|---|---|---| +| Authorships total | 3,805,507 | — | denominator | +| `author_position` populated | **100%** | `last_author_with_junior_first` (mentor): the classic supervision signature — PI last, junior first. | ✅ computable | +| `is_corresponding` populated | **100%** | reserved for later refinement (corresponding-author weighting). | ✅ available | +| `institutions.type` populated | **99.91%** | `cross_sector_share` / `industry_coauthor_share` (bridger + amplifier): share of works with a co-author at `type == "company"`. | ✅ computable | +| Company-institution occurrences | **67,131** | same | dense enough to rank on — this is the strongest *ID-linked* industry signal we have, stronger than any name-matched source. | + +**Contributes to:** confirms the metric set needs no fallbacks. Had `institutions.type` +been empty, the amplifier would have collapsed onto 123 high-confidence patents (see §6). + +### 3. Scale — where does the pair explosion land, and what cap do we need? + +Co-author pair generation is quadratic per work: a work with *n* authors yields +*n·(n−1)/2* pairs. The distribution of authors-per-work decides whether the self-join is +feasible locally and where to cap it. + +| Stat | Value | +|---|---| +| Authors per work p50 / p90 / p99 / max | **5 / 17 / 144 / 4,839** | +| Works with > 100 authors | **2,459** (1.3%) | +| Pair instances at cap 20 / 50 / 100 | **3.9M / 8.0M / 13.9M** | + +**Why `max_authors_per_work` matters** (the cap): the max-4,839-author work alone would +generate ~11.7M pairs — more than the *entire rest of the corpus* at cap 50 — and a +hyperauthored consortium paper (CERN/medical mega-trials) carries no real collaboration +signal: being 1 of 4,839 names says nothing about who actually works with whom, but it +*would* create a giant artificial clique that inflates betweenness and strength for +everyone on it, poisoning the bridger score. The cap drops works above the threshold +from **graph construction only** — they still count for publication years / `active_years`. + +**Chosen: `max_authors_per_work = 50`.** Rationale: p90 = 17, so a cap of 50 keeps ≥ 99% +of works (cap sits well above p90, below p99 = 144) while excluding only true +hyperauthorship; the resulting 8.0M pair instances collapse to ~1–2M distinct edges, +comfortably in-memory for polars. It's a config value (`extraction.max_authors_per_work`), +not code — tunable per institution. + +**Contributes to:** graph construction (Stage C); confirms the "pure local compute, no +DuckDB/warehouse" bet. + +### 4. Career quality — can we bucket careers, and how bad is profile merging? + +Background: `analysis/career_stage/` established that `first_publication_year` is +unreliable at UDE (merged OpenAlex profiles → debut years of 1893/1906 for active +professors) and that `active_years` (distinct years with ≥ 1 publication) is robust. +The pipeline therefore buckets by `active_years` and uses prefix-counted +`active_years_at(A, Y)` instead of debut years for the mentor metrics. + +| Stat | Value | Meaning / use | +|---|---|---| +| Suspicious profiles | **225 (4.6%)** | `first_year < 1970 or career_span > 60` (same flag as `persons/logic.py`). These are likely *merged identities*. They are **not dropped** — their `active_years` is still fine — but their evidence is marked `low_confidence`. Especially important for the **bridger** score: a merged profile is one node standing in for two people and *systematically* fakes bridging. | +| `active_years` p50 / p90 / max / mean | **4 / 25 / 60 / 8.9** | p50 = 4 means **half the cohort is career-stage "Early" (≤ 4)**. This is why percentile normalization happens *within career buckets* (Early/Emerging/Established/Senior via `_classify_career_stage`): institution-wide percentiles would just rank seniority, and no early-career person could ever surface as a multiplicator. | + +**Contributes to:** career bucketing (scoring), mentor junior/senior thresholds, +confidence flags on evidence. + +### 5. Permissions — can we ship the result anywhere? + +Initial spike: `PUT` to create an index on the INSE cluster → **403** (key can read, not +create). Resolved 2026-07-15: **`multiplicators_v1` was created by the cluster admin**, +and the standard INSE key can now write to it (verified: doc create + delete both +succeed). The build step must therefore *never* try to create/re-create the index — only +delete-by-institution + bulk-index into the existing one (same constraint as +`org_patents`, whose key also rejects `_delete_by_query`; use the search + bulk-delete +loop from `patents/org/elastic_search_client.py`). + +**Contributes to:** M2 index/build design. + +### 6. Signal reachability — which amplifier sources are real? + +| Stat | Value | Meaning | +|---|---|---| +| `org_patents` docs for UDE | **436** | The patent→OpenAlex-author link index exists and is populated. | +| — `match_type: name` | 313 | Name-only match. **Evidence only, weight 0** — name matching is the weakest link type. | +| — `match_type: both` | 65 | Institution assignee **and** name match — highest confidence. **Scores.** | +| — `match_type: institution` | 58 | Institution-assignee match. **Scores.** | + +**Contributes to:** amplifier sub-score. Only 123 patents are high-confidence, so patents +are a *secondary* amplifier signal; the primary is `industry_coauthor_share` (67k +ID-linked company co-authorships, §2). News (`aktuell_postproc`, exact-string person +match) enters at low weight; DFG (token containment) and Bund (no person link) are +excluded entirely. + +### Spike exit criteria — all met (see below for M1) + +- ✅ Extraction reproduces the audited counts exactly. +- ✅ Every planned metric is confirmed computable — no fallbacks needed. +- ✅ `max_authors_per_work = 50` chosen from measured data. +- ✅ Write path to `multiplicators_v1` verified end-to-end. +- ✅ Amplifier signal priorities re-ordered based on measured density + (industry co-authorship primary, patents secondary). + +--- + +## M1 results (metrics core, run 2026-07-15) + +Modules: `graph.py` (co-author graph via polars self-join, decay weights, hyperauthorship +cap), `metrics.py` (Brandes betweenness with inverted weights, Burt constraint on the +full graph incl. externals, field entropy, industry co-author share, debut-year-free +mentor metrics on `active_years_at`), `scoring.py` + `multipliers.yaml` +(within-career-bucket percentiles → weighted sub-scores → tags). 26 unit tests +(`pytest`), including exact agreement with networkx oracles for betweenness/constraint +and the planted-1893-outlier regression guard for `active_years_at`. + +Run with: + +```bash +python -m service.scripts.profiling.multipliers.build --institution-id I62318514 # scores + summary from the cache +python -m service.scripts.profiling.multipliers.validate_sample --institution-id I62318514 # 60-person exit check +``` + +### Full-corpus run (I62318514) + +| Stat | Value | +|---|---| +| Runtime end-to-end | **2.6 min** (load 15s, graph 31s, metrics 112s) — exit criterion was < 15 min | +| Graph | 639,544 nodes (4,921 focal + externals), 4,143,499 edges | +| Works used / capped | 160,396 / 4,823 (`max_authors_per_work = 50`) | +| Tags at threshold 0.85 | bridger 66, mentor 91, amplifier 609 | + +The amplifier tag count is inflated for now: only `industry_coauthor_share` exists at M1 +(patents/news/CORDIS join in M3), so weight redistribution makes it a single-metric +sub-score. Ignore amplifier tags until M3. + +### M1 exit check — PASS + +Against the 60 hand-labeled researchers in `analysis/career_stage/career_stage_sample.csv` +(31 Professor / 29 Researcher), mentor scores must concentrate on professors: + +| known status | n | median mentor score | +|---|---|---| +| Professor | 25 | **0.715** | +| Researcher | 18 | 0.493 | + +Top of the list is face-valid: senior professors with 30–50 mentored juniors and strong +last-author-with-junior-first signatures (Bacher, Sures, Hering, Gunzer, …). The two +high-scoring "Researchers" are informative, not embarrassing: e.g. a core-facility +scientist with 37 juniors but **zero** last-author works — the independent supervision +signature correctly separates "publishes with many juniors" from "supervises them". + +### ⚠ Cohort-coverage finding (must be decided in M2) + +17 of the 60 sample people are missing from the 4,921-author cohort. Diagnosed causes: + +1. **University-hospital clinicians are systematically excluded.** Prominent UDE + medicine professors (e.g. Witzke, Bingel) have + `last_known_institutions = Essen University Hospital (I4210119759)`, and the + hospital is **not** in UDE's OpenAlex lineage — OpenAlex models it as a *related* + institution, not a child. **2,437 active (2025+) authors** sit behind this gap — + roughly half a cohort. Fix: make the cohort definition accept a list of + institution IDs (`I62318514` + `I4210119759` + …) per deployment, sourced from + `associated_institutions` and confirmed by a human. +2. **Stale affiliation years exclude current staff.** E.g. Saccà has + `last_known = UDE` but no `affiliations.years >= 2025` entry, so the recency + filter drops her. Fix candidates: widen the window (>= 2023), or accept + `last_known = UDE` alone with a works-recency check. + +Both are extraction-time cohort decisions with precision/recall tradeoffs — they belong +to the coaches/product owner, not to code defaults. + +--- + +## M1 validation in detail (what was checked, against what ground truth) + +### The ground truth + +`analysis/career_stage/career_stage_sample.csv` — 60 UDE researchers with manually +researched **role labels** (`known_status`: 31 Professor / 29 Researcher incl. doctoral), +across five discipline groups (Biology, CS, Engineering, Medicine, Sociology), each with +an OpenAlex author ID (so the join to our scores is exact — no name matching involved). +The sample was originally built for the career-stage analysis; it does **not** label +anyone as a "multiplicator" — no such ground truth exists yet (that is the M3 golden set +the innovation coaches will provide). + +### What exactly was evaluated + +One directional sanity check on the riskiest sub-score: *supervision is part of the +professor role, so if the mentor sub-score measures anything like real mentorship, +professors must score systematically higher than researchers.* Defined check: +professors' **median mentor sub-score > researchers'**. + +The check is stronger than it looks because scores are percentiles **within career +buckets**: a Senior researcher is compared against Senior professors, not against PhD +students, so a trivial "older people score higher" effect is largely normalized away — +the gap has to come from mentor behaviour (juniors mentored, last-author-with-junior- +first works), not raw seniority. + +### Results (UDE-only cohort, 2026-07-15; archived as `cache/*_I62318514.udeonly.json`) + +43 of 60 matched (17 missing — see the cohort-coverage finding above). Medians: + +| sub-score | Professor (n=25) | Researcher (n=18) | check | +|---|---|---|---| +| **mentor** | **0.715** | **0.493** | **PASS** | +| bridger | 0.603 | 0.508 | (informational) | +| amplifier | 0.655 | 0.413 | (single-metric until M3 — ignore) | + +Ranking detail, more convincing than the medians: + +- Top = senior professors with strong dual signals: Gerd Bacher (37 juniors, 16 + last-author-junior-first works), Bernd Sures (52, 24), Daniel Hering (35, 25), + Matthias Gunzer (54 juniors). +- Bottom = early-career researchers with 0 juniors. +- The two high-scoring "Researchers" are the system working, not failing: + Birte Möhlendick (0.924, 12 juniors) — plausibly a group leader whose formal title + lags her role; Farnusch Kaschani (0.714, **37 juniors but 0 last-author works**) — + the classic core-facility-scientist profile: on many students' papers without + supervising them. The two mentor signals disagreeing on exactly this person is why + `last_author_with_junior_first` exists as an independent cross-check. + +### What this does NOT show + +It validates the *direction* of the mentor proxy, not that top-ranked people are good +mentors or multiplicators: professor-vs-researcher is a coarse label, n=43 is small, +bridger has no ground truth in this sample, and amplifier is a single-metric score until +M3. The real validation is the coach golden set (M3). This check is kept as a +regression: re-run `validate_sample.py` after every weight change or dump refresh. + +--- + +## Cohort fix + re-run (2026-07-15, config version 2) + +The hospital gap above is fixed by a **configurable cohort list**: `cohorts.. +institution_ids` in `multipliers.yaml`. **How the list was discovered — and how to +build one for another university — is documented in +[ASSOCIATED_INSTITUTIONS.md](docs/ASSOCIATED_INSTITUTIONS.md).** For UDE it holds 9 institutions — UDE, Essen +University Hospital, the West German Heart Center, the Erwin L. Hahn Institute, and the +five OpenAlex lineage children (RISP, DTNW, KWI, ZBT, IUTA) — with the deliberate +exclusions (Kliniken Essen-Mitte, the independent An-Institute) documented inline for +the coaches to revisit. Candidates were sourced from `associated_institutions` in +`openalex-institutions`; the extractor now matches `last_known_institutions` / +`affiliations` by **institution ID terms** over the whole list. + +### Before / after (UDE-only → 9-institution cohort) + +| | UDE-only | cohort | note | +|---|---|---|---| +| Authors | 4,921 | **6,583** | +1,662, mostly hospital clinicians | +| Works | 183,661 | **221,603** | | +| Graph | 640k nodes / 4.14M edges | 764k / 5.26M | | +| Pipeline runtime | 2.6 min | **4.5 min** | still far under the 15-min criterion | +| Sample matched | 43/60 | **45/60** | Witzke + Bingel recovered | +| Mentor exit check | 0.715 vs 0.493 PASS | **0.699 vs 0.493 PASS** | stable | +| Tags (bridger/mentor/amplifier) | 66/91/609 | 96/131/763 | scales with cohort | + +Face validity of the fix: both recovered professors immediately tag as mentors with +strong evidence — Witzke (Senior, 73 juniors mentored), Bingel (Senior, 34 juniors, +21 last-author-with-junior-first works). + +### The remaining 15 missing, fully diagnosed + +- **9 × correctly excluded** — they left UDE (`last_known` now Halle, Würzburg, + Greifswald, OU Netherlands, ISG, or none). The sample is older than the corpus; + these are not gaps. +- **6 × stale-affiliation cases** — `last_known` IS in the cohort but their most + recent cohort affiliation year is 2021–2024, so the `affiliation_years_gte: 2025` + recency filter drops them. At least one (Saccà, last seen 2024) is a current + professor — publication lag alone can push someone out of a 1-year window. + **Recommendation for M2:** set `extraction.affiliation_years_gte: 2023` (already + config) — captures normal publication lag while still excluding long-departed + authors. Decide with the coaches; it trades a little precision for recall. + +--- + +## M2 — pipeline + ES index (done 2026-07-15) + +New modules: `extract.py` (canonical cohort-aware extraction, config-driven), +`index.py` (`MultiplicatorsIndexClient` for `multiplicators_v1` on the INSE cluster), +`build.py` (single entry point: extract → graph → metrics → scoring → index). +`spike_audit.py` remains self-contained for auditing any institution. + +```bash +python -m service.scripts.profiling.multipliers.build --institution-id I62318514 # full run (reuses cache) +python -m service.scripts.profiling.multipliers.build --institution-id I62318514 --force-extract # refresh from ES +python -m service.scripts.profiling.multipliers.build --institution-id I62318514 --no-index # local artifacts only +``` + +### Index contract (`multiplicators_v1`, INSE cluster) + +- Doc `_id` = `_` (e.g. `I62318514_A5087456839`); + one doc per author per institution. +- Every doc: raw metrics, per-bucket percentiles, sub-scores, tags, career bucket, + `suspicious_profile`, evidence (junior ids), `config_hash`, `computed_at`, + `cohort_institution_ids`. Explicit mapping is PUT on every run (additive). +- Idempotent re-runs: collect the institution's doc ids → bulk-delete → bulk-index → + poll `_count` until the expected count is visible. **Verified: delete 9,474 → + index 9,474 → count 9,474.** + +### Key-permission gotchas (learned the hard way, encoded in `index.py`) + +The admin-created index + standard INSE key allows: read, `_bulk` index/delete, +`_mapping` updates, `_count`. It does **not** allow: index create/delete, +`_delete_by_query` (same as org_patents), and — new finding — **`_refresh` +(`indices:admin/refresh` → 403)**. A first client version silently relied on refresh +and saw phantom docs during delete (stale visibility inflated the delete count) and a +too-early post-index count. The client now never calls `_refresh`: it collects all doc +ids BEFORE deleting, and verifies by polling `_count` (auto-refresh ≈ 1s) instead. + +The same "add-only" limit applies to the mapping: the live index still carries +the retired v1 founder fields (`founding.probability`, `.applicable`, +`.p_within_2y`, `.models_agree`, `founding_features.h_index`, …) because the key +can add mappings but not delete them. New documents simply do not populate them. + +### Run with `affiliation_years_gte: 2023` (config v2 → v3) + +| | 2025 cutoff | 2023 cutoff | +|---|---|---| +| Authors / works | 6,583 / 221,603 | **9,475 / 267,467** | +| Graph | 764k nodes / 5.26M edges | 865k / 5.82M | +| Full runtime (incl. extract + index) | — | **~14.5 min** | +| Sample matched | 45/60 | **51/60** | +| Mentor exit check | 0.699 vs 0.493 PASS | **0.740 vs 0.494 PASS** (wider gap) | + +The 9 still-missing sample people are exactly the 9 confirmed leavers (last_known now +Halle, Würzburg, Greifswald, …) — correct exclusions, zero unexplained gaps. All six +stale-affiliation cases were recovered (some via 2023+ affiliations with the hospital / +institute cohort members rather than UDE itself). + +Career-bucket distribution in the index: Early 5,361 / Emerging 1,591 / +Established 777 / Senior 1,745. Tags: bridger 133, mentor 161, amplifier 1,107 +(amplifier still single-metric until M3 — ignore). + +### Next (M3) + +Wire the signal joins into the amplifier score (`org_patents` match_type +institution/both, news with name normalization at low weight, CORDIS DOI-join), +then calibrate the YAML weights with the innovation coaches against their golden set. +M4 (read router in `inse/`) once the UI needs it. + +--- + +## M3 — amplifier signal joins (done 2026-07-15) + +Before wiring, a live-index audit showed the amplifier was degenerate: its only input +(`industry_coauthor_share`) was 0 for 61.5% of the cohort, and the "top amplifiers" +were small-denominator ratio artifacts (share = 1.0 with 2 typed works). Two fixes: + +1. **Shrinkage**: scoring now uses `industry_coauthor_share_shrunk = company/(typed+k)` + (k=5, config `signals.industry_share_shrinkage_k`); the raw share stays in the doc. +2. **Three independent signal joins** (`signals.py`), weights in YAML + (shrunk share 0.50 / patents 0.25 / CORDIS 0.15 / news 0.10): + +| signal | join mechanism | UDE yield (9,474 authors) | +|---|---|---| +| `patent_count` | `org_patents.matched_authors` author IDs, `match_type ∈ {institution, both}`; name-only kept as `patent_count_name_only` evidence, never scored | 55 authors (17 more name-only) | +| `news_mentions` | `aktuell_postproc` LLM-extracted names, normalized-exact match (casefold + diacritic fold); a normalized name shared by >1 cohort authors credits NO ONE | 1,369 authors; **839 ambiguous names skipped** (precision over recall) | +| `cordis_eu_projects` | DOI overlap with `cordis_eu_*_publications` → distinct projectIDs. **Case-insensitive term matching** — 21% of CORDIS DOIs contain uppercase and a plain `terms` query silently misses them | 1,342 authors | + +Signal join runtime ≈ 9 min (the case-insensitive CORDIS batches dominate); total +pipeline ≈ 20 min. Mentor/bridger untouched: validation unchanged (51/60, mentor +check PASS 0.740 vs 0.494). + +### Effect on the amplifier tag + +Tags went **1,107 → 10**. With four independent inputs, a ≥0.85 *weighted mean* of +within-bucket percentiles requires being near the top on most channels — the tag now +means something. The new top-10 is face-valid (Wiltfang, Erbel, Kaiser, Schierning — +patent-holding, industry-connected, media-visible seniors). Two open calibration +questions for the coaches: + +- **Threshold per tag?** 0.85 yields 133 bridgers / 161 mentors / 10 amplifiers. + If more amplifier candidates are wanted, either lower a per-tag threshold + (currently one global `tags.threshold`) or re-weight. +- **Split-profile artifact**: an Early-bucket author with 1 active year made top-10 + amplifier — almost certainly a split OpenAlex profile of a senior professor + (patents/news land on the fragment). Bucket-relative ranking amplifies fragments; + the `suspicious_profile` flag does not catch splits (only merges). Known + limitation — ORCID-based resolution is the deferred fix. + +### M3 remaining + +The **coach calibration session**: golden set of 10–20 known multiplicators, tune the +YAML (weights, per-tag thresholds), re-run `validate_sample.py` as regression. + +--- + +## Founder-potential enrichment + +The three archetype scores answer *"who stands out in this cohort"*. Coaches also +need the orthogonal question — *"does this person's profile resemble people who +actually founded companies, and how soon"* — which no cohort-relative percentile +can answer. [`../founding_potential`](../founding_potential) already trained and +validated models for exactly that, so `founding.py` runs them rather than +inventing a fourth archetype. + +### Model lineage: v1 found broken here, v2 is the fix (2026-08-07) + +The first integration ran the v1 classifier +(`../founding_potential/production/classifier`) and found it behaving as an +**inverse-productivity score** — a controlled single-feature probe of the model +file gave P(founder) = 0.996 at 1 publication and 0.0002 at 800, and on the live +cohort median probability fell monotonically with output. Root cause upstream: +asymmetric observation windows (founders' totals truncated at founding, +non-founders' full-career), so window length itself became the class marker — +which also explains v1's inflated 0.976 ROC-AUC. Its residual-derived +`p_within_3y`/`p_within_5y` companions were degenerate too: exactly 1.0 for +every one of the 9,474 authors. + +The upstream package was rebuilt on a **symmetric landmark design** (every +person truncated at an index year — real founding year for founders, a +cohort-matched pseudo-founding year for non-founders; citation features dropped +as non-historicizable; thin-profile and name-collision artifacts filtered from +both classes). This module now runs those v2 bundles exclusively; the v1 model +files remain on disk but nothing references them, and they must not be +configured again. Full postmortem and design: `classifier_symmetric/README.md`. + +### Which models + +| bundle | question | honest OOF (5-fold) | notes | +|---|---|---|---| +| `founder_classifier_v2` | founder-propensity vs the reference cohort | ROC-AUC **0.866** / PR-AUC 0.726 | lightgbm; v1's 0.976 was the window artifact | +| `p_within_{1,3,5}y_v2` | founds within k years of the index | ROC-AUC 0.85–0.86 | one bundle per horizon, own reference quantiles | +| `transformer` (+ `lstm` cross-check) | how far into a career the activity pattern looks founding-like | MAE 0.180 / 0.208 | sequence point estimate only — its residual-derived probabilities are retired | + +### Two percentiles, two comparison sets — why this is still not a fourth sub-score + +`sub_scores.{bridger,mentor,amplifier}` are percentiles **within a career bucket +of this cohort**. `founding.percentile` is also a percentile — but against a +**fixed external reference cohort** (~9k academics from the 8 training +institutions, out-of-fold scores). Folding it into `sub_scores` would silently +mix the two comparison sets, so it lives in its own flat namespace, every field +explicitly mapped, and the coach query composes directly: + +```jsonc +// GET multiplicators_v1/_search — "mentors above the 90th percentile for founding within 3 years" +{"query": {"bool": {"filter": [ + {"term": {"institution_id": "I62318514"}}, + {"term": {"tags": "mentor"}}, + {"term": {"founding.in_population": true}}, + {"range": {"founding.p_within_3y_percentile": {"gte": 90}}} +]}}, "sort": [{"founding.percentile": "desc"}]} +``` + +All three horizons discriminate in v2 (OOF ROC-AUC 0.85–0.89, ≤0.1% of scores +saturated) — the v1 situation where filtering on `p_within_3y` selected the +entire cohort is gone. **Pick thresholds from the measured distributions, not +round numbers**: tags select established researchers, whose v2 scores are +structurally lower (mentors' founding percentile p90 is 47), so the ≥90 filter +above returns zero mentors at UDE — see "Measured residual" below for working +thresholds and the recommended `publications >= 7` co-filter. Field-by-field +documentation: [ROADMAP.md](docs/ROADMAP.md) §3, "Founder potential". + +### Numbers a UI may and may not show + +- **`founding.percentile` / `p_within_{k}y_percentile`** — the coach-facing + numbers: "higher founding propensity than X% of comparable academics". +- **`founding.probability_raw` / `p_within_{k}y_raw`** — case-control model + outputs. The training cohort is ~26% founders, far above any real base rate, + so these are **not** population founding probabilities and must never be + displayed as one. Indexed for diagnostics and future recalibration only. + +### The two applicability flags are load-bearing + +- **`founding.in_population`** — v2's population guard (≥4 publications, owned + by the wrapper, not by this pipeline's config). Below it the training classes + come from clashing sampling frames — founders from company databases include + 1-paper "academics", non-founders from institutional lists do not — and left + unguarded, "long career + tiny record" read as 65–72% founder in training. + Out-of-population rows carry `percentile: null` and must not be ranked. +- **`founding.timing_applicable`** — the sequence models only ever saw founding + ages in [1, 20] years, so a 35-year career is outside the regime they know. + Also false for `suspicious_profile` authors, because the timing output is + anchored on `first_publication_year` — the exact field this repo's career-stage + analysis found unreliable for merged OpenAlex profiles (debut years like 1893). + This is why the multiplicator metrics avoid that field entirely; the founder + models cannot, so the flag carries the caveat instead. + +### Feature sourcing: two decisions worth knowing + +**Patents have two possible sources; the production setting merges both.** +`founding.patent_source` selects the mode, and every document records what +actually fed it, because scores computed under different patent inputs are not +comparable. Measured on the full cohort (an earlier "7% / 12x" claim came from +a biased file-order 200-author sample — low OpenAlex ids cluster +long-established profiles): + +| source | authors with ≥1 patent (of 9,474) | cost | +|---|---|---| +| `org_patents` | 55 — 0.6% | free, reuses the amplifier's scan; for fast pipeline iteration only | +| name-matched API | 115 — 1.2% | ~20–65 min, cached per cohort | +| **`api` mode = per-author merge of both** (stamped `api+org_patents`) | **152 — 1.6%** | both of the above | + +The merge exists because the two sources **overlap on only 18 authors**: 37 +institution-confirmed patent holders get zero from the API (scan budget, name +variants, topic filter), and 97 name-matched holders are invisible to assignee +matching. Per author the higher count wins whole — never summed, since the same +patent can appear in both corpora with no id-level dedup at this aggregation. + +The v2 model consumes `patents`, `first_patent_year` and the derived +patent-rate/recency features; on `org_patents` alone those are zero for 99.4% +of the cohort, so a production run that ranks people must use `api`. **Do not +read a low founder percentile as "this person does not patent"** — check +`founding_features.patents` and `founding.patent_source`. + +The `api` source calls `/api/inse-service/authors/{id}/patents`, which is not a +reimplementation — that endpoint runs adaptive EPO+USPTO scanning, name-variant +matching, ambiguity rules, EPO family expansion and IPC-to-topic filtering +across ~3.8k lines that would fork if copied here. One request per author with +the backend container CPU-bound throughout; under that load the backend +intermittently 502s, so the join does a full-speed pass, retries the failures +sequentially once pressure drops, and raises only if >1% of the cohort still +fails (persistent gaps are printed, returned, and stored in the cache as +`failed_ids` — loud, never silent). + +**Known limitation of that endpoint.** It internally distinguishes "scanned +everything, found nothing" from "hit the scan budget, result inconclusive" (it +logs a warning for the latter) but does not expose the flag in its response. A +truncated-inconclusive author is therefore indistinguishable here from an author +with no patents, and both land as `patents: 0`. A 0 in +`founding_features.patents` means "nothing found", not "provably none" — the +error direction is under-counting, which is the safer one for a founder score. + +Either way both counts stay in the index — `patent_count` (institution-linked, +feeds the amplifier) and `founding_features.patents` (model input) — because they +answer different questions. + +**Research area is mapped, not skipped.** The classifier was trained on Dimensions +FOR 2-digit divisions; our works carry OpenAlex fields. Its README offers "pass +nothing and lose the signal" or "map"; `founding.py` holds an explicit 26-entry +lookup table. Full table and the per-entry judgment calls: +[docs/RESEARCH_AREA_MAPPING.md](docs/RESEARCH_AREA_MAPPING.md). Patents honestly +get the unknown token — the patent corpus carries IPC codes, and IPC→FOR is a +project of its own. + +### Run results (I62318514, 2026-08-07, v2 bundles, `patent_source: api` → merged) + +Full pipeline ~16 min end to end from the cached extract; the founder stage +itself (all six models over 9,474 authors) is **3.0 s** of the total. + +| stage | time | +|---|---| +| load cached extract (9,475 authors / 267,467 works) | 29 s | +| founder feature pass over the works | 3.0 s | +| graph (864,646 nodes / 5,822,006 edges) | 72 s | +| metrics | 327 s | +| signals (patents / news / CORDIS) | 419 s | +| patent join (cache hit; 20.4 min when cold) + merge | ~0 s | +| **founder models (v2 classifier + 3 horizons + 2 timing)** | **3.0 s** | +| index `multiplicators_v1` (9,474 docs) | 12 s | +| index `multiplicator_networks_v1` (9,474 docs) | 82 s | + +Founder-stage coverage and score shape: + +| | value | +|---|---| +| `in_population` (≥4 publications) | 5,712 (60.3%) | +| `timing_applicable` | 6,118 (64.6%) | +| `percentile` p5 / p50 / p95 (in population) | 1.4 / 33.1 / 89.3 | +| `percentile` ≥ 90 | 270 | +| horizon percentiles p50 (1y / 3y / 5y) | 30.9 / 33.1 / 41.2 — **all three discriminate** | +| patent profiles (api 115 ∪ org 55, overlap 18) | 152 (1.6%), stamped `api+org_patents` | +| `grants` max raw → capped | 7,934 → 7,077 (cap-table defect, see above) | + +Regression unchanged — `validate_sample.py` reports 51/60 matched (the 9 +missing are the documented leavers) and mentor medians of **0.740 Professor vs +0.494 Researcher**, identical to M3. Modal research areas resolve sensibly: +`32` Biomedical and Clinical (4,166), `40` Engineering (1,624), `44` Human +Society (748). + +### ⚠️ Measured residual: the population boundary owns the top of the ranking + +The ≥4-publications rule cut the worst of the sampling-frame clash, but its +residue concentrates **just above the cut line**, and on this cohort it owns +the top band: + +| percentile band | n | share with < 7 publications | +|---|---|---| +| ≥ 95 | 131 | **81%** (106) | +| 90–95 | 139 | 73% (102) | +| 50–90 | 1,667 | 27% | + +The ≥95 band has median career age **23 years** but median `active_years` +**4** (p90 career age: 70) — long-dormant, few-paper profiles, many visibly +split OpenAlex fragments ("HH-J Schmidt" *and* "H. H. Schmidt" both rank in +the top 10 at pubs=4, raw ≈ 0.998). Median percentile by volume: pubs [4,7) → +**61.5**, [7,15) → 26.7, [15,40) → 28.1, [40,100) → 36.2, 300+ → 12.3. + +By contrast the mid-volume slice is face-valid — top of `pubs ≥ 15`: an +Established researcher at pctl 98.4, and a Senior with 306 publications, +5 patents and 22 industry collaborations at 95.6. + +**Practical guidance until the model rule is revisited (decision belongs to +the model owner, not this pipeline):** read `founding.percentile` jointly with +`founding_features.publications` — a UI shortlist should add +`founding_features.publications >= 7` (or an equivalent activity-density +condition) on top of `in_population`. And calibrate tag-combined thresholds to +the measured distributions: mentors' founding percentile p50/p90/p99 is +**10 / 47 / 70** (the v2 score genuinely declines with volume — "favours +focused mid-volume researchers"), so *"mentors above founding percentile 40"* +is a real shortlist while *"above 90"* selects nobody. + +### ⚠️ `grants` inflation: v2 handles it in principle, but the shipped cap table under-caps + +`founding_features.grants` counts distinct OpenAlex `awards.id` values +acknowledged on the person's works, and consortium acknowledgement lists inflate +it (UDE max: **7,934 "grants" on a 76-publication profile** — ~104 funding +acknowledgements per paper; 467 authors exceed 100). v2 addresses this by +design: the wrapper de-inflates `grants` through a per-paper cap mapping shipped +in the bundle, and both raw and capped values are indexed +(`founding_features.grants` / `grants_capped`). + +**Found during integration:** the shipped interpolation table does not implement +the documented "cap 10 per paper". Its share bottoms out at ~0.89 from ~12.6 +grants/paper onward, so the 7,934-grant profile de-inflates to ~7,077, not +≤760. Practical impact is limited — grant features enter the model as `log1p`, +and both values sit far beyond every training-range split, so the trees +saturate either way — but the bundle's behaviour contradicts its README and +should be fixed at the next export (reported upstream 2026-08-07). This +pipeline deliberately does **not** pre-cap locally: double-shrinking through +the wrapper's table would muddy the contract, and `grants_capped` in the index +records what the model actually used. + +### Cost + +Model inference itself (all four v2 bundles + both sequence models over 9,474 +authors) is seconds. On `patent_source: org_patents` the whole founder stage is +nearly free — the patent profiles fall out of the amplifier's existing scan. + +The production `api` mode adds the name-matched join: one request per author at +concurrency 16, measured **20.4 min** with the backend's internal caches warm +and ~65 min cold. Raising concurrency does not help — the backend container sits +at ~100% CPU for the entire stage (a single uvicorn process running the name and +topic matching), and at concurrency 32 it saturates into read timeouts. The +result is cached to `cache/patents_named_.json.gz` keyed on a hash of the +cohort (with any persistent per-author failures stored as `failed_ids`), so it +is paid once per cohort and later retunes are free. Giving the backend more +uvicorn workers is the obvious way to cut it further, and has not been tried. + +--- + +## Network visualization index (`multiplicator_networks_v1`, added 2026-07-16) + +The scores index answers *what did this person score*; this companion index answers +*who are they connected to and how* — everything a frontend needs to draw the +ego-network figures (force layout, role colors, tooltips) without recomputing +anything. Materialized by `build.py` (`networks.py`) while the full graph is in +memory, because the **neighbor-neighbor edges** that make graph shape readable +(dense mesh = one community; spokes with gaps = brokered structural holes) come from +works that do NOT include the ego — no request-time query can reconstruct them. + +One doc per focal author, `_id = _` (same scheme as scores): + +| field | content | +|---|---| +| `nodes[]` | `{id, name, role, inst, active_years, suspicious}`; role ∈ ego / mentee / cohort / industry / external | +| `edges[]` | `{a, b, w, n_works, cross, first_year, last_year}` — `w` = decayed tie strength, `cross` = mostly cross-institution | +| `ego{}` | header duplicate (bucket, tags, sub_scores, max_sub_score) so a network endpoint renders standalone | +| totals | `total_coauthors`, `cohort_coauthors`, `mentee_count`, `shown`, `shown_mentees` | +| provenance | `config_hash`, `computed_at`, `cohort_institution_ids` | + +Selection: strongest `network.max_nodes` (42) co-authors by tie weight with up to +`network.max_forced_mentees` (14) mentees force-included first — mentees' ties are +decayed and team-size-divided, so a pure top-by-weight cut hides exactly the people +the mentor score is about. Positions are NOT stored: the webapp's echarts `graph` +series (force layout) lays out at render time; map role → color, active_years → +symbol size, `cross` → dashed line. + +`nodes`/`edges` are mapped `"enabled": false` (stored, never indexed) — the index +stays small and fast for the queryable header fields (`institution_id`, `author_id`, +`ego.tags`, `computed_at`, …). Skip building with `--no-network`. + +### Regenerating the HTML report + +`make_report.py` renders a self-contained HTML report of four contrasting cases +straight from the two live ES indices — no local cache required, so it works on any +machine with cluster access after a build has run: + +```bash +python -m service.scripts.profiling.multipliers.make_report --institution-id I62318514 +# -> reports/multiplier_networks.html (open in any browser; light/dark toggle) + +python -m service.scripts.profiling.multipliers.make_report --institution-id I62318514 \ + --author-ids A5113304257,A5043495754,A5007801159,A5123934012 # explicit cast +``` + +The cast is pinned in `report.featured_author_ids` (config) so the report is +reproducible across weight tunes and dump refreshes; `--author-ids` overrides it and +`--auto` falls back to selecting the current top bridger / mentor / amplifier plus the +highest-scoring person who carries **no** tag — the last one exposes where the +thresholds bite (and, when that person's best sub-score is *above* 0.85, the +`tags.min_active_years` guard that withholds tags from one-year profiles, which are +usually **split** OpenAlex identities — the case `suspicious_profile` cannot catch, +since that flag detects merges). + +The page layout lives in `report_template.html` (tracked); `reports/` and `cache/` are +gitignored, so a `git clean -fdx` or fresh checkout wipes generated reports and +extracts — re-run the command above to rebuild the report, and `build.py` only if the +indices themselves need refreshing. diff --git a/service/scripts/profiling/multipliers/build.py b/service/scripts/profiling/multipliers/build.py new file mode 100644 index 00000000..95901b93 --- /dev/null +++ b/service/scripts/profiling/multipliers/build.py @@ -0,0 +1,370 @@ +#!/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 +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 company flag (network docs) ---- + focal_short_ids = {short_id(a) for a in focal_ids} + dois_by_author: dict[str, set[str]] = {} + inst_by_author: dict[str, str] = {} + company_authors: set[str] = set() + for w in works: + doi = normalize_doi(w.get("doi")) + for a in w.get("authorships") or []: + aid = short_id((a.get("author") or {}).get("id")) + if not aid: + continue + if doi and aid in focal_short_ids: + dois_by_author.setdefault(aid, set()).add(doi) + for inst in a.get("institutions") or []: + if aid not in inst_by_author and inst.get("display_name"): + inst_by_author[aid] = inst["display_name"] + if inst.get("type") == "company": + company_authors.add(aid) + + # ---- 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_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] + ] + + 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() diff --git a/service/scripts/profiling/multipliers/conftest.py b/service/scripts/profiling/multipliers/conftest.py new file mode 100644 index 00000000..88b7f134 --- /dev/null +++ b/service/scripts/profiling/multipliers/conftest.py @@ -0,0 +1,5 @@ +"""Make the module root importable from tests/ (pytest inserts this dir via conftest).""" +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) diff --git a/service/scripts/profiling/multipliers/docs/ASSOCIATED_INSTITUTIONS.md b/service/scripts/profiling/multipliers/docs/ASSOCIATED_INSTITUTIONS.md new file mode 100644 index 00000000..c4eb893e --- /dev/null +++ b/service/scripts/profiling/multipliers/docs/ASSOCIATED_INSTITUTIONS.md @@ -0,0 +1,116 @@ +# Cohort discovery: finding a university's associated institutions in OpenAlex + +How the `cohorts..institution_ids` list in `multipliers.yaml` was built for the +University of Duisburg-Essen (I62318514), and how to repeat the process for another +university. Context: the multiplicator pipeline's author set is only as good as this +list — matching UDE alone silently excluded ~2,400 active clinicians, including +prominent medicine professors (found via the M1 validation, where 17/60 hand-labeled +people were missing). + +## Why this is necessary: `lineage` vs `associated_institutions` + +Every institution document in OpenAlex (index `openalex-institutions`) carries two +relationship fields: + +- **`lineage`** — the strict parent hierarchy: a list of institution IDs including the + institution itself and its parents. This is what ID-based filters normally use + (e.g. `company_connections/logic.py` checks `UDE_OPENALEX_ID in lineage`). +- **`associated_institutions`** — a looser list of linked institutions, each with a + `relationship` label: `child`, `parent`, or `related`. + +The trap: **OpenAlex models German university hospitals as `related`, not as lineage +children.** Essen University Hospital's own `lineage` contains only itself. Any filter +built on UDE's ID or lineage therefore can never match hospital-affiliated authors — +the entire clinical medical faculty — no matter how the query is written. + +## The discovery method (3 steps) + +### Step 1 — read the university's `associated_institutions` + +Query the `openalex-institutions` document for the primary ID and list its +`associated_institutions`. For UDE (I62318514): + +| ID | relationship | name | authors (all-time last_known) | +|---|---|---|---| +| I4210090139 | child | Rhein-Ruhr Institut für Sozialforschung | 11 | +| I4210092428 | child | Deutsches Textilforschungszentrum Nord-West | 170 | +| I4210110714 | child | Institute for Advanced Study in the Humanities (KWI) | 81 | +| I4210146441 | child | Hydrogen and Fuel Cell Center (ZBT) | 98 | +| I4210154243 | child | Institut für Energie- und Umwelttechnik (IUTA) | 233 | +| **I4210119759** | **related** | **Essen University Hospital** | **7,484** | +| I4210146447 | related | Kliniken Essen-Mitte | 788 | +| I2799342142 | related | Salomon Ludwig Steinheim-Institut | — | +| I4210124583 | related | IWW Water Centre | — | + +(For comparison: UDE itself has 14,388 all-time last_known authors.) + +### Step 2 — follow one hop into any `related` hospital + +The hospital's own `associated_institutions` revealed a member invisible from UDE's +record: the **West German Heart and Vascular Center Essen (I4210161917)** is a `child` +of the hospital (1,021 authors) — two hops from UDE. + +### Step 3 — validate against real people (this catches what no query can) + +The **Erwin L. Hahn Institute for MRI (I127668822)** was NOT found by any metadata +walk: in OpenAlex it is completely isolated — `lineage` contains only itself, +`associated_institutions` is empty. It surfaced only when diagnosing why a specific +hand-labeled professor (Ulrike Bingel) was missing from the cohort: it appeared in her +affiliation list. Lesson: after building the list from metadata, always check a set of +known current researchers against the extracted cohort — the misses point to +institutions the graph walk cannot reach. + +## Inclusion decisions for UDE (documented in `multipliers.yaml`) + +**Included (9):** + +- `I62318514` UDE (primary) +- `I4210119759` Essen University Hospital — it *is* the university medical centre; + its `related` label is an OpenAlex modelling choice, not an organisational fact +- `I4210161917` West German Heart and Vascular Center (child of the hospital) +- `I127668822` Erwin L. Hahn Institute (joint UDE institute; isolated in OpenAlex) +- The five lineage children: RISP, DTNW, KWI, ZBT, IUTA — small but unambiguous + +**Excluded by default (revisit with the coaches):** + +- `I4210146447` Kliniken Essen-Mitte — an independent hospital group; `related` + reflects collaboration, not membership; its staff are not UDE researchers +- `I2799342142` Salomon Ludwig Steinheim-Institut and `I4210124583` IWW Water + Centre — *An-Institute*: legally independent institutes **at** UDE, not **of** it + +The borderline cases are exactly the German-institutional-law ones (An-Institute, +municipal hospital groups). These are human judgment calls, which is why the list +lives in config with the reasoning inline, not in code. + +## Effect on the cohort (measured) + +| | UDE ID only | 9-institution cohort | +|---|---|---| +| Authors (affiliation ≥ 2023) | ~7,100¹ | 9,475 | +| Hand-labeled sample matched | 43/60² | 51/60 | +| Unexplained misses | 17 | **0** (the 9 remaining all verifiably left UDE) | + +¹ approximate — the single-ID number was measured at the 2025 cutoff (4,921); scaled here for context. +² at the 2025 cutoff; the cohort fix and the 2023 affiliation window each contributed. + +Recovered by the fix, as a face-validity check: Oliver Witzke (Senior, 73 juniors +mentored → tagged mentor) and Ulrike Bingel (Senior, 34 juniors, 21 +last-author-with-junior-first works → tagged mentor). + +## Repeating this for another university + +1. Fetch `associated_institutions` from `openalex-institutions` for the primary ID; + collect all `child` entries and every `related` entry. +2. For any `related` hospital / medical centre, fetch ITS `associated_institutions` + and collect its children. +3. For each candidate, count authors + (`last_known_institutions.id == ` on `openalex-authors`) — size tells + you what an inclusion decision is worth. +4. Decide inclusions with a human: university hospitals in; independent hospital + groups and An-Institute out unless the institution says otherwise. +5. Write the `cohorts.` block in `multipliers.yaml` with the reasoning + as inline comments. +6. Run the extraction, then validate against a list of known current researchers + (professors from several faculties, especially medicine). Every unexplained miss + is either a missing cohort member (like the Hahn Institute) or a stale-affiliation + case (tune `extraction.affiliation_years_gte`). diff --git a/service/scripts/profiling/multipliers/docs/RESEARCH_AREA_MAPPING.md b/service/scripts/profiling/multipliers/docs/RESEARCH_AREA_MAPPING.md new file mode 100644 index 00000000..f4483774 --- /dev/null +++ b/service/scripts/profiling/multipliers/docs/RESEARCH_AREA_MAPPING.md @@ -0,0 +1,63 @@ +# OpenAlex field → Dimensions FOR division + +The founder classifiers' three `*_research_area` inputs were trained on the +first two characters of Dimensions' **FOR** (Fields of Research) codes, unchanged +from v1 to v2. Our corpus classifies works with **OpenAlex's 26 fields** instead, +so `founding.py` holds an explicit lookup table (`OPENALEX_FIELD_TO_FOR`). + +The classifier README offers two options — pass the unknown token and lose the +signal, or map. We map. Each entry below is a judgment call about the closest +single FOR division; the genuinely arguable ones are annotated. + +| OpenAlex field | → FOR | FOR division | +|---|---|---| +| 11 Agricultural and Biological Sciences | 30 | Agricultural, Veterinary and Food Sciences | +| 12 Arts and Humanities | 36 | Creative Arts and Writing | +| 13 Biochemistry, Genetics and Molecular Biology | 31 | Biological Sciences | +| 14 Business, Management and Accounting | 35 | Commerce, Management, Tourism and Services | +| 15 Chemical Engineering | 40 | Engineering | +| 16 Chemistry | 34 | Chemical Sciences | +| 17 Computer Science | 46 | Information and Computing Sciences | +| 18 Decision Sciences | 49 | Mathematical Sciences | +| 19 Earth and Planetary Sciences | 37 | Earth Sciences | +| 20 Economics, Econometrics and Finance | 38 | Economics | +| 21 Energy | 40 | Engineering | +| 22 Engineering | 40 | Engineering | +| 23 Environmental Science | 41 | Environmental Sciences | +| 24 Immunology and Microbiology | 32 | Biomedical and Clinical Sciences | +| 25 Materials Science | 40 | Engineering (FOR 4016 Materials Engineering) | +| 26 Mathematics | 49 | Mathematical Sciences | +| 27 Medicine | 32 | Biomedical and Clinical Sciences | +| 28 Neuroscience | 32 | Biomedical and Clinical Sciences (FOR 3209) | +| 29 Nursing | 42 | Health Sciences (FOR 4205) | +| 30 Pharmacology, Toxicology and Pharmaceutics | 32 | Biomedical and Clinical Sciences (FOR 3214) | +| 31 Physics and Astronomy | 51 | Physical Sciences | +| 32 Psychology | 52 | Psychology | +| 33 Social Sciences | 44 | Human Society | +| 34 Veterinary | 30 | Agricultural, Veterinary and Food Sciences | +| 35 Dentistry | 32 | Biomedical and Clinical Sciences (FOR 3203) | +| 36 Health Professions | 42 | Health Sciences | + +## The arguable entries + +- **11 Agricultural and Biological Sciences → 30, not 31.** The field's + subfields are agronomy/forestry/food/soil-heavy, so the agricultural head term + wins. Pure molecular biology sits in OpenAlex field 13, which does map to 31. +- **18 Decision Sciences → 49.** Operations research and statistics dominate + this field's subfields, which puts it closer to Mathematical Sciences than to + Commerce or Information and Computing Sciences. +- **24 Immunology and Microbiology → 32.** Genuinely split: FOR 3204 Immunology + sits under Biomedical and Clinical Sciences, FOR 3107 Microbiology under + Biological Sciences. The immunology head term decides it. + +## What is not mapped + +`modal_research_area` sums per FOR code, not per OpenAlex field, so fields that +collapse to the same division (27 Medicine and 28 Neuroscience, both → 32) +**accumulate** rather than compete. Ties break on the FOR code, so repeated runs +over one extract agree. + +Patents get the unknown token `"n."` for the whole corpus: our patent records +carry IPC codes, and IPC→FOR is a project of its own. Grants have no research +area either, but the works a grant funded do, so `grant_research_area` is +derived from those — derived evidence, not a guess. diff --git a/service/scripts/profiling/multipliers/docs/ROADMAP.md b/service/scripts/profiling/multipliers/docs/ROADMAP.md new file mode 100644 index 00000000..b1ec4e77 --- /dev/null +++ b/service/scripts/profiling/multipliers/docs/ROADMAP.md @@ -0,0 +1,331 @@ +# Multiplicator Detection — Concept, Technical Walkthrough & Roadmap + +A ground-up explanation of what this module does, how every field in the +`multiplicators_v1` index is computed and what it means, where the ideas come from, +and where the project stands. Written for a reader with no prior context. + +Companion docs: [README.md](../README.md) (per-milestone results and stats), +[ASSOCIATED_INSTITUTIONS.md](ASSOCIATED_INSTITUTIONS.md) (cohort discovery method). + +--- + +## 1. What problem this solves + +The university's innovation coaches want to find **multiplicators**: people whose value +isn't only their own research output, but their effect on the system around them — they +connect groups that otherwise wouldn't talk, they grow junior researchers into +independent scientists, they carry research out of academia into industry and the +public. These people are invisible in classic rankings (citations, h-index), which +measure individual output, not systemic effect. + +The core bet of the whole project: **these behaviors leave measurable traces in +publication metadata.** Who you publish with, when, in what role, and across which +institutional boundaries is recorded in OpenAlex for every paper. So instead of asking +"who is influential?" we ask three narrower, checkable questions, each an archetype: + +- **Bridger** — do your collaborations span otherwise-disconnected communities, + fields, institutions, sectors? +- **Mentor** — do junior people repeatedly start their careers publishing with you, + in the role configuration typical of supervision? +- **Amplifier** — does your work escape academia: patents, industry co-authorship, + EU projects, press coverage? + +Everything else is machinery for answering those three questions honestly at the +scale of ~9,500 people. + +## 2. The pipeline, step by step + +**Step 1 — Define who "the university" is (cohort).** OpenAlex models Essen University +Hospital as merely *related* to UDE, not part of it, so filtering by UDE's ID alone +silently loses the entire clinical faculty (~2,400 active people). The cohort is +therefore an explicit list of 9 institution IDs (UDE + hospital + heart center + +affiliated institutes) — the `cohort_institution_ids` array on every document. An +author belongs if their last-known institution is in that list **and** they have an +affiliation year ≥ 2023 (publication lag makes a 1-year window drop current staff). +Details: [ASSOCIATED_INSTITUTIONS.md](ASSOCIATED_INSTITUTIONS.md). + +**Step 2 — Extract.** For those ~9,475 authors we pull **all their works globally** — +not just university-affiliated ones — with the *complete* author list of every paper, +including external co-authors and each co-author's institution (with its type: +education, company, healthcare…). Result: ~267k works, ~3.8M authorship records. +The "all works globally" property matters: it makes career histories *exact* for +cohort members, while external co-authors' histories are truncated to shared works — +a fact the mentor metrics must respect (see §3). + +**Step 3 — Build the co-authorship graph.** Every paper connects each pair of its +authors with an edge. Three refinements: + +- **Team-size weighting**: a pair on a 3-author paper gets weight 1/(n−1) = 0.5; on a + 40-author paper, 1/39. Being 2 of 3 authors is strong evidence you actually work + together; being 2 of 40 is weak evidence. +- **Time decay**: each paper's contribution is multiplied by 0.8^(years ago). A 2025 + collaboration counts full; a 2010 one counts ~3%. We're looking for *current* + multiplicators. +- **Hyperauthorship cap**: papers with >50 authors (CERN-style consortia; the corpus + max is 4,839 authors on one paper) are excluded from the graph entirely — that one + paper alone would create ~11.7M fake "collaboration" edges and a giant artificial + clique. Those papers still count for career metrics. + +Result: ~865k nodes (cohort + all their external co-authors), ~5.8M weighted edges. + +**Step 4 — Compute metrics on that graph** (§3, field by field). + +**Step 5 — Normalize fairly and score.** Raw metrics aren't comparable between a PhD +student and a 30-year professor, so every metric becomes a **percentile within the +person's career stage**, then three weighted sub-scores, then tags above a threshold +(§4). + +**Step 6 — Join external signals** (patents, news, EU projects). + +**Step 7 — Score founder potential.** The same profile data is assembled into the +input schema of the pre-trained v2 models in +`../founding_potential/production/classifier_symmetric` (plus the sequence +timing models) and run through all of them, adding a founder-propensity +**percentile against a fixed reference cohort** and per-horizon "founds within +k years" percentiles alongside the three archetype scores (§3, "Founder +potential"). This answers a question the archetypes cannot: the three +sub-scores rank people *against their cohort*, while a coach also needs to know +whether a specific person's profile resembles people who actually founded +companies. + +**Step 8 — Write everything to `multiplicators_v1`** — one document per person, +containing raw values, percentiles, scores, tags, model outputs, and evidence, so +a coach can always see *why* someone scored what they scored. + +## 3. A real document, field by field + +Example: Tabea M. G. Pakull, `_id = I62318514_A5043360678` (institution + author — +the same person at another university would be a separate doc). An ES `_version: 8` +just means the doc was overwritten 8 times by re-runs; the `fields` block ES returns +alongside `_source` is its internal columnar echo — ignore it. + +### Career context + +| field | example value | meaning | +|---|---|---| +| `active_years` | 3 | Distinct calendar years with ≥1 publication — our seniority measure. We deliberately do **not** use "years since first publication": the repo's career-stage analysis found merged OpenAlex profiles give active professors debut years like 1893. One wrong old paper distorts career span by decades but moves `active_years` by exactly +1. | +| `career_bucket` | "Early" | Early ≤4, Emerging ≤9, Established ≤14, Senior >14 active years — thresholds taken unchanged from the backend's `_classify_career_stage`, empirically validated against 60 known professors/researchers. **All percentiles are computed against the same bucket only.** | +| `n_works` | 12 | Works in the extract. | +| `suspicious_profile` | false | Merged-identity flag (first year <1970 or span >60). True ⇒ treat evidence as low-confidence; ~18% of Seniors carry it. | + +### Bridger metrics (network structure) + +| field | example | what it measures | +|---|---|---| +| `betweenness` | 0 | **Betweenness centrality** on the cohort-internal graph: how often the strongest connection paths between other cohort members run *through you*. High = the network's traffic must pass you = you connect groups. Edge weights are "closeness", so paths use inverted weights as distances. A 0 is normal early-career; the percentile can still be ~0.44 because most of the bucket is also 0 and ties share their average rank. | +| `constraint` → `brokerage` | 0.085 → 0.915 | **Burt's constraint** looks only at your *ego network* (you + your co-authors): do your contacts also know each other? High constraint = you sit inside one dense clique. Low = your contacts live in separate worlds and *you* are the only link — you span "structural holes". Stored as `brokerage = 1 − constraint` so higher = more bridging. Computed on the **full graph including external co-authors**, so it sees outward bridging that internal betweenness can't. In the example: 82 co-authors who barely know each other — 90th percentile of the Early bucket. | +| `field_entropy` | 0.98 | Shannon entropy over the scientific fields of the person's papers. 0 = monodisciplinary; 1.0 bit ≈ two fields evenly; 2.0 ≈ four. Topical breadth as a proxy for interdisciplinary bridging (OpenAlex has no faculty structure, so this is the honest substitute — it must never be presented as "bridges faculties"). | +| `cross_institution_share` | 0.85 | Share of collaboration weight with co-authors sharing *no* institution with the person — external orientation. | +| `strength`, `n_coauthors` | 8.25, 82 | Total decayed edge weight and distinct co-author count — "reach", context only, not scored directly. | + +### Mentor metrics + +OpenAlex has no supervision records and debut years are unreliable, so the mentor +signals are built on **`active_years_at(person, year)`** — how many active years +someone had accumulated *as of a given year* — which inherits the robustness of +`active_years` (a spurious 1893 paper shifts it by exactly 1, not 120). + +| field | definition | +|---|---| +| `juniors_mentored` | Count of cohort co-authors who, in the year of their *first* joint paper, had ≤4 active years (Early) **while the focal person had ≥10** (Established+). A seniority-*gap* criterion — two PhD students co-publishing never counts. | +| `junior_progression_rate` | Of those juniors, the fraction who later reached ≥5 active years — separates "grew them up" from "co-signed once". `null` = no juniors = not applicable (excluded from scoring, not counted against the person). | +| `last_author_with_junior_first` | Papers where the person is **last author** with an Early-career **first author** — the classic supervision signature (student first, PI last). Deliberately independent of the gap logic: when the two disagree (37 "juniors" but zero last-author papers) that's the core-facility-scientist pattern, not a mentor. | +| `mentoring_rate` | juniors ÷ own active years. Without a rate, prolific seniors win on volume alone (professor median 224 papers vs 11 for researchers). | + +Mentor metrics are computed **only between cohort members**: external co-authors' +histories are truncated to shared works, so an external senior would masquerade as a +junior. This scope restriction is a data-correctness requirement, not a choice. + +### Amplifier metrics + +| field | source & link quality | +|---|---| +| `industry_coauthor_share` | Share of typed works with ≥1 company-affiliated co-author. The strongest industry signal available because it's **institution-ID-linked** — no name matching. Kept raw for transparency. | +| `industry_coauthor_share_shrunk` | The **scored** variant: company ÷ (typed + 5). Why: with raw shares, someone with 2-of-2 company papers gets share 1.0 and beats someone with 40-of-80 — before this fix, the index's entire top-10 "amplifiers" were such small-denominator artifacts. The +5 makes small samples humble. | +| `patent_count` | From `org_patents`, which links patents to OpenAlex author IDs. Only high-confidence matches (`match_type` = institution/both) are scored. | +| `patent_count_name_only` | Name-only patent matches — **evidence only, never scored**. | +| `news_mentions` | University press corpus, LLM-extracted names, matched after normalizing case and diacritics (René = rene). If a normalized name belongs to *two* cohort people, **nobody** gets credit (839 names skipped at UDE) — miscrediting is worse than missing. Hence the low weight. | +| `cordis_eu_projects` | Distinct EU projects joined by **DOI overlap** (the person's paper DOIs ∩ DOIs attached to CORDIS project publications) — no name matching. Matching is case-insensitive because 21% of CORDIS DOIs contain uppercase. | + +### Founder potential (`founding.*`, `founding_features.*`) + +A different kind of field from everything above. The three archetypes are +*behavioural definitions we wrote and can defend line by line*; this block is the +output of **pre-trained models** from +[`../founding_potential`](../../founding_potential), run over the cohort and +attached to the same document. + +**Lineage:** the first integration (2026-08-06) ran the v1 classifier and this +pipeline's verification caught it behaving as an inverse-productivity score +(1 publication → P=0.996, 800 → 0.0002; cause: asymmetric observation windows in +training). The upstream package was rebuilt on a symmetric landmark design and +this module now runs the **v2 bundles** exclusively +(`production/classifier_symmetric`). v1 remains on disk, referenced by nothing. + +| bundle | role | honest OOF performance | +|---|---|---| +| `founder_classifier_v2` | founder propensity vs a fixed reference cohort | ROC-AUC 0.866 / PR-AUC 0.726 | +| `p_within_{1,3,5}y_v2` | founds within k years of the index | ROC-AUC 0.85–0.86 | +| `transformer` + `lstm` | how far into a career the pattern looks founding-like (point estimate only) | MAE 0.180 / 0.208 | + +**These are deliberately NOT a fourth sub-score.** Bridger/mentor/amplifier are +percentiles *within a career bucket of this cohort*; `founding.percentile` is a +percentile *against the fixed external reference cohort* (~9k academics from the +8 training institutions, out-of-fold scores). Same word, different comparison +set — so it lives in its own flat, explicitly-mapped namespace that a backend +can filter and range-query directly: + +```jsonc +// "mentors above the 90th percentile for founding within 3 years" +{"bool": {"filter": [ + {"term": {"tags": "mentor"}}, + {"term": {"founding.in_population": true}}, + {"range": {"founding.p_within_3y_percentile": {"gte": 90}}} +]}} +``` + +| field | meaning | +|---|---| +| `founding.percentile` | **The coach-facing number.** Rank of the person's propensity score against the reference cohort, 0–100. `null` when out of population — such rows must not be ranked. | +| `founding.probability_raw` | Raw case-control output behind the percentile. Training base rate ~26% founders — **not** a population founding probability; never display it as one. Diagnostics/recalibration only. | +| `founding.in_population` | v2's population guard (≥4 publications, owned by the wrapper). Below it the training classes come from clashing sampling frames ("long career + tiny record" read as 65–72% founder) and scores are not evidence. | +| `founding.p_within_{1,3,5}y_percentile` | Same construction per horizon bundle: "founds within k years of the index", percentile vs that bundle's reference cohort. All three discriminate (v1's saturated-at-1.0 fields are retired). | +| `founding.p_within_{1,3,5}y_raw` | The horizons' raw case-control outputs — same caveat as `probability_raw`. | +| `founding.predicted_founding_age` (`_cross_check`) | Transformer (and LSTM) estimate of *how far into a career* this activity pattern looks like a founding moment. Point estimate only; guarded by `timing_applicable`. | +| `founding.current_career_age` | `as_of_year − first_publication_year`. | +| `founding.years_to_founding` | `predicted_founding_age − current_career_age`. ≤ 0 means the profile already looks like a founding-moment profile. | +| `founding.timing_applicable` | False outside a 1–20 year career age (the only regime the sequence models were trained on) **and** for `suspicious_profile` authors — the timing output is anchored on `first_publication_year`, precisely the field this repo found unreliable for merged profiles. | +| `founding.as_of_year` | The index/scoring year — the corpus's newest publication year, not the wall clock, so a re-run on an unchanged extract is byte-identical. | +| `founding.classifier_model`, `.timing_model`, `.timing_cross_check_model` | Which bundles produced the numbers, so a later swap stays attributable. | +| `founding.patent_source` | `api` or `org_patents` — which patent link quality produced the patent features. Stamped per document because the two differ ~12x in recall, so scores computed under different sources are not comparable. | +| `founding_features.*` | The exact v2 input record — publications, patents, grants (raw **and** `grants_capped`, the de-inflated value the model effectively used), first-activity years, industry collaborations, research areas. A coach questioning a score reads the evidence rather than trusting the number. Citation metrics are gone by design: v2 excludes them as non-historicizable. | + +Two feature-sourcing decisions worth knowing: + +- **Patents are stamped per document; the production `api` mode merges both + sources.** The name-matched EPO+USPTO endpoint reaches 115 of 9,474 authors + (1.2%; ~20–65 min, cached per cohort, persistent gaps recorded as + `failed_ids`), org_patents 55 (0.6%) — and they overlap on only 18, so `api` + mode takes the per-author best of both (152 authors, 1.6%, stamped + `api+org_patents`; counts never summed across sources). Plain `org_patents` + exists for fast pipeline iteration only — under it the model's patent + features are zero for 99.4% of the cohort. The amplifier's own + `patent_count` stays institution-linked either way — the two answer + different questions, and both are in the document. +- **Research area is mapped, not skipped.** The classifiers were trained on + Dimensions FOR 2-digit divisions; our works carry OpenAlex fields. `founding.py` + holds an explicit 26-entry lookup table rather than passing "unknown" for + everyone — full table and per-entry judgment calls in + [RESEARCH_AREA_MAPPING.md](RESEARCH_AREA_MAPPING.md). Patents get "unknown" honestly — + the patent corpus carries IPC codes, and IPC→FOR is a project of its own. + +### Scoring plumbing + +| field | meaning | +|---|---| +| `percentiles.*` | Each raw metric's mean-rank percentile *within the career bucket*. Ties share their average rank — that's why a metric at 0 in a mostly-zero bucket shows ~0.44–0.50, not 1.0: a mass of zeros must not be rewarded. `null` metrics are excluded, and their weight is redistributed. | +| `sub_scores.{bridger,mentor,amplifier}` | Weighted means of the percentiles. Weights live in `multipliers.yaml`, never in code — coaches retune them. Current amplifier weights: shrunk share 0.50, patents 0.25, CORDIS 0.15, news 0.10. | +| `tags` | Sub-score ≥ `tags.threshold` (0.85) ⇒ tag; a person can hold 0–3. Current yield at UDE: 133 bridgers, 161 mentors, 10 amplifiers. | +| `max_sub_score` | Best sub-score — the default ranking key. | +| `evidence.junior_ids` | Receipts (which people count as mentees) — a coach never sees a bare number. | +| `config_hash`, `computed_at` | Which YAML weighting produced the score, and when. Scores are cohort-relative and weight-dependent; without this they'd be unfalsifiable after the next retune. | +| `institution_id`, `cohort_institution_ids` | Which university this doc belongs to and which 9 institutions defined its cohort. | + +Worked example (the Pakull doc): amplifier = 0.50·0.99 (shrunk share) + 0.25·0.50 +(patents, tie-mass) + 0.15·0.98 (one EU project — 98th percentile *for an +Early-career person*) + 0.10·0.47 (news) = **0.8131** — high, but under 0.85 ⇒ no +tag. Mentor 0.494 ≈ bucket median: all-zero mentor metrics in a bucket where nearly +everyone is zero lands exactly mid-pack. + +## 4. related work + +- **Co-authorship graphs as collaboration networks** — Mark Newman's early-2000s + studies of scientific collaboration networks, which also introduced the 1/(n−1) + team-size weighting. The warning that huge author lists break co-authorship + semantics is Blaise Cronin's "hyperauthorship" critique — the basis for the + 50-author cap. +- **Bridger, theory** — Granovetter's "strength of weak ties" (1973): novel + information flows across bridges between groups, not within dense cliques. +- **Bridger, operationalization** — *betweenness centrality* (Linton Freeman, 1977), + computed with Ulrik Brandes' 2001 algorithm (implemented in `metrics.py`, tested + against networkx); *structural holes and constraint* (Ronald Burt, 1992; his 2004 + "Structural holes and good ideas" showed brokers produce more good ideas). The + weights-are-distances inversion for betweenness is a standard weighted-network + practice. Shannon entropy as a diversity/interdisciplinarity indicator follows + standard scientometrics usage (Stirling-style diversity). +- **Mentor** — reading mentorship from publication genealogies is established in + scientometrics (e.g. Malmgren, Ottino & Amaral's Nature study of mentor–protégé + networks). The first-author-student / last-author-PI convention is a documented + authorship norm in the life sciences — credible at a medicine-heavy university. + Shipped caveat: co-authorship ≠ supervision; it's a proxy, validated directionally + against 60 hand-labeled people (professors' median mentor score 0.740 vs + researchers' 0.494). +- **Amplifier** — the university "third mission" / knowledge-transfer literature + (Etzkowitz & Leydesdorff's Triple Helix line): patents, industry co-publication, + joint projects as measurable transfer channels. Industry co-authorship as primary + indicator is pragmatic: it's the only channel linked by institution IDs rather + than names. +- **Fair comparison** — percentile indicators within reference groups are the modern + bibliometrics standard (compare like with like). Our reference group is the career + bucket; the buckets come from this repo's own `analysis/career_stage/` work, which + is also the empirical source for the most important design decision: rejecting + `first_publication_year` in favor of `active_years`. `active_years_at(A, Y)` is our + small extension of that finding. +- **Data-quality corrections** (all found by measuring, not assumed): the hospital + cohort gap (OpenAlex `related` vs lineage), ratio shrinkage, tie-sharing + percentiles, the news ambiguity rule, merged/split-profile flags — responses to + the well-known author-disambiguation weaknesses of bibliographic databases. + +## 5. What was achieved (status) + +Three falsifiable behavioral definitions instead of a vague label; a decay- and +team-size-weighted collaboration graph over the complete global publication history +of a correctly-defined 9-institution cohort; established network-science and +bibliometric measures, made robust against the two dominant data pathologies (merged +profiles, hyperauthorship); within-career-stage normalization; three independent +external evidence channels joined at their honest link quality; a founder-potential +layer that reuses four already-validated models rather than inventing a fourth +archetype, kept in its own absolute-valued namespace with the model authors' own +applicability caveats encoded as queryable flags; and a queryable index where every +person carries raw values, percentiles, scores, tags, model outputs and receipts — +validated against hand-labeled ground truth, every tunable in config, every score +stamped with the config that produced it. + +| Milestone | Status | +|---|---| +| M0 — de-risking spike against the real cluster | ✅ done | +| M1 — graph + metrics + scoring core, 60-person validation | ✅ done (PASS) | +| M2 — cohort fix, extraction module, idempotent `multiplicators_v1` indexing | ✅ done | +| M3 — amplifier signal joins (patents / news / CORDIS) + shrinkage fix | ✅ wired & indexed | +| M3b — founder-potential enrichment (v1 integrated → found miscalibrated by this pipeline's verification → v2 symmetric bundles + name-matched patents, queryable percentile fields) | ✅ wired & indexed | + +## 6. Roadmap — what's next + +1. **M3 calibration session (human, next).** Coaches provide a golden set of 10–20 + known multiplicators, ideally labeled by type. Tune `multipliers.yaml` + (sub-score weights, per-tag thresholds — 0.85 currently yields 133/161/10 + bridger/mentor/amplifier tags; if more amplifier candidates are wanted, introduce + per-tag thresholds). Re-run `validate_sample.py` after every change as regression. +2. **M4 — read-only serving layer**, once the UI needs it: thin FastAPI router in + `inse/multiplicators/` over BOTH indices — `multiplicators_v1` for list views + (by tag/bucket/score + per-person evidence) and `multiplicator_networks_v1` for + the ego-network visualization (one doc per author: nodes with roles, edges with + tie strength/cross-institution flags, ego header — render with echarts force + layout; see README "Network visualization index"). Then + `./gradlew :service:exportOpenApiSpec` to regenerate the Angular client. + The `founding.*` fields are mapped for exactly this: every one is an + explicitly-typed scalar, so tag + probability + horizon compose into a single + filtered query (§3, "Founder potential") with no scripting and no re-ranking + in the router. +3. **Scheduling** — re-run `build.py` per dump refresh (Airflow, like the other + crawlers); scores are batch-computed, serving is read-only. +4. **Deferred improvements**, in value order: + - **ORCID / `ude_persons_1.0` bridge** — the single highest-value follow-up: fixes + news linking, catches *split* profiles (the `suspicious_profile` flag only + catches merges; one split-profile artifact sits in the current amplifier + top-10), and would enable faculty-level bridging via the staff directory. + - Per-field percentile cohorts (biologist baselines ≠ sociologist baselines) — + decide with coaches. + - Project layer as graph edges (consortium co-membership), DFG/Bund signals if a + real person-link ever exists. + - Committing the module (currently untracked on `feature/find-multipliers`). diff --git a/service/scripts/profiling/multipliers/extract.py b/service/scripts/profiling/multipliers/extract.py new file mode 100644 index 00000000..e5509910 --- /dev/null +++ b/service/scripts/profiling/multipliers/extract.py @@ -0,0 +1,418 @@ +#!/usr/bin/env python3 +""" +extract.py — cohort-aware extraction of the author + work sets from Elasticsearch. + +Canonical home of the extraction logic (spike_audit.py and build.py both use it). + +The author set is a UNION OF TWO QUERIES — group 2 recovers ~4% of authors that +group 1 silently drops: + 1. backend_compatible last_known_institutions in the cohort AND a recent + cohort affiliation + 2. empty_last_known_recent recent cohort affiliation but NO last_known_institutions + +The cohort is `cohorts..institution_ids` from the YAML; OpenAlex does +not model university hospitals as lineage children, so the primary id alone +loses the clinical faculty (docs/ASSOCIATED_INSTITUTIONS.md). + +The work set is ALL works by those authors, globally, with full authorship lists +— without the external co-authors there is no bridging signal. +""" +from __future__ import annotations + +import gzip +import json +import os +import time +from pathlib import Path +from typing import Any, Iterable, Iterator + +import httpx +import yaml +from dotenv import load_dotenv + +SCRIPT_DIR = Path(__file__).resolve().parent + + +def _find_env() -> Path: + """Locate service/src/main/inse/.env by walking up from this file. + + A walk rather than fixed `.parent` hops: this module has moved once, and a + hard-coded hop count fails only at run time as "Missing NES credentials". + """ + relative = Path("src") / "main" / "inse" / ".env" + for directory in SCRIPT_DIR.parents: + candidate = directory / relative + if candidate.exists(): + return candidate + return SCRIPT_DIR / relative # not found; load_dotenv is a no-op, error surfaces later + + +ENV_PATH = _find_env() +load_dotenv(dotenv_path=ENV_PATH) + +NES_URL = (os.environ.get("ELASTICSEARCH_URL") or "").rstrip("/") +NES_KEY = os.environ.get("ELASTICSEARCH_API_KEY") or "" +INSE_URL = (os.environ.get("ELASTICSEARCH_INSE_URL") or "").rstrip("/") +INSE_KEY = os.environ.get("ELASTICSEARCH_INSE_API_KEY") or "" + +AUTHOR_PAGE_SIZE = 1000 +AUTHOR_BATCH_SIZE = 250 +WORK_PAGE_SIZE = 1000 +REQUEST_TIMEOUT = 180.0 + + +# --------------------------------------------------------------------- +# ES helpers +# --------------------------------------------------------------------- + + +def _headers(api_key: str) -> dict[str, str]: + return { + "Authorization": f"ApiKey {api_key}", + "Content-Type": "application/json", + "Accept": "application/json", + } + + +def es_request( + client: httpx.Client, + method: str, + base_url: str, + api_key: str, + path: str, + body: dict[str, Any] | None = None, +) -> httpx.Response: + url = f"{base_url}/{path.lstrip('/')}" + return client.request( + method, url, headers=_headers(api_key), json=body, timeout=REQUEST_TIMEOUT + ) + + +def es_search( + client: httpx.Client, base_url: str, api_key: str, index: str, body: dict[str, Any] +) -> dict[str, Any]: + response = es_request(client, "POST", base_url, api_key, f"{index}/_search", body) + if not response.is_success: + raise RuntimeError( + f"ES error {response.status_code} for {index}:\n{response.text[:1000]}" + ) + return response.json() + + +# --------------------------------------------------------------------- +# Config / cohort +# --------------------------------------------------------------------- + + +def load_config(path: str | Path) -> dict[str, Any]: + with open(path, "r", encoding="utf-8") as f: + return yaml.safe_load(f) or {} + + +def cohort_ids_for(config: dict[str, Any], primary_short_id: str) -> list[str]: + cohort = (config.get("cohorts") or {}).get(primary_short_id) or {} + ids = cohort.get("institution_ids") + return [str(i) for i in ids] if ids else [primary_short_id] + + +def resolve_institution(client: httpx.Client, institution_id: str) -> dict[str, Any]: + """Look up ror + display_name from openalex-institutions.""" + short = institution_id.strip().rsplit("/", 1)[-1] + full = f"https://openalex.org/{short}" + result = es_search( + client, NES_URL, NES_KEY, "openalex-institutions", + {"size": 1, "query": {"term": {"id": full}}}, + ) + hits = result["hits"]["hits"] + if not hits: + raise SystemExit(f"Institution {full} not found in openalex-institutions.") + source = hits[0]["_source"] + return { + "id": full, + "short_id": short, + "ror": source.get("ror"), + "display_name": source.get("display_name"), + } + + +# --------------------------------------------------------------------- +# Author queries +# --------------------------------------------------------------------- + + +def recent_affiliation_filter( + insts: list[dict[str, Any]], year_gte: int +) -> dict[str, Any]: + """Recent affiliation with ANY cohort institution (matched by id, ror as backup).""" + ids = [i["id"] for i in insts] + shoulds: list[dict[str, Any]] = [{"terms": {"affiliations.institution.id": ids}}] + rors = [i["ror"] for i in insts if i.get("ror")] + if rors: + shoulds.append({"terms": {"affiliations.institution.ror": rors}}) + return { + "nested": { + "path": "affiliations", + "query": { + "bool": { + "filter": [ + {"bool": {"should": shoulds, "minimum_should_match": 1}}, + {"range": {"affiliations.years": {"gte": year_gte}}}, + ] + } + }, + } + } + + +def last_known_filter(insts: list[dict[str, Any]]) -> dict[str, Any]: + return { + "nested": { + "path": "last_known_institutions", + "query": { + "terms": {"last_known_institutions.id": [i["id"] for i in insts]} + }, + } + } + + +def last_known_exists_filter() -> dict[str, Any]: + return { + "nested": { + "path": "last_known_institutions", + "query": {"exists": {"field": "last_known_institutions.display_name"}}, + } + } + + +AUTHOR_SOURCE = [ + "id", + "display_name", + "orcid", + "works_count", + "cited_by_count", + "summary_stats", # h_index / i10_index — free here, not from the works + "last_known_institutions", + "affiliations", +] + + +def collect_authors( + client: httpx.Client, + insts: list[dict[str, Any]], + affiliation_year_gte: int, +) -> dict[str, dict[str, Any]]: + groups = { + "backend_compatible": { + "bool": { + "filter": [ + last_known_filter(insts), + recent_affiliation_filter(insts, affiliation_year_gte), + ] + } + }, + "empty_last_known_recent": { + "bool": { + "filter": [recent_affiliation_filter(insts, affiliation_year_gte)], + "must_not": [last_known_exists_filter()], + } + }, + } + + authors: dict[str, dict[str, Any]] = {} + for group_name, query in groups.items(): + search_after = None + total = None + read = 0 + while True: + body: dict[str, Any] = { + "size": AUTHOR_PAGE_SIZE, + "track_total_hits": True, + "_source": AUTHOR_SOURCE, + "query": query, + "sort": [{"id": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + result = es_search(client, NES_URL, NES_KEY, "openalex-authors", body) + hits = result["hits"]["hits"] + if total is None: + total = result["hits"]["total"]["value"] + print(f" [{group_name}] expected {total}") + if not hits: + break + for hit in hits: + src = hit["_source"] + aid = src.get("id") + if not aid: + continue + if aid not in authors: + stats = src.get("summary_stats") or {} + authors[aid] = { + "id": aid, + "display_name": src.get("display_name"), + "orcid": src.get("orcid"), + "works_count": src.get("works_count"), + "cited_by_count": src.get("cited_by_count"), + "h_index": stats.get("h_index"), + "i10_index": stats.get("i10_index"), + # count only — the list would bloat the cache + "n_affiliations": len(src.get("affiliations") or []), + "source_sets": [group_name], + } + elif group_name not in authors[aid]["source_sets"]: + authors[aid]["source_sets"].append(group_name) + read += 1 + search_after = hits[-1]["sort"] + print(f" [{group_name}] read {read}/{total}") + time.sleep(0.05) + return authors + + +# --------------------------------------------------------------------- +# Work queries — FULL authorships, no inner_hits +# --------------------------------------------------------------------- + +WORK_SOURCE = [ + "id", + "doi", + "publication_year", + "type", + "cited_by_count", + "primary_topic.id", + "primary_topic.display_name", + "primary_topic.field.id", + "primary_topic.field.display_name", + "authorships.author.id", + "authorships.author.display_name", + "authorships.author_position", + "authorships.is_corresponding", + "authorships.institutions.id", + "authorships.institutions.display_name", + "authorships.institutions.type", + "authorships.institutions.country_code", + "authorships.institutions.lineage", + # nested fields: dotted _source paths work, only QUERIES need a nested wrapper + "awards.id", + "awards.funder_id", + "funders.id", +] + + +def collect_works( + client: httpx.Client, author_ids: list[str], work_year_gte: int +) -> dict[str, dict[str, Any]]: + works: dict[str, dict[str, Any]] = {} + total_batches = (len(author_ids) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE + for i in range(0, len(author_ids), AUTHOR_BATCH_SIZE): + batch = author_ids[i : i + AUTHOR_BATCH_SIZE] + batch_no = i // AUTHOR_BATCH_SIZE + 1 + search_after = None + while True: + body: dict[str, Any] = { + "size": WORK_PAGE_SIZE, + "track_total_hits": True, + "_source": WORK_SOURCE, + "query": { + "bool": { + "filter": [ + {"range": {"publication_year": {"gte": work_year_gte}}}, + { + "nested": { + "path": "authorships", + "query": { + "terms": {"authorships.author.id": batch} + }, + } + }, + ] + } + }, + "sort": [{"id": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + result = es_search(client, NES_URL, NES_KEY, "openalex-works*", body) + hits = result["hits"]["hits"] + if not hits: + break + for hit in hits: + src = hit["_source"] + wid = src.get("id") + if wid and wid not in works: + works[wid] = src + search_after = hits[-1]["sort"] + print(f" work batch {batch_no}/{total_batches}: unique works {len(works)}") + time.sleep(0.05) + return works + + +# --------------------------------------------------------------------- +# Cache IO +# --------------------------------------------------------------------- + + +def write_jsonl_gz(path: Path, records: Iterable[dict[str, Any]]) -> None: + with gzip.open(path, "wt", encoding="utf-8", newline="\n") as f: + for record in records: + f.write(json.dumps(record, ensure_ascii=True) + "\n") + + +def read_jsonl_gz(path: Path) -> Iterator[dict[str, Any]]: + with gzip.open(path, "rt", encoding="utf-8") as f: + for line in f: + line = line.strip() + if line: + yield json.loads(line) + + +# --------------------------------------------------------------------- +# Top-level: extract to cache +# --------------------------------------------------------------------- + + +def extract_to_cache( + institution_id: str, + config: dict[str, Any], + cache_dir: Path, + force: bool = False, +) -> tuple[Path, Path, list[dict[str, Any]]]: + """Extract authors + works for the cohort to jsonl.gz caches. + + Returns (authors_path, works_path, resolved cohort institutions). Reuses an + existing cache unless force=True. + """ + if not NES_URL or not NES_KEY: + raise SystemExit(f"Missing NES credentials. Checked {ENV_PATH}") + + short = institution_id.strip().rsplit("/", 1)[-1] + cache_dir.mkdir(parents=True, exist_ok=True) + authors_path = cache_dir / f"authors_{short}.jsonl.gz" + works_path = cache_dir / f"works_{short}.jsonl.gz" + + extraction_cfg = config.get("extraction") or {} + affiliation_year_gte = int(extraction_cfg.get("affiliation_years_gte", 2023)) + work_year_gte = int(extraction_cfg.get("work_year_gte", 1950)) + + with httpx.Client() as client: + insts = [ + resolve_institution(client, i) for i in cohort_ids_for(config, short) + ] + print(f"Cohort ({len(insts)} institutions, affiliation years >= {affiliation_year_gte}):") + for inst in insts: + print(f" {inst['short_id']:<14} {inst['display_name']}") + + if not force and authors_path.exists() and works_path.exists(): + print("Reusing cached extract (use --force-extract to refresh).") + return authors_path, works_path, insts + + print("\nExtracting authors...") + authors = collect_authors(client, insts, affiliation_year_gte) + write_jsonl_gz(authors_path, authors.values()) + print(f"Authors: {len(authors)} -> {authors_path}") + + print("\nExtracting works (full authorships)...") + works_map = collect_works(client, sorted(authors.keys()), work_year_gte) + write_jsonl_gz(works_path, works_map.values()) + print(f"Works: {len(works_map)} -> {works_path}") + + return authors_path, works_path, insts diff --git a/service/scripts/profiling/multipliers/founder_dashboard.html b/service/scripts/profiling/multipliers/founder_dashboard.html new file mode 100644 index 00000000..b70904d9 --- /dev/null +++ b/service/scripts/profiling/multipliers/founder_dashboard.html @@ -0,0 +1,352 @@ +Founder potential — coach dashboard + +
+ +
+

University of Duisburg-Essen · founder potential

+

Which researchers look like future founders?

+

A model scores every researcher against ~9,000 academics from eight universities. + The score alone is not a shortlist — most of the top scorers are broken database records. + This dashboard shows the screening, then the people who survive it.

+
+ +
+
Researchers scored
9,474
+
whole cohort
+
Pass data quality
3,742
+
39% of the cohort
+
On the shortlist
7
+
score ≥ 90
+
+ +
+

1 · Why the shortlist is small

+

Each bar is what remains after one screening rule. The two middle rules exist + because OpenAlex profiles are sometimes merged or wrongly dated — and this model is unusually + sensitive to that, since a wrong first-publication year makes someone look dormant, which the + model reads as founder-like.

+
+
+ +
+

2 · The shortlist

+

Move the threshold to trade list length against confidence. Keep the screen on + for a list you can act on; switch it off to see what the raw model score would have surfaced — + the orange rows are the records that failed a data-quality rule. Click anyone to open their card.

+ +
+ + + +
+ +
+
+
+ +
+

3 · Where the candidates come from

+

Both panels use the screened shortlist at the current threshold.

+
+
+
Career stage
+
+
Bars are candidate counts; the grey figure is that stage's screened pool.
+
+
+
Research field, vs its share of the cohort
+
+
Bars are candidate counts. The grey figure is how much of the whole + screened cohort that field represents — a field well above its share is over-producing.
+
+
+
+ +
+

4 · Reading a person's numbers

+

Every researcher carries two different kinds of percentile. Mixing them up is the + most common mistake, so the card keeps them in separate panels.

+
+
+
Founder potential
+

Compared to ~9,000 academics at other universities. Answers: + does this profile resemble people who actually founded companies?

+
    +
  • Score — the headline rank, 0–100.
  • +
  • Within 1 / 3 / 5 years — three separate models asking "does this look like + someone that many years before founding?" Read the shape: 1-year highest means soon.
  • +
+
+
+
Multiplier roles
+

Compared to peers at this university, at the same career stage. Answers: + what does this person do for the people around them?

+
    +
  • Mentor — juniors start their careers publishing with them.
  • +
  • Bridger — connects groups that otherwise would not meet.
  • +
  • Amplifier — patents, industry work, press, EU projects.
  • +
+
+
+

These two rarely overlap: the multiplier roles pick out + established, prolific people, while the founder model favours focused mid-career profiles. + Of the 7 shortlisted researchers, none carries a multiplier badge.

+
+ +
+ + diff --git a/service/scripts/profiling/multipliers/founding.py b/service/scripts/profiling/multipliers/founding.py new file mode 100644 index 00000000..1d4cc79d --- /dev/null +++ b/service/scripts/profiling/multipliers/founding.py @@ -0,0 +1,459 @@ +#!/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 diff --git a/service/scripts/profiling/multipliers/founding_stats.py b/service/scripts/profiling/multipliers/founding_stats.py new file mode 100644 index 00000000..262d8670 --- /dev/null +++ b/service/scripts/profiling/multipliers/founding_stats.py @@ -0,0 +1,472 @@ +#!/usr/bin/env python3 +""" +founding_stats.py — statistical evaluation of the founder-potential fields in +`multiplicators_v1`, next to the multiplicator archetypes. + +Reads the LIVE index (same precedent as make_report.py) and prints markdown: +cohort overview, percentile distribution per career stage, the founder +shortlist (plain and with the `publications >= 7` robustness co-filter that +screens the measured population-boundary artifact), overlap with the three +archetypes, research-area composition, and factor importance (the v2 model's +permutation importances next to local Spearman correlations). + +There is deliberately no binary "is a founder": v2 emits a percentile, and the +shortlist cutoff is operational (--threshold, default 90). + +Usage (repo root): + conda run -n potential python -m service.scripts.profiling.multipliers.founding_stats \ + --institution-id I62318514 + ... --threshold 75 --min-pubs 7 # different shortlist definition + ... --out service/scripts/profiling/multipliers/stats_generated.md +""" +from __future__ import annotations + +import argparse +import csv +import math +from pathlib import Path +from typing import Any, Iterable + +from service.scripts.profiling.multipliers.index import ( + MULTIPLICATORS_INDEX, + MultiplicatorsIndexClient, +) + +SCRIPT_DIR = Path(__file__).resolve().parent + +# Dimensions FOR 2-digit division names — only what founding.py can produce. +FOR_NAMES = { + "30": "Agricultural, Veterinary & Food Sciences", + "31": "Biological Sciences", + "32": "Biomedical & Clinical Sciences", + "34": "Chemical Sciences", + "35": "Commerce, Management, Tourism & Services", + "36": "Creative Arts & Writing", + "37": "Earth Sciences", + "38": "Economics", + "40": "Engineering", + "41": "Environmental Sciences", + "42": "Health Sciences", + "44": "Human Society", + "46": "Information & Computing Sciences", + "49": "Mathematical Sciences", + "51": "Physical Sciences", + "52": "Psychology", + "n.": "unknown / not classified", +} + +BUCKET_ORDER = ["Early", "Emerging", "Established", "Senior"] + +DOC_FIELDS = [ + "author_id", "display_name", "career_bucket", "active_years", "n_works", + "suspicious_profile", "tags", "sub_scores", "founding", "founding_features", + "news_mentions", +] + + +# --------------------------------------------------------------------- +# data access +# --------------------------------------------------------------------- + + +def fetch_rows(institution_id: str) -> list[dict[str, Any]]: + """All docs for the institution via search_after (same pagination pattern + as index.py's id collector).""" + es = MultiplicatorsIndexClient() + rows: list[dict[str, Any]] = [] + search_after = None + while True: + body: dict[str, Any] = { + "size": 1000, + "_source": DOC_FIELDS, + "query": {"term": {"institution_id": institution_id}}, + "sort": [{"author_id": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + r = es._request("POST", f"{MULTIPLICATORS_INDEX}/_search", json=body) + r.raise_for_status() + hits = r.json()["hits"]["hits"] + if not hits: + break + rows.extend(h["_source"] for h in hits) + search_after = hits[-1]["sort"] + return rows + + +# --------------------------------------------------------------------- +# small stats helpers (pure python — no pandas for a report tool) +# --------------------------------------------------------------------- + + +def quantile(sorted_values: list[float], q: float) -> float: + if not sorted_values: + return float("nan") + pos = q * (len(sorted_values) - 1) + lo, hi = int(math.floor(pos)), int(math.ceil(pos)) + if lo == hi: + return sorted_values[lo] + frac = pos - lo + return sorted_values[lo] * (1 - frac) + sorted_values[hi] * frac + + +def _ranks(values: list[float]) -> list[float]: + """Average ranks with tie handling (for Spearman).""" + order = sorted(range(len(values)), key=lambda i: values[i]) + ranks = [0.0] * len(values) + i = 0 + while i < len(order): + j = i + while j + 1 < len(order) and values[order[j + 1]] == values[order[i]]: + j += 1 + mean_rank = (i + j) / 2 + 1 + for k in range(i, j + 1): + ranks[order[k]] = mean_rank + i = j + 1 + return ranks + + +def spearman(xs: list[float], ys: list[float]) -> float: + """Spearman rank correlation, pure python. NaN-free inputs expected.""" + if len(xs) < 3: + return float("nan") + rx, ry = _ranks(xs), _ranks(ys) + mx = sum(rx) / len(rx) + my = sum(ry) / len(ry) + cov = sum((a - mx) * (b - my) for a, b in zip(rx, ry)) + vx = math.sqrt(sum((a - mx) ** 2 for a in rx)) + vy = math.sqrt(sum((b - my) ** 2 for b in ry)) + return cov / (vx * vy) if vx and vy else float("nan") + + +def md_table(headers: list[str], rows: Iterable[Iterable[Any]]) -> str: + lines = ["| " + " | ".join(str(h) for h in headers) + " |", + "|" + "|".join("---" for _ in headers) + "|"] + for row in rows: + lines.append("| " + " | ".join(str(c) for c in row) + " |") + return "\n".join(lines) + + +def pct(part: int, whole: int) -> str: + return f"{100 * part / whole:.1f}%" if whole else "–" + + +# --------------------------------------------------------------------- +# report sections +# --------------------------------------------------------------------- + + +def section_overview(rows: list[dict[str, Any]]) -> str: + n = len(rows) + in_pop = [r for r in rows if r["founding"]["in_population"]] + timing = sum(1 for r in rows if r["founding"]["timing_applicable"]) + with_pat = sum(1 for r in rows if (r["founding_features"].get("patents") or 0) >= 1) + sources = sorted({r["founding"]["patent_source"] for r in rows}) + buckets = {b: 0 for b in BUCKET_ORDER} + for r in rows: + buckets[r["career_bucket"]] = buckets.get(r["career_bucket"], 0) + 1 + out = [ + "## 1. Cohort overview", + "", + md_table( + ["", "n", "share"], + [ + ["documents", n, "100%"], + ["`founding.in_population` (≥4 publications)", len(in_pop), pct(len(in_pop), n)], + ["`founding.timing_applicable`", timing, pct(timing, n)], + ["≥1 patent (`founding_features.patents`)", with_pat, pct(with_pat, n)], + ["patent provenance", ", ".join(sources), ""], + ], + ), + "", + md_table( + ["career stage", "n", "share"], + [[b, buckets[b], pct(buckets[b], n)] for b in BUCKET_ORDER], + ), + ] + return "\n".join(out) + + +def _pctl(r: dict[str, Any]) -> float | None: + return r["founding"].get("percentile") + + +def section_percentile_by_stage(rows: list[dict[str, Any]], min_pubs: int) -> str: + out = ["## 2. Founding percentile by career stage (in population)", ""] + table = [] + for b in BUCKET_ORDER + ["ALL"]: + sub = [ + r for r in rows + if r["founding"]["in_population"] and (b == "ALL" or r["career_bucket"] == b) + ] + vals = sorted(v for v in (_pctl(r) for r in sub) if v is not None) + if not vals: + continue + table.append([ + b, len(vals), + f"{quantile(vals, 0.50):.1f}", f"{quantile(vals, 0.90):.1f}", + sum(1 for v in vals if v >= 75), sum(1 for v in vals if v >= 90), + ]) + out.append(md_table( + ["career stage", "n (in pop.)", "pctl p50", "pctl p90", "n ≥75", "n ≥90"], table)) + out.append("") + out.append(f"Same, restricted to `publications >= {min_pubs}` " + f"(screens the population-boundary artifact):") + table = [] + for b in BUCKET_ORDER + ["ALL"]: + sub = [ + r for r in rows + if r["founding"]["in_population"] + and (r["founding_features"].get("publications") or 0) >= min_pubs + and (b == "ALL" or r["career_bucket"] == b) + ] + vals = sorted(v for v in (_pctl(r) for r in sub) if v is not None) + if not vals: + continue + table.append([ + b, len(vals), + f"{quantile(vals, 0.50):.1f}", f"{quantile(vals, 0.90):.1f}", + sum(1 for v in vals if v >= 75), sum(1 for v in vals if v >= 90), + ]) + out.append(md_table( + ["career stage", "n", "pctl p50", "pctl p90", "n ≥75", "n ≥90"], table)) + return "\n".join(out) + + +def _shortlists(rows, threshold, min_pubs): + plain = [r for r in rows if (_pctl(r) or 0) >= threshold] + robust = [r for r in plain + if (r["founding_features"].get("publications") or 0) >= min_pubs] + return plain, robust + + +def section_shortlist(rows, threshold, min_pubs) -> str: + plain, robust = _shortlists(rows, threshold, min_pubs) + out = [f"## 3. The shortlist: founding percentile ≥ {threshold}", ""] + table = [] + for b in BUCKET_ORDER: + n_plain = sum(1 for r in plain if r["career_bucket"] == b) + n_robust = sum(1 for r in robust if r["career_bucket"] == b) + table.append([b, n_plain, n_robust]) + table.append(["**ALL**", len(plain), len(robust)]) + out.append(md_table( + ["career stage", f"pctl ≥{threshold}", f"… AND pubs ≥{min_pubs} (robust)"], + table)) + out.append("") + out.append( + f"The gap between the columns is the measured boundary artifact: " + f"{len(plain) - len(robust)} of {len(plain)} shortlisted profiles have " + f"fewer than {min_pubs} publications (long-dormant / fragment profiles " + f"scoring just above the ≥4 population cut)." + ) + return "\n".join(out) + + +def section_archetype_overlap(rows, threshold, min_pubs) -> str: + plain, robust = _shortlists(rows, threshold, min_pubs) + out = ["## 4. Founder potential × multiplicator archetypes", ""] + + def tag_counts(subset): + counts = {"mentor": 0, "bridger": 0, "amplifier": 0, "none": 0} + for r in subset: + tags = r.get("tags") or [] + if not tags: + counts["none"] += 1 + for t in tags: + if t in counts: + counts[t] += 1 + return counts + + tp, tr = tag_counts(plain), tag_counts(robust) + out.append(md_table( + ["", "mentor tag", "bridger tag", "amplifier tag", "no tag"], + [[f"shortlist (≥{threshold})", tp["mentor"], tp["bridger"], tp["amplifier"], tp["none"]], + [f"robust shortlist (pubs ≥{min_pubs})", tr["mentor"], tr["bridger"], tr["amplifier"], tr["none"]]], + )) + out.append("") + out.append("Tags fire for ~3% of the cohort, so the softer view — sub-score " + "≥ 0.7 within the person's career bucket — shows the overlap " + "structure better:") + table = [] + for label, subset in [(f"shortlist (≥{threshold})", plain), + (f"robust (pubs ≥{min_pubs})", robust)]: + row = [label, len(subset)] + for sub_name in ("mentor", "bridger", "amplifier"): + row.append(sum(1 for r in subset + if (r.get("sub_scores") or {}).get(sub_name, 0) >= 0.7)) + table.append(row) + out.append(md_table(["", "n", "mentor ≥0.7", "bridger ≥0.7", "amplifier ≥0.7"], table)) + out.append("") + out.append("And the reverse direction — the founding percentile of the tagged " + "multiplicators (why round thresholds select nobody):") + table = [] + for tag in ("mentor", "bridger", "amplifier"): + tagged = [r for r in rows + if tag in (r.get("tags") or []) and r["founding"]["in_population"]] + vals = sorted(v for v in (_pctl(r) for r in tagged) if v is not None) + if not vals: + table.append([tag, 0, "–", "–", 0]) + continue + table.append([tag, len(vals), f"{quantile(vals, 0.5):.0f}", + f"{quantile(vals, 0.9):.0f}", + sum(1 for v in vals if v >= 40)]) + out.append(md_table( + ["tagged as", "n (in pop.)", "founding pctl p50", "p90", "n ≥40"], table)) + return "\n".join(out) + + +def section_areas(rows, threshold, min_pubs) -> str: + plain, robust = _shortlists(rows, threshold, min_pubs) + cohort = [r for r in rows if r["founding"]["in_population"]] + + def area_counts(subset): + counts: dict[str, int] = {} + for r in subset: + area = (r["founding_features"].get("publication_research_area")) or "n." + counts[area] = counts.get(area, 0) + 1 + return counts + + ca, pa, ra = area_counts(cohort), area_counts(plain), area_counts(robust) + areas = sorted(ca, key=lambda a: -ca[a])[:10] + out = ["## 5. Research areas (FOR division, from OpenAlex publication fields)", ""] + table = [] + for a in areas: + table.append([ + f"{a} {FOR_NAMES.get(a, '')}", + f"{ca.get(a, 0)} ({pct(ca.get(a, 0), len(cohort))})", + f"{pa.get(a, 0)} ({pct(pa.get(a, 0), len(plain))})", + f"{ra.get(a, 0)} ({pct(ra.get(a, 0), len(robust))})", + ]) + out.append(md_table( + ["area", "cohort (in pop.)", f"shortlist ≥{threshold}", f"robust (pubs ≥{min_pubs})"], + table)) + return "\n".join(out) + + +def section_factors(rows, min_pubs: int) -> str: + out = ["## 6. Which factors drive founder identification", "", + "### 6a. The model's own permutation importances (training-side truth)", ""] + imp_path = (SCRIPT_DIR.parent / "founding_potential" / "results" + / "rq1_symmetric" / "permutation_importance.csv") + if imp_path.exists(): + with open(imp_path, newline="", encoding="utf-8") as f: + imp = list(csv.DictReader(f))[:12] + out.append(md_table( + ["feature", "importance (mean ROC-AUC drop)"], + [[r["feature"], f"{float(r['importance_mean']):.3f}"] for r in imp])) + out.append("") + out.append( + "⚠️ Deployment caveat: the top feature `patent_research_area_n.` is " + "CONSTANT in this index — our corpus has no IPC→FOR mapping, so every " + "record (patent holders included) carries `patent_research_area = " + "\"n.\"`. Locally that feature separates nothing, and the 152 patent " + "holders sit slightly off the training manifold (patents present but " + "no patent area). Mapping IPC→FOR (the backend's " + "`ipc_openalex_mapping` is a starting point) would unlock the " + "model's #1 and #8 features." + ) + else: + out.append(f"(permutation_importance.csv not found at {imp_path})") + + out += ["", "### 6b. Local Spearman rank correlation with `founding.percentile`", ""] + in_pop = [r for r in rows if r["founding"]["in_population"] and _pctl(r) is not None] + ref_year = in_pop[0]["founding"]["as_of_year"] if in_pop else 2026 + candidates = { + "publications": lambda r: r["founding_features"].get("publications"), + "pub_rate (pubs/career age)": lambda r: ( + (r["founding_features"].get("publications") or 0) + / max(1, ref_year - (r["founding_features"].get("first_publication_year") or ref_year)) + ), + "career_age": lambda r: r["founding"].get("current_career_age"), + "active_years": lambda r: r.get("active_years"), + "activity density (active_years/career_age)": lambda r: ( + (r.get("active_years") or 0) + / max(1, r["founding"].get("current_career_age") or 1) + ), + "patents": lambda r: r["founding_features"].get("patents"), + "grants_capped": lambda r: r["founding_features"].get("grants_capped"), + "industry_collab_papers": lambda r: r["founding_features"].get("industry_collab_papers"), + "news_mentions": lambda r: r.get("news_mentions") if "news_mentions" in r else 0, + "sub_score mentor": lambda r: (r.get("sub_scores") or {}).get("mentor"), + "sub_score bridger": lambda r: (r.get("sub_scores") or {}).get("bridger"), + "sub_score amplifier": lambda r: (r.get("sub_scores") or {}).get("amplifier"), + } + def corr_rows(subset): + y = [float(_pctl(r) or 0) for r in subset] # subset pre-filtered to non-None + return { + name: spearman([float(g(r) or 0) for r in subset], y) + for name, g in candidates.items() + } + + robust = [r for r in in_pop + if (r["founding_features"].get("publications") or 0) >= min_pubs] + all_c = corr_rows(in_pop) + rob_c = corr_rows(robust) + ordered = sorted(candidates, key=lambda n: -abs(rob_c[n])) + out.append(md_table( + ["observable", + f"ρ, all in population (n={len(in_pop)})", + f"ρ, pubs ≥{min_pubs} (n={len(robust)})"], + [[n, f"{all_c[n]:+.3f}", f"{rob_c[n]:+.3f}"] for n in ordered])) + out.append("") + out.append( + "Correlation on the scored cohort, not causation in the model — 6a is " + "what the model uses, 6b is how the score co-varies with everything " + "observable here (including archetype sub-scores the model never saw). " + "Read the two columns together: signs that flip or shrink between them " + "are carried by the sub-7-publication boundary zone, not by the " + "in-regime ranking." + ) + return "\n".join(out) + + +# --------------------------------------------------------------------- + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--institution-id", required=True) + parser.add_argument("--threshold", type=float, default=90.0, + help="founding percentile defining the shortlist (default 90)") + parser.add_argument("--min-pubs", type=int, default=7, + help="publication floor for the robust shortlist (default 7)") + parser.add_argument("--out", default=None, + help="also write the report to this markdown file") + args = parser.parse_args() + + short = args.institution_id.strip().rsplit("/", 1)[-1] + rows = fetch_rows(short) + if not rows: + raise SystemExit(f"No documents for {short} in {MULTIPLICATORS_INDEX}.") + + sections = [ + f"# Founder-potential statistics — {short}", + "", + f"Generated by `founding_stats.py` from the live `{MULTIPLICATORS_INDEX}` " + f"index ({len(rows)} documents, config_hash of the newest run applies). " + f"Shortlist = `founding.percentile >= {args.threshold:g}`; robust = " + f"additionally `publications >= {args.min_pubs}`. Regenerate with:", + "", + "```bash", + "conda run -n potential python -m " + "service.scripts.profiling.multipliers.founding_stats \\", + f" --institution-id {short} --threshold {args.threshold:g} " + f"--min-pubs {args.min_pubs}", + "```", + "", + section_overview(rows), "", + section_percentile_by_stage(rows, args.min_pubs), "", + section_shortlist(rows, args.threshold, args.min_pubs), "", + section_archetype_overlap(rows, args.threshold, args.min_pubs), "", + section_areas(rows, args.threshold, args.min_pubs), "", + section_factors(rows, args.min_pubs), + ] + report = "\n".join(sections) + "\n" + print(report) + if args.out: + Path(args.out).write_text(report, encoding="utf-8") + print(f"\n[written to {args.out}]") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/multipliers/graph.py b/service/scripts/profiling/multipliers/graph.py new file mode 100644 index 00000000..aad6b82c --- /dev/null +++ b/service/scripts/profiling/multipliers/graph.py @@ -0,0 +1,246 @@ +#!/usr/bin/env python3 +""" +graph.py — co-author graph construction for multiplicator detection (M1, Stage C). + +Input: the cached work extract as plain dicts. Output: + - edges: dict[(src, dst)] -> EdgeStats (undirected, src < dst, SHORT ids) + - nodes: dict[author_id] -> NodeStats (per-author aggregates) + +Weighting, time decay and the hyperauthorship cap are explained in +docs/ROADMAP.md §2, step 3. Pure computation over plain data — no I/O, no ES. +""" +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Iterable + +import polars as pl + +OPENALEX_PREFIX = "https://openalex.org/" + + +def short_id(raw: str | None) -> str | None: + if not raw: + return None + return raw.rsplit("/", 1)[-1] if "/" in raw else raw + + +@dataclass +class EdgeStats: + weight: float = 0.0 # decay- and team-size-weighted collaboration strength + n_works: int = 0 # raw shared-work count + cross_inst_weight: float = 0.0 # weight portion where the pair shared NO institution + first_joint_year: int | None = None + last_joint_year: int | None = None + + +@dataclass +class NodeStats: + display_name: str | None = None + is_focal: bool = False # member of the institution author set + publication_years: set[int] = field(default_factory=set) # ALL works (uncapped) + n_works: int = 0 # ALL works (uncapped) + field_counts: dict[str, int] = field(default_factory=dict) # primary_topic.field + n_company_works: int = 0 # works with >=1 co-author institution type=company + n_typed_works: int = 0 # works where >=1 institution has a non-null type + # supervision signature inputs (per work, position-aware; capped works only) + n_last_author_works: int = 0 + last_author_junior_first: list[tuple[str, int]] = field(default_factory=list) + # ^ (first_author_id, year) for works where THIS node was last author + + +@dataclass +class Graph: + edges: dict[tuple[str, str], EdgeStats] + nodes: dict[str, NodeStats] + n_works_used: int # works that entered pair generation + n_works_capped: int # works excluded by max_authors_per_work + ref_year: int # decay reference year + + +def _work_author_rows( + works: Iterable[dict[str, Any]], +) -> tuple[list[dict[str, Any]], dict[str, dict[str, Any]]]: + """Flatten works into one row per (work, author) plus per-work metadata.""" + rows: list[dict[str, Any]] = [] + work_meta: dict[str, dict[str, Any]] = {} + for w in works: + wid = short_id(w.get("id")) + year = w.get("publication_year") + if not wid or not isinstance(year, int): + continue + authorships = w.get("authorships") or [] + seen: set[str] = set() + work_rows = [] + has_company = False + has_typed = False + first_author: str | None = None + last_author: str | None = None + for a in authorships: + aid = short_id((a.get("author") or {}).get("id")) + if not aid or aid in seen: + continue + seen.add(aid) + insts = a.get("institutions") or [] + inst_ids = frozenset( + short_id(i.get("id")) for i in insts if i.get("id") + ) + for i in insts: + itype = i.get("type") + if itype: + has_typed = True + if itype == "company": + has_company = True + position = a.get("author_position") + if position == "first" and first_author is None: + first_author = aid + if position == "last": + last_author = aid + work_rows.append( + { + "work_id": wid, + "year": year, + "author_id": aid, + "display_name": (a.get("author") or {}).get("display_name"), + "inst_ids": inst_ids, + } + ) + n_authors = len(seen) + field_id = short_id(((w.get("primary_topic") or {}).get("field") or {}).get("id")) + work_meta[wid] = { + "year": year, + "n_authors": n_authors, + "field_id": field_id, + "has_company": has_company, + "has_typed": has_typed, + "first_author": first_author, + "last_author": last_author, + } + rows.extend(work_rows) + return rows, work_meta + + +def build_graph( + works: Iterable[dict[str, Any]], + focal_author_ids: set[str], + max_authors_per_work: int = 50, + decay: float = 0.8, + ref_year: int | None = None, +) -> Graph: + """Build the weighted co-author graph and per-author aggregates. + + `focal_author_ids` may contain full URLs or short ids; both are normalized. + `ref_year` defaults to the max publication year in the corpus so results are + deterministic for a given extract (never wall-clock dependent). + """ + focal = {short_id(a) for a in focal_author_ids} + rows, work_meta = _work_author_rows(works) + + if ref_year is None: + ref_year = max((m["year"] for m in work_meta.values()), default=0) + + # ---- node aggregates over ALL works (uncapped) ---- + nodes: dict[str, NodeStats] = {} + for row in rows: + aid = row["author_id"] + node = nodes.get(aid) + if node is None: + node = nodes[aid] = NodeStats( + display_name=row["display_name"], is_focal=aid in focal + ) + meta = work_meta[row["work_id"]] + node.publication_years.add(row["year"]) + node.n_works += 1 + if meta["field_id"]: + node.field_counts[meta["field_id"]] = ( + node.field_counts.get(meta["field_id"], 0) + 1 + ) + if meta["has_typed"]: + node.n_typed_works += 1 + if meta["has_company"]: + node.n_company_works += 1 + + # capped works only: "last author" on a 500-author consortium paper is not + # a supervision signal + for wid, meta in work_meta.items(): + if not (2 <= meta["n_authors"] <= max_authors_per_work): + continue + la, fa = meta["last_author"], meta["first_author"] + if la and la in nodes: + nodes[la].n_last_author_works += 1 + if fa and fa != la: + nodes[la].last_author_junior_first.append((fa, meta["year"])) + + # ---- pair generation via polars self-join (capped works only) ---- + usable_work_ids = { + wid + for wid, meta in work_meta.items() + if 2 <= meta["n_authors"] <= max_authors_per_work + } + n_capped = sum( + 1 for meta in work_meta.values() if meta["n_authors"] > max_authors_per_work + ) + + pair_rows = [r for r in rows if r["work_id"] in usable_work_ids] + edges: dict[tuple[str, str], EdgeStats] = {} + if pair_rows: + df = pl.DataFrame( + { + "work_id": [r["work_id"] for r in pair_rows], + "author_id": [r["author_id"] for r in pair_rows], + } + ) + pairs = ( + df.join(df, on="work_id", suffix="_b") + .filter(pl.col("author_id") < pl.col("author_id_b")) + .select("work_id", "author_id", "author_id_b") + ) + inst_by_work_author: dict[tuple[str, str], frozenset] = { + (r["work_id"], r["author_id"]): r["inst_ids"] for r in pair_rows + } + for wid, a, b in pairs.iter_rows(): + meta = work_meta[wid] + year = meta["year"] + w = (decay ** (ref_year - year)) / (meta["n_authors"] - 1) + key = (a, b) + e = edges.get(key) + if e is None: + e = edges[key] = EdgeStats() + e.weight += w + e.n_works += 1 + insts_a = inst_by_work_author[(wid, a)] + insts_b = inst_by_work_author[(wid, b)] + if not (insts_a & insts_b): + e.cross_inst_weight += w + if e.first_joint_year is None or year < e.first_joint_year: + e.first_joint_year = year + if e.last_joint_year is None or year > e.last_joint_year: + e.last_joint_year = year + + return Graph( + edges=edges, + nodes=nodes, + n_works_used=len(usable_work_ids), + n_works_capped=n_capped, + ref_year=ref_year, + ) + + +def adjacency(graph: Graph) -> dict[str, dict[str, float]]: + """Symmetric weighted adjacency over ALL nodes (focal + external).""" + adj: dict[str, dict[str, float]] = {} + for (a, b), e in graph.edges.items(): + adj.setdefault(a, {})[b] = e.weight + adj.setdefault(b, {})[a] = e.weight + return adj + + +def focal_subgraph(graph: Graph) -> dict[str, dict[str, float]]: + """Adjacency restricted to focal (institution-internal) nodes only.""" + adj: dict[str, dict[str, float]] = {} + for (a, b), e in graph.edges.items(): + na, nb = graph.nodes.get(a), graph.nodes.get(b) + if na and nb and na.is_focal and nb.is_focal: + adj.setdefault(a, {})[b] = e.weight + adj.setdefault(b, {})[a] = e.weight + return adj diff --git a/service/scripts/profiling/multipliers/index.py b/service/scripts/profiling/multipliers/index.py new file mode 100644 index 00000000..6ea429d0 --- /dev/null +++ b/service/scripts/profiling/multipliers/index.py @@ -0,0 +1,319 @@ +#!/usr/bin/env python3 +""" +index.py — idempotent indexing of scored multiplicator rows into Elasticsearch. + +Target: `multiplicators_v1` on the INSE cluster. The index is admin-created — +the standard API key can read/write/update-mapping but NOT create or delete +indices, call `_delete_by_query`, or call `_refresh`. Everything below is shaped +by those three limits; see README, "Key-permission gotchas". + +Idempotency: doc _id = "_", and every run first +deletes the institution's existing docs via search + bulk-delete-by-id. +""" +from __future__ import annotations + +import json +import time +from datetime import datetime, timezone +from typing import Any + +import httpx + +from service.scripts.profiling.multipliers.extract import INSE_KEY, INSE_URL, _headers + +MULTIPLICATORS_INDEX = "multiplicators_v1" +NETWORKS_INDEX = "multiplicator_networks_v1" +REQUEST_TIMEOUT = 120.0 +BULK_CHUNK = 500 + +MAPPING = { + "properties": { + "institution_id": {"type": "keyword"}, + "cohort_institution_ids": {"type": "keyword"}, + "author_id": {"type": "keyword"}, + "display_name": { + "type": "text", + "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, + }, + "career_bucket": {"type": "keyword"}, + "active_years": {"type": "integer"}, + "n_works": {"type": "integer"}, + "suspicious_profile": {"type": "boolean"}, + "tags": {"type": "keyword"}, + "max_sub_score": {"type": "float"}, + "sub_scores": { + "properties": { + "bridger": {"type": "float"}, + "mentor": {"type": "float"}, + "amplifier": {"type": "float"}, + } + }, + # M3 signal counts + "patent_count": {"type": "integer"}, + "patent_count_name_only": {"type": "integer"}, # evidence only, never scored + "news_mentions": {"type": "integer"}, + "cordis_eu_projects": {"type": "integer"}, + "industry_coauthor_share_shrunk": {"type": "float"}, + "industry_collab_papers": {"type": "integer"}, + # Founder-potential model output (founding.py, v2 symmetric models). + # Mapped explicitly, not dynamically: a float that happened to be + # integral in the first indexed doc would come back as `long` and break + # the range queries these fields exist for. The live index also still + # carries the unused v1 fields — the key can add mappings, not delete. + "founding": { + "properties": { + # `percentile` is the coach-facing number; `probability_raw` + # is a case-control score, NOT a population probability + "percentile": {"type": "float"}, + "probability_raw": {"type": "float"}, + "in_population": {"type": "boolean"}, + # conditional timing, one bundle per horizon + "p_within_1y_percentile": {"type": "float"}, + "p_within_3y_percentile": {"type": "float"}, + "p_within_5y_percentile": {"type": "float"}, + "p_within_1y_raw": {"type": "float"}, + "p_within_3y_raw": {"type": "float"}, + "p_within_5y_raw": {"type": "float"}, + # sequence point estimate (transformer + lstm cross-check) + "predicted_founding_age": {"type": "float"}, + "predicted_founding_age_cross_check": {"type": "float"}, + "current_career_age": {"type": "integer"}, + "years_to_founding": {"type": "float"}, + "timing_applicable": {"type": "boolean"}, + # provenance + "classifier_model": {"type": "keyword"}, + "timing_model": {"type": "keyword"}, + "timing_cross_check_model": {"type": "keyword"}, + "as_of_year": {"type": "integer"}, + "patent_source": {"type": "keyword"}, + } + }, + # the exact v2 input record, as coach-facing evidence. `grants` is raw; + # `grants_capped` is what the model effectively used. + "founding_features": { + "properties": { + "publications": {"type": "integer"}, + "patents": {"type": "integer"}, + "grants": {"type": "integer"}, + "grants_capped": {"type": "float"}, + "first_publication_year": {"type": "integer"}, + "first_patent_year": {"type": "integer"}, + "first_grant_year": {"type": "integer"}, + "industry_collab_papers": {"type": "integer"}, + "linked_patents_to_publications": {"type": "integer"}, + "publication_research_area": {"type": "keyword"}, + "grant_research_area": {"type": "keyword"}, + } + }, + # raw metrics + percentiles kept as dynamic float objects (calibration needs them) + "percentiles": {"type": "object", "dynamic": True}, + "evidence": { + "properties": {"junior_ids": {"type": "keyword"}}, + }, + "config_hash": {"type": "keyword"}, + "computed_at": {"type": "date"}, + } +} + +# Visualization docs: nodes/edges are _source-only ("enabled": false) — the +# frontend GETs whole docs, never queries into them, and per-field indexing of +# ~900 edge objects per doc would be wasted. +NETWORK_MAPPING = { + "properties": { + "institution_id": {"type": "keyword"}, + "cohort_institution_ids": {"type": "keyword"}, + "author_id": {"type": "keyword"}, + "display_name": { + "type": "text", + "fields": {"keyword": {"type": "keyword", "ignore_above": 256}}, + }, + "ego": { + "properties": { + "career_bucket": {"type": "keyword"}, + "active_years": {"type": "integer"}, + "n_works": {"type": "integer"}, + "suspicious_profile": {"type": "boolean"}, + "tags": {"type": "keyword"}, + "max_sub_score": {"type": "float"}, + "sub_scores": { + "properties": { + "bridger": {"type": "float"}, + "mentor": {"type": "float"}, + "amplifier": {"type": "float"}, + } + }, + } + }, + "total_coauthors": {"type": "integer"}, + "cohort_coauthors": {"type": "integer"}, + "mentee_count": {"type": "integer"}, + "shown": {"type": "integer"}, + "shown_mentees": {"type": "integer"}, + "nodes": {"type": "object", "enabled": False}, + "edges": {"type": "object", "enabled": False}, + "config_hash": {"type": "keyword"}, + "computed_at": {"type": "date"}, + } +} + + +class MultiplicatorsIndexClient: + def __init__( + self, + base_url: str | None = None, + api_key: str | None = None, + index: str = MULTIPLICATORS_INDEX, + transport: httpx.BaseTransport | None = None, + ): + self.base_url = (base_url or INSE_URL).rstrip("/") + self.api_key = api_key if api_key is not None else INSE_KEY + self.index = index + self.client = httpx.Client(transport=transport, timeout=REQUEST_TIMEOUT) + if not self.base_url or not self.api_key: + raise SystemExit("Missing INSE cluster credentials (ELASTICSEARCH_INSE_*).") + + def _request(self, method: str, path: str, **kwargs: Any) -> httpx.Response: + return self.client.request( + method, + f"{self.base_url}/{path.lstrip('/')}", + headers=_headers(self.api_key), + **kwargs, + ) + + def ensure_mapping(self, mapping: dict[str, Any] | None = None) -> None: + """PUT the explicit mapping (additive; safe on every run). Never creates the index.""" + response = self._request( + "PUT", f"{self.index}/_mapping", json=mapping or MAPPING + ) + if not response.is_success: + raise RuntimeError( + f"Mapping update failed ({response.status_code}): {response.text[:500]}" + ) + + def count_for_institution(self, institution_short_id: str) -> int: + response = self._request( + "POST", + f"{self.index}/_count", + json={"query": {"term": {"institution_id": institution_short_id}}}, + ) + response.raise_for_status() + return response.json()["count"] + + def _wait_for_count(self, institution_short_id: str, expected: int, + timeout_s: float = 30.0) -> int: + """Poll _count until it reaches `expected` or timeout — the key cannot + call _refresh, so polling auto-refresh (~1s) is the only verification + available.""" + deadline = time.time() + timeout_s + count = -1 + while time.time() < deadline: + count = self.count_for_institution(institution_short_id) + if count == expected: + return count + time.sleep(1.0) + return count + + def _collect_ids_for_institution(self, institution_short_id: str) -> list[str]: + """All doc _ids for the institution, collected BEFORE any deletes so + stale visibility cannot inflate or loop the delete.""" + ids: list[str] = [] + search_after = None + while True: + body: dict[str, Any] = { + "size": 1000, + "_source": False, + "query": {"term": {"institution_id": institution_short_id}}, + "sort": [{"author_id": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + response = self._request("POST", f"{self.index}/_search", json=body) + response.raise_for_status() + hits = response.json()["hits"]["hits"] + if not hits: + break + ids.extend(h["_id"] for h in hits) + search_after = hits[-1]["sort"] + return ids + + def delete_for_institution(self, institution_short_id: str) -> int: + """Collect ids, then bulk-delete-by-id (the key 403s on + _delete_by_query). Returns the number of docs actually deleted.""" + ids = self._collect_ids_for_institution(institution_short_id) + deleted = 0 + for start in range(0, len(ids), BULK_CHUNK): + chunk = ids[start : start + BULK_CHUNK] + lines = "".join( + json.dumps({"delete": {"_index": self.index, "_id": doc_id}}) + "\n" + for doc_id in chunk + ) + bulk = self.client.post( + f"{self.base_url}/_bulk", + headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"}, + content=lines, + ) + bulk.raise_for_status() + for item in bulk.json()["items"]: + result = item.get("delete", {}) + if result.get("result") == "deleted": + deleted += 1 + elif result.get("error"): + raise RuntimeError(f"Bulk delete error: {result['error']}") + if ids: + remaining = self._wait_for_count(institution_short_id, 0) + if remaining != 0: + raise RuntimeError( + f"{remaining} docs for {institution_short_id} still visible " + f"after delete (expected 0)" + ) + return deleted + + def index_rows( + self, + institution_short_id: str, + cohort_short_ids: list[str], + scored_rows: list[dict[str, Any]], + ) -> int: + """Delete-then-bulk-index all rows for the institution. Returns docs written.""" + computed_at = datetime.now(timezone.utc).isoformat() + deleted = self.delete_for_institution(institution_short_id) + print(f"Deleted {deleted} existing docs for {institution_short_id}") + + written = 0 + for start in range(0, len(scored_rows), BULK_CHUNK): + chunk = scored_rows[start : start + BULK_CHUNK] + lines = [] + for row in chunk: + doc = { + **row, + "institution_id": institution_short_id, + "cohort_institution_ids": cohort_short_ids, + "computed_at": computed_at, + } + doc_id = f"{institution_short_id}_{row['author_id']}" + lines.append( + json.dumps({"index": {"_index": self.index, "_id": doc_id}}) + ) + lines.append(json.dumps(doc, ensure_ascii=True)) + bulk = self.client.post( + f"{self.base_url}/_bulk", + headers={**_headers(self.api_key), "Content-Type": "application/x-ndjson"}, + content="\n".join(lines) + "\n", + ) + bulk.raise_for_status() + result = bulk.json() + if result.get("errors"): + first_error = next( + (i["index"].get("error") for i in result["items"] + if i.get("index", {}).get("error")), + None, + ) + raise RuntimeError(f"Bulk indexing reported errors, first: {first_error}") + written += len(chunk) + visible = self._wait_for_count(institution_short_id, written) + if visible != written: + raise RuntimeError( + f"Post-index count mismatch for {institution_short_id}: " + f"wrote {written}, index shows {visible} after 30s" + ) + return written diff --git a/service/scripts/profiling/multipliers/make_report.py b/service/scripts/profiling/multipliers/make_report.py new file mode 100644 index 00000000..bec6a675 --- /dev/null +++ b/service/scripts/profiling/multipliers/make_report.py @@ -0,0 +1,258 @@ +#!/usr/bin/env python3 +""" +make_report.py — render the ego-network HTML report from the LIVE ES indices. + +Reads `multiplicators_v1` + `multiplicator_networks_v1` — the same two documents +a frontend would fetch — and writes one self-contained HTML file to reports/. + + python make_report.py --institution-id I62318514 + python make_report.py --institution-id I62318514 \ + --author-ids A5113304257,A5043495754 # explicit cast instead of auto-pick + +Default cast: one showcase per tag plus the highest scorer who just misses the +threshold. The layout is baked in to keep the file dependency-free; a real +frontend should let echarts' `graph` series lay out the same nodes/edges live. +""" +from __future__ import annotations + +import argparse +import json +import math +import os +import random +import sys +from pathlib import Path + +import httpx +import yaml +from dotenv import load_dotenv + +SCRIPT_DIR = Path(__file__).resolve().parent +ENV_PATH = SCRIPT_DIR.parent.parent / "src" / "main" / "inse" / ".env" +load_dotenv(dotenv_path=ENV_PATH) + +INSE_URL = (os.environ.get("ELASTICSEARCH_INSE_URL") or "").rstrip("/") +INSE_KEY = os.environ.get("ELASTICSEARCH_INSE_API_KEY") or "" +SCORES_INDEX = "multiplicators_v1" +NETWORKS_INDEX = "multiplicator_networks_v1" + +SCORE_FIELDS = ( + "author_id", "display_name", "career_bucket", "active_years", "n_works", + "suspicious_profile", "tags", "sub_scores", "percentiles", "betweenness", + "brokerage", "constraint", "field_entropy", "cross_institution_share", + "strength", "n_coauthors", "industry_coauthor_share", + "industry_coauthor_share_shrunk", "juniors_mentored", + "junior_progression_rate", "mentoring_rate", "last_author_with_junior_first", + "patent_count", "news_mentions", "cordis_eu_projects", +) + + +# --------------------------------------------------------------------- +# ES access +# --------------------------------------------------------------------- + + +def _headers() -> dict[str, str]: + return {"Authorization": f"ApiKey {INSE_KEY}", "Content-Type": "application/json"} + + +def es_get(client: httpx.Client, index: str, doc_id: str) -> dict | None: + r = client.get(f"{INSE_URL}/{index}/_doc/{doc_id}", headers=_headers(), timeout=30) + if r.status_code == 404: + return None + r.raise_for_status() + return r.json()["_source"] + + +def es_search(client: httpx.Client, index: str, body: dict) -> dict: + r = client.post(f"{INSE_URL}/{index}/_search", headers=_headers(), json=body, timeout=60) + r.raise_for_status() + return r.json() + + +def pick_showcase(client: httpx.Client, institution: str) -> list[tuple[str, str]]: + """(author_id, kind) for the top bridger / mentor / amplifier + top near-miss.""" + picks: list[tuple[str, str]] = [] + seen: set[str] = set() + for tag in ("bridger", "mentor", "amplifier"): + res = es_search(client, SCORES_INDEX, { + "size": 5, + "_source": ["author_id"], + "query": {"bool": {"filter": [ + {"term": {"institution_id": institution}}, + {"term": {"tags": tag}}, + ]}}, + "sort": [{f"sub_scores.{tag}": {"order": "desc"}}], + }) + for hit in res["hits"]["hits"]: + aid = hit["_source"]["author_id"] + if aid not in seen: + picks.append((aid, tag)) + seen.add(aid) + break + # highest scorer that carries no tag — shows where the threshold bites + res = es_search(client, SCORES_INDEX, { + "size": 5, + "_source": ["author_id"], + "query": {"bool": { + "filter": [{"term": {"institution_id": institution}}], + "must_not": [{"exists": {"field": "tags"}}], + }}, + "sort": [{"max_sub_score": {"order": "desc"}}], + }) + for hit in res["hits"]["hits"]: + aid = hit["_source"]["author_id"] + if aid not in seen: + picks.append((aid, "example")) + seen.add(aid) + break + return picks + + +# --------------------------------------------------------------------- +# Layout +# --------------------------------------------------------------------- + + +def fr_layout(node_ids, edge_list, w=760, h=560, iters=350, seed=7): + """Fruchterman-Reingold with the ego pinned to the centre (deterministic seed).""" + rng = random.Random(seed) + pos = {n: [rng.uniform(0, w), rng.uniform(0, h)] for n in node_ids} + ego = node_ids[0] + pos[ego] = [w / 2, h / 2] + k = math.sqrt(w * h / max(len(node_ids), 1)) * 0.9 + t = w / 8 + wmax = max((e[2] for e in edge_list), default=1.0) + for _ in range(iters): + disp = {n: [0.0, 0.0] for n in node_ids} + for i, a in enumerate(node_ids): + for b in node_ids[i + 1:]: + dx = pos[a][0] - pos[b][0] + dy = pos[a][1] - pos[b][1] + d = max(math.hypot(dx, dy), 0.01) + f = k * k / d + disp[a][0] += dx / d * f; disp[a][1] += dy / d * f + disp[b][0] -= dx / d * f; disp[b][1] -= dy / d * f + for a, b, wt in edge_list: + dx = pos[a][0] - pos[b][0] + dy = pos[a][1] - pos[b][1] + d = max(math.hypot(dx, dy), 0.01) + f = d * d / k * (0.3 + 0.7 * wt / wmax) + disp[a][0] -= dx / d * f; disp[a][1] -= dy / d * f + disp[b][0] += dx / d * f; disp[b][1] += dy / d * f + for n in node_ids: + if n == ego: + continue + dx, dy = disp[n] + d = max(math.hypot(dx, dy), 0.01) + pos[n][0] = min(w - 20, max(20, pos[n][0] + dx / d * min(d, t))) + pos[n][1] = min(h - 20, max(20, pos[n][1] + dy / d * min(d, t))) + t *= 0.97 + return pos + + +def compose(client: httpx.Client, institution: str, picks: list[tuple[str, str]]) -> dict: + out: dict[str, dict] = {} + for author_id, kind in picks: + doc_id = f"{institution}_{author_id}" + net = es_get(client, NETWORKS_INDEX, doc_id) + score = es_get(client, SCORES_INDEX, doc_id) + if not net or not score: + print(f" skip {author_id}: missing doc", file=sys.stderr) + continue + node_ids = [n["id"] for n in net["nodes"]] + pos = fr_layout(node_ids, [(e["a"], e["b"], e["w"]) for e in net["edges"]]) + nodes = [] + for n in net["nodes"]: + entry = { + "id": n["id"], "name": n["name"], "role": n["role"], + "inst": n.get("inst", ""), "active_years": n["active_years"], + "x": round(pos[n["id"]][0], 1), "y": round(pos[n["id"]][1], 1), + } + if n.get("company_insts"): + entry["company_insts"] = n["company_insts"] + nodes.append(entry) + out[author_id] = { + "kind": kind, + "score_row": {k: score[k] for k in SCORE_FIELDS if k in score}, + "total_coauthors": net["total_coauthors"], + "shown": net["shown"], + "nodes": nodes, + "edges": [ + {"a": e["a"], "b": e["b"], "w": e["w"], "n": e["n_works"], + "cross": e["cross"], "y0": e["first_year"]} + for e in net["edges"] + ], + "config_hash": score.get("config_hash", ""), + "computed_at": (score.get("computed_at") or "")[:10], + } + roles: dict[str, int] = {} + for n in nodes: + roles[n["role"]] = roles.get(n["role"], 0) + 1 + print(f" {kind:<10} {score.get('display_name')}: {roles}", file=sys.stderr) + return out + + +TEMPLATE_PATH = SCRIPT_DIR / "report_template.html" + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--institution-id", required=True) + parser.add_argument( + "--author-ids", default="", + help="Comma-separated author IDs to feature. Overrides report.featured_author_ids " + "in the config; pass --auto to force automatic selection instead.", + ) + parser.add_argument( + "--auto", action="store_true", + help="Ignore the pinned cast and auto-select the current top scorer per tag.", + ) + parser.add_argument("--config", default=str(SCRIPT_DIR / "multipliers.yaml")) + parser.add_argument("--out", default=str(SCRIPT_DIR / "reports" / "multiplier_networks.html")) + args = parser.parse_args() + + if not INSE_URL or not INSE_KEY: + raise SystemExit(f"Missing INSE credentials. Checked {ENV_PATH}") + + institution = args.institution_id.strip().rsplit("/", 1)[-1] + + # cast precedence: --author-ids > --auto > config pin > automatic + pinned: list[str] = [] + if not args.auto and not args.author_ids: + config_path = Path(args.config) + if config_path.exists(): + config = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {} + pinned = [ + str(a) for a in ((config.get("report") or {}).get("featured_author_ids") or []) + ] + + with httpx.Client() as client: + ids = [a.strip() for a in args.author_ids.split(",") if a.strip()] or pinned + if ids: + kinds = ["bridger", "mentor", "amplifier", "example"] + picks = [(a, kinds[i] if i < len(kinds) else "example") + for i, a in enumerate(ids)] + source = "config-pinned" if pinned and not args.author_ids else "explicit" + print(f"Cast ({source}): {[p[0] for p in picks]}", file=sys.stderr) + else: + picks = pick_showcase(client, institution) + print(f"Auto-selected showcase: {[p[0] for p in picks]}", file=sys.stderr) + data = compose(client, institution, picks) + + if not data: + raise SystemExit("No documents found — has build.py run for this institution?") + + template = TEMPLATE_PATH.read_text(encoding="utf-8") + payload = json.dumps(data, ensure_ascii=True) + assert " {out_path} ({len(html):,} bytes, {len(data)} cases)") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/multipliers/metrics.py b/service/scripts/profiling/multipliers/metrics.py new file mode 100644 index 00000000..e36b434b --- /dev/null +++ b/service/scripts/profiling/multipliers/metrics.py @@ -0,0 +1,332 @@ +#!/usr/bin/env python3 +""" +metrics.py — bridger / mentor metrics for multiplicator detection (M1, Stage D). + +Pure computations over the structures produced by graph.py. Field-by-field +definitions and the rationale behind them: docs/ROADMAP.md §3. + +Two invariants the code depends on: + - Seniority is `active_years_at`, never first_publication_year — merged + OpenAlex profiles give active professors debut years like 1893. + - Mentor metrics run over FOCAL pairs only: external co-authors' year-sets + are truncated to shared works, so an external senior would look junior. + A data-correctness requirement, not a modelling choice. +""" +from __future__ import annotations + +import heapq +import math +from dataclasses import dataclass, field + +from service.scripts.profiling.multipliers.graph import EdgeStats, Graph, adjacency, focal_subgraph + + +def incident_edges(graph: Graph) -> dict[str, list[tuple[str, EdgeStats]]]: + """One pass over the edge dict -> per-author incident edge lists. + + Every per-author metric must use this instead of scanning graph.edges: a + full-edge scan per focal author is O(E * authors) and does not finish.""" + incident: dict[str, list[tuple[str, EdgeStats]]] = {} + for (a, b), e in graph.edges.items(): + incident.setdefault(a, []).append((b, e)) + incident.setdefault(b, []).append((a, e)) + return incident + + +# --------------------------------------------------------------------- +# Career primitives +# --------------------------------------------------------------------- + + +def active_years_at(publication_years: set[int], year: int) -> int: + """Distinct publication years up to and including `year` (robust seniority).""" + return sum(1 for y in publication_years if y <= year) + + +def is_suspicious_profile(publication_years: set[int]) -> bool: + """Merged-profile flag, same rule as inse/persons/logic.py.""" + if not publication_years: + return False + first = min(publication_years) + span = max(publication_years) - first + 1 + return first < 1970 or span > 60 + + +# --------------------------------------------------------------------- +# Betweenness — Brandes (2001), weighted variant with Dijkstra. +# Weights are collaboration STRENGTHS, shortest paths need DISTANCES, so +# distances are 1/weight. +# --------------------------------------------------------------------- + + +def betweenness_centrality( + adj: dict[str, dict[str, float]], normalized: bool = True +) -> dict[str, float]: + nodes = list(adj.keys()) + bc = {v: 0.0 for v in nodes} + + for s in nodes: + # per-source state is lazy (touched nodes only) — initialising over all + # V nodes per source would be O(V^2) before any work happens + dist: dict[str, float] = {s: 0.0} + sigma: dict[str, float] = {s: 1.0} + preds: dict[str, list[str]] = {} + done: set[str] = set() + order: list[str] = [] + heap: list[tuple[float, str]] = [(0.0, s)] + while heap: + d, v = heapq.heappop(heap) + if v in done: + continue + done.add(v) + order.append(v) + sigma_v = sigma[v] + for u, w in adj[v].items(): + if w <= 0: + continue + nd = d + 1.0 / w + old = dist.get(u) + if old is None or nd < old - 1e-12: + dist[u] = nd + sigma[u] = sigma_v + preds[u] = [v] + heapq.heappush(heap, (nd, u)) + elif abs(nd - old) <= 1e-12 and u not in done: + sigma[u] += sigma_v + preds.setdefault(u, []).append(v) + # accumulation, reverse order of discovery + delta: dict[str, float] = {} + for v in reversed(order): + dv = delta.get(v, 0.0) + coeff = (1.0 + dv) / sigma[v] + for p in preds.get(v, ()): + delta[p] = delta.get(p, 0.0) + sigma[p] * coeff + if v != s: + bc[v] += dv + + # undirected: each pair counted twice + for v in bc: + bc[v] /= 2.0 + if normalized and len(nodes) > 2: + scale = 1.0 / ((len(nodes) - 1) * (len(nodes) - 2) / 2.0) + for v in bc: + bc[v] *= scale + return bc + + +# --------------------------------------------------------------------- +# Burt's constraint — low constraint == structural-hole spanner (bridger). +# Computed on the FULL graph, external co-authors included. +# --------------------------------------------------------------------- + + +def burt_constraint( + adj: dict[str, dict[str, float]], nodes: list[str] | None = None +) -> dict[str, float]: + """Constraint c_i = sum_j (p_ij + sum_q p_iq * p_qj)^2 over neighbours j of i. + + p_ij = w_ij / sum_k w_ik. Isolates get constraint 1.0 (fully constrained). + """ + # once, not inside the O(d^2) inner loop — that would be O(d^3) and + # unusable on hub nodes + totals = {v: sum(neigh.values()) for v, neigh in adj.items()} + + result: dict[str, float] = {} + targets = nodes if nodes is not None else list(adj.keys()) + for i in targets: + neigh = adj.get(i) or {} + total = totals.get(i, 0.0) + if total <= 0: + result[i] = 1.0 + continue + p_i = {j: w / total for j, w in neigh.items()} + c = 0.0 + for j, p_ij in p_i.items(): + indirect = 0.0 + for q, p_iq in p_i.items(): + if q == j: + continue + q_neigh = adj.get(q) + if not q_neigh: + continue + w_qj = q_neigh.get(j) + if w_qj: + indirect += p_iq * (w_qj / totals[q]) + c += (p_ij + indirect) ** 2 + result[i] = c + return result + + +# --------------------------------------------------------------------- +# Simple per-node shares +# --------------------------------------------------------------------- + + +def field_entropy(field_counts: dict[str, int]) -> float: + """Shannon entropy (bits) over primary_topic.field of an author's works.""" + total = sum(field_counts.values()) + if total <= 0: + return 0.0 + ent = 0.0 + for c in field_counts.values(): + if c > 0: + p = c / total + ent -= p * math.log2(p) + return ent + + +def cross_institution_share( + graph: Graph, + author_id: str, + incident: dict[str, list[tuple[str, EdgeStats]]] | None = None, +) -> float: + """Share of an author's edge weight where the pair shared no institution.""" + if incident is None: + incident = incident_edges(graph) + total = 0.0 + cross = 0.0 + for _, e in incident.get(author_id, ()): + total += e.weight + cross += e.cross_inst_weight + return cross / total if total > 0 else 0.0 + + +# --------------------------------------------------------------------- +# Mentor metrics — debut-year-free (see module docstring) +# --------------------------------------------------------------------- + + +@dataclass +class MentorMetrics: + juniors_mentored: int = 0 + junior_progression_rate: float | None = None # None if no juniors + last_author_with_junior_first: int = 0 + mentoring_rate: float = 0.0 + junior_ids: list[str] = field(default_factory=list) # evidence + + +def mentor_metrics( + graph: Graph, + focal_author_id: str, + junior_active_years_max: int = 4, + senior_active_years_min: int = 10, + progressed_active_years_min: int = 5, + incident: dict[str, list[tuple[str, EdgeStats]]] | None = None, +) -> MentorMetrics: + """Seniority-gap mentorship over focal-internal pairs. + + A co-author J counts as "mentored" when, at the year Y of the FIRST joint work: + active_years_at(J, Y) <= junior_active_years_max (J was Early-career) + active_years_at(focal, Y) >= senior_active_years_min (focal was Established+) + Progression: J later reached >= progressed_active_years_min active years. + """ + focal_node = graph.nodes.get(focal_author_id) + if focal_node is None: + return MentorMetrics() + if incident is None: + incident = incident_edges(graph) + + juniors: list[str] = [] + progressed = 0 + for other, e in incident.get(focal_author_id, ()): + if e.first_joint_year is None: + continue + other_node = graph.nodes.get(other) + if other_node is None or not other_node.is_focal or not focal_node.is_focal: + continue # internal pairs only — external year-sets are truncated + y = e.first_joint_year + if ( + active_years_at(other_node.publication_years, y) <= junior_active_years_max + and active_years_at(focal_node.publication_years, y) >= senior_active_years_min + ): + juniors.append(other) + if len(other_node.publication_years) >= progressed_active_years_min: + progressed += 1 + + # supervision signature: focal last author, junior first author + last_author_junior_first = 0 + for first_author, year in focal_node.last_author_junior_first: + fa_node = graph.nodes.get(first_author) + if fa_node is None or not fa_node.is_focal: + continue + if active_years_at(fa_node.publication_years, year) <= junior_active_years_max: + last_author_junior_first += 1 + + total_active = len(focal_node.publication_years) + return MentorMetrics( + juniors_mentored=len(juniors), + junior_progression_rate=(progressed / len(juniors)) if juniors else None, + last_author_with_junior_first=last_author_junior_first, + mentoring_rate=(len(juniors) / total_active) if total_active else 0.0, + junior_ids=juniors, + ) + + +# --------------------------------------------------------------------- +# Orchestration: all raw metrics for every focal author +# --------------------------------------------------------------------- + + +def compute_all_metrics( + graph: Graph, + junior_active_years_max: int = 4, + senior_active_years_min: int = 10, + progressed_active_years_min: int = 5, + industry_share_shrinkage_k: int = 5, +) -> dict[str, dict]: + """Raw (un-normalized) metric rows keyed by focal author id.""" + internal = focal_subgraph(graph) + full_adj = adjacency(graph) + incident = incident_edges(graph) + focal_ids = [aid for aid, n in graph.nodes.items() if n.is_focal] + + bc = betweenness_centrality(internal) if internal else {} + constraint = burt_constraint(full_adj, nodes=[a for a in focal_ids if a in full_adj]) + + rows: dict[str, dict] = {} + for aid in focal_ids: + node = graph.nodes[aid] + mm = mentor_metrics( + graph, + aid, + junior_active_years_max=junior_active_years_max, + senior_active_years_min=senior_active_years_min, + progressed_active_years_min=progressed_active_years_min, + incident=incident, + ) + strength = sum(full_adj.get(aid, {}).values()) + rows[aid] = { + "author_id": aid, + "display_name": node.display_name, + "active_years": len(node.publication_years), + "n_works": node.n_works, + "suspicious_profile": is_suspicious_profile(node.publication_years), + # bridger + "betweenness": bc.get(aid, 0.0), + "constraint": constraint.get(aid, 1.0), + "brokerage": 1.0 - constraint.get(aid, 1.0), # higher = more bridging + "field_entropy": field_entropy(node.field_counts), + "cross_institution_share": cross_institution_share(graph, aid, incident), + "strength": strength, + "n_coauthors": len(full_adj.get(aid, {})), + # not scored; the founder classifier's `industry_collab_papers` + # input verbatim + "industry_collab_papers": node.n_company_works, + "industry_coauthor_share": ( + node.n_company_works / node.n_typed_works if node.n_typed_works else 0.0 + ), + # the SCORED variant: +k damps the small-denominator artifact + # where 2-of-2 company works outranks 40-of-80 + "industry_coauthor_share_shrunk": ( + node.n_company_works / (node.n_typed_works + industry_share_shrinkage_k) + if node.n_typed_works + else 0.0 + ), + # mentor + "juniors_mentored": mm.juniors_mentored, + "junior_progression_rate": mm.junior_progression_rate, + "last_author_with_junior_first": mm.last_author_with_junior_first, + "mentoring_rate": mm.mentoring_rate, + "junior_ids": mm.junior_ids, + } + return rows diff --git a/service/scripts/profiling/multipliers/multipliers.yaml b/service/scripts/profiling/multipliers/multipliers.yaml new file mode 100644 index 00000000..cac69e31 --- /dev/null +++ b/service/scripts/profiling/multipliers/multipliers.yaml @@ -0,0 +1,185 @@ +# Multiplicator detection — all tunables live here. +# Coaches will retune weights/thresholds; every output doc carries a config_hash +# of this file so scores stay attributable to the weighting that produced them. + +version: 2 + +# --------------------------------------------------------------------------- +# Cohorts — which OpenAlex institutions constitute "the university". +# +# Keyed by the primary institution ID passed as --institution-id. If a cohort +# entry exists, the author set is extracted over ALL listed IDs; otherwise the +# primary ID alone is used. Needed because OpenAlex does NOT model university +# hospitals as lineage children: Essen University Hospital is only "related" +# to UDE, which silently excluded ~2,437 active clinicians (incl. prominent +# medicine professors) from the cohort — found via the M1 validation, where +# 17/60 hand-labeled people were missing. +# +# Source of candidates: openalex-institutions `associated_institutions` of the +# primary ID (children + related), one hop deep. Every inclusion/exclusion is +# a human judgment call — document the reason next to each entry. +# --------------------------------------------------------------------------- +cohorts: + I62318514: + name: University of Duisburg-Essen + institution_ids: + - I62318514 # UDE itself (primary) + - I4210119759 # Essen University Hospital — the university medical centre; + # "related" in OpenAlex, NOT lineage, hence the coverage gap + - I4210161917 # West German Heart and Vascular Center Essen — child of the hospital + - I127668822 # Erwin L. Hahn Institute for MRI — joint UDE institute, + # isolated in OpenAlex (no lineage/associated links at all) + - I4210090139 # Rhein-Ruhr Institut für Sozialforschung (child of UDE) + - I4210092428 # Deutsches Textilforschungszentrum Nord-West (child of UDE) + - I4210110714 # Institute for Advanced Study in the Humanities Essen / KWI (child) + - I4210146441 # The Hydrogen and Fuel Cell Center / ZBT (child of UDE) + - I4210154243 # Institut für Energie- und Umwelttechnik / IUTA (child of UDE) + # Deliberately EXCLUDED (decide with the coaches before enabling): + # - I4210146447 Kliniken Essen-Mitte — independent hospital group, only + # "related"; staff are not UDE researchers (~788 authors) + # - I2799342142 Salomon Ludwig Steinheim-Institut — independent An-Institut + # - I4210124583 IWW Water Centre — independent An-Institut + +extraction: + # "Recent affiliation" cutoff for the author set. 2023 (not the current year): + # publication lag pushes current staff out of a 1-year window — the M1 validation + # found 6 current-ish people (incl. an active professor) with newest affiliation + # year 2021-2024. 2023 captures normal lag while still excluding long-departed. + affiliation_years_gte: 2023 + work_year_gte: 1950 + # Chosen from the M0 spike (authors/work p50=5, p90=17, p99=144, max=4839): + # cap 50 keeps >=99% of works and excludes only true hyperauthorship, which + # carries no collaboration signal but would create giant artificial cliques. + max_authors_per_work: 50 + +graph: + decay: 0.8 # per-year edge weight decay (ref = newest corpus year) + +career: + # active_years bucket thresholds — mirror inse/persons/logic.py _classify_career_stage. + # Buckets: Early <= 4, Emerging <= 9, Established <= 14, Senior > 14. + buckets: [4, 9, 14] + bucket_names: [Early, Emerging, Established, Senior] + +mentor: + junior_active_years_max: 4 # junior == Early-career at first joint work + senior_active_years_min: 10 # focal must be Established+ at first joint work + progressed_active_years_min: 5 + +signals: + # org_patents match_types that count toward the score; "name"-only matches are + # carried as evidence (patent_count_name_only) but never scored. + patent_match_types: [institution, both] + news_require_relevant: true # only aktuell_postproc docs the LLM marked relevant + # Shrinkage constant for industry_coauthor_share_shrunk = company/(typed+k): + # damps small denominators (2-of-2 works with a company co-author is not a + # stronger industry signal than 40-of-80). Found via the live-index audit, + # where all top-10 "amplifiers" were such ratio artifacts. + industry_share_shrinkage_k: 5 + +# --------------------------------------------------------------------------- +# Founder-potential enrichment (founding.py) — runs the SYMMETRIC v2 production +# models from ../founding_potential/production/classifier_symmetric over the +# cohort, plus the founder-timing sequence models, and attaches their output as +# flat, queryable `founding.*` / `founding_features.*` fields. +# +# v1 (production/classifier) MUST NOT be configured here again: it was trained +# with asymmetric observation windows and behaves as an inverse-productivity +# score (1 publication -> P(founder)=0.996, 800 -> 0.0002; found in this +# pipeline's first integration run, confirmed by single-feature probes). v2 +# rebuilds the dataset with a symmetric landmark design; its honest OOF scores +# are ROC-AUC 0.866 / PR-AUC 0.726, and the coach-facing number is a PERCENTILE +# against the ~9k-academic reference cohort, guarded by `in_population` +# (>= 4 publications — below that the training classes come from clashing +# sampling frames and scores are not evidence). +# +# These are NOT folded into sub_scores/tags: the three multiplicator archetypes +# are within-career-bucket percentiles of THIS cohort; founding.percentile is a +# rank against a fixed external reference cohort. Same word, different +# comparison set — merging them would make both unreadable. +# --------------------------------------------------------------------------- +founding: + enabled: true + models_dir: ../founding_potential/production # relative to this file + # Founder-propensity bundle (FounderClassifierV2 wrapper), path under models_dir. + classifier: classifier_symmetric/models/founder_classifier_v2.joblib + # "Founds within k years of the index" bundles — same wrapper class, own + # reference quantiles each. Keys become founding.p_within_y_* fields. + horizon_bundles: + 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 + # Sequence point-estimate models (production/sequence, unchanged): "how far + # into a career does this activity pattern look like a founding moment". + # Their residual-derived P(within k) fields are gone — measured degenerate + # (1.0 for every author at 3y/5y); the horizon bundles above replace them. + timing: transformer + timing_cross_check: lstm + # Sequence README §1: the timing models only ever saw founding ages in [1, 20] + # years. Beyond that `founding.timing_applicable` is false. + max_career_age: 20 + # Where the models' patent features come from. Measured on UDE (2026-08-07, + # full-cohort run; an earlier "7% / 12x" estimate came from a biased + # 200-author sample — low OpenAlex ids cluster long-established profiles): + # + # org_patents institution-assigned matches, reuses the amplifier's existing + # scan, FREE. 55 of 9,474 authors (0.6%) — the models' patent + # features are zero for everyone else. + # api the backend's name-matched EPO+USPTO endpoint. 115 authors + # (1.2%), ~20-65 min for the cohort (one request per author, + # container CPU-bound; cached per cohort afterwards). Under + # `api` the pipeline additionally MERGES org_patents in + # per-author (best count wins, never summed): the two sources + # overlap on only 18 authors, so the merge reaches 152 (1.6%) + # and index docs are stamped patent_source=api+org_patents. + # + # `api` is the production setting: the v2 scores ship to coaches, so patent + # coverage matters and the join is paid once per cohort. Drop back to + # org_patents for fast iteration on the pipeline itself. The amplifier's own + # patent_count is institution-linked either way. + patent_source: api # org_patents | api + api_base_url: http://localhost:8000 + api_concurrency: 16 + +network: + # Per-author ego-network docs for the visualization frontend + # (index multiplicator_networks_v1). Nodes shown = strongest co-authors by tie + # weight, with mentees force-included first — their decayed, team-size-divided + # ties otherwise never make the cut (a 100-mentee professor had ZERO mentees + # in his unforced top 42). + max_nodes: 42 + max_forced_mentees: 14 + +# Sub-score weights over WITHIN-BUCKET percentiles of the raw metrics. +# Weights within each sub-score should sum to 1. +weights: + bridger: + betweenness: 0.35 + brokerage: 0.25 # 1 - Burt constraint, full graph incl. externals + field_entropy: 0.20 + cross_institution_share: 0.20 + mentor: + juniors_mentored: 0.35 + mentoring_rate: 0.25 + last_author_with_junior_first: 0.25 + junior_progression_rate: 0.15 + amplifier: + industry_coauthor_share_shrunk: 0.50 # primary: ID-linked company co-authorship, shrunk + patent_count: 0.25 # high-confidence org_patents (institution/both) + cordis_eu_projects: 0.15 # DOI-join, no name matching + news_mentions: 0.10 # normalized-exact name match — lossy; keep low + +tags: + threshold: 0.85 # tag fires when sub-score >= threshold (multiple allowed) + min_active_years: 2 # never tag someone with <2 active years (no history) + +report: + # Cast for make_report.py, in order: bridger, mentor, amplifier, near-miss. + # Pinned so the report is reproducible — without this the script auto-picks the + # current top scorer per tag, which changes with every weight tune or dump refresh. + # Remove/empty the list to fall back to automatic selection. + featured_author_ids: + - A5113304257 # Jan Egger — top bridger + - A5043495754 # Cornelius Deuschl — top mentor + - A5007801159 # Jens Wiltfang — top amplifier + - A5043360678 # Tabea M. G. Pakull — strong profile just below the tag line diff --git a/service/scripts/profiling/multipliers/networks.py b/service/scripts/profiling/multipliers/networks.py new file mode 100644 index 00000000..7d2ba906 --- /dev/null +++ b/service/scripts/profiling/multipliers/networks.py @@ -0,0 +1,127 @@ +#!/usr/bin/env python3 +""" +networks.py — per-author ego-network documents for visualization. + +The scores index answers "what did this person score"; this one answers "who +are they connected to and how". Neighbour-neighbour edges come from works that +do not include the ego, so they can only be materialized here, while the full +graph is in memory. Doc shape and node-selection rules: README, "Network +visualization index". + +Node selection forces up to `max_forced_mentees` mentees in before the +top-by-weight cut: mentee ties are decayed and team-size-divided, so a pure +top-N hides exactly the people the mentor score is about. +""" +from __future__ import annotations + +from typing import Any + +from service.scripts.profiling.multipliers.graph import Graph +from service.scripts.profiling.multipliers.metrics import is_suspicious_profile + + +def build_network_docs( + graph: Graph, + metric_rows: dict[str, dict[str, Any]], + scored_rows: list[dict[str, Any]], + incident: dict[str, list], + inst_by_author: dict[str, str], + company_authors: set[str], + max_nodes: int = 42, + max_forced_mentees: int = 14, +) -> list[dict[str, Any]]: + """One visualization doc per focal author. + + metric_rows must still carry the FULL `junior_ids` (pre-scoring; the scored + rows' evidence list is capped). scored_rows supply the ego header fields. + """ + scored_by_id = {r["author_id"]: r for r in scored_rows} + docs: list[dict[str, Any]] = [] + + for ego_id, mrow in metric_rows.items(): + srow = scored_by_id.get(ego_id) + if srow is None: + continue + mentees = set(mrow.get("junior_ids") or []) + ranked = sorted( + incident.get(ego_id, []), key=lambda kv: kv[1].weight, reverse=True + ) + + mentee_picks = [n for n, _ in ranked if n in mentees][:max_forced_mentees] + forced = set(mentee_picks) + others = [n for n, _ in ranked if n not in forced] + selected = [ego_id] + mentee_picks + others[: max_nodes - len(mentee_picks)] + idset = set(selected) + + nodes = [] + for nid in selected: + node = graph.nodes[nid] + if nid == ego_id: + role = "ego" + elif nid in mentees: + role = "mentee" + elif nid in company_authors and not node.is_focal: + role = "industry" + elif node.is_focal: + role = "cohort" + else: + role = "external" + nodes.append( + { + "id": nid, + "name": node.display_name, + "role": role, + "inst": inst_by_author.get(nid, ""), + "active_years": len(node.publication_years), + "suspicious": is_suspicious_profile(node.publication_years), + } + ) + + # pair lookups against the edge dict (~900 per ego), NOT a scan of + # the 5.8M-edge dict per ego + edges = [] + for i, a in enumerate(selected): + for b in selected[i + 1:]: + e = graph.edges.get((a, b) if a < b else (b, a)) + if e is None: + continue + edges.append( + { + "a": a, + "b": b, + "w": round(e.weight, 3), + "n_works": e.n_works, + "cross": bool( + e.weight > 0 and e.cross_inst_weight / e.weight > 0.5 + ), + "first_year": e.first_joint_year, + "last_year": e.last_joint_year, + } + ) + + cohort_coauthors = sum( + 1 for n, _ in ranked if graph.nodes[n].is_focal + ) + docs.append( + { + "author_id": ego_id, + "display_name": srow.get("display_name"), + "ego": { + "career_bucket": srow.get("career_bucket"), + "active_years": srow.get("active_years"), + "n_works": srow.get("n_works"), + "suspicious_profile": srow.get("suspicious_profile"), + "tags": srow.get("tags", []), + "sub_scores": srow.get("sub_scores", {}), + "max_sub_score": srow.get("max_sub_score"), + }, + "total_coauthors": len(ranked), + "cohort_coauthors": cohort_coauthors, + "mentee_count": len(mentees), + "shown": len(selected) - 1, + "shown_mentees": len(mentee_picks), + "nodes": nodes, + "edges": edges, + } + ) + return docs diff --git a/service/scripts/profiling/multipliers/report_template.html b/service/scripts/profiling/multipliers/report_template.html new file mode 100644 index 00000000..99bce523 --- /dev/null +++ b/service/scripts/profiling/multipliers/report_template.html @@ -0,0 +1,461 @@ + + + + + +Multipliers, drawn as networks + + + + +
+
+

Smart-Guide · Multiplier detection

+

Four researchers, drawn as the networks that scored them

+

+ Each figure shows one person (ringed) and their strongest co-authors, with every + collaboration the corpus records among those co-authors. The shape is the + metric: spokes that don't touch are brokered structural holes; a dense mesh is a + tight community; green marks the juniors a mentor brought up; orange marks a + company link on the works shared with that person. Hover any node for its details. +

+
+ +
+ the person (ego) + cohort co-author + their mentee (junior at first joint paper) + company link on works shared with the ego + external academic + collaboration (width = decayed strength) + mostly cross-institution + node size = active years +
+ +
+ +
+ Data: OpenAlex works of the institution cohort (works ≤ 50 authors enter the graph; + edge strength decays 0.8/year), read from the multiplicators_v1 and + multiplicator_networks_v1 indices. Networks show each ego's strongest + co-authors — totals are given per figure. Scores are percentile-normalized within + career buckets; tag threshold 0.85. Config , computed + . Mentee marking uses the seniority-gap rule and is restricted + to cohort members; external co-authors' histories are truncated to shared works, so + their node size is a lower bound. An orange node means a company affiliation appeared + on a work shared with the ego — the company is named in the tooltip. +
+
+ +
+ + + + + diff --git a/service/scripts/profiling/multipliers/requirements.txt b/service/scripts/profiling/multipliers/requirements.txt new file mode 100644 index 00000000..125ead3b --- /dev/null +++ b/service/scripts/profiling/multipliers/requirements.txt @@ -0,0 +1,14 @@ +httpx>=0.27 +python-dotenv>=1.0 +polars>=1.0 +pyyaml>=6.0 + +# The founder-potential stage (founding.py) additionally needs the inference +# stack the shipped models were exported with. Rather than duplicating it here, +# run the pipeline in the `potential` conda env that +# ../founding_potential/README.md defines, with these four added: +# conda run -n potential pip install httpx python-dotenv polars pyyaml +# `--no-founding` runs the pipeline on this file's dependencies alone. + +# test-only (never in the service image): +# pip install pytest networkx diff --git a/service/scripts/profiling/multipliers/scoring.py b/service/scripts/profiling/multipliers/scoring.py new file mode 100644 index 00000000..dd5ea150 --- /dev/null +++ b/service/scripts/profiling/multipliers/scoring.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +""" +scoring.py — normalization, sub-scores and tags (M1, Stage F). + + 1. Bucket every focal author by career stage from `active_years`. + 2. Percentile-rank every raw metric WITHIN its bucket. + 3. Sub-scores = weighted mean of the percentiles (weights from the YAML). + 4. Tag anyone >= tags.threshold on a sub-score (multiple tags allowed). + +Raw values, percentiles and sub-scores are all persisted — coaches and +calibration both need the intermediates. None/NaN raw values are excluded from +ranking and their weight is redistributed. Rationale: docs/ROADMAP.md §3, +"Scoring plumbing". +""" +from __future__ import annotations + +import hashlib +import json +from typing import Any + +import yaml + + +def load_config(path: str) -> dict[str, Any]: + with open(path, "r", encoding="utf-8") as f: + config = yaml.safe_load(f) + config["_config_hash"] = hashlib.sha256( + json.dumps(config, sort_keys=True, default=str).encode() + ).hexdigest()[:12] + return config + + +def career_bucket(active_years: int, thresholds: list[int], names: list[str]) -> str: + """Bucket by active_years. thresholds=[4,9,14] -> Early/Emerging/Established/Senior.""" + for threshold, name in zip(thresholds, names): + if active_years <= threshold: + return name + return names[len(thresholds)] + + +def percentile_ranks(values: dict[str, float | None]) -> dict[str, float]: + """Mean-rank percentiles in (0, 1] over the non-None values. + + Ties share their mean rank, so a mostly-zero metric does not hand everyone + a high percentile. + """ + present = [(aid, v) for aid, v in values.items() if v is not None] + if not present: + return {} + present.sort(key=lambda kv: kv[1]) + n = len(present) + ranks: dict[str, float] = {} + i = 0 + while i < n: + j = i + while j + 1 < n and present[j + 1][1] == present[i][1]: + j += 1 + mean_rank = (i + j) / 2 + 1 # 1-based mean rank of the tie group + for k in range(i, j + 1): + ranks[present[k][0]] = mean_rank / n + i = j + 1 + return ranks + + +def score_rows( + metric_rows: dict[str, dict[str, Any]], config: dict[str, Any] +) -> list[dict[str, Any]]: + """Turn raw metric rows into scored, tagged, bucket-normalized output rows.""" + career_cfg = config["career"] + weights: dict[str, dict[str, float]] = config["weights"] + tag_threshold: float = config["tags"]["threshold"] + min_active_years: int = config["tags"].get("min_active_years", 0) + + # 1. bucket assignment + buckets: dict[str, list[str]] = {} + for aid, row in metric_rows.items(): + bucket = career_bucket( + row["active_years"], career_cfg["buckets"], career_cfg["bucket_names"] + ) + row["career_bucket"] = bucket + buckets.setdefault(bucket, []).append(aid) + + # 2. within-bucket percentiles for every metric used by any sub-score + metric_names = sorted({m for w in weights.values() for m in w}) + percentiles: dict[str, dict[str, float]] = {aid: {} for aid in metric_rows} + for bucket_members in buckets.values(): + for metric in metric_names: + values = { + aid: metric_rows[aid].get(metric) + for aid in bucket_members + if isinstance(metric_rows[aid].get(metric), (int, float)) + } + for aid, pctl in percentile_ranks(values).items(): + percentiles[aid][metric] = pctl + + # 3+4. weighted sub-scores and tags + out: list[dict[str, Any]] = [] + for aid, row in metric_rows.items(): + sub_scores: dict[str, float] = {} + for sub, metric_weights in weights.items(): + total_weight = 0.0 + acc = 0.0 + for metric, weight in metric_weights.items(): + pctl = percentiles[aid].get(metric) + if pctl is not None: + acc += weight * pctl + total_weight += weight + sub_scores[sub] = round(acc / total_weight, 4) if total_weight > 0 else 0.0 + + tags = ( + [s for s, v in sub_scores.items() if v >= tag_threshold] + if row["active_years"] >= min_active_years + else [] + ) + + out.append( + { + **{k: v for k, v in row.items() if k != "junior_ids"}, + "percentiles": { + m: round(p, 4) for m, p in percentiles[aid].items() + }, + "sub_scores": sub_scores, + "tags": tags, + "max_sub_score": max(sub_scores.values()) if sub_scores else 0.0, + "evidence": {"junior_ids": row.get("junior_ids", [])[:25]}, + "config_hash": config["_config_hash"], + } + ) + + out.sort(key=lambda r: r["max_sub_score"], reverse=True) + return out diff --git a/service/scripts/profiling/multipliers/signals.py b/service/scripts/profiling/multipliers/signals.py new file mode 100644 index 00000000..a58151f8 --- /dev/null +++ b/service/scripts/profiling/multipliers/signals.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python3 +""" +signals.py — M3 amplifier signal joins: patents, news, EU CORDIS projects. + +Sources and their link quality (README, "M3 — amplifier signal joins"): + PATENTS org_patents.matched_authors, real OpenAlex author ids. Only + {institution, both} match types are scored; name-only is evidence. + NEWS aktuell_postproc LLM-extracted names, normalized-exact match. + CORDIS DOI overlap, no name matching. + +All joins return plain dict[author_short_id, count] and are independent of the +graph/scoring modules. +""" +from __future__ import annotations + +import gzip +import hashlib +import json +import time +import unicodedata +from collections import defaultdict +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Any + +import httpx + +from service.scripts.profiling.multipliers.extract import INSE_KEY, INSE_URL, es_search + +PAGE_SIZE = 1000 +DOI_BATCH = 500 + + +# --------------------------------------------------------------------- +# Patents — org_patents (already author-ID-linked by index_org_patents.py) +# --------------------------------------------------------------------- + + +def patent_counts( + client: httpx.Client, + institution_short_id: str, + scored_match_types: tuple[str, ...] = ("institution", "both"), +) -> tuple[dict[str, dict[str, Any]], dict[str, int]]: + """Per-author patent profiles from org_patents. Returns (scored, name_only). + + `scored` covers docs whose match_type is in `scored_match_types`: + {"patents": int, "first_patent_year": int|None, + "last_patent_year": int|None, "counts_by_year": {year: int}} + The amplifier uses `patents`; the years feed the founder models off this + same scan. `name_only` is a bare count — evidence only, never scored. + """ + scored: dict[str, dict[str, Any]] = {} + name_only: dict[str, int] = defaultdict(int) + search_after = None + while True: + body: dict[str, Any] = { + "size": PAGE_SIZE, + "_source": [ + "match_type", + "publication_year", + "matched_authors.openalex_author_id", + ], + "query": {"term": {"institution_id": institution_short_id}}, + "sort": [{"patent_id": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + result = es_search(client, INSE_URL, INSE_KEY, "org_patents", body) + hits = result["hits"]["hits"] + if not hits: + break + for hit in hits: + src = hit["_source"] + is_scored = src.get("match_type") in scored_match_types + year = src.get("publication_year") + if not isinstance(year, int): + try: + year = int(str(year).strip()[:4]) + except (TypeError, ValueError): + year = None + for author in src.get("matched_authors") or []: + aid = author.get("openalex_author_id") + if not aid: + continue + if not is_scored: + name_only[aid] += 1 + continue + profile = scored.setdefault( + aid, {"patents": 0, "counts_by_year": {}} + ) + profile["patents"] += 1 + if year is not None: + profile["counts_by_year"][year] = ( + profile["counts_by_year"].get(year, 0) + 1 + ) + search_after = hits[-1]["sort"] + + for profile in scored.values(): + years = sorted(profile["counts_by_year"]) + profile["first_patent_year"] = years[0] if years else None + profile["last_patent_year"] = years[-1] if years else None + return scored, dict(name_only) + + +# --------------------------------------------------------------------- +# Patents, name-matched — higher-recall source for the founder models +# --------------------------------------------------------------------- +# Under `founding.patent_source: api` (production) these profiles are merged +# per-author with the org_patents profiles above. Coverage, cost, the merge +# rationale and this endpoint's known limitations: README, "Feature sourcing". + + +def author_patent_profiles( + author_ids: list[str], + base_url: str, + concurrency: int = 16, + timeout: float = 60.0, + retries: int = 5, + progress_every: int = 500, + max_failed_fraction: float = 0.01, +) -> tuple[dict[str, dict[str, Any]], list[str]]: + """Per-author patent profile from `/api/inse-service/authors/{id}/patents`. + + Returns (profiles, failed_ids). `profiles` contains only authors with >= 1 + patent — callers treat a missing key as zero. `publication_year` arrives as + a string and is coerced from its first four characters. + + Two-stage failure handling: the concurrent pass records failures instead of + raising, then retries them SEQUENTIALLY — under full load the backend 502s + on authors that succeed instantly once pressure drops, so per-request + retries alone are not enough. Raises only if survivors exceed + `max_failed_fraction`; smaller gaps are printed and returned, never silent. + """ + results: dict[str, dict[str, Any]] = {} + done = 0 + + def fetch(client: httpx.Client, author_id: str) -> bool: + """One author; True on success. Retries transient failures in-place.""" + nonlocal done + for attempt in range(retries): + try: + response = client.get( + f"{base_url.rstrip('/')}/api/inse-service/authors/{author_id}/patents" + ) + response.raise_for_status() + break + except (httpx.HTTPError, httpx.HTTPStatusError): + if attempt == retries - 1: + return False + time.sleep(2**attempt) + + patents = response.json().get("patents") or [] + done += 1 + if progress_every and done % progress_every == 0: + print(f" patents: {done}/{len(author_ids)} authors", flush=True) + if not patents: + return True + counts_by_year: dict[int, int] = defaultdict(int) + for patent in patents: + try: + year = int(str(patent.get("publication_year")).strip()[:4]) + except (TypeError, ValueError): + continue + counts_by_year[year] += 1 + years = sorted(counts_by_year) + results[author_id] = { + "patents": len(patents), + "first_patent_year": years[0] if years else None, + "last_patent_year": years[-1] if years else None, + "counts_by_year": dict(counts_by_year), + } + return True + + limits = httpx.Limits(max_connections=concurrency, max_keepalive_connections=concurrency) + with httpx.Client(timeout=timeout, limits=limits) as client: + with ThreadPoolExecutor(max_workers=concurrency) as pool: + outcomes = list(pool.map(lambda aid: fetch(client, aid), author_ids)) + failed = [aid for aid, ok in zip(author_ids, outcomes) if not ok] + + if failed: + print(f" patents: retrying {len(failed)} load-failed authors sequentially") + still_failed = [aid for aid in failed if not fetch(client, aid)] + else: + still_failed = [] + + if len(still_failed) > max(1, int(max_failed_fraction * len(author_ids))): + raise RuntimeError( + f"Patent join failed for {len(still_failed)}/{len(author_ids)} authors " + f"even after sequential retry — backend looks unhealthy, not flaky. " + f"First failures: {still_failed[:5]}" + ) + if still_failed: + print(f" WARNING: patent data missing for {len(still_failed)} authors " + f"(treated as zero patents): {still_failed}") + return results, still_failed + + +def cached_author_patent_profiles( + author_ids: list[str], + base_url: str, + cache_path: Path, + concurrency: int = 16, + force: bool = False, +) -> dict[str, dict[str, Any]]: + """`author_patent_profiles` with a disk cache keyed on the cohort, so a + changed author set invalidates it automatically. The join is the slowest + stage in the pipeline (20-65 min) and the YAML weights it feeds get retuned + repeatedly.""" + cohort_key = hashlib.sha256( + json.dumps(sorted(author_ids)).encode() + ).hexdigest()[:12] + + if not force and cache_path.exists(): + with gzip.open(cache_path, "rt", encoding="utf-8") as f: + cached = json.load(f) + if cached.get("cohort_key") == cohort_key: + failed = cached.get("failed_ids") or [] + print(f"Reusing cached patent join ({len(cached['profiles'])} authors " + f"with patents" + + (f"; {len(failed)} known gaps: {failed}" if failed else "") + + f") — delete {cache_path.name} or pass --force-extract to refresh.") + return { + aid: {**p, "counts_by_year": {int(y): c for y, c in + p["counts_by_year"].items()}} + for aid, p in cached["profiles"].items() + } + print("Cached patent join is for a different cohort — refetching.") + + profiles, failed_ids = author_patent_profiles( + author_ids, base_url, concurrency=concurrency + ) + cache_path.parent.mkdir(parents=True, exist_ok=True) + with gzip.open(cache_path, "wt", encoding="utf-8", newline="\n") as f: + # persisted so gaps stay visible on cached re-runs + json.dump({"cohort_key": cohort_key, "profiles": profiles, + "failed_ids": failed_ids}, f) + return profiles + + +def merge_patent_profiles( + primary: dict[str, dict[str, Any]], + secondary: dict[str, dict[str, Any]], +) -> tuple[dict[str, dict[str, Any]], dict[str, int]]: + """Best-available patent profile per author from two sources. + + Neither source dominates (README, "Feature sourcing"), so per author the + higher `patents` count wins whole (ties -> primary). Counts are never + summed: the same patent can exist in both corpora with no id-level dedup at + this aggregation, so summing would double-count. + + Returns (merged, stats) with stats counting who supplied each profile. + """ + merged: dict[str, dict[str, Any]] = {} + stats = {"primary": 0, "secondary": 0} + for aid in set(primary) | set(secondary): + p, s = primary.get(aid), secondary.get(aid) + if p is not None and (s is None or p["patents"] >= s["patents"]): + merged[aid] = p + stats["primary"] += 1 + else: + merged[aid] = s + stats["secondary"] += 1 + return merged, stats + + +# --------------------------------------------------------------------- +# News — aktuell_postproc (LLM-extracted names, normalized-exact match) +# --------------------------------------------------------------------- + + +def normalize_name(name: str) -> str: + """casefold + strip diacritics + collapse whitespace ("René Müller" -> "rene muller").""" + decomposed = unicodedata.normalize("NFKD", name) + stripped = "".join(c for c in decomposed if not unicodedata.combining(c)) + return " ".join(stripped.casefold().split()) + + +def news_mention_counts( + client: httpx.Client, + display_names: dict[str, str], + require_relevant: bool = True, +) -> tuple[dict[str, int], int]: + """Per-author news mention counts. + + display_names: author_short_id -> display_name for the whole cohort. + Returns (counts, ambiguous_names_skipped). A normalized name shared by more + than one cohort author is skipped entirely — miscrediting is worse than + missing. + """ + by_norm: dict[str, list[str]] = defaultdict(list) + for aid, name in display_names.items(): + if name: + by_norm[normalize_name(name)].append(aid) + ambiguous = {norm for norm, aids in by_norm.items() if len(aids) > 1} + + counts: dict[str, int] = defaultdict(int) + search_after = None + while True: + body: dict[str, Any] = { + "size": PAGE_SIZE, + "_source": ["authors", "relevant"], + "query": {"exists": {"field": "authors"}}, + "sort": [{"news_id.keyword": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + result = es_search(client, INSE_URL, INSE_KEY, "aktuell_postproc", body) + hits = result["hits"]["hits"] + if not hits: + break + for hit in hits: + src = hit["_source"] + if require_relevant and not src.get("relevant"): + continue + for name in src.get("authors") or []: + norm = normalize_name(name) + if norm in ambiguous: + continue + aids = by_norm.get(norm) + if aids: + counts[aids[0]] += 1 + search_after = hits[-1]["sort"] + return dict(counts), len(ambiguous) + + +# --------------------------------------------------------------------- +# EU CORDIS — DOI-overlap join +# --------------------------------------------------------------------- + + +def normalize_doi(doi: str | None) -> str | None: + if not doi: + return None + doi = doi.strip().casefold() + for prefix in ("https://doi.org/", "http://doi.org/", "doi.org/", "doi:"): + if doi.startswith(prefix): + doi = doi[len(prefix):] + return doi or None + + +def cordis_project_counts( + client: httpx.Client, + dois_by_author: dict[str, set[str]], +) -> dict[str, int]: + """Distinct CORDIS project count per author via DOI overlap. + + dois_by_author values must already be normalized (normalize_doi). + """ + all_dois = sorted({d for dois in dois_by_author.values() for d in dois}) + projects_by_doi: dict[str, set[str]] = defaultdict(set) + + for start in range(0, len(all_dois), DOI_BATCH): + batch = all_dois[start : start + DOI_BATCH] + # NOT a terms query: 21% of CORDIS DOIs contain uppercase and `terms` + # on a keyword field is case-sensitive. + result = es_search( + client, INSE_URL, INSE_KEY, "cordis_eu_*_publications", + { + "size": len(batch) * 4, # a DOI can appear in several frameworks + "_source": ["doi", "projectID"], + "query": { + "bool": { + "should": [ + {"term": {"doi": {"value": d, "case_insensitive": True}}} + for d in batch + ], + "minimum_should_match": 1, + } + }, + }, + ) + for hit in result["hits"]["hits"]: + src = hit["_source"] + doi = normalize_doi(src.get("doi")) + project = src.get("projectID") + if doi and project is not None: + projects_by_doi[doi].add(str(project)) + + counts: dict[str, int] = {} + for aid, dois in dois_by_author.items(): + projects: set[str] = set() + for doi in dois: + projects |= projects_by_doi.get(doi, set()) + if projects: + counts[aid] = len(projects) + return counts + + +# --------------------------------------------------------------------- +# Orchestration +# --------------------------------------------------------------------- + + +def collect_signals( + institution_short_id: str, + display_names: dict[str, str], + dois_by_author: dict[str, set[str]], + scored_match_types: tuple[str, ...] = ("institution", "both"), + news_require_relevant: bool = True, +) -> tuple[dict[str, dict[str, int]], dict[str, dict[str, Any]]]: + """All signal joins. + + Returns (metrics, org_patent_profiles). `metrics` are flat per-metric dicts + merged onto the metric rows and scored; `org_patent_profiles` is the nested + per-author structure from the same scan, returned separately because it + must NOT be merged onto a metric row. + """ + with httpx.Client() as client: + patents_scored, patents_name_only = patent_counts( + client, institution_short_id, scored_match_types + ) + news, ambiguous_skipped = news_mention_counts( + client, display_names, require_relevant=news_require_relevant + ) + cordis = cordis_project_counts(client, dois_by_author) + print( + f"Signals: patents scored for {len(patents_scored)} authors " + f"(name-only evidence: {len(patents_name_only)}), " + f"news mentions for {len(news)} (ambiguous names skipped: {ambiguous_skipped}), " + f"CORDIS projects for {len(cordis)}" + ) + metrics = { + "patent_count": {aid: p["patents"] for aid, p in patents_scored.items()}, + "patent_count_name_only": patents_name_only, + "news_mentions": news, + "cordis_eu_projects": cordis, + } + return metrics, patents_scored diff --git a/service/scripts/profiling/multipliers/spike_audit.py b/service/scripts/profiling/multipliers/spike_audit.py new file mode 100644 index 00000000..c60d0cd0 --- /dev/null +++ b/service/scripts/profiling/multipliers/spike_audit.py @@ -0,0 +1,639 @@ +#!/usr/bin/env python3 +""" +spike_audit.py — M0 de-risking spike for the multiplicator-detection module. + +Extracts the institution's OpenAlex author set (two-group union) and the +FULL-authorship work set for those authors, caches both as gzipped JSONL, and +prints an audit report covering: reproduction (author/work counts), field +coverage (author_position / is_corresponding / institution type), scale +(authors-per-work histogram, pair counts at caps 20/50/100), profile quality, +INSE cluster permissions, and org_patents signal reachability. + +Findings and what each one decided: README, "M0 spike results". + +Usage: + python service/scripts/multipliers/spike_audit.py --institution-id I62318514 + +Credentials come from service/src/main/inse/.env. Nothing is written to the real +cluster unless --probe-writes is passed (it creates and deletes a throwaway index). +""" +from __future__ import annotations + +import argparse +import collections +import gzip +import json +import math +import os +import statistics +import sys +import time +from pathlib import Path +from typing import Any, Iterable, Iterator + +import httpx +import yaml +from dotenv import load_dotenv + +SCRIPT_DIR = Path(__file__).resolve().parent +ENV_PATH = SCRIPT_DIR.parent.parent / "src" / "main" / "inse" / ".env" +load_dotenv(dotenv_path=ENV_PATH) + +# --- clusters ------------------------------------------------------------- + +NES_URL = (os.environ.get("ELASTICSEARCH_URL") or "").rstrip("/") +NES_KEY = os.environ.get("ELASTICSEARCH_API_KEY") or "" +INSE_URL = (os.environ.get("ELASTICSEARCH_INSE_URL") or "").rstrip("/") +INSE_KEY = os.environ.get("ELASTICSEARCH_INSE_API_KEY") or "" + +# --- extraction knobs (spike-only; the real build reads these from YAML) -- + +AFFILIATION_YEAR_GTE = 2025 +WORK_YEAR_GTE = 1950 +AUTHOR_PAGE_SIZE = 1000 +AUTHOR_BATCH_SIZE = 250 +WORK_PAGE_SIZE = 1000 +PAIR_CAPS = (20, 50, 100) +REQUEST_TIMEOUT = 180.0 +PROBE_INDEX = "multiplicators_spike_probe" + + +# ES helpers + + +def _headers(api_key: str) -> dict[str, str]: + return { + "Authorization": f"ApiKey {api_key}", + "Content-Type": "application/json", + "Accept": "application/json", + } + + +def es_request( + client: httpx.Client, + method: str, + base_url: str, + api_key: str, + path: str, + body: dict[str, Any] | None = None, +) -> httpx.Response: + url = f"{base_url}/{path.lstrip('/')}" + return client.request( + method, url, headers=_headers(api_key), json=body, timeout=REQUEST_TIMEOUT + ) + + +def es_search( + client: httpx.Client, base_url: str, api_key: str, index: str, body: dict[str, Any] +) -> dict[str, Any]: + response = es_request(client, "POST", base_url, api_key, f"{index}/_search", body) + if not response.is_success: + raise RuntimeError( + f"ES error {response.status_code} for {index}:\n{response.text[:1000]}" + ) + return response.json() + + +# --------------------------------------------------------------------- +# Institution resolution +# --------------------------------------------------------------------- + + +def resolve_institution(client: httpx.Client, institution_id: str) -> dict[str, Any]: + """Look up ror + display_name for --institution-id from openalex-institutions.""" + raw = institution_id.strip() + short = raw.rsplit("/", 1)[-1] + full = f"https://openalex.org/{short}" + + result = es_search( + client, + NES_URL, + NES_KEY, + "openalex-institutions", + {"size": 1, "query": {"term": {"id": full}}}, + ) + hits = result["hits"]["hits"] + if not hits: + raise SystemExit(f"Institution {full} not found in openalex-institutions.") + + source = hits[0]["_source"] + return { + "id": full, + "short_id": short, + "ror": source.get("ror"), + "display_name": source.get("display_name"), + } + + +# --------------------------------------------------------------------- +# Author queries (two-group union — group 2 recovers empty-last-known authors) +# --------------------------------------------------------------------- + + +def recent_affiliation_filter(insts: list[dict[str, Any]]) -> dict[str, Any]: + """Recent affiliation with ANY cohort institution (matched by id, ror as backup).""" + ids = [i["id"] for i in insts] + shoulds: list[dict[str, Any]] = [{"terms": {"affiliations.institution.id": ids}}] + rors = [i["ror"] for i in insts if i.get("ror")] + if rors: + shoulds.append({"terms": {"affiliations.institution.ror": rors}}) + return { + "nested": { + "path": "affiliations", + "query": { + "bool": { + "filter": [ + {"bool": {"should": shoulds, "minimum_should_match": 1}}, + {"range": {"affiliations.years": {"gte": AFFILIATION_YEAR_GTE}}}, + ] + } + }, + } + } + + +def last_known_filter(insts: list[dict[str, Any]]) -> dict[str, Any]: + """last_known_institutions membership in the cohort, matched by ID.""" + return { + "nested": { + "path": "last_known_institutions", + "query": { + "terms": {"last_known_institutions.id": [i["id"] for i in insts]} + }, + } + } + + +def last_known_exists_filter() -> dict[str, Any]: + return { + "nested": { + "path": "last_known_institutions", + "query": {"exists": {"field": "last_known_institutions.display_name"}}, + } + } + + +AUTHOR_SOURCE = [ + "id", + "display_name", + "orcid", + "works_count", + "cited_by_count", + "last_known_institutions", + "affiliations", +] + + +def author_query(query: dict[str, Any], search_after: Any) -> dict[str, Any]: + body = { + "size": AUTHOR_PAGE_SIZE, + "track_total_hits": True, + "_source": AUTHOR_SOURCE, + "query": query, + "sort": [{"id": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + return body + + +def collect_authors( + client: httpx.Client, insts: list[dict[str, Any]] +) -> dict[str, dict[str, Any]]: + groups = { + "backend_compatible": { + "bool": { + "filter": [last_known_filter(insts), recent_affiliation_filter(insts)] + } + }, + "empty_last_known_recent": { + "bool": { + "filter": [recent_affiliation_filter(insts)], + "must_not": [last_known_exists_filter()], + } + }, + } + + authors: dict[str, dict[str, Any]] = {} + for group_name, query in groups.items(): + search_after = None + total = None + read = 0 + while True: + result = es_search( + client, NES_URL, NES_KEY, "openalex-authors", + author_query(query, search_after), + ) + hits = result["hits"]["hits"] + if total is None: + total = result["hits"]["total"]["value"] + print(f" [{group_name}] expected {total}") + if not hits: + break + for hit in hits: + src = hit["_source"] + aid = src.get("id") + if not aid: + continue + if aid not in authors: + authors[aid] = { + "id": aid, + "display_name": src.get("display_name"), + "orcid": src.get("orcid"), + "works_count": src.get("works_count"), + "cited_by_count": src.get("cited_by_count"), + "source_sets": [group_name], + } + elif group_name not in authors[aid]["source_sets"]: + authors[aid]["source_sets"].append(group_name) + read += 1 + search_after = hits[-1]["sort"] + print(f" [{group_name}] read {read}/{total}") + time.sleep(0.05) + return authors + + +# --------------------------------------------------------------------- +# Work queries — FULL authorships, no inner_hits +# --------------------------------------------------------------------- + +WORK_SOURCE = [ + "id", + "doi", + "publication_year", + "type", + "cited_by_count", + "primary_topic.id", + "primary_topic.display_name", + "primary_topic.field.id", + "primary_topic.field.display_name", + "authorships.author.id", + "authorships.author.display_name", + "authorships.author_position", + "authorships.is_corresponding", + "authorships.institutions.id", + "authorships.institutions.display_name", + "authorships.institutions.type", + "authorships.institutions.country_code", + "authorships.institutions.lineage", +] + + +def works_batch_query(author_ids: list[str], search_after: Any) -> dict[str, Any]: + body = { + "size": WORK_PAGE_SIZE, + "track_total_hits": True, + "_source": WORK_SOURCE, + "query": { + "bool": { + "filter": [ + {"range": {"publication_year": {"gte": WORK_YEAR_GTE}}}, + { + "nested": { + "path": "authorships", + "query": {"terms": {"authorships.author.id": author_ids}}, + } + }, + ] + } + }, + "sort": [{"id": {"order": "asc"}}], + } + if search_after: + body["search_after"] = search_after + return body + + +def collect_works( + client: httpx.Client, author_ids: list[str] +) -> dict[str, dict[str, Any]]: + works: dict[str, dict[str, Any]] = {} + total_batches = (len(author_ids) + AUTHOR_BATCH_SIZE - 1) // AUTHOR_BATCH_SIZE + for i in range(0, len(author_ids), AUTHOR_BATCH_SIZE): + batch = author_ids[i : i + AUTHOR_BATCH_SIZE] + batch_no = i // AUTHOR_BATCH_SIZE + 1 + search_after = None + while True: + result = es_search( + client, NES_URL, NES_KEY, "openalex-works*", + works_batch_query(batch, search_after), + ) + hits = result["hits"]["hits"] + if not hits: + break + for hit in hits: + src = hit["_source"] + wid = src.get("id") + if wid and wid not in works: + works[wid] = src + search_after = hits[-1]["sort"] + print(f" work batch {batch_no}/{total_batches}: unique works {len(works)}") + time.sleep(0.05) + return works + + +# --------------------------------------------------------------------- +# Cache IO +# --------------------------------------------------------------------- + + +def write_jsonl_gz(path: Path, records: Iterable[dict[str, Any]]) -> None: + with gzip.open(path, "wt", encoding="utf-8", newline="\n") as f: + for record in records: + f.write(json.dumps(record, ensure_ascii=True) + "\n") + + +def read_jsonl_gz(path: Path) -> Iterator[dict[str, Any]]: + with gzip.open(path, "rt", encoding="utf-8") as f: + for line in f: + line = line.strip() + if line: + yield json.loads(line) + + +# --------------------------------------------------------------------- +# Audit computations +# --------------------------------------------------------------------- + + +def _percentile(sorted_vals: list[int], q: float) -> int: + if not sorted_vals: + return 0 + idx = min(len(sorted_vals) - 1, int(math.ceil(q * len(sorted_vals)) - 1)) + return sorted_vals[max(0, idx)] + + +def audit_field_coverage(works: list[dict[str, Any]]) -> dict[str, Any]: + n_authorships = 0 + with_position = 0 + with_corresponding = 0 + n_institutions = 0 + with_inst_type = 0 + company_institutions = 0 + + for w in works: + for a in w.get("authorships", []) or []: + n_authorships += 1 + if a.get("author_position"): + with_position += 1 + if a.get("is_corresponding") is not None: + with_corresponding += 1 + for inst in a.get("institutions", []) or []: + n_institutions += 1 + itype = inst.get("type") + if itype: + with_inst_type += 1 + if itype == "company": + company_institutions += 1 + + def pct(x: int, n: int) -> float: + return round(100.0 * x / n, 2) if n else 0.0 + + return { + "authorships_total": n_authorships, + "author_position_pct": pct(with_position, n_authorships), + "is_corresponding_pct": pct(with_corresponding, n_authorships), + "institutions_total": n_institutions, + "institution_type_pct": pct(with_inst_type, n_institutions), + "company_institutions": company_institutions, + } + + +def audit_scale(works: list[dict[str, Any]]) -> dict[str, Any]: + sizes: list[int] = [] + pairs_at_cap = {cap: 0 for cap in PAIR_CAPS} + for w in works: + author_ids = { + a["author"]["id"] + for a in (w.get("authorships") or []) + if a.get("author", {}).get("id") + } + n = len(author_ids) + sizes.append(n) + for cap in PAIR_CAPS: + if 2 <= n <= cap: + pairs_at_cap[cap] += n * (n - 1) // 2 + sizes_sorted = sorted(sizes) + return { + "works": len(sizes), + "authors_per_work": { + "p50": _percentile(sizes_sorted, 0.50), + "p90": _percentile(sizes_sorted, 0.90), + "p99": _percentile(sizes_sorted, 0.99), + "max": sizes_sorted[-1] if sizes_sorted else 0, + }, + "hyperauthorship_works_gt_100": sum(1 for s in sizes if s > 100), + "pair_instances_at_cap": pairs_at_cap, + } + + +def audit_career( + author_ids: set[str], works: list[dict[str, Any]] +) -> dict[str, Any]: + """active_years and suspicious-profile flags for in-set authors (exact history).""" + years_by_author: dict[str, set[int]] = collections.defaultdict(set) + for w in works: + year = w.get("publication_year") + if not isinstance(year, int): + continue + for a in w.get("authorships", []) or []: + aid = a.get("author", {}).get("id") + if aid in author_ids: + years_by_author[aid].add(year) + + active_years_list: list[int] = [] + suspicious = 0 + for aid in author_ids: + years = years_by_author.get(aid) + if not years: + continue + active_years_list.append(len(years)) + first_year = min(years) + span = max(years) - first_year + 1 + if first_year < 1970 or span > 60: + suspicious += 1 + + ay_sorted = sorted(active_years_list) + return { + "authors_with_works": len(ay_sorted), + "suspicious_profile_count": suspicious, + "suspicious_profile_pct": ( + round(100.0 * suspicious / len(ay_sorted), 2) if ay_sorted else 0.0 + ), + "active_years": { + "p50": _percentile(ay_sorted, 0.50), + "p90": _percentile(ay_sorted, 0.90), + "max": ay_sorted[-1] if ay_sorted else 0, + "mean": round(statistics.fmean(ay_sorted), 2) if ay_sorted else 0.0, + }, + } + + +def audit_signals(client: httpx.Client, inst: dict[str, Any]) -> dict[str, Any]: + """Probe org_patents (INSE cluster) for matched_authors + match_type breakdown.""" + if not INSE_URL or not INSE_KEY: + return {"error": "INSE cluster credentials missing"} + try: + result = es_search( + client, INSE_URL, INSE_KEY, "org_patents", + { + "size": 0, + "track_total_hits": True, + "query": {"term": {"institution_id": inst["short_id"]}}, + "aggs": {"by_match_type": {"terms": {"field": "match_type"}}}, + }, + ) + except RuntimeError as exc: + return {"error": str(exc)[:300]} + buckets = ( + result.get("aggregations", {}).get("by_match_type", {}).get("buckets", []) + ) + return { + "org_patents_for_institution": result["hits"]["total"]["value"], + "match_type_breakdown": {b["key"]: b["doc_count"] for b in buckets}, + } + + +def audit_permissions(client: httpx.Client, probe_writes: bool) -> dict[str, Any]: + """Test create / bulk / delete-by-query / delete on the INSE cluster.""" + if not probe_writes: + return {"skipped": "pass --probe-writes to test index create/bulk/delete"} + if not INSE_URL or not INSE_KEY: + return {"error": "INSE cluster credentials missing"} + + out: dict[str, Any] = {} + create = es_request( + client, "PUT", INSE_URL, INSE_KEY, PROBE_INDEX, + {"mappings": {"properties": {"institution_id": {"type": "keyword"}}}}, + ) + out["create_index"] = create.status_code + if create.is_success: + bulk_body = ( + json.dumps({"index": {"_index": PROBE_INDEX, "_id": "probe_1"}}) + + "\n" + + json.dumps({"institution_id": "PROBE"}) + + "\n" + ) + bulk = client.post( + f"{INSE_URL}/_bulk", + headers={**_headers(INSE_KEY), "Content-Type": "application/x-ndjson"}, + content=bulk_body, + timeout=REQUEST_TIMEOUT, + ) + out["bulk_index"] = bulk.status_code + client.post(f"{INSE_URL}/{PROBE_INDEX}/_refresh", headers=_headers(INSE_KEY)) + dbq = es_request( + client, "POST", INSE_URL, INSE_KEY, f"{PROBE_INDEX}/_delete_by_query", + {"query": {"term": {"institution_id": "PROBE"}}}, + ) + out["delete_by_query"] = dbq.status_code # expect 403 if it mirrors org_patents + drop = es_request(client, "DELETE", INSE_URL, INSE_KEY, PROBE_INDEX) + out["delete_index"] = drop.status_code + return out + + +# --------------------------------------------------------------------- +# Main +# --------------------------------------------------------------------- + + +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"), + help="YAML config; its cohorts..institution_ids extends the author set " + "beyond the primary institution (e.g. the university hospital).", + ) + parser.add_argument( + "--cache-dir", default=str(SCRIPT_DIR / "cache"), + help="Where to read/write the extracted author/work JSONL.gz", + ) + parser.add_argument( + "--skip-extract", action="store_true", + help="Reuse cached JSONL.gz instead of hitting ES for author/work extraction.", + ) + parser.add_argument( + "--probe-writes", action="store_true", + help="Create+bulk+delete a throwaway index on INSE to test write permissions.", + ) + args = parser.parse_args() + + if not NES_URL or not NES_KEY: + raise SystemExit(f"Missing NES credentials. Checked {ENV_PATH}") + + cache_dir = Path(args.cache_dir) + cache_dir.mkdir(parents=True, exist_ok=True) + short = args.institution_id.strip().rsplit("/", 1)[-1] + authors_path = cache_dir / f"authors_{short}.jsonl.gz" + works_path = cache_dir / f"works_{short}.jsonl.gz" + + cohort_ids = [short] + config_path = Path(args.config) + if config_path.exists(): + with open(config_path, "r", encoding="utf-8") as f: + cfg = yaml.safe_load(f) or {} + cohort_cfg = (cfg.get("cohorts") or {}).get(short) or {} + if cohort_cfg.get("institution_ids"): + cohort_ids = [str(i) for i in cohort_cfg["institution_ids"]] + + with httpx.Client() as client: + insts = [resolve_institution(client, i) for i in cohort_ids] + inst = insts[0] # primary + print(f"Cohort ({len(insts)} institutions):") + for i in insts: + print(f" {i['short_id']:<14} {i['display_name']}") + + if args.skip_extract and authors_path.exists() and works_path.exists(): + print("Reusing cached extract.") + authors = {a["id"]: a for a in read_jsonl_gz(authors_path)} + works = list(read_jsonl_gz(works_path)) + else: + print("\nExtracting authors...") + authors = collect_authors(client, insts) + write_jsonl_gz(authors_path, authors.values()) + print(f"Authors: {len(authors)} -> {authors_path}") + + print("\nExtracting works (full authorships)...") + author_ids = sorted(authors.keys()) + works_map = collect_works(client, author_ids) + works = list(works_map.values()) + write_jsonl_gz(works_path, works) + print(f"Works: {len(works)} -> {works_path}") + + author_id_set = set(authors.keys()) + + print("\nComputing audit...") + report = { + "institution": inst, + "cohort": [ + {"id": i["short_id"], "display_name": i["display_name"]} for i in insts + ], + "reproduction": { + "author_count": len(authors), + "work_count": len(works), + "group_breakdown": dict( + collections.Counter( + tuple(sorted(a["source_sets"])) and "+".join(sorted(a["source_sets"])) + for a in authors.values() + ) + ), + }, + "field_coverage": audit_field_coverage(works), + "scale": audit_scale(works), + "career_quality": audit_career(author_id_set, works), + "signals": audit_signals(client, inst), + "permissions": audit_permissions(client, args.probe_writes), + } + + report_path = cache_dir / f"spike_report_{short}.json" + with open(report_path, "w", encoding="utf-8", newline="\n") as f: + json.dump(report, f, ensure_ascii=False, indent=2) + + print("\n=== SPIKE AUDIT REPORT ===") + print(json.dumps(report, ensure_ascii=False, indent=2)) + print(f"\nWritten: {report_path}") + + +if __name__ == "__main__": + main() diff --git a/service/scripts/profiling/multipliers/stats.md b/service/scripts/profiling/multipliers/stats.md new file mode 100644 index 00000000..65d737d1 --- /dev/null +++ b/service/scripts/profiling/multipliers/stats.md @@ -0,0 +1,264 @@ +# `multiplicators_v1` — what every number means, and what the cohort looks like + +Two parts: + +- **Part A** documents every field a coach or backend developer will meet in a + `multiplicators_v1` document, using one real person — **Pedro José Marrón** + (`_id I62318514_A5047117780`, Senior, Computer Science) — as the worked + example, with the arithmetic shown. +- **Part B** is the measured statistics of the current UDE index (9,474 + documents, run of 2026-08-07, v2 symmetric models, merged patent sources). + +Part B is regenerable at any time — different thresholds included — with: + +```bash +conda run -n potential python -m service.scripts.profiling.multipliers.founding_stats \ + --institution-id I62318514 --threshold 90 --min-pubs 7 \ + --out service/scripts/profiling/multipliers/stats_generated_I62318514.md +``` + +--- + +# Part A — reading one document + +Every person carries **two unrelated kinds of percentile**. Keeping them apart +is the single most important thing to understand about this index: + +| | multiplicator `percentiles.*` / `sub_scores.*` | `founding.percentile` | +|---|---|---| +| compared against | **this cohort**, within the person's **career bucket** | a **fixed external reference cohort** (~9k academics from the 8 training universities) | +| produced by | percentile-ranking of behavioural metrics we compute and can defend line by line | a pre-trained LightGBM model (v2, symmetric landmark design) | +| answers | "who stands out *here*, among peers at the same career stage" | "does this profile resemble people who actually founded companies" | + +## A.1 Career context + +| field | Pedro | meaning | +|---|---|---| +| `active_years` | 28 | Distinct calendar years with ≥1 publication — the robust seniority measure (debut years are unreliable in OpenAlex; one merged 1893 paper shifts this by exactly 1). | +| `career_bucket` | Senior | Early ≤4, Emerging ≤9, Established ≤14, Senior >14 active years. **Every multiplicator percentile below compares him to Seniors only.** | +| `n_works` | 285 | Works in the extract. | +| `suspicious_profile` | false | Merged-identity flag (first year <1970 or span >60). | + +## A.2 Multiplicator metrics — raw value → within-bucket percentile → sub-score + +The pipeline stores all three layers so every score has receipts: raw metric, +its percentile **among the same career bucket**, and the weighted sub-score. + +### Bridger — `sub_scores.bridger = 0.4936` + +| metric | raw | percentile (among Seniors) | weight | +|---|---|---|---| +| `betweenness` | 0.0096 | 0.9335 | 0.35 | +| `brokerage` (1 − Burt constraint) | 0.853 | 0.1685 | 0.25 | +| `field_entropy` | 1.60 bits | 0.4905 | 0.20 | +| `cross_institution_share` | 0.355 | 0.1330 | 0.20 | + +`0.35·0.9335 + 0.25·0.1685 + 0.20·0.4905 + 0.20·0.1330 = 0.4936` ✓ + +Reading: his co-authorship position is a genuine traffic hub *inside* the +cohort (93rd pctl betweenness), but his ego-network is *denser than most +Seniors'* (brokerage raw 0.853 sounds high, yet is only the 17th percentile — +Seniors typically bridge more disconnected contacts) and his collaboration +weight is mostly within-institution. Net: an average bridger for his stage. +This is the within-bucket normalization doing its job — a raw value carries no +meaning until compared with stage peers. + +### Mentor — `sub_scores.mentor = 0.7815` (his best; tag line is 0.85) + +| metric | raw | percentile | weight | +|---|---|---|---| +| `juniors_mentored` | 18 | 0.7905 | 0.35 | +| `mentoring_rate` (juniors ÷ active years) | 0.643 | 0.7553 | 0.25 | +| `last_author_with_junior_first` | 23 | 0.9811 | 0.25 | +| `junior_progression_rate` | 0.333 | 0.4714 | 0.15 | + +`0.35·0.7905 + 0.25·0.7553 + 0.25·0.9811 + 0.15·0.4714 = 0.7815` ✓ + +Reading: 18 cohort co-authors began their careers publishing with him while he +was Established+ (their ids are in `evidence.junior_ids` — receipts, not just a +number), and 23 papers show the classic supervision signature (him last author, +an early-career person first) — 98th percentile among Seniors. A strong, +evidence-backed mentor just below the tag threshold; `max_sub_score = 0.7815`, +`tags = []`. + +### Amplifier — `sub_scores.amplifier = 0.6681` + +| metric | raw | percentile | weight | +|---|---|---|---| +| `industry_coauthor_share_shrunk` | 0.039 | 0.3731 | 0.50 | +| `patent_count` (institution-linked) | 1 | 0.9888 | 0.25 | +| `cordis_eu_projects` (DOI-joined) | 4 | 0.9097 | 0.15 | +| `news_mentions` (name-matched, ambiguity-guarded) | 18 | 0.9791 | 0.10 | + +`0.50·0.3731 + 0.25·0.9888 + 0.15·0.9097 + 0.10·0.9791 = 0.6681` ✓ + +Reading: visible in patents, EU projects and the press (all ≥90th pctl), but +industry co-authorship — the highest-weighted, id-linked channel — is modest +(9 of ~230 typed works), which caps the sub-score. + +## A.3 Founder potential — `founding.*` + +| field | Pedro | how to read it | +|---|---|---| +| `percentile` | **53.9** | **The coach-facing number.** His profile scores higher than ~54% of the reference cohort of comparable academics. Mid-pack — neither a founder-shaped profile nor the opposite. `null` would mean out of population (never rank those). | +| `probability_raw` | 0.2451 | Raw case-control model output behind the percentile. Trained at ~26% founder base rate → **not** a real-world founding probability; never display it as one. | +| `in_population` | true | ≥4 publications; he has 285. | +| `p_within_1y_percentile` | 49.5 | Percentile for "profile resembles people 1 year before founding". | +| `p_within_3y_percentile` | 32.4 | … 3 years before. | +| `p_within_5y_percentile` | 57.2 | … 5 years before. His ordering (5y > 1y > 3y) is mild and non-monotone — no urgent timing signal; contrast a sharp riser whose 1y ≫ 5y. | +| `p_within_{k}y_raw` | 0.199 / 0.078 / 0.268 | Case-control raws for the above — same caveat as `probability_raw`. | +| `predicted_founding_age` | 19.95 | Sequence model (transformer): "this activity pattern looks like founding-moment patterns ~20 years into a career". | +| `current_career_age` | 30 | 2026 − 1996. | +| `years_to_founding` | −10.0 | 19.95 − 30. Negative = the pattern-matched moment lies in his past. | +| `timing_applicable` | **false** | Career age 30 > 20, the only regime the sequence models ever saw. **The three timing fields above must be ignored for him** — that is exactly what this flag is for. The v2 horizon percentiles remain valid (they are separate models with no such window). | +| `classifier_model` | lightgbm_symmetric_founder_classifier_v2 | Provenance — which bundle produced the propensity numbers. | +| `as_of_year` | 2026 | Snapshot year (newest publication year in the corpus, not wall clock). | +| `patent_source` | api+org_patents | His patent features come from the per-author merge of the name-matched EPO/USPTO endpoint and the institution-assigned `org_patents`. | + +## A.4 `founding_features.*` — the evidence behind the founder score + +The exact input record the v2 models saw. A coach questioning the 53.9 reads +this, not the model's mind. + +| field | Pedro | note | +|---|---|---| +| `publications` | 285 | | +| `patents` / `first_patent_year` | 1 / 2015 | merged best-of-both-sources profile | +| `grants` / `grants_capped` | 24 / 24.0 | raw distinct award ids; cap changes nothing at 24 grants / 285 papers (the cap exists for consortium artifacts like 7,934 grants on 76 papers) | +| `first_publication_year` / `first_grant_year` | 1996 / 2009 | | +| `industry_collab_papers` | 9 | works with ≥1 company-affiliated co-author | +| `linked_patents_to_publications` | 0 | not derivable in this corpus (needs a patent→paper citation graph); documented model default | +| `publication_research_area` / `grant_research_area` | 46 / 46 | Information & Computing Sciences (FOR division, mapped from OpenAlex fields) | + +Why is a 285-publication Senior only at percentile 54? Because the v2 model — +by its own training data — favours *focused, mid-volume, patent/industry-heavy* +profiles: 5–17 publications at the index year score highest, and scores decline +with volume ("hyper-prolific researchers found less" in the cleaned training +cohort). His single patent and 9 industry collaborations don't offset 285 +publications over 30 years. Whether that decline is fully real or partly +residual data artifact is an open upstream question (v2 README, "Known +limitations") — one more reason the raw evidence ships with the score. + +## A.5 Plumbing + +| field | meaning | +|---|---| +| `evidence.junior_ids` | The mentees behind `juniors_mentored` (capped at 25). | +| `config_hash` | Hash of `multipliers.yaml` that produced the scores — scores are weight-dependent; this keeps them attributable after retunes. | +| `computed_at`, `institution_id`, `cohort_institution_ids` | Run timestamp; which university; the 9 institutions defining its cohort. | + +--- + +# Part B — the cohort, measured (I62318514, 2026-08-07) + +Snapshot of `founding_stats.py` output; regenerate with the command at the top +(full machine-generated copy: `stats_generated_I62318514.md`). + +**No binary "is a founder" exists in v2** — it emits a percentile. "Identified +as founder potential" below is the operational cutoff `percentile ≥ 90` +("shortlist"), and every table shows it next to the **robust** variant +(`AND publications ≥ 7`) because of the measured boundary artifact: profiles +with 4–6 publications sit just above the model's ≥4 population cut and +dominate the raw top band. + +## B.1 Who is shortlisted, by career stage + +| career stage | in population | pctl ≥90 | … AND pubs ≥7 (robust) | +|---|---|---|---| +| Early | 1,599 | 194 | **3** | +| Emerging | 1,591 | 50 | **33** | +| Established | 777 | 19 | **19** | +| Senior | 1,745 | 7 | **7** | +| **ALL** | 5,712 | 270 | **62** | + +208 of the 270 raw shortlist rows are the boundary artifact (<7 publications, +median career age 23 with median 4 active years — dormant or split-fragment +profiles). After screening, **founder potential concentrates in Emerging and +Established researchers** — face-valid: old enough to have a record, young +enough to leave. + +## B.2 Founder potential × multiplicator archetypes + +Tag overlap is essentially zero (0 mentors, 1 bridger, 0 amplifiers in the +raw shortlist; 0/0/0 in the robust one), and even at the softer +`sub_score ≥ 0.7` view only 4 bridger-ish and 8 amplifier-ish people appear +among the robust 62. The reverse view explains it: + +| tagged as | n (in pop.) | founding pctl p50 | p90 | n ≥40 | +|---|---|---|---|---| +| mentor | 161 | 10 | 47 | 25 | +| bridger | 124 | 10 | 62 | 23 | +| amplifier | 10 | 15 | 59 | 4 | + +**Multiplicators and founder-potential people are different populations.** +Multiplicator tags select prolific seniors; the v2 founder model scores +focused mid-volume profiles highest and declines with volume. Practical +consequence for coach queries: *"mentors above founding percentile 40"* is a +real shortlist (~25 people); *"above 90"* selects nobody. These are +complementary lenses, not one ranking. + +## B.3 Research areas (FOR divisions from OpenAlex publication fields) + +Cohort vs robust shortlist — over/under-representation is the story: + +| area | cohort (in pop.) | robust shortlist | ratio | +|---|---|---|---| +| 35 Commerce, Management, Tourism & Services | 1.9% | **12.9%** | **6.6×** | +| 46 Information & Computing Sciences | 4.0% | **11.3%** | **2.8×** | +| 40 Engineering | 18.8% | 21.0% | 1.1× | +| 32 Biomedical & Clinical Sciences | 44.3% | 37.1% | 0.8× | +| 31 Biological Sciences | 6.8% | 1.6% | 0.2× | +| 51 Physical Sciences | 2.4% | 0.0% | 0 | + +Business, computing and engineering profiles over-index; pure life/physical +sciences under-index — consistent with the founder literature and a sanity +check that the score is not noise. + +## B.4 Which factors drive founder identification + +**Training-side (the model's own permutation importance, v2):** having a +patent research area at all (top feature), publication *rate*, +first-publication year, industry collaborations, career age, patent count and +patent rate. ⚠️ One deployment caveat: `patent_research_area` is constant +`"n."` in this index (no IPC→FOR mapping yet), so the model's #1 feature +separates nothing *locally*, and the 152 patent holders sit slightly off the +training manifold. Wiring the backend's `ipc_openalex_mapping` into +`founding.py` would unlock it. + +**Cohort-side (Spearman ρ vs `founding.percentile`, robust column = +pubs ≥ 7, n = 4,571):** + +| observable | ρ (all in pop.) | ρ (pubs ≥7) | +|---|---|---| +| grants_capped | −0.582 | −0.563 | +| activity density (active_years/career_age) | −0.535 | **−0.557** | +| pub_rate | −0.574 | −0.502 | +| career_age | +0.258 | **+0.456** | +| sub_score bridger / mentor / amplifier | −0.27 / −0.14 / −0.14 | −0.36 / −0.25 / −0.20 | +| publications | −0.260 | **−0.061** | +| patents | +0.027 | +0.046 | + +Read together: raw publication *volume* stops mattering once the boundary zone +is screened (−0.06), while **low activity density and long career age remain +the strongest local drivers** — the score rewards "long career, sparse/paused +publishing", with heavy grant acquisition as the strongest counter-signal. +That pattern extends beyond the <7-pubs zone, which is the main open question +for the model owner: whether "dormancy" is genuine founder signal +(founders wind down publishing pre-founding) or residual artifact — and +whether the population rule should gain an activity-density term rather than +only a publication floor. + +## B.5 Standing caveats + +1. `probability_raw` / `p_within_*_raw` are case-control scores, never + population probabilities. +2. Always filter `in_population: true`; add `publications >= 7` for + coach-facing shortlists until the boundary rule is revisited upstream. +3. `timing_applicable: false` invalidates the three sequence-timing fields for + that person (36% of the cohort, mostly Seniors) — the horizon percentiles + stay valid. +4. Patent evidence is the per-author best of two sources (`api+org_patents`); + a 0 means "nothing found", not "provably none". +5. The grants de-inflation cap under-caps extreme consortium profiles + (shipped-table defect, reported upstream); `grants_capped` records what the + model actually used. diff --git a/service/scripts/profiling/multipliers/stats_generated_I62318514.md b/service/scripts/profiling/multipliers/stats_generated_I62318514.md new file mode 100644 index 00000000..4f2dbc34 --- /dev/null +++ b/service/scripts/profiling/multipliers/stats_generated_I62318514.md @@ -0,0 +1,131 @@ +# Founder-potential statistics — I62318514 + +Generated by `founding_stats.py` from the live `multiplicators_v1` index (9474 documents, config_hash of the newest run applies). Shortlist = `founding.percentile >= 90`; robust = additionally `publications >= 7`. Regenerate with: + +```bash +conda run -n potential python -m service.scripts.profiling.multipliers.founding_stats \ + --institution-id I62318514 --threshold 90 --min-pubs 7 +``` + +## 1. Cohort overview + +| | n | share | +|---|---|---| +| documents | 9474 | 100% | +| `founding.in_population` (≥4 publications) | 5712 | 60.3% | +| `founding.timing_applicable` | 6118 | 64.6% | +| ≥1 patent (`founding_features.patents`) | 152 | 1.6% | +| patent provenance | api+org_patents | | + +| career stage | n | share | +|---|---|---| +| Early | 5361 | 56.6% | +| Emerging | 1591 | 16.8% | +| Established | 777 | 8.2% | +| Senior | 1745 | 18.4% | + +## 2. Founding percentile by career stage (in population) + +| career stage | n (in pop.) | pctl p50 | pctl p90 | n ≥75 | n ≥90 | +|---|---|---|---|---|---| +| Early | 1599 | 40.2 | 92.4 | 393 | 194 | +| Emerging | 1591 | 23.8 | 76.7 | 167 | 50 | +| Established | 777 | 35.6 | 71.9 | 58 | 19 | +| Senior | 1745 | 33.5 | 68.3 | 82 | 7 | +| ALL | 5712 | 33.2 | 79.0 | 700 | 270 | + +Same, restricted to `publications >= 7` (screens the population-boundary artifact): +| career stage | n | pctl p50 | pctl p90 | n ≥75 | n ≥90 | +|---|---|---|---|---|---| +| Early | 572 | 11.4 | 55.1 | 14 | 3 | +| Emerging | 1477 | 21.9 | 73.0 | 127 | 33 | +| Established | 777 | 35.6 | 71.9 | 58 | 19 | +| Senior | 1745 | 33.5 | 68.3 | 82 | 7 | +| ALL | 4571 | 27.5 | 69.1 | 281 | 62 | + +## 3. The shortlist: founding percentile ≥ 90.0 + +| career stage | pctl ≥90.0 | … AND pubs ≥7 (robust) | +|---|---|---| +| Early | 194 | 3 | +| Emerging | 50 | 33 | +| Established | 19 | 19 | +| Senior | 7 | 7 | +| **ALL** | 270 | 62 | + +The gap between the columns is the measured boundary artifact: 208 of 270 shortlisted profiles have fewer than 7 publications (long-dormant / fragment profiles scoring just above the ≥4 population cut). + +## 4. Founder potential × multiplicator archetypes + +| | mentor tag | bridger tag | amplifier tag | no tag | +|---|---|---|---|---| +| shortlist (≥90.0) | 0 | 1 | 0 | 269 | +| robust shortlist (pubs ≥7) | 0 | 0 | 0 | 62 | + +Tags fire for ~3% of the cohort, so the softer view — sub-score ≥ 0.7 within the person's career bucket — shows the overlap structure better: +| | n | mentor ≥0.7 | bridger ≥0.7 | amplifier ≥0.7 | +|---|---|---|---|---| +| shortlist (≥90.0) | 270 | 1 | 31 | 23 | +| robust (pubs ≥7) | 62 | 1 | 4 | 8 | + +And the reverse direction — the founding percentile of the tagged multiplicators (why round thresholds select nobody): +| tagged as | n (in pop.) | founding pctl p50 | p90 | n ≥40 | +|---|---|---|---|---| +| mentor | 161 | 10 | 47 | 25 | +| bridger | 124 | 10 | 62 | 23 | +| amplifier | 10 | 15 | 59 | 4 | + +## 5. Research areas (FOR division, from OpenAlex publication fields) + +| area | cohort (in pop.) | shortlist ≥90.0 | robust (pubs ≥7) | +|---|---|---|---| +| 32 Biomedical & Clinical Sciences | 2530 (44.3%) | 118 (43.7%) | 23 (37.1%) | +| 40 Engineering | 1072 (18.8%) | 38 (14.1%) | 13 (21.0%) | +| 44 Human Society | 469 (8.2%) | 18 (6.7%) | 4 (6.5%) | +| 31 Biological Sciences | 389 (6.8%) | 11 (4.1%) | 1 (1.6%) | +| 46 Information & Computing Sciences | 228 (4.0%) | 14 (5.2%) | 7 (11.3%) | +| 41 Environmental Sciences | 190 (3.3%) | 6 (2.2%) | 1 (1.6%) | +| 51 Physical Sciences | 138 (2.4%) | 1 (0.4%) | 0 (0.0%) | +| 36 Creative Arts & Writing | 120 (2.1%) | 12 (4.4%) | 2 (3.2%) | +| 35 Commerce, Management, Tourism & Services | 111 (1.9%) | 21 (7.8%) | 8 (12.9%) | +| 52 Psychology | 110 (1.9%) | 6 (2.2%) | 0 (0.0%) | + +## 6. Which factors drive founder identification + +### 6a. The model's own permutation importances (training-side truth) + +| feature | importance (mean ROC-AUC drop) | +|---|---| +| patent_research_area_n. | 0.104 | +| pub_rate | 0.082 | +| first_publication_year | 0.055 | +| industry_collab_at_index | 0.045 | +| career_age_at_index | 0.030 | +| patents_at_index | 0.028 | +| patent_rate | 0.023 | +| patent_research_area_46 | 0.021 | +| publication_research_area_32 | 0.015 | +| years_since_first_grant | 0.009 | +| grant_research_area_51 | 0.008 | +| institution_berkeley | 0.007 | + +⚠️ Deployment caveat: the top feature `patent_research_area_n.` is CONSTANT in this index — our corpus has no IPC→FOR mapping, so every record (patent holders included) carries `patent_research_area = "n."`. Locally that feature separates nothing, and the 152 patent holders sit slightly off the training manifold (patents present but no patent area). Mapping IPC→FOR (the backend's `ipc_openalex_mapping` is a starting point) would unlock the model's #1 and #8 features. + +### 6b. Local Spearman rank correlation with `founding.percentile` + +| observable | ρ, all in population (n=5712) | ρ, pubs ≥7 (n=4571) | +|---|---|---| +| grants_capped | -0.582 | -0.563 | +| activity density (active_years/career_age) | -0.535 | -0.557 | +| pub_rate (pubs/career age) | -0.574 | -0.502 | +| career_age | +0.258 | +0.456 | +| sub_score bridger | -0.271 | -0.360 | +| sub_score mentor | -0.142 | -0.254 | +| sub_score amplifier | -0.139 | -0.195 | +| active_years | -0.060 | +0.164 | +| industry_collab_papers | -0.187 | -0.111 | +| publications | -0.260 | -0.061 | +| patents | +0.027 | +0.046 | +| news_mentions | -0.026 | +0.019 | + +Correlation on the scored cohort, not causation in the model — 6a is what the model uses, 6b is how the score co-varies with everything observable here (including archetype sub-scores the model never saw). Read the two columns together: signs that flip or shrink between them are carried by the sub-7-publication boundary zone, not by the in-regime ranking. diff --git a/service/scripts/profiling/multipliers/tests/test_founding.py b/service/scripts/profiling/multipliers/tests/test_founding.py new file mode 100644 index 00000000..63a5cc73 --- /dev/null +++ b/service/scripts/profiling/multipliers/tests/test_founding.py @@ -0,0 +1,171 @@ +"""Tests for the pure parts of the founder-potential enrichment (v2): the +OpenAlex-field -> Dimensions-FOR research-area mapping, the work-extract +feature pass, and the v2 model-input record. Model inference itself is not +unit-tested here — it is exercised end-to-end by build.py and validated by the +shipped out-of-fold metrics (classifier_symmetric/manifest.json).""" +from __future__ import annotations + +from service.scripts.profiling.multipliers.founding import ( + UNKNOWN_AREA, + PublicationFeatures, + build_model_record, + collect_publication_features, + modal_research_area, +) + + +# -------------------------------------------------------------------------- +# research-area mapping +# -------------------------------------------------------------------------- + + +def test_modal_research_area_picks_the_dominant_for_division(): + # fields 27 and 28 both map to FOR 32, so they must ACCUMULATE + assert modal_research_area({"27": 6, "28": 5, "17": 8}) == "32" + assert modal_research_area({"17": 8}) == "46" # Computer Science + assert modal_research_area({"31": 3}) == "51" # Physics -> Physical Sciences + + +def test_modal_research_area_unknown_and_deterministic_ties(): + assert modal_research_area({}) == UNKNOWN_AREA + assert modal_research_area({"99": 10}) == UNKNOWN_AREA # not an OpenAlex field + # ties break on the FOR code + assert modal_research_area({"16": 4, "17": 4}) == "34" + assert modal_research_area({"17": 4, "16": 4}) == "34" + + +# -------------------------------------------------------------------------- +# feature pass over the work extract +# -------------------------------------------------------------------------- + + +def _work(wid, year, citations, authors, field_id=None, awards=()): + return { + "id": f"https://openalex.org/{wid}", + "publication_year": year, + "cited_by_count": citations, + "primary_topic": {"field": {"id": f"https://openalex.org/fields/{field_id}"}} + if field_id + else None, + "awards": [{"id": f"https://openalex.org/{a}"} for a in awards], + "authorships": [ + {"author": {"id": f"https://openalex.org/{a}", "display_name": a}} + for a in authors + ], + } + + +WORKS = [ + _work("W1", 2020, 10, ["A1", "A2"], field_id="27", awards=["G1", "G2"]), + _work("W2", 2021, 5, ["A1"], field_id="27"), + _work("W3", 2021, 3, ["A1", "A3"], field_id="17", awards=["G1"]), + _work("W4", 2022, 0, ["A2"], field_id="27"), +] + + +def test_collect_publication_features_aggregates_per_focal_author(): + feats = collect_publication_features(WORKS, {"A1", "A2"}) + + a1 = feats["A1"] + assert a1.publications == 3 + assert a1.first_publication_year == 2020 + assert a1.last_publication_year == 2021 + assert a1.pub_counts_by_year == {2020: 1, 2021: 2} + assert a1.field_counts == {"27": 2, "17": 1} + + # A3 is a co-author but not in the focal set -> never aggregated + assert "A3" not in feats + assert feats["A2"].publications == 2 + + +def test_no_citation_aggregates_are_collected(): + """v2 excludes every citation-level feature as non-historicizable to an + index date; the feature pass must not even collect them, or someone will + eventually surface window-contaminated numbers next to symmetric scores.""" + a1 = collect_publication_features(WORKS, {"A1"})["A1"] + for name in ("citation_counts", "pub_citation_sum", "pub_citation_mean"): + assert not hasattr(a1, name), name + + +def test_grant_features_dedupe_awards_across_works(): + a1 = collect_publication_features(WORKS, {"A1"})["A1"] + # G1 is on both W1 and W3 -> counted once in the total... + assert a1.grants == 2 + # ...but the per-year channel sees it in each active year + assert a1.grant_counts_by_year == {2020: 2, 2021: 1} + assert (a1.first_grant_year, a1.last_grant_year) == (2020, 2021) + # grant research area comes from the funded works, not all works + assert a1.grant_field_counts == {"27": 1, "17": 1} + + +def test_author_with_no_grants_has_none_years(): + unfunded = [_work("W7", 2019, 1, ["A9"], field_id="27")] + a9 = collect_publication_features(unfunded, {"A9"})["A9"] + assert a9.grants == 0 + assert a9.grant_counts_by_year == {} + # None, not 0 — the wrapper coerces it; only founding_features maps it to 0 + assert a9.first_grant_year is None and a9.last_grant_year is None + + +def test_works_without_a_usable_year_are_skipped(): + broken = [_work("W9", None, 5, ["A1"]), _work("W8", "2020", 5, ["A1"])] + assert collect_publication_features(broken, {"A1"}) == {} + + +def test_duplicate_authorship_on_one_work_counts_once(): + """OpenAlex occasionally repeats an author across authorship entries of the + same work; double-counting would inflate `publications` — the anchor of the + v2 population rule and of every *_rate feature the wrapper derives.""" + dup = dict(WORKS[0]) + dup["authorships"] = dup["authorships"] + [dup["authorships"][0]] + assert collect_publication_features([dup], {"A1"})["A1"].publications == 1 + + +# -------------------------------------------------------------------------- +# v2 model-input record +# -------------------------------------------------------------------------- + + +def test_build_model_record_matches_the_v2_contract(): + pub = collect_publication_features(WORKS, {"A1"})["A1"] + record = build_model_record( + pub, + patent={"patents": 2, "first_patent_year": 2018, "last_patent_year": 2021}, + industry_collab_papers=5, + ) + assert record == { + "publications": 3, + "patents": 2, + "grants": 2, # raw — the wrapper de-inflates + "first_publication_year": 2020, + "first_patent_year": 2018, + "first_grant_year": 2020, + "industry_collab_papers": 5, + # 0 is the wrapper's documented default for a missing field + "linked_patents_to_publications": 0, + "publication_research_area": "32", + # no IPC->FOR mapping exists for our patent corpus + "patent_research_area": UNKNOWN_AREA, + "grant_research_area": "32", + } + # v1-only inputs must be gone + for stale in ("h-index", "i10-index", "g-index", "pub_citation_sum", + "pub_citation_mean", "activities_total", "affiliations", + "institution", "last_publication_year", "last_patent_year", + "last_grant_year", "grant_research_impact"): + assert stale not in record, stale + + +def test_missing_signals_stay_none_or_zero(): + """A researcher with no patents/grants: counts are 0, year fields are None + (the wrapper coerces None -> NaN -> its has_* flags come out False; a fake + year 0 would instead produce a 2026-year career age).""" + record = build_model_record( + PublicationFeatures(), patent={}, industry_collab_papers=0 + ) + assert record["patents"] == 0 and record["grants"] == 0 + assert record["first_publication_year"] is None + assert record["first_patent_year"] is None + assert record["first_grant_year"] is None + assert record["publication_research_area"] == UNKNOWN_AREA + assert record["grant_research_area"] == UNKNOWN_AREA diff --git a/service/scripts/profiling/multipliers/tests/test_graph.py b/service/scripts/profiling/multipliers/tests/test_graph.py new file mode 100644 index 00000000..741f445e --- /dev/null +++ b/service/scripts/profiling/multipliers/tests/test_graph.py @@ -0,0 +1,130 @@ +"""Tests for graph construction (pair generation, weights, caps, node aggregates).""" +from __future__ import annotations + +import pytest + +from service.scripts.profiling.multipliers.graph import build_graph, focal_subgraph, short_id + + +def make_work(wid, year, authors, field_id=None): + """authors: list of (author_id, institutions[(id,type)], position).""" + return { + "id": f"https://openalex.org/{wid}", + "publication_year": year, + "primary_topic": ( + {"field": {"id": f"https://openalex.org/fields/{field_id}"}} + if field_id + else None + ), + "authorships": [ + { + "author": {"id": f"https://openalex.org/{aid}", "display_name": aid}, + "author_position": pos, + "institutions": [ + {"id": f"https://openalex.org/{iid}", "type": itype} + for iid, itype in insts + ], + } + for aid, insts, pos in authors + ], + } + + +UDE = [("I1", "education")] +COMPANY = [("I9", "company")] + + +def test_short_id(): + assert short_id("https://openalex.org/A5023888391") == "A5023888391" + assert short_id("A5023888391") == "A5023888391" + assert short_id(None) is None + + +def test_edge_weight_decay_and_team_size(): + works = [ + make_work("W1", 2026, [("A1", UDE, "first"), ("A2", UDE, "last")]), + make_work("W2", 2025, [("A1", UDE, "first"), ("A2", UDE, "last")]), + ] + g = build_graph(works, {"A1", "A2"}, decay=0.8) + assert g.ref_year == 2026 + e = g.edges[("A1", "A2")] + # W1: 0.8^0 / 1 = 1.0 ; W2: 0.8^1 / 1 = 0.8 + assert e.weight == pytest.approx(1.8) + assert e.n_works == 2 + assert e.first_joint_year == 2025 + assert e.last_joint_year == 2026 + + +def test_team_size_divides_weight(): + works = [ + make_work( + "W1", 2026, + [("A1", UDE, "first"), ("A2", UDE, "middle"), ("A3", UDE, "last")], + ) + ] + g = build_graph(works, {"A1", "A2", "A3"}) + # n_authors=3 -> each pair gets 1/(3-1) = 0.5 + assert g.edges[("A1", "A2")].weight == pytest.approx(0.5) + assert len(g.edges) == 3 + + +def test_hyperauthorship_cap_excludes_pairs_but_keeps_years(): + big = make_work( + "W1", 2020, [(f"A{i}", UDE, "middle") for i in range(1, 61)] + ) + small = make_work("W2", 2021, [("A1", UDE, "first"), ("A2", UDE, "last")]) + g = build_graph([big, small], {"A1", "A2"}, max_authors_per_work=50) + assert g.n_works_capped == 1 + assert g.n_works_used == 1 + assert set(g.edges) == {("A1", "A2")} + # capped work still contributes publication years + assert 2020 in g.nodes["A1"].publication_years + assert 2021 in g.nodes["A1"].publication_years + + +def test_cross_institution_weight(): + works = [ + make_work("W1", 2026, [("A1", UDE, "first"), ("A2", COMPANY, "last")]), + make_work("W2", 2026, [("A1", UDE, "first"), ("A3", UDE, "last")]), + ] + g = build_graph(works, {"A1", "A2", "A3"}) + assert g.edges[("A1", "A2")].cross_inst_weight == pytest.approx(1.0) + assert g.edges[("A1", "A3")].cross_inst_weight == pytest.approx(0.0) + + +def test_company_share_and_fields(): + works = [ + make_work("W1", 2026, [("A1", UDE, "first"), ("A2", COMPANY, "last")], "F11"), + make_work("W2", 2026, [("A1", UDE, "first"), ("A3", UDE, "last")], "F22"), + ] + g = build_graph(works, {"A1"}) + n = g.nodes["A1"] + assert n.n_company_works == 1 and n.n_typed_works == 2 + assert n.field_counts == {"F11": 1, "F22": 1} + + +def test_focal_subgraph_excludes_externals(): + works = [ + make_work("W1", 2026, [("A1", UDE, "first"), ("EXT", COMPANY, "last")]), + make_work("W2", 2026, [("A1", UDE, "first"), ("A2", UDE, "last")]), + ] + g = build_graph(works, {"A1", "A2"}) + internal = focal_subgraph(g) + assert "EXT" not in internal + assert set(internal["A1"].keys()) == {"A2"} + + +def test_last_author_junior_first_recorded(): + works = [ + make_work("W1", 2026, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")]), + ] + g = build_graph(works, {"JUNIOR", "PROF"}) + assert g.nodes["PROF"].last_author_junior_first == [("JUNIOR", 2026)] + assert g.nodes["JUNIOR"].last_author_junior_first == [] + + +def test_duplicate_authorships_deduped(): + w = make_work("W1", 2026, [("A1", UDE, "first"), ("A1", UDE, "last"), ("A2", UDE, "middle")]) + g = build_graph([w], {"A1", "A2"}) + # A1 duplicated -> counts once; n_authors=2 -> weight divisor 1 + assert g.edges[("A1", "A2")].weight == pytest.approx(1.0) diff --git a/service/scripts/profiling/multipliers/tests/test_metrics.py b/service/scripts/profiling/multipliers/tests/test_metrics.py new file mode 100644 index 00000000..9048dd48 --- /dev/null +++ b/service/scripts/profiling/multipliers/tests/test_metrics.py @@ -0,0 +1,231 @@ +"""Tests for metrics: betweenness vs networkx oracle, constraint on a star, +active_years_at robustness (the planted-1893-outlier regression guard), mentor logic.""" +from __future__ import annotations + +import pytest + +from service.scripts.profiling.multipliers.graph import build_graph +from service.scripts.profiling.multipliers.metrics import ( + active_years_at, + betweenness_centrality, + burt_constraint, + compute_all_metrics, + field_entropy, + is_suspicious_profile, + mentor_metrics, +) +from service.scripts.profiling.multipliers.tests.test_graph import UDE, make_work + +networkx = pytest.importorskip("networkx") + + +# --------------------------------------------------------------------- +# active_years_at — regression guard for the debut-year-free design +# --------------------------------------------------------------------- + + +def test_active_years_at_unmoved_by_planted_1893_outlier(): + """A single misattributed 1893 work must shift active_years_at by exactly 1, + unlike first_pub_year-based career age, which it would shift by ~120 years.""" + clean = set(range(2010, 2026)) # 16 active years + poisoned = clean | {1893} # merged-profile artifact + + assert active_years_at(clean, 2025) == 16 + assert active_years_at(poisoned, 2025) == 17 # +1, not +120 + # seniority at the time of an early collaboration is unaffected + assert active_years_at(clean, 2013) == 4 # still "Early" in 2013 + assert active_years_at(poisoned, 2013) == 5 # off by exactly one year + + # the poisoned profile is still flagged + assert not is_suspicious_profile(clean) + assert is_suspicious_profile(poisoned) + + +# --------------------------------------------------------------------- +# betweenness — barbell fixture + networkx oracle +# --------------------------------------------------------------------- + + +def _nx_graph(adj): + g = networkx.Graph() + for a, neigh in adj.items(): + g.add_node(a) + for b, w in neigh.items(): + g.add_edge(a, b, weight=w, distance=1.0 / w) + return g + + +def test_betweenness_barbell_bridge_dominates(): + """Two triangles joined by one bridge node: the bridge has max betweenness.""" + adj = {} + + def add(a, b, w=1.0): + adj.setdefault(a, {})[b] = w + adj.setdefault(b, {})[a] = w + + for x, y in [("A", "B"), ("B", "C"), ("A", "C")]: + add(x, y) + for x, y in [("D", "E"), ("E", "F"), ("D", "F")]: + add(x, y) + add("C", "M") + add("M", "D") + + bc = betweenness_centrality(adj) + assert bc["M"] == max(bc.values()) + assert bc["A"] == pytest.approx(0.0) + + oracle = networkx.betweenness_centrality( + _nx_graph(adj), weight="distance", normalized=True + ) + for node, value in bc.items(): + assert value == pytest.approx(oracle[node], abs=1e-9), node + + +def test_betweenness_weighted_paths_vs_oracle(): + """Weighted graph where the shortest path is NOT the fewest-hops path.""" + adj = {} + + def add(a, b, w): + adj.setdefault(a, {})[b] = w + adj.setdefault(b, {})[a] = w + + # strong two-hop A-X-B (0.2+0.2) beats direct weak A-B (2) + add("A", "B", 0.5) + add("A", "X", 5.0) + add("X", "B", 5.0) + add("B", "C", 1.0) + + bc = betweenness_centrality(adj) + oracle = networkx.betweenness_centrality( + _nx_graph(adj), weight="distance", normalized=True + ) + for node, value in bc.items(): + assert value == pytest.approx(oracle[node], abs=1e-9), node + assert bc["X"] > 0.0 # X sits on the A->B shortest path + + +def test_betweenness_random_graph_vs_oracle(): + """Randomized (but seeded) graph, full oracle comparison.""" + rng = networkx.gnm_random_graph(24, 60, seed=7) + adj = {} + for a, b in rng.edges(): + w = ((a * 31 + b * 17) % 9 + 1) / 3.0 # deterministic pseudo-weights + adj.setdefault(str(a), {})[str(b)] = w + adj.setdefault(str(b), {})[str(a)] = w + for n in rng.nodes(): + adj.setdefault(str(n), {}) + + bc = betweenness_centrality(adj) + oracle = networkx.betweenness_centrality( + _nx_graph(adj), weight="distance", normalized=True + ) + for node, value in bc.items(): + assert value == pytest.approx(oracle[node], abs=1e-7), node + + +# --------------------------------------------------------------------- +# Burt constraint — star fixture +# --------------------------------------------------------------------- + + +def test_constraint_star_center_is_unconstrained(): + """Star: the hub bridges structural holes (low constraint); each spoke is + fully dependent on the hub (constraint 1.0). Clique members sit in between.""" + star = {} + for spoke in ["S1", "S2", "S3", "S4"]: + star.setdefault("HUB", {})[spoke] = 1.0 + star[spoke] = {"HUB": 1.0} + c = burt_constraint(star) + assert c["HUB"] == pytest.approx(0.25) # sum of (1/4)^2 * 4 + for spoke in ["S1", "S2", "S3", "S4"]: + assert c[spoke] == pytest.approx(1.0) + + triangle = { + "A": {"B": 1.0, "C": 1.0}, + "B": {"A": 1.0, "C": 1.0}, + "C": {"A": 1.0, "B": 1.0}, + } + c3 = burt_constraint(triangle) + # closed triad: everyone more constrained than the star hub + assert c3["A"] > c["HUB"] + oracle = networkx.constraint(_nx_graph(triangle), weight="weight") + assert c3["A"] == pytest.approx(oracle["A"], abs=1e-9) + + +def test_field_entropy(): + assert field_entropy({}) == 0.0 + assert field_entropy({"F1": 10}) == 0.0 + assert field_entropy({"F1": 5, "F2": 5}) == pytest.approx(1.0) + assert field_entropy({"F1": 1, "F2": 1, "F3": 1, "F4": 1}) == pytest.approx(2.0) + + +# --------------------------------------------------------------------- +# Mentor metrics +# --------------------------------------------------------------------- + + +def _career(aid, years, wid_prefix): + """Solo-ish works giving `aid` a publication history (paired with a throwaway + co-author so the works survive the n_authors >= 2 filter).""" + return [ + make_work(f"{wid_prefix}{y}", y, [(aid, UDE, "first"), (f"X_{aid}_{y}", [], "last")]) + for y in years + ] + + +def test_mentor_seniority_gap_and_progression(): + works = [] + # PROF: established since 2000 (>=10 active years by 2015) + works += _career("PROF", range(2000, 2026), "P") + # JUNIOR: first-ever activity 2015 (active_years_at(2015)=1), then progresses + works += [ + make_work("J1", 2015, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")]), + ] + works += _career("JUNIOR", range(2016, 2022), "J") # 6 more years -> progressed + # PEER: senior colleague, first joint work 2020 when both are senior + works += _career("PEER", range(2000, 2026), "Q") + works += [make_work("JP", 2020, [("PEER", UDE, "first"), ("PROF", UDE, "last")])] + + g = build_graph(works, {"PROF", "JUNIOR", "PEER"}) + mm = mentor_metrics(g, "PROF") + + assert mm.juniors_mentored == 1 + assert mm.junior_ids == ["JUNIOR"] + assert mm.junior_progression_rate == pytest.approx(1.0) + # PROF was last author on J1 with a junior first author + assert mm.last_author_with_junior_first == 1 + # the senior PEER never counts + assert "PEER" not in mm.junior_ids + + +def test_mentor_excludes_external_coauthors(): + """External co-authors have truncated year-sets and must never count as juniors.""" + works = _career("PROF", range(2000, 2026), "P") + works += [make_work("E1", 2020, [("EXT", [], "first"), ("PROF", UDE, "last")])] + g = build_graph(works, {"PROF"}) # EXT not focal + mm = mentor_metrics(g, "PROF") + assert mm.juniors_mentored == 0 + assert mm.last_author_with_junior_first == 0 + + +def test_mentor_requires_focal_seniority_at_first_joint_year(): + """Two juniors co-publishing: neither mentors the other.""" + works = [ + make_work("W1", 2020, [("J1", UDE, "first"), ("J2", UDE, "last")]), + make_work("W2", 2021, [("J1", UDE, "first"), ("J2", UDE, "last")]), + ] + g = build_graph(works, {"J1", "J2"}) + assert mentor_metrics(g, "J2").juniors_mentored == 0 + + +def test_compute_all_metrics_shapes(): + works = _career("PROF", range(2000, 2026), "P") + works += [make_work("J1", 2015, [("JUNIOR", UDE, "first"), ("PROF", UDE, "last")])] + g = build_graph(works, {"PROF", "JUNIOR"}) + rows = compute_all_metrics(g) + assert set(rows) == {"PROF", "JUNIOR"} + prof = rows["PROF"] + assert prof["juniors_mentored"] == 1 + assert prof["active_years"] == 26 + assert 0.0 <= prof["industry_coauthor_share"] <= 1.0 + assert prof["suspicious_profile"] is False diff --git a/service/scripts/profiling/multipliers/tests/test_scoring.py b/service/scripts/profiling/multipliers/tests/test_scoring.py new file mode 100644 index 00000000..9e8db7dd --- /dev/null +++ b/service/scripts/profiling/multipliers/tests/test_scoring.py @@ -0,0 +1,120 @@ +"""Property-style tests for scoring: percentile bounds, tie handling, bucket isolation, +weight redistribution for missing metrics, tagging rules.""" +from __future__ import annotations + +import pytest + +from service.scripts.profiling.multipliers.scoring import career_bucket, percentile_ranks, score_rows + +CONFIG = { + "_config_hash": "testhash", + "career": {"buckets": [4, 9, 14], "bucket_names": ["Early", "Emerging", "Established", "Senior"]}, + "weights": { + "bridger": {"betweenness": 0.5, "field_entropy": 0.5}, + "mentor": {"juniors_mentored": 1.0}, + }, + "tags": {"threshold": 0.85, "min_active_years": 2}, +} + + +def row(aid, active_years, betweenness=0.0, entropy=0.0, juniors=0): + return { + "author_id": aid, + "active_years": active_years, + "betweenness": betweenness, + "field_entropy": entropy, + "juniors_mentored": juniors, + "junior_ids": [], + } + + +def test_career_bucket_thresholds_match_backend(): + names = ["Early", "Emerging", "Established", "Senior"] + assert career_bucket(1, [4, 9, 14], names) == "Early" + assert career_bucket(4, [4, 9, 14], names) == "Early" + assert career_bucket(5, [4, 9, 14], names) == "Emerging" + assert career_bucket(9, [4, 9, 14], names) == "Emerging" + assert career_bucket(10, [4, 9, 14], names) == "Established" + assert career_bucket(14, [4, 9, 14], names) == "Established" + assert career_bucket(15, [4, 9, 14], names) == "Senior" + + +def test_percentiles_in_zero_one_and_ties_share_mean_rank(): + p = percentile_ranks({"a": 1.0, "b": 2.0, "c": 3.0, "d": 4.0}) + assert all(0.0 < v <= 1.0 for v in p.values()) + assert p["d"] == pytest.approx(1.0) + assert p["a"] == pytest.approx(0.25) + + # a mostly-zero metric must not hand out high percentiles + p = percentile_ranks({"a": 0, "b": 0, "c": 0, "d": 5}) + assert p["a"] == pytest.approx(0.5) # mean rank of the 3-way tie: (1+2+3)/3 / 4 + assert p["d"] == pytest.approx(1.0) + # None values are excluded entirely + p = percentile_ranks({"a": None, "b": 1.0}) + assert "a" not in p and p["b"] == pytest.approx(1.0) + + +def test_percentiles_computed_within_buckets_not_across(): + rows = { + # Early bucket: modest raw values + "e1": row("e1", 2, betweenness=0.1, entropy=0.5), + "e2": row("e2", 3, betweenness=0.0, entropy=0.0), + # Senior bucket: huge raw values + "s1": row("s1", 20, betweenness=0.9, entropy=3.0), + "s2": row("s2", 25, betweenness=0.8, entropy=2.0), + } + scored = {r["author_id"]: r for r in score_rows(rows, CONFIG)} + # e1 tops the Early bucket despite raw values far below the seniors + assert scored["e1"]["percentiles"]["betweenness"] == pytest.approx(1.0) + assert scored["s1"]["percentiles"]["betweenness"] == pytest.approx(1.0) + assert scored["e1"]["career_bucket"] == "Early" + assert scored["s1"]["career_bucket"] == "Senior" + + +def test_monotonicity_more_bridging_never_lowers_score(): + base = { + "a": row("a", 3, betweenness=0.1, entropy=1.0), + "b": row("b", 3, betweenness=0.2, entropy=1.0), + "c": row("c", 3, betweenness=0.3, entropy=1.0), + } + improved = { + "a": row("a", 3, betweenness=0.25, entropy=1.0), # a gains betweenness + "b": row("b", 3, betweenness=0.2, entropy=1.0), + "c": row("c", 3, betweenness=0.3, entropy=1.0), + } + s_base = {r["author_id"]: r for r in score_rows(base, CONFIG)} + s_improved = {r["author_id"]: r for r in score_rows(improved, CONFIG)} + assert ( + s_improved["a"]["sub_scores"]["bridger"] + >= s_base["a"]["sub_scores"]["bridger"] + ) + + +def test_missing_metric_weight_redistributed(): + rows = { + "a": {**row("a", 3, entropy=2.0), "betweenness": None}, + "b": {**row("b", 3, entropy=1.0), "betweenness": None}, + } + scored = {r["author_id"]: r for r in score_rows(rows, CONFIG)} + # bridger falls back to entropy alone + assert scored["a"]["sub_scores"]["bridger"] == pytest.approx(1.0) + + +def test_tags_fire_above_threshold_and_respect_min_active_years(): + rows = { + # 8-person Early bucket: m ranks 7/8 = 0.875 >= 0.85 threshold + **{f"x{i}": row(f"x{i}", 3, juniors=0) for i in range(6)}, + "m": row("m", 3, juniors=7), + "newbie": {**row("newbie", 1, juniors=9), "active_years": 1}, + } + scored = {r["author_id"]: r for r in score_rows(rows, CONFIG)} + assert "mentor" in scored["m"]["tags"] + assert scored["newbie"]["tags"] == [] # min_active_years=2 gate + + +def test_output_carries_raw_percentile_subscore_and_hash(): + scored = score_rows({"a": row("a", 3, betweenness=0.5)}, CONFIG)[0] + assert scored["betweenness"] == 0.5 # raw + assert "betweenness" in scored["percentiles"] # percentile + assert "bridger" in scored["sub_scores"] # sub-score + assert scored["config_hash"] == "testhash" diff --git a/service/scripts/profiling/multipliers/tests/test_signals.py b/service/scripts/profiling/multipliers/tests/test_signals.py new file mode 100644 index 00000000..9b05d0fc --- /dev/null +++ b/service/scripts/profiling/multipliers/tests/test_signals.py @@ -0,0 +1,135 @@ +"""Tests for the pure parts of the signal joins: name/DOI normalization, the +ambiguity rule for news matching, and the org_patents profile shape the founder +models consume.""" +from __future__ import annotations + +import httpx + +from service.scripts.profiling.multipliers.signals import ( + merge_patent_profiles, + normalize_doi, + normalize_name, + patent_counts, +) + + +def test_normalize_name_diacritics_case_whitespace(): + assert normalize_name("René Müller") == "rene muller" + assert normalize_name("CHRISTOPH GILLE") == "christoph gille" # news is often ALL-CAPS + assert normalize_name(" Anna-Lena Giesecke ") == "anna-lena giesecke" + assert normalize_name("Barbara Saccà") == normalize_name("Barbara Sacca") + assert normalize_name("Bülent Eken") == "bulent eken" + + +def test_normalize_doi_prefixes_and_case(): + assert normalize_doi("https://doi.org/10.1371/journal.pone.0018216") == \ + "10.1371/journal.pone.0018216" + assert normalize_doi("DOI:10.1016/J.CELL.2020.01.001") == "10.1016/j.cell.2020.01.001" + assert normalize_doi("doi.org/10.1/x") == "10.1/x" + assert normalize_doi("10.1/x") == "10.1/x" + assert normalize_doi("") is None + assert normalize_doi(None) is None + + +def test_ambiguous_name_rule(): + """Two cohort authors normalizing to the same name -> both excluded from news.""" + from collections import defaultdict + names = {"A1": "Wei Zhang", "A2": "Wei ZHANG", "A3": "Unique Person"} + by_norm = defaultdict(list) + for aid, n in names.items(): + by_norm[normalize_name(n)].append(aid) + ambiguous = {k for k, v in by_norm.items() if len(v) > 1} + assert normalize_name("Wei Zhang") in ambiguous + assert normalize_name("Unique Person") not in ambiguous + + +# -------------------------------------------------------------------------- +# org_patents profiles +# -------------------------------------------------------------------------- + +ORG_PATENT_HITS = [ + {"_source": {"match_type": "both", "publication_year": 2018, + "matched_authors": [{"openalex_author_id": "A1"}, + {"openalex_author_id": "A2"}]}, + "sort": [1]}, + {"_source": {"match_type": "institution", "publication_year": 2021, + "matched_authors": [{"openalex_author_id": "A1"}]}, + "sort": [2]}, + # publication_year arrives as a string on some docs + {"_source": {"match_type": "institution", "publication_year": "2015", + "matched_authors": [{"openalex_author_id": "A1"}]}, + "sort": [3]}, + # name-only never enters the scored profile + {"_source": {"match_type": "name", "publication_year": 2019, + "matched_authors": [{"openalex_author_id": "A3"}]}, + "sort": [4]}, + # unparseable year still counts toward `patents` + {"_source": {"match_type": "both", "publication_year": None, + "matched_authors": [{"openalex_author_id": "A2"}]}, + "sort": [5]}, +] + + +def _stub_client(pages): + """httpx client returning each page of ES hits in turn, then an empty page.""" + remaining = list(pages) + [[]] + + def handler(request): + return httpx.Response(200, json={"hits": {"hits": remaining.pop(0)}}) + + return httpx.Client(transport=httpx.MockTransport(handler)) + + +def test_patent_counts_builds_profiles_with_years(): + with _stub_client([ORG_PATENT_HITS]) as client: + scored, name_only = patent_counts(client, "I62318514") + + assert scored["A1"]["patents"] == 3 + assert scored["A1"]["counts_by_year"] == {2015: 1, 2018: 1, 2021: 1} + assert scored["A1"]["first_patent_year"] == 2015 # string year parsed + assert scored["A1"]["last_patent_year"] == 2021 + + # A2's second patent has no usable year: counted, contributes no year + assert scored["A2"]["patents"] == 2 + assert scored["A2"]["counts_by_year"] == {2018: 1} + assert scored["A2"]["first_patent_year"] == scored["A2"]["last_patent_year"] == 2018 + + +def test_name_only_matches_stay_out_of_the_scored_profile(): + """Name-only patents are coach evidence, never a scored or modelled input.""" + with _stub_client([ORG_PATENT_HITS]) as client: + scored, name_only = patent_counts(client, "I62318514") + assert "A3" not in scored + assert name_only == {"A3": 1} + + +def test_merge_patent_profiles_takes_best_per_author_never_sums(): + api = { + "A1": {"patents": 3, "first_patent_year": 2010, "last_patent_year": 2020, + "counts_by_year": {2010: 1, 2020: 2}}, + "A2": {"patents": 1, "first_patent_year": 2021, "last_patent_year": 2021, + "counts_by_year": {2021: 1}}, + } + org = { + "A2": {"patents": 4, "first_patent_year": 2015, "last_patent_year": 2019, + "counts_by_year": {2015: 2, 2019: 2}}, + "A3": {"patents": 2, "first_patent_year": 2018, "last_patent_year": 2018, + "counts_by_year": {2018: 2}}, + } + merged, stats = merge_patent_profiles(api, org) + assert set(merged) == {"A1", "A2", "A3"} + assert merged["A1"]["patents"] == 3 # api-only + # A2: org has more patents -> org profile wins whole, never summed + assert merged["A2"] == org["A2"] + assert merged["A3"] == org["A3"] # org-only + assert stats == {"primary": 1, "secondary": 2} + + +def test_merge_patent_profiles_tie_prefers_primary(): + api = {"A1": {"patents": 2, "first_patent_year": 2010, "last_patent_year": 2011, + "counts_by_year": {2010: 1, 2011: 1}}} + org = {"A1": {"patents": 2, "first_patent_year": 2015, "last_patent_year": 2016, + "counts_by_year": {2015: 1, 2016: 1}}} + merged, stats = merge_patent_profiles(api, org) + assert merged["A1"] == api["A1"] + assert stats == {"primary": 1, "secondary": 0} diff --git a/service/scripts/profiling/multipliers/validate_sample.py b/service/scripts/profiling/multipliers/validate_sample.py new file mode 100644 index 00000000..abf5ed1d --- /dev/null +++ b/service/scripts/profiling/multipliers/validate_sample.py @@ -0,0 +1,119 @@ +#!/usr/bin/env python3 +""" +validate_sample.py — M1 exit check against the 60-person hand-labeled sample. + +analysis/career_stage/career_stage_sample.csv holds 60 UDE researchers with +manually verified status (31 Professor / 29 Researcher). The mentor sub-score +is a proxy for supervision with no ground truth in OpenAlex, so the check is: +mentor scores must concentrate on the professors. + +Usage (from the repo root): + python -m service.scripts.profiling.multipliers.validate_sample --institution-id I62318514 +""" +from __future__ import annotations + +import argparse +import csv +import gzip +import json +import statistics +from pathlib import Path + +SCRIPT_DIR = Path(__file__).resolve().parent +SAMPLE_RELATIVE = Path("analysis") / "career_stage" / "career_stage_sample.csv" + + +def _find_sample_csv() -> Path: + """Locate the hand-labeled sample by walking up from this file — a walk + rather than fixed `.parent` hops, which broke when this module moved.""" + for directory in SCRIPT_DIR.parents: + candidate = directory / SAMPLE_RELATIVE + if candidate.exists(): + return candidate + raise SystemExit(f"Could not find {SAMPLE_RELATIVE} above {SCRIPT_DIR}") + + +SAMPLE_CSV = _find_sample_csv() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--institution-id", required=True) + parser.add_argument("--cache-dir", default=str(SCRIPT_DIR / "cache")) + args = parser.parse_args() + + short = args.institution_id.strip().rsplit("/", 1)[-1] + scores_path = Path(args.cache_dir) / f"scores_{short}.jsonl.gz" + if not scores_path.exists(): + raise SystemExit(f"Run build.py first — missing {scores_path}") + + scores: dict[str, dict] = {} + with gzip.open(scores_path, "rt", encoding="utf-8") as f: + for line in f: + row = json.loads(line) + scores[row["author_id"]] = row + + sample: list[dict] = [] + with open(SAMPLE_CSV, newline="", encoding="utf-8-sig") as f: + for rec in csv.DictReader(f): + sample.append(rec) + + by_status: dict[str, list[dict]] = {} + missing: list[str] = [] + for rec in sample: + aid = rec["openalex_author_id"].strip() + row = scores.get(aid) + if row is None: + missing.append(f"{rec['name']} ({aid})") + continue + by_status.setdefault(rec["known_status"], []).append( + {"name": rec["name"], "discipline": rec["discipline_group"], **row} + ) + + print(f"Sample: {len(sample)} people, matched in scores: " + f"{sum(len(v) for v in by_status.values())}, missing: {len(missing)}") + for m in missing: + print(f" MISSING: {m}") + + report: dict = {"missing": missing, "by_status": {}} + for sub in ("mentor", "bridger", "amplifier"): + print(f"\n=== {sub} sub-score by known status ===") + for status, rows in sorted(by_status.items()): + vals = [r["sub_scores"][sub] for r in rows] + entry = { + "n": len(vals), + "median": round(statistics.median(vals), 3), + "mean": round(statistics.fmean(vals), 3), + "min": round(min(vals), 3), + "max": round(max(vals), 3), + } + report["by_status"].setdefault(status, {})[sub] = entry + print(f" {status:<12} n={entry['n']:>2} median={entry['median']:.3f} " + f"mean={entry['mean']:.3f} range=[{entry['min']:.3f}, {entry['max']:.3f}]") + + # headline check: professors' median mentor score > researchers' + prof = report["by_status"].get("Professor", {}).get("mentor", {}) + res = report["by_status"].get("Researcher", {}).get("mentor", {}) + if prof and res: + ok = prof["median"] > res["median"] + print(f"\nM1 exit check — professors' median mentor score " + f"({prof['median']}) > researchers' ({res['median']}): " + f"{'PASS' if ok else 'FAIL'}") + report["m1_exit_mentor_check"] = "PASS" if ok else "FAIL" + + print("\n=== per-person (sorted by mentor score) ===") + everyone = [r for rows in by_status.values() for r in rows] + for r in sorted(everyone, key=lambda x: x["sub_scores"]["mentor"], reverse=True): + status = next(s for s, rows in by_status.items() if r in rows) + print(f" {r['sub_scores']['mentor']:.3f} {status:<11} {r['career_bucket']:<12}" + f" juniors={r['juniors_mentored']:>3} laj={r['last_author_with_junior_first']:>3}" + f" {r['name']} ({r['discipline']})") + + out = Path(args.cache_dir) / f"validation_{short}.json" + with open(out, "w", encoding="utf-8", newline="\n") as f: + json.dump(report, f, ensure_ascii=False, indent=2) + print(f"\nReport -> {out}") + + +if __name__ == "__main__": + main()