# AUTOGENERATED! DO NOT EDIT! File to edit: ../00_core.ipynb.

# %% auto 0
__all__ = ['plot_univariate_continuous', 'rr_corr', 'corr_graph']

# %% ../00_core.ipynb 3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import networkx as nx
import sklearn.feature_selection as skfl

# %% ../00_core.ipynb 13
def plot_univariate_continuous(df:pd.DataFrame, # Data
                               var:str, # Variable to plot
                               var_name:str, # Variable name
                               ax): # Axes on which to draw the plot
   
    ## Calculate the quantiles
    df_plot = df[[var]].copy()
    df_plot['qcut'] = pd.qcut(df_plot[var], [0, 0.25, 0.75, 1], labels=['1st', 'iqr', '4th'])
   
    # Define the plaette
    # color palette as dictionary
    palette = {"1st":"silver",
               "iqr":"gold",
               "4th":"silver"}
   
    # Create a density plot
    sns.histplot(data=df_plot,
                 x=var,
                 stat='percent',
                 ax=ax,
                 hue='qcut',
                 multiple='stack',
                 palette=palette)
   
   
    # Remove legend
    ax.get_legend().remove()
   
    # Add a vertical line at the mean
    var_mean = df[var].mean()
   
    ax.axvline(var_mean)
   
    # Add labels
    ax.set_xlabel(var_name, fontfamily='Century Gothic', fontsize=16)
    ax.set_ylabel('Percent', fontfamily='Century Gothic', fontsize=16)
   
    # Set tick font size
    for label in (ax.get_xticklabels() + ax.get_yticklabels()):
        label.set_name('Century Gothic')
        label.set_size(12)
   
    return ax

# %% ../00_core.ipynb 18
def rr_corr(df:pd.DataFrame, # Data
            ratio_vars:list): # Columns in `df` with ratio variables
    """
    Correlation between al pairs of ratio variables in `df`
    
    Uses the `corr` method of `pandas.DataFrame` 
    """
    
    # Extract ratio variables
    df_corr = df[ratio_vars].copy()
    
    # Calculate the correlation between ratio features in the dataset
    df_corr = df.corr()
    
    # Reshape into a table removing redundant pairs
    df_corr = df_corr.where(np.triu(np.ones(df_corr.shape), 1).astype(bool))
    df_corr = df_corr.stack().reset_index()
    df_corr.columns = ['feat_1', 'feat_2', 'corr']
    
    # Absolute value of correlation is used since we only searh for association
    df_corr['abs_corr'] = df_corr['corr'].abs()
    
    return df_corr.sort_values('abs_corr', ascending=False)

# %% ../00_core.ipynb 26
def corr_graph(cdf:pd.DataFrame, # A dataframe as output by `ratio_corr`
               abs_corr_threshold:float = 0.5): # Threshold for high correlation
        
    # Filter values below `abs_corr_threshold`
    high_corr = cdf[cdf.abs_corr >= abs_corr_threshold].copy()
    
    # Sort for visualization
    high_corr = high_corr.sort_values(['abs_corr', 'feat_1', 'feat_2'], ascending=False)
    
    # Generate the graph
    corr_graph = nx.from_pandas_edgelist(high_corr, 'feat_1', 'feat_2')
    for node in corr_graph.nodes():
        corr_graph.nodes[node]['label'] = node
            
    return high_corr, corr_graph
