tdgl-solver 0.1.1__py3-none-any.whl

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.
@@ -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"]
tdgl_solver/gui_st.py ADDED
@@ -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()