Exemplo n.º 1
0
def main():
    st.sidebar.image(logo, use_column_width=True)
    page = st.sidebar.selectbox("Escolha uma Análise", [
        HOME, MODELS, DATA, PAGE_CASE_DEATH_NUMBER_BR, CUM_DEATH_CART,
        PAGE_GLOBAL_CASES, MAPA, CREDITOS
    ])
    if page == HOME:
        st.header("Analisando a Pandemia de COVID-19 no Brasil")
        st.markdown(
            """Neste site buscamos trazer até você os números da epidemia, a medida que se revelam, 
        mas também um olhar analítico, capaz de desvelar a dinâmica do processo de transmissão do vírus SARS-Cov-2
        por meio de modelos matemáticos, análises estatísticas e visualização de informação.
        
Pelo *painel à esquerda* você pode ***navegar entre nossas análises***, as quais estaremos atualizando constantemente 
daqui para frente. 
## Outros Recursos de Interesse
Vamos compilar aqui também outras fontes de informação de confiança para que você possa se manter atualizado 
com os últimos resultados científicos sobre a Pandemia.

* Canal [A Matemática das Epidemias](https://www.youtube.com/channel/UCZFllLoI5kB4o_6w59YVzAA?view_as=subscriber).
* Grupo MAVE: [Métodos Analíticos em Vigilância Epidemiológica](https://covid-19.procc.fiocruz.br).

## Fontes de Dados
As sguintes fontes de dados foram usadas neste projeto:

* [Brasil.io](https://brasil.io): Dados de incidência e mortalidade no Brasil
* [Johns Hopkins CSSE](https://github.com/CSSEGISandData/COVID-19): Dados de incidência e mortalidade globais.

## Softwares opensource
Várias bibliotecas opensource foram utilizadas na construção deste dashboard:

* [Streamlit](https://streamlit.io): Web framework voltada para ciência de dados.
* [Epimodels](https://github.com/fccoelho/epimodels): Biblioteca de modelos matemáticos para simulação de epidemias.

        """)
        data = dashboard_data.get_data()
    elif page == MODELS:
        st.title("Explore a dinâmica da COVID-19")
        st.sidebar.markdown("### Parâmetros do modelo")
        chi = st.sidebar.slider('χ, Fração de quarentenados', 0.0, 1.0, 0.76)
        phi = st.sidebar.slider('φ, Taxa de Hospitalização', 0.0, 0.5, 0.005)
        beta = st.sidebar.slider('β, Taxa de transmissão', 0.0, 1.0, 0.6)
        rho = st.sidebar.slider('ρ, Taxa de alta dos hospitalizados:', 0.0,
                                1.0, 0.12)
        delta = st.sidebar.slider('δ, Taxa de recuperação de Sintomáticos:',
                                  0.0, 1.0, 0.1)
        gamma = st.sidebar.slider('γ, Taxa de recuperação de Assintomáticos:',
                                  0.0, 1.0, 0.05)
        alpha = st.sidebar.slider('α, Taxa de incubação', 0.0, 10.0, .37)
        mu = st.sidebar.slider('μ, Taxa de mortalidade pela COVID-19', 0.0,
                               1.0, .01)

        p = st.slider('Fração de assintomáticos:', 0.0, 1.0, 0.63)
        q = st.slider('Dia de início da Quarentena:', 1, 165, 35)
        r = st.slider('duração em dias da Quarentena:', 0, 200, 80)
        N = st.number_input('População em Risco:',
                            value=102.3e6,
                            max_value=200e6,
                            step=1e6)
        st.markdown(
            f"""$R_0={(beta * (1-chi)*(p*(phi+delta)+(1-p)*gamma)) / (gamma*(delta+phi)):.2f}$, durante a quarentena. &nbsp 
                    $R_0={(beta * (1-0)*(p*(phi+delta)+(1-p)*gamma)) / (gamma*(delta+phi)):.2f}$, fora da quarentena."""
        )

        params = {
            'chi': chi,
            'phi': phi,
            'beta': beta,
            'rho': rho,
            'delta': delta,
            'gamma': gamma,
            'alpha': alpha,
            'mu': mu,
            'p': p,
            'q': q,
            'r': r
        }
        traces = pd.DataFrame(data=seqiahr_model(params=params)).rename(
            columns=COLUMNS)
        final_traces = dashboard_models.prepare_model_data(
            traces, VARIABLES, COLUMNS, N)

        # Dataframes
        Hospitalizacoes = traces['Hospitalizações Acumuladas']
        Hosp_t = traces['Hospitalizados']
        Mortes = traces['Mortes Acumuladas']
        Infectados = traces['Infectados']
        Recuperados = traces['Recuperados']

        # Valores
        pico_infectados = Infectados.iloc[Infectados.idxmax()]
        pico_hosp = Hosp_t.iloc[Hosp_t.idxmax()]
        pico_mortes = Mortes.iloc[Mortes.diff().idxmax()]
        Hospitalizacoes_totais = Hospitalizacoes.iloc[-1]
        mortes_totais = Mortes.iloc[-1]
        inf_tot = N - Recuperados.iloc[-1] - mortes_totais

        stats = pd.DataFrame(data={
            'Pico': [
                hp.intword(pico_infectados * N),
                hp.intword(pico_hosp * N),
                hp.intword(pico_mortes * N)
            ],
            'Total': [
                hp.intword(inf_tot),
                hp.intword(Hospitalizacoes_totais * N),
                hp.intword(mortes_totais * N)
            ]
        },
                             index=['Infecções', 'Hospitalizações', 'Mortes'])

        st.markdown(f"""### Números importantes da simulação""")
        st.dataframe(stats)
        st.markdown(
            f"""O pico das hospitalizações ocorrerá após {Hosp_t.idxmax()} dias"""
        )
        st.markdown(
            f"""O pico das Mortes ocorrerá após {Mortes.diff().idxmax()} dias"""
        )

        dashboard_models.plot_model(final_traces, q, r)
        st.markdown('''### Comparando Projeções e Dados
Podemos agora comparar nossa série simulada de Hospitalizações acumuladas com o número de casos acumulados 
de notificações oficiais.
        ''')
        ofs = st.number_input("Atraso no início da notificação (dias)",
                              value=0,
                              min_value=0,
                              max_value=90,
                              step=1)
        st.markdown(
            'Na caixa acima, você pode mover lateralmente a curva, Assumindo que os primeiro caso '
            'notificado não corresponde ao início da transmissão')
        dashboard_models.plot_predictions(ofs, final_traces, dias=365)
        st.markdown('### Formulação do modelo')
        st.write(r"""
                $\frac{dS}{dt}=-\lambda[(1-\chi) S]$

                $\frac{dE}{dt}= \lambda [(1-\chi) S] -\alpha E$

                $\frac{dI}{dt}= (1-p)\alpha E - \delta I -\phi I$

                $\frac{dA}{dt}= p\alpha E - \gamma A$

                $\frac{dH}{dt}= \phi I -(\rho+\mu) H$

                $\frac{dR}{dt}= \delta I + \rho H+\gamma A$

                $\lambda=\beta(I+A)$

                $\mathcal{R}_0 = \frac{\beta(1-\chi)( p (\phi + \delta) +(1-p)\gamma)}{\gamma(\delta + \phi)}$
                """)

    elif page == DATA:
        st.title('Probabilidade de Epidemia por Município ao Longo do tempo')

        @st.cache
        def read_video():
            with open('dashboard/video_prob.mp4', 'rb') as v:
                video = v.read()
            return video

        st.video(read_video())
        st.markdown(r'''## Descrição da modelagem:
Os municípios brasileiros são conectados por uma malha de transporte muito bem desenvolvida e através desta,
cidadãs e cidadãos viajam diariamente entre as cidades para trabalhar, estudar e realizar outras atividades.
Considerando o fluxo de indivíduos (infectados) que chega em um município em um determinado dia, caso este município
ainda não estejam em transmissão comunitária, podemos calcular a probabilidade de uma epidemia se estabelecer.
Esta probabilidade é dada por esta fórmula:

$$P_{epi}=1-\left(\frac{1}{R_0}\right)^{I_0}$$,

onde $I_0$ é o número de infectados chegando diáriamente no município. Neste cenário usamos um $R_0=2.5$.
        ''')

    elif page == PAGE_CASE_DEATH_NUMBER_BR:
        st.title(PAGE_CASE_DEATH_NUMBER_BR)
        x_variable = "date"
        y_variable = "Casos Confirmados"
        y_variable2 = "Mortes Acumuladas"

        data = dashboard_data.get_data()
        ufs = sorted(list(data.state.drop_duplicates().values))
        uf_option = st.multiselect("Selecione o Estado", ufs)

        city_options = None

        if uf_option:
            cities = dashboard_data.get_city_list(data, uf_option)
            city_options = st.multiselect("Selecione os Municípios", cities)

        is_log = st.checkbox('Escala Logarítmica', value=False)
        region_name, data_uf_confirmed = dashboard_data.get_data_uf(
            data, uf_option, city_options, y_variable)
        region_name, data_uf_deaths = dashboard_data.get_data_uf(
            data, uf_option, city_options, y_variable2)

        figure = dashboard_data.plot_series(data_uf_confirmed, x_variable,
                                            y_variable, region_name, is_log)
        figure = dashboard_data.add_series(figure, data_uf_deaths, x_variable,
                                           y_variable2, region_name, is_log)

        st.plotly_chart(figure)

        st.markdown(
            "**Fonte**: [brasil.io](https://brasil.io/dataset/covid19/caso)")
        st.markdown(r"""## Evolução da Letalidade por Estado Brasileiro
No gráfico abaixo, podemos ver como a letalidade(Fração dos casos confirmados que foi a óbito) está evoluindo 
com o tempo em cada estado.

É importante lembrar que estes números não representam todas as mortes por COVID-19 no país, pois apenas as mortes de 
casos testados e confirmados são efetivamente contadas como mortes oficiais pela COVID-19. Devido à escassez de testes e 
recomendações sobre quem deve ser testado, existe um viés nestas estimativas.

Na figura abaixo o eixo vertical representa a letalidade: $\frac{mortes}{casos}$, o eixo Horizontal representa o número 
total de casos. O tamanho dos círculos representa o número total de mortes em cada estado. Este gráfico é mais fácil de 
ser estudado em tela cheia. clicando na legenda é possível "ligar" e "desligar" a visualização dos estados individualmente,
para facilitar a visualização dos demais. Passando o mouse por sobre os circulos, podemos ler os valores da letalidade e 
da data a que corresponde.
        """)
        dashboard_data.plot_scatter_CFR(data)

        st.markdown('''## Excesso de Mortes por Estado
Abaixo, exploramos o excesso de mortalidade nos estados que a COVID-19 representa, quando comparada à média dos 
últimos 10 anos de mortes por doenças respiratórias.
        ''')
        uf_option2 = st.selectbox("Selecione o Estado", ufs)
        viral = st.checkbox(
            "Apenas Mortalidade por pneumonia viral? Desmarque para comparar com o total de mortes respiratórias",
            value=True)
        dashboard_data.plot_excess_deaths(data, uf_option2, viral)

    elif page == CUM_DEATH_CART:
        st.title(CUM_DEATH_CART)
        x_variable = "date"
        y_variable = "deaths_covid19"
        y_variable2 = "Mortes Acumuladas"
        data = dashboard_data.get_data_from_source(
            dashboard_data.BRASIL_IO_CART, usecols=None, rename_cols=None)
        data2 = dashboard_data.get_data()
        ufs = sorted(list(data.state.drop_duplicates().values))
        uf_option = st.multiselect("Selecione o Estado", ufs)
        is_log = st.checkbox('Escala Logarítmica', value=False)
        city_options = None
        # get data
        region_name, data_uf = dashboard_data.get_data_cart(
            data, uf_option, y_variable)
        region_name, data_uf_deaths = dashboard_data.get_data_uf(
            data2, uf_option, city_options, y_variable2)
        # Plota mortes dos cartorios
        fig = dashboard_data.plot_series(
            data_uf,
            x_variable,
            y_variable,
            region_name,
            is_log,
            label='Mortes registradas em Cartório')
        fig = dashboard_data.add_series(fig, data_uf_deaths, x_variable,
                                        y_variable2, region_name, is_log,
                                        "Mortes Oficiais")

        st.plotly_chart(fig)

        st.markdown(
            "**Fonte**: [brasil.io](https://brasil.io/dataset/covid19/obito_cartorio)"
        )

    elif page == MAPA:

        # Precisa refatorar
        st.title("Distribuição Geográfica de Casos")
        cases = dashboard_data.get_data()
        estados = dashboard_data.load_lat_long()
        estados['casos'] = 0
        cases = cases[cases.place_type != 'state'].groupby(['date',
                                                            'state']).sum()
        cases.reset_index(inplace=True)

        for i, row in estados.iterrows():
            if row.Estados in list(cases.state):
                estados.loc[estados.Estados == row.Estados, 'casos'] += \
                    cases[(cases.state == row.Estados) & (cases.is_last)]['Casos Confirmados'].iloc[0]

        midpoint = (np.average(estados["Latitude"]),
                    np.average(estados["Longitude"]))

        layer = pdk.Layer("ColumnLayer",
                          data=estados,
                          get_position=["Longitude", "Latitude"],
                          get_elevation=['casos'],
                          auto_highlight=True,
                          radius=50000,
                          elevation_scale=300,
                          get_color=[100, 255, 100, 255],
                          pickable=True,
                          extruded=True,
                          coverage=1)

        view_state = pdk.ViewState(
            longitude=midpoint[1],
            latitude=midpoint[0],
            zoom=3,
            pitch=20.,
        )

        mapbox_style = 'mapbox://styles/mapbox/light-v9'
        mapbox_key = 'pk.eyJ1IjoiZmNjb2VsaG8iLCJhIjoiY2s4c293dzc3MGJodzNmcGEweTgxdGpudyJ9.UmSRs3e4EqTOte6jYWoaxg'

        st.write(
            pdk.Deck(
                map_style=mapbox_style,
                mapbox_key=mapbox_key,
                initial_view_state=view_state,
                layers=[layer],
                tooltip={
                    "html":
                    "<b>Estado:</b> {Estados}<br><b>Número de casos:</b> {casos}",
                    "style": {
                        "color": "white"
                    }
                },
            ))

        st.markdown(
            "**Fonte**: [brasil.io](https://brasil.io/dataset/covid19/caso)")

    elif page == PAGE_GLOBAL_CASES:
        st.title(PAGE_GLOBAL_CASES)
        x_variable = "Data"
        y_variable = "Casos"
        global_cases = dashboard_data.get_global_cases() \
            .drop(["Province/State", "Lat", "Long"], axis="columns")

        melted_global_cases = pd.melt(global_cases,
                                      id_vars=["País/Região"],
                                      var_name=x_variable,
                                      value_name=y_variable)
        melted_global_cases["Data"] = pd.to_datetime(
            melted_global_cases["Data"])
        countries = dashboard_data.get_countries_list(melted_global_cases)
        countries_options = st.multiselect("Selecione os Países", countries)

        region_name, countries_data = dashboard_data.get_countries_data(
            melted_global_cases, countries_options)
        is_log = st.checkbox('Escala Logarítmica', value=False)

        fig = dashboard_data.plot_series(countries_data, x_variable,
                                         y_variable, region_name, is_log)
        st.plotly_chart(fig)
        st.markdown(
            "**Fonte**: [Johns Hopkins CSSE](https://github.com/CSSEGISandData/COVID-19)"
        )

    elif page == CREDITOS:
        st.markdown(open('dashboard/creditos.md', 'r').read())
Exemplo n.º 2
0
df = pd.read_json(S2_LAYER_DATA)

# Define a layer to display on a map
layer = pdk.Layer(
    "S2Layer",
    df,
    pickable=True,
    wireframe=False,
    filled=True,
    extruded=True,
    elevation_scale=1000,
    getS2Token="token",
    get_fill_color="[value * 255, (1 - value) * 255, (1 - value) * 128]",
    get_elevation="value",
)

# Set the viewport location
view_state = pdk.ViewState(latitude=37.7749295,
                           longitude=-122.4194155,
                           zoom=11,
                           bearing=0,
                           pitch=45)

# Render
r = pdk.Deck(
    layers=[layer],
    initial_view_state=view_state,
    tooltip={"text": "{token} value: {value}"},
)
r.to_html("s2_layer.html")
Exemplo n.º 3
0
    return z


df_line['coordinates'] = coordinate_dummy
df_line['color'] = df_line['line_name'].apply(make_color)
df_line['weight'] = df_line['line_name'].apply(take_weight)

#Render

line_layer = pdk.Layer(
    'PathLayer',
    df_line,
    get_path='coordinates',
    get_width='weight',
    get_color='[color[0],color[1],color[2]]',
)

point_layer = pdk.Layer('ScatterplotLayer',
                        df_merge,
                        get_position='[X좌표,Y좌표]',
                        get_radius=20,
                        get_fill_color='[255,255,255]',
                        pickable=True,
                        auto_highlight=True)

center = [126.9825876, 37.5377887]
view_state = pdk.ViewState(longitude=center[0], latitude=center[1], zoom=10)

r = pdk.Deck(layers=[line_layer, point_layer], initial_view_state=view_state)
r.to_html("bus_line_data_visulation.html")
Exemplo n.º 4
0
"""
BitmapLayer
===========

A 1906 Britton & Rey's map of San Francisco's 1906 fire, overlaid on
an interactive map of San Francisco.
"""

import pydeck


# Map of San Francisco from 1906
IMG_URL = '"https://i.imgur.com/W95ked7.jpg"'

BOUNDS = [
    [-122.52690000000051, 37.70313158980733],
    [-122.52690000000051, 37.816395657523195],
    [-122.34604834372873, 37.816134829424335],
    [-122.34656848822227, 37.70339041384273],
]

bitmap_layer = pydeck.Layer("BitmapLayer", data=None, image=IMG_URL, bounds=BOUNDS, opacity=0.7)

view_state = pydeck.ViewState(latitude=37.7576171, longitude=-122.5776844, zoom=10, bearing=-45, pitch=60,)

r = pydeck.Deck(bitmap_layer, initial_view_state=view_state, map_style="mapbox://styles/mapbox/satellite-v9",)

r.to_html("bitmap_layer.html", notebook_display=False)
Exemplo n.º 5
0
        pdk.Layer(
            "HeatmapLayer",
            data=data,
            opacity=0.9,
            get_position=["lon", "lat"],
            aggregation=pdk.types.String("MEAN"),
            color_range=[[240, 249, 232], [204, 235, 197], [168, 221, 181],
                         [123, 204, 196], [67, 162, 202], [8, 104, 172]],
            threshold=1,
            pickable=True,
        )
    ],
             initial_view_state=pdk.ViewState(latitude=40.720589,
                                              longitude=-73.856084,
                                              zoom=8,
                                              min_zoom=5,
                                              max_zoom=15,
                                              pitch=40.5,
                                              bearing=-27.36),
             tooltip={"text": "Concetration of pickups"}))

#slider
st.subheader('Map of pickups by hour')
hour_filter = st.slider('Select hour', 0, 23, 17)
#mapa
layer = pdk.Layer(
    "GridLayer",
    data[data['date/time'].dt.hour == hour_filter][['lon', 'lat']].dropna(),
    pickable=True,
    extruded=True,
    cell_size=200,
Exemplo n.º 6
0
def sl():
    b = st.radio("Select Batch:", ["First Batch", "Second Batch"])
    if b == "First Batch":
        b = "F"
    else:
        b = "S"
    try:
        for x in range(0, 10, 1):
            dfd1 = pd.read_csv("{}Bdetails-{}.csv".format(b, x))

            dfm1 = pd.read_csv(f"{b}BdelivMap-{x}.csv")
            #dfm2=pd.read_csv(f"SBdelivMap-{x}.csv")
            #print(dfd1,dfd2,dfm1,dfm2)
            print(dfd1)
            for index, a in dfd1.iterrows():
                for index2, y in enumerate(a):
                    if index2 == 1:
                        print(y, index2)
                        if index == 0:
                            st.write(f"Route #{a[index2]}")
                        if index == 1:
                            st.write(f"Total cost: ${a[index2]}")
                        if index == 2:
                            st.write("Total hours: {}".format(a[index2]))
                        if index == 3:
                            st.write("Route: {}".format(a[index2]))

            df = dfm1
            view = pdk.ViewState(latitude=df["from_lat"].mean(),
                                 longitude=df["from_lon"].mean(),
                                 pitch=20,
                                 zoom=9)

            arc_layer = pdk.Layer("ArcLayer",
                                  data=df,
                                  get_source_position=["from_lon", "from_lat"],
                                  get_target_position=["to_lon", "to_lat"],
                                  get_width=5,
                                  get_tilt=15,
                                  get_source_color=[255, 165, 0, 80],
                                  get_target_color=[128, 0, 128, 80])
            column_layer = pdk.Layer(
                "ColumnLayer",
                data=df,
                get_position=["from_lon", "from_lat"],
                get_elevation="Cases",
                elevation_scale=2,
                radius=250,
                pickable=True,
                auto_highlight=True,
            )

            tooltip = {
                "html":
                "<b>{Name}</b>  Rev: <b>${Rev}</b> Cases:{Cases} Flavors: Celebrate-{Cel} Dream-{Dre} Achieve:{Ach}",
                "style": {
                    "background": "grey",
                    "color": "white",
                    "font-family": '"Helvetica Neue", Arial',
                    "z-index": "10000"
                }
            }

            arc_layer_map = pdk.Deck(
                map_style='mapbox://styles/mapbox/light-v10',
                layers=[arc_layer, column_layer],
                initial_view_state=view,
                mapbox_key=mbapi,
                tooltip=tooltip)
            arc_layer_map.to_html("First_Batch_Sales_Map.html")
            data = df.to_dict()
            print(data)
            st.pydeck_chart(arc_layer_map)
    except:
        pass
Exemplo n.º 7
0
def clustercentroids():
    kmeans=load('modelos/clustering.joblib')
    df1,_=obtencionCoords()
    df1.columns=["Lat","Lon"]
    df1cpy=df1.iloc[:,[0,1]]

    y_pred= kmeans.predict(df1.iloc[:,0:2].values)
    plt.figure(figsize=(8,6))
    df1['pred_class']=y_pred
    colores=["yellowgreen","teal","purple","blue"]
    for c, samples in df1.groupby("pred_class"):#clase 0 todas las de la clase cero, clase 1, la c es una agrupacion
        plt.scatter(x=samples.iloc[:,0],y=samples.iloc[:,1],label="Numero de nodo: "+str(c+1),c=colores[c])#estoy seleccionando la columna comleta de dos
    plt.legend()
    plt.grid(True)#con cuadricula

    listc=list()

    C = kmeans.cluster_centers_ #el modelo ya me calcula los centoides de los datos
    plt.scatter(C[:, 0], C[:, 1], marker='*', s=500,c=colores)
    for i in range(kmeans.n_clusters): 
        listc.append([C[i,0],C[i,1]])
    dfc=pd.DataFrame(listc,columns=["lat","lon"])#se guardan latitudes y longitudes, sustituyendo a df2
    #print(listc)
    layers2= pdk.Layer(
            'ScatterplotLayer',#puntos, es para emergencias
            data=df1cpy,#aqui obtengo datos de lat y lon
            get_position='[Lon, Lat]',
            get_color='[100, 230, 0, 160]',
            get_radius=2,
        )
    layers1= pdk.Layer(
            'HexagonLayer',#puntos en forma de hexagono, es para nodos
            data=dfc,#aqui obtengo datos de lat y lon
            get_position='[lon, lat]',
            radius=3,
            elevation_scale=4,
            elevation_range=[0, 10],
            pickable=True,
            extruded=True,
            auto_highlight=True,
            coverage=1
        )


    view_state=pdk.ViewState(
        latitude=20.63494981128319,#lat y lon inicial 
        longitude=-103.40648023281342,
        zoom=16,
        pitch=40.5,
        bearing=-27.36
    )

    # Render
    #print(df1cpy)
    r = pdk.Deck(layers=[layers1,layers2], initial_view_state=view_state)
    r.to_html('templates/centroides.html')
    #plt.show()
    #plt.imshow(background, alpha = 0.15)
    plt.savefig("centroides.png")
    plt.clf()
    plt.close()
    dfi.export(dfc,"coordenadascentroides.png")

    return render_template('centroides.html')
Exemplo n.º 8
0
layer = pdk.Layer(
    "GreatCircleLayer",
    df,
    pickable=True,
    get_stroke_width=12,
    get_source_position="from.coordinates",
    get_target_position="to.coordinates",
    get_source_color=[64, 255, 0],
    get_target_color=[0, 128, 200],
    auto_highlight=True,
)

# Set the viewport location
view_state = pdk.ViewState(latitude=50,
                           longitude=-40,
                           zoom=1,
                           bearing=0,
                           pitch=0)

# Render
r = pdk.Deck(
    layers=[layer],
    initial_view_state=view_state,
)
r.picking_radius = 10

app = dash.Dash(__name__)

app.layout = html.Div(
    dash_deck.DeckGL(
        r.to_json(),
Exemplo n.º 9
0
    def testPyDeckMap(self, longitude=-0.1252, latitude=51.5315):
        rows = st.slider('Number of data points',
                         min_value=10000,
                         max_value=50000,
                         step=5000,
                         value=10000,
                         key=2)
        spread = st.slider('Spread',
                           min_value=0.0,
                           max_value=1.0,
                           step=0.01,
                           value=0.25,
                           key=2)
        spread /= 10

        # randn generates a standard normal distribution array of shape (D0, D1,    . Dn) with mean=0 and sd=1
        # randn(1000, 2) generates a 1000 rows x 2 cols array of normally distributed data points
        df_map = pd.DataFrame(np.random.randn(rows, 2) * [spread, spread] +
                              [longitude, latitude],
                              columns=['longitude', 'latitude'])

        COLOUR_RANGE = [[29, 53, 87], [69, 123, 157], [168, 218, 220],
                        [241, 250, 238], [239, 35, 60], [217, 4, 41]]

        test_success_outcome = False
        try:
            # HexagonLayer bins its data points within each hex shape bucket
            st.pydeck_chart(
                pdk.Deck(
                    map_style='mapbox://styles/mapbox/light-v9',
                    initial_view_state=pdk.ViewState(latitude=latitude,
                                                     longitude=longitude,
                                                     zoom=10,
                                                     pitch=55),
                    layers=[
                        pdk.Layer(type='HexagonLayer',
                                  data=df_map,
                                  color_range=COLOUR_RANGE,
                                  get_position=['longitude', 'latitude'],
                                  radius=200,
                                  elevation_scale=4,
                                  elevation_range=[0, 1000],
                                  pickable=True,
                                  extruded=True,
                                  opacity=0.8,
                                  stroked=False,
                                  filled=True),
                        pdk.Layer(type='ScatterplotLayer',
                                  data=df_map,
                                  get_position=['longitude', 'latitude'],
                                  get_color=[0, 121, 63, 160],
                                  get_radius=200),
                    ],
                ))
            test_success_outcome = True
        except:
            st.warning('Can\'t display map with supplied settings')

        st.write('First Longitude = %.4f, First Latitude = %.4f' %
                 (df_map['longitude'].iloc[0], df_map['latitude'].iloc[0]))

        self.assertTrue(test_success_outcome == True)
    st.write(
        f"The {option_nn} neighbours for {map_data.geography_name[0]} {option_gra} "
        +
        f"are: {other_neighbours} and {map_data.geography_name[n_neighbours]}."
        + f" {noise_warning}")

st.write(f"The features to find the neighbours are {list(cols_for_metric)}.")

# %%
### Making the plots
st.pydeck_chart(
    pdk.Deck(
        map_style="mapbox://styles/mapbox/light-v9",
        initial_view_state=pdk.ViewState(
            latitude=np.median(map_data.lati),
            longitude=np.median(map_data.long),
            zoom=5,
            pitch=5,
        ),
        layers=[
            pdk.Layer(
                "ScatterplotLayer",
                data=map_data,
                get_position=["long", "lati"],
                get_color=[f"lati =={map_data.lati[0]}? 255: 0", 30, 200, 150],
                # auto_highlight=True,
                get_radius=3000,  # seems not to scale automatically
                # pickable=True
            ),
        ],
    ))
Exemplo n.º 11
0
def show_map(data, stat, region=None, date=None):
    st.header('Color maps')

    if not date:
        date = max([max(data[key]['Date']) for key in data.keys()])

    # Custom color scale (colorbrewer2.org -> Sequential Single-Hue)
    breaks = [.0, .2, .4, .6, .8, 1]
    color_range = [
        # 6-class Blues
        [255, 255, 255],
        [198, 219, 239],
        [158, 202, 225],
        [107, 174, 214],
        [49, 130, 189],
        [8, 81, 156],

        # # 6-class Purples (For reference)
        # [242,240,247],
        # [218,218,235],
        # [188,189,220],
        # [158,154,200],
        # [117,107,177],
        # [84,39,143],
    ]

    def color_scale(val):
        for i, b in enumerate(breaks):
            if val <= b:
                return color_range[i]
        return color_range[i]

    def elevation_scale(val, scale):
        for i, b in enumerate(breaks):
            if val <= b:
                return i * scale

    def set_nan(val):
        if np.isnan(val):
            return -1
        else:
            return val

    stat_text = {
        'infections': ['Infections', 'Casualties'],
        'vaccines': ['Administered', 'Fully Vaccinated']
    }

    for key, stat_key in stat.items():
        if key == 'infections':
            st.subheader('Infections')
        elif key == 'vaccines':
            st.subheader('Vaccines')

        st.write(
            f'* Color depths: {stat_text[key][0]} \n* Elevation: {stat_text[key][1]}'
        )
        stat_tot = sum(['Tot' in stat_keys for stat_keys in stat_key])

        # Load in the JSON data
        if region and region != 'Worldwide' and stat_tot == 0:
            src_geo = 'data/geojson/' + region + '.json'
        else:
            src_geo = 'data/geojson/countries.json'

        json_geo = pd.read_json(src_geo)
        df = pd.DataFrame()

        # Parse the geometry out in Pandas
        df["coordinates"] = json_geo["features"].apply(
            lambda row: row["geometry"]["coordinates"])
        df["name"] = json_geo["features"].apply(
            lambda row: row["properties"]["name"])
        df["adm0_a3"] = json_geo["features"].apply(
            lambda row: row["properties"]["adm0_a3"])
        df["admin"] = json_geo["features"].apply(
            lambda row: row["properties"]["admin"])

        df['param'] = f"{str.title(key)} {sorted(set(val[1] for val in read_columns[key].values() if val[0] in stat_key))[0]}"
        df['stat_text0'] = stat_text[key][0]
        df['stat_text1'] = stat_text[key][1]

        stat_key = [
            stat_keys[1:] if stat_keys[0] == 'r' else stat_keys
            for stat_keys in stat_key
        ]
        filtered_data = data[key].loc[
            data[key]['Date'] == date,
            ['adm0_a3', 'Province/State', 'lat', 'lon'] + stat_key]

        if not region or region == 'Worldwide' or stat_tot > 0:
            filtered_data = filtered_data.groupby(
                ['adm0_a3'])[['lat', 'lon'] + stat_key].mean()
            df = pd.merge(df,
                          filtered_data,
                          how='inner',
                          left_on=['adm0_a3'],
                          right_on=['adm0_a3'])
            df['name'] = 'N/A'
            if region and region != 'Worldwide':
                zoom = 3
            else:
                zoom = 1
        else:
            filtered_data = filtered_data.loc[
                filtered_data['adm0_a3'] == region,
                ['adm0_a3', 'Province/State', 'lat', 'lon'] + stat_key]
            df = pd.merge(df,
                          filtered_data,
                          how='inner',
                          left_on=['name', 'adm0_a3'],
                          right_on=['Province/State', 'adm0_a3'])
            zoom = 3

        # Moved to generic.py
        # df.loc[df[stat_keys[0]]<0,stat_keys[0]] = 0
        # df.loc[df[stat_keys[1]]<0,stat_keys[1]] = 0
        # df[stat_keys[0]] = df[stat_keys[0]].apply(set_nan)
        # df[stat_keys[1]] = df[stat_keys[1]].apply(set_nan)

        df['fill_color'] = (df[stat_key[0]] / df[stat_key[0]].max()).replace(
            np.nan, 0).apply(color_scale)
        df['elevation'] = (df[stat_key[1]] / df[stat_key[1]].max()).replace(
            np.nan, 0).apply(lambda x: elevation_scale(x, 1e4))

        df.rename(columns={
            stat_key[0]: 'stat_0',
            stat_key[1]: 'stat_1'
        },
                  inplace=True)

        if not region or region == 'Worldwide':
            lat = df.loc[(df['lat'] != 0) & (df['lon'] != 0),
                         'lat'].mean(skipna=True)
            lon = df.loc[(df['lat'] != 0) & (df['lon'] != 0),
                         'lon'].mean(skipna=True)
        else:
            lat = df.loc[(df['adm0_a3'] == region) & (df['lat'] != 0) &
                         (df['lon'] != 0), 'lat'].mean(skipna=True)
            lon = df.loc[(df['adm0_a3'] == region) & (df['lat'] != 0) &
                         (df['lon'] != 0), 'lon'].mean(skipna=True)

        view_state = pdk.ViewState(
            latitude=
            lat,  #df.loc[(df['lat'] != 0) & (df['lon'] != 0),'lat'].mean(skipna=True),
            longitude=
            lon,  #df.loc[(df['lat'] != 0) & (df['lon'] != 0),'lon'].mean(skipna=True),
            # bearings=15,
            # pitch=45,
            zoom=zoom)

        polygon_layer = pdk.Layer(
            "PolygonLayer",
            df,
            id="geojson",
            opacity=0.2,
            stroked=False,
            get_polygon="coordinates",
            filled=True,
            get_elevation='elevation',
            # elevation_scale=1e5,
            # elevation_range=[0,100],
            extruded=True,
            # wireframe=True,
            get_fill_color='fill_color',
            get_line_color=[255, 255, 255],
            auto_highlight=True,
            pickable=True,
        )

        tooltip = {
            "html":
            "<b>Country/Region:</b> {admin} <br /><b>Province/State:</b> {name} <br /><b>Type:</b> {param}<br /><b>{stat_text0}:</b> {stat_0} <br /><b>{stat_text1}:</b> {stat_1}"
        }

        r = pdk.Deck(
            layers=[polygon_layer],
            initial_view_state=view_state,
            map_style='light',
            tooltip=tooltip,
        )

        # return r
        st.pydeck_chart(r, use_container_width=True)
    # Parse the geometry out in Pandas
    df = pd.DataFrame()
    df["coordinates"] = sig_geo.apply(lambda row: row["coordinates"][0])
    df["SIG_CD"] = sig_prop.apply(lambda row: row["SIG_CD"])
    df['SIG_CD'] = df['SIG_CD'].astype(int)
    df["SIG_ENG_NM"] = sig_prop.apply(lambda row: row["SIG_ENG_NM"])
    df["SIG_KOR_NM"] = sig_prop.apply(lambda row: row["SIG_KOR_NM"])
    return aptdeal_wide, df


aptdeal_wide, df = load_data()
view_state = pdk.ViewState(
    **{
        "latitude": 37.5642135,
        "longitude": 127.0016985,
        "zoom": 9,
        "maxZoom": 14,
        "pitch": 60,
        "bearing": 0
    })
COLOR_RANGE = [
    [65, 182, 196],
    [127, 205, 187],
    [199, 233, 180],
    [237, 248, 177],
    [255, 255, 204],
    [255, 237, 160],
    [254, 217, 118],
    [254, 178, 76],
    [253, 141, 60],
    [252, 78, 42],
Exemplo n.º 13
0
    "HexagonLayer",
    data=data,
    get_position="[lng, lat]",
    auto_highlight=True,
    elevation_scale=50,
    pickable=True,
    elevation_range=[0, 3000],
    extruded=True,
    coverage=1,
)

# Set the viewport location
view_state = pdk.ViewState(longitude=-1.415,
                           latitude=52.2323,
                           zoom=6,
                           min_zoom=5,
                           max_zoom=15,
                           pitch=40.5,
                           bearing=-27.36)

# Combined all of it and render a viewport
r = pdk.Deck(
    map_style="mapbox://styles/mapbox/light-v9",
    layers=[layer],
    initial_view_state=view_state,
    tooltip={
        "html": "<b>Elevation Value:</b> {elevationValue}",
        "style": {
            "color": "white"
        }
    },
Exemplo n.º 14
0
    )
    if chart == '地図':
        sel_country = result.loc[idx, 'country']
        result['color_idx'] = 0
        result.loc[result['country'] == sel_country, 'color_idx'] = 1
        result['color'] = result['color_idx'].map(lambda x : COLOR_LIST[x])

        geo = result[['country', 'lat', 'lon', 'color']]
        geo['cnt'] = geo['country'].map(geo.country.value_counts())
        geo = geo.drop_duplicates(subset='country')

        st.pydeck_chart(pdk.Deck(
            map_style='mapbox://styles/hiromu/ckfqgnutx0rbm19o703uqrdjf',
            initial_view_state=pdk.ViewState(
                latitude=0,
                longitude=0,
                zoom=1
            ),
            layers=[
                pdk.Layer(
                    "ScatterplotLayer",
                    data=geo,
                    get_position=['lon', 'lat'],
                    pickable=True,
                    opacity=0.8,
                    stroked=True,
                    filled=True,
                    get_fill_color='color',
                    get_line_color=[0, 0, 0],
                    get_radius='cnt',
                    radius_scale=100000,
Exemplo n.º 15
0
    data=caminos_data,
    stroked=False,
    filled=True,
    extruded=True,
    wireframe=True,
    get_line_color=[255, 0, 0],
)

line_layer = pdk.Layer("LineLayer",
                       data=merged_data[['InputLoc', 'TargetLoc']],
                       get_width=100,
                       get_source_position="InputLoc",
                       get_target_position="TargetLoc",
                       highlight_color=[255, 255, 0],
                       pickable=True)

# Set the viewport location
view_state = pdk.ViewState(longitude=node_data['lon'].mean(),
                           latitude=node_data['lat'].mean(),
                           zoom=7,
                           min_zoom=1,
                           max_zoom=20,
                           pitch=40.5,
                           bearing=-27.36)
layers = [nodes_layer, line_layer]
# Combined all of it and render a viewport
r = pdk.Deck(map_style="mapbox://styles/mapbox/light-v9",
             layers=layers,
             initial_view_state=view_state)
st.dataframe(edge_data)  # Same as st.write(df)
st.pydeck_chart(r)
Exemplo n.º 16
0
def main():
    st.button("Re-run")

    #set up layout
    st.title("Welcome to the pag3")
    st.markdown("Coming soon ... Sign up [here]() to get notified.")

    #### MAP OPEN-STREET MAP #####
    df = pd.DataFrame(np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
                      columns=['lat', 'lon'])
    st.map(df)

    # #### GRAPH-VISUAL #####
    import graphviz as graphviz
    # Create a graphlib graph object
    graph = graphviz.Digraph()
    graph.edge('run', 'intr')
    graph.edge('intr', 'runbl')
    graph.edge('runbl', 'run')
    graph.edge('run', 'kernel')
    graph.edge('kernel', 'zombie')
    graph.edge('kernel', 'sleep')
    graph.edge('kernel', 'runmem')
    graph.edge('sleep', 'swap')
    graph.edge('swap', 'runswap')
    graph.edge('runswap', 'new')
    graph.edge('runswap', 'runmem')
    graph.edge('new', 'runmem')
    graph.edge('sleep', 'runmem')
    st.graphviz_chart(graph)

    # ### SINGLE-TABLE ####
    st.subheader('DATAFRAME')
    df = pd.DataFrame(np.random.randn(50, 20),
                      columns=('col %d' % i for i in range(20)))
    st.dataframe(df)  # Same as st.write(df)

    ### SINGLE-TABLE - yellowMAX ####
    st.subheader('DATAFRAME WITH MAX UNDERLIANED')
    df = pd.DataFrame(np.random.randn(10, 20),
                      columns=('col %d' % i for i in range(20)))
    st.dataframe(df.style.highlight_max(axis=0))

    ### STATIC TABLE ####
    #Display a static table.
    ''' This differs from st.dataframe in that the table in this case is static: 
    its entire contents are laid out directly on the page.'''
    st.subheader('TABLE')
    df = pd.DataFrame(np.random.randn(10, 5),
                      columns=('col %d' % i for i in range(5)))
    st.table(df)

    ### LINE CHART ####
    st.subheader('LINE CHART')
    chart_data = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])

    st.line_chart(chart_data)

    ### LINE CHART AREA####
    st.subheader('LINE CHART AREA')
    chart_data = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])

    st.area_chart(chart_data)

    #### BAR-CHART #####
    st.subheader('BAR CHART')
    chart_data = pd.DataFrame(np.random.randn(50, 3), columns=["a", "b", "c"])

    st.bar_chart(chart_data)

    #### HISTOGRAM-MATPLOTLIB #####
    import matplotlib.pyplot as plt
    st.subheader('HISTOGRAM MATPLOTLIB')

    arr = np.random.normal(1, 1, size=100)
    fig, ax = plt.subplots()
    ax.hist(arr, bins=20)
    st.pyplot(fig)

    #### scatter-ALTAIR #####
    st.subheader('SCATTER ALTAIR')
    import altair as alt
    df = pd.DataFrame(np.random.randn(200, 3), columns=['a', 'b', 'c'])

    c = alt.Chart(df).mark_circle().encode(x='a',
                                           y='b',
                                           size='c',
                                           color='c',
                                           tooltip=['a', 'b', 'c'])
    st.altair_chart(c, use_container_width=True)

    #### PLOTLY #########
    st.subheader('PLOTLY DIAGRAM')
    import plotly.figure_factory as ff
    # Add histogram data
    x1 = np.random.randn(200) - 2
    x2 = np.random.randn(200)
    x3 = np.random.randn(200) + 2

    # Group data together
    hist_data = [x1, x2, x3]

    group_labels = ['Group 1', 'Group 2', 'Group 3']

    # Create distplot with custom bin_size
    fig = ff.create_distplot(hist_data, group_labels, bin_size=[.1, .25, .5])
    # Plot!
    st.plotly_chart(fig, use_container_width=True)

    #### BOKEH #########
    st.subheader('BOKEH')
    from bokeh.plotting import figure
    x = [1, 2, 3, 4, 5]
    y = [6, 7, 2, 4, 5]

    p = figure(title='simple line example', x_axis_label='x', y_axis_label='y')
    p.line(x, y, line_width=2)
    st.bokeh_chart(p, use_container_width=True)

    #### Plotly 2 ################
    import plotly.express as px
    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    from numpy import random

    pts = 50
    x1 = np.arange(pts)
    y1 = np.random.rand(pts)
    y2 = np.random.rand(pts)
    y3 = (x1 / pts)**2

    fig = make_subplots(rows=1, cols=2)

    fig.add_trace(go.Scatter(x=x1, y=y1, mode='markers', name='markers'),
                  row=1,
                  col=1)
    fig.add_trace(go.Scatter(x=x1, y=y2, mode='markers', name='markers2'),
                  row=1,
                  col=2)
    fig.add_trace(go.Scatter(x=x1, y=y3, mode='lines', name='lines'),
                  row=1,
                  col=2)

    fig.update_layout(height=300,
                      width=800,
                      title_text="Side By Side Subplots")
    st.plotly_chart(fig)

    #### exagonbar-3d ###########################################
    st.subheader('exagon bar-3d')
    import pydeck as pdk
    df = pd.DataFrame(np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
                      columns=['lat', 'lon'])

    st.pydeck_chart(
        pdk.Deck(
            map_style='mapbox://styles/mapbox/light-v9',
            initial_view_state=pdk.ViewState(
                latitude=37.76,
                longitude=-122.4,
                zoom=11,
                pitch=50,
            ),
            layers=[
                pdk.Layer(
                    'HexagonLayer',
                    data=df,
                    get_position='[lon, lat]',
                    radius=200,
                    elevation_scale=4,
                    elevation_range=[0, 1000],
                    pickable=True,
                    extruded=True,
                ),
                pdk.Layer(
                    'ScatterplotLayer',
                    data=df,
                    get_position='[lon, lat]',
                    get_color='[200, 30, 0, 160]',
                    get_radius=200,
                ),
            ],
        ))

    #### exagonbar-3d ACCIDENT ###########################################

    UK_ACCIDENTS_DATA = (
        'https://raw.githubusercontent.com/uber-common/'
        'deck.gl-data/master/examples/3d-heatmap/heatmap-data.csv')

    # Define a layer to display on a map
    layer = pdk.Layer('HexagonLayer',
                      UK_ACCIDENTS_DATA,
                      get_position=['lng', 'lat'],
                      auto_highlight=True,
                      elevation_scale=50,
                      pickable=True,
                      elevation_range=[0, 3000],
                      extruded=True,
                      coverage=1)

    # Set the viewport location
    view_state = pdk.ViewState(longitude=-1.415,
                               latitude=52.2323,
                               zoom=6,
                               min_zoom=5,
                               max_zoom=15,
                               pitch=40.5,
                               bearing=-27.36)
    # Render
    st.pydeck_chart(pdk.Deck(layers=[layer], initial_view_state=view_state))

    #### one-image ###########################################
    st.subheader('one-image from URL')
    from PIL import Image
    #image = Image.open('images/cat.jpg')
    image = 'https://static.streamlit.io/examples/cat.jpg'
    st.image(image, use_column_width=True)

    #### more-images###########################################
    st.subheader('more-images')
    col1, col2, col3 = st.beta_columns(3)
    with col1:
        st.header("A cat")
        st.image("https://static.streamlit.io/examples/cat.jpg",
                 use_column_width=True)

    with col2:
        st.header("A dog")
        st.image("https://static.streamlit.io/examples/dog.jpg",
                 use_column_width=True)

    with col3:
        st.header("An owl")
        st.image("https://static.streamlit.io/examples/owl.jpg",
                 use_column_width=True)

    #### display -code ###########################################
    st.subheader('display code')
    with st.echo():
        st.write('This code will be printed')

    show_footer()
Exemplo n.º 17
0
def app():
    st.title('Recoverd')
    engine = create_engine("mysql+pymysql://alex:test123@db:3306/airflowcovid")

    recover = pd.read_sql_table('recoverd', engine)
    dfrecover = recover.copy()
    
    dfrecover['Date'] =  pd.to_datetime(dfrecover['Date'])
    max_date = max(dfrecover['Date'])
    min_date = min(dfrecover['Date'])
    description = "The following page will provide you with information about the recoverd cases around the world. This data has been gathered and display from " + str(min_date) + " to  " + str(max_date) + " to give you a better knowledge of the information you're presented with."

    group_by_country_and_date = dfrecover.groupby(['Country', 'Date'])['Recovered'].sum().reset_index()
    group_by_super = dfrecover.groupby(['Country', 'Date', 'Lat', 'Lon'])['Recovered'].sum().reset_index()
    group_by_super["Lon"] = pd.to_numeric(group_by_super["Lon"], downcast="float")
    group_by_super["Lat"] = pd.to_numeric(group_by_super["Lat"], downcast="float")

    total_cases = dfrecover[dfrecover['Date'] == max_date]
    total_cases.rename(columns = {'Recovered': 'Total_Cases'}, inplace = True)
    group_by_country_total = total_cases.groupby(['Country'])['Total_Cases'].sum()
    

    # FRONT-END
    st.write(description)
    
    st.subheader('Raw Data')
    st.write(dfrecover)  
    
    st.subheader('Total Recovered by ' + str(max_date))
    st.dataframe(group_by_country_total)
    
    st.subheader('Top 10 countries with more recovered cases by date')
    hour_selected = st.date_input(label="Select a Date", value=dfrecover['Date'].min(),  min_value=dfrecover['Date'].min(),  max_value=dfrecover['Date'].max())
    df_filter_date = dfrecover[dfrecover['Date'] == hour_selected.isoformat()]
    df_filter_date.rename(columns = {'Recovered': 'Total_Cases'}, inplace = True)
    group_by_country_date = df_filter_date.groupby(['Country'])['Total_Cases'].sum().reset_index()
    group_by_country_date.sort_values(by=['Total_Cases'], ascending=False, inplace = True)
    a = group_by_country_date.head(10)
    
    s = alt.Chart(a).mark_bar().encode(
        alt.X('Country'),
        alt.Y('Total_Cases')
    )

    st.altair_chart(s, use_container_width=True)
    
    st.subheader('Historical data by country')
    countries_sel = st.multiselect(
     'Select a Contry',
     dfrecover['Country'].unique())

    if len(countries_sel) > 0:
        filter_his_by_country = group_by_country_and_date[group_by_country_and_date.Country.isin(countries_sel)]
        q = alt.Chart(filter_his_by_country).mark_line().encode(
            x='Date',
            y='Recovered',
            color='Country',
            strokeDash='Country',
        )
        st.altair_chart(q, use_container_width=True)

    
    
    st.subheader('Historical Map')

    # 2020-11-04 00:00:00


    a = pd.date_range(start=min_date,end=max_date)
    fin = pd.DataFrame(a, columns=['fecha'])
    fin.insert(0, 'ID', range(0, len(fin)))

    x = st.slider('Drag Date', min_value=0, max_value=len(fin), value=1)
    
    filterd = fin[fin['ID'] == x]['fecha']
    
    st.write(filterd.iloc[0]) 

    
    group_by_super_date = group_by_super[group_by_super['Date'] == filterd.iloc[0]]
    # Set viewport for the deckgl map
    view = pdk.ViewState(latitude=0, longitude=0, zoom=0.2,)

    
    # Create the scatter plot layer
    covidLayer = pdk.Layer(
            "ScatterplotLayer",
            group_by_super_date[['Recovered','Lat','Lon']],
            get_position=['Lon', 'Lat'],
            get_radius='Recovered',          # Radius is given in meters
            get_fill_color=[252, 136, 3],
            get_line_color=[255,0,0],
            pickable=False,
            opacity=0.3,
            stroked=True,
            filled=True,
            radius_scale=10,
            radius_min_pixels=2,
            radius_max_pixels=25,
            line_width_min_pixels=1
        )

    # Create the deck.gl map
    r = pdk.Deck(
        layers=[covidLayer],
        initial_view_state=view,
        map_style="mapbox://styles/mapbox/light-v10"
    )
    map = st.pydeck_chart(r)
Exemplo n.º 18
0
		list(dogs.keys()))

#Initial estimate for duration depends on dog breed
duration = st.number_input('How much time (minutes) do you have for this walk?', step = 5, value = 10 * int(1.2 * dogs[temp][0]))

if duration > 60:
	st.write('This is a long walk! It might take a while to route...')

#Estimate for walking speed depends on dog breed
#Vary by ~20% depending on dog height
walking_rate = set_walking_rate(80 - (15/14)*(14-dogs[temp][1])) #m/min

#If we want to avoid busy streets, we adjust the edge weights later
avoid_busy_streets = st.checkbox('Keep me away from busy streets', value=False, key=1)

submit = st.button('Calculate route - Go!', key=1)
if not submit:
	st.pydeck_chart(pdk.Deck(
		map_style="mapbox://styles/mapbox/light-v9", 
		initial_view_state=pdk.ViewState(latitude = 42.358, longitude = -71.085, zoom=11)))
else:
	if select=='Going out for a walk':
		with st.spinner('Routing...'):
			source_to_source(G, gdf_nodes, gdf_edges, input1, walking_rate*duration, False, avoid_busy_streets)
	elif select=='Take me to a park':
		with st.spinner('Routing...'):
			source_to_source(G, gdf_nodes, gdf_edges, input1, walking_rate*duration, True, avoid_busy_streets)
	else:
		with st.spinner('Routing...'):
			source_to_dest(G, gdf_nodes, gdf_edges, input1, input2, walking_rate*duration, walking_rate, avoid_busy_streets)
Exemplo n.º 19
0
    "https://raw.githubusercontent.com/johan/world.geo.json/master/countries.geo.json"
)

custom_layer = pydeck.Layer(
    "LabeledGeoJsonLayer",
    data=DATA_URL,
    filled=False,
    billboard=False,
    get_line_color=[180, 180, 180],
    get_label="properties.name",
    get_label_size=200000,
    get_label_color=[0, 255, 255],
    label_size_units='"meters"',
    line_width_min_pixels=1,
)

view_state = pydeck.ViewState(latitude=0, longitude=0, zoom=1)

r = pydeck.Deck(custom_layer, initial_view_state=view_state, map_provider=None)

external_scripts = [{
    "src":
    "https://unpkg.com/pydeck-custom-layer-demo/dist/bundle.js"
}]
app = dash.Dash(__name__, external_scripts=external_scripts)

app.layout = html.Div(dash_deck.DeckGL(r.to_json(), id="deck-gl"))

if __name__ == "__main__":
    app.run_server(debug=True)
Exemplo n.º 20
0
def source_to_source(G, gdf_nodes, gdf_edges, s, dist, to_park, avoid_streets):
	#Inputs: Graph, nodes, edges, source, distance to walk, to_park bool = route to park, avoid_streets bool = avoid busy roads
	
	#Set default source to Insight Offices
	if s == '':
		#No address, default to Insight
		st.write('Source address not found, defaulting to Insight Offices')
		s = '280 Summer St Boston'
		start_location = ox.geo_utils.geocode(s)
	else:
		try:
			start_location = ox.geo_utils.geocode(s + ' Boston')
		except:
			#No address found, default to Insight
			st.write('Source address not found, defaulting to Insight Offices')
			s = '280 Summer St Boston'
			start_location = ox.geo_utils.geocode(s)

	#Get coordinates from start address and snap to node
	start_coords = (start_location[0], start_location[1])
	start_node = ox.get_nearest_node(G, start_coords)

	#Calculate new edge weights
	tree_counts = {}
	road_safety = {}
	lengths = {}

	for row in gdf_edges.itertuples():
		u = getattr(row,'u')
		v = getattr(row,'v')
		key = getattr(row, 'key')
		tree_count = getattr(row, 'trees')
		safety_score = getattr(row, 'safety')
		length = getattr(row, 'length')

		tree_counts[(u,v,key)] = tree_count
		road_safety[(u,v,key)] = safety_score
		lengths[(u,v,key)] = length

	#Optimized attribute is a weighted combo of normal length, tree counts, and road safety.
	#Larger value is worse
	optimized = {}
	for key in lengths.keys():
		temp = int(lengths[key])
		temp += int(250/int(max(1,tree_counts[key])))
		if avoid_streets:
			temp += int(100*(road_safety[key]))
		optimized[key] = temp
			
	#Generate new edge attributes - depending on user prefs
	nx.set_edge_attributes(G, optimized, 'optimized')

	if to_park:
		#Get coords of park and path to it
		parks = pd.read_csv('data/parks.csv')
		midpoint, park_index = find_park(G, parks, start_node, start_location, dist)

		#Get path to park
		path = nx.shortest_path(G, start_node, midpoint, weight = 'optimized')
		
		#Display name of park on the map
		text_layer = make_textlayer(get_text_df(parks.iloc[park_index]['Name'], (parks.iloc[park_index]['lat'], parks.iloc[park_index]['lon'])), '[0,0,0]')

	else:
		#Get coords of midpoint nodes
		midpoints = find_midpoint(G, start_node, dist)

		#Get path to midpoint
		path = nx.shortest_path(G, start_node, midpoints[0], weight = 'optimized')
		
		if len(midpoints) > 1:
			path.append(midpoints[1])
		if len(midpoints) > 2:
			path.append(midpoints[2])

		#Dummy code because we are not outputting text
		text_layer = make_textlayer(get_text_df('', start_coords), '[255,255,255]')

	#Step 3: Adjust edge weights to penalize backtracking
	for node in range(-1+len(path)):
		G[path[node]][path[node+1]][0]['optimized'] += 300

	#Step 4: Get new route back
	if to_park:
		route_back = nx.shortest_path(G, start_node, midpoint, weight = 'optimized')
	else:
		route_back = nx.shortest_path(G, start_node, midpoints[len(midpoints)-1], weight = 'optimized')

	#Step 5: Reset edge weights
	for node in range(-1+len(path)):
		G[path[node]][path[node+1]][0]['optimized'] -= 300

	#Step 6: Plot route
	loop1_start_lat, loop1_start_lon, loop1_dest_lat, loop1_dest_lon = nodes_to_lats_lons(gdf_nodes, path)
	loop2_start_lat, loop2_start_lon, loop2_dest_lat, loop2_dest_lon = nodes_to_lats_lons(gdf_nodes, route_back)
	
	#This finds the bounds of the final map to show based on the paths
	min_x, max_x, min_y, max_y = get_map_bounds(gdf_nodes, path, route_back)

	#Find the average lat/long to center the map
	center_x = 0.5*(max_x + min_x)
	center_y = 0.5*(max_y + min_y)

	#Move coordinates into dfs
	loop1_df = pd.DataFrame({'startlat':loop1_start_lat, 'startlon':loop1_start_lon, 'destlat': loop1_dest_lat, 'destlon':loop1_dest_lon})
	loop2_df = pd.DataFrame({'startlat':loop2_start_lat, 'startlon':loop2_start_lon, 'destlat': loop2_dest_lat, 'destlon':loop2_dest_lon})

	#Add map marker icon at start 
	start_node_df = get_node_df(start_location)
	outbound_layer = make_linelayer(loop1_df, '[150,150,220]')
	inbound_layer = make_linelayer(loop2_df, '[220,50,50]')
	icon_layer = make_iconlayer(start_node_df)

	st.pydeck_chart(pdk.Deck(
		map_style="mapbox://styles/mapbox/light-v9", 
		initial_view_state=pdk.ViewState(latitude = center_y, longitude = center_x, zoom = 13, max_zoom = 15, min_zoom = 12),
		layers=[text_layer, outbound_layer, inbound_layer, icon_layer]))
	
	st.write('From your location, take the blue path to the turnaround point. Then return via the red path.')
	return
Exemplo n.º 21
0
def write():
    st.subheader("Data Cleaning")
    df = pd.read_csv('data/ljubljana_categories.csv', sep=',')
    # Drop location duplicates
    st.success(
        'If multiple rows have the same GPS coordinates, only the last one is kept.'
    )

    # Renaming id column
    df.columns = df.columns.str.lower()

    df = df.drop_duplicates(subset=['latitude', 'longitude'], keep='last')
    df = df.reset_index(drop=True)

    # Adding a distance
    df_d = df.assign(distance=0)
    for i in range(len(df_d) - 1):
        j = i + 1
        df_d.loc[j, 'distance'] = round(
            distance((df_d.latitude[i], df_d.longitude[i]),
                     (df_d.latitude[j], df_d.longitude[j])) * 1000, 2)

    # Filtering for min. and max. distances
    st.subheader('Plausibility tests')
    data_points = len(df_d)
    slide_max = int(df_d['distance'].max()) + 10

    dist = st.slider(
        'Select a range of plausible distances beween observations to be included: ',
        0, slide_max, (0, 200))
    df_d = df_d[(df_d['distance'] >= dist[0]) & (df_d['distance'] <= dist[1])]

    filtered_points = len(df_d)
    message = 'Minimum distance is ' + str(dist[0]) + ' meters and maximum distance is ' + str(dist[1]) + ' meters. Your data are reduced by: ' + \
        str(round(100 * (1 - filtered_points / data_points), 2)) + \
        ' %. Using the slider, you can change these values and see the effect in the table below. There are ' + \
        str(filtered_points) + ' data rows now.'
    st.success(message)

    # Display DataFrame
    df_d = df_d.reset_index(drop=True)
    st.dataframe(df_d[[
        'time', 'latitude', 'longitude', 'distance', 'sats', 'precision',
        'category'
    ]].style.background_gradient(subset=['distance', 'precision'],
                                 cmap='Blues'))

    # Safe new data frame
    st.markdown(get_table_download_link(df_d), unsafe_allow_html=True)

    # Pairwise Viz
    st.subheader("Pairwise comparison of mapping data")
    fig2 = plt.subplots()
    fig2 = sns.pairplot(
        df_d[['latitude', 'longitude', 'rawtime', 'category', 'distance']],
        markers=["o", "s", "D", "*"])  # hue='Category'
    st.pyplot(fig2)

    # Use of categories
    col1, col2 = st.beta_columns(2)
    col1.info('This bar chart shows the usage frequency per category.')
    cat = df_d[['category']].groupby(['category']).size()

    catSeries = pd.Series([0, 0, 0, 0, 0, 0])
    catSeries = catSeries[1:6]
    for x in cat.index:
        catSeries[x] = cat[x]
    fig, ax = plt.subplots()
    ax = sns.barplot(x=catSeries.index, y=catSeries)
    col1.pyplot(fig)

    # GPS quality
    col2.info(
        'This bar chart indicates the quality of your GPS coordinates. 5+ is good.'
    )
    satDistribution = df_d.groupby(
        df_d['sats']).size().sort_values(ascending=False)
    satNum = list(satDistribution.keys())
    satFreq = list(satDistribution)
    fig2, ax2 = plt.subplots()
    ax2 = sns.barplot(x=satNum, y=satFreq)
    col2.pyplot(fig2)

    # category coloring
    # tracks_d = categories.assign(Distance=0)
    df_d['color'] = ""
    df_d['color'] = df_d['color'].astype('object')

    cat_color = {
        1: [0, 0, 255, 250],  # Blue
        2: [255, 0, 0, 250],  # Red
        3: [0, 255, 0, 250],  # Green
        4: [255, 106, 0, 250],  # Orange
        5: [0, 88, 0, 250]  # Dark Green
    }
    for i in range(len(df_d)):
        df_d.at[i, 'color'] = cat_color[df_d.at[i, 'category']]

    st.subheader("Data Map")
    st.info(
        "... let's draw maps! You can choose the size of markers (4-12 is recommended) and the map's background."
    )
    marker = st.number_input('Marker Size: ', min_value=2, value=8)

    MapColor = {
        "Dark": 'mapbox://styles/innodesign/ckl128luk027z17mwftpdxyg1',
        "Light": 'mapbox://styles/mapbox/streets-v8',
    }
    map_col = st.radio("Map Background: ", list(MapColor.keys()))

    data = df_d[['latitude', 'longitude', 'color']]
    midpoint = (np.average(data['latitude']), np.average(data['longitude']))
    st.info('Centre coordinates of the map: ' + str(round(midpoint[0], 4)) +
            ' and ' + str(round(midpoint[1], 4)))
    components.html("""
        <h4 style="font-family: Verdana, sans-serif">Color coding of categories:</h4>
<ul style="font-family: Verdana, sans-serif; background-color: rgb(219, 213, 213)">
    <li style="color: rgb(0, 0, 255); list-style: none; background-color: rgb(219, 213, 213)"> Category 1: Blue</li>
    <li style="color: rgb(255, 0, 0); list-style: none; background-color: rgb(219, 213, 213)">Category 2: Red</li>
    <li style="color: rgb(0, 255, 0); list-style: none; background-color: rgb(219, 213, 213)">Category 3: Green</li>
    <li style="color: rgb(255, 106, 0); list-style: none; background-color: rgb(219, 213, 213)">Category 4: Orange</li>
    <li style="color: rgb(0, 88, 0); list-style: none; background-color: rgb(219, 213, 213)">Category 5: Dark Green</li>
    <li style="color: rgb(219, 213, 213); list-style: none; background-color: rgb(219, 213, 213)"..<li>
</ul>
    """,
                    height=180)

    st.pydeck_chart(
        pdk.Deck(
            # map_style='mapbox://styles/mapbox/dark-v9',
            # map_style='mapbox://styles/mapbox/streets-v8',
            map_style=MapColor[map_col],
            initial_view_state=pdk.ViewState(
                latitude=midpoint[0],
                longitude=midpoint[1],
                zoom=13,
                pitch=0,
            ),
            layers=pdk.Layer(
                "ScatterplotLayer",
                # type='HexagonLayer' / ScatterplotLayer / PointCloudLayer,
                data=data,
                get_position='[longitude, latitude]',
                elevation_scale=4,
                get_fill_color='color',
                get_radius=marker,
                opacity=0.5,
                filled=True)))
    st.info(
        'The heatmap below gives an impression of those areas, where most observations have been mapped. The more you zoom in, the more fine grained the aggregation becomes.'
    )
    st.pydeck_chart(
        pdk.Deck(map_style=MapColor[map_col],
                 initial_view_state=pdk.ViewState(
                     latitude=midpoint[0],
                     longitude=midpoint[1],
                     zoom=13,
                     pitch=0,
                 ),
                 layers=pdk.Layer(
                     "HeatmapLayer",
                     data=data,
                     get_position='[longitude, latitude]',
                     get_fill_color='color',
                     opacity=0.9,
                     aggregation='MEAN',
                 )))
Exemplo n.º 22
0
def source_to_dest(G, gdf_nodes, gdf_edges, s, e, dist, pace, avoid_streets):
	#Inputs: Graph, nodes, edges, source, end, distance to walk, pace = speed, w2 bool = avoid busy roads

	if s == '':
		#No address, default to Insight
		st.write('Source address not found, defaulting to Insight Offices')
		s = '280 Summer St Boston'
		start_location = ox.geo_utils.geocode(s)
	else:
		try:
			start_location = ox.geo_utils.geocode(s + ' Boston')
		except:
			#No address found, default to Insight
			st.write('Source address not found, defaulting to Insight Offices')
			s = '280 Summer St Boston'
			start_location = ox.geo_utils.geocode(s)

	if e == '':
		#No address, default to Fenway Park
		st.write('Destination address not found, defaulting to Fenway Park')
		e = 'Fenway Park Boston'
		end_location = ox.geo_utils.geocode(e)
	else:
		try:
			end_location = ox.geo_utils.geocode(e + ' Boston')
		except:
			#No address found, default to Insight
			st.write('Destination address not found, defaulting to Fenway Park')
			e = 'Fenway Park Boston'
			end_location = ox.geo_utils.geocode(e)

	#Get coordinates from addresses
	start_coords = (start_location[0], start_location[1])
	end_coords = (end_location[0], end_location[1])

	#Snap addresses to graph nodes
	start_node = ox.get_nearest_node(G, start_coords)
	end_node = ox.get_nearest_node(G, end_coords)

	#Calculate new edge weights
	tree_counts = {}
	road_safety = {}
	lengths = {}

	for row in gdf_edges.itertuples():
		u = getattr(row,'u')
		v = getattr(row,'v')
		key = getattr(row, 'key')
		tree_count = getattr(row, 'trees')
		safety_score = getattr(row, 'safety')
		length = getattr(row, 'length')

		tree_counts[(u,v,key)] = tree_count
		road_safety[(u,v,key)] = safety_score
		lengths[(u,v,key)] = length

	#We need to make sure that dist is at least the length of the shortest path
	min_dist = nx.shortest_path_length(G, start_node, end_node, weight = 'length')

	if dist < min_dist:
		st.write('This walk will probably take a bit longer - approximately ' + str(int(min_dist/pace)) + ' minutes total.')
		
		#We are in a rush, take the shortest path
		optimized_route = nx.shortest_path(G, start_node, end_node, weight = 'length')

	#Optimized attribute is a weighted combo of normal length, tree counts, and road safety.
	#Larger value is worse
	elif dist < 1.3*min_dist:
		#We have some extra time, length term still important
		optimized = {}
		for key in lengths.keys():
			temp = int(lengths[key])
			temp += int(250/int(max(1,tree_counts[key])))
			if avoid_streets:
				temp += int(100*(road_safety[key]))
			optimized[key] = temp

		#Generate new edge attribute
		nx.set_edge_attributes(G, optimized, 'optimized')
		
		#Path of nodes
		optimized_route = nx.shortest_path(G, start_node, end_node, weight = 'optimized')

	else:
		#dist > 1.3*min_dist
		opt_dist = nx.shortest_path_length(G, start_node, end_node, weight = 'optimized')
		if dist > 1.3*opt_dist:
			st.write('You can take your time! The walk should only take approximately ' + str(int(opt_dist/pace)) + ' minutes.')
		#We have a lot of extra time, let trees/safety terms dominate
		optimized = {}
		for key in lengths.keys():
			temp = 0.2*int(lengths[key])
			temp += int(250/int(max(1,tree_counts[key])))
			if avoid_streets:
				temp += int(100*(road_safety[key]))
			optimized[key] = temp

		#Generate new edge attributes
		nx.set_edge_attributes(G, optimized, 'optimized')

		#Path of nodes
		optimized_route = nx.shortest_path(G, start_node, end_node, weight = 'optimized')

	shortest_route = nx.shortest_path(G, start_node, end_node, weight = 'length')
	short_start_lat, short_start_lon, short_dest_lat, short_dest_lon = nodes_to_lats_lons(gdf_nodes, shortest_route)
	short_df = pd.DataFrame({'startlat':short_start_lat, 'startlon':short_start_lon, 'destlat': short_dest_lat, 'destlon':short_dest_lon})
	short_layer = make_linelayer(short_df, '[200,200,200]')
	
	#This finds the bounds of the final map to show based on the paths
	min_x, max_x, min_y, max_y = get_map_bounds(gdf_nodes, shortest_route, optimized_route)

	#These are lists of origin/destination coords of the paths that the routes take
	opt_start_lat, opt_start_lon, opt_dest_lat, opt_dest_lon = nodes_to_lats_lons(gdf_nodes, optimized_route)

	#Find the average lat/long to center the map
	center_x = 0.5*(max_x + min_x)
	center_y = 0.5*(max_y + min_y)

	#Move coordinates into dfs
	opt_df = pd.DataFrame({'startlat':opt_start_lat, 'startlon':opt_start_lon, 'destlat': opt_dest_lat, 'destlon':opt_dest_lon})

	start_node_df = get_node_df(start_location)
	icon_layer = make_iconlayer(start_node_df)
	optimized_layer = make_linelayer(opt_df, '[50,220,50]')

	st.pydeck_chart(pdk.Deck(
		map_style="mapbox://styles/mapbox/light-v9", 
		initial_view_state=pdk.ViewState(latitude = center_y, longitude = center_x, zoom=13, max_zoom = 15, min_zoom = 12), 
		layers=[short_layer, optimized_layer, icon_layer]))

	st.write('From your location, take the green path to your destination. The gray path (if present) is the quickest path.')
	return
Exemplo n.º 23
0
hour_selected = st.date_input("Seleccione fecha", data['Fecha'].min(),
                              data['Fecha'].min(), data['Fecha'].max())

paises = st.multiselect('¿Qué países es?', df['Pais'].unique())

st.write("""Gráfica de casos confirmados de coronavirus en el mundo
    """)

mostrar = data[data[DATE_TIME] == hour_selected.isoformat()]
if len(paises) > 0:
    mostrar = mostrar[mostrar.Pais.isin(paises)]

# Set viewport for the deckgl map
view = pdk.ViewState(
    latitude=0,
    longitude=0,
    zoom=0.2,
)

# Create the scatter plot layer
covidLayer = pdk.Layer("ScatterplotLayer",
                       data=mostrar[['Casos', 'lat', 'lon']],
                       pickable=False,
                       opacity=0.3,
                       stroked=True,
                       filled=True,
                       radius_scale=10,
                       radius_min_pixels=2,
                       radius_max_pixels=25,
                       line_width_min_pixels=1,
                       get_position=["lon", "lat"],
Exemplo n.º 24
0
nn = pd.DataFrame(nodos, columns=['lat'])

dato = pd.read_csv('region.csv', encoding="latin1")
df = (dato)
df = df.fillna(0)  # elimina los nan

st.title("Grafo y Arbol region 10")
st.markdown("Grafo")

st.pydeck_chart(
    pdk.Deck(
        map_style="mapbox://styles/mapbox/light-v9",
        initial_view_state=pdk.ViewState(
            latitude=-41.46852167033,
            longitude=-72.960548400879,
            zoom=8,
            pitch=40,
        ),
        layers=[
            pdk.Layer(
                "HexagonLayer",
                df,
                get_position="[lon, lat]",
                radius=300,
                elevation_scale=40,
                elevation_range=[200, 1000],
                pickable=True,
                extruded=True,
            ),
            pdk.Layer(
                "LineLayer",
Exemplo n.º 25
0
    "color": [255, 255, 255],
    "intensity": 1.0
}

lighting_effect = {
    "@@type": "LightingEffect",
    "shadowColor": [0, 0, 0, 0.5],
    "ambientLight": ambient_light,
    "directionalLights": [sunlight],
}

view_state = pydeck.ViewState(
    **{
        "latitude": 49.254,
        "longitude": -123.13,
        "zoom": 11,
        "maxZoom": 16,
        "pitch": 45,
        "bearing": 0
    })

LAND_COVER = [[[-123.0, 49.196], [-123.0, 49.324], [-123.306, 49.324],
               [-123.306, 49.196]]]

polygon_layer = pydeck.Layer(
    "PolygonLayer",
    LAND_COVER,
    stroked=False,
    # processes the data as a flat longitude-latitude pair
    get_polygon="-",
    get_fill_color=[0, 0, 0, 20],
Exemplo n.º 26
0
# AWS Open Data Terrain Tiles
TERRAIN_IMAGE = '"https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"'

# Define how to parse elevation tiles
ELEVATION_DECODER = {
    "rScaler": 256,
    "gScaler": 1,
    "bScaler": 1 / 256,
    "offset": -32768
}

SURFACE_IMAGE = '"https://api.mapbox.com/v4/mapbox.satellite/{{z}}/{{x}}/{{y}}@2x.png?access_token={}"'.format(
    MAPBOX_API_KEY)

terrain_layer = pdk.Layer("TerrainLayer",
                          data=None,
                          elevation_decoder=ELEVATION_DECODER,
                          texture=SURFACE_IMAGE,
                          elevation_data=TERRAIN_IMAGE)

view_state = pdk.ViewState(latitude=46.24,
                           longitude=-122.18,
                           zoom=11.5,
                           bearing=140,
                           pitch=60)

r = pdk.Deck(terrain_layer, initial_view_state=view_state)

r.to_html("terrain_layer.html")
Exemplo n.º 27
0
# this map shows all the trips done from the user
#it take the starting point and the end point, it does not show the route but just the distance from start to end
#represented with the arc

df_id = df[[
    'start_latitude', 'start_longitude', 'end_latitude', 'end_longitude'
]]
midpoint = (np.average(df_id["end_latitude"]),
            np.average(df_id["end_longitude"]))

#mapbox used for the arc plot map
st.pydeck_chart(
    pdk.Deck(map_style='mapbox://styles/mapbox/light-v9',
             initial_view_state=pdk.ViewState(
                 latitude=midpoint[0],
                 longitude=midpoint[1],
                 zoom=11,
                 pitch=50,
             ),
             layers=[
                 pdk.Layer(
                     "ArcLayer",
                     data=df_id,
                     get_source_position="[start_longitude, start_latitude]",
                     get_target_position="[end_longitude, end_latitude]",
                     get_source_color=[0, 30, 87, 160],
                     get_target_color=[0, 30, 190, 160])
             ]))

#This section of the first part contains a map that shows the costumer engagement
# Data is taken from the csv files
# What the code does, is that it takes all the costumer engagement from all the days they have been active
Exemplo n.º 28
0
    "ArcLayer",
    data=df,
    get_width="S000 * 2",
    get_source_position=["lng_h", "lat_h"],
    get_target_position=["lng_w", "lat_w"],
    get_tilt=15,
    get_source_color=RED_RGB,
    get_target_color=GREEN_RGB,
    pickable=True,
    auto_highlight=True,
)

view_state = pdk.ViewState(
    latitude=37.7576171,
    longitude=-122.5776844,
    bearing=45,
    pitch=50,
    zoom=8,
)

TOOLTIP_TEXT = {
    "html":
    "{S000} jobs <br /> Home of commuter in red; work location in green"
}
r = pdk.Deck(
    arc_layer,
    initial_view_state=view_state,
    mapbox_key=mapbox_api_token,
)

app = dash.Dash(__name__)
Exemplo n.º 29
0
def monta_estados(taxa_mortalidade):
    df = load_data_brasil_io()
    states = df['state'].sort_values(ascending=True).unique()
    if states is not None:
        state = st.sidebar.selectbox('Qual o estado você deseja visualizar?', states)

        dados_estado =df[(df['state'] == state)&(df['place_type']=='state')]
        dados_estado_cities =df[(df['state'] == state)&(df['place_type'] != 'state')]

        st.subheader(f"Dados de COVID em {state}")

        dados_estado_plot = dados_estado[['date', 'confirmed', 'deaths']].sort_values(by=['date'], ascending=True)
        dados_estado_plot.reset_index(drop=True, inplace=True)
        dados_estado_plot.set_index(['date'], inplace=True)

        hoje = dados_estado[dados_estado['is_last']]
        hoje.reset_index(drop=True, inplace=True)
        dia_atual = hoje['date'].dt.strftime('%d-%m-%Y')[0]

        confirmados = hoje['confirmed'][0]
        mortes = hoje['deaths'][0]
        quantidade_estimada = (100 * mortes / taxa_mortalidade).astype(int)
        taxa = round(hoje['death_rate'][0] * 10000) / 100

        st.markdown(f"O estado de **{state}** teve até o dia **{dia_atual}** "
                    f"um total de **{confirmados}** casos confirmados e"
                    f" **{mortes}** mortes com uma taxa de mortalidade de **{taxa}%**.")
        if mortes > 0:
            st.markdown(f"Com base na taxa de mortalidade de outros países (**{taxa_mortalidade}%** dos infectados) "
                        f"a quantidade estimada de infectados seria de **{quantidade_estimada}** para a quantidade de mortos atual.")

        #st.line_chart(dados_estado_plot)

        data_state = get_map_state(state)
        data_cities = get_map_city(state)
        view = get_view(state)

        slide =  st.slider('Semana epidemiológica', 0, 255, 1 )

        dia_atual_mapa = dados_estado_cities[dados_estado_cities.is_last==True]

        st.write(  dia_atual_mapa)
        for feature in data_cities['features']:
            id_city = feature['id']
            dados =dia_atual_mapa[dia_atual_mapa.city_ibge_code == id_city].reset_index().T.rename(columns={0: 'dados'})
            feature['properties'] = dados.to_dict()

        # m = folium.Map(location=[45.5236, -122.6750])
        # html = m.get_root().render()
        # st.markdown(html.encode('utf8'),False)
        #st.write(data_cities)
        # Set the viewport location
        view_state = pdk.ViewState(
            longitude=view[1],
            latitude=view[0],
            zoom=6,
            min_zoom=1,
            max_zoom=60,
            pitch=50,#40.5,
            bearing=0)#-27.36

        geojson = pdk.Layer(
            'GeoJsonLayer',
            data_state,
            opacity=1,
            #stroked=False,
            filled=True,
            #extruded=True,
            #wireframe=True,
            get_fill_color=[255,  255, 255],
            get_line_color=[100, 100, 90],
            #pickable=True
        )

        geojson2 = pdk.Layer(
            'GeoJsonLayer',
            data_cities,
            opacity=0.8,
            stroked=False,
            filled=True,
            extruded=True,
            wireframe=True,
            get_elevation='properties.dados.deaths*1000',
            get_fill_color='[255/2, properties.dados.confirmed  , 255]',
            get_line_color=[0, slide, 255],
            pickable=True
        )
        max_val=1000
        min_val=0

        # Combined all of it and render a viewport
        r = pdk.Deck(layers=[geojson,geojson2],
                     tooltip={"html": f"<b>Color Value:</b> {state}", "style": {"color": "white"}},

                     initial_view_state=view_state,
                     height=800,
                     width=800,
                     map_style="mapbox://styles/mapbox/light-v9",
                     mapbox_key='pk.eyJ1IjoidGVvcmlhIiwiYSI6ImNqODRpNWJrNjA5dGIyd3FoMnZ6am13NjcifQ.OgxGf081lfoKQAOhlYh1Tg'
                     )
        st.pydeck_chart(r)

        dados_estado_melt = pd.melt(
            dados_estado[['date', 'confirmed', 'deaths']],
            id_vars=['date'],
            value_vars=['confirmed', 'deaths'])

        df = dados_estado_melt.groupby(["date", 'variable']).sum().reset_index()

        fig = px.line(df, x="date", y="value", color='variable')

        fig.update_layout(title=f'Casos de Covid em {state}',
                          xaxis_title='Data',
                          yaxis_title='Número de casos')
        st.plotly_chart(fig)
#
# """This app demonstrates the use of the awesome [deck.gl]() framework for visual
# exploratory data analysis of large datasets.
#
# Deck.gl is now (as of Streamlit v. 0.53) supported via the
# [`st.pydeck_chart`](https://docs.streamlit.io/api.html?highlight=pydeck#streamlit.pydeck_chart)
# function.
#
# We use data from the
# [Global Power Plant Database](http://datasets.wri.org/dataset/globalpowerplantdatabase) to
# illustrate the locations, fuel types and capacities of the worlds power plants.
# """
#
#
# import pathlib
#
# import pandas as pd
# import pydeck as pdk
# import streamlit as st
#
# POWER_PLANT_PATH = (
#     pathlib.Path.cwd() / "gallery/global_power_plant_database/global_power_plant_database.csv"
# )
#
# POWER_PLANT_URL = (
#     "https://raw.githubusercontent.com/MarcSkovMadsen/awesome-streamlit/master/"
#     "gallery/global_power_plant_database/global_power_plant_database.csv"
# )
#
# LATITUDE_COLUMN = "latitude"
# LONGITUDE_COLUMN = "longitude"
#
# LOCATIONS = {
#     "Orsted Copenhagen HQ": {"latitude": 55.676098, "longitude": 12.568337},
#     "Orsted Boston": {"latitude": 2.361145, "longitude": -71.057083},
# }
# ORSTED_CPH_HQ = LOCATIONS["Orsted Copenhagen HQ"]
#
# FUEL_COLORS = {
#     "Oil": "black",
#     "Solar": "green",
#     "Gas": "black",
#     "Other": "gray",
#     "Hydro": "blue",
#     "Coal": "black",
#     "Petcoke": "black",
#     "Biomass": "green",
#     "Waste": "green",
#     "Cogeneration": "gray",
#     "Storage": "orange",
#     "Wind": "green",
# }
#
# COLORS_R = {"black": 0, "green": 0, "blue": 0, "orange": 255, "gray": 128}
#
# COLORS_G = {"black": 0, "green": 128, "blue": 0, "orange": 165, "gray": 128}
#
# COLORS_B = {"black": 0, "green": 0, "blue": 255, "orange": 0, "gray": 128}
#
#
# class ViewStateComponent:
#     """Component to let the user set the initial view state to for example Copenhagen or Boston"""
#
#     def __init__(self):
#         self.latitude = ORSTED_CPH_HQ["latitude"]
#         self.longitude = ORSTED_CPH_HQ["longitude"]
#         self.zoom = 1
#         self.pitch = 40.0
#
#     def edit_view(self):
#         """Lets the user edit the attributes"""
#         location = st.sidebar.selectbox("Location", options=list(LOCATIONS.keys()), index=0)
#         self.latitude = LOCATIONS[location]["latitude"]
#         self.longitude = LOCATIONS[location]["longitude"]
#
#         self.zoom = st.sidebar.slider("Zoom", min_value=0, max_value=20, value=self.zoom)
#         self.pitch = st.sidebar.slider(
#             "Pitch", min_value=0.0, max_value=100.0, value=self.pitch, step=10.0
#         )
#
#     @property
#     def view_state(self) -> pdk.ViewState:
#         """The ViewState according to the attributes
#
#         Returns:
#             pdk.ViewState -- [description]
#         """
#         return pdk.ViewState(
#             longitude=self.longitude,
#             latitude=self.latitude,
#             zoom=self.zoom,
#             min_zoom=0,
#             max_zoom=15,
#             pitch=self.pitch,
#             # bearing=-27.36,
#         )
#
#
# class GlobalPowerPlantDatabaseApp:
#     """The main app showing the Global Power Plant Database"""
#
#     def __init__(self):
#         self.view_state_component = ViewStateComponent()
#         self.data = self.get_data()
#         self.show_data = False
#
#     @staticmethod
#     @st.cache
#     def get_data() -> pd.DataFrame:
#         """The Global Power Plant data
#
#         Returns:
#             pd.DataFrame -- The Global Power Plant data cleaned and transformed
#         """
#         try:
#             data = pd.read_csv(POWER_PLANT_PATH)
#         except FileNotFoundError:
#             data = pd.read_csv(POWER_PLANT_URL)
#
#         # Clean
#         data.primary_fuel = data.primary_fuel.fillna("NA")
#         data.capacity_mw = data.capacity_mw.fillna(1)
#
#         # Transform
#         data["primary_fuel_color"] = data.primary_fuel.map(FUEL_COLORS)
#         data["primary_fuel_color"] = data["primary_fuel_color"].fillna("gray")
#         data["color_r"] = data["primary_fuel_color"].map(COLORS_R)
#         data["color_g"] = data["primary_fuel_color"].map(COLORS_G)
#         data["color_b"] = data["primary_fuel_color"].map(COLORS_B)
#         data["color_a"] = 140
#
#         return data[
#             [
#                 "capacity_mw",
#                 LATITUDE_COLUMN,
#                 LONGITUDE_COLUMN,
#                 "primary_fuel_color",
#                 "color_r",
#                 "color_g",
#                 "color_b",
#                 "color_a",
#             ]
#         ]
#
#     def _scatter_plotter_layer(self):
#         return pdk.Layer(
#             "ScatterplotLayer",
#             data=self.data,
#             get_position=[LONGITUDE_COLUMN, LATITUDE_COLUMN],
#             get_fill_color="[color_r, color_g, color_b, color_a]",
#             get_radius="capacity_mw*10",
#             pickable=True,
#             opacity=0.8,
#             stroked=False,
#             filled=True,
#             wireframe=True,
#         )
#
#     def _deck(self):
#         return pdk.Deck(
#             map_style="mapbox://styles/mapbox/light-v9",
#             initial_view_state=self.view_state_component.view_state,
#             layers=[self._scatter_plotter_layer()],
#             tooltip={"html": "<b>Color Value:</b> {primary_fuel}", "style": {"color": "white"}},
#         )
#
#     def view(self):
#         """Main view of the app"""
#         # self.view_state_component.edit_view() # Does not work
#         st.write(__doc__)
#
#         st.pydeck_chart(self._deck())
#
#         st.write(
#             """The maps shows the power plant
#
# - **location** by latitude, longitude coordinates
# - **fuel type** by color and
# - **capacity in MW** by bubble size
# """
#         )
#         st.json(FUEL_COLORS)
#
#         st.write(
#             """Unfortunately **tooltips are not supported**. And there are also other issues.
# See
#
# - [Issue 984](https://github.com/streamlit/streamlit/issues/984)
# - [Issue 985](https://github.com/streamlit/streamlit/issues/985)"""
#         )
#
#
# APP = GlobalPowerPlantDatabaseApp()
# APP.view()
Exemplo n.º 30
0
    sns.barplot(x='y/m', y='price', data=df)
    st.write(fig)

df.date = pd.to_datetime(df.date)
ano_selecionado = st.sidebar.slider("Selecione um ano", 2014, 2015)
df_selected = df[df.date.dt.year == ano_selecionado]

st.subheader('Mapa da cidade de Seattle')
# st.map(df)

st.pydeck_chart(pdk.Deck(
    initial_view_state=pdk.ViewState(
        latitude=47.608013,
        longitude=-122.335167,
        zoom=7.5,
        min_zoom=3,
        max_zoom=15,
        pitch=40.5,
        bearing=-27.36
    ),
    layers=[
        pdk.Layer(
            'HexagonLayer',
            data=df_selected[['lat', 'lon']],  # df
            get_position='[lon,lat]',
            radius=150,
            auto_highlight=True,
            elevation_scale=25,
            pickable=False,  # Interfere na manipulação do mapa.
            elevation_range=[0, 3000],
            extruded=True,