"""Attach one-hot node features from nodes_ML to the saved PyG graph. Each feature group is one categorical column; a node has exactly one 1 per group, so every row sums to the number of groups. """ import duckdb import torch from node2vec_model import load_graph from paths import DB_PATH, GRAPH_PATH DB = DB_PATH GRAPH = GRAPH_PATH # column expression -> group name. tissue is field 2 of the pipe-delimited # factor string, e.g. "(Camellia sinensis|leaf||experimental sample|...)". GROUPS = { "n.Study": "Study", "n.Analytics": "Analytics", "n.species": "species", "n.factor1_org": "factor1_org", "n.factor2_org": "factor2_org", "n.color_group": "color_group", "n.color_group_upper1": "color_group_upper1", "split_part(trim(n.factor1, '()'), '|', 2)": "tissue1", "split_part(trim(n.factor2, '()'), '|', 2)": "tissue2", } data = load_graph(GRAPH) con = duckdb.connect(DB, read_only=True) select = ", ".join(f'{e} AS "{name}"' for e, name in GROUPS.items()) rows = con.execute(f""" SELECT g.id, {select} FROM graph_nodes g JOIN nodes_ML n ON n.id = g.id ORDER BY g.idx """).fetchall() ids = [r[0] for r in rows] assert ids == data.node_id, "node order does not match the saved graph" blocks, names, bounds = [], [], {} offset = 0 for col, group in enumerate(GROUPS.values(), start=1): values = sorted({r[col] for r in rows}) index = {v: i for i, v in enumerate(values)} block = torch.zeros(len(rows), len(values)) block[torch.arange(len(rows)), torch.tensor([index[r[col]] for r in rows])] = 1.0 blocks.append(block) names += [f"{group}={v}" for v in values] bounds[group] = (offset, offset + len(values)) offset += len(values) print(f" {group:<20} {len(values):>4} dims cols {bounds[group]}") x = torch.cat(blocks, dim=1) data.x = x data.feature_names = names data.feature_groups = bounds torch.save(data, GRAPH) print(f"\nx = {tuple(x.shape)} {x.dtype}") print(f"row sums: min={x.sum(1).min():.0f} max={x.sum(1).max():.0f} " f"(expected {len(GROUPS)} = one 1 per group)") print(f"all-zero columns: {(x.sum(0) == 0).sum().item()}") print(f"density: {x.mean():.4f}") print(f"saved -> {GRAPH}") print(data)