class pdd_service(object): def __init__(self, epanet_network, diafact=10.0, coords=False, adfcalc=True): self.epanet_network = epanet_network self.diafact = diafact self.adfcalc = adfcalc self.open_network(epanet_network) if (coords): self.read_coordinates(epanet_network) self.orig_networkfile = epanet_network self._get_units() def _get_units(self): import re pattern = re.compile("^\s*Units\s*([A-Z]{3})\s*$") self.units = None with open(self.orig_networkfile, "r") as f: for line in f: p = pattern.search(line) if p: self.units = p.group(1) break if not self.units: raise Exception( "Wrong file format. Can Not find 'Units XXX' entry") def read_coordinates(self, epanet_network): """Reads the epanet input file and extracts the coorinates of: 1. nodes 2. link vertices if any """ with open(epanet_network, 'r') as f: l = [x.strip() for x in f.readlines()] data = [x for x in l if (x and x != '' and x[0] != ';')] # drop all empty lines st = data.index("[COORDINATES]") lines = data[st + 1:-1] for line in lines: if line[0] + line[-1] == '[]': break vals = str.split(line) self.nodes[vals[0]].x = float(vals[1]) self.nodes[vals[0]].y = float(vals[2]) # now check and raise error if a certain node does not have coordinates try: for i, node in self.nodes.items(): node.x node.y except AttributeError as e: logger.warn("Exception raised(see below): %e" % e) logger.warn( "There is an error in your network file, some nodes do not have coordinates. Fix them and retry please." ) logger.warn("Offending item: %s: Node: %s (%d)" % (epanet_network, node.id, i)) raise AttributeError( "There is an error in your network file, some nodes do not have coordinates. Fix them and retry please." ) for i, link in self.links.items(): if (link.start.x == link.end.x): link.start.x = link.start.x link.end.x = link.end.x # now extract vertices (if any) st = data.index("[VERTICES]") lines = data[st + 1:-1] # first add empty list called vertices for i, link in self.links.items(): link.vertices = [] # now find any vertices and append them for line in lines: if line[0] + line[-1] == '[]': break vals = str.split(line) self.links[vals[0]].vertices.append( (float(vals[1]), float(vals[2]))) def open_network(self, epanet_network): logger.info("Opening network %s" % epanet_network) self.es = EPANetSimulation(epanet_network, pdd=True) if (self.adfcalc): logger.info("Doing ADF calculations") self.es.adfcalc(diafact=self.diafact) else: logger.info("Skipping ADF") self._set_static_values() # set nodes, links for easy access! self.nodes = Nodes() self.links = Links() logger.info("Mapping nodes and links to new objects") for key, value in self.es.network.nodes.items(): n = _Node() n.id = value.id self.nodes[key] = n for key, value in self.es.network.links.items(): l = _Link() l.id = value.id l.length = value.length l.diameter = value.diameter try: l.ADF = value.ADF except: pass l.start = self.nodes[value.start.id] l.end = self.nodes[value.end.id] self.links[key] = l # self.nodes = self.es.network.nodes # self.links = self.es.network.links def _set_static_values(self): """ Adds attibutes of length, diameter for easy access.""" for i, link in self.es.network.links.items(): d = Link.value_type['EN_DIAMETER'] l = Link.value_type['EN_LENGTH'] link.diameter = link.results[d][0] link.length = link.results[l][0] def get_total_demand(self): self.es.run() total = 0.0 st = self.es.network.tsteps j = Node.node_types['JUNCTION'] for (i, node) in [(i, x) for i, x in self.es.network.nodes.items() if x.node_type == j]: d = Node.value_type["EN_DEMAND"] dem = [x * y for x, y in zip(node.results[d], st)] total = total + sum(dem) return total def _c_and_r(self, vals): try: r = vals[0] results = vals[1] except: r = vals results = None if (r != 0): # pragma: no cover raise Exception("epanettools error!") return results def get_pipe_closed_demand(self, pipeindex, dia_factor): import os prefix_ = "epanet_" + self._c_and_r(self.es.ENgetlinkid(pipeindex)) fd, f = tempfile.mkstemp(suffix=".inp", prefix=prefix_, dir=tempfile.gettempdir(), text=True) os.close(fd) d = Link.value_type['EN_DIAMETER'] ret, diam = self.es.ENgetlinkvalue(pipeindex, d) dsmall = diam / float(dia_factor) self._c_and_r(self.es.ENsetlinkvalue(pipeindex, d, dsmall)) self.es.ENsaveinpfile(f) self._c_and_r(self.es.ENsetlinkvalue(pipeindex, d, diam)) # reset diameter self.es = EPANetSimulation(f, pdd=True) demand = self.get_total_demand() self.es = EPANetSimulation( self.orig_networkfile) # reset original network return demand
#obtener la cantidad de conductos ret, num_links = es.ENgetcount(es.EN_LINKCOUNT) #numero de links #leer propiedades de la red diametros = Link.value_type['EN_DIAMETER'] scabrezze = Link.value_type['EN_ROUGHNESS'] presiones = Node.value_type['EN_PRESSURE'] flow = Link.value_type['EN_FLOW'] elevations = Node.value_type['EN_ELEVATION'] velocities = Link.value_type['EN_VELOCITY'] #Raccogliere ixs condotte in Cast Iron e listare le loro scabrezze lista_IX_CI_PIPES = [] for i in range(num_links): C = es.ENgetlinkvalue(i, scabrezze) if C[1] != 0 and 70 < C[1] < 101: lista_IX_CI_PIPES.append(i) lista_RUG = [] for i in lista_IX_CI_PIPES: C = es.ENgetlinkvalue(i, scabrezze) if C[1] != 0: lista_RUG.append(C[1]) #Ottenere l'indice del nodo da calibrare es.run() nodo_12_index = nod['5'].index p12 = nod[nodo_12_index].results[presiones][:24] obj = [ 69.59861755371094, 69.14949798583984, 68.551025390625, 67.80951690673828, 66.9296875, 64.7691879272461, 58.91615676879883, 51.11674118041992,
Create an object of EPANetSimulation with the network file Change needed values using ENsetxxxx calls (just changing the attributes of EPANetSimulation will not work!) Save the changed data to a new file using ENsaveinpfile. Create an object of EPANetSimulation with the new saved file. ''' d=Link.value_type['EN_DIAMETER'] e=Node.value_type['EN_ELEVATION'] es.network.links[81].results[d] # new interface es.ENgetnodevalue(55,e)[1] # low level interface es.network.nodes[55].results[e] #new interface r=es.ENsetlinkvalue(81,d,99) # now let's change values - link r # zero means no error! r=es.ENsetnodevalue(55,e,18.25) # change elevation of node r #zero means no error # Note: the original network is not changed! Only the low level values changed. This is a limitation of current implementation es.network.links[81].results[d], es.ENgetlinkvalue(81,d)[1], es.network.nodes[55].results[e], es.ENgetnodevalue(55,e)[1] # to permanantly change values, the changed network has to be written to a new file import tempfile, os f=os.path.join(tempfile.gettempdir(),"temp.inp") es.ENsaveinpfile(f) # save the changed file e2=EPANetSimulation(f) e2.network.links[81].results[d], e2.ENgetlinkvalue(81,d)[1], e2.network.nodes[55].results[e], e2.ENgetnodevalue(55,e)[1] # now in both high level and low level interfaces, we have the right value. ''' changing the pattern of the network ''' patId = "NewPattern"; ret=es.ENaddpattern(patId) print(ret)