import numpy as np
import torch
import scipy.sparse as sp
import numba
from katz_solver import *
import warnings

warnings.filterwarnings("ignore")
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')

all_graph = ['Cora', 'Citeseer', 'ogbn-arxiv', 'as-skitter', 'ogbn-proteins', 'com-orkut', 'cit-patent', 'ogbl-ppa', 'ogbn-products',
               'wiki-talk', 'com-youtube', 'ogbn-mag', 'soc-lj1', 'reddit', 'pubmed', 'wiki-en21',
               'com-friendster', 'ogbn-papers100M', 'ogb-mag240m']

graph_names = ['wiki-talk', ]
path = './dataset/'

exp_result = np.load('./results/ppr_exp_result_new.npy', allow_pickle=True)
exp_result = exp_result.reshape(1, -1)[0][0]
lambda_result = np.load('./results/katz_exp_lambda.npy', allow_pickle=True)
lambda_result = lambda_result.reshape(1, -1)[0][0]

for graph_name in graph_names:
    all_result = {}
    graph_path = path + graph_name + '/'
    adj_matrix = sp.load_npz(graph_path + graph_name + '_csr-mat.npz')
    indices = adj_matrix.indices
    indptr = adj_matrix.indptr
    n = len(indptr) - 1
    degree = np.array(adj_matrix.sum(1)).flatten()
    lambda_1 = lambda_result[graph_name]
    alpha = 1. / (lambda_1 + 1)
    omega = 2. / (1 + np.sqrt(1 - (alpha * lambda_1) ** 2))
    eps = np.power(2.0, 8) / n
    mineps = np.power(2.0, -18) / n
    np.random.seed(17)
    s_nodes = exp_result[graph_name][0]
    while True:
        if eps >= 1 / degree.max():
            eps /= 2
            continue
        print(graph_name, eps, end=' ')
        graph_result = solve_a_graph_gpu(n, indptr, indices, degree, alpha, eps, s_nodes)
        print(graph_result[1].mean(), graph_result[2].mean())
        all_result[eps] = graph_result
        np.save('./results/' + graph_name +'/katz_exp_ratio_cuda_result_new.npy', all_result)
        eps /= 2
        if eps < mineps:
            break
