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