grid_graph.py 1.88 KB
Newer Older
1
2
3
# author: xbresson
# code link: https://github.com/xbresson/CE7454_2019/blob/master/codes/labs_lecture14/lab01_ChebGCNs/lib/grid_graph.py

4
5
6
import numpy as np
import scipy.sparse  # scipy.spatial.distance
import scipy.sparse.linalg
7
8
9
10
import sklearn
import sklearn.metrics


11
def grid_graph(grid_side, number_edges, metric):
12
13
14
15
    """Generate graph of a grid"""
    z = grid(grid_side)
    dist, idx = distance_sklearn_metrics(z, k=number_edges, metric=metric)
    A = adjacency(dist, idx)
16
    print("nb edges: ", A.nnz)
17
18
19
20
21
22
    return A


def grid(m, dtype=np.float32):
    """Return coordinates of grid points"""
    M = m**2
23
24
    x = np.linspace(0, 1, m, dtype=dtype)
    y = np.linspace(0, 1, m, dtype=dtype)
25
    xx, yy = np.meshgrid(x, y)
26
27
28
    z = np.empty((M, 2), dtype)
    z[:, 0] = xx.reshape(M)
    z[:, 1] = yy.reshape(M)
29
30
31
    return z


32
def distance_sklearn_metrics(z, k=4, metric="euclidean"):
33
    """Compute pairwise distances"""
34
    # d = sklearn.metrics.pairwise.pairwise_distances(z, metric=metric, n_jobs=-2)
35
36
    d = sklearn.metrics.pairwise.pairwise_distances(z, metric=metric, n_jobs=1)
    # k-NN
37
    idx = np.argsort(d)[:, 1 : k + 1]
38
    d.sort()
39
    d = d[:, 1 : k + 1]
40
41
42
43
44
45
46
47
48
49
50
    return d, idx


def adjacency(dist, idx):
    """Return adjacency matrix of a kNN graph"""
    M, k = dist.shape
    assert M, k == idx.shape
    assert dist.min() >= 0
    assert dist.max() <= 1

    # Pairwise distances
51
52
    sigma2 = np.mean(dist[:, -1]) ** 2
    dist = np.exp(-(dist**2) / sigma2)
53
54
55

    # Weight matrix
    I = np.arange(0, M).repeat(k)
56
57
    J = idx.reshape(M * k)
    V = dist.reshape(M * k)
58
59
60
61
62
63
64
65
66
67
68
69
70
    W = scipy.sparse.coo_matrix((V, (I, J)), shape=(M, M))

    # No self-connections
    W.setdiag(0)

    # Undirected graph
    bigger = W.T > W
    W = W - W.multiply(bigger) + W.T.multiply(bigger)

    assert W.nnz % 2 == 0
    assert np.abs(W - W.T).mean() < 1e-10
    assert type(W) is scipy.sparse.csr.csr_matrix
    return W