def linkedin():
    if st.button('Linkedin'):
        js = "window.open('https://www.linkedin.com/in/silviocesarlima/')"  # New tab or window
        #js = "window.location.href = 'https://www.streamlit.io/'"  # Current tab
        html = '<img src onerror="{}">'.format(js)
        div = Div(text=html)
        st.bokeh_chart(div)
示例#2
0
def create_condition_page():
    st.title('Сторінка для створення власної умови задачі')
    annotation = get_condition_state()
    if st.button('Додати експерта'):
        annotation.append(tuple())

    if st.button('Видалити останнього експерта'):
        annotation.pop(len(annotation) - 1)

    for i in range(len(annotation)):
        st.subheader('Експерт №{}'.format(i + 1))
        a = st.number_input('Початок роботи {}-го експерта'.format(i + 1),
                            step=1,
                            value=5,
                            min_value=1,
                            max_value=100)
        b = st.number_input('Кінець роботи {}-го експерта'.format(i + 1),
                            step=1,
                            value=20,
                            min_value=1,
                            max_value=100)
        annotation[i] = (a, b)

    if st.button('Візуалізувати'):
        st.bokeh_chart(draw_graphic_of_condition(annotation))
    if st.button('Створити'):
        create_file_with_condition(annotation)
示例#3
0
def plot_model_distributions(policy, row):
    model = policy.module.model
    n_samples = st.number_input("Number of observation samples",
                                min_value=1,
                                step=1)
    samples = get_model_samples(model, row, n_samples)

    data = {f"obs[{i}]": samples[..., i] for i in range(samples.shape[-1])}
    dataset = pd.DataFrame(data)

    new_obs = row[SampleBatch.NEXT_OBS]
    target_data = {
        f"new_obs[{i}]": new_obs[i][None]
        for i in range(new_obs.shape[-1])
    }
    target_dataset = pd.DataFrame(target_data)

    bins = st.number_input(
        "Histogram bins",
        min_value=1,
        max_value=n_samples,
        value=(1 + n_samples) // 2,
        step=1,
    )
    st.bokeh_chart(make_histograms(dataset, bins))
    st.bokeh_chart(scatter_matrix(dataset, target_dataset))
示例#4
0
def bokeh_histogram(x,
                    y,
                    pay_norm,
                    x_label: str,
                    y_label: str,
                    x_range: list,
                    title: str = '',
                    bc: str = "#f0f0f0",
                    bfc: str = "#fafafa"):

    bin_size = x[1] - x[0]

    s = bokeh_fig_init(x_range=x_range,
                       title=title,
                       x_label=x_label,
                       y_label=y_label,
                       bc=bc,
                       bfc=bfc)

    # Add copyright
    l1 = add_copyright()
    s.add_layout(l1)

    s.vbar(x=x,
           top=y,
           width=0.95 * bin_size,
           fill_color="#f8b739",
           fill_alpha=0.5,
           line_color=None)
    if CURRENCY_NORM and pay_norm == 1:
        s.xaxis[0].formatter = PrintfTickFormatter(format="$%ik")
    else:
        s.xaxis[0].formatter = PrintfTickFormatter(format="$%i")
    st.bokeh_chart(s, use_container_width=True)
def run():
    st.title("Mohr's Circle App")

    stress_x = st.sidebar.number_input("stress in x", value=2.0, step=0.1)
    stress_y = st.sidebar.number_input("stress in y", value=5.0, step=0.1)
    shear = st.sidebar.number_input("shear xy", value=4.0, step=0.1)

    # find center and radius
    C, r = mohr_c(stress_x, stress_y, shear)

    # build arrays plot circle
    circle_x, circle_y = c_array(C, r)

    # build arrays to plot line through the circle
    X, Y = X_Y(stress_x, stress_y, shear)

    st.sidebar.markdown(f"max stress = {round(C+r,2)}")
    st.sidebar.markdown(f"min stress = {round(C-r,2)}")
    st.sidebar.markdown(f"max shear = {round(r,2)}")

    p = figure(
        title="Mohr's Circle",
        x_axis_label="stress",
        y_axis_label="shear",
        match_aspect=True,
        tools="pan,reset,save,wheel_zoom",
    )

    p.line(circle_x, circle_y, color="#1f77b4", line_width=3, line_alpha=0.6)
    p.line(X, Y, color="#ff7f0e", line_width=3, line_alpha=0.6)

    p.xaxis.fixed_location = 0
    p.yaxis.fixed_location = 0

    st.bokeh_chart(p)
示例#6
0
def main():

    st.title('Figurinhas!!')
    st.write(
        "Vamos analisar a nossa rede sociais de participantes das figurinhas..."
    )

    people = get_people()
    data = get_netdata()

    option = st.selectbox('Gostaria de ver a rede de qual jogador?',
                          ['None'] + people['user'].tolist())

    if option != "None":
        'Você selecionou: ', option, "\n\nConfira as informações básicas deste usuário:\n"
        st.table(people[people['user'] == option].rename(
            columns={
                "user": "******",
                "qtde_relacionamentos": "Relacionamentos",
                "qtde_figurinhas": "Figurinhas Trocadas"
            }))
        simple_graph = get_user_network(data, option)
    else:
        st.dataframe(
            people.rename(
                columns={
                    "user": "******",
                    "qtde_relacionamentos": "Relacionamentos",
                    "qtde_figurinhas": "Figurinhas Trocadas"
                }))

        simple_graph = make_network(data)

    st.bokeh_chart(hv.render(simple_graph, backend='bokeh'),
                   use_container_width=True)
示例#7
0
def main():
    """A Reactive View of the KickstarterDashboard"""
    kickstarter_df = get_kickstarter_df()
    kickstarter_dashboard = KickstarterDashboard(kickstarter_df=kickstarter_df)
    st.markdown(__doc__)
    st.info(INFO)

    options = get_categories()
    categories_selected = st.multiselect("Select Categories", options=options)
    if not categories_selected and kickstarter_dashboard.categories:
        kickstarter_dashboard.categories = []
    else:
        kickstarter_dashboard.categories = categories_selected

    st.sidebar.title("Selections")
    x_range = st.sidebar.slider("Select create_at range", 2009, 2018,
                                (2009, 2018))
    y_range = st.sidebar.slider("Select usd_pledged", 0.0, 5.0, (0.0, 5.0))
    filter_df = KickstarterDashboard.filter_on_categories(
        kickstarter_df, categories_selected)
    filter_df = kickstarter_dashboard.filter_on_ranges(
        filter_df,
        (pd.Timestamp(x_range[0], 1, 1), pd.Timestamp(x_range[1], 12, 31)),
        y_range)
    kickstarter_dashboard.scatter_df = filter_df

    st.bokeh_chart(hv.render(kickstarter_dashboard.scatter_plot_view()))
    st.bokeh_chart(hv.render(kickstarter_dashboard.bar_chart_view()))
示例#8
0
def app():
    if variable_store.status == True:
        if variable_store.product != None:
            title_value = 'Price comparison for ' + variable_store.product
            st.header(title_value)
            # ams_price = scrape_ams(variable_store.product_references[variable_store.product][3])
            st.write(
                'Amazon Price for the product - ',
                variable_store.product_references[variable_store.product][4])
            st.write(
                'Walmart Price for the product - ',
                variable_store.product_references[variable_store.product][5])
            st.write(
                'eBay Price for the product - ',
                variable_store.product_references[variable_store.product][6])
            x = [1, 2, 3]
            y = [
                variable_store.product_references[variable_store.product][4],
                variable_store.product_references[variable_store.product][5],
                variable_store.product_references[variable_store.product][6]
            ]
            p = figure(
                title='simple line example',
                x_axis_label=
                'Amazon                -                 Walmart                -                 Ebay',
                y_axis_label='Cost')
            p.line(x, y, line_width=1)
            st.bokeh_chart(p, use_container_width=False)
        else:
            st.write(variable_store.product_error_msg)
    else:
        st.write("Please login first")
示例#9
0
def plot_ratings(df, highlight):
    colors = ["blue", "firebrick", "black", "gold"]
    sources = []
    for name in highlight:
        sources.append(
            ColumnDataSource(df[df["Alias"] == name].sort_values(
                'Date', ascending=True)))

    TOOLS = 'save,pan,box_zoom,reset,wheel_zoom'
    p = figure(title="Rating over Time",
               x_axis_type='datetime',
               y_axis_type="linear",
               plot_height=400,
               tools=TOOLS,
               plot_width=800)
    p.background_fill_color = "#dddddd"
    p.background_fill_alpha = 0.1
    p.title.align = "center"
    p.xaxis.axis_label = 'Date'
    p.yaxis.axis_label = 'Rating'

    for item in sources:
        p.line(x="Date",
               y="Rating",
               line_color=colors[sources.index(item)],
               line_width=1,
               source=item)

    p.add_tools(
        HoverTool(tooltips=[("Alias", "@Alias"), ("Date", "@Date{%Y-%m-%d}"),
                            ('Rating', '@Rating')],
                  formatters={'@Date': 'datetime'}))

    st.bokeh_chart(p)
    def plot_andamenti_dl(self, fitModel):
        if fitModel != 0:
            history_dict = fitModel.history
            history_dict.keys()

            acc = history_dict['mean_absolute_error']
            val_acc = history_dict['val_mean_absolute_error']
            loss = history_dict['loss']
            val_loss = history_dict['val_loss']

            epochs = range(1, len(acc) + 1)

            ds().nuova_fig(1)
            ds().titoli(titolo="Training loss", xtag='Epochs', ytag='Loss', griglia=0)
            ds().dati(epochs, loss, descrizione = 'Training loss', colore='red')
            ds().dati(epochs, val_loss, descrizione = 'Validation loss')
            ds().dati(epochs, loss, colore='red', scat_plot ='scat', larghezza_riga =10)
            ds().dati(epochs, val_loss, scat_plot ='scat', larghezza_riga =10)
            ds().range_plot(bottomY =np.array(val_loss).mean()-np.array(val_loss).std()*6, topY = np.array(val_loss).mean()+np.array(val_loss).std()*6)
            ds().legenda()
            st.pyplot()


            p = figure(title='Training and validation accuracy', x_axis_label='Epochs', y_axis_label='MAE', y_range = (np.array(val_acc).mean()-np.array(val_acc).std()*6, np.array(val_acc).mean()+np.array(val_acc).std()*6))
            p.scatter(epochs, acc, legend_label='Training acc', line_width=1, color = 'red')
            p.line(epochs, acc, line_width=1, color = 'red')
            p.scatter(epochs, val_acc, legend_label='Validation acc', line_width=1, color = 'blue')
            p.line(epochs, val_acc, line_width=1, color = 'blue')
            st.bokeh_chart(p, use_container_width=True)
示例#11
0
    def show_world_map(self):
        palette_ = tuple(reversed(palette))
        with open('geojson/world-geo.json') as f:
            json_data = json.load(f)
        color_mapper = LogColorMapper(palette=palette_)

        country, lon, lat = self.get_coordinates(json_data)
        df_countries = pd.DataFrame(
            {
                "country": country,
                "lon": lon,
                "lat": lat
            },
            columns=['country', 'lon', 'lat'])
        df_tmp = self.df_world[['country', 'confirmed', 'deaths', 'recovered']]
        df4 = pd.merge(df_countries,
                       df_tmp,
                       how='left',
                       left_on='country',
                       right_on='country')

        confirmed = df4['confirmed'].values
        deaths = df4['deaths'].values
        recovered = df4['recovered'].values
        countries = df4['country'].values
        lon = df4['lon'].values
        lat = df4['lat'].values

        data = dict(x=lon,
                    y=lat,
                    name=countries,
                    confirmed=confirmed,
                    recovered=recovered,
                    deaths=deaths)

        TOOLS = "pan,wheel_zoom,reset,hover,save"
        p = figure(title="Total worldwide COVID-19 cases",
                   x_axis_location=None,
                   y_axis_location=None,
                   tooltips=[("Name", "@name"), ("Confirmed", "@confirmed"),
                             ("Deaths", "@deaths"),
                             ("Recovered", "@recovered")],
                   active_scroll='wheel_zoom',
                   match_aspect=True)

        p.grid.grid_line_color = None
        p.hover.point_policy = "follow_mouse"

        p.patches('x',
                  'y',
                  source=data,
                  fill_color={
                      'field': 'confirmed',
                      'transform': color_mapper
                  },
                  fill_alpha=0.7,
                  line_color="white",
                  line_width=0.5)

        st.bokeh_chart(p)
示例#12
0
def main():
    # pylint:disable=too-many-locals
    import sys

    assert len(sys.argv) <= 2, "Only one episode log from `rllib rollout` allowed."
    path, _ = osp.splitext(sys.argv[1])

    episodes = []
    with shelve.open(path) as rollouts:
        for episode_index in range(rollouts["num_episodes"]):
            episodes += [rollouts[str(episode_index)]]

    rows = []
    for idx, episode in enumerate(episodes):
        for timestep, transition in enumerate(episode):
            obs, act, _, rew, done, *_ = transition
            row = {"episode": idx, "timestep": timestep, "reward": rew, "done": done}
            for dim, ob_ in enumerate(obs):
                row[f"obs[{dim}]"] = ob_
            for dim, ac_ in enumerate(act):
                row[f"act[{dim}]"] = ac_
            rows += [row]

    keys = rows[0].keys()
    data = pd.DataFrame(data={k: np.stack([r[k] for r in rows]) for k in keys})
    data["done"] = data["done"].astype(np.float32)

    stats_columns = [c for c in data.columns if c not in {"timestep", "episode"}]
    grouped = data.groupby("timestep")[stats_columns]
    means = grouped.mean()
    stds = grouped.std()

    pics = []
    for key in stats_columns:
        pic = figure(title=key)
        pic.xaxis.axis_label = "timestep"
        pic.yaxis.axis_label = "value"

        # pylint:disable=too-many-function-args
        pic.line(means.index, means[key])
        pic.varea(
            means.index,
            y1=means[key] - stds[key],
            y2=means[key] + stds[key],
            fill_alpha=0.25,
        )
        # pylint:enable=too-many-function-args

        pics += [[pic]]

    st.bokeh_chart(
        gridplot(
            pics,
            plot_width=350,
            plot_height=100,
            sizing_mode="scale_both",
            toolbar_location="right",
        )
    )
示例#13
0
def open_link(url, new_tab=True):
    if new_tab:
        js = f"window.open('{url}')"  # New tab or window
    else:
        js = f"window.location.href = '{url}'"  # Current tab
    html = '<img src onerror="{}">'.format(js)
    div = Div(text=html)
    st.bokeh_chart(div)
示例#14
0
    def test_figure(self):
        """Test that it can be called with figure."""
        plot = figure()
        plot.line([1], [1])
        st.bokeh_chart(plot)

        c = self.get_delta_from_queue().new_element.bokeh_chart
        self.assertEqual(hasattr(c, 'figure'), True)
示例#15
0
def main():
    env = gym.make("IBMisCalibration-v0").unwrapped
    p = goldstone_dynamics_landscape(env)
    if st.checkbox("Display rho_s"):
        p = goldstone_rhos(env, p=p)
    if st.checkbox("Display r_min and r_opt"):
        p = goldstone_rmin_and_ropt(env, p=p)
    st.bokeh_chart(p)
示例#16
0
 def chartBokeh(self, data, par):
     p = figure(x_axis_label='data',
                y_axis_label=par,
                x_axis_type="datetime")
     p.line(data.data, data[par], legend_label=par, line_width=2)
     p.background_fill_alpha = 0
     p.border_fill_alpha = 0
     st.bokeh_chart(p, use_container_width=True)
示例#17
0
def plot_logp_stats(outputs, bins):
    st.write("Entropy:", outputs["entropy"])
    st.write("grad_norm(nll):", outputs["nll_grad"].norm(p=2))

    dataset = pd.DataFrame({k: outputs[k].numpy() for k in "logp log_prob".split()})
    st.bokeh_chart(make_histograms(dataset, bins))
    dataset = pd.DataFrame({"nll_grad": outputs["nll_grad"].numpy()})
    st.bokeh_chart(make_histograms(dataset, bins))
示例#18
0
def open_link(url, new_tab=True):
    """Dirty hack to open a new web page with a streamlit button."""
    if new_tab:
        js = f"window.open('{url}')"  # New tab or window
    else:
        js = f"window.location.href = '{url}'"  # Current tab
    html = '<img src onerror="{}">'.format(js)
    div = Div(text=html)
    st.bokeh_chart(div)
示例#19
0
def ridge_plots(model_df):
    models = list(model_df.keys())
    models.reverse()
    for i, model in enumerate(models):
        if 'name' in model:
            models.pop(i)

    palette = [cc.rainbow[i * 15] for i in range(len(models))]

    x = np.linspace(-20, 110, 500)

    source = ColumnDataSource(data=dict(x=x))

    p = figure(y_range=models,
               plot_width=900,
               x_range=(0, 5),
               toolbar_location=None)

    for i, model in enumerate(models):
        if 'name' in model:
            continue
        pdf = gaussian_kde(model_df[model].dropna())
        y = ridge(model, pdf(x))
        source.add(y, model)
        p.patch('x',
                model,
                color=palette[i],
                alpha=0.6,
                line_color="black",
                source=source)

    p.outline_line_color = None
    p.background_fill_color = "#efefef"

    p.xaxis.ticker = FixedTicker(
        ticks=list(range(int(model_df.min().min()), 5, 1)))
    # p.xaxis.formatter = PrintfTickFormatter(format="%d%%")

    p.ygrid.grid_line_color = None
    p.xgrid.grid_line_color = "#dddddd"
    p.xgrid.ticker = p.xaxis[0].ticker

    p.axis.minor_tick_line_color = None
    p.axis.major_tick_line_color = None
    p.axis.axis_line_color = None

    p.y_range.range_padding = 2

    base = Span(location=1,
                dimension='height',
                line_color='black',
                line_dash='dashed',
                line_width=3)
    p.add_layout(base)

    st.bokeh_chart(p)
    return
示例#20
0
def bokeh_plot(data, type, axis_type):

    y_label = type
    y_axis_type = axis_type

    p = figure(title='Active cases',
               x_axis_type='datetime',
               y_axis_label=y_label,
               y_axis_type=y_axis_type,
               toolbar_location=None,
               plot_height=400)
    x = data.index

    colors = itertools.cycle(palette)

    for column in data.columns:
        if column != 'Date':
            df = list(data[column])
            p.line(x,
                   df,
                   legend_label=column,
                   line_width=2,
                   color=next(colors))

    for year in ['2020', '2021', '2022']:
        vline = Span(
            location=datetime.strptime(f'1/1/{year}', '%d/%m/%Y'),
            dimension='height',
            line_color='black',
            line_width=0.25,
        )
        text = Label(x=datetime.strptime(f'1/1/{year}', '%d/%m/%Y'),
                     y=0,
                     text=f"{year}",
                     text_color='black',
                     angle=1.5708,
                     text_font_size='8pt',
                     text_alpha=0.7,
                     x_offset=15,
                     y_offset=-12)

        p.renderers.extend([vline])
        p.add_layout(text)

    hover = p.select(dict(type=HoverTool))
    hover.tooltips = [("cases", "@y")]

    p.legend.location = "top_left"
    # p.yaxis.formatter.use_scientific = False
    p.yaxis.formatter = NumeralTickFormatter(format="0,0M")
    p.xaxis.formatter = DatetimeTickFormatter(months=['%B'])
    p.xaxis.axis_label_text_align = 'right'  # <== THIS APPEARS TO DO NOTHING
    p.toolbar.active_scroll = p.select_one(WheelZoomTool)
    p.js_on_event(DoubleTap, CustomJS(args=dict(p=p), code='p.reset.emit()'))

    st.bokeh_chart(p, use_container_width=True)
示例#21
0
def income_expenses_over_time(df_orig):
    # Time interval aggregation level
    time_interval = st.sidebar.radio(
        "Time interval:", ("Month", "Quarter", "Year"), index=1)
    dfn, n_levels = time_interval_aggregation(df_orig, time_interval)
    if st.sidebar.checkbox('Invert sign of "Income"', value=True):
        dfn.loc["Income", :] = -dfn.loc["Income", :].values
    st.subheader('Income and Expenses over Time')
    plot_type = st.sidebar.selectbox('Plot type', ["pyplot", "altair", "bokeh"], key="plot_type")
    df_L0 = dfn.groupby(["Account_L0"]) \
        .sum() \
        .transpose() \
        .reset_index()

    df_L0.columns.name = "Account"
    if plot_type == "pyplot":
        fig = plt.figure(figsize=(14, 5))
        ax = plt.axes()
        df_L0.plot.bar(ax=ax, x=time_interval, y=["Income", "Expenses"],
                       xlabel=time_interval, ylabel=df_L0["level_0"][0], rot=90)
        ax.locator_params(axis="x", tight=True, nbins=40)
        st.pyplot(fig)
    elif plot_type == "altair":
        n_intervals = df_L0.shape[0]
        df_new = df_L0.drop(columns="level_0") \
            .set_index(time_interval) \
            .stack() \
            .reset_index() \
            .rename(columns={0: dfn.columns.levels[0][0]})
        custom_spacing = 2
        chart = alt.Chart(df_new).mark_bar().encode(
            column=alt.Column(time_interval, spacing=custom_spacing, header=alt.Header(title="Income and Expenses",
                                                                                       labelOrient='bottom',
                                                                                       labelAlign='right',
                                                                                       labelAngle=-90)),
            x=alt.X('Account:O', axis=alt.Axis(title=None, labels=False, ticks=False)),
            y=alt.Y('{}:Q'.format(dfn.columns.levels[0][0]), title=dfn.columns.levels[0][0], axis=alt.Axis(grid=False)),
            color=alt.Color('Account', scale=alt.Scale(range=['#EA98D2', '#659CCA'])),
            tooltip=[alt.Tooltip('Account:O', title='Account'),
                     alt.Tooltip('{}:Q'.format(dfn.columns.levels[0][0]), title=dfn.columns.levels[0][0]),
                     alt.Tooltip('{}:N'.format(time_interval), title=time_interval)]
        ).properties(width=(700 - n_intervals * custom_spacing) / n_intervals)
        st.altair_chart(chart, use_container_width=False)
    elif plot_type == "bokeh":
        x = [(ti, acnt) for ti in df_L0[time_interval] for acnt in ["Income", "Expenses"]]
        counts = sum(zip(df_L0['Income'], df_L0['Expenses']), ())
        source = ColumnDataSource(data=dict(x=x, counts=counts))
        p = figure(x_range=FactorRange(*x), plot_height=450, plot_width=900, title="Income and Expenses",
                   toolbar_location="above", tooltips=[("Period, Account", "@x"), ("Value", "@counts")])
        p.vbar(x='x', top='counts', width=0.9, source=source)
        p.y_range.start = 0
        p.x_range.range_padding = 0.5
        p.xaxis.major_label_orientation = 1
        p.xgrid.grid_line_color = None
        st.bokeh_chart(p)
    return
def open_link(url, new_tab=True):
    """Dirty hack to open a new web page with a streamlit button."""
    # From: https://discuss.streamlit.io/t/how-to-link-a-button-to-a-webpage/1661/3
    if new_tab:
        js = f"window.open('{url}')"  # New tab or window
    else:
        js = f"window.location.href = '{url}'"  # Current tab
    html = '<img src onerror="{}">'.format(js)
    div = Div(text=html)
    st.bokeh_chart(div)
示例#23
0
def plot_action_distributions(outputs, bins, ranges=()):
    acts, det = map(lambda x: x.numpy(), dutil.get_keys(outputs, "acts", "det"))
    data = {f"act[{i}]": acts[..., i] for i in range(acts.shape[-1])}
    dataset = pd.DataFrame(data)

    det_data = {f"det[{i}]": det[..., i] for i in range(det.shape[-1])}
    det_dataset = pd.DataFrame(det_data)

    st.bokeh_chart(make_histograms(dataset, bins, ranges=ranges))
    st.bokeh_chart(scatter_matrix(dataset, det_dataset))
示例#24
0
    def show_us_map(self):
        palette_ = tuple(reversed(palette))
        with open('geojson/world-geo.json') as f:
            json_data = json.load(f)
        color_mapper = LogColorMapper(palette=palette_)

        states_geo = self.get_geojson()
        states, lons, lats = self.get_coordinates(states_geo)

        states_geo = pd.DataFrame({
            'state': states,
            'lons': lons,
            'lats': lats
        })

        states_df = pd.merge(states_geo,
                             self.latest_states,
                             left_on='state',
                             right_on='state')
        states_df.set_index('state', inplace=True)

        cases = states_df['cases'].values
        deaths = states_df['deaths'].values
        death_pct = [x / y * 100 for x, y in zip(deaths, cases)]

        data = dict(x=lons,
                    y=lats,
                    name=states,
                    cases=cases,
                    deaths=deaths,
                    pct=death_pct)

        TOOLS = "pan,wheel_zoom,reset,hover,save"
        p = figure(title="Total US COVID-19 cases",
                   x_axis_location=None,
                   y_axis_location=None,
                   tooltips=[("Name", "@name"), ("Cases", "@cases"),
                             ("Deaths", "@deaths"), ("Percentage", "@pct%")],
                   active_scroll='wheel_zoom',
                   match_aspect=True)

        p.grid.grid_line_color = None
        p.hover.point_policy = "follow_mouse"

        p.patches('x',
                  'y',
                  source=data,
                  fill_color={
                      'field': 'cases',
                      'transform': color_mapper
                  },
                  fill_alpha=0.7,
                  line_color="white",
                  line_width=0.5)
        st.bokeh_chart(p)
示例#25
0
def main():
    print("Conecatando...", end="")
    conn = open_db()
    print("Ok.")

    query = import_query(os.path.join(SRC_DIR, "query.sql"))
    df = pd.read_sql_query(query, conn)

    G = nx.from_pandas_edgelist(df, source='user_a', target='user_b')

    st.bokeh_chart(hv.render(G, backend='bokeh'))
示例#26
0
def main():
    if loadcase is Cases.FAT:
        Wind_mult = wind_multipliers.Wind_multipliers(render_hc)
        Wind = wind.Wind(Wind_mult, loadcase)
        Geom = geometry.Geometry(Wind)
        Geom.st_geom_picker()
        if Geom.structure_type is Structure_type.RHS:
            #TODO - Add API calls
            st.warning("Not yet implemented, try selecting SIGNS")
            pass
        if Geom.structure_type is Structure_type.CHS:
            Geom.calc_drag_CHS_AASHTO()
            Geom.calc_wind_pressure_sign_fat()
        if Geom.structure_type is Structure_type.SIGN:
            Geom.calc_drag_sign_AASHTO()
            Geom.calc_wind_pressure_sign_fat()
        #plot_sign = Geom.st_plot_wind_pressure()
        #st.bokeh_chart(plot_sign,False)
    else:
        Wind_mult = wind_multipliers.Wind_multipliers(render_hc)
        Wind_mult.st_region_inputs()
        Wind_mult.st_terrain_inputs()
        Wind_mult.terrain_multiplier()
        Wind_mult.st_wind_multipliers_input()
        Wind_mult.st_wind_direction_inputs()
        Wind_mult.calc_wind_direction_multiplier()
        Wind_mult.render_multipliers()

        Wind = wind.Wind(Wind_mult, loadcase)
        Wind.st_wind_speed_inputs()
        Wind.calc_regional_wind_speed()
        Wind.st_display_regional_wind_speed()
        Wind.calc_site_wind_speed()

        Geom = geometry.Geometry(Wind)
        Geom.st_geom_picker()
        if Geom.structure_type is Structure_type.RHS:
            Geom.calc_drag_RHS_AS1170()
            Geom.calc_wind_pressure_RHS()
            plot_RHS = Geom.st_RHS_plotting()
            st.bokeh_chart(plot_RHS, False)
        elif Geom.structure_type is Structure_type.CHS:
            Geom.calc_drag_CHS_AS1170()
            if Geom.frame_type is Frame.NONE:
                Geom.calc_wind_pressure_CHS()
            else:
                Geom.calc_drag_frame_CHS_AS1170()
                Geom.calc_wind_pressure_CHS()
        elif Geom.structure_type is Structure_type.SIGN:
            Geom.calc_drag_sign_AS1170()
            Geom.calc_solidity_factor()
            Geom.calc_wind_pressure_sign()
            plot_sign = Geom.st_plot_wind_pressure()
            st.bokeh_chart(plot_sign, False)
示例#27
0
def open_link(url: str, new_tab: bool = True) -> None:
    """Hack to open a new web page with a streamlit button."""
    from bokeh.models.widgets import Div

    # From: https://discuss.streamlit.io/t/how-to-link-a-button-to-a-webpage/1661/3
    if new_tab:
        js = f"window.open('{url}')"  # New tab or window
    else:
        js = f"window.location.href = '{url}'"  # Current tab
    html = '<img src onerror="{}">'.format(js)
    div = Div(text=html)
    st.bokeh_chart(div)
示例#28
0
def footer():
    st.markdown("""
	* * *
	Built with ❤️and :coffee: by [HEMANG BHAVASAR](https://www.linkedin.com/in/hemangbhavasar/)
	""")

    if st.button('Donation'):
        js = "window.open('https://paypal.me/hemangbhavasar')"  # New tab or window
        js = "window.location.href = 'https://paypal.me/hemangbhavasar'"  # Current tab
        html = '<img src onerror="{}">'.format(js)
        div = Div(text=html)
        st.bokeh_chart(div)
示例#29
0
def get_doctop_vis(clustering_pipeline, media='videos'):
    """ calls a function to generate bokeh visualization

    Parameters
    ----------
    clustering_pipeline : class reference
        The current modeling pipeling
    media : str, optional
        'articles' or 'videos', by default 'videos'
    """
    bokeh_layout = clustering_pipeline.generate_bokeh_umap(media)
    st.bokeh_chart(bokeh_layout)
示例#30
0
def main():
    momo_raw, sex, regions, age = get_data(online=True)

    selected_communities, selected_age, selected_sex, days_to_delete, mortality_rate, days_to_death = user_filters(
        sex, regions, age)

    st.title('Analizando fallecidos y contagiados por el Covid-19 en ' +
             str(selected_communities).strip())

    momo = filtering_momo(momo_raw, selected_sex, selected_age,
                          selected_communities)

    momo = contagiuous(momo, days_to_death, mortality_rate, days_to_delete)

    st.write(
        "En el siguiente gráfico se pueden observar "
        "las diferencias entre fallecimientos esperados y fallecimientos observados en "
        + str(selected_communities) +
        ". Asumimos que estas diferencias son provocadas por el Covid-19. "
        "Los valores están agruapdos por semana")

    plot_timeline(momo,
                  variable="Exceso de Defunciones",
                  selected_communities=selected_communities,
                  selected_age=selected_age,
                  selected_sex=selected_sex)

    st.write(
        "A continuación, teniendo en cuenta el porcentaje de mortalidad del virus seleccionado, se muestra una "
        "aproximación de los contagiados en " + str(selected_communities) +
        ". Los valores están agrupados por semana")

    plot_timeline(momo,
                  variable="Contagiados",
                  selected_communities=selected_communities,
                  selected_age=selected_age,
                  selected_sex=selected_sex)

    st.write("")
    st.write("¿Alguna conclusión o comentario que te gustaría compartir? ")

    if st.button('Puedes contactarme aquí. '):
        js = "window.open('https://www.linkedin.com/in/carloscamorales')"  # New tab or window
        html = '<img src onerror="{}">'.format(js)
        div = Div(text=html)
        st.bokeh_chart(div)

    if st.button('Puedes encontrar el código en el siguiente enlace.'):
        js = "window.open('https://github.com/camorales197/covid-app')"  # New tab or window
        html = '<img src onerror="{}">'.format(js)
        div = Div(text=html)
        st.bokeh_chart(div)