class Test1(unittest.TestCase):
    def Error(self, e):
        if (e):
            s = "Epanet Error: %d : %s" % (e, self.es.ENgeterror(e, 500)[1])
            raise Exception(s)

    def setUp(self):
        print("SETUP!")
        self.file = os.path.join(os.path.dirname(simple.__file__), 'Net3.inp')
        self.es = EPANetSimulation(self.file)

    def tearDown(self):
        # Bug! the ENclose cause core dumps on posix  -- No, on windows as well!
        if (False):  # os.name!="posix"):
            self.Error(self.es.ENclose())
        print("TEAR DOWN!")

    def test_alter_with_ENset_and_check_with_a_file(self):
        self.Error(self.es.ENsaveinpfile("1.inp"))
        self.Error(self.es.ENsetlinkvalue(81, 0, 9999))
        self.Error(self.es.ENsaveinpfile("2.inp"))
        self.assertEqual(tt.compareFiles("1.inp", "2.inp"), '16>1e+04; ')
    plt.plot(obj)
    plt.plot(p12)
    plt.ylabel('Pressure(m)')
    plt.show()

elif len(lista_IX_CI_PIPES) != 0:
    plt.plot(obj)
    plt.plot(p12)
    plt.ylabel('Pressure(m)')
    plt.show()
    RMS = []
    while (abs(min(obj) - min(p12))) > 1:
        #modifica las rugosidades de los tubos en la red
        for i in range(int(min(lista_RUG)), 60, -1):
            for j in lista_IX_CI_PIPES:
                es.ENsetlinkvalue(j, scabrezze, i)
                #import tempfile
                #f=os.path.join(tempfile.gettempdir(),'new.inp')#NON FUNZIONA
                #es.ENsaveinpfile(f)
                #es2=EPANetSimulation(f)5
            print(i)
            es.run()
            p12 = nod[nodo_12_index].results[presiones][:len(obj)]
            rms = sqrt(mean_squared_error(obj, p12))
            RMS.append(rms)
            if rms < 1 and (abs(min(obj) - min(p12))) < 1:
                print('Rugosidad aceptable=', i, ' rms=', rms)
                import tempfile
                f = os.path.join(tempfile.gettempdir(), 'new.inp')
                es.ENsaveinpfile(f)
                es2 = EPANetSimulation(f)
class Test1(unittest.TestCase):
    def Error(self, e):
        if (e):
            s = "Epanet Error: %d : %s" % (e, self.es.ENgeterror(e, 500)[1])
            raise Exception(s)

    def setUp(self):
        print("SETUP!")
        file = os.path.join(os.path.dirname(simple.__file__), 'Net3.inp')
        self.es = EPANetSimulation(file)

    def tearDown(self):
        self.es.clean()
        print("TEAR DOWN!")

    @skip
    def test_runs_a_simulation_with_pipe_closed_and_get_results_pdd_give_reasonable_results(
            self):
        # now do the same with pipe '247' closed.
        ind = self.es.network.links['247'].index
        dia = Link.value_type["EN_DIAMETER"]  # get the code for EN_STATUS
        # use old interface to set diameter to zero
        self.Error(self.es.ENsetlinkvalue(ind, dia,
                                          0.1))  # now link diameter is small
        file = "1.inp"
        ret = self.es.ENsaveinpfile(file)
        self.assertEqual(ret, 0)
        # now create a new object with the new file.
        es = EPANetSimulation(file, pdd=True)
        es.run()
        p = Node.value_type['EN_PRESSURE']
        d = Node.value_type['EN_DEMAND']
        self.assertAlmostEquals(es.network.nodes['215'].results[p][5],
                                -1.3,
                                places=1)
        self.assertAlmostEqual(es.network.nodes['215'].results[d][5],
                               0.0,
                               places=1)

    def test_runs_a_normal_pressure_simulation_and_get_results_pdd_does_not_change_results(
            self):
        # self.fail("Not yet calling epanet emitter properly")
        def mod1():
            p = Node.value_type['EN_PRESSURE']
            self.assertAlmostEqual(self.es.network.nodes['103'].results[p][5],
                                   59.301,
                                   places=3)
            self.assertAlmostEqual(self.es.network.nodes['125'].results[p][5],
                                   66.051,
                                   places=3)
            self.assertEqual(self.es.network.time[5], 15213)
            self.assertEqual(self.es.network.tsteps[5], 2787)
            self.assertEqual(self.es.network.tsteps[6], 3600)
            self.assertEqual(len(self.es.network.time),
                             len(self.es.network.nodes[1].results[p]))

            d = Node.value_type['EN_DEMAND']
            h = Node.value_type['EN_HEAD']
            self.assertAlmostEqual(self.es.network.nodes['103'].results[d][5],
                                   101.232,
                                   places=3)
            self.assertAlmostEqual(self.es.network.nodes['103'].results[h][5],
                                   179.858,
                                   places=3)

        def mod2():
            p = Link.value_type['EN_DIAMETER']
            self.assertAlmostEquals(
                self.es.network.links[1].results[p][0], 99.0,
                places=1)  # index is not important. Diameter is fixed. !
            self.assertAlmostEquals(self.es.network.links['105'].results[p][0],
                                    12.0,
                                    places=1)
            v = Link.value_type['EN_VELOCITY']
            self.assertAlmostEquals(self.es.network.links[2].results[v][22],
                                    0.025,
                                    places=2)
            self.assertAlmostEquals(self.es.network.links['111'].results[v][1],
                                    3.23,
                                    places=2)

        def mod3():
            p = Node.value_type['EN_PRESSURE']
            self.assertAlmostEqual(self.es.network.nodes['215'].results[p][5],
                                   58.7571,
                                   places=3)
            self.assertAlmostEqual(self.es.network.nodes['225'].results[p][5],
                                   58.320,
                                   places=3)

            d = Node.value_type['EN_DEMAND']
            self.assertAlmostEqual(self.es.network.nodes['215'].results[d][5],
                                   70.064,
                                   places=3)
            self.assertAlmostEqual(self.es.network.nodes['225'].results[d][5],
                                   17.328,
                                   places=3)

        def mod4():
            p = Node.value_type['EN_PRESSURE']
            self.assertAlmostEqual(self.es.network.nodes['215'].results[p][5],
                                   58.7571,
                                   places=3)
            self.assertAlmostEqual(self.es.network.nodes['225'].results[p][5],
                                   58.320,
                                   places=3)

            d = Node.value_type['EN_DEMAND']
            self.assertAlmostEqual(self.es.network.nodes['215'].results[d][5],
                                   70.064,
                                   places=3)
            self.assertAlmostEqual(self.es.network.nodes['225'].results[d][5],
                                   17.328,
                                   places=3)

        self.es.run()
        mod1()
        mod2()
        self.es.runq()
        q = Node.value_type['EN_QUALITY']
        self.assertAlmostEqual(self.es.network.nodes['117'].results[q][4],
                               85.317,
                               places=3)
        self.assertAlmostEqual(self.es.network.nodes['117'].results[q][5],
                               100.0)
        e = Link.value_type['EN_ENERGY']
        self.assertAlmostEquals(self.es.network.links['111'].results[e][23],
                                .00685,
                                places=2)
        mod1()
        mod2()
        mod3()

        file = "1.inp"
        self.Error(self.es.ENsaveinpfile(file))
        # now create a new object with the new file.
        es = EPANetSimulation(file, pdd=True)
        es.run()
        mod1()
        mod2()
        mod3()
示例#4
0
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
'''
Changing the network
Currently the new (object-based) interface above only supports read access to the underlying network. To change the values of the network, it is recommended to use the Legacy interface calls. Legacy calls can be accessed from within the new interface. The steps in changing network:

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.

'''