File size: 2,210 Bytes
91034b5
 
 
 
 
 
 
 
 
 
 
1a6e388
91034b5
1a6e388
 
91034b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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)