Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merging Abhi's Raingage API work #198

Merged
merged 4 commits into from
Jul 26, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pyswmm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pyswmm.simulation import Simulation
from pyswmm.subcatchments import Subcatchment, Subcatchments
from pyswmm.system import SystemStats
from pyswmm.raingages import RainGages, RainGage

VERSION_INFO = (0, 5, 0, 'dev0')
__version__ = '.'.join(map(str, VERSION_INFO))
Expand All @@ -26,5 +27,5 @@
__licence__ = 'BSD2'
__all__ = [
Link, Links, LidControls, LidGroups, Node, Nodes, Subcatchment, Subcatchments, Simulation,
SystemStats
SystemStats, RainGages, RainGage
]
241 changes: 241 additions & 0 deletions pyswmm/raingages.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2019 Bryant E. McDonnell
#
# Licensed under the terms of the BSD2 License
# See LICENSE.txt for details
# -----------------------------------------------------------------------------
"""Raingages module for the pythonic interface to SWMM5."""

# Local imports
from pyswmm.swmm5 import PYSWMMException
from pyswmm.toolkitapi import RainGageResults, ObjectType


class RainGages(object):
"""
Rain Gages Iterator Methods.

:param object model: Open Model Instance

Examples:

>>> from pyswmm import Simulation, Nodes
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... for raingage in RainGages(sim):
... print(raingage)
... print(raingage.raingageid)
...
>>> <swmm5.RainGage object at 0x031B0350>
>>> Gage1
>>> <swmm5.RainGage object at 0x030693D0>
>>> Gage4
>>> <swmm5.RainGage object at 0x031B0350>
>>> Gage3
>>> <swmm5.RainGage object at 0x030693D0>
>>> Gage10

Iterating over Nodes Object

>>> raingages = RainGages(sim)
>>> for raingage in raingages:
... print(raingage.raingageid)
>>> Gage1
>>> Gage4
>>> Gage3
>>> Gage10

Testing Existence

>>> raingages = RainGages(sim)
>>> "Gage1" in raingages
>>> True

Initializing a node Object

>>> raingages = RainGages(sim)
>>> gage1 = raingages['Gage1']
>>> print(gage1.total_precip)
>>> 0.04
>>>
>>> gage1.total_precip = 1
>>> print(gage1.total_precip)
>>> 1
"""

def __init__(self, model):
if not model._model.fileLoaded:
raise PYSWMMException("SWMM Model Not Open")
self._model = model._model
self._cuindex = 0
self._nRaingages = self._model.getProjectSize(ObjectType.GAGE.value)

def __len__(self):
"""
Return number of raingages. Use the expression 'len(RainGages(sim))'.

:return: Number of Raingages
:rtype: int

"""
return self._model.getProjectSize(ObjectType.GAGE.value)

def __contains__(self, raingageid):
"""
Checks if Rain Gage ID exists.

:return: ID Exists
:rtype: bool
"""
return self._model.ObjectIDexist(ObjectType.GAGE.value, raingageid)

def __getitem__(self, raingageid):
if self.__contains__(raingageid):
rg = RainGage(self._model, raingageid)
return rg
else:
raise PYSWMMException("Raingage ID: {} Does not Exist".format(raingageid))

def __iter__(self):
return self

def __next__(self):
if self._cuindex < self._nRaingages:
raingageobject = self.__getitem__(self._raingageid)
self._cuindex += 1 # Next Iteration
return raingageobject
else:
raise StopIteration()

next = __next__ # Python 2

@property
def _raingageid(self):
"""Node ID."""
return self._model.getObjectId(ObjectType.GAGE.value, self._cuindex)


class RainGage(object):
"""
Raingage Methods.

:param object model: Open Model Instance
:param str raingageid: Raingage ID

Examples:

>>> from pyswmm import Simulation, Raingages
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... rg1 = Raingages(sim)["Gage1"]
... print(rg1.raingageid)
... for step in simulation:
... print(rg1.total_precip)
... Gage1
... 0
... 10
"""

def __init__(self, model, raingageid):
if not model.fileLoaded:
raise PYSWMMException("SWMM Model Not Open")
if raingageid not in model.getObjectIDList(ObjectType.GAGE.value):
raise PYSWMMException("ID Not valid")
self._model = model
self._raingageid = raingageid

# --- Get Parameters
# -------------------------------------------------------------------------
@property
def raingageid(self):
"""
Get Rain Gage ID.

:return: Parameter Value
:rtype: float

Examples:

>>> from pyswmm import Simulation, RainGages
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... rg = RainGage(sim)["Gage1"]
... print(rg.raingageid)
>>> Gage1
"""
return self._raingageid

@property
def total_precip(self):
jennwuu marked this conversation as resolved.
Show resolved Hide resolved
"""
Get/set raingage total precipitation rate (like in/hr or mm/hr).

:return: Parameter Value
:rtype: float

Examples:

>>> from pyswmm import Simulation, RainGages
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... rg1 = RainGages(sim)["Gage1"]
... print(rg1.total_precip)
>>> 1.0

Setting the value

>>> from pyswmm import Simulation, RainGages
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... rg1 = RainGages(sim)["Gage1"]
... print(rg1.total_precip)
... rg1.total_precip = 0.2
... print(rg1.total_precip)
>>> 1.0
>>> 0.2
"""
return self._model.getGagePrecip(self._raingageid)[RainGageResults.total_precip.value]

@total_precip.setter
def total_precip(self, param):
"""Set Total Precipitation Rate (in/hr or mm/hr)."""
self._model.setGagePrecip(self._raingageid, param)

@property
def rainfall(self):
"""
Get raingage total rainfall rate (like in/hr or mm/hr).

:return: Parameter Value
:rtype: float

Examples:

>>> from pyswmm import Simulation, RainGages
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... rg1 = RainGages(sim)["Gage1"]
... print(rg1.rainfall)
>>> 1.0
"""
return self._model.getGagePrecip(self._raingageid)[RainGageResults.rainfall.value]

@property
def snowfall(self):
"""
Get raingage total snowfall rate (like in/hr or mm/hr).

:return: Parameter Value
:rtype: float

Examples:

>>> from pyswmm import Simulation, RainGages
>>>
>>> with Simulation('tests/data/TestModel1_weirSetting.inp') as sim:
... rg1 = RainGages(sim)["Gage1"]
... print(rg1.snowfall)
>>> 0.0
"""
return self._model.getGagePrecip(self._raingageid)[RainGageResults.snowfall.value]
73 changes: 68 additions & 5 deletions pyswmm/swmm5.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def _error_message(self, errcode):
errcode = ctypes.c_int(errcode)
_errmsg = ctypes.create_string_buffer(257)
self.SWMMlibobj.swmm_getAPIError(errcode, _errmsg)
print(_errmsg.value.decode("utf-8"))
#print(_errmsg.value.decode("utf-8"))
return _errmsg.value.decode("utf-8")

def _error_check(self, errcode):
Expand Down Expand Up @@ -669,11 +669,9 @@ def getObjectIDIndex(self, objecttype, ID):
C_ID = ctypes.c_char_p(six.b(ID))
index = ctypes.c_int()
errcode = self.SWMMlibobj.swmm_project_findObject(objecttype, C_ID, ctypes.byref(index))
self._error_check(errcode)
index = index.value
if index != -1:
return index
else:
raise Exception("ID Does Not Exist")
return index

def ObjectIDexist(self, objecttype, ID):
"""Check if Object ID Exists. Mostly used as an internal function."""
Expand Down Expand Up @@ -1076,6 +1074,7 @@ def setLidUParam(self, subcatchID, lidIndex, parameter, value):
lidIndex,
parameter,
_val)
self._error_check(errcode)

def getLidUOption(self, subcatchID, lidIndex, parameter):
"""
Expand Down Expand Up @@ -1226,6 +1225,48 @@ def getSubcatchOutConnection(self, ID):
outindex.value)

return (TYPELoadSurface.value, LoadID)
# =======================================================
# Rainfall API

def getGagePrecip(self, ID):
"""
Get precipitation from gage

This function returns the rainfall, show and total precipitation
associated with the gage

:param str ID: Gage ID
:return: (total, rainfall, snow)
:rtype: tuple

Examples:

>>> swmm_model = PySWMM(r'\\.inp',r'\\.rpt',r'\\.out')
>>> swmm_model.swmm_open()
>>> swmm_model.getGagePrecip('Gage1')
>>> 0.0 0.0 0.0
>>> swmm_model.swmm_close()

"""
index = self.getObjectIDIndex(tka.ObjectType.GAGE.value, ID)

result = ctypes.POINTER(ctypes.c_double * 3)()

precip_values = []

errcode = self.SWMMlibobj.swmm_getGagePrecip(index,
ctypes.byref(result))

for ind in range(3):
value = ctypes.cast(result, ctypes.POINTER(ctypes.c_double))[ind]
precip_values.append(value)

self._error_check(errcode)

freeresultarray = self.SWMMlibobj.freeArray
freeresultarray(ctypes.byref(result))

return precip_values

# --- Active Simulation Result "Getters"
# -------------------------------------------------------------------------
Expand Down Expand Up @@ -1914,6 +1955,28 @@ def setOutfallStage(self, ID, stage):
errcode = self.SWMMlibobj.swmm_setOutfallStage(index, q)
self._error_check(errcode)

def setGagePrecip(self, ID, value):
"""
Set precipitation to gage

This function sets the rainfall intensity to the gage

:param str ID: Gage ID
:param float valve: rainfall intensity
:return: errcode

Examples:

>>> swmm_model = PySWMM(r'\\.inp',r'\\.rpt',r'\\.out')
>>> swmm_model.swmm_open()
>>> swmm_model.setGagePrecip('Gage1', 10.0)
>>> swmm_model.swmm_close()

"""
index = self.getObjectIDIndex(tka.ObjectType.GAGE.value, ID)
val = ctypes.c_double(value)
errcode = self.SWMMlibobj.swmm_setGagePrecip(index, val)
self._error_check(errcode)

if __name__ == '__main__':
test = PySWMM(
Expand Down
4 changes: 4 additions & 0 deletions pyswmm/tests/data/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,12 @@
MODEL_STORAGE_PUMP = os.path.join(DATA_PATH, 'model_storage_pump.inp')
MODEL_STORAGE_PUMP_MGD = os.path.join(DATA_PATH, 'model_storage_pump_MGD.inp')
MODEL_POLLUTANTS_PATH = os.path.join(DATA_PATH, 'model_pollutants.inp')
MODEL_RAIN = os.path.join(DATA_PATH, 'model_rain.inp')
MODEL_LIDS_PATH = os.path.join(DATA_PATH, 'model_lids.inp')
MODEL_BAD_INPUT_PATH_1 = os.path.join(DATA_PATH, 'model_bad_input_1.inp')

WIN_SWMM_LIB_PATH = os.path.join(DATA_PATH, '..\\..\\lib\\windows',
'swmm5.dll')
if sys.maxsize > 2**32:
WIN_SWMM_LIB_PATH = os.path.join(DATA_PATH, '..\\..\\lib\\windows',
'swmm5-x64.dll')
Expand Down
Loading