Datasets:
File size: 3,107 Bytes
ccf24a6 60e5f94 ccf24a6 60e5f94 ccf24a6 60e5f94 ccf24a6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | """Build an undirected PyG graph from the edge_ML_expected_ge5 DuckDB table."""
import duckdb
import torch
from torch_geometric.data import Data
from torch_geometric.utils import contains_self_loops, is_undirected, to_undirected
from paths import DB_PATH, GRAPH_PATH
DB = DB_PATH
TABLE = "edge_ML_expected_ge5"
OUT = GRAPH_PATH
con = duckdb.connect(DB, read_only=True)
# Map every id appearing in either column to a contiguous 0..N-1 index,
# ordered lexicographically so the mapping is reproducible.
con.execute(f"""
CREATE OR REPLACE TEMP TABLE node_map AS
SELECT id, (row_number() OVER (ORDER BY id) - 1)::BIGINT AS idx
FROM (
SELECT DISTINCT id FROM (
SELECT start_id AS id FROM {TABLE}
UNION ALL
SELECT end_id AS id FROM {TABLE}
)
)
""")
node_ids = [r[0] for r in con.execute("SELECT id FROM node_map ORDER BY idx").fetchall()]
num_nodes = len(node_ids)
pairs = con.execute(f"""
SELECT s.idx AS src, t.idx AS dst,
e.OddsRatio_log2, e.ChiTestsPValue
FROM {TABLE} e
JOIN node_map s ON s.id = e.start_id
JOIN node_map t ON t.id = e.end_id
""").fetchnumpy()
src = torch.from_numpy(pairs["src"]).to(torch.long)
dst = torch.from_numpy(pairs["dst"]).to(torch.long)
directed_edge_index = torch.stack([src, dst], dim=0)
# float64: ChiTestsPValue reaches ~1.8e-79, below the float32 normal range.
directed_edge_attr = torch.stack(
[
torch.from_numpy(pairs["OddsRatio_log2"]).to(torch.float64),
torch.from_numpy(pairs["ChiTestsPValue"]).to(torch.float64),
],
dim=1,
)
# to_undirected() adds the reverse of every edge and coalesces duplicates,
# so a pair present as both (a,b) and (b,a) in the table yields one edge pair.
# Both attributes are invariant under transposing the 2x2 table -- ad/(bc) and
# the chi-square statistic are unchanged -- so the reverse edge carries the
# same values, and the reduce= for any collapsed duplicate is immaterial.
edge_index, edge_attr = to_undirected(
directed_edge_index, directed_edge_attr, num_nodes=num_nodes, reduce="mean"
)
data = Data(edge_index=edge_index, edge_attr=edge_attr, num_nodes=num_nodes)
data.node_id = node_ids # index -> original string id
data.edge_attr_names = ["OddsRatio_log2", "ChiTestsPValue"]
torch.save(data, OUT)
print(f"rows in table : {directed_edge_index.size(1):,}")
print(f"nodes : {num_nodes:,}")
print(f"edge_index columns : {edge_index.size(1):,} (= 2 x undirected edges)")
print(f"undirected edges : {edge_index.size(1) // 2:,}")
print(f"is_undirected : {is_undirected(edge_index, num_nodes=num_nodes)}")
print(f"contains_self_loops : {contains_self_loops(edge_index)}")
print(f"isolated nodes : {num_nodes - torch.unique(edge_index[0]).numel():,}")
print(f"edge_attr : {tuple(edge_attr.shape)} {edge_attr.dtype} {data.edge_attr_names}")
print(f" OddsRatio_log2 range : {edge_attr[:, 0].min():.4f} .. {edge_attr[:, 0].max():.4f}")
print(f" ChiTestsPValue range : {edge_attr[:, 1].min():.6g} .. {edge_attr[:, 1].max():.6g}")
print(f"saved to : {OUT}")
print(data)
|