# GNN 101 hands-on lab: an office building as a graph. numpy only, runs offline.
# Mahmoud Abdelrahman, 2026 CCS Urban AI + Agent Workshop, Harbin Institute of Technology
import numpy as np
np.set_printoptions(precision=2, suppress=True)

# ===== Lab 1: the building as a graph =====
# Three floors, each a 4 x 5 grid of rooms. Room id = floor*20 + row*5 + col.
ROWS, COLS, FLOORS = 4, 5, 3
N = ROWS * COLS * FLOORS
def rid(f, r, c):
    return f * ROWS * COLS + r * COLS + c

edges = []
for f in range(FLOORS):
    for r in range(ROWS):
        for c in range(COLS):
            if c + 1 < COLS:   edges.append((rid(f, r, c), rid(f, r, c + 1)))   # shared wall (east)
            if r + 1 < ROWS:   edges.append((rid(f, r, c), rid(f, r + 1, c)))   # shared wall (south)
            if f + 1 < FLOORS: edges.append((rid(f, r, c), rid(f + 1, r, c)))   # floor slab (room above)

A = np.zeros((N, N))              # adjacency matrix: A[i, j] = 1 if room i and room j touch
for i, j in edges:
    A[i, j] = A[j, i] = 1
deg = A.sum(1)                    # degree: how many rooms touch each room

# ===== node features: what each room knows about itself =====
rng = np.random.default_rng(7)
sun  = rng.uniform(0, 8, N)                   # hours of direct sun on the window
occ  = rng.integers(1, 9, N).astype(float)    # number of occupants
area = rng.uniform(15, 40, N)                 # floor area in m2
X = np.c_[sun, occ, area]

# ===== label: is the room "too warm" in the afternoon? =====
# Each room has its own heat gain (sun + people per m2).
# A room is warmed a little by its own gain and mostly by heat leaking in from the rooms it touches.
gain = 0.6 * sun + 5.0 * occ / area
heat = 0.4 * gain + 1.0 * (A @ gain) / deg
y = (heat > np.median(heat)).astype(int)      # 1 = too warm, 0 = fine

# We only have occupant complaints (labels) for 20 rooms; we must predict the other 40.
train = np.sort(np.random.default_rng(1).choice(N, 20, replace=False))
test = np.setdiff1d(np.arange(N), train)

def standardise(F):
    return (F - F.mean(0)) / F.std(0)

def logistic_regression(F, y, train, lr=0.5, epochs=500):
    """Plain logistic regression trained only on the labelled rooms."""
    w = np.zeros(F.shape[1]); b = 0.0
    for _ in range(epochs):
        p = 1 / (1 + np.exp(-(F[train] @ w + b)))
        g = p - y[train]
        w -= lr * F[train].T @ g / len(train)
        b -= lr * g.mean()
    return (1 / (1 + np.exp(-(F @ w + b))) > 0.5).astype(int)

# ===== Lab 2: one round of message passing =====
def mean_of_neighbours(A, H):
    """Each room collects the features of the rooms it touches and takes the average."""
    return (A @ H) / A.sum(1, keepdims=True)

# ===== Lab 3: a GraphSAGE-style layer (mean aggregator) =====
def sage_features(A, H):
    """Concatenate [own features | mean of neighbours' features] (Hamilton et al., 2017)."""
    return np.c_[H, mean_of_neighbours(A, H)]

# ===== Lab 5 (stretch): the GCN propagation matrix =====
def normalised_adjacency(A):
    A_hat = A + np.eye(len(A))                 # self loop: a room also listens to itself
    D_inv_sqrt = np.diag(1 / np.sqrt(A_hat.sum(1)))
    return D_inv_sqrt @ A_hat @ D_inv_sqrt     # Kipf & Welling (2017)

if __name__ == '__main__':
    print('Lab 1')
    print('rooms:', N, '| edges:', len(edges))
    print('room 26 touches rooms:', np.nonzero(A[26])[0].tolist(), '| degree:', int(deg[26]))
    print('labelled rooms:', train.tolist())

    print('\nLab 2')
    M = mean_of_neighbours(A, X)
    print('room 26 own [sun, occupants, area]:      ', X[26])
    print('room 26 mean of neighbours [sun, occ, area]:', M[26])

    print('\nLab 3 and 4')
    pred_no_graph = logistic_regression(standardise(X), y, train)
    pred_graph = logistic_regression(standardise(sage_features(A, X)), y, train)
    acc0 = (pred_no_graph[test] == y[test]).mean()
    acc1 = (pred_graph[test] == y[test]).mean()
    print('accuracy on 40 unlabelled rooms, own features only:      ', round(acc0, 2))
    print('accuracy on 40 unlabelled rooms, own + neighbour features:', round(acc1, 2))

    print('\nLab 4b: the same test on 50 different random labelled sets')
    a0, a1 = [], []
    for s in range(50):
        tr = np.sort(np.random.default_rng(100 + s).choice(N, 20, replace=False))
        te = np.setdiff1d(np.arange(N), tr)
        a0.append((logistic_regression(standardise(X), y, tr)[te] == y[te]).mean())
        a1.append((logistic_regression(standardise(sage_features(A, X)), y, tr)[te] == y[te]).mean())
    print('mean accuracy, own features only:      ', round(float(np.mean(a0)), 2))
    print('mean accuracy, own + neighbour features:', round(float(np.mean(a1)), 2))

    print('\nLab 5 (stretch): two rounds of message passing')
    S = normalised_adjacency(A)
    two_hop = np.c_[X, S @ X, S @ S @ X]
    a2 = []
    for s in range(50):
        tr = np.sort(np.random.default_rng(100 + s).choice(N, 20, replace=False))
        te = np.setdiff1d(np.arange(N), tr)
        a2.append((logistic_regression(standardise(two_hop), y, tr)[te] == y[te]).mean())
    print('mean accuracy, own + 1-hop + 2-hop (GCN propagation):', round(float(np.mean(a2)), 2))
