

#import chart_studio.plotly as py
import plotly.graph_objects as go
import plotly.figure_factory as ff
import tkinter
from plotly.subplots import make_subplots
from scipy.spatial.distance import pdist

from igraph import Graph, EdgeSeq
import scipy.stats

from plotly.graph_objs import *
import numpy as np
import pandas as pd
from QMS_Algorithms import *

import warnings
warnings.filterwarnings('ignore')

def make_annotations(pos, labels,M, font_size=20, font_color='white'):
    L=len(pos)
    if len(labels)!=L:
        raise ValueError('The lists pos and text must have the same len')
    annotations = []
    for k in range(L):
        annotations.append(
            dict(
                text=labels[k], # or replace labels with a different list for the text within the circle
                x=pos[k][0], y=2*M-pos[k][1],
                xref='x1', yref='y1',
                bordercolor="#c7c7c7",
                borderwidth=2,
                borderpad=4,
                bgcolor="Royalblue",
                opacity=0.65,
                font=dict(color=font_color, size=font_size),
                showarrow=False)
        )
    return annotations


def unpack(rows, key):
    return list(map(key,rows))



def ControlPlot(ftrDataframe,xdict,figName):

  # eg,
  # fileName = 'data_preprocessed_original.csv'
  # featureName = 'ftr25'
  # data = pd.read_csv(fileName)
  # ftrDataframe = data[featureName].dropna()
  # xdict = CalcControlArgs(ftrDataframe,40.056,40.026)
  # figName = 'ControlPlot'
  # ControlPlot(ftrDataframe,xdict,figName)    
    
    
    y = ftrDataframe.values
    x = list(range(0,len(y)))    
    zone_c_upper_limit = xdict['Zone_c_limit'][0]
    zone_c_lower_limit = xdict['Zone_c_limit'][1]
    zone_b_upper_limit = xdict['Zone_b_limit'][0]
    zone_b_lower_limit = xdict['Zone_b_limit'][1]
    zone_a_upper_limit = xdict['Zone_a_limit'][0]
    zone_a_lower_limit = xdict['Zone_a_limit'][1]
    
    centerL = xdict['Center']
    ucl = xdict['UCL']
    lcl = xdict['LCL']
    x2 = [x[0]-(x[-1]-x[0])/10, x[-1]+(x[-1]-x[0])/10]
    x3 = [x[0]-(x[-1]-x[0])/10, x[-1]+(x[-1]-x[0])/10, None, x[0]-(x[-1]-x[0])/10, x[-1]+(x[-1]-x[0])/10]
    
    
    
    trace1 = {
      "uid": "cb8982", 
      "line": {
        "color": "rgb(0,116,217)", 
        "width": 2
      }, 
      "mode": "lines+markers", 
      "name": "Data", 
      "type": "scatter", 
      # "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36], 
      # "y": [-0.2625, -0.2925, -0.1425, -0.0875, -0.01, -0.045, -0.04, -0.0075, -0.0025, -0.1875, -0.21, -0.1725, -0.2025, -0.125, -0.14, -0.065, 0.0325, -0.13, -0.0925, 0.0825, 0.235, -0.0125, 0.065, 0.065, 0.215, 0.0975, 0.085, -0.235, -0.205, -0.27, -0.205, -0.1875, -0.1725, -0.185, -0.195, -0.105], 
      "x": unpack(x,str),
      "y": y,
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "rgb(0,116,217)", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "rgb(0,116,217)", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    
    
    
    
    trace2 = {
      "uid": "135942", 
      "line": {
        "color": "black", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "Center", 
      "type": "scatter", 
      "x": unpack(x2,str), 
      "y": [centerL, centerL], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "black", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "black", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    if isinstance (lcl,float):
        trace3 = {
          "uid": "df651f", 
          "line": {
            "color": "rgb(255,133,27)", 
            "width": 2,
            "dash":'dot'
          }, 
          "mode": "lines", 
          "name": "LCL/UCL", 
          "type": "scatter", 
          "x": unpack(x3,str), 
          "y": [lcl, lcl, None, ucl, ucl], 
          "xaxis": "x", 
          "yaxis": "y", 
          "marker": {
            "size": 8, 
            "color": "rgb(255,133,27)", 
            "symbol": "circle"
          }, 
          "error_x": {"copy_ystyle": True}, 
          "error_y": {
            "color": "rgb(255,133,27)", 
            "width": 1, 
            "thickness": 1
          }, 
          "visible": True, 
          "showlegend": True
        }
    else:
        trace3l = {
          "uid": "df651f", 
          "line": {
            "color": "rgb(255,133,27)", 
            "width": 2,
            "dash":'dot'
          }, 
          "mode": "lines", 
          "name": "LCL/UCL", 
          "type": "scatter", 
          "x": unpack(x,str), 
          "y": lcl, 
          "xaxis": "x", 
          "yaxis": "y", 
          "marker": {
            "size": 8, 
            "color": "rgb(255,133,27)", 
            "symbol": "circle"
          }, 
          "error_x": {"copy_ystyle": True}, 
          "error_y": {
            "color": "rgb(255,133,27)", 
            "width": 1, 
            "thickness": 1
          }, 
          "visible": True, 
          "showlegend": True
        }

        trace3u = {
          "uid": "df651f", 
          "line": {
            "color": "rgb(255,133,27)", 
            "width": 2,
            "dash":'dot'
          }, 
          "mode": "lines", 
          "name": "LCL/UCL", 
          "type": "scatter", 
          "x": unpack(x,str), 
          "y": ucl, 
          "xaxis": "x", 
          "yaxis": "y", 
          "marker": {
            "size": 8, 
            "color": "rgb(255,133,27)", 
            "symbol": "circle"
          }, 
          "error_x": {"copy_ystyle": True}, 
          "error_y": {
            "color": "rgb(255,133,27)", 
            "width": 1, 
            "thickness": 1
          }, 
          "visible": True, 
          "showlegend": True
        }

    
    trace4 = {
      "uid": "df651f", 
      "line": {
        "color": "grey", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "zone a", 
      "type": "scatter", 
      "x": unpack(x3,str), 
      "y": [zone_a_lower_limit, zone_a_lower_limit, None, zone_a_upper_limit, zone_a_upper_limit], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "grey", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "grey", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    
    trace5 = {
      "uid": "df651f", 
      "line": {
        "color": "grey", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "zone b", 
      "type": "scatter", 
      "x": unpack(x3,str), 
      "y": [zone_b_lower_limit, zone_b_lower_limit, None, zone_b_upper_limit, zone_b_upper_limit], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "grey", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "grey", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    
    trace6 = {
      "uid": "df651f", 
      "line": {
        "color": "grey", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "zone c", 
      "type": "scatter", 
      "x": unpack(x3,str), 
      "y": [zone_c_lower_limit, zone_c_lower_limit, None, zone_c_upper_limit, zone_c_upper_limit], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "magenta", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "magenta", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
        
    if isinstance (lcl,float):
        traceList = [trace1, trace2, trace3, trace4, trace5, trace6]
    else:    
        traceList = [trace1, trace2, trace3l, trace3u, trace4, trace5, trace6]
        
    colorModeList = [
        '#ff7f0e',  # safety orange
        '#2ca02c',  # cooked asparagus green
        '#d62728',  # brick red
        '#9467bd',  # muted purple
        '#8c564b',  # chestnut brown
        '#e377c2',  # raspberry yogurt pink
        'aqua',  # middle gray
        '#bcbd22',  # curry yellow-green
    ]
    for ix_trace in range(7,15):
        y1 = list(xdict['Rule'+str(ix_trace - 6)].values)
        x1 = list(xdict['Rule'+str(ix_trace - 6)].index)
        # if len(x1)!=0:
        locals()['trace'+str(ix_trace)] = {
          "uid": "d7228d", 
           "line": {
             "color": colorModeList[ix_trace - 7], 
             "width": 2
           }, 
          "mode": "markers", 
          "name": 'Rule'+str(ix_trace - 7), 
          "type": "scatter", 
          "x": unpack(x1,str), 
          "y": y1, 
          "xaxis": "x", 
          "yaxis": "y", 
          "marker": {
            # "line": {"width": 3}, 
            "size": 12, 
            "color": colorModeList[ix_trace - 7], 
            "symbol": "circle", 
            "opacity": 0.5
          }, 
           "error_x": {"copy_ystyle": True}, 
           "error_y": {
             "color": colorModeList[ix_trace - 7], 
             "width": 1, 
             "thickness": 1
           }, 
          "visible": True, 
          "showlegend": True
        }
        traceList.append(locals()['trace'+str(ix_trace)])
    
    
    
    data = Data(traceList)
    
    layout = {"title": str(figName)}
    # "title": "SPC 控制图"} 
    fig = Figure(data=data, layout=layout)
    # fig.update_yaxes(title_text=featureName)
    # fig.write_html(figName+'.html',auto_open = False)

    # fig.write_html('/home/QMSBI/'+figName+'.html',auto_open = False)
    # fig.write_html('e:/'+figName+'.html',auto_open = False)
    # fig.show()
    return fig.to_html()



def CorrPlot(x, y, size_in):
    
    tmpdf = pd.DataFrame({})
    
    # Mapping from olumn names to integer coordinates
    x_labels = [v for v in sorted(x.unique())]
    y_labels = [v for v in sorted(y.unique())] 
    y_to_num = {p[1]:p[0] for p in enumerate(y_labels)}
    x_to_num = dict(zip(y_labels,list(y_to_num.values())[::-1]))
    
    tmpdf['varX'] = x
    tmpdf['varY'] = y
    tmpdf['corr_value'] = size_in
    tmpdf['xcode'] = x.map(x_to_num) # Use mapping for x
    tmpdf['ycode'] = y.map(y_to_num) # Use mapping for y
    tmpdf['sum'] = tmpdf['xcode'] + tmpdf['ycode'] 
    
    tmpdf['compare'] = tmpdf['sum'] < (len(x_labels)-1)
    
    tmpdf_upper = tmpdf.loc[tmpdf['compare'] == True]
    tmpdf_lower = tmpdf.loc[tmpdf['compare'] == False]
    
    fig = px.scatter(
        x=tmpdf_upper['xcode'], # Use mapping for x
        y=tmpdf_upper['ycode'], # Use mapping for y
        size=np.abs(tmpdf_upper['corr_value']),
        color=tmpdf_upper['corr_value'],
        color_continuous_scale='RdBu',
        range_color=[-1,1]
    )
    
    fig.add_trace(
        go.Scatter(
            x=tmpdf_lower['xcode'], 
            y=tmpdf_lower['ycode'],
            mode='text',
            text = np.round(tmpdf_lower['corr_value'],2),
        )
    )
        
    fig.update_layout(
        title='相关图',
        showlegend=False,
        plot_bgcolor='rgba(0,0,0,0)',
        xaxis = dict(
        tickmode = 'array',
        tickvals = [x_to_num[v] for v in x_labels],
        ticktext = x_labels,
        title = None,
        tickangle = -30,
        side = 'top'
        ),
        yaxis = dict(
        tickmode = 'array',
        tickvals = [y_to_num[v] for v in y_labels],
        ticktext = y_labels,
        title = None      
        )
    )
    
    # fig.show()
    # fig.write_html('e:/new_corr.html')
    
    return fig.to_html()


def CPKBoxPlot(ftrDataframe,xdict,figName):
        
    # eg,
    # fileName = 'data_preprocessed_original.csv'
    # featureName = 'ftr25'
    # data = pd.read_csv(fileName)
    # ftrDataframe = data[featureName].dropna()
    # xdict = CalcCpkArgs(ftrDataframe,40.056,40.026,3,5)
    # figName = 'cpkBoxPlot'
    # cpkBoxPlot(ftrDataframe,xdict,figName)    
        
    fig = make_subplots(rows=1, cols=2,column_widths=[0.85,0.15],subplot_titles = ['Cpk, '+'组数 = '+str(len(xdict['CpkSeq'])),'Ppk'], start_cell="bottom-left")
    for cpk_ix in range(len(xdict['CpkSeq'])):
        fig.add_trace(go.Box(
            y=xdict['ListedDataForBoxplot'][cpk_ix],
            x=len(xdict['ListedDataForBoxplot'][cpk_ix])*[xdict['CpkSeq'][cpk_ix]],
            name='Cpk '+str(np.round(xdict['CpkSeq'][cpk_ix],2)),
            # marker_color='#FF851B'
        ), row=1, col=1)
    
    
    fig.add_trace(go.Box(
        y=ftrDataframe,
        x=len(ftrDataframe)*[xdict['Ppk']],
        name='Ppk '+str(np.round(xdict['Ppk'],2)),
        # marker_color='#FF851B'
    ), row=1, col=2)
    
    x = xdict['CpkSeq'].values
    x3 = [x[0]-(x[-1]-x[0])/10, x[-1]+(x[-1]-x[0])/10, None, x[0]-(x[-1]-x[0])/10, x[-1]+(x[-1]-x[0])/10]
    ucl = xdict['UCL']
    lcl = xdict['LCL']
    x4 = [xdict['Ppk']-xdict['Ppk'], xdict['Ppk']+xdict['Ppk'], None, xdict['Ppk']-xdict['Ppk'], xdict['Ppk']+xdict['Ppk']]
    trace3 = {
      "uid": "df651f", 
      "line": {
        "color": "rgb(255,133,27)", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "LCL/UCL", 
      "type": "scatter", 
      "x": unpack(x3,str), 
      "y": [lcl, lcl, None, ucl, ucl], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "rgb(255,133,27)", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "rgb(255,133,27)", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    trace4 = {
      "uid": "df651f", 
      "line": {
        "color": "rgb(255,133,27)", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "LCL/UCL", 
      "type": "scatter", 
      "x": unpack(x4,str), 
      "y": [lcl, lcl, None, ucl, ucl], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "rgb(255,133,27)", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "rgb(255,133,27)", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    fig.add_trace(trace3, row=1, col=1)
    fig.add_trace(trace4, row=1, col=2)
    fig.update_xaxes(title_text='Cpk', row=1, col=1)
    fig.update_xaxes(title_text='Ppk', row=1, col=2)    
    
    # fig.write_html('/home/cpkbox.html',auto_open = False)
    return fig.to_html()



def PPKHistPlot(inputdata,xdict,featureName):
        
    # eg,
    # fileName = 'data_preprocessed_original.csv'
    # featureName = 'ftr25'
    # data = pd.read_csv(fileName)
    # inputdata = data.ftr25.dropna()
    # xdict = CalcPpkArgs(inputdata,40.056,40.026)
    # figName = 'PpkHistPlot'    
    # PpkHistPlot(inputdata,xdict,figName)
    
    # fig = go.Figure()
    fig = make_subplots(specs=[[{"secondary_y": True}]])

    fig.add_trace(go.Scatter(x = xdict['DensityCurve_x'],
                             y = xdict['DensityCurve_y'],
                             line = {"color": "orange",
                                     "width": 3},                          
                             opacity = 0.5,
                             name = '拟合曲线'
                             ),
                             secondary_y = False)
    
    fig.add_trace(go.Histogram(x=inputdata,
                               # nbinsx=int(len(xdict['DensityCurve_x'])/10),
                               xbins=dict(
                                   start=xdict['DensityCurve_x'][0],
                                   end=xdict['DensityCurve_x'][-1],                               
                                   size= (xdict['DensityCurve_x'][-1] - xdict['DensityCurve_x'][0])/10),
                               autobinx = True,
                               marker = {"color": 'Royalblue'},
                               opacity = 0.5,
                               name = featureName),
                               secondary_y = True)

    zone_a_upper_limit = xdict['Sample_mean'] + xdict['Sigma']*3
    zone_a_lower_limit = xdict['Sample_mean'] - xdict['Sigma']*3
    zone_b_upper_limit = xdict['Sample_mean'] + xdict['Sigma']*2
    zone_b_lower_limit = xdict['Sample_mean'] - xdict['Sigma']*2
    zone_c_upper_limit = xdict['Sample_mean'] + xdict['Sigma']
    zone_c_lower_limit = xdict['Sample_mean'] - xdict['Sigma']
    
    centerL = xdict['Sample_mean']
    ucl = xdict['Sample_mean'] + xdict['Sigma']*xdict['UpperSigmaLvl']
    lcl = xdict['Sample_mean'] - xdict['Sigma']*xdict['LowerSigmaLvl']
    x2 = [0, 1.5*np.max(xdict['DensityCurve_y'])]
    x3 = [0, 1.5*np.max(xdict['DensityCurve_y']), None, 0, 1.5*np.max(xdict['DensityCurve_y'])]
    
    trace1 = {
      "uid": "135942", 
      "line": {
        "color": "black", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "μ", 
      "type": "scatter", 
      "y": unpack(x2,str), 
      "x": [centerL, centerL], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "black", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "black", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    
    trace2 = {
      "uid": "df651f", 
      "line": {
        "color": "rgb(255,133,27)", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "LCL/UCL", 
      "type": "scatter", 
      "y": unpack(x3,str), 
      "x": [lcl, lcl, None, ucl, ucl], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "rgb(255,133,27)", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "rgb(255,133,27)", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    
    trace3 = {
      "uid": "df651f", 
      "line": {
        "color": "grey", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "3σ", 
      "type": "scatter", 
      "y": unpack(x3,str), 
      "x": [zone_a_lower_limit, zone_a_lower_limit, None, zone_a_upper_limit, zone_a_upper_limit], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "grey", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "grey", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    
    trace4 = {
      "uid": "df651f", 
      "line": {
        "color": "grey", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "2σ", 
      "type": "scatter", 
      "y": unpack(x3,str), 
      "x": [zone_b_lower_limit, zone_b_lower_limit, None, zone_b_upper_limit, zone_b_upper_limit], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "grey", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "grey", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    
    trace5 = {
      "uid": "df651f", 
      "line": {
        "color": "grey", 
        "width": 2,
        "dash":'dot'
      }, 
      "mode": "lines", 
      "name": "σ", 
      "type": "scatter", 
      "y": unpack(x3,str), 
      "x": [zone_c_lower_limit, zone_c_lower_limit, None, zone_c_upper_limit, zone_c_upper_limit], 
      "xaxis": "x", 
      "yaxis": "y", 
      "marker": {
        "size": 8, 
        "color": "magenta", 
        "symbol": "circle"
      }, 
      "error_x": {"copy_ystyle": True}, 
      "error_y": {
        "color": "magenta", 
        "width": 1, 
        "thickness": 1
      }, 
      "visible": True, 
      "showlegend": True
    }
    
    
    fig.add_trace(trace1)
    fig.add_trace(trace2)
    fig.add_trace(trace3)
    fig.add_trace(trace4)
    fig.add_trace(trace5)
    fig.update_layout(
        # showlegend=False,
        annotations=[
            dict(
                x=(xdict['DensityCurve_x'][-1]-xdict['DensityCurve_x'][0])*0.85+xdict['DensityCurve_x'][0],
                y=np.max(xdict['DensityCurve_y']),
                xref="x",
                yref="y",
                text="Ppk = "+str(round(xdict['Ppk'],2))+ "<br>" + "μ = "+str(round(xdict['Sample_mean'],2))\
                    + "<br>" + "σ = "+str(round(xdict['Sample_mean'],5))\
                    + "<br>"  + str(round(xdict['LowerPercent<LCL']*100,2))+"% < LCL"\
                    + "<br>"  + str(round(xdict['HigherPercent>UCL']*100,2))+"% > UCL",
            )
        ]
    )
    
    # fig.write_html('/home/QMSBI/PpkHist.html',auto_open = False)
    fig.update_xaxes(title_text="测量值")
    
    
    fig.update_yaxes(title_text="概率密度", secondary_y=False)
    fig.update_yaxes(title_text="直方图计数", secondary_y=True)


    return fig.to_html()


def DendrogramPlot(data_array,labels,figName,LinkageFun= "complete",DistanceFun = pdist, linkName = '完全聚类法',distMeasureName = '相关系数距离'):
        
    # eg,    
    # linkName = '完全聚类法'
    # distMeasureName = '相关系数距离'
    # fileName = 'data_preprocessed_original.csv'
    # data = pd.read_csv(fileName)
    # data_array = data.ffill().bfill().iloc[:,14:29].values
    # data_array = data_array.transpose()
    # labels = tuple(data.columns.values[14:29])
    # DistanceFun = pdist
    # LinkageFun  = "complete"
    # figName = 'DendrogramPlot'  
    # DendrogramPlot(data_array,labels,LinkageFun,DistanceFun,figName,linkName,distMeasureName)   
    
    # root = tkinter.Tk()
    width = 1920 #root.winfo_screenwidth()
    height = 1080 #root.winfo_screenheight()
    # Initialize figure by creating upper dendrogram
    fig = ff.create_dendrogram(data_array,
                               orientation='bottom', 
                               labels=labels,
                               colorscale=None,distfun=DistanceFun, 
                               linkagefun=lambda x: sch.linkage(x, LinkageFun),
                               hovertext=None,
                               color_threshold=None,)
    
    # Plot!
    fig.update_layout(title = '树状图<br>'+' '*75+'连接法：'+linkName+'<br>'+' '*75+'距离度量：'+distMeasureName,
                      width=width*0.85, height=height*0.75)
    fig.update_xaxes(title_text='变量')
    fig.update_yaxes(title_text='相似性')
    
    fig.show()

    # fig.write_html('e:/varcluster.html',auto_open = False)

    return fig.to_html()

def XGBPlot(tree2output,figName):
        
    # eg,
    # fileName = 'data_preprocessed_original.csv'
    # featureName = ['ftr12','ftr3','ftr14']
    # labelName = 'ftr13'
    # data = pd.read_csv(fileName)
    # data = data.ffill().bfill()
    # obs_in = data[featureName].iloc[0:15].values
    # outcomes_in = data[labelName].iloc[0:15].values
    # tree2output = CalcXGBArgs(obs_in,outcomes_in) 
    # figName = 'XGBPlot'    
    # XGBPlot(tree2output,figName)


    nr_vertices = len(tree2output)
    
    G = Graph.Tree(nr_vertices, 2) # 2 stands for children number
    lay = G.layout('tree')
    
    position = {k: lay[k] for k in range(nr_vertices)}
    Y = [lay[k][1] for k in range(nr_vertices)]
    M = max(Y)
    
    es = EdgeSeq(G) # sequence of edges
    E = [e.tuple for e in G.es] # list of edges
    
    L = len(position)
    Xn = [position[k][0] for k in range(L)]
    Yn = [2*M-position[k][1] for k in range(L)]
    Xe = []
    Ye = []
    
    labels = []
    yesno = []
    x_judge = []
    y_judge = []
    ix = 0
    labels.append(tree2output.Feature[ix]+' < '+str(tree2output.Split[ix]))
    splitNo = 0
    while(ix<nr_vertices):
        splitNo = splitNo+1
        id_no = tree2output.No[ix]
        yesno.append('No')
        
        id_yes = tree2output.Yes[ix]
        yesno.append('Yes')
        ix_idno = tree2output.Gain.loc[tree2output.ID == id_no].index[0]
        ix_idyes = tree2output.Gain.loc[tree2output.ID == id_yes].index[0]
            
        if tree2output.Feature.loc[tree2output.ID == id_no].values[0]!='Leaf':       
            labels.append(tree2output.Feature.loc[tree2output.ID == id_no].values[0] +' < '+str(tree2output.Split.loc[tree2output.ID == id_no].values[0]))
            labels.append('Leaf = '+str(tree2output.Gain.loc[tree2output.ID == id_yes].values[0]))
            ix = ix_idno
        else:
            labels.append('Leaf = '+str(tree2output.Gain.loc[tree2output.ID == id_no].values[0]))
            labels.append('Leaf = '+str(tree2output.Gain.loc[tree2output.ID == id_yes].values[0]))
            break
    
    for edge in E:
        Xe+=[position[edge[0]][0],position[edge[1]][0], None]
        Ye+=[2*M-position[edge[0]][1],2*M-position[edge[1]][1], None]
    for yesno_ix in [0]:
        x_judge.append((Xn[yesno_ix]+Xn[yesno_ix+1])/2)
        y_judge.append((Yn[yesno_ix]+Yn[yesno_ix+1])/2)
        x_judge.append((Xn[yesno_ix]+Xn[yesno_ix+2])/2)
        y_judge.append((Yn[yesno_ix]+Yn[yesno_ix+2])/2) 
    for yesno_ix in range(1,nr_vertices-3,2):
        x_judge.append((Xn[yesno_ix]+Xn[yesno_ix+2])/2)
        y_judge.append((Yn[yesno_ix]+Yn[yesno_ix+2])/2)
        x_judge.append((Xn[yesno_ix]+Xn[yesno_ix+3])/2)
        y_judge.append((Yn[yesno_ix]+Yn[yesno_ix+3])/2) 
    
    fig = go.Figure()
    fig.add_trace(go.Scatter(x=Xe,
                       y=Ye,
                       mode='lines',
                       line=dict(color='Royalblue', width=3),
                       opacity=0.4,
                       ))
    
    fig.add_trace(go.Scatter(
        x=x_judge,
        y=y_judge,
        mode="text",
        name="Text",
        text=yesno,
        textfont=dict(
        # family="sans serif",
        size=25,
        color=['black' if yn_ix == 'Yes' else 'red' for yn_ix in yesno]),
    ))    
     
      
        
    axis = dict(showline=False, # hide axis line, grid, ticklabels and  title
                zeroline=False,
                showgrid=False,
                showticklabels=False,
                )
    
    fig.update_layout(title= "规则:自左向右",
                  annotations=make_annotations(position, labels,M),
                  font_size=20,
                  # font_color = 'Black',
                  showlegend=False,
                  xaxis=axis,
                  yaxis=axis,
                  margin=dict(l=40, r=40, b=85, t=100),
                  hovermode='closest',
                  plot_bgcolor='rgb(250,250,250)'
                  )
    # fig.show()
    
    # fig.write_html(figName+'.html',auto_open = True)

    return fig.html()



def ProbPlot(ftrDataframe):
    ftr_seq = ftrDataframe.values

    qq = scipy.stats.probplot(ftr_seq, dist='norm')
    axisx = np.array([qq[0][0][0],qq[0][0][-1]])

    pts = go.Scatter(x=qq[0][0],
                    y=qq[0][1], 
                    mode = 'markers',
                    showlegend=False
                    )
    line = go.Scatter(x=axisx,
                    y=qq[1][1] + qq[1][0]*axisx,
                    showlegend=False,
                    mode='lines'
                    )

    res = [pts, line]
    layout = dict(xaxis = dict(zeroline = False,
                            linewidth = 1,
                            mirror = True),
                yaxis = dict(zeroline = False, 
                            linewidth = 1,
                            mirror = True),
                )

    fig = go.Figure(data=res, layout=layout)

    ad_value = scipy.stats.anderson(ftr_seq,dist = 'norm').statistic
    ref_value = scipy.stats.anderson(ftr_seq,dist = 'norm').critical_values[2]
    
    fig.update_layout(title= "正态概率图"+" AD="+str(np.around(ad_value,decimals = 3))+" 参照值 "+ str(ref_value),
                    font_size=20)
    
    # fig.show()
    # fig.write_html('/home/QMSBI/ProbPlot.html',auto_open = False)
    return fig.to_html()


def TimeSeriesPlot(x,y):
    
    data = [go.Scatter(
                x=x,
                y=y)]   
    layout = dict(
        title='Value的时间序列图',
        xaxis={"title":"指数"},
        yaxis={"title":"Value"}
        )
   
    fig = go.Figure(data = data,layout = layout)
    
    # fig.write_html('/home/QMSBI/TimeSeriesPlot.html',auto_open = False)

    return fig.to_html()    




def GroupScatterPlot(x,y):
    
    data = [go.Scatter(
                x=x,
                y=y,
                mode = 'markers')]   
    layout = dict(
        title='最后25子组散点图',
        xaxis={"title":"指数"},
        yaxis={"title":"Value"}
        )
   
    fig = go.Figure(data = data,layout = layout)
    
    # fig.write_html('/home/QMSBI/ScatterGroupPlot.html',auto_open = False)
    # fig.show()
    return fig.to_html()    




# def CorrPlot(dataz,data_label):
        
#     # data = pd.read_csv('corrMat.csv')
#     # dataz = data.iloc[:,1::].values
#     # data_label = data.iloc[:,0].values
#     # figName = 'corrPlot'    
#     # corrPlot(dataz,data_label,figName)
        
#     dataz = list(dataz)
#     dataz.reverse()
#     data_labelx = list(data_label)
#     data_labely = data_labelx[::-1]
#     font_colors = ["black", "orange"]
#     fig = ff.create_annotated_heatmap(
#         z= np.around(dataz,2),
#         x= data_labelx,
#         y= data_labely,
#         text = dataz,
#         colorscale='RdBu',
#         font_colors=font_colors,
#         showscale = True,
#         hoverongaps = False)
#     fig.update_layout(
#         title='相关图')
#     # fig.show()
#     # fig.write_html(figName+'.html',auto_open = True)
#     # fig.write_html('/home/Corr_Plot.html',auto_open = False)

#     return fig.to_html()

