# CELL 0
# Obtaining flow surrogate

# CELL 1
In this jupyter notebook, we describe how we obtain the flow surrogate of a neural architecture, which represents the flow within a neural architecture.

# CELL 2
## 1. Prerequisite

# CELL 3
### 1.1. Required libraries

# CELL 4
## For running
import numpy as np
import copy
import torch
from tqdm import tqdm
from torch_scatter import scatter_sum
from torch_geometric.data import Data

## For visualization
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

# CELL 5
### 1.2. Source code

# CELL 6
## Key code
def give_flow_surrogate (d, alpha, x1, trans_vector, inter_vector, is_301 = False) : 
    
    np.random.seed(0)
    
    operation_vector = d.x @ trans_vector
    
    newX1 = torch.zeros((d.x.shape[0], x1.shape[0]), dtype = torch.float32)
    
    newX1[0] = x1
    if is_301 : # Each architecture in the NB-301 dataset has two input nodes.
        newX1[1] = x1
    
    ## Forward

    src = d.edge_index[0]
    des = d.edge_index[1]

    for m in range(d.edge_masks.shape[0]) : 

        out = scatter_sum(newX1[src], des, dim = 0)

        cur_mask = d.edge_masks[m, :]
        
        newX1[des[cur_mask]] = alpha * out[des[cur_mask]] + (1-alpha) * torch.relu(torch.hstack([operation_vector[des[cur_mask]], out[des[cur_mask]]]) @ inter_vector)
        
    ## Backward

    src = d.edge_index[1]
    des = d.edge_index[0]

    for m in range(d.edge_masks.shape[0]) : 

        out = scatter_sum(newX1[src], des, dim = 0)

        cur_mask = d.edge_masks[d.edge_masks.shape[0] - m - 1, :]
        
        newX1[des[cur_mask]] = alpha * out[des[cur_mask]] + (1-alpha) * torch.relu(torch.hstack([operation_vector[des[cur_mask]], out[des[cur_mask]]]) @ inter_vector)

    
    if is_301 : 
        fwbw_proxy = (newX1[0].reshape(1, -1) + newX1[1].reshape(1, -1))
        
    else : 
        fwbw_proxy = newX1[0].reshape(1, -1)
    
    return fwbw_proxy

def obtaining_surrogate (dataset, k, std, is_301 = False) : 
    
    np.random.seed(0)
    
    idid = 0
    
    x1 = np.random.uniform(0, 1.0, size = k) # vector r in the paper
    x2 = np.random.uniform(0, 1.0, size = k) # sub-vectors
    x1 = torch.tensor(x1, dtype = torch.float32)
    
    trans_matrix = np.random.normal(0, std, size = (dataset[0].x.shape[1], k)) # matrix P in the paper
    mul_matrix = np.random.normal(0, std, size = (k * 2, k)) # matrix W in the paper
    trans_matrix = torch.tensor(trans_matrix, dtype = torch.float32)
    mul_matrix = torch.tensor(mul_matrix, dtype = torch.float32)
    
    ground_truth_perf = []
    total_surrogate = torch.zeros((len(dataset), k))

    for tmpD in tqdm(dataset) : 

        newx1 = copy.deepcopy(x1)
        new_trans = copy.deepcopy(trans_matrix)

        surrogate = give_flow_surrogate(tmpD, alpha = 0.5, x1 = newx1,
                                        trans_vector = trans_matrix, 
                                        inter_vector = mul_matrix, 
                                        is_301 = is_301)

        total_surrogate[idid] = surrogate[0]
        ground_truth_perf.append(tmpD.y)

        idid += 1
        
    return total_surrogate, ground_truth_perf

# CELL 7
## 2. Obtain surrogate

# CELL 8
### 2.1. Hyperparameter configuration

# CELL 9
## Hyperparameters
mapper = {"nb101" : {"k": 4, "std": 1.0}, 
          "nb201" : {"k": 7, "std": 0.1}, 
          "nb301" : {"k": 12, "std": 0.1}}

# CELL 10
### 2.2. Nas-Bench-101 dataset

# CELL 11
## set data name
dname = "nb101"
orig_data = torch.load("./dataset/{0}_unified.pt".format(dname))

## Obtain surrogates
k = mapper[dname]["k"]
stds = mapper[dname]["std"]

total_surrogate, ground_truth_perf =  obtaining_surrogate (dataset = orig_data, k = k, std = stds, is_301 = False)
    
## Visualization

pca = PCA(n_components=3)
newX = pca.fit_transform(total_surrogate.cpu().numpy())

ranks = np.array(ground_truth_perf).argsort().argsort()

fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(newX[:, 0], newX[:, 1], newX[:, 2], c = ranks, cmap = "seismic")

# CELL 12
### 2.3. NAS-Bench-201 datasets

# CELL 13
## set data name
dname = "nb201"
orig_data = torch.load("./dataset/{0}_unified.pt".format(dname))

## Obtain surrogates
k = mapper[dname]["k"]
stds = mapper[dname]["std"]

total_surrogate, ground_truth_perf =  obtaining_surrogate (dataset = orig_data, k = k, std = stds, is_301 = False)
    
## Visualization

pca = PCA(n_components=3)
newX = pca.fit_transform(total_surrogate.cpu().numpy())

ranks = np.array(ground_truth_perf).argsort().argsort()

fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(newX[:, 0], newX[:, 1], newX[:, 2], c = ranks, cmap = "seismic")

# CELL 14
### 2.4. NAS-Bench-301 dataset

# CELL 15
## set data name
dname = "nb301"
orig_data = torch.load("./dataset/{0}_unified.pt".format(dname))

## Obtain surrogates
k = mapper[dname]["k"]
stds = mapper[dname]["std"]

total_surrogate, ground_truth_perf =  obtaining_surrogate (dataset = orig_data, k = k, std = stds, is_301 = True)
    
## Visualization
pca = PCA(n_components=3)
newX = pca.fit_transform(total_surrogate.cpu().numpy())

ranks = np.array(ground_truth_perf).argsort().argsort()

fig = plt.figure(figsize=(9, 9))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(newX[:,0], newX[:, 2], newX[:, 1], c = ranks, cmap = "seismic")