162 lines
5.7 KiB
Python
162 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Prueba final de corrección TSNet - simulando PythonInterop.cs
|
|
"""
|
|
|
|
import sys
|
|
import os
|
|
import tempfile
|
|
|
|
|
|
def test_complete_tsnet_fix():
|
|
"""
|
|
Prueba la corrección completa de TSNet usando el mismo código que PythonInterop.cs
|
|
"""
|
|
print("=== PRUEBA FINAL CORRECCIÓN 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=== SIMULANDO CÓDIGO DE PythonInterop.cs ===")
|
|
|
|
# PASO 1: Cargar modelo TSNet
|
|
print("1. Cargando modelo TSNet...")
|
|
tm = tsnet.network.TransientModel(inp_path)
|
|
print("✓ Modelo cargado")
|
|
|
|
# PASO 2: CORRECCIÓN DIVISIÓN POR CERO
|
|
print("\n2. Aplicando corrección división por cero...")
|
|
print(f"simulation_period inicial = {getattr(tm, 'simulation_period', 'N/A')}")
|
|
print(f"time_step inicial = {getattr(tm, 'time_step', 'N/A')}")
|
|
|
|
if hasattr(tm, "simulation_period") and tm.simulation_period <= 0:
|
|
tm.simulation_period = 1.0
|
|
print("✓ simulation_period configurado = 1.0 (era <= 0)")
|
|
|
|
if hasattr(tm, "time_step") and tm.time_step <= 0:
|
|
tm.time_step = 0.1
|
|
print("✓ time_step configurado = 0.1 (era <= 0)")
|
|
|
|
# Verificar relación entre parámetros
|
|
if tm.time_step >= tm.simulation_period:
|
|
tm.time_step = tm.simulation_period / 10.0
|
|
print(f"✓ time_step ajustado a {tm.time_step} (era >= simulation_period)")
|
|
|
|
print(f"simulation_period final = {tm.simulation_period}")
|
|
print(f"time_step final = {tm.time_step}")
|
|
print(f"pasos de simulación = {int(tm.simulation_period/tm.time_step)}")
|
|
|
|
# PASO 3: CORRECCIÓN INITIAL_HEAD e INITIAL_VELOCITY (nueva versión)
|
|
print("\n3. Aplicando corrección initial_head e initial_velocity...")
|
|
pipes_fixed = 0
|
|
try:
|
|
# Acceder a pipes usando pipe_name_list y get_link
|
|
if hasattr(tm, "pipe_name_list") and hasattr(tm, "get_link"):
|
|
pipe_names = tm.pipe_name_list
|
|
print(f"Pipes encontrados: {pipe_names}")
|
|
|
|
for pipe_name in pipe_names:
|
|
try:
|
|
pipe_obj = tm.get_link(pipe_name)
|
|
print(f" Pipe {pipe_name}: tipo {type(pipe_obj)}")
|
|
|
|
# Corrección initial_head
|
|
if not hasattr(pipe_obj, "initial_head"):
|
|
pipe_obj.initial_head = 0.0
|
|
pipes_fixed += 1
|
|
print(f" ✓ initial_head asignado = 0.0")
|
|
else:
|
|
print(
|
|
f" ✓ ya tiene initial_head = {pipe_obj.initial_head}"
|
|
)
|
|
|
|
# Corrección initial_velocity
|
|
if not hasattr(pipe_obj, "initial_velocity"):
|
|
pipe_obj.initial_velocity = 0.0
|
|
pipes_fixed += 1
|
|
print(f" ✓ initial_velocity asignado = 0.0")
|
|
else:
|
|
print(
|
|
f" ✓ ya tiene initial_velocity = {pipe_obj.initial_velocity}"
|
|
)
|
|
|
|
except Exception as e:
|
|
print(f" ✗ Error corrigiendo pipe {pipe_name}: {e}")
|
|
|
|
print(f"✓ {pipes_fixed} atributos corregidos en pipes")
|
|
|
|
except Exception as e:
|
|
print(f"✗ Error aplicando corrección pipes: {e}")
|
|
|
|
# PASO 4: SIMULACIÓN
|
|
print("\n4. Ejecutando simulación TSNet...")
|
|
try:
|
|
results = tsnet.simulation.MOCSimulator(
|
|
tm, results_obj="results", friction="steady"
|
|
)
|
|
print("🎉 ¡SIMULACIÓN TSNET EXITOSA!")
|
|
print("✅ Todas las correcciones funcionan correctamente")
|
|
print("✅ TSNet funciona sin fallback a WNTR")
|
|
return True
|
|
|
|
except Exception as tsnet_error:
|
|
print(f"✗ Error en TSNet: {tsnet_error}")
|
|
|
|
# Analizar el tipo de error
|
|
error_str = str(tsnet_error)
|
|
if "initial_head" in error_str:
|
|
print("❌ Error de initial_head - corrección insuficiente")
|
|
elif "division by zero" in error_str:
|
|
print("❌ Error de división por cero - corrección insuficiente")
|
|
else:
|
|
print(f"❌ Nuevo error: {error_str}")
|
|
|
|
print("\n--- TRACEBACK DE TSNET ---")
|
|
import traceback
|
|
|
|
traceback.print_exc()
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f"✗ Error general: {e}")
|
|
import traceback
|
|
|
|
traceback.print_exc()
|
|
return False
|
|
|
|
|
|
def main():
|
|
"""Función principal"""
|
|
success = test_complete_tsnet_fix()
|
|
|
|
if success:
|
|
print("\n🎉 ¡CORRECCIÓN COMPLETA EXITOSA!")
|
|
print("La simulación TSNet funciona perfectamente")
|
|
print("Listo para usar en CtrEditor sin fallback")
|
|
else:
|
|
print("\n⚠️ CORRECCIÓN PARCIAL O FALLIDA")
|
|
print("Revisar errores para ajustes adicionales")
|
|
|
|
return success
|
|
|
|
|
|
if __name__ == "__main__":
|
|
success = main()
|
|
sys.exit(0 if success else 1)
|