import os
import pandas as pd
import seaborn as sns
import plotly.express as px
import plotly.io as pio
import plotly.graph_objects as go
import matplotlib.pyplot as plt

from hbn.constants import Defaults
from hbn.visualization import visualize

import warnings
warnings.filterwarnings("ignore")

%load_ext autoreload
%autoreload 2

%matplotlib inline

# pio.renderers.default = 'iframe'

import ipywidgets as widgets       # interactive display
%config InlineBackend.figure_format = 'svg' # other available formats are: 'retina', 'png', 'jpeg', 'pdf'
# load model output

df_classify = pd.read_csv(os.path.join(Defaults.MODEL_DIR, 'classifier-all-phenotypic-models-performance.csv'))
df_regress = pd.read_csv(os.path.join(Defaults.MODEL_DIR, 'regression-all-phenotypic-models-performance.csv'))

df_classify['data'] = df_classify['data'].map({'model-data': 'data', 'model-null': 'null'})

for idx,col in enumerate(['Assessment', 'Domain', 'Measure']):
    df_classify[col] = df_classify['features'].str.split('-').str.get(idx)
df_feature = pd.read_csv(os.path.join(Defaults.MODEL_DIR, 'classifier-feature_importance.csv'))

df_feature = df_feature[df_feature['Measure']!='all']
# set plotting style
visualize.plotting_style()
def interactive_plot(df, x='features', y='roc_auc_score'):
    
    fig = go.Figure()

    fig.add_trace(go.Violin(x=df[x][df['data']=='data'],
                            y=df[y][df['data']=='data'],
                            legendgroup='Null', scalegroup='Null', name='Null',
                            side='negative',
                            line_color='blue')
                 )
    fig.add_trace(go.Violin(x=df[x][df['data']=='null'],
                            y=df[y][df['data']=='null'],
                            legendgroup='Data', scalegroup='Data', name='Data',
                            side='positive',
                            line_color='orange')
                 )
    fig.update_traces(meanline_visible=True, box_visible=False)
    fig.update_layout(violingap=0, violinmode='overlay')
    fig.update_xaxes(showticklabels=False)
    fig.update_yaxes(title_text=y)
    fig.show()
    
def stable_plot(df, x='features', y='roc_auc_score', hue='data'):
    ax = sns.violinplot(
        x=x, 
        y=y, 
        hue=hue, 
        data=df, 
        split=True,  
        scale='width',
        inner='quartile'
        )
    ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.1),
              ncol=2, fancybox=True, shadow=True)
    plt.xticks(rotation=90)
    plt.show()
# Child Measures - Language Tasks

df1 = df_classify[(df_classify['target']=='DX_01_Cat_binarize') & 
                  (df_classify['Assessment']=='Child_Measures') & 
                  (df_classify['Domain']=='Language_Tasks')]


interactive_plot(df=df1)
# Parent Measures - Demographics

df1 = df_classify[(df_classify['target']=='DX_01_Cat_binarize') & 
                  (df_classify['Assessment']=='Parent_Measures') & 
                  (df_classify['Domain']=='Demographic_Questionnaire_Measures')]


interactive_plot(df=df1)
# Parent Measures - Interview of Emotional and Psychological Function

df1 = df_classify[(df_classify['target']=='DX_01_Cat_binarize') & 
                  (df_classify['Assessment']=='Parent_Measures') & 
                  (df_classify['Domain']=='Interview_of_Emotional_and_Psychological_Function')]


interactive_plot(df=df1)
# Child Measures - Cognitive Testing

df1 = df_classify[(df_classify['target']=='DX_01_Cat_binarize') & 
                  (df_classify['Assessment']=='Child_Measures') & 
                  (df_classify['Domain']=='Cognitive_Testing')]


interactive_plot(df=df1)
# Child Measures - Questionnaire_Measures_of_Emotional_and_Cognitive_Status

df1 = df_classify[(df_classify['target']=='DX_01_Cat_binarize') & 
                  (df_classify['Assessment']=='Child_Measures') & 
                  (df_classify['Domain']=='Questionnaire_Measures_of_Emotional_and_Cognitive_Status')]


interactive_plot(df=df1)
# Child Measures : all other domains

df1 = df_classify[(df_classify['target']=='DX_01_Cat_binarize') & 
                  (df_classify['Assessment']=='Child_Measures')]

cols = ['Physical_Fitness_and_Status', 'Neurologic_Function', 'Physiologic_Function', 'Vision', 'Motor_Skills']

df1 = df1[df1['Domain'].isin(cols)]

interactive_plot(df=df1)
# interactive visualization of features
@widgets.interact(
                feature=df_feature['features'].unique(),
                )

def visualize_features(feature):
    df = df_feature[df_feature['features']==feature]
    fig = px.line(df, x='feature_names_sum', y='feature_sum', markers=True, title=feature)
    fig.update_xaxes(showticklabels=False)
    fig.update_xaxes(type='category')
    
    fig.show()
"},"metadata":{},"output_type":"display_data"}],"tabbable":null,"tooltip":null}},"5c0ced5a3fb546ebb3f6bcfd6e1f7518":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"63ebb2a5eb704cb7a624ebb03f371b1d":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"VBoxModel","state":{"_dom_classes":["widget-interact"],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"VBoxModel","_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"VBoxView","box_style":"","children":["IPY_MODEL_855c76c2e01b43e987c3be43583c66b2","IPY_MODEL_0bbcdebbe82548d59cf98e4b1914a7bc"],"layout":"IPY_MODEL_d5faf1a719884c59886b7c876a9391ee","tabbable":null,"tooltip":null}},"7eb63b118b414d86b6b80e4e3669b35d":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"DescriptionStyleModel","state":{"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"DescriptionStyleModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"StyleView","description_width":""}},"855c76c2e01b43e987c3be43583c66b2":{"model_module":"@jupyter-widgets/controls","model_module_version":"2.0.0","model_name":"DropdownModel","state":{"_dom_classes":[],"_model_module":"@jupyter-widgets/controls","_model_module_version":"2.0.0","_model_name":"DropdownModel","_options_labels":["Parent_Measures-Demographic_Questionnaire_Measures-Financial_Support_Questionnaire","Parent_Measures-Demographic_Questionnaire_Measures-Strengths_and_Difficulties_Questionnaire_(with_impact_supplement)","Child_Measures-Questionnaire_Measures_of_Emotional_and_Cognitive_Status-Inventory_of_Callous-Unemotional_Traits","Child_Measures-Language_Tasks-Test_of_Word_Reading_Efficiency_-_II","Parent_Measures-Interview_of_Emotional_and_Psychological_Function-Negative_Life_Events_Scale_–_Parent_Report","Child_Measures-Questionnaire_Measures_of_Emotional_and_Cognitive_Status-WHO_Disability_Assessment_Schedule_–_Self_Report","Parent_Measures-Demographic_Questionnaire_Measures-Demographics","Parent_Measures-Demographic_Questionnaire_Measures-Child_Behavior_Checklist","Parent_Measures-Demographic_Questionnaire_Measures-Social_Responsiveness_Scale-2","Parent_Measures-Demographic_Questionnaire_Measures-The_Columbia_Impairment_Scale-Parent_Report_Version","Parent_Measures-Demographic_Questionnaire_Measures-Repetitive_Behavior_Scale","Parent_Measures-Demographic_Questionnaire_Measures-Barratt_Simplified_Measure_of_Social_Status","Parent_Measures-Demographic_Questionnaire_Measures-Mood_and_Feelings_Questionnaire","Parent_Measures-Demographic_Questionnaire_Measures-Extended_Strengths_and_Weaknesses_Assessment_of_Normal_Behavior-Parent_Report","Parent_Measures-Demographic_Questionnaire_Measures-Strengths_and_Weaknesses_Assessment_of_ADHD_and_Normal_Behavior","Child_Measures-Questionnaire_Measures_of_Emotional_and_Cognitive_Status-The_Columbia_Impairment_Scale-Self_Report_Version","Child_Measures-Interview_of_Emotional_and_Psychological_Function-Negative_Life_Events_Scale_","Parent_Measures-Demographic_Questionnaire_Measures-Inventory_of_Callous-Unemotional_Traits_–_Parent_Report","Child_Measures-Cognitive_Testing-Wechsler_Intelligence_Scale_for_Children_-_V","Child_Measures-Neurologic_Function-Electro-encephalography","Parent_Measures-Demographic_Questionnaire_Measures-Affective_Reactivity_Index-Parent","Child_Measures-Physical_Fitness_and_Status-Physical_Activity_Questionnaire_for_Adolescents_","Child_Measures-Vision-Ishihara_Color_Vision_Test","Child_Measures-Language_Tasks-Clinical_Evaluation_of_Language_Fundamentals__Screening_Test","Child_Measures-Questionnaire_Measures_of_Emotional_and_Cognitive_Status-Mood_and_Feelings_Questionnaire_–_Long_Version","Child_Measures-Physiologic_Function-Physical_Measures","Child_Measures-Cognitive_Testing-Wechsler_Individual_Achievement_Test_-_III","Child_Measures-Physical_Fitness_and_Status-Edinburgh_Handedness","Child_Measures-Questionnaire_Measures_of_Emotional_and_Cognitive_Status-Affective_Reactivity_Index_–_Self_Report","Child_Measures-Language_Tasks-Clinical_Evaluation_of_Language_Fundamentals"],"_view_count":null,"_view_module":"@jupyter-widgets/controls","_view_module_version":"2.0.0","_view_name":"DropdownView","description":"feature","description_allow_html":false,"disabled":false,"index":0,"layout":"IPY_MODEL_5c0ced5a3fb546ebb3f6bcfd6e1f7518","style":"IPY_MODEL_7eb63b118b414d86b6b80e4e3669b35d","tabbable":null,"tooltip":null}},"98b148ae32504132b1056f4bcdc93345":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}},"d5faf1a719884c59886b7c876a9391ee":{"model_module":"@jupyter-widgets/base","model_module_version":"2.0.0","model_name":"LayoutModel","state":{"_model_module":"@jupyter-widgets/base","_model_module_version":"2.0.0","_model_name":"LayoutModel","_view_count":null,"_view_module":"@jupyter-widgets/base","_view_module_version":"2.0.0","_view_name":"LayoutView","align_content":null,"align_items":null,"align_self":null,"border_bottom":null,"border_left":null,"border_right":null,"border_top":null,"bottom":null,"display":null,"flex":null,"flex_flow":null,"grid_area":null,"grid_auto_columns":null,"grid_auto_flow":null,"grid_auto_rows":null,"grid_column":null,"grid_gap":null,"grid_row":null,"grid_template_areas":null,"grid_template_columns":null,"grid_template_rows":null,"height":null,"justify_content":null,"justify_items":null,"left":null,"margin":null,"max_height":null,"max_width":null,"min_height":null,"min_width":null,"object_fit":null,"object_position":null,"order":null,"overflow":null,"padding":null,"right":null,"top":null,"visibility":null,"width":null}}},"version_major":2,"version_minor":0}