Пример #1
0
         [
             html.Div(dbc.Card(dbc.CardBody([
                 dcc.Dropdown(id='graph_options',
                              options=var_options,
                              value=[
                                  'Eerste donatie', 'Terugkerende donatie',
                                  'Derde donatie'
                              ],
                              multi=True)
             ]),
                               className="dash-bootstrap"),
                      className="dash-bootstrap"),
             dcc.Graph(id='donaties-graph'),
             html.Div(
                 daq.BooleanSwitch(id='switch_mean_sum',
                                   on=True,
                                   labelPosition="top",
                                   color='#FFFF00')),
             html.Div(
                 id='boolean-switch-output',
                 style={
                     'textAlign': 'center'  #'color': colors['text'],
                 })
         ],
         width={
             "size": 8,
             "offset": 2
         })
 ]),
 html.Br(),
 html.Br(),
 #lines
Пример #2
0
                # ),

                #html.Div(children=[
                html.Label(id='label-constitutive-model-formula',
                           children='Principal Cauchy Stress',
                           style={'marginBottom': '0.5em'}),
                html.Img(id='constitutive-model-formula',
                         src=app.get_asset_url('Ogden.svg'),
                         width='100%',
                         style={'marginBottom': '2em'}),
                #], style={'marginBottom': '1em'}),
                dbc.Row([
                    daq.BooleanSwitch(
                        id='toggle-fit-mode',
                        on=False,
                        #label='True / Engineering',
                        #labelPosition='bottom',
                        color=sorored,
                        style={'padding': '10px'}),
                    html.Label('Model selection : Manual/Auto'),
                ]),
                dbc.Row([
                    daq.BooleanSwitch(
                        id='toggle-data-type',
                        on=False,
                        #label='True / Engineering',
                        #labelPosition='bottom',
                        color=sorored,
                        style={'padding': '10px'}),
                    html.Label('Data type: True/Engineering'),
                ]),
Пример #3
0
                   max=1000,
                   marks={
                       0: {
                           'label': 'Journey Start',
                           'style': {
                               'color': '#77b0b1'
                           }
                       },
                       1000: {
                           'label': 'Journey End',
                           'style': {
                               'color': '#77b0b1'
                           }
                       },
                   }),
        daq.BooleanSwitch(id='active-view', on=False, label='Reorient')
    ]),
])

#######################################################################################################################


# TODO: Create Class
def get_route(address_start, address_end):
    """
    :param address_start: User-readable text address for lat/lon encoding
    :param address_end: User-readable text address for lat/lon encoding
    :returns: path: List of lat/long pairs along navigation trajectory between
              address_start and address_end
              waypoints: List of lat/long pairs that represent a navigation inflection
              instructions: List of html instructions that describe the points of inflection
Пример #4
0
def charts_layout(df, settings, **inputs):
    """
    Builds main dash inputs with dropdown options populated with the columns of the dataframe associated with the
    page. Inputs included are: chart tabs, query, x, y, z, group, aggregation, rolling window/computation,
    chart per group toggle, bar sort, bar mode, y-axis range editors

    :param df: dataframe to drive the charts built on page
    :type df: :class:`pandas:pandas.DataFrame`
    :param settings: global settings associated with this dataframe (contains properties like "query")
    :type param: dict
    :return: dash markup
    """
    chart_type, x, y, z, group, agg = (inputs.get(p) for p in ['chart_type', 'x', 'y', 'z', 'group', 'agg'])
    y = y or []
    show_input = show_input_handler(chart_type)
    show_cpg = show_chart_per_group(**inputs)
    show_yaxis = show_yaxis_ranges(**inputs)
    bar_style, barsort_input_style = bar_input_style(**inputs)
    animate_style, animate_by_style, animate_opts = animate_styles(df, **inputs)

    options = build_input_options(df, **inputs)
    x_options, y_multi_options, y_single_options, z_options, group_options, barsort_options, yaxis_options = options
    query_placeholder = (
        "Enter pandas query (ex: col1 == 1)"
    )
    query_value = inputs.get('query') or inner_build_query(settings, settings.get('query'))
    query_label = html.Div([
        html.Span('Query'),
        html.A(html.I(className='fa fa-info-circle ml-4'),
               href='https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-query',
               target='_blank', style={'color': 'white'})
    ], className='input-group-addon', style={'minWidth': '7em'})
    yaxis_type = (inputs.get('yaxis') or {}).get('type') or 'default'
    yaxis_type_style = {'borderRadius': '0 0.25rem 0.25rem 0'} if yaxis_type == 'default' else None
    show_map = chart_type == 'maps'
    map_props = ['map_type', 'loc_mode', 'loc', 'lat', 'lon', 'map_val']
    map_type, loc_mode, loc, lat, lon, map_val = (inputs.get(p) for p in map_props)
    map_scope, proj = (inputs.get(p) for p in ['scope', 'proj'])
    loc_options, lat_options, lon_options, map_val_options = build_map_options(df, type=map_type, loc=loc, lat=lat,
                                                                               lon=lon, map_val=map_val)
    cscale_style = colorscale_input_style(**inputs)
    default_cscale = 'Greens' if chart_type == 'heatmap' else 'Reds'

    group_val_style, main_input_class = main_inputs_and_group_val_display(inputs)
    group_val = [json.dumps(gv) for gv in inputs.get('group_val') or []]

    def show_style(show):
        return {'display': 'block' if show else 'none'}

    def show_map_style(show):
        return {} if show else {'display': 'none'}
    return html.Div([
        dcc.Store(id='query-data', data=inputs.get('query')),
        dcc.Store(id='input-data', data={k: v for k, v in inputs.items() if k not in ['cpg', 'barmode', 'barsort']}),
        dcc.Store(id='chart-input-data', data={k: v for k, v in inputs.items() if k in ['cpg', 'barmode', 'barsort']}),
        dcc.Store(
            id='map-input-data',
            data={k: v for k, v in inputs.items() if k in ['map_type', 'map_code', 'lat', 'lon', 'map_val', 'scope',
                                                           'proj']}
        ),
        dcc.Store(id='range-data'),
        dcc.Store(id='yaxis-data', data=inputs.get('yaxis')),
        dcc.Store(id='last-chart-input-data', data=inputs),
        dcc.Input(id='chart-code', type='hidden'),
        html.Div(html.Div(dcc.Tabs(
            id='chart-tabs',
            value=chart_type or 'line',
            children=[build_tab(t.get('label', t['value'].capitalize()), t['value']) for t in CHARTS],
            style=dict(height='36px')
        ), className='col-md-12'), className='row pt-3 pb-3 charts-filters'),
        html.Div(html.Div([
            html.Div([
                query_label, dcc.Input(
                    id='query-input', type='text', placeholder=query_placeholder, className='form-control',
                    value=query_value, style={'lineHeight': 'inherit'})
            ], className='input-group mr-3')],
            className='col'
        ), className='row pt-3 pb-3 charts-filters'),
        html.Div(
            [html.Div([
                html.Div(
                    [
                        build_input(
                            [html.Div('X'), html.Small('(Agg By)')],
                            dcc.Dropdown(
                                id='x-dropdown',
                                options=x_options,
                                placeholder='Select a column',
                                value=x,
                                style=dict(width='inherit'),
                            ),
                            label_class='input-group-addon d-block pt-1 pb-0'
                        ),
                        build_input(
                            'Y',
                            dcc.Dropdown(
                                id='y-multi-dropdown',
                                options=y_multi_options,
                                multi=True,
                                placeholder='Select a column(s)',
                                style=dict(width='inherit'),
                                value=y if show_input('y', 'multi') else None
                            ),
                            className='col',
                            id='y-multi-input',
                            style=show_style(show_input('y', 'multi'))
                        ),
                        build_input(
                            [html.Div('Y'), html.Small('(Agg By)')],
                            dcc.Dropdown(
                                id='y-single-dropdown',
                                options=y_single_options,
                                placeholder='Select a column',
                                style=dict(width='inherit'),
                                value=y[0] if show_input('y') and len(y) else None
                            ),
                            className='col',
                            label_class='input-group-addon d-block pt-1 pb-0',
                            id='y-single-input',
                            style=show_style(show_input('y'))
                        ),
                        build_input('Z', dcc.Dropdown(
                            id='z-dropdown',
                            options=z_options,
                            placeholder='Select a column',
                            style=dict(width='inherit'),
                            value=z
                        ), className='col', id='z-input', style=show_style(show_input('z'))),
                        build_input(
                            'Group',
                            dcc.Dropdown(
                                id='group-dropdown',
                                options=group_options,
                                multi=True,
                                placeholder='Select a group(s)',
                                value=group,
                                style=dict(width='inherit'),
                            ),
                            className='col',
                            id='group-input',
                            style=show_style(show_input('group'))
                        )
                    ],
                    id='non-map-inputs', style={} if not show_map else {'display': 'none'},
                    className='row p-0 charts-filters'
                ),
                html.Div(
                    [
                        build_map_type_tabs(map_type),
                        html.Div(
                            [
                                html.Div(
                                    [
                                        build_loc_mode_hover(loc_mode),
                                        dcc.Dropdown(
                                            id='map-loc-mode-dropdown',
                                            options=[build_option(v) for v in ["ISO-3", "USA-states", "country names"]],
                                            style=dict(width='inherit'),
                                            value=loc_mode
                                        )
                                    ],
                                    className='input-group mr-3',
                                )
                            ],
                            id='map-loc-mode-input', style=show_map_style(map_type == 'choropleth'),
                            className='col-auto'
                        ),
                        build_input(
                            [html.Div('Locations'), html.Small('(Agg By)')],
                            dcc.Dropdown(
                                id='map-loc-dropdown',
                                options=loc_options,
                                placeholder='Select a column',
                                value=loc,
                                style=dict(width='inherit'),
                            ),
                            id='map-loc-input',
                            label_class='input-group-addon d-block pt-1 pb-0',
                            style=show_map_style(map_type == 'choropleth')
                        ),
                        build_input(
                            [html.Div('Lat'), html.Small('(Agg By)')],
                            dcc.Dropdown(
                                id='map-lat-dropdown',
                                options=lat_options,
                                placeholder='Select a column',
                                value=lat,
                                style=dict(width='inherit'),
                            ),
                            id='map-lat-input',
                            label_class='input-group-addon d-block pt-1 pb-0',
                            style=show_map_style(map_type == 'scattergeo')
                        ),
                        build_input(
                            [html.Div('Lon'), html.Small('(Agg By)')],
                            dcc.Dropdown(
                                id='map-lon-dropdown',
                                options=lon_options,
                                placeholder='Select a column',
                                style=dict(width='inherit'),
                                value=lon
                            ),
                            id='map-lon-input',
                            label_class='input-group-addon d-block pt-1 pb-0',
                            style=show_map_style(map_type == 'scattergeo')
                        ),
                        build_input('Scope', dcc.Dropdown(
                            id='map-scope-dropdown',
                            options=[build_option(v) for v in SCOPES],
                            style=dict(width='inherit'),
                            value=map_scope or 'world'
                        ), id='map-scope-input', style=show_map_style(map_type == 'scattergeo')),
                        html.Div(
                            [
                                html.Div(
                                    [
                                        build_proj_hover(proj),
                                        dcc.Dropdown(
                                            id='map-proj-dropdown',
                                            options=[build_option(v) for v in PROJECTIONS],
                                            style=dict(width='inherit'),
                                            value=proj
                                        )
                                    ],
                                    className='input-group mr-3',
                                )
                            ],
                            id='map-proj-input', style=show_map_style(map_type == 'scattergeo'), className='col-auto'
                        ),
                        build_input('Value', dcc.Dropdown(
                            id='map-val-dropdown',
                            options=map_val_options,
                            placeholder='Select a column',
                            style=dict(width='inherit'),
                            value=map_val
                        )),
                        build_input(
                            'Group',
                            dcc.Dropdown(
                                id='map-group-dropdown',
                                options=group_options,
                                multi=True,
                                placeholder='Select a group(s)',
                                value=inputs.get('map_group'),
                                style=dict(width='inherit'),
                            ),
                            className='col',
                            id='map-group-input'
                        )
                    ],
                    id='map-inputs', className='row pt-3 pb-3 charts-filters',
                    style={} if show_map else {'display': 'none'}
                ),
                html.Div([
                    build_input('Aggregation', dcc.Dropdown(
                        id='agg-dropdown',
                        options=[build_option(v, AGGS[v]) for v in ['raw', 'count', 'nunique', 'sum', 'mean', 'rolling',
                                                                    'corr', 'first', 'last', 'median', 'min', 'max',
                                                                    'std', 'var', 'mad', 'prod', 'pctsum', 'pctct']],
                        placeholder='Select an aggregation',
                        style=dict(width='inherit'),
                        value=agg or 'raw',
                    )),
                    html.Div([
                        build_input('Window', dcc.Input(
                            id='window-input', type='number', placeholder='Enter days',
                            className='form-control text-center', style={'lineHeight': 'inherit'},
                            value=inputs.get('window')
                        )),
                        build_input('Computation', dcc.Dropdown(
                            id='rolling-comp-dropdown',
                            options=[
                                build_option('corr', 'Correlation'),
                                build_option('count', 'Count'),
                                build_option('cov', 'Covariance'),
                                build_option('kurt', 'Kurtosis'),
                                build_option('max', 'Maximum'),
                                build_option('mean', 'Mean'),
                                build_option('median', 'Median'),
                                build_option('min', 'Minimum'),
                                build_option('skew', 'Skew'),
                                build_option('std', 'Standard Deviation'),
                                build_option('sum', 'Sum'),
                                build_option('var', 'Variance'),
                            ],
                            placeholder='Select an computation',
                            style=dict(width='inherit'), value=inputs.get('rolling_comp')
                        ))
                    ], id='rolling-inputs', style=show_style(agg == 'rolling'))
                ], className='row pt-3 pb-3 charts-filters'),
                html.Div(
                    [
                        build_input('Chart Per\nGroup',
                                    html.Div(daq.BooleanSwitch(id='cpg-toggle', on=inputs.get('cpg') or False),
                                             className='toggle-wrapper'),
                                    id='cpg-input', style=show_style(show_cpg), className='col-auto'),
                        build_input('Barmode', dcc.Dropdown(
                            id='barmode-dropdown',
                            options=[
                                build_option('group', 'Group'),
                                build_option('stack', 'Stack'),
                                build_option('relative', 'Relative'),
                            ],
                            value=inputs.get('barmode') or 'group',
                            placeholder='Select a mode',
                        ), className='col-auto addon-min-width', style=bar_style, id='barmode-input'),
                        build_input('Barsort', dcc.Dropdown(
                            id='barsort-dropdown', options=barsort_options, value=inputs.get('barsort')
                        ), className='col-auto addon-min-width', style=barsort_input_style, id='barsort-input'),
                        html.Div(
                            html.Div(
                                [
                                    html.Span('Y-Axis', className='input-group-addon'),
                                    html.Div(
                                        dcc.Tabs(
                                            id='yaxis-type',
                                            value=yaxis_type,
                                            children=get_yaxis_type_tabs(y),
                                        ),
                                        id='yaxis-type-div',
                                        className='form-control col-auto pt-3',
                                        style=yaxis_type_style
                                    ),
                                    dcc.Dropdown(id='yaxis-dropdown', options=yaxis_options),
                                    html.Span('Min:', className='input-group-addon col-auto', id='yaxis-min-label'),
                                    dcc.Input(
                                        id='yaxis-min-input', type='number', className='form-control col-auto',
                                        style={'lineHeight': 'inherit'}
                                    ),
                                    html.Span('Max:', className='input-group-addon col-auto', id='yaxis-max-label'),
                                    dcc.Input(
                                        id='yaxis-max-input', type='number', className='form-control col-auto',
                                        style={'lineHeight': 'inherit'}
                                    )
                                ],
                                className='input-group', id='yaxis-min-max-options',
                            ),
                            className='col-auto addon-min-width', id='yaxis-input',
                            style=show_style(show_yaxis)
                        ),
                        build_input('Colorscale', dcc.Dropdown(
                            id='colorscale-dropdown', options=[build_option(o) for o in COLORSCALES],
                            value=inputs.get('colorscale') or default_cscale
                        ), className='col-auto addon-min-width', style=cscale_style, id='colorscale-input'),
                        build_input(
                            'Animate',
                            html.Div(daq.BooleanSwitch(id='animate-toggle', on=inputs.get('animate') or False),
                                     className='toggle-wrapper'),
                            id='animate-input',
                            style=animate_style,
                            className='col-auto'
                        ),
                        build_input('Animate By', dcc.Dropdown(
                            id='animate-by-dropdown', options=animate_opts,
                            value=inputs.get('animate_by')
                        ), className='col-auto addon-min-width', style=animate_style, id='animate-by-input'),
                    ],
                    className='row pt-3 pb-5 charts-filters', id='chart-inputs'
                )],
                id='main-inputs', className=main_input_class
            ), build_input('Group(s)', dcc.Dropdown(
                id='group-val-dropdown',
                multi=True,
                placeholder='Select a group value(s)',
                value=group_val,
                style=dict(width='inherit'),
            ), className='col-md-4 pt-3 pb-5', id='group-val-input', style=group_val_style)],
            className='row'
        ),
        dcc.Loading(html.Div(id='chart-content', style={'height': '69vh'}), type='circle'),
        dcc.Textarea(id="copy-text", style=dict(position='absolute', left='-110%'))
    ], className='charts-body')
Пример #5
0
                            }),

                        # Regression show Block
                        html.Div(
                            [
                                html.H4("Show Linear Regression"),
                                html.Div([
                                    html.Div("Off",
                                             style={
                                                 "display": "inline-block",
                                                 "verticalAlign": "top",
                                                 "padding-top": "2px"
                                             }),
                                    # Switch
                                    daq.BooleanSwitch(
                                        id="RegressionSwitch",
                                        on=True,
                                        style={"display": "inline-block"}),
                                    html.Div("On",
                                             style={
                                                 "display": "inline-block",
                                                 "verticalAlign": "top",
                                                 "padding-top": "2px"
                                             })
                                ])
                            ],
                            style={
                                "width": "45%",
                                "display": "table-cell",
                                "padding-left": "5%"
                            })
                    ],
Пример #6
0
def serve_layout():
    layout = html.Div([
        html.Div([
            html.Div([
                html.Div([    
                    dcc.Upload([
                        'Drag and Drop or ',
                        html.A('Select a File', id="select-link")
                    ], id="upload")
                ], id="upload-container", className="grid-row"),
                html.Div([
                    html.Img(src="assets/hexagons-white.png", id="tiles-label"),
                    html.Div([
                        dcc.Slider(id="input-tiles", min=100, max=800, step=100, value=400, tooltip={"placement": "bottom", "always_visible": True}),
                    ], id="tiles-container"),
                    html.Img(src="assets/hexagons-white-many.png", id="tiles-label-many"),
                ], id="grid-container-r1", className="grid-row"),
                html.Div([  
                    html.Img(src="assets/3d-cube-white.png", id="radios-label"),
                    dcc.RadioItems(
                        options=[
                            {'label': 'X', 'value': 'x'},
                            {'label': 'Y', 'value': 'y'},
                            {'label': 'Z', 'value': 'z'}
                        ], value='z', id="radio-items"),
                ], id="grid-container-r2", className="grid-row"),
                html.Div([
                    html.Div([
                        html.Label("Min", htmlFor="min-input", id="min-label"),
                        dcc.Input(type="number", value=0, id="min-input")
                    ], id="min-container"),
                    html.Div([
                        html.Label("Max", htmlFor="max-input", id="max-label"),
                        dcc.Input(type="number", value=20, id="max-input")
                    ], id="max-container"),
                ], id="grid-min-max", className="grid-row"),
                html.Div([
                    html.Div([
                        html.Img(src="assets/icon-lw.png", id="lw-label"),
                        daq.BooleanSwitch(id='checklist', on=True),
                    ], id='line-width-container'),
                    dcc.Dropdown(
                        id='colormap-dropdown',
                        options=[
                            {'label': 'Blues', 'value': 'Blues'},
                            {'label': 'Grays', 'value': 'gray'},
                            {'label': 'Viridis', 'value': 'viridis'},
                            {'label': 'Inferno', 'value': 'inferno'},
                        ], value='Blues',
                    ),
                ], id="grid-colormap", className="grid-row"),
            ], id="pannel"),
            html.Div([
                dcc.Loading(id="loading", type="default", children=html.Img(src="assets/default_img.png", id="plt-figure"))
            ], id="canvas")
        ], id="content-container"),
        html.Div([
            html.A("About", id="about", n_clicks=0),
            html.A("View code", id="code", href="https://github.com/MalloryWittwer/voronoi_IPF", target="_blank"),
            dbc.Modal([
                dbc.ModalBody("In a face-centered cubic material, the orientation distribution of misorientation of a large number of crystallites is displayed. The value is averaged in discrete cells that represent equal partitions of the orientation space. The data was gathered in 2021 by Mallory Wittwer in Prof. Matteo Seita\'s group at NTU.", id="modal-body"),
                html.Img(src="assets/figure-about.png", id="modal-image"),
                dbc.ModalFooter(
                    dbc.Button("Close", id="close", className="mr-auto", n_clicks=0), 
                    id="modal-footer"),
            ], id="modal", is_open=False, backdrop=True, centered=True, fade=True),
        ], id="footer-container"),
    ], id="content-wrapper")
    return layout
Пример #7
0
range_layout = go.Layout(
    polar=dict(
        sector=[0, 180],
        radialaxis=dict(visible=True, range=[0, 80]),
        angularaxis=dict(
            rotation=90,
            direction="clockwise",
        ),
    ),
    showlegend=False,
)

layout = html.Div([
    create_div("Values", [
        html.Div([
            daq.BooleanSwitch(label="Distances", id='distances-switch'),
            html.Div(id='analog-raw-div')
        ])
    ]),
    dcc.Interval(
        id='analog-interval-component',
        interval=2 * 1000,  # in milliseconds
        n_intervals=0),
])


@app.callback(Output('analog-raw-div', 'children'),
              [Input('analog-interval-component', 'n_intervals')],
              [State('distances-switch', 'on')])
def update_values(n_intervals, distance_mode):
    data = pd.read_csv('/ramdisk/system.csv')
Пример #8
0
def factor_layout():
    layout = html.Div([
        # controls
        html.Div(
            className="three columns card",
            children=[
                html.Div(
                    className="bg-white user-control",
                    children=[
                        # select entity_type
                        html.Div(
                            className="padding-top-bot",
                            children=[
                                html.H6("select entity type:"),
                                dcc.Dropdown(id='entity-type-selector',
                                             placeholder='select entity type',
                                             options=[{
                                                 'label': name,
                                                 'value': name
                                             } for name in zvt_context.
                                                      entity_schema_map.keys()
                                                      ],
                                             value='stock')
                            ],
                        ),

                        # select code
                        html.Div(
                            className="padding-top-bot",
                            children=[
                                html.H6("select code:"),
                                dcc.Dropdown(id='code-selector',
                                             placeholder='select code')
                            ],
                        ),
                        # select levels
                        html.Div(
                            className="padding-top-bot",
                            children=[
                                html.H6("select levels:"),
                                dcc.Dropdown(
                                    id='levels-selector',
                                    options=[{
                                        'label':
                                        level.name,
                                        'value':
                                        level.value
                                    } for level in (IntervalLevel.LEVEL_1WEEK,
                                                    IntervalLevel.LEVEL_1DAY)],
                                    value='1d',
                                    multi=True)
                            ],
                        ),
                        # select factor
                        html.Div(className="padding-top-bot",
                                 children=[
                                     html.H6("select factor:"),
                                     dcc.Dropdown(
                                         id='factor-selector',
                                         placeholder='select factor',
                                         options=[{
                                             'label':
                                             name,
                                             'value':
                                             name
                                         } for name in zvt_context.
                                                  factor_cls_registry.keys()],
                                         value='TechnicalFactor')
                                 ]),
                        # select data
                        html.Div(children=[
                            html.Div([
                                html.H6(
                                    "related/all data to show in sub graph",
                                    style={"display": "inline-block"}),
                                daq.BooleanSwitch(
                                    id='data-switch',
                                    on=True,
                                    style={
                                        "display": "inline-block",
                                        "float": "right",
                                        "vertical-align": "middle",
                                        "padding": "8px"
                                    }),
                            ], ),
                            dcc.Dropdown(id='data-selector',
                                         placeholder='schema')
                        ],
                                 style={"padding-top": "12px"}),
                        # select properties
                        html.Div(children=[
                            dcc.Dropdown(id='schema-column-selector',
                                         placeholder='properties')
                        ],
                                 style={"padding-top": "6px"}),
                    ])
            ]),
        # Graph
        html.Div(className="nine columns card-left",
                 children=[html.Div(id='factor-details')])
    ])

    return layout
Пример #9
0
        align='center',
    ),  #Row2

    #=========================================================================#
    #=== Row 3
    dbc.Row(
        [
            #=====================================================================#
            #=== Col1
            dbc.Col(
                [
                    dbc.Card(
                        [
                            html.Div([
                                dbc.Row([
                                    daq.BooleanSwitch(
                                        id='boolean_switch_spain', on=False),
                                    dbc.Label('Animate Map')
                                ]),
                            ],
                                     style={
                                         'padding': '0.5rem 0.5rem',
                                     }),
                            dbc.FormGroup(
                                [
                                    #=========================================================#
                                    #=== Map Data Selector
                                    dbc.RadioItems(
                                        id='Spain_Map_Data_to_show',
                                        options=[
                                            {
                                                'label': 'Confirmed',
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_daq as daq

app = dash.Dash(__name__)

app.layout = html.Div([daq.BooleanSwitch(id='my-daq-booleanswitch', on=True)])

if __name__ == '__main__':
    app.run_server(debug=True)
Пример #11
0
def charts_layout(df, **inputs):
    """
    Builds main dash inputs with dropdown options populated with the columns of the dataframe associated with the
    page. Inputs included are: chart tabs, query, x, y, z, group, aggregation, rolling window/computation,
    chart per group toggle, bar sort, bar mode, y-axis range editors

    :param df: dataframe to drive the charts built on page
    :return: dash markup
    """
    [chart_type, x, y, z, group, agg] = [
        inputs.get(p) for p in ['chart_type', 'x', 'y', 'z', 'group', 'agg']
    ]
    y = y or []
    show_input = show_input_handler(chart_type)
    show_cpg = show_chart_per_group(**inputs)
    show_yaxis = show_yaxis_ranges(**inputs)
    bar_style = bar_input_style(**inputs)

    options = build_input_options(df, **inputs)
    x_options, y_multi_options, y_single_options, z_options, group_options, barsort_options, yaxis_options = options
    query_placeholder = ("Enter pandas query (ex: col1 == 1)")
    query_label = html.Div([
        html.Span('Query'),
        html.
        A(html.I(className='fa fa-info-circle ml-4'),
          href=
          'https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-query',
          target='_blank',
          style={'color': 'white'})
    ],
                           className='input-group-addon',
                           style={'min-width': '7em'})
    return html.Div([
        dcc.Store(id='query-data', data=inputs.get('query')),
        dcc.Store(id='input-data',
                  data={
                      k: v
                      for k, v in inputs.items()
                      if k not in ['cpg', 'barmode', 'barsort']
                  }),
        dcc.Store(id='chart-input-data',
                  data={
                      k: v
                      for k, v in inputs.items()
                      if k in ['cpg', 'barmode', 'barsort']
                  }),
        dcc.Store(id='range-data'),
        dcc.Store(id='yaxis-data', data=inputs.get('yaxis')),
        dcc.Store(id='last-chart-input-data', data=inputs),
        html.Div(html.Div(dcc.Tabs(
            id='chart-tabs',
            value=chart_type or 'line',
            children=[
                build_tab(t.get('label', t['value'].capitalize()), t['value'])
                for t in CHARTS
            ],
            style=dict(height='36px')),
                          className='col-md-12'),
                 className='row pt-3 pb-3 charts-filters'),
        html.Div(html.Div([
            html.Div([
                query_label,
                dcc.Input(id='query-input',
                          type='text',
                          placeholder=query_placeholder,
                          className='form-control',
                          value=inputs.get('query'),
                          style={'line-height': 'inherit'})
            ],
                     className='input-group mr-3')
        ],
                          className='col'),
                 className='row pt-3 pb-3 charts-filters'),
        html.Div([
            build_input(
                'X',
                dcc.Dropdown(
                    id='x-dropdown',
                    options=x_options,
                    placeholder='Select a column',
                    value=x,
                    style=dict(width='inherit'),
                )),
            build_input(
                'Y',
                dcc.Dropdown(id='y-multi-dropdown',
                             options=y_multi_options,
                             multi=True,
                             placeholder='Select a column(s)',
                             style=dict(width='inherit'),
                             value=y if show_input('y', 'multi') else None),
                className='col',
                id='y-multi-input',
                style={
                    'display': 'block' if show_input('y', 'multi') else 'none'
                }),
            build_input(
                'Y',
                dcc.Dropdown(
                    id='y-single-dropdown',
                    options=y_single_options,
                    placeholder='Select a column',
                    style=dict(width='inherit'),
                    value=y[0] if show_input('y') and len(y) else None),
                className='col',
                id='y-single-input',
                style={'display': 'block' if show_input('y') else 'none'}),
            build_input(
                'Z',
                dcc.Dropdown(id='z-dropdown',
                             options=z_options,
                             placeholder='Select a column',
                             style=dict(width='inherit'),
                             value=z),
                className='col',
                id='z-input',
                style={'display': 'block' if show_input('z') else 'none'}),
            build_input(
                'Group',
                dcc.Dropdown(
                    id='group-dropdown',
                    options=group_options,
                    multi=True,
                    placeholder='Select a group(s)',
                    value=group,
                    style=dict(width='inherit'),
                ),
                className='col',
                id='group-input',
                style={'display': 'block' if show_input('group') else 'none'}),
        ],
                 className='row pt-3 pb-3 charts-filters'),
        html.Div([
            build_input(
                'Aggregation',
                dcc.Dropdown(
                    id='agg-dropdown',
                    options=[
                        build_option(v, AGGS[v]) for v in [
                            'count', 'nunique', 'sum', 'mean', 'rolling',
                            'corr', 'first', 'last', 'median', 'min', 'max',
                            'std', 'var', 'mad', 'prod'
                        ]
                    ],
                    placeholder='Select an aggregation',
                    style=dict(width='inherit'),
                    value=agg,
                )),
            html.Div([
                build_input(
                    'Window',
                    dcc.Input(id='window-input',
                              type='number',
                              placeholder='Enter days',
                              className='form-control text-center',
                              style={'line-height': 'inherit'},
                              value=inputs.get('window'))),
                build_input(
                    'Computation',
                    dcc.Dropdown(id='rolling-comp-dropdown',
                                 options=[
                                     build_option('corr', 'Correlation'),
                                     build_option('count', 'Count'),
                                     build_option('cov', 'Covariance'),
                                     build_option('kurt', 'Kurtosis'),
                                     build_option('max', 'Maximum'),
                                     build_option('mean', 'Mean'),
                                     build_option('median', 'Median'),
                                     build_option('min', 'Minimum'),
                                     build_option('skew', 'Skew'),
                                     build_option('std', 'Standard Deviation'),
                                     build_option('sum', 'Sum'),
                                     build_option('var', 'Variance'),
                                 ],
                                 placeholder='Select an computation',
                                 style=dict(width='inherit'),
                                 value=inputs.get('rolling_comp')))
            ],
                     id='rolling-inputs',
                     style=dict(
                         display='block' if agg == 'rolling' else 'none'))
        ],
                 className='row pt-3 pb-3 charts-filters'),
        html.Div([
            build_input('Chart Per\nGroup',
                        html.Div(daq.BooleanSwitch(
                            id='cpg-toggle', on=inputs.get('cpg') or False),
                                 className='toggle-wrapper'),
                        id='cpg-input',
                        style={'display': 'block' if show_cpg else 'none'},
                        className='col-auto'),
            build_input('Barmode',
                        dcc.Dropdown(
                            id='barmode-dropdown',
                            options=[
                                build_option('group', 'Group'),
                                build_option('stack', 'Stack'),
                                build_option('relative', 'Relative'),
                            ],
                            value=inputs.get('barmode') or 'group',
                            placeholder='Select a mode',
                        ),
                        className='col-auto addon-min-width',
                        style=bar_style,
                        id='barmode-input'),
            build_input('Barsort',
                        dcc.Dropdown(id='barsort-dropdown',
                                     options=barsort_options,
                                     value=inputs.get('barsort')),
                        className='col-auto addon-min-width',
                        style=bar_style,
                        id='barsort-input'),
            html.Div(html.Div(
                [
                    html.Span('Y-Axis', className='input-group-addon'),
                    dcc.Dropdown(id='yaxis-dropdown', options=yaxis_options),
                    html.Span('Min:', className='input-group-addon col-auto'),
                    dcc.Input(id='yaxis-min-input',
                              type='number',
                              className='form-control col-auto',
                              style={'line-height': 'inherit'}),
                    html.Span('Max:', className='input-group-addon col-auto'),
                    dcc.Input(id='yaxis-max-input',
                              type='number',
                              className='form-control col-auto',
                              style={'line-height': 'inherit'})
                ],
                className='input-group',
            ),
                     className='col-auto addon-min-width',
                     id='yaxis-input',
                     style=dict(display='block' if show_yaxis else 'none')),
        ],
                 className='row pt-3 pb-5 charts-filters'),
        dcc.Loading(html.Div(id='chart-content'), type='circle'),
    ],
                    className='charts-body')
Пример #12
0
     dcc.Dropdown(id='price-data',
                  options=[{
                      'label': i,
                      'value': i
                  } for i in available_price_data],
                  value=available_price_data[0]),
     html.Div(id='fee-rate-bps-display'),
     dcc.Slider(id='fee-rate-bps',
                className='slid',
                min=0,
                max=100,
                step=1,
                value=10),
     daq.BooleanSwitch(
         id='use-vol-weight',
         label="Weight by Inverse Volatility (Antonacci)",
         labelPosition="top",
         on=False)
 ],
          style={
              'width': '49%',
              'display': 'inline-block'
          }),
 html.Div([
     html.Div(id='top-n-display'),
     dcc.Slider(id='top-n',
                className='slid',
                min=1,
                max=30,
                step=1,
                value=2),
Пример #13
0
    def render(self):
        bau_breakdown = self.maybe_bau_breakdown()
        dom_nodes = [
            singleColRow(html.H2(self.model.name)),
            dbc.Row([
                dbc.Col([
                    html.P([
                        dbc.Badge("Sprint Goal",
                                  color="success",
                                  className="mr-1"), self.model.goal
                    ])
                ],
                        width=9),
                dbc.Col([
                    daq.BooleanSwitch(id='goal-completion-toggle',
                                      label='Goal Achieved',
                                      color='#008000',
                                      on=self.model.goal_completed)
                ],
                        width=3)
            ]),
            singleColRow(html.H4("Sprint Summary")),
            singleColRow(
                html.Div(id="planned-unplanned",
                         children=[self.mk_summary_table()],
                         style={
                             'padding-top': 20,
                             'padding-bottom': 20
                         })),
        ]
        # FIXME: When in edit mode we have to add a hidden Div representing
        # the edit button from read only mode, and visa versa.
        # If we don't we get callback errors for which ever button doesn't
        # exist. There should be a better way to account for conditionally
        # rendered dom nodes.
        if self.edit_notes:
            row_children = [
                dbc.Col([
                    html.H4("Notes"),
                    self.editable_notes(self.model.notes),
                    html.Div(id="edit-notes", hidden=True)
                ],
                        width=6)
            ]
        else:
            row_children = [
                dbc.Col([
                    html.H4("Notes"),
                    self.read_only_notes(self.model.notes),
                    html.Div(id="submit-notes", hidden=True),
                    html.Div(id="notes-content", hidden=True)
                ],
                        width=6)
            ]

        if bau_breakdown:
            row_children.append(
                dbc.Col([
                    singleColRow(html.H4("BAU Breakdown")),
                    singleColRow(
                        dcc.Graph(id='bau-breakdown',
                                  figure=bau_breakdown,
                                  config={
                                      'displayModeBar': False,
                                      'fillFrame': True,
                                      'frameMargins': 0
                                  }))
                ],
                        width=6))
        dom_nodes.append(dbc.Row(row_children))
        dom_nodes.extend([
            singleColRow(html.H4("Details", style={'padding-top': 20})),
            singleColRow(
                html.Div(self.details_table(), style={'padding-bottom': 20}))
        ])
        # dom_nodes.append(
        #     dcc.Graph(id="breakdown", figure=self.mk_overview_trace()))
        return dom_nodes
Пример #14
0
                width='20%',
                display='table-cell',
                verticalAlign="middle",
            ),
        ),
    ], style=dict(
        width='100%',
        display='table',
    ),
    ),

    html.Br(),
    html.Button('Show Indicators', id='show-indicators-btn'),
    sd_material_ui.Drawer(id='indicators-drawer', width='20%', docked=False, openSecondary=True,
                          children=sd_material_ui.Paper([
                              daq.BooleanSwitch(label='Simple Moving Average', id='0', on=False, labelPosition='right'),
                              daq.BooleanSwitch(label='Exponential Moving Average', id='1', on=False,
                                                labelPosition='right'),
                              daq.BooleanSwitch(label='Weighted Moving Average', id='2', on=False,
                                                labelPosition='right'),
                              daq.BooleanSwitch(label='Double Exponential Moving Average', id='3', on=False,
                                                labelPosition='right'),
                              daq.BooleanSwitch(label='Triple Exponential Moving Average', id='4', on=False,
                                                labelPosition='right'),
                              daq.BooleanSwitch(label='Triangular Moving Average', id='5', on=False,
                                                labelPosition='right'),
                              daq.BooleanSwitch(label='Kaufman Adaptive Moving Average', id='6', on=False,
                                                labelPosition='right'),
                              daq.BooleanSwitch(label='MESA Adaptive Moving Average', id='7', on=False,
                                                labelPosition='right'),
                              daq.BooleanSwitch(label='Triple Exponential Moving Average', id='8', on=False,
Пример #15
0
def make_explore_page(corpus, table, conc, slug, spec=False):
    """
    Create every tab, as well as the top rows of stuff, and tab container

    Return html.Div
    """
    config = CorpusModel.objects.get(slug=slug)
    slug_div = html.Div(id="slug", title=slug, style={"display": "none"})
    dataset = _build_dataset_space(corpus, config)
    frequencies = _build_frequencies_space(corpus, table, config)
    chart = _build_chart_space(table)
    concordance = _build_concordance_space(corpus, conc, config, slug)
    print(f"Corpus length (debug) {len(corpus)}")
    label = _make_search_name(config.name, len(corpus), 0)  # 0 == english
    search_from = [dict(value=0, label=label)]
    show = html.Button("Show",
                       id="show-this-dataset",
                       style=style.MARGIN_5_MONO)
    show.title = "Show the selected corpus or search result in the Dataset tab"
    clear = html.Button("Clear history",
                        id="clear-history",
                        style=style.MARGIN_5_MONO)
    langselect = html.Div(
        id="langselect-box",
        children=[
            daq.BooleanSwitch(
                theme=DAQ_THEME,
                className="colour-off",
                id="language-switch",
                on=False,  # false == en, true == de; get from user model
                style={
                    "verticalAlign": "top",
                    **style.MARGIN_5_MONO
                },
            ),
            html.Div(
                id="language-text",
                style={
                    "verticalAlign": "bottom",
                    "textAlign": "center",
                    **style.MARGIN_5_MONO
                },
            ),
        ],
        style={"marginRight": "20px"})
    clear.title = "Delete all searches and frequency tables"
    langselect.title = "Select language for the interface"

    dropdown = dcc.Dropdown(
        id="search-from",
        options=search_from,
        value=0,
        disabled=True,
        style={
            **style.VERY_NEAR_FRONT,
            **{
                "fontSize": "12px"
            }
        },
    )

    drop_style = {
        "fontFamily": "monospace",
        "width": "50%",
        **style.HORIZONTAL_PAD_5,
        **style.BLOCK_MIDDLE_35,
        **style.VERY_NEAR_FRONT,
    }
    # remove the paddingTop, which is not needed in explore view
    nav = {k: v for k, v in style.NAV_HEADER.items() if k != "paddingTop"}

    mainlink = "/" if not spec else f"/{slug}"
    img = html.Img(src="../../static/bolt.jpg",
                   height=42,
                   width=38,
                   style=style.BLOCK_MIDDLE_35)
    top_bit = [
        html.A(["buzzword", img], href=mainlink, style=nav),
        # these spaces are used to flash messages to the user if something is wrong
        dcc.ConfirmDialog(id="dialog-search", message=""),
        dcc.ConfirmDialog(id="dialog-table", message=""),
        dcc.ConfirmDialog(id="dialog-chart", message=""),
        dcc.ConfirmDialog(id="dialog-conc", message=""),
        html.Div(dropdown, style=drop_style),
        html.Div(show, style=dict(width="10%", **style.BLOCK_MIDDLE_35)),
        html.Div(clear, style=dict(width="10%", **style.BLOCK_MIDDLE_35)),
        html.Div(langselect,
                 style=dict(**style.BLOCK_MIDDLE_35, **{
                     "float": "right",
                     "marginRight": "10px"
                 })),
    ]
    top_bit = html.Div(top_bit, style=style.VERTICAL_MARGINS)

    tab_headers = dcc.Tabs(
        id="tabs",
        value="dataset",
        style={
            "lineHeight": 0,
            "fontFamily": "monospace",
            "font": "12px Arial",
            "fontWeight": 600,
            "color": "#555555",
            "paddingLeft": "10px",
            "paddingRight": "10px",
        },
        children=[
            dcc.Tab(id="dataset-tab-label", label="DATASET", value="dataset"),
            dcc.Tab(id="freq-tab-label",
                    label="FREQUENCIES",
                    value="frequencies"),
            dcc.Tab(id="chart-tab-label", label="CHART", value="chart"),
            dcc.Tab(id="conc-tab-label",
                    label="CONCORDANCE",
                    value="concordance"),
        ],
    )
    blk = {"display": "block", **style.HORIZONTAL_PAD_5}
    conll_display = html.Div(id="display-dataset", children=[dataset])
    hide = {"display": "none"}

    tab_contents = [
        html.Div(children=[
            html.Div(id="tab-dataset", style=blk, children=[conll_display]),
            html.Div(id="tab-frequencies", style=hide, children=[frequencies]),
            html.Div(id="tab-chart", style=hide, children=[chart]),
            html.Div(id="tab-concordance", style=hide, children=[concordance]),
        ])
    ]

    pad = {"paddingLeft": "10px", "paddingRight": "10px"}
    tab_contents = html.Div(id="tab-contents", children=tab_contents)
    store = _make_storage()
    children = [slug_div, store, top_bit, tab_headers, tab_contents]
    return html.Div(id="everything", children=children, style=pad)
Пример #16
0
def serve_layout():
    """Render layout of webpage.

    Returns
    -------
    Div of application used in web rendering.

    """
    timestamp = Time(0, format="jd")
    init_time_ago = (Time.now() - timestamp).to("min")
    init_time_color = "red"
    session_id = str(uuid.uuid4())

    return html.Div(
        [
            html.Div(session_id, id="session-id", style={"display": "none"}),
            dbc.Row(
                [
                    dbc.Col(
                        html.Small(
                            html.Div(
                                id="auto-time",
                                children=[
                                    html.Span(
                                        "Autocorrelations from ",
                                        style={"font-weight": "bold"},
                                    ),
                                    html.Span(
                                        f"{init_time_ago.value:.0f} {init_time_ago.unit.long_names[0]}s ago ",
                                        style={
                                            "font-weight": "bold",
                                            "color": init_time_color,
                                        },
                                    ),
                                    html.Span(
                                        f"({timestamp.iso} JD:{timestamp.jd:.3f})",
                                        style={"font-weight": "bold"},
                                    ),
                                ],
                                style={"text-align": "center"},
                            ),
                        ),
                        width=10,
                    ),
                ],
                justify="center",
                align="center",
            ),
            dbc.Row(
                [
                    dbc.Col(
                        daq.BooleanSwitch(
                            id="reload-box",
                            on=False,
                            label="Reload Data",
                            labelPosition="top",
                            style={"text-align": "center"},
                        ),
                        width=1,
                    ),
                    html.Label(
                        [
                            "Statistic:",
                            dcc.Dropdown(
                                id="stat-dropdown",
                                options=[
                                    {"label": "Autos", "value": "spectra"},
                                    {"label": "PAM Power", "value": "pam_power"},
                                    {"label": "ADC Power", "value": "adc_power"},
                                    {"label": "ADC RMS", "value": "adc_rms"},
                                    {
                                        "label": "FEM IMU THETA",
                                        "value": "fem_imu_theta",
                                    },
                                    {"label": "FEM IMU PHI", "value": "fem_imu_phi"},
                                    {"label": "EQ COEFFS", "value": "eq_coeffs"},
                                ],
                                multi=False,
                                value="spectra",
                                clearable=False,
                                style={"width": "100%"},
                            ),
                        ],
                        style={"width": "30%"},
                    ),
                    html.Label(
                        [
                            "Node(s):",
                            dcc.Dropdown(
                                id="node-dropdown",
                                options=[{"label": "Unknown Node", "value": "Unknown"}],
                                multi=True,
                                style={"width": "100%"},
                            ),
                        ],
                        style={"width": "30%"},
                    ),
                ],
                justify="center",
                align="center",
            ),
            dcc.Graph(
                id="graph",
                config={"doubleClick": "reset+autosize"},
                style={"height": "72.5vh"},
            ),
            # A timer to re-load data every minute
            # interval value is milliseconds
            dcc.Interval(
                id="interval-component",
                interval=60 * 1000,
                n_intervals=0,
                disabled=True,
            ),
            dcc.Interval(
                id="time-display-interval-component",
                interval=60 * 1000,
                n_intervals=0,
                disabled=False,
            ),
        ],
        style={"height": "100%", "width": "100%"},
    )
Пример #17
0
def direct_dimension_setup():
    return [
        html.H5(
            children='Direct dimension',
            style={
                'textAlign': 'left',
                'color': colors['text']
            }
        ),

        # environment
        html.Div([html.H6('Environment parameters')],
            style={
                'margin-bottom': '5px',
                'margin-top': '35px',
                'color': colors['text']
            }
        ),

        # Nucleus
        html.Label('Nucleus'),
        html.Div(id='nucleus_widget_id', children=[
            dcc.Dropdown(
                id='nucleus_id'
            )],
            style={'margin-bottom': '10px', 'margin-top': '0px'}
        ),

        # Magnetic flux density
        html.Label(id='Magnetic_flux_density_output_container'),
        html.Div([dcc.Slider(
                id='magnetic_flux_density',
                min=0,
                max=30,
                step=0.1,
                value=9.4
            )],
            style={'margin-bottom': '10px', 'margin-top': '0px'}
        ),

        # Magic angle spinning
        html.Label(id='spinning_frequency_output_container'),
        html.Div(className='row', children=[
            dcc.Slider(
                className='col s6 m6 l6',
                id='spinning_frequency_in_kHz_coarse',
                min=0.0,
                max=110,
                step=5.0,
                value=0,
            ),
            dcc.Slider(
                className='col s6 m6 l6',
                id='spinning_frequency_in_kHz_fine',
                min=0,
                max=5,
                step=0.050,
                value=2.5,
            )],
            style={'margin-bottom': '10px', 'margin-top': '0px'}
        ),




        # dimension
        html.Div(className='row', children=[
            html.H6(className='col s6 m6 l6', children='Dimension parameters'),
            daq.BooleanSwitch(
                id='ppm_switch',
                className='col s6 m6 l6',
                label='Show ppm',
                labelPosition='bottom',
                # size=40,
                style={
                    'margin-bottom': '0px',
                    'margin-top': '5px',
                    'color': colors['text']
                }
            )],
            style={
                'margin-bottom': '0px',
                'margin-top': '35px',
                'color': colors['text']
            }
        ),

        # Number of points
        html.Label(id='number_of_points_output_container'),
        html.Div([dcc.Slider(
                id='number_of_points',
                min=8,
                max=16,
                step=1,
                value=10,
                marks={8: '', 9: '', 10: '', 11: '', 12: '', 13: '', 14: '', 15: '', 16: ''}
            )],
            style={'margin-bottom': '10px', 'margin-top': '0px'}
        ),

        # Spectral width
        html.Label(id='frequency_bandwidth_output_container', style={'display': 'block'}),
        html.Div(className='row', children=[
            dcc.Slider(
                className='col s6 m6 l6',
                id='frequency_bandwidth_coarse',
                min=1.0,
                max=1000,
                step=10,
                value=100
            ),
            dcc.Slider(
                className='col s6 m6 l6',
                id='frequency_bandwidth_fine',
                min=0.0,
                max=10,
                step=0.050,
                value=5,
            )],
            style={'margin-bottom': '10px', 'margin-top': '0px'}
        ),

        # Reference offset
        html.Label(id='reference_offset_output_container'),
        html.Div(className='row', children=[
            dcc.Slider(
                className='col s6 m6 l6',
                id='reference_offset_coarse',
                min=0.0,
                max=100,
                step=5,
                value=0,
            ),
            dcc.Slider(
                className='col s6 m6 l6',
                id='reference_offset_fine',
                min=0,
                max=5,
                step=0.050,
                value=2.5,
            )],
        style={'margin-bottom': '10px', 'margin-top': '0px'}
        ),
    ]
Пример #18
0
           })
     ],
                style={
                    "color": "#151516",
                    'font-size': '20px'
                })
 ]),
 dbc.Row([html.Br()]),
 dbc.Row([
     dbc.Col([
         html.H3(id="tsc", style={'display': 'inline-block'}),
         html.Br(),
         html.P("Cummulative", style={'display': 'inline-block'}),
         daq.BooleanSwitch(id='cum-tc',
                           on=False,
                           style={
                               'display': 'inline-block',
                               'size': '20%'
                           }),
         dcc.Graph(id="fig3", figure=plot_total_cases('Daily new cases'))
     ]),
     dbc.Col([
         html.H3(id="tsd", style={'display': 'inline-block'}),
         html.Br(),
         html.P("Cummulative", style={'display': 'inline-block'}),
         daq.BooleanSwitch(id='cum-td',
                           on=False,
                           style={
                               'display': 'inline-block',
                               'size': '20%'
                           }),
         dcc.Graph(id="fig4", figure=plot_total_deaths('Daily new cases'))
Пример #19
0
                     multi=True),
    ]),
    #
    html.Div([
        html.Label('Case'),
        dcc.Dropdown(id="case",
                     options=[{
                         'label': name,
                         'value': name
                     } for name in CASES],
                     value=[],
                     multi=True),
    ]),
    #
    html.Div([
        daq.BooleanSwitch(label='Log Scale', id='log_scale', on=False),
    ]),
    #
    html.Div([dcc.Graph(id="graph")]),
])


# =================================================================
@app.callback(Output("graph", "figure"), [
    Input("country", "value"),
    Input("case", "value"),
    Input('log_scale', 'on')
])
def update_graph(countries, cases, log_scale):

    if len(countries) == 0:
Пример #20
0
                     children=[
                         dcc.Markdown(
                             className=
                             "pretty-markdown-left",
                             children=[
                                 "**Auto-PDF**"
                             ])
                     ]),
             ],
             style={
                 "padding-top": "6px",
             }),
         html.Div(className="three columns",
                  children=[
                      daq.BooleanSwitch(
                          id="pdf-copy",
                          on=True,
                      ),
                  ],
                  style={
                      "padding-top": "6px",
                  }),
         dcc.Markdown(id="pdf-copy-output", )
     ]),
 html.Div(
     className="row padding-top-bot",
     children=[
         html.Div(
             className="four columns centering",
             children=[
                 dcc.Markdown("**Dots**"),
             ],
Пример #21
0
 ],
          className="row"),
 html.Div([
     dcc.Graph(id="my-graph"),
 ], className="row"),
 html.Div(
     [
         html.Span("Legend Visible :  ",
                   className="three columns",
                   style={
                       'textAlign': "left",
                       "padding-top": 2
                   }),
         daq.BooleanSwitch(id="legend",
                           on=True,
                           label=["Hide", "Show"],
                           labelPosition="top",
                           color="#137d1c",
                           className="two columns"),
         html.Span("Legend Orientation :",
                   className="four columns",
                   style={
                       'textAlign': "left",
                       "padding-top": 2
                   }),
         daq.ToggleSwitch(id="position",
                          value=True,
                          label=["Horizontal", "Vertical"],
                          labelPosition="top",
                          className="three columns")
     ],
     className="row",
Пример #22
0
                            daq.Knob(id='light-intensity-knob',
                                     size=110,
                                     color=colors['accent'],
                                     value=0),
                        ],
                    ),
                    # autoscale
                    html.Div(className='status-box-title',
                             children=["autoscale plot"]),
                    html.Div(
                        id='autoscale-switch-container',
                        title='Controls whether the plot automatically resizes \
                to fit the spectra.',
                        children=[
                            daq.BooleanSwitch(id='autoscale-switch',
                                              on=True,
                                              color=colors['accent'])
                        ]),

                    # submit button
                    html.Div(
                        id='submit-button-container',
                        title='Sends all of the control values below the graph \
                to the spectrometer.',
                        children=[
                            html.Button('update',
                                        id='submit-button',
                                        n_clicks=0,
                                        n_clicks_timestamp=0)
                        ]),
Пример #23
0
app.layout = html.Div([
    html.H1(
        "🎥 Netflimap - browse Netflix titles with a map 🎥",
        style={"textAlign": "center"},
    ),
    html.Div(id="df-filtered", style={"display": "none"}),
    html.Hr(),
    html.Div(
        [
            html.Div(
                [
                    dcc.Graph(
                        id="nf-map",
                        figure=get_nf_count_map(df_country_counts_and_titles),
                    ),
                    daq.BooleanSwitch(
                        id="movies-switch", label="Movies", on=True),
                    html.Div(
                        [dcc.RangeSlider(**SLIDERS["movie-len-slider"])],
                        id="div-movie-len-slider",
                        style={"display": "block"},
                    ),
                    daq.BooleanSwitch(
                        id="tv-shows-switch", label="TV Shows", on=True),
                    html.Div(
                        [dcc.RangeSlider(**SLIDERS["n-seasons-slider"])],
                        id="div-n-seasons-slider",
                        style={"display": "block"},
                    ),
                    html.Br(),
                    html.Div(
                        dcc.Input(
Пример #24
0
def _build_frequencies_space(corpus, table, config):
    """
    Build stuff related to the frequency table
    """
    cols = _get_cols(corpus, config.add_governor)
    show_check = dcc.Dropdown(
        placeholder="Features to show",
        multi=True,
        id="show-for-table",
        options=cols,
        value=[],
        style={
            **style.MARGIN_5_MONO,
            **style.NEAR_FRONT
        },
    )
    show_check = html.Div(show_check, style=style.TSTYLE)
    subcorpora_drop = dcc.Dropdown(
        id="subcorpora-for-table",
        options=[dict(value="_corpus", label="Entire corpus")] + cols,
        placeholder="Feature for index",
        style={
            **style.MARGIN_5_MONO,
            **style.NEAR_FRONT
        },
    )
    subcorpora_drop = html.Div(subcorpora_drop, style=style.TSTYLE)
    relative_drop = dcc.Dropdown(
        id="relative-for-table",
        style={
            **style.MARGIN_5_MONO,
            **style.NEAR_FRONT
        },
        options=[
            {
                "label": "Absolute frequency",
                "value": "ff"
            },
            {
                "label": "Relative of result",
                "value": "tf"
            },
            {
                "label": "Relative of corpus",
                "value": "nf"
            },
            {
                "label": "Keyness: log likelihood",
                "value": "fl"
            },
            {
                "label": "Keyness: percent difference",
                "value": "fp"
            },
        ],
        placeholder="Relative/keyness calculation",
    )
    relative_drop = html.Div(relative_drop,
                             style={
                                 **style.TSTYLE,
                                 **{
                                     "width": "21%"
                                 }
                             })
    sort_drop = dcc.Dropdown(
        id="sort-for-table",
        style={
            **style.MARGIN_5_MONO,
            **style.NEAR_FRONT
        },
        options=[
            {
                "label": "Total",
                "value": "total"
            },
            {
                "label": "Infrequent",
                "value": "infreq"
            },
            {
                "label": "Alphabetical",
                "value": "name"
            },
            {
                "label": "Reverse-alphabetical",
                "value": "reverse"
            },
            {
                "label": "Increasing",
                "value": "increase"
            },
            {
                "label": "Decreasing",
                "value": "decrease"
            },
            {
                "label": "Static",
                "value": "static"
            },
            {
                "label": "Turbulent",
                "value": "turbulent"
            },
        ],
        placeholder="Sort columns by...",
    )
    sort_drop = html.Div(sort_drop, style=style.TSTYLE)
    max_row, max_col = settings.TABLE_SIZE
    print(f"Making {max_row}x{max_col} table for {config.name} ...")
    table = table.iloc[:100, :100]

    style_index = style.FILE_INDEX
    style_index["if"]["column_id"] = "year"
    index_name = table.index.name

    table = table.reset_index()

    if "file" in table.columns:
        table["file"] = table["file"].apply(os.path.basename)
        table["file"] = table["file"].str.rstrip(".conllu")
        try:
            table = _add_links(table, slug=config.slug, conc=False)
        except ObjectDoesNotExist:
            pass

    columns, data = _update_frequencies(table, False, False)
    print("Done!")

    freq_table = dcc.Loading(
        type="default",
        children=[
            dash_table.DataTable(
                id="freq-table",
                columns=columns,
                data=data,
                editable=False,
                style_cell={
                    **style.HORIZONTAL_PAD_5,
                    **{
                        "maxWidth": "145px",
                        "minWidth": "60px"
                    },
                },
                filter_action="native",
                sort_action="native",
                sort_mode="multi",
                row_deletable=False,
                selected_rows=[],
                page_current=0,
                page_size=20,
                page_action="native",
                fixed_rows={
                    "headers": True,
                    "data": 0
                },
                #virtualization=True,
                #style_table={"overflowY": "scroll", "overflowX": "hidden"},
                style_header=style.BOLD_DARK,
                style_cell_conditional=style.LEFT_ALIGN,
                style_data_conditional=[{
                    "if": {
                        "column_id": index_name
                    },
                    "backgroundColor": "#fafafa",
                    "color": "#555555",
                    "fontWeight": "bold",
                    "width": "20%",
                }] + style.STRIPES,
                merge_duplicate_headers=True,
                #export_format="xlsx",
                #export_headers="display",
                css=[{
                    "selector": ".show-hide",
                    "rule": "display: none"
                }],
            )
        ],
    )

    sty = {"width": "22%", **style.CELL_MIDDLE_35, **style.MARGIN_5_MONO}

    multi = html.Span(
        children=[
            daq.BooleanSwitch(
                theme=DAQ_THEME,
                id="multiindex-switch",
                on=False,
                disabled=True,
                style={
                    **style.MARGIN_5_MONO,
                    **style.TSTYLE
                },
            ),
            html.Div(
                children="Multicolumn mode",
                id="multiindex-text",
                style={
                    **style.MARGIN_5_MONO,
                    **style.TSTYLE,
                    **{
                        "whiteSpace": "nowrap"
                    },
                },
            ),
        ],
        style={
            **style.CELL_MIDDLE_35,
            **style.TSTYLE
        },
    )
    # disabled in swisslaw
    content = html.Span(
        children=[
            daq.BooleanSwitch(
                theme={
                    **DAQ_THEME,
                    **{
                        "primary": "#47d153"
                    }
                },
                id="content-table-switch",
                on=False,
                style={
                    **style.MARGIN_5_MONO,
                    **style.TSTYLE
                },
            ),
            html.Div(
                children="Show content, not frequency",
                style={
                    **style.MARGIN_5_MONO,
                    **style.TSTYLE
                },
            ),
        ],
        style={
            **style.CELL_MIDDLE_35,
            **style.TSTYLE
        },
    )

    gen = "Generate table"
    generate = html.Button(gen,
                           id="table-button",
                           style={
                               **style.MARGIN_5_MONO,
                               **style.TSTYLE
                           })
    top = html.Div(
        [show_check, subcorpora_drop, sort_drop, relative_drop,
         generate])  # multi, content
    #bottom = html.Div([sort_drop, relative_drop, generate])
    toolbar = html.Div([top], style=style.VERTICAL_MARGINS)  # , bottom
    div = html.Div([toolbar, freq_table])
    return html.Div(id="display-frequencies", children=[div])
Пример #25
0
} for country in df.country.unique()]
default_countries_drop_down = [
    'Germany', 'Italy', 'United_States_of_America', 'United_Kingdom'
]

app.layout = html.Div(children=[
    dcc.Markdown(children=markdown_text),
    dcc.Markdown(children='## Cumulated Cases'),
    html.Label('Select countries:'),
    dcc.Dropdown(id='multi_drop_down_selection_countries',
                 options=options_countries,
                 value=default_countries_drop_down,
                 multi=True),
    html.Button(id='button_update_plot', n_clicks=0, children='update graph'),
    daq.BooleanSwitch(
        id='boolean_switch_log_linear', on=True,
        label='log-linear'),  #, labelPosition='right'), #color="#9B51E0"
    dcc.Graph(id='plot_cases_cumulated'),
])


@app.callback(Output('plot_cases_cumulated', 'figure'), [
    Input('button_update_plot', 'n_clicks'),
    Input('boolean_switch_log_linear', 'on')
], [
    State('multi_drop_down_selection_countries', 'value'),
    State('boolean_switch_log_linear', 'on')
])
def update_plot_cases_cumulated_upon_button_update_plot_pressed(
        n_clicks, _, countries, y_axis_log):
Пример #26
0
def _build_dataset_space(df, config):
    """
    Build the search interface and the conll display
    """
    if isinstance(df, Corpus):
        df = df.files[0].load()
    cols = _get_cols(df, config.add_governor)
    extra = [("Dependencies", "d"), ("Describe thing", "describe")]
    grams = [("Match (default)", 0), ("Bigrams of match", 1),
             ("Trigrams of match", 2)]
    extra = [dict(label=l, value=v) for l, v in extra]
    grams = [dict(label=l, value=v) for l, v in grams]
    cols = extra + cols
    df = _drop_cols_for_datatable(df, config.add_governor)
    df = df.reset_index()
    corpus_size = len(df)
    df = df.iloc[:settings.PAGE_SIZE]
    # no file extensions
    df["file"] = df["file"].str.replace(".conllu", "", regex=False)
    df["file"] = df["file"].str.replace("^.*/conllu/", "", regex=True)
    max_row, max_col = settings.TABLE_SIZE
    if max_row:
        df = df.iloc[:max_row]
    if max_col:
        df = df.iloc[:, :max_col]
    if config.pdfs:
        df = _add_links(df, slug=config.slug, conc=False)
    pieces = [
        dcc.Dropdown(
            id="search-target",
            options=cols,
            value="w",
            # title="Select the column you wish to search (e.g. word/lemma/POS) "
            # + ", or query language (e.g. Tgrep2, Depgrep)",
            style={
                "width": "200px",
                "fontFamily": "monospace"
            },
        ),
        # the matching/not matching button and its text
        html.Div(
            id="matching-box",
            children=[
                daq.BooleanSwitch(
                    theme=DAQ_THEME,
                    className="colour-off",
                    id="skip-switch",
                    on=False,
                    style={
                        "verticalAlign": "top",
                        **style.MARGIN_5_MONO
                    },
                ),
                html.Div(
                    id="matching-text",
                    style={
                        "verticalAlign": "bottom",
                        **style.MARGIN_5_MONO
                    },
                ),
            ],
        ),
        dcc.Input(id="input-box",
                  type="text",
                  placeholder="Enter search query...",
                  size="60",
                  style={
                      **style.MARGIN_5_MONO,
                      **{
                          "fontSize": "14px"
                      }
                  },
                  className="input-lg form-control"),
        html.Div(
            id="regex-box",
            children=[
                daq.BooleanSwitch(
                    theme=DAQ_THEME,
                    className="colour-off",
                    id="use-regex",
                    on=False,
                    style={
                        "verticalAlign": "top",
                        **style.MARGIN_5_MONO
                    },
                ),
                html.Div(
                    id="regex-text",
                    style={
                        "textAlign": "center",
                        "verticalAlign": "bottom",
                        "width": "140px",
                        **style.MARGIN_5_MONO
                    },
                ),
            ],
        ),
        #dcc.Dropdown(
        #    id="gram-select",
        #    options=grams,
        #    # value="",
        #    placeholder="What to return from search",
        #    disabled=False,
        #    style={"width": "240px", "fontFamily": "monospace", **style.FRONT},
        #),
        html.Button("Search", id="search-button"),
    ]
    pieces = [html.Div(piece, style=style.CELL_MIDDLE_35) for piece in pieces]

    search_space = html.Div(pieces,
                            style={
                                "fontFamily": "bold",
                                **style.VERTICAL_MARGINS
                            })
    columns = [{
        "name":
        _capitalize_first(SHORT_TO_COL_NAME.get(i, i)).replace("_", " "),
        "id":
        i,
        "deletable":
        False,
        "hideable":
        True,
        "presentation": ("markdown" if i == "file" else None)
    } for i in df.columns]
    data = df.to_dict("rows")

    conll_table = dash_table.DataTable(
        id="conll-view",
        columns=columns,
        data=data,
        # editable=True,
        style_cell={
            **style.HORIZONTAL_PAD_5,
            **{
                "minWidth": "60px"
            }
        },
        filter_action="custom",
        sort_action="custom",
        sort_mode="multi",
        sort_by=[],
        row_deletable=False,
        selected_rows=[],
        page_action="custom",
        page_current=0,
        page_size=settings.PAGE_SIZE,
        page_count=ceil(corpus_size / settings.PAGE_SIZE),
        # style_as_list_view=True,
        css=[{
            "selector": ".show-hide",
            "rule": "display: none"
        }],
        # virtualization=True,
        # style_table={},
        fixed_rows={
            "headers": True,
            "data": 0
        },
        style_header=style.BOLD_DARK,
        style_cell_conditional=style.LEFT_ALIGN,
        style_data_conditional=style.INDEX + style.STRIPES,
        merge_duplicate_headers=True,
        #export_format="xlsx",
        #export_headers="display",
    )
    # add loading
    conll_table = dcc.Loading(
        type="default",
        id="loading-main",
        fullscreen=True,
        className="loading-main",
        children=conll_table,
    )
    data_space = html.Div([search_space, conll_table])
    div = html.Div(id="dataset-container", children=data_space)
    return html.Div(id="display-dataset-1", children=[div])
Пример #27
0
                 ),
                 dcc.Dropdown(
                     id='period_selection',
                     options=[{
                         'label':
                         i,
                         'value':
                         i
                     } for i in period_options],
                     value='Week'
                     # ,style={'width': '30%', 'display': 'inline-block'}
                 ),
                 dqq.BooleanSwitch(
                     id='change_in_cgi_toggle',
                     on=True,
                     label='Use Change in CGI',
                     labelPosition='top'
                     # ,style={'width': '30%', 'display': 'inline-block'}
                 ),
                 html.Br(),
                 html.Div('Adjust number of Medications to show:'),
                 dcc.Input(
                     id='num_meds_to_show', value=5, type='number')
             ],
             id='hidden_div')
     ])
 ],
 style={
     'width': '48%',
     'float': 'right',
     'display': 'inline-block'
Пример #28
0
def _build_chart_space(table,
                       iterate_over=None,
                       width="95vw",
                       no_from_select=False,
                       height="60vh"):
    """
    Div representing the chart tab
    """
    charts = []
    iterate_over = iterate_over or [
        (1, "stacked_bar"),
        (2, "line"),
        (3, "area"),
        (4, "heatmap"),
        (5, "bar"),
    ]

    for chart_num, kind in iterate_over:
        table_from = [dict(value=0, label=_make_table_name())]
        if not no_from_select:
            dropdown = dcc.Dropdown(
                id=f"chart-from-{chart_num}",
                options=table_from,
                value=0,
                style=style.MARGIN_5_MONO,
            )
        else:
            dropdown = html.Div("", style={"display": "none"})
        types = [
            dict(label=_capitalize_first(i).replace("_", " "), value=i)
            for i in sorted(CHART_TYPES)
        ]
        chart_type = dcc.Dropdown(
            id=f"chart-type-{chart_num}",
            options=types,
            value=kind,
            style=style.MARGIN_5_MONO,
        )
        transpose = daq.BooleanSwitch(
            theme=DAQ_THEME,
            id=f"chart-transpose-{chart_num}",
            on=False,
            style={
                "verticalAlign": "middle",
                "marginLeft": "10px",
                "marginRight": "10px"
            },
        )
        top_n = dcc.Input(id=f"chart-top-n-{chart_num}",
                          placeholder="Results to plot",
                          type="number",
                          min=1,
                          max=99,
                          value=7,
                          style={
                              **style.MARGIN_5_MONO,
                              **{
                                  "marginRight": "20px"
                              }
                          },
                          className="form-control input-lg")
        update = html.Button("Update", id=f"figure-button-{chart_num}")

        toolbar = [dropdown, chart_type, top_n, transpose, update]
        widths = {
            dropdown: "60%" if not no_from_select else "0%",
            chart_type: "25%",
            top_n: "8%",
            transpose: "4%",
            update: "13%",
        }
        tools = list()
        for component in toolbar:
            this_width = widths.get(component, "10%")
            nstyle = {**style.CELL_MIDDLE_35, **{"width": this_width}}
            div = html.Div(component, style=nstyle)
            if component == transpose:
                div.title = "Transpose axes"
            elif component == top_n:
                div.title = "Number of entries to display"
            tools.append(div)
        toolbar = html.Div(tools,
                           style=style.VERTICAL_MARGINS,
                           className="chart-toolbar")

        figure = _df_to_figure(table, kind=kind)
        chart_data = dict(
            id=f"chart-{chart_num}",
            figure=figure,
            style={
                "height": height,
                "width": width
            },
        )
        chart = dcc.Loading(type="default",
                            id=f"chart-holder-{chart_num}",
                            children=[dcc.Graph(**chart_data)])
        chart_space = html.Div([toolbar, chart])
        name = f"Chart #{chart_num}"
        summary = html.Summary(name,
                               id=f"chart-num-{chart_num}",
                               style=style.CHART_SUMMARY)
        drop = [summary, html.Div(chart_space)]
        collapse = html.Details(drop, open=chart_num == 1)
        charts.append(collapse)
    div = html.Div(charts)
    return html.Div(id="display-chart", children=[div])
Пример #29
0
def create_app():
    """
    Dash app factory and layout definition.
    """
    app = dash.Dash(__name__, external_stylesheets=external_stylesheets, sharing=True)
    app.config['suppress_callback_exceptions'] = True

    app.layout = html.Div([
        dcc.Store(id='memory'),
        dcc.Store(id='params'),
        html.Div(children=[
            html.H3(id='problem-type', style={'margin-top': '40px', 'display': 'inline-block'}),
            daq.BooleanSwitch(
                id='type-switch',
                on=False,
                style={'margin-left': '20px', 'display': 'inline-block'}
            ),
            comp.vbar(),
            html.Table(children=[
                html.Tr(id='upload-row', children=[
                    html.Td(children=[
                        comp.upload(idx='city-input', name='City coordinates:'),
                        html.Div(id='output-city')],
                        style={'width': '33%', 'vertical-align': 'top'}),

                    html.Td(children=[
                        comp.upload(idx='paths-input', name='Paths information'),
                        html.Div(id='paths-output')],
                        style={'width': '33%', 'vertical-align': 'top'}),

                    html.Td(children=[
                        comp.upload(idx='time-solution-input', name='Magic .csv with time:'),
                        html.Div(id='time-output')],
                        style={'width': '33%', 'vertical-align': 'top'}),
                ]),
            ], style={'width': '100%', 'height': '100px'}),
            daq.BooleanSwitch(
                id='exact-solver',
                on=False,
                label='Use exact solver',
                labelPosition='top',
                style={'margin-right': '20px', 'display': 'inline-block'}
            ),
            daq.BooleanSwitch(
                id='plot-switch',
                on=True,
                label='Plot solution',
                labelPosition='top',
                style={'margin-right': '20px', 'display': 'inline-block'}
            ),
            html.Div(id='time-slider-output', style={'margin-top': '10px'}),
            dcc.Slider(min=5, max=65, value=15, id='time-slider',
                       marks={(5 * (i+1)): f'{5 * (i+1)}s' for i in range(13)}),

            html.Div(id='simulations-slider-output', style={'margin-top': '40px'}),
            dcc.Slider(min=10, max=490, value=90, id='simulations-slider',
                       marks={(10 * i * i): f'{10 * i * i}' for i in range(1, 8)}),
            comp.button('solve-btn', 'solve'),
        ]),

        html.Div(children=[
            dcc.Loading([html.Div(id='tsp-solution')], color='#1EAEDB'),
            dcc.Loading([html.Div(id='tsp-graph')], color='#1EAEDB')
        ], style={'margin-top': '40px'})

    ], style={'width': '85%', 'margin-left': '7.5%'})

    @app.callback([Output('output-city', 'children')],
                  [Input('city-input', 'contents')],
                  [State('city-input', 'filename')])
    def upload_city_matrix(content, name):
        if content:
            if '.csv' not in name:
                return html.Div(comp.error('Only .csv files ar supported!')),

            df = parse_contents(content)
            result = fh.validate_cities(df)
            if not result.status:
                return comp.error(result.msg)

            return comp.upload_table(name, df)
        return [None]

    @app.callback([Output('paths-output', 'children')],
                  [Input('paths-input', 'contents'), Input('city-input', 'contents')],
                  [State('paths-input', 'filename')])
    def upload_paths(content, cities, name):
        if content:
            if '.csv' not in name:
                return html.Div(comp.error('Only .csv files ar supported!')),

            df = parse_contents(content)
            cities = parse_contents(cities)
            result = fh.validate_paths(df, cities)
            if not result.status:
                return comp.error(result.msg)

            return comp.upload_table(name, df)
        return [None]

    @app.callback([Output('time-output', 'children')],
                  [Input('type-switch', 'on'), Input('time-solution-input', 'contents')],
                  [State('time-solution-input', 'filename')])
    def upload_time_solution(old_solution, content, name):
        if old_solution and content:
            if '.txt' not in name:
                return html.Div(comp.error('Only .txt files ar supported!')),

            result = fh.validate_solution(content)
            if not result.status:
                return comp.error(result.msg)
            return [html.Div([html.P(f'File {name} successfully uploaded!')])]

        if content:
            if '.csv' not in name:
                return [html.Div(comp.error('Only .csv files ar supported!'))]

            df = parse_contents(content)
            result = fh.validate_time(df)
            if not result.status:
                return comp.error(result.msg)

            return comp.upload_table(name, df)
        return [None]

    @app.callback([Output('tsp-solution', 'children'), Output('memory', 'data')],
                  [Input('type-switch', 'on'),
                   Input('exact-solver', 'on'),
                   Input('solve-btn', 'n_clicks'),
                   Input('city-input', 'contents'),
                   Input('paths-input', 'contents'),
                   Input('time-solution-input', 'contents'),
                   Input('simulations-slider', 'value'),
                   Input('time-slider', 'value')
                   ],
                  [State('memory', 'data')])
    def generate_solution(old_solution, exact, n_clicks, city, paths, df_time, n_sim, time_limit, cache):
        global CLICKS
        if old_solution and n_clicks and n_clicks > CLICKS:
            solution_content = df_time
            if solution_content:
                CLICKS += 1
                solution = fh.solution_to_output(solution_content)

                if city and paths:
                    paths = parse_contents(paths)
                    if paths.shape[0] > 0:
                        mean_time = np.mean(paths.travel_time.values)
                    else:
                        mean_time = 0.0
                    cities, edges = data_from_solution(cities=parse_contents(city),
                                                       paths=paths,
                                                       solution=solution)
                else:
                    mean_time = 0.0
                    cities, edges = data_from_solution(cities=None,
                                                       paths=None,
                                                       solution=solution)

                # Save solution
                fh.save_solution(solution, solution.time_left, new=False)

                # Generate html elements
                output = [html.H3(children='Solution'), comp.vbar()]
                output += comp.stats(0.0, solution, cities, new=False, mean_time=mean_time)

                # Cache data
                cache = {'cities': prepare_data(cities), 'edges': list(edges)}

                return output, cache

        # New solution
        elif n_clicks and city and paths and df_time and n_clicks > CLICKS:
            CLICKS += 1

            tic = time.time()
            df_time = parse_contents(df_time)
            paths = parse_contents(paths)
            if paths.shape[0] > 0:
                mean_time = np.mean(paths.travel_time.values)
            else:
                mean_time = 0.0

            solution, cities, edges = make_plot_data(cities=parse_contents(city),
                                                     paths=paths,
                                                     time=df_time,
                                                     simulations=n_sim,
                                                     time_limit=time_limit,
                                                     exact=exact)
            solving_time = time.time() - tic

            # Save solution
            fh.save_solution(solution, df_time.time.values[0])

            # Generate html elements
            output = [html.H3(children='Solution'), comp.vbar()]
            output += comp.stats(solving_time, solution, cities, input_time=df_time.time.values[0], mean_time=mean_time)

            # Cache data
            cache = {'cities': prepare_data(cities), 'edges': list(edges)}

            return output, cache

        return [None], None

    @app.callback([Output('tsp-graph', 'children')],
                  [Input('memory', 'data'), Input('plot-switch', 'on')],
                  [State('memory', 'data')])
    def show_plot(_, plot, cache):
        if cache and plot:
            cities, edges = cache.values()

            output = list([html.H3(children='Plot'), comp.vbar()])
            output.append(comp.graph(cities, edges))
            return output,
        return None,

    @app.server.route('/tmp/solution')
    def download_solution():
        return flask.send_file('tmp/solution.txt',
                               mimetype='text',
                               attachment_filename='solution.txt',
                               as_attachment=True)

    @app.callback([Output('time-slider-output', 'children')],
                  [Input('time-slider', 'value')])
    def update_time(n):
        return [f'Max time {n} s']

    @app.callback([Output('simulations-slider-output', 'children')],
                  [Input('simulations-slider', 'value')])
    def update_simulations(n):
        return [f'Random walks per node {n}']

    @app.callback([Output('problem-type', 'children'), Output('upload-row', 'children')],
                  [Input('type-switch', 'on')])
    def update_view(old_solution):
        if old_solution:
            title = ['Upload solved problem']
            row = [
            html.Td(children=[
                comp.upload(idx='time-solution-input', name='Upload solution'),
                html.Div(id='time-output')],
                style={'width': '33%', 'vertical-align': 'top'}),

                html.Td(children=[
                    comp.upload(idx='city-input', name='Optional city matrix'),
                    html.Div(id='output-city')],
                    style={'width': '33%', 'vertical-align': 'top'}),

                html.Td(children=[
                    comp.upload(idx='paths-input', name='Upload paths'),
                    html.Div(id='paths-output')],
                    style={'width': '33%', 'vertical-align': 'top'}),
                ]
            return title, row

        title = ['Solve']
        row = [
            html.Td(children=[
                comp.upload(idx='city-input', name='City coordinates:'),
                html.Div(id='output-city')],
                style={'width': '33%', 'vertical-align': 'top'}),

            html.Td(children=[
                comp.upload(idx='paths-input', name='Paths information'),
                html.Div(id='paths-output')],
                style={'width': '33%', 'vertical-align': 'top'}),

            html.Td(children=[
                comp.upload(idx='time-solution-input', name='Magic .csv with time:'),
                html.Div(id='time-output')],
                style={'width': '33%', 'vertical-align': 'top'}),
        ]

        return title, row

    return app
Пример #30
0
import dash_html_components as html

external_stylesheets = ['https://codepen.io/anon/pen/mardKv.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

theme = {
    'dark': True,
    'detail': '#007439',
    'primary': '#00EA64',
    'secondary': '#6E6E6E',
}

rootLayout = html.Div([
    daq.BooleanSwitch(on=True,
                      id='darktheme-daq-booleanswitch',
                      className='dark-theme-control'),
    html.Br(),
    daq.ToggleSwitch(id='darktheme-daq-toggleswitch',
                     className='dark-theme-control'),
    html.Br(),
    daq.ColorPicker(value=17,
                    id='darktheme-daq-colorpicker',
                    className='dark-theme-control'),
    html.Br(),
    daq.Gauge(min=0,
              max=10,
              value=6,
              color=theme['primary'],
              id='darktheme-daq-gauge',
              className='dark-theme-control'),