def plot_connection_histogram(self, gid, conn_type): self.load_connection_list(conn_type) targets = utils.get_targets(self.connection_lists[conn_type], gid) tgt_ids, tgt_weights, tgt_delays = targets[:, 1], targets[:, 2], targets[:, 3] sources = utils.get_sources(self.connection_lists[conn_type], gid) src_ids, src_weights, src_delays = sources[:, 1], sources[:, 2], sources[:, 3] fig = pylab.figure(figsize=(14, 10)) # ax1 = fig.add_subplot(1, 1, 1) # set blank? the set title pylab.subplots_adjust(hspace=.35, wspace=.25) ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 2) ax3 = fig.add_subplot(2, 2, 3) ax4 = fig.add_subplot(2, 2, 4) ax1.set_title('$\sigma^w_{X} = %.2f \sigma^w_{V}=%.2f$' % (self.params['w_sigma_x'], self.params['w_sigma_v'])) tgt_weights_sorted = tgt_weights.copy() tgt_weights_sorted.sort() ax1.bar(range(len(tgt_ids)), tgt_weights_sorted, width=1) ax1.set_ylabel('Outgoing weights [uS]') ax1.set_xlabel('sorted targets') ax1.set_xlim((0, len(tgt_ids))) n_weight_bins = 20 count, bins = np.histogram(tgt_weights, bins=n_weight_bins) ax2.bar(bins[:-1], count, width=bins[1] - bins[0]) ax2.set_xlabel('Outgoing weight [uS]') ax2.set_ylabel('#') src_weights_sorted = src_weights.copy() src_weights_sorted.sort() ax3.bar(range(len(src_ids)), src_weights_sorted, width=1) ax3.set_ylabel('Incoming weights [uS]') ax3.set_xlabel('sorted sources') ax3.set_xlim((0, len(src_ids))) n_weight_bins = 20 count, bins = np.histogram(src_weights, bins=n_weight_bins) ax4.bar(bins[:-1], count, width=bins[1] - bins[0]) ax4.set_xlabel('Incoming weight [uS]') ax4.set_ylabel('#') output_fn = self.params['figures_folder'] + 'connection_histogram_wsigmaxv_%.2f_%.2f_%d.png' % (self.params['w_sigma_x'], self.params['w_sigma_v'], gid) print 'Saving fig to:', output_fn pylab.savefig(output_fn, dpi=200)
}, "tests/Analyser_Osmosis_Soundex-france_alsace-2014-06-17.xml.bz2" ) self.check_num_marker(50) def test_two_sources(self): self.check_num_marker(0) update( {"id": 1}, "tests/Analyser_Osmosis_Soundex-france_alsace-2014-06-17.xml.bz2") self.check_num_marker(50) update({ "id": 2 }, "tests/Analyser_Osmosis_Broken_Highway_Level_Continuity-france_reunion-2014-06-11.xml.bz2" ) self.check_num_marker(50 + 99) ########################################################################### if __name__ == "__main__": sources = utils.get_sources() if len(sys.argv) == 1: for k in sorted([int(x) for x in sources.keys()]): source = sources[str(k)] print_source(source) elif sys.argv[1] == "--help": show(u"usage: update.py <source number> <url>") else: update(utils.get_sources()[sys.argv[1]], sys.argv[2])
def main(): session_state = session.SessionState.get( update=False, number_beds=None, number_ventilators=None, deaths=None, cases=None, state="Acre", city="Todos", refresh=False, ) utils.localCSS("style.css") utils.genHeroSection( "Farol", "Entenda e controle a Covid-19 em sua cidade e estado." ) # GET DATA config = yaml.load(open("configs/config.yaml", "r"), Loader=yaml.FullLoader) df_cities, df_states = get_data(config) # REGION/CITY USER INPUT user_input = dict() user_input["state_name"] = st.selectbox( "Estado", df_cities["state_name"].sort_values().unique() ) user_input["city_name"] = st.selectbox( "Município", utils.add_all( df_cities[df_cities["state_name"] == user_input["state_name"]][ "city_name" ].unique() ), ) user_input, data = filter_options(user_input, df_cities, df_states, config) # SOURCES PARAMS user_input = utils.get_sources(user_input, data, df_cities, ["beds", "ventilators"]) print(user_input["number_ventilators"], user_input["number_beds"]) # POPULATION PARAMS user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": int(data["active_cases"].fillna(0).values[0]), "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), } user_input["last_updated_cases"] = data["last_updated_subnotification"].max() if data["confirmed_cases"].sum() == 0: st.write( f"""<div class="base-wrapper"> Seu município ou regional de saúde ainda não possui casos reportados oficialmente. Portanto, simulamos como se o primeiro caso ocorresse hoje. <br><br>Caso queria, você pode mudar esse número abaixo: </div>""", unsafe_allow_html=True, ) user_input["population_params"]["I"] = 1 else: infectious_period = ( config["br"]["seir_parameters"]["severe_duration"] + config["br"]["seir_parameters"]["critical_duration"] ) st.write( f"""<div class="base-wrapper"> O número de casos confirmados oficialmente no seu município ou estado é de {int(data['confirmed_cases'].sum())} em {pd.to_datetime(data["data_last_refreshed"].values[0]).strftime("%d/%m/%Y")}. Dada a progressão clínica da doença (em média, {infectious_period} dias) e a taxa de notificação ajustada para o município ou estado de ({int(100*data['notification_rate'].values[0])}%), <b>estimamos que o número de casos ativos é de {int(data['active_cases'].sum())}</b>.<br> <br>Caso queria, você pode mudar esse número para a simulação abaixo: </div>""", unsafe_allow_html=True, ) # INDICATORS CARDS indicators = IndicatorCards indicators = update_indicators(indicators, data, config, user_input, session_state) utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, ) # SPACE AFTER CARDS st.write("<div class='base-wrapper product-section'></div>", unsafe_allow_html=True) st.write( """ <div class='base-wrapper'> <i>* Utilizamos 50% da capacidade hospitalar reportada por %s em %s (leitos) e %s em %s (ventiladores) para o cálculo da projeção de dias para atingir a capacidade máxima. Caso tenha dados mais atuais, sugerimos que mude os valores e refaça essa estimação abaixo.</i> </div> """ % ( user_input["author_number_beds"], user_input["last_updated_number_beds"], user_input["author_number_ventilators"], user_input["last_updated_number_ventilators"], ), unsafe_allow_html=True, ) if st.button("Confira a evolução de indicadores-chave"): if st.button("Esconder"): pass st.write( f""" <div class="base-wrapper"> <span class="section-header primary-span">TAXA DE ISOLAMENTO SOCIAL EM {user_input["locality"]}</span> <br><br> Percentual de smartphones que não deixou o local de residência, em cada dia, calculado pela inloco. Para mais informações, <a target="_blank" style="color:#3E758A;" href="https://mapabrasileirodacovid.inloco.com.br/pt/">veja aqui</a>. </div> """, unsafe_allow_html=True, ) if user_input["city_id"]: locality_id = user_input["city_id"] else: df_state_mapping = pd.read_csv("./configs/states_table.csv") locality_id = df_state_mapping.loc[ df_state_mapping["state_name"] == data["state_name"].values[0] ].iloc[0]["state_num_id"] try: fig = plts.gen_social_dist_plots_placeid(locality_id) st.plotly_chart(fig, use_container_width=True) except: st.write("Seu município ou estado não possui mais de 30 dias de dado.") st.write( f""" <div class="base-wrapper"> <span class="section-header primary-span">CÁLCULO DO RITMO DE CONTÁGIO EM {user_input["locality"]}</span> <br><br> O ritmo de contágio, conhecido como número de reprodução efetivo (Rt), traduz a dinâmica de disseminação do Covid a cada dia. <br>O valor pode ser lido como o número médio de novas infecções diárias causadas por uma única pessoa infectada. Para mais informações, visite a página de Metodologia. </div> """, unsafe_allow_html=True, ) try: fig2 = plts.plot_rt_wrapper(locality_id) st.plotly_chart(fig2, use_container_width=True) except: st.write("Seu município ou estado não possui mais de 30 dias de dado.") st.write( "<div class='base-wrapper'><i>Em breve:</i> gráficos de subnotificação.</div>", unsafe_allow_html=True, ) # CHANGE DATA SECTION utils.genInputCustomizationSectionHeader(user_input["locality"]) user_input, session_state = utils.genInputFields(user_input, config, session_state) if session_state.update: session_state.refresh = True session_state.update = False session.rerun() # AMBASSADOR SECTION utils.genAmbassadorSection() indicators["hospital_capacity"].left_display = user_input["number_beds"] indicators["hospital_capacity"].right_display = user_input["number_ventilators"] indicators["subnotification_rate"].left_display = user_input["population_params"][ "D" ] # TOOLS products = ProductCards products[1].recommendation = f'Risco {data["overall_alert"].values[0]}' utils.genProductsSection(products) product = st.selectbox( "", [ "Como você gostaria de prosseguir?", "SimulaCovid", "Saúde em Ordem (em breve)", ], ) if product == "SimulaCovid": sm.main(user_input, indicators, data, config, session_state) elif product == "Saúde em Ordem (em breve)": pass st.write( """ <div class="base-wrapper"> Estamos à disposição para apoiar o gestor público a aprofundar a análise para seu estado ou município, de forma inteiramente gratuita. <a target="_blank" style="color:#3E758A;" href="https://coronacidades.org/fale-conosco/"><b>Entre em contato conosco</a> </div> """, unsafe_allow_html=True, )
def main(session_state): # GOOGLE ANALYTICS SETUP if os.getenv("IS_DEV") == "FALSE": utils.setup_google_analytics() # Amplitude: Get user info user_analytics = amplitude.gen_user(utils.get_server_session()) opening_response = user_analytics.safe_log_event("opened farol", session_state, is_new_page=True) config = yaml.load(open("configs/config.yaml", "r"), Loader=yaml.FullLoader) utils.localCSS("style.css") st.write( """<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MKWTV7X" height="0" width="0" style="display:none;visibility:hidden"></iframe>""", unsafe_allow_html=True, ) utils.genHeroSection( title1="Farol", title2="Covid", subtitle="Entenda e controle a Covid-19 em sua cidade e estado.", logo="https://i.imgur.com/CkYDPR7.png", header=True, explain=True) # TEMPORARY BANNER FC escolasegura_logo = utils.load_image("imgs/escolasegura_favicon.png") st.write( f"""<div> <div class="base-wrapper flex flex-column" style="background-color:#0090A7"> <div class="white-span header p1" style="font-size:30px;"><img class="icon-cards" src="data:image/png;base64,{escolasegura_logo}" alt="Fonte: Impulso"> COMO PLANEJAR UMA REABERTURA SEGURA?</div> <span class="white-span">Veja guias e protocolos para facilitar uma reabertura planejada da rede pública de ensino, respeitando boas práticas de distanciamento e segurança sanitária para controle da Covid-19. <br><b>Acesse o Escola Segura: <a target="_blank" style="color:#FFFFFF;" href="http://escolasegura.coronacidades.org">http://escolasegura.coronacidades.org</a></b></span> </div>""", unsafe_allow_html=True, ) st.write( """ <div class="base-wrapper primary-span"> <span class="section-header">Selecione seu estado ou município no mapa abaixo:</span> </div>""", unsafe_allow_html=True, ) # GET DATA dfs, cnes_sources = get_data(config) # REGION/CITY USER INPUT user_input = dict() user_input["state_name"] = st.selectbox("Estado", utils.filter_place(dfs, "state")) user_input["health_region_name"] = st.selectbox( "Região de Saúde", utils.filter_place(dfs, "health_region", state_name=user_input["state_name"]), ) user_input["city_name"] = st.selectbox( "Município", utils.filter_place( dfs, "city", state_name=user_input["state_name"], health_region_name=user_input["health_region_name"], ), ) changed_city = user_analytics.safe_log_event( "picked farol place", session_state, event_args={ "state": user_input["state_name"], "city": user_input["city_name"] }, ) user_input, data = update_user_input_places(user_input, dfs, config) # GENERATE MAPS map_place_id = utils.Dictionary().get_state_alphabetical_id_by_name( user_input["state_name"]) if os.getenv("IS_LOCAL").upper() == "TRUE": map_url = config["br"]["api"]["mapserver_local"] else: map_url = config["br"]["api"]["mapserver_external"] st.write( f""" <div class="brazil-map-div"> <div class="alert-levels-map-overlay"> </div> <div> <iframe id="map" src="resources/iframe-gen.html?url={map_url}maps/map-iframe?place_id=BR" class="map-br" scrolling="no"> </iframe> </div> </div> """, unsafe_allow_html=True, ) st.write( f""" <iframe id="map-state" src="resources/iframe-gen.html?url={map_url}maps/map-iframe?place_id={map_place_id}" class="map-state" scrolling="no"> </iframe> """, unsafe_allow_html=True, ) st.write( f""" <div class="selectors-box" id="selectors-box"> </div> <iframe src="resources/select-box-mover.html?place_id={user_input["state_name"]}{user_input["health_region_name"]}{user_input["city_name"]}" height="0px"> </iframe>""", unsafe_allow_html=True, ) # SOURCES PARAMS user_input = utils.get_sources(user_input, data, cnes_sources, ["beds", "icu_beds"]) # POPULATION PARAMS try: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": int(data["active_cases"].fillna(0).values[0]), "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } except: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": 0, "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } user_input["Rt"] = { "best": data["rt_low_95"].values[0], "worst": data["rt_high_95"].values[0], "is_valid": data["rt_most_likely"].apply(str).values[0], } user_input["last_updated_cases"] = data[ "last_updated_subnotification"].max() # Update session values to standard ones if changed city or opened page or reseted values if (session_state.state_name != user_input["state_name"] or session_state.health_region_name != user_input["health_region_name"] or session_state.city_name != user_input["city_name"] or session_state.number_beds is None or session_state.reset): session_state.state_name = user_input["state_name"] session_state.health_region_name = user_input["health_region_name"] session_state.city_name = user_input["city_name"] session_state.state_num_id = user_input["state_num_id"] session_state.health_region_id = user_input["health_region_id"] session_state.city_id = user_input["city_id"] session_state.number_beds = int( user_input["number_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_icu_beds = int( user_input["number_icu_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_cases = user_input["population_params"][ "I_confirmed"] session_state.number_deaths = user_input["population_params"]["D"] session_state.reset = True if data["confirmed_cases"].sum() == 0: st.write( f"""<div class="base-wrapper"> Seu município ou Região de Saúde ainda não possui casos reportados oficialmente. Portanto, simulamos como se o primeiro caso ocorresse hoje. <br><br>Caso queria, você pode mudar esse número abaixo: </div>""", unsafe_allow_html=True, ) user_input["population_params"]["I"] = 1 else: infectious_period = ( config["br"]["seir_parameters"]["severe_duration"] + config["br"]["seir_parameters"]["critical_duration"]) placeholder_value_pls_solve_this = 0 # TEMPORARY BANNER - TODO: remove after done if user_input["state_name"] in ["Mato Grosso", "Espírito Santo"]: st.write(""" <div> <div class="base-wrapper flex flex-column" style="background-color:#0090A7"> <div class="white-span header p1" style="font-size:30px;">⚠️ ATENÇÃO: Os municípios e regionais de saúde de MT e ES estão desatualizados</div> <span class="white-span">Utilizamos dados abertos das secretarias estaduais para os cálculos dos indicadores. Esses dados são capturados diariamente por voluntários do Brasil.io, que vêm enfrenteando problemas na atualização dos dados desses estados. Estamos resolvendo a situação e iremos retornar com os indicadores o mais breve possível.</b></span> </div> <div>""", unsafe_allow_html=True) # DIMENSIONS CARDS dimensions = DimensionCards utils.genAnalysisDimmensionsSection(dimensions) # INDICATORS CARDS indicators = IndicatorCards indicators = update_indicators(indicators, data, config, user_input, session_state) data["overall_alert"] = data["overall_alert"].map( config["br"]["farolcovid"]["categories"]) if "state" in user_input["place_type"]: # Add disclaimer to cities in state alert levels total_alert_regions = (dfs["health_region"][ dfs["health_region"]["state_num_id"] == data["state_num_id"]. unique()[0]].assign(overall_alert=lambda df: df["overall_alert"]. map(config["br"]["farolcovid"]["categories"])) ["overall_alert"].value_counts()) utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, n_colapse_regions=total_alert_regions[ total_alert_regions.index.isin(["altíssimo", "alto"])].sum(), ) elif "city" in user_input["place_type"]: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, rt_type=data["rt_place_type"].values[0], ) else: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, ) # AVAILABLE CAPACITY DISCLAIMER st.write( """ <div class='base-wrapper'> <i>* Utilizamos %s% do total de leitos UTI reportados por %s em %s para cálculo da projeção de dias para atingir capacidade máxima.<br><b>Para municípios, utilizamos os recursos da respectiva regional de saúde.</b> Leitos enfermaria contém os tipos: cirúrgicos, clínicos e hospital-dia; sendo considerado %s% já ocupado.</i> </div> """ % ( str( int(config["br"]["simulacovid"] ["resources_available_proportion"] * 100)), user_input["author_number_beds"], user_input["last_updated_number_beds"], str( int(config["br"]["simulacovid"] ["resources_available_proportion"] * 100)), ), unsafe_allow_html=True, ) # TODO: remove comment on this later! # utils.gen_pdf_report() # INDICATORS PLOTS if st.button("Confira a evolução de indicadores-chave"): opening_response = user_analytics.log_event("picked key_indicators", dict()) if st.button("Esconder"): pass st.write( f""" <div class="base-wrapper"> <span class="section-header primary-span">CÁLCULO DA TAXA DE CONTÁGIO EM {user_input["locality"]}</span> <br><br> <b>A taxa de contágio, conhecida como número de reprodução efetivo (Rt), traduz a dinâmica de disseminação da Covid-19 a cada dia.</b> <br>O valor pode ser lido como o número médio de novas infecções diárias causadas por uma única pessoa infectada. Para mais informações, visite a página de Modelos no menu lateral. </div> """, unsafe_allow_html=True, ) try: fig2 = plots.plot_rt_wrapper(user_input[user_input["place_type"]], user_input["place_type"], config) st.plotly_chart(fig2, use_container_width=True) except: st.write( """<div class="base-wrapper"><b>Seu município, regional ou estado não possui mais de 30 dias de dados de casos confirmados.</b>""", unsafe_allow_html=True, ) st.write( "<div class='base-wrapper'><i>Em breve:</i> gráficos de subnotificação e média móvel (últimos 7 dias) de novos casos por 100k habitantes.</div>", unsafe_allow_html=True, ) utils.stylizeButton( name="Confira a evolução de indicadores-chave", style_string= """border: 1px solid var(--main-white);box-sizing: border-box;border-radius: 15px; width: auto;padding: 0.5em;text-transform: uppercase;font-family: var(--main-header-font-family);color: var(--main-white);background-color: var(--main-primary);font-weight: bold;text-align: center;text-decoration: none;font-size: 18px;animation-name: fadein;animation-duration: 3s;margin-top: 1em;""", session_state=session_state, ) # AMBASSADOR SECTION utils.gen_ambassador_section() # PDF-REPORT GEN BUTTON # if st.button("Gerar Relatório PDF"): # user_analytics.log_event("generated pdf") # st.write( # """<div class="base-wrapper">Aguarde um momento por favor...</div>""", # unsafe_allow_html=True, # ) # st.markdown( # pdfgen.gen_pdf_report(user_input, indicators, data, config), # unsafe_allow_html=True, # ) # TOOLS products = ProductCards utils.genProductsSection(products) # SELECTION BUTTONS # TODO: limpar esse código! está 100% repetido!!! if session_state.continuation_selection is None: session_state.continuation_selection = [False, False, False, False] simula_button_name = "Clique Aqui" # Simula covid 0space saude_button_name = "Clique Aqui " # Saude em ordem 1space distancia_button_name = "Clique_Aqui" # Distanciamento social onda_button_name = "Clique_Aqui " # onda covid if st.button(simula_button_name): # SIMULA session_state.continuation_selection = [True, False, False, False] if st.button(distancia_button_name): # DISTANCIAMENTO session_state.continuation_selection = [False, True, False, False] if st.button(saude_button_name): # SAUDE session_state.continuation_selection = [False, False, True, False] if st.button(onda_button_name): # ONDA session_state.continuation_selection = [False, False, False, True] utils.stylizeButton( name=simula_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 1}, ) utils.stylizeButton( name=distancia_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 2}, ) utils.stylizeButton( name=saude_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 3}, ) utils.stylizeButton( name=onda_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 4}, ) if session_state.continuation_selection[0]: user_analytics.safe_log_event( "picked simulacovid", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) # Downloading the saved data from memory sm.main(user_input, indicators, data, config, session_state) # TODO: remove comment on this later! # utils.gen_pdf_report() elif session_state.continuation_selection[1]: user_analytics.safe_log_event( "picked distanciamento", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) ds.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[2]: user_analytics.safe_log_event( "picked saude_em_ordem", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) so.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[3]: user_analytics.safe_log_event( "picked onda", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) oc.main(user_input, indicators, data, config, session_state) # BIG TABLE gen_big_table(config, dfs, user_input["state_name"]) # FOOTER utils.gen_whatsapp_button(config["impulso"]["contact"]) utils.gen_footer() user_analytics.conclude_user_session(session_state)
def show(source): print "source #%s" % source["id"] for k in source: if k == "id": continue if type(source[k]) == list: for e in source[k]: print " %-10s = %s" % (k, e) else: print " %-10s = %s" % (k, source[k]) ########################################################################### if __name__ == "__main__": sources = utils.get_sources() if len(sys.argv) > 1: try: num = int(sys.argv[1]) except ValueError: for k in sorted([int(x) for x in sources.keys()]): source = sources[str(k)] if source["comment"].startswith("stats-"): print source show(source) sys.exit(1) else: sources = {sys.argv[1]: sources[sys.argv[1]]}
def test_duplicate_update(self): self.check_num_marker(0) update({"id": 1}, "tests/Analyser_Osmosis_Soundex-france_alsace-2014-06-17.xml.bz2") self.check_num_marker(50) with self.assertRaises(OsmoseUpdateAlreadyDone) as cm: update({"id": 1}, "tests/Analyser_Osmosis_Soundex-france_alsace-2014-06-17.xml.bz2") self.check_num_marker(50) def test_two_sources(self): self.check_num_marker(0) update({"id": 1}, "tests/Analyser_Osmosis_Soundex-france_alsace-2014-06-17.xml.bz2") self.check_num_marker(50) update({"id": 2}, "tests/Analyser_Osmosis_Broken_Highway_Level_Continuity-france_reunion-2014-06-11.xml.bz2") self.check_num_marker(50 + 99) ########################################################################### if __name__ == "__main__": sources = utils.get_sources() if len(sys.argv) == 1: for k in sorted([int(x) for x in sources.keys()]): source = sources[str(k)] print_source(source) elif sys.argv[1] == "--help": show(u"usage: update.py <source number> <url>") else: update(utils.get_sources()[sys.argv[1]], sys.argv[2])
def show(source): print "source #%s"%source["id"] for k in source: if k == "id": continue if type(source[k])== list: for e in source[k]: print " %-10s = %s"%(k, e) else: print " %-10s = %s"%(k, source[k]) ########################################################################### if __name__ == "__main__": sources = utils.get_sources() if len(sys.argv) > 1: try: num = int(sys.argv[1]) except ValueError: for k in sorted([int(x) for x in sources.keys()]): source = sources[str(k)] if source["comment"].startswith("stats-"): print source show(source) sys.exit(1) else: sources = {sys.argv[1]: sources[sys.argv[1]]}
def plot_connection_type(self, src_gid, conn_type, marker, color, outgoing_conns=True, with_directions=False, plot_delays=False, annotate=False, with_histogram=False): self.load_connection_list(conn_type) if outgoing_conns: src_tgts = utils.get_targets(self.connection_lists[conn_type], src_gid) tgt_ids, weights, delays = src_tgts[:, 1], src_tgts[:, 2], src_tgts[:, 3] print 'Cell %d connects to:' % src_gid, tgt_ids else: src_tgts = utils.get_sources(self.connection_lists[conn_type], src_gid) tgt_ids, weights, delays = src_tgts[:, 0], src_tgts[:, 2], src_tgts[:, 3] print 'Cell %d receives input from:' % src_gid, tgt_ids if conn_type == 'ee': src_tp = self.tp_exc tgt_tp = self.tp_exc legend_txt = 'exc src gid: %d --> exc tgts, n=%d' % (src_gid, len(tgt_ids)) elif conn_type == 'ei': src_tp = self.tp_exc tgt_tp = self.tp_inh legend_txt = 'exc src gid: %d --> inh tgts, n=%d' % (src_gid, len(tgt_ids)) elif conn_type == 'ie': src_tp = self.tp_inh tgt_tp = self.tp_exc legend_txt = 'inh src gid: %d --> exc tgts, n=%d' % (src_gid, len(tgt_ids)) elif conn_type == 'ii': src_tp = self.tp_inh tgt_tp = self.tp_inh legend_txt = 'inh src gid: %d --> inh tgts, n=%d' % (src_gid, len(tgt_ids)) if len(tgt_ids) > 0: plot = self.plot_connections(tgt_ids, tgt_tp, weights, marker, color, with_directions, annotate, outgoing_conns) if outgoing_conns: print 'Average weight for outgoing connections: %.2e +- %.2e ' % (weights.mean(), weights.std()) if outgoing_conns: print 'Average weight for outgoing connections: %.2e +- %.2e ' % (weights.mean(), weights.std()) else: return [] if plot_delays: delay_min, delay_max = delays.min(), delays.max() # delay_min, delay_max = self.params['delay_range'][0], self.params['delay_range'][1] norm = matplotlib.mpl.colors.Normalize(vmin=delay_min, vmax=delay_max) m = matplotlib.cm.ScalarMappable(norm=norm, cmap=cm.jet)#spring) m.set_array(np.arange(delay_min, delay_max, 0.01)) if not self.delay_colorbar_set: cb = self.fig.colorbar(m) cb.set_label('Connection delays [ms]', fontsize=28) self.delay_colorbar_set = True x_src, y_src = src_tp[src_gid, 0], src_tp[src_gid, 1] for i_, tgt_gid in enumerate(tgt_ids): x_tgt, y_tgt = tgt_tp[tgt_gid, 0] % self.params['torus_width'], tgt_tp[tgt_gid, 1] % self.params['torus_height'] c = m.to_rgba(delays[i_]) self.ax.plot((x_src, x_tgt), (y_src, y_tgt), c=c, lw=2, alpha=.5) # s = 1. # saturation # for # if activity[frame, tgt_gid] < 0: # l = 1. - 0.5 * activity[frame, tgt_gid] / activity_min # h = 0. # else: # l = 1. - 0.5 * activity[frame, tgt_gid] / activity_max # h = 240. # assert (0 <= h and h < 360) # assert (0 <= l and l <= 1) # assert (0 <= s and s <= 1) # (r, g, b) = utils.convert_hsl_to_rgb(h, s, l) # colors[frame, tgt_gid, :] = [r, g, b] # if with_histogram: print '\nPlotting weight and delay histogram' self.plot_weight_and_delay_histogram(weights, delays) self.legends.append((plot[0], legend_txt)) print 'src_gid %d has %d outgoing %s->%s connection' % (src_gid, len(weights), conn_type[0].capitalize(), conn_type[1].capitalize()) return tgt_ids
def main(session_state): # GOOGLE ANALYTICS SETUP if os.getenv("IS_DEV") == "FALSE": utils.setup_google_analytics() # Amplitude: Get user info user_analytics = amplitude.gen_user(utils.get_server_session()) opening_response = user_analytics.safe_log_event("opened farol", session_state, is_new_page=True) config = yaml.load(open("configs/config.yaml", "r"), Loader=yaml.FullLoader) utils.localCSS("style.css") st.write( """<iframe src="https://www.googletagmanager.com/ns.html?id=GTM-MKWTV7X" height="0" width="0" style="display:none;visibility:hidden"></iframe>""", unsafe_allow_html=True, ) utils.genHeroSection( title1="Farol", title2="Covid", subtitle="Entenda e controle a Covid-19 em sua cidade e estado.", logo="https://i.imgur.com/CkYDPR7.png", header=True, explain=True) if os.getenv("IS_HEROKU") == "TRUE": urlpath = os.getenv("urlpath") elif os.getenv("IS_DEV") == "TRUE": urlpath = 'http://localhost:8501/' else: urlpath = 'https://farolcovid.coronacidades.org/' # urlpath = 'http://localhost:8501/' vaccine_logo = utils.load_image("imgs/vaccine.png") st.write( f"""<div> <div class="base-wrapper flex flex-column" style="background-color:#0090A7"> <div class="white-span header p1" style="font-size:30px;"><img class="icon-cards" src="data:image/png;base64,{vaccine_logo}" alt="Fonte: Impulso">QUER SABER MAIS SOBRE A VACINAÇÃO?</div> <span class="white-span">Acompanhe nossos novos dados e descobra como avança a vacinação no seu município ou estado!<br><br> <a class="btn-ambassador" href="{urlpath}?page=4" target="_self"> Veja aqui! </a> <br><br><span class="white-span">Saiba quando podemos controlar a pandemia no Brasil no nosso estudo realizado com dados inéditos obtidos pela Lei de Acesso à Informação.<br><br> <a class="btn-ambassador" href="{urlpath}?page=3" target="_self"> Ler aqui! </a> </div>""", unsafe_allow_html=True, ) st.write( """ <div class="base-wrapper primary-span"> <span class="section-header">Selecione seu estado ou município no mapa abaixo:</span> </div>""", unsafe_allow_html=True, ) # PEGA BASE DA API # GET DATA dfs, cnes_sources = get_data(config) map_url = "https://helper.coronacidades.org/" col1, col2 = st.beta_columns([0.6, 0.35]) with col2: # REGIAO/CIDADE SELECAO USUARIO # REGION/CITY USER INPUT user_input = dict() user_input["state_name"] = st.selectbox( "Estado", utils.filter_place(dfs, "state")) user_input["health_region_name"] = st.selectbox( "Região de Saúde", utils.filter_place(dfs, "health_region", state_name=user_input["state_name"]), ) user_input["city_name"] = st.selectbox( "Município", utils.filter_place( dfs, "city", state_name=user_input["state_name"], health_region_name=user_input["health_region_name"], ), ) changed_city = user_analytics.safe_log_event( "picked farol place", session_state, event_args={ "state": user_input["state_name"], "city": user_input["city_name"] }, ) user_input, data = update_user_input_places(user_input, dfs, config) map_place_id = utils.Dictionary().get_state_alphabetical_id_by_name( user_input["state_name"]) st.write( f""" <div class="brazil-map-div"> <br><br> <iframe id="map-state" src="{map_url}maps/map-iframe?place_id={map_place_id}" class="map-state" scrolling="no"> </iframe> </div> """, unsafe_allow_html=True, ) with col1: # GENERATE MAPS # st.write( # f""" # <div class="brazil-map-div"> # <div class="alert-levels-map-overlay"> # </div> # <div> # <iframe id="map" src="resources/iframe-gen.html?url={map_url}maps/map-iframe?place_id=BR" class="map-br" scrolling="no"> # </iframe> # </div> # </div> # """, # unsafe_allow_html=True, # ) st.write( f""" <div class="brazil-map-div"> <iframe id="map" src="{map_url}maps/map-iframe?place_id=BR" class="map-br" scrolling="no"> </iframe> </div> """, unsafe_allow_html=True, ) # st.write( # f""" # """, # unsafe_allow_html=True, # ) # st.write( # f""" # <iframe id="map-state" src="resources/iframe-gen.html?url={map_url}maps/map-iframe?place_id={map_place_id}" class="map-state" scrolling="no"> # </iframe> # """, # unsafe_allow_html=True, # ) # st.write( # f""" # <div class="selectors-box" id="selectors-box"> # </div> # <iframe src="resources/select-box-mover.html?place_id={user_input["state_name"]}{user_input["health_region_name"]}{user_input["city_name"]}" height="0px"> # </iframe>""", # unsafe_allow_html=True, # ) # SOURCES PARAMS user_input = utils.get_sources(user_input, data, cnes_sources, ["beds", "icu_beds"]) # POPULATION PARAMS try: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": int(data["active_cases"].fillna(0).values[0]), "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } except: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": 0, "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } user_input["Rt"] = { "best": data["rt_low_95"].values[0], "worst": data["rt_high_95"].values[0], "is_valid": data["rt_most_likely"].apply(str).values[0], } user_input["last_updated_cases"] = data[ "last_updated_subnotification"].max() # Update session values to standard ones if changed city or opened page or reseted values if (session_state.state_name != user_input["state_name"] or session_state.health_region_name != user_input["health_region_name"] or session_state.city_name != user_input["city_name"] or session_state.number_beds is None or session_state.reset): session_state.state_name = user_input["state_name"] session_state.health_region_name = user_input["health_region_name"] session_state.city_name = user_input["city_name"] session_state.state_num_id = user_input["state_num_id"] session_state.health_region_id = user_input["health_region_id"] session_state.city_id = user_input["city_id"] session_state.number_beds = int( user_input["number_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_icu_beds = int( user_input["number_icu_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_cases = user_input["population_params"][ "I_confirmed"] session_state.number_deaths = user_input["population_params"]["D"] session_state.reset = True if data["confirmed_cases"].sum() == 0: st.write( f"""<div class="base-wrapper"> Seu município ou Região de Saúde ainda não possui casos reportados oficialmente. Portanto, simulamos como se o primeiro caso ocorresse hoje. <br><br>Caso queria, você pode mudar esse número abaixo: </div>""", unsafe_allow_html=True, ) user_input["population_params"]["I"] = 1 else: infectious_period = ( config["br"]["seir_parameters"]["severe_duration"] + config["br"]["seir_parameters"]["critical_duration"]) placeholder_value_pls_solve_this = 0 # ALERT BANNER # Aqui ele cria uma lista só com os estados que todas as cidades estao sem o overall_alert para criar um alerta para o estado states_list = dfs["city"].groupby(["state_name"]).agg({ "overall_alert": "count", "state_name": "max" }) states_list = states_list.loc[states_list['overall_alert'] < 1] # Adiciona forcadamente MT para a lista states_list = states_list.append( { 'state_name': 'Mato Grosso', 'overall_alert': 0 }, ignore_index=True) states_list = states_list['state_name'].to_list() utils.noOverallalert(user_input, data, states_list) # DIMENSIONS CARDS dimensions = DimensionCards utils.genAnalysisDimmensionsSection(dimensions) # INDICATORS CARDS indicators = IndicatorCards indicators = update_indicators(indicators, data, config, user_input, session_state) data["overall_alert"] = data["overall_alert"].map({ 0: "novo normal", 1: "moderado", 2: "alto", 3: "altíssimo" }) if "state" in user_input["place_type"]: # Add disclaimer to cities in state alert levels total_alert_regions = (dfs["health_region"][ dfs["health_region"]["state_num_id"] == data["state_num_id"].unique()[0]].assign( overall_alert=lambda df: df["overall_alert"].map({ 0: "novo normal", 1: "moderado", 2: "alto", 3: "altíssimo" }))["overall_alert"].value_counts()) utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, n_colapse_regions=total_alert_regions[ total_alert_regions.index.isin(["altíssimo", "alto"])].sum(), ) elif "city" in user_input["place_type"]: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, rt_type=data["rt_place_type"].values[0], ) else: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, ) # AVAILABLE CAPACITY DISCLAIMER # TODO -> VOLTAR PARA PROJECAO DE LEITOS # """ # <div class='base-wrapper'> # <i>* Utilizamos 100% do total de leitos UTI reportados por %s em %s # para cálculo da projeção de dias para atingir capacidade máxima.<br><b>Para municípios, utilizamos os recursos da respectiva regional de saúde.</b> # Leitos enfermaria contém os tipos: cirúrgicos, clínicos e hospital-dia; sendo considerado %s% já ocupado.</i> # </div> # """ st.write( """ <div class='base-wrapper' <i>* <b>Vacinação</b> </i> <li>“A porcentagem da população vacinada em seu local” - Total de pessoas que tomaram ao menos uma dose, dividido pelo total da população do local.<br> <li>“Porcentagem da população imunizada” - Total de pessoas que receberam todas as doses recomendadas do imunizante, dividido pelo total da população do local.<br> <li>“Total da população sem vacinar” - Número absoluto de habitantes do local que ainda não recebeu nenhuma dose do imunizante.<br> <i>Para mais detalhes e explicação completa confira nossa página de Metodologia no menu lateral.</i> </div> """, unsafe_allow_html=True, ) st.write( """ <div class='base-wrapper'> <i>* <b>Mudamos o indicador afim de refinarmos ajustes no cálculo de projeção de leitos.</b> Entendemos que a projeção apresentada não capturava a situação da 2ª onda observada nos municípios, regionais e estados, logo substituímos este indicador por ora para revisão dos cálculos. Os valores de referência se baseiam nas estatísticas de países da OCDE, <a target="_blank" style="color:#0068c9;" href="https://docs.google.com/spreadsheets/d/1MKFOHRCSg4KMx5Newi7TYCrjtNyPwMQ38GE1wQ6as70/edit?usp=sharing">veja mais aqui</a></b>. As simulações personalizadas ainda podem ser realizadas através do SimulaCovid mais abaixo.<br> <li> Leitos Enfermaria: Consideramos %s% do total reportado por %s em %s dos tipos Cirúrgico, Clínico e Hospital-dia. Para municípios, utilizamos os recursos da respectiva regional de saúde.<br> <li> Leitos UTI: Consideramos 100% do total de leitos UTI reportado por %s em %s. Para municípios, utilizamos os recursos da respectiva regional de saúde.</i> </div> """ % ( str( int(config["br"]["simulacovid"] ["resources_available_proportion"] * 100)), user_input["author_number_beds"], user_input["last_updated_number_beds"], user_input[ "author_number_icu_beds"], # remover na volta de projecao user_input[ "last_updated_number_icu_beds"], # remover na volta de projecao ), unsafe_allow_html=True, ) # TODO: remove comment on this later! # utils.gen_pdf_report() # INDICATORS PLOTS if st.button("Confira a evolução de indicadores-chave"): opening_response = user_analytics.log_event("picked key_indicators", dict()) if st.button("Esconder"): pass st.write( f""" <div class="base-wrapper"> <span class="section-header primary-span">CÁLCULO DA TAXA DE CONTÁGIO EM {user_input["locality"]}</span> <br><br> <b>A taxa de contágio, conhecida como número de reprodução efetivo (Rt), traduz a dinâmica de disseminação da Covid-19 a cada dia.</b> <br>O valor pode ser lido como o número médio de novas infecções diárias causadas por uma única pessoa infectada. Para mais informações, visite a página de Modelos no menu lateral. </div> """, unsafe_allow_html=True, ) try: fig2 = plots.plot_rt_wrapper(user_input[user_input["place_type"]], user_input["place_type"], config) st.plotly_chart(fig2, use_container_width=True) except: st.write( """<div class="base-wrapper"><b>Seu município, regional ou estado não possui mais de 30 dias de dados de casos confirmados.</b>""", unsafe_allow_html=True, ) st.write( "<div class='base-wrapper'><i>Em breve:</i> gráficos de subnotificação e média móvel (últimos 7 dias) de novos casos por 100k habitantes.</div>", unsafe_allow_html=True, ) utils.stylizeButton( name="Confira a evolução de indicadores-chave", style_string= """border: 1px solid var(--main-white);box-sizing: border-box;border-radius: 15px; width: auto;padding: 0.5em;text-transform: uppercase;font-family: var(--main-header-font-family);color: var(--main-white);background-color: var(--main-primary);font-weight: bold;text-align: center;text-decoration: none;font-size: 18px;animation-name: fadein;animation-duration: 3s;margin-top: 1em;""", session_state=session_state, ) # AMBASSADOR SECTION utils.gen_ambassador_section() # PDF-REPORT GEN BUTTON # if st.button("Gerar Relatório PDF"): # user_analytics.log_event("generated pdf") # st.write( # """<div class="base-wrapper">Aguarde um momento por favor...</div>""", # unsafe_allow_html=True, # ) # st.markdown( # pdfgen.gen_pdf_report(user_input, indicators, data, config), # unsafe_allow_html=True, # ) # TOOLS products = ProductCards utils.genProductsSection(products) # SELECTION BUTTONS # TODO: limpar esse código! está 100% repetido!!! if session_state.continuation_selection is None: session_state.continuation_selection = [False, False, False, False] simula_button_name = "Clique Aqui" # Simula covid 0space saude_button_name = "Clique Aqui " # Saude em ordem 1space distancia_button_name = "Clique_Aqui" # Distanciamento social onda_button_name = "Clique_Aqui " # onda covid if st.button(simula_button_name): # SIMULA session_state.continuation_selection = [True, False, False, False] if st.button(distancia_button_name): # DISTANCIAMENTO session_state.continuation_selection = [False, True, False, False] if st.button(saude_button_name): # SAUDE session_state.continuation_selection = [False, False, True, False] if st.button(onda_button_name): # ONDA session_state.continuation_selection = [False, False, False, True] utils.stylizeButton( name=simula_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 1}, ) utils.stylizeButton( name=distancia_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 2}, ) utils.stylizeButton( name=saude_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 3}, ) utils.stylizeButton( name=onda_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 4}, ) if session_state.continuation_selection[0]: user_analytics.safe_log_event( "picked simulacovid", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) # Downloading the saved data from memory sm.main(user_input, indicators, data, config, session_state) # TODO: remove comment on this later! # utils.gen_pdf_report() elif session_state.continuation_selection[1]: user_analytics.safe_log_event( "picked distanciamento", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) ds.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[2]: user_analytics.safe_log_event( "picked saude_em_ordem", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) so.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[3]: user_analytics.safe_log_event( "picked onda", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) oc.main(user_input, indicators, data, config, session_state) # CHAMA FUNCAO QUE GERA TABELA ID big_table # CALL FUNCTION TO GENERATE ID big_table gen_big_table(config, dfs, user_input["state_name"]) # CHAMA FUNCOES DO UTILS PARA O FOOTER # CALL FUNCTIONS IN UTILS TO FOOTER utils.gen_whatsapp_button(config["impulso"]["contact"]) utils.gen_footer() user_analytics.conclude_user_session(session_state)
## ## ## This program is free software: you can redistribute it and/or modify ## ## it under the terms of the GNU General Public License as published by ## ## the Free Software Foundation, either version 3 of the License, or ## ## (at your option) any later version. ## ## ## ## This program is distributed in the hope that it will be useful, ## ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## ## GNU General Public License for more details. ## ## ## ## You should have received a copy of the GNU General Public License ## ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## ## ## ########################################################################### import utils if __name__ == "__main__": sources = [int(x) for x in utils.get_sources().keys()] dbconn = utils.get_dbconn() dbcurs = dbconn.cursor() tables = ["dynpoi_class", "marker", "dynpoi_status", "dynpoi_update"] for t in tables: dbcurs.execute("SELECT source FROM %s GROUP BY source;"%t) for res in dbcurs.fetchall(): if res[0] not in sources: print "DELETE FROM %s WHERE source = %d;"%(t, res[0])
def main(session_state): # ==== GOOGLE ANALYTICS SETUP ==== GOOGLE_ANALYTICS_CODE = os.getenv("GOOGLE_ANALYTICS_CODE") if GOOGLE_ANALYTICS_CODE: import pathlib from bs4 import BeautifulSoup GA_JS = (""" window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', '%s'); """ % GOOGLE_ANALYTICS_CODE) index_path = pathlib.Path(st.__file__).parent / "static" / "index.html" soup = BeautifulSoup(index_path.read_text(), features="lxml") if not soup.find(id="google-analytics-loader"): script_tag_import = soup.new_tag( "script", src="https://www.googletagmanager.com/gtag/js?id=%s" % GOOGLE_ANALYTICS_CODE, ) soup.head.append(script_tag_import) script_tag_loader = soup.new_tag("script", id="google-analytics-loader") script_tag_loader.string = GA_JS soup.head.append(script_tag_loader) index_path.write_text(str(soup)) # ==== # Amplitude: Get user info user_analytics = amplitude.gen_user(utils.get_server_session()) opening_response = user_analytics.safe_log_event("opened farol", session_state, is_new_page=True) utils.localCSS("style.css") utils.genHeroSection( title1="Farol", title2="Covid", subtitle="Entenda e controle a Covid-19 em sua cidade e estado.", logo="https://i.imgur.com/CkYDPR7.png", header=True) config = yaml.load(open("configs/config.yaml", "r"), Loader=yaml.FullLoader) #TEMPORARY BANNER FC st.write( """ <div> <div class="base-wrapper flex flex-column" style="background-color:#0090A7"> <div class="white-span header p1" style="font-size:30px;">O FAROLCOVID ESTÁ DE CARA NOVA!</div> <span class="white-span">Aprimoramos a plataforma e adicionamos novas ferramentas para acompanhamento da crise da Covid-19 no Brasil. <b>Que tal explorar com a gente?</b></span> <br><div style="margin-top: 15px;"></div> <div> <a href="#novidades" class="info-btn">Entenda como navegar</a> </div> <div id="novidades" class="nov-modal-window"> <div> <a href="#" title="Close" class="info-btn-close" style="color: white;">×</a> <div style="margin: 10px 15px 15px 15px;"> <h1 class="primary-span">Saiba como cada ferramenta apoia a resposta ao coronavírus</h1> <p class="darkblue-span uppercase"> <b>Farol Covid</b> </p> <img class="img-modal" src=%s alt="Ícone Farol Covid"> <div> <p> Acompanhe as 4 dimensões:</p> - Situação da Doença (número de novos casos por habitante);</br> - Controle da Doença (ritmo de contágio)</br> - Capacidade do sistema (número de leitos e capacidade UTI)</br> - Confiança de dados (taxa de subnotificação)</br> <p> E descubra o nível de alerta do estado, regional de saúde ou município.</p> </div> <div> <p class="darkblue-span uppercase"> <b>SimulaCovid</b> </p> <img class="img-modal" src=%s alt="Ícone SimulaCovid"> <p style="height:100px;">Simule o que pode acontecer com o sistema de saúde local se o ritmo de contágio aumentar ou diminuir e planeje suas ações para evitar a sobrecarga hospitalar.</p> </div> <div> <p class="darkblue-span uppercase"> <b>Distanciamento Social</b> </p> <img class="img-modal" src=%s alt="Ícone Distanciamento Social"> <p style="height:100px;">Acompanhe a atualização diária do índice e descubra como está a circulação de pessoas e o distanciamento social no seu estado ou município. </p> </div> <div> <p class="darkblue-span uppercase"> <b>Saúde em Ordem</b> </p> <img class="img-modal" src=%s alt="Ícone Saúde em Ordem"> <p> Entenda quais atividades deveriam reabrir primeiro na sua região, considerando: </p> - Segurança Sanitária: quais setores trazem menor risco de exposição à Covid-19 para os trabalhadores.</br> - Contribuição Econômica: quais setores movimentam mais a economia daquele estado ou regional de saúde.</br> <p> </p> </div> <div> <p class="darkblue-span uppercase"> <b>Onda Covid</b> </p> <img class="img-modal" src=%s alt="Ícone Onda Covid"> <p>Com base no número de óbitos de Covid-19 registrados, acompanhe se seu município já saiu do pico da doença. </p> </div> </div> </div> </div> </div>""" % (config["br"]["icons"]["farolcovid_logo"], config["br"]["icons"]["simulacovid_logo"], config["br"]["icons"]["distanciamentosocial_logo"], config["br"]["icons"]["saudeemordem_logo"], config["br"]["icons"]["ondacovid_logo"]), unsafe_allow_html=True, ) st.write( """ <div class="base-wrapper primary-span"> <span class="section-header">Selecione seu estado ou município no mapa abaixo:</span> </div>""", unsafe_allow_html=True, ) # GET DATA dfs = get_data(config) # REGION/CITY USER INPUT user_input = dict() user_input["state_name"] = st.selectbox("Estado", utils.filter_place(dfs, "state")) user_input["health_region_name"] = st.selectbox( "Região de Saúde", utils.filter_place(dfs, "health_region", state_name=user_input["state_name"]), ) user_input["city_name"] = st.selectbox( "Município", utils.filter_place( dfs, "city", state_name=user_input["state_name"], health_region_name=user_input["health_region_name"], ), ) changed_city = user_analytics.safe_log_event( "picked farol place", session_state, event_args={ "state": user_input["state_name"], "city": user_input["city_name"] }, ) user_input, data = update_user_input_places(user_input, dfs, config) # GENERATE MAPS map_place_id = utils.Dictionary().get_state_alphabetical_id_by_name( user_input["state_name"]) if os.getenv("IS_LOCAL") == "TRUE": map_url = config["br"]["api"]["mapserver_local"] else: map_url = config["br"]["api"]["mapserver_external"] st.write( f""" <div class="brazil-map-div"> <div class="alert-levels-map-overlay"> </div> <div> <iframe id="map" src="resources/iframe-gen.html?url={map_url}map-iframe?place_id=BR" class="map-br" scrolling="no"> </iframe> </div> </div> """, unsafe_allow_html=True, ) st.write( f""" <iframe id="map-state" src="resources/iframe-gen.html?url={map_url}map-iframe?place_id={map_place_id}" class="map-state" scrolling="no"> </iframe> """, unsafe_allow_html=True, ) st.write( f""" <div class="selectors-box" id="selectors-box"> </div> <iframe src="resources/select-box-mover.html?place_id={user_input["state_name"]}{user_input["health_region_name"]}{user_input["city_name"]}" height="0px"> </iframe>""", unsafe_allow_html=True, ) # SOURCES PARAMS user_input = utils.get_sources(user_input, data, dfs["city"], ["beds", "icu_beds"]) # POPULATION PARAMS try: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": int(data["active_cases"].fillna(0).values[0]), "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } except: user_input["population_params"] = { "N": int(data["population"].fillna(0).values[0]), "D": int(data["deaths"].fillna(0).values[0]), "I": 0, "I_confirmed": int(data["confirmed_cases"].fillna(0).values[0]), "I_compare": int(data["confirmed_cases"].fillna(0).values[0]), } user_input["Rt"] = { "best": data["rt_low_95"].values[0], "worst": data["rt_high_95"].values[0], "is_valid": data["rt_most_likely"].apply(str).values[0], } user_input["last_updated_cases"] = data[ "last_updated_subnotification"].max() # Update session values to standard ones if changed city or opened page or reseted values if (session_state.state_name != user_input["state_name"] or session_state.health_region_name != user_input["health_region_name"] or session_state.city_name != user_input["city_name"] or session_state.number_beds is None or session_state.reset): session_state.state_name = user_input["state_name"] session_state.health_region_name = user_input["health_region_name"] session_state.city_name = user_input["city_name"] session_state.state_num_id = user_input["state_num_id"] session_state.health_region_id = user_input["health_region_id"] session_state.city_id = user_input["city_id"] session_state.number_beds = int( user_input["number_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_icu_beds = int( user_input["number_icu_beds"] * config["br"]["simulacovid"]["resources_available_proportion"]) session_state.number_cases = user_input["population_params"][ "I_confirmed"] session_state.number_deaths = user_input["population_params"]["D"] session_state.reset = True if data["confirmed_cases"].sum() == 0: st.write( f"""<div class="base-wrapper"> Seu município ou Região de Saúde ainda não possui casos reportados oficialmente. Portanto, simulamos como se o primeiro caso ocorresse hoje. <br><br>Caso queria, você pode mudar esse número abaixo: </div>""", unsafe_allow_html=True, ) user_input["population_params"]["I"] = 1 else: infectious_period = ( config["br"]["seir_parameters"]["severe_duration"] + config["br"]["seir_parameters"]["critical_duration"]) placeholder_value_pls_solve_this = 0 # DIMENSIONS CARDS dimensions = DimensionCards utils.genAnalysisDimmensionsSection(dimensions) # INDICATORS CARDS indicators = IndicatorCards indicators = update_indicators(indicators, data, config, user_input, session_state) data["overall_alert"] = data["overall_alert"].map( config["br"]["farolcovid"]["categories"]) if "state" in user_input["place_type"]: # Add disclaimer to cities in state alert levels total_alert_regions = dfs["health_region"][ dfs["health_region"]["state_num_id"] == data["state_num_id"]. unique()[0]].assign(overall_alert=lambda df: df[ "overall_alert"].map(config["br"]["farolcovid"]["categories"]) )["overall_alert"].value_counts() utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, n_colapse_regions=total_alert_regions[ total_alert_regions.index.isin(["altíssimo", "alto"])].sum(), ) else: utils.genKPISection( place_type=user_input["place_type"], locality=user_input["locality"], alert=data["overall_alert"].values[0], indicators=indicators, ) # AVAILABLE CAPACITY DISCLAIMER st.write( """ <div class='base-wrapper'> <i>* Utilizamos %s% da capacidade hospitalar reportada por %s em %s para cálculo da projeção de dias para atingir capacidade máxima.<br><b>Para municípios, utilizamos os recursos da respectiva regional de saúde.</b> São considerados leitos os tipos: cirúrgicos, clínicos e hospital-dia. A capacidade de UTI é dada pelo total de leitos UTI Covid adulto.</i> </div> """ % ( str( int(config["br"]["simulacovid"] ["resources_available_proportion"] * 100)), user_input["author_number_beds"], user_input["last_updated_number_beds"], ), unsafe_allow_html=True, ) # TODO: remove comment on this later! # utils.gen_pdf_report() # INDICATORS PLOTS if st.button("Confira a evolução de indicadores-chave"): opening_response = user_analytics.log_event("picked key_indicators", dict()) if st.button("Esconder"): pass st.write( f""" <div class="base-wrapper"> <span class="section-header primary-span">CÁLCULO DO RITMO DE CONTÁGIO EM {user_input["locality"]}</span> <br><br> O ritmo de contágio, conhecido como número de reprodução efetivo (Rt), traduz a dinâmica de disseminação do Covid a cada dia. <br>O valor pode ser lido como o número médio de novas infecções diárias causadas por uma única pessoa infectada. Para mais informações, visite a página de Metodologia. </div> """, unsafe_allow_html=True, ) try: fig2 = plots.plot_rt_wrapper(user_input[user_input["place_type"]], user_input["place_type"]) st.plotly_chart(fig2, use_container_width=True) except: st.write( """<div class="base-wrapper"><b>Seu município, regional ou estado não possui mais de 30 dias de dados de casos confirmados.</b>""", unsafe_allow_html=True, ) st.write( "<div class='base-wrapper'><i>Em breve:</i> gráficos de subnotificação e média móvel de novos casos por 100k habitantes.</div>", unsafe_allow_html=True, ) utils.stylizeButton( name="Confira a evolução de indicadores-chave", style_string= """border: 1px solid var(--main-white);box-sizing: border-box;border-radius: 15px; width: auto;padding: 0.5em;text-transform: uppercase;font-family: var(--main-header-font-family);color: var(--main-white);background-color: var(--main-primary);font-weight: bold;text-align: center;text-decoration: none;font-size: 18px;animation-name: fadein;animation-duration: 3s;margin-top: 1em;""", session_state=session_state, ) # AMBASSADOR SECTION utils.gen_ambassador_section() # indicators["hospital_capacity"].left_display = user_input["number_beds"] # indicators["hospital_capacity"].right_display = user_input["number_icu_beds"] # indicators["subnotification_rate"].left_display = user_input["population_params"][ # "D" # ] # PDF-REPORT GEN BUTTON # if st.button("Gerar Relatório PDF"): # user_analytics.log_event("generated pdf") # st.write( # """<div class="base-wrapper">Aguarde um momento por favor...</div>""", # unsafe_allow_html=True, # ) # st.markdown( # pdfgen.gen_pdf_report(user_input, indicators, data, config), # unsafe_allow_html=True, # ) # TOOLS products = ProductCards # products[2].recommendation = f'Risco {data["overall_alert"].values[0]}' utils.genProductsSection(products) # SELECTION BUTTONS # TODO: limpar esse código! está 100% repetido!!! if session_state.continuation_selection is None: session_state.continuation_selection = [False, False, False, False] simula_button_name = "Clique Aqui" # Simula covid 0space saude_button_name = "Clique Aqui " # Saude em ordem 1space distancia_button_name = "Clique_Aqui" # Distanciamento social onda_button_name = "Clique_Aqui " # onda covid if st.button(simula_button_name): # SIMULA session_state.continuation_selection = [True, False, False, False] if st.button(distancia_button_name): # DISTANCIAMENTO session_state.continuation_selection = [False, True, False, False] if st.button(saude_button_name): # SAUDE session_state.continuation_selection = [False, False, True, False] if st.button(onda_button_name): # ONDA session_state.continuation_selection = [False, False, False, True] utils.stylizeButton( name=simula_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 1}, ) utils.stylizeButton( name=distancia_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 2}, ) utils.stylizeButton( name=saude_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 3}, ) utils.stylizeButton( name=onda_button_name, style_string="""border: 1px solid black;""", session_state=session_state, others={"ui_binSelect": 4}, ) if session_state.continuation_selection[0]: user_analytics.safe_log_event( "picked simulacovid", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) # Downloading the saved data from memory user_input["number_beds"] = session_state.number_beds user_input["number_icu_beds"] = session_state.number_icu_beds user_input["number_deaths"] = session_state.number_deaths user_input["number_cases"] = session_state.number_cases sm.main(user_input, indicators, data, config, session_state) # TODO: remove comment on this later! # utils.gen_pdf_report() elif session_state.continuation_selection[1]: user_analytics.safe_log_event( "picked distanciamento", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) ds.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[2]: user_analytics.safe_log_event( "picked saude_em_ordem", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) so.main(user_input, indicators, data, config, session_state) elif session_state.continuation_selection[3]: user_analytics.safe_log_event( "picked onda", session_state, event_args={ "state": session_state.state_name, "health_region": session_state.health_region_name, "city": session_state.city_name, }, alternatives=[ "picked saude_em_ordem", "picked simulacovid", "picked onda", "picked distanciamento", ], ) oc.main(user_input, indicators, data, config, session_state) # BIG TABLE gen_big_table(config, dfs) # FOOTER utils.gen_whatsapp_button(config["impulso"]["contact"]) utils.gen_footer() user_analytics.conclude_user_session(session_state)
## ## ## This program is free software: you can redistribute it and/or modify ## ## it under the terms of the GNU General Public License as published by ## ## the Free Software Foundation, either version 3 of the License, or ## ## (at your option) any later version. ## ## ## ## This program is distributed in the hope that it will be useful, ## ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## ## GNU General Public License for more details. ## ## ## ## You should have received a copy of the GNU General Public License ## ## along with this program. If not, see <http://www.gnu.org/licenses/>. ## ## ## ########################################################################### import utils if __name__ == "__main__": sources = [int(x) for x in utils.get_sources().keys()] dbconn = utils.get_dbconn() dbcurs = dbconn.cursor() tables = ["dynpoi_class", "marker", "dynpoi_status", "dynpoi_update"] for t in tables: dbcurs.execute("SELECT source FROM %s GROUP BY source;" % t) for res in dbcurs.fetchall(): if res[0] not in sources: print "DELETE FROM %s WHERE source = %d;" % (t, res[0])