tdgl-solver 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. tdgl_solver-0.1.1/LICENSE +21 -0
  2. tdgl_solver-0.1.1/PKG-INFO +92 -0
  3. tdgl_solver-0.1.1/README.md +71 -0
  4. tdgl_solver-0.1.1/pyproject.toml +38 -0
  5. tdgl_solver-0.1.1/setup.cfg +4 -0
  6. tdgl_solver-0.1.1/src/tdgl_solver/__init__.py +10 -0
  7. tdgl_solver-0.1.1/src/tdgl_solver/gui_st.py +445 -0
  8. tdgl_solver-0.1.1/src/tdgl_solver/gui_tk.py +561 -0
  9. tdgl_solver-0.1.1/src/tdgl_solver/io_handler.py +97 -0
  10. tdgl_solver-0.1.1/src/tdgl_solver/octave_engine/config_simulacion.m +29 -0
  11. tdgl_solver-0.1.1/src/tdgl_solver/octave_engine/main.m +57 -0
  12. tdgl_solver-0.1.1/src/tdgl_solver/octave_engine/src/aplicar_suavizado_3d.m +74 -0
  13. tdgl_solver-0.1.1/src/tdgl_solver/octave_engine/src/calcular_observables.m +97 -0
  14. tdgl_solver-0.1.1/src/tdgl_solver/octave_engine/src/exportar_resultados.m +45 -0
  15. tdgl_solver-0.1.1/src/tdgl_solver/octave_engine/src/guardar_restart.m +24 -0
  16. tdgl_solver-0.1.1/src/tdgl_solver/octave_engine/src/init_sistema.m +147 -0
  17. tdgl_solver-0.1.1/src/tdgl_solver/octave_engine/src/solver_tdgl_2d.m +150 -0
  18. tdgl_solver-0.1.1/src/tdgl_solver/octave_engine/src/solver_tdgl_3d.m +176 -0
  19. tdgl_solver-0.1.1/src/tdgl_solver/runner.py +235 -0
  20. tdgl_solver-0.1.1/src/tdgl_solver.egg-info/PKG-INFO +92 -0
  21. tdgl_solver-0.1.1/src/tdgl_solver.egg-info/SOURCES.txt +24 -0
  22. tdgl_solver-0.1.1/src/tdgl_solver.egg-info/dependency_links.txt +1 -0
  23. tdgl_solver-0.1.1/src/tdgl_solver.egg-info/entry_points.txt +2 -0
  24. tdgl_solver-0.1.1/src/tdgl_solver.egg-info/requires.txt +11 -0
  25. tdgl_solver-0.1.1/src/tdgl_solver.egg-info/top_level.txt +1 -0
  26. tdgl_solver-0.1.1/tests/test_tdgl_solver.py +173 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ludere65-eng
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,92 @@
1
+ Metadata-Version: 2.4
2
+ Name: tdgl-solver
3
+ Version: 0.1.1
4
+ Summary: Simulador numérico TDGL (2D 2-Bandas y 3D) con motor Octave e interfaces gráficas en Python.
5
+ Author: Luder Espitia Guzmán
6
+ License: MIT
7
+ Requires-Python: >=3.9
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: numpy>=1.24.0
11
+ Requires-Dist: scipy>=1.10.0
12
+ Requires-Dist: matplotlib>=3.7.0
13
+ Requires-Dist: streamlit>=1.30.0
14
+ Requires-Dist: plotly>=5.18.0
15
+ Requires-Dist: pandas>=2.0.0
16
+ Requires-Dist: seaborn>=0.13.0
17
+ Provides-Extra: docs
18
+ Requires-Dist: mkdocs-material>=9.0.0; extra == "docs"
19
+ Requires-Dist: mkdocstrings[python]>=0.24.0; extra == "docs"
20
+ Dynamic: license-file
21
+
22
+ # TDGL Solver
23
+
24
+ Un paquete integral en Python para la simulación numérica y análisis avanzado de ecuaciones dependientes del tiempo de Ginzburg-Landau (TDGL). Diseñado para estudiar la dinámica de vórtices y skyrmiones en sistemas superconductores de múltiples bandas.
25
+
26
+ ## Características Principales
27
+
28
+ * **Motor Numérico Híbrido:** Núcleo de cálculo modularizado en GNU Octave encapsulado mediante un orquestador en Python.
29
+ * **Modelos Soportados:**
30
+ * **2D de Dos Bandas:** Acoplamiento interbanda (`Gap`) para densidades fraccionarias.
31
+ * **3D de Una Banda:** Entornos de caja interna/externa con geometrías configurables (`tau`) y suavizado de bordes.
32
+ * **Sistema de Caché Inteligente:** Detección de huella digital (SHA-256) de parámetros que evita recalcular configuraciones ya simuladas.
33
+ * **Interfaces Gráficas de Usuario (GUIs):**
34
+ * **Escritorio (Tkinter):** Monitor de progreso en tiempo real y ejecución asíncrona.
35
+ * **Web/Dashboard (Streamlit):** Análisis multivariable con Plotly, correlaciones estadísticas (Pandas/Seaborn), streamlines vectoriales y reconstrucción de vórtices 3D.
36
+
37
+ ## Requisitos Previos
38
+
39
+ 1. **GNU Octave:** El motor requiere que GNU Octave esté instalado y disponible en las variables de entorno del sistema (`PATH`).
40
+ * **Linux (Debian/Ubuntu):** `sudo apt install octave`
41
+ * **Windows:** Descargar desde [gnu.org/software/octave](https://gnu.org/software/octave) y agregar a la ruta (`PATH`).
42
+ 2. **Python 3.9+**
43
+
44
+ ## Instalación
45
+
46
+ Clona el repositorio e instala el paquete con todas sus dependencias en modo editable:
47
+
48
+ ```bash
49
+ git clone https://github.com/ludere65-eng/Ginzburg-Landau_solver.git
50
+ cd Ginzburg-Landau_solver
51
+ pip install -e .
52
+ ```
53
+
54
+ Para instalar también las herramientas de generación de documentación:
55
+
56
+ ```bash
57
+ pip install -e ".[docs]"
58
+ ```
59
+
60
+ ## Uso
61
+
62
+ Una vez instalado, tienes dos formas de lanzar la suite de herramientas:
63
+
64
+ ### 1. Interfaz Web Analítica (Streamlit)
65
+ Ideal para análisis de datos interactivos, visualización 3D y gráficos estadísticos:
66
+ ```bash
67
+ streamlit run src/tdgl_solver/gui_st.py
68
+ ```
69
+
70
+ ### 2. Interfaz de Escritorio (Tkinter)
71
+ Ligera y nativa, ideal para lanzar simulaciones rápidamente de forma local:
72
+ ```bash
73
+ tdgl-tk
74
+ ```
75
+
76
+ ## Documentación
77
+
78
+ Para generar y visualizar la documentación técnica localmente con MkDocs:
79
+
80
+ ```bash
81
+ mkdocs serve
82
+ ```
83
+
84
+ Para desplegarla directamente en GitHub Pages:
85
+
86
+ ```bash
87
+ mkdocs gh-deploy
88
+ ```
89
+
90
+ ## Estructura del Proyecto
91
+
92
+ Los resultados de las simulaciones se guardan automáticamente en la carpeta `runs/` en la raíz del proyecto, clasificados por modelo y un hash único de los parámetros físicos utilizados. Las carpetas `Codigo2/output` y `Codigo3/output` mantienen la compatibilidad con las corridas *legacy*.
@@ -0,0 +1,71 @@
1
+ # TDGL Solver
2
+
3
+ Un paquete integral en Python para la simulación numérica y análisis avanzado de ecuaciones dependientes del tiempo de Ginzburg-Landau (TDGL). Diseñado para estudiar la dinámica de vórtices y skyrmiones en sistemas superconductores de múltiples bandas.
4
+
5
+ ## Características Principales
6
+
7
+ * **Motor Numérico Híbrido:** Núcleo de cálculo modularizado en GNU Octave encapsulado mediante un orquestador en Python.
8
+ * **Modelos Soportados:**
9
+ * **2D de Dos Bandas:** Acoplamiento interbanda (`Gap`) para densidades fraccionarias.
10
+ * **3D de Una Banda:** Entornos de caja interna/externa con geometrías configurables (`tau`) y suavizado de bordes.
11
+ * **Sistema de Caché Inteligente:** Detección de huella digital (SHA-256) de parámetros que evita recalcular configuraciones ya simuladas.
12
+ * **Interfaces Gráficas de Usuario (GUIs):**
13
+ * **Escritorio (Tkinter):** Monitor de progreso en tiempo real y ejecución asíncrona.
14
+ * **Web/Dashboard (Streamlit):** Análisis multivariable con Plotly, correlaciones estadísticas (Pandas/Seaborn), streamlines vectoriales y reconstrucción de vórtices 3D.
15
+
16
+ ## Requisitos Previos
17
+
18
+ 1. **GNU Octave:** El motor requiere que GNU Octave esté instalado y disponible en las variables de entorno del sistema (`PATH`).
19
+ * **Linux (Debian/Ubuntu):** `sudo apt install octave`
20
+ * **Windows:** Descargar desde [gnu.org/software/octave](https://gnu.org/software/octave) y agregar a la ruta (`PATH`).
21
+ 2. **Python 3.9+**
22
+
23
+ ## Instalación
24
+
25
+ Clona el repositorio e instala el paquete con todas sus dependencias en modo editable:
26
+
27
+ ```bash
28
+ git clone https://github.com/ludere65-eng/Ginzburg-Landau_solver.git
29
+ cd Ginzburg-Landau_solver
30
+ pip install -e .
31
+ ```
32
+
33
+ Para instalar también las herramientas de generación de documentación:
34
+
35
+ ```bash
36
+ pip install -e ".[docs]"
37
+ ```
38
+
39
+ ## Uso
40
+
41
+ Una vez instalado, tienes dos formas de lanzar la suite de herramientas:
42
+
43
+ ### 1. Interfaz Web Analítica (Streamlit)
44
+ Ideal para análisis de datos interactivos, visualización 3D y gráficos estadísticos:
45
+ ```bash
46
+ streamlit run src/tdgl_solver/gui_st.py
47
+ ```
48
+
49
+ ### 2. Interfaz de Escritorio (Tkinter)
50
+ Ligera y nativa, ideal para lanzar simulaciones rápidamente de forma local:
51
+ ```bash
52
+ tdgl-tk
53
+ ```
54
+
55
+ ## Documentación
56
+
57
+ Para generar y visualizar la documentación técnica localmente con MkDocs:
58
+
59
+ ```bash
60
+ mkdocs serve
61
+ ```
62
+
63
+ Para desplegarla directamente en GitHub Pages:
64
+
65
+ ```bash
66
+ mkdocs gh-deploy
67
+ ```
68
+
69
+ ## Estructura del Proyecto
70
+
71
+ Los resultados de las simulaciones se guardan automáticamente en la carpeta `runs/` en la raíz del proyecto, clasificados por modelo y un hash único de los parámetros físicos utilizados. Las carpetas `Codigo2/output` y `Codigo3/output` mantienen la compatibilidad con las corridas *legacy*.
@@ -0,0 +1,38 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "tdgl-solver"
7
+ version = "0.1.1"
8
+ description = "Simulador numérico TDGL (2D 2-Bandas y 3D) con motor Octave e interfaces gráficas en Python."
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = {text = "MIT"}
12
+ authors = [
13
+ {name = "Luder Espitia Guzmán"}
14
+ ]
15
+ dependencies = [
16
+ "numpy>=1.24.0",
17
+ "scipy>=1.10.0",
18
+ "matplotlib>=3.7.0",
19
+ "streamlit>=1.30.0",
20
+ "plotly>=5.18.0",
21
+ "pandas>=2.0.0",
22
+ "seaborn>=0.13.0"
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ docs = [
27
+ "mkdocs-material>=9.0.0",
28
+ "mkdocstrings[python]>=0.24.0"
29
+ ]
30
+
31
+ [project.scripts]
32
+ tdgl-tk = "tdgl_solver.gui_tk:main"
33
+
34
+ [tool.setuptools.packages.find]
35
+ where = ["src"]
36
+
37
+ [tool.setuptools.package-data]
38
+ tdgl_solver = ["octave_engine/*.m", "octave_engine/src/*.m"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,10 @@
1
+ """
2
+ Paquete `tdgl_solver`: Simulación y análisis de vórtices en superconductores
3
+ mediante ecuaciones dependientes del tiempo de Ginzburg-Landau (2D y 3D).
4
+ """
5
+
6
+ from .runner import TDGLRunner
7
+ from .io_handler import TDGLDataLoader
8
+
9
+ __version__ = "0.1.0"
10
+ __all__ = ["TDGLRunner", "TDGLDataLoader"]
@@ -0,0 +1,445 @@
1
+ # src/tdgl_solver/gui_st.py
2
+
3
+ """
4
+ Interfaz web interactiva completa en Streamlit para simulación TDGL (con caché)
5
+ y análisis avanzado (cuadrículas, mapas interactivos, vectores, estadística y 3D).
6
+ """
7
+
8
+ import time
9
+ from pathlib import Path
10
+ from typing import Dict, List, Any
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ import matplotlib.pyplot as plt
15
+ import streamlit as st
16
+
17
+ import plotly.express as px
18
+ import plotly.graph_objects as go
19
+ import plotly.figure_factory as ff
20
+
21
+ from tdgl_solver.io_handler import TDGLDataLoader
22
+ from tdgl_solver.runner import TDGLRunner
23
+
24
+
25
+ st.set_page_config(
26
+ page_title="TDGL Solver | Suite de Simulación y Análisis",
27
+ layout="wide",
28
+ initial_sidebar_state="expanded",
29
+ )
30
+
31
+ RUTAS_BASE: Dict[str, str] = {
32
+ "Modularizado": "output_modular",
33
+ "2D_2bandas sin modularizar": "Codigo2/output",
34
+ "3D_1banda sin modularizar": "Codigo3/output",
35
+ }
36
+
37
+ NOMBRES_VARIABLES: Dict[str, str] = {
38
+ "d": "Densidad Banda 1 (|ψ₁|)",
39
+ "B": "Densidad Banda 2 (|ψ₂|)",
40
+ "d4": "Parámetro Orden 3D (|ψ|)",
41
+ "d2": "Logaritmo Orden (log|ψ|)",
42
+ "hz": "Campo Magnético (Bz)",
43
+ "phase": "Fase Superconductora (θ)",
44
+ "aJx": "Supercorriente X (Jx)",
45
+ "aJy": "Supercorriente Y (Jy)",
46
+ }
47
+
48
+
49
+ def resolver_ruta(ruta_str: str) -> Path:
50
+ p = Path(ruta_str)
51
+ if p.exists():
52
+ return p
53
+ return Path(__file__).resolve().parents[2] / ruta_str
54
+
55
+
56
+ def construir_figura_base(
57
+ matriz: np.ndarray,
58
+ var_key: str,
59
+ h_val: str,
60
+ z_idx: int,
61
+ cmap_name: str,
62
+ fijar_escala: bool,
63
+ ) -> plt.Figure:
64
+ """Genera figura Matplotlib compacta para la cuadrícula y animación."""
65
+ if matriz.ndim == 3:
66
+ vista = matriz[:, :, z_idx]
67
+ subtitulo = f"H = {h_val} | Z = {z_idx}"
68
+ else:
69
+ vista = matriz
70
+ subtitulo = f"H = {h_val}"
71
+
72
+ fig, ax = plt.subplots(figsize=(3.5, 3.0), dpi=110)
73
+
74
+ vmin, vmax = None, None
75
+ if fijar_escala:
76
+ if var_key in ("d4", "B"):
77
+ vmin, vmax = 0.0, 1.0
78
+ elif var_key == "phase":
79
+ vmin, vmax = -np.pi, np.pi
80
+
81
+ im = ax.imshow(
82
+ vista, cmap=cmap_name, origin="lower", vmin=vmin, vmax=vmax, aspect="equal"
83
+ )
84
+ cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04)
85
+ cbar.ax.tick_params(labelsize=7)
86
+
87
+ titulo = NOMBRES_VARIABLES.get(var_key, var_key)
88
+ ax.set_title(f"{titulo}\n({subtitulo})", fontsize=8.5, fontweight="bold")
89
+ ax.set_xlabel("x", fontsize=7)
90
+ ax.set_ylabel("y", fontsize=7)
91
+ ax.tick_params(labelsize=7)
92
+ fig.tight_layout()
93
+ return fig
94
+
95
+
96
+ def mostrar_panel_simulacion(runner: TDGLRunner) -> None:
97
+ st.subheader("⚙️ Configurar y Ejecutar Nueva Simulación TDGL")
98
+ st.markdown(
99
+ "El sistema verificará automáticamente si ya existe una simulación "
100
+ "con los mismos parámetros y cargará los resultados desde la memoria caché."
101
+ )
102
+
103
+ modelo = st.radio(
104
+ "Arquitectura del Modelo:", options=["2D_2Bandas", "3D_1Banda"], horizontal=True
105
+ )
106
+
107
+ col_geom, col_fis, col_mag = st.columns(3)
108
+
109
+ with col_geom:
110
+ st.markdown("#### 1. Geometría y Malla")
111
+ dx = st.number_input("Paso espacial dx:", value=0.25, step=0.05)
112
+ dy = st.number_input("Paso espacial dy:", value=0.25, step=0.05)
113
+ a = st.number_input(
114
+ "Caja externa X (a):", value=10.0 if modelo == "2D_2Bandas" else 20.0, step=1.0
115
+ )
116
+ b = st.number_input(
117
+ "Caja externa Y (b):", value=10.0 if modelo == "2D_2Bandas" else 20.0, step=1.0
118
+ )
119
+ if modelo == "3D_1Banda":
120
+ dz = st.number_input("Paso espacial dz:", value=0.25, step=0.05)
121
+ c = st.number_input("Caja externa Z (c):", value=10.0, step=1.0)
122
+ aa = st.number_input("Caja interna X (aa):", value=10.0, step=1.0)
123
+ bb = st.number_input("Caja interna Y (bb):", value=10.0, step=1.0)
124
+ cc = st.number_input("Caja interna Z (cc):", value=5.0, step=1.0)
125
+
126
+ with col_fis:
127
+ st.markdown("#### 2. Parámetros Físicos")
128
+ kappa = st.number_input("Parámetro G-L (κ):", value=1.0, step=0.1)
129
+ bt = st.number_input("Relajación (β):", value=1.0, step=0.1)
130
+ T = st.number_input("Temperatura (T/Tc):", value=0.0, max_value=0.99, step=0.05)
131
+ if modelo == "2D_2Bandas":
132
+ Gap = st.number_input("Acoplamiento (Gap):", value=-0.001, format="%.4f")
133
+ else:
134
+ geometria_tau = st.selectbox("Geometría enlaces (tau):", ["bloque", "estricto"])
135
+ suavizado_bordes = st.selectbox(
136
+ "Suavizado fronteras 3D:", ["8_vertices", "12_aristas", "ambos"]
137
+ )
138
+
139
+ with col_mag:
140
+ st.markdown("#### 3. Control y Barrido H")
141
+ Hi = st.number_input("Campo inicial (Hi):", value=0.0, step=0.1)
142
+ Hf = st.number_input("Campo final (Hf):", value=0.2, step=0.1)
143
+ dH = st.number_input("Paso de campo (dH):", value=0.1, step=0.05)
144
+ eps = st.number_input(
145
+ "Tolerancia (eps):", value=1e-5 if modelo == "2D_2Bandas" else 1e-7, format="%.1e"
146
+ )
147
+ nMax = st.number_input("Iteraciones máx (nMax):", value=10000000, step=100000)
148
+ lMax = st.number_input("Sub-iteraciones (lMax):", value=100, step=10)
149
+
150
+ params: Dict[str, Any] = {
151
+ "modelo": modelo, "dx": dx, "dy": dy, "a": a, "b": b,
152
+ "kappa": kappa, "bt": bt, "T": T, "Hi": Hi, "Hf": Hf,
153
+ "dH": dH, "eps": eps, "nMax": int(nMax), "lMax": int(lMax),
154
+ }
155
+ if modelo == "3D_1Banda":
156
+ params.update({
157
+ "dz": dz, "c": c, "aa": aa, "bb": bb, "cc": cc,
158
+ "geometria_tau": geometria_tau, "suavizado_bordes": suavizado_bordes,
159
+ })
160
+ else:
161
+ params.update({"Gap": Gap})
162
+
163
+ en_cache, ruta_esperada, norm = runner.verificar_cache(params)
164
+ if en_cache:
165
+ st.success(
166
+ f"⚡ **Parámetros detectados en caché.** Resultados disponibles en `{ruta_esperada.name}`."
167
+ )
168
+
169
+ col_btn1, col_btn2 = st.columns([1, 1])
170
+ with col_btn1:
171
+ iniciar = st.button("🚀 Simular / Cargar", type="primary", use_container_width=True)
172
+ with col_btn2:
173
+ forzar = st.checkbox("Forzar recálculo", value=False)
174
+
175
+ if iniciar:
176
+ if en_cache and not forzar:
177
+ st.session_state["ruta_activa"] = str(ruta_esperada)
178
+ st.info("Pasa a la pestaña **📊 Visualizador Analítico** para ver las gráficas.")
179
+ else:
180
+ st.warning(f"Calculando en `{ruta_esperada.name}`. Guardando progresivamente...")
181
+ barra = st.progress(0)
182
+ caja_log = st.empty()
183
+ log_lineas: List[str] = []
184
+ tot_pasos = max(1, int(round((norm["Hf"] - norm["Hi"]) / norm["dH"])) + 1)
185
+ pasos_ok = 0
186
+
187
+ def callback(linea: str) -> None:
188
+ nonlocal pasos_ok
189
+ log_lineas.append(linea)
190
+ caja_log.code("\n".join(log_lineas[-10:]), language="text")
191
+ if "completado en" in linea:
192
+ pasos_ok += 1
193
+ barra.progress(min(1.0, pasos_ok / tot_pasos))
194
+
195
+ try:
196
+ out_dir, _ = runner.ejecutar_con_progreso(
197
+ params, callback_linea=callback, forzar_recalculo=forzar
198
+ )
199
+ barra.progress(1.0)
200
+ st.session_state["ruta_activa"] = str(out_dir)
201
+ st.success("✅ Simulación completada.")
202
+ except Exception as e:
203
+ st.error(f"Error: {e}")
204
+
205
+
206
+ def main() -> None:
207
+ st.title("Simulador TDGL — Plataforma de Análisis Integral")
208
+ runner = TDGLRunner()
209
+
210
+ tab_vis, tab_sim = st.tabs([
211
+ "📊 Visualizador Analítico Multivariable",
212
+ "⚙️ Nueva Simulación (Cálculo)"
213
+ ])
214
+
215
+ with tab_sim:
216
+ mostrar_panel_simulacion(runner)
217
+
218
+ with tab_vis:
219
+ ops_totales: Dict[str, str] = dict(RUTAS_BASE)
220
+ ops_totales.update(runner.listar_simulaciones_cacheadas())
221
+
222
+ st.sidebar.header("1. Selección de Datos")
223
+ nombres_opc = list(ops_totales.keys())
224
+
225
+ idx_def = 0
226
+ if "ruta_activa" in st.session_state:
227
+ ra = st.session_state["ruta_activa"]
228
+ for i, k in enumerate(nombres_opc):
229
+ if Path(ops_totales[k]).resolve() == Path(ra).resolve():
230
+ idx_def = i
231
+ break
232
+
233
+ opcion_modelo = st.sidebar.selectbox("Conjunto de simulación:", options=nombres_opc, index=idx_def)
234
+ ruta_path = resolver_ruta(ops_totales[opcion_modelo])
235
+
236
+ try:
237
+ loader = TDGLDataLoader(str(ruta_path))
238
+ campos = loader.listar_campos_disponibles()
239
+ except FileNotFoundError:
240
+ st.error(f"No se encontró el directorio para **{opcion_modelo}**.")
241
+ return
242
+
243
+ if not campos:
244
+ st.warning("Carpeta vacía (sin pasos H guardados).")
245
+ return
246
+
247
+ datos_test = loader.cargar_paso_campo(campos[0])
248
+ vars_disp = list(datos_test.keys())
249
+ es_3d = any(mat.ndim == 3 for mat in datos_test.values())
250
+
251
+ st.sidebar.header("2. Opciones Base")
252
+ vars_sel: List[str] = st.sidebar.multiselect(
253
+ "Variables activas:", options=vars_disp, default=vars_disp[:min(2, len(vars_disp))],
254
+ format_func=lambda k: NOMBRES_VARIABLES.get(k, k)
255
+ )
256
+ cmap_elegido = st.sidebar.selectbox("Paleta (Mapas 2D):", ["inferno", "viridis", "plasma", "coolwarm", "RdBu_r"], index=0)
257
+ fijar_escala = st.sidebar.checkbox("Fijar escala (Recomendado para animación)", value=True)
258
+
259
+ z_slice = 0
260
+ if es_3d:
261
+ max_z = max(mat.shape[2] for mat in datos_test.values() if mat.ndim == 3) - 1
262
+ st.sidebar.header("3. Corte Transversal Z")
263
+ z_slice = st.sidebar.slider("Capa Z:", 0, max_z, max_z // 2)
264
+
265
+ st.sidebar.header("4. Control H (Animación)")
266
+ modo_anim = st.sidebar.toggle("Animar H (Aplica a Cuadrícula)", value=False)
267
+ h_sel = campos[0]
268
+ if not modo_anim:
269
+ h_sel = st.sidebar.select_slider("Valor de Campo H (Gráficos estáticos):", options=campos, value=campos[0])
270
+ else:
271
+ vel = st.sidebar.slider("Pausa entre cuadros (s):", 0.05, 1.0, 0.2)
272
+ repetir = st.sidebar.checkbox("Bucle continuo", value=False)
273
+ btn_play = st.sidebar.button("▶ Reproducir", type="primary")
274
+
275
+ if not vars_sel:
276
+ st.info("Selecciona variables en el menú lateral.")
277
+ return
278
+
279
+ # Pestañas analíticas internas
280
+ subtabs = st.tabs([
281
+ "🖥️ Cuadrícula Base",
282
+ "🗺️ Plotly: Interactivo",
283
+ "↗️ Flujo y Vectores",
284
+ "📈 Estadística y Correlación",
285
+ "🧊 Reconstrucción 3D"
286
+ ])
287
+
288
+ datos = loader.cargar_paso_campo(h_sel)
289
+
290
+ # -----------------------------------------------------------------
291
+ # 1. CUADRÍCULA BASE (Matplotlib - Soporta Animación Nativa)
292
+ # -----------------------------------------------------------------
293
+ with subtabs[0]:
294
+ cont_grid = st.empty()
295
+
296
+ def dibujar_grid(h_val: str):
297
+ dts = loader.cargar_paso_campo(h_val)
298
+ with cont_grid.container():
299
+ st.markdown(f"**H = {h_val}**")
300
+ cols = st.columns(min(3, len(vars_sel)))
301
+ for idx, vkey in enumerate(vars_sel):
302
+ if vkey in dts:
303
+ fig = construir_figura_base(dts[vkey], vkey, h_val, z_slice, cmap_elegido, fijar_escala)
304
+ with cols[idx % len(cols)]:
305
+ st.pyplot(fig, use_container_width=False)
306
+ plt.close(fig)
307
+
308
+ if modo_anim and btn_play:
309
+ barra_anim = st.progress(0)
310
+ while True:
311
+ for i, hv in enumerate(campos):
312
+ dibujar_grid(hv)
313
+ barra_anim.progress((i + 1) / len(campos))
314
+ time.sleep(vel)
315
+ if not repetir:
316
+ break
317
+ else:
318
+ dibujar_grid(h_sel)
319
+
320
+ # -----------------------------------------------------------------
321
+ # 2. PLOTLY: MAPAS INTERACTIVOS
322
+ # -----------------------------------------------------------------
323
+ with subtabs[1]:
324
+ st.markdown("Gráficos interactivos con hover, zoom y paneo (Estado estático actual).")
325
+ col1, col2 = st.columns(2)
326
+
327
+ var_c1 = vars_sel[0] if len(vars_sel) > 0 else vars_disp[0]
328
+ var_c2 = vars_sel[1] if len(vars_sel) > 1 else vars_disp[-1]
329
+
330
+ for i, (col, vk) in enumerate(zip([col1, col2], [var_c1, var_c2])):
331
+ if vk in datos:
332
+ vista = datos[vk][:, :, z_slice] if es_3d else datos[vk]
333
+ if i == 0:
334
+ fig = go.Figure(data=go.Contour(z=vista, colorscale=cmap_elegido.capitalize(), contours=dict(showlines=False)))
335
+ fig.update_layout(title=f"Contorno: {NOMBRES_VARIABLES.get(vk, vk)}")
336
+ else:
337
+ fig = px.imshow(vista, color_continuous_scale="RdBu_r", title=f"Mapa de Calor: {NOMBRES_VARIABLES.get(vk, vk)}")
338
+ col.plotly_chart(fig, use_container_width=True)
339
+
340
+ # -----------------------------------------------------------------
341
+ # 3. FLUJO Y VECTORES
342
+ # -----------------------------------------------------------------
343
+ with subtabs[2]:
344
+ st.markdown("Análisis vectorial de supercorrientes.")
345
+ if "aJx" in datos and "aJy" in datos:
346
+ jx = datos["aJx"][:, :, z_slice] if es_3d else datos["aJx"]
347
+ jy = datos["aJy"][:, :, z_slice] if es_3d else datos["aJy"]
348
+
349
+ # Quiver interactivo (Reducir densidad de vectores para rendimiento)
350
+ x, y = np.meshgrid(np.arange(0, jx.shape[1], 2), np.arange(0, jx.shape[0], 2))
351
+ u, v = jx[::2, ::2], jy[::2, ::2]
352
+
353
+ fig_q = ff.create_quiver(x, y, u, v, scale=0.5, arrow_scale=0.3, name='J', line_color='crimson')
354
+ fig_q.update_layout(title="Quiver Plot (Vectores J)", margin=dict(l=0, r=0, t=30, b=0))
355
+ st.plotly_chart(fig_q, use_container_width=True)
356
+
357
+ # Streamplot de Matplotlib
358
+ fig_st, ax_st = plt.subplots(figsize=(6, 4))
359
+ magnitud = np.sqrt(jx**2 + jy**2)
360
+ ax_st.streamplot(np.arange(jx.shape[1]), np.arange(jx.shape[0]), jx, jy, density=1.5, color=magnitud, cmap='plasma')
361
+ ax_st.set_title("Líneas de Corriente (Streamlines)")
362
+ st.pyplot(fig_st)
363
+ else:
364
+ st.info("Requiere variables aJx y aJy en los datos actuales.")
365
+
366
+ # -----------------------------------------------------------------
367
+ # 4. ESTADÍSTICA Y CORRELACIÓN
368
+ # -----------------------------------------------------------------
369
+ with subtabs[3]:
370
+ st.markdown("Distribuciones globales para todo el dominio simulado.")
371
+
372
+ # 1. Extraer matrices y manejar las diferencias de tamaño de la malla escalonada
373
+ matrices = {k: v for k, v in datos.items() if v.ndim in (2, 3)}
374
+
375
+ if matrices:
376
+ # 2. Encontrar la forma (shape) mínima común en todas las dimensiones
377
+ ref_ndim = list(matrices.values())[0].ndim
378
+ min_shape = [min(v.shape[i] for v in matrices.values()) for i in range(ref_ndim)]
379
+
380
+ # 3. Recortar y aplanar para garantizar que todas las columnas midan lo mismo
381
+ df_dict = {}
382
+ for k, v in matrices.items():
383
+ if ref_ndim == 2:
384
+ recorte = v[:min_shape[0], :min_shape[1]]
385
+ else:
386
+ recorte = v[:min_shape[0], :min_shape[1], :min_shape[2]]
387
+ df_dict[k] = recorte.flatten()
388
+
389
+ df = pd.DataFrame(df_dict)
390
+
391
+ ce1, ce2, ce3 = st.columns(3)
392
+ with ce1:
393
+ var_hist = st.selectbox("Variable distribuciones:", list(df.columns), key="v_hist")
394
+ fig_h = px.histogram(df, x=var_hist, marginal="box", title=f"Histograma ({var_hist})")
395
+ st.plotly_chart(fig_h, use_container_width=True)
396
+ with ce2:
397
+ fig_v = px.violin(df, y=var_hist, box=True, title=f"Violín ({var_hist})")
398
+ st.plotly_chart(fig_v, use_container_width=True)
399
+ with ce3:
400
+ st.markdown("**Matriz de Correlación**")
401
+ fig_c = px.imshow(df.corr(), text_auto=".2f", color_continuous_scale="RdBu_r")
402
+ st.plotly_chart(fig_c, use_container_width=True)
403
+
404
+ st.markdown("### Relaciones Multivariables")
405
+ cm1, cm2 = st.columns(2)
406
+ df_samp = df.sample(n=min(3000, len(df)), random_state=42)
407
+
408
+ with cm1:
409
+ vx = st.selectbox("Eje X (Dispersión):", list(df.columns), index=0)
410
+ vy = st.selectbox("Eje Y (Dispersión):", list(df.columns), index=min(1, len(df.columns)-1))
411
+ fig_j = px.scatter(df_samp, x=vx, y=vy, marginal_x="histogram", marginal_y="histogram", opacity=0.4)
412
+ st.plotly_chart(fig_j, use_container_width=True)
413
+ with cm2:
414
+ vp = st.multiselect("Coordenadas Paralelas:", list(df.columns), default=list(df.columns)[:4])
415
+ if len(vp) > 1:
416
+ fig_p = px.parallel_coordinates(df_samp, dimensions=vp, color=vp[0], color_continuous_scale=px.colors.diverging.Tealrose)
417
+ st.plotly_chart(fig_p, use_container_width=True)
418
+ # -----------------------------------------------------------------
419
+ # 5. RECONSTRUCCIÓN 3D INTERACTIVA
420
+ # -----------------------------------------------------------------
421
+ with subtabs[4]:
422
+ st.markdown("Visualización volumétrica (Requiere modelo 3D y variable de densidad de pares).")
423
+ if es_3d and ("d4" in datos or "d" in datos):
424
+ var_vol = "d4" if "d4" in datos else "d"
425
+ vol_data = datos[var_vol]
426
+ X, Y, Z = np.mgrid[0:vol_data.shape[0], 0:vol_data.shape[1], 0:vol_data.shape[2]]
427
+
428
+ fig_3d = go.Figure(data=go.Isosurface(
429
+ x=X.flatten(), y=Y.flatten(), z=Z.flatten(),
430
+ value=vol_data.flatten(),
431
+ isomin=0.1, isomax=0.9, surface_count=4,
432
+ colorscale="Viridis", caps=dict(x_show=False, y_show=False)
433
+ ))
434
+ fig_3d.update_layout(
435
+ scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title='Z'),
436
+ title=f"Isosuperficies 3D (Tubos de flujo para {var_vol})",
437
+ margin=dict(l=0, r=0, b=0, t=30)
438
+ )
439
+ st.plotly_chart(fig_3d, use_container_width=True)
440
+ else:
441
+ st.info("La simulación actual no es 3D o carece de la variable de densidad requerida.")
442
+
443
+
444
+ if __name__ == "__main__":
445
+ main()