Пример #1
0
    def __init__(self, tree: "DataTree"):
        self.tree = tree
        JupyterDash.infer_jupyter_proxy_config()
        self.app = JupyterDash(__name__, external_stylesheets=STYLESHEET)
        self.server = self.app.server
        self.model = CellModel(tree)
        self.scatter = Scatter(self.app, data={"model": self.model})
        self.dim_dropdowns = DropDownColumn(
            self.app,
            data=dict(title_list=self.model.DIMENSIONS,
                      options=self.model.col_options))
        self.sliders = SliderColumn(
            data={"slider_params": self.model.MARKER_ARGS_PARAMS})
        self.col_adder = ColumnAdder()
        self.annotator = ScatterAnnotator(data={
            "model": self.model,
            "options": self.model.col_options
        })
        self.colname_store = DropDownOptionsStore()
        self.gene_data = GeneData(self.app, data={"model": self.model})

        self.colname_store.callbacks(master=self.annotator,
                                     subscribers=[
                                         *self.dim_dropdowns.contents,
                                         self.annotator.dropdown
                                     ])
        self.annotator.callbacks(self.scatter, self.col_adder)
        self.scatter.callbacks(self.dim_dropdowns, self.sliders)
        self.gene_data.callbacks(self.scatter)
Пример #2
0
    def __init__(self, as_website=False):
        # global app_data
        # global fig
        self.as_website = as_website
        self.app_port = get_unused_port(initial_port=port)
        self.as_website = as_website
        # just for testing local website
        # self.app_data = {'traces':{}, 'selection':{}} #application_data.ApplicationData()
        # self.app_data = app_data

        self.server = flask.Flask(__name__)  # define flask app.server
        #self.app = JupyterDash(__name__, external_stylesheets=external_stylesheets, external_scripts=external_scripts,server=self.server)
        self.app = JupyterDash(__name__,
                               external_stylesheets=external_stylesheets,
                               external_scripts=external_scripts,
                               server=self.server)
        if not as_website:
            self.socketio = SocketIO(self.server)
        #self.app = JupyterSocketDash(__name__, external_stylesheets=external_stylesheets,external_scripts=external_scripts, server=self.server)
        self.app.server.secret_key = 'SOME_KEY_STRING'
        self.app.title = "Spectrum Viewer"

        self.app_data = process_manager.dict()
        self.app_data_timestamp = process_manager.dict()
        for key, value in self.build_app_data().items():
            self.app_data[key] = value

        # setting the default values, which also show in the UI dropdown.

        #self.app_data['traces'] = {}
        #self.app_data['fitted_models'] = {}
        #self.app_data['selection'] = {}
        self.app_data_timestamp['timestamp'] = 0
        self.debug_data = process_manager.dict()

        self.smoother = Smoother()
        self.model_fitter = ModelFitter()

        # self.spectral_lines_info = spectral_lines_info
        # self.view = V.SpecView(width, height, dpi)
        # self.view.select_all_button.on_clicked(self.select_all_button_callback)
        # self.view.delete_unchecked_button.on_clicked(self.delete_unchecked_button_callback)
        # self.model = M.SpecModel(streams=OrderedDict(), spectral_lines=OrderedDict())

        # self.spec_figure = make_subplots(rows=1, cols=1)
        # self.fill_spec_figure_with_app_data()
        #self.spec_figure = self.get_spec_figure_from_data(self.app_data)

        #app.layout = self.load_app_layout
        storage_mode = "session" if as_website else "memory"
        self.app.layout = app_layout.load_app_layout(self, self.app_port,
                                                     storage_mode)
        callbacks.load_callbacks(self)

        @self.server.route('/api/health')
        def health():
            return {'is_healthy': True}
Пример #3
0
    def main_function(self, mode):

        external_stylesheets = [
            'https://raw.githubusercontent.com/rab657/explainx/master/explainx.css',
            dbc.themes.BOOTSTRAP, {
                'href': 'https://fonts.googleapis.com/css?family=Montserrat',
                'rel': 'stylesheet'
            }
        ]

        local = JupyterDash(__name__,
                            external_stylesheets=external_stylesheets,
                            suppress_callback_exceptions=True)

        local.title = "explainX.ai - Feature Interaction"

        local.layout = feature_interaction.layout_interaction(
            self.data, self.df_with_shap, local)

        if mode == None:
            import random
            port = random.randint(5000, 6000)
            return local.run_server(port=port)
        else:
            import random
            port = random.randint(5000, 6000)
            return local.run_server(mode='inline', port=port)
Пример #4
0
    def __init__(self, mode='default', **kwargs):
        external_stylesheets = [BOOTSTRAP]
        if mode == 'jupyter':
            self.app = JupyterDash(external_stylesheets=external_stylesheets)
        else:
            self.app = Dash(external_stylesheets=external_stylesheets)

        app = self.app  # For referencing with the decorator (see line below)
        app.title = 'CEHS Uganda'

        @app.server.route('/static/<asset_type>/<path>')
        def static_file(asset_type, path):
            return send_from_directory(here / 'static' / asset_type, path)
Пример #5
0
    def __init__(self, mode="default", **kwargs):
        external_stylesheets = [BOOTSTRAP]
        if mode == "jupyter":
            self.app = JupyterDash(external_stylesheets=external_stylesheets)
        else:
            self.app = Dash(
                external_stylesheets=external_stylesheets,
                prevent_initial_callbacks=True,
            )

        app = self.app  # For referencing with the decorator (see line below)
        app.title = "CEHS Uganda"

        @app.server.route("/static/<asset_type>/<path>")
        def static_file(asset_type, path):
            return send_from_directory(here / "static" / asset_type, path)
Пример #6
0
    def __init__(self, graph_one, graph_two, app_display='default'):
        """
        Initialises the dual graph interface and generates the interface layout.

        :param graph_one: (Graph) The first graph for the comparison interface.
        :param graph_two: (Graph) The second graph for the comparison interface.
        :param app_display: (str) 'default' by default and 'jupyter notebook' for running Dash inside Jupyter Notebook.
        """

        # Dash app styling with Bootstrap
        if app_display == 'jupyter notebook':
            self.app = JupyterDash(__name__,
                                   external_stylesheets=[dbc.themes.BOOTSTRAP])
        else:
            self.app = Dash(__name__,
                            external_stylesheets=[dbc.themes.BOOTSTRAP])

        # Setting input graphs as objest variables
        cyto.load_extra_layouts()
        self.graph_one = graph_one
        self.graph_two = graph_two

        # Getting a list of tuples with differnet edge connections
        difference = graph_one.get_difference(graph_two)

        # Updating the elements needed for the Dash Cytoscape Graph object
        self.one_components = None
        self.two_components = None
        self._update_elements_dual(self.graph_one, difference, 1)
        self._update_elements_dual(self.graph_two, difference, 2)

        self.cyto_one = None
        self.cyto_two = None

        # Callback functions to allow simultaneous node selection when clicked
        self.app.callback(Output('cytoscape_two',
                                 'elements'), [Input('cytoscape', 'tapNode')],
                          [State('cytoscape_two', 'elements')])(
                              DualDashGraph._select_other_graph_node)
        self.app.callback(Output('cytoscape', 'elements'),
                          [Input('cytoscape_two', 'tapNode')],
                          [State('cytoscape', 'elements')])(
                              DualDashGraph._select_other_graph_node)
Пример #7
0
    def main_function(self, mode):

        external_stylesheets = [
            'https://raw.githubusercontent.com/rab657/explainx/master/explainx.css',
            dbc.themes.BOOTSTRAP, {
                'href': 'https://fonts.googleapis.com/css?family=Montserrat',
                'rel': 'stylesheet'
            }
        ]
        local = JupyterDash(__name__,
                            external_stylesheets=external_stylesheets,
                            suppress_callback_exceptions=True)

        local.title = "explainX.ai - Local Level Explanation"

        local.layout = local_explanation.layout_local(self.shapley_values,
                                                      self.data,
                                                      self.df_with_shap, local)
        debug_value = False
        if mode is None:
            import random
            port = random.randint(6000, 7000)
            return local.run_server(port=port,
                                    debug=debug_value,
                                    dev_tools_ui=debug_value,
                                    dev_tools_props_check=debug_value,
                                    dev_tools_silence_routes_logging=True,
                                    dev_tools_hot_reload=True)
        else:
            import random
            port = random.randint(6000, 7000)
            return local.run_server(mode='inline',
                                    port=port,
                                    debug=debug_value,
                                    dev_tools_ui=debug_value,
                                    dev_tools_props_check=debug_value,
                                    dev_tools_silence_routes_logging=True,
                                    dev_tools_hot_reload=True)
Пример #8
0
    def main_function(self, mode):

        external_stylesheets = [
            'https://raw.githubusercontent.com/rab657/explainx/master/explainx.css',
            dbc.themes.BOOTSTRAP, {
                'href': 'https://fonts.googleapis.com/css?family=Montserrat',
                'rel': 'stylesheet'
            }
        ]
        cohort = JupyterDash(__name__,
                             external_stylesheets=external_stylesheets,
                             suppress_callback_exceptions=True)

        cohort.title = "explainX.ai - Model Performance Analysis"

        cohort.layout = cohort_app.test_func(self.data, self.model, cohort)
        debug_value = False
        if mode == None:
            import random
            port = random.randint(4000, 5000)
            return cohort.run_server(port=port,
                                     debug=debug_value,
                                     dev_tools_ui=debug_value,
                                     dev_tools_props_check=debug_value,
                                     dev_tools_silence_routes_logging=True,
                                     dev_tools_hot_reload=True)
        else:
            import random
            port = random.randint(4000, 5000)
            return cohort.run_server(mode='inline',
                                     port=port,
                                     debug=debug_value,
                                     dev_tools_ui=debug_value,
                                     dev_tools_props_check=debug_value,
                                     dev_tools_silence_routes_logging=True,
                                     dev_tools_hot_reload=True)
Пример #9
0
def create_app(available_indicators, df):
    external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

    app = JupyterDash(__name__, external_stylesheets=external_stylesheets)

    # Create server variable with Flask server object for use with gunicorn
    server = app.server

    app.layout = html.Div([
        html.Div(
            [
                html.Div([
                    dcc.Dropdown(
                        id='crossfilter-xaxis-column',
                        options=[{
                            'label': i,
                            'value': i
                        } for i in available_indicators],
                        value='Fertility rate, total (births per woman)'),
                    dcc.RadioItems(id='crossfilter-xaxis-type',
                                   options=[{
                                       'label': i,
                                       'value': i
                                   } for i in ['Linear', 'Log']],
                                   value='Linear',
                                   labelStyle={'display': 'inline-block'})
                ],
                         style={
                             'width': '49%',
                             'display': 'inline-block'
                         }),
                html.Div([
                    dcc.Dropdown(
                        id='crossfilter-yaxis-column',
                        options=[{
                            'label':
                            i,
                            'value':
                            i
                        } for i in available_indicators],
                        value='Life expectancy at birth, total (years)'),
                    dcc.RadioItems(id='crossfilter-yaxis-type',
                                   options=[{
                                       'label': i,
                                       'value': i
                                   } for i in ['Linear', 'Log']],
                                   value='Linear',
                                   labelStyle={'display': 'inline-block'})
                ],
                         style={
                             'width': '49%',
                             'float': 'right',
                             'display': 'inline-block'
                         })
            ],
            style={
                'borderBottom': 'thin lightgrey solid',
                'backgroundColor': 'rgb(250, 250, 250)',
                'padding': '10px 5px'
            }),
        html.Div([
            dcc.Graph(id='crossfilter-indicator-scatter',
                      hoverData={'points': [{
                          'customdata': 'Japan'
                      }]})
        ],
                 style={
                     'width': '49%',
                     'display': 'inline-block',
                     'padding': '0 20'
                 }),
        html.Div([
            dcc.Graph(id='x-time-series'),
            dcc.Graph(id='y-time-series'),
        ],
                 style={
                     'display': 'inline-block',
                     'width': '49%'
                 }),
        html.Div(dcc.Slider(
            id='crossfilter-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),
                 style={
                     'width': '49%',
                     'padding': '0px 20px 20px 20px'
                 })
    ])

    @app.callback(
        dash.dependencies.Output('crossfilter-indicator-scatter', 'figure'), [
            dash.dependencies.Input('crossfilter-xaxis-column', 'value'),
            dash.dependencies.Input('crossfilter-yaxis-column', 'value'),
            dash.dependencies.Input('crossfilter-xaxis-type', 'value'),
            dash.dependencies.Input('crossfilter-yaxis-type', 'value'),
            dash.dependencies.Input('crossfilter-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'],
                    customdata=dff[dff['Indicator Name'] ==
                                   yaxis_column_name]['Country Name'],
                    mode='markers',
                    marker={
                        'size': 25,
                        'opacity': 0.7,
                        'color': 'orange',
                        'line': {
                            'width': 2,
                            'color': 'purple'
                        }
                    })
            ],
            'layout':
            dict(xaxis={
                'title': xaxis_column_name,
                'type': 'linear' if xaxis_type == 'Linear' else 'log'
            },
                 yaxis={
                     'title': yaxis_column_name,
                     'type': 'linear' if yaxis_type == 'Linear' else 'log'
                 },
                 margin={
                     'l': 40,
                     'b': 30,
                     't': 10,
                     'r': 0
                 },
                 height=450,
                 hovermode='closest')
        }

    def create_time_series(dff, axis_type, title):
        return {
            'data':
            [dict(x=dff['Year'], y=dff['Value'], mode='lines+markers')],
            'layout': {
                'height':
                225,
                'margin': {
                    'l': 20,
                    'b': 30,
                    'r': 10,
                    't': 10
                },
                'annotations': [{
                    'x': 0,
                    'y': 0.85,
                    'xanchor': 'left',
                    'yanchor': 'bottom',
                    'xref': 'paper',
                    'yref': 'paper',
                    'showarrow': False,
                    'align': 'left',
                    'bgcolor': 'rgba(255, 255, 255, 0.5)',
                    'text': title
                }],
                'yaxis': {
                    'type': 'linear' if axis_type == 'Linear' else 'log'
                },
                'xaxis': {
                    'showgrid': False
                }
            }
        }

    @app.callback(dash.dependencies.Output('x-time-series', 'figure'), [
        dash.dependencies.Input('crossfilter-indicator-scatter', 'hoverData'),
        dash.dependencies.Input('crossfilter-xaxis-column', 'value'),
        dash.dependencies.Input('crossfilter-xaxis-type', 'value')
    ])
    def update_y_timeseries(hoverData, xaxis_column_name, axis_type):
        country_name = hoverData['points'][0]['customdata']
        dff = df[df['Country Name'] == country_name]
        dff = dff[dff['Indicator Name'] == xaxis_column_name]
        title = '<b>{}</b><br>{}'.format(country_name, xaxis_column_name)
        return create_time_series(dff, axis_type, title)

    @app.callback(dash.dependencies.Output('y-time-series', 'figure'), [
        dash.dependencies.Input('crossfilter-indicator-scatter', 'hoverData'),
        dash.dependencies.Input('crossfilter-yaxis-column', 'value'),
        dash.dependencies.Input('crossfilter-yaxis-type', 'value')
    ])
    def update_x_timeseries(hoverData, yaxis_column_name, axis_type):
        dff = df[df['Country Name'] == hoverData['points'][0]['customdata']]
        dff = dff[dff['Indicator Name'] == yaxis_column_name]
        return create_time_series(dff, axis_type, yaxis_column_name)

    return app
Пример #10
0
import plotly.graph_objects as go
import pandas as pd
import json

# Load Data
#df = px.data.tips()
df = pd.read_csv('FcstCompare.csv', parse_dates=True)

with open('../shps/AEZs.geojson') as f:
    counties = json.load(f)

for feature in counties["features"]:
    feature['id'] = str(feature['properties']['COUNTY'])

# Build App
app = JupyterDash(__name__)
app.layout = html.Div([
    html.H1("RHEAS-DSSAT Demo"),
    dcc.Dropdown(id='fcst-dropdown',
                 clearable=False,
                 value='fcst_dates',
                 options=[{
                     'label': f,
                     'value': f
                 } for f in df['fcst_date'].unique()]),
    dcc.Graph(id='map'),
    dcc.Graph(id='graph'),
    dcc.Dropdown(id='cnty-dropdown',
                 clearable=False,
                 value='fcst_dates',
                 options=[{
Пример #11
0
    def init_app(self):

        app = JupyterDash(__name__)
        # app = dash.Dash()
        app.css.config.serve_locally = True
        app.scripts.config.serve_locally = True

        # self.add_rec(['main', 'MLPClassifier'], 'alpha=0.1', self.icicle_data)
        # self.add_rec(['main', 'MLPClassifier'], 'alpha=0.01', self.icicle_data)

        def df_to_dict(ut):
            data = {}
            for col_name in self.hierarchy_path:
                for i, g in ut.groupby(col_name):
                    data_key = g[col_name].iloc[0]
                    data[data_key] = {}

        data = copy.deepcopy(self.icicle_data)

        icicle_plot_fig = icicle_plot.Icicle(id='icicle_plot_fig',
                                             value='main/',
                                             label='my-label',
                                             low=self.low_color,
                                             high=self.high_color,
                                             data=data)

        def make_ints(row):
            for col in self.hierarchy_path:
                if row[col] != None:
                    try:
                        row[col] = float(row[col].split("=")[1])
                    except:
                        row[col]
            return row

        pc_data_numeric = self.pc_data.apply(make_ints, axis=1)

        pc = go.Figure(data=[go.Scatter(x=[], y=[])])
        if self.pc_data is not 0 and not self.pc_data.empty:
            pc = px.parallel_coordinates(pc_data_numeric.apply(make_ints,
                                                               axis=1),
                                         color="accuracy",
                                         dimensions=self.hierarchy_path +
                                         ['accuracy'],
                                         color_continuous_scale='RdBu',
                                         height=350)
        pc_o = pc

        marks = {}
        for i in range(0, 100, 10):
            marks[i / 100] = str(i / 100)

        button_style = {
            "background-color": "#008CBA",
            "border": "none",
            "color": "white",
            "padding": "15px 32px",
            "text-align": "center",
            "display": "inline-block",
            "font-size": 16,
            "margin": "4px 2px",
            "cursor": "pointer",
            "width": "150px",
            "border-radius": "5%"
        }

        app.layout = html.Div(
            [
                html.Div(
                    [
                        html.Div(icicle_plot_fig, id='icicle-wrap'),
                        dcc.Graph(id='pc', figure=pc, style={'height': 350}),
                        dcc.Interval(
                            id='interval-component',
                            interval=1000,  # in milliseconds
                            n_intervals=0),
                        dcc.Interval(
                            id='interval-component2',
                            interval=1000,  # in milliseconds
                            n_intervals=0),
                        dcc.Interval(id='interval-loading',
                                     interval=100,
                                     n_intervals=0),
                        html.H3('Sand Box', id='sandboxtext'),
                        dcc.Textarea(id='sandbox',
                                     value='',
                                     style={
                                         'height': 120,
                                         'width': '90%'
                                     }),
                        html.Div([
                            html.Button('Execute',
                                        id='execute-button',
                                        style=button_style),
                            dcc.Loading(id="loading",
                                        children=html.Div(
                                            [html.Div(id='output')]),
                                        type="circle",
                                        style={'margin-bottom': '6%'})
                        ])
                    ],
                    style={
                        'width': '87%',
                        'height': '100%',
                        'float': 'left'
                    }),
                html.Div([
                    dcc.RangeSlider(id='metric-slider',
                                    min=0,
                                    max=1,
                                    step=0.01,
                                    value=[0, 1],
                                    marks=marks,
                                    vertical=True,
                                    verticalHeight=500)
                ],
                         style={
                             'margin-left': '90%',
                             'margin-top': '2%'
                         })
                # html.Div([
                #         html.H3('Sand Box', id='sandboxtext', style={"text-align": 'center'}),
                #         dcc.Textarea(
                #             id='sandbox',
                #             value='',
                #             style={'height': 400}
                #         ),
                #         html.Div([
                #             html.Button('Execute', id='execute-button', style=button_style),
                #             dcc.Loading(
                #                 id="loading",
                #                 children=html.Div([
                #                     html.Div(id='output')
                #                 ]),
                #                 type="circle"
                #             )
                #         ], style= {'right': 37, 'position': 'absolute'})
                #     ], style={'margin-left': '5%'})
            ],
            style={
                'height': '100%',
                'overflow': 'hidden'
            })

        @app.callback(Output('icicle-wrap', 'children'), [
            Input('metric-slider', 'value'),
            Input('interval-component', 'n_intervals')
        ])
        def update_icicle(rangeData, n):
            trigger_context = dash.callback_context.triggered[0]['prop_id']
            if len(dash.callback_context.triggered
                   ) <= 1 and self.update_available == False and (
                       trigger_context == 'interval-component.n_intervals'
                       or trigger_context == '.'):
                raise PreventUpdate

            # revert to original state
            data = copy.deepcopy(self.icicle_data)
            # print(data)
            if not self.pc_data.empty:
                # delete entries
                self.remove_nodes_out_of_range(rangeData[0], rangeData[1],
                                               data)
                filtered_accs = self.pc_data.query(
                    "accuracy >= " + str(rangeData[0]) + " and accuracy <= " +
                    str(rangeData[1]))['accuracy']
                self.low_color = filtered_accs.min()
                self.high_color = filtered_accs.max()
                if rangeData != self.rangeDataOld:
                    self.id_updater += 1
                    self.rangeDataOld = rangeData

            if self.update_available:
                # print("update vailable")
                self.id_updater += 1
                self.update_available = False

            # id is dictionary for Dash pattern matching callbacks
            return icicle_plot.Icicle(id={
                'role': 'icicle_plot_fig',
                'index': self.id_updater
            },
                                      value='main/',
                                      label='my-label',
                                      low=self.low_color,
                                      high=self.high_color,
                                      data=data)

        @app.callback(Output('pc', 'figure'), [
            Input({
                'role': 'icicle_plot_fig',
                'index': ALL
            }, 'value'),
            Input('metric-slider', 'value'),
            Input('interval-component2', 'n_intervals')
        ])
        def update_pc(clickData, rangeData, n):
            if self.pc_data.empty:
                return go.Figure(data=[go.Scatter(x=[], y=[])])
            trigger_context = dash.callback_context.triggered[0]['prop_id']
            if len(dash.callback_context.triggered
                   ) <= 1 and self.update_available == False and (
                       trigger_context == 'interval-component2.n_intervals'):
                raise PreventUpdate

            pc_data_copy = self.pc_data

            if len(clickData) == 0:
                if self.update_available:
                    pc = px.parallel_coordinates(
                        pc_data_copy.apply(make_ints, axis=1),
                        color="accuracy",
                        dimensions=self.hierarchy_path + ['accuracy'],
                        color_continuous_scale='RdBu',
                        height=350)
                    return pc
                raise PreventUpdate
                # return self.pc
                # revert to original state
            # delete entries
            pc_data_copy = pc_data_copy.query("accuracy >= " +
                                              str(rangeData[0]) +
                                              " and accuracy <= " +
                                              str(rangeData[1]))

            if isinstance(clickData, list):
                clickData = clickData[0]

            if 'recommendationval' in clickData:
                raise PreventUpdate

            if clickData.split("/")[:-2] == []:
                pc = px.parallel_coordinates(pc_data_copy.apply(make_ints,
                                                                axis=1),
                                             color="accuracy",
                                             dimensions=self.hierarchy_path +
                                             ['accuracy'],
                                             color_continuous_scale='RdBu',
                                             height=350)
                return pc
            if clickData:
                click_path = clickData.split("/")[:-1][1:]
                subset_counter = len(click_path)
                if click_path == []:
                    return pc_o

                selected_df = pc_data_copy
                j = -1
                for i in click_path:
                    j += 1
                    if "=" in i:
                        comps_name = i.split("=")
                        hyp_name = comps_name[0]
                        hyp_val = comps_name[1]
                        selected_df = selected_df[selected_df.apply(
                            lambda x: x['model_params'][hyp_name] == hyp_val
                            if hyp_name in x['model_params'] else False,
                            axis=1)]
                    else:
                        selected_df = selected_df[selected_df['model'] == i]
                sample_vals = selected_df.iloc[0]
                labels_pc = {}
                for i in self.hierarchy_path[subset_counter:]:
                    if sample_vals[i]:
                        labels_pc[i] = sample_vals[i].split("=")[0]

                selected_df = selected_df.apply(make_ints, axis=1)
                self.pc = px.parallel_coordinates(
                    selected_df,
                    color="accuracy",
                    dimensions=self.hierarchy_path[subset_counter:] +
                    ['accuracy'],
                    labels=labels_pc,
                    color_continuous_scale='RdBu',
                    height=350)
                # print(pc_data_copy.apply(make_ints, axis=1))
                return self.pc
            self.pc = px.parallel_coordinates(pc_data_copy.apply(make_ints,
                                                                 axis=1),
                                              color="accuracy",
                                              dimensions=self.hierarchy_path +
                                              ['accuracy'],
                                              color_continuous_scale='RdBu',
                                              height=350)
            return self.pc

        @app.callback(
            Output('sandbox', 'value'),
            [Input({
                'role': 'icicle_plot_fig',
                'index': ALL
            }, 'value')])
        def update_sandbox(clickData):
            if len(clickData) == 0:
                raise PreventUpdate

            if isinstance(clickData, list):
                clickData = clickData[0]
            if 'recommendationval' in clickData:
                # update the sand box
                clickData = clickData.replace(" recommendationval", "")
                model_name = ""
                params_rec = {}
                for i in clickData.split("/"):
                    if 'main' in i or not i or not i.strip():
                        continue

                    # model name
                    if '=' not in i:
                        model_name = i
                        continue

                    try:
                        params_rec[i.split("=")[0]] = float(i.split(
                            "=")[1])  # for int, long, float and complex
                        if params_rec[i.split("=")[0]].is_integer():
                            params_rec[i.split("=")[0]] = int(
                                params_rec[i.split("=")[0]])
                    except ValueError:
                        params_rec[i.split("=")[0]] = i.split("=")[1]

                code = "app.experiment(\nlibrary = 'sklearn',\nmodel = " + model_name + ",\nparams = \n" + str(
                    params_rec).replace('{', '{\n  ').replace(
                        ',', ',\n ').replace('}',
                                             '\n}') + ",\nhighlighted = True)"
                return code
            else:
                raise PreventUpdate

        @app.callback(Output('execute-button', 'style'),
                      [Input('interval-loading', 'n_intervals')])
        def check_execution(n_intervals):

            button_style = {
                "background-color": "#008CBA",
                "border": "none",
                "color": "white",
                "padding": "15px 32px",
                "text-align": "center",
                "display": "inline-block",
                "font-size": 16,
                "margin": "4px 2px",
                "cursor": "pointer",
                "width": "150px",
                "border-radius": "5%"
            }

            if not self.running_experiment and not self.running_recommendation:
                return button_style

            if self.running_recommendation:
                button_style['visibility'] = "hidden"
                button_style["cursor"] = 'not-allowed'
                button_style['pointer-events'] = "none"
                return button_style

            button_style["cursor"] = 'not-allowed'
            button_style['pointer-events'] = "none"
            button_style["opacity"] = 0.5
            return button_style

        # execute button handler
        app.callback(Output('output',
                            'value'), [Input('execute-button', 'n_clicks')],
                     [State('sandbox', 'value')])(self.execute_code)

        self.app = app
Пример #12
0
                             filter_action='none',
                             sort_action="native",
                             style_cell={
                                 'textAlign': 'center',
                                 'font-family': 'sans-serif'
                             },
                             editable=False))
])

content = html.Div([
    html.H2('Transcript Review Tool', style=TEXT_STYLE),
    html.Hr(), content_row
],
                   style=CONTENT_STYLE)

app = JupyterDash(external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div([sidebar, content])


@app.callback(Output(
    component_id='bee_data_table', component_property='data'), [
        Input(component_id='submit_button', component_property='n_clicks'),
        State(component_id='state_dropdown', component_property='value'),
        State(component_id='range_slider', component_property='value')
    ])
def update_dash_table(n_clicks, state, date_range):
    dash_table_data = (grouped_df.loc[grouped_df["State"] == state].loc[
        grouped_df["Year"] >= date_range[0]].loc[
            grouped_df["Year"] <= date_range[1]].to_dict('records'))
    return dash_table_data
Пример #13
0
                       id="fade-transition-button",
                       className="mb-3",
                       n_clicks=0), fade
        ])
    ]))

result_card = dbc.Card([dbc.CardBody([dbc.Row([result_blurb])])])

survey_card = dbc.Card(
    [dbc.CardBody(dbc.Row([html.Embed(src=form, height=900, width=750)]))],
    style={
        'width': 'auto',
        'height': 'auto'
    })

app = JupyterDash(external_stylesheets=[dbc.themes.LITERA])
server = app.server

top_cell = dbc.Col([html.H2('Politics of Earth Dashboard')], width=12)
right_col = dbc.Col([survey_card], width=6)
left_col = dbc.Col([result_card], width=6)
app.layout = html.Div([dbc.Row([top_cell]), dbc.Row([left_col, right_col])])


@app.callback(
    Output("fade-transition", "is_in"),
    [Input("fade-transition-button", "n_clicks")],
    [State("fade-transition", "is_in")],
)
def toggle_fade(n_clicks, is_in):
    if n_clicks != 0:
Пример #14
0
def show_task(jeditaskid, verbose=False, mode='inline'):
    # get task
    task = queryPandaMonUtils.query_tasks(23518002, verbose=False)[-1][0]
    # get tasks of the user
    tasks = queryPandaMonUtils.query_tasks(username=task['username'], verbose=False)[-1]
    tids = set([x['jeditaskid'] for x in tasks])
    tids.add(jeditaskid)

    # Build App
    app = JupyterDash(__name__)
    app.layout = html.Div([
        html.Div([
            html.H2("TaskID: "),
            dcc.Dropdown(
                id='dropdown_taskid',
                options=[{'label': i, 'value': i} for i in tids],
                value=jeditaskid
            ),],
            style={'display': 'inline-block', 'width': '20%'}
        ),
        html.Div([
            html.Div([
                html.H2('Task Attributes'),
                dash_table.DataTable(id='00_table',
                                     columns=[{'id': 'attribute', 'name': 'attribute'},
                                              {'id': 'value', 'name': 'value'}],
                                     page_action='none',
                                     style_table={'height': '330px', 'overflowY': 'auto'},
                                     style_cell_conditional=[
                                         {
                                             'if': {'column_id': 'value'},
                                             'textAlign': 'left'
                                         },
                                     ]),],
                style={'display': 'inline-block', 'width': '49%', 'float': 'left', 'padding-top': '30px'}
            ),
            html.Div([
                dcc.Graph(id='01_graph'),],
                style={'display': 'inline-block', 'width': '49%'}
            ),
        ],),
        html.Div([
            html.Div([
                dcc.Graph(id='10_graph')],
                style={'display': 'inline-block', 'width': '49%'}),
            html.Div([
                dcc.Graph(id='11_graph')],
                style={'display': 'inline-block', 'width': '49%'})
        ],),
    ])

    # Run app and display result inline in the notebook
    app.run_server(mode=mode)


    @app.callback(
        Output('00_table', 'data'),
        Output('01_graph', 'figure'),
        Output('10_graph', 'figure'),
        Output('11_graph', 'figure'),
        Input('dropdown_taskid', "value")
    )
    def make_elements(jeditaskid):
        verbose = False
        task = queryPandaMonUtils.query_tasks(jeditaskid, verbose=verbose)[-1][0]
        jobs = queryPandaMonUtils.query_jobs(jeditaskid, drop=False, verbose=verbose)[-1]['jobs']
        jobs = pd.DataFrame(jobs)

        # task data
        task_data = [{'attribute': k, 'value': task[k]} for k in task if isinstance(task[k], (str, type(None)))]

        # figures
        site_fig = px.histogram(jobs, x="computingsite", color="jobstatus")
        ram_fig = px.histogram(jobs, x="maxrss")

        exectime_fig = go.Figure()
        legend_set = set()
        for d in jobs.itertuples(index=False):
            if d.jobstatus == 'finished':
                t_color = 'green'
            elif d.jobstatus == 'failed':
                t_color = 'red'
            else:
                t_color = 'orange'
            if d.jobstatus not in legend_set:
                show_legend = True
                legend_set.add(d.jobstatus)
                exectime_fig.add_trace(
                    go.Scatter(
                        x=[d.creationtime, d.creationtime],
                        y=[d.pandaid, d.pandaid],
                        mode="lines",
                        line=go.scatter.Line(color=t_color),
                        showlegend=True,
                        legendgroup=d.jobstatus,
                        name=d.jobstatus,
                        hoverinfo='skip'
                    )
                )
            exectime_fig.add_trace(
                go.Scatter(
                    x=[d.creationtime, d.endtime],
                    y=[d.pandaid, d.pandaid],
                    mode="lines",
                    line=go.scatter.Line(color=t_color),
                    showlegend=False,
                    legendgroup=d.jobstatus,
                    name="",
                    hovertemplate="PandaID: %{y:d}")
            )
        exectime_fig.update_xaxes(range=[jobs['creationtime'].min(), jobs['endtime'].max()],
                                  title_text='Job Lifetime')
        exectime_fig.update_yaxes(range=[jobs['pandaid'].min() * 0.999, jobs['pandaid'].max() * 1.001],
                                  title_text='PandaID')

        return task_data, site_fig, ram_fig, exectime_fig
Пример #15
0
from jupyter_dash import JupyterDash
import plotly.graph_objects as go
import plotly.express as px
from flask import Flask

import numpy as np  # library to handle data in a vectorized manner

pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

import requests  # library to handle requests

from urllib.request import urlopen
from urllib.request import Request

app = JupyterDash(__name__)

app.config.suppress_callback_exceptions = True

#state_AT = pd.read_csv('C:/Users/Raihan/Downloads/JUPYTER LAB/state_AT.csv')
url = 'https://github.com/Roijin/Covid-Dash-App/blob/808bc92d8a4107a97f98ca836b5050e700aa798e/state_AT.csv?raw=true'

state_AT = pd.read_csv(url)

states = state_AT['code']
cells = state_AT['Cell_Num']
cases = state_AT['Total Cases']

q1, q2, q3 = state_AT['Cell_Num'].quantile([.25, .5, .75])
q4 = state_AT['Cell_Num'].max()
Пример #16
0
# Just replace the standard `dash.Dash` class with the `jupyter_dash.JupyterDash` subclass.

# %%
from jupyter_dash import JupyterDash

# %%
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd

# %% [markdown]
# When running in JupyterHub or Binder, call the `infer_jupyter_config` function to detect the proxy configuration.

# %%
JupyterDash.infer_jupyter_proxy_config()

# %% [markdown]
# Load and preprocess data

# %%
df = pd.read_csv('https://plotly.github.io/datasets/country_indicators.csv')
available_indicators = df['Indicator Name'].unique()

# %% [markdown]
# Construct the app and callbacks

# %%
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
Пример #17
0

# In[41]:


import plotly
import plotly.graph_objects as go 
# import dash
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

external_stylesheets=[{'crossorigin':'anonymous','rel':'stylesheet','href':"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"}]

app = JupyterDash(__name__,external_stylesheets=external_stylesheets)
# app = dash.Dash(__name__)
server = app.server
site_indicators = result['Site'].unique().tolist()
all_options={}
config={"editable":True, "edits":{"shapePosition": False}, #"scrollZoom": False,
    'modeBarButtonsToAdd':['drawline',
#                                         'drawopenpath',
#                                         'drawclosedpath',
                                        'drawcircle',
                                        'drawrect',
                                        'eraseshape'
                                       ],
       'modeBarButtonsToRemove':['lasso2d',
#                                         'drawopenpath',
#                                         'drawclosedpath',
Пример #18
0
# replace invalid values in 'Installs', 'Size' and 'Price' columns with nans
df['Price'] = df['Price'].replace('Everyone', np.nan)
df['Installs'] = df['Installs'].replace('Free', np.nan)
df['Size'] = df['Size'].replace('Varies with device', np.nan)

# convert the column type
df['Installs'] = pd.to_numeric(df['Installs'])
df['Size'] = pd.to_numeric(df['Size'])
df['Price'] = pd.to_numeric(df['Price'])

# drop the invalid value from 'Type' column
df.drop(df.index[df['Type'] == '0'], inplace=True)

#------------------------------------------------------------ build app -------------------------------------------------------------------

app = JupyterDash(__name__)
app.layout = html.Div(children=[
    # All elements from the top of the page
    html.Div([
        html.H1("App Store Dashboard", style={'text-align': 'center'}),
        html.P('Select The Type Of The App:'),
        dcc.Dropdown(id="type_select",
                     options=[{
                         "label": "Free",
                         "value": "Free"
                     }, {
                         "label": "Paid",
                         "value": "Paid"
                     }],
                     multi=False,
                     value="Free",
    df: Input airline data.

Returns:
    Computed average dataframes for carrier delay, weather delay, NAS delay, security delay, and late aircraft delay.
"""
def compute_data_choice_2(df):
    # Compute delay averages
    avg_car = df.groupby(['Month','Reporting_Airline'])['CarrierDelay'].mean().reset_index()
    avg_weather = df.groupby(['Month','Reporting_Airline'])['WeatherDelay'].mean().reset_index()
    avg_NAS = df.groupby(['Month','Reporting_Airline'])['NASDelay'].mean().reset_index()
    avg_sec = df.groupby(['Month','Reporting_Airline'])['SecurityDelay'].mean().reset_index()
    avg_late = df.groupby(['Month','Reporting_Airline'])['LateAircraftDelay'].mean().reset_index()
    return avg_car, avg_weather, avg_NAS, avg_sec, avg_late

# Create a dash application
app = JupyterDash(__name__)
JupyterDash.infer_jupyter_proxy_config()

app.config.suppress_callback_exceptions = True

# Application layout
app.layout = html.Div(children=[
                                html.H1('US Domestic Airline Flights Performance', style={'textAlign': 'center', 'color': '#503D36', 'font-size': 24}),

                                # Create an outer division
                                html.Div([
                                    # Add an division
                                    html.Div([
                                        # Create a division for adding dropdown helper text for report type
                                        html.Div(
                                            [
Пример #20
0
    def __init__(self, model, N_handles=4):
        self.model = model

        # Generate an initial state
        init_state = dict(
            signal_mode='sin',  # sin, am, fm, qpsk_bb, or qpsk_if
            fc=20000,
            fm=2000,
            agc_ref=0.7,
            agc_alpha=0.6,
            agc_window=6,
            agc_graph_mode='time',  # time, const, freq
            t=self.model.t,
            N_handles=N_handles,
            handle_pos=[
                ((i + 1) * self.model.N / self.model.fs / (N_handles + 1), 1)
                for i in range(N_handles)
            ],
        )

        (init_state['i'],
         init_state['q']) = model.ref_signal(init_state['signal_mode'],
                                             init_state['fc'],
                                             init_state['fm'])

        model.agc_cfg(1, init_state['agc_window'], init_state['agc_ref'],
                      init_state['agc_alpha'])

        (init_state['agc_i'], init_state['agc_q'],
         init_state['agc_g']) = model.agc_loopback(init_state['i'],
                                                   init_state['q'])

        # Set preset configurations
        init_state['presets'] = {
            'Default': {
                'signal_mode':
                'sin',
                'fm':
                2000,
                'fc':
                20000,
                'agc_ref':
                0.7,
                'agc_alpha':
                0.7,
                'agc_window':
                64,
                'agc_bypass':
                False,
                'agc_graph_mode':
                'time',
                'handle_pos':
                [(x * self.model.N / self.model.fs, y)
                 for (x, y) in [(0.2, 1.0), (0.4, 1.0), (0.6, 1.0), (0.8, 1.0)]
                 ],
            },
            'Slow fading': {
                'signal_mode':
                'sin',
                'fm':
                2000,
                'fc':
                40000,
                'agc_ref':
                0.7,
                'agc_alpha':
                1.0,
                'agc_window':
                64,
                'agc_bypass':
                False,
                'agc_graph_mode':
                'time',
                'handle_pos':
                [(x * self.model.N / self.model.fs, y)
                 for (x, y) in [(0.1, 1.0), (0.4, 0.2), (0.5, 0.2), (0.9, 1.0)]
                 ],
            },
            'AM envelope preservation': {
                'signal_mode':
                'am',
                'fm':
                8000,
                'fc':
                80000,
                'agc_ref':
                0.4,
                'agc_alpha':
                0.9,
                'agc_window':
                256,
                'agc_bypass':
                False,
                'agc_graph_mode':
                'time',
                'handle_pos':
                [(x * self.model.N / self.model.fs, y)
                 for (x, y) in [(0.1, 1.0), (0.105, 0.1), (0.6,
                                                           0.1), (0.62, 1.0)]],
            },
            'Packet preambles with QPSK': {
                'signal_mode':
                'qpsk_bb',
                'fm':
                8000,
                'fc':
                80000,
                'agc_ref':
                0.7,
                'agc_alpha':
                0.5,
                'agc_window':
                64,
                'agc_bypass':
                False,
                'agc_graph_mode':
                'time',
                'handle_pos':
                [(x * self.model.N / self.model.fs, y)
                 for (x, y) in [(0.18, 0), (0.181, 1.0), (0.68, 1.0), (0.681,
                                                                       0)]],
            },
        }
        self.init_state = init_state
        view = view_template(init_state)

        # Make Dash app
        app = JupyterDash(
            __name__,
            external_stylesheets=[
                dbc.themes.BOOTSTRAP,
                'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css'
            ])
        app.layout = view
        self.app = app

        @app.callback(Output('agc-ref-label', 'children'),
                      [Input('agc-ref', 'value')])
        def update_data_rate_label(f):
            return f'{int(f*100)} %'

        @app.callback(Output('agc-window-label', 'children'),
                      [Input('agc-window', 'value')])
        def update_data_rate_label(f):
            return f'{int(2**f)} Samples'

        @app.callback(Output('agc-alpha-label', 'children'),
                      [Input('agc-alpha', 'value')])
        def update_data_rate_label(f):
            return str(f)

        @app.callback(Output('in-f-data-label', 'children'),
                      [Input('in-f-data', 'value')])
        def update_data_rate_label(f):
            return f'{int(f)} Hz'

        @app.callback(Output('in-f-carrier-label', 'children'),
                      [Input('in-f-carrier', 'value')])
        def update_carrier_label(f):
            return f'{int(f)} kHz'

        @app.callback([
            Output('in-sig-type', 'value'),
            Output('in-f-carrier', 'value'),
            Output('in-f-data', 'value'),
            Output('agc-ref', 'value'),
            Output('agc-alpha', 'value'),
            Output('agc-window', 'value'),
            Output('agc-bypass', 'value'),
            Output('agc-graph-mode', 'value'),
            Output('new-env-preset', 'value'),
        ], [Input('preset-option', 'value')])
        def set_to_preset(preset_name):

            preset = self.init_state['presets'][preset_name]

            # Return new GUI values
            return (preset['signal_mode'], preset['fc'] / 1000, preset['fm'],
                    preset['agc_ref'], preset['agc_alpha'],
                    int(np.log2(preset['agc_window'])), preset['agc_bypass'],
                    preset['agc_graph_mode'], str(preset['handle_pos']))

        @app.callback([
            Output('graph-inputs', 'figure'),
            Output('new-input-signal', 'children')
        ], [
            Input('graph-inputs', 'relayoutData'),
            Input('btn-add-handle', 'n_clicks'),
            Input('btn-rm-handle', 'n_clicks'),
            Input('in-sig-type', 'value'),
            Input('in-f-carrier', 'value'),
            Input('in-f-data', 'value'),
            Input('new-env-preset', 'value'),
        ], [State('graph-inputs', 'figure')])
        def input_stage_callback(_, _btnadd, _btnrm, in_sig_type, in_f_carrier,
                                 in_data_rate, env_preset, fig_in):

            changed_ids = [
                p['prop_id'] for p in dash.callback_context.triggered
            ]
            if 'btn-add-handle' in changed_ids[0]:
                add_envelope_handle(fig_in['layout']['shapes'],
                                    max(self.model.t))
            if 'btn-rm-handle' in changed_ids[0]:
                rm_envelope_handle(fig_in['layout']['shapes'])
            if any(map(lambda x: 'new-env-preset' in x, changed_ids)):
                h_template = get_envelope_handle(fig_in['layout']['shapes'], 0)
                points = ast.literal_eval(env_preset)
                if points:
                    new_shapes = []
                    for (i, (x, y)) in enumerate(points):
                        p = dict(h_template)
                        p.update({
                            'name': 'envelope_' + str(i),
                            'xanchor': x,
                            'yanchor': y,
                        })
                        new_shapes.append(p)
                    fig_in['layout']['shapes'] = new_shapes

            in_f_carrier = in_f_carrier * 1000
            (ref_i, ref_q) = self.model.ref_signal(in_sig_type, in_f_carrier,
                                                   in_data_rate)

            handles = get_envelope_handles(fig_in['layout']['shapes'])
            env = self.model.envelope(handles)
            (trace_i, trace_q) = self.model.test_input((ref_i, ref_q), env)
            trace_t = self.model.t

            fig_in['data'][0]['x'] = trace_t
            fig_in['data'][0]['y'] = trace_i
            fig_in['data'][1]['x'] = trace_t
            fig_in['data'][1]['y'] = trace_q
            return fig_in, [
                f'{in_sig_type} {in_f_carrier} {in_data_rate}, {handles}'
            ]

        @app.callback(Output('graph-agc', 'figure'), [
            Input('new-input-signal', 'children'),
            Input('agc-ref', 'value'),
            Input('agc-alpha', 'value'),
            Input('agc-window', 'value'),
            Input('agc-bypass', 'value'),
            Input('agc-graph-mode', 'value')
        ], [State('graph-inputs', 'figure'),
            State('graph-agc', 'figure')])
        def agc_stage_callback(_, agc_ref, agc_alpha, agc_window, agc_bypass,
                               graph_mode, fig_in, fig_agc):
            # TODO Check if State uses client... if so, remove the graph-inputs state arg to avoid round trip for no reason
            agc_en = 0 if agc_bypass else 1
            self.model.agc_cfg(agc_en, agc_window, agc_ref, agc_alpha)

            (trace_i, trace_q) = (fig_in['data'][0]['y'],
                                  fig_in['data'][1]['y'])
            (agc_i, agc_q, agc_g) = self.model.agc_loopback(trace_i, trace_q)
            trace_t = self.model.t

            if graph_mode == 'time':
                fig_agc['data'][0]['x'] = trace_t
                fig_agc['data'][0]['y'] = agc_i
                fig_agc['data'][1]['x'] = trace_t
                fig_agc['data'][1]['y'] = agc_q
                fig_agc['data'][2]['x'] = trace_t
                fig_agc['data'][2]['y'] = agc_g
                fig_agc['layout']['xaxis']['title'] = "Time (s)"
                fig_agc['layout']['yaxis']['title'] = "Normalised Amplitude"
                fig_agc['layout']['shapes'] = [
                    dict(
                        visible=True,
                        type='rect',
                        editable=False,
                        layer='below',
                        opacity=0.6,
                        fillcolor='#DCD8EA',
                        xref='x',
                        x0=self.model.t[-1] - (2**agc_window / self.model.fs),
                        x1=self.model.t[-1],
                        yref='y',
                        y0=-1,
                        y1=1,
                        line={'width': -1},
                    )
                ]
            if graph_mode == 'const':
                fig_agc['data'][0]['x'] = agc_i
                fig_agc['data'][0]['y'] = agc_q
                fig_agc['data'][1]['x'] = []
                fig_agc['data'][1]['y'] = []
                fig_agc['data'][2]['x'] = []
                fig_agc['data'][2]['y'] = []
                fig_agc['layout']['xaxis']['title'] = "I Amplitude"
                fig_agc['layout']['yaxis']['title'] = "Q Amplitude"
                fig_agc['layout']['shapes'] = []
            if graph_mode == 'freq':
                (freq_x, freq_y) = self.model.calc_fft(agc_i, agc_q)
                fig_agc['data'][0]['x'] = freq_x
                fig_agc['data'][0]['y'] = freq_y
                fig_agc['data'][1]['x'] = []
                fig_agc['data'][1]['y'] = []
                fig_agc['data'][2]['x'] = []
                fig_agc['data'][2]['y'] = []
                fig_agc['layout']['xaxis']['title'] = "Frequency (Hz)"
                fig_agc['layout']['yaxis']['title'] = "Power dB"
                fig_agc['layout']['shapes'] = []

            return fig_agc
Пример #21
0
from jupyter_dash import JupyterDash

from nkicap.gradient import cap_to_gradient
from nkicap.utils import get_project_path

gradient_space = cap_to_gradient(
    Path(get_project_path()) / "data/cap_gradient_space.tsv"
)

gradient_space["type"] = None
mask_group = gradient_space["participant_id"] == "group"
gradient_space.loc[mask_group, "type"] = "group"
gradient_space.loc[~mask_group, "type"] = "sub"


app = JupyterDash(__name__)
app.layout = html.Div(
    [
        dcc.Graph(id="gradient-space"),
        html.P("CAP label"),
        dcc.Checklist(
            id="cap-label",
            options=[{"label": f"{i}", "value": f"{i}"} for i in range(1, 9)],
            value=["1", "2"],
            labelStyle={"display": "inline-block"},
        ),
    ]
)


@app.callback(Output("gradient-space", "figure"), [Input("cap-label", "value")])
Пример #22
0
from crystal_toolkit.helpers.layouts import Columns, Column
from crystal_toolkit.settings import SETTINGS
from jupyter_dash import JupyterDash
from pydefect.analyzer.calc_results import CalcResults
from pydefect.analyzer.dash_components.cpd_energy_dash import CpdEnergyComponent
from pydefect.chem_pot_diag.chem_pot_diag import ChemPotDiag, CpdPlotInfo,     CompositionEnergy
from pydefect.corrections.manual_correction import ManualCorrection
from pydefect.input_maker.defect_entry import DefectEntry
from pymatgen import Composition, Structure, Lattice, Element
import dash_html_components as html
import crystal_toolkit.components as ctc
from dash.dependencies import Input, Output, State
import json

app = JupyterDash(suppress_callback_exceptions=True,
               assets_folder=SETTINGS.ASSETS_PATH)
from vise.analyzer.band_edge_properties import BandEdge

comp_energies = [
    CompositionEnergy(Composition("Mg"), 0.0, "a"),
    CompositionEnergy(Composition("Ca"), 0.0, "a"),
    CompositionEnergy(Composition("Sr"), 0.0, "a"),
    CompositionEnergy(Composition("O"), 0.0, "a"),
    CompositionEnergy(Composition("H"), 0.0, "a"),
#    CompositionEnergy(Composition("MgCaO3"), -100.0, "a"),
    CompositionEnergy(Composition("MgCaSrO3"), -100.0, "a"),
]
#cpd = ChemPotDiag(comp_energies, target=Composition("MgCaO3"))
cpd = ChemPotDiag(comp_energies, target=Composition("MgCaSrO3"))
cpd_plot_info = CpdPlotInfo(cpd)
Пример #23
0
                color_discrete_map={
                    'male': 'blue',
                    'female': 'red'
                })
gss_p6.update(layout=dict(title=dict(x=0.5)))
gss_p6.update_layout(showlegend=False)

mycol_ch2 = [
    'satjob', 'relationship', 'male_breadwinner', 'men_bettersuited',
    'child_suffer', 'men_overwork'
]
cat_columns3 = ['sex', 'region', 'education']
anes_ft2 = gss_clean[mycol_ch2 + cat_columns3].dropna()
anes_ft2['index_col'] = anes_ft2.index

app = JupyterDash(__name__, external_stylesheets=external_stylesheets)
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
colors = {'background': '#111111', 'text': '#7FDBFF'}

table.update_layout(plot_bgcolor=colors['background'],
                    paper_bgcolor=colors['background'],
                    font_color=colors['text'])

gss_p3.update_layout(plot_bgcolor=colors['background'],
                     paper_bgcolor=colors['background'],
                     font_color=colors['text'])

app.layout = html.Div([
    html.H1("Wage gap study"),
    dcc.Markdown(style={
        "background-color": "yellow",
Пример #24
0
import pandas as pd
! pip install dash==0.36.0rc1
! pip install dash_html_components
! pip install dash_core_components
import dash
! pip install jupyter-dash
from jupyter_dash import JupyterDash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
import plotly.graph_objects as go
import plotly.express as px


# Create a dash application
app = JupyterDash(__name__)
JupyterDash.infer_jupyter_proxy_config()

# REVIEW1: Clear the layout and do not display exception till callback gets executed
app.config.suppress_callback_exceptions = True

# Read the airline data into pandas dataframe
airline_data =  pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/airline_data.csv', 
                            encoding = "ISO-8859-1",
                            dtype={'Div1Airport': str, 'Div1TailNum': str, 
                                   'Div2Airport': str, 'Div2TailNum': str})


# List of years 
year_list = [i for i in range(2005, 2021, 1)]
    if selected_value == 1:
        return random.choice([
            "/content/network-snapshot-000480.pkl",
            "/content/network-snapshot-000492.pkl",
        ])
    else:
        return random.choice([
            "/content/network-snapshot-000612.pkl",
            "/content/network-snapshot-000624.pkl",
            "/content/network-snapshot-000636.pkl",
        ])


img_no = 50

app = JupyterDash(external_stylesheets=[dbc.themes.DARKLY])
server = app.server

navbar = dbc.NavbarSimple(
    children=[
        dbc.NavItem(
            dbc.NavLink(
                "Github Repo",
                href="https://github.com/mphirke/fire-emblem-fake-portaits-GBA",
                target="_blank",
                style={"font-weight": "bold"},
            )),
    ],
    style={
        "margin-bottom": "20px",
        "padding": "5px"
Пример #26
0
    def DashBoard(self, pos):
        #creating web app name
        app = JupyterDash(__name__)

        #colors and style
        colors = {'background': "darkslategrey", 'text': "cyan"}
        style = {'textAlign': 'right', 'color': "cyan"}

        app.layout = html.Div(
            style={'backgroundColor': colors['background']},
            children=[
                html.H1(
                    children="Backtesting Forex Strategy",  #header
                    style={
                        'textAlign': 'center',
                        'color': colors['text']
                    }),
                html.Div([  #division for plotting
                    html.Label(['Forex strategy type'], style=style),
                    dcc.Dropdown(  # dropdown method
                        id='my_dropdown',
                        options=[
                            {
                                'label': 'Long only',
                                'value': 'P&L_Buy'
                            },  #dropdown labels
                            {
                                'label': 'Short only',
                                'value': 'P&L_Sell'
                            },
                            {
                                'label': 'Long-Short',
                                'value': 'P&L'
                            },
                        ],
                        value='P&L',
                        multi=False,
                        clearable=False,
                        style={"width": "50%"}),
                ]),
                html.Div([
                    html.Label(
                        ["Strategy Report"],  #label for the each division
                        style=style),
                    html.Label(["P&L for the strategy"], style=style),
                    dcc.Graph(id='the_graph')
                ]),  #we plot here by taking the id of that plot  
            ])

        @app.callback(  #callback function for chnage in input of dropdown
            Output(component_id='the_graph', component_property='figure'),
            [Input(component_id='my_dropdown', component_property='value')])
        def update_graph(my_dropdown):

            if (my_dropdown == "P&L"):
                df = pos
                fig_ = go.Figure()
                fig_.add_traces(data=go.Scatter(y=pos['P&L'], name="P&L_"))
                fig_.update_layout(title="P&L from both long and short",
                                   title_x=0.5,
                                   plot_bgcolor=colors['background'],
                                   paper_bgcolor=colors['text'],
                                   xaxis_title="Toatal Data",
                                   yaxis_title="Profit",
                                   width=1300,
                                   height=500,
                                   xaxis={'showgrid': False},
                                   yaxis={'showgrid': False})
            elif (my_dropdown == "P&L_Buy"):
                df = pos
                fig_ = go.Figure()
                fig_.add_traces(data=go.Scatter(y=pos['P&L'].loc[pos.loc[
                    pos['Pred'] == 1].index],
                                                name="P&L_"))
                fig_.update_layout(title="P&L from long only",
                                   title_x=0.5,
                                   plot_bgcolor=colors['background'],
                                   paper_bgcolor=colors['text'],
                                   xaxis_title="Total Data",
                                   yaxis_title="Profit",
                                   width=1300,
                                   height=500,
                                   xaxis={'showgrid': False},
                                   yaxis={'showgrid': False})
            elif (my_dropdown == "P&L_Sell"):
                df = pos
                fig_ = go.Figure()
                fig_.add_traces(data=go.Scatter(y=pos['P&L'].loc[pos.loc[
                    pos['Pred'] == 0].index],
                                                name="P&L_"))
                fig_.update_layout(title="P&L from short only",
                                   title_x=0.5,
                                   plot_bgcolor=colors['background'],
                                   paper_bgcolor=colors['text'],
                                   xaxis_title="Total Data",
                                   yaxis_title="Profit",
                                   width=1300,
                                   height=500,
                                   xaxis={'showgrid': False},
                                   yaxis={'showgrid': False})
            return (fig_)

        app.run_server(mode='external', port=9181)
        return
# Import required libraries
import pandas as pd
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash
import plotly.graph_objects as go
import plotly.express as px
from dash import no_update


# Create a dash application
app = JupyterDash(__name__)
JupyterDash.infer_jupyter_proxy_config()

# REVIEW1: Clear the layout and do not display exception till callback gets executed
app.config.suppress_callback_exceptions = True

# Read the airline data into pandas dataframe
airline_data =  pd.read_csv('https://cf-courses-data.s3.us.cloud-object-storage.appdomain.cloud/IBMDeveloperSkillsNetwork-DV0101EN-SkillsNetwork/Data%20Files/airline_data.csv', 
                            encoding = "ISO-8859-1",
                            dtype={'Div1Airport': str, 'Div1TailNum': str, 
                                   'Div2Airport': str, 'Div2TailNum': str})


# List of years 
year_list = [i for i in range(2005, 2021, 1)]

"""Compute graph data for creating yearly airline performance report 
Пример #28
0
from callbacks import register_callbacks

###############################################################################
# Start coding

# For the structure of the app, I took Phillippe's advice from this thread:
# https://community.plotly.com/t/dash-callback-in-a-separate-file/14122/15

##### Use Dash if running the script in Anaconda prompt #####
##### Use JupyterDash if running in Spyder (or Jupyter Notebook) #####

shell = ''
try:
    shell = get_ipython().__class__.__name__
    if shell == 'ZMQInteractiveShell':
        app = JupyterDash(__name__,
                          external_stylesheets=[dbc.themes.BOOTSTRAP])
    elif shell == 'TerminalInteractiveShell':
        app = dash.Dash(__name__)
        # , external_stylesheets =[dbc.themes.BOOTSTRAP]
    else:
        app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
except NameError:
    app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

app.layout = layout
# app.layout = html.Div([layout])
register_callbacks(app)

app.config.suppress_callback_exceptions = True

if __name__ == '__main__':
Пример #29
0
# Copyright (C) 2021, RTE (http://www.rte-france.com/)
# See AUTHORS.txt
# SPDX-License-Identifier: MPL-2.0
"""
This file handles the html entry point of the application through dash components.
It will generate the layout of a given page and handle the routing
"""

import dash_bootstrap_components as dbc

# from dash import Dash
from jupyter_dash import JupyterDash

# We need to create app before importing the rest of the project as it uses @app decorators
JupyterDash.infer_jupyter_proxy_config(
)  # for binder or jupyterHub for instance
app = JupyterDash(__name__, external_stylesheets=[
    dbc.themes.BOOTSTRAP
])  # ,server_url="http://127.0.0.1:8050/")
"""
Get Imports to create layout and callbacks 
"""
from grid2viz.main_callbacks import register_callbacks_main
from grid2viz.layout import make_layout as layout

from grid2viz.src.episodes.episodes_clbk import register_callbacks_episodes
from grid2viz.src.overview.overview_clbk import (
    register_callbacks_overview, )  # as overview_clbk
from grid2viz.src.macro.macro_clbk import register_callbacks_macro  # as macro_clbk
from grid2viz.src.micro.micro_clbk import register_callbacks_micro  # as micro_clbk
"""
Пример #30
0
# code and plot setup
# settings
pd.options.plotting.backend = "plotly"
countdown = 20
#global df

# sample dataframe of a wide format
cols = ['temperature']
X = np.ones(50) * 18
df = pd.DataFrame(X, columns=cols)

# plotly figure
fig = df.plot(template='plotly_dark')

app = JupyterDash(__name__)
app.layout = html.Div([
    html.H1("Winecellar temperatures"),
    dcc.Interval(
        id='interval-component',
        interval=20 * 1000,  # in milliseconds
        n_intervals=0),
    dcc.Graph(id='graph'),
])


# Define callback to update graph
@app.callback(Output('graph', 'figure'),
              [Input('interval-component', "n_intervals")])
def streamFig(value):