-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
1800 lines (1596 loc) · 63.9 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
import dash
from dash import dcc, html, dash_table
from dash.dependencies import Input, Output, State
import dash_bootstrap_components as dbc
import geopandas as gpd
import pandas as pd
import plotly.express as px
from dash.exceptions import PreventUpdate
import plotly.graph_objects as go
from sqlalchemy import create_engine
import os
from dotenv import load_dotenv
import unicodedata
from sqlalchemy.exc import SQLAlchemyError
from functools import lru_cache
import numpy as np
import math
import socket
def is_port_in_use(port):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('127.0.0.1', port)) == 0
# Configuración global para todos los gráficos
GRAPH_CONFIG = {
'displayModeBar': True,
'responsive': True,
'displaylogo': False,
'modeBarButtonsToRemove': ['lasso2d', 'select2d'],
'toImageButtonOptions': {
'format': 'png',
'filename': 'grafico',
'height': None,
'width': None,
'scale': 2
}
}
# Configuración común para layouts
GRAPH_LAYOUT = {
'margin': dict(l=50, r=50, t=50, b=50),
'autosize': True,
'height': 400,
'hoverlabel': dict(
bgcolor="white",
font_size=12,
font_family="Arial",
bordercolor='gray',
namelength=-1
),
'font': dict(
family="Arial",
size=12
),
'hovermode': 'closest'
}
# Agrega esta línea cerca del inicio de tu script, después de las importaciones
mapbox_access_token = 'pk.eyJ1IjoiaHBlcmV6Yzk3IiwiYSI6ImNtMm92ZWRzZTBrNTkybnBydGkydzJyajMifQ.ng34bPCD2cV5eNBnBMiCXg'
# Cargar variables de entorno
load_dotenv()
# Configuración de la conexión a PostgreSQL
DB_USER = os.getenv('DB_USER')
DB_PASSWORD = os.getenv('DB_PASSWORD')
DB_HOST = os.getenv('DB_HOST')
DB_PORT = os.getenv('DB_PORT', '5432') # Agregamos el puerto
DB_NAME = os.getenv('DB_NAME')
# Crear conexión a la base de datos
DATABASE_URL = f"postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
engine = create_engine(
DATABASE_URL,
pool_size=5,
max_overflow=10,
pool_timeout=30,
pool_recycle=1800,
connect_args={
'connect_timeout': 10,
'application_name': 'TableroEventosAmenaza'
}
)
# Verificar la conexión
with engine.connect() as conn:
print("Conexión exitosa a la base de datos")
# Modificar la función cargar_datos
@lru_cache(maxsize=32)
def cargar_datos():
try:
# Cargar municipios
query_municipios = """
SELECT "MpNombre", ST_Transform(geometry, 4326) as geometry
FROM municipios
"""
gdf_municipios = gpd.GeoDataFrame.from_postgis(
query_municipios,
engine,
geom_col='geometry',
crs='EPSG:4326'
)
# Cargar eventos desde la base UNGRD
query_eventos = """
SELECT "MUNICIPIO",
"TIPO",
"FECHA",
"COMENTARIOS",
'UNGRD' as "FUENTE"
FROM eventos_ungrd
"""
with engine.connect().execution_options(timeout=30) as conn:
df_eventos_ungrd = pd.read_sql(query_eventos, conn)
# Cargar eventos desde DAGRAN
query_eventos_dagran = """
SELECT "MUNICIPIO",
"TIPO",
"FECHA",
"COMENTARIOS",
'DAGRAN' as "FUENTE"
FROM eventos_dagran
"""
with engine.connect().execution_options(timeout=30) as conn:
df_eventos_dagran = pd.read_sql(query_eventos_dagran, conn)
# Cargar eventos desde SIMMA
query_eventos_simma = """
SELECT "TIPO",
"SUBTIPO" as "COMENTARIOS",
ST_Transform(geometry, 4326) as geometry,
'SIMMA' as "FUENTE"
FROM eventos_simma
"""
gdf_eventos_shp = gpd.GeoDataFrame.from_postgis(
query_eventos_simma,
engine,
geom_col='geometry',
crs='EPSG:4326'
)
gdf_eventos_shp['FECHA'] = None
# Combinar todos los eventos
df_eventos_municipio = pd.concat([
df_eventos_ungrd,
df_eventos_dagran
], ignore_index=True)
return gdf_municipios, df_eventos_municipio, gdf_eventos_shp
except SQLAlchemyError as e:
print(f"Error al cargar datos: {str(e)}")
return gpd.GeoDataFrame(), pd.DataFrame(), gpd.GeoDataFrame()
# Modificar la carga inicial de datos
gdf_municipios, df_eventos_municipio, gdf_eventos_shp = cargar_datos()
# Ajusta el valor de tolerancia para la simplificación
# Un valor más pequeño preservará más detalles, un valor más grande simplificará más
# Prueba con diferentes valores hasta encontrar el equilibrio adecuado
gdf_municipios['geometry'] = gdf_municipios['geometry'].simplify(tolerance=0.003)
gdf_municipios = gdf_municipios[['MpNombre', 'geometry']] # Mantén solo las columnas necesarias
# Modificar la función obtener_municipios_unicos
def obtener_municipios_unicos():
try:
query = """
SELECT DISTINCT "MUNICIPIO" FROM (
SELECT "MUNICIPIO" FROM eventos_ungrd
UNION
SELECT "MUNICIPIO" FROM eventos_dagran
) as municipios
WHERE "MUNICIPIO" IS NOT NULL
"""
with engine.connect().execution_options(timeout=10) as conn:
municipios = pd.read_sql(query, conn)['MUNICIPIO'].unique()
return sorted([mun.split('/')[1].strip() if '/' in mun else mun for mun in municipios])
except SQLAlchemyError as e:
print(f"Error al obtener municipios: {str(e)}")
return []
municipios_unicos = obtener_municipios_unicos()
def normalizar_texto(texto):
"""
Elimina tildes y convierte a mayúsculas
"""
if pd.isna(texto):
return texto
texto_sin_tildes = ''.join(c for c in unicodedata.normalize('NFD', str(texto))
if unicodedata.category(c) != 'Mn')
return texto_sin_tildes.upper().strip()
def normalizar_tipo_evento(tipo):
"""
Normaliza los tipos de eventos para asegurar consistencia entre las tres fuentes de datos.
"""
if pd.isna(tipo):
return "NO ESPECIFICADO"
tipo = str(tipo).upper().strip()
normalizacion = {
'MOVIMIENTO EN MASA': [
'DESLIZAMIENTO', 'REMOCION EN MASA', 'DERRUMBE',
'MOVIMIENTOS EN MASA', 'DESLIZAMIENTOS', 'REPTACIÓN',
'MOVIMIENTO', 'MASA'
],
'INUNDACION': [
'INUNDACIONES', 'DESBORDAMIENTO', 'ANEGACIÓN',
'ENCHARCAMIENTO', 'INUNDACIÓN', 'DESBORDAMIENTOS'
],
'AVENIDA TORRENCIAL': [
'AVENIDA', 'TORRENCIAL', 'CRECIENTE',
'FLUJO TORRENCIAL', 'AVENIDAS TORRENCIALES',
'FLUJOS', 'AVENIDAS'
],
'VENDAVAL': [
'VIENTOS FUERTES', 'TORMENTA', 'VENDAVALES',
'TORNADO', 'TORMENTA ELÉCTRICA', 'VENDAVAL'
],
'SISMO': [
'TEMBLOR', 'TERREMOTO', 'ACTIVIDAD SÍSMICA',
'SISMICIDAD', 'MICROSISMICIDAD'
],
'INCENDIO FORESTAL': [
'INCENDIO DE COBERTURA VEGETAL', 'INCENDIO COBERTURA',
'QUEMA', 'CONFLAGRACIÓN', 'INCENDIOS'
],
'SEQUIA': [
'DESABASTECIMIENTO', 'SEQUÍA', 'DÉFICIT HÍDRICO',
'SEQUIA', 'DESABASTECIMIENTO DE AGUA'
],
'GRANIZADA': [
'GRANIZO', 'PRECIPITACIÓN SÓLIDA', 'GRANIZADAS'
],
'EROSION': [
'SOCAVACIÓN', 'EROSIÓN COSTERA', 'EROSIÓN FLUVIAL',
'EROSIÓN', 'SOCAVAMIENTO'
]
}
for categoria, variantes in normalizacion.items():
if tipo in variantes or any(variante in tipo for variante in variantes):
return categoria
return tipo
# Modificar la función obtener_tipos_eventos
def obtener_tipos_eventos():
try:
query = """
SELECT DISTINCT "TIPO" FROM (
SELECT "TIPO" FROM eventos_ungrd
UNION
SELECT "TIPO" FROM eventos_dagran
UNION
SELECT "TIPO" FROM eventos_simma
) as tipos
WHERE "TIPO" IS NOT NULL
"""
with engine.connect().execution_options(timeout=10) as conn:
tipos = pd.read_sql(query, conn)['TIPO'].unique()
tipos_normalizados = [normalizar_tipo_evento(tipo) for tipo in tipos if pd.notna(tipo)]
return sorted(list(set(tipos_normalizados)))
except SQLAlchemyError as e:
print(f"Error al obtener tipos de eventos: {str(e)}")
return []
# Obtener los tipos de eventos después de definir las funciones
tipos_eventos = obtener_tipos_eventos()
# Inicializar la aplicación Dash con un tema de Bootstrap
app = dash.Dash(__name__,
external_stylesheets=[
dbc.themes.BOOTSTRAP,
'https://use.fontawesome.com/releases/v5.15.4/css/all.css'
])
# Estilos personalizados
SIDEBAR_STYLE = {
"position": "fixed",
"top": 0,
"left": 0,
"bottom": 0,
"width": "16rem",
"padding": "2rem 1rem",
"background-color": "#f8f9fa", # Color gris claro
"border-right": "1px solid #dee2e6" # Borde sutil
}
CONTENT_STYLE = {
"margin-left": "18rem",
"margin-right": "2rem",
"padding": "2rem 1rem",
"@media (max-width: 768px)": {
"margin-left": "0",
"margin-top": "6rem"
}
}
# Definir una paleta de colores profesional
COLORS = {
'primary': '#0d6efd', # Azul principal
'secondary': '#6c757d', # Gris
'success': '#198754', # Verde
'info': '#0dcaf0', # Azul claro
'dark': '#212529', # Negro/gris oscuro
'light': '#f8f9fa', # Gris muy claro
'white': '#ffffff', # Blanco
'border': '#dee2e6' # Color para bordes
}
# Estilos para las tarjetas
CARD_STYLE = {
'box-shadow': '0 2px 4px rgba(0,0,0,0.1)',
'border': f'1px solid {COLORS["border"]}',
'border-radius': '8px'
}
# Paleta de colores para gráficos
GRAPH_COLORS = [
'#0d6efd', # Azul principal
'#198754', # Verde
'#dc3545', # Rojo
'#fd7e14', # Naranja
'#6f42c1', # Morado
'#20c997', # Verde azulado
'#0dcaf0', # Azul claro
'#ffc107' # Amarillo
]
# Primero definimos las fuentes disponibles
FUENTES_DATOS = ['UNGRD', 'DAGRAN', 'SIMMA']
# Modificar el sidebar para incluir iconos
sidebar = html.Div([
html.H4([
html.I(className="fas fa-filter me-2"), # Icono para Filtros
"Filtros"
], className="mb-3 text-secondary d-flex align-items-center"),
html.Hr(style={'border-color': COLORS['border']}),
# Filtro de municipio con icono
dbc.Row([
dbc.Col([
dbc.Label([
html.I(className="fas fa-map-marker-alt me-2"), # Icono para Municipio
"Selecciona un municipio"
], html_for="municipio-input", className="mb-2 text-secondary fw-bold d-flex align-items-center"),
dbc.Input(
id="municipio-input",
type="text",
placeholder="Nombre del municipio",
className="mb-3",
style={'border-radius': '6px'}
)
])
]),
# Mejorar apariencia de las cards de filtros con iconos
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-database me-2"), # Icono para Fuentes de Datos
"Fuentes de Datos"
], className="fw-bold d-flex align-items-center", style={'background-color': COLORS['light']}),
dbc.CardBody(
dcc.Checklist(
id='fuentes-checklist',
options=[{'label': f' {fuente}', 'value': fuente} for fuente in FUENTES_DATOS],
value=FUENTES_DATOS,
labelStyle={'display': 'block', 'margin-bottom': '8px'},
className="checklist-custom"
)
)
], className="mb-3", style=CARD_STYLE),
# Filtro de tipos de eventos con icono
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-exclamation-triangle me-2"), # Icono para Tipos de Eventos
"Tipos de Eventos"
], className="fw-bold d-flex align-items-center", style={'background-color': COLORS['light']}),
dbc.CardBody(
dcc.Checklist(
id='tipo-evento-checklist',
options=[{'label': 'Seleccionar todos', 'value': 'todos'}] +
[{'label': tipo, 'value': tipo} for tipo in tipos_eventos],
value=[],
labelStyle={'display': 'block', 'margin-bottom': '8px'},
className="checklist-custom"
)
)
], style={"maxHeight": "400px", "overflowY": "scroll"}, className="mb-3")
], style=SIDEBAR_STYLE)
# Modificar el contenido principal para incluir la barra de título y el modal
content = html.Div([
# Barra de título
dbc.Navbar(
dbc.Container([
dbc.Row([
dbc.Col(html.H3([
html.I(className="fas fa-database me-2"), # Icono para el título
"Consulta y Análisis de Eventos de Amenaza para Colombia"
], className="text-white mb-0 d-flex align-items-center")),
dbc.Col(
dbc.Button([
html.I(className="fas fa-info-circle me-2"), # Icono para el botón
"Acerca de"
],
id="open-modal",
color="light",
className="ms-auto",
style={'font-weight': '500'}),
width="auto"
)
], align="center", className="w-100")
]),
color="dark",
dark=True,
className="mb-4 shadow-sm"
),
# Modal
dbc.Modal([
dbc.ModalHeader("Acerca de"),
dbc.ModalBody([
html.P([
"Esta aplicación tiene como objetivo facilitar la consulta y análisis de eventos de amenaza ",
"en Colombia, permitiendo visualizar y analizar datos históricos actualizados al año 2024 ",
"de diferentes fuentes oficiales como UNGRD, DAGRAN y SIMMA."
]),
html.P([
"Desarrollado por: Hector Camilo Perez Contreras",
html.Br(),
"Geólogo, Especialista en Sistemas de Información Geográfica",
html.Br(),
"Magister (c) en Geoinformática",
html.Br(),
html.A("[email protected]", href="mailto:[email protected]")
])
])
], id="modal", size="lg"),
# Contador de eventos
dbc.Row([
dbc.Col(html.Div(id='total-eventos', className="lead text-center fade-in"), width=12)
], className="mb-4"),
# Mapa
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-map-marked-alt me-2"),
"Mapa de Localización",
html.I(className="fas fa-info-circle ms-2",
id="info-mapa",
style={'cursor': 'pointer', 'color': COLORS['primary']})
], className="fw-bold d-flex align-items-center"),
dbc.CardBody([
dbc.Spinner(dcc.Graph(id='mapa-colombia'), color="primary")
]),
dbc.Tooltip(
"Este mapa muestra la densidad de eventos por km² en cada municipio. "
"Los colores más intensos indican mayor densidad de eventos. "
"Al seleccionar un municipio, se resalta en rojo y se hace zoom sobre él.",
target="info-mapa",
placement="top"
)
], style=CARD_STYLE)
], width=12, className="fade-in"),
], className="mb-4"),
# Gráficos principales
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-chart-bar me-2"),
"Eventos por Tipo",
html.I(className="fas fa-info-circle ms-2",
id="info-eventos-tipo",
style={'cursor': 'pointer', 'color': COLORS['primary']})
], className="fw-bold d-flex align-items-center"),
dbc.CardBody([
dbc.Spinner(dcc.Graph(id='grafico-eventos-tipo'), color="primary")
]),
dbc.Tooltip(
"Muestra la distribución total de eventos por cada tipo. "
"La altura de las barras indica la cantidad de eventos registrados.",
target="info-eventos-tipo",
placement="top"
)
], style=CARD_STYLE)
], width=8, className="fade-in"),
dbc.Col([
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-chart-pie me-2"),
"Distribución por Fuente",
html.I(className="fas fa-info-circle ms-2",
id="info-fuente",
style={'cursor': 'pointer', 'color': COLORS['primary']})
], className="fw-bold d-flex align-items-center"),
dbc.CardBody([
dbc.Spinner(dcc.Graph(id='grafico-fuente-datos'), color="primary")
]),
dbc.Tooltip(
"Representa la proporción de eventos según su fuente de datos. "
"Cada sector del gráfico muestra el porcentaje de eventos por fuente.",
target="info-fuente",
placement="top"
)
], style=CARD_STYLE)
], width=4, className="fade-in"),
], className="mb-4"),
# Gráfico de eventos por tipo y fuente
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-chart-bar me-2"),
"Eventos por Tipo y Fuente",
html.I(className="fas fa-info-circle ms-2",
id="info-tipo-fuente",
style={'cursor': 'pointer', 'color': COLORS['primary']})
], className="fw-bold d-flex align-items-center"),
dbc.CardBody([
dbc.Spinner(dcc.Graph(id='grafico-eventos-tipo-fuente'), color="primary")
]),
dbc.Tooltip(
"Muestra la distribución de eventos por tipo y fuente de datos. "
"Las barras agrupadas permiten comparar la cantidad de eventos entre fuentes para cada tipo.",
target="info-tipo-fuente",
placement="top"
)
], style=CARD_STYLE)
], width=12, className="fade-in"),
], className="mb-4"),
# Serie temporal
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-chart-line me-2"),
"Serie Temporal de Eventos",
html.I(className="fas fa-info-circle ms-2",
id="info-serie",
style={'cursor': 'pointer', 'color': COLORS['primary']})
], className="fw-bold d-flex align-items-center"),
dbc.CardBody([
dbc.Spinner(dcc.Graph(id='grafico-serie-tiempo'), color="primary")
]),
dbc.Tooltip(
"Muestra la evolución temporal del número de eventos a lo largo de los años. "
"Permite identificar tendencias y patrones temporales en la ocurrencia de eventos.",
target="info-serie",
placement="top"
)
], style=CARD_STYLE)
], width=12, className="fade-in"),
], className="mb-4"),
# Componentes de descarga
dcc.Download(id="descargar-resumen"),
dcc.Download(id="descargar-detalle"),
# Tablas
dbc.Row([
dbc.Col([
html.H3([
html.I(className="fas fa-table me-2"),
"Resumen de Eventos"
], className="d-flex align-items-center"),
html.Div(id='tabla-resumen', className="fade-in"),
dbc.ButtonGroup([
dbc.Button([
html.I(className="fas fa-file-excel me-2"),
"Descargar Resumen (Excel)"
], id="btn-descargar-resumen-excel", color="primary", className="mt-2 me-2"),
dbc.Button([
html.I(className="fas fa-file-csv me-2"),
"Descargar Resumen (CSV)"
], id="btn-descargar-resumen-csv", color="secondary", className="mt-2"),
]),
], width=12),
], className="mb-4"),
dbc.Row([
dbc.Col([
html.H3([
html.I(className="fas fa-list-alt me-2"),
"Detalle de Eventos"
], className="d-flex align-items-center"),
html.Div(id='tabla-detallada', className="fade-in"),
dbc.ButtonGroup([
dbc.Button([
html.I(className="fas fa-file-excel me-2"),
"Descargar Detalle (Excel)"
], id="btn-descargar-detalle-excel", color="primary", className="mt-2 me-2"),
dbc.Button([
html.I(className="fas fa-file-csv me-2"),
"Descargar Detalle (CSV)"
], id="btn-descargar-detalle-csv", color="secondary", className="mt-2"),
]),
], width=12),
], className="mb-5"),
# Switch para Análisis Avanzados
dbc.Row([
dbc.Col([
html.Hr(className="mb-4"),
dbc.Switch(
id='switch-analisis-avanzados',
label=[
html.I(className="fas fa-microscope me-2"),
"Mostrar Análisis Avanzados"
],
value=False,
className="mb-3 d-flex align-items-center"
)
], width=12)
]),
# Contenedor para Análisis Avanzados
html.Div([
html.H2([
html.I(className="fas fa-chart-area me-2"),
"Análisis Avanzados"
], className="mt-4 mb-4 d-flex align-items-center fade-in"),
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-calendar-alt me-2"),
"Distribución Temporal Mensual",
html.I(className="fas fa-info-circle ms-2",
id="info-heatmap",
style={'cursor': 'pointer', 'color': COLORS['primary']})
], className="fw-bold d-flex align-items-center"),
dbc.CardBody([
dbc.Spinner(dcc.Graph(id='grafico-heatmap-temporal'), color="primary")
]),
dbc.Tooltip(
"Mapa de calor que muestra la intensidad de eventos por mes y año. "
"Los colores más intensos indican mayor cantidad de eventos.",
target="info-heatmap",
placement="top"
)
], style=CARD_STYLE)
], width=12, className="fade-in"),
], className="mb-4"),
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-chart-bar me-2"),
"Estacionalidad de Eventos",
html.I(className="fas fa-info-circle ms-2",
id="info-estacionalidad",
style={'cursor': 'pointer', 'color': COLORS['primary']})
], className="fw-bold d-flex align-items-center"),
dbc.CardBody([
dbc.Spinner(dcc.Graph(id='grafico-estacionalidad'), color="primary")
]),
dbc.Tooltip(
"Muestra la distribución mensual agregada de eventos. "
"Permite identificar los meses con mayor frecuencia de eventos.",
target="info-estacionalidad",
placement="top"
)
], style=CARD_STYLE)
], width=6, className="fade-in"),
dbc.Col([
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-project-diagram me-2"),
"Correlación entre Tipos de Eventos",
html.I(className="fas fa-info-circle ms-2",
id="info-correlacion",
style={'cursor': 'pointer', 'color': COLORS['primary']})
], className="fw-bold d-flex align-items-center"),
dbc.CardBody([
dbc.Spinner(dcc.Graph(id='grafico-correlacion'), color="primary")
]),
dbc.Tooltip(
"Matriz que muestra la correlación entre diferentes tipos de eventos. "
"Colores más intensos indican mayor correlación entre tipos de eventos.",
target="info-correlacion",
placement="top"
)
], style=CARD_STYLE)
], width=6, className="fade-in"),
], className="mb-4"),
dbc.Row([
dbc.Col([
dbc.Card([
dbc.CardHeader([
html.I(className="fas fa-chart-line me-2"),
"Tendencias por Tipo de Evento",
html.I(className="fas fa-info-circle ms-2",
id="info-tendencias",
style={'cursor': 'pointer', 'color': COLORS['primary']})
], className="fw-bold d-flex align-items-center"),
dbc.CardBody([
dbc.Spinner(dcc.Graph(id='grafico-tendencias'), color="primary")
]),
dbc.Tooltip(
"Muestra la evolución temporal de cada tipo de evento. "
"Permite comparar tendencias entre diferentes tipos de eventos a lo largo del tiempo.",
target="info-tendencias",
placement="top"
)
], style=CARD_STYLE)
], width=12, className="fade-in"),
], className="mb-4"),
], id='contenedor-analisis-avanzados', style={'display': 'none'})
], style=CONTENT_STYLE)
app.index_string = '''
<!DOCTYPE html>
<html>
<head>
{%metas%}
<title>{%title%}</title>
{%favicon%}
{%css%}
<style>
/* Animaciones de entrada */
.fade-in {
animation: fadeIn 0.5s ease-in;
opacity: 0;
animation-fill-mode: forwards;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
/* Efectos hover en las tarjetas */
.card {
transition: transform 0.3s ease, box-shadow 0.3s ease;
border-radius: 8px;
}
.card:hover {
transform: translateY(-5px);
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
/* Estilo para los iconos */
.card-header i:not(.fa-info-circle) {
color: #4285f4;
}
/* Animación para los spinners */
.spinner-border {
animation-duration: 1s;
}
/* Estilo para los tooltips */
.tooltip {
animation: tooltipFade 0.2s;
font-size: 0.9rem;
}
@keyframes tooltipFade {
from { opacity: 0; }
to { opacity: 1; }
}
/* Estilos para los botones */
.btn {
transition: all 0.2s ease;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
/* Estilo para el switch */
.custom-switch {
padding-left: 2.25rem;
}
.custom-control-label {
padding-top: 0.125rem;
}
/* Estilo para las tablas */
.dash-table-container {
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
/* Estilo para los encabezados */
h2, h3 {
color: #2c3e50;
font-weight: 600;
}
/* Estilo para el navbar */
.navbar {
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
/* Estilo para los íconos de info */
.fa-info-circle {
transition: color 0.2s ease;
}
.fa-info-circle:hover {
color: #1a73e8 !important;
}
</style>
</head>
<body>
{%app_entry%}
<footer>
{%config%}
{%scripts%}
{%renderer%}
</footer>
</body>
</html>
'''
# Layout principal
app.layout = html.Div([sidebar, content])
@app.callback(
Output('tipo-evento-checklist', 'value'),
Input('tipo-evento-checklist', 'value')
)
def update_checklist(selected_values):
if 'todos' in selected_values:
return ['todos'] + list(tipos_eventos)
else:
return [value for value in selected_values if value != 'todos']
# Modificar la función crear_grafico_serie_tiempo
def crear_grafico_serie_tiempo(df):
"""
Crea un gráfico de línea que muestra la evolución temporal de eventos
"""
try:
if df.empty:
return px.line(title="No hay datos disponibles")
df = df.copy()
df['FECHA'] = pd.to_datetime(df['FECHA'])
eventos_por_año = df.groupby(df['FECHA'].dt.year).size().reset_index()
eventos_por_año.columns = ['Año', 'Cantidad']
fig = go.Figure()
# Agregar área con relleno
fig.add_trace(go.Scatter(
x=eventos_por_año['Año'],
y=eventos_por_año['Cantidad'],
mode='lines+markers',
line=dict(color='rgb(66, 133, 244)', width=2),
fill='tozeroy', # Relleno desde la línea hasta el eje x
fillcolor='rgba(66, 133, 244, 0.2)', # Color azul semi-transparente
name='Eventos'
))
fig.update_layout(
title='Eventos por Año',
xaxis_title='Año',
yaxis_title='Número de eventos',
showlegend=False,
plot_bgcolor='white',
paper_bgcolor='white',
xaxis=dict(
showgrid=True,
gridcolor='rgba(0,0,0,0.1)'
),
yaxis=dict(
showgrid=True,
gridcolor='rgba(0,0,0,0.1)'
)
)
return fig
except Exception as e:
print(f"Error en crear_grafico_serie_tiempo: {str(e)}")
return px.line(title="Error al crear el gráfico")
# Modificar el callback principal para incluir el nuevo input
@app.callback(
[Output('total-eventos', 'children'),
Output('mapa-colombia', 'figure'),
Output('grafico-eventos-tipo', 'figure'),
Output('grafico-fuente-datos', 'figure'),
Output('grafico-eventos-tipo-fuente', 'figure'),
Output('grafico-serie-tiempo', 'figure'),
Output('tabla-resumen', 'children'),
Output('tabla-detallada', 'children'),
Output('grafico-heatmap-temporal', 'figure'),
Output('grafico-estacionalidad', 'figure'),
Output('grafico-correlacion', 'figure'),
Output('grafico-tendencias', 'figure')],
[Input('municipio-input', 'value'),
Input('tipo-evento-checklist', 'value'),
Input('fuentes-checklist', 'value')]
)
def actualizar_graficos(municipio, tipos_seleccionados, fuentes_seleccionadas):
try:
if not municipio:
return ("No se ha seleccionado ningún municipio", crear_mapa_colombia(),
px.bar(), px.pie(), px.bar(), px.line(), None, None,
px.imshow([[0]], title="No hay datos disponibles"),
px.bar(title="No hay datos disponibles"),
px.imshow([[0]], title="No hay datos disponibles"),
px.line(title="No hay datos disponibles"))
if not fuentes_seleccionadas:
return ("Debe seleccionar al menos una fuente de datos", crear_mapa_colombia(),
px.bar(), px.pie(), px.bar(), px.line(), None, None,
px.imshow([[0]], title="No hay datos disponibles"),
px.bar(title="No hay datos disponibles"),
px.imshow([[0]], title="No hay datos disponibles"),
px.line(title="No hay datos disponibles"))
municipio_norm = normalizar_texto(municipio)
# Filtrar eventos del municipio seleccionado por cada fuente
eventos_ungrd = pd.DataFrame()
eventos_dagran = pd.DataFrame()
eventos_simma = gpd.GeoDataFrame()
if 'UNGRD' in fuentes_seleccionadas:
eventos_ungrd = df_eventos_municipio[
(df_eventos_municipio['MUNICIPIO'].apply(normalizar_texto).str.contains(municipio_norm, case=False, na=False)) &
(df_eventos_municipio['FUENTE'] == 'UNGRD')
].copy()
if 'DAGRAN' in fuentes_seleccionadas:
eventos_dagran = df_eventos_municipio[
(df_eventos_municipio['MUNICIPIO'].apply(normalizar_texto).str.contains(municipio_norm, case=False, na=False)) &
(df_eventos_municipio['FUENTE'] == 'DAGRAN')
].copy()
if 'SIMMA' in fuentes_seleccionadas:
municipio_geom = gdf_municipios[gdf_municipios['MpNombre'].apply(normalizar_texto).str.contains(municipio_norm, case=False)].geometry
if not municipio_geom.empty:
eventos_simma = gdf_eventos_shp[gdf_eventos_shp.geometry.within(municipio_geom.iloc[0])].copy()
eventos_simma['FUENTE'] = 'SIMMA'
# Concatenar los eventos de las fuentes seleccionadas
df_total_municipio = pd.concat([
df for df in [eventos_ungrd, eventos_dagran, eventos_simma]
if not df.empty
])
if df_total_municipio.empty:
return (f"No se encontraron eventos para {municipio}", crear_mapa_colombia(),
px.bar(), px.pie(), px.bar(), px.line(), None, None,
px.imshow([[0]], title="No hay datos disponibles"),
px.bar(title="No hay datos disponibles"),
px.imshow([[0]], title="No hay datos disponibles"),
px.line(title="No hay datos disponibles"))
# Asegurarse de que la columna FECHA esté en formato datetime
df_total_municipio['FECHA'] = pd.to_datetime(df_total_municipio['FECHA'], errors='coerce')
# Normalizar los tipos de eventos
df_total_municipio['TIPO'] = df_total_municipio['TIPO'].apply(normalizar_tipo_evento)
# Filtrar por tipos de eventos seleccionados
if tipos_seleccionados and 'todos' not in tipos_seleccionados:
df_total_municipio = df_total_municipio[df_total_municipio['TIPO'].isin(tipos_seleccionados)]
total_eventos = len(df_total_municipio)
# Crear todos los gráficos