Beispiel #1
0
def serve_layout(channels):
    return html.Div([
        html.Div([
            html.H1('Muse streaming'),

            Interval(
                id='interval_component',
                interval=1*100,
                n_intervals=0
            ),

            Checklist(
                id='channels_selected',
                options=[
                    {'label': 'TP9', 'value': 'TP9'},
                    {'label': 'AF7', 'value': 'AF7'},
                    {'label': 'AF8', 'value': 'AF8'},
                    {'label': 'TP10', 'value': 'TP10'},
                    {'label': 'AUX', 'value': 'Right AUX'}
                ],
                value=channels
            ),

            html.Button('Zoom In', id='zoom_in', n_clicks=0),

            html.Button('Zoom Out', id='zoom_out', n_clicks=0),

            html.Button('Reset', id='reset', n_clicks=0),

            html.Button('Play/Stop', id='playstop', n_clicks=0),

            html.P('Expand graphs'),

            BooleanSwitch(id='expand_graphs', on=False), # lgtm [py/call-to-non-callable]

            html.P('Update interval'),

            Slider(
                id='interval_modifier',
                min=200,
                max=5000,
                value=200,
                step=200,
                marks={
                    200: {'label': '200 ms'},
                    500: {'label': '500 ms'},
                    750: {'label': '750 ms'},
                    1000: {'label': '1 s'},
                    1500: {'label': '1.5 s'},
                    2000: {'label': '2 s'},
                    3000: {'label': '3 s'},
                    5000: {'label': '5 s'}
                }
            ),

        ], style={'margin': 'auto', 'text-align': 'center'}),

        html.Div(id='graphs')
    ])
Beispiel #2
0
    def adaptable_slider(url_string, n_clicks, graphdata):
        if n_clicks == 0:
            return Slider(id='idate_slider', value=None)

        id_serie = parse_url(url_string)
        fromdate, todate = unpack_dates(graphdata)
        idates = insertion_dates(id_serie, fromdate, todate)
        showlabel = len(idates) < 25
        slider = Slider(id='idate_slider',
                        min=0,
                        max=len(idates) - 1,
                        value=len(idates) - 1,
                        step=None,
                        marks={
                            str(idx): elt if showlabel else ''
                            for idx, elt in enumerate(idates)
                        })
        return slider
Beispiel #3
0
    def _create_dash_components(self):
        """Create the graph, slider, figure, etc."""
        info = self._slice_info

        # Prep low-res slices. The get_thumbnail_size() is a bit like
        # a simulation to get the low-res size.
        if not self._thumbnail:
            thumbnail_size = None
            info["thumbnail_size"] = info["size"]
        else:
            thumbnail_size = self._thumbnail
            info["thumbnail_size"] = get_thumbnail_size(
                info["size"][:2], thumbnail_size)
        thumbnails = [
            img_array_to_uri(self._slice(i), thumbnail_size)
            for i in range(info["size"][2])
        ]

        # Create the figure object - can be accessed by user via slicer.graph.figure
        self._fig = fig = plotly.graph_objects.Figure(data=[])
        fig.update_layout(
            template=None,
            margin={
                "l": 0,
                "r": 0,
                "b": 0,
                "t": 0,
                "pad": 4
            },
            dragmode="pan",  # good default mode
        )
        fig.update_xaxes(
            showgrid=False,
            showticklabels=False,
            zeroline=False,
            autorange=True,
            constrain="range",
        )
        fig.update_yaxes(
            showgrid=False,
            scaleanchor="x",
            showticklabels=False,
            zeroline=False,
            autorange="reversed" if self._reverse_y else True,
            constrain="range",
        )

        # Create the graph (graph is a Dash component wrapping a Plotly figure)
        self._graph = Graph(
            id=self._subid("graph"),
            figure=fig,
            config={"scrollZoom": True},
        )

        # Create a slider object that the user can put in the layout (or not).
        # Note that the tooltip introduces a measurable performance penalty,
        # so maybe we can display it in a different way?
        self._slider = Slider(
            id=self._subid("slider"),
            min=0,
            max=info["size"][2] - 1,
            step=1,
            value=info["size"][2] // 2,
            updatemode="drag",
            tooltip={
                "always_visible": False,
                "placement": "left"
            },
        )

        # Create the stores that we need (these must be present in the layout)

        # A dict of static info for this slicer
        self._info = Store(id=self._subid("info"), data=info)

        # A list of low-res slices, or the full-res data (encoded as base64-png)
        self._thumbs_data = Store(id=self._subid("thumbs"), data=thumbnails)

        # A list of mask slices (encoded as base64-png or null)
        self._overlay_data = Store(id=self._subid("overlay"), data=[])

        # Slice data provided by the server
        self._server_data = Store(id=self._subid("server-data"),
                                  data={
                                      "index": -1,
                                      "slice": None
                                  })

        # Store image traces for the slicer.
        self._img_traces = Store(id=self._subid("img-traces"), data=[])

        # Store indicator traces for the slicer.
        self._indicator_traces = Store(id=self._subid("indicator-traces"),
                                       data=[])

        # Store user traces for the slider.
        self._extra_traces = Store(id=self._subid("extra-traces"), data=[])

        # A timer to apply a rate-limit between slider.value and index.data
        self._timer = Interval(id=self._subid("timer"),
                               interval=100,
                               disabled=True)

        # The (public) state of the slicer. This value is rate-limited. Initially null.
        self._state = Store(id=self._subid("state", True), data=None)

        # Signal to set the position of other slicers with the same scene_id.
        self._setpos = Store(id=self._subid("setpos", True), data=None)

        self._stores = [
            self._info,
            self._thumbs_data,
            self._overlay_data,
            self._server_data,
            self._img_traces,
            self._indicator_traces,
            self._extra_traces,
            self._timer,
            self._state,
            self._setpos,
        ]
Beispiel #4
0
          src='data:image/jpg;base64,{}'.format(github_image.decode()),
          style={
              'height' : '8%',
              'width' : '8%',
              'float' : 'right',
              'padding-top' : 0,
              'padding-right' : 0
          })], href="https://github.com/KKAnumalasetty/simulation-app-heroku", target="_blank", 
         )]),
 P('Unit Margin = $50 and Lead Time for Purchase Order = 2 days'),
 Div([P('Days to simulate (1 to 30 days) :')],style={'display': 'inline-block'}),
 Div([P(id='days-slider-output')],style={'display': 'inline-block','color':'red','padding':'20px','font-size':'160%'}),
 Div([Slider(
  id='days-slider',
  min=0,
  max=30,
  step=1,
  value=25,
  updatemode='drag',        
  )],style={"width" : "25%"}),
 Div([P('Inventory Cutoff level (units 1 to 100) :')],style={'display': 'inline-block'}),
 Div([P(id='inv-cutoff-slider-output')],style={'display': 'inline-block','color':'red','padding':'20px','font-size':'160%'}),
 Div([Slider(
  id='inv-cutoff-slider',
  min=0,
  max=100,
  step=1,
  value=32,
  updatemode='drag'
  )],style={"width" : "25%"}),
 Div([P('Inventory Target level (units 1 to 100)  :')],style={'display': 'inline-block'}),
 Div([P(id='inv-target-slider-output')],style={'display': 'inline-block','color':'red','padding':'20px','font-size':'160%'}),
Beispiel #5
0
 Dropdown(id='formatter-{0}'.format(APP_UID),
          options=[{
              'label': 'str',
              'value': 'str'
          }, {
              'label': 'repr',
              'value': 'repr'
          }],
          value='str',
          clearable=False,
          className='app-widget'),
 H5(children='Decimals'),
 Slider(id='decimals-{0}'.format(APP_UID),
        min=1,
        max=15,
        step=1,
        value=10,
        marks={i + 1: str(i + 1)
               for i in range(15)},
        className='app-widget'),
 Pre([Code(id='primaries-{0}'.format(APP_UID), className='code shell')],
     className='app-widget app-output'),
 Ul([
     Li([Link('Back to index...', href='/', className='app-link')],
        className='list-inline-item'),
     Li([
         A('Permalink',
           href=urlparse.urljoin(SERVER_URL, APP_PATH),
           target='_blank')
     ],
        className='list-inline-item'),
     Li([
Beispiel #6
0
app.layout = Div(children=[
    H1('Evento X'),
    H3('idade das pessoas que foram ao evento'),
    Dropdown(options=[{
        'label': 'Menores de Idade',
        'value': 'menores'
    }, {
        'label': 'Bebes',
        'value': 'bebes'
    }, {
        'label': 'Maiores de idade',
        'value': 'maiores'
    }],
             value='menores'),
    Slider(min=0, max=10, step=1, value=5),
    Checklist(options=[{
        'label': 'Menores de Idade',
        'value': 'menores'
    }, {
        'label': 'Bebes',
        'value': 'bebes'
    }, {
        'label': 'Maiores de idade',
        'value': 'maiores'
    }],
              value=['bebes']),
    Graph(config={'displayModeBar': False},
          figure={
              'data': [
                  {
        options.append({'label': i, 'value': i})

world_bank_layout = html.Div([
    html.H2('Market Indicators'),
    html.H4('Dash Developer Preview App'),
    html.Hr(),
    Dropdown(id='indicator-dropdown-single',
             options=options,
             value='GDP growth (annual %)'),
    html.Div([
        html.Div([
            Graph(id='choropleth'),
            Graph(id='indicator-over-time'),
        ],
                 className="eight columns"),
        html.Div([Slider(id='year-slider')],
                 style={
                     'marginTop': 25,
                     'marginBottom': 25
                 }),
        html.Div(id='table',
                 style={
                     'height': '850px',
                     'overflowY': 'scroll'
                 },
                 className="four columns"),
    ],
             className="row"),
    html.Hr(),
    html.H3('Indicators over Time'),
    html.Div([
Beispiel #8
0
def setup_dash_layout(app: Dash, sk: DivSkeleton) -> dash.Dash:
    def create_sliders(
    ) -> tuple[RangeSlider, RangeSlider, RangeSlider, RangeSlider]:
        slider_height = 460
        year_slider = RangeSlider(
            INPID_YEAR,
            min=(mn := etl.ATTRS.index.get_level_values("year").min()),
            max=(mx := etl.ATTRS.index.get_level_values("year").max()),
            value=[2012, 2018],
            marks={y: str(y)
                   for y in range(mn, mx + 1)},
            vertical=True,
            verticalHeight=slider_height,
            updatemode="mouseup",
            **PERSIST_ARGS,
        )
        mileage_slider = RangeSlider(
            INPID_MILEAGE,
            min=0,
            max=etl.MAX_MILEAGE,
            value=[10000, 70000],
            marks={
                y: f"{y // 1000}k"
                for y in range(0, etl.MAX_MILEAGE, 25_000)
            },
            step=1,
            vertical=True,
            updatemode="mouseup",
            verticalHeight=slider_height,
            **PERSIST_ARGS,
        )
        price_slider = RangeSlider(
            INPID_PRICE,
            min=0,
            max=etl.MAX_PRICE,
            value=[10000, 35000],
            marks={
                int(y): f"{y // 1000}k"
                for y in range(0, etl.MAX_PRICE, 10_000)
            },
            step=1,
            vertical=True,
            updatemode="mouseup",
            verticalHeight=slider_height,
            **PERSIST_ARGS,
        )
        mpg_slider = RangeSlider(
            INPID_MPG,
            min=etl.ATTRS["mpg"].min(),
            max=(mx := etl.ATTRS["mpg"].max()),
            value=[20, mx],
            marks={int(y): f"{y:.0f}"
                   for y in range(10,
                                  int(mx) + 1, 10)},
            step=1,
            vertical=True,
            updatemode="mouseup",
            verticalHeight=slider_height,
            **PERSIST_ARGS,
        )

        return year_slider, mileage_slider, price_slider, mpg_slider

    for name, slider, div_id in zip(
        ["Year", "Mileage", "Price", "MPG"],
            create_sliders(),
        [SK_SLIDER_MILEAGE, SK_SLIDER_PRICE, SK_SLIDER_YEAR, SK_SLIDER_MPG],
    ):
        sk.fill(
            div_id,
            [dbc.Badge(name, color="primary", className="slider"), slider],
        )
    top_selectors = [
        dbc.Alert("Select your location.",
                  id="alert-loc-picker",
                  color="primary"),
        Dropdown(
            id=INPID_ZIPCODE,
            placeholder="Zipcode",
            clearable=False,
            options=opts_from_vals(etl.LATLONG_BY_ZIP.keys()),
            **PERSIST_ARGS,
        ),
        Slider(
            id=INPID_MAX_DIST,
            className="form-control",
            min=10,
            max=250,
            marks={
                mark: dict(label=str(mark) + ("mi." if mark == 10 else ""))
                for mark in [10, 50, 100, 150, 200, 250]
            },
            value=50,
            **PERSIST_ARGS,
        ),
        dbc.Alert("Limit dealership states.",
                  id="alert-state-picker",
                  color="primary"),
        Dropdown(
            id=INPID_STATE,
            # options by callback
            multi=True,
            **PERSIST_ARGS,
        ),
        Div(
            id="plot-info-flex",
            children=[
                dbc.Button(children="Plot Cars Now!",
                           id=PLOT_BUTTON,
                           color="success"),
                Div(
                    id=PLOT_ALERT_BOX,
                    children=dbc.Alert(id=PLOT_ALERT,
                                       children="",
                                       color="danger"),
                    hidden=True,
                ),
                dbc.Alert("Plot does not refresh automatically.",
                          color="light"),
            ],
            style={
                "display": "flex",
                "flex-direction": "column-reverse"
            },
        ),
    ]
    ## car options pickers
    top_selectors.extend([])

    ###
    ##
    # === BOTTOM ROW ===
    ##
    ###

    sk.fill(SK_TOP_SELECTORS, top_selectors)
    mm_picker_menu = [
        dbc.Alert(
            "Select makes and models you are interested in. "
            "Filtered by sliders.",
            id=ALERT_MM_PICKER,
            color="primary",
        ),
        Dropdown(
            id=INPID_MM_PICKER,
            # options by callback
            multi=True,
            placeholder="Select makes",
            clearable=False,
            **PERSIST_ARGS,
        ),
    ]

    sk.fill(SK_MM_PICKER, mm_picker_menu)
    sk.fill(
        SK_LL_INFO,
        dbc.Alert(
            id="alert-site-info",
            children=(
                "Used car picker by Evgeny Naumov.",
                html.Br(),
                "Built on top of Truecar data with Plotly + Dash.",
            ),
            color="light",
        ),
    )
    # car type options

    button_layout = {
        ("Transmission", INPID_OPTS_TRANS): scr.TRANSMISSIONS,
        ("Fuel Type", INPID_OPTS_FUEL): scr.KNOWN_FUEL_TYPES,
        ("Drivetrain", INPID_OPTS_DRIVETRAIN): scr.KNOWN_DRIVETRAINS,
        ("Body", INPID_OPTS_BODY): scr.KNOWN_BODIES,
    }

    car_opt_picker = [
        dbc.Alert("Select car attributes.", color="primary"),
        Div(
            id="car-opts-box",
            className=TOGGLE_BUTTON_BOX,
            children=[
                button
                for (inp_name, inp_id), inp_opts in button_layout.items()
                for button in ToggleButtonGroup.make_buttons(
                    label=inp_name,
                    values=inp_opts,
                    selectors=dict(input=inp_id),
                )
            ],
        ),
    ]
    sk.fill(SK_CAR_OPTS_BOX, car_opt_picker)

    mmt_refine_menu = [
        dbc.Alert("Select models to refine trims.",
                  id="mmt-alert",
                  color="secondary"),
        Div(id="mmt-card-group"),
    ]
    sk.fill(SK_MMT_MATRIX, mmt_refine_menu)
    sk.fill(
        SK_CACHE,
        [
            Interval(IVAL_TRIGGER_LOAD, max_intervals=1, interval=1),
            Store(
                id=STORE_ALL_CARS,
                storage_type="memory",
                data=etl.RAW_CLIENT_DATA,
            ),
            Store(id=STORE_FILTERED_CARS, storage_type="session"),
            Div(id="devnull"),
        ],
    )

    ## GRAPH
    scatter_graph = html.Div(
        id="scatter-box",
        children=Graph(id="scatter-price-mileage"),
        hidden=True,
    )
    sk.fill(SK_SCATTER, scatter_graph)

    ### ALERTS

    alert_link = dbc.Alert(
        id="output-link",
        children="A plot of listings will appear above when executed.",
        color="secondary",
    )
    sk.fill(SK_INFO_A, alert_link)

    app.layout = sk["root"]
    return app
Beispiel #9
0
def get_app(server, path):

    df = Model().df
    ldesc = Model().ldesc

    dash_example = Dash(__name__, server=server, url_base_pathname=path)

    label_map = loads(ldesc.to_json(orient="index"))

    dash_example.layout = Div(className="dash-div",
                              children=[
                                  Dropdown(
                                      id='label-dropdown',
                                      options=[{
                                          'label':
                                          label_map[i]["label_description"],
                                          'value':
                                          i
                                      } for i in df['label'].unique()],
                                      value=df['label'].unique()[0]),
                                  Slider(id='filter-slider',
                                         min=0,
                                         max=20,
                                         step=1,
                                         value=10),
                                  Graph(id="bubble-chart")
                              ])

    @dash_example.callback(
        Output('bubble-chart', 'figure'),
        [Input('label-dropdown', 'value'),
         Input('filter-slider', 'value')])
    def update_figure(label, value):
        df = Model().df
        ndf = getBubbleData(df, label, value)
        #print(ndf.head())
        bar = px.bar(ndf,
                     y="text",
                     x="count",
                     color="category",
                     orientation='h',
                     barmode='group')
        bar.update_layout(autosize=False,
                          width=960,
                          height=550,
                          paper_bgcolor='rgba(0,0,0,0)',
                          plot_bgcolor='rgba(0,0,0,0)',
                          hovermode='closest',
                          font=dict(family="Courier New, monospace",
                                    size=18,
                                    color="white"))
        #return fig
        return bar

    @dash_example.callback(Output('filter-slider', 'value'),
                           [Input('label-dropdown', 'value')])
    def update_slider_min(label):
        df = Model().df
        ndf = getBubbleData(df, label)
        #print(ndf.head())
        return ndf["count"].min()

    @dash_example.callback(Output('filter-slider', 'min'),
                           [Input('label-dropdown', 'value')])
    def update_slider_min(label):
        df = Model().df
        ndf = getBubbleData(df, label)
        #print(ndf.head())
        return ndf["count"].min()

    @dash_example.callback(Output('filter-slider', 'max'),
                           [Input('label-dropdown', 'value')])
    def update_slider_max(label):
        df = Model().df
        ndf = getBubbleData(df, label)
        #print(ndf.head())
        return ndf["count"].max()

    return dash_example
Beispiel #10
0
    def update():
        
        if request.endpoint == url_base:
            app.index_string = render_template(
                'data_page.html'
            )
            rv = rv_plot.public
            curr_user = g.user['atype']
            if curr_user == 'admin' or curr_user == 'researcher':
                rv = rv_plot.data
            app.layout = Div([
                Tooltip(
                    "Set the Y axis to a linear or logarithmic scale.",
                    target="log-switch",
                ),
                Tooltip(
                    "Enables data to be separated by order on the spectrograph",
                    target="dim-switch",
                ),
                Tooltip(
                    "The name of the file being displayed",
                    target="click-data",
                    placement="bottom"
                ),
                Tooltip(
                    "Selects which orders of the spectrum to render",
                    target="order-tool",
                ),
                Tooltip(
                    "Reduces the amount of points rendered to the screen",
                    target="res-tool",
                ),
                Tooltip(
                    "Each graph has a tool bar in the upper-right hand corner that appears when you mouse over a graph."
                    "Use the buttons in the tool bar to zoom in, zoom out, reset the axis, save a screen shot, "
                    "and more. Click on a point in the Radial Velocity graph to display the Spectrum graph below."  
                    "Hover over the slider and toggle bottoms below the lower graph to further interact with the"
                    "spectrum data.",
                    target="graph-tool"
                ),
                Loading([
                    Div([
                        Button([
                                I(
                                    className="fas fa-info-circle",
                                ),
                                Span(
                                    ' Info',
                                )
                            ],
                            id='graph-tool',
                            className='btn btn-warning btn-sm',
                        ),
                    ]),
                    Div(
                        id='rv-download-container'
                    ),
                    Button([
                            I(
                                className="fas fa-download",
                            ),
                            Span(
                                " Download Radial Velocities",
                            )
                        ],
                        id='rv-download',
                        className='btn btn-primary btn-sm float-right',
                    ),
                    Download(
                        id='rv-download-data'
                    ),
                    DatePickerRange(
                        id='date-range',
                        className='pt-1 d-flex justify-content-end w-100',
                    ),
                    Graph(
                        id='rv-plot',
                        className="",
                        config={
                            'modeBarButtonsToRemove': ['pan2d', 'lasso2d', 'autoscale']
                        }
                    ),
                    
                ], type="default", className='d-flex justify-content-end w-100'),
                Div(
                    id='rv-data',
                    children=rv[rv_label].to_json(),
                    className='d-none'
                ),
                Div([
                    Pre(id='click-data', className=' d-inline'),
                ]),
                
                
                Br(),
                Br(),
                Div([
                    Loading([
                        Div([
                            Div([
                                Button([
                                        I(
                                            className="fas fa-download",
                                        ),
                                        Span(
                                            " Download 1D",
                                        )
                                    ],
                                    id='1d-spec-download',
                                    className='btn btn-primary btn-sm',
                                ),

                                Download(
                                    id='1d-spec-download-data'
                                ),
                            ], className='pr-2'),
                            Div([
                                Button([
                                    I(
                                        className="fas fa-download",
                                    ),
                                    Span(
                                        " Download 2D",
                                    )],
                                    id='2d-spec-download',
                                    className='btn btn-primary btn-sm',
                                ),

                                Download(
                                    id='2d-spec-download-data'
                                ),
                            ], className=""),
                        ], className="row justify-content-end d-none", id="spec-download-container"),
                        Div(
                            id='spec-data',
                            children=[],
                            className='d-none'
                        ),
                        Graph(
                            id='spec-plot',
                            className="pt-0",
                            config={
                                'modeBarButtonsToRemove': ['pan2d', 'lasso2d', 'autoscale']
                            }
                        ),
                    ], type="default", ),


                    Div([
                        Span([
                            'Order Range\n'
                        ], id='order-tool', className='d-none'),
                        Span([
                            'Resolution\n'
                        ], id='res-tool', className='d-none')
                    ],
                    id='slide-label',
                    className='w-100 text-center'),


                    Div([
                        
                        Slider(
                            min=1,
                            max=200,
                            value=100,
                            marks={
                                1: {'label': '1:1', 'style': {'color': '#77b0b1'}},
                                20: {'label': '20:1'},
                                50: {'label': '50:1'},
                                100: {'label': '100:1'},
                                200: {'label': '200:1', 'style': {'color': '#f50'}}
                            },
                            id='resolution',
                            className='col d-none',
                        ),
                        RangeSlider(
                            id='spec-range',
                            className='col d-none',
                            min=0,
                            max=85,
                            step=1,
                            value=[40, 45],
                            marks={
                                0: {'label': '0'},
                                40: {'label': '40'},
                                45: {'label': '45'},
                                85: {'label': '85'}
                            }
                        ),
                    ], className='row'),
                ], id='spec-container'),
                Br(),
                Div([
                    Div([
                        daq.ToggleSwitch(
                            label='lin/log',
                            id='log-switch',
                            className='d-inline-block',
                            labelPosition='bottom'
                        ),
                    ], className='col text-center'),
                    Div([
                        daq.ToggleSwitch(
                            label='1D / 2D',
                            id='dim-switch',
                            className='d-inline-block',
                            labelPosition='bottom'
                        )
                    ], className='col text-center'),
                ], className="row")
            ])