Use of the wflow OpenStreams framework API

This ipython notebook demonstrates how to load an openstreams python model and execute it step-by-step and investigate the (intermediate) results. The first steps is to load the model and framework:


In [2]:
# First import the model. Here we use the HBV version
%pylab inline 

from wflow.wflow_hbv import *
import IPython
from IPython.display import display, clear_output

#clear_output = IPython.core.display.clear_output


---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-2-f439981457cf> in <module>()
      1 # First import the model. Here we use the HBV version
----> 2 get_ipython().magic(u'pylab inline')
      3 from wflow.wflow_hbv import *
      4 import IPython
      5 from IPython.display import display, clear_output

/home/jaap/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s)
   2305         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2306         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2307         return self.run_line_magic(magic_name, magic_arg_s)
   2308 
   2309     #-------------------------------------------------------------------------

/home/jaap/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)
   2226                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2227             with self.builtin_trap:
-> 2228                 result = fn(*args,**kwargs)
   2229             return result
   2230 

/home/jaap/anaconda/lib/python2.7/site-packages/IPython/core/magics/pylab.pyc in pylab(self, line)

/home/jaap/anaconda/lib/python2.7/site-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
    191     # but it's overkill for just that one bit of state.
    192     def magic_deco(arg):
--> 193         call = lambda f, *a, **k: f(*a, **k)
    194 
    195         if callable(arg):

/home/jaap/anaconda/lib/python2.7/site-packages/IPython/core/magics/pylab.pyc in pylab(self, line)
    142             import_all = not args.no_import_all
    143 
--> 144         gui, backend, clobbered = self.shell.enable_pylab(args.gui, import_all=import_all)
    145         self._show_matplotlib_backend(args.gui, backend)
    146         print ("Populating the interactive namespace from numpy and matplotlib")

/home/jaap/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in enable_pylab(self, gui, import_all, welcome_message)
   3138         from IPython.core.pylabtools import import_pylab
   3139 
-> 3140         gui, backend = self.enable_matplotlib(gui)
   3141 
   3142         # We want to prevent the loading of pylab to pollute the user's

/home/jaap/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in enable_matplotlib(self, gui)
   3099                 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
   3100 
-> 3101         pt.activate_matplotlib(backend)
   3102         pt.configure_inline_support(self, backend)
   3103 

/home/jaap/anaconda/lib/python2.7/site-packages/IPython/core/pylabtools.pyc in activate_matplotlib(backend)
    272     matplotlib.rcParams['backend'] = backend
    273 
--> 274     import matplotlib.pyplot
    275     matplotlib.pyplot.switch_backend(backend)
    276 

/home/jaap/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py in <module>()
    107 
    108 from matplotlib.backends import pylab_setup
--> 109 _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
    110 
    111 

/home/jaap/anaconda/lib/python2.7/site-packages/matplotlib/backends/__init__.pyc in pylab_setup()
     30     # imports. 0 means only perform absolute imports.
     31     backend_mod = __import__(backend_name,
---> 32                              globals(),locals(),[backend_name],0)
     33 
     34     # Things we pull in from all backends

/home/jaap/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py in <module>()
     15 from matplotlib.figure import Figure
     16 
---> 17 from .backend_qt5agg import NavigationToolbar2QTAgg
     18 from .backend_qt5agg import FigureCanvasQTAggBase
     19 

/home/jaap/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5agg.py in <module>()
     16 
     17 from .backend_agg import FigureCanvasAgg
---> 18 from .backend_qt5 import QtCore
     19 from .backend_qt5 import QtGui
     20 from .backend_qt5 import FigureManagerQT

/home/jaap/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py in <module>()
     29     figureoptions = None
     30 
---> 31 from .qt_compat import QtCore, QtGui, QtWidgets, _getSaveFileName, __version__
     32 from matplotlib.backends.qt_editor.formsubplottool import UiSubplotTool
     33 

/home/jaap/anaconda/lib/python2.7/site-packages/matplotlib/backends/qt_compat.py in <module>()
     89     if QT_API in [QT_API_PYQT, QT_API_PYQTv2]:  # PyQt4 API
     90 
---> 91         from PyQt4 import QtCore, QtGui
     92 
     93         try:

ImportError: /home/jaap/anaconda/lib/python2.7/site-packages/PyQt4/../../../libQtGui.so.4: undefined symbol: _ZN20QEventDispatcherGlib16staticMetaObjectE

Set model run-time parameters

Set the:

  • start and time time
  • set the runid (this is where the results are stored, relative to the casename)
  • set the name of the configfile (stire in the case directory
  • set the clone mape (usually the wflow_subcatch.map)
  • set the casename. This is where all the model the model resides

In [2]:
# define start and stop time of the run
startTime = 1
stopTime = 200
currentTime = 1
     
# set runid, cl;onemap and casename. Also define the ini file
runId = "memtest"
#configfile="wflow_hbv_mem.ini"
configfile="wflow_hbv.ini"
wflow_cloneMap = 'wflow_subcatch.map' 

# the casename points to the complete model setup with both static and dynamic input
caseName="../examples/wflow_rhine_hbv"

In [3]:
#make a usermodel object     
myModel = WflowModel(wflow_cloneMap, caseName,runId,configfile)

# initialise the framework
dynModelFw = wf_DynamicFramework(myModel, stopTime,startTime)

In [4]:
dynModelFw.createRunId(NoOverWrite=False,level=logging.ERROR)
dynModelFw.setQuiet(1)
# Run the initial part of the model (reads parameters and sets initial values)
dynModelFw._runInitial() # Runs initial part

In [5]:
dynModelFw._runResume() # gets the state variables from disk
# Get list of variables supplied by the model
print dynModelFw.wf_supplyVariableNamesAndRoles()


[['Altitude', 0, '2'], ['FreeWater', 2, '4'], ['SoilMoisture', 2, '4'], ['UpperZoneStorage', 2, '4'], ['LowerZoneStorage', 2, '4'], ['InterceptionStorage', 2, '4'], ['SurfaceRunoff', 2, '1'], ['WaterLevel', 2, '2'], ['Percolation', 1, '0']]

Investigate a couple of model variables


In [6]:
#
sm = dynModelFw.wf_supplyMapAsNumpy("SoilMoisture")
sm[sm == -999] = np.nan
uz = dynModelFw.wf_supplyMapAsNumpy("UpperZoneStorage")
uz[uz == -999] = np.nan
lz = dynModelFw.wf_supplyMapAsNumpy("LowerZoneStorage")
lz[lz == -999] = np.nan
imshow(sm)
title("Soilmoisture")
colorbar()


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-62431d7f832d> in <module>()
      1 #
      2 sm = dynModelFw.wf_supplyMapAsNumpy("SoilMoisture")
----> 3 sm[sm == -999] = np.nan
      4 uz = dynModelFw.wf_supplyMapAsNumpy("UpperZoneStorage")
      5 uz[uz == -999] = np.nan

NameError: name 'np' is not defined

In [41]:
imshow(uz)
title("UpperZoneStorage")
colorbar()


Out[41]:
<matplotlib.colorbar.Colorbar instance at 0x000000002214F188>

In [42]:
imshow(lz)
title("LowerZoneStorage")
colorbar()


Out[42]:
<matplotlib.colorbar.Colorbar instance at 0x000000000CD6EAC8>

In [9]:
dynModelFw.wf_setValueLdd("TopoLdd",5.0,6.46823,51.6821)
npmap0 = dynModelFw.wf_supplyMapAsNumpy("TopoLdd")
ltt = dynModelFw.wf_supplyMapAsList("SurfaceRunoff")


C:\Users\schelle\AppData\Local\Continuum\Anaconda\lib\site-packages\wflow\wflow_lib.py:528: RuntimeWarning: invalid value encountered in absolute
  col_ =  absolute(diffx) <= (XX[0,0] * tolerance)  # cellsize
C:\Users\schelle\AppData\Local\Continuum\Anaconda\lib\site-packages\wflow\wflow_lib.py:528: RuntimeWarning: invalid value encountered in less_equal
  col_ =  absolute(diffx) <= (XX[0,0] * tolerance)  # cellsize
C:\Users\schelle\AppData\Local\Continuum\Anaconda\lib\site-packages\wflow\wflow_lib.py:529: RuntimeWarning: invalid value encountered in absolute
  row_ =  absolute(diffy) <= (XX[0,0] * tolerance)# cellsize
C:\Users\schelle\AppData\Local\Continuum\Anaconda\lib\site-packages\wflow\wflow_lib.py:529: RuntimeWarning: invalid value encountered in less_equal
  row_ =  absolute(diffy) <= (XX[0,0] * tolerance)# cellsize

Run for a number of timesteps


In [43]:
f, ax = plt.subplots(1,3,figsize=(16, 6))

plotar = []

for ts in range(20,80):
         # Get value at pit
      
        inflowQ = dynModelFw.wf_supplyScalar("SurfaceRunoff",6.46823,51.6821)
        plotar.append(inflowQ)
        
        dynModelFw.wf_setValues("PET",scalar(2.0))
        
        dynModelFw._runDynamic(ts,ts) # runs for all timesteps
        npmap1 = dynModelFw.wf_supplyMapAsNumpy("P")
        run = dynModelFw.wf_supplyMapAsNumpy("SurfaceRunoff")
        uz = dynModelFw.wf_supplyMapAsNumpy("UpperZoneStorage")
        sm = dynModelFw.wf_supplyMapAsNumpy("SoilMoisture")
        
        sm[sm == -999] = np.nan
        #dynModelFw.wf_setValues("UpperZoneStorage",uz * 10.1)
        uz[uz == -999] = np.nan
        run[run == -999] = np.nan
        ax[0].imshow(uz)
        ax[1].imshow(sm)
        #ax[2].imshow(log(run))
        ax[2].plot(plotar,'b')
        ax[2].set_title(str(ts))
        clear_output()
        display(f)
        
plt.close()



In [11]:
dynModelFw._runSuspend() # saves the state variables
dynModelFw._wf_shutdown()

In [12]:
run = dynModelFw.wf_supplyMapAsNumpy("SurfaceRunoff")
run[run == -999] = np.nan

In [15]:
imshow(log(run))


Out[15]:
<matplotlib.image.AxesImage at 0x1505ba58>

In [ ]: