Example #1
0
    def page2_result(content, date, ret, vol, df_comp):
        if type(content) == str:
            return dcc.ConfirmDialog(id='confirm', message=content)

        table_title1 = [html.Thead(html.Tr([html.H4("리밸런싱 전/후 비교")]))]
        table_title2 = [html.Thead(html.Tr([html.H4("자산별 구성 및 운용성과")]))]
        table_title3 = [html.Thead(html.Tr([html.H4("리밸런싱 과거 내역")]))]

        table_header_comp = [
            html.Thead(html.Tr([html.Th(col)
                                for col in list(df_comp.columns)]))
        ]

        print('table_header_comp is : {}'.format(table_header_comp))
        print('in page2_result, df_comp is', df_comp)
        rows = df_comp.values.tolist()
        # print(rows)
        comp_row = list()
        for row in rows:
            temp = [html.Td(record) for record in row]
            comp_row.extend([html.Tr(temp)])

        print('in page2_result, comp_row is', comp_row)

        table_header = [
            html.Thead(
                html.Tr([
                    html.Th("시점"),
                    html.Th("Cash"),
                    html.Th("Equity"),
                    html.Th("Fixed Income"),
                    html.Th("Alternative"),
                    html.Th("Total"),
                    html.Th("누적수익률(%)"),
                    html.Th("변동성(%)")
                ]))
        ]

        # print('content.date: {}'.format(content.date))
        # print('date: {}'.format(date))
        latest_content = content.loc[content.date == date, :]
        latest_content.value = to_numeric(latest_content.value)
        print('content.columns: {}'.format(content.columns))
        print('content.shape: {}'.format(content.shape))
        print('content: {}'.format(content))
        # print('----------------------------')
        # print('latest_content.shape: {}'.format(latest_content.shape))
        # print('latest_content.columns: {}'.format(latest_content.columns))
        # print('latest_content: {}'.format(latest_content))
        # print('latest_content.date: {}, date: {}'.format(latest_content.date, date))
        # print('latest_content[latest_content[asset_class] == Cash][value]: {}'.format(latest_content.loc[latest_content.asset_class == 'Cash', 'value']))
        summary = latest_content.loc[:, ['asset_class', 'value']].groupby(
            'asset_class').sum().reset_index()

        total = summary.value.sum()
        total = '{:,}'.format(int(total))

        latest_content.value = latest_content.value.astype(int).apply(
            lambda x: "{:,}".format(x))
        summary.value = summary.value.astype(int).apply(
            lambda x: "{:,}".format(x))

        row1 = html.Tr([
            html.Td("현재"),
            html.Td(summary.loc[summary.asset_class == 'Cash', 'value']),
            html.Td(summary.loc[summary.asset_class == 'Equity', 'value']),
            html.Td(summary.loc[summary.asset_class == 'Fixed Income',
                                'value']),
            html.Td(summary.loc[summary.asset_class == 'Alternative',
                                'value']),
            html.Td(total),
            html.Td('{:.1f}'.format(float(ret) * 100)),
            html.Td('{:.1f}'.format(float(vol) * 100))
        ])

        # print('----page2_result에서 상세내역 찍기 시작---')
        # result = user.closeData(select, name=user.name, date=user.date, choice=False)
        # print('content 첫줄 보면..')
        # print(content.iloc[:1, :3])

        # 과거 내역(detail) 중 리밸런싱이 발생한 날짜의 레코드만
        result = content.loc[content.original == 'Rebal', :]
        print('content.shape: {}, result.shape: {}'.format(
            content.shape, result.shape))

        # RA자문 탭에서 상세잔고내역의 컬럼명/컬럼순서 변경
        result = result.loc[:, [
            'date', 'name', 'itemname', 'price', 'quantity', 'value', 'wt',
            'original'
        ]]
        result.date = to_datetime(result.date).dt.strftime('%Y-%m-%d')
        result.loc[:,
                   ['price', 'quantity', 'value'
                    ]] = result.loc[:, ['price', 'quantity', 'value']].astype(
                        float).astype(int).applymap(lambda x: "{:,}".format(x))
        result.loc[:, ['wt']] = (result.loc[:, ['wt']].astype(float) *
                                 100).applymap(lambda x: "{:.1f}".format(x))
        result = result.rename(
            columns={
                'date': '날짜',
                'name': '이름',
                'itemname': '종목명',
                'price': '종가',
                'quantity': '보유수량',
                'value': '평가금액',
                'wt': '비중(%)',
                'original': '납입금여부'
            })

        table_header_detail = [
            html.Thead(html.Tr([html.Th(col) for col in list(result.columns)]))
        ]

        rows = result.values.tolist()
        # print(rows)
        table_row = list()
        for row in rows:
            temp = [html.Td(data) for data in row]
            table_row.extend([html.Tr(temp)])

        print('table_header_detail is {}'.format(table_header_detail))
        print('in page2_result, table_row is', table_row)

        return html.Div([
            dbc.Table(table_title1,
                      bordered=False,
                      style={
                          'margin-top': '18px',
                          'margin-bottom': '10px',
                          'text-align': 'left',
                          'paddingLeft': 12
                      }),
            dbc.Table(table_header_comp + [html.Tbody(comp_row)],
                      bordered=True,
                      style={
                          'margin-top': '18px',
                          'margin-bottom': '10px',
                          'text-align': 'left',
                          'paddingLeft': 12
                      }),
            dbc.Table(table_title2,
                      bordered=False,
                      style={
                          'margin-top': '18px',
                          'margin-bottom': '10px',
                          'text-align': 'left',
                          'paddingLeft': 12
                      }),
            dbc.Table(table_header + [html.Tbody([row1])],
                      bordered=True,
                      style={
                          'margin-top': '18px',
                          'margin-bottom': '10px',
                          'text-align': 'left',
                          'paddingLeft': 12
                      }),
            dbc.Table(table_title3,
                      bordered=False,
                      style={
                          'margin-top': '18px',
                          'margin-bottom': '10px',
                          'text-align': 'left',
                          'paddingLeft': 12
                      }),
            dbc.Table(table_header_detail + [html.Tbody(table_row)],
                      bordered=True,
                      style={
                          'margin-top': '18px',
                          'margin-bottom': '10px',
                          'text-align': 'left',
                          'paddingLeft': 12
                      })
        ])
Example #2
0
    html.Div(id='display-selected-values'),

    #State
    html.H1("State (Independent)"),
    html.Div([
        dcc.Input(id="input-1", type="text", value="Montréal"),
        dcc.Input(id="input-2", type="text", value="Canada"),
        html.Div(id="number-output"),
    ]),

    #Numbers
    html.H1("Calculations with multiple outputs"),
    html.Div([
        dcc.Input(id='num-multi', type='number', value=5),
        html.Table([
            html.Tr([html.Td(['x', html.Sup(2)]),
                     html.Td(id='square')]),
            html.Tr([html.Td(['x', html.Sup(3)]),
                     html.Td(id='cube')]),
            html.Tr([html.Td([2, html.Sup('x')]),
                     html.Td(id='twos')]),
            html.Tr([html.Td([3, html.Sup('x')]),
                     html.Td(id='threes')]),
            html.Tr([html.Td(['x', html.Sup('x')]),
                     html.Td(id='x^x')]),
        ]),
    ])
])


@app.callback(Output('cities-radio', 'options'),
                     value='paper',
                     clearable=False,
                     persistence=False,
                     style={'width': '35%'}),
    ]),
    html.Br(),
    html.Br(),
    html.Table(id='rows-content'),
    html.Br(),
    html.Button(id='add-instrument-row', n_clicks=0,
                children='Add instrument'),

    # Hidden table to give an output target to update_instruments' callback
    html.Table([
        html.Tr([
            html.Td(c, style={'display': 'none'})
            for c in instrument_rows(n, display='none')
        ]) for n in range(0, MAX_INSTRUMENTS)
    ]),
])


def dynamic_rows(num_rows):
    table = [
        html.Tr([
            html.Th(c, style={'width': '150px'})
            for c in ('Symbol', 'Size', 'Bar period (s)', 'Order type',
                      'Start/Stop')
        ])
    ] + [
        html.Tr([
Example #4
0
        Numbers can be entered plain (previously they needed to be wrapped in
        `num()`):
        - `> 5000` in the "gdpPercap" column
        - `< 80` in the `lifeExp` column

        ## Operators

        Many operators have two forms: a symbol (`=`) and a word (`eq`) that
        can be used interchangeably.

        """)),
    html.Table([
        html.Tr([
            html.Td([
                html.H4(html.P([html.Code('='), ' ',
                                html.Code('eq')]),
                        style={'margin': '0'}),
                dcc.Markdown('Default operator for `number` columns')
            ]),
            html.Td(
                dcc.Markdown(
                    dedent("""
            Are the two numbers equal? Regardless of type, will first try to
            convert both sides to numbers and compare the numbers. If either
            cannot be converted to a number, looks for an exact match.
            """)))
        ]),
        html.Tr([
            html.Td([
                html.H4(html.P(html.Code('contains')), style={'margin': '0'}),
                dcc.Markdown('Default operator for `text` and `any` columns')
            ]),
Example #5
0
def make_dash_table( df ):
    ''' Return a dash definitio of an HTML table for a Pandas dataframe '''
    table = []
    for index, row in df.iterrows():
        html_row = []
        for i in range(len(row)):
            html_row.append( html.Td([ row[i] ]) )
        table.append( html.Tr( html_row ) )
    return table

modifed_perf_table = make_dash_table( df_perf_summary )

modifed_perf_table.insert( 
    0, html.Tr( [ 
            html.Td([]), 
            html.Td(['Cumulative'], colSpan=4, style=dict(textAlign="center")), 
            html.Td(['Annualised'], colSpan=4, style=dict(textAlign="center")) 
        ], style = dict( background='white', fontWeight=600 )
    ) 
)

df_fund_info = pd.read_csv('https://plot.ly/~jackp/17544.csv')
df_fund_characteristics = pd.read_csv('https://plot.ly/~jackp/17542.csv')
df_fund_facts = pd.read_csv('https://plot.ly/~jackp/17540.csv')
df_bond_allocation = pd.read_csv('https://plot.ly/~jackp/17538.csv')

dash.__version__

app = dash.Dash('GS Bond II Portfolio')
Example #6
0
def predict(cif):
    """Outputs a table with predictions and a div with explanaition if the prediction worked"""

    features = _featurize(cif)

    if not isinstance(features, pd.DataFrame):  # pylint:disable=no-else-return
        # Featurization exception occured, we do not return a results table but rather an error message
        return dbc.Alert(
            'An error occured during the featurization. Ensure that your structure is valid, non-disordered and contains no clashing atoms.',
            dismissable=True,
            color='warning',
            style={
                'margin-left': '3rem',
                'margin-right': '1rem'
            },
        )
    else:
        features = SCALER.transform(features)
        prediction_01 = MODEL_01.predict(features) * 255
        prediction_09 = MODEL_09.predict(features) * 255
        prediction_median = MODEL_MEDIAN.predict(features) * 255

        prediction_median_rounded = [int(c) for c in prediction_median[0]]
        prediction_01_rounded = [int(c) for c in prediction_01[0]]
        prediction_09_rounded = [int(c) for c in prediction_09[0]]
        hex_median = [
            rgb_to_hex((int(c[0]), int(c[1]), int(c[2])))
            for c in prediction_median
        ][0]
        hex_01 = [
            rgb_to_hex((int(c[0]), int(c[1]), int(c[2])))
            for c in prediction_01
        ][0]
        hex_09 = [
            rgb_to_hex((int(c[0]), int(c[1]), int(c[2])))
            for c in prediction_09
        ][0]
        return html.Div([
            dbc.Table(
                [
                    html.Thead([
                        html.Td(),
                        html.Td('Median'),
                        html.Td('10 %'),
                        html.Td('90 %'),
                    ]),
                    html.Tr([
                        html.Td('color'),
                        html.Td(style={'background-color': hex_median}),
                        html.Td(style={'background-color': hex_01}),
                        html.Td(style={'background-color': hex_09}),
                    ]),
                    html.Tr([
                        html.Td('RGB'),
                        html.Td('{} {} {}'.format(
                            prediction_median_rounded[0],
                            prediction_median_rounded[1],
                            prediction_median_rounded[2],
                        )),
                        html.Td('{} {} {}'.format(
                            prediction_01_rounded[0],
                            prediction_01_rounded[1],
                            prediction_01_rounded[2],
                        )),
                        html.Td('{} {} {}'.format(
                            prediction_09_rounded[0],
                            prediction_09_rounded[1],
                            prediction_09_rounded[2],
                        )),
                    ]),
                    html.Tr([
                        html.Td('Hex'),
                        html.Td(hex_median),
                        html.Td(hex_01),
                        html.Td(hex_09),
                    ]),
                    html.Tr([
                        html.Td('Closest name from the xkcd survey'),
                        html.Td(closest_name(prediction_median_rounded)),
                        html.Td(closest_name(prediction_01_rounded)),
                        html.Td(closest_name(prediction_09_rounded)),
                    ]),
                ],
                bordered=True,
                style={
                    'width': '93%',
                    'margin-left': '5%'
                },
            ),
            html.P(
                [
                    'We show three different colors as the predictions a model makes are samples from some distribution.'
                    ' The most important point is the median, which is the center of the distribution and this should be closest to the real color.',
                    ' The 10% and 20% quantiles represent the lower and upper errorbars.',
                    ' If the model is quite sure about the prediction, the colors will be close to the median.',
                ],
                style={
                    'width': '93%',
                    'margin-left': '5%'
                },
            ),
        ])
Example #7
0
def portfolio_delta(start_date, end_date):
    df_start = dp(th, st, start_date)
    portfolio_start = pp(df_start, st, start_date)
    ps_start = portfolio_analysis(portfolio_start, v_param=True)
    df_end = dp(th, st, end_date)
    portfolio_end = pp(df_end, st, end_date)
    ps_end = portfolio_analysis(portfolio_end, v_param=True)

    table_header = [html.Thead(html.Tr([html.Th("Indicator"),
                                        html.Th(f"Value at {start_date}"),
                                        html.Th(f"Value at {end_date}"),
                                        html.Th(f"Delta")]
                                       )
                               )
                    ]
    row1 = html.Tr([html.Td("PNL LIVE"),
                    html.Td(f"{ps_start[3]:.2f}"),
                    html.Td(f"{ps_end[3]:.2f}"),
                    html.Td(f"{ps_end[3] - ps_start[3]:.2f}")])
    row2 = html.Tr([html.Td("PNL CLOSED"),
                    html.Td(f"{ps_start[2]:.2f}"),
                    html.Td(f"{ps_end[2]:.2f}"),
                    html.Td(f"{ps_end[2] - ps_start[2]:.2f}")])
    row3 = html.Tr([html.Td("PNL TOTAL"),
                    html.Td(f"{ps_start[3] + ps_start[2]:.2f}"),
                    html.Td(f"{ps_end[3] + ps_end[2]:.2f}"),
                    html.Td(f"{(ps_end[3] + ps_end[2]) - (ps_start[3] + ps_start[2]):.2f}")])
    row4 = html.Tr([html.Td("TOTAL COST"),
                    html.Td(f"{ps_start[4]:.2f}"),
                    html.Td(f"{ps_end[4]:.2f}"),
                    html.Td(f"{ps_end[4] - ps_start[4]:.2f}")])
    row5 = html.Tr([html.Td("P VAL OPEN"),
                    html.Td(f"{ps_start[0]:.2f}"),
                    html.Td(f"{ps_end[0]:.2f}"),
                    html.Td(f"{ps_end[0] - ps_start[0]:.2f}")])
    row6 = html.Tr([html.Td("P VAL NOW"),
                    html.Td(f"{ps_start[1]:.2f}"),
                    html.Td(f"{ps_end[1]:.2f}"),
                    html.Td(f"{ps_end[1] - ps_start[1]:.2f}")])
    row7 = html.Tr([html.Td("OPEN RETURN"),
                    html.Td(f"{((ps_start[1] / ps_start[0] - 1) * 100):.2f}%"),
                    html.Td(f"{((ps_end[1] / ps_end[0] - 1) * 100):.2f}%"),
                    html.Td(f"{(((ps_end[1] / ps_end[0] - 1) - (ps_start[1] / ps_start[0] - 1)) * 100):.2f}%")])
    row8 = html.Tr([html.Td("TOTAL RETURN"),
                    html.Td(f"{(((ps_start[1] + ps_start[2] + ps_start[4]) / ps_start[0] - 1) * 100):.2f}%"),
                    html.Td(f"{(((ps_end[1] + ps_end[2] + ps_end[4]) / ps_end[0] - 1) * 100):.2f}%"),
                    html.Td(f"""{((((ps_end[1] + ps_end[2] + ps_end[4]) / ps_end[0] - 1) -
                                   ((ps_start[1] + ps_start[2] + ps_start[4]) / ps_start[0] - 1)) * 100):.2f}%""")])
    table_body = [html.Tbody([row1, row2, row3, row4, row5, row6, row7, row8])]
    return table_header + table_body
Example #8
0
             'margin-bottom': '5px'
         }),
 dbc.Col([
     dcc.Upload(id='upload-data',
                children=html.Div(
                    ['Drag and Drop or ',
                     html.A('Select Files')]),
                multiple=False,
                className='upload-file'),
     html.Div(id='alert-container')
 ]),
 dbc.Col([
     html.H5('How to export chat history'),
     html.Table([
         html.Tr([
             html.Td('1. '),
             html.Td(['Select personal or group chat on WhatsApp'])
         ]),
         html.Tr([
             html.Td('2. '),
             html.Td([
                 'Click ',
                 html.I(className='fas fa-ellipsis-v'),
                 ' button > ',
                 html.Strong('More')
             ])
         ]),
         html.Tr([
             html.Td('3. '),
             html.Td([
                 'Select ',
Example #9
0
             style={
                 'text-align': 'left',
                 'width': '20%'
             }),
     html.Th('Example', style={
         'text-align': 'left',
         'width': '20%'
     }),
     html.Th('Description',
             style={
                 'text-align': 'left',
                 'width': '60%'
             })
 ]),
 html.Tr([
     html.Td(rc.Markdown('`YYYY`'), style={'text-align': 'left'}),
     html.Td(rc.Markdown('`2014`'), style={'text-align': 'left'}),
     html.Td('4 or 2 digit year')
 ]),
 html.Tr([
     html.Td(rc.Markdown('`YY`'), style={'text-align': 'left'}),
     html.Td(rc.Markdown('`14`'), style={'text-align': 'left'}),
     html.Td('2 digit year')
 ]),
 html.Tr([
     html.Td(rc.Markdown('`Y`'), style={'text-align': 'left'}),
     html.Td(rc.Markdown('`-25`'), style={'text-align': 'left'}),
     html.Td('Year with any number of digits and sign')
 ]),
 html.Tr([
     html.Td(rc.Markdown('`Q`'), style={'text-align': 'left'}),
        #html.Div(['More information about dataset:',
        #html.A('https://archive.ics.uci.edu/ml/datasets/seeds')
        #]),
        html.H3('Classification with Trained Model'),

        #['Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness','Insulin','BMI', 'DiabetesPedigreeFunction', 'Age']
        # [P,G,BP,S,I,BMI,D,A]

        # Create the table to put input values
        html.Table(
            [
                html.Tbody([
                    # Pregnancies
                    html.Tr([
                        html.Td(html.B('Pregnancies (P):',
                                       style={'font-size': '9pt'}),
                                style={'width': '25%'}),
                        html.Td(dcc.Slider(
                            id='slider-P',
                            min=0,
                            max=17,
                            step=1,
                            value=6,
                        ),
                                style={'width': '55%'}),
                        html.Td(html.P(id='value-slider-P', children=''),
                                style={'width': '10%'}),
                    ]),
                    # Glucose
                    html.Tr([
                        html.Td(html.B('Glucose (G):',
Example #11
0
                    'border-right': '1px solid #dee2e6'
                }),
        html.Th('N/A',
                colSpan=3,
                style={
                    'width': '5rem',
                    'border-right': '1px solid #dee2e6'
                })
    ])
]

table_subheader_hispanic = [
    html.Tr([
        html.Td('',
                style={
                    'border-right': '1px solid #dee2e6',
                    'border-top': '0px',
                    'border-bottom': '0px'
                }),
        html.Td('Hisp.'),
        html.Td('Non-H.'),
        html.Td('N/A', style={'border-right': '1px solid #dee2e6'}),
        html.Td('Hisp.'),
        html.Td('Non-H.'),
        html.Td('N/A', style={'border-right': '1px solid #dee2e6'}),
        html.Td('Hisp.'),
        html.Td('Non-H.'),
        html.Td('N/A', style={'border-right': '1px solid #dee2e6'}),
        html.Td('Hisp.'),
        html.Td('Non-H.'),
        html.Td('N/A', style={'border-right': '1px solid #dee2e6'}),
        html.Td('Hisp.'),
Example #12
0
import dash
from dash.dependencies import Output, Input, State
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc

global parameterTable, gridColor, uoaLightBlue, uoaDarkBlue, textColor, uoaGray, lightGray, textGray, oxfordBlue, skobeloff, middleYellow

#color values
uoaLightBlue = '#009AC7'
uoaDarkBlue = 'rgb(18, 61, 113)'
uoaGray = "#8D9091"
lightGray = "rgb(228, 231, 235)"
oxfordBlue = '#001629'
skobeloff = '#127475'
middleYellow = '#F7E733'
prussianBlue = '#002C52'
richBlack = "#000B14"
darkGray = '#3D3D3D'

textColor = '#C5C6C7'
gridColor = '#192841'

#system parameter table
parameterTableHeader = [html.Thead(html.Tr([html.Th("Parameter"), html.Th("Value")]))]
row1 = html.Tr([html.Td("Max Voltage at H-Bridge"), html.Td("12V")])
row2 = html.Tr([html.Td("Max Current at H-Bridge"), html.Td("2.5A")])
row3 = html.Tr([html.Td("Car Power Rating"), html.Td("30W")])
parameterTableBody = [html.Tbody([row1, row2, row3])]

parameterTable = dbc.Table(parameterTableHeader + parameterTableBody, className = "table table-dark", bordered = True, striped = True, hover = True)
# App Auth
# Set username and password in local install, instead of hello world
auth = dash_auth.BasicAuth(app, [['hello', 'world']])

# App Layout
app.layout = html.Div([
    dcc.Markdown(instruction),
    dcc.Dropdown(id='site', options=[]),
    html.Table([
        html.Tr([
            html.Td(
                html.Div([
                    dcc.Checklist(id='items',
                                  options=[{
                                      'label': 'No options',
                                      'value': 'none'
                                  }],
                                  values=[],
                                  labelStyle={'display': 'block'}),
                    html.Button('<--', id='unzoom'),
                    html.Button('-->', id='zoom')
                ])),
            html.Td(dcc.Graph(id='hlevel_graph'))
        ])
    ]),
    html.Div('errmsghere-todo-', id='msg0'),
    html.Div('app_state', id='app_state'),
    html.Br()
])


def initApp(
Example #14
0
    def page3Layout(result, from_date, allowable):
        chart, table = result
        print('chart: {}, chart.keys(): {}'.format(chart, chart.keys()))
        print('table: {}'.format(table))
        pie = px.pie(chart,
                     names=chart['asset_class'].tolist(),
                     values=chart['wt'].tolist())
        fig = dcc.Graph(id='pie-chart-page3')
        fig.figure = pie

        table_header = [
            html.Thead(
                html.Tr([
                    html.Th("종목명"),
                    html.Th("평가액"),
                    html.Th("비중(%)"),
                    html.Th("자산군")
                ]))
        ]
        informations = table.loc[:, ['itemname', 'value', 'wt', 'asset_class']]

        # informations.loc[:, 'wt'] = informations.loc[:, 'wt']*100
        total_value = informations.value.str.replace(',',
                                                     '').astype(float).sum()
        total_value = '{:,}'.format(round(total_value))
        informations.wt = informations.wt.str.replace(',', '').astype(float)
        total_wt = informations.wt.sum()
        total_wt = '{:.1f}'.format(float(total_wt))
        informations.wt = informations.wt.apply(lambda x: '{:.1f}'.format(x))

        sumOfInfo = [
            html.Td('계'),
            html.Td(total_value),
            html.Td(total_wt),
            html.Td('')
        ]
        informations = informations.values.tolist()

        table_row = list()
        for row in informations:
            temp = [html.Td(data) for data in row]
            table_row.extend([html.Tr(temp)])
        table_row.extend([html.Tr(sumOfInfo)])
        table_result = html.Div(
            dbc.Table(table_header + [html.Tbody(table_row)], bordered=True))

        x_axis = [from_date]
        now = from_date
        while now < allowable:
            now += timedelta(days=30)
            x_axis.append(now)
        y_axis = np.random.randn(2, len(x_axis)).tolist()
        y_axis[0].sort()
        y_axis[1].sort()

        # fig_2 = dcc.Graph(id='line-chart')
        # fig_line = go.Figure()
        # fig_line.add_trace(go.Scatter(
        #     x=x_axis, y=y_axis[0], mode='lines+markers', name='before'))
        # fig_line.add_trace(go.Scatter(
        #     x=x_axis, y=y_axis[1], mode='lines+markers', name='after'))
        # fig_2.figure = fig_line

        return html.Div([fig, table_result])
Example #15
0
def setting_VariantInfo(booleanSU, booleanD, variants_Data, Database):
    if not booleanD:
        layout = []
        start = 0
        while start < len(variants_Data):
            if booleanSU:
                boolSU = False
            else:
                boolSU = True
            enzyme_Info = variants_Data[start]
            if len(enzyme_Info) > 1:
                rows = []
                Variants_found = found_Variants(enzyme_Info)
                if len(Variants_found[0]) > 0:
                    if booleanSU:
                        shared = shared_Variants(Variants_found)
                        info_string = ' shared '
                        header_string = ' Shared '
                    else:
                        shared = unique_Variants(Variants_found)
                        info_string = ' unique '
                        header_string = ' Unique '
                    if len(shared[0]) > 0:
                        variants = []
                        for key in shared[0]:
                            variants.append(key)
                        dataBase_extraction = get_TableInfo(
                            Database, shared[1])
                        parse = 0
                        table_Rows = []
                        while parse < len(variants):
                            ID = variants[parse]
                            info = 0
                            while info < len(dataBase_extraction):
                                if ID == dataBase_extraction[info][1]:
                                    name = dataBase_extraction[info][2]
                                    position = dataBase_extraction[info][3]
                                    effect = dataBase_extraction[info][4]
                                    del dataBase_extraction[info]
                                    break
                                info = info + 1
                            samples_Data = Samples_format(shared[0].get(
                                variants[parse]))
                            Table_row = html.Tr([
                                html.Td(ID),
                                html.Td(name),
                                html.Td(position),
                                html.Td(effect),
                                html.Td(samples_Data)
                            ])
                            rows.append(Table_row)
                            parse = parse + 1
                        table_headers = [
                            html.Thead(
                                html.Tr([
                                    html.Th('Variant ID'),
                                    html.Th('Variant Name'),
                                    html.Th('Position'),
                                    html.Th('Effect'),
                                    html.Th('Samples with variants')
                                ]))
                        ]
                        heading = html.H5(shared[1] + ' - ' + header_string +
                                          ' variants in the selected files')
                        tabel = dbc.Table(table_headers + rows,
                                          bordered=True,
                                          dark=boolSU,
                                          responsive=True)
                        layout.append(heading)
                        layout.append(tabel)
                    else:
                        heading = html.H5(shared[1] + ' - No' + info_string +
                                          'variants in the selected files')
                        layout.append(heading)
                else:
                    heading = html.H5(
                        Variants_found[1] +
                        ' - No Pharmaco Variants found in the selected files')
                    layout.append(heading)

            start = start + 1
        return layout
Example #16
0
def display_output(timestamp, data):
    if timestamp is None:
        raise PreventUpdate

    if data is not None:
        STORED_TOKENS = list(data.get('tokens'))
        if STORED_TOKENS[-1] is not None:
            public_token = STORED_TOKENS[-1]
            response = client.Item.public_token.exchange(public_token)
            access_token = response['access_token']
            start_date = '{:%Y-%m-%d}'.format(datetime.datetime.now() +
                                              datetime.timedelta(-30))
            end_date = '{:%Y-%m-%d}'.format(datetime.datetime.now())
            try:
                transactions_response = client.Transactions.get(
                    access_token=access_token,
                    start_date=start_date,
                    end_date=end_date)
            except plaid.errors.PlaidError as e:
                return html.P(jsonify(format_error(e)))

            transactions = transactions_response.get('transactions')

            names = [transaction['name'] for transaction in transactions]
            categories = [
                transaction['category'] for transaction in transactions
            ]
            locations = [
                transaction['location'] for transaction in transactions
            ]
            statuses = [transaction['pending'] for transaction in transactions]
            amounts = [transaction['amount'] for transaction in transactions]
            # Payment Method: payment_meta
            dates = [transaction['date'] for transaction in transactions]
            trans_id = [
                transaction['transaction_id'] for transaction in transactions
            ]

            TOKEN_MEAT = []
            for a in range(len(STORED_TOKENS)):
                if a is not None:
                    TOKEN_MEAT.append(html.Tr([html.Td(STORED_TOKENS[a]), '']))

            INFO_MEAT = []
            for b in range(len(transactions)):
                INFO_MEAT.append(
                    html.Tr([
                        html.Td(names[b]),
                        html.Td(amounts[b]),
                        html.Td(dates[b])
                    ]))

            return html.Div([
                html.Table([
                    html.Thead([
                        html.Tr([html.Th('Stored Public Tokens')]),
                        html.Tbody([*TOKEN_MEAT]),
                    ]),
                    html.Table([
                        html.Thead([
                            html.Tr([
                                html.Th('Name'),
                                html.Th('Amount'),
                                html.Th('Date')
                            ])
                        ]),
                        html.Tbody([*INFO_MEAT]),
                    ]),
                ]),
            ])
    return "Navigate Plaid Link to Obtain Token"
Example #17
0
def df_to_table(df):
    return html.Table([html.Tr([html.Th(col) for col in df.columns])] + [
        html.Tr([html.Td(df.iloc[i][col]) for col in df.columns])
        for i in range(len(df))
    ])
Example #18
0
     'fontFamily': 'Arial',
     'borderLeft': '1px solid #d6d6d6',
     'borderRight': '1px solid #d6d6d6',
     'borderBottom': '1px solid #d6d6d6',
     'padding': '44px'
 },
 children=[
     dcc.Tab(
         label='Tips Data Set',
         value='tab-1',
         children=[
             html.Div(
                 [
                     html.Table([
                         html.Tr([
                             html.Td([html.P('Table :')],
                                     style={'width': '150px'}),
                             html.Td([
                                 dcc.Dropdown(
                                     id='namaTable',
                                     options=[
                                         {
                                             'label':
                                             'Titanic',
                                             'value': 'titanic'
                                         },
                                         {
                                             'label':
                                             'Titanic Outlier Calculation',
                                             'value': 'titanicoutcalc'
                                         },
                                     ],
Example #19
0
     id='BuildSizeInput',
     min=0,
     max=1000,
     step=10,
     marks={
         250: '250 SF (Studio)',
         500: '500 SF (1 Bed)',
         750: '750 SF (2 Bed)',
     },
     value=500,
 ),
 html.H2("  "),
 html.Div(id='BuildSizeOutput', style={'textAlign': 'center'}),
 html.Table([
     html.Tr(
         [html.Td(['Construction Cost']),
          html.Td(id='ConstructCost')]),
     html.Tr([html.Td(['+ Sales Tax (10.1%) ']),
              html.Td(id='Tax')]),
     html.Tr([
         html.Td(['+ Sewer Capacity Charge ']),
         html.Td(id='SewerCharge')
     ]),
     html.Tr([html.Td(['+  Permit Fee']),
              html.Td(id='PermitFee')]),
     html.Tr(
         [html.Td(['+  Architecture Fee']),
          html.Td(id='DesignCost')]),
     html.Tr([html.Td(['=  Estimated Cost']),
              html.Td(id='TotalCost')]),
     html.Tr([
Example #20
0
def generate_top_tables(n_top, df_cust, customer_id, shaps):
    """
    For a given customer id, retrieves the n_top criteria having most impact on loan decision.
    
    params:
        n_top:
            Number of top criteria to display.
        df_cust:
            A customer description DataFrame.
        customer_id :
            The SK_ID_CURR value of the customer for whom main criteria are searched.
        shaps :
            A numpy array containing aggregated shapley values.
    
    returns:
        Two tables of main criteria :
        - Top decisive criteria for selected customer;
        - Top decisive overall criteria compared to the customer values.
    """
    # Retrieve shap values for selected customer
    df_1 = pd.DataFrame(shaps[0].T, index=df_cust.columns)
    df_1.columns = ['Impact']

    # Retrieve criteria values for selected customer
    df_2 = df_cust.loc[[customer_id]].T
    df_2.columns = ['Values']

    # Merge
    df_table = df_1.merge(df_2, left_index=True, right_index=True)
    df_table['abs'] = df_1['Impact'].apply('abs')
    df_table['Criteria'] = df_table.index
    df_table['Criteria'] = df_table['Criteria'].apply(lambda x: str(x)[:30])

    # Top n table sorted by impact for selected customer
    df_table_c = df_table.sort_values(by='abs', ascending=False)
    df_table_c = df_table_c[['Criteria', 'Values', 'Impact']].head(n_top)
    df_table_c = df_table_c.applymap(lambda x: round(x, 3)
                                     if pd.api.types.is_number(x) else x)

    child_c = [
        html.Div(children=[
            html.H3(children=f'Top {n_top} criteria - Customer'),
            html.Table([
                html.Thead(
                    html.Tr([html.Th(col) for col in df_table_c.columns])),
                html.Tbody([
                    html.Tr([
                        html.Td(children=df_table_c.iloc[i][col],
                                style={'fontSize': 10})
                        for col in df_table_c.columns
                    ]) for i in range(len(df_table_c))
                ])
            ])
        ],
                 className='five columns')
    ]

    # Top table sorted by mean absolute impact for all customers
    file = 'mean_abs_shaps.joblib'
    mean_abs_shaps = joblib.load(source_path + file)

    overall_top = mean_abs_shaps.sort_values(ascending=False).head(n_top)
    df_overall = df_table.loc[overall_top.index]
    df_overall['Mean impact'] = overall_top
    df_overall['Criteria'] = df_overall.index
    df_overall['Criteria'] = df_overall['Criteria'].apply(
        lambda x: str(x)[:30])
    df_overall = df_overall.applymap(lambda x: round(x, 3)
                                     if pd.api.types.is_number(x) else x)
    df_overall = df_overall[['Criteria', 'Mean impact', 'Values', 'Impact']]

    child_o = [
        html.Div(children=[
            html.H3(children=f'Top {n_top} criteria - Overall'),
            html.Table([
                html.Thead(
                    html.Tr([html.Th(col) for col in df_overall.columns])),
                html.Tbody([
                    html.Tr([
                        html.Td(children=df_overall.iloc[i][col],
                                style={'fontSize': 10})
                        for col in df_overall.columns
                    ]) for i in range(len(df_overall))
                ])
            ],
                       style={
                           "textOverflow": 'ellipsis',
                           'overflow': 'hidden',
                           'maxWidth': 0
                       })
        ],
                 className='seven columns')
    ]

    # Append and return children
    children = child_c + child_o
    return children
Example #21
0
def init_app(config):
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

    app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
    server = app.server
    app.config.suppress_callback_exceptions = False

    indata = load(config['files']['input']).flatten()
    outdata = load(config['files']['output']).flatten()

    invars = indata.dtype.names
    outvars = outdata.dtype.names
    dd_opts_in = [{'label': invar, 'value': invar} for invar in invars]
    dd_opts_out = [{'label': outvar, 'value': outvar} for outvar in outvars]

    col_width = 400
    txt_width = 100
    dd_width = 250
    log_width = 50
    graph_height = 620
    txt_check_width = 50
    check_txt_width = txt_width-txt_check_width
    ax_opt_tit_sty = {'width': col_width}
    ax_opt_txt_sty = {'width': txt_width}
    ax_opt_log_sty = {'width': log_width}
    dd_sty = {'width': dd_width}
    axis_options_div_style = {'display': 'flex', 'align-items': 'center', 'height':36, 'padding': 1}
    fit_opt_txt_sty = {'width': txt_width}
    headline_sty = {'text-align': 'center', 'display': 'block', 'width': col_width-25}
    input_div_sty = {'height': 40}
    input_sty = {'width': 125}
    col_sty = {'padding-left':5, 'padding-right':5}
    col_sty_th = {**col_sty, 'text-align':'center'}
    button_sty = {'padding-left':15, 'padding-right':15}

    # try to load model with 'save' and 'fit' config option
    path = config['fit']['save'] or config['fit']['load']
    try:
        sur = Surrogate.load_model(path)
    except (TypeError, FileNotFoundError):
            print('Model could not be loaded')

    app.layout = html.Div(children=[
        html.Table(children=[html.Tr(children=[
            html.Td(id='axis-options', style={'width': '20%'}, children=[
                html.Div(dcc.RadioItems(
                    id='graph-type',
                    options=[{'label': i, 'value': i} for i in ['1D', '2D', '2D contour', '3D']],
                    value='1D',
                    labelStyle={'display': 'inline-block'})),
                html.Div(id='header-opt', children=[html.B("Axis options:", style=headline_sty)], style=ax_opt_tit_sty),
                html.Div(id='invar-1-div', style=axis_options_div_style, children=[
                    html.B('x: ', style=ax_opt_txt_sty),
                    dcc.Dropdown(id='invar', options=dd_opts_in, value=invars[0], style=dd_sty),
                    dcc.Checklist(id='invar-1-log', options=[{'label': 'log', 'value': 'log'}], style=ax_opt_log_sty),
                ]),
                html.Div(id='invar-2-div', style=axis_options_div_style, children=[
                    html.B('y: ', style=ax_opt_txt_sty),
                    dcc.Dropdown(
                        id='invar_2',
                        options=dd_opts_in,
                        value=invars[1] if len(invars) > 1 else invars[0],
                        style=dd_sty, ),
                    dcc.Checklist(
                        id='invar-2-log',
                        options=[{'label': 'log', 'value': 'log'}],
                        style=ax_opt_log_sty, ),
                ]),
                html.Div(id='invar-3-div', style=axis_options_div_style, children=[
                    html.B('z: ', style=ax_opt_txt_sty),
                    dcc.Dropdown(
                        id='invar_3',
                        options=dd_opts_in,
                        value=invars[2] if len(invars) > 2 else invars[0],
                        style=dd_sty,
                    ),
                    dcc.Checklist(
                        id='invar-3-log',
                        options=[{'label': 'log', 'value': 'log'}],
                        style=ax_opt_log_sty,
                    ),
                ]),
                html.Div(id='outvar-div', style=axis_options_div_style, children=[
                    html.B('output: ', style=ax_opt_txt_sty),
                    dcc.Dropdown(
                        id='outvar',
                        options=dd_opts_out,
                        value=outvars[0],
                        style=dd_sty, ),
                    dcc.Checklist(
                        id='outvar-log',
                        options=[{'label': 'log', 'value': 'log'}],
                        style=ax_opt_log_sty, ),
                ]),
                html.Div(id='color-div', style=axis_options_div_style, children=[
                    html.B("color: ", style={'width': txt_check_width}),
                    dcc.Checklist(
                        id='color-use',
                        options=[{'label': '', 'value': 'true'}],
                        style={'width': check_txt_width},
                        value=['true'], ),
                    dcc.Dropdown(
                        id='color-dropdown',
                        options=[{'label': 'OUTPUT', 'value': 'OUTPUT'}] + dd_opts_in + dd_opts_out,
                        value='OUTPUT',
                        style=dd_sty, ),
                ]),
                html.Div(id='error-div', style=axis_options_div_style, children=[
                    html.B("error: ", style={'width': txt_check_width}),
                    dcc.Checklist(
                        id='error-use',
                        options=[{'label': '', 'value': 'true'}],
                        style={'width': check_txt_width}, ),
                    dcc.Dropdown(
                        id='error-dropdown',
                        options=dd_opts_out,
                        value=outvars[-1],
                        style=dd_sty, ),
                ]),
                html.Div(id='fit-opt', children=html.B("Fit options:", style=headline_sty), style=ax_opt_tit_sty),
                html.Div(id='fit-use-div', style=axis_options_div_style, children=[
                    html.B("display fit:", style=fit_opt_txt_sty),
                    dcc.Checklist(
                        id='fit-use',
                        options=[{'label': '', 'value': 'show'}],
                        labelStyle={'display': 'inline-block'}, ),
                ]),
                html.Div(id='fit-multiinput-div', style=axis_options_div_style, children=[
                    html.B("multi-fit:", style=fit_opt_txt_sty),
                    dcc.Dropdown(
                        id='fit-multiinput-dropdown',
                        options=dd_opts_in,
                        value=invars[-1],
                        style=dd_sty, ),
                ]),
                html.Div(id='fit-number-div', style=axis_options_div_style, children=[
                    html.B("#fits:", style=fit_opt_txt_sty),
                    dcc.Input(id='fit-number', type='number', value=1, min=1),
                ]),
                html.Div(id='fit-conf-div', style=axis_options_div_style, children=[
                    html.B("\u03c3-confidence:", style=fit_opt_txt_sty),
                    dcc.Input(id='fit-conf', type='number', value=2, min=0),
                ]),
                html.Div(id='fit-noise-div', style=axis_options_div_style, children=[
                    dcc.Checklist(
                        id='fit-var',
                        options=[{'label': 'add noise covariance', 'value': 'add'}],
                        style={'margin-left': txt_width},
                    )
                ]),
                html.Div(id='fit-color-div', style=axis_options_div_style, children=[
                    html.B("fit-color:", style=fit_opt_txt_sty),
                    dcc.RadioItems(
                        id='fit-color',
                        options=[{'label': 'output', 'value': 'output'},
                                 {'label': 'multi-fit', 'value': 'multi-fit'},
                                 {'label': 'marker-color', 'value': 'marker-color'}],
                        value='output',
                        labelStyle={'display': 'inline-block'}, ),
                ]),
                html.Div(id='fit-opacity-div', style=axis_options_div_style, children=[
                    html.B("fit-opacity:", style=fit_opt_txt_sty),
                    html.Div(style={'width': col_width-txt_width}, children=[
                        dcc.Slider(
                            id='fit-opacity',
                            min=0,
                            max=1,
                            step=0.1,
                            value=0.5,
                            marks={i: {'label': f'{100 * i:.0f}%'} for i in [0, 0.2, 0.4, 0.6, 0.8, 1]},
                        ),
                    ]),
                ]),
                html.Div(id='fit-sampling-div', style=axis_options_div_style, children=[
                    html.B("#points:", style=fit_opt_txt_sty),
                    dcc.Input(id='fit-sampling', type='number', value=50, min=1, debounce=True, style={'appearance': 'textfield'}),
                ]),
            ]),
            html.Td(id='graph', style={'width': '80%'}, children=[html.Div(dcc.Graph(id='graph1'))]),
        ])]),
        html.Div(html.Table(id='filters', children=[html.Tr([
            html.Td(html.Div([
                dcc.Dropdown(
                    id='filter-dropdown',
                    options=dd_opts_in,
                    value=invars[0],
                    style={'width': 200, 'margin-right': 10},
                ),
                html.Button("Add Filter", id='add-filter', n_clicks=0, style=button_sty),
            ], style={'display': 'flex'}), style={**col_sty, 'border-bottom-width':0}),
            html.Td(html.Button("Clear all Filter", id='clear-all-filter', n_clicks=0, style=button_sty), style={**col_sty, 'border-bottom-width':0}),
            html.Td(dcc.Slider(id='scale-slider',
                               min=-0.5, max=0.5,
                               value=0, step=0.01,
                               marks={i: f'{100*i:.0f}%' for i in [-0.5, -0.25, 0, 0.25, 0.5]},
                               ),
                    style={**col_sty, 'width': 500, 'border-bottom-width':0}
            ),
            html.Td(html.Button("Scale Filter span", id='scale', n_clicks=0, style=button_sty), style={**col_sty, 'border-bottom-width':0}),
        ])])),
        html.Div(html.Table(id='param-table', children=[
            html.Thead(id='param-table-head', children=[
                html.Tr(children=[
                    html.Th("Parameter", style={**col_sty, **input_sty}),
                    html.Th("log", style=col_sty_th),
                    html.Th("Slider", style={**col_sty_th, 'width': 300}),
                    html.Th("Range (min/max)", style=col_sty_th),
                    html.Th("center/span", style=col_sty_th),
                    html.Th("filter active", style=col_sty_th),
                    html.Th("#digits", style=col_sty_th),
                    html.Th("reset", style=col_sty_th),
                    html.Th("", style=col_sty_th),
                ]),
            ]),
            html.Tbody(id='param-table-body', children=[
                html.Tr(children=[
                    html.Td(html.Div(id='param-text-div', children=[]), style=col_sty),
                    html.Td(html.Div(id='param-log-div', children=[]), style=col_sty),
                    html.Td(html.Div(id='param-slider-div', children=[]), style=col_sty),
                    html.Td(html.Div(id='param-range-div', children=[]), style=col_sty),
                    html.Td(html.Div(id='param-center-div', children=[]), style=col_sty),
                    html.Td(html.Div(id='param-active-div', children=[]), style=col_sty),
                    html.Td(html.Div(id='param-digits-div', children=[]), style=col_sty),
                    html.Td(html.Div(id='param-reset-div', children=[]), style=col_sty),
                    html.Td(html.Div(id='param-clear-div', children=[]), style=col_sty),
                ]),
            ]),
        ])),
    ])


    @app.callback(
        [Output('param-text-div', 'children'),
         Output('param-log-div', 'children'),
         Output('param-slider-div', 'children'),
         Output('param-range-div', 'children'),
         Output('param-center-div', 'children'),
         Output('param-active-div', 'children'),
         Output('param-digits-div', 'children'),
         Output('param-reset-div', 'children'),
         Output('param-clear-div', 'children'), ],
        [Input('add-filter', 'n_clicks'),
         Input('clear-all-filter', 'n_clicks'),
         Input({'type': 'param-clear', 'index': ALL}, 'n_clicks')],
        [State('filter-dropdown', 'value'),
         State('param-text-div', 'children'),
         State('param-log-div', 'children'),
         State('param-slider-div', 'children'),
         State('param-range-div', 'children'),
         State('param-center-div', 'children'),
         State('param-active-div', 'children'),
         State('param-digits-div', 'children'),
         State('param-reset-div', 'children'),
         State('param-clear-div', 'children')],
    )
    def add_filterrow(n_clicks, clear_all, clear_clicks, filter_dd, text, log, slider, range_div, center_div, active_div, dig_div, reset_div, clear_div):
        ctx = dash.callback_context
        trigger_id = ctx.triggered[0]["prop_id"].split(".")[0]
        if trigger_id == 'clear-all-filter':
            return [], [], [], [], [], [], [], [], []
        elif trigger_id == 'add-filter':
            for i in range(len(text)):
                if text[i]['props']['children'][0] == filter_dd:
                    #return text, log, slider, range_div, center_div, active_div, dig_div, reset_div, clear_div
                    raise PreventUpdate
            ind = invars.index(filter_dd) #index of the variable
            new_text = html.Div(id={'type': 'dyn-text', 'index': ind}, children=[filter_dd], style={**input_div_sty, **input_sty})
            new_log = html.Div(id={'type': 'dyn-log', 'index': ind}, style={**input_div_sty, 'text-align':'center'}, children=[
                dcc.Checklist(id={'type': 'param-log', 'index': ind}, options=[{'label': '', 'value': 'log'}])], )
            new_slider = html.Div(id={'type': 'dyn-slider', 'index': ind}, style=input_div_sty, children=[
                create_slider(filter_dd)], )
            new_range = html.Div(id={'type': 'dyn-range', 'index': ind}, style=input_div_sty, children=[
                dcc.Input(id={'type': 'param-range-min', 'index': ind}, type='number', debounce=True, style={**input_sty, 'appearance': 'textfield'}),
                dcc.Input(id={'type': 'param-range-max', 'index': ind}, type='number', debounce=True, style={**input_sty, 'appearance': 'textfield'}),
            ], )
            new_center = html.Div(id={'type': 'dyn-center', 'index': ind}, style=input_div_sty, children=[
                dcc.Input(id={'type': 'param-center', 'index': ind}, type='number', debounce=True, style={**input_sty, 'appearance': 'textfield'}),
                dcc.Input(id={'type': 'param-span', 'index': ind}, type='number', debounce=True, style={**input_sty, 'appearance': 'textfield'}),
            ], )
            new_active = html.Div(id={'type': 'dyn-active', 'index': ind},
                                  style={**input_div_sty, 'text-align': 'center'},
                                  children=[
                                      dcc.Checklist(id={'type': 'param-active', 'index': ind},
                                                    options=[{'label': '', 'value': 'act'}],
                                                    value=['act'], )
                                  ])
            new_dig = html.Div(id={'type': 'dyn-dig', 'index': ind}, children=[
                dcc.Input(id={'type': 'param-dig', 'index': ind}, type='number', value=5, min=0, style={'width':100})
            ], style={'height':40})
            new_reset = html.Div(id={'type': 'dyn-reset', 'index': ind}, children=[
                html.Button("reset", id={'type': 'param-reset', 'index': ind}, n_clicks=0,
                            style={'padding-left':15, 'padding-right':15})
            ])
            new_clear = html.Div(id={'type': 'dyn-clear', 'index': ind}, children=[
                html.Button("x", id={'type': 'param-clear', 'index': ind}, n_clicks=0,
                            style={'border':'none', 'padding-left':5, 'padding-right':5})
            ])
            text.append(new_text)
            log.append(new_log)
            slider.append(new_slider)
            range_div.append(new_range)
            center_div.append(new_center)
            active_div.append(new_active)
            dig_div.append(new_dig)
            reset_div.append(new_reset)
            clear_div.append(new_clear)
        elif len(trigger_id) >=1 and trigger_id[0] == "{":
            for i in range(len(text)):
                # search table row to delete
                if int(text[i]['props']['id']['index']) == int(trigger_id.split(',')[0].split(':')[1]):
                    text.pop(i)
                    log.pop(i)
                    slider.pop(i)
                    range_div.pop(i)
                    center_div.pop(i)
                    active_div.pop(i)
                    dig_div.pop(i)
                    reset_div.pop(i)
                    clear_div.pop(i)
                    break
        return text, log, slider, range_div, center_div, active_div, dig_div, reset_div, clear_div


    @app.callback(
        [Output({'type': 'param-range-min', 'index': MATCH}, 'step'),
         Output({'type': 'param-range-max', 'index': MATCH}, 'step'),
         Output({'type': 'param-center', 'index': MATCH}, 'step'),
         Output({'type': 'param-span', 'index': MATCH}, 'step'),
         Output({'type': 'param-slider', 'index': MATCH}, 'step'), ],
        Input({'type': 'param-dig', 'index': MATCH}, 'value')
    )
    def update_step(dig):
        """ Function to update an synchronise step-sizes throughout the filter-table.

        Args:
            dig (int): Number of digits to be used. Selected by the user via a 'dcc.Input'-layout-element.

        Returns:
            step: Step-size for the 4 'dcc.Input'-Elements and the slider step.

        """
        step = 10**(-dig)
        return step, step, step, step, step


    @app.callback(
        [Output({'type': 'param-range-min', 'index': MATCH}, 'value'),
         Output({'type': 'param-range-max', 'index': MATCH}, 'value'),
         Output({'type': 'param-slider', 'index': MATCH}, 'value'),
         Output({'type': 'param-slider', 'index': MATCH}, 'min'),
         Output({'type': 'param-slider', 'index': MATCH}, 'max'),
         Output({'type': 'param-center', 'index': MATCH}, 'value'),
         Output({'type': 'param-span', 'index': MATCH}, 'value'),
         Output({'type': 'param-slider', 'index': MATCH}, 'marks'), ],
        [Input('param-text-div', 'children'),
         Input({'type': 'param-log', 'index': MATCH}, 'value'),
         Input({'type': 'param-range-min', 'index': MATCH}, 'value'),
         Input({'type': 'param-range-max', 'index': MATCH}, 'value'),
         Input({'type': 'param-slider', 'index': MATCH}, 'value'),
         Input({'type': 'param-center', 'index': MATCH}, 'value'),
         Input({'type': 'param-span', 'index': MATCH}, 'value'),
         Input('scale', 'n_clicks'),
         Input({'type': 'param-dig', 'index': MATCH}, 'value'),
         Input({'type': 'param-reset', 'index': MATCH}, 'n_clicks'), ],
        [State({'type': 'param-slider', 'index': MATCH}, 'id'),
         State('scale-slider', 'value'),
         State({'type': 'param-slider', 'index': MATCH}, 'marks'), ]
    )
    def update_dyn_slider_range(text_div, log_act, dyn_min, dyn_max, slider_val, center, span, scale, dig, reset, id, scale_slider, marks):
        ctx = dash.callback_context
        try:
            trigger_id = ctx.triggered[0]["prop_id"].split('}')[0].split(',')[1].split(':')[1]
        except IndexError:
            trigger_id = ctx.triggered[0]["prop_id"]

        mark_lim = [float(i) for i in list(marks.keys())]

        data_in = indata[invars[id['index']]]
        data_min_0 = min(data_in[data_in > 0])

        if trigger_id == '"param-log"' and log_act != ['log']:
            dyn_min = 10**dyn_min
            dyn_max = 10**dyn_max
            slider_val = [10**val for val in slider_val]
            mark_lim = [10 ** lim for lim in mark_lim]
            if min(data_in) < 0 and slider_val[0] > 0:
                mark_lim[0] = min(data_in)
            span = (slider_val[1] - slider_val[0])/2
            center = (slider_val[0] + slider_val[1])/2

        if trigger_id != '"param-log"' and log_act == ['log']:
            dyn_min = 10 ** dyn_min
            dyn_max = 10 ** dyn_max
            slider_val = [10 ** val for val in slider_val]
            mark_lim = [10 ** lim for lim in mark_lim]
            if min(data_in) < 0 and slider_val[0] > 0:
                mark_lim[0] = min(data_in)

        if trigger_id == '"param-reset"':
            slider_val = [min(data_in), max(data_in)]

        if ctx.triggered[0]["prop_id"] == "scale.n_clicks":
            # print('scale')
            span = span * (1 + scale_slider)
            if log_act == ['log']:
                trigger_id = '"param-span"'
            else:
                dyn_min = center - span
                dyn_max = center + span
                slider_val = [dyn_min, dyn_max]

        if trigger_id == '"param-center"' or trigger_id == '"param-span"' and (center and span):
            # print('center')
            if log_act == ['log']:
                dyn_min = 10**(center-span)
                dyn_max = 10**(center+span)
            else:
                dyn_min = center - span
                dyn_max = center + span
            slider_val = [dyn_min, dyn_max]
        elif (trigger_id == '"param-range-min"' or trigger_id == '"param-range-max"') and (
                dyn_min is not None and dyn_max is not None):
            # print('range')
            slider_val = [dyn_min, dyn_max]
            span = (slider_val[1] - slider_val[0]) / 2
            center = (slider_val[0] + slider_val[1]) / 2
        elif slider_val:
            # print('slider')
            dyn_min = slider_val[0]
            dyn_max = slider_val[1]
            span = (slider_val[1] - slider_val[0]) / 2
            center = (slider_val[0] + slider_val[1]) / 2

        if log_act == ['log']:
            # log values
            try:
                log_dyn_min = log10(dyn_min)
            except ValueError:
                log_dyn_min = log10(data_min_0)
            log_dyn_max = log10(dyn_max)
            log_slider_val = [log_dyn_min, log_dyn_max]
            try:
                log_mark_lim = [log10(mark) for mark in mark_lim]
            except ValueError:
                log_mark_lim = [log10(data_min_0), log10(mark_lim[1])]
            log_span = (log_slider_val[1] - log_slider_val[0])/2
            log_center = log_slider_val[0] + log_span
            log_marks = {log_mark_lim[0]: str(round(log_mark_lim[0], dig)),
                         log_mark_lim[1]: str(round(log_mark_lim[1], dig))}
            return round(log_dyn_min, dig), round(log_dyn_max, dig), log_slider_val, log_mark_lim[0], log_mark_lim[1],\
                   round(log_center, dig), round(log_span, dig), log_marks
        else:
            marks = {mark_lim[0]: str(round(mark_lim[0], dig)), mark_lim[1]: str(round(mark_lim[1], dig))}
            return round(dyn_min, dig), round(dyn_max, dig), slider_val, mark_lim[0], mark_lim[1], \
                   round(center, dig), round(span, dig), marks


    @app.callback(
        [Output('invar-2-div', 'style'),
         Output('invar-3-div', 'style'),
         Output('color-div', 'style'),
         Output('error-div', 'style'),
         Output('fit-use-div', 'style'),
         Output('fit-multiinput-div', 'style'),
         Output('fit-number-div', 'style'),
         Output('fit-number', 'value'),
         Output('fit-conf-div', 'style'),
         Output('fit-noise-div', 'style'),
         Output('fit-color-div', 'style'),
         Output('fit-opacity-div', 'style'), ],
        [Input('graph-type', 'value'), ],
        [State('fit-number', 'value'), ]
    )
    def div_visibility(graph_type, fits):
        hide = axis_options_div_style.copy()
        hide['visibility'] = 'hidden'
        show = axis_options_div_style.copy()
        show['visibility'] = 'visible'
        if graph_type == '1D':
            return hide, hide, show, show, show, show, show, fits, show, show, hide, show
        if graph_type == '2D':
            if len(invars) <= 2:
                return show, hide, show, show, show, hide, hide, 1, show, show, show, show
            else:
                return show, hide, show, show, show, show, show, fits, show, show, show, show
        if graph_type == '2D contour':
            return show, hide, show, hide, hide, hide, hide, fits, hide, hide, hide, hide
        if graph_type == '3D':
            return show, show, hide, hide, show, hide, show, fits, hide, hide, hide, show
        else:
            return show, show, show, show, show, show, show, fits, show, show, show, show


    @app.callback(
        Output('graph1', 'figure'),
        [Input('invar', 'value'),
         Input('invar_2', 'value'),
         Input('invar_3', 'value'),
         Input('outvar', 'value'),
         Input('invar-1-log', 'value'),
         Input('invar-2-log', 'value'),
         Input('invar-3-log', 'value'),
         Input('outvar-log', 'value'),
         Input({'type': 'param-slider', 'index': ALL}, 'value'),
         Input('graph-type', 'value'),
         Input('color-use', 'value'),
         Input('color-dropdown', 'value'),
         Input('error-use', 'value'),
         Input('error-dropdown', 'value'),
         Input({'type': 'param-active', 'index': ALL}, 'value'),
         Input('fit-use', 'value'),
         Input('fit-multiinput-dropdown', 'value'),
         Input('fit-number', 'value'),
         Input('fit-conf', 'value'),
         Input('fit-var', 'value'),
         Input('fit-color', 'value'),
         Input('fit-opacity', 'value'),
         Input('fit-sampling', 'value'), ],
        [State({'type': 'param-slider', 'index': ALL}, 'id'),
         State({'type': 'param-center', 'index': ALL}, 'value'),
         State({'type': 'param-log', 'index': ALL}, 'value')],
    )
    def update_figure(invar, invar_2, invar_3, outvar, invar1_log, invar2_log, invar3_log, outvar_log, param_slider,
                      graph_type, color_use, color_dd, error_use, error_dd, filter_active, fit_use, fit_dd, fit_num, fit_conf, add_noise_var, fit_color,
                      fit_opacity, fit_sampling, id_type, param_center, param_log):
        for i in range(len(param_slider)):
            if param_log[i] == ['log']:
                param_slider[i] = [10**val for val in param_slider[i]]
                param_center[i] = 10**param_center[i]
        if invar is None:
            return go.Figure()
        sel_y = np.full((len(outdata),), True)
        dds_value = []
        for iteration, values in enumerate(param_slider):
            dds_value.append(invars[id_type[iteration]['index']])
            # filter for minimum
            sel_y_min = np.array(indata[dds_value[iteration]] >= param_slider[iteration][0])
            # filter for maximum
            sel_y_max = np.array(indata[dds_value[iteration]] <= param_slider[iteration][1])
            # print('iter ', iteration, 'filer', filter_active[iteration][0])
            if filter_active != [[]]:
                if filter_active[iteration] == ['act']:
                    sel_y = sel_y_min & sel_y_max & sel_y
        if graph_type == '1D':
            fig = go.Figure(
                data=[go.Scatter(
                    x=indata[invar][sel_y],
                    y=outdata[outvar][sel_y],
                    mode='markers',
                    name='data',
                    error_y=dict(type='data', array=outdata[error_dd][sel_y], visible= error_use == ['true']),
                    # text=[(invar, outvar) for i in range(len(indata[invar][sel_y]))],
                    # hovertemplate=" %{text} <br> %{x} <br> %{y}",
                )],
                layout=go.Layout(xaxis=dict(title=invar, rangeslider=dict(visible=True)), yaxis=dict(title=outvar))
            )
            if fit_use == ['show']:
                mesh_in, mesh_out, mesh_out_std, fit_dd_values = mesh_fit(param_slider, id_type, fit_dd, fit_num,
                                                                          param_center, [invar], [invar1_log],
                                                                          outvar, fit_sampling, add_noise_var)
                for i in range(len(fit_dd_values)):
                    fig.add_trace(go.Scatter(
                        x=mesh_in[i][invars.index(invar)],
                        y=mesh_out[i],
                        mode='lines',
                        name=f'fit: {fit_dd}={fit_dd_values[i]:.1e}',
                        line_color=colormap(indata[fit_dd].min(), indata[fit_dd].max(), fit_dd_values[i]),
                        marker_line=dict(coloraxis="coloraxis2"),
                    ))
                    fig.add_trace(go.Scatter(
                        x=np.hstack((mesh_in[i][invars.index(invar)], mesh_in[i][invars.index(invar)][::-1])),
                        y=np.hstack((mesh_out[i] + fit_conf * mesh_out_std[i], mesh_out[i][::-1] - fit_conf * mesh_out_std[i][::-1])),
                        showlegend=False,
                        fill='toself',
                        line_color=colormap(indata[fit_dd].min(), indata[fit_dd].max(), fit_dd_values[i]),
                        marker_line=dict(coloraxis="coloraxis2"),
                        opacity=fit_opacity,
                    ))
        elif graph_type == '2D':
            fig = go.Figure(
                data=[go.Scatter3d(
                    x=indata[invar][sel_y],
                    y=indata[invar_2][sel_y],
                    z=outdata[outvar][sel_y],
                    mode='markers',
                    name='Data',
                    error_z=dict(type='data', array=outdata[error_dd][sel_y], visible=error_use == ['true'], width= 10)
                )],
                layout=go.Layout(scene=dict(xaxis_title=invar, yaxis_title=invar_2, zaxis_title=outvar))
            )
            if fit_use == ['show'] and invar != invar_2:
                mesh_in, mesh_out, mesh_out_std, fit_dd_values = mesh_fit(param_slider, id_type, fit_dd, fit_num,
                                                                          param_center, [invar, invar_2],
                                                                          [invar1_log, invar2_log], outvar,
                                                                          fit_sampling, add_noise_var)
                for i in range(len(fit_dd_values)):
                    fig.add_trace(go.Surface(
                        x=mesh_in[i][invars.index(invar)].reshape((fit_sampling, fit_sampling)),
                        y=mesh_in[i][invars.index(invar_2)].reshape((fit_sampling, fit_sampling)),
                        z=mesh_out[i].reshape((fit_sampling, fit_sampling)),
                        name=f'fit: {fit_dd}={fit_dd_values[i]:.2f}',
                        surfacecolor=fit_dd_values[i] * np.ones([fit_sampling, fit_sampling])
                            if fit_color == 'multi-fit' else
                            (mesh_in[i][invars.index(color_dd)].reshape((fit_sampling, fit_sampling))
                             if (fit_color == 'marker-color' and color_dd in invars) else
                             mesh_out[i].reshape((fit_sampling, fit_sampling))),
                        opacity=fit_opacity,
                        coloraxis="coloraxis2" if (fit_color == 'multi-fit' or
                            (fit_color == 'output' and (color_dd != outvar and color_dd != 'OUTPUT'))) else "coloraxis",
                        showlegend=True if len(invars) > 2 else False,
                    ))
                    if fit_conf > 0:
                        fig.add_trace(go.Surface(
                            x=mesh_in[i][invars.index(invar)].reshape((fit_sampling, fit_sampling)),
                            y=mesh_in[i][invars.index(invar_2)].reshape((fit_sampling, fit_sampling)),
                            z=mesh_out[i].reshape((fit_sampling, fit_sampling)) + fit_conf * mesh_out_std[i].reshape((fit_sampling, fit_sampling)),
                            showlegend=False,
                            name=f'fit+v: {fit_dd}={fit_dd_values[i]:.2f}',
                            surfacecolor=fit_dd_values[i] * np.ones([fit_sampling, fit_sampling])
                                if fit_color == 'multi-fit' else
                                (mesh_in[i][invars.index(color_dd)].reshape((fit_sampling, fit_sampling))
                                 if (fit_color == 'marker-color' and color_dd in invars) else
                                 mesh_out[i].reshape((fit_sampling, fit_sampling))),
                            opacity=fit_opacity,
                            coloraxis="coloraxis2" if (fit_color == 'multi-fit' or
                                (fit_color == 'output' and (color_dd != outvar and color_dd != 'OUTPUT')))
                                else "coloraxis",
                        ))
                        fig.add_trace(go.Surface(
                            x=mesh_in[i][invars.index(invar)].reshape((fit_sampling, fit_sampling)),
                            y=mesh_in[i][invars.index(invar_2)].reshape((fit_sampling, fit_sampling)),
                            z=mesh_out[i].reshape((fit_sampling, fit_sampling)) - fit_conf * mesh_out_std[i].reshape((fit_sampling, fit_sampling)),
                            showlegend=False,
                            name=f'fit-v: {fit_dd}={fit_dd_values[i]:.2f}',
                            surfacecolor=fit_dd_values[i] * np.ones([fit_sampling, fit_sampling])
                                if fit_color == 'multi-fit' else
                                (mesh_in[i][invars.index(color_dd)].reshape((fit_sampling, fit_sampling))
                                 if (fit_color == 'marker-color' and color_dd in invars) else
                                 mesh_out[i].reshape((fit_sampling, fit_sampling))),
                            opacity=fit_opacity,
                            coloraxis="coloraxis2" if (fit_color == 'multi-fit' or
                                (fit_color == 'output' and (color_dd != outvar and color_dd != 'OUTPUT')))
                                else "coloraxis",
                        ))
                fig.update_layout(coloraxis2=dict(
                    colorbar=dict(title=outvar if fit_color == 'output' else fit_dd),
                    cmin=min(fit_dd_values) if fit_color == 'multi-fit' else None,
                    cmax=max(fit_dd_values) if fit_color == 'multi-fit' else None,
                ))
        elif graph_type == '2D contour':
            mesh_in, mesh_out, mesh_out_std, fit_dd_values = mesh_fit(param_slider, id_type, fit_dd, fit_num,
                                                                      param_center, [invar, invar_2],
                                                                      [invar1_log, invar2_log], outvar,
                                                                      fit_sampling, add_noise_var)
            data_x = mesh_in[0][invars.index(invar)]
            data_y = mesh_in[0][invars.index(invar_2)]
            fig = go.Figure()
            if min(data_x) != max(data_x):
                if min(data_y) != max(data_y):
                    fig.add_trace(go.Scatter(
                        x=indata[invar][sel_y],
                        y=indata[invar_2][sel_y],
                        mode='markers',
                        name='Data',
                    ))
                    fig.add_trace(go.Contour(
                        x=mesh_in[0][invars.index(invar)],
                        y=mesh_in[0][invars.index(invar_2)],
                        z=mesh_out[0],
                        contours_coloring='heatmap',
                        contours_showlabels=True,
                        coloraxis='coloraxis2',
                        name='fit',
                    ))
                    fig.update_xaxes(
                        range=[log10(min(fig.data[1]['x'])), log10(max(fig.data[1]['x']))] if invar1_log == ['log']
                        else [min(fig.data[1]['x']), max(fig.data[1]['x'])])
                    fig.update_yaxes(
                        range=[log10(min(fig.data[1]['y'])), log10(max(fig.data[1]['y']))] if invar2_log == ['log']
                        else [min(fig.data[1]['y']), max(fig.data[1]['y'])])
                    fig.update_layout(xaxis_title=invar,
                                      yaxis_title=invar_2,
                                      coloraxis2=dict(colorbar=dict(title=outvar),
                                                      colorscale='solar',
                                                      cmin=min(fig.data[1]['z']),
                                                      cmax=max(fig.data[1]['z'])))
                else:
                    fig.update_layout(title="y-data is constant, no contour-plot possible")
            else:
                fig.update_layout(title="x-data is constant, no contour-plot possible")
        elif graph_type == '3D':
            fig = go.Figure(
                data=go.Scatter3d(
                    x=indata[invar][sel_y],
                    y=indata[invar_2][sel_y],
                    z=indata[invar_3][sel_y],
                    mode='markers',
                    marker=dict(
                            color=outdata[outvar][sel_y],
                            coloraxis="coloraxis2",
                        ),
                    name='Data',
                ),
                layout=go.Layout(scene=dict(xaxis_title=invar, yaxis_title=invar_2, zaxis_title=invar_3)),
            )
            fig.update_layout(coloraxis2=dict(
                colorbar=dict(title=outvar),
            ))
            if fit_use == ['show'] and len({invar, invar_2, invar_3}) == 3:
                mesh_in, mesh_out, mesh_out_std, fit_dd_values = mesh_fit(param_slider, id_type, fit_dd, fit_num,
                                                                          param_center, [invar, invar_2, invar_3],
                                                                          [invar1_log, invar2_log, invar3_log], outvar,
                                                                          fit_sampling, add_noise_var)
                for i in range(len(fit_dd_values)):
                    fig.add_trace(
                        go.Isosurface(
                            x=mesh_in[i][invars.index(invar)],
                            y=mesh_in[i][invars.index(invar_2)],
                            z=mesh_in[i][invars.index(invar_3)],
                            value=mesh_out[i],
                            surface_count=fit_num,
                            coloraxis="coloraxis2",
                            isomin=mesh_out[i].min() * 1.1,
                            isomax=mesh_out[i].max() * 0.9,
                            caps=dict(x_show=False, y_show=False, z_show=False),
                            opacity=fit_opacity,
                        ),
                    )
        else:
            fig = go.Figure()
        fig.update_layout(legend=dict(xanchor="left", x=0.01))
        # log scale
        log_dict = {'1D': (invar1_log, outvar_log),
                    '2D': (invar1_log, invar2_log, outvar_log),
                    '2D contour': (invar1_log, invar2_log),
                    '3D': (invar1_log, invar2_log, invar3_log),}
        log_list = ['linear' if log is None or len(log) == 0 else log[0] for log in log_dict[graph_type]]
        log_key = ['xaxis', 'yaxis', 'zaxis']
        comb_dict = dict(zip(log_key, [{'type': log} for log in log_list]))
        if len(log_list) < 3 :
            fig.update_layout(**comb_dict)
        else:
            fig.update_scenes(**comb_dict)
        # color
        if color_use == ['true']:
            if fit_use == ['show'] and (graph_type=='2D' and (fit_color=='multi-fit' and color_dd==fit_dd)):
                fig.update_traces(
                    marker=dict(
                        coloraxis="coloraxis2",
                        color=indata[color_dd][sel_y] if color_dd in indata.dtype.names else outdata[color_dd][sel_y],
                    ),
                    selector=dict(mode='markers'),
                )
            elif graph_type == '3D':
                fig.update_traces(
                    marker=dict(
                        coloraxis="coloraxis2",
                        color=outdata[outvar][sel_y],
                    ),
                    selector=dict(mode='markers'),
                )
            elif graph_type=='1D':
                fig.update_traces(
                    marker=dict(
                        coloraxis="coloraxis2",
                        color=outdata[outvar][sel_y] if color_dd == 'OUTPUT' else
                        (indata[color_dd][sel_y] if color_dd in indata.dtype.names else outdata[color_dd][sel_y]),
                    ),
                    selector=dict(mode='markers'),
                )
                if color_dd==fit_dd:
                    fig.update_layout(coloraxis2=dict(colorscale='cividis', colorbar=dict(title=fit_dd)))
                elif color_dd == 'OUTPUT':
                    fig.update_layout(coloraxis2=dict(colorscale='plasma', colorbar=dict(title=outvar)))
                else:
                    fig.update_layout(coloraxis2=dict(colorscale='plasma', colorbar=dict(title=color_dd)))
            elif graph_type =='2D contour':
                fig.update_traces(
                    marker=dict(
                        coloraxis="coloraxis",
                        color=outdata[outvar][sel_y] if color_dd == 'OUTPUT' else
                        (indata[color_dd][sel_y] if color_dd in indata.dtype.names else outdata[color_dd][sel_y]),
                    ),
                    selector=dict(mode='markers'),
                )
                if color_dd == outvar or color_dd == 'OUTPUT':
                    fig.update_traces(marker_coloraxis="coloraxis2", selector=dict(mode='markers'))
                else:
                    fig.update_layout(coloraxis=dict(colorbar=dict(title=color_dd, x=1.1),
                                                     colorscale='ice'))
            else:
                fig.update_traces(
                    marker=dict(
                        coloraxis="coloraxis",
                        color=outdata[outvar][sel_y] if color_dd == 'OUTPUT' else
                        (indata[color_dd][sel_y] if color_dd in indata.dtype.names else outdata[color_dd][sel_y]),
                    ),
                    selector=dict(mode='markers'),
                )
                fig.update_layout(coloraxis=dict(
                    colorbar=dict(title=outvar if color_dd == 'OUTPUT' else color_dd, x=1.1),
                    colorscale='viridis',
                ))
        fig.update_layout(height=graph_height)
        return fig


    def mesh_fit(param_slider, id_type, fit_dd, fit_num, param_center, invar_list, invar_log_list, outvar, num_samples, add_noise_var):
        try:  # collecting min/max of slider for variable of multifit
            fit_dd_min, fit_dd_max = param_slider[[i['index'] for i in id_type].index(invars.index(fit_dd))]
        except ValueError:
            fit_dd_min = min(indata[fit_dd])
            fit_dd_max = max(indata[fit_dd])

        if fit_num == 1: # generate list of value of variable of multifit
            fit_dd_values = np.array([(fit_dd_max + fit_dd_min) / 2])
        else:
            fit_dd_values = np.linspace(fit_dd_min, fit_dd_max, fit_num)

        for iteration, fit_dd_value in enumerate(fit_dd_values): # iteration for each fit
            # set fit parameter for all invars as center of range
            fit_params = [(max(indata[var_invar]) + min(indata[var_invar])) / 2 for var_invar in invars]
            # for all invars with filter change fit_param to center defined by filter
            flt_ind_list = [] # list of filter indices
            for i, center_values in enumerate(param_center):
                flt_ind_list.append(id_type[i]['index'])
                fit_params[flt_ind_list[i]] = center_values
            # change param of fit-variable
            fit_params[invars.index(fit_dd)] = fit_dd_value
            # change param for axis invars
            for i, ax_in in enumerate(invar_list):
                if invars.index(ax_in) in flt_ind_list:
                    ax_min, ax_max = param_slider[flt_ind_list.index(invars.index(ax_in))]
                else:
                    ax_min = min(indata[ax_in])
                    ax_max = max(indata[ax_in])
                if invar_log_list[i] == ['log']:
                    fit_params[invars.index(ax_in)] = np.logspace(log10(ax_min), log10(ax_max), num_samples)
                else:
                    fit_params[invars.index(ax_in)] = np.linspace(ax_min, ax_max, num_samples)
            grid = np.meshgrid(*fit_params) # generate grid
            x_pred = np.vstack([g.flatten() for g in grid]).T  # extract vector for predict
            fit_data, fit_var = sur.predict(x_pred, add_noise_var == ['add']) # generate fit data and variance
            # generated data
            new_mesh_in = np.array([[grid[invars.index(invar)].flatten() for invar in invars]])
            new_mesh_out = np.array([fit_data[:, outvars.index(outvar)]])
            new_mesh_out_std = np.array([np.sqrt(fit_var[:, 0])])
            # stack data together
            if iteration == 0:
                mesh_in = new_mesh_in
                mesh_out = new_mesh_out
                mesh_out_std = new_mesh_out_std
            else:
                mesh_in = np.vstack((mesh_in, new_mesh_in))
                mesh_out = np.vstack((mesh_out, new_mesh_out))
                mesh_out_std = np.vstack((mesh_out_std, new_mesh_out_std))
        return mesh_in, mesh_out, mesh_out_std, fit_dd_values


    def create_slider(dd_value):
        ind = invars.index(dd_value)
        slider_min = indata[dd_value].min()
        slider_max = indata[dd_value].max()
        step_exponent = -3
        new_slider = dcc.RangeSlider(
            id={'type': 'param-slider', 'index': ind},
            step=10 ** step_exponent,
            min=slider_min,
            max=slider_max,
            value=[slider_min, slider_max],
            marks={slider_min: str(round(slider_min, -step_exponent)),
                   slider_max: str(round(slider_max, -step_exponent))},
        )
        return new_slider


    def colormap(cmin, cmax, c):
        if cmin == cmax:
            c_scal = 0.5
        else:
            c_scal = (c-cmin)/(cmax-cmin)
        return color2hex(colormaps.cividis(c_scal))

    return app
Example #22
0
                )),
            dbc.Col([
                html.H2("Graph"),
                dcc.Graph(
                    # figure={"data": [{"x": x1_val, "y": y1_val}]}
                    figure=fig),
            ]),
        ])
    ],
    className="mt-4",
)

table_header = [html.Thead(html.Tr([html.Th("Data"), html.Th("Y")]))]

# row1 = html.Tr([html.Td("Data"), html.Td("Y")])
row2 = html.Tr([html.Td(), html.Td("1")])
row3 = html.Tr([html.Td("2"), html.Td("4")])
row4 = html.Tr([html.Td("3"), html.Td("3")])
row5 = html.Tr([html.Td("4"), html.Td("9")])
row6 = html.Tr([html.Td("5"), html.Td("6")])
row7 = html.Tr([html.Td("6"), html.Td("2")])

table_body = [html.Tbody([row2, row3, row4, row5, row6, row7])]
table = dbc.Table(table_header + table_body, bordered=True)

tab2 = dbc.Container(
    [
        dbc.Row([
            dbc.Col(
                dbc.Container(
                    html.Ul([
Example #23
0
def tablesmb(rows):
    #unicodedata.normalize('NFKD', rows).encode('ascii','ignore')
    table_header = [
        html.Thead(
            html.Tr([
                html.Th('Id'),
                html.Th('stamp'),
                html.Th('devId'),
                html.Th('str1'),
                html.Th('str2'),
                html.Th('str3'),
                html.Th('str4'),
                html.Th('str5'),
                html.Th('str6'),
                html.Th('str7'),
                html.Th('str8'),
                html.Th('str9'),
                html.Th('str10'),
                html.Th('str11'),
                html.Th('str12'),
                html.Th('str13'),
                html.Th('vol1'),
                html.Th('vol2'),
                html.Th('vol3'),
                html.Th('vol4'),
                html.Th('vol5'),
                html.Th('vol6'),
                html.Th('vol7'),
                html.Th('vol8'),
                html.Th('vol9'),
                html.Th('vol10'),
                html.Th('vol11'),
                html.Th('vol12'),
                html.Th('vol13'),
                html.Th('temp')
            ]))
    ]
    table_body = [
        #html.Tbody(html.Tr([html.Td(dev['id']),html.Td(dev['stamp']),html.Td(dev['devId']),html.Td(dev['SPA']),html.Td(dev['TA'])]))for dev in rows]
        html.Tbody(
            html.Tr([
                html.Td(dev[0]),
                html.Td(dev[1]),
                html.Td(dev[2]),
                html.Td(dev[3]),
                html.Td(dev[4]),
                html.Td(dev[5]),
                html.Td(dev[6]),
                html.Td(dev[7]),
                html.Td(dev[8]),
                html.Td(dev[9]),
                html.Td(dev[10]),
                html.Td(dev[11]),
                html.Td(dev[12]),
                html.Td(dev[13]),
                html.Td(dev[14]),
                html.Td(dev[15]),
                html.Td(dev[16]),
                html.Td(dev[17]),
                html.Td(dev[18]),
                html.Td(dev[19]),
                html.Td(dev[20]),
                html.Td(dev[21]),
                html.Td(dev[22]),
                html.Td(dev[23]),
                html.Td(dev[24]),
                html.Td(dev[25]),
                html.Td(dev[26]),
                html.Td(dev[27]),
                html.Td(dev[28]),
                html.Td(dev[29])
            ])) for dev in rows
    ]
    #html.Tbody(html.Tr([html.Td(conv(dev.id)),html.Td(conv(dev.stamp)),html.Td(conv(dev.devId)),html.Td(conv(dev.SPA)),html.Td(conv(dev.TA))]))for dev in rows]
    #html.Tbody(html.Tr([html.Td(dev.id),html.Td(dev.stamp),html.Td(dev.devId),html.Td(dev.SPA),html.Td(dev.TA)]))for dev in rows]
    table = dbc.Table(table_header + table_body,
                      bordered=True,
                      striped=True,
                      hover=True,
                      style={"backgroundColor": "white"})
    return table
Example #24
0
    ],
             style={'textAlign': 'center'}),

    # Div for small multiples of the choropleths
    html.Div([
        html.H3("Univariate Choropleths of Census Statistics"),
        html.Table(
            [
                html.Tbody([
                    html.Tr([
                        html.Td(
                            [
                                html.P(dd_list_stats[0]),
                                dcc.Graph(figure=small_multiple_choropleths[0])
                            ],
                            style={
                                'width': '33.3%',
                                'display': 'inline-block',
                                'margin': '0',
                                'padding': '0',
                                'border': 'none'
                            }),
                        html.Td(
                            [
                                html.P(dd_list_stats[3]),
                                dcc.Graph(figure=small_multiple_choropleths[3])
                            ],
                            style={
                                'width': '33.3%',
                                'display': 'inline-block',
                                'margin': '0',
                                'padding': '0',
import myFunction
from myFunction import titanicDF, titanicOutDF

app = dash.Dash()
app.title = 'Latihan Ujian'

app.layout = html.Div(
    children=[
        dcc.Tabs(id='tabs', value='tab-1', 
            children=[
                dcc.Tab(label='Ujian Titanic Database', value='tab-1', children=[
                    html.Div([
                        html.Table([
                            html.Tr([
                                html.Td([html.P('Table: ')]),
                                html.Td([
                                    dcc.Dropdown(
                                        id='ddl-table-tab1',
                                        options=[
                                            {'label': 'Titanic', 'value': 'titanicDF'},
                                            {'label': 'Titanic Outlier', 'value': 'titanicOutDF'}
                                        ],
                                        value='titanicDF'
                                    ),
                                ]),
                            ])
                        ], style = {'width' : '800px'}),
                        dcc.Graph(
                            id='tbl-titanic-tab1',
                            figure = { 
Example #26
0
def generate_prop_table(component_name, component_names, library_name):
    '''Generate a prop table for each component (both React and Python).

    :param (str) component_name: The name of the component as it is
    defined within the package.
    :param (dict[list]) component_names: A dictionary defining which
    components are React components, and which are Python
    components. The keys in the dictionary are 'react' and 'python',
    and the values for each are lists containing the names of the
    components that belong to each category.
    :param (str) library_name: The name of the library.

    :rtype (object): An html.Table containing data on the props of the component.

    '''

    regex = {
        'python':
        r'^\s*([a-zA-Z_]*)\s*\(([a-zA-Z\/]*);\s*([a-z]*)\):\s*(.*?)\s*(\(Default:\s*(.*)\)|)\s*$'
    }

    component_type = 'react' \
        if component_name in component_names['react'] else 'python'

    tableRows = [
        html.Tr([
            html.Th('Attribute'),
            html.Th('Description'),
            html.Th('Type'),
            html.Th('Default value')
        ])
    ]

    exec("import {}".format(library_name))

    if component_type == 'python':
        sep = '\n-'
        doc = eval("{}.{}".format(library_name, component_name)).__doc__

        props = doc.split(sep)

    elif component_type == 'react':

        path = os.path.join(
            os.path.dirname(os.path.abspath(eval(library_name).__file__)),
            'metadata.json')
        with open(path, 'r') as f:
            metadata = json.load(f)

        # Mol3d for some reason is a plain JS file, not a react file
        cname = '{}.react.js'.format(component_name)
        if component_name == 'Molecule3dViewer':
            cname = 'Molecule3dViewer.js'
        elif component_name == 'Molecule2dViewer':
            cname = 'Molecule2dViewer.react.js'
        docs = metadata['src/lib/components/{}'.format(cname)]

        props = docs['props']

    for prop in props:
        if component_type == 'python':
            desc_sections = prop.split('\n\n')

            partone = desc_sections[0].replace('    ', ' ')

            r = re.match(re.compile(regex[component_type]),
                         partone.replace('\n', ' '))

            if r is None:
                continue

            (prop_name, prop_type, prop_optional, prop_desc, _,
             prop_default) = r.groups()
            if prop_default is None:
                prop_default = ''
            if 'optional' in prop_optional:
                prop_optional = ''

            if len(desc_sections) > 1:
                prop_desc += ' '
                prop_desc += desc_sections[1]

        elif component_type == 'react':
            prop_name = prop
            prop_desc = props[prop]['description']
            prop_type = js_to_py_type(props[prop]['type'])

            if 'defaultValue' in props[prop].keys():
                prop_default = props[prop]['defaultValue']['value']
            else:
                prop_default = ''

        tableRows.append(
            html.Tr([
                html.Td(rc.Markdown(prop_name)),
                html.Td(rc.Markdown(prop_desc)),
                html.Td(rc.Markdown(prop_type)),
                html.Td(rc.Markdown('```python \n' + prop_default + '\n```'))
            ]))

    return html.Div([
        html.H3("{} Properties".format(component_name)),
        html.Table(tableRows)
    ])
Example #27
0
def generate_table(data, max_rows):
    return html.Table([html.Tr([html.Th(col) for col in data.columns])] + [
        html.Tr([html.Td(data.iloc[i][col]) for col in data.columns])
        for i in range(min(len(data), max_rows))
    ])
Example #28
0
def drugs_Affected(enzymes, selected_Drug, Database):
    Database = mysql.connector.connect(
        host='localhost',
        user='******',
        passwd='PharmacoEnzymeVariantInfo@Thulani971108',
        database='enzyme_variantinfo',
    )
    start = 0
    table_color = False
    path = os.getcwd()
    store_items = []
    path = path + '\\Drugs\\' + selected_Drug
    while start < len(enzymes):
        enzymeName = enzymes[start]
        drugs_detail = get_TableInfo(Database, selected_Drug)
        parse = 0
        drugName = selected_Drug.lower()
        tableNames = html.Div(
            html.H6(enzymeName + " metabolized " + selected_Drug))
        store_items.append(tableNames)
        header = [
            html.Thead(
                html.Tr([
                    html.Th("Drug Name"),
                    html.Th("Function"),
                    html.Th("Structure"),
                    html.Th("Metabolite(s)")
                ]))
        ]
        Table_rows = []
        while parse < len(drugs_detail):
            affected = False
            drug_Type = drugs_detail[parse]
            involved_Enzy = drug_Type[2]
            Enzy_list = involved_Enzy.split(',')
            find_Enzy = 0
            while find_Enzy < len(Enzy_list):
                if enzymeName == Enzy_list[find_Enzy].strip():
                    structure_Path = path + '\\' + drug_Type[1]
                    structure_List = [
                        join(structure_Path, fn)
                        for fn in listdir(structure_Path.strip())
                        if isfile(join(structure_Path, fn))
                        and fn.lower().endswith(('.png', '.jpg'))
                    ]
                    metabolite_Path = structure_Path + '\\' + 'Metabolite(s)'
                    metabolite_List = [
                        join(metabolite_Path, fn)
                        for fn in listdir(metabolite_Path.strip())
                        if isfile(join(metabolite_Path, fn))
                        and fn.lower().endswith((
                            '.png', '.jpg')) and fn.startswith(enzymeName)
                    ]
                    affected = True
                    break
                find_Enzy = find_Enzy + 1
            if affected:
                parse2 = 0
                store_metabolite = []
                while parse2 < len(metabolite_List):
                    metabolite = Image.open(metabolite_List[parse2])
                    store_metabolite.append(html.Img(src=metabolite))
                    store_metabolite.append(html.Br())
                    parse2 = parse2 + 1
                structure = Image.open(structure_List[0])
                row = html.Tr([
                    html.Td(drug_Type[1]),
                    html.Td(drug_Type[3]),
                    html.Td(html.Img(src=structure)),
                    html.Td(html.Div(store_metabolite))
                ])
                Table_rows.append(row)
            parse = parse + 1
        if len(Table_rows) > 0:
            table_body = [html.Tbody(Table_rows)]
            store_items.append(
                dbc.Table(header + table_body, bordered=True,
                          dark=table_color))
            if table_color:
                table_color = False
            else:
                table_color = True
        else:
            store_items.append(
                html.Div(
                    'Enzyme does not participate in metabolizing any drug in selected category'
                ))
        start = start + 1
    layout = html.Div(children=store_items)
    return layout
Example #29
0
        id='cadena',
        options=[{'label': i, 'value': i} for i in cadenas],
        value='Zorro Abarrotero'
    )
    html.Div(id='display-table'),

], style={'columnCount': 1})

@app.callback(
        Output(

def generate_table(dataframe, max_rows=15):
    return html.Table(
        # Header
        [html.Tr([html.Th(col) for col in dataframe.columns]) ] +
        # Body
        [html.Tr([
            html.Td(dataframe.iloc[i][col]) for col in dataframe.columns
        ]) for i in range(min(len(dataframe), max_rows))]
    )

app = dash.Dash(__name__, )

app.layout = html.Div(children=[
    html.H4(children='Proyecto Zorro'),
    generate_table(df)
])

if __name__ == '__main__':
    app.run_server(debug=True)
Example #30
0
def generate_table(deployed_data, collectionName):
    print collectionName
    simplified_list = []
    connection = pymongo.MongoClient(
        "mongodb://" + os.environ['aem_user'] + ":" + os.environ['aem_pwd'] +
        "@mongodb:27017/libertyglobal-online-aem?ssl=false")
    db = connection['libertyglobal-online-aem']
    collec = db[collectionName]
    try:
        while True:
            data = deployed_data.next()
            for key, value in data.iteritems():
                if key == 'version':
                    version = int(value)
                    print "version:::" + str(version)
                    records = collec.find({
                        'job': 'PATCH',
                        'version': version
                    }, {
                        'Environment': 1,
                        'status': 1,
                        'date': 1,
                        '_id': 0
                    })
                    patch_count = collec.find(
                        {
                            'job': 'PATCH',
                            'version': version
                        }, {
                            'Environment': 1,
                            'status': 1,
                            'date': 1,
                            '_id': 0
                        }).count()
                    print "counttt:" + str(patch_count)
                elif key == 'Release_Notes':
                    releaseNotes = value

            if patch_count > 0:
                try:
                    while True:
                        patch_data = records.next()
                        print patch_data
                        print "env:" + patch_data['Environment']
                        simplified_list.append([
                            version, releaseNotes, patch_data['Environment'],
                            patch_data['status'], patch_data['date']
                        ])
                except StopIteration:
                    pass
            else:
                simplified_list.append([version, releaseNotes, "", "", ""])

    except StopIteration:
        pass

    return html.Div([
        html.Table(
            className='reaponsive-table',
            # Header
            children=[
                html.Thead(
                    html.Tr([
                        html.Th('Version', style=th_style),
                        html.Th('Release-Notes', style=th_style),
                        html.Th('Deployed-Into', style=th_style),
                        html.Th('Job-Status', style=th_style),
                        html.Th('Date', style=th_style)
                    ])),

                # Body
                html.Tbody([
                    html.Tr([
                        html.Td(eachList[0], style=td_style),
                        html.Td((html.Div([
                            html.Div(eachartifact)
                            for eachartifact in eachList[1]
                        ])),
                                style=td_style),
                        html.Td(eachList[2], style=td_style),
                        html.Td(eachList[3], style=td_style),
                        html.Td(eachList[4], style=td_style)
                    ]) for eachList in simplified_list
                ])
            ],
            style={
                'margin-left': 'auto',
                'margin-right': 'auto',
                'padding-left': '50px',
                'padding-right': '50px',
                'textAlign': 'left',
            })
    ])