Files
smartguide/service/scripts/profiling/founding_potential/src/sequence_data.py
T
2026-08-27 13:53:10 +02:00

103 lines
4.3 KiB
Python

"""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)