CtrEditor/investigate_tsnet_structure.py

159 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""
Investigación detallada de la estructura de pipes en TSNet
"""
import sys
import os
def investigate_tsnet_pipe_structure():
"""
Investiga la estructura real de los objetos Pipe en TSNet
"""
print("=== INVESTIGACIÓN DE ESTRUCTURA PIPE EN 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 un archivo INP existente que funcione
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:
tm = tsnet.network.TransientModel(inp_path)
print("✓ Modelo cargado exitosamente")
# Investigar todos los atributos del modelo
print("\n=== ATRIBUTOS DEL TRANSIENT MODEL ===")
model_attrs = [attr for attr in dir(tm) if not attr.startswith("_")]
for attr in sorted(model_attrs):
print(f" - {attr}")
# Verificar si tiene links
if hasattr(tm, "links"):
print(f"\n✓ tm.links existe, tipo: {type(tm.links)}")
print(
f" - Número de links: {len(tm.links) if hasattr(tm.links, '__len__') else 'N/A'}"
)
for i, link in enumerate(tm.links):
print(f"\n=== LINK {i} ===")
print(f" Tipo: {type(link)}")
print(f" Nombre: {getattr(link, 'name', 'NO NAME')}")
# Todos los atributos del link
link_attrs = [attr for attr in dir(link) if not attr.startswith("_")]
print(f" Atributos ({len(link_attrs)}):")
for attr in sorted(link_attrs):
try:
value = getattr(link, attr)
value_str = (
str(value)[:50] + "..."
if len(str(value)) > 50
else str(value)
)
print(f" - {attr}: {value_str}")
except:
print(f" - {attr}: <error al acceder>")
# Verificar si es un Pipe específicamente
if "Pipe" in str(type(link)):
print(f" ✓ ES UN PIPE")
# Verificar initial_head
if hasattr(link, "initial_head"):
print(f" ✓ Tiene initial_head: {link.initial_head}")
else:
print(f" ✗ NO tiene initial_head")
# Intentar asignar
try:
link.initial_head = 0.0
print(f" ✓ initial_head asignado exitosamente")
except Exception as e:
print(f" ✗ Error al asignar initial_head: {e}")
# Verificar si el objeto es read-only o tiene restricciones
print(f" Investigando restricciones...")
print(f" __dict__: {hasattr(link, '__dict__')}")
if hasattr(link, "__dict__"):
print(
f" __dict__ keys: {list(link.__dict__.keys())}"
)
# Verificar otras posibles estructuras
attrs_to_check = ["pipes", "network", "wn", "model"]
for attr_name in attrs_to_check:
if hasattr(tm, attr_name):
attr_value = getattr(tm, attr_name)
print(f"\n✓ tm.{attr_name} existe, tipo: {type(attr_value)}")
# Si es una colección, ver qué contiene
if hasattr(attr_value, "__iter__") and not isinstance(attr_value, str):
try:
items = (
list(attr_value) if hasattr(attr_value, "__iter__") else []
)
print(f" - Número de elementos: {len(items)}")
if items:
print(f" - Primer elemento tipo: {type(items[0])}")
except:
print(f" - No se pudo iterar")
print("\n=== INVESTIGANDO SIMULACIÓN ===")
# Verificar qué pasa cuando intentamos simular
try:
results = tsnet.simulation.MOCSimulator(
tm, results_obj="results", friction="steady"
)
print("✓ Simulación exitosa sin initial_head fix")
except Exception as e:
print(f"✗ Error en simulación: {e}")
# Análisis del error
error_str = str(e)
if "initial_head" in error_str:
print(" → Confirmado: Error por initial_head")
# Buscar dónde exactamente se produce el error
import traceback
print("\nTRACEBACK COMPLETO:")
traceback.print_exc()
else:
print(" → Error diferente, no relacionado con initial_head")
return True
except Exception as e:
print(f"✗ Error general: {e}")
import traceback
traceback.print_exc()
return False
def main():
"""Función principal"""
print("Iniciando investigación detallada de TSNet...")
success = investigate_tsnet_pipe_structure()
return success
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)