USEPA / WNTR

An EPANET compatible python package to simulate and analyze water distribution networks under disaster scenarios.
Other
312 stars 181 forks source link

Error checking #438

Open aloisio0 opened 1 month ago

aloisio0 commented 1 month ago

Summary I'm using wntr to develop a plugin for QGIS. I'm doing a check to avoid simulation errors. My goal is to display a message with the error code when I try to simulate a network with an error. My goal is to get just an error message informing the code, without generating the error. Is there any documentation or examples that work with this? Error messages or how to get the error code.

Example Using this simple script and simulating a network with error, I get the error and the following message: wntr.epanet.toolkit.EpanetException: EPANET Error 110

import wntr

inp_file = r"C:\Users\Aloísio\Desktop\rede.inp"
wn = wntr.network.WaterNetworkModel(inp_file)
print(wn)

sim = wntr.sim.EpanetSimulator(wn)
results = sim.run_sim()

pressoes = results.node['pressure']
print("Pressões")
print()

Is there any way to obtain, in cases of simulation error, only the message with the error code, without generating the simulation error?

kbonney commented 1 month ago

This would be an appropriate use case for a try-except block. You can read more about handling exceptions here: https://docs.python.org/3/tutorial/errors.html#handling-exceptions.

aloisio0 commented 1 month ago

I've already tried something, my question is what to put in except.

import wntr
import os

inp_file = r"C:\Users\Aloísio\Desktop\rede.inp"
wn = wntr.network.WaterNetworkModel(inp_file)

path = r"C:\Users\Aloísio\Desktop\ex"
nome = 'rede' + '_temp'
file_prefix = os.path.join(path, nome)

try:
    # Simulação hidráulica da rede
    sim = wntr.sim.EpanetSimulator(wn)
    results = sim.run_sim()

    # Obtendo as pressões
    pressoes = results.node['pressure']
    print("Pressões")
    print(pressoes)
except:
    inpfile = file_prefix + '.inp'
    enData = wntr.epanet.toolkit.ENepanet()
    ENlib = enData.ENlib
    project = enData._project
    errcode = ENlib.EN_open(project, inpfile)
    print(errcode)
kaklise commented 1 month ago

The following example will print the EPANET error code

import wntr

# Create a water network model
inp_file = "networks/Net3.inp"
wn = wntr.network.WaterNetworkModel(inp_file)

# Add an invalid value to wn so that the simulation fails
link = wn.get_link('123')
link.diameter = -1

# Run the simulation in a try:except block and print the error message
try:
    sim = wntr.sim.EpanetSimulator(wn)
    results = sim.run_sim()
    pressure = results.node['pressure']
except Exception as e:
    print(e)