Beispiel #1
0
def update_figure(c_list):
    PQ, SE = [], []
    for c in c_list:
        PQ_fig = px.line(wpgs[c], x='Month', y='Value', color='Year',
                         facet_row='Type', category_orders={'Type': ['Baht', 'Ton']})
        PQ.append(Graph(figure=PQ_fig))

        SE_fig = px.bar(csdp[c], x='Month', y='EC', color='Type',
                        facet_row='Year')
        SE.append(Graph(figure=SE_fig))

    return PQ, SE
 def get_html(self) -> List[ComponentMeta]:
     """Initializes the header dash html
     """
     return [
         H2(self.content["new-admissions-title"]),
         Markdown(self.content["new-admissions-text"]),
         Graph(id="new-admissions-graph"),
         Table(id="new-admissions-table"),
         H2(self.content["admitted-patients-title"]),
         Markdown(self.content["admitted-patients-text"]),
         Graph(id="admitted-patients-graph"),
         Table(id="admitted-patients-table"),
     ]
Beispiel #3
0
def col_histograms(df):
    """
    Generate plotly.Dash's Bar chart component. One barchart for each column of the dataframe
    :param df: pandas.DataFrame
    :return: dash_core_components.Graph
    """
    describe_bar_chart = Div(children=[])
    for col in df.columns:
        t = Histogram(x=df[col], name=col)
        l = Layout(title='Histogram for colunm {}'.format(t.name),
            autosize=False,
            width=500,
            height=500,
            margin={
                'l': 50,
                'r': 50,
                'b': 100,
                't': 100,
                'pad': 4
            })
        fig = Figure(data=[t], layout=l)
        g = Graph(figure=fig,className="col-sm-4", config={'staticPlot': True, 'responsive': True})
        describe_bar_chart.children.append(g)

    return describe_bar_chart
Beispiel #4
0
def per_machine_per_device_pie_charts(GPU_STATS, KEEP_ALIVE):
    compute_machines = []
    for machine_name, machine in GPU_STATS.items():
        machine_devices = []
        devices = machine["devices"]

        for i, d in enumerate(devices):

            used = d["used"] // MB_DIVISOR
            total = d["total"] // MB_DIVISOR

            used_ratio = used / total
            used_ratio = [used_ratio] + [1.0 - used_ratio]

            hover_text = [f"used:{used:.0f}mb", f"free:{total - used:.0f}mb"]

            machine_devices.append(
                Div(
                    [
                        Graph(
                            id=f"gpu_stats_{machine_name}{i}",
                            figure={
                                "data": [
                                    graph_objs.Pie(
                                        values=used_ratio,
                                        text=hover_text,
                                        name="used ratio",
                                        hole=0.4,
                                    )
                                ],
                                "layout":
                                graph_objs.Layout(
                                    title=f"{d['name']} cuda_idx:{d['id']}",
                                    showlegend=False,
                                    hovermode="closest",
                                ),
                            },
                            style={
                                "width": "100%",
                            },
                        )
                    ],
                    className="col",
                ))
        compute_machines.append(
            Div(
                [
                    H3(
                        f"{machine_name}: {KEEP_ALIVE[machine_name]} sec ago",
                        className="text-monospace",
                        style={"text-decoration": "underline"},
                    ),
                    Div([*machine_devices], className="row"),
                ],
                style={
                    "text-align": "center",
                    "width": "100%",
                },
            ))
    return compute_machines
Beispiel #5
0
def layout(symbols):
    """Return the UI layout."""
    periods = [('1 day', 0), ('1 week', 1), ('1 month', 2), ('3 months', 3),
               ('1 year', 4), ('5 years', 5)]
    return Div([
        H3('Stock prices'),
        Div([
            Div([_symbol_selector_dropdown(symbols)],
                style={
                    'width': '45%',
                    'float': 'left',
                    'display': 'inline-block'
                }),
            Div([_period_selector_radio(periods)],
                style={
                    'width': '45%',
                    'float': 'right',
                    'display': 'inline-block'
                })
        ],
            style={
                'display': 'inline-block',
                'width': '100%'
            }),
        Graph(id='plot-stock', config={'displayModeBar': False})
    ])
Beispiel #6
0
def makeCard(plot, view, hide=False):

    layout = \
    {
        'title'            : f'<b>{plot} of {view}</b>',

        'xaxis_showgrid'   : False,
        'xaxis_zeroline'   : False,
        'xaxis_visible'    : False,
        'yaxis_showgrid'   : False,
        'yaxis_zeroline'   : False,
        'yaxis_visible'    : False,

        'paper_bgcolor'    : BG_PAPER,
        'plot_bgcolor'     : BG_PLOT,
    }

    config = \
    {
        'displaylogo' : False,
        'showTips'    : True,
        'frameMargins' : 0,
    }

    style = \
    {
        'background' : 'blue'
    }

    wrap = plot.replace('plot', 'wrap')
    card = plot.replace('plot', 'card')
    mask = plot.replace('plot', 'mask')
    load = plot.replace('plot', 'load')

    figure = upFigure(traces=[], layout=layout)

    return Div(id=wrap,
               className='wrap',
               children=[
                   Card(id=card,
                        className=f'{view}',
                        children=[
                            Div(id=mask,
                                className='mask',
                                hidden=False,
                                children=[
                                    Loading(id=load,
                                            className='load',
                                            children=[
                                                Graph(id=plot,
                                                      figure=figure,
                                                      config=config,
                                                      style=style)
                                            ]),
                                ])
                        ])
               ])
Beispiel #7
0
def get_altitude_fig(trip: Trip):
    conn = Database.get_db()
    res = list(map(list, conn.execute("SELECT mileage, altitude FROM position WHERE Timestamp>=? and Timestamp<=?;",
                                      (trip.start_at, trip.end_at)).fetchall()))
    start_mileage = res[0][0]
    for line in res:
        line[0] = line[0] - start_mileage
    fig = px.line(res, x=0, y=1)
    fig.update_layout(xaxis_title="Distance km", yaxis_title="Altitude m")
    conn.close()
    return html.Div(Graph(figure=fig))
Beispiel #8
0
def plot_listings(listings: DataFrame) -> Graph:
    fig = go.Figure(
        go.Scattergl(
            x=listings["mileage"],
            y=listings["price"],
            customdata=listings[[
                "vin",
                "make",
                "model",
                "style",
                "mpg",
                "dealer_name",
                "distance",
                "year",
                "price",
                "drivetrain",
                "engine",
            ]],
            hoverlabel=dict(bgcolor="#F8F5F0"),
            hovertemplate=('<b style="color: green;">$%{customdata[8]}</i><br>'
                           "<i>%{customdata[0]}</i><br>"
                           '<b style="font-size:16">'
                           "%{customdata[7]} %{customdata[1]} "
                           "%{customdata[2]} %{customdata[3]}"
                           "</b><br>"
                           "<i>%{customdata[9]} - %{customdata[10]}</b><br>"
                           "Dealer: %{customdata[5]}<br>"
                           "<b>About %{customdata[6]:.0f} miles from you.</b>"
                           "<extra></extra>"),
            marker=dict(
                color=listings["color_rgb"].fillna("#000000"),
                opacity=1 -
                0.75 * listings["color_rgb"].transform(pd.isna).astype(int),
                size=10,
                line=dict(width=0),
            ),
            mode="markers+text",
        ),
        layout=dict(
            clickmode="event",
            xaxis=dict(title="Mileage, mi", ticks="inside"),
            yaxis=dict(title="Price, $", ticks="inside"),
            margin=dict(b=0, t=0, l=0, r=0, pad=0),
        ),
    )

    fig.update_yaxes(automargin=True)
    fig.update_xaxes(automargin=True)

    graph = Graph(id=INPID_GRAPH,
                  config=dict(displayModeBar=False),
                  figure=fig)

    return graph
Beispiel #9
0
def get_battery_curve_fig(row: dict, car: Car):
    start_date = dash_date_to_datetime(row["start_at"])
    stop_at = dash_date_to_datetime(row["stop_at"])
    conn = Database.get_db()
    res = Database.get_battery_curve(conn, start_date, car.vin)
    conn.close()
    res.insert(0, {"level": row["start_level"], "date": start_date})
    res.append({"level": row["end_level"], "date": stop_at})
    battery_curves = []
    speed = 0
    for x in range(1, len(res)):
        start_level = res[x - 1]["level"]
        end_level = res[x]["level"]
        speed = car.get_charge_speed(start_level, end_level, (res[x]["date"] - res[x - 1]["date"]).total_seconds())
        battery_curves.append({"level": start_level, "speed": speed})
    battery_curves.append({"level": row["end_level"], "speed": speed})
    fig = px.line(battery_curves, x="level", y="speed")
    fig.update_layout(xaxis_title="Battery %", yaxis_title="Charging speed in kW")
    return html.Div(Graph(figure=fig))
Beispiel #10
0
    def callback(self, *args, **kwargs) -> List[Any]:
        """Renders the parameter dependent plots and tables
        """
        pars = kwargs["pars"]

        if kwargs["show_additional_projections"]:
            title = self.content["infected-v-revovered-title"]

            time_evolution = self._build_frame(**kwargs)

            time_evolution_data = plot_dataframe(
                time_evolution.drop(columns=self.content["susceptible"]),
                max_y_axis=pars.max_y_axis,
            )

            children = [
                H4(title, id="infected-v-revovered-title"),
                Graph(figure=time_evolution_data,
                      id="infected-v-revovered-graph"),
            ]

            if kwargs["show_tables"]:
                if kwargs["as_date"]:
                    time_evolution.index = time_evolution.index.strftime(
                        "%b, %d")
                time_evolution_table_data = (df_to_html_table(
                    time_evolution, data_only=True, n_mod=7)
                                             if kwargs["show_tables"] else {})
                children.append(
                    Table(time_evolution_table_data,
                          id="infected-v-revovered-table"))

        else:
            children = []

        return [children]
Beispiel #11
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%'}),
       Div([Slider(
        id='inv-target-slider',
        min=0,
        max=100,
        step=1,
        value=75,
        updatemode='drag'
        )],style={"width" : "25%"}),
        Graph(id='my-graph')
        ])
        
#Server logic of DASH app

@app.callback(
    [Output('days-slider-output',component_property='children'),
    Output('inv-cutoff-slider-output',component_property='children'),
    Output('inv-target-slider-output',component_property='children'),
    Output('my-graph',component_property='figure')],
    [Input('days-slider',component_property='value'),
     Input('inv-cutoff-slider',component_property='value'),
     Input('inv-target-slider',component_property='value'),
     ])
def update_graph(days_slider,inv_cutoff_slider,inv_target_slider):
    
Beispiel #12
0
def get_figures(trips: Trips, charging: Tuple[dict]):
    global consumption_fig, consumption_df, trips_map, consumption_fig_by_speed, table_fig, info, battery_info, \
        battery_table, consumption_graph_by_temp
    lats = []
    lons = []
    names = []
    for trip in trips:
        for points in trip.positions:
            lats = np.append(lats, points.longitude)
            lons = np.append(lons, points.latitude)
            names = np.append(names, [str(trip.start_at)])
        lats = np.append(lats, None)
        lons = np.append(lons, None)
        names = np.append(names, None)
    trips_map = px.line_mapbox(lat=lats, lon=lons, hover_name=names,
                               mapbox_style="stamen-terrain", zoom=12)
    # table
    nb_format = Format(precision=2, scheme=Scheme.fixed, symbol=Symbol.yes)
    table_fig = dash_table.DataTable(
        id='trips-table',
        sort_action='native',
        # sort_by=[{'column_id': 'start_at', 'direction': 'desc'}],
        columns=[{'id': 'start_at', 'name': 'start at', 'type': 'datetime'},
                 {'id': 'duration', 'name': 'duration', 'type': 'numeric',
                  'format': deepcopy(nb_format).symbol_suffix(" min").precision(0)},
                 {'id': 'speed_average', 'name': 'average speed', 'type': 'numeric',
                  'format': deepcopy(nb_format).symbol_suffix(" km/h").precision(0)},
                 {'id': 'consumption_km', 'name': 'average consumption', 'type': 'numeric',
                  'format': deepcopy(nb_format).symbol_suffix(" kWh/100km")},
                 {'id': 'consumption_fuel_km', 'name': 'average consumption fuel', 'type': 'numeric',
                  'format': deepcopy(nb_format).symbol_suffix(" L/100km")},
                 {'id': 'distance', 'name': 'distance', 'type': 'numeric',
                  'format': nb_format.symbol_suffix(" km").precision(1)},
                 {'id': 'mileage', 'name': 'mileage', 'type': 'numeric',
                  'format': nb_format.symbol_suffix(" km").precision(1)}],
        data=[tr.get_info() for tr in trips[::-1]],
        page_size=50
    )
    # consumption_fig
    consumption_df = DataFrame.from_records(trips.get_long_trips())
    consumption_fig = px.line(consumption_df, x="date", y="consumption", title='Consumption of the car')
    consumption_fig.update_layout(yaxis_title="Consumption kWh/100Km")

    consumption_fig_by_speed = px.histogram(consumption_df, x="speed", y="consumption_km", histfunc="avg",
                                            title="Consumption by speed")
    consumption_fig_by_speed.update_traces(xbins_size=15)
    consumption_fig_by_speed.update_layout(bargap=0.05)
    consumption_fig_by_speed.add_trace(
        go.Scatter(mode="markers", x=consumption_df["speed"], y=consumption_df["consumption_km"],
                   name="Trips"))
    consumption_fig_by_speed.update_layout(xaxis_title="average Speed km/h", yaxis_title="Consumption kWh/100Km")
    kw_per_km = float(consumption_df["consumption_km"].mean())
    info = "Average consumption: {:.1f} kWh/100km".format(kw_per_km)

    # charging
    charging_data = DataFrame.from_records(charging)
    co2_per_kw = __calculate_co2_per_kw(charging_data)
    co2_per_km = co2_per_kw * kw_per_km / 100
    try:
        charge_speed = 3600 * charging_data["kw"].mean() / \
                       (charging_data["stop_at"] - charging_data["start_at"]).mean().total_seconds()
    except (TypeError, KeyError):  # when there is no data yet:
        charge_speed = 0

    battery_info = dash_table.DataTable(
        id='battery_info',
        sort_action='native',
        columns=[{'id': 'name', 'name': ''},
                 {'id': 'value', 'name': ''}],
        style_header={'display': 'none'},
        style_data={'border': '0px'},
        data=[{"name": "Average emission:", "value": "{:.1f} g/km".format(co2_per_km)},
              {"name": " ", "value:": "{:.1f} g/kWh".format(co2_per_kw)},
              {"name": "Average charge speed:", "value": "{:.3f} kW".format(charge_speed)}])
    battery_info = html.Div(children=[html.Tr(
        [
            html.Td('Average emission:', rowSpan=2),
            html.Td("{:.1f} g/km".format(co2_per_km)),
        ]
    ),
        html.Tr(
            [
                "{:.1f} g/kWh".format(co2_per_kw),
            ]
        ),
        html.Tr(
            [
                html.Td("Average charge speed:"),
                html.Td("{:.3f} kW".format(charge_speed))
            ]
        )
    ])

    battery_table = dash_table.DataTable(
        id='battery-table',
        sort_action='native',
        sort_by=[{'column_id': 'start_at', 'direction': 'desc'}],
        columns=[{'id': 'start_at', 'name': 'start at', 'type': 'datetime'},
                 {'id': 'stop_at', 'name': 'stop at', 'type': 'datetime'},
                 {'id': 'start_level', 'name': 'start level', 'type': 'numeric'},
                 {'id': 'end_level', 'name': 'end level', 'type': 'numeric'},
                 {'id': 'co2', 'name': 'CO2', 'type': 'numeric',
                  'format': deepcopy(nb_format).symbol_suffix(" g/kWh").precision(1)},
                 {'id': 'kw', 'name': 'consumption', 'type': 'numeric',
                  'format': deepcopy(nb_format).symbol_suffix(" kWh").precision(3)}],
        data=charging,
    )
    consumption_by_temp_df = consumption_df[consumption_df["consumption_by_temp"].notnull()]
    if len(consumption_by_temp_df) > 0:
        consumption_fig_by_temp = px.histogram(consumption_by_temp_df, x="consumption_by_temp", y="consumption_km",
                                               histfunc="avg", title="Consumption by temperature")
        consumption_fig_by_temp.update_traces(xbins_size=2)
        consumption_fig_by_temp.update_layout(bargap=0.05)
        consumption_fig_by_temp.add_trace(
            go.Scatter(mode="markers", x=consumption_by_temp_df["consumption_by_temp"],
                       y=consumption_by_temp_df["consumption_km"], name="Trips"))
        consumption_fig_by_temp.update_layout(xaxis_title="average temperature in °C",
                                              yaxis_title="Consumption kWh/100Km")
        consumption_graph_by_temp = Graph(figure=consumption_fig_by_temp, id="consumption_fig_by_temp")

    else:
        consumption_graph_by_temp = Graph(style={'display': 'none'})
Beispiel #13
0
def get_figures(trips: Trips, charging: List[dict]):
    global consumption_fig, consumption_df, trips_map, consumption_fig_by_speed, table_fig, info, battery_info, \
        battery_table, consumption_graph_by_temp
    lats = []
    lons = []
    names = []
    for trip in trips:
        for points in trip.positions:
            lats = np.append(lats, points.latitude)
            lons = np.append(lons, points.longitude)
            names = np.append(names, [str(trip.start_at)])
        lats = np.append(lats, None)
        lons = np.append(lons, None)
        names = np.append(names, None)
    trips_map = px.line_mapbox(lat=lats,
                               lon=lons,
                               hover_name=names,
                               mapbox_style="stamen-terrain",
                               zoom=12)
    # table
    nb_format = Format(precision=2, scheme=Scheme.fixed, symbol=Symbol.yes)  # pylint: disable=no-member
    table_fig = dash_table.DataTable(
        id='trips-table',
        sort_action='native',
        sort_by=[{
            'column_id': 'id',
            'direction': 'desc'
        }],
        columns=[{
            'id': 'id',
            'name': '#',
            'type': 'numeric'
        }, {
            'id': 'start_at',
            'name': 'start at',
            'type': 'datetime'
        }, {
            'id':
            'duration',
            'name':
            'duration',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" min").precision(0)
        }, {
            'id':
            'speed_average',
            'name':
            'average speed',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" km/h").precision(0)
        }, {
            'id': 'consumption_km',
            'name': 'average consumption',
            'type': 'numeric',
            'format': deepcopy(nb_format).symbol_suffix(" kWh/100km")
        }, {
            'id': 'consumption_fuel_km',
            'name': 'average consumption fuel',
            'type': 'numeric',
            'format': deepcopy(nb_format).symbol_suffix(" L/100km")
        }, {
            'id': 'distance',
            'name': 'distance',
            'type': 'numeric',
            'format': nb_format.symbol_suffix(" km").precision(1)
        }, {
            'id': 'mileage',
            'name': 'mileage',
            'type': 'numeric',
            'format': nb_format
        }, {
            'id': 'altitude_diff',
            'name': 'Altitude diff',
            'type': 'numeric',
            'format': deepcopy(nb_format).symbol_suffix(" m").precision(0)
        }],
        style_data_conditional=[{
            'if': {
                'column_id': ['altitude_diff']
            },
            'color': 'dodgerblue',
            "text-decoration": "underline"
        }],
        data=trips.get_info(),
        page_size=50)
    # consumption_fig
    consumption_df = DataFrame.from_records(trips.get_long_trips())
    consumption_fig = px.histogram(consumption_df,
                                   x="date",
                                   y="consumption_km",
                                   title='Consumption of the car',
                                   histfunc="avg")
    consumption_fig.update_layout(yaxis_title="Consumption kWh/100Km")

    consumption_fig_by_speed = px.histogram(consumption_df,
                                            x="speed",
                                            y="consumption_km",
                                            histfunc="avg",
                                            title="Consumption by speed")
    consumption_fig_by_speed.update_traces(xbins_size=15)
    consumption_fig_by_speed.update_layout(bargap=0.05)
    consumption_fig_by_speed.add_trace(
        go.Scatter(mode="markers",
                   x=consumption_df["speed"],
                   y=consumption_df["consumption_km"],
                   name="Trips"))
    consumption_fig_by_speed.update_layout(xaxis_title="average Speed km/h",
                                           yaxis_title="Consumption kWh/100Km")
    kw_per_km = float(consumption_df["consumption_km"].mean())
    info = "Average consumption: {:.1f} kWh/100km".format(kw_per_km)

    # charging
    charging_data = DataFrame.from_records(charging)
    co2_per_kw = __calculate_co2_per_kw(charging_data)
    co2_per_km = co2_per_kw * kw_per_km / 100
    try:
        charge_speed = 3600 * charging_data["kw"].mean() / \
                       (charging_data["stop_at"] - charging_data["start_at"]).mean().total_seconds()
        price_kw = (charging_data["price"] / charging_data["kw"]).mean()
        total_elec = kw_per_km * trips.get_distance() / 100
    except (TypeError, KeyError,
            ZeroDivisionError):  # when there is no data yet:
        charge_speed = 0
        price_kw = 0
        total_elec = 0

    SUMMARY_CARDS["Average charge speed"]["text"] = f"{charge_speed:.2f} kW"
    SUMMARY_CARDS["Average emission"]["text"] = [
        html.P(f"{co2_per_km:.1f} g/km"),
        html.P(f"{co2_per_kw:.1f} g/kWh")
    ]
    SUMMARY_CARDS["Electricity consumption"]["text"] = [f"{total_elec:.0f} kWh", html.Br(), \
                                                        f"{total_elec * price_kw:.0f} {ElecPrice.currency}"]
    SUMMARY_CARDS["Average consumption"][
        "text"] = f"{consumption_df['consumption_km'].mean():.1f} kWh/100km"
    battery_table = dash_table.DataTable(
        id='battery-table',
        sort_action='native',
        sort_by=[{
            'column_id': 'start_at',
            'direction': 'desc'
        }],
        columns=[{
            'id': 'start_at',
            'name': 'start at',
            'type': 'datetime'
        }, {
            'id': 'stop_at',
            'name': 'stop at',
            'type': 'datetime'
        }, {
            'id': 'start_level',
            'name': 'start level',
            'type': 'numeric'
        }, {
            'id': 'end_level',
            'name': 'end level',
            'type': 'numeric'
        }, {
            'id':
            'co2',
            'name':
            'CO2',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" g/kWh").precision(1)
        }, {
            'id':
            'kw',
            'name':
            'consumption',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" kWh").precision(2)
        }, {
            'id':
            'price',
            'name':
            'price',
            'type':
            'numeric',
            'format':
            deepcopy(nb_format).symbol_suffix(" " +
                                              ElecPrice.currency).precision(2),
            'editable':
            True
        }],
        data=charging,
        style_data_conditional=[{
            'if': {
                'column_id': ['start_level', "end_level"]
            },
            'color': 'dodgerblue',
            "text-decoration": "underline"
        }, {
            'if': {
                'column_id': 'price'
            },
            'backgroundColor': 'rgb(230, 246, 254)'
        }],
    )
    consumption_by_temp_df = consumption_df[
        consumption_df["consumption_by_temp"].notnull()]
    if len(consumption_by_temp_df) > 0:
        consumption_fig_by_temp = px.histogram(
            consumption_by_temp_df,
            x="consumption_by_temp",
            y="consumption_km",
            histfunc="avg",
            title="Consumption by temperature")
        consumption_fig_by_temp.update_traces(xbins_size=2)
        consumption_fig_by_temp.update_layout(bargap=0.05)
        consumption_fig_by_temp.add_trace(
            go.Scatter(mode="markers",
                       x=consumption_by_temp_df["consumption_by_temp"],
                       y=consumption_by_temp_df["consumption_km"],
                       name="Trips"))
        consumption_fig_by_temp.update_layout(
            xaxis_title="average temperature in °C",
            yaxis_title="Consumption kWh/100Km")
        consumption_graph_by_temp = html.Div(
            Graph(figure=consumption_fig_by_temp),
            id="consumption_graph_by_temp")

    else:
        consumption_graph_by_temp = html.Div(Graph(style={'display': 'none'}),
                                             id="consumption_graph_by_temp")
    return True
Beispiel #14
0
def historic(app,
             tsa,
             routes_pathname_prefix='/tshistory/',
             request_pathname_prefix='/',
             cachedir=None):

    request_pathname_prefix_adv = request_pathname_prefix + routes_pathname_prefix

    external_stylesheets = [
        'https://codepen.io/chriddyp/pen/bWLwgP.css',
        'https://cdn.rawgit.com/plotly/dash-app-stylesheets/2d266c578d2a6e8850ebce48fdb52759b2aef506/stylesheet-oil-and-gas.css'
    ]

    if request_pathname_prefix != '/':
        dashboard = dash.Dash(
            'tsview',
            server=app,
            routes_pathname_prefix=routes_pathname_prefix,
            requests_pathname_prefix=request_pathname_prefix_adv,
            external_stylesheets=external_stylesheets)
    else:
        dashboard = dash.Dash('tsview',
                              server=app,
                              url_base_pathname=routes_pathname_prefix,
                              external_stylesheets=external_stylesheets)

    dashboard.config['suppress_callback_exceptions'] = True
    if request_pathname_prefix != '/':
        dashboard.config.requests_pathname_prefix = request_pathname_prefix_adv

    if cachedir:
        cacheconfig = {'CACHE_TYPE': 'filesystem', 'CACHE_DIR': cachedir}
    else:
        cacheconfig = {'CACHE_TYPE': 'simple'}
    cache = Cache(dashboard.server, config=cacheconfig)
    cache.init_app(dashboard.server)

    dashboard.layout = Div([
        Location(id='url', refresh=False),

        #Placeholders
        Div(Dropdown(id='idate_slider', value=None), style={'display':
                                                            'none'}),
        Graph(id='ts_snapshot'),
        Button(id='submit-button',
               n_clicks=0,
               children='Show Republications',
               style={
                   'width': '100%',
                   'background-color': '#F7F7F7',
               }),
        Graph(id='ts_by_appdate', hoverData={'points': [{
            'text': None
        }]}),
        html.P('Select an insertion date:',
               style={
                   'font-family': 'Helvetica',
                   "font-size": "100%",
                   'text-align': 'center',
               }),
        Div(id='slider-container'),
        Div([Br()]),
        Div([Br()]),
        html.P(
            'Place the mouse on the graph above to see the versions '
            'of one application date:',
            style={
                'font-family': 'Helvetica',
                "font-size": "100%",
                'text-align': 'center',
            }),
        Graph(id='ts_by_insertdate'),
    ])

    @cache.memoize(timeout=300)
    def _history(id_serie, fromdate, todate):
        return {
            # canonicalize the keys immediately
            dt.strftime('%Y-%m-%d %H:%M:%S'): serie
            for dt, serie in tsa.history(id_serie,
                                         from_value_date=fromdate,
                                         to_value_date=todate).items()
        }

    def history(id_serie, fromdate=None, todate=None):
        return _history(id_serie, fromdate, todate)

    def insertion_dates(id_serie, fromdate=None, todate=None):
        return list(history(id_serie, fromdate, todate).keys())

    def parse_url(url_string):
        if (url_string in (routes_pathname_prefix, request_pathname_prefix_adv)
                or url_string is None or len(url_string.strip('/')) == 0):
            id_serie = ''
        else:
            id_serie = url_string.split('/')[-1]
        return id_serie

    @dashboard.callback(
        dash.dependencies.Output('slider-container', 'children'), [
            dash.dependencies.Input('url', 'pathname'),
            dash.dependencies.Input('submit-button', 'n_clicks')
        ], [dash.dependencies.State('ts_snapshot', 'relayoutData')])
    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

    @dashboard.callback(dash.dependencies.Output('ts_snapshot', 'figure'),
                        [dash.dependencies.Input('url', 'pathname')])
    def ts_snapshot(url_string):
        id_serie = parse_url(url_string)
        ts = tsa.get(id_serie)

        if id_serie is None or ts is None:
            return {'data': [], 'layout': {}}

        trace = [
            go.Scatter(x=ts.index,
                       y=ts.values,
                       name=id_serie,
                       mode='lines',
                       line={'color': ('rgb(255, 127, 80)')})
        ]
        layout = go.Layout({
            'yaxis': {
                'fixedrange': True
            },
            'showlegend': True,
            'title': 'Zoom to select the date interval:'
        })

        return {'data': trace, 'layout': layout}

    @dashboard.callback(dash.dependencies.Output('ts_by_appdate', 'figure'), [
        dash.dependencies.Input('idate_slider', 'value'),
        dash.dependencies.Input('submit-button', 'n_clicks')
    ], [
        dash.dependencies.State('url', 'pathname'),
        dash.dependencies.State('ts_snapshot', 'relayoutData')
    ])
    def ts_by_appdate(idx, n_clicks, url_string, graphdata):
        if n_clicks == 0:
            return {'data': [], 'layout': {}}

        fromdate, todate = unpack_dates(graphdata)
        idx = idx if idx else 0

        id_serie = parse_url(url_string)
        ts_final = tsa.get(id_serie,
                           from_value_date=fromdate,
                           to_value_date=todate)
        versions = history(id_serie, fromdate, todate)
        idates = list(versions.keys())

        if idx > len(idates):
            # may happen when the input div are not refreshed at the same time
            idx = len(idates) - 1

        insert_date = idates[idx]
        ts_unti_now = versions[insert_date]

        traces = []
        # all versions
        for idate in idates:
            ts = versions[idate].loc[fromdate:todate]
            # plolty does not plot a line with only one point
            mode = 'lines' if len(ts) > 1 else 'markers'
            color = COLOR_BEFORE if idate <= insert_date else COLOR_AFTER
            traces.append(
                go.Scatter(x=ts.index,
                           y=ts.values,
                           text=[str(elt) for elt in ts.index],
                           name=idate,
                           showlegend=False,
                           mode=mode,
                           line={'color': color},
                           opacity=0.2))

        # final snapshot
        traces.append(
            go.Scatter(x=ts_final.index,
                       y=ts_final.values,
                       name='last',
                       text=[str(elt) for elt in ts_final.index],
                       mode='lines',
                       line={'color': COLOR_LAST},
                       opacity=1))

        # ts as of
        mode = 'lines' if len(ts_unti_now) > 1 else 'markers'
        traces.append(
            go.Scatter(
                x=ts_unti_now.index,
                y=ts_unti_now.values,
                text=[str(elt) for elt in ts_unti_now.index],
                name=str(pd.to_datetime(insert_date)),
                mode=mode,
                line={'color': COLOR_CURRENT},
            ))

        tsminvalue = min(ts.values.min() for ts in versions.values()
                         if len(ts))
        tsmaxvalue = max(ts.values.max() for ts in versions.values()
                         if len(ts))

        return {
            'data':
            traces,
            'layout':
            go.Layout(
                hovermode='closest',
                xaxis={'range': [ts_final.index.min(),
                                 ts_final.index.max()]},
                yaxis={'range': [tsminvalue, tsmaxvalue]},
                title='{} <br>Insertion date : {}'.format(
                    id_serie, insert_date),
                shapes=[{
                    'type': 'line',
                    'x0': insert_date,
                    'y0': tsminvalue,
                    'x1': insert_date,
                    'y1': tsmaxvalue,
                    'line': {
                        'dash': 'dot',
                        'color': 'rgb(0, 0, 0)',
                        'width': 1
                    }
                }])
        }

    @dashboard.callback(
        dash.dependencies.Output('ts_by_insertdate', 'figure'),
        [dash.dependencies.Input('ts_by_appdate', 'hoverData')], [
            dash.dependencies.State('url', 'pathname'),
            dash.dependencies.State('ts_snapshot', 'relayoutData')
        ])
    def ts_by_insertdate(hoverdata, url_string, graphdata):
        id_serie = parse_url(url_string)
        if id_serie is None:
            return {'data': [], 'layout': {}}

        date_str = hoverdata['points'][0]['text']
        if date_str is None:
            return {'data': [go.Scatter()], 'layout': go.Layout()}

        fromdate, todate = unpack_dates(graphdata)

        versions = history(id_serie, fromdate, todate)
        index = []
        values = []

        lastvalue = None
        dt = pd.to_datetime(date_str)
        for idate, ts in sorted(versions.items()):
            if dt in ts.index:
                value = ts[dt]
                if value == lastvalue:
                    continue
                index.append(idate)
                values.append(value)
                lastvalue = value

        traces = [
            go.Scatter(
                x=index,
                y=values,
                name=date_str,
                mode='lines',
                line={'color': ('rgb(20, 180, 40)')},
            )
        ]

        return {
            'data':
            traces,
            'layout':
            go.Layout(
                hovermode='closest',
                title='Application date : {}'.format(date_str),
            )
        }
Beispiel #15
0
def create_app():
    app = Flask(__name__)

    dash_app = Dash(__name__,
                    server=app,
                    url_base_pathname='/dash/',
                    external_stylesheets=[{
                        "href":
                        "https://fonts.googleapis.com/css2?"
                        "family=Lato:wght@400;700&display=swap",
                        "rel":
                        "stylesheet",
                    }])

    dash_app.layout = Div(children=[
        Div(children=[
            P(children='📈', className='header-emoji'),
            H1(children='Dash-PTS', className='header-title'),
            P(
                children='''
                        A Free and Open Source project-tracking systems tool:
                        ''',
                className='header-description',
            ),
            P(
                children='https://github.com/dunossauro/dash-pts',
                className='header-description',
            ),
        ],
            className='header'),
        Div(
            children=[
                Div(children=[
                    Div(children='Department', className='menu-title'),
                    Dropdown(id='department-name',
                             options=[{
                                 'label': i,
                                 'value': i
                             } for i in ['Sales', 'R&D', 'Support']],
                             value='R&D',
                             className='dropdown')
                ], ),
                Div(children=[
                    Div(children='Team', className='menu-title'),
                    Dropdown(
                        id='team-name',
                        options=[{
                            'label': i,
                            'value': i
                        } for i in ['Data Science', 'Mobile', 'WEB', 'QA']],
                        value='Mobile',
                        className='dropdown')
                ], ),
            ],
            className='menu',
        ),
        Div(
            children=[
                Graph(
                    id='burn-down',
                    className='card',
                    config={'displayModeBar': False},
                ),
                Graph(
                    id='velocity',
                    className='card',
                    config={'displayModeBar': False},
                )
            ],
            className='wrapper',
        )
    ], )

    @app.route('/dash')
    def index():
        return dash_app.index()

    @dash_app.callback([
        Output(component_id='burn-down', component_property='figure'),
        Output(component_id='velocity', component_property='figure'),
    ], [
        Input(component_id='team-name', component_property='value'),
        Input(component_id='department-name', component_property='value'),
    ])
    def generate_graphs(team_name, department_name):
        return (burn_down(
            sprint='',
            initial_data=datetime(2021, 4, 5),
            final_data=datetime(2021, 4, 16),
            total_points=50,
            sprint_data=[50, 45, 41, 37, 39, 39, 39, 35, 27, 13],
        ),
                velocity({
                    'names': ['Sprint ' + str(x) for x in range(1, 7)],
                    'commitment': [50, 47, 61, 53, 50, 51],
                    'completed': [52, 43, 58, 58, 49, 39],
                }))

    return app
Beispiel #16
0
                        sort_mode='multi',
                        filter_action='native',
                        page_size=50,
                    ),
                ], style={'width': '100%'})
            ], className='div-content-center', style={'textAlign': 'center'})
        ]
    ),

    # graph
    Loading(
        id='download--loading--graph--time-series--number-of-downloaded-scenes-by-date',
        type='circle',
        color=colors['text'],
        children=[
            Graph(id='download--graph--graph--time-series--number-of-downloaded-scenes-by-date')
        ]
    ),

    # map
    Loading(
        id='download--loading--map--number-of-downloaded-scenes-by-location',
        type='circle',
        color=colors['text'],
        children=[
            # leaflet map - my code
            Div([
                # title
                P(
                    children='Map: Number of Downloaded Scenes by Location (long/lat)',
                    style={'textAlign': 'left', 'color': colors['text']}
Beispiel #17
0
    def draw_graph(in_interval, in_channels_selected, in_zoom_in, in_zoom_out, in_reset, in_playstop, in_expand_graphs):
        global df, data_shown, playpause, expand_graphs

        changed_id = [p['prop_id'] for p in callback_context.triggered][0]

        if 'zoom_in' in changed_id:
            if data_shown != 200:
                data_shown = data_shown - 200
        if 'zoom_out' in changed_id:
            data_shown = data_shown + 200
        if 'reset' in changed_id:
            data_shown = 1400
        if 'playstop' in changed_id:
            playpause = True if playpause == False else False

        graphs = []
        for index, inlet in enumerate(inlets):
            if playpause == True:
                samples, timestamps = inlet.pull_chunk(timeout=0.0, max_samples=1024)
                utc = [datetime.utcfromtimestamp(timestamp).replace(tzinfo=timezone.utc).astimezone(tz=None).strftime('%H:%M:%S.%f') for index, timestamp in enumerate(timestamps)]

                df_aux = pd.DataFrame(samples, columns=cols[index], index=utc)
                df[index] = df[index].append(df_aux)
                df_to_show = df[index].tail(data_shown)
                df_to_show = df_to_show[in_channels_selected]
            else:
                df_to_show = df[index].tail(data_shown)
                df_to_show = df_to_show[in_channels_selected]
            
            channel_qualities = []
            for i in in_channels_selected:
                if abs(df_to_show[i].tail(200).max() - df_to_show[i].tail(200).min()) < 300:
                    channel_qualities.append(i + ' - GOOD ' + u'\u2713')
                else:
                    channel_qualities.append(i + ' - BAD ' + u'\u2716')

            if in_expand_graphs == False:
                if len(df_to_show.columns) % 2 == 0:
                    fig = make_subplots(rows=int(len(df_to_show.columns) / 2), cols=2, subplot_titles=channel_qualities)
                else:
                    fig = make_subplots(rows=int((len(df_to_show.columns) / 2) + 0.5), cols=2, subplot_titles=channel_qualities)
                
                j = [1, 1, 2, 2, 3]
                k = [1, 2, 1, 2, 1]
                for index2, column in enumerate(df_to_show.columns):
                    fig.add_trace(
                        Scatter({
                            'x': df_to_show.index2,
                            'y': df_to_show[column]
                        }),
                        row=j[index2],
                        col=k[index2]
                    )
                heights = [500, 500, 800, 800, 1100]
                fig.update_layout(height=heights[len(df_to_show.columns)-1], showlegend=False)
            else:
                fig = make_subplots(rows=len(df_to_show.columns), cols=1, subplot_titles=channel_qualities)
                j = 1
                for i in df_to_show.columns:
                    fig.add_trace(
                        Scatter({
                            'x': df_to_show.index,
                            'y': df_to_show[i]
                        }),
                        row=j,
                        col=1
                    )
                    j += 1
                heights = [500, 900, 1200, 1500, 1600]
                fig.update_layout(height=heights[len(df_to_show.columns)-1], showlegend=False)

            graphs.append(
                html.Div([
                    html.H3(inlet.info().name()),
                    Graph(
                        id='muse_livestream',
                        config={
                            'displaylogo': False,
                            'modeBarButtonsToRemove': ['pan2d','lasso2d']
                        },
                        figure=fig
                    )
                ], style={'margin': 'auto', 'text-align': 'center'})
            )

        return(html.Div(graphs))
Beispiel #18
0
 html.Div(
     id="map-container",
     children=[
         Graph(
             id="choropleth",
             # figure=dict(
             #     # data=[
             #     #     dict(
             #     #         lat=df_lat_lon["Latitude "],
             #     #         lon=df_lat_lon["Longitude"],
             #     #         text=df_lat_lon["Hover"],
             #     #         type="scattermapbox",
             #     #     )
             #     # ],
             #     layout=dict(
             #         mapbox=dict(
             #             layers=[],
             #             accesstoken=mapbox_access_token,
             #             style=mapbox_style,
             #             center=dict(
             #                 lat=38.72490, lon=-95.61446
             #             ),
             #             pitch=0,
             #             zoom=3.5,
             #         ),
             #         autosize=True,
             #     ),
             # ),
         ),
     ],
     className="six columns"),
 html.Div(children=[
Beispiel #19
0
 def get_html(self) -> List[ComponentMeta]:
     """Initializes the header dash html
     """
     today = date.today().strftime(self.content["date-format"])
     return [
         Container(
             className="mt-5",
             children=[
                 H2(self.content["new-admissions-title"]),
                 Markdown(self.content["new-admissions-text"]),
             ]
         ),
         Container(fluid=True, children=Graph(id="new_admissions_graph")),
         Container([
             A(
                 self.content["download-text"],
                 id="new_admissions_download",
                 download="admissions_{}.csv".format(today),
                 href="",
                 target="_blank",
                 className="btn btn-sm btn-info",
             ),
             Div(
                 children=Button(
                     "Lock Zoom", 
                     id="new_admissions_lock_zoom", 
                     color="info", 
                     outline=False,
                     className="btn btn-sm"
                     ),
                 style={"display": "inline-block", "padding": 10}
             ),
             Div(
                 className="row justify-content-center",
                 children=Div(
                     id="new_admissions_table_container",
                     className="col-auto",
                     children=Table(
                         id="new_admissions_table",
                         className="table-responsive mx-auto"
                     ),
                 ),
             ),
         ]),
         Container(
             className="mt-5",
             children=[
                 H2(self.content["admitted-patients-title"]),
                 Markdown(self.content["admitted-patients-text"]),
             ],
         ),
         Container(fluid=True, children=Graph(id="admitted_patients_graph")),
         Container([
             A(
                 self.content["download-text"],
                 id="admitted_patients_download",
                 download="census_{}.csv".format(today),
                 href="",
                 target="_blank",
                 className="btn btn-sm btn-info",
             ),
             Div(
                 children=Button(
                     "Lock Zoom", 
                     id="admitted_patients_lock_zoom", 
                     color="info", 
                     outline=False, 
                     className="btn btn-sm"
                     ),
                 style={"display": "inline-block", "padding": 10}
             ),
             Div(
                 className="row justify-content-center",
                 children=Div(
                     id="admitted_patients_table_container",
                     className="col-auto",
                     children=Table(
                         id="admitted_patients_table",
                         className="table-responsive"
                     ),
                 ),
             ),
         ]),
         Container(
             className="mt-5",
             children=[
                 H2(self.content["SIR-title"]),
                 Markdown(self.content["SIR-text"]),
             ],
         ),
         Container(fluid=True, children=Graph(id="SIR_graph")),
         Container([
             A(
                 self.content["download-text"],
                 id="SIR_download",
                 download="SIR_{}.csv".format(today),
                 href="",
                 target="_blank",
                 className="btn btn-sm btn-info my-4",
             ),
             Div(
                 children=Button(
                     "Lock Zoom", 
                     id="SIR_lock_zoom", 
                     color="info", 
                     outline=False, 
                     className="btn btn-sm"
                     ),
                 style={"display": "inline-block", "padding": 10}
             ),
             Div(
                 className="row justify-content-center",
                 children=Div(
                     id="SIR_table_container",
                     className="col-auto",
                     children=Table(
                         id="SIR_table",
                         className="table-responsive"
                     ),
                 ),
             ),
         ])
     ]
Beispiel #20
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")
            ])
Beispiel #21
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 #22
0
    }, {
        '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': [
                  {
                      'y': database['maiores'],
                      'x': database['index'],
                      'name': 'Maiores'
                  },
              ],
          })
])

app.run_server(debug=True)
options = []
for k, v in indicators.iteritems():
    options.append({'label': k, 'value': k, 'disabled': True})
    for i in v:
        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"),
    ],
Beispiel #24
0
                    )
                ], className='div-content-center'),
                P(
                    id='scene--output-container-date-picker-range',
                    style={'color': colors['text']}
                )
            ])
        ], style={'width': '50%'}),
    ], className='div-content-center'),

    # add a loading component during graph loading
    Loading(
        id='scene--loading--graph--bubble-map--number-of-scenes',
        type='circle',
        color=colors['text'],
        children=[Graph(id='scene--graph--bar-plot--number-of-scenes')]
    ),

    # map
    Loading(
        id='scene--loading--map--number-of-scenes-by-location',
        type='circle',
        color=colors['text'],
        children=[
            # leaflet map - my code
            Div([
                # title
                P(
                    children='Map: Number of Scenes by Location (long/lat) and Year-Month',
                    style={'textAlign': 'left', 'color': colors['text']}
                ),
Beispiel #25
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 #26
0
        html.Div(id='date_selector_container',
                 children=[
                     html.H4(id='text_date_selector'),
                     DatePickerSingle(id='date_selector',
                                      min_date_allowed=min_date,
                                      max_date_allowed=max_date,
                                      date=max_date),
                     html.Br(),
                 ],
                 className="six columns"),
    ],
             className="row"),
    html.Div([
        html.Div(id="map-container",
                 children=[
                     Graph(id="choropleth", ),
                 ],
                 className="six columns"),
        html.Div(children=[
            html.H5(id='text_map_description'),
            html.Div(id='pie-container',
                     children=[
                         Graph(id='piechart'),
                         html.H5(id='text_pie_description'),
                     ])
        ],
                 className="six columns"),
    ],
             className="row"),
])
Beispiel #27
0
              }],
              value=['bebes']),
    Dropdown(id='meu_dropdown',
             options=[
                 {
                     'label': 'Linha',
                     'value': 'line'
                 },
                 {
                     'label': 'Barra',
                     'value': 'bar'
                 },
             ],
             value='line'),
    Graph(
        id='meu_grafico',
        config={'displayModeBar': False},
    )
])


@app.callback(Output('meu_grafico', 'figure'), [
    Input('meu_check_list', 'value'),
    Input('meu_dropdown', 'value'),
])
def my_callback(input_data, graph_type):
    grafico = {'data': []}
    for x in input_data:
        grafico['data'].append(
            {
                'y': database[x],
                'x': database['index'],
Beispiel #28
0
def icon(src, href, title):
    return A(
        [
            Img(
                src=f'/assets/{src}.png',
                className='icon',
            ),
        ],
        href=href,
        title=title,
    )


app.layout = Div([
    Graph(id='graph'),
    Row(
        [
            Col(
                [
                    Div(
                        [
                            'Date Range:',
                            Button( '1y', id='date-1yr',),
                            Button( '2y', id='date-2yr',),
                            Button( '3y', id='date-3yr',),
                            Button( '4y', id='date-4yr',),
                            Button( '5y', id='date-5yr',),
                            Button('All', id='date-all',),
                        ],
                        className='control-header',
Beispiel #29
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,
        ]
             "background": "white",
             "border": "#d6d6d6",
             "primary": "#1975FA",
         },
     ),
     Div(
         children=[
             P(
                 id="tab-text",
                 style={"margin": "20px", "font-size": "13px"},
             )
         ]
         + [
             Div(
                 Graph(
                     id=x + "-graph"
                 ),
                 id=x + "-graph-div",
                 style={"display": "none"}
             )
             for x in TAB_DICT.keys()
         ],
         style={"border": "1px solid #d6d6d6"},
     ),
 ],
 className="nine columns",
 style={
     "padding-left": 20,
     "padding-right": 2,
     "background-color": "white",
     "padding-top": 20,