Пример #1
0
class Test1(unittest.TestCase):
    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_false(self):
        assert False

    def test_patterns_are_retrieved_properly(self):
        p = self.es.network.patterns
        self.assertEqual(len(p), 5)  # there are five patterns
        [self.assertEqual(p[x].id, str(x)) for x in range(1,
                                                          len(p) + 1)
         ]  # the ids of patterns are '1','2',..,'5' - how convienient!
        l = [len(p[x]) for x in range(1, len(p) + 1)]
        [self.assertEqual(x, 24)
         for x in l]  # all thoese patterns are 24 length
        # check a few values of pattern 1
        self.assertAlmostEqual(p[1][1], 1.34, delta=2)
        self.assertAlmostEqual(p[1][24], 1.67, delta=2)
        self.assertAlmostEqual(p[1][22], .96, delta=2)
class Test1(unittest.TestCase):

    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_false(self):
        assert False

    def test_patterns_are_retrieved_properly(self):
        p = self.es.network.patterns
        self.assertEqual(len(p), 5)  # there are five patterns
        [self.assertEqual(p[x].id, str(x))
         for x in range(1, len(p) + 1)]  # the ids of patterns are '1','2',..,'5' - how convienient!
        l = [len(p[x]) for x in range(1, len(p) + 1)]
        [self.assertEqual(x, 24) for x in l]  # all thoese patterns are 24 length
        # check a few values of pattern 1
        self.assertAlmostEqual(p[1][1], 1.34, delta=2)
        self.assertAlmostEqual(p[1][24], 1.67, delta=2)
        self.assertAlmostEqual(p[1][22], .96, delta=2)
def GetConnectionData(inputFile):
    d = EPANetSimulation(inputFile)
    ret, nnodes = d.ENgetcount(d.EN_NODECOUNT)
    ret, llinks = d.ENgetcount(d.EN_LINKCOUNT)
    Conn = []
    NoConn = []
    h_degree = 0
    if (len(Conn) == 0):
        for n in range(0, nnodes + 1):
            c = []
            Conn.append(c)

    # generate mapping used later for resilience calculation
    for i in range(0, (llinks + 1)):
        if (len(Conn) == (nnodes + 1)):
            nodes = d.ENgetlinknodes(i + 1)
            if (nodes[0] == 0):
                Conn[nodes[1]].append(i + 1)
                Conn[nodes[2]].append(i + 1)
                h_degree = max(len(Conn[nodes[0]]), len(Conn[nodes[1]]),
                               h_degree)

    for idx in range(0, nnodes + 1):
        NoConn.append(len(Conn[idx]))
        while (len(Conn[idx]) < h_degree):
            Conn[idx].append(0)
    del Conn[0]
    del NoConn[0]

    return Conn, NoConn
Пример #4
0
    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
Пример #5
0
class Test1(unittest.TestCase):

    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_false(self):
        assert False

    def test_EPANetSimulation_by_default_has_no_ADF_values(self):
        d= Link.value_type['EN_DIAMETER']
        self.assertAlmostEqual(self.es.network.links[1].results[d][0],99.,delta=1)
        self.assertRaises(AttributeError, getattr, self.es.network.links[1], "ADF")
        
    def test_EPANetSimulation_after_calling_adfcalc_has_ADF_values(self):
        d= Link.value_type['EN_DIAMETER']
        self.assertAlmostEqual(self.es.network.links[1].results[d][0],99.,delta=1)
        raised=False
        try:
            self.assertAlmostEqual(self.es.network.links[1].ADF,.05) 
        except AttributeError:
            raised=True
        self.assertTrue(raised,"Did not raise exception.")
        self.es.adfcalc()
        self.assertAlmostEqual(self.es.network.links[1].ADF,0.99996,delta=.001) 
        self.assertAlmostEqual(self.es.network.links['151'].ADF,0.974816, delta=0.001)    
Пример #6
0
 def test_properly_open_a_network_file(self):
     import filecmp
     file = os.path.join(os.path.dirname(simple.__file__), 'Net3.inp')
     es = EPANetSimulation(file)
     self.assertNotEqual(file, self.es.inputfile)
     self.assertTrue(os.path.isfile(self.es.inputfile))
     self.assertFalse(os.path.isdir(self.es.inputfile))
     # file names are unique
     self.assertEqual(
         len(set([EPANetSimulation(file).inputfile for i in range(100)])),
         100)
     # file content is identical to the original file
     self.assertTrue(filecmp.cmp(self.es.inputfile, file))
     # but names are not the same
     self.assertFalse(self.es.inputfile == file)
Пример #7
0
 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)
Пример #8
0
 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)
Пример #9
0
 def fitness(self, x):
     from epanettools import epanet2 as et
     from epanettools.epanettools import EPANetSimulation, Node, Link, Network, Nodes, \
         Links, Patterns, Pattern, Controls, Control  # import all elements needed
     d = EPANetSimulation('/home/varsha/Documents/Project.inp')
     f1 = Cost.Cost(x)
     f2 = PRI.PRI(x, d)
     return [f1, f2]
Пример #10
0
    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
Пример #11
0
class Test1(unittest.TestCase):
    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_false(self):
        assert False

    def test_EPANetSimulation_by_default_has_no_ADF_values(self):
        d = Link.value_type['EN_DIAMETER']
        self.assertAlmostEqual(self.es.network.links[1].results[d][0],
                               99.,
                               delta=1)
        self.assertRaises(AttributeError, getattr, self.es.network.links[1],
                          "ADF")

    def test_EPANetSimulation_after_calling_adfcalc_has_ADF_values(self):
        d = Link.value_type['EN_DIAMETER']
        self.assertAlmostEqual(self.es.network.links[1].results[d][0],
                               99.,
                               delta=1)
        raised = False
        try:
            self.assertAlmostEqual(self.es.network.links[1].ADF, .05)
        except AttributeError:
            raised = True
        self.assertTrue(raised, "Did not raise exception.")
        self.es.adfcalc()
        self.assertAlmostEqual(self.es.network.links[1].ADF,
                               0.99996,
                               delta=.001)
        self.assertAlmostEqual(self.es.network.links['151'].ADF,
                               0.974816,
                               delta=0.001)
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; ')
Пример #13
0
class my_mo_problem(Problem):
    d = EPANetSimulation('/home/varsha/Documents/Project.inp')
    ret, nlinks = d.ENgetcount(d.EN_LINKCOUNT)

    def __init__(self):
        super(my_mo_problem, self).__init__(self.nlinks, 2, 2)
        self.types[:] = [Integer(0, 16)] * self.nlinks
        self.constraints[:] = "<=0"
        self.directions[:] = Problem.MINIMIZE

    def evaluate(self, solution):
        y = solution.variables
        solution.objectives[:] = [PRI.PRI(y, self.d), Cost.Cost(y, self.d)]
        solution.constraints[:] = Constraint.Constraint(y, self.d)
Пример #14
0
class my_mo_problem(Problem):
    d = EPANetSimulation('/home/varshac/optimization/Optimization-Code/d-town.inp')
    ret, nlinks = d.ENgetcount(d.EN_LINKCOUNT)
    hStar = Settings.SetValues(d)
    Functions.SetVariables(d)
    def __init__(self):
        super(my_mo_problem, self).__init__(self.nlinks, 2, 2)
        self.types[:] = [Integer(0, 16)]*self.nlinks
        self.constraints[:] = "<=0"
        self.directions[:] = Problem.MINIMIZE
    def evaluate(self, solution):
        y = solution.variables
        solution.objectives[:] = [-Functions.Res(y,self.d,self.hStar),Functions.Cost(y,self.d)]
        solution.constraints[:] = Functions.Constraint(self.hStar)
def SetValues(inputFile, id="", ep=True):
    d = Network(inputFile)
    curves = len(d.curves)
    max_elevation = 0

    if (ep):
        d.add_curve('C1', [(1000, 180)])
        d.add_curve('C2', [(2000, 200)])
        d.add_curve('C3', [(3000, 220)])
        d.add_curve('C4', [(4000, 240)])
        d.add_curve('C5', [(5000, 260)])
        d.add_curve('C6', [(1000, 200)])
        d.add_curve('C7', [(2000, 220)])
        d.add_curve('C8', [(3000, 240)])
        d.add_curve('C9', [(4000, 260)])
        d.add_curve('C10', [(5000, 280)])

    MinHead = [40]
    nodes = d.nodes
    nnodes = len(nodes)
    hStar = [0] * nnodes
    nbOfPipes = 0
    nbOfPumps = 0
    nbOfTanks = 0
    links = d.links
    curves = len(d.curves)
    for link in links:
        if link.link_type == 'pipe':
            nbOfPipes += 1
        elif link.link_type == 'pump':
            nbOfPumps += 1
    nbofJunctions = 0
    for node in nodes:
        if node.node_type == 'Junction':
            hStar[nbofJunctions] = random.choice(MinHead)
            max_elevation = max(max_elevation, node.elevation)
            nbofJunctions += 1
        elif node.node_type == 'Tank':
            nbOfTanks += 1
    #d.save_inputfile('temp.inp')

    if ep:
        d.save_inputfile('temp' + id + '.inp')
        et = EPANetSimulation('temp' + id + '.inp')
        Conn, NoConn = GetConnectionDetails(et)
        return et, hStar, curves, curves, nbOfPipes, nbOfPumps, nbOfTanks, Conn, NoConn, max_elevation
    else:
        return nbOfPipes, nbOfPumps, nbOfTanks, max_elevation
# -*- coding: utf-8 -*-
import os, pprint
pp=pprint.PrettyPrinter() # we'll use this later.
from  epanettools.epanettools import EPANetSimulation, Node, Link, Network, Nodes,Links, Patterns, Pattern, Controls, Control # import all elements needed
from epanettools.examples import simple # this is just to get the path of standard examples
file = os.path.join(os.path.dirname(simple.__file__),'Net3.inp') # open an example
es=EPANetSimulation(file)

#https://pypi.org/project/EPANET/

#Nodes
len(es.network.nodes)

list(es.network.nodes)[:5]
[es.network.nodes[x].id for x in list(es.network.nodes)[:5]] # Get ids of first five nodes.

n=es.network.nodes
n[4].id
n[94].id
n['10'].index # get the index of the node with id '10'

#Links
m=es.network.links
len(m)
m[1].id
m[3].id
m[119].id

#connectivity
[m[1].start.id,m[1].end.id] # get the two ends of a link
[m[118].start.id,m[118].end.id]
Пример #17
0
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()
Пример #18
0
class Test1(unittest.TestCase):
    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_false(self):
        assert False

    def test_epnetsimulation_has_a_network_which_has_nodes_and_links(self):
        self.assertIsInstance(self.es.network, Network)
        self.assertIsInstance(self.es.network.links, Links)
        self.assertIsInstance(self.es.network.nodes, Nodes)
        self.assertIsInstance(self.es.network.nodes[1], Node)
        self.assertIsInstance(self.es.network.links[1], Link)

    def test_network_has_patterns(self):
        self.assertIsInstance(self.es.network.patterns, Patterns)
        self.assertIsInstance(self.es.network.patterns[1], Pattern)
        self.assertEqual(len(self.es.network.patterns), 5)
        self.assertEqual(self.es.network.patterns['4'][7],
                         1777)  # can call with index or...
        self.assertEqual(self.es.network.patterns[4][7],
                         1777)  # id. And for specific value, call the item.

    def test_network_has_controls(self):
        self.assertIsInstance(self.es.network.controls, Controls)
        self.assertIsInstance(self.es.network.controls[1], Control)
        self.assertEqual(len(self.es.network.controls), 6)
        c = [self.es.network.controls[x] for x in range(1, 5)]
        self.assertEqual(c[0].link.id, '10')
        self.assertEqual(c[0].node, None)
        self.assertEqual(c[0].level, 3600.)
        self.assertAlmostEqual(c[0].setting, Link.OPENED)
        self.assertEqual(c[0].ctype, Control.control_types['TIMER_CONTROL'])

        self.assertAlmostEqual(c[1].setting, Link.CLOSED)

        self.assertAlmostEqual(
            c[2].setting, Link.OPENED)  #Link 335 OPEN IF Node 1 BELOW 17.1
        self.assertEqual(c[2].link.id, '335')
        self.assertEqual(c[2].node.id, '1')
        self.assertAlmostEqual(c[2].level, 17.1, places=1)
        self.assertEqual(c[2].ctype,
                         Control.control_types['LOW_LEVEL_CONTROL'])

        self.assertAlmostEqual(
            c[3].setting, Link.CLOSED)  #Link 335 OPEN IF Node 1 BELOW 17.1
        self.assertEqual(c[3].link.id, '335')
        self.assertEqual(c[3].node.id, '1')
        self.assertAlmostEqual(c[3].level, 19.1, places=1)
        self.assertEqual(c[3].ctype,
                         Control.control_types['HIGH_LEVEL_CONTROL'])

    def test_water_quality_analysis_type_is_set(self):
        self.assertEqual(self.es.network.WaterQualityAnalysisType,
                         Network.WaterQualityAnalysisTypes["EN_TRACE"])
        self.assertEqual(self.es.network.WaterQualityTraceNode.id, 'Lake')

    def test_proper_options_are_set(self):
        n = self.es.network
        self.assertAlmostEqual(n.en_accuracy, 0.001, places=3)
        self.assertAlmostEqual(n.en_demandmult, 1.0, places=3)
        self.assertAlmostEqual(n.en_emitexpon, 0.5, places=2)
        self.assertAlmostEqual(n.en_tolerance, .01, places=5)
        self.assertAlmostEqual(n.en_trials, 40.0, places=3)

    def test_can_import_EPANetSimulation(self):
        try:
            from epanettools.epanettools import EPANetSimulation
        except (Exception):
            assert False

    def test_non_existing_file_raise_error(self):
        self.assertRaises(FileNotFoundError, EPANetSimulation, "Silly file")

    def test_in_input_type_nodes_node_data_has_only_one_value(self):
        def mod1():
            for j, node in self.es.network.nodes.items():
                for t, i in Node.value_type.items():
                    if (not i in Node.settable_values):
                        continue
                    self.assertEqual(len(node.results[i]), 1)

        mod1()
        self.es.run()
        mod1()
        self.es.runq()
        mod1()

    def test_in_output_type_nodes_node_data_has_multiple_values(self):
        def mod1(before_run=True):
            for j, node in self.es.network.nodes.items():
                for t, i in Node.value_type.items():
                    if (i in Node.input_values):
                        continue
                    if (before_run):
                        self.assertEqual(len(node.results[i]), 0)
                    else:
                        self.assertEqual(len(node.results[i]),
                                         len(self.es.network.time))

        mod1()
        self.es.run()
        mod1(False)
        self.es.runq()
        mod1(False)

    def test_for_input_type_links_link_data_has_only_one_value(self):
        def mod1():
            for j, link in self.es.network.links.items():
                for t, i in Link.value_type.items():
                    if (not i in Link.settable_values):
                        continue
                    self.assertEqual(len(link.results[i]), 1)

        mod1()
        self.es.run()
        mod1()
        self.es.runq()
        mod1()

    def test_for_output_type_links_link_data_has_multiple_values(self):
        def mod1(before_run=True):
            for j, link in self.es.network.links.items():
                for t, i in Link.value_type.items():
                    if (i in Link.settable_values):
                        continue
                    if (before_run):
                        self.assertEqual(len(link.results[i]), 0)
                    else:
                        self.assertEqual(len(link.results[i]),
                                         len(self.es.network.time))

        mod1()
        self.es.run()
        mod1(False)
        self.es.runq()
        mod1(False)

    def test_properly_open_a_network_file(self):
        import filecmp
        file = os.path.join(os.path.dirname(simple.__file__), 'Net3.inp')
        es = EPANetSimulation(file)
        self.assertNotEqual(file, self.es.inputfile)
        self.assertTrue(os.path.isfile(self.es.inputfile))
        self.assertFalse(os.path.isdir(self.es.inputfile))
        # file names are unique
        self.assertEqual(
            len(set([EPANetSimulation(file).inputfile for i in range(100)])),
            100)
        # file content is identical to the original file
        self.assertTrue(filecmp.cmp(self.es.inputfile, file))
        # but names are not the same
        self.assertFalse(self.es.inputfile == file)

    def test_get_correct_network_information(self):
        n = self.es.network.nodes
        self.assertEqual(n[1].id, '10')
        self.assertEqual(n[3].id, '20')
        self.assertEqual(n[25].id, '129')
        self.assertEqual(n[94].id, 'Lake')

        self.assertEqual(n[94].index, 94)

        m = self.es.network.links
        self.assertEqual(m[1].id, '20')
        self.assertEqual(m[3].id, '50')
        self.assertEqual(m[119].id, '335')
        self.assertEqual([m[1].start.id, m[1].end.id], ['3', '20'])
        self.assertEqual([m[118].start.id, m[118].end.id], ['Lake', '10'])

        # types of nodes
        self.assertEqual(n[94].node_type, Node.node_types['RESERVOIR'])
        self.assertEqual(n[1].node_type, Node.node_types['JUNCTION'])
        self.assertEqual(n['2'].node_type, Node.node_types['TANK'])

        #types of links
        self.assertEqual(m['335'].link_type, Link.link_types['PUMP'])
        self.assertEqual(m['101'].link_type, Link.link_types['PIPE'])
        self.assertEqual(m[1].link_type, Link.link_types['PIPE'])

        self.assertEqual(m[119].index, 119)

        # link or node can be searched with ID too.
        self.assertEqual(n['Lake'].id, 'Lake')
        self.assertEqual(n['Lake'].index, 94)
        self.assertEqual(m['335'].id, '335')
        self.assertEqual(m['335'].index, 119)

        # get the links connected to a node.
        self.assertEqual(sorted([i.id for i in n['169'].links]),
                         ['183', '185', '187', '211'])

    def test_can_access_low_level_EN_type_functions(self):
        self.assertEqual(self.es.ENgetnodeid(3), [0, '20'])

    def test_each_node_and_link_has_the_epanetsimulation_object_linked_to_it_as_variable_es(
            self):
        self.assertIsInstance(self.es.network.links[1].network.es,
                              EPANetSimulation)
        self.assertIsInstance(self.es.network.nodes[1].network.es,
                              EPANetSimulation)

    def test_runs_a_simulation_and_get_results(self):
        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)

        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()

    def test_hydraulic_file_is_saved_only_when_save_is_true(self):
        self.es.run(save=False)
        self.assertFalse(os.path.exists(self.es.hydraulicfile))
        self.es.run(save=True)
        self.assertTrue(os.path.exists(self.es.hydraulicfile))

    def test_clean_will_remove_results(self):
        self.assertTrue(os.path.exists(self.es.inputfile))
        self.es.run()
        self.assertTrue(os.path.exists(self.es.rptfile))
        self.assertTrue(os.path.exists(self.es.hydraulicfile))
        self.es.runq()
        self.assertTrue(os.path.exists(self.es.rptfile))
        self.assertTrue(os.path.exists(self.es.binfile))
        self.assertTrue(os.path.exists(self.es.hydraulicfile))
        self.es.clean()
        self.assertTrue(os.path.exists(self.es.inputfile))
        self.assertFalse(os.path.exists(self.es.rptfile))
        self.assertFalse(os.path.exists(self.es.binfile))
        self.assertFalse(os.path.exists(self.es.hydraulicfile))

    def test_settable_values_for_links_and_nodes(self):
        self.assertEqual(Link.settable_values,
                         [0, 1, 2, 3, 4, 5, 6, 7, 11, 12])
        self.assertEqual(
            Node.settable_values,
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 15, 17, 18, 20, 21, 22, 23])

    def xtest_node_values_are_saved_when_synced(self):
        #change copule'a values
        d = Link.value_type['EN_DIAMETER']
        self.es.network.links[1].results[d][0]
        self.es.network.links[1].results[d][0] = 152.0
        self.es.network.links['105'].results[d][0] = 18.0
        #first without 'syncing""
        self.assertAlmostEquals(self.es._legacy_get('LINK', 1, d),
                                99.0,
                                places=1)

        self.assertAlmostEquals(self.es._legacy_get(
            'LINK', self.es.network.links['105'].index, d),
                                12.0,
                                places=1)
        #now after 'syncing'
        self.es.sync()
        self.assertAlmostEquals(self.es._legacy_get('LINK', 1, d),
                                152.0,
                                places=1)
        self.assertAlmostEquals(self.es._legacy_get(
            'LINK', self.es.network.links['105'].index, d),
                                18.0,
                                places=1)
        # now run and get results
        self.es.run()
        self.assertAlmostEquals(
            self.es.network.links[1].results[Link.value_type["EN_FLOW"]][0],
            -2246.30,
            places=1)
Пример #19
0
 def setUp(self):
     print("SETUP!")
     file = os.path.join(os.path.dirname(simple.__file__), 'Net3.inp')
     self.es = EPANetSimulation(file)
Пример #20
0
This workflow runs extended-period simulation of CTOWN network and plots pressure reads
   for junction J193
Dependencies: epanettools and matplot modules
"""

from epanettools import epanet2 as et
from epanettools.epanettools import EPANetSimulation
import matplotlib.pyplot as plt
import os

dir = os.path.abspath('testEPANETTOOLS.py')
dir = '\\'.join(dir.split('\\')[0:-2])
file_directory = dir + '\\resources\\CTOWN.inp'

ret = et.ENopen(file_directory, "CTOWN.rpt", "")
es = EPANetSimulation(file_directory)
n = es.network.nodes

junction = 'J193'

pres = []
nodes = []
time = []

et.ENopenH()
et.ENinitH(0)
while True:
    ret, t = et.ENrunH()
    ret, p = et.ENgetnodevalue(n[junction].index, et.EN_PRESSURE)
    print t, p
    ret, t_step = et.ENnextH()
Пример #21
0
Created on Thu May 30 10:21:45 2019

This file will propose an algorithm to apply the adaptive control methodology for the network of richmond
but solely for pump 4B

Tank D    min 0       max 2.11      initial 1.94  LZHZTariff

Linearization pump D to tank D- 0.3m/hour.pumping

@author: Marcelo
"""
#Define Initial conditions and Determine ID's of pumps and tanks

from Inital_Conditions import tarifario_ST, tarifario_CB, tarifario_S, tarifario_HH, tarifario_LZG, tarifario_LZHZ
from epanettools.epanettools import EPANetSimulation, Node, Link, Network, Nodes, Links, Patterns, Pattern, Controls, Control
es = EPANetSimulation('richmondNet.inp')

p_status_1A = [
    0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
]  #CBTariff
p_status_2A = [
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
]  #CBTariff
p_status_3A = [
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
]  #STTariff
p_status_4B = [
    0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1
]  #LZHZTariff
p_status_5C = [
    0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1
Пример #22
0
    '2': 12,
    'aTU1093150205': 6
}

no_leaks = 18696
no_flow_files = 18696
no_pressure_files = 18696
no_pressure_sensors = 21
no_flow_sensors = 7

import os

path_init = "F:\\manual\\Tese\\exploratory\\wisdom\\dataset\\"

path = path_init + "INP Files\\StatusQuoVerao2018.inp"
es = EPANetSimulation(path)

tg_links = [
    es.network.links[x].id for x in list(es.network.links)[:]
    if es.network.links[x].id in epanet_to_scada_flow.keys()
]
print(tg_links)
#7
print("Links:" + str(len(tg_links)))

from os import listdir
from os.path import isfile, join

pathtxt = path_init + "\\simulated\\fugas_txt\\"
pathflowtxt = path_init + "\\simulated\\fugas_txt\\Rotura_Q\\"
pathpressuretxt = path_init + "\\simulated\\fugas_txt\\Rotura_Pnova\\"
Пример #23
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
Пример #24
0
#importar dependencias
import os
from epanettools.epanettools import EPANetSimulation, Node, Link, Network
from epanettools.examples import simple
import numpy as np
import scipy
from sklearn.metrics import mean_squared_error
from math import sqrt
import matplotlib.pyplot as plt
import setPROPERTY

#leer la red
file = os.path.join(os.path.dirname(simple.__file__), 'test.inp')
es = EPANetSimulation(file)

#instanciar clases y metodos
cond = es.network.links
nod = es.network.nodes

#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
 def setUp(self):
     print("SETUP!")
     file = os.path.join(os.path.dirname(simple.__file__), 'Net3.inp')
     self.es = EPANetSimulation(file)
class Test1(unittest.TestCase):

    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_false(self):
        assert False

    def test_epnetsimulation_has_a_network_which_has_nodes_and_links(self):
        self.assertIsInstance(self.es.network, Network)
        self.assertIsInstance(self.es.network.links, Links)
        self.assertIsInstance(self.es.network.nodes, Nodes)
        self.assertIsInstance(self.es.network.nodes[1], Node)
        self.assertIsInstance(self.es.network.links[1], Link)

    def test_network_has_patterns(self):
        self.assertIsInstance(self.es.network.patterns, Patterns)
        self.assertIsInstance(self.es.network.patterns[1], Pattern)
        self.assertEqual(len(self.es.network.patterns), 5)
        self.assertEqual(self.es.network.patterns['4'][7], 1777)  # can call with index or...
        self.assertEqual(
            self.es.network.patterns[4][7],
            1777)   # id. And for specific value, call the item.

    def test_network_has_controls(self):
        self.assertIsInstance(self.es.network.controls, Controls)
        self.assertIsInstance(self.es.network.controls[1], Control)
        self.assertEqual(len(self.es.network.controls), 6)
        c = [self.es.network.controls[x] for x in range(1, 5)]
        self.assertEqual(c[0].link.id, '10')
        self.assertEqual(c[0].node, None)
        self.assertEqual(c[0].level, 3600.)
        self.assertAlmostEqual(c[0].setting, Link.OPENED)
        self.assertEqual(c[0].ctype, Control.control_types['TIMER_CONTROL'])

        self.assertAlmostEqual(c[1].setting, Link.CLOSED)

        self.assertAlmostEqual(c[2].setting, Link.OPENED)  # Link 335 OPEN IF Node 1 BELOW 17.1
        self.assertEqual(c[2].link.id, '335')
        self.assertEqual(c[2].node.id, '1')
        self.assertAlmostEqual(c[2].level, 17.1, places=1)
        self.assertEqual(c[2].ctype, Control.control_types['LOW_LEVEL_CONTROL'])

        self.assertAlmostEqual(c[3].setting, Link.CLOSED)  # Link 335 OPEN IF Node 1 BELOW 17.1
        self.assertEqual(c[3].link.id, '335')
        self.assertEqual(c[3].node.id, '1')
        self.assertAlmostEqual(c[3].level, 19.1, places=1)
        self.assertEqual(c[3].ctype, Control.control_types['HIGH_LEVEL_CONTROL'])

    def test_water_quality_analysis_type_is_set(self):
        self.assertEqual(
            self.es.network.WaterQualityAnalysisType,
            Network.WaterQualityAnalysisTypes["EN_TRACE"])
        self.assertEqual(self.es.network.WaterQualityTraceNode.id, 'Lake')

    def test_proper_options_are_set(self):
        n = self.es.network
        self.assertAlmostEqual(n.en_accuracy, 0.001, places=3)
        self.assertAlmostEqual(n.en_demandmult, 1.0, places=3)
        self.assertAlmostEqual(n.en_emitexpon, 0.5, places=2)
        self.assertAlmostEqual(n.en_tolerance, .01, places=5)
        self.assertAlmostEqual(n.en_trials, 40.0, places=3)

    def test_can_import_EPANetSimulation(self):
        try:
            from epanettools.epanettools import EPANetSimulation
        except (Exception):
            assert False

    def test_non_existing_file_raise_error(self):
        v1 = sys.version_info[0]
        v2 = sys.version_info[1]
        if (v1 == 3):
            self.assertRaises(FileNotFoundError, EPANetSimulation, "Silly file")
            return
        if (v1 == 2):
            if(v2 >= 7):
                self.assertRaises(IOError, EPANetSimulation, "Silly file")
            else:
                self.fail

    def test_in_input_type_nodes_node_data_has_only_one_value(self):
        def mod1():
            for j, node in self.es.network.nodes.items():
                for t, i in Node.value_type.items():
                    if(not i in Node.settable_values):
                        continue
                    self.assertEqual(len(node.results[i]), 1)
        mod1()
        self.es.run()
        mod1()
        self.es.runq()
        mod1()

    def test_in_output_type_nodes_node_data_has_multiple_values(self):
        def mod1(before_run=True):
            for j, node in self.es.network.nodes.items():
                for t, i in Node.value_type.items():
                    if(i in Node.input_values):
                        continue
                    if(before_run):
                        self.assertEqual(len(node.results[i]), 0)
                    else:
                        self.assertEqual(len(node.results[i]), len(self.es.network.time))
        mod1()
        self.es.run()
        mod1(False)
        self.es.runq()
        mod1(False)

    def test_for_input_type_links_link_data_has_only_one_value(self):
        def mod1():
            for j, link in self.es.network.links.items():
                for t, i in Link.value_type.items():
                    if(not i in Link.settable_values):
                        continue
                    self.assertEqual(len(link.results[i]), 1)
        mod1()
        self.es.run()
        mod1()
        self.es.runq()
        mod1()

    def test_for_output_type_links_link_data_has_multiple_values(self):
        def mod1(before_run=True):
            for j, link in self.es.network.links.items():
                for t, i in Link.value_type.items():
                    if(i in Link.settable_values):
                        continue
                    if(before_run):
                        self.assertEqual(len(link.results[i]), 0)
                    else:
                        self.assertEqual(len(link.results[i]), len(self.es.network.time))
        mod1()
        self.es.run()
        mod1(False)
        self.es.runq()
        mod1(False)

    def test_properly_open_a_network_file(self):
        import filecmp
        file = os.path.join(os.path.dirname(simple.__file__), 'Net3.inp')
        es = EPANetSimulation(file)
        self.assertNotEqual(file, self.es.inputfile)
        self.assertTrue(os.path.isfile(self.es.inputfile))
        self.assertFalse(os.path.isdir(self.es.inputfile))
        # file names are unique
        self.assertEqual(len(set([EPANetSimulation(file).inputfile for i in range(100)])), 100)
        # file content is identical to the original file
        self.assertTrue(filecmp.cmp(self.es.inputfile, file))
        # but names are not the same
        self.assertFalse(self.es.inputfile == file)

    def test_get_correct_network_information(self):
        n = self.es.network.nodes
        self.assertEqual(n[1].id, '10')
        self.assertEqual(n[3].id, '20')
        self.assertEqual(n[25].id, '129')
        self.assertEqual(n[94].id, 'Lake')

        self.assertEqual(n[94].index, 94)

        m = self.es.network.links
        self.assertEqual(m[1].id, '20')
        self.assertEqual(m[3].id, '50')
        self.assertEqual(m[119].id, '335')
        self.assertEqual([m[1].start.id, m[1].end.id], ['3', '20'])
        self.assertEqual([m[118].start.id, m[118].end.id], ['Lake', '10'])

        # types of nodes
        self.assertEqual(n[94].node_type, Node.node_types['RESERVOIR'])
        self.assertEqual(n[1].node_type, Node.node_types['JUNCTION'])
        self.assertEqual(n['2'].node_type, Node.node_types['TANK'])

        # types of links
        self.assertEqual(m['335'].link_type, Link.link_types['PUMP'])
        self.assertEqual(m['101'].link_type, Link.link_types['PIPE'])
        self.assertEqual(m[1].link_type, Link.link_types['PIPE'])

        self.assertEqual(m[119].index, 119)

        # link or node can be searched with ID too.
        self.assertEqual(n['Lake'].id, 'Lake')
        self.assertEqual(n['Lake'].index, 94)
        self.assertEqual(m['335'].id, '335')
        self.assertEqual(m['335'].index, 119)

        # get the links connected to a node.
        self.assertEqual(sorted([i.id for i in n['169'].links]), ['183', '185', '187', '211'])

    def xtest_sync_does_not_make_mistakes_in_saving_back_same_values(self):
        self.es.ENsaveinpfile("a.inp")
        self.es.sync(i_know_what_i_am_doing=True)
        self.es.ENsaveinpfile("b.inp")
        self.assertEqual(tt.compareFiles("a.inp", "b.inp"), '')

    def test_results_get_correct_values(self):
        n = self.es.network.nodes
        nan = float("NaN")
        # Tank has correct values
        r = {0: [116.5],
             1: [0.0],
             2: [0.0],
             3: [0.0],
             4: [0.0],
             5: [nan],
             6: [nan],
             7: [nan],
             8: [23.5],
             9: [],
             10: [],
             11: [],
             12: [],
             13: [],
             14: [46142.140625],
             15: [0.0],
             16: [79128.8671875],
             17: [50.0],
             18: [12762.7197265625],
             19: [0.0],
             20: [6.5],
             21: [40.29999923706055],
             22: [1.0],
             23: [0.0]}
        del r[5], r[7], r[6]
        a = copy.deepcopy(n['2'].results)
        del a[5], a[7], a[6]
        self.assertEqual(a, r)

        # Reservoirs have correct values
        r = {0: [220.0],
             1: [0.0],
             2: [0.0],
             3: [0.0],
             4: [0.0],
             5: [nan],
             6: [nan],
             7: [nan],
             8: [0.0],
             9: [],
             10: [],
             11: [],
             12: [],
             13: [],
             14: [0.0],
             15: [0.0],
             16: [0.0],
             17: [0.0],
             18: [0.0],
             19: [0.0],
             20: [0.0],
             21: [0.0],
             22: [1.0],
             23: [0.0]}
        a = copy.deepcopy(n['River'].results)
        del r[5], r[7], r[6]
        del a[5], a[7], a[6]
        self.assertEqual(a, r)

        m = self.es.network.links

        # Link has correct values
        r = {0: [18.0],
             1: [14200.0],
             2: [110.0],
             3: [0.0],
             4: [1.0],
             5: [110.0],
             6: [0.0],
             7: [0.0],
             8: [],
             9: [],
             10: [],
             11: [0.0],
             12: [110.0],
             13: []}
        a = copy.deepcopy(m['101'].results)
        del r[5], r[7], r[6]
        del a[5], a[7], a[6]
        self.assertEqual(a, r)

    def test_can_access_low_level_EN_type_functions(self):
        self.assertEqual(self.es.ENgetnodeid(3), [0, '20'])

    def test_each_node_and_link_has_the_epanetsimulation_object_linked_to_it_as_variable_es(self):
        self.assertIsInstance(self.es.network.links[1].network.es, EPANetSimulation)
        self.assertIsInstance(self.es.network.nodes[1].network.es, EPANetSimulation)

    def test_runs_a_simulation_and_get_results(self):
        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)

        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()

    def test_hydraulic_file_is_saved_only_when_save_is_true(self):
        self.es.run(save=False)
        self.assertFalse(os.path.exists(self.es.hydraulicfile))
        self.es.run(save=True)
        self.assertTrue(os.path.exists(self.es.hydraulicfile))

    @skip
    def test_clean_will_remove_results(self):
        self.assertTrue(os.path.exists(self.es.inputfile))
        self.es.run()
        self.assertTrue(os.path.exists(self.es.rptfile))
        self.assertTrue(os.path.exists(self.es.hydraulicfile))
        self.es.runq()
        self.assertTrue(os.path.exists(self.es.rptfile))
        self.assertTrue(os.path.exists(self.es.binfile))
        self.assertTrue(os.path.exists(self.es.hydraulicfile))
        self.es.clean()
        self.assertTrue(os.path.exists(self.es.inputfile))
        self.assertFalse(os.path.exists(self.es.rptfile))
        self.assertFalse(os.path.exists(self.es.binfile))
        self.assertFalse(os.path.exists(self.es.hydraulicfile))

    def test_settable_values_for_links_and_nodes(self):
        self.assertEqual(Link.settable_values, [0, 1, 2, 3, 4, 5, 6, 7, 11, 12])
        self.assertEqual(
            Node.settable_values,
            [0,
             1,
             2,
             3,
             4,
             5,
             6,
             7,
             8,
             15,
             17,
             18,
             20,
             21,
             22,
             23])

    def xtest_synced_link_values_are_saved_when_synced(self):
        # change copule'a values
        d = Link.value_type['EN_DIAMETER']
        self.es.network.links[1].results[d][0]
        self.es.network.links[1].results[d][0] = 152.0
        self.es.network.links['105'].results[d][0] = 18.0
        # first without 'syncing""
        self.assertAlmostEquals(self.es._legacy_get('LINK', 1, d), 99.0, places=1)

        self.assertAlmostEquals(
            self.es._legacy_get('LINK',
                                self.es.network.links['105'].index,
                                d),
            12.0,
            places=1)
        # save input file
        self.es.ENsaveinpfile("a.inp")
        # now after 'syncing'
        self.es.sync(i_know_what_i_am_doing=True)
        self.assertAlmostEquals(self.es._legacy_get('LINK', 1, d), 152.0, places=1)
        self.assertAlmostEquals(
            self.es._legacy_get('LINK',
                                self.es.network.links['105'].index,
                                d),
            18.0,
            places=1)
        self.es.ENsaveinpfile("b.inp")
        # run
        self.es.run()
        # save input file again
        self.es.ENsaveinpfile("c.inp")
        self.assertEqual(tt.compareFiles("a.inp", "b.inp"), '99>152; 12>18; ')
        self.assertEqual(tt.compareFiles("a.inp", "c.inp"), '99>152; 12>18; ')
def run_epanet_model(request):
    start_time = time.time()

    return_obj = {
        'success': False,
        'message': None,
        'results': "",
    }

    if request.is_ajax() and request.method == 'POST':
        model = request.POST['model']
        quality = request.POST['quality']

        temp = 'tmp_' + str(uuid.uuid4()) + '.inp'

        with open(temp, 'w') as f:
            f.write(model)
        try:
            print("Initializing es")
            es = EPANetSimulation(temp)
            print("--- %s seconds ---" % (time.time() - start_time))
            start_time = time.time()

            print("run")
            es.run()
            print("--- %s seconds ---" % (time.time() - start_time))
            start_time = time.time()

            if quality != "NONE":
                print("runq")
                es.runq()
                print("--- %s seconds ---" % (time.time() - start_time))
                start_time = time.time()

            n = es.network.nodes
            nodes = {}
            node_threads = []
            node_range = 500
            print("getNodeRes")
            if len(n) > node_range:
                process = Process(target=getNodeResults,
                                  args=(n, range(1, node_range), nodes))
                process.start()
                node_threads.append(process)

                while node_range < len(n):
                    if len(n) - node_range - 500 < 0:
                        r = range(node_range, len(n) - node_range)
                    else:
                        r = range(node_range, node_range + 500)

                    process = Process(target=getNodeResults,
                                      args=(n, r, nodes))
                    process.start()
                    node_threads.append(process)

                    node_range += 500

            else:
                getNodeResults(n, range(0, len(n)), nodes)

            l = es.network.links
            links = {}
            link_threads = []
            link_range = 500
            if len(l) > link_range:
                process = Process(target=getLinkResults,
                                  args=(l, range(1, link_range), links))
                process.start()
                link_threads.append(process)

                while link_range < len(l):
                    if len(l) - link_range - 500 < 0:
                        r = range(link_range, len(l) - link_range)
                    else:
                        r = range(link_range, link_range + 500)

                    process = Process(target=getLinkResults,
                                      args=(l, r, links))
                    process.start()
                    link_threads.append(process)

                    link_range += 500

            else:
                getLinkResults(l, range(0, len(l)), links)

            if len(node_threads) > 0:
                for thread in node_threads:
                    thread.join()
                for thread in link_threads:
                    thread.join()

            print("--- %s seconds ---" % (time.time() - start_time))
            start_time = time.time()

            print("Setting return obj")

            return_obj['results'] = {'nodes': nodes, 'edges': links}
            print("--- %s seconds ---" % (time.time() - start_time))

            return_obj['success'] = True

        except Exception as e:
            print e
            return_obj[e]

        finally:
            os.remove(temp)

    else:
        return_obj['message'] = message_template_wrong_req_method.format(
            method="POST")

    print("Returning obj")
    return JsonResponse(return_obj)
class Test1(unittest.TestCase):

    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_false(self):
        assert False

    def test_can_retrieve_patterns_with_correct_length_and_values(self):
        self.assertAlmostEqual(self.es.network.patterns[1][1],1.34,delta=.01 )
        self.assertAlmostEqual(self.es.network.patterns[1][2],1.94,delta=.01 )
        self.assertAlmostEqual(self.es.network.patterns[1][3],1.46,delta=.01 )
        self.assertEqual(len(self.es.network.patterns[1]),24)
        self.assertAlmostEqual(self.es.network.patterns[1][24],1.67,delta=.01)
        self.assertEqual(len(self.es.network.patterns),5)
        with self.assertRaises(KeyError):
            self.es.network.patterns[6]
        with self.assertRaises(KeyError):
            self.es.network.patterns[1][25]
            
            
    def test_set_patternvalue_changes_pattern_values(self):
        self.assertAlmostEqual(self.es.ENgetpatternvalue(1,3)[1],1.46,delta=.01 )
        self.assertEqual(self.es.ENsetpatternvalue(1,3,1.8),0)
        self.assertAlmostEqual(self.es.ENgetpatternvalue(1,3)[1],1.8,delta=.01 )
        
    def test_set_patternvalue_can_append_pattern_value(self):
        self.assertEqual(len(self.es.network.patterns[1]),24)
        with self.assertRaises(TypeError):
            self.assertEqual(self.es.ENsetpattern(6,1.,3),0)
            
    def test_ENsetpatterndim_will_allocate_a_pattern(self):
        index = self.create_pattern()
        self.assertEqual(self.es.ENsetpatterndim(index,24),0)
        self.assertEqual(self.es.ENgetpatternlen(index),[0,24])
        for i in range(25):
            p=self.es.ENgetpatternvalue(index,i+1)
            if(i<24):
                self.assertEqual(p[0],0)
                self.assertAlmostEqual(p[1],0.0, delta=.01)
            else:
                self.assertEqual(p[0],251)                

    def create_pattern(self):
        self.assertEqual(self.es.ENaddpattern(patId),0)
        ret,index=self.es.ENgetpatternindex(patId)
        return index

    def test_ENsetpattern_will_successfully_allocate_and_fill_an_exiting_pattern(self):
        index=self.create_pattern()
        pat=[1.0,2.0,3.0,4.0,8.0,9.0,10.0,11.0,
             1.5,2.5,3.5,4.5,8.5,9.5,10.5,11.5,
             1.6,2.6,3.6,4.6,8.6,9.6,10.6,11.6,]
        self.assertEqual(self.es.ENsetpattern(index,pat),0)
        self.assertEqual(self.es.ENgetpatternlen(index),[0,24])
        for i in range(len(pat)):
            p=self.es.ENgetpatternvalue(index,i+1)
            self.assertEqual(p[0],0)
            self.assertAlmostEqual(p[1],pat[i],delta=0.001)   
        
    def test_ENsetpattern_with_pat_id_not_index_will_successfully_allocate_and_fill_an_exiting_pattern(self):
        index=self.create_pattern()
        pat=[1.0,2.0,3.0,4.0,8.0,9.0,10.0,11.0,
             1.5,2.5,3.5,4.5,8.5,9.5,10.5,11.5,
             1.6,2.6,3.6,4.6,8.6,9.6,10.6,11.6,]
        with self.assertRaises(Exception):
            self.es.ENsetpattern("boo",pat)
        self.assertEqual(self.es.ENsetpattern(patId,pat),0)
        self.assertEqual(self.es.ENgetpatternlen(index),[0,24])
        for i in range(len(pat)):
            p=self.es.ENgetpatternvalue(index,i+1)
            self.assertEqual(p[0],0)
            self.assertAlmostEqual(p[1],pat[i],delta=0.001) 
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()
Пример #30
0
    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()
    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()
Пример #32
0
        return 2

    def get_bounds(self):
        return ([-4] * 2, [4] * 2)

    def get_nic(self):
        return 6

    def get_nix(self):

        return 2


from PyGMO import population

d = EPANetSimulation('/home/varsha/Documents/Project.inp')
prob = problem(my_udp())
print(prob)
algo = pg.algorithm.sms_emoa(
    gen=2000)  # 2000 generations of SMS-EMOA should solve it
pop = population(prob, 500)
pop = algo.evolve(pop)

print(prob.objfun(pop.champion.x))
import matplotlib.pyplot as plt
import numpy as np

F = np.array([ind.cur_f for ind in pop]).T
plt.scatter(F[0], F[1])
plt.xlabel("Objective 1")
plt.ylabel("Objective 2")
#INSTALATION !!!!
#pip install epanettools

#LINKS
#https://pypi.org/project/EPANETTOOLS/
#https://wntr.readthedocs.io/en/latest/apidoc/wntr.epanet.toolkit.html
#https://github.com/Vitens/epynet/blob/master/epynet/epanet2.py

import os, pprint

pp = pprint.PrettyPrinter()
from epanettools.epanettools import EPANetSimulation, Node, Link, Network, Nodes, Links, Patterns, Pattern, Controls, Control
from epanettools.examples import simple

file = os.path.join(os.path.dirname(simple.__file__), 'Net3.inp')
es = EPANetSimulation(file)
'''
getting to understand the network
'''

#Number of elements
Number_nodes = len(es.network.nodes)
Number_links = len(es.network.links)
Number_controls = len(es.network.controls)

#List of indexes
List_constrols = [
    es.network.controls[x].index for x in list(es.network.controls)
]
List_nodes = [es.network.nodes[x].id for x in list(es.network.nodes)]
List_links = [es.network.links[x].id for x in list(es.network.links)]
Пример #34
0
# -*- coding: utf-8 -*-
#richmondNet

from Inital_Conditions import tarifario_ST, tarifario_CB, tarifario_S, tarifario_HH, tarifario_LZG, tarifario_LZHZ
import pprint
pp = pprint.PrettyPrinter()
from epanettools.epanettools import EPANetSimulation, Node, Link, Network, Nodes, Links, Patterns, Pattern, Controls, Control
es = EPANetSimulation('richmondNet.inp')
'''
getting to understand the network
'''
Number_nodes = len(es.network.nodes)
Number_links = len(es.network.links)
Number_controls = len(es.network.controls)

pp.pprint(Node.node_types)
pp.pprint(Link.link_types)
pp.pprint(Control.control_types)
pp.pprint(Link.value_type)
pp.pprint(Node.value_type)

[
    y.id for x, y in es.network.links.items()
    if y.link_type == Link.link_types['PUMP']
]  # get ids of pumps
[
    y.id for x, y in es.network.nodes.items()
    if y.node_type == Node.node_types['TANK']
]  # get ids of tanks
'''
['7F', '2A', '5C', '6D', '3A', '4B', '1A'] ---> pumps