hedtorresca commited on
Commit
da783e2
Β·
verified Β·
1 Parent(s): cd2e77c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +301 -337
app.py CHANGED
@@ -1,6 +1,16 @@
 
 
 
 
 
 
 
 
 
1
  import re
2
  import unicodedata
3
  import warnings
 
4
 
5
  import branca
6
  import folium
@@ -15,60 +25,75 @@ import geopandas as gpd
15
 
16
  warnings.filterwarnings("ignore")
17
 
18
- # ─────────────────── helpers ───────────────────
19
- _norm = lambda t: unicodedata.normalize("NFKD", t).encode("ascii", "ignore").decode()
20
- snake = lambda cols: [re.sub(r"[^\w]+", "_", _norm(c).strip().lower()).strip("_") for c in cols]
 
 
 
 
 
21
  sin_dato = lambda s: s.fillna("Sin dato").replace("", "Sin dato")
 
22
  NUM_VARS = ["edad", "creatinina"]
23
 
24
- # ─────────────────── rutas ─────────────────────
25
- DATA_XLSX = "VasculitisAsociadasA-Bdd3_DATA_LABELS_2025-04-16_1949 (1).xlsx"
 
 
26
  LOCALIDADES = "loca.json"
27
  GEO_AMBIENTALES = {
28
- "PM10": "pm10_prom_anual.geojson", # solo mapa
29
- "PM2.5": "pm25_prom_anual_2023 (2).geojson",
30
- "Ozono": "ozono_prom_anual_2022 (2).geojson",
31
- "Temperatura": "temp_anualprom_2023 (2).geojson",
32
  "PrecipitaciΓ³n": "precip_anualacum_2023 (2).geojson",
33
- "Viento": "vel_viento_0_23h_anual_2023.geojson",
34
- "WQI": "tramo_wqi.geojson",
35
- "Heatmap pacientes": None,
36
  }
37
 
38
- # variables ambientales que SÍ entran en grÑficos
39
  ENV_VARS = [k for k in GEO_AMBIENTALES if k not in ("WQI", "Heatmap pacientes", "PM10")]
40
 
41
- # colormaps meta
42
  META_CAPAS = {
43
- "PM10": ("conc_pm10", "Β΅g/mΒ³", branca.colormap.linear.OrRd_09, "id", "Zona"),
44
- "PM2.5": ("conc_pm25", "Β΅g/mΒ³", branca.colormap.linear.Reds_09, "id", "Zona"),
45
- "Ozono": ("conc_ozono", "ppb", branca.colormap.linear.PuBuGn_09, "id", "Zona"),
46
- "Temperatura": ("temperatur", "Β°C", branca.colormap.linear.YlOrBr_09, "id", "Zona"),
47
- "PrecipitaciΓ³n": ("precip_per", "mm", branca.colormap.linear.Blues_09, "id", "Zona"),
48
- "Viento": ("velocidad", "m/s", branca.colormap.linear.GnBu_09, "id", "Zona"),
49
- "WQI": ("wqi_val", "", None, "tramo", "Tramo"), # cmap se asigna luego
50
  }
51
 
52
- # ─────────────────── cargar pacientes ──────────
 
 
 
53
  df_all = pd.read_excel(DATA_XLSX, dtype=str)
54
  df_all.columns = snake(df_all.columns)
55
 
56
- lat_col = next(c for c in df_all.columns if "residencia" in c and "latitud" in c)
57
- lon_col = next(c for c in df_all.columns if "residencia" in c and "longitud" in c)
 
58
 
59
  df_all = df_all.rename(columns={lat_col: "latitud_raw", lon_col: "longitud_raw"})
60
- df_all["latitud"] = pd.to_numeric(df_all["latitud_raw"].str.replace(",", "."), errors="coerce")
61
  df_all["longitud"] = pd.to_numeric(df_all["longitud_raw"].str.replace(",", "."), errors="coerce")
62
 
63
  # variables categΓ³ricas bΓ‘sicas
64
- df_all["genero_cat"] = sin_dato(df_all.get("genero"))
65
  df_all["estrato_socioeconomico_cat"] = sin_dato(df_all.get("estrato_socioeconomico"))
66
 
67
- # edad quinquenios
68
- bins = list(range(0, 105, 5))
69
  age_labels = [f"{b}-{b+4}" for b in bins[:-1]]
70
 
71
- df_all["edad"] = pd.to_numeric(df_all.get("edad_en_anos_del_paciente").str.replace(",", "."), errors="coerce")
 
 
 
72
  df_all["edad_cat"] = pd.Categorical(
73
  sin_dato(pd.cut(df_all["edad"], bins=bins, labels=age_labels, right=False).astype(str)),
74
  categories=age_labels + ["Sin dato"],
@@ -76,83 +101,98 @@ df_all["edad_cat"] = pd.Categorical(
76
  )
77
 
78
  # ANCA / MPO / PR3
79
- do_map = {"ancas": "anca_cat", "mpo": "mpo_cat", "pr3": "pr3_cat"}
80
- for src, dst in do_map.items():
81
  df_all[dst] = sin_dato(df_all.get(src))
82
 
83
- # clΓ­nicos y antecedentes bΓ‘sicos
84
- clin_cols = {
85
- "sindrome_renal": "sindrome_renal_al_ingreso",
86
- "manifestaciones_extrarenales": "manifestaciones_extrarenales",
87
- "proteinuria": "proteinuria",
88
  }
89
- for dst, src in clin_cols.items():
90
  df_all[dst] = sin_dato(df_all.get(src)).str.capitalize()
91
 
92
  df_all["creatinina"] = pd.to_numeric(df_all.get("creatinina").str.replace(",", "."), errors="coerce")
93
 
94
  ANT_COLS_HUMAN = {
95
- "Diabetes": "antecedente_personal_de_diabetes",
96
- "Falla cardΓ­aca": "antecedente_personal_de_falla_cardiaca",
97
- "EPOC": "antecedente_personal_de_epoc",
98
- "HipertensiΓ³n": "antecedente_personal_de_hipertension_arterial",
99
- "VIH": "antecedente_personal_de_vih",
100
- "Enf. autoinmune": "antecedente_personal_de_otra_enfermedad_autoinmune",
101
- "CΓ‘ncer": "antecedente_personal_de_cancer",
102
  }
103
-
104
  for lbl, raw in ANT_COLS_HUMAN.items():
105
- col = snake([lbl])[0] # creates diabetes, falla_cardiaca, etc.
106
- df_all[col] = np.where(df_all.get(raw, "").str.lower().isin(["si", "sΓ­", "checked", "1", "positivo"]),
107
- "Positivo", "Negativo")
108
- ANT_COLS_HUMAN[lbl] = col # store cleaned name
109
-
110
- # biopsia
111
- aux = [c for c in df_all.columns if c.startswith("hallazgos_histologicos_en_biopsia")]
112
- ren_bio = {c: f"bio_{i}" for i, c in enumerate(aux, 1)}
113
- df_all = df_all.rename(columns=ren_bio)
 
 
114
  BIO_REGEX = [
115
- (r"sin_alteraciones$", "Sin alteraciones"),
116
- (r"sin_proliferacion_extracapilar", "Necrosis sin PC"),
117
- (r"menos_del_50.*focal", "Focal"),
118
- (r"clase_mixta", "Mixta"),
119
- (r"mas_del_50.*cresc", "CrescΓ©ntica"),
120
- (r"sin_compromiso_glomerular$", "Vasculitis sin glom."),
121
- (r"con_compromiso_glomerular$", "Vasculitis + glom."),
122
- (r"sin_dato$", "Sin dato"),
123
  ]
124
- raw2short = {next(r for r in aux if re.search(p, r)): s for p, s in BIO_REGEX}
125
-
126
-
127
- def _hallar(r):
128
- out = [raw2short[raw] for raw, flag in ren_bio.items() if str(r[flag]).strip().lower() in
129
- ("si", "sΓ­", "checked", "1", "positivo")]
130
- return out or ["Sin dato"]
131
-
132
-
133
- df_all["biopsia_patrones"] = df_all.apply(_hallar, axis=1)
134
- df_all["biopsia_patron_str"] = df_all["biopsia_patrones"].apply("; ".join)
135
- df_all["biopsia_positiva"] = np.where(df_all["biopsia_patron_str"] == "Sin dato", "Negativo", "Positivo")
 
136
 
137
- # ─────────────── localidades ───────────────
 
 
 
138
  geo_loc = gpd.read_file(LOCALIDADES).to_crs(4326)
139
  geo_loc.columns = snake(geo_loc.columns)
140
- geo_loc = geo_loc.rename(columns={"locnombre": "localidad"})
141
  geo_loc["localidad"] = geo_loc["localidad"].str.upper()
142
 
143
- # puntos
144
- pts_raw = df_all.dropna(subset=["latitud", "longitud"]).copy()
 
 
145
  pts_raw["geometry"] = [Point(xy) for xy in zip(pts_raw["longitud"], pts_raw["latitud"])]
146
  pts_raw = gpd.GeoDataFrame(pts_raw, geometry="geometry", crs=4326)
147
- pts_raw = gpd.sjoin(pts_raw, geo_loc[["localidad", "geometry"]], how="left", predicate="within").drop(
148
- columns="index_right")
149
-
150
- # unir columna localidad calculada
151
- df_all = df_all.merge(pts_raw[["localidad"]], how="left", left_index=True, right_index=True)
152
 
153
- # ─────────────── capas base ───────────────
 
 
 
 
 
 
 
 
 
 
 
154
 
155
- def load_gjson(path):
 
 
 
156
  g = gpd.read_file(path).to_crs(4326)
157
  g.columns = snake(g.columns)
158
  for c in g.columns:
@@ -162,290 +202,214 @@ def load_gjson(path):
162
  g[c] = g[c].astype(str)
163
  return g
164
 
165
- caps_base = {k: load_gjson(v) for k, v in GEO_AMBIENTALES.items() if v}
 
166
 
167
- # WQI
168
- wqi_bins = [0, 20, 35, 50, 70, 100]
169
- wqi_labels = ["Pobre", "Marginal", "Regular", "Buena", "Excelente"]
170
- _gw = caps_base["WQI"].copy()
171
  _gw["wqi_val"] = pd.to_numeric(_gw["wqi"], errors="coerce")
172
  _gw["wqi_cat"] = pd.cut(_gw["wqi_val"], bins=wqi_bins, labels=wqi_labels, include_lowest=True)
173
- wqi_cmap = branca.colormap.StepColormap(colors=["red", "olive", "purple", "green", "blue"],
174
- index=wqi_bins, caption="WQI")
 
 
 
175
  caps_base["WQI"] = _gw
176
  META_CAPAS["WQI"] = (*META_CAPAS["WQI"][:2], wqi_cmap, *META_CAPAS["WQI"][3:])
177
 
178
- # ─────────────── filtros ───────────────
179
-
180
- def filtrar(d, gen, edades, locs, renal, ants, bios, anca, mpo, pr3):
181
- d2 = d.copy()
 
182
  if gen != "Todos":
183
- d2 = d2[d2["genero_cat"] == gen]
184
  if edades:
185
- d2 = d2[d2["edad_cat"].isin(edades)]
186
  if locs:
187
- d2 = d2[d2["localidad"].fillna("Sin dato").isin(locs)]
188
  if renal != "Todos":
189
- d2 = d2[d2["biopsia_positiva"] == renal]
190
  if bios and bios != ["Todos"]:
191
- d2 = d2[d2["biopsia_patrones"].apply(lambda lst: any(p in lst for p in bios))]
192
  if anca != "Todos":
193
- d2 = d2[d2["anca_cat"] == anca]
194
  if mpo != "Todos":
195
- d2 = d2[d2["mpo_cat"] == mpo]
196
  if pr3 != "Todos":
197
- d2 = d2[d2["pr3_cat"] == pr3]
 
198
  for ant in ants:
199
- if ant == "Todos":
200
- continue
201
  col = ANT_COLS_HUMAN[ant]
202
- d2 = d2[d2[col] == "Positivo"]
203
- return d2
204
-
205
- # ─────────────── conteos dinΓ‘micos ──────────
206
-
207
- def capas_conteos(pts):
208
- out = {}
 
209
  for capa, g0 in caps_base.items():
210
- if capa in ("Heatmap pacientes", "WQI"):
211
- out[capa] = g0
212
  continue
213
- g = g0.copy()
214
  g["pacientes"] = 0
215
- j = gpd.sjoin(pts[["geometry"]], g, how="left", predicate="within")
216
- counts = j["index_right"].value_counts()
217
  g.loc[counts.index, "pacientes"] = counts.values
218
- out[capa] = g
219
- return out
220
-
221
- # ─────────────── helpers grΓ‘ficos ──────────
222
-
223
- def prep_pts(d):
224
- d2 = d.dropna(subset=["latitud", "longitud"]).copy()
225
- d2["geometry"] = gpd.points_from_xy(d2["longitud"].astype(float), d2["latitud"].astype(float), crs=4326)
226
- return gpd.GeoDataFrame(d2, geometry="geometry", crs=4326)
227
-
228
-
229
- def env_series(var, pts):
230
- g = capas_conteos(pts)[var].copy()
231
- val, uni, *_ = META_CAPAS[var]
232
- j = gpd.sjoin(pts[["geometry"]], g[["geometry", val]], how="left", predicate="within")
233
-
234
- def _fmt(r):
235
- if pd.isna(r[val]):
236
- return "Sin dato"
237
- try:
238
- v = float(r[val])
239
- return f"Zona {int(r['index_right'])} ({v:.1f} {uni})"
240
- except Exception:
241
- return str(r[val])
242
-
243
- ser = j.apply(_fmt, axis=1)
244
- ser.index = j.index # garantiza mismo tamaΓ±o
245
- return ser
246
-
247
-
248
- def env_df(var, pts):
249
- g = capas_conteos(pts)[var].copy()
250
- val, uni, *_ = META_CAPAS[var]
251
- g["zona"] = g.apply(lambda r: f"Zona {int(r['id'])} ({r[val]:.1f} {uni})", axis=1)
252
- return g[["zona", "pacientes"]]
253
-
254
- is_num = lambda v: v in NUM_VARS
255
- DISPLAY_MAP = {"Localidad": "localidad", "Estrato": "estrato_socioeconomico_cat", **ANT_COLS_HUMAN}
256
-
257
- # ─────────────── univariado ───────────────
258
-
259
- def g_uni(v, d):
260
- col_real = DISPLAY_MAP.get(v, v)
261
- if v in ENV_VARS:
262
- df = env_df(v, prep_pts(d))
263
- df = df.sort_values("zona")
264
- return px.bar(df, x="zona", y="pacientes", text_auto=True, title=v,
265
- labels={"zona": "Zona", "pacientes": "Pacientes"})
266
- if v == "Localidad":
267
- s = d[col_real].fillna("Sin dato")
268
- return px.histogram(s, x=s, category_orders={s.name: sorted(s.unique())}, text_auto=True, title=v)
269
- if is_num(col_real):
270
- return px.histogram(d, x=col_real, nbins=20, title=v)
271
- order = sorted(d[col_real].astype(str).unique())
272
- return px.histogram(d, x=col_real, category_orders={col_real: order}, text_auto=True, title=v)
273
-
274
- # ─────────────── bivariado ───────────────
275
-
276
- def g_bi(x, y, d):
277
- col_x, col_y = DISPLAY_MAP.get(x, x), DISPLAY_MAP.get(y, y)
278
- pts = prep_pts(d)
279
- if x in ENV_VARS:
280
- d = d.assign(**{x: env_series(x, pts)})
281
- col_x = x
282
- if y in ENV_VARS:
283
- d = d.assign(**{y: env_series(y, pts)})
284
- col_y = y
285
- num_x, num_y = is_num(col_x), is_num(col_y)
286
- if not num_x and not num_y:
287
- ord_x = sorted(map(str, d[col_x].unique()))
288
- ord_y = sorted(map(str, d[col_y].unique()))
289
- return px.histogram(d, x=col_x, color=col_y, barmode="group",
290
- category_orders={col_x: ord_x, col_y: ord_y}, title=f"{x} vs {y}")
291
- if num_x and not num_y:
292
- return px.box(d, x=col_y, y=col_x, points="all", title=f"{x} vs {y}")
293
- if not num_x and num_y:
294
- return px.box(d, x=col_x, y=col_y, points="all", title=f"{x} vs {y}")
295
- return px.scatter(d, x=col_x, y=col_y, title=f"{x} vs {y}")
296
-
297
- # ─────────────── pop-up ───────────────
298
-
299
- def popup(r):
300
- lab = lambda k: f"<b>{k}:</b> SΓ­<br>" if r[f"{k.lower()}_cat"].lower() == "positivo" else ""
301
- edad = f"{int(r['edad'])} aΓ±os" if pd.notna(r['edad']) else "Sin dato edad"
302
- ants = "; ".join(lbl for lbl, col in ANT_COLS_HUMAN.items() if r.get(col) == "Positivo") or "Ninguno"
303
- return (
304
- f"<b>Localidad:</b> {r['localidad']}<br><b>Edad:</b> {edad}<br>"
305
- f"<b>GΓ©nero:</b> {r['genero_cat']}<br>{lab('ANCA')}{lab('MPO')}{lab('PR3')}"
306
- f"<b>Biopsia:</b> {'; '.join(r['biopsia_patrones'])}<br>"
307
- f"<b>Antecedentes:</b> {ants}"
308
  )
309
 
310
- # ─────────────── choropleth ───────────────
 
 
 
 
 
 
 
 
311
 
312
- def choropleth(m, g, val, title, cmap, zfield, zalias):
313
- g = g.copy()
314
- g[val] = pd.to_numeric(g[val], errors="coerce")
315
- for c in g.columns:
316
- if np.issubdtype(g[c].dtype, np.datetime64):
317
- g[c] = g[c].astype(str)
318
- cm = cmap.scale(g[val].min(), g[val].max()) if cmap != wqi_cmap else cmap
319
- cm.caption = title
320
- cm.add_to(m)
321
- is_line = g.geometry.iloc[0].geom_type.startswith("Line")
322
-
323
- def _style(f, vc=val):
324
- if is_line:
325
- return {"color": cm(f['properties'][vc]), "weight": 4, "opacity": 0.9}
326
- return {"fillColor": cm(f['properties'][vc]), "fillOpacity": 0.8, "color": "black", "weight": 0.3}
327
-
328
- fields, aliases = [zfield, val], [zalias, title]
329
- if "pacientes" in g.columns and val != "pacientes":
330
- fields.append("pacientes"); aliases.append("Pacientes")
331
- if "wqi_cat" in g.columns:
332
- fields.insert(2, "wqi_cat"); aliases.insert(2, "Calidad")
333
-
334
- folium.GeoJson(
335
- g,
336
- name=title,
337
- style_function=_style,
338
- highlight_function=lambda _: {"weight": 2, "color": "#444"},
339
- tooltip=folium.GeoJsonTooltip(fields, aliases, sticky=True),
340
- ).add_to(m)
341
-
342
- # ─────────────── mapa ───────────────
343
-
344
- def crear_mapa(d_filt, capas_sel, ver_cluster):
345
- pts = prep_pts(d_filt)
346
- caps = capas_conteos(pts)
347
- # base
348
- g_loc = pts.groupby("localidad").size().reset_index(name="pacientes")
349
- geo = geo_loc.merge(g_loc, on="localidad", how="left").fillna({"pacientes": 0})
350
- m = folium.Map(location=[4.65, -74.1], zoom_start=11, tiles="CartoDB positron")
351
- choropleth(m, geo, "pacientes", "No. Pacientes", branca.colormap.linear.Reds_09, "localidad", "Localidad")
352
-
353
- for capa in capas_sel:
354
  if capa == "Heatmap pacientes":
 
 
355
  continue
 
356
  if capa == "WQI":
357
- choropleth(m, caps["WQI"], "wqi_val", "WQI", wqi_cmap, "tramo", "Tramo")
 
 
 
 
 
 
 
 
 
 
 
 
358
  continue
359
- val, uni, cmap, zf, za = META_CAPAS[capa]
360
- choropleth(m, caps[capa], val, f"{capa} ({uni})", cmap, zf, za)
361
 
362
- if "Heatmap pacientes" in capas_sel and not pts.empty:
363
- HeatMap(pts[["latitud", "longitud"]].values, radius=18, name="Heatmap pacientes").add_to(m)
364
-
365
- fg = folium.FeatureGroup("Pacientes", overlay=True)
366
- for _, r in pts.iterrows():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  folium.CircleMarker(
368
- (r["latitud"], r["longitud"]), radius=6, color="#c00", fill=True, fill_color="#fff",
369
- fill_opacity=0.9, popup=popup(r)
370
- ).add_to(fg)
371
- fg.add_to(m)
372
-
373
- if ver_cluster and len(pts) > 2:
374
- coords = np.radians(pts[["latitud", "longitud"]])
375
- lab = DBSCAN(eps=1 / 6371, min_samples=3, metric="haversine").fit_predict(coords)
376
- pts["cluster"] = lab
377
- cl_fg = folium.FeatureGroup("ClΓΊsteres (1 km)", overlay=True)
378
- pal = branca.colormap.linear.Set1_09
379
- for cl in sorted(c for c in pts["cluster"].unique() if c != -1):
380
- color = pal(cl / max(1, pts["cluster"].nunique() - 1))
381
- for _, r in pts[pts["cluster"] == cl].iterrows():
382
- folium.CircleMarker(
383
- (r["latitud"], r["longitud"]), radius=7, color=color, fill=True, fill_color=color,
384
- fill_opacity=0.9, popup=f"<b>ClΓΊster {cl}</b><br>" + popup(r)
385
- ).add_to(cl_fg)
386
- cl_fg.add_to(m)
387
 
388
  folium.LayerControl(collapsed=False).add_to(m)
389
- return m._repr_html_()
390
-
391
- # ─────────────── interfaz ───────────────
392
-
393
- gen_opts = ["Todos"] + sorted(df_all["genero_cat"].unique())
394
- age_opts = list(df_all["edad_cat"].dtype.categories)
395
- loc_opts = sorted(df_all["localidad"].fillna("Sin dato").unique())
396
- anca_opts = ["Todos"] + sorted(df_all["anca_cat"].unique())
397
- mpo_opts = ["Todos"] + sorted(df_all["mpo_cat"].unique())
398
- pr3_opts = ["Todos"] + sorted(df_all["pr3_cat"].unique())
399
-
400
- vars_cat = ["Localidad"] + ENV_VARS + [
401
- "genero_cat", "Estrato", "edad_cat", "sindrome_renal", "manifestaciones_extrarenales", "proteinuria",
402
- "anca_cat", "mpo_cat", "pr3_cat",
403
- ] + list(ANT_COLS_HUMAN.keys())
404
- vars_all = vars_cat + NUM_VARS
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
405
 
406
- with gr.Blocks(title="Vasculitis ANCA BogotΓ‘") as demo:
407
- gr.Markdown("## Explorador geoespacial – Vasculitis ANCA (BogotΓ‘)")
408
  with gr.Row():
409
- ui_gen = gr.Dropdown(gen_opts, label="GΓ©nero", value="Todos")
410
- ui_age = gr.CheckboxGroup(age_opts, label="Edad (quinquenios)")
411
- ui_loc = gr.Dropdown(loc_opts, multiselect=True, label="Localidades")
412
- ui_renal = gr.Dropdown(["Todos", "SΓ­", "No"], value="Todos", label="Biopsia positiva")
413
- ui_ant = gr.CheckboxGroup(["Todos"] + list(ANT_COLS_HUMAN.keys()), label="Antecedentes")
414
- ui_bio = gr.CheckboxGroup(["Todos"] + list({p for lst in df_all["biopsia_patrones"] for p in lst}),
415
- label="PatrΓ³n biopsia")
416
- with gr.Row():
417
- ui_anca = gr.Dropdown(anca_opts, label="ANCA", value="Todos")
418
- ui_mpo = gr.Dropdown(mpo_opts, label="MPO", value="Todos")
419
- ui_pr3 = gr.Dropdown(pr3_opts, label="PR3", value="Todos")
420
-
421
- ui_capas = gr.CheckboxGroup(list(GEO_AMBIENTALES.keys()), label="Capas mapa")
422
- ui_clu = gr.Checkbox(label="Mostrar clΓΊsteres (1 km)")
423
-
424
- with gr.Tab("Mapa"):
425
- btn_map = gr.Button("Generar mapa"); out_map = gr.HTML()
426
- btn_map.click(
427
- lambda *i: crear_mapa(filtrar(df_all, *i[:-2]), i[-2], i[-1]),
428
- inputs=[ui_gen, ui_age, ui_loc, ui_renal, ui_ant, ui_bio, ui_anca, ui_mpo, ui_pr3, ui_capas, ui_clu],
429
- outputs=out_map,
430
- )
431
-
432
- with gr.Tab("Univariado"):
433
- ui_var = gr.Dropdown(vars_all, label="Variable"); btn_uni = gr.Button("Graficar"); out_uni = gr.Plot()
434
- btn_uni.click(
435
- lambda v, *i: g_uni(v, filtrar(df_all, *i)),
436
- inputs=[ui_var, ui_gen, ui_age, ui_loc, ui_renal, ui_ant, ui_bio, ui_anca, ui_mpo, ui_pr3],
437
- outputs=out_uni,
438
- )
439
-
440
- with gr.Tab("Bivariado"):
441
- ui_x = gr.Dropdown(vars_all, label="Variable X")
442
- ui_y = gr.Dropdown(vars_all, label="Variable Y")
443
- btn_bi = gr.Button("Graficar"); out_bi = gr.Plot()
444
- btn_bi.click(
445
- lambda x, y, *i: g_bi(x, y, filtrar(df_all, *i)),
446
- inputs=[ui_x, ui_y, ui_gen, ui_age, ui_loc, ui_renal, ui_ant, ui_bio, ui_anca, ui_mpo, ui_pr3],
447
- outputs=out_bi,
448
- )
449
 
450
  if __name__ == "__main__":
451
- demo.launch(share=False)
 
1
+ #!/usr/bin/env python
2
+ # ──────────────────────────────
3
+ # app.py – Dashboard Vasculitis
4
+ # ──────────────────────────────
5
+ # Requisitos (pip):
6
+ # pandas numpy geopandas shapely folium branca plotly scikit-learn
7
+ # gradio==4.*
8
+ # ──────────────────────────────
9
+
10
  import re
11
  import unicodedata
12
  import warnings
13
+ from pathlib import Path
14
 
15
  import branca
16
  import folium
 
25
 
26
  warnings.filterwarnings("ignore")
27
 
28
+ # ════════════════════════════
29
+ # utilidades bΓ‘sicas
30
+ # ════════════════════════════
31
+
32
+ _norm = lambda t: unicodedata.normalize("NFKD", str(t)).encode("ascii", "ignore").decode()
33
+ snake = lambda cols: [
34
+ re.sub(r"[^\w]+", "_", _norm(c).strip().lower()).strip("_") for c in cols
35
+ ]
36
  sin_dato = lambda s: s.fillna("Sin dato").replace("", "Sin dato")
37
+
38
  NUM_VARS = ["edad", "creatinina"]
39
 
40
+ # ════════════════════════════
41
+ # Rutas (ajusta si es necesario)
42
+ # ════════════════════════════
43
+ DATA_XLSX = "VasculitisAsociadasA-Bdd3_DATA_LABELS_2025-04-16_1949 (1).xlsx"
44
  LOCALIDADES = "loca.json"
45
  GEO_AMBIENTALES = {
46
+ "PM10": "pm10_prom_anual.geojson", # sΓ³lo en mapa
47
+ "PM2.5": "pm25_prom_anual_2023 (2).geojson",
48
+ "Ozono": "ozono_prom_anual_2022 (2).geojson",
49
+ "Temperatura": "temp_anualprom_2023 (2).geojson",
50
  "PrecipitaciΓ³n": "precip_anualacum_2023 (2).geojson",
51
+ "Viento": "vel_viento_0_23h_anual_2023.geojson",
52
+ "WQI": "tramo_wqi.geojson",
53
+ "Heatmap pacientes": None, # capa dinΓ‘mica
54
  }
55
 
56
+ # variables ambientales que SÍ se grafican
57
  ENV_VARS = [k for k in GEO_AMBIENTALES if k not in ("WQI", "Heatmap pacientes", "PM10")]
58
 
59
+ # metadatos para color-maps
60
  META_CAPAS = {
61
+ "PM10": ("conc_pm10", "Β΅g/mΒ³", branca.colormap.linear.OrRd_09, "id", "Zona"),
62
+ "PM2.5": ("conc_pm25", "Β΅g/mΒ³", branca.colormap.linear.Reds_09, "id", "Zona"),
63
+ "Ozono": ("conc_ozono","ppb", branca.colormap.linear.PuBuGn_09, "id", "Zona"),
64
+ "Temperatura": ("temperatur","Β°C", branca.colormap.linear.YlOrBr_09, "id", "Zona"),
65
+ "PrecipitaciΓ³n": ("precip_per","mm", branca.colormap.linear.Blues_09, "id", "Zona"),
66
+ "Viento": ("velocidad", "m/s", branca.colormap.linear.GnBu_09, "id", "Zona"),
67
+ "WQI": ("wqi_val", "", None, "tramo", "Tramo"),
68
  }
69
 
70
+ # ════════════════════════════
71
+ # Cargar pacientes
72
+ # ════════════════════════════
73
+ print("β†’ Cargando datos de pacientes…")
74
  df_all = pd.read_excel(DATA_XLSX, dtype=str)
75
  df_all.columns = snake(df_all.columns)
76
 
77
+ # detectar columnas de lat/lon
78
+ lat_col = next(c for c in df_all.columns if "residencia" in c and "latitud" in c)
79
+ lon_col = next(c for c in df_all.columns if "residencia" in c and "longitud" in c)
80
 
81
  df_all = df_all.rename(columns={lat_col: "latitud_raw", lon_col: "longitud_raw"})
82
+ df_all["latitud"] = pd.to_numeric(df_all["latitud_raw"].str.replace(",", "."), errors="coerce")
83
  df_all["longitud"] = pd.to_numeric(df_all["longitud_raw"].str.replace(",", "."), errors="coerce")
84
 
85
  # variables categΓ³ricas bΓ‘sicas
86
+ df_all["genero_cat"] = sin_dato(df_all.get("genero"))
87
  df_all["estrato_socioeconomico_cat"] = sin_dato(df_all.get("estrato_socioeconomico"))
88
 
89
+ # edad β†’ quinquenios
90
+ bins = list(range(0, 105, 5))
91
  age_labels = [f"{b}-{b+4}" for b in bins[:-1]]
92
 
93
+ df_all["edad"] = pd.to_numeric(
94
+ df_all.get("edad_en_anos_del_paciente").str.replace(",", "."),
95
+ errors="coerce",
96
+ )
97
  df_all["edad_cat"] = pd.Categorical(
98
  sin_dato(pd.cut(df_all["edad"], bins=bins, labels=age_labels, right=False).astype(str)),
99
  categories=age_labels + ["Sin dato"],
 
101
  )
102
 
103
  # ANCA / MPO / PR3
104
+ for src, dst in {"ancas":"anca_cat","mpo":"mpo_cat","pr3":"pr3_cat"}.items():
 
105
  df_all[dst] = sin_dato(df_all.get(src))
106
 
107
+ # clΓ­nicos y antecedentes
108
+ CLIN_COLS = {
109
+ "sindrome_renal": "sindrome_renal_al_ingreso",
110
+ "manifestaciones_extrarenales":"manifestaciones_extrarenales",
111
+ "proteinuria": "proteinuria",
112
  }
113
+ for dst, src in CLIN_COLS.items():
114
  df_all[dst] = sin_dato(df_all.get(src)).str.capitalize()
115
 
116
  df_all["creatinina"] = pd.to_numeric(df_all.get("creatinina").str.replace(",", "."), errors="coerce")
117
 
118
  ANT_COLS_HUMAN = {
119
+ "Diabetes": "antecedente_personal_de_diabetes",
120
+ "Falla cardΓ­aca": "antecedente_personal_de_falla_cardiaca",
121
+ "EPOC": "antecedente_personal_de_epoc",
122
+ "HipertensiΓ³n": "antecedente_personal_de_hipertension_arterial",
123
+ "VIH": "antecedente_personal_de_vih",
124
+ "Enf. autoinmune": "antecedente_personal_de_otra_enfermedad_autoinmune",
125
+ "CΓ‘ncer": "antecedente_personal_de_cancer",
126
  }
 
127
  for lbl, raw in ANT_COLS_HUMAN.items():
128
+ col = snake([lbl])[0] # ej. diabetes, vih…
129
+ df_all[col] = np.where(
130
+ df_all.get(raw,"").str.lower().isin(["si","sΓ­","checked","1","positivo"]),
131
+ "Positivo","Negativo"
132
+ )
133
+ ANT_COLS_HUMAN[lbl] = col # guardamos nombre limpio
134
+
135
+ # biopsia β†’ patrones
136
+ aux = [c for c in df_all.columns if c.startswith("hallazgos_histologicos_en_biopsia")]
137
+ ren_bio = {c:f"bio_{i}" for i,c in enumerate(aux,1)}
138
+ df_all = df_all.rename(columns=ren_bio)
139
  BIO_REGEX = [
140
+ (r"sin_alteraciones$", "Sin alteraciones"),
141
+ (r"sin_proliferacion_extracapilar", "Necrosis sin PC"),
142
+ (r"menos_del_50.*focal", "Focal"),
143
+ (r"clase_mixta", "Mixta"),
144
+ (r"mas_del_50.*cresc", "CrescΓ©ntica"),
145
+ (r"sin_compromiso_glomerular$", "Vasculitis sin glom."),
146
+ (r"con_compromiso_glomerular$", "Vasculitis + glom."),
147
+ (r"sin_dato$", "Sin dato"),
148
  ]
149
+ raw2short = {next(r for r in aux if re.search(p,r)):s for p,s in BIO_REGEX}
150
+
151
+ def _patrones_biopsia(row):
152
+ encontrados = [
153
+ raw2short[raw] for raw, flag in ren_bio.items()
154
+ if str(row[flag]).strip().lower() in ("si","sΓ­","checked","1","positivo")
155
+ ]
156
+ return encontrados or ["Sin dato"]
157
+ df_all["biopsia_patrones"] = df_all.apply(_patrones_biopsia, axis=1)
158
+ df_all["biopsia_patron_str"] = df_all["biopsia_patrones"].apply("; ".join)
159
+ df_all["biopsia_positiva"] = np.where(
160
+ df_all["biopsia_patron_str"] == "Sin dato", "Negativo", "Positivo"
161
+ )
162
 
163
+ # ════════════════════════════
164
+ # Localidades (polΓ­gonos)
165
+ # ════════════════════════════
166
+ print("β†’ Cargando localidades…")
167
  geo_loc = gpd.read_file(LOCALIDADES).to_crs(4326)
168
  geo_loc.columns = snake(geo_loc.columns)
169
+ geo_loc = geo_loc.rename(columns={"locnombre":"localidad"})
170
  geo_loc["localidad"] = geo_loc["localidad"].str.upper()
171
 
172
+ # ════════════════════════════
173
+ # Calcular localidad de cada paciente mediante spatial join
174
+ # ════════════════════════════
175
+ pts_raw = df_all.dropna(subset=["latitud","longitud"]).copy()
176
  pts_raw["geometry"] = [Point(xy) for xy in zip(pts_raw["longitud"], pts_raw["latitud"])]
177
  pts_raw = gpd.GeoDataFrame(pts_raw, geometry="geometry", crs=4326)
 
 
 
 
 
178
 
179
+ pts_raw = gpd.sjoin(
180
+ pts_raw,
181
+ geo_loc[["localidad","geometry"]],
182
+ how="left", predicate="within"
183
+ ).drop(columns="index_right")
184
+
185
+ # incorporar la columna calculada a df_all
186
+ df_all = df_all.merge(
187
+ pts_raw[["localidad"]], # ← ojo: NO usamos tupla, sΓ³lo lista
188
+ how="left",
189
+ left_index=True, right_index=True,
190
+ )
191
 
192
+ # ════════════════════════════
193
+ # Cargar capas base geoambientales
194
+ # ════════════════════════════
195
+ def load_gjson(path: str|Path) -> gpd.GeoDataFrame:
196
  g = gpd.read_file(path).to_crs(4326)
197
  g.columns = snake(g.columns)
198
  for c in g.columns:
 
202
  g[c] = g[c].astype(str)
203
  return g
204
 
205
+ print("β†’ Cargando capas ambientales…")
206
+ caps_base = {k: load_gjson(v) for k,v in GEO_AMBIENTALES.items() if v}
207
 
208
+ # WQI β†’ discretizamos y creamos colormap
209
+ wqi_bins = [0,20,35,50,70,100]
210
+ wqi_labels = ["Pobre","Marginal","Regular","Buena","Excelente"]
211
+ _gw = caps_base["WQI"].copy()
212
  _gw["wqi_val"] = pd.to_numeric(_gw["wqi"], errors="coerce")
213
  _gw["wqi_cat"] = pd.cut(_gw["wqi_val"], bins=wqi_bins, labels=wqi_labels, include_lowest=True)
214
+
215
+ wqi_cmap = branca.colormap.StepColormap(
216
+ colors=["red","olive","purple","green","blue"],
217
+ index=wqi_bins, caption="WQI"
218
+ )
219
  caps_base["WQI"] = _gw
220
  META_CAPAS["WQI"] = (*META_CAPAS["WQI"][:2], wqi_cmap, *META_CAPAS["WQI"][3:])
221
 
222
+ # ════════════════════════════
223
+ # Filtros (helper)
224
+ # ════════════════════════════
225
+ def filtrar(df, gen, edades, locs, renal, ants, bios, anca, mpo, pr3):
226
+ d = df.copy()
227
  if gen != "Todos":
228
+ d = d[d["genero_cat"] == gen]
229
  if edades:
230
+ d = d[d["edad_cat"].isin(edades)]
231
  if locs:
232
+ d = d[d["localidad"].fillna("Sin dato").isin(locs)]
233
  if renal != "Todos":
234
+ d = d[d["biopsia_positiva"] == renal]
235
  if bios and bios != ["Todos"]:
236
+ d = d[d["biopsia_patrones"].apply(lambda lst: any(p in lst for p in bios))]
237
  if anca != "Todos":
238
+ d = d[d["anca_cat"] == anca]
239
  if mpo != "Todos":
240
+ d = d[d["mpo_cat"] == mpo]
241
  if pr3 != "Todos":
242
+ d = d[d["pr3_cat"] == pr3]
243
+ # antecedentes
244
  for ant in ants:
245
+ if ant == "Todos": continue
 
246
  col = ANT_COLS_HUMAN[ant]
247
+ d = d[d[col] == "Positivo"]
248
+ return d
249
+
250
+ # ════════════════════════════
251
+ # Conteo dinΓ‘mico de pacientes por polΓ­gono
252
+ # ════════════════════════════
253
+ def capas_conteos(pts: gpd.GeoDataFrame):
254
+ res = {}
255
  for capa, g0 in caps_base.items():
256
+ if capa in ("Heatmap pacientes","WQI"):
257
+ res[capa] = g0
258
  continue
259
+ g = g0.copy()
260
  g["pacientes"] = 0
261
+ joined = gpd.sjoin(pts[["geometry"]], g, how="left", predicate="within")
262
+ counts = joined["index_right"].value_counts()
263
  g.loc[counts.index, "pacientes"] = counts.values
264
+ res[capa] = g
265
+ return res
266
+
267
+ # ════════════════════════════
268
+ # Mapas Folium
269
+ # ════════════════════════════
270
+ def generar_mapa(df_filtrado: pd.DataFrame, capa_activa: str):
271
+ # puntos de pacientes
272
+ pts = df_filtrado.dropna(subset=["latitud","longitud"]).copy()
273
+ gpts = gpd.GeoDataFrame(
274
+ pts, geometry=gpd.points_from_xy(pts["longitud"], pts["latitud"]), crs=4326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
275
  )
276
 
277
+ # actualizar conteos en capas
278
+ capas = capas_conteos(gpts)
279
+
280
+ m = folium.Map(location=[4.65,-74.1], zoom_start=11, control_scale=True)
281
+
282
+ # aΓ±adir capas poligonales
283
+ for capa, g in capas.items():
284
+ meta = META_CAPAS[capa]
285
+ var, unit, cmap, popup_id, popup_lbl = meta
286
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  if capa == "Heatmap pacientes":
288
+ # Heatmap a partir de puntos
289
+ HeatMap(gpts[["latitud","longitud"]].values, name=capa).add_to(m)
290
  continue
291
+
292
  if capa == "WQI":
293
+ for _, row in g.iterrows():
294
+ folium.GeoJson(
295
+ data=row["geometry"],
296
+ tooltip=f"{popup_lbl}: {row[popup_id]}<br>WQI: {row['wqi_val']:.1f}",
297
+ style_function=lambda _: {
298
+ "fillColor": wqi_cmap(row["wqi_val"]),
299
+ "color": "black",
300
+ "weight": 0.5,
301
+ "fillOpacity": 0.6
302
+ },
303
+ name=capa,
304
+ ).add_to(m)
305
+ wqi_cmap.add_to(m)
306
  continue
 
 
307
 
308
+ # otras capas
309
+ for _, row in g.iterrows():
310
+ col_val = row[var]
311
+ num_pac = row["pacientes"]
312
+ tooltip = (
313
+ f"{popup_lbl}: {row[popup_id]}<br>"
314
+ f"{var}: {col_val:.2f} {unit}<br>"
315
+ f"Pacientes: {num_pac}"
316
+ )
317
+ folium.GeoJson(
318
+ data=row["geometry"],
319
+ tooltip=tooltip,
320
+ style_function=lambda _: {
321
+ "fillColor": cmap(col_val) if not pd.isna(col_val) else "#999999",
322
+ "color": "black",
323
+ "weight": 0.5,
324
+ "fillOpacity": 0.6
325
+ },
326
+ name=capa,
327
+ ).add_to(m)
328
+ cmap.caption = f"{capa} ({unit})"
329
+ cmap.add_to(m)
330
+
331
+ # puntos de pacientes sobrepuestos
332
+ for _, row in gpts.iterrows():
333
  folium.CircleMarker(
334
+ location=[row["latitud"], row["longitud"]],
335
+ radius=4,
336
+ fill=True, fill_opacity=0.8,
337
+ popup=(f"Paciente #{row.name}"
338
+ f"<br>Edad: {row['edad']}"
339
+ f"<br>GΓ©nero: {row['genero_cat']}"),
340
+ color="red"
341
+ ).add_to(m)
 
 
 
 
 
 
 
 
 
 
 
342
 
343
  folium.LayerControl(collapsed=False).add_to(m)
344
+ return m
345
+
346
+ # ════════════════════════════
347
+ # GrΓ‘ficos Plotly
348
+ # ════════════════════════════
349
+ def grafico_barras(df_filtrado: pd.DataFrame, eje_x:str, colorear:str|None=None):
350
+ d = df_filtrado.copy()
351
+ d[eje_x] = d[eje_x].fillna("Sin dato")
352
+ fig = px.histogram(
353
+ d, x=eje_x, color=colorear,
354
+ category_orders={eje_x: sorted(d[eje_x].dropna().unique())},
355
+ text_auto=True
356
+ )
357
+ fig.update_layout(bargap=0.15, title=f"DistribuciΓ³n por {eje_x}")
358
+ return fig
359
+
360
+ # ════════════════════════════
361
+ # Interface Gradio
362
+ # ════════════════════════════
363
+ GENEROS = ["Todos"] + sorted(df_all["genero_cat"].unique())
364
+ EDAD_OPTS = list(df_all["edad_cat"].cat.categories)
365
+ LOC_OPTIONS = ["Todas"] + sorted(df_all["localidad"].dropna().unique())
366
+ RENAL_OPTS = ["Todos","Positivo","Negativo"]
367
+ BIO_OPTS = ["Todos"] + sorted({p for sub in df_all["biopsia_patrones"] for p in sub})
368
+ ANCA_OPTS = ["Todos"] + sorted(df_all["anca_cat"].unique())
369
+ MPO_OPTS = ["Todos"] + sorted(df_all["mpo_cat"].unique())
370
+ PR3_OPTS = ["Todos"] + sorted(df_all["pr3_cat"].unique())
371
+ ANT_OPTS = ["Todos"] + list(ANT_COLS_HUMAN.keys())
372
+ CAPA_OPTS = list(GEO_AMBIENTALES.keys())
373
+
374
+ def dashboard(
375
+ genero, edades, locs, renal, ants, bios, anca, mpo, pr3, capa
376
+ ):
377
+ if "Todas" in locs:
378
+ locs = [] # sin filtro
379
+ df_f = filtrar(
380
+ df_all, genero, edades, locs, renal, ants, bios, anca, mpo, pr3
381
+ )
382
+ mapa = generar_mapa(df_f, capa)
383
+ fig_edad= grafico_barras(df_f, "edad_cat", colorear=None)
384
+ fig_loc = grafico_barras(df_f, "localidad", colorear="genero_cat")
385
+ return mapa, fig_edad, fig_loc, f"{len(df_f)} pacientes seleccionados"
386
 
387
+ with gr.Blocks(title="Vasculitis Dashboard") as demo:
 
388
  with gr.Row():
389
+ with gr.Column(scale=1):
390
+ genero_in = gr.Dropdown(GENEROS, label="GΓ©nero", value="Todos")
391
+ edad_in = gr.CheckboxGroup(EDAD_OPTS, label="Edades (quinquenios)")
392
+ loc_in = gr.Dropdown(LOC_OPTIONS, multiselect=True, value=["Todas"], label="Localidad")
393
+ renal_in = gr.Radio(RENAL_OPTS, label="Biopsia positiva", value="Todos")
394
+ bios_in = gr.CheckboxGroup(BIO_OPTS, label="Patrones biopsia", value=["Todos"])
395
+ anca_in = gr.Radio(ANCA_OPTS, label="ANCA", value="Todos")
396
+ mpo_in = gr.Radio(MPO_OPTS, label="MPO", value="Todos")
397
+ pr3_in = gr.Radio(PR3_OPTS, label="PR3", value="Todos")
398
+ ant_in = gr.CheckboxGroup(ANT_OPTS, label="Antecedentes", value=["Todos"])
399
+ capa_in = gr.Dropdown(CAPA_OPTS, label="Capa ambiental", value="PM2.5")
400
+ btn = gr.Button("Actualizar")
401
+
402
+ with gr.Column(scale=2):
403
+ mapa_out = gr.HTML(label="Mapa")
404
+ fig1_out = gr.Plot(label="Edades")
405
+ fig2_out = gr.Plot(label="Localidad vs GΓ©nero")
406
+ texto_out = gr.Markdown()
407
+
408
+ btn.click(
409
+ dashboard,
410
+ inputs=[genero_in, edad_in, loc_in, renal_in, ant_in, bios_in, anca_in, mpo_in, pr3_in, capa_in],
411
+ outputs=[mapa_out, fig1_out, fig2_out, texto_out],
412
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
413
 
414
  if __name__ == "__main__":
415
+ demo.launch()