Example #1
0
    # Main Plot
    dcc.Graph(id='main-graph')
])

################################################################################
################################### CALLBACK ###################################
################################################################################


# Tells output and input
# If only using one input it still needs to be a list
# Value is what's associated with teh dropdown, and is constantly being changed/updated

@app.callback(
    Output('main-graph', 'figure'),
    [Input('graph-dropdown-1', 'value'),
    Input('graph-dropdown-2', 'value')])
def graph_maker(col1, col2):
    '''
    Returns the figure dict for main plot
    '''
    data = []

    # markers
    for target in range(3):
        trace = go.Scatter(
            x=df[df['target'] == target][col1],
            y=df[df['target'] == target][col2],
            mode='markers',
        )
        data.append(trace)
all_options = {
    'Emotion_final.csv': ['all', 'sadness', 'anger', 'love', 'surprise', 
                          'fear', 'happy'],
    'text_emotion.csv': [u'all', 'empty', 'sadness', 'enthusiasm', 'neutral', 'worry', 'surprise', 'love', 'fun', 'hate', 'happy', 'boredom', 'relief', 'anger']
}




#############################################################################
############################### PAGE HOME ###################################
#############################################################################
@app.callback(
    Output("modal_Home", "is_open"),
    [Input("open-centered", "n_clicks"), Input("close-centered", "n_clicks")],
    [State("modal_Home", "is_open")],
)
def toggle_modal(n1, n2, is_open):
    if n1 or n2:
        return not is_open
    return is_open

@app.callback(
    Output('app-home-display-value', 'children'),
    Input('app-home-dropdown', 'value'))
def display_value(value):
    return 'You have selected "{}"'.format(value)

@app.callback(
    Output('output_container', 'children'),
Example #3
0
        os.remove(f)
    



def subCallback(stream_id,data,state,log,crtl):
    #store data locally in some file
    fileName = 'data'+str(stream_id)+'.csv'
    df = pd.DataFrame([data])
    with open(fileName,'a') as f:
        df.to_csv(f,mode='a',header=not f.tell(),index=False)
    return state


@app.callback(Output('subTime','data'),
            Input('keyValues','modified_timestamp'),
            State('keyValues','data'),State('subTime','data'))
def start_sub(n,streamList,subscribed):

    if streamList is None:
        #too early
        raise PreventUpdate 
    try:
        for stream in streamList:
            sub.subscribe(stream ,callback = subCallback)
        return time.time()
    except Exception as e:
        logger.exception("Ran into error subscribing to streams in index.py")
    return False

@app.callback(Output('streamID','data'),
Example #4
0
app = dash.Dash()
server = app.server

app.config['suppress_callback_exceptions'] = True

app.layout = html.Div([
    html.H1('Dash Tabs component demo'),
    dcc.Tabs(id="tabs-example", value='tab-1-example', children=[
        dcc.Tab(label='Tab One', value='tab-1-example'),
        dcc.Tab(label='Tab Two', value='tab-2-example'),
    ]),
    html.Div(id='tabs-content-example')
])

@app.callback(Output('tabs-content-example', 'children'),
              [Input('tabs-example', 'value')])
def render_content(tab):
    if tab == 'tab-1-example':
        return tab_1.tab_1_layout
    elif tab == 'tab-2-example':
        return tab_2.tab_2_layout

# Tab 1 callback
@app.callback(dash.dependencies.Output('page-1-content', 'children'),
              [dash.dependencies.Input('page-1-dropdown', 'value')])
def page_1_dropdown(value):
    return 'You have selected "{}"'.format(value)

# Tab 2 callback
@app.callback(Output('page-2-content', 'children'),
              [Input('page-2-radios', 'value')])
                    dcc.Graph(id='pie_chart',
                              config={'displayModeBar': 'hover'}),
                ],
                         className="create_container2 six columns"),
            ],
            className="row flex-display"),
    ],
    id="mainContainer",
    style={
        "display": "flex",
        "flex-direction": "column"
    })


@app.callback(Output('pie_chart',
                     'figure'), [Input('select_country', 'value')],
              [Input('date_range', 'start_date')],
              [Input('date_range', 'end_date')])
def update_graph(select_country, start_date, end_date):
    covid1 = covid.groupby(['Date', 'Country/Region'
                            ])[['Confirmed', 'Deaths', 'Recovered',
                                'Active']].sum().reset_index()
    covid2 = covid1[covid1['Country/Region'] == select_country][[
        'Country/Region', 'Date', 'Confirmed'
    ]].reset_index()
    covid2[
        'daily confirmed'] = covid2['Confirmed'] - covid2['Confirmed'].shift(1)
    covid2.fillna(0, inplace=True)
    daily_confirmed = covid2[(covid2['Country/Region'] == select_country)
                             & (covid2['Date'].between(start_date, end_date)
                                )]['daily confirmed'].sum()
Example #6
0
def callbacks(app):  # pylint: disable=redefined-outer-name
    @app.callback(Output('mol3d-data-info', 'children'),
                  [Input('dropdown-demostr', 'value')])
    def show_data(molecule_selected):
        if molecule_selected in data_info.keys():
            mol = data_info[molecule_selected]
            return [
                html.H4(mol['name']), mol['description'],
                html.A('(source)', href=mol['link'])
            ]
        return ''

    @app.callback(Output('dropdown-demostr',
                         'value'), [Input('mol3d-upload-data', 'contents')],
                  [State('dropdown-demostr', 'value')])
    def reset_dropdown(upload_content, dem):
        if upload_content is not None:
            return None
        return dem

    # Callback for updating dropdown options
    @app.callback(Output('mol3d-coloring-key', 'options'),
                  [Input('dropdown-style-color', 'value')])
    def update_color_options(mol_style):
        color_dict_keys = {
            'atom': list(sparser.ATOM_COLOR_DICT.keys()),
            'residue': list(sparser.RESIDUE_COLOR_DICT.keys()),
            'residue_type': list(sparser.RESIDUE_TYPE_COLOR_DICT.keys()),
            'chain': list(sparser.CHAIN_COLOR_DICT.keys())
        }

        options = [{
            'label': k.upper(),
            'value': k
        } for k in color_dict_keys[mol_style]]

        return options

    @app.callback(Output('mol3d-color-storage', 'data'), [
        Input('mol3d-coloring-value', 'value'),
        Input('dropdown-style-color', 'value')
    ],
                  state=[
                      State('mol3d-coloring-key', 'value'),
                      State('mol3d-color-storage', 'data')
                  ])
    def update_color_dict(color_value, color_style, color_key, current):

        if color_style is None:
            return {}

        if color_key is None or color_value is None:
            return current

        # clear the dict if the color style has changed
        if '{}_colors'.format(color_style) not in current.keys():
            current = {'{}_colors'.format(color_style): {}}

        # finally update the dict

        current['{}_colors'.format(
            color_style)][color_key] = color_value['hex']

        return current

    # Callback for molecule visualization based on uploaded PDB file
    @app.callback(
        Output('mol3d-biomolecule-viewer', 'children'),
        [
            Input('mol3d-upload-data', 'contents'),
            Input('dropdown-demostr', 'value'),
            Input('dropdown-styles', 'value'),
            Input('dropdown-style-color', 'value'),
            Input('mol3d-color-storage', 'modified_timestamp')
        ],
        [State('mol3d-color-storage', 'data')],
    )
    def use_upload(contents, demostr, mol_style, color_style, mt,
                   custom_colors):

        if demostr is not None:
            copy2(demostr, './str.pdb')
            fname = './str.pdb'
        elif contents is not None and demostr is None:
            try:
                content_type, content_string = str(contents).split(',')
                decoded_contents = base64.b64decode(content_string).decode(
                    "UTF-8")
                f = tempfile.NamedTemporaryFile(suffix=".pdb",
                                                delete=False,
                                                mode='w+')
                f.write(decoded_contents)
                fname = f.name
                f.close()
            except AttributeError:
                pass
        else:
            return 'demostr and contents are none'

        # Create the model data from the decoded contents
        modata = parser.create_data(fname)

        fmodel = files_data_style(modata)
        with open(fmodel) as fm:
            mdata = json.load(fm)

        # Create the cartoon style from the decoded contents
        datstyle = sparser.create_style(fname, mol_style, color_style,
                                        **custom_colors)

        fstyle = files_data_style(datstyle)
        with open(fstyle) as sf:
            data_style = json.load(sf)

        # Delete all the temporary files that were created
        for x in [fname, fmodel, fstyle]:
            if os.path.isfile(x):
                os.unlink(x)
            else:
                pass

        # Return the new molecule visualization container
        return dash_bio.Molecule3dViewer(
            id='mol-3d',
            selectionType='atom',
            modelData=mdata,
            styles=data_style,
            selectedAtomIds=[],
            backgroundOpacity='0',
            atomLabelsShown=False,
        )

    # Callback to print details of each selected atom of the biomolecule

    @app.callback(
        Output("mol3d-selection-output", "children"),
        [Input("mol-3d", "selectedAtomIds"),
         Input("mol-3d", "modelData")])
    def selout(selected_atom_ids, model_data):
        residue_summary = []
        for atom_id in selected_atom_ids:
            res_info = model_data['atoms'][atom_id]
            residues = {
                "residue": res_info['residue_name'],
                "atom": res_info['name'],
                "chain": res_info['chain'],
                "xyz": res_info['positions']
            }
            residue_summary += [
                html.P('{}: {}'.format(key, str(residues[key])))
                for key in residues
            ]
            residue_summary.append(html.Br())
        if len(residue_summary) == 0:
            residue_summary.append("No atoms have been selected. Click \
            on an atom to select it.")

        return html.Div(residue_summary)
Example #7
0
                    children=dcc.Graph(
                        id="volume-chart", config={"displayModeBar": False},
                    ),
                    className="card",
                ),
            ],
            className="wrapper",
        ),
    ]
)


@app.callback(
    [Output("price-chart", "figure"), Output("volume-chart", "figure")],
    [
        Input("region-filter", "value"),
        Input("type-filter", "value"),
        Input("date-range", "start_date"),
        Input("date-range", "end_date"),
    ],
)
def update_charts(region, avocado_type, start_date, end_date):
    mask = (
        (data.region == region)
        & (data.type == avocado_type)
        & (data.Date >= start_date)
        & (data.Date <= end_date)
    )
    filtered_data = data.loc[mask, :]
    price_chart_figure = {
        "data": [
Example #8
0
def get_backtesting_report_dash_app(backtesting_result: dict, dash_app=None):
    # global app
    if dash_app is not None:
        app = dash_app
    else:
        app = app_
    app.layout = html.Div(
        [
            html.H2('Backtesting Result'),
            dcc.Location(id='url', refresh=False),
            dcc.Link('Index', href='/'),
            html.Br(),
            dcc.Link('General Performance', href='/btPerformance'),
            # dcc.Tab(),
            html.Br(),
            dcc.Link('Monthly Analysis', href='/monthlyAnalysis'),
            html.Br(),
            # todo holding position question
            dcc.Link('Entry and exit Detail', href='/details'),
            html.Br(),
            dcc.Link('Trading history', href='/history'),
            html.Br(),
            # dcc.Tabs(id='tabs', value='tab', children=[
            #     dcc.Tab(label='General Performance', value='tab-1'),
            #     dcc.Tab(label='Monthly Analysis', value='tab-2'),
            #     dcc.Tab(label='Entry and exit Detail', value='tab-3'),
            #     dcc.Tab(label='Trading history', value='tab-4'),
            #     # dcc.Tab(label='Tab two', value='tab-2'),
            # ]),
            html.Div(id='page-content'),
        ],
        style={'margin': '30px'})

    profile = json.dumps(backtesting_result['strategy_profile'], indent=2)

    index_page = html.Div([
        html.Pre(profile),
        # todo 行情profile
        # benchmark
        # each stock
        # each time frame
        # strategy basic information
        # name

        # todo 回测类型
        #
    ]),

    # --------------- index page callback ---------------
    @app.callback(Output('page-content', 'children'),
                  [Input('url', 'pathname')])
    def display_page(pathname):
        if pathname == '/btPerformance':
            return dash_report.get_layout(backtesting_result)
        elif pathname == '/monthlyAnalysis':
            return monthly_analysis.get_layout(backtesting_result)
        elif pathname == '/details':
            return entry_exit_analysis.get_layout(backtesting_result)
        elif pathname == '/history':
            return trading_history.get_layout(backtesting_result)
        else:
            return index_page

    # --------------- general page callback ---------------
    @app.callback(
        [Output('general_markdown', 'children')],
        [Input('risk-free-rate', 'value'),
         Input('annul-factor', 'value')])
    def update_general_performance(risk_free_rate, annulizaed_factor):
        strategy_net_value = backtesting_result['net_value']
        returns = backtesting_result['rate of return']
        risk_free_rate = float(risk_free_rate)
        annulizaed_factor = int(annulizaed_factor)
        general_performance = {
            'Initial capital':
            "{:.2f}".format(strategy_net_value[0]),
            'End capital':
            "{:.2f}".format(strategy_net_value[-1]),
            'Cumulative Return %':
            "{:.2f} %".format(100 * backtesting_result['cumulative_return']),
            'CAGR %':
            "{:.2f} %".format(100 * backtesting_result['cagr']),
            'First traded':
            backtesting_result['first_traded'],
            'Last traded':
            backtesting_result['last_traded'],
            'Num of trade':
            backtesting_result['num_trade'],
            'Win rate %':
            "{:.2f} %".format(100 *
                              backtesting_result['win_rate']),  # type: float
            'Avg win':
            "{:.2f}".format(backtesting_result['avg_win']),
            'Avg loss':
            "{:.2f}".format(backtesting_result['avg_loss']),
            'Payoff ratio':
            "{:.2f}".format(backtesting_result['payoff_ratio']),

            # returns statistics
            'Volatility %':
            "{:.2f} %".format(100 * backtesting_result['volatility']),
            'Skew':
            "{:.2f}".format(backtesting_result['skew']),
            'Kurtosis':
            "{:.2f}".format(backtesting_result['Kurtosis']),
            'Sharpe':
            "{:.2f}".format(
                sharpe_ratio(returns, risk_free_rate, annulizaed_factor)),
            'Sortino':
            "{:.2f}".format(sortino(returns, risk_free_rate,
                                    annulizaed_factor)),
        }
        general_ss = pd.Series(general_performance, name='Performance')
        return general_ss.to_markdown(),

    @app.callback([
        Output('top-k-markdown', 'children'),
        Output('top-max-drawdown', 'figure')
    ], [Input('top-k-drawdown', 'value')])
    def update_top_drawdown(top_k):
        top_k = int(top_k)
        strategy_net_value = backtesting_result['net_value']
        table = backtesting_result['drawdown_detail'].sort_values(
            by='max drawdown')[:min(top_k,
                                    len(backtesting_result['drawdown_detail'])
                                    )]  # type: pd.DataFrame
        table['max drawdown'] = table['max drawdown'].apply(
            lambda x: "{:.2f} %".format(100 * x))

        # table['99% max drawdown'] = table['99% max drawdown'].apply(lambda x: "{:.2f} %".format(100 *x))
        table.reset_index(inplace=True)
        table.drop(columns=['99% max drawdown', 'index'], inplace=True)
        fig = net_value_plot(strategy_net_value)

        red_color = [
            '#CE0000', '#EA0000', '#FF0000', '#FF2D2D', '#FF2D2D', '#FF5151',
            '#FF7575', '#FF9797', '#FFB5B5', '#FFD2D2'
        ]
        shapes = [
            dict(
                type="rect",
                # x-reference is assigned to the x-values
                xref="x",
                # y-reference is assigned to the plot paper [0,1]
                yref="paper",
                x0=row['start'].replace('-', '/'),
                y0=0,
                x1=row['end'].replace('-', '/'),
                y1=1,
                fillcolor=red_color[idx],
                opacity=0.5,
                layer="below",
                line_width=0,
            ) for idx, row in table.iterrows()
        ]
        fig.update_layout(shapes=shapes)
        return table.to_markdown(), fig

    # --------------- monthly page callback ---------------
    @app.callback([
        Output('title', 'children'),
        Output('return-heatmap', 'figure'),
        Output('returns-distribution', 'figure'),
        Output('key_period', 'children')
    ], [Input('dropdown', 'value')])
    def change_selection(value):
        if value == 'D':
            agg_ret = aggregate_returns(backtesting_result['rate of return'],
                                        'day')  # type: pd.Series
            # todo trade statistics
            # trade_group = backtesting_result['trade_list'].groupby('order_time')

            heatmap = aggregate_returns_heatmap(agg_ret, 'day')
            displot = returns_distribution_plot(agg_ret)
            consec_win = agg_ret.groupby((agg_ret > 0).cumsum())
            consec_loss = agg_ret.groupby((agg_ret < 0).cumsum())
            period_performance = {
                'Best Day': agg_ret.index[agg_ret.argmax()].date(),
                'Best Day Return': "{:.2f} %".format(100 * agg_ret.max()),
                'Worst Day': agg_ret.index[agg_ret.argmin()].date(),
                'Worst Day Return': "{:.2f} %".format(100 * agg_ret.min()),
                'Days of Consecutive Win': consec_win.cumcount().max(),
                'Days of Consecutive Losses': consec_loss.cumcount().max(),
                'Avg Daily Return %': "{:.2f} %".format(100 * agg_ret.mean()),
                'Daily Return Vol %': "{:.2f} %".format(100 * agg_ret.std()),
                'Daily Return Skew': "{:.2f} ".format(agg_ret.skew()),
                'Daily Return Kurt': "{:.2f} ".format(agg_ret.kurt()),
            }

            return 'Daily Analysis', heatmap, displot, pd.Series(
                period_performance,
                name='Daily Key Performance').to_markdown()
        elif value == 'W':
            agg_ret = aggregate_returns(backtesting_result['rate of return'],
                                        'week')
            heatmap = aggregate_returns_heatmap(agg_ret, 'week')
            displot = returns_distribution_plot(agg_ret)
            consec_win = agg_ret.groupby((agg_ret > 0).cumsum())
            consec_loss = agg_ret.groupby((agg_ret < 0).cumsum())
            period_performance = {
                'Best Week': agg_ret.index[agg_ret.argmax()].date(),
                'Best Week Return': "{:.2f} %".format(100 * agg_ret.max()),
                'Worst Week': agg_ret.index[agg_ret.argmin()].date(),
                'Worst Week Return': "{:.2f} %".format(100 * agg_ret.min()),
                'Weeks of Consecutive Win': consec_win.cumcount().max(),
                'Weeks of Consecutive Losses': consec_loss.cumcount().max(),
                'Avg Weekly Return %': "{:.2f} %".format(100 * agg_ret.mean()),
                'Weekly Return Vol %': "{:.2f} %".format(100 * agg_ret.std()),
                'Weekly Return Skew': "{:.2f} ".format(agg_ret.skew()),
                'Weekly Return Kurt': "{:.2f} ".format(agg_ret.kurt()),
            }

            return 'Weekly Analysis', heatmap, displot, pd.Series(
                period_performance, name='Week Key Performance').to_markdown()
        elif value == 'M':
            agg_ret = aggregate_returns(backtesting_result['rate of return'],
                                        'month')
            heatmap = aggregate_returns_heatmap(agg_ret, 'month')
            displot = returns_distribution_plot(agg_ret)
            consec_win = agg_ret.groupby((agg_ret > 0).cumsum())
            consec_loss = agg_ret.groupby((agg_ret < 0).cumsum())
            period_performance = {
                'Best Month': agg_ret.index[agg_ret.argmax()].date(),
                'Best Month Return': "{:.2f} %".format(100 * agg_ret.max()),
                'Worst Month': agg_ret.index[agg_ret.argmin()].date(),
                'Worst Month Return': "{:.2f} %".format(100 * agg_ret.min()),
                'Months of Consecutive Win': consec_win.cumcount().max(),
                'Months of Consecutive Losses': consec_loss.cumcount().max(),
                'Avg Monthly Return %':
                "{:.2f} %".format(100 * agg_ret.mean()),
                'Monthly Return Vol %': "{:.2f} %".format(100 * agg_ret.std()),
                'Monthly Return Skew': "{:.2f} ".format(agg_ret.skew()),
                'Monthly Return Kurt': "{:.2f} ".format(agg_ret.kurt()),
            }

            return 'Monthly Analysis', heatmap, displot, pd.Series(
                period_performance,
                name='Monthly Key Performance').to_markdown()
        elif value == 'Q':
            agg_ret = aggregate_returns(backtesting_result['rate of return'],
                                        'quarter')
            heatmap = aggregate_returns_heatmap(agg_ret, 'quarter')
            displot = returns_distribution_plot(agg_ret)
            consec_win = agg_ret.groupby((agg_ret > 0).cumsum())
            consec_loss = agg_ret.groupby((agg_ret < 0).cumsum())
            period_performance = {
                'Best Quarter': agg_ret.index[agg_ret.argmax()].date(),
                'Best Quarter Return': "{:.2f} %".format(100 * agg_ret.max()),
                'Worst Quarter': agg_ret.index[agg_ret.argmin()].date(),
                'Worst Quarter Return': "{:.2f} %".format(100 * agg_ret.min()),
                'Quarters of Consecutive Win': consec_win.cumcount().max(),
                'Quarters of Consecutive Losses': consec_loss.cumcount().max(),
                'Avg Quarterly Return %':
                "{:.2f} %".format(100 * agg_ret.mean()),
                'Quarterly Return Vol %':
                "{:.2f} %".format(100 * agg_ret.std()),
                'Quarterly Return Skew': "{:.2f} ".format(agg_ret.skew()),
                'Quarterly Return Kurt': "{:.2f} ".format(agg_ret.kurt()),
            }

            return 'Quarter Analysis', heatmap, displot, pd.Series(
                period_performance,
                name='Quarterly Key Performance').to_markdown()
        elif value == 'Y':
            agg_ret = aggregate_returns(backtesting_result['rate of return'],
                                        'year')
            heatmap = aggregate_returns_heatmap(agg_ret, 'year')
            displot = returns_distribution_plot(agg_ret)
            consec_win = agg_ret.groupby((agg_ret > 0).cumsum())
            consec_loss = agg_ret.groupby((agg_ret < 0).cumsum())
            period_performance = {
                'Best Year': agg_ret.index[agg_ret.argmax()].date(),
                'Best Year Return': "{:.2f} %".format(100 * agg_ret.max()),
                'Worst Year': agg_ret.index[agg_ret.argmin()].date(),
                'Worst Year Return': "{:.2f} %".format(100 * agg_ret.min()),
                'Years of Consecutive Win': consec_win.cumcount().max(),
                'Years of Consecutive Losses': consec_loss.cumcount().max(),
                'Avg Yearly Return %': "{:.2f} %".format(100 * agg_ret.mean()),
                'Yearly Return Vol %': "{:.2f} %".format(100 * agg_ret.std()),
                'Yearly Return Skew': "{:.2f} ".format(agg_ret.skew()),
                'Yearly Return Kurt': "{:.2f} ".format(agg_ret.kurt()),
            }
            return 'Year Analysis', heatmap, displot, pd.Series(
                period_performance,
                name='Yearly Key Performance').to_markdown()

    # --------------- entry exit page callback ---------------
    @app.callback(Output('timeframe', 'options'),
                  [Input('asset-selection', 'value')])
    def change_display(value):
        return [{
            'label': i,
            'value': i
        } for i in backtesting_result['data'][value].keys()]

    @app.callback([
        Output('entry-exit', 'figure'),
        Output('trade_table', 'data'),
        Output('trade_table', 'style_data_conditional')
    ], [Input('submit', 'n_clicks'),
        Input('trade_table', 'selected_rows')], [
            State('ta-list', 'children'),
            State('my-date-picker-range', 'start_date'),
            State('my-date-picker-range', 'end_date'),
            State('asset-selection', 'value'),
            State('timeframe', 'value'),
            State('ohlc-line', 'value'),
            State('entrust', 'value'),
        ])
    def update_entry_exit(n_clicks, selected_rows, ta_dict, start_date,
                          end_date, symbol, timeframe, line, entrust):
        data = backtesting_result['data'][symbol][
            timeframe]  # type: pd.DataFrame
        data = data[(data.index >= pd.to_datetime(start_date))
                    & (data.index <= pd.to_datetime(end_date))]
        trade = backtesting_result['trade_list']
        trade = trade[(trade['order_time'] >= pd.to_datetime(start_date))
                      & (trade['order_time'] <= pd.to_datetime(end_date))]
        ohlc_graph = True
        # print(entrust)
        if len(selected_rows) > 0:
            trade_graph = trade.iloc[selected_rows]
            selected_cond = [{
                'if': {
                    'row_index': i
                },
                'background_color': '#D2F3FF'
            } for i in selected_rows]

        else:
            trade_graph = trade
            selected_cond = []

        if line == 'line':
            ohlc_graph = False
        e = False
        if entrust is None or len(entrust) == 0:
            e = False
        else:
            e = True

        ta = json.loads(ta_dict)
        return entry_and_exit_plot(data, trade_graph, symbol, ohlc_graph, entrust=e, ta_dict=ta), \
               trade.to_dict('records'), selected_cond

    @app.callback(Output('indicator-name', 'options'),
                  [Input('indicator-category', 'value')])
    def update_ta(category):
        l = []
        if category == 'customization':
            l = customization.__func__
        elif category == 'momentum':
            l = momentum.__func__
        elif category == 'volatility':
            l = volatility.__func__
        elif category == 'overlap':
            l = overlap.__func__
        elif category == 'volume':
            l = volume.__func__
        elif category == 'pattern':
            l = pattern.__func__

        return [{'label': i, 'value': i} for i in l]

    @app.callback(Output('parameter', 'children'),
                  [Input('indicator-name', 'value')])
    def update_ta_parameter(ta_name):
        if ta_name is None:
            return None
        func = eval(str(ta_name))
        para_dict = inspect.signature(func).parameters
        children = []
        for k, v in para_dict.items():
            if k == 'inputs':
                continue
            else:
                # todo can it possible to make it a line?
                children.append(html.H6(k, style={'displace': 'inline-block'}))
                if isinstance(v.default, MA_Type):
                    value = v.default.name
                    children.append(
                        dcc.Dropdown(
                            id=k,
                            options=[{
                                'label': label,
                                'value': label
                            } for label, value_ in
                                     v.default._member_map_.items()],
                            value=value,
                        ))
                else:
                    value = v.default
                    children.append(dcc.Input(id=k, value=value,
                                              debounce=True))
        return children

    @app.callback(
        [Output('ta-list', 'children'),
         Output('remove-name', 'options')], [
             Input(
                 'add-indicator',
                 'n_clicks',
             ),
             Input('remove-indicator', 'n_clicks')
         ], [
             State('indicator-name', 'value'),
             State('parameter', 'children'),
             State('overlap', 'value'),
             State('remove-name', 'value'),
             State('ta-list', 'children')
         ])
    def update_ta_list(add_clicks, remove_clicks, indicator, parameters,
                       overlap, remove, ta_list):
        if ta_list is None:
            ta_dict = {}
        else:
            ta_dict = json.loads(ta_list)
        if indicator is not None:
            indicator_str = ''
            indicator_str += indicator
            indicator_str += '(inputs, '
            for p in parameters:
                if p['type'] == 'Input':
                    if p['props']['value'] == '' or p['props']['value'] is None:
                        continue
                    indicator_str += p['props']['id']

                    try:
                        value = str(int(p['props']['value']))
                    except ValueError:
                        try:
                            value = str(float(p['props']['value']))
                        except ValueError:
                            value = "'" + p['props']['value'] + "'"
                    indicator_str += "=" + value + ','
                elif p['type'] == 'Dropdown':
                    indicator_str += p['props']['id'] + '=MA_Type.' + p[
                        'props']['value'] + ','
            indicator_str += ')'
            ta_dict[indicator_str] = True if 'overlap' in overlap else False
            if remove is not None:
                try:
                    del ta_dict[remove]
                except:
                    remove = None
            options = [{'label': i, 'value': i} for i in ta_dict.keys()]
            return json.dumps(ta_dict), options
        else:
            if remove is not None:
                try:
                    del ta_dict[remove]
                except:
                    remove = None
            options = [{'label': i, 'value': i} for i in ta_dict.keys()]
            return json.dumps(ta_dict), options

    # --------------- trade list page callback ---------------

    @app.callback(Output('table', 'data'), [
        Input('date-picker-range', 'start_date'),
        Input('date-picker-range', 'end_date')
    ])
    def update_output(date_from, date_to):
        if date_to is None or date_from is None:
            return
        df = backtesting_result['trade_list']
        df_ = df[(df['order_time'] >= pd.to_datetime(date_from))
                 & (df['order_time'] <= pd.to_datetime(date_to))]
        return df_.to_dict('records')

    return app
Example #9
0
        ]), width=4     )
    )
    columns.append(     dbc.Col(    dbc.FormGroup([
        dbc.Label('Learning rate'),
        html.Button(id='add-lr', type='submit', children='add learning rate'),
        html.Div( id='learning-rates' )
        ]), width=4     )
    )
    return dbc.Row( columns )

"""
    Adds one text input box for the learning rate parameter
"""
@app.callback(
    Output('learning-rates', 'children'),
    [Input('add-lr', 'n_clicks')]
)
def add_learning_rates(clicks):
    if clicks is None:
        return [dcc.Input(id={'type':'lr', 'index':0}, type='number', min=0, max=1)]
    inputs = []
    for i in range (clicks):
        inputs.append(dcc.Input(id={'type':'lr', 'index':i}, type='number', min=0, max=1))
    return inputs


"""
    filters out trace options
    trace files available for generating graphs are determined
    by the chosen dataset ('dataset' checklist component in 'build' config menu tab)
"""
Example #10
0
    ]),
    dcc.Graph(id='indicator-graphic'),
    dcc.Slider(id='year--slider',
               min=df['Year'].min(),
               max=df['Year'].max(),
               value=df['Year'].max(),
               marks={str(year): str(year)
                      for year in df['Year'].unique()},
               step=None)
])

print({str(year): str(year) for year in df['Year'].unique()})


@app.callback(Output('indicator-graphic', 'figure'), [
    Input('xaxis-column', 'value'),
    Input('yaxis-column', 'value'),
    Input('xaxis-type', 'value'),
    Input('yaxis-type', 'value'),
    Input('year--slider', 'value')
])
def update_graph(xaxis_column_name, yaxis_column_name, xaxis_type, yaxis_type,
                 year_value):
    dff = df[df['Year'] == year_value]

    return {
        'data': [
            dict(x=dff[dff['Indicator Name'] == xaxis_column_name]['Value'],
                 y=dff[dff['Indicator Name'] == yaxis_column_name]['Value'],
                 text=dff[dff['Indicator Name'] == yaxis_column_name]
                 ['Country Name'],
Example #11
0
])

# figure loading
figdict = {'tc':'tccrop.jpg','pca':'pccrop.jpg','veg':'vfccrop.jpg','heat':'hfccrop.jpg'}
figpath = 'assets/images/'
titledict = {
    'tc':'True Color',
    'pca':'Spectral Principal Components',
    'veg':'Near Infrared (Vegetation=Red)',
    'heat':'Shortwave Infrared'
    }

@app.callback(
    [Output('leftgraph', 'figure'),
     Output('lefttitle', 'children')],
    [Input('leftbutton', 'value')]
    )
def update_left_figure(button):
    array = io.imread(figpath+figdict[button])
    fig = px.imshow(array)
    fig.update_layout(width=780, height=900, margin={'l':5,'r':5,'b':5,'t':5})
    return fig, titledict[button]

@app.callback(
    [Output('rightgraph', 'figure'),
     Output('righttitle', 'children')],
    [Input('rightbutton', 'value')]
    )
def update_right_figure(button):
    array = io.imread(figpath+figdict[button])
    fig = px.imshow(array)
                        ])
                    ],
                    width={
                        "size": 6,
                        "offset": 3
                    },
                ),
            ]),
        ],
        fluid=True,
    )


@APP.callback(
    Output("memory_custom_dimensions", "data"),
    Input("sample_definition_custom_dimensions", "value"),
)
def _get_memory_custom_dimensions(sample_definition):
    return load_feather(
        f"correlation_between_accelerated_aging_dimensions/custom_dimensions_{sample_definition}.feather"
    ).to_dict()


@APP.callback(
    Output("memory_scores_custom_dimensions", "data"),
    Input("sample_definition_custom_dimensions", "value"),
)
def _modify_store_custom_dimensions(sample_definition):
    score_sample_definition = sample_definition
    if sample_definition == "all_samples_when_possible_otherwise_average":
        score_sample_definition = "all_samples_per_participant"
Example #13
0
     html.Div(id='page-content')])

options = html.Div([
    html.H3('Dashboard Options'),
    html.Div(id='operation-display-value'),
    dcc.Link('Go to Operation', href='/publisher-dashboard/operation'),
    html.Div(id='performance-display-value'),
    dcc.Link('Go to Performance', href='/publisher-dashboard/performance'),
    html.Div(id='orbiting-display-value'),
    dcc.Link('Go to Orbiting', href='/publisher-dashboard/orbiting'),
    html.Div(id='positioning-display-value'),
    dcc.Link('Go to Positioning', href='/publisher-dashboard/positioning'),
])


@app.callback(Output('page-content', 'children'), [Input('url', 'pathname')])
def display_page(pathname):
    if pathname == '/publisher-dashboard/operation':
        return operation.layout
    elif pathname == '/publisher-dashboard/performance':
        return performance.layout
    elif pathname == '/publisher-dashboard/orbiting':
        return orbiting.layout
    elif pathname == '/publisher-dashboard/positioning':
        return positioning.layout
    else:
        return options


if __name__ == '__main__':
    app.run_server(debug=DEBUG_MODE, host=SERVER_HOST, port=SERVER_PORT)
Example #14
0
    ])

    return layout


##################################################################
#                       CALLBACKS
##################################################################


#Toggle winners map if selected target
@app.callback(
    Output('alert_target_not_selected_gsom', 'is_open'),
    Output('collapse_winnersmap_gsom', 'is_open'),
    Output('dropdown_target_selection_gsom', 'value'),
    Input('info_table_gsom', 'children'),  #udpate on load
    Input('dropdown_target_selection_gsom', 'value'),
)
def toggle_winners_gsom(info_table, target_value):

    ctx = dash.callback_context
    trigger_id = ctx.triggered[0]["prop_id"].split(".")[0]

    preselected_target = session_data.get_target_name()

    if (trigger_id == 'info_table_gsom'):  #init call
        if (preselected_target is None):
            return False, True, None

        else:
            return False, True, preselected_target
Example #15
0
    }, content_style={
        'fontFamily': 'Arial',
        'borderBottom': '1px solid #d6d6d6',
        'borderLeft': '1px solid #d6d6d6',
        'borderRight': '1px solid #d6d6d6',
        'padding': '44px'
    })
], style={
    'maxWidth': '1200px',
    'margin': '0 auto'
})


@app.callback(
    Output(component_id='categoricalPlot', component_property='figure'),
    [Input(component_id='jenisPlot', component_property='value'),
    Input(component_id='jenisDiamond', component_property='value')]
)
def update_graph_categorical(jenisPlot,jenisDiamond):
    return {
        'data': getPlot(jenisPlot,jenisDiamond),
        'layout': go.Layout(
                    xaxis={'title':jenisDiamond},
                    yaxis={'title':'price'},
                    margin={'l':40,'b':40,'t':10,'r':10},
                    # legend={'x':0, 'y':1},
                    hovermode='closest',boxmode='group',violinmode='group'
                )
    }
 
@app.callback(
Example #16
0
                chart_df = chart_df.groupby(
                    "iyear")[chart_dp_value].value_counts().reset_index(
                        name="count")

        if chart_df.shape[0]:
            pass
        else:
            chart_df = pd.DataFrame(columns=['iyear', 'count', chart_dp_value])

            chart_df.loc[0] = [0, 0, "No data"]
        fig = px.area(chart_df, x="iyear", y="count", color=chart_dp_value)

    return dcc.Graph(figure=fig)


@app.callback(Output("date", "options"), [Input("month", "value")])
def update_date(month):
    option = []
    if month:
        option = [{"label": m, "value": m} for m in date_list]
    return option


@app.callback([
    Output("region-dropdown", "value"),
    Output("region-dropdown", "disabled"),
    Output("country-dropdown", "value"),
    Output("country-dropdown", "disabled")
], [Input("subtabs", "value")])
def update_r(tab):
    region = None
Example #17
0
                      className='six columns u-full-width',
                      style={"border":'1px solid White'}),
             html.Div([
                 html.Img(id='wordcloud', className='u-full-width')],
                      className='six columns')],
                  className="row")],
              className="container u-full-width")
     # html.Div(
     #     [html.Div(id='time-log')],
     #     className="container")
     ],
    className='container')

@app.callback(
    Output('search-grid', 'children'),
    [Input('search-method','value')])
def update_search_method(search_method):
    """
    Update search method depending on user choices
    """
    if search_method == 'choice':
        return DROPDOWN_ITEM
    return INPUT_ITEM

@app.callback(
    Output('job-id', 'children'),
    [Input('button', 'n_clicks')],
    state=[State('keyword', 'value'),
           State('sourcechoice', 'values')])
def submit_query(n_click, keyword, sourcechoice):
    """
Example #18
0
                    ),
                ],
                className="row flex-display",
            ),
            html.Div(   
                    [dcc.Graph(id="prarameter_table")],
                    id="tables-container",
                    className="twelve columns",
            ),
            html.Div(id='intermediate-value', style={'display': 'none'})

            ])

@app.callback(
        [Output("opening_text", "children"),Output("closing_text", "children"),Output("pnl_text", "children"),Output("pnl_percent_text", "children")],
        [Input("strategy_name","value"), Input('intermediate-value', 'children')],
        )
def update_text(strategy_name,json_strategy_report):
            
    try:
        df_strategy_report = pd.read_json(json_strategy_report, orient='split')
        open_balance = 10000
        for strat_index in df_strategy_report.index:
            if(df_strategy_report['stratgy_name'][strat_index] == strategy_name):
                break
        close_balance = df_strategy_report['value_at_end'][strat_index]
        pnl = df_strategy_report['profit_loss'][strat_index]
        pnl_percentage = df_strategy_report['roe'][strat_index]
        return "₹" + str(open_balance), "₹" + str(close_balance), "₹" + str(pnl), str(pnl_percentage) + "%"
    except:
Example #19
0
import dash_html_components as html
from dash.dependencies import Input, Output

import plotly.graph_objs as go
import squarify
import pandas as pd

app = dash.Dash()
server = app.server
app.config.supress_callback_exceptions = True
rfm = pd.read_csv('rfm.csv')
rfm['Counts'] = rfm.groupby(['Segment'])['CustomerID'].transform('count')
app.layout = html.Div([dcc.Graph(id='treemap')])


@app.callback(Output('treemap', 'figure'), [Input('treemap', 'value')])
def treemap(value):

    #values = [500, 433, 78, 25, 25, 7]
    values = rfm['Segment'].value_counts().values
    index = rfm['Segment'].value_counts().index
    parents_segment = rfm['Segment'].head(20).values
    childs = rfm['CustomerID'].head(20).values
    segment_counts = rfm['Counts'].head(20).values

    # Choose colors from http://colorbrewer2.org/ under "Export"

    trace = go.Sunburst(ids=childs,
                        labels=parents_segment,
                        values=segment_counts,
                        outsidetextfont={
Example #20
0
                          'scrollZoom': True,
                          'showTips': True
                      })
        ])
    ],
                  fluid=True)
],
                           fluid=True)


@app.callback([
    Output('basic-interactions', 'figure'),
    Output('infected', 'children'),
    Output('basic-interactions2', 'figure')
], [
    Input('pop', 'value'),
    Input('recDays', 'value'),
    Input('avgInfections', 'value'),
    Input('initialInfections', 'value'),
    Input('worlds', 'value')
])
def runModel(Pop, recDays, avgInfections, initialInfections, worlds):
    if recDays and Pop and avgInfections and initialInfections:

        def runRegular(recDays, Pop, avgInfections, initialInfections):
            global fig, stringy
            # Number of people self-isolating
            selfIsolating = Pop
            # Number of people susceptible
            S_0 = Pop - initialInfections
            # Number of people infected
Example #21
0
    # simulate expensive query
    print('Computing value with {}'.format(value))
    time.sleep(5)
    return df[df['category'] == value]


def generate_figure(value, figure):
    fig = copy.deepcopy(figure)
    filtered_dataframe = global_store(value)
    fig['data'][0]['x'] = filtered_dataframe['x']
    fig['data'][0]['y'] = filtered_dataframe['y']
    fig['layout'] = {'margin': {'l': 20, 'r': 10, 'b': 20, 't': 10}}
    return fig


@app.callback(Output('signal', 'children'), [Input('dropdown', 'value')])
def compute_value(value):
    # compute value and send a signal when done
    global_store(value)
    return value


@app.callback(Output('graph-1', 'figure'), [Input('signal', 'children')])
def update_graph_1(value):
    # generate_figure gets data from `global_store`.
    # the data in `global_store` has already been computed
    # by the `compute_value` callback and the result is stored
    # in the global redis cached
    return generate_figure(
        value, {
            'data': [{
Example #22
0
        #   ]
        # ),
        html.Div(id='add-node-signal', children="", hidden=True),
        dcc.Location(id='url', refresh=False),
    ],
    fluid=True,
    className="m-0 p-0")


@app.callback(
    [
        Output("cytoscape-net", "layout"),
        Output("layout-algo-select", "label"),
    ],
    [
        Input("layout-algo-select-circle", "n_clicks"),
        Input('layout-algo-select-random', "n_clicks"),
        Input('layout-algo-select-grid', "n_clicks"),
        Input('layout-algo-select-concentric', "n_clicks"),
        Input('layout-algo-select-breadthfirst', "n_clicks"),
        #Input('layout-algo-select-fcose',"n_clicks"),
        Input('layout-algo-select-cose', "n_clicks"),
        Input('layout-algo-select-cose-bilkent', "n_clicks"),
        Input('layout-algo-select-dagre', "n_clicks"),
        Input('layout-algo-select-cola', "n_clicks"),
        Input('layout-algo-select-klay', "n_clicks"),
        Input('layout-algo-select-spread', "n_clicks"),
        Input('layout-algo-select-euler', "n_clicks"),
    ],
    [State("cytoscape-net", "layout"),
     State("layout-algo-select", "label")])
Example #23
0
                            n_clicks=0)
            ]),
            html.Div(children=[
                html.H2(children=lang['wanna_know_more']),
                html.Button("", id='change-info', n_clicks=0),
                html.Div(id='div-info-pipotron', children="")
            ])
        ])


#####################################################################
# CALLBACKS :


@app.callback(Output('real-review', 'children'),
              [Input('change-real-review', 'n_clicks')])
def update_real_review(n_clicks):
    return S_pipotron_reviews.sample(1)


@app.callback(
    Output('fake-review', 'children'),
    [Input('change-fake-review', 'n_clicks'),
     Input('color-choice', 'value')])
def update_fake_review(n_clicks, color):
    return get_fake_review(color)


@app.callback([
    Output('div-info-pipotron', 'children'),
    Output('change-info', 'children')
Example #24
0
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

import plotly.graph_objs as go
import numpy as np
import pandas as pd

df = pd.read_csv('OldFaithful.csv')
colors = {'background': '#111111', 'text': '#7FDBFF'}
app = dash.Dash()

app.layout = html.Div([
    dcc.Input(id='my-id', value='Initial Text', type='text'),
    html.Div(id='my-div')
])


@app.callback(Output(component_id='my-div', component_property='children'),
              [Input(component_id='my-id', component_property='value')])
def update_output_div(input_value):
    return "You entered : {}".format(input_value)


if __name__ == '__main__':
    app.run_server()
                    'value': 'Category'
                }, {
                    'label': 'Resolution',
                    'value': 'Resolution'
                }],
                value='Resolution',
                placeholder="Select by your choice",
            )),
        html.Div(html.Div(dcc.Graph(id='Sankey-with-dropdown')))
    ])
])


@app.callback(
    Output('histogram-with-slider', 'figure'),
    [Input('xaxis-column', 'value'),
     Input('DayOfWeek-slider', 'value')])
def update_figure(xaxis_column_name, selected_DayOfWeek):
    mapp = {
        1: 'Monday',
        2: 'Tuesday',
        3: 'Wednesday',
        4: 'Thursday',
        5: 'Friday',
        6: 'Saturday',
        7: 'Sunday'
    }
    filtered_df = df[df.DayOfWeek == mapp[selected_DayOfWeek]]
    #crime_category = filtered_df['Descript']
    fig = px.histogram(filtered_df,
                       x=filtered_df[xaxis_column_name],
Example #26
0
def register_flow_callbacks(app, cache):
    @app.callback(
        Output("flowplot", "figure"),
        [
            Input("url", "pathname"),
            Input("metric", "value"),
            Input("tasktype", "value"),
            Input("parameter", "value"),
        ],
    )
    @cache.memoize(timeout=TIMEOUT)
    def update_flow_plots(pathname, metric, tasktype, parameter):
        """

        :param pathname: url path
        :param metric: dropdown to choose function/metric
        :param tasktype:drop down to choose task type
        :param parameter: dropdown to choose parameter
        :return:
        """

        if pathname is not None and "/dashboard/flow" in pathname:
            flow_id = int(re.search(r"flow/(\d+)", pathname).group(1))
        else:
            return []

        # Get all tasks of selected task type
        task_type_enum = [
            TaskType.SUPERVISED_CLASSIFICATION,
            TaskType.SUPERVISED_REGRESSION,
            TaskType.LEARNING_CURVE,
            TaskType.SUPERVISED_DATASTREAM_CLASSIFICATION,
            TaskType.SUPERVISED_DATASTREAM_CLASSIFICATION,
            TaskType.CLUSTERING,
            TaskType.MACHINE_LEARNING_CHALLENGE,
            TaskType.SURVIVAL_ANALYSIS,
            TaskType.SUBGROUP_DISCOVERY,
        ]
        task_types = [
            "Supervised classification",
            "Supervised regression",
            "Learning curve",
            "Supervised data stream classification",
            "Clustering",
            "Machine Learning Challenge",
            "Survival Analysis",
            "Subgroup Discovery",
        ]
        t_list = tasks.list_tasks(
            task_type=task_type_enum[task_types.index(tasktype)])
        task_id = [value["tid"] for key, value in t_list.items()]

        # Get all evaluations of selected metric and flow
        import time

        start = time.time()
        df = evaluations.list_evaluations_setups(
            function=metric,
            flows=[flow_id],
            size=1000,
            output_format="dataframe",
            sort_order="desc",
        )
        end = time.time()
        print("list flow evals took ", end - start, " sec")
        if df.empty:
            return go.Figure()

        # Filter type of task
        df = df[df["task_id"].isin(task_id)]
        run_link = []
        tick_text = []
        # Set clickable labels
        for run_id in df["run_id"].values:
            link = '<a href="https://www.openml.org/r/' + str(run_id) + '/"> '
            run_link.append(link)

        for data_id in df["data_id"].values:
            link = '<a href="https://www.openml.org/d/' + str(data_id) + '/">'
            tick_text.append(link)
        hover_text = []
        if parameter == "None":
            color = [1] * len(df["data_name"])
            hover_text = df["value"]
            marker = dict(
                opacity=0.8,
                symbol="diamond",
                color=color,  # set color equal to a variable
                colorscale="Jet",
            )
        else:
            color = []
            for param_dict in df.parameters:
                values = [
                    value for key, value in param_dict.items()
                    if parameter == key
                ]

                if not values:
                    color.append("0")
                else:
                    color.append(values[0])
                    hover_text.append(values[0])
            if color[0].isdigit():
                color = list(map(int, color))
            else:
                color = pd.DataFrame(color)[0].astype("category").cat.codes
            marker = dict(
                opacity=0.8,
                symbol="diamond",
                color=color,  # set color equal to a variable
                colorscale="Jet",
                colorbar=dict(title="Colorbar"),
            )
        data = [
            go.Scatter(
                x=df["value"],
                y=df["data_name"],
                mode="text+markers",
                text=run_link,
                hovertext=hover_text,
                hoverlabel=dict(bgcolor="white", bordercolor="black"),
                marker=marker,
            )
        ]
        layout = go.Layout(
            hovermode="closest",
            title="Every point is a run, click for details <br>"
            "Every y label is a dataset, click for details <br>"
            "Top 1000 runs shown",
            font=dict(size=11),
            autosize=True,
            height=500 + 15 * df["data_name"].nunique(),
            xaxis=go.layout.XAxis(showgrid=False),
            yaxis=go.layout.YAxis(
                showgrid=True,
                ticktext=tick_text + df["data_name"],
                tickvals=df["data_name"],
                showticklabels=True,
            ),
        )
        fig = go.Figure(data, layout)
        return fig
Example #27
0
   print("\n #17 ", list_of_radio_items_id,"\n"),
   #// itemx_state = State('radioitem_12_4','value'),

  #// print("\n #12 Printing state :\n", itemx_state)

  print("\n #22 START: Printing list_of_row_column_pair:"),
  print(list_of_row_column_pair),
  print("\n #22 END \n"),
  print("#29 END: Loading layout"),
  print("#35 Printing the latest dataframe [post_cleansing_df]..."),
  print(post_cleansing_df)
])

@app.callback(
    Output('output-container-button', 'children'),
    [Input('apply_btn', 'n_clicks')],
    callback_loop_radioitem_id()
    #// callback_loop(),
)
def update_output(n_clicks, *radio_item_value_id):
    if n_clicks is None:
        raise PreventUpdate
    else:
        print("\n -> #3 update_output_div()\n \"Apply\" button has been pressed ")

        returnx = ""
        # Print Debug:
        print("#13 START printing value:")
        print(radio_item_value_id)
        print("#13 END \n")
Example #28
0
def autoencoder(app,
                model,
                dataset,
                latent_options,
                paths,
                pre_process=None,
                prefix=""):
    prefix += '-ae-'

    header = dbc.Row([
        html.Div(html.H5("Auto Encoder"), className="col-md-6"),
        dbc.Row([
            html.Div("Model: ", className="col-4 text-right m-auto pr-0"),
            html.Div(dcc.Dropdown(id=prefix + 'selected-model',
                                  options=[{
                                      "label": k,
                                      "value": v
                                  } for k, v in paths.items()],
                                  value=paths[next(iter(paths.keys()))],
                                  searchable=False),
                     className="col-5 pl-0 "),
            html.Div(dbc.Button('reload',
                                color="info",
                                id=prefix + 'reload-model',
                                className="col"),
                     className="col-3 pl-0")
        ],
                className="col-md-6 tools")
    ])

    input_div = dbc.Col(
        dbc.Card([
            dbc.CardHeader([
                "Input",
                dbc.Button('sample',
                           color="info",
                           id=prefix + 'sample-input',
                           className="mr-1 float-right",
                           n_clicks=0),
            ]),
            dbc.CardBody([
                html.Div(children=[], id=prefix + 'input-content'),
                html.Span(children="",
                          id=prefix + 'input-content-id',
                          className='d-none'),
            ],
                         className="d-flex justify-content-center"),
        ]))

    latent_size = latent_options['n']
    latent_space = []
    # just used to fill initial space in the html
    init_hidden_space = ",".join(
        [str(latent_options['min']) for _ in range(latent_size)])

    for _ in range(latent_size):
        id = prefix + 'latent-slider-' + str(_)
        latent_space.append(
            dcc.Slider(min=latent_options['min'],
                       max=latent_options['max'],
                       step=latent_options['step'],
                       updatemode='drag',
                       id=id,
                       value=latent_options['min'],
                       className="mt-3 mb-3"))
    latent_div = dbc.Col(
        dbc.Card([
            dbc.CardHeader("Latent Space"),
            html.Span(id=prefix + "hidden-latent-space",
                      children=init_hidden_space,
                      className='d-none'),
            dbc.CardBody(
                [html.Div(children=latent_space,
                          id=prefix + 'output-latent')]),
        ]))

    output_div = dbc.Col(
        dbc.Card([
            dbc.CardHeader("Output"),
            dbc.CardBody([
                html.Div(children=[], id=prefix + 'output-content'),
            ],
                         className="d-flex justify-content-center"),
        ]))

    @app.callback([
        Output(component_id=prefix + 'input-content-id',
               component_property='children'),
        Output(component_id=prefix + 'input-content',
               component_property='children'),
        Output(component_id=prefix + "hidden-latent-space",
               component_property='children')
    ], [
        Input(component_id=prefix + 'sample-input',
              component_property='n_clicks')
    ])
    def sample_input(n_clicks):
        input_id = random.randint(0, len(dataset) - 1)
        # img, _ = dataset[input_id]
        img = dataset[input_id]

        # hx = model.encoder(img.view(-1))
        hx = model.encode(Variable(torch.FloatTensor(img).unsqueeze(0)))
        hx = [
            round(_, len(str(latent_options['step']).split('.')[-1]))
            for _ in hx[0].cpu().data.numpy().tolist()
        ]

        # pre-process to get PIL image
        if pre_process is not None:
            disp_img = pre_process(img)
        else:
            disp_img = img
        disp_img = _img_resize(disp_img)

        # convert to byte code image
        output = BytesIO()
        disp_img.save(output, format='PNG')
        output.seek(0)
        encoded_image = base64.b64encode(output.read())

        html_img = html.Img(
            src='data:image/png;base64,{}'.format(str(encoded_image)[2:-1]))
        hx = ','.join([str(_) for _ in hx])
        return str(input_id), html_img, hx

    for slider_id in range(latent_size):

        @app.callback(
            Output(component_id=prefix + 'latent-slider-' + str(slider_id),
                   component_property="value"), [
                       Input(component_id=prefix + "hidden-latent-space",
                             component_property='children')
                   ],
            [
                State(component_id=prefix + 'latent-slider-' + str(slider_id),
                      component_property="id")
            ])
        def set_latent_slider(latent_space, slider_id):
            slider_id = int(slider_id.split("-")[-1])
            return float(latent_space.split(",")[slider_id])

    @app.callback(
        Output(component_id=prefix + 'output-content',
               component_property='children'),
        [
            Input(component_id=prefix + 'latent-slider-' + str(slider_id),
                  component_property='value')
            for slider_id in range(latent_size)
        ])
    def predicted_output(*latent_space):
        output = model.decode(
            Variable(torch.FloatTensor(latent_space).unsqueeze(0)))

        # pre-process to get numpy image
        if pre_process is not None:
            # img = pre_process(output.reshape(dataset[0].shape))
            img = pre_process(output)
        img = _img_resize(img)
        # convert to img
        output = BytesIO()
        img.save(output, format='PNG')
        output.seek(0)
        encoded_image = base64.b64encode(output.read())

        html_img = html.Img(
            src='data:image/png;base64,{}'.format(str(encoded_image)[2:-1]))
        return html_img

    @app.callback(
        Output(component_id=prefix + 'sample-input',
               component_property='n_clicks'), [
                   Input(component_id=prefix + 'selected-model',
                         component_property='value'),
                   Input(component_id=prefix + 'reload-model',
                         component_property='n_clicks')
               ], [
                   State(component_id=prefix + 'sample-input',
                         component_property='n_clicks')
               ])
    def refresh_model(model_path, reload, n_clicks):
        model.load_state_dict(torch.load(model_path, map_location='cpu'))
        return int(n_clicks) + 1

    ae_div = dbc.Card([
        dbc.CardHeader(header),
        dbc.CardBody(
            dbc.Row([input_div, latent_div, output_div], className='m-2'))
    ],
                      className="mt-4 mb-4 border-secondary autoencoder-box")
    return ae_div
Example #29
0
                                    autofill=True,
                                    margin=dict(t=75, r=50, b=100, l=50),
                                ),
                            ),
                        ),
                    ],
                ),
            ],
        ),
    ],
)


@app.callback(
    Output("county-choropleth", "figure"),
    [Input("years-slider", "value")],
    [State("county-choropleth", "figure")],
)
def display_map(year, figure):
    cm = dict(zip(BINS, DEFAULT_COLORSCALE))

    data = [
        dict(
            lat=df_lat_lon["Latitude "],
            lon=df_lat_lon["Longitude"],
            text=df_lat_lon["Hover"],
            type="scattermapbox",
            hoverinfo="text",
            marker=dict(size=5, color="white", opacity=0),
        )
    ]
Example #30
0
            dbc.Collapse(
                dbc.Nav([search_bar], className="ml-auto", navbar=True),
                id="navbar-collapse",
                navbar=True,
            ),
        ],
        fluid=True,
    ),
    color="#2c6693",
    dark=True,
)


@app.callback(
    Output("navbar-collapse", "is_open"),
    [Input("navbar-toggler", "n_clicks")],
    [State("navbar-collapse", "is_open")],
)
def toggle_navbar_collapse(n, is_open):
    if n:
        return not is_open
    return is_open


# the style arguments for the sidebar. We use position:fixed and a fixed width
SIDEBAR_STYLE = {
    "position": "fixed",
    "top": 120,
    "left": 0,
    "bottom": 0,
    "width": "16rem",