HillStreetSample / src /data_prep /node_features.py
benroodman's picture
Create node_features.py
aca3199 verified
Raw
History Blame Contribute Delete
29 kB
"""
src/data_prep/node_features.py
Replacement for the (duplicated, half-finished) Phase-3 node-feature code inside
``temporal_data.py``. It reproduces *exactly* the node tensors that the deprecated
``DynamicGraphBuilder`` (graph_builder.py) fed to ``BipartiteSAGEExtended``, using the
same data sources and the same lookups in ``feature_lookups.py`` -- but aligned to the
global node-id maps emitted by Phase 4 instead of the old per-snapshot LabelEncoders.
It provides two entry points:
build_node_features(...) -- Phase 3. Assembles and SAVES the five static node
tensors (x_pol, pol_state, x_comp, comp_sec, comp_ind)
plus a metadata sidecar. Must run AFTER Phase 4, because
it aligns to src_id_map.npy / dst_id_map.npy.
load_combined_graph(...) -- Recombines the per-year shards into ONE static graph
(the yearly split was only to keep file sizes sane),
converts the unified node ids back to the bipartite-local
convention the model expects, loads the saved node
tensors, and returns everything ready for the model.
------------------------------------------------------------------------------------
WHY THE OLD PHASE 3 WAS WRONG
------------------------------------------------------------------------------------
``BipartiteSAGEExtended.forward`` needs five node tensors:
x_pol [n_pol, pol_dim], pol_state [n_pol],
x_comp [n_comp, comp_dim], comp_sec [n_comp], comp_ind [n_comp]
The old Phase 3 produced free-floating committee/SEC parquets that were (a) never
aligned to the node-id maps, (b) missing the categorical embedding indices entirely,
and (c) reading from ad-hoc ``data/cropped`` paths instead of the config paths the
lookups use. This module fixes all three.
------------------------------------------------------------------------------------
COMPOSITION (mirrors DynamicGraphBuilder, with your current config flags)
------------------------------------------------------------------------------------
x_pol (pol_dim = 42 with PERFORMANCE+BIO+IDEOLOGY+COMMITTEES, ECON off):
[ win_rate, log_count, buy_ratio ] performance (3)
[ chamber, party x4, is_leader ] bio = full_bio[:5]+[leader] (6)
[ coord1D, coord2D ] ideology (2)
[ committee one-hot ] committees (31)
NB: the 56-dim state one-hot from PoliticianBioLookup is intentionally dropped --
state is carried as the learned `pol_state` embedding instead.
x_comp (comp_dim = 10 with COMPANY_SIC, FINANCIALS off):
[ SIC-division one-hot ] (10)
Categoricals (from the transactions CSV, NOT the lookups -- matches the old
get_categorical_ids snippet):
pol_state <- dominant `State` per BioGuideID, label-encoded
comp_sec <- dominant `Sector` per Ticker, label-encoded
comp_ind <- dominant `Industry`per Ticker, label-encoded
Index 0 of every categorical vocabulary is reserved for "UNK" so that nodes which only
appear in structural edges (and therefore have no transaction row) get a valid index.
Snapshot policy: time-varying lookups are evaluated as-of the LAST event date in the
window (per your call). Performance stats are aggregated over the full window, exactly
as the deprecated builder did.
"""
from __future__ import annotations
import os
import glob
import json
from typing import Dict, List, Optional, Tuple
import numpy as np
import pandas as pd
# torch / config / lookups are guarded so the pure-pandas helpers in this module remain
# importable and unit-testable in environments without the full project / torch stack.
try:
import torch
except ImportError: # pragma: no cover
torch = None
# ----------------------------------------------------------------------------------
# Constants -- msg column layout must stay in sync with all_msg_cols in temporal_data.py
# ----------------------------------------------------------------------------------
MSG_COLUMNS = [
"Trade_Size_USD", "Filing_Gap", "Transaction",
"is_sponsorship", "voted_yea", "Fin_Amt", "Geo_Weight",
"vol_20d", "vol_60d", "vol_120d", "vol_252d", "vol_of_vol_60d", "vol_trend", "idio_vol_60d",
"mom_60d", "mom_252d", "reversal_21d",
"beta_20d", "beta_60d", "downside_beta", "excess_vol", "max_dd_60d", "skew_60d", "sharpe_60d",
]
_COL = {c: i for i, c in enumerate(MSG_COLUMNS)}
# Trade-edge feature columns fed to the decoder when trade features are ON.
# = trade mechanics (3) + 17 market features. The 4 structural-only msg columns
# (is_sponsorship/voted_yea/Fin_Amt/Geo_Weight) are zero on trade edges and excluded.
# -> trade_feat_dim = 20.
TRADE_FEAT_COLS = [
"Trade_Size_USD", "Filing_Gap", "Transaction",
"vol_20d", "vol_60d", "vol_120d", "vol_252d", "vol_of_vol_60d", "vol_trend", "idio_vol_60d",
"mom_60d", "mom_252d", "reversal_21d",
"beta_20d", "beta_60d", "downside_beta", "excess_vol", "max_dd_60d", "skew_60d", "sharpe_60d",
]
_TRADE_IDX = [_COL[c] for c in TRADE_FEAT_COLS]
EVENT_TRADE, EVENT_LOBBY, EVENT_CAMPAIGN, EVENT_GEO = 0, 1, 2, 3
INCLUDE_PERFORMANCE = True # matches the flag hard-set in graph_builder.py
PERF_DEFAULT = [0.5, 0.0, 0.5] # win_rate, log_count, buy_ratio for non-traders
UNK = "UNK"
NODE_BUNDLE_NAME = "node_features_static.pt"
NODE_META_NAME = "node_features_meta.json"
def _require_torch():
if torch is None:
raise ImportError("PyTorch is required for this function but is not installed.")
# ==================================================================================
# Pure helpers (no torch / no project deps) -- unit-testable
# ==================================================================================
def invert_node_maps(src_map: dict, dst_map: dict) -> Tuple[List, List, int, int]:
"""Given Phase-4 maps (bioguide->idx in [0,n_pol); ticker->global idx in
[n_pol, n_pol+n_comp)), return ordered id lists plus (n_pol, n_comp).
ordered_bio[i] = bioguide id whose politician index is i
ordered_tick[j] = ticker whose *local* company index is j (== global - n_pol)
"""
n_pol = len(src_map)
n_comp = len(dst_map)
inv_src = {int(idx): bio for bio, idx in src_map.items()}
inv_dst_local = {int(idx) - n_pol: tick for tick, idx in dst_map.items()}
missing_pol = [i for i in range(n_pol) if i not in inv_src]
missing_comp = [j for j in range(n_comp) if j not in inv_dst_local]
if missing_pol or missing_comp:
raise ValueError(f"Node maps are not a contiguous 0..N-1 range "
f"(missing pol idx {missing_pol[:5]}, comp idx {missing_comp[:5]}).")
ordered_bio = [inv_src[i] for i in range(n_pol)]
ordered_tick = [inv_dst_local[j] for j in range(n_comp)]
return ordered_bio, ordered_tick, n_pol, n_comp
def _dominant(series: pd.Series):
"""Most frequent non-null value in a Series, or None if all null/empty."""
s = series.dropna()
if s.empty:
return None
m = s.mode()
return m.iloc[0] if not m.empty else s.iloc[0]
def build_label_encoder(values, reserve_unk: bool = True) -> Dict[str, int]:
"""Stable str->index map. Index 0 is reserved for UNK when requested."""
uniq = sorted({str(v) for v in values if pd.notna(v) and str(v) != "nan"})
classes = ([UNK] + uniq) if reserve_unk else uniq
return {c: i for i, c in enumerate(classes)}
def encode_per_node(ordered_ids: List, id_to_value: Dict, vocab: Dict[str, int]) -> np.ndarray:
"""Map ordered node ids -> categorical index via (id_to_value) then (vocab),
falling back to UNK (0) for unknown ids/values."""
out = np.zeros(len(ordered_ids), dtype=np.int64)
for i, nid in enumerate(ordered_ids):
val = id_to_value.get(nid, None)
out[i] = vocab.get(str(val), 0) if val is not None else 0
return out
def aggregate_pair_edges(
src_local: np.ndarray,
dst_local: np.ndarray,
times_sec: np.ndarray,
snapshot_sec: int,
amount: Optional[np.ndarray] = None,
) -> Tuple[np.ndarray, np.ndarray]:
"""Collapse repeated (politician, company) structural edges into one weighted edge,
reconstructing the per-pair stats the old lookups produced.
Returns
-------
edge_index : int64 [2, P] bipartite-local (row0 = pol, row1 = comp)
feats : float32 [P, F]
amount is None -> F=2: [interaction_count, days_since] (lobbying)
amount given -> F=3: [log1p(sum_amount), pair_count, days_since] (campaign)
days_since is measured from the most recent edge in each pair to the snapshot.
"""
if len(src_local) == 0:
F = 3 if amount is not None else 2
return np.empty((2, 0), dtype=np.int64), np.empty((0, F), dtype=np.float32)
df = pd.DataFrame({"s": src_local, "d": dst_local, "t": times_sec})
if amount is not None:
df["amt"] = amount
agg = {"t": ["count", "max"]}
if amount is not None:
agg["amt"] = "sum"
g = df.groupby(["s", "d"], sort=False).agg(agg)
g.columns = ["_".join(c).strip("_") for c in g.columns]
g = g.reset_index()
edge_index = np.stack([g["s"].to_numpy(), g["d"].to_numpy()]).astype(np.int64)
days_since = np.maximum(0.0, (snapshot_sec - g["t_max"].to_numpy()) / 86400.0)
count = g["t_count"].to_numpy().astype(np.float32)
if amount is not None:
log_amt = np.log1p(np.maximum(0.0, g["amt_sum"].to_numpy()))
feats = np.column_stack([log_amt, count, days_since]).astype(np.float32)
else:
feats = np.column_stack([count, days_since]).astype(np.float32)
return edge_index, feats
# ==================================================================================
# PHASE 3 -- build & save the static node tensors (needs torch + project deps)
# ==================================================================================
def build_node_features(
map_dir: str = "data/processed/pyg_graph",
trades_csv: str = "data/cropped/ml_dataset_continuous.csv",
processed_dir: str = "data/processed",
snapshot_date: Optional[str] = None,
save: bool = True,
) -> Dict:
"""Assemble the five static node tensors aligned to the Phase-4 node-id maps.
Replicates DynamicGraphBuilder.__init__ / build_pol_features / build_comp_features
plus the categorical-id construction that used to live in the training script.
"""
_require_torch()
from src import config # local import: keeps module importable without the project
from src.data_prep.feature_lookups import (
TermLookup, PoliticianBioLookup, IdeologyLookup,
CommitteeLookup, CompanySICLookup, CompanyFinancialsLookup,
)
def flag(name, default=False):
return getattr(config, name, default)
print("==================================================")
print("PHASE 3: STATIC NODE FEATURE EXTRACTION")
print("==================================================")
# --- 0. Node universe from the Phase-4 maps -----------------------------------
src_map = np.load(os.path.join(map_dir, "src_id_map.npy"), allow_pickle=True).item()
dst_map = np.load(os.path.join(map_dir, "dst_id_map.npy"), allow_pickle=True).item()
ordered_bio, ordered_tick, n_pol, n_comp = invert_node_maps(src_map, dst_map)
print(f" -> Node universe: {n_pol} politicians | {n_comp} companies")
# --- 1. Transactions: performance stats + categorical sources -----------------
df_tx = pd.read_csv(trades_csv, low_memory=False)
ticker_col = next((c for c in ("Ticker", "Matched_Ticker") if c in df_tx.columns), None)
if ticker_col is None:
raise ValueError("Transactions CSV needs a 'Ticker' or 'Matched_Ticker' column.")
for cat in ("State", "Sector", "Industry"):
if cat not in df_tx.columns:
print(f" [WARN] '{cat}' missing from transactions -> all UNK for that embedding.")
df_tx[cat] = np.nan
df_tx["BioGuideID"] = df_tx["BioGuideID"].astype(str)
df_tx[ticker_col] = df_tx[ticker_col].astype(str).str.upper()
snapshot = pd.to_datetime(snapshot_date) if snapshot_date else pd.to_datetime(df_tx["Filed"]).max()
print(f" -> Snapshot (as-of) date for time-varying features: {snapshot.date()}")
# Performance dict over the full window (matches the deprecated behaviour).
perf: Dict[str, list] = {}
if INCLUDE_PERFORMANCE:
label_col = "Excess_Return_6M"
t = df_tx.copy()
t["_lbl"] = (pd.to_numeric(t[label_col], errors="coerce") > 0).astype(float) if label_col in t else 0.0
t["_buy"] = t["Transaction"].astype(str).str.lower().str.contains("purchase", na=False).astype(float)
for bio_id, grp in t.groupby("BioGuideID"):
perf[bio_id] = [grp["_lbl"].mean(), float(np.log1p(len(grp))), grp["_buy"].mean()]
# --- 2. Instantiate the same lookups graph_builder used ------------------------
need_term = any(flag(f, False) or d for f, d in [
("INCLUDE_POLITICIAN_BIO", True), ("INCLUDE_IDEOLOGY", True), ("INCLUDE_COMMITTEES", True)
])
term_lookup = TermLookup(config.CONGRESS_TERMS_PATH) if need_term else None
lookups: Dict[str, object] = {}
pol_dim = 0
if INCLUDE_PERFORMANCE:
pol_dim += 3
if flag("INCLUDE_POLITICIAN_BIO", True):
lookups["bio"] = PoliticianBioLookup(config.CONGRESS_TERMS_PATH, term_lookup)
pol_dim += lookups["bio"].dim - lookups["bio"].state_dim # drop state one-hot
if flag("INCLUDE_IDEOLOGY", True):
lookups["ideology"] = IdeologyLookup(config.IDEOLOGY_PATH, term_lookup)
pol_dim += lookups["ideology"].dim
if flag("INCLUDE_COMMITTEES", True):
lookups["committee"] = CommitteeLookup(config.COMMITTEE_PATH, term_lookup)
pol_dim += lookups["committee"].dim
comp_dim = 0
if flag("INCLUDE_COMPANY_SIC", True):
lookups["sic"] = CompanySICLookup(config.COMPANY_SIC_PATH)
comp_dim += lookups["sic"].dim
if flag("INCLUDE_COMPANY_FINANCIALS", False):
lookups["financials"] = CompanyFinancialsLookup(config.COMPANY_FIN_PATH)
comp_dim += lookups["financials"].dim
print(f" -> Dimensions: pol_dim={pol_dim}, comp_dim={comp_dim}")
# --- 3. Dense politician features ---------------------------------------------
print(" -> Building politician features...")
x_pol = np.zeros((n_pol, pol_dim), dtype=np.float32)
for i, bio_id in enumerate(ordered_bio):
vec: List[float] = []
if INCLUDE_PERFORMANCE:
vec += perf.get(str(bio_id), list(PERF_DEFAULT))
if "bio" in lookups:
fb = lookups["bio"].get_vector(bio_id, snapshot).tolist()
leader_idx = lookups["bio"].dim - 1 # last entry is is_leader
vec += fb[:5] + [fb[leader_idx]] # chamber + party(4) + leader
if "ideology" in lookups:
vec += lookups["ideology"].get_vector(bio_id, snapshot).tolist()
if "committee" in lookups:
vec += lookups["committee"].get_vector(bio_id, snapshot).tolist()
if vec:
x_pol[i] = np.asarray(vec, dtype=np.float32)
# --- 4. Dense company features ------------------------------------------------
print(" -> Building company features...")
x_comp = np.zeros((n_comp, comp_dim), dtype=np.float32)
for j, tick in enumerate(ordered_tick):
vec = []
if "sic" in lookups:
vec += lookups["sic"].get_vector(tick, snapshot).tolist()
if "financials" in lookups:
vec += lookups["financials"].get_vector(tick, snapshot).tolist()
if vec:
x_comp[j] = np.asarray(vec, dtype=np.float32)
# --- 5. Categorical embedding indices (from transactions) ---------------------
print(" -> Encoding categorical embedding indices (state / sector / industry)...")
state_by_bio = {str(k): _dominant(v) for k, v in df_tx.groupby("BioGuideID")["State"]}
sector_by_tick = {str(k): _dominant(v) for k, v in df_tx.groupby(ticker_col)["Sector"]}
ind_by_tick = {str(k): _dominant(v) for k, v in df_tx.groupby(ticker_col)["Industry"]}
state_vocab = build_label_encoder(state_by_bio.values())
sector_vocab = build_label_encoder(sector_by_tick.values())
ind_vocab = build_label_encoder(ind_by_tick.values())
pol_state = encode_per_node([str(b) for b in ordered_bio], state_by_bio, state_vocab)
comp_sec = encode_per_node([str(t) for t in ordered_tick], sector_by_tick, sector_vocab)
comp_ind = encode_per_node([str(t) for t in ordered_tick], ind_by_tick, ind_vocab)
num_states, num_sectors, num_industries = len(state_vocab), len(sector_vocab), len(ind_vocab)
# The deprecated model defaulted to Embedding sizes 60/20/150; warn if data outgrew them.
for nm, n, old in [("states", num_states, 60), ("sectors", num_sectors, 20),
("industries", num_industries, 150)]:
if n > old:
print(f" [NOTE] num_{nm}={n} exceeds the old default {old}; size embeddings with the value above.")
meta = {
"pol_dim": int(pol_dim), "comp_dim": int(comp_dim),
"num_states": int(num_states), "num_sectors": int(num_sectors),
"num_industries": int(num_industries),
"n_pol": int(n_pol), "n_comp": int(n_comp),
"snapshot_date": str(snapshot),
"state_vocab": state_vocab, "sector_vocab": sector_vocab, "industry_vocab": ind_vocab,
}
bundle = {
"x_pol": torch.from_numpy(x_pol),
"pol_state": torch.from_numpy(pol_state),
"x_comp": torch.from_numpy(x_comp),
"comp_sec": torch.from_numpy(comp_sec),
"comp_ind": torch.from_numpy(comp_ind),
"meta": meta,
}
if save:
os.makedirs(processed_dir, exist_ok=True)
torch.save(bundle, os.path.join(processed_dir, NODE_BUNDLE_NAME))
with open(os.path.join(processed_dir, NODE_META_NAME), "w") as f:
json.dump(meta, f, indent=2)
print(f" -> Saved node tensors to {os.path.join(processed_dir, NODE_BUNDLE_NAME)}")
print("==================================================\n")
return bundle
# ==================================================================================
# Recombine shards -> one static bipartite graph for the model
# ==================================================================================
def load_combined_graph(
shard_dir: str = "data/processed/pyg_graph",
node_bundle_path: Optional[str] = None,
processed_dir: str = "data/processed",
device: str = "cpu",
build_aux: bool = True,
time_max=None, # str/Timestamp or epoch-seconds int; keep only edges with time <= cutoff
) -> Dict:
"""Concatenate all yearly shards into one static graph and attach node tensors.
Converts unified node ids back to the bipartite-local convention the model expects
(company index = global index - n_pol). Trades are the primary supervised edges;
lobbying / campaign are returned as the model's ``aux_edges`` dict; geo edges are
returned separately (the deprecated model has no geo conv).
Returns a dict with: x_pol, pol_state, x_comp, comp_sec, comp_ind, meta,
edge_index (trades, [2,E]), y (trade labels), aux_edges (model-ready),
geo_edges (for future use), and edge_time (trade epoch-seconds).
"""
_require_torch()
bundle_path = node_bundle_path or os.path.join(processed_dir, NODE_BUNDLE_NAME)
bundle = torch.load(bundle_path, map_location=device, weights_only=False)
meta = bundle["meta"]
n_pol = int(meta["n_pol"])
snapshot_sec = int(pd.to_datetime(meta["snapshot_date"]).timestamp())
# --- recombine shards ---------------------------------------------------------
shard_paths = sorted(glob.glob(os.path.join(shard_dir, "hillstreet_temporal_graph_*.pt")))
if not shard_paths:
raise FileNotFoundError(f"No shards found in {shard_dir}.")
src_l, dst_l, t_l, msg_l, y_l, et_l, ls_l = [], [], [], [], [], [], []
for p in shard_paths:
d = torch.load(p, map_location=device, weights_only=False)
src_l.append(d.src); dst_l.append(d.dst); t_l.append(d.t)
msg_l.append(d.msg); y_l.append(d.y); et_l.append(d.event_type)
# last_seen is the recency endpoint added when structural edges are collapsed.
# Older shards predate it; fall back to t (earliest == latest for un-collapsed).
ls_l.append(getattr(d, "last_seen", d.t))
src = torch.cat(src_l); dst = torch.cat(dst_l); t = torch.cat(t_l)
msg = torch.cat(msg_l); y = torch.cat(y_l); event_type = torch.cat(et_l)
last_seen = torch.cat(ls_l)
print(f" -> Recombined {len(shard_paths)} shards: {src.numel():,} total edges")
if time_max is not None:
tmax = int(time_max) if isinstance(time_max, (int, float)) else int(pd.to_datetime(time_max).timestamp())
# Filter on t (relationship START). An edge whose relationship began on or
# before the cutoff is kept even if its last_seen extends past it -- correct
# for expanding-window studies (the relationship existed as of the cutoff).
keep = t <= tmax
src, dst, t = src[keep], dst[keep], t[keep]
msg, y, event_type = msg[keep], y[keep], event_type[keep]
last_seen = last_seen[keep]
snapshot_sec = tmax # days_since measured as-of the cutoff, not the global meta snapshot
print(f" -> time_max applied (t <= {tmax}): {src.numel():,} edges remain")
dst_local = dst - n_pol # unified -> bipartite-local company index
def _split(et):
# Returns the EARLIEST timestamp as `t` (relationship age) and the most
# recent as `ls` (recency). Aggregations that want days-since pass `ls`.
m = event_type == et
return src[m], dst_local[m], t[m], msg[m], y[m], last_seen[m]
# --- trades (primary, supervised) ---------------------------------------------
s, d, tt, mm, yy, _ = _split(EVENT_TRADE)
edge_index = torch.stack([s, d], dim=0).to(torch.long)
out = {
"x_pol": bundle["x_pol"].to(device), "pol_state": bundle["pol_state"].to(device),
"x_comp": bundle["x_comp"].to(device), "comp_sec": bundle["comp_sec"].to(device),
"comp_ind": bundle["comp_ind"].to(device), "meta": meta,
"edge_index": edge_index, "y": yy.to(torch.long), "edge_time": tt,
"edge_attr": mm[:, _TRADE_IDX].to(torch.float32), # [E, 20] trade features for the decoder
"aux_edges": {}, "geo_edges": None,
}
if not build_aux:
return out
# --- auxiliary edges ----------------------------------------------------------
def _to_dev(ei_np, ft_np):
return {
"edge_index": torch.from_numpy(ei_np).to(torch.long).to(device),
"features": torch.from_numpy(ft_np).to(torch.float32).to(device),
}
# Lobbying: split by the structural flags packed in msg, aggregate per pair -> [count, days_since].
# days_since is computed from last_seen (recency), not t (which is now relationship age).
s, d, tt, mm, _, ls = _split(EVENT_LOBBY)
if s.numel() > 0:
spons = mm[:, _COL["is_sponsorship"]] > 0.5
voted = mm[:, _COL["voted_yea"]] > 0.5
for key, mask in (("lobby_strong", spons), ("lobby_weak", voted)):
if mask.any():
ei, ft = aggregate_pair_edges(
s[mask].cpu().numpy(), d[mask].cpu().numpy(),
ls[mask].cpu().numpy(), snapshot_sec)
if ei.shape[1] > 0:
out["aux_edges"][key] = _to_dev(ei, ft)
# Campaign: aggregate per pair -> [log1p(sum Fin_Amt), donation_count, days_since]
s, d, tt, mm, _, ls = _split(EVENT_CAMPAIGN)
if s.numel() > 0:
ei, ft = aggregate_pair_edges(
s.cpu().numpy(), d.cpu().numpy(), ls.cpu().numpy(),
snapshot_sec, amount=mm[:, _COL["Fin_Amt"]].cpu().numpy())
if ei.shape[1] > 0:
out["aux_edges"]["campaign"] = _to_dev(ei, ft)
# Geo: carried but not consumed by the deprecated model. Aggregate weight per pair.
s, d, tt, mm, _, ls = _split(EVENT_GEO)
if s.numel() > 0:
ei, ft = aggregate_pair_edges(
s.cpu().numpy(), d.cpu().numpy(), ls.cpu().numpy(),
snapshot_sec, amount=mm[:, _COL["Geo_Weight"]].cpu().numpy())
if ei.shape[1] > 0:
out["geo_edges"] = _to_dev(ei, ft)
present = list(out["aux_edges"].keys()) + (["geo"] if out["geo_edges"] is not None else [])
print(f" -> Edge groups ready: trades={edge_index.shape[1]:,} | aux/extra={present}")
return out
# ==================================================================================
# Raw-edge loader for expanding-window studies
# ==================================================================================
def load_raw_edges(
shard_dir: str = "data/processed/pyg_graph",
node_bundle_path: Optional[str] = None,
processed_dir: str = "data/processed",
device: str = "cpu",
) -> Dict:
"""Recombine all yearly shards ONCE and return the raw concatenated tensors plus
the static node bundle, so an expanding-window driver can build each monthly
window cheaply (boolean time masks + per-cutoff aux re-aggregation) without
re-reading the shards twelve times.
Unlike load_combined_graph, this does NOT pre-aggregate aux edges or fix a
snapshot -- recency (days_since) depends on the window cutoff, so the driver
must call aggregate_pair_edges per cutoff with snapshot = that cutoff.
Returns
-------
dict with:
src int64 [E] politician local idx in [0, n_pol)
dst_local int64 [E] company local idx in [0, n_comp)
t int64 [E] epoch seconds -- EARLIEST event of the edge (relationship start)
last_seen int64 [E] epoch seconds -- MOST RECENT event of the edge; pass THIS
(not t) as the time source to aggregate_pair_edges so
days_since measures recency, not relationship age
msg float [E, 24] full message tensor (use _COL / _TRADE_IDX to slice)
y int64 [E] labels (-1 on structural edges)
event_type int64 [E] EVENT_TRADE/LOBBY/CAMPAIGN/GEO
n_pol int
bundle dict node tensors (x_pol, pol_state, x_comp, comp_sec, comp_ind, meta)
meta dict
"""
_require_torch()
bundle_path = node_bundle_path or os.path.join(processed_dir, NODE_BUNDLE_NAME)
if not os.path.exists(bundle_path):
raise FileNotFoundError(
f"Node bundle not found: {bundle_path}. Did Phase 3 run? "
f"(re-run temporal_data.py WITHOUT --skip_node_features)")
print(f" -> Loading node bundle: {bundle_path}", flush=True)
bundle = torch.load(bundle_path, map_location=device, weights_only=False)
meta = bundle["meta"]
n_pol = int(meta["n_pol"])
shard_paths = sorted(glob.glob(os.path.join(shard_dir, "hillstreet_temporal_graph_*.pt")))
if not shard_paths:
raise FileNotFoundError(
f"No shards (hillstreet_temporal_graph_*.pt) found in {shard_dir}. Did Phase 4 run?")
print(f" -> Found {len(shard_paths)} shard(s) in {shard_dir}; loading...", flush=True)
src_l, dst_l, t_l, msg_l, y_l, et_l, ls_l = [], [], [], [], [], [], []
running = 0
for i, p in enumerate(shard_paths, 1):
try:
d = torch.load(p, map_location=device, weights_only=False)
except Exception as e:
raise RuntimeError(f"Failed to load shard {p}: {e}") from e
src_l.append(d.src); dst_l.append(d.dst); t_l.append(d.t)
msg_l.append(d.msg); y_l.append(d.y); et_l.append(d.event_type)
# Recency endpoint; fall back to t on shards built before the dedup change.
ls_l.append(getattr(d, "last_seen", d.t))
running += int(d.src.numel())
print(f" [{i}/{len(shard_paths)}] {os.path.basename(p)}: "
f"{int(d.src.numel()):,} edges (running total {running:,})", flush=True)
print(" -> Concatenating shard tensors...", flush=True)
raw = {
"src": torch.cat(src_l),
"dst_local": torch.cat(dst_l) - n_pol,
"t": torch.cat(t_l),
"last_seen": torch.cat(ls_l),
"msg": torch.cat(msg_l),
"y": torch.cat(y_l),
"event_type": torch.cat(et_l),
"n_pol": n_pol,
"bundle": bundle,
"meta": meta,
}
n_trade = int((raw["event_type"] == EVENT_TRADE).sum())
print(f" -> load_raw_edges: {n_trade:,} trade edges across {len(shard_paths)} shards "
f"({n_pol} politicians | {int(meta['n_comp'])} companies)")
return raw