hedtorresca commited on
Commit
76dcb13
Β·
verified Β·
1 Parent(s): 7c6e2c9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +310 -261
app.py CHANGED
@@ -1,5 +1,7 @@
 
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
4
  from folium.plugins import HeatMap
5
  from sklearn.cluster import DBSCAN
@@ -8,10 +10,10 @@ import plotly.express as px
8
  warnings.filterwarnings("ignore")
9
 
10
  # ─────────────────── helpers ───────────────────
11
- norm = lambda t: unicodedata.normalize("NFKD", t).encode("ascii","ignore").decode()
12
- snake = lambda cols:[re.sub(r"[^\w]+","_",norm(c).strip().lower()).strip("_") for c in cols]
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"
@@ -26,18 +28,17 @@ GEO_AMBIENTALES = {
26
  "WQI": "tramo_wqi.geojson",
27
  "Heatmap pacientes": None
28
  }
29
- ENV_VARS=[k for k in GEO_AMBIENTALES if k not in ("WQI","Heatmap pacientes")]
30
 
31
- # colormaps
32
  META_CAPAS = {
33
- "PM10": ("conc_pm10","Β΅g/mΒ³", branca.colormap.linear.OrRd_09 ,"id" ,"Zona"),
34
- "PM2.5": ("conc_pm25","Β΅g/mΒ³", branca.colormap.linear.Reds_09 ,"id" ,"Zona"),
35
- "Ozono": ("conc_ozono","ppb", branca.colormap.linear.PuBuGn_09,"id" ,"Zona"),
36
- "Temperatura": ("temperatur","Β°C", branca.colormap.linear.YlOrBr_09,"id" ,"Zona"),
37
- "PrecipitaciΓ³n":("precip_per","mm", branca.colormap.linear.Blues_09 ,"id" ,"Zona"),
38
- "Viento": ("velocidad","m/s", branca.colormap.linear.GnBu_09 ,"id" ,"Zona"),
39
- # El colormap para WQI se asigna despuΓ©s de crearlo
40
- "WQI": ("wqi_val","", None ,"tramo","Tramo")
41
  }
42
 
43
  # ─────────────────── cargar pacientes ──────────
@@ -46,332 +47,380 @@ df_all.columns = snake(df_all.columns)
46
 
47
  lat_col = next(c for c in df_all.columns if "residencia" in c and "latitud" in c)
48
  lon_col = next(c for c in df_all.columns if "residencia" in c and "longitud" in c)
49
- df_all = df_all.rename(columns={lat_col:"latitud_raw", lon_col:"longitud_raw"})
50
  df_all["latitud"] = pd.to_numeric(df_all["latitud_raw"].str.replace(",", "."), errors="coerce")
51
  df_all["longitud"] = pd.to_numeric(df_all["longitud_raw"].str.replace(",", "."), errors="coerce")
52
 
53
  # variables categΓ³ricas bΓ‘sicas
54
- for col in ("genero","estrato_socioeconomico"):
55
  df_all[f"{col}_cat"] = sin_dato(df_all.get(col))
56
 
57
  # edad quinquenios
58
- bins=list(range(0,105,5)); age_labels=[f"{b}-{b+4}" for b in bins[:-1]]
59
- df_all["edad"]=pd.to_numeric(df_all.get("edad_en_anos_del_paciente").str.replace(",", "."), errors="coerce")
60
- df_all["edad_cat"]=pd.Categorical(
61
- sin_dato(pd.cut(df_all["edad"],bins=bins,labels=age_labels,right=False).astype(str)),
62
- categories=age_labels+["Sin dato"], ordered=True)
63
-
64
- # ANCA / MPO / PR3 (mantenemos texto original: Positivo/Negativo)
65
- for col in ("ancas","mpo","pr3"):
 
66
  df_all[f"{col.split('s')[0]}_cat"] = sin_dato(df_all.get(col))
67
 
68
- # clΓ­nicos y antecedentes
69
  clin_cols = {
70
  "sindrome_renal": "sindrome_renal_al_ingreso",
71
  "manifestaciones_extrarenales": "manifestaciones_extrarenales",
72
  "proteinuria": "proteinuria",
73
  }
74
- for dst,src in clin_cols.items():
75
  df_all[dst] = sin_dato(df_all.get(src)).str.capitalize()
76
 
77
  df_all["creatinina"] = pd.to_numeric(df_all.get("creatinina").str.replace(",", "."), errors="coerce")
78
 
79
- ante_cols={
80
- "diabetes":"antecedente_personal_de_diabetes",
 
81
  "falla_cardiaca":"antecedente_personal_de_falla_cardiaca",
82
- "epoc":"antecedente_personal_de_epoc",
83
- "hipertension":"antecedente_personal_de_hipertension_arterial",
84
- "vih":"antecedente_personal_de_vih",
85
- "autoinmune":"antecedente_personal_de_otra_enfermedad_autoinmune",
86
- "cancer":"antecedente_personal_de_cancer"
87
  }
88
- resumen_ante={
89
- "Diabetes":"diabetes","Falla cardΓ­aca":"falla_cardiaca","EPOC":"epoc",
90
- "HipertensiΓ³n":"hipertension","VIH":"vih","Enf. autoinmune":"autoinmune","CΓ‘ncer":"cancer"}
91
- for k,col in ante_cols.items():
92
- df_all[k]=np.where(df_all.get(col,"").str.lower().isin(["si","sΓ­","checked","1","positivo"]), "Positivo", "Negativo")
93
-
94
- # biopsia (igual que antes)
95
- bio_raw=[c for c in df_all.columns if c.startswith("hallazgos_histologicos_en_biopsia")]
96
- ren_bio={c:f"bio_{i}" for i,c in enumerate(bio_raw,1)}
97
- df_all=df_all.rename(columns=ren_bio)
98
- BIO_REGEX=[(r"sin_alteraciones$","Sin alteraciones"),
99
- (r"sin_proliferacion_extracapilar","Necrosis sin PC"),
100
- (r"menos_del_50.*focal","Focal"),
101
- (r"clase_mixta","Mixta"),
102
- (r"mas_del_50.*cresc","CrescΓ©ntica"),
103
- (r"sin_compromiso_glomerular$","Vasculitis sin glom."),
104
- (r"con_compromiso_glomerular$","Vasculitis + glom."),
105
- (r"sin_dato$","Sin dato")]
106
- raw2short={next(r for r in bio_raw if re.search(p,r)):s for p,s in BIO_REGEX}
 
 
 
 
 
 
 
 
 
107
 
108
  def hallar(r):
109
- return [raw2short[raw] for raw,flag in ren_bio.items()
110
- if str(r[flag]).strip().lower() in ("si","sΓ­","checked","1","positivo")] or ["Sin dato"]
111
 
112
- df_all["biopsia_patrones"]=df_all.apply(hallar,axis=1)
113
- df_all["biopsia_patron_str"]=df_all["biopsia_patrones"].apply("; ".join)
114
- df_all["biopsia_positiva"]=np.where(df_all["biopsia_patron_str"]=="Sin dato","Negativo","Positivo")
115
 
116
  # ─────────────── localidades ───────────────
117
- geo_loc=gpd.read_file(LOCALIDADES).to_crs(4326)
118
- geo_loc.columns=snake(geo_loc.columns)
119
- geo_loc=geo_loc.rename(columns={"locnombre":"localidad"})
120
- geo_loc["localidad"]=geo_loc["localidad"].str.upper()
121
 
122
- # crear GeoDataFrame de pacientes con geometrΓ­a
123
- geom_pts = df_all.dropna(subset=["latitud","longitud"]).copy()
124
  geom_pts["geometry"] = [Point(xy) for xy in zip(geom_pts["longitud"], geom_pts["latitud"])]
125
- geom_pts = gpd.GeoDataFrame(geom_pts, geometry="geometry", crs=4326)
126
-
127
- # asignar localidad por uniΓ³n espacial
128
- geom_pts = gpd.sjoin(geom_pts, geo_loc[["localidad","geometry"]], how="left", predicate="within").drop(columns="index_right")
129
-
130
- df_all = df_all.merge(geom_pts[["localidad"]], how="left", left_index=True, right_index=True)
131
-
132
 
133
  # ─────────────── capas base ───────────────
134
-
135
- def load_gjson(p):
136
- g=gpd.read_file(p).to_crs(4326); g.columns=snake(g.columns)
137
- # convertir strings numΓ©ricos y fechas a valores serializables
138
  for c in g.columns:
139
- if g[c].dtype==object:
140
- # intentar numΓ©rico
141
- g[c]=pd.to_numeric(g[c].str.strip(),errors="ignore")
142
- if np.issubdtype(g[c].dtype, np.datetime64):
143
- g[c]=g[c].astype(str)
144
  return g
145
 
146
- caps_base={k:load_gjson(v) for k,v in GEO_AMBIENTALES.items() if v}
147
 
148
- # WQI colormap
149
- wqi_bins=[0,20,35,50,70,100]; wqi_labels=["Pobre","Marginal","Regular","Buena","Excelente"]
150
- g_wqi=caps_base["WQI"].copy()
151
- g_wqi["wqi_val"]=pd.to_numeric(g_wqi["wqi"],errors="coerce")
152
- g_wqi["wqi_cat"]=pd.cut(g_wqi["wqi_val"],bins=wqi_bins,labels=wqi_labels,include_lowest=True)
153
- wqi_cmap=branca.colormap.StepColormap(colors=["red","olive","purple","green","blue"],index=wqi_bins,caption="WQI")
154
- caps_base["WQI"]=g_wqi; META_CAPAS["WQI"]=META_CAPAS["WQI"][:2]+(wqi_cmap,)+META_CAPAS["WQI"][3:]
 
 
 
155
 
156
  # ─────────────── filtros ───────────────
157
-
158
- def filtrar(d,gen,edades,locs,renal,ants,bios,anca,mpo,pr3):
159
- d2=d.copy()
160
- if gen!="Todos": d2=d2[d2["genero_cat"]==gen]
161
- if edades: d2=d2[d2["edad_cat"].isin(edades)]
162
- if locs: d2=d2[d2["localidad"].fillna("Sin dato").isin(locs)]
163
- if renal!="Todos": d2=d2[d2["biopsia_positiva"]==renal]
164
- if bios and bios!=["Todos"]:
165
- d2=d2[d2["biopsia_patrones"].apply(lambda lst:any(p in lst for p in bios))]
166
- if anca!="Todos": d2=d2[d2["ancas_cat"]==anca]
167
- if mpo!="Todos": d2=d2[d2["mpo_cat"]==mpo]
168
- if pr3!="Todos": d2=d2[d2["pr3_cat"]==pr3]
169
  for ant in ants:
170
- if ant=="Todos": continue
171
- key=next(k for k,v in resumen_ante.items() if v==ant)
172
- d2=d2[d2[key]=="SΓ­"]
173
  return d2
174
 
175
  # ─────────────── conteos dinΓ‘micos ──────────
176
-
177
  def capas_conteos(pts):
178
- caps={}
179
- for capa,g0 in caps_base.items():
180
- if capa in ("Heatmap pacientes","WQI"):
181
- caps[capa]=g0; continue
182
- g=g0.copy(); g["pacientes"]=0
183
- join=gpd.sjoin(pts[["geometry"]],g,how="left",predicate="within")
184
- counts=join["index_right"].value_counts()
185
- g.loc[counts.index,"pacientes"]=counts.values
186
- caps[capa]=g
 
 
187
  return caps
188
 
189
  # ─────────────── helpers grΓ‘ficos ──────────
190
-
191
  def prep_pts(d):
192
- d2=d.dropna(subset=["latitud","longitud"]).copy()
193
- d2["geometry"]=gpd.points_from_xy(d2["longitud"].astype(float),d2["latitud"].astype(float),crs=4326)
194
- return gpd.GeoDataFrame(d2,geometry="geometry",crs=4326)
195
-
196
- def env_series(var,pts):
197
- g=caps_conteos(pts)[var].copy()
198
- val,uni,*_=META_CAPAS[var]
199
- join=gpd.sjoin(pts[["geometry"]],g[["geometry",val]],how="left",predicate="within")
 
200
  def fmt(r):
201
- if pd.isna(r[val]):
202
- return "Sin dato"
203
  try:
204
- v=float(r[val])
205
  return f"Zona {int(r['index_right'])} ({v:.1f} {uni})"
206
  except Exception:
207
  return str(r[val])
208
- ser=join.apply(fmt,axis=1)
209
- ser.index=pts.index
210
- return ser
211
-
212
- def env_df(var,pts):
213
- g=caps_conteos(pts)[var].copy()
214
- val,uni,*_=META_CAPAS[var]
215
- g["zona"]=g.apply(lambda r:f"Zona {int(r['id'])} ({r[val]:.1f} {uni})",axis=1)
216
- return g[["zona","pacientes"]]
217
 
218
- def is_num(v): return v in NUM_VARS
 
 
 
 
219
 
220
- # ─────────────── univariado ───────────────
221
 
222
- def g_uni(v,d):
 
223
  if v in ENV_VARS:
224
- df=env_df(v,prep_pts(d))
225
- df=df.sort_values("zona")
226
- return px.bar(df,x="zona",y="pacientes",text_auto=True,title=v,labels={"zona":"Zona","pacientes":"Pacientes"})
227
- if v=="Localidad":
228
- s=d["localidad"].fillna("Sin dato")
229
- return px.histogram(s,x=s,category_orders={s.name:sorted(s.unique())},text_auto=True,title="Localidad")
 
230
  if is_num(v):
231
- return px.histogram(d,x=v,nbins=20,title=v)
232
- order=sorted(d[v].astype(str).unique())
233
- return px.histogram(d,x=v,category_orders={v:order},text_auto=True,title=v)
234
-
235
- # ─────────────── bivariado ───────────────
236
-
237
- def g_bi(x,y,d):
238
- pts=prep_pts(d)
239
- if x in ENV_VARS: d=d.assign(**{x:env_series(x,pts)})
240
- if y in ENV_VARS: d=d.assign(**{y:env_series(y,pts)})
241
- num_x,num_y=is_num(x),is_num(y)
242
  if not num_x and not num_y:
243
- ord_x=sorted(map(str,d[x].unique())); ord_y=sorted(map(str,d[y].unique()))
244
- return px.histogram(d,x=x,color=y,barmode="group",category_orders={x:ord_x,y:ord_y},title=f"{x} vs {y}")
 
 
 
245
  if num_x and not num_y:
246
- return px.box(d,x=y,y=x,points="all",title=f"{x} vs {y}")
247
  if not num_x and num_y:
248
- return px.box(d,x=x,y=y,points="all",title=f"{x} vs {y}")
249
- return px.scatter(d,x=x,y=y,title=f"{x} vs {y}")
250
-
251
- # ─────────────── pop-up ───────────────
252
 
 
253
  def popup(r):
254
- lab=lambda k:f"<b>{k}:</b> SΓ­<br>" if r[f"{k.lower()}_cat"].lower()=="positivo" else ""
255
- edad=f"{int(r['edad'])} aΓ±os" if pd.notna(r['edad']) else "Sin dato edad"
256
- ants="; ".join(v for k,v in resumen_ante.items() if r.get(k)=="SΓ­") or "Ninguno"
257
- return (f"<b>Localidad:</b> {r['localidad']}<br><b>Edad:</b> {edad}<br>"
258
- f"<b>GΓ©nero:</b> {r['genero_cat']}<br>{lab('ANCA')}{lab('MPO')}{lab('PR3')}"
 
 
259
  f"<b>Biopsia:</b> {'; '.join(r['biopsia_patrones'])}<br>"
260
  f"<b>Antecedentes:</b> {ants}")
261
 
262
- # ─────────────── choropleth ───────────────
263
-
264
- def choropleth(m,g,val,title,cmap,zfield,zalias):
265
- g=g.copy(); g[val]=pd.to_numeric(g[val],errors="coerce")
266
- # asegurar serializaciΓ³n JSON
267
- for c in g.columns:
268
- if np.issubdtype(g[c].dtype, np.datetime64):
269
- g[c]=g[c].astype(str)
270
- cm=cmap.scale(g[val].min(),g[val].max()) if cmap!=wqi_cmap else cmap
271
- cm.caption=title; cm.add_to(m)
272
- is_line=g.geometry.iloc[0].geom_type.startswith("Line")
273
- style=lambda f,vc=val:({"color":cm(f['properties'][vc]),"weight":4,"opacity":0.9} if is_line else
274
- {"fillColor":cm(f['properties'][vc]),"fillOpacity":0.8,"color":"black","weight":0.3})
275
- fields=[zfield,val]; aliases=[zalias,title]
276
- if "pacientes" in g.columns and val!="pacientes":
 
 
 
277
  fields.append("pacientes"); aliases.append("Pacientes")
278
  if "wqi_cat" in g.columns:
279
- fields.insert(2,"wqi_cat"); aliases.insert(2,"Calidad")
280
- folium.GeoJson(g,name=title,style_function=style,
281
- highlight_function=lambda _:{"weight":2,"color":"#444"},
282
- tooltip=folium.GeoJsonTooltip(fields,aliases,sticky=True)).add_to(m)
283
-
284
- # ─────────────── mapa ───────────────
285
-
286
- def crear_mapa(d_filt,capas_sel,ver_cluster):
287
- pts=prep_pts(d_filt)
288
- caps=capas_conteos(pts)
289
- # base
290
- g_loc=pts.groupby("localidad").size().reset_index(name="pacientes")
291
- geo=geo_loc.merge(g_loc,on="localidad",how="left").fillna({"pacientes":0})
292
- m=folium.Map(location=[4.65,-74.1],zoom_start=11,tiles="CartoDB positron")
293
- choropleth(m,geo,"pacientes","No. Pacientes",branca.colormap.linear.Reds_09,"localidad","Localidad")
 
 
 
 
 
294
  for capa in capas_sel:
295
- if capa=="Heatmap pacientes": continue
296
- if capa=="WQI":
297
- choropleth(m,caps["WQI"],"wqi_val","WQI",wqi_cmap,"tramo","Tramo"); continue
298
- val,uni,cmap,zf,za=META_CAPAS[capa]
299
- choropleth(m,caps[capa],val,f"{capa} ({uni})",cmap,zf,za)
 
 
300
  if "Heatmap pacientes" in capas_sel and not pts.empty:
301
- HeatMap(pts[["latitud","longitud"]].values,radius=18,name="Heatmap pacientes").add_to(m)
302
- fg=folium.FeatureGroup("Pacientes",overlay=True)
303
- for _,r in pts.iterrows():
304
- folium.CircleMarker((r["latitud"],r["longitud"]),radius=6,color="#c00",fill=True,fill_color="#fff",fill_opacity=0.9,popup=popup(r)).add_to(fg)
 
 
 
 
 
 
305
  fg.add_to(m)
306
- if ver_cluster and len(pts)>2:
307
- coords=np.radians(pts[["latitud","longitud"]])
308
- lab=DBSCAN(eps=1/6371,min_samples=3,metric="haversine").fit_predict(coords)
309
- pts["cluster"]=lab
310
- cl_fg=folium.FeatureGroup("ClΓΊsteres (1 km)",overlay=True)
311
- pal=branca.colormap.linear.Set1_09
312
- for cl in sorted(c for c in pts["cluster"].unique() if c!=-1):
313
- color=pal(cl/max(1,pts["cluster"].nunique()-1))
314
- for _,r in pts[pts["cluster"]==cl].iterrows():
315
- folium.CircleMarker((r["latitud"],r["longitud"]),radius=7,color=color,fill=True,fill_color=color,fill_opacity=0.9,popup=f"<b>ClΓΊster {cl}</b><br>"+popup(r)).add_to(cl_fg)
 
 
 
 
 
 
316
  cl_fg.add_to(m)
 
317
  folium.LayerControl(collapsed=False).add_to(m)
318
  return m._repr_html_()
319
 
320
- # ─────────────── interfaz ───────────────
321
-
322
- gen_opts=["Todos"]+sorted(df_all["genero_cat"].unique())
323
- age_opts=list(df_all["edad_cat"].dtype.categories)
324
- loc_opts=sorted(df_all["localidad"].fillna("Sin dato").unique())
325
- anca_opts=["Todos"]+sorted(df_all["ancas_cat"].unique())
326
- mpo_opts=["Todos"]+sorted(df_all["mpo_cat"].unique())
327
- pr3_opts=["Todos"]+sorted(df_all["pr3_cat"].unique())
328
-
329
- vars_cat=["Localidad"]+ENV_VARS+[
330
- "genero_cat","estrato_cat","edad_cat","sindrome_renal",
331
- "manifestaciones_extrarenales","proteinuria",
332
- "ancas_cat","mpo_cat","pr3_cat","biopsia_patron_str"]+list(resumen_ante.values())
333
- vars_all=vars_cat+NUM_VARS
334
 
335
  with gr.Blocks(title="Vasculitis ANCA BogotΓ‘") as demo:
336
  gr.Markdown("## Explorador geoespacial – Vasculitis ANCA (BogotΓ‘)")
337
  with gr.Row():
338
- ui_gen=gr.Dropdown(gen_opts,label="GΓ©nero",value="Todos")
339
- ui_age=gr.CheckboxGroup(age_opts,label="Edad (quinquenios)")
340
- ui_loc =gr.Dropdown(loc_opts,multiselect=True,label="Localidades")
341
- ui_renal =gr.Dropdown(["Todos","SΓ­","No"],value="Todos",label="Biopsia positiva")
342
- ui_ant =gr.CheckboxGroup(["Todos"]+list(resumen_ante.values()),label="Antecedentes")
343
- ui_bio =gr.CheckboxGroup(["Todos"]+list(set(sum(df_all["biopsia_patrones"],[]))),label="PatrΓ³n biopsia")
 
 
344
  with gr.Row():
345
- ui_anca=gr.Dropdown(anca_opts,label="ANCA",value="Todos")
346
- ui_mpo =gr.Dropdown(mpo_opts ,label="MPO" ,value="Todos")
347
- ui_pr3 =gr.Dropdown(pr3_opts ,label="PR3" ,value="Todos")
348
 
349
- ui_capas=gr.CheckboxGroup(list(GEO_AMBIENTALES.keys()),label="Capas mapa")
350
- ui_clu =gr.Checkbox(label="Mostrar clΓΊsteres (1 km)")
351
 
 
352
  with gr.Tab("Mapa"):
353
- btn_map=gr.Button("Generar mapa"); out_map=gr.HTML()
354
- btn_map.click(lambda *i:crear_mapa(filtrar(df_all,*i[:-2]),i[-2],i[-1]),
355
- inputs=[ui_gen,ui_age,ui_loc,ui_renal,
356
- ui_ant,ui_bio,ui_anca,ui_mpo,ui_pr3,
357
- ui_capas,ui_clu],
358
- outputs=out_map)
359
-
 
 
 
360
  with gr.Tab("Univariado"):
361
- ui_var=gr.Dropdown(vars_all,label="Variable"); btn_uni=gr.Button("Graficar"); out_uni=gr.Plot()
362
- btn_uni.click(lambda v,*i:g_uni(v,filtrar(df_all,*i)),
363
- inputs=[ui_var,ui_gen,ui_age,ui_loc,ui_renal,
364
- ui_ant,ui_bio,ui_anca,ui_mpo,ui_pr3],
365
- outputs=out_uni)
366
-
 
 
 
 
367
  with gr.Tab("Bivariado"):
368
- ui_x=gr.Dropdown(vars_all,label="Variable X")
369
- ui_y=gr.Dropdown(vars_all,label="Variable Y")
370
- btn_bi=gr.Button("Graficar"); out_bi=gr.Plot()
371
- btn_bi.click(lambda x,y,*i:g_bi(x,y,filtrar(df_all,*i)),
372
- inputs=[ui_x,ui_y,ui_gen,ui_age,ui_loc,ui_renal,
373
- ui_ant,ui_bio,ui_anca,ui_mpo,ui_pr3],
374
- outputs=out_bi)
375
-
376
- if __name__=="__main__":
 
 
377
  demo.launch(share=False)
 
1
+ # -*- coding: utf-8 -*-
2
  import re, unicodedata, warnings, branca, folium, gradio as gr
3
  import pandas as pd, geopandas as gpd, numpy as np
4
+ from pandas.api.types import is_datetime64_any_dtype # ← correcciΓ³n
5
  from shapely.geometry import Point
6
  from folium.plugins import HeatMap
7
  from sklearn.cluster import DBSCAN
 
10
  warnings.filterwarnings("ignore")
11
 
12
  # ─────────────────── helpers ───────────────────
13
+ norm = lambda t: unicodedata.normalize("NFKD", t).encode("ascii", "ignore").decode()
14
+ snake = lambda cols: [re.sub(r"[^\w]+", "_", norm(c).strip().lower()).strip("_") for c in cols]
15
+ sin_dato = lambda s: s.fillna("Sin dato").replace("", "Sin dato")
16
+ NUM_VARS = ["edad", "creatinina"]
17
 
18
  # ─────────────────── rutas ─────────────────────
19
  DATA_XLSX = "VasculitisAsociadasA-Bdd3_DATA_LABELS_2025-04-16_1949 (1).xlsx"
 
28
  "WQI": "tramo_wqi.geojson",
29
  "Heatmap pacientes": None
30
  }
31
+ ENV_VARS = [k for k in GEO_AMBIENTALES if k not in ("WQI", "Heatmap pacientes")]
32
 
33
+ # colormaps (valor, unidad, cmap, id-field, alias)
34
  META_CAPAS = {
35
+ "PM10": ("conc_pm10", "Β΅g/mΒ³", branca.colormap.linear.OrRd_09, "id", "Zona"),
36
+ "PM2.5": ("conc_pm25", "Β΅g/mΒ³", branca.colormap.linear.Reds_09, "id", "Zona"),
37
+ "Ozono": ("conc_ozono", "ppb", branca.colormap.linear.PuBuGn_09, "id", "Zona"),
38
+ "Temperatura": ("temperatur","Β°C", branca.colormap.linear.YlOrBr_09, "id", "Zona"),
39
+ "PrecipitaciΓ³n":("precip_per","mm", branca.colormap.linear.Blues_09, "id", "Zona"),
40
+ "Viento": ("velocidad", "m/s", branca.colormap.linear.GnBu_09, "id", "Zona"),
41
+ "WQI": ("wqi_val", "", None, "tramo", "Tramo")
 
42
  }
43
 
44
  # ─────────────────── cargar pacientes ──────────
 
47
 
48
  lat_col = next(c for c in df_all.columns if "residencia" in c and "latitud" in c)
49
  lon_col = next(c for c in df_all.columns if "residencia" in c and "longitud" in c)
50
+ df_all = df_all.rename(columns={lat_col: "latitud_raw", lon_col: "longitud_raw"})
51
  df_all["latitud"] = pd.to_numeric(df_all["latitud_raw"].str.replace(",", "."), errors="coerce")
52
  df_all["longitud"] = pd.to_numeric(df_all["longitud_raw"].str.replace(",", "."), errors="coerce")
53
 
54
  # variables categΓ³ricas bΓ‘sicas
55
+ for col in ("genero", "estrato_socioeconomico"):
56
  df_all[f"{col}_cat"] = sin_dato(df_all.get(col))
57
 
58
  # edad quinquenios
59
+ bins = list(range(0, 105, 5))
60
+ age_labels = [f"{b}-{b+4}" for b in bins[:-1]]
61
+ df_all["edad"] = pd.to_numeric(df_all.get("edad_en_anos_del_paciente").str.replace(",", "."), errors="coerce")
62
+ df_all["edad_cat"] = pd.Categorical(
63
+ sin_dato(pd.cut(df_all["edad"], bins=bins, labels=age_labels, right=False).astype(str)),
64
+ categories=age_labels + ["Sin dato"], ordered=True)
65
+
66
+ # ANCA / MPO / PR3 (Positivo / Negativo tal cual)
67
+ for col in ("ancas", "mpo", "pr3"):
68
  df_all[f"{col.split('s')[0]}_cat"] = sin_dato(df_all.get(col))
69
 
70
+ # clΓ­nicos
71
  clin_cols = {
72
  "sindrome_renal": "sindrome_renal_al_ingreso",
73
  "manifestaciones_extrarenales": "manifestaciones_extrarenales",
74
  "proteinuria": "proteinuria",
75
  }
76
+ for dst, src in clin_cols.items():
77
  df_all[dst] = sin_dato(df_all.get(src)).str.capitalize()
78
 
79
  df_all["creatinina"] = pd.to_numeric(df_all.get("creatinina").str.replace(",", "."), errors="coerce")
80
 
81
+ # antecedentes β†’ Positivo / Negativo
82
+ ante_cols = {
83
+ "diabetes": "antecedente_personal_de_diabetes",
84
  "falla_cardiaca":"antecedente_personal_de_falla_cardiaca",
85
+ "epoc": "antecedente_personal_de_epoc",
86
+ "hipertension": "antecedente_personal_de_hipertension_arterial",
87
+ "vih": "antecedente_personal_de_vih",
88
+ "autoinmune": "antecedente_personal_de_otra_enfermedad_autoinmune",
89
+ "cancer": "antecedente_personal_de_cancer"
90
  }
91
+ resumen_ante = {
92
+ "Diabetes": "diabetes",
93
+ "Falla cardΓ­aca": "falla_cardiaca",
94
+ "EPOC": "epoc",
95
+ "HipertensiΓ³n": "hipertension",
96
+ "VIH": "vih",
97
+ "Enf. autoinmune": "autoinmune",
98
+ "CΓ‘ncer": "cancer"
99
+ }
100
+ for k, col in ante_cols.items():
101
+ df_all[k] = np.where(df_all.get(col, "").str.lower().isin(
102
+ ["si", "sΓ­", "checked", "1", "positivo"]), "Positivo", "Negativo")
103
+
104
+ # biopsia
105
+ bio_raw = [c for c in df_all.columns if c.startswith("hallazgos_histologicos_en_biopsia")]
106
+ ren_bio = {c: f"bio_{i}" for i, c in enumerate(bio_raw, 1)}
107
+ df_all = df_all.rename(columns=ren_bio)
108
+ BIO_REGEX = [
109
+ (r"sin_alteraciones$", "Sin alteraciones"),
110
+ (r"sin_proliferacion_extracapilar", "Necrosis sin PC"),
111
+ (r"menos_del_50.*focal", "Focal"),
112
+ (r"clase_mixta", "Mixta"),
113
+ (r"mas_del_50.*cresc", "CrescΓ©ntica"),
114
+ (r"sin_compromiso_glomerular$", "Vasculitis sin glom."),
115
+ (r"con_compromiso_glomerular$", "Vasculitis + glom."),
116
+ (r"sin_dato$", "Sin dato")
117
+ ]
118
+ raw2short = {next(r for r in bio_raw if re.search(p, r)): s for p, s in BIO_REGEX}
119
 
120
  def hallar(r):
121
+ return [raw2short[raw] for raw, flag in ren_bio.items()
122
+ if str(r[flag]).strip().lower() in ("si", "sΓ­", "checked", "1", "positivo")] or ["Sin dato"]
123
 
124
+ df_all["biopsia_patrones"] = df_all.apply(hallar, axis=1)
125
+ df_all["biopsia_patron_str"] = df_all["biopsia_patrones"].apply("; ".join)
126
+ df_all["biopsia_positiva"] = np.where(df_all["biopsia_patron_str"] == "Sin dato", "Negativo", "Positivo")
127
 
128
  # ─────────────── localidades ───────────────
129
+ geo_loc = gpd.read_file(LOCALIDADES).to_crs(4326)
130
+ geo_loc.columns = snake(geo_loc.columns)
131
+ geo_loc = geo_loc.rename(columns={"locnombre": "localidad"})
132
+ geo_loc["localidad"] = geo_loc["localidad"].str.upper()
133
 
134
+ # puntos de pacientes
135
+ geom_pts = df_all.dropna(subset=["latitud", "longitud"]).copy()
136
  geom_pts["geometry"] = [Point(xy) for xy in zip(geom_pts["longitud"], geom_pts["latitud"])]
137
+ geom_pts = gpd.GeoDataFrame(geom_pts, geometry="geometry", crs=4326)
138
+ geom_pts = gpd.sjoin(
139
+ geom_pts, geo_loc[["localidad", "geometry"]], how="left",
140
+ predicate="within").drop(columns="index_right")
141
+ df_all = df_all.merge(geom_pts[["localidad"]], left_index=True, right_index=True, how="left")
 
 
142
 
143
  # ─────────────── capas base ───────────────
144
+ def load_gjson(pth):
145
+ g = gpd.read_file(pth).to_crs(4326)
146
+ g.columns = snake(g.columns)
 
147
  for c in g.columns:
148
+ if g[c].dtype == object:
149
+ g[c] = pd.to_numeric(g[c].str.strip(), errors="ignore")
150
+ if is_datetime64_any_dtype(g[c]): # ← correcciΓ³n fechas con tz
151
+ g[c] = g[c].astype(str)
 
152
  return g
153
 
154
+ caps_base = {k: load_gjson(v) for k, v in GEO_AMBIENTALES.items() if v}
155
 
156
+ # WQI
157
+ wqi_bins = [0, 20, 35, 50, 70, 100]
158
+ wqi_labels = ["Pobre", "Marginal", "Regular", "Buena", "Excelente"]
159
+ g_wqi = caps_base["WQI"].copy()
160
+ g_wqi["wqi_val"] = pd.to_numeric(g_wqi["wqi"], errors="coerce")
161
+ g_wqi["wqi_cat"] = pd.cut(g_wqi["wqi_val"], bins=wqi_bins, labels=wqi_labels, include_lowest=True)
162
+ wqi_cmap = branca.colormap.StepColormap(colors=["red", "olive", "purple", "green", "blue"],
163
+ index=wqi_bins, caption="WQI")
164
+ caps_base["WQI"] = g_wqi
165
+ META_CAPAS["WQI"] = META_CAPAS["WQI"][:2] + (wqi_cmap,) + META_CAPAS["WQI"][3:]
166
 
167
  # ─────────────── filtros ───────────────
168
+ def filtrar(d, gen, edades, locs, renal, ants, bios, anca, mpo, pr3):
169
+ d2 = d.copy()
170
+ if gen != "Todos": d2 = d2[d2["genero_cat"] == gen]
171
+ if edades: d2 = d2[d2["edad_cat"].isin(edades)]
172
+ if locs: d2 = d2[d2["localidad"].fillna("Sin dato").isin(locs)]
173
+ if renal != "Todos": d2 = d2[d2["biopsia_positiva"] == renal]
174
+ if bios and bios != ["Todos"]:
175
+ d2 = d2[d2["biopsia_patrones"].apply(lambda lst: any(p in lst for p in bios))]
176
+ if anca != "Todos": d2 = d2[d2["anca_cat"] == anca]
177
+ if mpo != "Todos": d2 = d2[d2["mpo_cat"] == mpo]
178
+ if pr3 != "Todos": d2 = d2[d2["pr3_cat"] == pr3]
 
179
  for ant in ants:
180
+ if ant == "Todos": continue
181
+ key = resumen_ante[ant]
182
+ d2 = d2[d2[key] == "Positivo"] # ← correcciΓ³n
183
  return d2
184
 
185
  # ─────────────── conteos dinΓ‘micos ──────────
 
186
  def capas_conteos(pts):
187
+ caps = {}
188
+ for capa, g0 in caps_base.items():
189
+ if capa in ("Heatmap pacientes", "WQI"):
190
+ caps[capa] = g0
191
+ continue
192
+ g = g0.copy()
193
+ g["pacientes"] = 0
194
+ join = gpd.sjoin(pts[["geometry"]], g, how="left", predicate="within")
195
+ counts = join["index_right"].value_counts()
196
+ g.loc[counts.index, "pacientes"] = counts.values
197
+ caps[capa] = g
198
  return caps
199
 
200
  # ─────────────── helpers grΓ‘ficos ──────────
 
201
  def prep_pts(d):
202
+ d2 = d.dropna(subset=["latitud", "longitud"]).copy()
203
+ d2["geometry"] = gpd.points_from_xy(d2["longitud"].astype(float),
204
+ d2["latitud"].astype(float), crs=4326)
205
+ return gpd.GeoDataFrame(d2, geometry="geometry", crs=4326)
206
+
207
+ def env_series(var, pts):
208
+ g = capas_conteos(pts)[var]
209
+ val, uni, *_ = META_CAPAS[var]
210
+ join = gpd.sjoin(pts[["geometry"]], g[["geometry", val]], how="left", predicate="within")
211
  def fmt(r):
212
+ if pd.isna(r[val]): return "Sin dato"
 
213
  try:
214
+ v = float(r[val])
215
  return f"Zona {int(r['index_right'])} ({v:.1f} {uni})"
216
  except Exception:
217
  return str(r[val])
218
+ out = join.apply(fmt, axis=1)
219
+ out.index = pts.index
220
+ return out
 
 
 
 
 
 
221
 
222
+ def env_df(var, pts):
223
+ g = capas_conteos(pts)[var]
224
+ val, uni, *_ = META_CAPAS[var]
225
+ g["zona"] = g.apply(lambda r: f"Zona {int(r['id'])} ({r[val]:.1f} {uni})", axis=1)
226
+ return g[["zona", "pacientes"]]
227
 
228
+ is_num = lambda v: v in NUM_VARS
229
 
230
+ # ─────────────── grΓ‘ficos univariados ──────
231
+ def g_uni(v, d):
232
  if v in ENV_VARS:
233
+ df = env_df(v, prep_pts(d)).sort_values("zona")
234
+ return px.bar(df, x="zona", y="pacientes", text_auto=True, title=v,
235
+ labels={"zona": "Zona", "pacientes": "Pacientes"})
236
+ if v == "Localidad":
237
+ s = d["localidad"].fillna("Sin dato")
238
+ return px.histogram(s, x=s, category_orders={s.name: sorted(s.unique())},
239
+ text_auto=True, title="Localidad")
240
  if is_num(v):
241
+ return px.histogram(d, x=v, nbins=20, title=v)
242
+ order = sorted(d[v].astype(str).unique())
243
+ return px.histogram(d, x=v, category_orders={v: order},
244
+ text_auto=True, title=v)
245
+
246
+ # ─────────────── grΓ‘ficos bivariados ───────
247
+ def g_bi(x, y, d):
248
+ pts = prep_pts(d)
249
+ if x in ENV_VARS: d = d.assign(**{x: env_series(x, pts)})
250
+ if y in ENV_VARS: d = d.assign(**{y: env_series(y, pts)})
251
+ num_x, num_y = is_num(x), is_num(y)
252
  if not num_x and not num_y:
253
+ ord_x = sorted(map(str, d[x].unique()))
254
+ ord_y = sorted(map(str, d[y].unique()))
255
+ return px.histogram(d, x=x, color=y, barmode="group",
256
+ category_orders={x: ord_x, y: ord_y},
257
+ title=f"{x} vs {y}")
258
  if num_x and not num_y:
259
+ return px.box(d, x=y, y=x, points="all", title=f"{x} vs {y}")
260
  if not num_x and num_y:
261
+ return px.box(d, x=x, y=y, points="all", title=f"{x} vs {y}")
262
+ return px.scatter(d, x=x, y=y, title=f"{x} vs {y}")
 
 
263
 
264
+ # ─────────────── pop-up de paciente ─────────
265
  def popup(r):
266
+ lab = lambda k: f"<b>{k}:</b> Positivo<br>" if r[f"{k.lower()}_cat"].lower() == "positivo" else ""
267
+ edad = f"{int(r['edad'])} aΓ±os" if pd.notna(r['edad']) else "Sin dato edad"
268
+ ants = "; ".join(lbl for lbl, key in resumen_ante.items() if r.get(key) == "Positivo") or "Ninguno"
269
+ return (f"<b>Localidad:</b> {r['localidad']}<br>"
270
+ f"<b>Edad:</b> {edad}<br>"
271
+ f"<b>GΓ©nero:</b> {r['genero_cat']}<br>"
272
+ f"{lab('ANCA')}{lab('MPO')}{lab('PR3')}"
273
  f"<b>Biopsia:</b> {'; '.join(r['biopsia_patrones'])}<br>"
274
  f"<b>Antecedentes:</b> {ants}")
275
 
276
+ # ─────────────── choropleth ────────────────
277
+ def choropleth(m, g, val, title, cmap, zfield, zalias):
278
+ g = g.copy()
279
+ g[val] = pd.to_numeric(g[val], errors="coerce")
280
+ for c in g.columns: # asegurar serializaciΓ³n
281
+ if is_datetime64_any_dtype(g[c]):
282
+ g[c] = g[c].astype(str)
283
+ cm = cmap.scale(g[val].min(), g[val].max()) if cmap is not wqi_cmap else cmap
284
+ cm.caption = title
285
+ cm.add_to(m)
286
+ is_line = g.geometry.iloc[0].geom_type.startswith("Line")
287
+ style = (lambda f, vc=val:
288
+ {"color": cm(f['properties'][vc]), "weight": 4, "opacity": .9} if is_line else
289
+ {"fillColor": cm(f['properties'][vc]), "fillOpacity": .8,
290
+ "color": "black", "weight": .3})
291
+ fields = [zfield, val]
292
+ aliases = [zalias, title]
293
+ if "pacientes" in g.columns and val != "pacientes":
294
  fields.append("pacientes"); aliases.append("Pacientes")
295
  if "wqi_cat" in g.columns:
296
+ fields.insert(2, "wqi_cat"); aliases.insert(2, "Calidad")
297
+ folium.GeoJson(
298
+ g, name=title, style_function=style,
299
+ highlight_function=lambda _: {"weight": 2, "color": "#444"},
300
+ tooltip=folium.GeoJsonTooltip(fields, aliases, sticky=True)
301
+ ).add_to(m)
302
+
303
+ # ─────────────── mapa ───────────────────────
304
+ def crear_mapa(d_filt, capas_sel, ver_cluster):
305
+ pts = prep_pts(d_filt)
306
+ caps = capas_conteos(pts)
307
+
308
+ # base localidades
309
+ g_loc = pts.groupby("localidad").size().reset_index(name="pacientes")
310
+ geo = geo_loc.merge(g_loc, on="localidad", how="left").fillna({"pacientes": 0})
311
+
312
+ m = folium.Map(location=[4.65, -74.1], zoom_start=11, tiles="CartoDB positron")
313
+ choropleth(m, geo, "pacientes", "No. Pacientes",
314
+ branca.colormap.linear.Reds_09, "localidad", "Localidad")
315
+
316
  for capa in capas_sel:
317
+ if capa == "Heatmap pacientes": continue
318
+ if capa == "WQI":
319
+ choropleth(m, caps["WQI"], "wqi_val", "WQI", wqi_cmap, "tramo", "Tramo")
320
+ continue
321
+ val, uni, cmap, zf, za = META_CAPAS[capa]
322
+ choropleth(m, caps[capa], val, f"{capa} ({uni})", cmap, zf, za)
323
+
324
  if "Heatmap pacientes" in capas_sel and not pts.empty:
325
+ HeatMap(pts[["latitud", "longitud"]].values, radius=18,
326
+ name="Heatmap pacientes").add_to(m)
327
+
328
+ fg = folium.FeatureGroup("Pacientes", overlay=True)
329
+ for _, r in pts.iterrows():
330
+ folium.CircleMarker(
331
+ (r["latitud"], r["longitud"]), radius=6, color="#c00",
332
+ fill=True, fill_color="#fff", fill_opacity=.9,
333
+ popup=popup(r)
334
+ ).add_to(fg)
335
  fg.add_to(m)
336
+
337
+ # clΓΊsteres
338
+ if ver_cluster and len(pts) > 2:
339
+ coords = np.radians(pts[["latitud", "longitud"]])
340
+ lab = DBSCAN(eps=1/6371, min_samples=3, metric="haversine").fit_predict(coords)
341
+ pts["cluster"] = lab
342
+ cl_fg = folium.FeatureGroup("ClΓΊsteres (1 km)", overlay=True)
343
+ pal = branca.colormap.linear.Set1_09
344
+ for cl in sorted(c for c in pts["cluster"].unique() if c != -1):
345
+ color = pal(cl / max(1, pts["cluster"].nunique() - 1))
346
+ for _, r in pts[pts["cluster"] == cl].iterrows():
347
+ folium.CircleMarker(
348
+ (r["latitud"], r["longitud"]), radius=7, color=color,
349
+ fill=True, fill_color=color, fill_opacity=.9,
350
+ popup=f"<b>ClΓΊster {cl}</b><br>"+popup(r)
351
+ ).add_to(cl_fg)
352
  cl_fg.add_to(m)
353
+
354
  folium.LayerControl(collapsed=False).add_to(m)
355
  return m._repr_html_()
356
 
357
+ # ─────────────── interfaz ───────────────────
358
+ gen_opts = ["Todos"] + sorted(df_all["genero_cat"].unique())
359
+ age_opts = list(df_all["edad_cat"].dtype.categories)
360
+ loc_opts = sorted(df_all["localidad"].fillna("Sin dato").unique())
361
+ anca_opts = ["Todos"] + sorted(df_all["anca_cat"].unique())
362
+ mpo_opts = ["Todos"] + sorted(df_all["mpo_cat"].unique())
363
+ pr3_opts = ["Todos"] + sorted(df_all["pr3_cat"].unique())
364
+
365
+ vars_cat = ["Localidad"] + ENV_VARS + [
366
+ "genero_cat", "estrato_cat", "edad_cat", "sindrome_renal",
367
+ "manifestaciones_extrarenales", "proteinuria",
368
+ "anca_cat", "mpo_cat", "pr3_cat", "biopsia_patron_str"
369
+ ] + list(resumen_ante.keys())
370
+ vars_all = vars_cat + NUM_VARS
371
 
372
  with gr.Blocks(title="Vasculitis ANCA BogotΓ‘") as demo:
373
  gr.Markdown("## Explorador geoespacial – Vasculitis ANCA (BogotΓ‘)")
374
  with gr.Row():
375
+ ui_gen = gr.Dropdown(gen_opts, label="GΓ©nero", value="Todos")
376
+ ui_age = gr.CheckboxGroup(age_opts, label="Edad (quinquenios)")
377
+ ui_loc = gr.Dropdown(loc_opts, multiselect=True, label="Localidades")
378
+ ui_renal = gr.Dropdown(["Todos", "Positivo", "Negativo"],
379
+ value="Todos", label="Biopsia positiva")
380
+ ui_ant = gr.CheckboxGroup(["Todos"] + list(resumen_ante.keys()), label="Antecedentes")
381
+ ui_bio = gr.CheckboxGroup(["Todos"] + sorted(set(sum(df_all["biopsia_patrones"], []))),
382
+ label="PatrΓ³n biopsia")
383
  with gr.Row():
384
+ ui_anca = gr.Dropdown(anca_opts, label="ANCA", value="Todos")
385
+ ui_mpo = gr.Dropdown(mpo_opts, label="MPO", value="Todos")
386
+ ui_pr3 = gr.Dropdown(pr3_opts, label="PR3", value="Todos")
387
 
388
+ ui_capas = gr.CheckboxGroup(list(GEO_AMBIENTALES.keys()), label="Capas mapa")
389
+ ui_clu = gr.Checkbox(label="Mostrar clΓΊsteres (1 km)")
390
 
391
+ # --- mapa ---
392
  with gr.Tab("Mapa"):
393
+ btn_map = gr.Button("Generar mapa")
394
+ out_map = gr.HTML()
395
+ btn_map.click(
396
+ lambda *i: crear_mapa(filtrar(df_all, *i[:-2]), i[-2], i[-1]),
397
+ inputs=[ui_gen, ui_age, ui_loc, ui_renal,
398
+ ui_ant, ui_bio, ui_anca, ui_mpo, ui_pr3,
399
+ ui_capas, ui_clu],
400
+ outputs=out_map)
401
+
402
+ # --- univariado ---
403
  with gr.Tab("Univariado"):
404
+ ui_var = gr.Dropdown(vars_all, label="Variable")
405
+ btn_uni = gr.Button("Graficar")
406
+ out_uni = gr.Plot()
407
+ btn_uni.click(
408
+ lambda v, *i: g_uni(v, filtrar(df_all, *i)),
409
+ inputs=[ui_var, ui_gen, ui_age, ui_loc, ui_renal,
410
+ ui_ant, ui_bio, ui_anca, ui_mpo, ui_pr3],
411
+ outputs=out_uni)
412
+
413
+ # --- bivariado ---
414
  with gr.Tab("Bivariado"):
415
+ ui_x = gr.Dropdown(vars_all, label="Variable X")
416
+ ui_y = gr.Dropdown(vars_all, label="Variable Y")
417
+ btn_bi = gr.Button("Graficar")
418
+ out_bi = gr.Plot()
419
+ btn_bi.click(
420
+ lambda x, y, *i: g_bi(x, y, filtrar(df_all, *i)),
421
+ inputs=[ui_x, ui_y, ui_gen, ui_age, ui_loc, ui_renal,
422
+ ui_ant, ui_bio, ui_anca, ui_mpo, ui_pr3],
423
+ outputs=out_bi)
424
+
425
+ if __name__ == "__main__":
426
  demo.launch(share=False)