CtrEditor/investigate_source.py

173 lines
6.1 KiB
Python

#!/usr/bin/env python3
"""
Investigación profunda del código fuente de TSNet para encontrar la causa exacta
"""
import sys
import os
import numpy as np
def investigate_tsnet_source():
"""
Investiga exactamente qué está causando el error de índices
"""
print("=== INVESTIGACIÓN CÓDIGO FUENTE TSNET ===")
try:
import tsnet
import wntr
print(f"✓ TSNet version: {tsnet.__version__}")
print(f"✓ WNTR version: {wntr.__version__}")
except ImportError as e:
print(f"✗ Error al importar: {e}")
return False
# Usar archivo INP existente
temp_dir = r"c:\Users\migue\AppData\Local\Temp\TSNet"
inp_path = os.path.join(temp_dir, "network_20250912_003944.inp")
if not os.path.exists(inp_path):
print(f"✗ Archivo INP no encontrado: {inp_path}")
return False
try:
print("\n=== MODELO SIMPLE PARA DEPURACIÓN ===")
# Cargar modelo
tm = tsnet.network.TransientModel(inp_path)
# Correcciones básicas
if hasattr(tm, "simulation_period") and tm.simulation_period <= 0:
tm.simulation_period = 1.0
if hasattr(tm, "time_step") and tm.time_step <= 0:
tm.time_step = 0.1
print(f"simulation_period = {tm.simulation_period}")
print(f"time_step = {tm.time_step}")
# ESTRATEGIA DIFERENTE: Usar la configuración automática de TSNet
print("\n=== INTENTANDO CONFIGURACIÓN AUTOMÁTICA TSNET ===")
# No modificar los atributos inicialmente, dejar que TSNet maneje la inicialización
# Solo agregar los atributos que definitivamente faltan
for pipe_name in tm.pipe_name_list:
pipe_obj = tm.get_link(pipe_name)
print(f"\nPipe {pipe_name}:")
# Solo agregar wavev si no existe (es crítico)
if not hasattr(pipe_obj, "wavev"):
pipe_obj.wavev = 1000.0
print(f" ✓ wavev = 1000.0")
# Solo agregar roughness_height si no existe
if not hasattr(pipe_obj, "roughness_height"):
if hasattr(pipe_obj, "roughness"):
pipe_obj.roughness_height = pipe_obj.roughness
print(f" ✓ roughness_height = {pipe_obj.roughness}")
else:
pipe_obj.roughness_height = 0.001
print(f" ✓ roughness_height = 0.001")
# Intentar NO TOCAR initial_head, initial_velocity, number_of_segments
# Dejar que TSNet los maneje automáticamente
print(f" ⏭️ Dejando initial_head/velocity para TSNet automático")
# Configurar bombas
for pump_name in tm.pump_name_list:
pump_obj = tm.get_link(pump_name)
if not hasattr(pump_obj, "curve_coef") or pump_obj.curve_coef is None:
pump_obj.curve_coef = [100.0, -0.1, 0.0]
print(f"Bomba {pump_name}: curve_coef = [100.0, -0.1, 0.0]")
# PROBAR SIMULACIÓN CON CONFIGURACIÓN MÍNIMA
print(f"\n=== SIMULACIÓN CON CONFIGURACIÓN MÍNIMA ===")
try:
results = tsnet.simulation.MOCSimulator(
tm, results_obj="results", friction="steady"
)
print("🎉 ¡SIMULACIÓN EXITOSA CON CONFIGURACIÓN MÍNIMA!")
print("✅ TSNet maneja la inicialización automáticamente")
return True
except Exception as e:
print(f"✗ Error con configuración mínima: {e}")
# Si sigue fallando, investigar más profundamente el traceback
print("\n--- ANÁLISIS DETALLADO DEL ERROR ---")
import traceback
tb = traceback.format_exc()
print(tb)
# Buscar la línea exacta que falla
tb_lines = tb.split("\n")
for i, line in enumerate(tb_lines):
if "dVdx[n-1]" in line or "index" in line:
print(f"\n🔍 LÍNEA PROBLEMÁTICA: {line}")
if i > 0:
print(f"🔍 CONTEXTO ANTERIOR: {tb_lines[i-1]}")
if i < len(tb_lines) - 1:
print(f"🔍 CONTEXTO POSTERIOR: {tb_lines[i+1]}")
# Intentar otra estrategia: configuración completa pero con análisis preciso
print(f"\n=== ESTRATEGIA DE CONFIGURACIÓN ANALÍTICA ===")
for pipe_name in tm.pipe_name_list:
pipe_obj = tm.get_link(pipe_name)
pipe_length = getattr(pipe_obj, "length", 1.0)
# Basándome en el error, parece que necesitamos n-1 elementos
# Si el error es "index n-1 is out of bounds for axis 0 with size n"
# entonces necesitamos al menos n elementos para que n-1 sea válido
# Usar una heurística diferente: más segmentos
num_segments = max(int(pipe_length * 100), 50) # Al menos 50 segmentos
print(
f"Pipe {pipe_name}: longitud={pipe_length}, probando {num_segments} segmentos"
)
pipe_obj.initial_head = np.zeros(num_segments)
pipe_obj.initial_velocity = np.zeros(num_segments)
pipe_obj.number_of_segments = num_segments
# Probar de nuevo
try:
results = tsnet.simulation.MOCSimulator(
tm, results_obj="results", friction="steady"
)
print("🎉 ¡SIMULACIÓN EXITOSA CON MÁS SEGMENTOS!")
return True
except Exception as e2:
print(f"✗ Sigue fallando con más segmentos: {e2}")
return False
except Exception as e:
print(f"✗ Error general: {e}")
import traceback
traceback.print_exc()
return False
def main():
"""Función principal"""
success = investigate_tsnet_source()
if success:
print("\n🎉 ¡PROBLEMA RESUELTO!")
print("TSNet funciona sin fallback")
else:
print("\n📋 INFORMACIÓN RECOPILADA")
print("Para análisis más profundo")
return success
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)