├── MANIFEST.in ├── logo.png ├── epynet ├── lib │ ├── epanet2.dll │ ├── libepanet.so │ ├── libepanet.dylib │ └── libepanet-old.dylib ├── __init__.py ├── lazy_property.py ├── curve.py ├── pattern.py ├── objectcollection.py ├── .ipynb_checkpoints │ └── objectcollection-checkpoint.py ├── baseobject.py ├── link.py ├── node.py ├── network.py └── epanet2.py ├── .gitignore ├── setup.py ├── appveyor.yml ├── .travis.yml ├── tests ├── test_multiple_pumps.py ├── testnetwork.inp ├── test_network.py ├── test_threaded.py ├── test_creation.py └── .ipynb_checkpoints │ └── test_creation-checkpoint.py ├── README.md └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | graft epynet/lib 2 | -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/epynet/HEAD/logo.png -------------------------------------------------------------------------------- /epynet/lib/epanet2.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/epynet/HEAD/epynet/lib/epanet2.dll -------------------------------------------------------------------------------- /epynet/lib/libepanet.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/epynet/HEAD/epynet/lib/libepanet.so -------------------------------------------------------------------------------- /epynet/lib/libepanet.dylib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/epynet/HEAD/epynet/lib/libepanet.dylib -------------------------------------------------------------------------------- /epynet/lib/libepanet-old.dylib: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Vitens/epynet/HEAD/epynet/lib/libepanet-old.dylib -------------------------------------------------------------------------------- /epynet/__init__.py: -------------------------------------------------------------------------------- 1 | from .network import Network 2 | from .link import Link, Pipe, Pump, Valve 3 | from .node import Node, Junction, Reservoir, Tank 4 | from .objectcollection import ObjectCollection 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Python Modules 2 | *.pyc 3 | 4 | # Setuptools distribution folder. 5 | /dist/ 6 | 7 | # Python egg metadata, regenerated from source files by setuptools 8 | /*.egg-info 9 | 10 | .DS_Store 11 | 12 | *.rpt 13 | -------------------------------------------------------------------------------- /epynet/lazy_property.py: -------------------------------------------------------------------------------- 1 | def lazy_property(fn): 2 | '''Decorator that makes a property lazy-evaluated. 3 | ''' 4 | attr_name = fn.__name__ 5 | 6 | @property 7 | def _lazy_property(self): 8 | if attr_name not in self._values: 9 | self._values[attr_name] = fn(self) 10 | return self._values[attr_name] 11 | return _lazy_property 12 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | setup(name='epynet', 4 | version='1.1', 5 | description='Vitens EPANET 2.0 wrapper and utilities', 6 | url='https://github.com/vitenstc/epynet', 7 | author='Abel Heinsbroek', 8 | author_email='abel.heinsbroek@vitens.nl', 9 | license='Apache Licence 2.0', 10 | packages=['epynet'], 11 | package_data={'epynet': ['lib/*']}, 12 | install_requires = [ 13 | 'pandas' 14 | ], 15 | zip_safe=False) 16 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | build: false 2 | 3 | environment: 4 | PYTHON_VERSION: "2.7" 5 | PYTHON_ARCH: "64" 6 | MINICONDA: C:\Miniconda-x64 7 | 8 | init: 9 | - "ECHO %PYTHON% %PYTHON_VERSION% %PYTHON_ARCH%" 10 | 11 | install: 12 | - "set PATH=%MINICONDA%;%MINICONDA%\\Scripts;%PATH%" 13 | - conda config --set always_yes yes --set changeps1 no 14 | - conda update -q conda 15 | - conda info -a 16 | - "conda create -q -n test-environment python=%PYTHON_VERSION% pandas nose" 17 | - activate test-environment 18 | 19 | test_script: 20 | - python setup.py install 21 | - nosetests -v 22 | -------------------------------------------------------------------------------- /epynet/curve.py: -------------------------------------------------------------------------------- 1 | from . import epanet2 2 | import weakref 3 | 4 | class Curve(object): 5 | 6 | def __init__(self, uid, network): 7 | self.uid = uid 8 | self.network = weakref.ref(network) 9 | 10 | def __str__(self): 11 | return "" 12 | 13 | @property 14 | def index(self): 15 | return self.network().ep.ENgetcurveindex(self.uid) 16 | 17 | @property 18 | def values(self): 19 | return self.network().ep.ENgetcurve(self.index) 20 | 21 | @values.setter 22 | def values(self, value): 23 | self.network().ep.ENsetcurve(self.index, value) 24 | -------------------------------------------------------------------------------- /epynet/pattern.py: -------------------------------------------------------------------------------- 1 | from . import epanet2 2 | import weakref 3 | 4 | 5 | class Pattern(object): 6 | 7 | def __init__(self, uid, network): 8 | self.uid = uid 9 | self.network = weakref.ref(network) 10 | 11 | def __str__(self): 12 | return "" 13 | 14 | @property 15 | def index(self): 16 | return self.network().ep.ENgetpatternindex(self.uid) 17 | 18 | @property 19 | def values(self): 20 | values = [] 21 | n_values = self.network().ep.ENgetpatternlen(self.index) 22 | for n in range(1, n_values+1): 23 | values.append(self.network().ep.ENgetpatternvalue(self.index, n)) 24 | return values 25 | 26 | @values.setter 27 | def values(self, value): 28 | self.network().ep.ENsetpattern(self.index, value) 29 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | python: 3 | - "3.6" 4 | 5 | # Setup anaconda 6 | before_install: 7 | - sudo apt-get update 8 | # We do this conditionally because it saves us some downloading if the 9 | # version is the same. 10 | - wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh; 11 | - bash miniconda.sh -b -p $HOME/miniconda 12 | - export PATH="$HOME/miniconda/bin:$PATH" 13 | - hash -r 14 | - conda config --set always_yes yes --set changeps1 no 15 | - conda update -q conda 16 | # Useful for debugging any issues with conda 17 | - conda info -a 18 | 19 | # Replace dep1 dep2 ... with your dependencies 20 | - conda create -q -n test-environment python=$TRAVIS_PYTHON_VERSION pandas nose 21 | - source activate test-environment 22 | - python setup.py install 23 | # Run test 24 | script: 25 | - nosetests -v 26 | -------------------------------------------------------------------------------- /epynet/objectcollection.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import pandas as pd 3 | 4 | class ObjectCollection(dict): 5 | 6 | # magic methods to transform collection attributes to Pandas Series or, if we return classes, another list 7 | def __getattr__(self,name): 8 | values = {} 9 | 10 | for key, item in self.items(): 11 | values[item.uid] = getattr(item,name) 12 | 13 | if isinstance(values[item.uid], pd.Series): 14 | return pd.concat(values,axis=1) 15 | 16 | return pd.Series(values) 17 | 18 | def __setattr__(self, name, value): 19 | 20 | if isinstance(value, pd.Series): 21 | for key, val in value.items(): 22 | setattr(self[key],name,val) 23 | return 24 | 25 | for key, item in self.items(): 26 | setattr(item,name,value) 27 | 28 | def __getitem__(self, key): 29 | # support for index slicing through pandas 30 | if isinstance(key, pd.Series): 31 | ids = key[key==True].index 32 | return_dict = ObjectCollection() 33 | for uid in ids: 34 | obj = super(ObjectCollection, self).__getitem__(uid) 35 | return_dict[uid] = obj 36 | return return_dict 37 | 38 | return super(ObjectCollection, self).__getitem__(key) 39 | 40 | def __iter__(self): 41 | return iter(self.values()) 42 | -------------------------------------------------------------------------------- /epynet/.ipynb_checkpoints/objectcollection-checkpoint.py: -------------------------------------------------------------------------------- 1 | import collections 2 | import pandas as pd 3 | 4 | class ObjectCollection(dict): 5 | 6 | # magic methods to transform collection attributes to Pandas Series or, if we return classes, another list 7 | def __getattr__(self,name): 8 | values = {} 9 | 10 | for key, item in self.items(): 11 | values[item.uid] = getattr(item,name) 12 | 13 | if isinstance(values[item.uid], pd.Series): 14 | return pd.concat(values,axis=1) 15 | 16 | return pd.Series(values) 17 | 18 | def __setattr__(self, name, value): 19 | 20 | if isinstance(value, pd.Series): 21 | for key, val in value.items(): 22 | setattr(self[key],name,val) 23 | return 24 | 25 | for key, item in self.items(): 26 | setattr(item,name,value) 27 | 28 | def __getitem__(self, key): 29 | # support for index slicing through pandas 30 | if isinstance(key, pd.Series): 31 | ids = key[key==True].index 32 | return_dict = ObjectCollection() 33 | for uid in ids: 34 | obj = super(ObjectCollection, self).__getitem__(uid) 35 | return_dict[uid] = obj 36 | return return_dict 37 | 38 | return super(ObjectCollection, self).__getitem__(key) 39 | 40 | def __iter__(self): 41 | return iter(self.values()) 42 | -------------------------------------------------------------------------------- /tests/test_multiple_pumps.py: -------------------------------------------------------------------------------- 1 | from epynet import Network 2 | from nose.tools import assert_equal, assert_almost_equal 3 | import pandas as pd 4 | 5 | 6 | class TestMultiplePumps(object): 7 | @classmethod 8 | def setup_class(self): 9 | self.network = Network() 10 | 11 | 12 | def test01_multiple_pumps(self): 13 | 14 | network = self.network 15 | 16 | network.add_reservoir("R1", 0, 0, 0) 17 | network.add_junction("J1", 1, 0) 18 | network.add_junction("J2", 2, 0) 19 | network.add_junction("J3", 3, 0) 20 | network.add_junction("J4", 4, 0) 21 | network.add_reservoir("R2", 5, 0, 0) 22 | 23 | network.add_pipe("P1", "R1", "J1", 200, 100) 24 | network.add_pipe("P2", "J2", "J4", 200, 100) 25 | network.add_pipe("P3", "J3", "J4", 200, 100) 26 | network.add_pipe("P4", "J4", "R2", 200, 100) 27 | 28 | P1 = network.add_pump("PU1", "J1", "J2", 1) 29 | P2 = network.add_pump("PU2", "J1", "J3", 1) 30 | 31 | C1 = network.add_curve("1", [[100, 30], [200, 20], [300, 10]]) 32 | C2 = network.add_curve("2", [[100, 40], [200, 25], [300, 10]]) 33 | 34 | P1.curve = C1 35 | P2.curve = C2 36 | 37 | network.solve() 38 | 39 | assert_almost_equal(P1.flow, 225.88, 2) 40 | assert_almost_equal(P2.flow, 248.14, 2) 41 | 42 | C3 = network.add_curve("3", [[100, 30]]) 43 | C4 = network.add_curve("4", [[100, 50]]) 44 | 45 | P1.curve = C3 46 | P2.curve = C4 47 | 48 | network.solve() 49 | 50 | assert_almost_equal(P1.flow, 173.09, 2) 51 | assert_almost_equal(P2.flow, 184.10, 2) 52 | -------------------------------------------------------------------------------- /epynet/baseobject.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import warnings 3 | import weakref 4 | 5 | 6 | def lazy_property(fn): 7 | '''Decorator that makes a property lazy-evaluated. 8 | ''' 9 | attr_name = fn.__name__ 10 | 11 | @property 12 | def _lazy_property(self): 13 | if attr_name not in self._values.keys(): 14 | self._values[attr_name] = fn(self) 15 | return self._values[attr_name] 16 | return _lazy_property 17 | 18 | class BaseObject(object): 19 | 20 | static_properties = {} 21 | properties = {} 22 | 23 | def __init__(self, uid, network): 24 | 25 | # the object index 26 | self.uid = uid 27 | # weak reference to the network 28 | self.network = weakref.ref(network) 29 | # cache of values 30 | self._values = {} 31 | # dictionary of calculation results, only gets 32 | # filled during solve() method 33 | self.results = {} 34 | # list of times 35 | self.times = [] 36 | # index caching 37 | self._index = None 38 | 39 | def get_index(self, uid): 40 | raise NotImplementedError 41 | 42 | def set_object_value(self, code, value): 43 | raise NotImplementedError 44 | 45 | def get_object_value(self, code): 46 | raise NotImplementedError 47 | 48 | def reset(self): 49 | self._values = {} 50 | self.results = {} 51 | self.times = [] 52 | 53 | def __str__(self): 54 | return "" 55 | 56 | def __getattr__(self, name): 57 | 58 | if name in self.static_properties.keys(): 59 | return self.get_property(self.static_properties[name]) 60 | 61 | elif name in self.properties.keys(): 62 | if not self.network().solved: 63 | warnings.warn("requesting dynamic properties from an unsolved network") 64 | if self.results == {}: 65 | return self.get_property(self.properties[name]) 66 | else: 67 | return pd.Series(self.results[name], index=self.times) 68 | else: 69 | raise AttributeError('Nonexistant Attribute', name) 70 | 71 | def __setattr__(self, name, value): 72 | if name in self.properties.keys(): 73 | raise AttributeError("Illegal Assignment to Computed Value") 74 | 75 | if name in self.static_properties.keys(): 76 | self.set_static_property(self.static_properties[name], value) 77 | else: 78 | super(BaseObject, self).__setattr__(name, value) 79 | 80 | def set_static_property(self, code, value): 81 | # set network as unsolved 82 | self.network().solved = False 83 | self._values[code] = value 84 | self.set_object_value(code, value) 85 | 86 | def get_property(self, code): 87 | if code not in self._values.keys(): 88 | self._values[code] = self.get_object_value(code) 89 | return self._values[code] 90 | 91 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | Epynet Logo 3 |

4 | 5 | 6 | EPYNET is an object oriented wrapper around the EPANET 2.1 community edition hydraulic network solver. 7 | 8 | ## Features 9 | - [x] Hydraulic calculations 10 | - [x] Object oriented access to Nodes, Junctions, Reservoirs, Tanks, Links, Pipes, Valves and Pumps 11 | - [x] Convienent access to simulation results such as flow, velocity and pressure through class properties 12 | - [x] Manipulation of valve and pump settings 13 | - [x] Manipulation of pipe, junction, reservoir and tank settings 14 | - [x] Support for time series 15 | - [x] Pattern and Curve creation and manipulation 16 | - [x] Create and remove nodes and links 17 | - [x] Work on multiple networks at the same time 18 | - [ ] [TODO] Chemical calculations 19 | 20 | ## Example Usage 21 | ```python 22 | # load a network 23 | from epynet import Network 24 | network = Network('network.inp') 25 | # solve network 26 | network.solve() 27 | # properties 28 | print(network.pipes['4'].flow) 29 | print(network.nodes['1'].demand) 30 | # valve manipulation 31 | network.valves['12'].setting = 10 32 | # convinience properties 33 | print(network.pipes['5'].downstream_node.pressure) 34 | print(network.nodes['1'].upstream_links[0].velocity) 35 | # pandas integration 36 | print(network.pipes.flow) 37 | print(network.pipes.length[network.pipes.velocity > 1]) 38 | print(network.nodes.demand[network.nodes.pressure < 10].max()) 39 | # network manipulaton 40 | network.add_tank('tankid', x=10, y=10, elevation=10) 41 | network.add_junction('junctionid', x=20, y=10, elevation=5) 42 | network.add_pipe('tankid', 'junctionid', length=10, diameter=200, roughness=0.1) 43 | ``` 44 | 45 | ## Installation 46 | * Clone or download repository 47 | * ```python setup.py install``` 48 | 49 | ## Requirements 50 | * 64 bit Python 2.7 or 3 51 | * Windows, OSX or Linux 52 | 53 | ## Unit Tests 54 | | **Mac/Linux** | **Windows** | 55 | |---|---| 56 | | [![Build Status](https://travis-ci.org/Vitens/epynet.svg?branch=master)](https://travis-ci.org/Vitens/epynet) | [![Build status](https://ci.appveyor.com/api/projects/status/ewa92p50rw5u0yfd?svg=true)](https://ci.appveyor.com/project/AbelHeinsbroek/epynet) | 57 | 58 | ## Acknowledgements 59 | This project makes use of the [EPANET 2.1](https://github.com/OpenWaterAnalytics/EPANET) community version and is (partly) derived from the [epanettools](https://github.com/asselapathirana/epanettools) package (Assela Pathirana) and the [epanet-python](https://github.com/OpenWaterAnalytics/epanet-python) library (Maurizio Cingi) 60 | 61 | ## About Vitens 62 | 63 | Vitens is the largest drinking water company in The Netherlands. We deliver top quality drinking water to 5.6 million people and companies in the provinces Flevoland, Fryslân, Gelderland, Utrecht and Overijssel and some municipalities in Drenthe and Noord-Holland. Annually we deliver 350 million m³ water with 1,400 employees, 100 water treatment works and 49,000 kilometres of water mains. 64 | 65 | One of our main focus points is using advanced water quality, quantity and hydraulics models to further improve and optimize our treatment and distribution processes. 66 | 67 | ## Licence 68 | 69 | Copyright 2016 Vitens 70 | 71 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 72 | 73 | http://www.apache.org/licenses/LICENSE-2.0 74 | 75 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 76 | -------------------------------------------------------------------------------- /epynet/link.py: -------------------------------------------------------------------------------- 1 | """ EPYNET Classes """ 2 | from . import epanet2 3 | from .baseobject import BaseObject, lazy_property 4 | from .curve import Curve 5 | 6 | class Link(BaseObject): 7 | """ EPANET Link Class """ 8 | 9 | properties = {'flow': epanet2.EN_FLOW} 10 | 11 | def __init__(self, uid, network): 12 | super(Link, self).__init__(uid, network) 13 | self.from_node = None 14 | self.to_node = None 15 | 16 | def get_index(self, uid): 17 | if not self._index: 18 | self._index = self.network().ep.ENgetlinkindex(uid) 19 | return self._index 20 | 21 | def set_object_value(self, code, value): 22 | index = self.get_index(self.uid) 23 | return self.network().ep.ENsetlinkvalue(index, code, value) 24 | 25 | def get_object_value(self, code): 26 | index = self.get_index(self.uid) 27 | return self.network().ep.ENgetlinkvalue(index, code) 28 | 29 | @property 30 | def comment(self): 31 | return self.network().ep.ENgetcomment(1, self.index) # get comment from LINK table 32 | 33 | @comment.setter 34 | def comment(self, value): 35 | return self.network().ep.ENsetcomment(1, self.index, value) # set comment from LINK table 36 | 37 | 38 | @property 39 | def index(self): 40 | return self.get_index(self.uid) 41 | 42 | 43 | # upstream and downstream nodes 44 | @lazy_property 45 | def upstream_node(self): 46 | if self.flow >= 0: 47 | return self.from_node 48 | else: 49 | return self.to_node 50 | 51 | @lazy_property 52 | def downstream_node(self): 53 | if self.flow >= 0: 54 | return self.to_node 55 | else: 56 | return self.from_node 57 | 58 | @lazy_property 59 | def vertices(self): 60 | return self.network().get_vertices(self.uid) 61 | 62 | @lazy_property 63 | def path(self): 64 | return [self.from_node.coordinates] + self.vertices + [self.to_node.coordinates] 65 | 66 | class Pipe(Link): 67 | """ EPANET Pipe Class """ 68 | link_type = 'pipe' 69 | 70 | static_properties = {'diameter': epanet2.EN_DIAMETER, 'length': epanet2.EN_LENGTH, 71 | 'roughness': epanet2.EN_ROUGHNESS, 'minorloss': epanet2.EN_MINORLOSS, 72 | 'initstatus': epanet2.EN_INITSTATUS, 'status': epanet2.EN_STATUS} 73 | properties = {'flow': epanet2.EN_FLOW, 'headloss': epanet2.EN_HEADLOSS, 'velocity': epanet2.EN_VELOCITY} 74 | 75 | @lazy_property 76 | def check_valve(self): 77 | type_code = self.network().ep.ENgetlinktype(self.index) 78 | return (type_code == epanet2.EN_CVPIPE) 79 | 80 | 81 | class Pump(Link): 82 | """ EPANET Pump Class """ 83 | link_type = 'pump' 84 | 85 | static_properties = {'length': epanet2.EN_LENGTH, 'initstatus': epanet2.EN_INITSTATUS, 86 | 'speed': epanet2.EN_INITSETTING} 87 | properties = {'flow': epanet2.EN_FLOW, 'energy': epanet2.EN_ENERGY} 88 | 89 | @property 90 | def velocity(self): 91 | return 1.0 92 | 93 | @property 94 | def curve(self): 95 | curve_index = self.network().ep.ENgetheadcurveindex(self.index) 96 | curve_uid = self.network().ep.ENgetcurveid(curve_index) 97 | return Curve(curve_uid, self.network()) 98 | 99 | @curve.setter 100 | def curve(self, value): 101 | 102 | 103 | if isinstance(value, int): 104 | curve_index = value 105 | elif isinstance(value, str): 106 | curve_index = self.network().ep.ENgetcurveindex(value) 107 | elif isinstance(value, Curve): 108 | curve_index = value.index 109 | else: 110 | raise ValueError("Invalid input for curve") 111 | 112 | # set network as unsolved 113 | self.network().solved = False 114 | self.network().ep.ENsetheadcurveindex(self.index, curve_index) 115 | 116 | 117 | class Valve(Link): 118 | """ EPANET Valve Class """ 119 | 120 | static_properties = {'setting': epanet2.EN_INITSETTING, 'initstatus': epanet2.EN_INITSTATUS, 121 | 'diameter': epanet2.EN_DIAMETER} 122 | properties = {'velocity': epanet2.EN_VELOCITY, 'flow': epanet2.EN_FLOW} 123 | 124 | link_type = 'valve' 125 | 126 | types = {3: "PRV", 4: "PSV", 5: "PBV", 6: "FCV", 7: "TCV", 8: "GPV"} 127 | 128 | @lazy_property 129 | def valve_type(self): 130 | try: 131 | type_code = self.network().ep.ENgetlinktype(self.index) 132 | except Exception as e: 133 | print(e) 134 | raise e 135 | return self.types[type_code] 136 | -------------------------------------------------------------------------------- /epynet/node.py: -------------------------------------------------------------------------------- 1 | """ EPYNET Classes """ 2 | from . import epanet2 3 | from .objectcollection import ObjectCollection 4 | from .baseobject import BaseObject, lazy_property 5 | from .pattern import Pattern 6 | 7 | class Node(BaseObject): 8 | """ Base EPANET Node class """ 9 | 10 | static_properties = {'elevation': epanet2.EN_ELEVATION} 11 | properties = {'head': epanet2.EN_HEAD, 'pressure': epanet2.EN_PRESSURE, 'quality': epanet2.EN_QUALITY} 12 | 13 | def __init__(self, uid, network): 14 | super(Node, self).__init__(uid, network) 15 | self.links = ObjectCollection() 16 | 17 | def get_index(self, uid): 18 | if not self._index: 19 | self._index = self.network().ep.ENgetnodeindex(uid) 20 | return self._index 21 | 22 | def set_object_value(self, code, value): 23 | return self.network().ep.ENsetnodevalue(self.index, code, value) 24 | 25 | def get_object_value(self, code): 26 | return self.network().ep.ENgetnodevalue(self.index, code) 27 | 28 | @property 29 | def comment(self): 30 | return self.network().ep.ENgetcomment(0, self.index) # get comment from NODE table 31 | 32 | @comment.setter 33 | def comment(self, value): 34 | return self.network().ep.ENsetcomment(0, self.index, value) # set comment from LINK table 35 | 36 | @property 37 | def index(self): 38 | return self.get_index(self.uid) 39 | 40 | @lazy_property 41 | def coordinates(self): 42 | return self.network().ep.ENgetcoord(self.index) 43 | 44 | # extra functionality 45 | @lazy_property 46 | def upstream_links(self): 47 | """ return a list of upstream links """ 48 | if self.results != {}: 49 | raise ValueError("This method is only supported for steady state simulations") 50 | 51 | links = ObjectCollection() 52 | for link in self.links: 53 | if (link.to_node == self and link.flow >= 1e-3) or (link.from_node == self and link.flow < -1e-3): 54 | links[link.uid] = link 55 | return links 56 | 57 | @lazy_property 58 | def downstream_links(self): 59 | """ return a list of downstream nodes """ 60 | if self.results != {}: 61 | raise ValueError("This method is only supported for steady state simulations") 62 | 63 | links = ObjectCollection() 64 | for link in self.links: 65 | if (link.from_node == self and link.flow >= 1e-3) or (link.to_node == self and link.flow < -1e-3): 66 | links[link.uid] = link 67 | return links 68 | 69 | @lazy_property 70 | def inflow(self): 71 | outflow = 0 72 | for link in self.upstream_links: 73 | outflow += abs(link.flow) 74 | return outflow 75 | 76 | @lazy_property 77 | def outflow(self): 78 | outflow = 0 79 | for link in self.downstream_links: 80 | outflow += abs(link.flow) 81 | return outflow 82 | """ calculates all the water flowing out of the node """ 83 | 84 | class Reservoir(Node): 85 | """ EPANET Reservoir Class """ 86 | node_type = "Reservoir" 87 | 88 | class Junction(Node): 89 | """ EPANET Junction Class """ 90 | static_properties = {'elevation': epanet2.EN_ELEVATION, 'basedemand': epanet2.EN_BASEDEMAND, 'emitter': epanet2.EN_EMITTER} 91 | properties = {'head': epanet2.EN_HEAD, 'pressure': epanet2.EN_PRESSURE, 'demand': epanet2.EN_DEMAND, 'quality': epanet2.EN_QUALITY} 92 | node_type = "Junction" 93 | 94 | @property 95 | def pattern(self): 96 | pattern_index = int(self.get_property(epanet2.EN_PATTERN)) 97 | uid = self.network().ep.ENgetpatternid(pattern_index) 98 | return Pattern(uid, self.network()) 99 | 100 | @pattern.setter 101 | def pattern(self, value): 102 | if isinstance(value, int): 103 | pattern_index = value 104 | elif isinstance(value, str): 105 | pattern_index = self.network().ep.ENgetpatternindex(value) 106 | else: 107 | pattern_index = value.index 108 | 109 | self.network().solved = False 110 | self.set_object_value(epanet2.EN_PATTERN, pattern_index) 111 | 112 | class Tank(Node): 113 | """ EPANET Tank Class """ 114 | node_type = "Tank" 115 | 116 | static_properties = {'elevation': epanet2.EN_ELEVATION, 'basedemand': epanet2.EN_BASEDEMAND, 117 | 'initvolume': epanet2.EN_INITVOLUME, 'diameter': epanet2.EN_TANKDIAM, 118 | 'minvolume': epanet2.EN_MINVOLUME, 'minlevel': epanet2.EN_MINLEVEL, 119 | 'maxlevel': epanet2.EN_MAXLEVEL, 'maxvolume': 25, 'tanklevel': epanet2.EN_TANKLEVEL} 120 | properties = {'head': epanet2.EN_HEAD, 'pressure': epanet2.EN_PRESSURE, 121 | 'demand': epanet2.EN_DEMAND, 'volume': 24, 'level': epanet2.EN_TANKLEVEL} 122 | -------------------------------------------------------------------------------- /tests/testnetwork.inp: -------------------------------------------------------------------------------- 1 | [TITLE] 2 | 3 | 4 | [JUNCTIONS] 5 | ;ID Elev Demand Pattern 6 | 2 0 0 ;testcommentjunction 7 | 3 0 0 ; 8 | 4 5 1 1 ; 9 | 5 0 1 1 ; 10 | 6 0 1 1 ; 11 | 7 0 1 1 ; 12 | 8 0 1 1 ; 13 | 9 0 1 1 ; 14 | 10 0 1 1 ; 15 | 16 | [RESERVOIRS] 17 | ;ID Head Pattern 18 | in 10 ;testcommentreservoir 19 | 20 | [TANKS] 21 | ;ID Elevation InitLevel MinLevel MaxLevel Diameter MinVol VolCurve 22 | 11 0 10 0 20 50 0 ;testcommenttank 23 | 24 | [PIPES] 25 | ;ID Node1 Node2 Length Diameter Roughness MinorLoss Status 26 | 1 in 2 100 100 0.1 0 Open ;testcommentpipe 27 | 3 3 4 100 100 0.1 0 Open ; 28 | 4 4 5 100 100 0.1 0 Open ; 29 | 5 5 6 100 100 0.1 0 Open ; 30 | 6 6 7 100 100 0.1 0 Open ; 31 | 7 7 8 100 100 0.1 0 Open ; 32 | 8 8 9 100 100 0.1 0 Open ; 33 | 10 5 8 100 100 0.1 0 Open ; 34 | 11 4 9 100 150 0.1 0.1 Open ; 35 | 12 9 11 100 100 0.1 0 Open ; 36 | 37 | [PUMPS] 38 | ;ID Node1 Node2 Parameters 39 | 2 2 3 HEAD 1 ;testcommentpump 40 | 41 | [VALVES] 42 | ;ID Node1 Node2 Diameter Type Setting MinorLoss 43 | 9 9 10 100 PRV 5 0 ;testcommentvalve 44 | 45 | [TAGS] 46 | 47 | [DEMANDS] 48 | ;Junction Demand Pattern Category 49 | 50 | [STATUS] 51 | ;ID Status/Setting 52 | 53 | [PATTERNS] 54 | ;ID Multipliers 55 | ; 56 | 1 1 2 3 4 5 4 57 | 1 3 2 1 1 58 | 59 | [CURVES] 60 | ;ID X-Value Y-Value 61 | ;PUMP: PUMP: 62 | 1 100 50 63 | 64 | [CONTROLS] 65 | 66 | 67 | [RULES] 68 | 69 | 70 | [ENERGY] 71 | Global Efficiency 75 72 | Global Price 0 73 | Demand Charge 0 74 | 75 | [EMITTERS] 76 | ;Junction Coefficient 77 | 78 | [QUALITY] 79 | ;Node InitQual 80 | 81 | [SOURCES] 82 | ;Node Type Quality Pattern 83 | 84 | [REACTIONS] 85 | ;Type Pipe/Tank Coefficient 86 | 87 | 88 | [REACTIONS] 89 | Order Bulk 1 90 | Order Tank 1 91 | Order Wall 1 92 | Global Bulk 0 93 | Global Wall 0 94 | Limiting Potential 0 95 | Roughness Correlation 0 96 | 97 | [MIXING] 98 | ;Tank Model 99 | 100 | [TIMES] 101 | Duration 10:00 102 | Hydraulic Timestep 1:00 103 | Quality Timestep 0:05 104 | Pattern Timestep 1:00 105 | Pattern Start 0:00 106 | Report Timestep 1:00 107 | Report Start 0:00 108 | Start ClockTime 12 am 109 | Statistic NONE 110 | 111 | [REPORT] 112 | Status No 113 | Summary No 114 | Page 0 115 | 116 | [OPTIONS] 117 | Units CMH 118 | Headloss D-W 119 | Specific Gravity 1 120 | Viscosity 1 121 | Trials 40 122 | Accuracy 0.001 123 | CHECKFREQ 2 124 | MAXCHECK 10 125 | DAMPLIMIT 0 126 | Unbalanced Continue 10 127 | Pattern 1 128 | Demand Multiplier 1.0 129 | Emitter Exponent 0.5 130 | Quality None mg/L 131 | Diffusivity 1 132 | Tolerance 0.01 133 | 134 | [COORDINATES] 135 | ;Node X-Coord Y-Coord 136 | 2 648.91 5747.69 137 | 3 1155.46 5747.69 138 | 4 2103.02 5747.69 139 | 5 2104.94 4506.17 140 | 6 2103.02 3709.56 141 | 7 3884.90 3709.56 142 | 8 3884.90 4508.12 143 | 9 3884.90 5747.69 144 | 10 5184.06 5753.65 145 | in 166.19 5747.69 146 | 11 3884.90 6558.18 147 | 148 | [VERTICES] 149 | ;Link X-Coord Y-Coord 150 | 151 | [LABELS] 152 | ;X-Coord Y-Coord Label & Anchor Node 153 | 154 | [BACKDROP] 155 | DIMENSIONS 0.00 0.00 10000.00 10000.00 156 | UNITS None 157 | FILE 158 | OFFSET 0.00 0.00 159 | 160 | [END] 161 | -------------------------------------------------------------------------------- /tests/test_network.py: -------------------------------------------------------------------------------- 1 | from epynet import Network 2 | from nose.tools import assert_equal, assert_almost_equal 3 | import pandas as pd 4 | 5 | class TestNetwork(object): 6 | @classmethod 7 | def setup_class(self): 8 | self.network = Network(inputfile="tests/testnetwork.inp") 9 | self.network.solve() 10 | 11 | @classmethod 12 | def teadown(self): 13 | self.network.ep.ENclose() 14 | 15 | def test01_network(self): 16 | # test0 node count 17 | assert_equal(len(self.network.nodes),11) 18 | # test0 link count 19 | assert_equal(len(self.network.links),12) 20 | # test0 reservoir count 21 | assert_equal(len(self.network.reservoirs),1) 22 | # test0 valve count 23 | assert_equal(len(self.network.valves),1) 24 | # test0 pump count 25 | assert_equal(len(self.network.pumps),1) 26 | # test0 tank count 27 | assert_equal(len(self.network.tanks),1) 28 | 29 | def test02_link(self): 30 | # test0 the properties of a single link 31 | link = self.network.links["11"] 32 | # pipe index and uid 33 | assert_equal(link.index,9) 34 | assert_equal(link.uid,"11") 35 | # from/to node 36 | assert_equal(link.from_node.uid,"4") 37 | assert_equal(link.to_node.uid,"9") 38 | 39 | def test03_pipe(self): 40 | # test0 the properties of a single pipe 41 | pipe = self.network.links["11"] 42 | # check type 43 | assert_equal(pipe.link_type,"pipe") 44 | 45 | assert_almost_equal(pipe.length,100,2) 46 | assert_almost_equal(pipe.diameter,150,2) 47 | assert_almost_equal(pipe.roughness,0.1,2) 48 | assert_almost_equal(pipe.minorloss,0.1,2) 49 | # flow 50 | assert_almost_equal(pipe.flow,87.92,2) 51 | # direction 52 | assert_almost_equal(pipe.velocity,1.38,2) 53 | # status 54 | assert_equal(pipe.status,1) 55 | # headloss 56 | assert_almost_equal(pipe.headloss,1.29,2) 57 | # upstream/downstream node 58 | assert_equal(pipe.upstream_node.uid,"4") 59 | assert_equal(pipe.downstream_node.uid,"9") 60 | 61 | def test04_pump(self): 62 | pump = self.network.pumps["2"] 63 | # check type 64 | assert_equal(pump.link_type,"pump") 65 | 66 | assert_equal(pump.speed,1.0) 67 | assert_almost_equal(pump.flow,109.67,2) 68 | # change speed 69 | pump.speed = 1.5 70 | assert_equal(pump.speed,1.5) 71 | # resolve network 72 | self.network.solve() 73 | assert_almost_equal(pump.flow,164.5,2) 74 | # revert speed 75 | pump.speed = 1.0 76 | self.network.solve() 77 | 78 | def test05_valve(self): 79 | valve = self.network.valves["9"] 80 | # check type 81 | assert_equal(valve.link_type,"valve") 82 | # check valve type 83 | assert_equal(valve.valve_type,"PRV") 84 | # valve settings 85 | assert_equal(valve.setting,5) 86 | assert_almost_equal(valve.downstream_node.pressure,5,2) 87 | # change setting 88 | valve.setting = 10 89 | assert_equal(valve.setting,10) 90 | self.network.solve() 91 | assert_almost_equal(valve.downstream_node.pressure,10,2) 92 | 93 | def test06_node(self): 94 | node = self.network.nodes["4"] 95 | # uid 96 | assert_equal(node.uid,"4") 97 | # coordinates 98 | coordinates = node.coordinates 99 | assert_almost_equal(coordinates[0],2103.02,2) 100 | assert_almost_equal(coordinates[1],5747.69,2) 101 | # links 102 | assert_equal(len(node.links),3) 103 | # up and downstream links 104 | assert_equal(len(node.downstream_links),2) 105 | assert_equal(len(node.upstream_links),1) 106 | # inflow 107 | assert_equal(round(node.inflow,2),109.67) 108 | # outflow 109 | assert_equal(round(node.outflow,2),round(node.inflow,2)-node.demand) 110 | # elevation 111 | assert_equal(node.elevation,5) 112 | # head 113 | assert_equal(round(node.head,2),25.13) 114 | 115 | def test07_junction(self): 116 | junction = self.network.junctions["4"] 117 | 118 | assert_equal(round(junction.basedemand,2),1) 119 | assert_equal(round(junction.demand,2),1) 120 | 121 | def test08_tank(self): 122 | tank = self.network.tanks["11"] 123 | assert_equal(round(tank.diameter,2),50) 124 | assert_equal(round(tank.initvolume,2),19634.95) 125 | assert_equal(tank.minvolume,0) 126 | assert_equal(tank.minlevel,0) 127 | assert_equal(tank.maxlevel,20) 128 | assert_equal(round(tank.volume,2),19634.95) 129 | assert_equal(round(tank.maxvolume),2*round(tank.volume)) 130 | 131 | def test09_time(self): 132 | junction = self.network.junctions["4"] 133 | self.network.solve(3600) 134 | assert_equal(round(junction.demand,2),2) 135 | self.network.solve(7200) 136 | assert_equal(round(junction.demand,2),3) 137 | 138 | def test10_collections(self): 139 | # collection attributes as pandas Series 140 | assert_almost_equal(self.network.pipes.flow.mean(),46.78,2) 141 | assert_almost_equal(self.network.pipes.diameter.max(),150,2) 142 | assert_almost_equal(self.network.pipes.velocity.min(),0.105,2) 143 | 144 | assert_equal(self.network.valves.setting.mean(),10) 145 | 146 | assert_almost_equal(self.network.junctions.demand.mean(),2.33,2) 147 | 148 | # filtering and slicing collections 149 | assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),3) 150 | assert_equal(len(self.network.nodes[self.network.nodes.pressure < 20]),5) 151 | 152 | #increase the size of all pipes 153 | self.network.pipes.diameter += 500 154 | assert_almost_equal(self.network.pipes.diameter.mean(),605,2) 155 | 156 | self.network.pipes.diameter -= 500 157 | self.network.solve() 158 | 159 | # resize pipes, and recalculate velocity 160 | self.network.pipes[self.network.pipes.velocity > 3].diameter += 100 161 | self.network.solve() 162 | 163 | assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),0) 164 | 165 | def test11_timeseries(self): 166 | # run network 167 | self.network.run() 168 | # check return types 169 | # should return Series 170 | assert(isinstance(self.network.pipes["1"].velocity, pd.Series)) 171 | # should return Dataframe 172 | assert(isinstance(self.network.pipes.velocity, pd.DataFrame)) 173 | 174 | # timeseries operations 175 | # pipe 1 max velocity 176 | assert_almost_equal(self.network.pipes["1"].velocity.mean(),1.66,2) 177 | # all day mean velocity 178 | assert_almost_equal(self.network.pipes.velocity.mean().mean(),1.14,2) 179 | 180 | # test revert to steady state calculation 181 | self.network.solve() 182 | assert(isinstance(self.network.pipes["1"].velocity, float)) 183 | assert(isinstance(self.network.pipes.velocity, pd.Series)) 184 | 185 | def test12_comments(self): 186 | # test reading comments 187 | assert_equal(self.network.links['1'].comment, "testcommentpipe") 188 | assert_equal(self.network.reservoirs['in'].comment, "testcommentreservoir") 189 | assert_equal(self.network.tanks['11'].comment, "testcommenttank") 190 | assert_equal(self.network.junctions['2'].comment, "testcommentjunction") 191 | 192 | # test writing comments 193 | self.network.links['1'].comment = 'testwrite' 194 | assert_equal(self.network.links['1'].comment, 'testwrite') 195 | 196 | 197 | -------------------------------------------------------------------------------- /tests/test_threaded.py: -------------------------------------------------------------------------------- 1 | from epynet import Network, epanet2 2 | from nose.tools import assert_equal, assert_almost_equal 3 | import pandas as pd 4 | 5 | class TestGeneratedNetwork(object): 6 | 7 | @classmethod 8 | def setup_class(self): 9 | threaded = Network('tests/testnetwork.inp') 10 | self.network = Network() 11 | 12 | @classmethod 13 | def teadown(self): 14 | self.network.ep.ENclose() 15 | 16 | def test00_build_network(self): 17 | network = self.network 18 | 19 | network.ep.ENsettimeparam(epanet2.EN_DURATION, 10*3600) 20 | # add nodes 21 | reservoir = network.add_reservoir('in',0,30) 22 | reservoir.elevation = 10 23 | 24 | pattern_values = [1,2,3,4,5,4,3,2,1,1] 25 | 26 | pattern = network.add_pattern('1',pattern_values) 27 | 28 | junctions = {'2':(10,30,0), 29 | '3':(20,30,0), 30 | '4':(30,30,1), 31 | '5':(30,20,1), 32 | '6':(30,10,1), 33 | '7':(40,10,1), 34 | '8':(40,20,1), 35 | '9':(40,30,1), 36 | '10':(50,30,1)} 37 | 38 | links = {'1':('in','2'), 39 | '3':('3','4'), 40 | '4':('4','5'), 41 | '5':('5','6'), 42 | '6':('6','7'), 43 | '7':('7','8'), 44 | '8':('8','9'), 45 | '10':('5','8'), 46 | '11':('4','9'), 47 | '12':('9','11')} 48 | 49 | for uid, coord in junctions.items(): 50 | node = network.add_junction(uid, coord[0], coord[1], elevation=0, basedemand=coord[2]) 51 | node.pattern = pattern 52 | 53 | tank = network.add_tank('11',40,40, diameter=50, maxlevel=20, minlevel=0, tanklevel=10) 54 | 55 | for uid, coord in links.items(): 56 | link = network.add_pipe(uid, coord[0], coord[1], diameter=100, length=100, roughness=0.1) 57 | 58 | valve = network.add_valve('9','prv','9','10', diameter=100, setting=5) 59 | 60 | pump = network.add_pump('2','2','3', speed=1) 61 | 62 | curve = network.add_curve('1',[(100,50)]) 63 | pump.curve = curve 64 | 65 | network.nodes['4'].elevation = 5 66 | network.links['11'].diameter = 150 67 | network.links['11'].minorloss = 0.1 68 | 69 | network.solve() 70 | 71 | def test01_network(self): 72 | # test0 node count 73 | assert_equal(len(self.network.nodes),11) 74 | # test0 link count 75 | assert_equal(len(self.network.links),12) 76 | # test0 reservoir count 77 | assert_equal(len(self.network.reservoirs),1) 78 | # test0 valve count 79 | assert_equal(len(self.network.valves),1) 80 | # test0 pump count 81 | assert_equal(len(self.network.pumps),1) 82 | # test0 tank count 83 | assert_equal(len(self.network.tanks),1) 84 | 85 | def test02_link(self): 86 | # test0 the properties of a single link 87 | link = self.network.links['11'] 88 | # pipe index and uid 89 | assert_equal(link.uid,'11') 90 | # from/to node 91 | assert_equal(link.from_node.uid,'4') 92 | assert_equal(link.to_node.uid,'9') 93 | 94 | def test03_pipe(self): 95 | # test0 the properties of a single pipe 96 | pipe = self.network.links['11'] 97 | # check type 98 | assert_equal(pipe.link_type,'pipe') 99 | 100 | assert_almost_equal(pipe.length,100,2) 101 | assert_almost_equal(pipe.diameter,150,2) 102 | assert_almost_equal(pipe.roughness,0.1,2) 103 | assert_almost_equal(pipe.minorloss,0.1,2) 104 | # flow 105 | assert_almost_equal(pipe.flow,87.92,2) 106 | # direction 107 | assert_almost_equal(pipe.velocity,1.38,2) 108 | # status 109 | assert_equal(pipe.status,1) 110 | # headloss 111 | assert_almost_equal(pipe.headloss,1.29,2) 112 | # upstream/downstream node 113 | assert_equal(pipe.upstream_node.uid,'4') 114 | assert_equal(pipe.downstream_node.uid,'9') 115 | 116 | def test04_pump(self): 117 | pump = self.network.pumps['2'] 118 | # check type 119 | assert_equal(pump.link_type,'pump') 120 | 121 | assert_equal(pump.speed,1.0) 122 | assert_almost_equal(pump.flow,109.67,2) 123 | # change speed 124 | pump.speed = 1.5 125 | assert_equal(pump.speed,1.5) 126 | # resolve network 127 | self.network.solve() 128 | assert_almost_equal(pump.flow,164.5,2) 129 | # revert speed 130 | pump.speed = 1.0 131 | self.network.solve() 132 | 133 | def test05_valve(self): 134 | valve = self.network.valves['9'] 135 | # check type 136 | assert_equal(valve.link_type,'valve') 137 | # check valve type 138 | assert_equal(valve.valve_type,'PRV') 139 | # valve settings 140 | assert_equal(valve.setting,5) 141 | assert_almost_equal(valve.downstream_node.pressure,5,2) 142 | # change setting 143 | valve.setting = 10 144 | assert_equal(valve.setting,10) 145 | self.network.solve() 146 | assert_almost_equal(valve.downstream_node.pressure,10,2) 147 | 148 | def test06_node(self): 149 | node = self.network.nodes['4'] 150 | # uid 151 | assert_equal(node.uid,'4') 152 | # coordinates 153 | #coordinates = node.coordinates 154 | # dont test these for created networks 155 | #assert_almost_equal(coordinates[0],2103.02,2) 156 | #assert_almost_equal(coordinates[1],5747.69,2) 157 | # links 158 | assert_equal(len(node.links),3) 159 | # up and downstream links 160 | assert_equal(len(node.downstream_links),2) 161 | assert_equal(len(node.upstream_links),1) 162 | # inflow 163 | assert_equal(round(node.inflow,2),109.67) 164 | # outflow 165 | assert_equal(round(node.outflow,2),round(node.inflow,2)-node.demand) 166 | # elevation 167 | assert_equal(node.elevation,5) 168 | # head 169 | assert_equal(round(node.head,2),25.13) 170 | 171 | def test07_junction(self): 172 | junction = self.network.junctions['4'] 173 | 174 | assert_equal(round(junction.basedemand,2),1) 175 | assert_equal(round(junction.demand,2),1) 176 | 177 | def test08_tank(self): 178 | tank = self.network.tanks['11'] 179 | assert_equal(tank.diameter,50) 180 | assert_equal(round(tank.initvolume,2),19634.95) 181 | assert_equal(tank.minvolume,0) 182 | assert_equal(tank.minlevel,0) 183 | assert_equal(tank.maxlevel,20) 184 | assert_equal(round(tank.volume,2),19634.95) 185 | assert_equal(round(tank.maxvolume),2*round(tank.volume)) 186 | 187 | def test09_time(self): 188 | junction = self.network.junctions['4'] 189 | self.network.solve(3600) 190 | assert_equal(round(junction.demand,2),2) 191 | self.network.solve(7200) 192 | assert_equal(round(junction.demand,2),3) 193 | 194 | def test10_collections(self): 195 | # collection attributes as pandas Series 196 | assert_almost_equal(self.network.pipes.flow.mean(),46.78,2) 197 | assert_almost_equal(self.network.pipes.diameter.max(),150,2) 198 | assert_almost_equal(self.network.pipes.velocity.min(),0.105,2) 199 | 200 | assert_equal(self.network.valves.setting.mean(),10) 201 | 202 | assert_almost_equal(self.network.junctions.demand.mean(),2.33,2) 203 | 204 | # filtering and slicing collections 205 | assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),3) 206 | assert_equal(len(self.network.nodes[self.network.nodes.pressure < 20]),5) 207 | 208 | #increase the size of all pipes 209 | self.network.pipes.diameter += 500 210 | assert_almost_equal(self.network.pipes.diameter.mean(),605,2) 211 | 212 | self.network.pipes.diameter -= 500 213 | self.network.solve() 214 | # resize pipes, and recalculate velocity 215 | self.network.pipes[self.network.pipes.velocity > 3].diameter += 100 216 | self.network.solve() 217 | 218 | assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),0) 219 | 220 | def test11_timeseries(self): 221 | # run network 222 | self.network.run() 223 | # check return types 224 | # should return Series 225 | assert(isinstance(self.network.pipes['1'].velocity, pd.Series)) 226 | # should return Dataframe 227 | assert(isinstance(self.network.pipes.velocity, pd.DataFrame)) 228 | # timeseries operations 229 | # pipe 1 max velocity 230 | assert_almost_equal(self.network.pipes['1'].velocity.mean(),1.66,2) 231 | # all day mean velocity 232 | assert_almost_equal(self.network.pipes.velocity.mean().mean(),1.14,2) 233 | # test revert to steady state calculation 234 | self.network.solve() 235 | print(type(self.network.pipes['1'].velocity)) 236 | assert(isinstance(self.network.pipes['1'].velocity, float)) 237 | assert(isinstance(self.network.pipes.velocity, pd.Series)) 238 | 239 | -------------------------------------------------------------------------------- /tests/test_creation.py: -------------------------------------------------------------------------------- 1 | from epynet import Network, epanet2 2 | from nose.tools import assert_equal, assert_almost_equal 3 | import pandas as pd 4 | 5 | class TestGeneratedNetwork(object): 6 | 7 | @classmethod 8 | def setup_class(self): 9 | self.network = Network() 10 | 11 | @classmethod 12 | def teadown(self): 13 | self.network.ep.ENclose() 14 | 15 | def test00_build_network(self): 16 | network = self.network 17 | 18 | network.ep.ENsettimeparam(epanet2.EN_DURATION, 10*3600) 19 | # add nodes 20 | reservoir = network.add_reservoir('in',0,30) 21 | reservoir.elevation = 10 22 | 23 | pattern_values = [1,2,3,4,5,4,3,2,1,1] 24 | 25 | pattern = network.add_pattern('1',pattern_values) 26 | 27 | junctions = {'2':(10,30,0), 28 | '3':(20,30,0), 29 | '4':(30,30,1), 30 | '5':(30,20,1), 31 | '6':(30,10,1), 32 | '7':(40,10,1), 33 | '8':(40,20,1), 34 | '9':(40,30,1), 35 | '10':(50,30,1)} 36 | 37 | links = {'1':('in','2'), 38 | '3':('3','4'), 39 | '4':('4','5'), 40 | '5':('5','6'), 41 | '6':('6','7'), 42 | '7':('7','8'), 43 | '8':('8','9'), 44 | '10':('5','8'), 45 | '11':('4','9'), 46 | '12':('9','11')} 47 | 48 | for uid, coord in junctions.items(): 49 | node = network.add_junction(uid, coord[0], coord[1], elevation=0, basedemand=coord[2]) 50 | node.pattern = pattern 51 | 52 | tank = network.add_tank('11',40,40, diameter=50, maxlevel=20, minlevel=0, tanklevel=10) 53 | 54 | for uid, coord in links.items(): 55 | link = network.add_pipe(uid, coord[0], coord[1], diameter=100, length=100, roughness=0.1) 56 | 57 | valve = network.add_valve('9','prv','9','10', diameter=100, setting=5) 58 | 59 | pump = network.add_pump('2','2','3', speed=1) 60 | 61 | curve = network.add_curve('1',[(100,50)]) 62 | pump.curve = curve 63 | 64 | network.nodes['4'].elevation = 5 65 | network.links['11'].diameter = 150 66 | network.links['11'].minorloss = 0.1 67 | 68 | network.solve() 69 | 70 | def test01_network(self): 71 | # test0 node count 72 | assert_equal(len(self.network.nodes),11) 73 | # test0 link count 74 | assert_equal(len(self.network.links),12) 75 | # test0 reservoir count 76 | assert_equal(len(self.network.reservoirs),1) 77 | # test0 valve count 78 | assert_equal(len(self.network.valves),1) 79 | # test0 pump count 80 | assert_equal(len(self.network.pumps),1) 81 | # test0 tank count 82 | assert_equal(len(self.network.tanks),1) 83 | 84 | def test02_link(self): 85 | # test0 the properties of a single link 86 | link = self.network.links['11'] 87 | # pipe index and uid 88 | assert_equal(link.uid,'11') 89 | # from/to node 90 | assert_equal(link.from_node.uid,'4') 91 | assert_equal(link.to_node.uid,'9') 92 | 93 | def test03_pipe(self): 94 | # test0 the properties of a single pipe 95 | pipe = self.network.links['11'] 96 | # check type 97 | assert_equal(pipe.link_type,'pipe') 98 | 99 | assert_almost_equal(pipe.length,100,2) 100 | assert_almost_equal(pipe.diameter,150,2) 101 | assert_almost_equal(pipe.roughness,0.1,2) 102 | assert_almost_equal(pipe.minorloss,0.1,2) 103 | # flow 104 | assert_almost_equal(pipe.flow,87.92,2) 105 | # direction 106 | assert_almost_equal(pipe.velocity,1.38,2) 107 | # status 108 | assert_equal(pipe.status,1) 109 | # headloss 110 | assert_almost_equal(pipe.headloss,1.29,2) 111 | # upstream/downstream node 112 | assert_equal(pipe.upstream_node.uid,'4') 113 | assert_equal(pipe.downstream_node.uid,'9') 114 | 115 | def test04_pump(self): 116 | pump = self.network.pumps['2'] 117 | # check type 118 | assert_equal(pump.link_type,'pump') 119 | 120 | assert_equal(pump.speed,1.0) 121 | assert_almost_equal(pump.flow,109.67,2) 122 | # change speed 123 | pump.speed = 1.5 124 | assert_equal(pump.speed,1.5) 125 | # resolve network 126 | self.network.solve() 127 | assert_almost_equal(pump.flow,164.5,2) 128 | # revert speed 129 | pump.speed = 1.0 130 | self.network.solve() 131 | 132 | def test05_valve(self): 133 | valve = self.network.valves['9'] 134 | # check type 135 | assert_equal(valve.link_type,'valve') 136 | # check valve type 137 | assert_equal(valve.valve_type,'PRV') 138 | # valve settings 139 | assert_equal(valve.setting,5) 140 | assert_almost_equal(valve.downstream_node.pressure,5,2) 141 | # change setting 142 | valve.setting = 10 143 | assert_equal(valve.setting,10) 144 | self.network.solve() 145 | assert_almost_equal(valve.downstream_node.pressure,10,2) 146 | 147 | def test06_node(self): 148 | node = self.network.nodes['4'] 149 | # uid 150 | assert_equal(node.uid,'4') 151 | # coordinates 152 | #coordinates = node.coordinates 153 | # dont test these for created networks 154 | #assert_almost_equal(coordinates[0],2103.02,2) 155 | #assert_almost_equal(coordinates[1],5747.69,2) 156 | # links 157 | assert_equal(len(node.links),3) 158 | # up and downstream links 159 | assert_equal(len(node.downstream_links),2) 160 | assert_equal(len(node.upstream_links),1) 161 | # inflow 162 | assert_equal(round(node.inflow,2),109.67) 163 | # outflow 164 | assert_equal(round(node.outflow,2),round(node.inflow,2)-node.demand) 165 | # elevation 166 | assert_equal(node.elevation,5) 167 | # head 168 | assert_equal(round(node.head,2),25.13) 169 | 170 | def test07_junction(self): 171 | junction = self.network.junctions['4'] 172 | 173 | assert_equal(round(junction.basedemand,2),1) 174 | assert_equal(round(junction.demand,2),1) 175 | 176 | def test08_tank(self): 177 | tank = self.network.tanks['11'] 178 | assert_equal(tank.diameter,50) 179 | assert_equal(round(tank.initvolume,2),19634.95) 180 | assert_equal(tank.minvolume,0) 181 | assert_equal(tank.minlevel,0) 182 | assert_equal(tank.maxlevel,20) 183 | assert_equal(round(tank.volume,2),19634.95) 184 | assert_equal(round(tank.maxvolume),2*round(tank.volume)) 185 | 186 | def test09_time(self): 187 | junction = self.network.junctions['4'] 188 | self.network.solve(3600) 189 | assert_equal(round(junction.demand,2),2) 190 | self.network.solve(7200) 191 | assert_equal(round(junction.demand,2),3) 192 | 193 | def test10_collections(self): 194 | # collection attributes as pandas Series 195 | assert_almost_equal(self.network.pipes.flow.mean(),46.78,2) 196 | assert_almost_equal(self.network.pipes.diameter.max(),150,2) 197 | assert_almost_equal(self.network.pipes.velocity.min(),0.105,2) 198 | 199 | assert_equal(self.network.valves.setting.mean(),10) 200 | 201 | assert_almost_equal(self.network.junctions.demand.mean(),2.33,2) 202 | 203 | # filtering and slicing collections 204 | assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),3) 205 | assert_equal(len(self.network.nodes[self.network.nodes.pressure < 20]),5) 206 | 207 | #increase the size of all pipes 208 | self.network.pipes.diameter += 500 209 | assert_almost_equal(self.network.pipes.diameter.mean(),605,2) 210 | 211 | self.network.pipes.diameter -= 500 212 | self.network.solve() 213 | # resize pipes, and recalculate velocity 214 | self.network.pipes[self.network.pipes.velocity > 3].diameter += 100 215 | self.network.solve() 216 | 217 | assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),0) 218 | 219 | def test11_timeseries(self): 220 | # run network 221 | self.network.run() 222 | # check return types 223 | # should return Series 224 | assert(isinstance(self.network.pipes['1'].velocity, pd.Series)) 225 | # should return Dataframe 226 | assert(isinstance(self.network.pipes.velocity, pd.DataFrame)) 227 | # timeseries operations 228 | # pipe 1 max velocity 229 | assert_almost_equal(self.network.pipes['1'].velocity.mean(),1.66,2) 230 | # all day mean velocity 231 | assert_almost_equal(self.network.pipes.velocity.mean().mean(),1.14,2) 232 | # test revert to steady state calculation 233 | self.network.solve() 234 | print(type(self.network.pipes['1'].velocity)) 235 | assert(isinstance(self.network.pipes['1'].velocity, float)) 236 | assert(isinstance(self.network.pipes.velocity, pd.Series)) 237 | 238 | def test12_deletion(self): 239 | # Delete node 240 | self.network.delete_node('10') 241 | assert_equal(len(self.network.nodes), 10) 242 | assert_equal(len(self.network.links), 11) 243 | assert_equal(len(self.network.valves), 0) 244 | 245 | self.network.solve() 246 | assert_almost_equal(self.network.junctions['9'].pressure, 11.21, 2) 247 | 248 | # Delete Tank 249 | self.network.delete_node('11') 250 | 251 | assert_equal(len(self.network.tanks), 0) 252 | assert_equal(len(self.network.links), 10) 253 | 254 | self.network.solve() 255 | assert_almost_equal(self.network.junctions['9'].pressure, 76.60, 2) 256 | 257 | # Delete link 258 | self.network.delete_link('7') 259 | assert_equal(len(self.network.links), 9) 260 | 261 | self.network.solve() 262 | assert_almost_equal(self.network.pipes['6'].flow, 1) 263 | 264 | # delete pump 265 | self.network.delete_link('2') 266 | assert_equal(len(self.network.pumps), 0) 267 | 268 | # add link instead 269 | self.network.add_pipe('R2', '2', '3', diameter=200, length=100, roughness=0.1) 270 | self.network.solve() 271 | 272 | assert_almost_equal(self.network.junctions['9'].pressure, 9.99, 2) 273 | -------------------------------------------------------------------------------- /tests/.ipynb_checkpoints/test_creation-checkpoint.py: -------------------------------------------------------------------------------- 1 | from epynet import Network, epanet2 2 | from nose.tools import assert_equal, assert_almost_equal 3 | import pandas as pd 4 | 5 | class TestGeneratedNetwork(object): 6 | 7 | @classmethod 8 | def setup_class(self): 9 | self.network = Network() 10 | 11 | @classmethod 12 | def teadown(self): 13 | self.network.ep.ENclose() 14 | 15 | def test00_build_network(self): 16 | network = self.network 17 | 18 | network.ep.ENsettimeparam(epanet2.EN_DURATION, 10*3600) 19 | # add nodes 20 | reservoir = network.add_reservoir('in',0,30) 21 | reservoir.elevation = 10 22 | 23 | pattern_values = [1,2,3,4,5,4,3,2,1,1] 24 | 25 | pattern = network.add_pattern('1',pattern_values) 26 | 27 | junctions = {'2':(10,30,0), 28 | '3':(20,30,0), 29 | '4':(30,30,1), 30 | '5':(30,20,1), 31 | '6':(30,10,1), 32 | '7':(40,10,1), 33 | '8':(40,20,1), 34 | '9':(40,30,1), 35 | '10':(50,30,1)} 36 | 37 | links = {'1':('in','2'), 38 | '3':('3','4'), 39 | '4':('4','5'), 40 | '5':('5','6'), 41 | '6':('6','7'), 42 | '7':('7','8'), 43 | '8':('8','9'), 44 | '10':('5','8'), 45 | '11':('4','9'), 46 | '12':('9','11')} 47 | 48 | for uid, coord in junctions.items(): 49 | node = network.add_junction(uid, coord[0], coord[1], elevation=0, basedemand=coord[2]) 50 | node.pattern = pattern 51 | 52 | tank = network.add_tank('11',40,40, diameter=50, maxlevel=20, minlevel=0, tanklevel=10) 53 | 54 | for uid, coord in links.items(): 55 | link = network.add_pipe(uid, coord[0], coord[1], diameter=100, length=100, roughness=0.1) 56 | 57 | valve = network.add_valve('9','prv','9','10', diameter=100, setting=5) 58 | 59 | pump = network.add_pump('2','2','3', speed=1) 60 | 61 | curve = network.add_curve('1',[(100,50)]) 62 | pump.curve = curve 63 | 64 | network.nodes['4'].elevation = 5 65 | network.links['11'].diameter = 150 66 | network.links['11'].minorloss = 0.1 67 | 68 | network.solve() 69 | 70 | def test01_network(self): 71 | # test0 node count 72 | assert_equal(len(self.network.nodes),11) 73 | # test0 link count 74 | assert_equal(len(self.network.links),12) 75 | # test0 reservoir count 76 | assert_equal(len(self.network.reservoirs),1) 77 | # test0 valve count 78 | assert_equal(len(self.network.valves),1) 79 | # test0 pump count 80 | assert_equal(len(self.network.pumps),1) 81 | # test0 tank count 82 | assert_equal(len(self.network.tanks),1) 83 | 84 | def test02_link(self): 85 | # test0 the properties of a single link 86 | link = self.network.links['11'] 87 | # pipe index and uid 88 | assert_equal(link.uid,'11') 89 | # from/to node 90 | assert_equal(link.from_node.uid,'4') 91 | assert_equal(link.to_node.uid,'9') 92 | 93 | def test03_pipe(self): 94 | # test0 the properties of a single pipe 95 | pipe = self.network.links['11'] 96 | # check type 97 | assert_equal(pipe.link_type,'pipe') 98 | 99 | assert_almost_equal(pipe.length,100,2) 100 | assert_almost_equal(pipe.diameter,150,2) 101 | assert_almost_equal(pipe.roughness,0.1,2) 102 | assert_almost_equal(pipe.minorloss,0.1,2) 103 | # flow 104 | assert_almost_equal(pipe.flow,87.92,2) 105 | # direction 106 | assert_almost_equal(pipe.velocity,1.38,2) 107 | # status 108 | assert_equal(pipe.status,1) 109 | # headloss 110 | assert_almost_equal(pipe.headloss,1.29,2) 111 | # upstream/downstream node 112 | assert_equal(pipe.upstream_node.uid,'4') 113 | assert_equal(pipe.downstream_node.uid,'9') 114 | 115 | def test04_pump(self): 116 | pump = self.network.pumps['2'] 117 | # check type 118 | assert_equal(pump.link_type,'pump') 119 | 120 | assert_equal(pump.speed,1.0) 121 | assert_almost_equal(pump.flow,109.67,2) 122 | # change speed 123 | pump.speed = 1.5 124 | assert_equal(pump.speed,1.5) 125 | # resolve network 126 | self.network.solve() 127 | assert_almost_equal(pump.flow,164.5,2) 128 | # revert speed 129 | pump.speed = 1.0 130 | self.network.solve() 131 | 132 | def test05_valve(self): 133 | valve = self.network.valves['9'] 134 | # check type 135 | assert_equal(valve.link_type,'valve') 136 | # check valve type 137 | assert_equal(valve.valve_type,'PRV') 138 | # valve settings 139 | assert_equal(valve.setting,5) 140 | assert_almost_equal(valve.downstream_node.pressure,5,2) 141 | # change setting 142 | valve.setting = 10 143 | assert_equal(valve.setting,10) 144 | self.network.solve() 145 | assert_almost_equal(valve.downstream_node.pressure,10,2) 146 | 147 | def test06_node(self): 148 | node = self.network.nodes['4'] 149 | # uid 150 | assert_equal(node.uid,'4') 151 | # coordinates 152 | #coordinates = node.coordinates 153 | # dont test these for created networks 154 | #assert_almost_equal(coordinates[0],2103.02,2) 155 | #assert_almost_equal(coordinates[1],5747.69,2) 156 | # links 157 | assert_equal(len(node.links),3) 158 | # up and downstream links 159 | assert_equal(len(node.downstream_links),2) 160 | assert_equal(len(node.upstream_links),1) 161 | # inflow 162 | assert_equal(round(node.inflow,2),109.67) 163 | # outflow 164 | assert_equal(round(node.outflow,2),round(node.inflow,2)-node.demand) 165 | # elevation 166 | assert_equal(node.elevation,5) 167 | # head 168 | assert_equal(round(node.head,2),25.13) 169 | 170 | def test07_junction(self): 171 | junction = self.network.junctions['4'] 172 | 173 | assert_equal(round(junction.basedemand,2),1) 174 | assert_equal(round(junction.demand,2),1) 175 | 176 | def test08_tank(self): 177 | tank = self.network.tanks['11'] 178 | assert_equal(tank.diameter,50) 179 | assert_equal(round(tank.initvolume,2),19634.95) 180 | assert_equal(tank.minvolume,0) 181 | assert_equal(tank.minlevel,0) 182 | assert_equal(tank.maxlevel,20) 183 | assert_equal(round(tank.volume,2),19634.95) 184 | assert_equal(round(tank.maxvolume),2*round(tank.volume)) 185 | 186 | def test09_time(self): 187 | junction = self.network.junctions['4'] 188 | self.network.solve(3600) 189 | assert_equal(round(junction.demand,2),2) 190 | self.network.solve(7200) 191 | assert_equal(round(junction.demand,2),3) 192 | 193 | def test10_collections(self): 194 | # collection attributes as pandas Series 195 | assert_almost_equal(self.network.pipes.flow.mean(),46.78,2) 196 | assert_almost_equal(self.network.pipes.diameter.max(),150,2) 197 | assert_almost_equal(self.network.pipes.velocity.min(),0.105,2) 198 | 199 | assert_equal(self.network.valves.setting.mean(),10) 200 | 201 | assert_almost_equal(self.network.junctions.demand.mean(),2.33,2) 202 | 203 | # filtering and slicing collections 204 | assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),3) 205 | assert_equal(len(self.network.nodes[self.network.nodes.pressure < 20]),5) 206 | 207 | #increase the size of all pipes 208 | self.network.pipes.diameter += 500 209 | assert_almost_equal(self.network.pipes.diameter.mean(),605,2) 210 | 211 | self.network.pipes.diameter -= 500 212 | self.network.solve() 213 | # resize pipes, and recalculate velocity 214 | self.network.pipes[self.network.pipes.velocity > 3].diameter += 100 215 | self.network.solve() 216 | 217 | assert_equal(len(self.network.pipes[self.network.pipes.velocity > 3]),0) 218 | 219 | def test11_timeseries(self): 220 | # run network 221 | self.network.run() 222 | # check return types 223 | # should return Series 224 | assert(isinstance(self.network.pipes['1'].velocity, pd.Series)) 225 | # should return Dataframe 226 | assert(isinstance(self.network.pipes.velocity, pd.DataFrame)) 227 | # timeseries operations 228 | # pipe 1 max velocity 229 | assert_almost_equal(self.network.pipes['1'].velocity.mean(),1.66,2) 230 | # all day mean velocity 231 | assert_almost_equal(self.network.pipes.velocity.mean().mean(),1.14,2) 232 | # test revert to steady state calculation 233 | self.network.solve() 234 | print(type(self.network.pipes['1'].velocity)) 235 | assert(isinstance(self.network.pipes['1'].velocity, float)) 236 | assert(isinstance(self.network.pipes.velocity, pd.Series)) 237 | 238 | def test12_deletion(self): 239 | # Delete node 240 | self.network.delete_node('10') 241 | assert_equal(len(self.network.nodes), 10) 242 | assert_equal(len(self.network.links), 11) 243 | assert_equal(len(self.network.valves), 0) 244 | 245 | self.network.solve() 246 | assert_almost_equal(self.network.junctions['9'].pressure, 11.21, 2) 247 | 248 | # Delete Tank 249 | self.network.delete_node('11') 250 | 251 | assert_equal(len(self.network.tanks), 0) 252 | assert_equal(len(self.network.links), 10) 253 | 254 | self.network.solve() 255 | assert_almost_equal(self.network.junctions['9'].pressure, 76.60, 2) 256 | 257 | # Delete link 258 | self.network.delete_link('7') 259 | assert_equal(len(self.network.links), 9) 260 | 261 | self.network.solve() 262 | assert_almost_equal(self.network.pipes['6'].flow, 1) 263 | 264 | # delete pump 265 | self.network.delete_link('2') 266 | assert_equal(len(self.network.pumps), 0) 267 | 268 | # add link instead 269 | self.network.add_pipe('R2', '2', '3', diameter=200, length=100, roughness=0.1) 270 | self.network.solve() 271 | 272 | assert_almost_equal(self.network.junctions['9'].pressure, 9.99, 2) 273 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /epynet/network.py: -------------------------------------------------------------------------------- 1 | """ EPYNET Classes """ 2 | import atexit 3 | 4 | from . import epanet2 5 | from .objectcollection import ObjectCollection 6 | from .node import Junction, Tank, Reservoir 7 | from .link import Pipe, Valve, Pump 8 | from .curve import Curve 9 | from .pattern import Pattern 10 | 11 | 12 | class Network(object): 13 | """ self.epANET Network Simulation Class """ 14 | def __init__(self, inputfile=None, units=epanet2.EN_CMH, headloss=epanet2.EN_DW, charset='UTF8'): 15 | 16 | # create multithreaded EPANET instance 17 | self.ep = epanet2.EPANET2(charset=charset) 18 | 19 | if inputfile: 20 | self.inputfile = inputfile 21 | self.rptfile = self.inputfile[:-3]+"rpt" 22 | self.binfile = self.inputfile[:-3]+"bin" 23 | self.ep.ENopen(self.inputfile, self.rptfile, self.binfile) 24 | else: 25 | self.inputfile = False 26 | 27 | self.rptfile = "" 28 | self.binfile = "" 29 | 30 | self.ep.ENinit(self.rptfile.encode(), self.binfile.encode(), units, headloss) 31 | 32 | 33 | 34 | 35 | self.vertices = {} 36 | # prepare network data 37 | self.nodes = ObjectCollection() 38 | self.junctions = ObjectCollection() 39 | self.reservoirs = ObjectCollection() 40 | self.tanks = ObjectCollection() 41 | 42 | self.links = ObjectCollection() 43 | self.pipes = ObjectCollection() 44 | self.valves = ObjectCollection() 45 | self.pumps = ObjectCollection() 46 | 47 | self.curves = ObjectCollection() 48 | self.patterns = ObjectCollection() 49 | 50 | self.solved = False 51 | self.solved_for_simtime = None 52 | 53 | self.load_network() 54 | 55 | def load_network(self): 56 | """ Load network data """ 57 | # load nodes 58 | for index in range(1, self.ep.ENgetcount(epanet2.EN_NODECOUNT)+1): 59 | # get node type 60 | node_type = self.ep.ENgetnodetype(index) 61 | uid = self.ep.ENgetnodeid(index) 62 | 63 | if node_type == 0: 64 | node = Junction(uid, self) 65 | self.junctions[node.uid] = node 66 | elif node_type == 1: 67 | node = Reservoir(uid, self) 68 | self.reservoirs[node.uid] = node 69 | self.nodes[node.uid] = node 70 | else: 71 | node = Tank(uid, self) 72 | self.tanks[node.uid] = node 73 | 74 | self.nodes[node.uid] = node 75 | 76 | 77 | # load links 78 | for index in range(1, self.ep.ENgetcount(epanet2.EN_LINKCOUNT)+1): 79 | link_type = self.ep.ENgetlinktype(index) 80 | uid = self.ep.ENgetlinkid(index) 81 | # pipes 82 | if link_type <= 1: 83 | link = Pipe(uid, self) 84 | self.pipes[link.uid] = link 85 | elif link_type == 2: 86 | link = Pump(uid, self) 87 | self.pumps[link.uid] = link 88 | elif link_type >= 3: 89 | link = Valve(uid, self) 90 | self.valves[link.uid] = link 91 | 92 | self.links[link.uid] = link 93 | link_nodes = self.ep.ENgetlinknodes(index) 94 | link.from_node = self.nodes[self.ep.ENgetnodeid(link_nodes[0])] 95 | link.from_node.links[link.uid] = link 96 | link.to_node = self.nodes[self.ep.ENgetnodeid(link_nodes[1])] 97 | link.to_node.links[link.uid] = link 98 | 99 | 100 | # load curves 101 | 102 | for index in range(1, self.ep.ENgetcount(epanet2.EN_CURVECOUNT)+1): 103 | uid = self.ep.ENgetcurveid(index) 104 | self.curves[uid] = Curve(uid, self) 105 | 106 | # load patterns 107 | for index in range(1, self.ep.ENgetcount(epanet2.EN_PATCOUNT)+1): 108 | uid = self.ep.ENgetpatternid(index) 109 | self.patterns[uid] = Pattern(uid, self) 110 | 111 | def reset(self): 112 | 113 | self.solved = False 114 | self.solved_for_simtime = None 115 | 116 | for link in self.links: 117 | link.reset() 118 | for node in self.nodes: 119 | node.reset() 120 | 121 | def delete_node(self, uid): 122 | index = self.ep.ENgetnodeindex(uid) 123 | node_type = self.ep.ENgetnodetype(index) 124 | 125 | for link in list(self.nodes[uid].links): 126 | self.delete_link(link.uid); 127 | 128 | del self.nodes[uid] 129 | 130 | if node_type == epanet2.EN_JUNCTION: 131 | del self.junctions[uid] 132 | elif node_type == epanet2.EN_RESERVOIR: 133 | del self.reservoirs[uid] 134 | elif node_type == epanet2.EN_TANK: 135 | del self.tanks[uid] 136 | 137 | self.ep.ENdeletenode(index) 138 | 139 | self.invalidate_nodes() 140 | self.invalidate_links() 141 | 142 | def delete_link(self, uid): 143 | 144 | index = self.ep.ENgetlinkindex(uid) 145 | link_type = self.ep.ENgetlinktype(index) 146 | 147 | link = self.links[uid] 148 | del link.from_node.links[uid] 149 | del link.to_node.links[uid] 150 | 151 | del self.links[uid] 152 | 153 | if link_type == epanet2.EN_PIPE or link_type == epanet2.EN_CVPIPE: 154 | del self.pipes[uid] 155 | elif link_type == epanet2.EN_PUMP: 156 | del self.pumps[uid] 157 | else: 158 | del self.valves[uid] 159 | 160 | self.ep.ENdeletelink(index) 161 | 162 | self.invalidate_nodes() 163 | self.invalidate_links() 164 | 165 | 166 | def add_reservoir(self, uid, x, y, elevation=0): 167 | 168 | self.ep.ENaddnode(uid, epanet2.EN_RESERVOIR) 169 | 170 | index = self.ep.ENgetnodeindex(uid) 171 | 172 | self.ep.ENsetcoord(index, x, y) 173 | 174 | node = Reservoir(uid, self) 175 | node.elevation = elevation 176 | 177 | self.reservoirs[uid] = node 178 | self.nodes[uid] = node 179 | 180 | self.invalidate_nodes() 181 | 182 | return node 183 | 184 | def add_junction(self, uid, x, y, basedemand=0, elevation=0): 185 | self.ep.ENaddnode(uid, epanet2.EN_JUNCTION) 186 | index = self.ep.ENgetnodeindex(uid) 187 | self.ep.ENsetcoord(index, x, y) 188 | node = Junction(uid, self) 189 | self.junctions[uid] = node 190 | self.nodes[uid] = node 191 | 192 | # configure node 193 | node.basedemand = basedemand 194 | node.elevation = elevation 195 | 196 | self.invalidate_nodes() 197 | 198 | return node 199 | 200 | def add_tank(self, uid, x, y, diameter=0, maxlevel=0, minlevel=0, tanklevel=0): 201 | self.ep.ENaddnode(uid, epanet2.EN_TANK) 202 | index = self.ep.ENgetnodeindex(uid) 203 | self.ep.ENsetcoord(index, x, y) 204 | node = Tank(uid, self) 205 | self.tanks[uid] = node 206 | self.nodes[uid] = node 207 | # config tank 208 | node.diameter = diameter 209 | node.maxlevel = maxlevel 210 | node.minlevel = minlevel 211 | node.tanklevel = tanklevel 212 | 213 | self.invalidate_nodes() 214 | 215 | return node 216 | 217 | def add_pipe(self, uid, from_node, to_node, diameter=100, length=10, roughness=0.1, check_valve=False): 218 | 219 | from_node = from_node if isinstance(from_node, str) else from_node.uid 220 | to_node = to_node if isinstance(to_node, str) else to_node.uid 221 | 222 | if check_valve: 223 | self.ep.ENaddlink(uid, epanet2.EN_CVPIPE, from_node, to_node) 224 | else: 225 | self.ep.ENaddlink(uid, epanet2.EN_PIPE, from_node, to_node) 226 | 227 | link = Pipe(uid, self) 228 | 229 | link.diameter = diameter 230 | link.length = length 231 | link.roughness = roughness 232 | 233 | link.from_node = self.nodes[from_node] 234 | link.to_node = self.nodes[to_node] 235 | link.to_node.links[link.uid] = link 236 | link.from_node.links[link.uid] = link 237 | self.pipes[uid] = link 238 | self.links[uid] = link 239 | 240 | # set link properties 241 | link.diameter = diameter 242 | link.length = length 243 | 244 | self.invalidate_links() 245 | 246 | return link 247 | 248 | def add_pump(self, uid, from_node, to_node, speed=0): 249 | 250 | from_node = from_node if isinstance(from_node, str) else from_node.uid 251 | to_node = to_node if isinstance(to_node, str) else to_node.uid 252 | 253 | self.ep.ENaddlink(uid, epanet2.EN_PUMP, from_node, to_node) 254 | link = Pump(uid, self) 255 | link.speed = speed 256 | link.from_node = self.nodes[from_node] 257 | link.speed = speed 258 | link.to_node = self.nodes[to_node] 259 | link.to_node.links[link.uid] = link 260 | link.from_node.links[link.uid] = link 261 | self.pumps[uid] = link 262 | self.links[uid] = link 263 | 264 | self.invalidate_links() 265 | 266 | return link 267 | 268 | def add_curve(self, uid, values): 269 | self.ep.ENaddcurve(uid) 270 | 271 | curve = Curve(uid, self) 272 | curve.values = values 273 | self.curves[uid] = curve 274 | 275 | return curve 276 | 277 | def add_pattern(self, uid, values): 278 | self.ep.ENaddpattern(uid) 279 | pattern = Pattern(uid, self) 280 | pattern.values = values 281 | self.patterns[uid] = pattern 282 | 283 | return pattern 284 | 285 | def add_valve(self, uid, valve_type, from_node, to_node, diameter=100, setting=0): 286 | 287 | from_node = from_node if isinstance(from_node, str) else from_node.uid 288 | to_node = to_node if isinstance(to_node, str) else to_node.uid 289 | 290 | if valve_type.lower() == "gpv": 291 | valve_type_code = epanet2.EN_GPV 292 | elif valve_type.lower() == "fcv": 293 | valve_type_code = epanet2.EN_FCV 294 | elif valve_type.lower() == "pbv": 295 | valve_type_code = epanet2.EN_PBV 296 | elif valve_type.lower() == "tcv": 297 | valve_type_code = epanet2.EN_TCV 298 | elif valve_type.lower() == "prv": 299 | valve_type_code = epanet2.EN_PRV 300 | elif valve_type.lower() == "psv": 301 | valve_type_code = epanet2.EN_PSV 302 | else: 303 | raise ValueError("Unknown Valve Type") 304 | 305 | self.ep.ENaddlink(uid, valve_type_code, from_node, to_node) 306 | link = Valve(uid, self) 307 | link.diameter = diameter 308 | link.setting = setting 309 | link.from_node = self.nodes[from_node] 310 | link.to_node = self.nodes[to_node] 311 | link.to_node.links[link.uid] = link 312 | link.from_node.links[link.uid] = link 313 | self.valves[uid] = link 314 | self.links[uid] = link 315 | 316 | self.invalidate_links() 317 | 318 | return link 319 | 320 | def invalidate_links(self): 321 | # set network as unsolved 322 | self.solved = False 323 | # reset link index caches 324 | for link in self.links: 325 | link._index = None 326 | 327 | def invalidate_nodes(self): 328 | # set network as unsolved 329 | self.solved = False 330 | # reset node index caches 331 | for node in self.nodes: 332 | node._index = None 333 | 334 | def solve(self, simtime=0): 335 | """ Solve Hydraulic Network for Single Timestep""" 336 | if self.solved and self.solved_for_simtime == simtime: 337 | return 338 | 339 | self.reset() 340 | self.ep.ENsettimeparam(4, simtime) 341 | self.ep.ENopenH() 342 | self.ep.ENinitH(0) 343 | self.ep.ENrunH() 344 | self.ep.ENcloseH() 345 | self.solved = True 346 | self.solved_for_simtime = simtime 347 | 348 | def run(self): 349 | self.reset() 350 | self.time = [] 351 | # open network 352 | self.ep.ENopenH() 353 | self.ep.ENinitH(0) 354 | 355 | self.ep.ENopenQ() 356 | self.ep.ENinitQ() 357 | 358 | simtime = 0 359 | timestep = 1 360 | qstep = 1 361 | 362 | self.solved = True 363 | 364 | while timestep > 0: 365 | self.ep.ENrunH() 366 | self.ep.ENrunQ() 367 | timestep = self.ep.ENnextH() 368 | self.ep.ENnextQ() 369 | self.time.append(simtime) 370 | self.load_attributes(simtime) 371 | simtime += timestep 372 | 373 | self.ep.ENcloseH() 374 | self.ep.ENcloseQ() 375 | 376 | def load_attributes(self, simtime): 377 | for node in self.nodes: 378 | for property_name in node.properties.keys(): 379 | if property_name not in node.results.keys(): 380 | node.results[property_name] = [] 381 | # clear cached values 382 | node._values = {} 383 | node.results[property_name].append(node.get_property(node.properties[property_name])) 384 | node.times.append(simtime) 385 | 386 | for link in self.links: 387 | for property_name in link.properties.keys(): 388 | if property_name not in link.results.keys(): 389 | link.results[property_name] = [] 390 | # clear cached values 391 | link._values = {} 392 | link.results[property_name].append(link.get_property(link.properties[property_name])) 393 | link.times.append(simtime) 394 | 395 | def save_inputfile(self, name): 396 | self.ep.ENsaveinpfile(name) 397 | 398 | def get_vertices(self, link_uid): 399 | if self.vertices == {}: 400 | self.parse_vertices() 401 | return self.vertices.get(link_uid, []) 402 | 403 | def parse_vertices(self): 404 | vertices = False 405 | if not self.inputfile or len(self.vertices) > 0: 406 | return 407 | 408 | with open(self.inputfile, 'rb') as handle: 409 | for line in handle.readlines(): 410 | if b'[VERTICES]' in line: 411 | vertices = True 412 | continue 413 | elif b'[' in line: 414 | vertices = False 415 | 416 | if b";" in line: 417 | continue 418 | 419 | if vertices: 420 | components = [c.strip() for c in line.decode(self.ep.charset).split()] 421 | if len(components) < 3: 422 | continue 423 | if components[0] not in self.vertices: 424 | self.vertices[components[0]] = [] 425 | self.vertices[components[0]].append((float(components[1]), float(components[2]))) 426 | 427 | 428 | 429 | def close(self): 430 | print('closing') 431 | self.ep.ENdeleteproject() 432 | -------------------------------------------------------------------------------- /epynet/epanet2.py: -------------------------------------------------------------------------------- 1 | """Python EpanetToolkit interface 2 | 3 | added function ENsimtime""" 4 | 5 | import ctypes 6 | import platform 7 | import datetime 8 | import os 9 | import warnings 10 | 11 | 12 | class EPANET2(object): 13 | 14 | def __init__(self, charset='UTF8'): 15 | _plat= platform.system() 16 | if _plat=='Darwin': 17 | dll_path = os.path.join(os.path.dirname(__file__), "lib/libepanet.dylib") 18 | self._lib = ctypes.cdll.LoadLibrary(dll_path) 19 | ctypes.c_float = ctypes.c_double 20 | elif _plat=='Linux': 21 | dll_path = os.path.join(os.path.dirname(__file__), "lib/libepanet.so") 22 | self._lib = ctypes.CDLL(dll_path) 23 | ctypes.c_float = ctypes.c_double 24 | elif _plat=='Windows': 25 | ctypes.c_float = ctypes.c_double 26 | try: 27 | # if epanet2.dll compiled with __cdecl (as in OpenWaterAnalytics) 28 | dll_path = os.path.join(os.path.dirname(__file__), "lib/epanet2.dll") 29 | self._lib = ctypes.CDLL(dll_path) 30 | except ValueError: 31 | # if epanet2.dll compiled with __stdcall (as in EPA original DLL) 32 | try: 33 | self._lib = ctypes.windll.epanet2 34 | self._lib.EN_getversion(self.ph, ctypes.byref(ctypes.c_int())) 35 | except ValueError: 36 | raise Exception("epanet2.dll not suitable") 37 | 38 | else: 39 | raise Exception('Platform '+ _plat +' unsupported (not yet)') 40 | 41 | 42 | self.charset = charset 43 | self._current_simulation_time= ctypes.c_long() 44 | 45 | self.ph = ctypes.c_void_p() 46 | self._lib.EN_createproject.argtypes = [ctypes.c_void_p] 47 | self._lib.EN_createproject(ctypes.byref(self.ph)) 48 | 49 | self._max_label_len= 32 50 | self._err_max_char= 80 51 | 52 | def ENepanet(self,nomeinp, nomerpt='', nomebin='', vfunc=None): 53 | """Runs a complete EPANET simulation. 54 | 55 | Arguments: 56 | nomeinp: name of the input file 57 | nomerpt: name of an output report file 58 | nomebin: name of an optional binary output file 59 | vfunc : pointer to a user-supplied function which accepts a character string as its argument.""" 60 | if vfunc is not None: 61 | CFUNC = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_char_p) 62 | callback= CFUNC(vfunc) 63 | else: 64 | callback= None 65 | ierr= self._lib.EN_epanet(self.ph, ctypes.c_char_p(nomeinp.encode()), 66 | ctypes.c_char_p(nomerpt.encode()), 67 | ctypes.c_char_p(nomebin.encode()), 68 | callback) 69 | if ierr!=0: raise ENtoolkitError(self, ierr) 70 | 71 | 72 | def ENopen(self, nomeinp, nomerpt='', nomebin=''): 73 | """Opens the Toolkit to analyze a particular distribution system 74 | 75 | Arguments: 76 | nomeinp: name of the input file 77 | nomerpt: name of an output report file 78 | nomebin: name of an optional binary output file 79 | """ 80 | ierr= self._lib.EN_open(self.ph, ctypes.c_char_p(nomeinp.encode()), 81 | ctypes.c_char_p(nomerpt.encode()), 82 | ctypes.c_char_p(nomebin.encode())) 83 | if ierr!=0: 84 | raise ENtoolkitError(self, ierr) 85 | 86 | 87 | def ENdeleteproject(self): 88 | """Closes down the Toolkit system (including all files being processed)""" 89 | ierr= self._lib.EN_deleteproject(ctypes.byref(self.ph)) 90 | if ierr!=0: raise ENtoolkitError(self, ierr) 91 | 92 | 93 | def ENgetnodeindex(self, nodeid): 94 | """Retrieves the index of a node with a specified ID. 95 | 96 | Arguments: 97 | nodeid: node ID label""" 98 | j= ctypes.c_int() 99 | ierr= self._lib.EN_getnodeindex(self.ph, ctypes.c_char_p(nodeid.encode(self.charset)), ctypes.byref(j)) 100 | if ierr!=0: raise ENtoolkitError(self, ierr) 101 | return j.value 102 | 103 | def ENgetcomment(self, object_type, index): 104 | """Retrieves the comment of an object with a object type and index 105 | 106 | Arguments: 107 | object_type: object type 108 | index: object index 109 | """ 110 | label = ctypes.create_string_buffer(1024) 111 | ierr = self._lib.EN_getcomment(self.ph, object_type, index, ctypes.byref(label)) 112 | if ierr!=0: raise ENtoolkitError(self, ierr) 113 | return label.value.decode(self.charset) 114 | 115 | def ENsetcomment(self, object_type, index, comment): 116 | """Retrieves the comment of an object with a object type and index 117 | 118 | Arguments: 119 | object_type: object type 120 | index: object index 121 | """ 122 | ierr = self._lib.EN_setcomment(self.ph, object_type, index, ctypes.c_char_p(comment.encode(self.charset))) 123 | if ierr!=0: raise ENtoolkitError(self, ierr) 124 | 125 | 126 | 127 | def ENgetnodeid(self, index): 128 | """Retrieves the ID label of a node with a specified index. 129 | 130 | Arguments: 131 | index: node index""" 132 | label = ctypes.create_string_buffer(self._max_label_len) 133 | ierr= self._lib.EN_getnodeid(self.ph, index, ctypes.byref(label)) 134 | if ierr!=0: raise ENtoolkitError(self, ierr) 135 | return label.value.decode(self.charset) 136 | 137 | 138 | def ENgetnodetype(self, index): 139 | """Retrieves the node-type code for a specific node. 140 | 141 | Arguments: 142 | index: node index""" 143 | j= ctypes.c_int() 144 | ierr= self._lib.EN_getnodetype(self.ph, index, ctypes.byref(j)) 145 | if ierr!=0: raise ENtoolkitError(self, ierr) 146 | return j.value 147 | 148 | def ENgetcoord(self, index): 149 | """Retrieves the coordinates (x,y) for a specific node. 150 | 151 | Arguments: 152 | index: node index""" 153 | x= ctypes.c_float() 154 | y= ctypes.c_float() 155 | ierr= self._lib.EN_getcoord(self.ph, index, ctypes.byref(x), ctypes.byref(y)) 156 | if ierr!=0: raise ENtoolkitError(self, ierr) 157 | return (x.value,y.value) 158 | 159 | 160 | def ENgetnodevalue(self, index, paramcode): 161 | """Retrieves the value of a specific node parameter. 162 | 163 | Arguments: 164 | index: node index 165 | paramcode: Node parameter codes consist of the following constants: 166 | EN_ELEVATION Elevation 167 | EN_BASEDEMAND ** Base demand 168 | EN_PATTERN ** Demand pattern index 169 | EN_EMITTER Emitter coeff. 170 | EN_INITQUAL Initial quality 171 | EN_SOURCEQUAL Source quality 172 | EN_SOURCEPAT Source pattern index 173 | EN_SOURCETYPE Source type (See note below) 174 | EN_TANKLEVEL Initial water level in tank 175 | EN_DEMAND * Actual demand 176 | EN_HEAD * Hydraulic head 177 | EN_PRESSURE * Pressure 178 | EN_QUALITY * Actual quality 179 | EN_SOURCEMASS * Mass flow rate per minute of a chemical source 180 | * computed values) 181 | ** primary demand category is last on demand list 182 | 183 | The following parameter codes apply only to storage tank nodes: 184 | EN_INITVOLUME Initial water volume 185 | EN_MIXMODEL Mixing model code (see below) 186 | EN_MIXZONEVOL Inlet/Outlet zone volume in a 2-compartment tank 187 | EN_TANKDIAM Tank diameter 188 | EN_MINVOLUME Minimum water volume 189 | EN_VOLCURVE Index of volume versus depth curve (0 if none assigned) 190 | EN_MINLEVEL Minimum water level 191 | EN_MAXLEVEL Maximum water level 192 | EN_MIXFRACTION Fraction of total volume occupied by the inlet/outlet zone in a 2-compartment tank 193 | EN_TANK_KBULK Bulk reaction rate coefficient""" 194 | j= ctypes.c_float() 195 | ierr= self._lib.EN_getnodevalue(self.ph, index, paramcode, ctypes.byref(j)) 196 | if ierr!=0: raise ENtoolkitError(self, ierr) 197 | return j.value 198 | 199 | 200 | ##------ 201 | def ENgetlinkindex(self, linkid): 202 | """Retrieves the index of a link with a specified ID. 203 | 204 | Arguments: 205 | linkid: link ID label""" 206 | j= ctypes.c_int() 207 | ierr= self._lib.EN_getlinkindex(self.ph, ctypes.c_char_p(linkid.encode(self.charset)), ctypes.byref(j)) 208 | if ierr!=0: raise ENtoolkitError(self, ierr) 209 | return j.value 210 | 211 | 212 | def ENgetlinkid(self, index): 213 | """Retrieves the ID label of a link with a specified index. 214 | 215 | Arguments: 216 | index: link index""" 217 | label = ctypes.create_string_buffer(self._max_label_len) 218 | ierr= self._lib.EN_getlinkid(self.ph, index, ctypes.byref(label)) 219 | if ierr!=0: raise ENtoolkitError(self, ierr) 220 | return label.value.decode(self.charset) 221 | 222 | 223 | def ENgetlinktype(self, index): 224 | """Retrieves the link-type code for a specific link. 225 | 226 | Arguments: 227 | index: link index""" 228 | j= ctypes.c_int() 229 | ierr= self._lib.EN_getlinktype(self.ph, index, ctypes.byref(j)) 230 | if ierr!=0: raise ENtoolkitError(self, ierr) 231 | return j.value 232 | 233 | 234 | def ENgetlinknodes(self, index): 235 | """Retrieves the indexes of the end nodes of a specified link. 236 | 237 | Arguments: 238 | index: link index""" 239 | j1= ctypes.c_int() 240 | j2= ctypes.c_int() 241 | ierr= self._lib.EN_getlinknodes(self.ph, index,ctypes.byref(j1),ctypes.byref(j2)) 242 | if ierr!=0: raise ENtoolkitError(self, ierr) 243 | return j1.value,j2.value 244 | 245 | def ENgetlinkvalue(self, index, paramcode): 246 | """Retrieves the value of a specific link parameter. 247 | 248 | Arguments: 249 | index: link index 250 | paramcode: Link parameter codes consist of the following constants: 251 | EN_DIAMETER Diameter 252 | EN_LENGTH Length 253 | EN_ROUGHNESS Roughness coeff. 254 | EN_MINORLOSS Minor loss coeff. 255 | EN_INITSTATUS Initial link status (0 = closed, 1 = open) 256 | EN_INITSETTING Roughness for pipes, initial speed for pumps, initial setting for valves 257 | EN_KBULK Bulk reaction coeff. 258 | EN_KWALL Wall reaction coeff. 259 | EN_FLOW * Flow rate 260 | EN_VELOCITY * Flow velocity 261 | EN_HEADLOSS * Head loss 262 | EN_STATUS * Actual link status (0 = closed, 1 = open) 263 | EN_SETTING * Roughness for pipes, actual speed for pumps, actual setting for valves 264 | EN_ENERGY * Energy expended in kwatts 265 | * computed values""" 266 | j= ctypes.c_float() 267 | ierr= self._lib.EN_getlinkvalue(self.ph, index, paramcode, ctypes.byref(j)) 268 | if ierr!=0: raise ENtoolkitError(self, ierr) 269 | return j.value 270 | #------ 271 | 272 | def ENgetpatternid(self, index): 273 | """Retrieves the ID label of a particular time pattern. 274 | 275 | Arguments: 276 | index: pattern index""" 277 | label = ctypes.create_string_buffer(self._max_label_len) 278 | ierr= self._lib.EN_getpatternid(self.ph, index, ctypes.byref(label)) 279 | if ierr!=0: raise ENtoolkitError(self, ierr) 280 | return label.value.decode(self.charset) 281 | 282 | def ENgetpatternindex(self, patternid): 283 | """Retrieves the index of a particular time pattern. 284 | 285 | Arguments: 286 | id: pattern ID label""" 287 | j= ctypes.c_int() 288 | ierr= self._lib.EN_getpatternindex(self.ph, ctypes.c_char_p(patternid.encode(self.charset)), ctypes.byref(j)) 289 | if ierr!=0: raise ENtoolkitError(self, ierr) 290 | return j.value 291 | 292 | 293 | def ENgetpatternlen(self, index): 294 | """Retrieves the number of time periods in a specific time pattern. 295 | 296 | Arguments: 297 | index:pattern index""" 298 | j= ctypes.c_int() 299 | ierr= self._lib.EN_getpatternlen(self.ph, index, ctypes.byref(j)) 300 | if ierr!=0: raise ENtoolkitError(self, ierr) 301 | return j.value 302 | 303 | def ENgetpatternvalue(self, index, period): 304 | """Retrieves the multiplier factor for a specific time period in a time pattern. 305 | 306 | Arguments: 307 | index: time pattern index 308 | period: period within time pattern""" 309 | j= ctypes.c_float() 310 | ierr= self._lib.EN_getpatternvalue(self.ph, index, period, ctypes.byref(j)) 311 | if ierr!=0: raise ENtoolkitError(self, ierr) 312 | return j.value 313 | 314 | 315 | 316 | def ENgetcount(self, countcode): 317 | """Retrieves the number of network components of a specified type. 318 | 319 | Arguments: 320 | countcode: component code EN_NODECOUNT 321 | EN_TANKCOUNT 322 | EN_LINKCOUNT 323 | EN_PATCOUNT 324 | EN_CURVECOUNT 325 | EN_CONTROLCOUNT""" 326 | j= ctypes.c_int() 327 | ierr= self._lib.EN_getcount(self.ph, countcode, ctypes.byref(j)) 328 | if ierr!=0: raise ENtoolkitError(self, ierr) 329 | return j.value 330 | 331 | 332 | def ENgetflowunits(self): 333 | """Retrieves a code number indicating the units used to express all flow rates.""" 334 | j= ctypes.c_int() 335 | ierr= self._lib.EN_getflowunits(self.ph, ctypes.byref(j)) 336 | if ierr!=0: raise ENtoolkitError(self, ierr) 337 | return j.value 338 | 339 | 340 | def ENgettimeparam(self, paramcode): 341 | """Retrieves the value of a specific analysis time parameter. 342 | Arguments: 343 | paramcode: EN_DURATION 344 | EN_HYDSTEP 345 | EN_QUALSTEP 346 | EN_PATTERNSTEP 347 | EN_PATTERNSTART 348 | EN_REPORTSTEP 349 | EN_REPORTSTART 350 | EN_RULESTEP 351 | EN_STATISTIC 352 | EN_PERIODS""" 353 | j= ctypes.c_int() 354 | ierr= self._lib.EN_gettimeparam(self.ph, paramcode, ctypes.byref(j)) 355 | if ierr!=0: raise ENtoolkitError(self, ierr) 356 | return j.value 357 | 358 | def ENgetqualtype(self, qualcode): 359 | """Retrieves the type of water quality analysis called for 360 | returns qualcode: Water quality analysis codes are as follows: 361 | EN_NONE 0 No quality analysis 362 | EN_CHEM 1 Chemical analysis 363 | EN_AGE 2 Water age analysis 364 | EN_TRACE 3 Source tracing 365 | tracenode: index of node traced in a source tracing 366 | analysis (value will be 0 when qualcode 367 | is not EN_TRACE)""" 368 | qualcode= ctypes.c_int() 369 | tracenode= ctypes.c_int() 370 | ierr= self._lib.EN_getqualtype(self.ph, ctypes.byref(qualcode), 371 | ctypes.byref(tracenode)) 372 | if ierr!=0: raise ENtoolkitError(self, ierr) 373 | return qualcode.value, tracenode.value 374 | 375 | 376 | 377 | #-------Retrieving other network information-------- 378 | def ENgetcontrol(self, cindex, ctype, lindex, setting, nindex, level ): 379 | """Retrieves the parameters of a simple control statement. 380 | Arguments: 381 | cindex: control statement index 382 | ctype: control type code EN_LOWLEVEL (Low Level Control) 383 | EN_HILEVEL (High Level Control) 384 | EN_TIMER (Timer Control) 385 | EN_TIMEOFDAY (Time-of-Day Control) 386 | lindex: index of link being controlled 387 | setting: value of the control setting 388 | nindex: index of controlling node 389 | level: value of controlling water level or pressure for level controls 390 | or of time of control action (in seconds) for time-based controls""" 391 | #int ENgetcontrol(int cindex, int* ctype, int* lindex, float* setting, int* nindex, float* level ) 392 | ierr= self._lib.EN_getcontrol(self.ph, ctypes.c_int(cindex), ctypes.c_int(ctype), 393 | ctypes.c_int(lindex), ctypes.c_float(setting), 394 | ctypes.c_int(nindex), ctypes.c_float(level) ) 395 | if ierr!=0: raise ENtoolkitError(self, ierr) 396 | 397 | 398 | def ENgetoption(self, optioncode): 399 | """Retrieves the value of a particular analysis option. 400 | 401 | Arguments: 402 | optioncode: EN_TRIALS 403 | EN_ACCURACY 404 | EN_TOLERANCE 405 | EN_EMITEXPON 406 | EN_DEMANDMULT""" 407 | j= ctypes.c_int() 408 | ierr= self._lib.EN_getoption(self.ph, optioncode, ctypes.byref(j)) 409 | if ierr!=0: raise ENtoolkitError(self, ierr) 410 | return j.value 411 | 412 | def ENgetversion(self): 413 | """Retrieves the current version number of the Toolkit.""" 414 | j= ctypes.c_int() 415 | ierr= self._lib.EN_getversion(self.ph, ctypes.byref(j)) 416 | if ierr!=0: raise ENtoolkitError(self, ierr) 417 | return j.value 418 | 419 | 420 | 421 | #---------Setting new values for network parameters------------- 422 | def ENaddcontrol(self, ctype, lindex, setting, nindex, level ): 423 | """Sets the parameters of a simple control statement. 424 | Arguments: 425 | ctype: control type code EN_LOWLEVEL (Low Level Control) 426 | EN_HILEVEL (High Level Control) 427 | EN_TIMER (Timer Control) 428 | EN_TIMEOFDAY (Time-of-Day Control) 429 | lindex: index of link being controlled 430 | setting: value of the control setting 431 | nindex: index of controlling node 432 | level: value of controlling water level or pressure for level controls 433 | or of time of control action (in seconds) for time-based controls""" 434 | #int ENsetcontrol(int cindex, int* ctype, int* lindex, float* setting, int* nindex, float* level ) 435 | cindex = ctypes.c_int() 436 | ierr= self._lib.EN_addcontrol(self.ph, ctypes.byref(cindex), ctypes.c_int(ctype), 437 | ctypes.c_int(lindex), ctypes.c_float(setting), 438 | ctypes.c_int(nindex), ctypes.c_float(level)) 439 | if ierr!=0: raise ENtoolkitError(self, ierr) 440 | return cindex 441 | 442 | def ENsetcontrol(self, cindex, ctype, lindex, setting, nindex, level ): 443 | """Sets the parameters of a simple control statement. 444 | Arguments: 445 | cindex: control statement index 446 | ctype: control type code EN_LOWLEVEL (Low Level Control) 447 | EN_HILEVEL (High Level Control) 448 | EN_TIMER (Timer Control) 449 | EN_TIMEOFDAY (Time-of-Day Control) 450 | lindex: index of link being controlled 451 | setting: value of the control setting 452 | nindex: index of controlling node 453 | level: value of controlling water level or pressure for level controls 454 | or of time of control action (in seconds) for time-based controls""" 455 | #int ENsetcontrol(int cindex, int* ctype, int* lindex, float* setting, int* nindex, float* level ) 456 | ierr= self._lib.EN_setcontrol(self.ph, ctypes.c_int(cindex), ctypes.c_int(ctype), 457 | ctypes.c_int(lindex), ctypes.c_float(setting), 458 | ctypes.c_int(nindex), ctypes.c_float(level) ) 459 | if ierr!=0: raise ENtoolkitError(self, ierr) 460 | 461 | 462 | def ENsetnodevalue(self, index, paramcode, value): 463 | """Sets the value of a parameter for a specific node. 464 | Arguments: 465 | index: node index 466 | paramcode: Node parameter codes consist of the following constants: 467 | EN_ELEVATION Elevation 468 | EN_BASEDEMAND ** Base demand 469 | EN_PATTERN ** Demand pattern index 470 | EN_EMITTER Emitter coeff. 471 | EN_INITQUAL Initial quality 472 | EN_SOURCEQUAL Source quality 473 | EN_SOURCEPAT Source pattern index 474 | EN_SOURCETYPE Source type (See note below) 475 | EN_TANKLEVEL Initial water level in tank 476 | ** primary demand category is last on demand list 477 | The following parameter codes apply only to storage tank nodes 478 | EN_TANKDIAM Tank diameter 479 | EN_MINVOLUME Minimum water volume 480 | EN_MINLEVEL Minimum water level 481 | EN_MAXLEVEL Maximum water level 482 | EN_MIXMODEL Mixing model code 483 | EN_MIXFRACTION Fraction of total volume occupied by the inlet/outlet 484 | EN_TANK_KBULK Bulk reaction rate coefficient 485 | value:parameter value""" 486 | ierr= self._lib.EN_setnodevalue(self.ph, ctypes.c_int(index), ctypes.c_int(paramcode), ctypes.c_float(value)) 487 | if ierr!=0: raise ENtoolkitError(self, ierr) 488 | 489 | 490 | def ENsetlinkvalue(self, index, paramcode, value): 491 | """Sets the value of a parameter for a specific link. 492 | Arguments: 493 | index: link index 494 | paramcode: Link parameter codes consist of the following constants: 495 | EN_DIAMETER Diameter 496 | EN_LENGTH Length 497 | EN_ROUGHNESS Roughness coeff. 498 | EN_MINORLOSS Minor loss coeff. 499 | EN_INITSTATUS * Initial link status (0 = closed, 1 = open) 500 | EN_INITSETTING * Roughness for pipes, initial speed for pumps, initial setting for valves 501 | EN_KBULK Bulk reaction coeff. 502 | EN_KWALL Wall reaction coeff. 503 | EN_STATUS * Actual link status (0 = closed, 1 = open) 504 | EN_SETTING * Roughness for pipes, actual speed for pumps, actual setting for valves 505 | * Use EN_INITSTATUS and EN_INITSETTING to set the design value for a link's status or setting that 506 | exists prior to the start of a simulation. Use EN_STATUS and EN_SETTING to change these values while 507 | a simulation is being run (within the ENrunH - ENnextH loop). 508 | 509 | value:parameter value""" 510 | ierr= self._lib.EN_setlinkvalue(self.ph, ctypes.c_int(index), 511 | ctypes.c_int(paramcode), 512 | ctypes.c_float(value)) 513 | if ierr!=0: raise ENtoolkitError(self, ierr) 514 | 515 | # ---- EPYNET Extensions ---- # 516 | 517 | def ENinit(self, rptfile, binfile, units_code, headloss_code): 518 | ierr = self._lib.EN_init(self.ph, ctypes.c_char_p(rptfile), ctypes.c_char_p(binfile), ctypes.c_int(units_code), ctypes.c_int(headloss_code)) 519 | if ierr!=0: raise ENtoolkitError(self, ierr) 520 | 521 | def ENaddnode(self, node_id, node_type_code): 522 | index = ctypes.c_int() 523 | 524 | ierr= self._lib.EN_addnode(self.ph, ctypes.c_char_p(node_id.encode(self.charset)), ctypes.c_int(node_type_code), ctypes.byref(index)) 525 | if ierr!=0: raise ENtoolkitError(self, ierr) 526 | 527 | return index 528 | 529 | def ENdeletenode(self, node_index, conditional=0): 530 | ierr= self._lib.EN_deletenode(self.ph, ctypes.c_int(node_index), ctypes.c_int(conditional)) 531 | if ierr!=0: raise ENtoolkitError(self, ierr) 532 | 533 | def ENdeletelink(self, link_index, conditional=0): 534 | ierr= self._lib.EN_deletelink(self.ph, ctypes.c_int(link_index), ctypes.c_int(conditional)) 535 | if ierr!=0: raise ENtoolkitError(self, ierr) 536 | 537 | def ENaddlink(self, link_id, link_type_code, from_node_id, to_node_id): 538 | 539 | index = ctypes.c_int() 540 | 541 | ierr= self._lib.EN_addlink(self.ph, ctypes.c_char_p(link_id.encode(self.charset)), ctypes.c_int(link_type_code), ctypes.c_char_p(from_node_id.encode(self.charset)), ctypes.c_char_p(to_node_id.encode(self.charset)), ctypes.byref(index)) 542 | if ierr!=0: raise ENtoolkitError(self, ierr) 543 | 544 | def ENsetheadcurveindex(self, pump_index, curve_index): 545 | ierr = self._lib.EN_setheadcurveindex(self.ph, ctypes.c_int(pump_index), ctypes.c_int(curve_index)) 546 | if ierr!=0: raise ENtoolkitError(self, ierr) 547 | 548 | def ENgetheadcurveindex(self, pump_index): 549 | j= ctypes.c_int() 550 | ierr = self._lib.EN_getheadcurveindex(self.ph, ctypes.c_int(pump_index), ctypes.byref(j)) 551 | if ierr!=0: raise ENtoolkitError(self, ierr) 552 | return j.value 553 | 554 | def ENaddcurve(self, curve_id): 555 | ierr = self._lib.EN_addcurve(self.ph, ctypes.c_char_p(curve_id.encode(self.charset))) 556 | if ierr!=0: raise ENtoolkitError(self, ierr) 557 | 558 | def ENsetcurvevalue(self, curve_index,point_index, x ,y): 559 | ierr = self._lib.EN_setcurvevalue(self.ph, ctypes.c_int(curve_index), ctypes.c_int(point_index), ctypes.c_float(x), ctypes.c_float(y)) 560 | if ierr!=0: raise ENtoolkitError(self, ierr) 561 | 562 | def ENsetcoord(self, index, x, y): 563 | ierr= self._lib.EN_setcoord(self.ph, ctypes.c_int(index), 564 | ctypes.c_float(x), 565 | ctypes.c_float(y)) 566 | if ierr!=0: raise ENtoolkitError(self, ierr) 567 | 568 | def ENaddpattern(self, patternid): 569 | """Adds a new time pattern to the network. 570 | Arguments: 571 | id: ID label of pattern""" 572 | ierr= self._lib.EN_addpattern(self.ph, ctypes.c_char_p(patternid.encode(self.charset))) 573 | if ierr!=0: raise ENtoolkitError(self, ierr) 574 | 575 | 576 | def ENsetpattern(self, index, factors): 577 | """Sets all of the multiplier factors for a specific time pattern. 578 | Arguments: 579 | index: time pattern index 580 | factors: multiplier factors list for the entire pattern""" 581 | # int ENsetpattern( int index, float* factors, int nfactors ) 582 | nfactors= len(factors) 583 | cfactors_type= ctypes.c_float* nfactors 584 | cfactors= cfactors_type() 585 | for i in range(nfactors): 586 | cfactors[i]= float(factors[i] ) 587 | ierr= self._lib.EN_setpattern(self.ph, ctypes.c_int(index), cfactors, ctypes.c_int(nfactors) ) 588 | if ierr!=0: raise ENtoolkitError(self, ierr) 589 | 590 | 591 | def ENsetpatternvalue(self, index, period, value): 592 | """Sets the multiplier factor for a specific period within a time pattern. 593 | Arguments: 594 | index: time pattern index 595 | period: period within time pattern 596 | value: multiplier factor for the period""" 597 | #int ENsetpatternvalue( int index, int period, float value ) 598 | ierr= self._lib.EN_setpatternvalue(self.ph, ctypes.c_int(index), 599 | ctypes.c_int(period), 600 | ctypes.c_float(value) ) 601 | if ierr!=0: raise ENtoolkitError(self, ierr) 602 | 603 | 604 | 605 | def ENsetqualtype(self, qualcode, chemname, chemunits, tracenode): 606 | """Sets the type of water quality analysis called for. 607 | Arguments: 608 | qualcode: water quality analysis code 609 | chemname: name of the chemical being analyzed 610 | chemunits: units that the chemical is measured in 611 | tracenode: ID of node traced in a source tracing analysis """ 612 | ierr= self._lib.EN_setqualtype(self.ph, ctypes.c_int(qualcode), 613 | ctypes.c_char_p(chemname.encode(self.charset)), 614 | ctypes.c_char_p(chemunits.encode(self.charset)), 615 | ctypes.c_char_p(tracenode.encode(self.charset))) 616 | if ierr!=0: raise ENtoolkitError(self, ierr) 617 | 618 | 619 | def ENsettimeparam(self, paramcode, timevalue): 620 | """Sets the value of a time parameter. 621 | Arguments: 622 | paramcode: time parameter code EN_DURATION 623 | EN_HYDSTEP 624 | EN_QUALSTEP 625 | EN_PATTERNSTEP 626 | EN_PATTERNSTART 627 | EN_REPORTSTEP 628 | EN_REPORTSTART 629 | EN_RULESTEP 630 | EN_STATISTIC 631 | EN_PERIODS 632 | timevalue: value of time parameter in seconds 633 | The codes for EN_STATISTIC are: 634 | EN_NONE none 635 | EN_AVERAGE averaged 636 | EN_MINIMUM minimums 637 | EN_MAXIMUM maximums 638 | EN_RANGE ranges""" 639 | ierr= self._lib.EN_settimeparam(self.ph, ctypes.c_int(paramcode), ctypes.c_int(timevalue)) 640 | if ierr!=0: raise ENtoolkitError(self, ierr) 641 | 642 | 643 | def ENsetoption(self, optioncode, value): 644 | """Sets the value of a particular analysis option. 645 | 646 | Arguments: 647 | optioncode: option code EN_TRIALS 648 | EN_ACCURACY 649 | EN_TOLERANCE 650 | EN_EMITEXPON 651 | EN_DEMANDMULT 652 | value: option value""" 653 | ierr= self._lib.EN_setoption(self.ph, ctypes.c_int(paramcode), ctypes.c_float(value)) 654 | if ierr!=0: raise ENtoolkitError(self, ierr) 655 | 656 | 657 | #----- Saving and using hydraulic analysis results files ------- 658 | def ENsavehydfile(self, fname): 659 | """Saves the current contents of the binary hydraulics file to a file.""" 660 | ierr= self._lib.EN_savehydfile(self.ph, ctypes.c_char_p(fname.encode())) 661 | if ierr!=0: raise ENtoolkitError(self, ierr) 662 | 663 | def ENusehydfile(self, fname): 664 | """Uses the contents of the specified file as the current binary hydraulics file""" 665 | ierr= self._lib.EN_usehydfile(self.ph, ctypes.c_char_p(fname.encode())) 666 | if ierr!=0: raise ENtoolkitError(self, ierr) 667 | 668 | 669 | 670 | #----------Running a hydraulic analysis -------------------------- 671 | def ENsolveH(self): 672 | """Runs a complete hydraulic simulation with results 673 | for all time periods written to the binary Hydraulics file.""" 674 | ierr= self._lib.EN_solveH(self.ph, ) 675 | if ierr!=0: raise ENtoolkitError(self, ierr) 676 | 677 | 678 | def ENopenH(self): 679 | """Opens the hydraulics analysis system""" 680 | ierr= self._lib.EN_openH(self.ph, ) 681 | 682 | 683 | def ENinitH(self, flag=None): 684 | """Initializes storage tank levels, link status and settings, 685 | and the simulation clock time prior 686 | to running a hydraulic analysis. 687 | 688 | flag EN_NOSAVE [+EN_SAVE] [+EN_INITFLOW] """ 689 | ierr= self._lib.EN_initH(self.ph, flag) 690 | if ierr!=0: raise ENtoolkitError(self, ierr) 691 | 692 | 693 | def ENrunH(self): 694 | """Runs a single period hydraulic analysis, 695 | retrieving the current simulation clock time t""" 696 | ierr= self._lib.EN_runH(self.ph, ctypes.byref(self._current_simulation_time)) 697 | if ierr>=100: 698 | raise ENtoolkitError(self, ierr) 699 | elif ierr>0: 700 | warnings.warn(self.ENgeterror(ierr)) 701 | return self.ENgeterror(ierr) 702 | 703 | def ENabort(self): 704 | self._lib.EN_abort(self.ph, ) 705 | 706 | def ENsimtime(self): 707 | """retrieves the current simulation time t as datetime.timedelta instance""" 708 | return datetime.timedelta(seconds= self._current_simulation_time.value ) 709 | 710 | def ENnextH(self): 711 | """Determines the length of time until the next hydraulic event occurs in an extended period 712 | simulation.""" 713 | _deltat= ctypes.c_long() 714 | ierr= self._lib.EN_nextH(self.ph, ctypes.byref(_deltat)) 715 | if ierr!=0: raise ENtoolkitError(self, ierr) 716 | return _deltat.value 717 | 718 | 719 | def ENcloseH(self): 720 | """Closes the hydraulic analysis system, freeing all allocated memory.""" 721 | ierr= self._lib.EN_closeH(self.ph, ) 722 | if ierr!=0: raise ENtoolkitError(self, ierr) 723 | 724 | #-------------------------------------------- 725 | 726 | #----------Running a quality analysis -------------------------- 727 | def ENsolveQ(self): 728 | """Runs a complete water quality simulation with results 729 | at uniform reporting intervals written to EPANET's binary Output file.""" 730 | ierr= self._lib.EN_solveQ(self.ph, ) 731 | if ierr!=0: raise ENtoolkitError(self, ierr) 732 | 733 | 734 | def ENopenQ(self): 735 | """Opens the water quality analysis system""" 736 | ierr= self._lib.EN_openQ(self.ph, ) 737 | 738 | 739 | def ENinitQ(self, flag=None): 740 | """Initializes water quality and the simulation clock 741 | time prior to running a water quality analysis. 742 | 743 | flag EN_NOSAVE | EN_SAVE """ 744 | ierr= self._lib.EN_initQ(self.ph, flag) 745 | if ierr!=0: raise ENtoolkitError(self, ierr) 746 | 747 | def ENrunQ(self): 748 | """Makes available the hydraulic and water quality results 749 | that occur at the start of the next time period of a water quality analysis, 750 | where the start of the period is returned in t.""" 751 | ierr= self._lib.EN_runQ(self.ph, ctypes.byref(self._current_simulation_time)) 752 | if ierr>=100: 753 | raise ENtoolkitError(self, ierr) 754 | elif ierr>0: 755 | return self.ENgeterror(ierr) 756 | 757 | def ENnextQ(self): 758 | """Advances the water quality simulation 759 | to the start of the next hydraulic time period.""" 760 | _deltat= ctypes.c_long() 761 | ierr= self._lib.EN_nextQ(self.ph, ctypes.byref(_deltat)) 762 | if ierr!=0: raise ENtoolkitError(self, ierr) 763 | return _deltat.value 764 | 765 | 766 | def ENstepQ(self): 767 | """Advances the water quality simulation one water quality time step. 768 | The time remaining in the overall simulation is returned in tleft.""" 769 | tleft= ctypes.c_long() 770 | ierr= self._lib.EN_nextQ(self.ph, ctypes.byref(tleft)) 771 | if ierr!=0: raise ENtoolkitError(self, ierr) 772 | return tleft.value 773 | 774 | def ENcloseQ(self): 775 | """Closes the water quality analysis system, 776 | freeing all allocated memory.""" 777 | ierr= self._lib.EN_closeQ(self.ph, ) 778 | if ierr!=0: raise ENtoolkitError(self, ierr) 779 | #-------------------------------------------- 780 | 781 | 782 | 783 | 784 | 785 | def ENsaveH(self): 786 | """Transfers results of a hydraulic simulation 787 | from the binary Hydraulics file to the binary 788 | Output file, where results are only reported at 789 | uniform reporting intervals.""" 790 | ierr= self._lib.EN_saveH(self.ph, ) 791 | if ierr!=0: raise ENtoolkitError(self, ierr) 792 | 793 | 794 | def ENsaveinpfile(self, fname): 795 | """Writes all current network input data to a file 796 | using the format of an EPANET input file.""" 797 | ierr= self._lib.EN_saveinpfile(self.ph, ctypes.c_char_p(fname.encode())) 798 | if ierr!=0: raise ENtoolkitError(self, ierr) 799 | 800 | 801 | def ENreport(self): 802 | """Writes a formatted text report on simulation results 803 | to the Report file.""" 804 | ierr= self._lib.EN_report(self.ph, ) 805 | if ierr!=0: raise ENtoolkitError(self, ierr) 806 | 807 | def ENresetreport(self): 808 | """Clears any report formatting commands 809 | 810 | that either appeared in the [REPORT] section of the 811 | EPANET Input file or were issued with the 812 | ENsetreport function""" 813 | ierr= self._lib.EN_resetreport(self.ph, ) 814 | if ierr!=0: raise ENtoolkitError(self, ierr) 815 | 816 | def ENsetreport(self, command): 817 | """Issues a report formatting command. 818 | 819 | Formatting commands are the same as used in the 820 | [REPORT] section of the EPANET Input file.""" 821 | ierr= self._lib.EN_setreport(self.ph, ctypes.c_char_p(command.encode(self.charset))) 822 | if ierr!=0: raise ENtoolkitError(self, ierr) 823 | 824 | def ENsetstatusreport(self, statuslevel): 825 | """Sets the level of hydraulic status reporting. 826 | 827 | statuslevel: level of status reporting 828 | 0 - no status reporting 829 | 1 - normal reporting 830 | 2 - full status reporting""" 831 | ierr= self._lib.EN_setstatusreport(self.ph, ctypes.c_int(statuslevel)) 832 | if ierr!=0: raise ENtoolkitError(self, ierr) 833 | 834 | def ENgeterror(self, errcode): 835 | """Retrieves the text of the message associated with a particular error or warning code.""" 836 | errmsg= ctypes.create_string_buffer(self._err_max_char) 837 | self._lib.ENgeterror(errcode,ctypes.byref(errmsg), self._err_max_char ) 838 | return errmsg.value.decode(self.charset) 839 | 840 | def ENwriteline(self, line ): 841 | """Writes a line of text to the EPANET report file.""" 842 | ierr= self._lib.EN_writeline(self.ph, ctypes.c_char_p(line.encode(self.charset) )) 843 | if ierr!=0: raise ENtoolkitError(self, ierr) 844 | 845 | 846 | 847 | def ENgetcurve(self, curveIndex): 848 | curveid = ctypes.create_string_buffer(self._max_label_len) 849 | nValues = ctypes.c_int() 850 | xValues= (ctypes.c_float*100)() 851 | yValues= (ctypes.c_float*100)() 852 | ierr= self._lib.EN_getcurve(self.ph, curveIndex, 853 | ctypes.byref(curveid), 854 | ctypes.byref(nValues), 855 | xValues, 856 | yValues 857 | ) 858 | # strange behavior of ENgetcurve: it returns also curveID 859 | # better split in two distinct functions .... 860 | if ierr!=0: raise ENtoolkitError(self, ierr) 861 | curve= [] 862 | for i in range(nValues.value): 863 | curve.append( (xValues[i],yValues[i]) ) 864 | return curve 865 | 866 | def ENsetcurve(self, curveIndex, values): 867 | nValues = len(values) 868 | Values_type = ctypes.c_float* nValues 869 | xValues = Values_type() 870 | yValues = Values_type() 871 | for i in range(nValues): 872 | xValues[i] = float(values[i][0]) 873 | yValues[i] = float(values[i][1]) 874 | 875 | ierr = self._lib.EN_setcurve(self.ph, curveIndex, xValues, yValues, nValues) 876 | if ierr!=0: raise ENtoolkitError(self, ierr) 877 | 878 | 879 | def ENgetcurveid(self, curveIndex): 880 | curveid = ctypes.create_string_buffer(self._max_label_len) 881 | nValues = ctypes.c_int() 882 | 883 | xValues= (ctypes.c_float * 100)() 884 | yValues= (ctypes.c_float * 100)() 885 | 886 | ierr= self._lib.EN_getcurve(self.ph, curveIndex, 887 | ctypes.byref(curveid), 888 | ctypes.byref(nValues), 889 | xValues, 890 | yValues) 891 | # strange behavior of ENgetcurve: it returns also curveID 892 | # better split in two distinct functions .... 893 | if ierr!=0: raise ENtoolkitError(self, ierr) 894 | return curveid.value.decode(self.charset) 895 | 896 | def ENgetcurveindex(self, curveId): 897 | j= ctypes.c_int() 898 | ierr= self._lib.EN_getcurveindex(self.ph, ctypes.c_char_p(curveId.encode(self.charset)), ctypes.byref(j)) 899 | if ierr!=0: raise ENtoolkitError(self, ierr) 900 | return j.value 901 | 902 | def ENgetcurvelen(self, curveIndex): 903 | j= ctypes.c_int() 904 | ierr= self._lib.EN_getcurvelen(self.ph, ctypes.c_int(curveIndex), ctypes.byref(j)) 905 | if ierr!=0: raise ENtoolkitError(self, ierr) 906 | return j.value 907 | 908 | def ENgetcurvevalue(self, curveIndex, point): 909 | x = ctypes.c_float() 910 | y = ctypes.c_float() 911 | ierr= self._lib.EN_getcurvevalue(self.ph, ctypes.c_int(curveIndex), ctypes.c_int(point-1), ctypes.byref(x), ctypes.byref(y)) 912 | if ierr!=0: raise ENtoolkitError(self, ierr) 913 | return x.value, y.value 914 | 915 | 916 | EN_ELEVATION = 0 # /* Node parameters */ 917 | EN_BASEDEMAND = 1 918 | EN_PATTERN = 2 919 | EN_EMITTER = 3 920 | EN_INITQUAL = 4 921 | EN_SOURCEQUAL = 5 922 | EN_SOURCEPAT = 6 923 | EN_SOURCETYPE = 7 924 | EN_TANKLEVEL = 8 925 | EN_DEMAND = 9 926 | EN_HEAD = 10 927 | EN_PRESSURE = 11 928 | EN_QUALITY = 12 929 | EN_SOURCEMASS = 13 930 | EN_INITVOLUME = 14 931 | EN_MIXMODEL = 15 932 | EN_MIXZONEVOL = 16 933 | 934 | EN_TANKDIAM = 17 935 | EN_MINVOLUME = 18 936 | EN_VOLCURVE = 19 937 | EN_MINLEVEL = 20 938 | EN_MAXLEVEL = 21 939 | EN_MIXFRACTION = 22 940 | EN_TANK_KBULK = 23 941 | 942 | EN_DIAMETER = 0 # /* Link parameters */ 943 | EN_LENGTH = 1 944 | EN_ROUGHNESS = 2 945 | EN_MINORLOSS = 3 946 | EN_INITSTATUS = 4 947 | EN_INITSETTING = 5 948 | EN_KBULK = 6 949 | EN_KWALL = 7 950 | EN_FLOW = 8 951 | EN_VELOCITY = 9 952 | EN_HEADLOSS = 10 953 | EN_STATUS = 11 954 | EN_SETTING = 12 955 | EN_ENERGY = 13 956 | 957 | EN_DURATION = 0 # /* Time parameters */ 958 | EN_HYDSTEP = 1 959 | EN_QUALSTEP = 2 960 | EN_PATTERNSTEP = 3 961 | EN_PATTERNSTART = 4 962 | EN_REPORTSTEP = 5 963 | EN_REPORTSTART = 6 964 | EN_RULESTEP = 7 965 | EN_STATISTIC = 8 966 | EN_PERIODS = 9 967 | 968 | EN_NODECOUNT = 0 # /* Component counts */ 969 | EN_TANKCOUNT = 1 970 | EN_LINKCOUNT = 2 971 | EN_PATCOUNT = 3 972 | EN_CURVECOUNT = 4 973 | EN_CONTROLCOUNT = 5 974 | 975 | EN_JUNCTION = 0 # /* Node types */ 976 | EN_RESERVOIR = 1 977 | EN_TANK = 2 978 | 979 | EN_CVPIPE = 0 # /* Link types */ 980 | EN_PIPE = 1 981 | EN_PUMP = 2 982 | EN_PRV = 3 983 | EN_PSV = 4 984 | EN_PBV = 5 985 | EN_FCV = 6 986 | EN_TCV = 7 987 | EN_GPV = 8 988 | 989 | EN_NONE = 0 # /* Quality analysis types */ 990 | EN_CHEM = 1 991 | EN_AGE = 2 992 | EN_TRACE = 3 993 | 994 | EN_CONCEN = 0 # /* Source quality types */ 995 | EN_MASS = 1 996 | EN_SETPOINT = 2 997 | EN_FLOWPACED = 3 998 | 999 | EN_CFS = 0 # /* Flow units types */ 1000 | EN_GPM = 1 1001 | EN_MGD = 2 1002 | EN_IMGD = 3 1003 | EN_AFD = 4 1004 | EN_LPS = 5 1005 | EN_LPM = 6 1006 | EN_MLD = 7 1007 | EN_CMH = 8 1008 | EN_CMD = 9 1009 | 1010 | EN_HW = 0 1011 | EN_DW = 1 1012 | EN_CM = 2 1013 | 1014 | EN_TRIALS = 0 # /* Misc. options */ 1015 | EN_ACCURACY = 1 1016 | EN_TOLERANCE = 2 1017 | EN_EMITEXPON = 3 1018 | EN_DEMANDMULT = 4 1019 | 1020 | EN_LOWLEVEL = 0 # /* Control types */ 1021 | EN_HILEVEL = 1 1022 | EN_TIMER = 2 1023 | EN_TIMEOFDAY = 3 1024 | 1025 | EN_AVERAGE = 1 # /* Time statistic types. */ 1026 | EN_MINIMUM = 2 1027 | EN_MAXIMUM = 3 1028 | EN_RANGE = 4 1029 | 1030 | EN_MIX1 = 0 # /* Tank mixing models */ 1031 | EN_MIX2 = 1 1032 | EN_FIFO = 2 1033 | EN_LIFO = 3 1034 | 1035 | EN_NOSAVE = 0 # /* Save-results-to-file flag */ 1036 | EN_SAVE = 1 1037 | EN_INITFLOW = 10 # /* Re-initialize flow flag */ 1038 | 1039 | 1040 | 1041 | FlowUnits= { EN_CFS :"cfs" , 1042 | EN_GPM :"gpm" , 1043 | EN_MGD :"a-f/d" , 1044 | EN_IMGD:"mgd" , 1045 | EN_AFD :"Imgd" , 1046 | EN_LPS :"L/s" , 1047 | EN_LPM :"Lpm" , 1048 | EN_MLD :"m3/h" , 1049 | EN_CMH :"m3/d" , 1050 | EN_CMD :"ML/d" } 1051 | 1052 | class ENtoolkitError(Exception): 1053 | def __init__(self, epanet2, ierr): 1054 | self.warning= ierr < 100 1055 | self.args= (ierr,) 1056 | self.message = epanet2.ENgeterror(ierr) 1057 | 1058 | if self.message=='' and ierr!=0: 1059 | self.message='ENtoolkit Undocumented Error '+str(ierr)+': look at text.h in epanet sources' 1060 | def __str__(self): 1061 | return self.message 1062 | --------------------------------------------------------------------------------