# -*- coding: utf-8 -*-
"""
This module allows to visualize, plot and compute metrics on the infered gene regulatory networks, using built-in metrics in `networkx`_.

.. _scikit-learn:
    https://scikit-learn.org
"""
import pandas as pd
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
from scipy import stats
from grenadine.Inference.inference import rank_GRN
from sklearn.decomposition import PCA
from sklearn.metrics import roc_curve
from sklearn.metrics import roc_auc_score
from sklearn.metrics import auc
from sklearn.metrics import precision_recall_curve
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from tqdm import tqdm


__author__ = "Sergio Peignier, Pauline Schmitt, Baptiste Sorin"
__copyright__ = "Copyright 2019, The GReNaDIne Project"
__license__ = "GPL"
__version__ = "0.0.1"
__maintainer__ = "Sergio Peignier"
__email__ = "sergio.peignier@insa-lyon.fr"
__status__ = "pre-alpha"



def to_graph(ranking_df):
    """
    This method returns a directed graph generated by networkx
    """
    return(nx.from_pandas_edgelist(ranking_df,source='TF',target='TG'))
  
def draw_by(G, dico, maxi):  
    colnodes = list()
    sizenodes = list()
    for node in G.nodes:
        colnodes.append(dico[node])
        sizenodes.append((120.*dico[node])/maxi)
    nx.draw(G, pos = nx.nx_agraph.graphviz_layout(G), node_color = colnodes, node_size = sizenodes, cmap = 'plasma')

      
def rich_club_coefficient(G,show=False):
    undir_G=nx.to_undirected(G)
    rich_club = nx.rich_club_coefficient(undir_G)
    if(show):
        plt.bar(*zip(*rich_club.items()))
        plt.xlabel('k minimum')
        plt.ylabel('Coefficient rich club')
        plt.show()
    return(rich_club)
  

def betweenness_centrality(G,show=False):
    between = nx.betweenness_centrality(G)
    if(show):
        plt.bar(*zip(*between.items()))
        plt.xlabel('gene')
        plt.ylabel('Betweeness centrality')
        plt.show()
    return(between)
  
def clustering_coefficient(G,show=False):
    undir_G=nx.to_undirected(G)
    clust = nx.clustering(undir_G)
    if(show):
        plt.bar(*zip(*clust.items()))
        plt.xlabel('gene')
        plt.ylabel('Clustering coefficient')
        plt.show()
    return(clust)
  
def closeness_centrality(G,show=False):
    undir_G=nx.to_undirected(G)
    closeness = nx.closeness_centrality(undir_G)
    if(show):
        plt.bar(*zip(*closeness.items()))
        plt.xlabel('gene')
        plt.ylabel('Closeness centrality')
        plt.show()
    return(closeness)
