Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import re, unicodedata, warnings, branca, folium, gradio as gr
|
| 2 |
import pandas as pd, geopandas as gpd, numpy as np
|
| 3 |
from shapely.geometry import Point
|
|
@@ -13,6 +16,19 @@ snake = lambda cols:[re.sub(r"[^\w]+","_",norm(c).strip().lower()).strip("_") fo
|
|
| 13 |
sin_dato = lambda s:s.fillna("Sin dato").replace("", "Sin dato")
|
| 14 |
NUM_VARS = ["edad","creatinina"]
|
| 15 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
# βββββββββββββββββββ rutas βββββββββββββββββββββ
|
| 17 |
DATA_XLSX = "VasculitisAsociadasA-Bdd3_DATA_LABELS_2025-04-16_1949 (1).xlsx"
|
| 18 |
LOCALIDADES = "loca.json"
|
|
@@ -60,8 +76,9 @@ df_all["edad_cat"]=pd.Categorical(
|
|
| 60 |
sin_dato(pd.cut(df_all["edad"],bins=bins,labels=age_labels,right=False).astype(str)),
|
| 61 |
categories=age_labels+["Sin dato"], ordered=True)
|
| 62 |
|
| 63 |
-
# marcadores ANCA/MPO/PR3
|
| 64 |
-
|
|
|
|
| 65 |
df_all[f"{col}_cat"]=sin_dato(df_all.get(col))
|
| 66 |
|
| 67 |
# clΓnicos
|
|
@@ -147,7 +164,7 @@ def filtrar(d,gen,edades,locs,renal,ants,bios,anca,mpo,pr3):
|
|
| 147 |
if renal!="Todos": d2=d2[d2["biopsia_positiva"]==renal]
|
| 148 |
if bios and bios!=["Todos"]:
|
| 149 |
d2=d2[d2["biopsia_patrones"].apply(lambda lst:any(p in lst for p in bios))]
|
| 150 |
-
if anca!="Todos": d2=d2[d2["
|
| 151 |
if mpo!="Todos": d2=d2[d2["mpo_cat"]==mpo]
|
| 152 |
if pr3!="Todos": d2=d2[d2["pr3_cat"]==pr3]
|
| 153 |
for ant in ants:
|
|
@@ -176,53 +193,52 @@ def prep_pts(d):
|
|
| 176 |
return gpd.GeoDataFrame(d2,geometry="geometry",crs=4326)
|
| 177 |
|
| 178 |
def env_df(var,pts):
|
| 179 |
-
g=
|
| 180 |
val,uni,*_=META_CAPAS[var]
|
| 181 |
g["zona"]=g.apply(lambda r:f"Zona {int(r['id'])} ({r[val]:.1f} {uni})",axis=1)
|
| 182 |
return g[["zona","pacientes"]]
|
| 183 |
|
| 184 |
def is_num(v): return v in NUM_VARS
|
|
|
|
| 185 |
|
| 186 |
# βββββββββββββββ univariado βββββββββββββββ
|
| 187 |
def g_uni(v,d):
|
|
|
|
| 188 |
if v in ENV_VARS:
|
| 189 |
df=env_df(v,prep_pts(d))
|
| 190 |
-
df=df.sort_values("zona")
|
| 191 |
return px.bar(df,x="zona",y="pacientes",text_auto=True,title=v,
|
| 192 |
labels={"zona":"Zona","pacientes":"Pacientes"})
|
| 193 |
if v=="Localidad":
|
| 194 |
s=d["localidad"].fillna("Sin dato")
|
| 195 |
return px.histogram(s,x=s,category_orders={s.name:sorted(s.unique())},
|
| 196 |
text_auto=True,title="Localidad")
|
| 197 |
-
if is_num(
|
| 198 |
-
return px.histogram(d,x=
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
return px.histogram(d,x=v,category_orders={v:order},text_auto=True,title=v)
|
| 202 |
|
| 203 |
# βββββββββββββββ bivariado βββββββββββββββ
|
| 204 |
def g_bi(x,y,d):
|
|
|
|
| 205 |
pts=prep_pts(d)
|
| 206 |
if x in ENV_VARS: d=d.assign(**{x:env_df(x,pts).loc[d.index,"zona"]})
|
| 207 |
if y in ENV_VARS: d=d.assign(**{y:env_df(y,pts).loc[d.index,"zona"]})
|
| 208 |
-
num_x,num_y=is_num(
|
| 209 |
-
# cat-cat β barras conteo absoluto
|
| 210 |
if not num_x and not num_y:
|
| 211 |
-
ord_x=sorted(map(str,d[
|
| 212 |
-
return px.histogram(d,x=
|
| 213 |
-
category_orders={
|
| 214 |
title=f"{x} vs {y}")
|
| 215 |
-
# num-cat
|
| 216 |
if num_x and not num_y:
|
| 217 |
-
return px.box(d,x=
|
| 218 |
if not num_x and num_y:
|
| 219 |
-
return px.box(d,x=
|
| 220 |
-
|
| 221 |
-
return px.scatter(d,x=x,y=y,title=f"{x} vs {y}")
|
| 222 |
|
| 223 |
# βββββββββββββββ pop-up βββββββββββββββ
|
| 224 |
def popup(r):
|
| 225 |
-
lab=lambda k:f"<b>{k}:</b> SΓ<br>" if r[f"{k.lower()}_cat"].lower()=="positivo" else ""
|
| 226 |
edad=f"{int(r['edad'])} aΓ±os" if pd.notna(r['edad']) else "Sin dato edad"
|
| 227 |
ants="; ".join(v for k,v in resumen_ante.items() if r.get(k)=="SΓ") or "Ninguno"
|
| 228 |
return (f"<b>Localidad:</b> {r['localidad']}<br><b>Edad:</b> {edad}<br>"
|
|
@@ -253,14 +269,12 @@ def crear_mapa(d_filt,capas_sel,ver_cluster):
|
|
| 253 |
pts=prep_pts(d_filt)
|
| 254 |
caps=capas_conteos(pts)
|
| 255 |
|
| 256 |
-
# base: pacientes por localidad
|
| 257 |
g_loc=pts.groupby("localidad").size().reset_index(name="pacientes")
|
| 258 |
geo=geo_loc.merge(g_loc,on="localidad",how="left").fillna({"pacientes":0})
|
| 259 |
m=folium.Map(location=[4.65,-74.1],zoom_start=11,tiles="CartoDB positron")
|
| 260 |
choropleth(m,geo,"pacientes","No. Pacientes",
|
| 261 |
branca.colormap.linear.Reds_09,"localidad","Localidad")
|
| 262 |
|
| 263 |
-
# capas seleccionadas
|
| 264 |
for capa in capas_sel:
|
| 265 |
if capa=="Heatmap pacientes": continue
|
| 266 |
if capa=="WQI":
|
|
@@ -268,11 +282,9 @@ def crear_mapa(d_filt,capas_sel,ver_cluster):
|
|
| 268 |
val,uni,cmap,zf,za=META_CAPAS[capa]
|
| 269 |
choropleth(m,caps[capa],val,f"{capa} ({uni})",cmap,zf,za)
|
| 270 |
|
| 271 |
-
# heatmap
|
| 272 |
if "Heatmap pacientes" in capas_sel and not pts.empty:
|
| 273 |
HeatMap(pts[["latitud","longitud"]].values,radius=18,name="Heatmap pacientes").add_to(m)
|
| 274 |
|
| 275 |
-
# puntos
|
| 276 |
fg=folium.FeatureGroup("Pacientes",overlay=True)
|
| 277 |
for _,r in pts.iterrows():
|
| 278 |
folium.CircleMarker((r["latitud"],r["longitud"]),radius=6,color="#c00",
|
|
@@ -280,7 +292,6 @@ def crear_mapa(d_filt,capas_sel,ver_cluster):
|
|
| 280 |
popup=popup(r)).add_to(fg)
|
| 281 |
fg.add_to(m)
|
| 282 |
|
| 283 |
-
# clusters
|
| 284 |
if ver_cluster and len(pts)>2:
|
| 285 |
coords=np.radians(pts[["latitud","longitud"]])
|
| 286 |
lab=DBSCAN(eps=1/6371,min_samples=3,metric="haversine").fit_predict(coords)
|
|
@@ -302,14 +313,14 @@ def crear_mapa(d_filt,capas_sel,ver_cluster):
|
|
| 302 |
gen_opts=["Todos"]+sorted(df_all["genero_cat"].unique())
|
| 303 |
age_opts=list(df_all["edad_cat"].dtype.categories)
|
| 304 |
loc_opts=sorted(df_all["localidad"].fillna("Sin dato").unique())
|
| 305 |
-
anca_opts=["Todos"]+sorted(df_all["
|
| 306 |
mpo_opts=["Todos"]+sorted(df_all["mpo_cat"].unique())
|
| 307 |
pr3_opts=["Todos"]+sorted(df_all["pr3_cat"].unique())
|
| 308 |
|
| 309 |
vars_cat=["Localidad"]+ENV_VARS+[
|
| 310 |
"genero_cat","estrato_cat","edad_cat","sindrome_renal",
|
| 311 |
"manifestaciones_extrarenales","proteinuria",
|
| 312 |
-
"
|
| 313 |
vars_all=vars_cat+NUM_VARS
|
| 314 |
|
| 315 |
with gr.Blocks(title="Vasculitis ANCA BogotΓ‘") as demo:
|
|
|
|
| 1 |
+
# app.py β Explorador geoespacial Vasculitis ANCA (BogotΓ‘)
|
| 2 |
+
# VersiΓ³n 25-abr-2025 Β· FIX: columnas anca_cat, mapeos UI-DataFrame, NameErrors, KeyErrors
|
| 3 |
+
|
| 4 |
import re, unicodedata, warnings, branca, folium, gradio as gr
|
| 5 |
import pandas as pd, geopandas as gpd, numpy as np
|
| 6 |
from shapely.geometry import Point
|
|
|
|
| 16 |
sin_dato = lambda s:s.fillna("Sin dato").replace("", "Sin dato")
|
| 17 |
NUM_VARS = ["edad","creatinina"]
|
| 18 |
|
| 19 |
+
# Mapeo nombre legible β nombre real de columna
|
| 20 |
+
display_to_col = {
|
| 21 |
+
"Localidad": "localidad",
|
| 22 |
+
"PatrΓ³n biopsia": "biopsia_patron_str",
|
| 23 |
+
"Diabetes": "diabetes",
|
| 24 |
+
"Falla cardΓaca": "falla_cardiaca",
|
| 25 |
+
"EPOC": "epoc",
|
| 26 |
+
"HipertensiΓ³n": "hipertension",
|
| 27 |
+
"VIH": "vih",
|
| 28 |
+
"Enf. autoinmune": "autoinmune",
|
| 29 |
+
"CΓ‘ncer": "cancer",
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
# βββββββββββββββββββ rutas βββββββββββββββββββββ
|
| 33 |
DATA_XLSX = "VasculitisAsociadasA-Bdd3_DATA_LABELS_2025-04-16_1949 (1).xlsx"
|
| 34 |
LOCALIDADES = "loca.json"
|
|
|
|
| 76 |
sin_dato(pd.cut(df_all["edad"],bins=bins,labels=age_labels,right=False).astype(str)),
|
| 77 |
categories=age_labels+["Sin dato"], ordered=True)
|
| 78 |
|
| 79 |
+
# marcadores ANCA/MPO/PR3 (cola singular corregida)
|
| 80 |
+
df_all["anca_cat"] = sin_dato(df_all.get("ancas"))
|
| 81 |
+
for col in ("mpo","pr3"):
|
| 82 |
df_all[f"{col}_cat"]=sin_dato(df_all.get(col))
|
| 83 |
|
| 84 |
# clΓnicos
|
|
|
|
| 164 |
if renal!="Todos": d2=d2[d2["biopsia_positiva"]==renal]
|
| 165 |
if bios and bios!=["Todos"]:
|
| 166 |
d2=d2[d2["biopsia_patrones"].apply(lambda lst:any(p in lst for p in bios))]
|
| 167 |
+
if anca!="Todos": d2=d2[d2["anca_cat"]==anca]
|
| 168 |
if mpo!="Todos": d2=d2[d2["mpo_cat"]==mpo]
|
| 169 |
if pr3!="Todos": d2=d2[d2["pr3_cat"]==pr3]
|
| 170 |
for ant in ants:
|
|
|
|
| 193 |
return gpd.GeoDataFrame(d2,geometry="geometry",crs=4326)
|
| 194 |
|
| 195 |
def env_df(var,pts):
|
| 196 |
+
g=capas_conteos(pts)[var].copy()
|
| 197 |
val,uni,*_=META_CAPAS[var]
|
| 198 |
g["zona"]=g.apply(lambda r:f"Zona {int(r['id'])} ({r[val]:.1f} {uni})",axis=1)
|
| 199 |
return g[["zona","pacientes"]]
|
| 200 |
|
| 201 |
def is_num(v): return v in NUM_VARS
|
| 202 |
+
def col_real(v): return display_to_col.get(v,v) # mapeo visibleβreal
|
| 203 |
|
| 204 |
# βββββββββββββββ univariado βββββββββββββββ
|
| 205 |
def g_uni(v,d):
|
| 206 |
+
v_real=col_real(v)
|
| 207 |
if v in ENV_VARS:
|
| 208 |
df=env_df(v,prep_pts(d))
|
| 209 |
+
df=df.sort_values("zona")
|
| 210 |
return px.bar(df,x="zona",y="pacientes",text_auto=True,title=v,
|
| 211 |
labels={"zona":"Zona","pacientes":"Pacientes"})
|
| 212 |
if v=="Localidad":
|
| 213 |
s=d["localidad"].fillna("Sin dato")
|
| 214 |
return px.histogram(s,x=s,category_orders={s.name:sorted(s.unique())},
|
| 215 |
text_auto=True,title="Localidad")
|
| 216 |
+
if is_num(v_real):
|
| 217 |
+
return px.histogram(d,x=v_real,nbins=20,title=v)
|
| 218 |
+
order=sorted(d[v_real].astype(str).unique())
|
| 219 |
+
return px.histogram(d,x=v_real,category_orders={v_real:order},text_auto=True,title=v)
|
|
|
|
| 220 |
|
| 221 |
# βββββββββββββββ bivariado βββββββββββββββ
|
| 222 |
def g_bi(x,y,d):
|
| 223 |
+
x_r,y_r=col_real(x),col_real(y)
|
| 224 |
pts=prep_pts(d)
|
| 225 |
if x in ENV_VARS: d=d.assign(**{x:env_df(x,pts).loc[d.index,"zona"]})
|
| 226 |
if y in ENV_VARS: d=d.assign(**{y:env_df(y,pts).loc[d.index,"zona"]})
|
| 227 |
+
num_x,num_y=is_num(x_r),is_num(y_r)
|
|
|
|
| 228 |
if not num_x and not num_y:
|
| 229 |
+
ord_x=sorted(map(str,d[x_r].unique())); ord_y=sorted(map(str,d[y_r].unique()))
|
| 230 |
+
return px.histogram(d,x=x_r,color=y_r,barmode="group",
|
| 231 |
+
category_orders={x_r:ord_x,y_r:ord_y},
|
| 232 |
title=f"{x} vs {y}")
|
|
|
|
| 233 |
if num_x and not num_y:
|
| 234 |
+
return px.box(d,x=y_r,y=x_r,points="all",title=f"{x} vs {y}")
|
| 235 |
if not num_x and num_y:
|
| 236 |
+
return px.box(d,x=x_r,y=y_r,points="all",title=f"{x} vs {y}")
|
| 237 |
+
return px.scatter(d,x=x_r,y=y_r,title=f"{x} vs {y}")
|
|
|
|
| 238 |
|
| 239 |
# βββββββββββββββ pop-up βββββββββββββββ
|
| 240 |
def popup(r):
|
| 241 |
+
lab=lambda k:f"<b>{k}:</b> SΓ<br>" if str(r[f"{k.lower()}_cat"]).lower()=="positivo" else ""
|
| 242 |
edad=f"{int(r['edad'])} aΓ±os" if pd.notna(r['edad']) else "Sin dato edad"
|
| 243 |
ants="; ".join(v for k,v in resumen_ante.items() if r.get(k)=="SΓ") or "Ninguno"
|
| 244 |
return (f"<b>Localidad:</b> {r['localidad']}<br><b>Edad:</b> {edad}<br>"
|
|
|
|
| 269 |
pts=prep_pts(d_filt)
|
| 270 |
caps=capas_conteos(pts)
|
| 271 |
|
|
|
|
| 272 |
g_loc=pts.groupby("localidad").size().reset_index(name="pacientes")
|
| 273 |
geo=geo_loc.merge(g_loc,on="localidad",how="left").fillna({"pacientes":0})
|
| 274 |
m=folium.Map(location=[4.65,-74.1],zoom_start=11,tiles="CartoDB positron")
|
| 275 |
choropleth(m,geo,"pacientes","No. Pacientes",
|
| 276 |
branca.colormap.linear.Reds_09,"localidad","Localidad")
|
| 277 |
|
|
|
|
| 278 |
for capa in capas_sel:
|
| 279 |
if capa=="Heatmap pacientes": continue
|
| 280 |
if capa=="WQI":
|
|
|
|
| 282 |
val,uni,cmap,zf,za=META_CAPAS[capa]
|
| 283 |
choropleth(m,caps[capa],val,f"{capa} ({uni})",cmap,zf,za)
|
| 284 |
|
|
|
|
| 285 |
if "Heatmap pacientes" in capas_sel and not pts.empty:
|
| 286 |
HeatMap(pts[["latitud","longitud"]].values,radius=18,name="Heatmap pacientes").add_to(m)
|
| 287 |
|
|
|
|
| 288 |
fg=folium.FeatureGroup("Pacientes",overlay=True)
|
| 289 |
for _,r in pts.iterrows():
|
| 290 |
folium.CircleMarker((r["latitud"],r["longitud"]),radius=6,color="#c00",
|
|
|
|
| 292 |
popup=popup(r)).add_to(fg)
|
| 293 |
fg.add_to(m)
|
| 294 |
|
|
|
|
| 295 |
if ver_cluster and len(pts)>2:
|
| 296 |
coords=np.radians(pts[["latitud","longitud"]])
|
| 297 |
lab=DBSCAN(eps=1/6371,min_samples=3,metric="haversine").fit_predict(coords)
|
|
|
|
| 313 |
gen_opts=["Todos"]+sorted(df_all["genero_cat"].unique())
|
| 314 |
age_opts=list(df_all["edad_cat"].dtype.categories)
|
| 315 |
loc_opts=sorted(df_all["localidad"].fillna("Sin dato").unique())
|
| 316 |
+
anca_opts=["Todos"]+sorted(df_all["anca_cat"].unique())
|
| 317 |
mpo_opts=["Todos"]+sorted(df_all["mpo_cat"].unique())
|
| 318 |
pr3_opts=["Todos"]+sorted(df_all["pr3_cat"].unique())
|
| 319 |
|
| 320 |
vars_cat=["Localidad"]+ENV_VARS+[
|
| 321 |
"genero_cat","estrato_cat","edad_cat","sindrome_renal",
|
| 322 |
"manifestaciones_extrarenales","proteinuria",
|
| 323 |
+
"anca_cat","mpo_cat","pr3_cat","PatrΓ³n biopsia"]+list(resumen_ante.values())
|
| 324 |
vars_all=vars_cat+NUM_VARS
|
| 325 |
|
| 326 |
with gr.Blocks(title="Vasculitis ANCA BogotΓ‘") as demo:
|