Skip to content

Commit

Permalink
Workaround for EPyT bug 54
Browse files Browse the repository at this point in the history
  • Loading branch information
andreArtelt committed Jul 18, 2024
1 parent d5f8b21 commit 8ca3a35
Showing 1 changed file with 41 additions and 2 deletions.
43 changes: 41 additions & 2 deletions epyt_flow/simulation/scenario_simulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import sys
import os
import pathlib
import time
from typing import Generator, Union
from copy import deepcopy
import shutil
Expand Down Expand Up @@ -114,12 +115,45 @@ def __init__(self, f_inp_in: str = None, f_msx_in: str = None,
# Treat all warnings as exceptions when trying to load .inp and .msx files
warnings.simplefilter('error')

self.epanet_api = epanet(self.__f_inp_in, ph=self.__f_msx_in is None,
# Workaround for EPyT bug concerning parallel simulations (see EPyT issue #54):
# 1. Create random tmp folder (make sure it is unique!)
# 2. Copy .inp and .msx file there
# 3. Use those copies when loading EPyT
tmp_folder_path = os.path.join(get_temp_folder(), f"{random.randint(int(1e5), int(1e7))}{time.time()}")
pathlib.Path(tmp_folder_path).mkdir(parents=True, exist_ok=False)

def __file_exists(file_in: str) -> bool:
try:
return pathlib.Path(file_in).is_file()
except Exception:
return False

if not __file_exists(self.__f_inp_in):
my_f_inp_in = self.__f_inp_in
self.__my_f_inp_in = None
else:
my_f_inp_in = os.path.join(tmp_folder_path, pathlib.Path(self.__f_inp_in).name)
shutil.copyfile(self.__f_inp_in, my_f_inp_in)
self.__my_f_inp_in = my_f_inp_in

if self.__f_msx_in is not None:
if not __file_exists(self.__f_msx_in):
my_f_msx_in = self.__f_msx_in
self.__my_f_msx_in = None
else:
my_f_msx_in = os.path.join(tmp_folder_path, pathlib.Path(self.__f_msx_in).name)
shutil.copyfile(self.__f_msx_in, my_f_msx_in)
self.__my_f_msx_in = my_f_msx_in
else:
my_f_msx_in = None
self.__my_f_msx_in = None

self.epanet_api = epanet(my_f_inp_in, ph=self.__f_msx_in is None,
customlib=custom_epanet_lib, loadfile=True,
display_msg=epanet_verbose)

if self.__f_msx_in is not None:
self.epanet_api.loadMSXFile(self.__f_msx_in, customMSXlib=custom_epanetmsx_lib)
self.epanet_api.loadMSXFile(my_f_msx_in, customMSXlib=custom_epanetmsx_lib)

self.__sensor_config = self.__get_empty_sensor_config()
if scenario_config is not None:
Expand Down Expand Up @@ -420,6 +454,11 @@ def close(self):

self.epanet_api.unload()

if self.__my_f_inp_in is not None:
shutil.rmtree(pathlib.Path(self.__my_f_inp_in).parent)
if self.__my_f_msx_in is not None:
shutil.rmtree(pathlib.Path(self.__my_f_msx_in).parent)

def __enter__(self):
return self

Expand Down

0 comments on commit 8ca3a35

Please sign in to comment.