text_prompt
stringlengths 100
17.7k
⌀ | code_prompt
stringlengths 7
9.86k
⌀ |
---|---|
<SYSTEM_TASK:>
Before updating, the given names are checked to be valid
<END_TASK>
<USER_TASK:>
Description:
def update(self, *names: Any) -> None:
"""Before updating, the given names are checked to be valid
variable identifiers.
>>> from hydpy.core.devicetools import Keywords
>>> keywords = Keywords('first_keyword', 'second_keyword',
... 'keyword_3', 'keyword_4',
... 'keyboard')
>>> keywords.update('test_1', 'test 2') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: While trying to add the keyword `test 2` to device ?, \
the following error occurred: The given name string `test 2` does not \
define a valid variable identifier. ...
Note that even the first string (`test1`) is not added due to the
second one (`test 2`) being invalid.
>>> keywords
Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4",
"second_keyword")
After correcting the second string, everything works fine:
>>> keywords.update('test_1', 'test_2')
>>> keywords
Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4",
"second_keyword", "test_1", "test_2")
""" |
_names = [str(name) for name in names]
self._check_keywords(_names)
super().update(_names) |
<SYSTEM_TASK:>
Before adding a new name, it is checked to be valid variable
<END_TASK>
<USER_TASK:>
Description:
def add(self, name: Any) -> None:
"""Before adding a new name, it is checked to be valid variable
identifiers.
>>> from hydpy.core.devicetools import Keywords
>>> keywords = Keywords('first_keyword', 'second_keyword',
... 'keyword_3', 'keyword_4',
... 'keyboard')
>>> keywords.add('1_test') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: While trying to add the keyword `1_test` to device ?, \
the following error occurred: The given name string `1_test` does not \
define a valid variable identifier. ...
>>> keywords
Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4",
"second_keyword")
After correcting the string, everything works fine:
>>> keywords.add('one_test')
>>> keywords
Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4",
"one_test", "second_keyword")
""" |
self._check_keywords([str(name)])
super().add(str(name)) |
<SYSTEM_TASK:>
Add the given |Node| or |Element| object to the actual
<END_TASK>
<USER_TASK:>
Description:
def add_device(self, device: Union[DeviceType, str]) -> None:
"""Add the given |Node| or |Element| object to the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Nodes
>>> nodes = Nodes()
>>> nodes.add_device('old_node')
>>> nodes
Nodes("old_node")
>>> nodes.add_device('new_node')
>>> nodes
Nodes("new_node", "old_node")
Method |Devices.add_device| is disabled for immutable |Nodes|
and |Elements| objects:
>>> nodes.mutable = False
>>> nodes.add_device('newest_node')
Traceback (most recent call last):
...
RuntimeError: While trying to add the device `newest_node` to a \
Nodes object, the following error occurred: Adding devices to immutable \
Nodes objects is not allowed.
""" |
try:
if self.mutable:
_device = self.get_contentclass()(device)
self._name2device[_device.name] = _device
_id2devices[_device][id(self)] = self
else:
raise RuntimeError(
f'Adding devices to immutable '
f'{objecttools.classname(self)} objects is not allowed.')
except BaseException:
objecttools.augment_excmessage(
f'While trying to add the device `{device}` to a '
f'{objecttools.classname(self)} object') |
<SYSTEM_TASK:>
Remove the given |Node| or |Element| object from the actual
<END_TASK>
<USER_TASK:>
Description:
def remove_device(self, device: Union[DeviceType, str]) -> None:
"""Remove the given |Node| or |Element| object from the actual
|Nodes| or |Elements| object.
You can pass either a string or a device:
>>> from hydpy import Node, Nodes
>>> nodes = Nodes('node_x', 'node_y')
>>> node_x, node_y = nodes
>>> nodes.remove_device(Node('node_y'))
>>> nodes
Nodes("node_x")
>>> nodes.remove_device(Node('node_x'))
>>> nodes
Nodes()
>>> nodes.remove_device(Node('node_z'))
Traceback (most recent call last):
...
ValueError: While trying to remove the device `node_z` from a \
Nodes object, the following error occurred: The actual Nodes object does \
not handle such a device.
Method |Devices.remove_device| is disabled for immutable |Nodes|
and |Elements| objects:
>>> nodes.mutable = False
>>> nodes.remove_device('node_z')
Traceback (most recent call last):
...
RuntimeError: While trying to remove the device `node_z` from a \
Nodes object, the following error occurred: Removing devices from \
immutable Nodes objects is not allowed.
""" |
try:
if self.mutable:
_device = self.get_contentclass()(device)
try:
del self._name2device[_device.name]
except KeyError:
raise ValueError(
f'The actual {objecttools.classname(self)} '
f'object does not handle such a device.')
del _id2devices[_device][id(self)]
else:
raise RuntimeError(
f'Removing devices from immutable '
f'{objecttools.classname(self)} objects is not allowed.')
except BaseException:
objecttools.augment_excmessage(
f'While trying to remove the device `{device}` from a '
f'{objecttools.classname(self)} object') |
<SYSTEM_TASK:>
A set of all keywords of all handled devices.
<END_TASK>
<USER_TASK:>
Description:
def keywords(self) -> Set[str]:
"""A set of all keywords of all handled devices.
In addition to attribute access via device names, |Nodes| and
|Elements| objects allow for attribute access via keywords,
allowing for an efficient search of certain groups of devices.
Let us use the example from above, where the nodes `na` and `nb`
have no keywords, but each of the other three nodes both belongs
to either `group_a` or `group_b` and `group_1` or `group_2`:
>>> from hydpy import Node, Nodes
>>> nodes = Nodes('na',
... Node('nb', variable='W'),
... Node('nc', keywords=('group_a', 'group_1')),
... Node('nd', keywords=('group_a', 'group_2')),
... Node('ne', keywords=('group_b', 'group_1')))
>>> nodes
Nodes("na", "nb", "nc", "nd", "ne")
>>> sorted(nodes.keywords)
['group_1', 'group_2', 'group_a', 'group_b']
If you are interested in inspecting all devices belonging to
`group_a`, select them via this keyword:
>>> subgroup = nodes.group_1
>>> subgroup
Nodes("nc", "ne")
You can further restrict the search by also selecting the devices
belonging to `group_b`, which holds only for node "e", in the given
example:
>>> subsubgroup = subgroup.group_b
>>> subsubgroup
Node("ne", variable="Q",
keywords=["group_1", "group_b"])
Note that the keywords already used for building a device subgroup
are not informative anymore (as they hold for each device) and are
thus not shown anymore:
>>> sorted(subgroup.keywords)
['group_a', 'group_b']
The latter might be confusing if you intend to work with a device
subgroup for a longer time. After copying the subgroup, all
keywords of the contained devices are available again:
>>> from copy import copy
>>> newgroup = copy(subgroup)
>>> sorted(newgroup.keywords)
['group_1', 'group_a', 'group_b']
""" |
return set(keyword for device in self
for keyword in device.keywords if
keyword not in self._shadowed_keywords) |
<SYSTEM_TASK:>
Return a shallow copy of the actual |Nodes| or |Elements| object.
<END_TASK>
<USER_TASK:>
Description:
def copy(self: DevicesTypeBound) -> DevicesTypeBound:
"""Return a shallow copy of the actual |Nodes| or |Elements| object.
Method |Devices.copy| returns a semi-flat copy of |Nodes| or
|Elements| objects, due to their devices being not copyable:
>>> from hydpy import Nodes
>>> old = Nodes('x', 'y')
>>> import copy
>>> new = copy.copy(old)
>>> new == old
True
>>> new is old
False
>>> new.devices is old.devices
False
>>> new.x is new.x
True
Changing the |Device.name| of a device is recognised both by the
original and the copied collection objects:
>>> new.x.name = 'z'
>>> old.z
Node("z", variable="Q")
>>> new.z
Node("z", variable="Q")
Deep copying is permitted due to the above reason:
>>> copy.deepcopy(old)
Traceback (most recent call last):
...
NotImplementedError: Deep copying of Nodes objects is not supported, \
as it would require to make deep copies of the Node objects themselves, \
which is in conflict with using their names as identifiers.
""" |
new = type(self)()
vars(new).update(vars(self))
vars(new)['_name2device'] = copy.copy(self._name2device)
vars(new)['_shadowed_keywords'].clear()
for device in self:
_id2devices[device][id(new)] = new
return new |
<SYSTEM_TASK:>
Call method |Element.init_model| of all handle |Element| objects.
<END_TASK>
<USER_TASK:>
Description:
def init_models(self) -> None:
"""Call method |Element.init_model| of all handle |Element| objects.
We show, based the `LahnH` example project, that method
|Element.init_model| prepares the |Model| objects of all elements,
including building the required connections and updating the
derived parameters:
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, pub, TestIO
>>> with TestIO():
... hp = HydPy('LahnH')
... pub.timegrids = '1996-01-01', '1996-02-01', '1d'
... hp.prepare_network()
... hp.init_models()
>>> hp.elements.land_dill.model.parameters.derived.dt
dt(0.000833)
Wrong control files result in error messages like the following:
>>> with TestIO():
... with open('LahnH/control/default/land_dill.py', 'a') as file_:
... _ = file_.write('zonetype(-1)')
... hp.init_models() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
ValueError: While trying to initialise the model object of element \
`land_dill`, the following error occurred: While trying to load the control \
file `...land_dill.py`, the following error occurred: At least one value of \
parameter `zonetype` of element `?` is not valid.
By default, missing control files result in exceptions:
>>> del hp.elements.land_dill.model
>>> import os
>>> with TestIO():
... os.remove('LahnH/control/default/land_dill.py')
... hp.init_models() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
FileNotFoundError: While trying to initialise the model object of \
element `land_dill`, the following error occurred: While trying to load the \
control file `...land_dill.py`, the following error occurred: ...
>>> hasattr(hp.elements.land_dill, 'model')
False
When building new, still incomplete *HydPy* projects, this behaviour
can be annoying. After setting the option
|Options.warnmissingcontrolfile| to |False|, missing control files
only result in a warning:
>>> with TestIO():
... with pub.options.warnmissingcontrolfile(True):
... hp.init_models()
Traceback (most recent call last):
...
UserWarning: Due to a missing or no accessible control file, \
no model could be initialised for element `land_dill`
>>> hasattr(hp.elements.land_dill, 'model')
False
""" |
try:
for element in printtools.progressbar(self):
element.init_model(clear_registry=False)
finally:
hydpy.pub.controlmanager.clear_registry() |
<SYSTEM_TASK:>
Save the control parameters of the |Model| object handled by
<END_TASK>
<USER_TASK:>
Description:
def save_controls(self, parameterstep: 'timetools.PeriodConstrArg' = None,
simulationstep: 'timetools.PeriodConstrArg' = None,
auxfiler: 'Optional[auxfiletools.Auxfiler]' = None):
"""Save the control parameters of the |Model| object handled by
each |Element| object and eventually the ones handled by the
given |Auxfiler| object.""" |
if auxfiler:
auxfiler.save(parameterstep, simulationstep)
for element in printtools.progressbar(self):
element.model.parameters.save_controls(
parameterstep=parameterstep,
simulationstep=simulationstep,
auxfiler=auxfiler) |
<SYSTEM_TASK:>
Save the initial conditions of the |Model| object handled by
<END_TASK>
<USER_TASK:>
Description:
def load_conditions(self) -> None:
"""Save the initial conditions of the |Model| object handled by
each |Element| object.""" |
for element in printtools.progressbar(self):
element.model.sequences.load_conditions() |
<SYSTEM_TASK:>
Save the calculated conditions of the |Model| object handled by
<END_TASK>
<USER_TASK:>
Description:
def save_conditions(self) -> None:
"""Save the calculated conditions of the |Model| object handled by
each |Element| object.""" |
for element in printtools.progressbar(self):
element.model.sequences.save_conditions() |
<SYSTEM_TASK:>
A nested dictionary containing the values of all
<END_TASK>
<USER_TASK:>
Description:
def conditions(self) -> \
Dict[str, Dict[str, Dict[str, Union[float, numpy.ndarray]]]]:
"""A nested dictionary containing the values of all
|ConditionSequence| objects of all currently handled models.
See the documentation on property |HydPy.conditions| for further
information.
""" |
return {element.name: element.model.sequences.conditions
for element in self} |
<SYSTEM_TASK:>
Gather all "new" |Node| or |Element| objects.
<END_TASK>
<USER_TASK:>
Description:
def extract_new(cls) -> DevicesTypeUnbound:
"""Gather all "new" |Node| or |Element| objects.
See the main documentation on module |devicetools| for further
information.
""" |
devices = cls.get_handlerclass()(*_selection[cls])
_selection[cls].clear()
return devices |
<SYSTEM_TASK:>
Return the |Double| object appropriate for the given |Element|
<END_TASK>
<USER_TASK:>
Description:
def get_double(self, group: str) -> pointerutils.Double:
"""Return the |Double| object appropriate for the given |Element|
input or output group and the actual |Node.deploymode|.
Method |Node.get_double| should be of interest for framework
developers only (and eventually for model developers).
Let |Node| object `node1` handle different simulation and
observation values:
>>> from hydpy import Node
>>> node = Node('node1')
>>> node.sequences.sim = 1.0
>>> node.sequences.obs = 2.0
The following `test` function shows for a given |Node.deploymode|
if method |Node.get_double| either returns the |Double| object
handling the simulated value (1.0) or the |Double| object handling
the observed value (2.0):
>>> def test(deploymode):
... node.deploymode = deploymode
... for group in ('inlets', 'receivers', 'outlets', 'senders'):
... print(group, node.get_double(group))
In the default mode, nodes (passively) route simulated values
through offering the |Double| object of sequence |Sim| to all
|Element| input and output groups:
>>> test('newsim')
inlets 1.0
receivers 1.0
outlets 1.0
senders 1.0
Setting |Node.deploymode| to `obs` means that a node receives
simulated values (from group `outlets` or `senders`), but provides
observed values (to group `inlets` or `receivers`):
>>> test('obs')
inlets 2.0
receivers 2.0
outlets 1.0
senders 1.0
With |Node.deploymode| set to `oldsim`, the node provides
(previously) simulated values (to group `inlets` or `receivers`)
but does not receive any values. Method |Node.get_double| just
returns a dummy |Double| object with value 0.0 in this case
(for group `outlets` or `senders`):
>>> test('oldsim')
inlets 1.0
receivers 1.0
outlets 0.0
senders 0.0
Other |Element| input or output groups are not supported:
>>> node.get_double('test')
Traceback (most recent call last):
...
ValueError: Function `get_double` of class `Node` does not support \
the given group name `test`.
""" |
if group in ('inlets', 'receivers'):
if self.deploymode != 'obs':
return self.sequences.fastaccess.sim
return self.sequences.fastaccess.obs
if group in ('outlets', 'senders'):
if self.deploymode != 'oldsim':
return self.sequences.fastaccess.sim
return self.__blackhole
raise ValueError(
f'Function `get_double` of class `Node` does not '
f'support the given group name `{group}`.') |
<SYSTEM_TASK:>
Plot the |IOSequence.series| of the |Sim| sequence object.
<END_TASK>
<USER_TASK:>
Description:
def plot_simseries(self, **kwargs: Any) -> None:
"""Plot the |IOSequence.series| of the |Sim| sequence object.
See method |Node.plot_allseries| for further information.
""" |
self.__plot_series([self.sequences.sim], kwargs) |
<SYSTEM_TASK:>
Plot the |IOSequence.series| of the |Obs| sequence object.
<END_TASK>
<USER_TASK:>
Description:
def plot_obsseries(self, **kwargs: Any) -> None:
"""Plot the |IOSequence.series| of the |Obs| sequence object.
See method |Node.plot_allseries| for further information.
""" |
self.__plot_series([self.sequences.obs], kwargs) |
<SYSTEM_TASK:>
The |Model| object handled by the actual |Element| object.
<END_TASK>
<USER_TASK:>
Description:
def model(self) -> 'modeltools.Model':
"""The |Model| object handled by the actual |Element| object.
Directly after their initialisation, elements do not know
which model they require:
>>> from hydpy import Element
>>> hland = Element('hland', outlets='outlet')
>>> hland.model
Traceback (most recent call last):
...
AttributeError: The model object of element `hland` has been \
requested but not been prepared so far.
During scripting and when working interactively in the Python
shell, it is often convenient to assign a |model| directly.
>>> from hydpy.models.hland_v1 import *
>>> parameterstep('1d')
>>> hland.model = model
>>> hland.model.name
'hland_v1'
>>> del hland.model
>>> hasattr(hland, 'model')
False
For the "usual" approach to prepare models, please see the method
|Element.init_model|.
The following examples show that assigning |Model| objects
to property |Element.model| creates some connection required by
the respective model type automatically . These
examples should be relevant for developers only.
The following |hbranch| model branches a single input value
(from to node `inp`) to multiple outputs (nodes `out1` and `out2`):
>>> from hydpy import Element, Node, reverse_model_wildcard_import
>>> reverse_model_wildcard_import()
>>> element = Element('a_branch',
... inlets='branch_input',
... outlets=('branch_output_1', 'branch_output_2'))
>>> inp = element.inlets.branch_input
>>> out1, out2 = element.outlets
>>> from hydpy.models.hbranch import *
>>> parameterstep()
>>> xpoints(0.0, 3.0)
>>> ypoints(branch_output_1=[0.0, 1.0], branch_output_2=[0.0, 2.0])
>>> parameters.update()
>>> element.model = model
To show that the inlet and outlet connections are built properly,
we assign a new value to the inlet node `inp` and verify that the
suitable fractions of this value are passed to the outlet nodes
out1` and `out2` by calling method |Model.doit|:
>>> inp.sequences.sim = 999.0
>>> model.doit(0)
>>> fluxes.input
input(999.0)
>>> out1.sequences.sim
sim(333.0)
>>> out2.sequences.sim
sim(666.0)
""" |
model = vars(self).get('model')
if model:
return model
raise AttributeError(
f'The model object of element `{self.name}` has '
f'been requested but not been prepared so far.') |
<SYSTEM_TASK:>
A set of all different |Node.variable| values of the |Node|
<END_TASK>
<USER_TASK:>
Description:
def variables(self) -> Set[str]:
"""A set of all different |Node.variable| values of the |Node|
objects directly connected to the actual |Element| object.
Suppose there is an element connected to five nodes, which (partly)
represent different variables:
>>> from hydpy import Element, Node
>>> element = Element('Test',
... inlets=(Node('N1', 'X'), Node('N2', 'Y1')),
... outlets=(Node('N3', 'X'), Node('N4', 'Y2')),
... receivers=(Node('N5', 'X'), Node('N6', 'Y3')),
... senders=(Node('N7', 'X'), Node('N8', 'Y4')))
Property |Element.variables| puts all the different variables of
these nodes together:
>>> sorted(element.variables)
['X', 'Y1', 'Y2', 'Y3', 'Y4']
""" |
variables: Set[str] = set()
for connection in self.__connections:
variables.update(connection.variables)
return variables |
<SYSTEM_TASK:>
Prepare the |IOSequence.series| objects of all `input`, `flux` and
<END_TASK>
<USER_TASK:>
Description:
def prepare_allseries(self, ramflag: bool = True) -> None:
"""Prepare the |IOSequence.series| objects of all `input`, `flux` and
`state` sequences of the model handled by this element.
Call this method before a simulation run, if you need access to
(nearly) all simulated series of the handled model after the
simulation run is finished.
By default, the time series are stored in RAM, which is the faster
option. If your RAM is limited, pass |False| to function argument
`ramflag` to store the series on disk.
""" |
self.prepare_inputseries(ramflag)
self.prepare_fluxseries(ramflag)
self.prepare_stateseries(ramflag) |
<SYSTEM_TASK:>
Plot the `flux` series of the handled model.
<END_TASK>
<USER_TASK:>
Description:
def plot_fluxseries(
self, names: Optional[Iterable[str]] = None,
average: bool = False, **kwargs: Any) \
-> None:
"""Plot the `flux` series of the handled model.
See the documentation on method |Element.plot_inputseries| for
additional information.
""" |
self.__plot(self.model.sequences.fluxes, names, average, kwargs) |
<SYSTEM_TASK:>
Plot the `state` series of the handled model.
<END_TASK>
<USER_TASK:>
Description:
def plot_stateseries(
self, names: Optional[Iterable[str]] = None,
average: bool = False, **kwargs: Any) \
-> None:
"""Plot the `state` series of the handled model.
See the documentation on method |Element.plot_inputseries| for
additional information.
""" |
self.__plot(self.model.sequences.states, names, average, kwargs) |
<SYSTEM_TASK:>
Convert all pure Python calculation functions of the model class to
<END_TASK>
<USER_TASK:>
Description:
def _init_methods(self):
"""Convert all pure Python calculation functions of the model class to
methods and assign them to the model instance.
""" |
for name_group in self._METHOD_GROUPS:
functions = getattr(self, name_group, ())
uniques = {}
for func in functions:
name_func = func.__name__
method = types.MethodType(func, self)
setattr(self, name_func, method)
shortname = '_'.join(name_func.split('_')[:-1])
if shortname in uniques:
uniques[shortname] = None
else:
uniques[shortname] = method
for (shortname, method) in uniques.items():
if method is not None:
setattr(self, shortname, method) |
<SYSTEM_TASK:>
Name of the model type.
<END_TASK>
<USER_TASK:>
Description:
def name(self):
"""Name of the model type.
For base models, |Model.name| corresponds to the package name:
>>> from hydpy import prepare_model
>>> hland = prepare_model('hland')
>>> hland.name
'hland'
For application models, |Model.name| corresponds the module name:
>>> hland_v1 = prepare_model('hland_v1')
>>> hland_v1.name
'hland_v1'
This last example has only technical reasons:
>>> hland.name
'hland'
""" |
name = self.__name
if name:
return name
subs = self.__module__.split('.')
if len(subs) == 2:
type(self).__name = subs[1]
else:
type(self).__name = subs[2]
return self.__name |
<SYSTEM_TASK:>
Connect the link sequences of the actual model.
<END_TASK>
<USER_TASK:>
Description:
def connect(self):
"""Connect the link sequences of the actual model.""" |
try:
for group in ('inlets', 'receivers', 'outlets', 'senders'):
self._connect_subgroup(group)
except BaseException:
objecttools.augment_excmessage(
'While trying to build the node connection of the `%s` '
'sequences of the model handled by element `%s`'
% (group[:-1], objecttools.devicename(self))) |
<SYSTEM_TASK:>
Apply all methods stored in the hidden attribute
<END_TASK>
<USER_TASK:>
Description:
def calculate_single_terms(self):
"""Apply all methods stored in the hidden attribute
`PART_ODE_METHODS`.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> k(0.25)
>>> states.s = 1.0
>>> model.calculate_single_terms()
>>> fluxes.q
q(0.25)
""" |
self.numvars.nmb_calls = self.numvars.nmb_calls+1
for method in self.PART_ODE_METHODS:
method(self) |
<SYSTEM_TASK:>
Get the sum of the fluxes calculated so far.
<END_TASK>
<USER_TASK:>
Description:
def get_sum_fluxes(self):
"""Get the sum of the fluxes calculated so far.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> fluxes.q = 0.0
>>> fluxes.fastaccess._q_sum = 1.0
>>> model.get_sum_fluxes()
>>> fluxes.q
q(1.0)
""" |
fluxes = self.sequences.fluxes
for flux in fluxes.numerics:
flux(getattr(fluxes.fastaccess, '_%s_sum' % flux.name)) |
<SYSTEM_TASK:>
Perform a dot multiplication between the fluxes and the
<END_TASK>
<USER_TASK:>
Description:
def integrate_fluxes(self):
"""Perform a dot multiplication between the fluxes and the
A coefficients associated with the different stages of the
actual method.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> model.numvars.idx_method = 2
>>> model.numvars.idx_stage = 1
>>> model.numvars.dt = 0.5
>>> points = numpy.asarray(fluxes.fastaccess._q_points)
>>> points[:4] = 15., 2., -999., 0.
>>> model.integrate_fluxes()
>>> from hydpy import round_
>>> from hydpy import pub
>>> round_(numpy.asarray(model.numconsts.a_coefs)[1, 1, :2])
0.375, 0.125
>>> fluxes.q
q(2.9375)
""" |
fluxes = self.sequences.fluxes
for flux in fluxes.numerics:
points = getattr(fluxes.fastaccess, '_%s_points' % flux.name)
coefs = self.numconsts.a_coefs[self.numvars.idx_method-1,
self.numvars.idx_stage,
:self.numvars.idx_method]
flux(self.numvars.dt *
numpy.dot(coefs, points[:self.numvars.idx_method])) |
<SYSTEM_TASK:>
Set the sum of the fluxes calculated so far to zero.
<END_TASK>
<USER_TASK:>
Description:
def reset_sum_fluxes(self):
"""Set the sum of the fluxes calculated so far to zero.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> fluxes.fastaccess._q_sum = 5.
>>> model.reset_sum_fluxes()
>>> fluxes.fastaccess._q_sum
0.0
""" |
fluxes = self.sequences.fluxes
for flux in fluxes.numerics:
if flux.NDIM == 0:
setattr(fluxes.fastaccess, '_%s_sum' % flux.name, 0.)
else:
getattr(fluxes.fastaccess, '_%s_sum' % flux.name)[:] = 0. |
<SYSTEM_TASK:>
Add up the sum of the fluxes calculated so far.
<END_TASK>
<USER_TASK:>
Description:
def addup_fluxes(self):
"""Add up the sum of the fluxes calculated so far.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> fluxes.fastaccess._q_sum = 1.0
>>> fluxes.q(2.0)
>>> model.addup_fluxes()
>>> fluxes.fastaccess._q_sum
3.0
""" |
fluxes = self.sequences.fluxes
for flux in fluxes.numerics:
sum_ = getattr(fluxes.fastaccess, '_%s_sum' % flux.name)
sum_ += flux
if flux.NDIM == 0:
setattr(fluxes.fastaccess, '_%s_sum' % flux.name, sum_) |
<SYSTEM_TASK:>
Estimate the numerical error based on the fluxes calculated
<END_TASK>
<USER_TASK:>
Description:
def calculate_error(self):
"""Estimate the numerical error based on the fluxes calculated
by the current and the last method.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> model.numvars.idx_method = 2
>>> results = numpy.asarray(fluxes.fastaccess._q_results)
>>> results[:4] = 0., 3., 4., 0.
>>> model.calculate_error()
>>> from hydpy import round_
>>> round_(model.numvars.error)
1.0
""" |
self.numvars.error = 0.
fluxes = self.sequences.fluxes
for flux in fluxes.numerics:
results = getattr(fluxes.fastaccess, '_%s_results' % flux.name)
diff = (results[self.numvars.idx_method] -
results[self.numvars.idx_method-1])
self.numvars.error = max(self.numvars.error,
numpy.max(numpy.abs(diff))) |
<SYSTEM_TASK:>
Estimate the numerical error to be expected when applying all
<END_TASK>
<USER_TASK:>
Description:
def extrapolate_error(self):
"""Estimate the numerical error to be expected when applying all
methods available based on the results of the current and the
last method.
Note that this expolation strategy cannot be applied on the first
method. If the current method is the first one, `-999.9` is returned.
>>> from hydpy.models.test_v1 import *
>>> parameterstep()
>>> model.numvars.error = 1e-2
>>> model.numvars.last_error = 1e-1
>>> model.numvars.idx_method = 10
>>> model.extrapolate_error()
>>> from hydpy import round_
>>> round_(model.numvars.extrapolated_error)
0.01
>>> model.numvars.idx_method = 9
>>> model.extrapolate_error()
>>> round_(model.numvars.extrapolated_error)
0.001
""" |
if self.numvars.idx_method > 2:
self.numvars.extrapolated_error = modelutils.exp(
modelutils.log(self.numvars.error) +
(modelutils.log(self.numvars.error) -
modelutils.log(self.numvars.last_error)) *
(self.numconsts.nmb_methods-self.numvars.idx_method))
else:
self.numvars.extrapolated_error = -999.9 |
<SYSTEM_TASK:>
Perform a HydPy workflow in agreement with the given XML configuration
<END_TASK>
<USER_TASK:>
Description:
def run_simulation(projectname: str, xmlfile: str):
"""Perform a HydPy workflow in agreement with the given XML configuration
file available in the directory of the given project. ToDo
Function |run_simulation| is a "script function" and is normally used as
explained in the main documentation on module |xmltools|.
""" |
write = commandtools.print_textandtime
hydpy.pub.options.printprogress = False
write(f'Start HydPy project `{projectname}`')
hp = hydpytools.HydPy(projectname)
write(f'Read configuration file `{xmlfile}`')
interface = XMLInterface(xmlfile)
write('Interpret the defined options')
interface.update_options()
hydpy.pub.options.printprogress = False
write('Interpret the defined period')
interface.update_timegrids()
write('Read all network files')
hp.prepare_network()
write('Activate the selected network')
hp.update_devices(interface.fullselection)
write('Read the required control files')
hp.init_models()
write('Read the required condition files')
interface.conditions_io.load_conditions()
write('Read the required time series files')
interface.series_io.prepare_series()
interface.series_io.load_series()
write('Perform the simulation run')
hp.doit()
write('Write the desired condition files')
interface.conditions_io.save_conditions()
write('Write the desired time series files')
interface.series_io.save_series() |
<SYSTEM_TASK:>
Raise an error if the actual XML does not agree with one of the
<END_TASK>
<USER_TASK:>
Description:
def validate_xml(self) -> None:
"""Raise an error if the actual XML does not agree with one of the
available schema files.
# ToDo: should it be accompanied by a script function?
The first example relies on a distorted version of the configuration
file `single_run.xml`:
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import TestIO, xml_replace
>>> from hydpy.auxs.xmltools import XMLInterface
>>> import os
>>> with TestIO(): # doctest: +ELLIPSIS
... xml_replace('LahnH/single_run',
... firstdate='1996-01-32T00:00:00')
template file: LahnH/single_run.xmlt
target file: LahnH/single_run.xml
replacements:
config_start --> <...HydPyConfigBase.xsd"
...HydPyConfigSingleRun.xsd"> (default argument)
firstdate --> 1996-01-32T00:00:00 (given argument)
zip_ --> false (default argument)
zip_ --> false (default argument)
config_end --> </hpcsr:config> (default argument)
>>> with TestIO():
... interface = XMLInterface('single_run.xml', 'LahnH')
>>> interface.validate_xml() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
hydpy.core.objecttools.xmlschema.validators.exceptions.\
XMLSchemaDecodeError: While trying to validate XML file `...single_run.xml`, \
the following error occurred: failed validating '1996-01-32T00:00:00' with \
XsdAtomicBuiltin(name='xs:dateTime').
...
Reason: day is out of range for month
...
Schema:
...
Instance:
...
<firstdate xmlns="https://github.com/hydpy-dev/hydpy/releases/\
download/your-hydpy-version/HydPyConfigBase.xsd">1996-01-32T00:00:00</firstdate>
...
Path: /hpcsr:config/timegrid/firstdate
...
In the second example, we examine a correct configuration file:
>>> with TestIO(): # doctest: +ELLIPSIS
... xml_replace('LahnH/single_run')
... interface = XMLInterface('single_run.xml', 'LahnH')
template file: LahnH/single_run.xmlt
target file: LahnH/single_run.xml
replacements:
config_start --> <...HydPyConfigBase.xsd"
...HydPyConfigSingleRun.xsd"> (default argument)
firstdate --> 1996-01-01T00:00:00 (default argument)
zip_ --> false (default argument)
zip_ --> false (default argument)
config_end --> </hpcsr:config> (default argument)
>>> interface.validate_xml()
The XML configuration file must correctly refer to the corresponding
schema file:
>>> with TestIO(): # doctest: +ELLIPSIS
... xml_replace('LahnH/single_run',
... config_start='<config>',
... config_end='</config>')
... interface = XMLInterface('single_run.xml', 'LahnH')
template file: LahnH/single_run.xmlt
target file: LahnH/single_run.xml
replacements:
config_start --> <config> (given argument)
firstdate --> 1996-01-01T00:00:00 (default argument)
zip_ --> false (default argument)
zip_ --> false (default argument)
config_end --> </config> (given argument)
>>> interface.validate_xml() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
RuntimeError: While trying to validate XML file `...single_run.xml`, \
the following error occurred: Configuration file `single_run.xml` does not \
correctly refer to one of the available XML schema files \
(HydPyConfigSingleRun.xsd and HydPyConfigMultipleRuns.xsd).
XML files based on `HydPyConfigMultipleRuns.xsd` can be validated
as well:
>>> with TestIO():
... interface = XMLInterface('multiple_runs.xml', 'LahnH')
>>> interface.validate_xml() # doctest: +ELLIPSIS
""" |
try:
filenames = ('HydPyConfigSingleRun.xsd',
'HydPyConfigMultipleRuns.xsd')
for name in filenames:
if name in self.root.tag:
schemafile = name
break
else:
raise RuntimeError(
f'Configuration file `{os.path.split(self.filepath)[-1]}` '
f'does not correctly refer to one of the available XML '
f'schema files ({objecttools.enumeration(filenames)}).')
schemapath = os.path.join(conf.__path__[0], schemafile)
schema = xmlschema.XMLSchema(schemapath)
schema.validate(self.filepath)
except BaseException:
objecttools.augment_excmessage(
f'While trying to validate XML file `{self.filepath}`') |
<SYSTEM_TASK:>
Update the |Options| object available in module |pub| with the
<END_TASK>
<USER_TASK:>
Description:
def update_options(self) -> None:
"""Update the |Options| object available in module |pub| with the
values defined in the `options` XML element.
>>> from hydpy.auxs.xmltools import XMLInterface
>>> from hydpy import data, pub
>>> interface = XMLInterface('single_run.xml', data.get_path('LahnH'))
>>> pub.options.printprogress = True
>>> pub.options.printincolor = True
>>> pub.options.reprdigits = -1
>>> pub.options.utcoffset = -60
>>> pub.options.ellipsis = 0
>>> pub.options.warnsimulationstep = 0
>>> interface.update_options()
>>> pub.options
Options(
autocompile -> 1
checkseries -> 1
dirverbose -> 0
ellipsis -> 0
forcecompiling -> 0
printprogress -> 0
printincolor -> 0
reprcomments -> 0
reprdigits -> 6
skipdoctests -> 0
trimvariables -> 1
usecython -> 1
usedefaultvalues -> 0
utcoffset -> 60
warnmissingcontrolfile -> 0
warnmissingobsfile -> 1
warnmissingsimfile -> 1
warnsimulationstep -> 0
warntrim -> 1
flattennetcdf -> True
isolatenetcdf -> True
timeaxisnetcdf -> 0
)
>>> pub.options.printprogress = False
>>> pub.options.reprdigits = 6
""" |
options = hydpy.pub.options
for option in self.find('options'):
value = option.text
if value in ('true', 'false'):
value = value == 'true'
setattr(options, strip(option.tag), value)
options.printprogress = False
options.printincolor = False |
<SYSTEM_TASK:>
Update the |Timegrids| object available in module |pub| with the
<END_TASK>
<USER_TASK:>
Description:
def update_timegrids(self) -> None:
"""Update the |Timegrids| object available in module |pub| with the
values defined in the `timegrid` XML element.
Usually, one would prefer to define `firstdate`, `lastdate`, and
`stepsize` elements as in the XML configuration file of the
`LahnH` example project:
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, pub, TestIO
>>> from hydpy.auxs.xmltools import XMLInterface
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.prepare_network()
... XMLInterface('single_run.xml').update_timegrids()
>>> pub.timegrids
Timegrids(Timegrid('1996-01-01T00:00:00',
'1996-01-06T00:00:00',
'1d'))
Alternatively, one can provide the file path to a `seriesfile`,
which must be a valid NetCDF file. The |XMLInterface| object
then interprets the file's time information:
>>> name = 'LahnH/series/input/hland_v1_input_p.nc'
>>> with TestIO():
... with open('LahnH/single_run.xml') as file_:
... lines = file_.readlines()
... for idx, line in enumerate(lines):
... if '<timegrid>' in line:
... break
... with open('LahnH/single_run.xml', 'w') as file_:
... _ = file_.write(''.join(lines[:idx+1]))
... _ = file_.write(
... f' <seriesfile>{name}</seriesfile>\\n')
... _ = file_.write(''.join(lines[idx+4:]))
... XMLInterface('single_run.xml').update_timegrids()
>>> pub.timegrids
Timegrids(Timegrid('1996-01-01 00:00:00',
'2007-01-01 00:00:00',
'1d'))
""" |
timegrid_xml = self.find('timegrid')
try:
timegrid = timetools.Timegrid(
*(timegrid_xml[idx].text for idx in range(3)))
hydpy.pub.timegrids = timetools.Timegrids(timegrid)
except IndexError:
seriesfile = find(timegrid_xml, 'seriesfile').text
with netcdf4.Dataset(seriesfile) as ncfile:
hydpy.pub.timegrids = timetools.Timegrids(
netcdftools.query_timegrid(ncfile)) |
<SYSTEM_TASK:>
Yield all |Element| objects returned by |XMLInterface.selections|
<END_TASK>
<USER_TASK:>
Description:
def elements(self) -> Iterator[devicetools.Element]:
"""Yield all |Element| objects returned by |XMLInterface.selections|
and |XMLInterface.devices| without duplicates.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.prepare_network()
... interface = XMLInterface('single_run.xml')
>>> interface.find('selections').text = 'headwaters streams'
>>> for element in interface.elements:
... print(element.name)
land_dill
land_lahn_1
stream_dill_lahn_2
stream_lahn_1_lahn_2
stream_lahn_2_lahn_3
""" |
selections = copy.copy(self.selections)
selections += self.devices
elements = set()
for selection in selections:
for element in selection.elements:
if element not in elements:
elements.add(element)
yield element |
<SYSTEM_TASK:>
A |Selection| object containing all |Element| and |Node| objects
<END_TASK>
<USER_TASK:>
Description:
def fullselection(self) -> selectiontools.Selection:
"""A |Selection| object containing all |Element| and |Node| objects
defined by |XMLInterface.selections| and |XMLInterface.devices|.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.prepare_network()
... interface = XMLInterface('single_run.xml')
>>> interface.find('selections').text = 'nonheadwaters'
>>> interface.fullselection
Selection("fullselection",
nodes=("dill", "lahn_2", "lahn_3"),
elements=("land_dill", "land_lahn_1", "land_lahn_2",
"land_lahn_3"))
""" |
fullselection = selectiontools.Selection('fullselection')
for selection in self.selections:
fullselection += selection
fullselection += self.devices
return fullselection |
<SYSTEM_TASK:>
Call |XMLSubseries.prepare_series| of all |XMLSubseries|
<END_TASK>
<USER_TASK:>
Description:
def prepare_series(self) -> None:
# noinspection PyUnresolvedReferences
"""Call |XMLSubseries.prepare_series| of all |XMLSubseries|
objects with the same memory |set| object.
>>> from hydpy.auxs.xmltools import XMLInterface, XMLSubseries
>>> from hydpy import data
>>> interface = XMLInterface('single_run.xml', data.get_path('LahnH'))
>>> series_io = interface.series_io
>>> from unittest import mock
>>> prepare_series = XMLSubseries.prepare_series
>>> XMLSubseries.prepare_series = mock.MagicMock()
>>> series_io.prepare_series()
>>> args = XMLSubseries.prepare_series.call_args_list
>>> len(args) == len(series_io.readers) + len(series_io.writers)
True
>>> args[0][0][0]
set()
>>> args[0][0][0] is args[-1][0][0]
True
>>> XMLSubseries.prepare_series = prepare_series
""" |
memory = set()
for output in itertools.chain(self.readers, self.writers):
output.prepare_series(memory) |
<SYSTEM_TASK:>
The |Selections| object defined for the respective `reader`
<END_TASK>
<USER_TASK:>
Description:
def selections(self) -> selectiontools.Selections:
"""The |Selections| object defined for the respective `reader`
or `writer` element of the actual XML file. ToDo
If the `reader` or `writer` element does not define a special
selections element, the general |XMLInterface.selections| element
of |XMLInterface| is used.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.prepare_network()
... hp.init_models()
... interface = XMLInterface('single_run.xml')
>>> series_io = interface.series_io
>>> for seq in (series_io.readers + series_io.writers):
... print(seq.info, seq.selections.names)
all input data ()
precipitation ('headwaters',)
soilmoisture ('complete',)
averaged ('complete',)
""" |
selections = self.find('selections')
master = self
while selections is None:
master = master.master
selections = master.find('selections')
return _query_selections(selections) |
<SYSTEM_TASK:>
The additional devices defined for the respective `reader`
<END_TASK>
<USER_TASK:>
Description:
def devices(self) -> selectiontools.Selection:
"""The additional devices defined for the respective `reader`
or `writer` element contained within a |Selection| object. ToDo
If the `reader` or `writer` element does not define its own additional
devices, |XMLInterface.devices| of |XMLInterface| is used.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.prepare_network()
... interface = XMLInterface('single_run.xml')
>>> series_io = interface.series_io
>>> for seq in (series_io.readers + series_io.writers):
... print(seq.info, seq.devices.nodes, seq.devices.elements)
all input data Nodes() \
Elements("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3")
precipitation Nodes() Elements("land_lahn_1", "land_lahn_2")
soilmoisture Nodes("dill") Elements("land_dill", "land_lahn_1")
averaged Nodes() Elements()
""" |
devices = self.find('devices')
master = self
while devices is None:
master = master.master
devices = master.find('devices')
return _query_devices(devices) |
<SYSTEM_TASK:>
Configure the |SequenceManager| object available in module
<END_TASK>
<USER_TASK:>
Description:
def prepare_sequencemanager(self) -> None:
"""Configure the |SequenceManager| object available in module
|pub| following the definitions of the actual XML `reader` or
`writer` element when available; if not use those of the XML
`series_io` element.
Compare the following results with `single_run.xml` to see that the
first `writer` element defines the input file type specifically,
that the second `writer` element defines a general file type, and
that the third `writer` element does not define any file type (the
principle mechanism is the same for other options, e.g. the
aggregation mode):
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface, pub
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.prepare_network()
... interface = XMLInterface('single_run.xml')
>>> series_io = interface.series_io
>>> with TestIO():
... series_io.writers[0].prepare_sequencemanager()
>>> pub.sequencemanager.inputfiletype
'asc'
>>> pub.sequencemanager.fluxfiletype
'npy'
>>> pub.sequencemanager.fluxaggregation
'none'
>>> with TestIO():
... series_io.writers[1].prepare_sequencemanager()
>>> pub.sequencemanager.statefiletype
'nc'
>>> pub.sequencemanager.stateoverwrite
False
>>> with TestIO():
... series_io.writers[2].prepare_sequencemanager()
>>> pub.sequencemanager.statefiletype
'npy'
>>> pub.sequencemanager.fluxaggregation
'mean'
>>> pub.sequencemanager.inputoverwrite
True
>>> pub.sequencemanager.inputdirpath
'LahnH/series/input'
""" |
for config, convert in (
('filetype', lambda x: x),
('aggregation', lambda x: x),
('overwrite', lambda x: x.lower() == 'true'),
('dirpath', lambda x: x)):
xml_special = self.find(config)
xml_general = self.master.find(config)
for name_manager, name_xml in zip(
('input', 'flux', 'state', 'node'),
('inputs', 'fluxes', 'states', 'nodes')):
value = None
for xml, attr_xml in zip(
(xml_special, xml_special, xml_general, xml_general),
(name_xml, 'general', name_xml, 'general')):
try:
value = find(xml, attr_xml).text
except AttributeError:
continue
break
setattr(hydpy.pub.sequencemanager,
f'{name_manager}{config}',
convert(value)) |
<SYSTEM_TASK:>
A nested |collections.defaultdict| containing the model specific
<END_TASK>
<USER_TASK:>
Description:
def model2subs2seqs(self) -> Dict[str, Dict[str, List[str]]]:
"""A nested |collections.defaultdict| containing the model specific
information provided by the XML `sequences` element.
>>> from hydpy.auxs.xmltools import XMLInterface
>>> from hydpy import data
>>> interface = XMLInterface('single_run.xml', data.get_path('LahnH'))
>>> series_io = interface.series_io
>>> model2subs2seqs = series_io.writers[2].model2subs2seqs
>>> for model, subs2seqs in sorted(model2subs2seqs.items()):
... for subs, seq in sorted(subs2seqs.items()):
... print(model, subs, seq)
hland_v1 fluxes ['pc', 'tf']
hland_v1 states ['sm']
hstream_v1 states ['qjoints']
""" |
model2subs2seqs = collections.defaultdict(
lambda: collections.defaultdict(list))
for model in self.find('sequences'):
model_name = strip(model.tag)
if model_name == 'node':
continue
for group in model:
group_name = strip(group.tag)
for sequence in group:
seq_name = strip(sequence.tag)
model2subs2seqs[model_name][group_name].append(seq_name)
return model2subs2seqs |
<SYSTEM_TASK:>
A |collections.defaultdict| containing the node-specific
<END_TASK>
<USER_TASK:>
Description:
def subs2seqs(self) -> Dict[str, List[str]]:
"""A |collections.defaultdict| containing the node-specific
information provided by XML `sequences` element.
>>> from hydpy.auxs.xmltools import XMLInterface
>>> from hydpy import data
>>> interface = XMLInterface('single_run.xml', data.get_path('LahnH'))
>>> series_io = interface.series_io
>>> subs2seqs = series_io.writers[2].subs2seqs
>>> for subs, seq in sorted(subs2seqs.items()):
... print(subs, seq)
node ['sim', 'obs']
""" |
subs2seqs = collections.defaultdict(list)
nodes = find(self.find('sequences'), 'node')
if nodes is not None:
for seq in nodes:
subs2seqs['node'].append(strip(seq.tag))
return subs2seqs |
<SYSTEM_TASK:>
Call |IOSequence.activate_ram| of all sequences selected by
<END_TASK>
<USER_TASK:>
Description:
def prepare_series(self, memory: set) -> None:
"""Call |IOSequence.activate_ram| of all sequences selected by
the given output element of the actual XML file.
Use the memory argument to pass in already prepared sequences;
newly prepared sequences will be added.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.prepare_network()
... hp.init_models()
... interface = XMLInterface('single_run.xml')
>>> interface.update_timegrids()
>>> series_io = interface.series_io
>>> memory = set()
>>> pc = hp.elements.land_dill.model.sequences.fluxes.pc
>>> pc.ramflag
False
>>> series_io.writers[0].prepare_series(memory)
>>> pc in memory
True
>>> pc.ramflag
True
>>> pc.deactivate_ram()
>>> pc.ramflag
False
>>> series_io.writers[0].prepare_series(memory)
>>> pc.ramflag
False
""" |
for sequence in self._iterate_sequences():
if sequence not in memory:
memory.add(sequence)
sequence.activate_ram() |
<SYSTEM_TASK:>
Load time series data as defined by the actual XML `reader`
<END_TASK>
<USER_TASK:>
Description:
def load_series(self) -> None:
"""Load time series data as defined by the actual XML `reader`
element.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.prepare_network()
... hp.init_models()
... interface = XMLInterface('single_run.xml')
... interface.update_options()
... interface.update_timegrids()
... series_io = interface.series_io
... series_io.prepare_series()
... series_io.load_series()
>>> from hydpy import print_values
>>> print_values(
... hp.elements.land_dill.model.sequences.inputs.t.series[:3])
-0.298846, -0.811539, -2.493848
""" |
kwargs = {}
for keyword in ('flattennetcdf', 'isolatenetcdf', 'timeaxisnetcdf'):
argument = getattr(hydpy.pub.options, keyword, None)
if argument is not None:
kwargs[keyword[:-6]] = argument
hydpy.pub.sequencemanager.open_netcdf_reader(**kwargs)
self.prepare_sequencemanager()
for sequence in self._iterate_sequences():
sequence.load_ext()
hydpy.pub.sequencemanager.close_netcdf_reader() |
<SYSTEM_TASK:>
Save time series data as defined by the actual XML `writer`
<END_TASK>
<USER_TASK:>
Description:
def save_series(self) -> None:
"""Save time series data as defined by the actual XML `writer`
element.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, TestIO, XMLInterface
>>> hp = HydPy('LahnH')
>>> with TestIO():
... hp.prepare_network()
... hp.init_models()
... interface = XMLInterface('single_run.xml')
... interface.update_options()
>>> interface.update_timegrids()
>>> series_io = interface.series_io
>>> series_io.prepare_series()
>>> hp.elements.land_dill.model.sequences.fluxes.pc.series[2, 3] = 9.0
>>> hp.nodes.lahn_2.sequences.sim.series[4] = 7.0
>>> with TestIO():
... series_io.save_series()
>>> import numpy
>>> with TestIO():
... os.path.exists(
... 'LahnH/series/output/land_lahn_2_flux_pc.npy')
... os.path.exists(
... 'LahnH/series/output/land_lahn_3_flux_pc.npy')
... numpy.load(
... 'LahnH/series/output/land_dill_flux_pc.npy')[13+2, 3]
... numpy.load(
... 'LahnH/series/output/lahn_2_sim_q_mean.npy')[13+4]
True
False
9.0
7.0
""" |
hydpy.pub.sequencemanager.open_netcdf_writer(
flatten=hydpy.pub.options.flattennetcdf,
isolate=hydpy.pub.options.isolatenetcdf)
self.prepare_sequencemanager()
for sequence in self._iterate_sequences():
sequence.save_ext()
hydpy.pub.sequencemanager.close_netcdf_writer() |
<SYSTEM_TASK:>
Write the complete base schema file `HydPyConfigBase.xsd` based
<END_TASK>
<USER_TASK:>
Description:
def write_xsd(cls) -> None:
"""Write the complete base schema file `HydPyConfigBase.xsd` based
on the template file `HydPyConfigBase.xsdt`.
Method |XSDWriter.write_xsd| adds model specific information to the
general information of template file `HydPyConfigBase.xsdt` regarding
reading and writing of time series data and exchanging parameter
and sequence values e.g. during calibration.
The following example shows that after writing a new schema file,
method |XMLInterface.validate_xml| does not raise an error when
either applied on the XML configuration files `single_run.xml` or
`multiple_runs.xml` of the `LahnH` example project:
>>> import os
>>> from hydpy.auxs.xmltools import XSDWriter, XMLInterface
>>> if os.path.exists(XSDWriter.filepath_target):
... os.remove(XSDWriter.filepath_target)
>>> os.path.exists(XSDWriter.filepath_target)
False
>>> XSDWriter.write_xsd()
>>> os.path.exists(XSDWriter.filepath_target)
True
>>> from hydpy import data
>>> for configfile in ('single_run.xml', 'multiple_runs.xml'):
... XMLInterface(configfile, data.get_path('LahnH')).validate_xml()
""" |
with open(cls.filepath_source) as file_:
template = file_.read()
template = template.replace(
'<!--include model sequence groups-->', cls.get_insertion())
template = template.replace(
'<!--include exchange items-->', cls.get_exchangeinsertion())
with open(cls.filepath_target, 'w') as file_:
file_.write(template) |
<SYSTEM_TASK:>
Return a sorted |list| containing all application model names.
<END_TASK>
<USER_TASK:>
Description:
def get_modelnames() -> List[str]:
"""Return a sorted |list| containing all application model names.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_modelnames()) # doctest: +ELLIPSIS
[...'dam_v001', 'dam_v002', 'dam_v003', 'dam_v004', 'dam_v005',...]
""" |
return sorted(str(fn.split('.')[0])
for fn in os.listdir(models.__path__[0])
if (fn.endswith('.py') and (fn != '__init__.py'))) |
<SYSTEM_TASK:>
Return the complete string to be inserted into the string of the
<END_TASK>
<USER_TASK:>
Description:
def get_insertion(cls) -> str:
"""Return the complete string to be inserted into the string of the
template file.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_insertion()) # doctest: +ELLIPSIS
<element name="arma_v1"
substitutionGroup="hpcb:sequenceGroup"
type="hpcb:arma_v1Type"/>
<BLANKLINE>
<complexType name="arma_v1Type">
<complexContent>
<extension base="hpcb:sequenceGroupType">
<sequence>
<element name="fluxes"
minOccurs="0">
<complexType>
<sequence>
<element
name="qin"
minOccurs="0"/>
...
</complexType>
</element>
</sequence>
</extension>
</complexContent>
</complexType>
<BLANKLINE>
""" |
indent = 1
blanks = ' ' * (indent+4)
subs = []
for name in cls.get_modelnames():
subs.extend([
f'{blanks}<element name="{name}"',
f'{blanks} substitutionGroup="hpcb:sequenceGroup"',
f'{blanks} type="hpcb:{name}Type"/>',
f'',
f'{blanks}<complexType name="{name}Type">',
f'{blanks} <complexContent>',
f'{blanks} <extension base="hpcb:sequenceGroupType">',
f'{blanks} <sequence>'])
model = importtools.prepare_model(name)
subs.append(cls.get_modelinsertion(model, indent + 4))
subs.extend([
f'{blanks} </sequence>',
f'{blanks} </extension>',
f'{blanks} </complexContent>',
f'{blanks}</complexType>',
f''
])
return '\n'.join(subs) |
<SYSTEM_TASK:>
Return the insertion string required for the given application model.
<END_TASK>
<USER_TASK:>
Description:
def get_modelinsertion(cls, model, indent) -> str:
"""Return the insertion string required for the given application model.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> from hydpy import prepare_model
>>> model = prepare_model('hland_v1')
>>> print(XSDWriter.get_modelinsertion(model, 1)) # doctest: +ELLIPSIS
<element name="inputs"
minOccurs="0">
<complexType>
<sequence>
<element
name="p"
minOccurs="0"/>
...
</element>
<element name="fluxes"
minOccurs="0">
...
</element>
<element name="states"
minOccurs="0">
...
</element>
""" |
texts = []
for name in ('inputs', 'fluxes', 'states'):
subsequences = getattr(model.sequences, name, None)
if subsequences:
texts.append(
cls.get_subsequencesinsertion(subsequences, indent))
return '\n'.join(texts) |
<SYSTEM_TASK:>
Return the insertion string required for the given group of
<END_TASK>
<USER_TASK:>
Description:
def get_subsequencesinsertion(cls, subsequences, indent) -> str:
"""Return the insertion string required for the given group of
sequences.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> from hydpy import prepare_model
>>> model = prepare_model('hland_v1')
>>> print(XSDWriter.get_subsequencesinsertion(
... model.sequences.fluxes, 1)) # doctest: +ELLIPSIS
<element name="fluxes"
minOccurs="0">
<complexType>
<sequence>
<element
name="tmean"
minOccurs="0"/>
<element
name="tc"
minOccurs="0"/>
...
<element
name="qt"
minOccurs="0"/>
</sequence>
</complexType>
</element>
""" |
blanks = ' ' * (indent*4)
lines = [f'{blanks}<element name="{subsequences.name}"',
f'{blanks} minOccurs="0">',
f'{blanks} <complexType>',
f'{blanks} <sequence>']
for sequence in subsequences:
lines.append(cls.get_sequenceinsertion(sequence, indent + 3))
lines.extend([f'{blanks} </sequence>',
f'{blanks} </complexType>',
f'{blanks}</element>'])
return '\n'.join(lines) |
<SYSTEM_TASK:>
Return the complete string related to the definition of exchange
<END_TASK>
<USER_TASK:>
Description:
def get_exchangeinsertion(cls):
"""Return the complete string related to the definition of exchange
items to be inserted into the string of the template file.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_exchangeinsertion()) # doctest: +ELLIPSIS
<complexType name="arma_v1_mathitemType">
...
<element name="setitems">
...
<complexType name="arma_v1_setitemsType">
...
<element name="additems">
...
<element name="getitems">
...
""" |
indent = 1
subs = [cls.get_mathitemsinsertion(indent)]
for groupname in ('setitems', 'additems', 'getitems'):
subs.append(cls.get_itemsinsertion(groupname, indent))
subs.append(cls.get_itemtypesinsertion(groupname, indent))
return '\n'.join(subs) |
<SYSTEM_TASK:>
Return a string defining the XML element for the given
<END_TASK>
<USER_TASK:>
Description:
def get_itemsinsertion(cls, itemgroup, indent) -> str:
"""Return a string defining the XML element for the given
exchange item group.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_itemsinsertion(
... 'setitems', 1)) # doctest: +ELLIPSIS
<element name="setitems">
<complexType>
<sequence>
<element ref="hpcb:selections"
minOccurs="0"/>
<element ref="hpcb:devices"
minOccurs="0"/>
...
<element name="hland_v1"
type="hpcb:hland_v1_setitemsType"
minOccurs="0"
maxOccurs="unbounded"/>
...
<element name="nodes"
type="hpcb:nodes_setitemsType"
minOccurs="0"
maxOccurs="unbounded"/>
</sequence>
<attribute name="info" type="string"/>
</complexType>
</element>
<BLANKLINE>
""" |
blanks = ' ' * (indent*4)
subs = []
subs.extend([
f'{blanks}<element name="{itemgroup}">',
f'{blanks} <complexType>',
f'{blanks} <sequence>',
f'{blanks} <element ref="hpcb:selections"',
f'{blanks} minOccurs="0"/>',
f'{blanks} <element ref="hpcb:devices"',
f'{blanks} minOccurs="0"/>'])
for modelname in cls.get_modelnames():
type_ = cls._get_itemstype(modelname, itemgroup)
subs.append(f'{blanks} <element name="{modelname}"')
subs.append(f'{blanks} type="hpcb:{type_}"')
subs.append(f'{blanks} minOccurs="0"')
subs.append(f'{blanks} maxOccurs="unbounded"/>')
if itemgroup in ('setitems', 'getitems'):
type_ = f'nodes_{itemgroup}Type'
subs.append(f'{blanks} <element name="nodes"')
subs.append(f'{blanks} type="hpcb:{type_}"')
subs.append(f'{blanks} minOccurs="0"')
subs.append(f'{blanks} maxOccurs="unbounded"/>')
subs.extend([
f'{blanks} </sequence>',
f'{blanks} <attribute name="info" type="string"/>',
f'{blanks} </complexType>',
f'{blanks}</element>',
f''])
return '\n'.join(subs) |
<SYSTEM_TASK:>
Return a string defining the required types for the given
<END_TASK>
<USER_TASK:>
Description:
def get_itemtypesinsertion(cls, itemgroup, indent) -> str:
"""Return a string defining the required types for the given
exchange item group.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_itemtypesinsertion(
... 'setitems', 1)) # doctest: +ELLIPSIS
<complexType name="arma_v1_setitemsType">
...
</complexType>
<BLANKLINE>
<complexType name="dam_v001_setitemsType">
...
<complexType name="nodes_setitemsType">
...
""" |
subs = []
for modelname in cls.get_modelnames():
subs.append(cls.get_itemtypeinsertion(itemgroup, modelname, indent))
subs.append(cls.get_nodesitemtypeinsertion(itemgroup, indent))
return '\n'.join(subs) |
<SYSTEM_TASK:>
Return a string defining the required types for the given
<END_TASK>
<USER_TASK:>
Description:
def get_nodesitemtypeinsertion(cls, itemgroup, indent) -> str:
"""Return a string defining the required types for the given
combination of an exchange item group and |Node| objects.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_nodesitemtypeinsertion(
... 'setitems', 1)) # doctest: +ELLIPSIS
<complexType name="nodes_setitemsType">
<sequence>
<element ref="hpcb:selections"
minOccurs="0"/>
<element ref="hpcb:devices"
minOccurs="0"/>
<element name="sim"
type="hpcb:setitemType"
minOccurs="0"
maxOccurs="unbounded"/>
<element name="obs"
type="hpcb:setitemType"
minOccurs="0"
maxOccurs="unbounded"/>
<element name="sim.series"
type="hpcb:setitemType"
minOccurs="0"
maxOccurs="unbounded"/>
<element name="obs.series"
type="hpcb:setitemType"
minOccurs="0"
maxOccurs="unbounded"/>
</sequence>
</complexType>
<BLANKLINE>
""" |
blanks = ' ' * (indent * 4)
subs = [
f'{blanks}<complexType name="nodes_{itemgroup}Type">',
f'{blanks} <sequence>',
f'{blanks} <element ref="hpcb:selections"',
f'{blanks} minOccurs="0"/>',
f'{blanks} <element ref="hpcb:devices"',
f'{blanks} minOccurs="0"/>']
type_ = 'getitemType' if itemgroup == 'getitems' else 'setitemType'
for name in ('sim', 'obs', 'sim.series', 'obs.series'):
subs.extend([
f'{blanks} <element name="{name}"',
f'{blanks} type="hpcb:{type_}"',
f'{blanks} minOccurs="0"',
f'{blanks} maxOccurs="unbounded"/>'])
subs.extend([
f'{blanks} </sequence>',
f'{blanks}</complexType>',
f''])
return '\n'.join(subs) |
<SYSTEM_TASK:>
Return a string defining the required types for the given
<END_TASK>
<USER_TASK:>
Description:
def get_subgroupiteminsertion(
cls, itemgroup, model, subgroup, indent) -> str:
"""Return a string defining the required types for the given
combination of an exchange item group and a specific variable
subgroup of an application model or class |Node|.
Note that for `setitems` and `getitems` `setitemType` and
`getitemType` are referenced, respectively, and for all others
the model specific `mathitemType`:
>>> from hydpy import prepare_model
>>> model = prepare_model('hland_v1')
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_subgroupiteminsertion( # doctest: +ELLIPSIS
... 'setitems', model, model.parameters.control, 1))
<element name="control"
minOccurs="0"
maxOccurs="unbounded">
<complexType>
<sequence>
<element ref="hpcb:selections"
minOccurs="0"/>
<element ref="hpcb:devices"
minOccurs="0"/>
<element name="area"
type="hpcb:setitemType"
minOccurs="0"
maxOccurs="unbounded"/>
<element name="nmbzones"
...
</sequence>
</complexType>
</element>
>>> print(XSDWriter.get_subgroupiteminsertion( # doctest: +ELLIPSIS
... 'getitems', model, model.parameters.control, 1))
<element name="control"
...
<element name="area"
type="hpcb:getitemType"
minOccurs="0"
maxOccurs="unbounded"/>
...
>>> print(XSDWriter.get_subgroupiteminsertion( # doctest: +ELLIPSIS
... 'additems', model, model.parameters.control, 1))
<element name="control"
...
<element name="area"
type="hpcb:hland_v1_mathitemType"
minOccurs="0"
maxOccurs="unbounded"/>
...
For sequence classes, additional "series" elements are added:
>>> print(XSDWriter.get_subgroupiteminsertion( # doctest: +ELLIPSIS
... 'setitems', model, model.sequences.fluxes, 1))
<element name="fluxes"
...
<element name="tmean"
type="hpcb:setitemType"
minOccurs="0"
maxOccurs="unbounded"/>
<element name="tmean.series"
type="hpcb:setitemType"
minOccurs="0"
maxOccurs="unbounded"/>
<element name="tc"
...
</sequence>
</complexType>
</element>
""" |
blanks1 = ' ' * (indent * 4)
blanks2 = ' ' * ((indent+5) * 4 + 1)
subs = [
f'{blanks1}<element name="{subgroup.name}"',
f'{blanks1} minOccurs="0"',
f'{blanks1} maxOccurs="unbounded">',
f'{blanks1} <complexType>',
f'{blanks1} <sequence>',
f'{blanks1} <element ref="hpcb:selections"',
f'{blanks1} minOccurs="0"/>',
f'{blanks1} <element ref="hpcb:devices"',
f'{blanks1} minOccurs="0"/>']
seriesflags = (False,) if subgroup.name == 'control' else (False, True)
for variable in subgroup:
for series in seriesflags:
name = f'{variable.name}.series' if series else variable.name
subs.append(f'{blanks1} <element name="{name}"')
if itemgroup == 'setitems':
subs.append(f'{blanks2}type="hpcb:setitemType"')
elif itemgroup == 'getitems':
subs.append(f'{blanks2}type="hpcb:getitemType"')
else:
subs.append(
f'{blanks2}type="hpcb:{model.name}_mathitemType"')
subs.append(f'{blanks2}minOccurs="0"')
subs.append(f'{blanks2}maxOccurs="unbounded"/>')
subs.extend([
f'{blanks1} </sequence>',
f'{blanks1} </complexType>',
f'{blanks1}</element>'])
return '\n'.join(subs) |
<SYSTEM_TASK:>
Create a new mask object based on the given |numpy.ndarray|
<END_TASK>
<USER_TASK:>
Description:
def array2mask(cls, array=None, **kwargs):
"""Create a new mask object based on the given |numpy.ndarray|
and return it.""" |
kwargs['dtype'] = bool
if array is None:
return numpy.ndarray.__new__(cls, 0, **kwargs)
return numpy.asarray(array, **kwargs).view(cls) |
<SYSTEM_TASK:>
Return a new |DefaultMask| object associated with the
<END_TASK>
<USER_TASK:>
Description:
def new(cls, variable, **kwargs):
"""Return a new |DefaultMask| object associated with the
given |Variable| object.""" |
return cls.array2mask(numpy.full(variable.shape, True)) |
<SYSTEM_TASK:>
Return a new |IndexMask| object of the same shape as the
<END_TASK>
<USER_TASK:>
Description:
def new(cls, variable, **kwargs):
"""Return a new |IndexMask| object of the same shape as the
parameter referenced by |property| |IndexMask.refindices|.
Entries are only |True|, if the integer values of the
respective entries of the referenced parameter are contained
in the |IndexMask| class attribute tuple `RELEVANT_VALUES`.
""" |
indices = cls.get_refindices(variable)
if numpy.min(getattr(indices, 'values', 0)) < 1:
raise RuntimeError(
f'The mask of parameter {objecttools.elementphrase(variable)} '
f'cannot be determined, as long as parameter `{indices.name}` '
f'is not prepared properly.')
mask = numpy.full(indices.shape, False, dtype=bool)
refvalues = indices.values
for relvalue in cls.RELEVANT_VALUES:
mask[refvalues == relvalue] = True
return cls.array2mask(mask, **kwargs) |
<SYSTEM_TASK:>
Determine the reference discharge within the given space-time interval.
<END_TASK>
<USER_TASK:>
Description:
def calc_qref_v1(self):
"""Determine the reference discharge within the given space-time interval.
Required state sequences:
|QZ|
|QA|
Calculated flux sequence:
|QRef|
Basic equation:
:math:`QRef = \\frac{QZ_{new}+QZ_{old}+QA_{old}}{3}`
Example:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> states.qz.new = 3.0
>>> states.qz.old = 2.0
>>> states.qa.old = 1.0
>>> model.calc_qref_v1()
>>> fluxes.qref
qref(2.0)
""" |
new = self.sequences.states.fastaccess_new
old = self.sequences.states.fastaccess_old
flu = self.sequences.fluxes.fastaccess
flu.qref = (new.qz+old.qz+old.qa)/3. |
<SYSTEM_TASK:>
Calculate the flown through area and the wetted perimeter
<END_TASK>
<USER_TASK:>
Description:
def calc_am_um_v1(self):
"""Calculate the flown through area and the wetted perimeter
of the main channel.
Note that the main channel is assumed to have identical slopes on
both sides and that water flowing exactly above the main channel is
contributing to |AM|. Both theoretical surfaces seperating water
above the main channel from water above both forelands are
contributing to |UM|.
Required control parameters:
|HM|
|BM|
|BNM|
Required flux sequence:
|H|
Calculated flux sequence:
|AM|
|UM|
Examples:
Generally, a trapezoid with reflection symmetry is assumed. Here its
smaller base (bottom) has a length of 2 meters, its legs show an
inclination of 1 meter per 4 meters, and its height (depths) is 1
meter:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> bm(2.0)
>>> bnm(4.0)
>>> hm(1.0)
The first example deals with normal flow conditions, where water
flows within the main channel completely (|H| < |HM|):
>>> fluxes.h = 0.5
>>> model.calc_am_um_v1()
>>> fluxes.am
am(2.0)
>>> fluxes.um
um(6.123106)
The second example deals with high flow conditions, where water
flows over the foreland also (|H| > |HM|):
>>> fluxes.h = 1.5
>>> model.calc_am_um_v1()
>>> fluxes.am
am(11.0)
>>> fluxes.um
um(11.246211)
The third example checks the special case of a main channel with zero
height:
>>> hm(0.0)
>>> model.calc_am_um_v1()
>>> fluxes.am
am(3.0)
>>> fluxes.um
um(5.0)
The fourth example checks the special case of the actual water stage
not being larger than zero (empty channel):
>>> fluxes.h = 0.0
>>> hm(1.0)
>>> model.calc_am_um_v1()
>>> fluxes.am
am(0.0)
>>> fluxes.um
um(0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
if flu.h <= 0.:
flu.am = 0.
flu.um = 0.
elif flu.h < con.hm:
flu.am = flu.h*(con.bm+flu.h*con.bnm)
flu.um = con.bm+2.*flu.h*(1.+con.bnm**2)**.5
else:
flu.am = (con.hm*(con.bm+con.hm*con.bnm) +
((flu.h-con.hm)*(con.bm+2.*con.hm*con.bnm)))
flu.um = con.bm+(2.*con.hm*(1.+con.bnm**2)**.5)+(2*(flu.h-con.hm)) |
<SYSTEM_TASK:>
Calculate the discharge of the main channel after Manning-Strickler.
<END_TASK>
<USER_TASK:>
Description:
def calc_qm_v1(self):
"""Calculate the discharge of the main channel after Manning-Strickler.
Required control parameters:
|EKM|
|SKM|
|Gef|
Required flux sequence:
|AM|
|UM|
Calculated flux sequence:
|lstream_fluxes.QM|
Examples:
For appropriate strictly positive values:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> ekm(2.0)
>>> skm(50.0)
>>> gef(0.01)
>>> fluxes.am = 3.0
>>> fluxes.um = 7.0
>>> model.calc_qm_v1()
>>> fluxes.qm
qm(17.053102)
For zero or negative values of the flown through surface or
the wetted perimeter:
>>> fluxes.am = -1.0
>>> fluxes.um = 7.0
>>> model.calc_qm_v1()
>>> fluxes.qm
qm(0.0)
>>> fluxes.am = 3.0
>>> fluxes.um = 0.0
>>> model.calc_qm_v1()
>>> fluxes.qm
qm(0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
if (flu.am > 0.) and (flu.um > 0.):
flu.qm = con.ekm*con.skm*flu.am**(5./3.)/flu.um**(2./3.)*con.gef**.5
else:
flu.qm = 0. |
<SYSTEM_TASK:>
Calculate the flown through area and the wetted perimeter of both
<END_TASK>
<USER_TASK:>
Description:
def calc_av_uv_v1(self):
"""Calculate the flown through area and the wetted perimeter of both
forelands.
Note that the each foreland lies between the main channel and one
outer embankment and that water flowing exactly above the a foreland
is contributing to |AV|. The theoretical surface seperating water
above the main channel from water above the foreland is not
contributing to |UV|, but the surface seperating water above the
foreland from water above its outer embankment is contributing to |UV|.
Required control parameters:
|HM|
|BV|
|BNV|
Required derived parameter:
|HV|
Required flux sequence:
|H|
Calculated flux sequence:
|AV|
|UV|
Examples:
Generally, right trapezoids are assumed. Here, for simplicity, both
forelands are assumed to be symmetrical. Their smaller bases (bottoms)
hava a length of 2 meters, their non-vertical legs show an inclination
of 1 meter per 4 meters, and their height (depths) is 1 meter. Both
forelands lie 1 meter above the main channels bottom.
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> hm(1.0)
>>> bv(2.0)
>>> bnv(4.0)
>>> derived.hv(1.0)
The first example deals with normal flow conditions, where water flows
within the main channel completely (|H| < |HM|):
>>> fluxes.h = 0.5
>>> model.calc_av_uv_v1()
>>> fluxes.av
av(0.0, 0.0)
>>> fluxes.uv
uv(0.0, 0.0)
The second example deals with moderate high flow conditions, where
water flows over both forelands, but not over their embankments
(|HM| < |H| < (|HM| + |HV|)):
>>> fluxes.h = 1.5
>>> model.calc_av_uv_v1()
>>> fluxes.av
av(1.5, 1.5)
>>> fluxes.uv
uv(4.061553, 4.061553)
The third example deals with extreme high flow conditions, where
water flows over the both foreland and their outer embankments
((|HM| + |HV|) < |H|):
>>> fluxes.h = 2.5
>>> model.calc_av_uv_v1()
>>> fluxes.av
av(7.0, 7.0)
>>> fluxes.uv
uv(6.623106, 6.623106)
The forth example assures that zero widths or hights of the forelands
are handled properly:
>>> bv.left = 0.0
>>> derived.hv.right = 0.0
>>> model.calc_av_uv_v1()
>>> fluxes.av
av(4.0, 3.0)
>>> fluxes.uv
uv(4.623106, 3.5)
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
for i in range(2):
if flu.h <= con.hm:
flu.av[i] = 0.
flu.uv[i] = 0.
elif flu.h <= (con.hm+der.hv[i]):
flu.av[i] = (flu.h-con.hm)*(con.bv[i]+(flu.h-con.hm)*con.bnv[i]/2.)
flu.uv[i] = con.bv[i]+(flu.h-con.hm)*(1.+con.bnv[i]**2)**.5
else:
flu.av[i] = (der.hv[i]*(con.bv[i]+der.hv[i]*con.bnv[i]/2.) +
((flu.h-(con.hm+der.hv[i])) *
(con.bv[i]+der.hv[i]*con.bnv[i])))
flu.uv[i] = ((con.bv[i])+(der.hv[i]*(1.+con.bnv[i]**2)**.5) +
(flu.h-(con.hm+der.hv[i]))) |
<SYSTEM_TASK:>
Calculate the discharge of both forelands after Manning-Strickler.
<END_TASK>
<USER_TASK:>
Description:
def calc_qv_v1(self):
"""Calculate the discharge of both forelands after Manning-Strickler.
Required control parameters:
|EKV|
|SKV|
|Gef|
Required flux sequence:
|AV|
|UV|
Calculated flux sequence:
|lstream_fluxes.QV|
Examples:
For appropriate strictly positive values:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> ekv(2.0)
>>> skv(50.0)
>>> gef(0.01)
>>> fluxes.av = 3.0
>>> fluxes.uv = 7.0
>>> model.calc_qv_v1()
>>> fluxes.qv
qv(17.053102, 17.053102)
For zero or negative values of the flown through surface or
the wetted perimeter:
>>> fluxes.av = -1.0, 3.0
>>> fluxes.uv = 7.0, 0.0
>>> model.calc_qv_v1()
>>> fluxes.qv
qv(0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
for i in range(2):
if (flu.av[i] > 0.) and (flu.uv[i] > 0.):
flu.qv[i] = (con.ekv[i]*con.skv[i] *
flu.av[i]**(5./3.)/flu.uv[i]**(2./3.)*con.gef**.5)
else:
flu.qv[i] = 0. |
<SYSTEM_TASK:>
Calculate the flown through area and the wetted perimeter of both
<END_TASK>
<USER_TASK:>
Description:
def calc_avr_uvr_v1(self):
"""Calculate the flown through area and the wetted perimeter of both
outer embankments.
Note that each outer embankment lies beyond its foreland and that all
water flowing exactly above the a embankment is added to |AVR|.
The theoretical surface seperating water above the foreland from water
above its embankment is not contributing to |UVR|.
Required control parameters:
|HM|
|BNVR|
Required derived parameter:
|HV|
Required flux sequence:
|H|
Calculated flux sequence:
|AVR|
|UVR|
Examples:
Generally, right trapezoids are assumed. Here, for simplicity, both
forelands are assumed to be symmetrical. Their smaller bases (bottoms)
hava a length of 2 meters, their non-vertical legs show an inclination
of 1 meter per 4 meters, and their height (depths) is 1 meter. Both
forelands lie 1 meter above the main channels bottom.
Generally, a triangles are assumed, with the vertical side
seperating the foreland from its outer embankment. Here, for
simplicity, both forelands are assumed to be symmetrical. Their
inclinations are 1 meter per 4 meters and their lowest point is
1 meter above the forelands bottom and 2 meters above the main
channels bottom:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> hm(1.0)
>>> bnvr(4.0)
>>> derived.hv(1.0)
The first example deals with moderate high flow conditions, where
water flows over the forelands, but not over their outer embankments
(|HM| < |H| < (|HM| + |HV|)):
>>> fluxes.h = 1.5
>>> model.calc_avr_uvr_v1()
>>> fluxes.avr
avr(0.0, 0.0)
>>> fluxes.uvr
uvr(0.0, 0.0)
The second example deals with extreme high flow conditions, where
water flows over the both foreland and their outer embankments
((|HM| + |HV|) < |H|):
>>> fluxes.h = 2.5
>>> model.calc_avr_uvr_v1()
>>> fluxes.avr
avr(0.5, 0.5)
>>> fluxes.uvr
uvr(2.061553, 2.061553)
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
for i in range(2):
if flu.h <= (con.hm+der.hv[i]):
flu.avr[i] = 0.
flu.uvr[i] = 0.
else:
flu.avr[i] = (flu.h-(con.hm+der.hv[i]))**2*con.bnvr[i]/2.
flu.uvr[i] = (flu.h-(con.hm+der.hv[i]))*(1.+con.bnvr[i]**2)**.5 |
<SYSTEM_TASK:>
Calculate the discharge of both outer embankments after
<END_TASK>
<USER_TASK:>
Description:
def calc_qvr_v1(self):
"""Calculate the discharge of both outer embankments after
Manning-Strickler.
Required control parameters:
|EKV|
|SKV|
|Gef|
Required flux sequence:
|AVR|
|UVR|
Calculated flux sequence:
|QVR|
Examples:
For appropriate strictly positive values:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> ekv(2.0)
>>> skv(50.0)
>>> gef(0.01)
>>> fluxes.avr = 3.0
>>> fluxes.uvr = 7.0
>>> model.calc_qvr_v1()
>>> fluxes.qvr
qvr(17.053102, 17.053102)
For zero or negative values of the flown through surface or
the wetted perimeter:
>>> fluxes.avr = -1.0, 3.0
>>> fluxes.uvr = 7.0, 0.0
>>> model.calc_qvr_v1()
>>> fluxes.qvr
qvr(0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
for i in range(2):
if (flu.avr[i] > 0.) and (flu.uvr[i] > 0.):
flu.qvr[i] = (con.ekv[i]*con.skv[i] *
flu.avr[i]**(5./3.)/flu.uvr[i]**(2./3.)*con.gef**.5)
else:
flu.qvr[i] = 0. |
<SYSTEM_TASK:>
Sum the through flown area of the total cross section.
<END_TASK>
<USER_TASK:>
Description:
def calc_ag_v1(self):
"""Sum the through flown area of the total cross section.
Required flux sequences:
|AM|
|AV|
|AVR|
Calculated flux sequence:
|AG|
Example:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> fluxes.am = 1.0
>>> fluxes.av= 2.0, 3.0
>>> fluxes.avr = 4.0, 5.0
>>> model.calc_ag_v1()
>>> fluxes.ag
ag(15.0)
""" |
flu = self.sequences.fluxes.fastaccess
flu.ag = flu.am+flu.av[0]+flu.av[1]+flu.avr[0]+flu.avr[1] |
<SYSTEM_TASK:>
Calculate the discharge of the total cross section.
<END_TASK>
<USER_TASK:>
Description:
def calc_qg_v1(self):
"""Calculate the discharge of the total cross section.
Method |calc_qg_v1| applies the actual versions of all methods for
calculating the flown through areas, wetted perimeters and discharges
of the different cross section compartments. Hence its requirements
might be different for various application models.
""" |
flu = self.sequences.fluxes.fastaccess
self.calc_am_um()
self.calc_qm()
self.calc_av_uv()
self.calc_qv()
self.calc_avr_uvr()
self.calc_qvr()
flu.qg = flu.qm+flu.qv[0]+flu.qv[1]+flu.qvr[0]+flu.qvr[1] |
<SYSTEM_TASK:>
Determine an starting interval for iteration methods as the one
<END_TASK>
<USER_TASK:>
Description:
def calc_hmin_qmin_hmax_qmax_v1(self):
"""Determine an starting interval for iteration methods as the one
implemented in method |calc_h_v1|.
The resulting interval is determined in a manner, that on the
one hand :math:`Qmin \\leq QRef \\leq Qmax` is fulfilled and on the
other hand the results of method |calc_qg_v1| are continuous
for :math:`Hmin \\leq H \\leq Hmax`.
Required control parameter:
|HM|
Required derived parameters:
|HV|
|lstream_derived.QM|
|lstream_derived.QV|
Required flux sequence:
|QRef|
Calculated aide sequences:
|HMin|
|HMax|
|QMin|
|QMax|
Besides the mentioned required parameters and sequences, those of the
actual method for calculating the discharge of the total cross section
might be required. This is the case whenever water flows on both outer
embankments. In such occasions no previously determined upper boundary
values are available and method |calc_hmin_qmin_hmax_qmax_v1| needs
to increase the value of :math:`HMax` successively until the condition
:math:`QG \\leq QMax` is met.
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
aid = self.sequences.aides.fastaccess
if flu.qref <= der.qm:
aid.hmin = 0.
aid.qmin = 0.
aid.hmax = con.hm
aid.qmax = der.qm
elif flu.qref <= min(der.qv[0], der.qv[1]):
aid.hmin = con.hm
aid.qmin = der.qm
aid.hmax = con.hm+min(der.hv[0], der.hv[1])
aid.qmax = min(der.qv[0], der.qv[1])
elif flu.qref < max(der.qv[0], der.qv[1]):
aid.hmin = con.hm+min(der.hv[0], der.hv[1])
aid.qmin = min(der.qv[0], der.qv[1])
aid.hmax = con.hm+max(der.hv[0], der.hv[1])
aid.qmax = max(der.qv[0], der.qv[1])
else:
flu.h = con.hm+max(der.hv[0], der.hv[1])
aid.hmin = flu.h
aid.qmin = flu.qg
while True:
flu.h *= 2.
self.calc_qg()
if flu.qg < flu.qref:
aid.hmin = flu.h
aid.qmin = flu.qg
else:
aid.hmax = flu.h
aid.qmax = flu.qg
break |
<SYSTEM_TASK:>
Approximate the water stage resulting in a certain reference discarge
<END_TASK>
<USER_TASK:>
Description:
def calc_h_v1(self):
"""Approximate the water stage resulting in a certain reference discarge
with the Pegasus iteration method.
Required control parameters:
|QTol|
|HTol|
Required flux sequence:
|QRef|
Modified aide sequences:
|HMin|
|HMax|
|QMin|
|QMax|
Calculated flux sequence:
|H|
Besides the parameters and sequences given above, those of the
actual method for calculating the discharge of the total cross section
are required.
Examples:
Essentially, the Pegasus method is a root finding algorithm which
sequentially decreases its search radius (like the simple bisection
algorithm) and shows superlinear convergence properties (like the
Newton-Raphson algorithm). Ideally, its convergence should be proved
for each application model to be derived from HydPy-L-Stream.
The following examples focus on the methods
|calc_hmin_qmin_hmax_qmax_v1| and |calc_qg_v1| (including their
submethods) only:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> model.calc_hmin_qmin_hmax_qmax = model.calc_hmin_qmin_hmax_qmax_v1
>>> model.calc_qg = model.calc_qg_v1
>>> model.calc_qm = model.calc_qm_v1
>>> model.calc_av_uv = model.calc_av_uv_v1
>>> model.calc_qv = model.calc_qv_v1
>>> model.calc_avr_uvr = model.calc_avr_uvr_v1
>>> model.calc_qvr = model.calc_qvr_v1
Define the geometry and roughness values for the first test channel:
>>> bm(2.0)
>>> bnm(4.0)
>>> hm(1.0)
>>> bv(0.5, 10.0)
>>> bbv(1.0, 2.0)
>>> bnv(1.0, 8.0)
>>> bnvr(20.0)
>>> ekm(1.0)
>>> skm(20.0)
>>> ekv(1.0)
>>> skv(60.0, 80.0)
>>> gef(0.01)
Set the error tolerances of the iteration small enough to not
compromise the shown first six decimal places of the following
results:
>>> qtol(1e-10)
>>> htol(1e-10)
Derive the required secondary parameters:
>>> derived.hv.update()
>>> derived.qm.update()
>>> derived.qv.update()
Define a test function, accepting a reference discharge and printing
both the approximated water stage and the related discharge value:
>>> def test(qref):
... fluxes.qref = qref
... model.calc_hmin_qmin_hmax_qmax()
... model.calc_h()
... print(repr(fluxes.h))
... print(repr(fluxes.qg))
Zero discharge and the following discharge values are related to the
only discontinuities of the given root finding problem:
>>> derived.qm
qm(8.399238)
>>> derived.qv
qv(left=154.463234, right=23.073584)
The related water stages are the ones (directly or indirectly)
defined above:
>>> test(0.0)
h(0.0)
qg(0.0)
>>> test(derived.qm)
h(1.0)
qg(8.399238)
>>> test(derived.qv.left)
h(2.0)
qg(154.463234)
>>> test(derived.qv.right)
h(1.25)
qg(23.073584)
Test some intermediate water stages, inundating the only the main
channel, the main channel along with the right foreland, and the
main channel along with both forelands respectively:
>>> test(6.0)
h(0.859452)
qg(6.0)
>>> test(10.0)
h(1.047546)
qg(10.0)
>>> test(100.0)
h(1.77455)
qg(100.0)
Finally, test two extreme water stages, inundating both outer
foreland embankments:
>>> test(200.0)
h(2.152893)
qg(200.0)
>>> test(2000.0)
h(4.240063)
qg(2000.0)
There is a potential risk of the implemented iteration method to fail
for special channel geometries. To test such cases in a more
condensed manner, the following test methods evaluates different water
stages automatically in accordance with the example above. An error
message is printed only, the estimated discharge does not approximate
the reference discharge with six decimal places:
>>> def test():
... derived.hv.update()
... derived.qm.update()
... derived.qv.update()
... qm, qv = derived.qm, derived.qv
... for qref in [0.0, qm, qv.left, qv.right,
... 2.0/3.0*qm+1.0/3.0*min(qv),
... 2.0/3.0*min(qv)+1.0/3.0*max(qv),
... 3.0*max(qv), 30.0*max(qv)]:
... fluxes.qref = qref
... model.calc_hmin_qmin_hmax_qmax()
... model.calc_h()
... if abs(round(fluxes.qg-qref) > 0.0):
... print('Error!', 'qref:', qref, 'qg:', fluxes.qg)
Check for a triangle main channel:
>>> bm(0.0)
>>> test()
>>> bm(2.0)
Check for a completely flat main channel:
>>> hm(0.0)
>>> test()
Repeat the last example but with a decreased value of |QTol|
allowing to trigger another stopping mechanisms if the
iteration algorithm:
>>> qtol(0.0)
>>> test()
>>> hm(1.0)
>>> qtol(1e-10)
Check for a nonexistend main channel:
>>> bm(0.0)
>>> bnm(0.0)
>>> test()
>>> bm(2.0)
>>> bnm(4.0)
Check for a nonexistend forelands:
>>> bv(0.0)
>>> bbv(0.0)
>>> test()
>>> bv(0.5, 10.0)
>>> bbv(1., 2.0)
Check for nonexistend outer foreland embankments:
>>> bnvr(0.0)
>>> test()
To take the last test as an illustrative example, one can see that
the given reference discharge is met by the estimated total discharge,
which consists of components related to the main channel and the
forelands only:
>>> fluxes.qref
qref(3932.452785)
>>> fluxes.qg
qg(3932.452785)
>>> fluxes.qm
qm(530.074621)
>>> fluxes.qv
qv(113.780226, 3288.597937)
>>> fluxes.qvr
qvr(0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
aid = self.sequences.aides.fastaccess
aid.qmin -= flu.qref
aid.qmax -= flu.qref
if modelutils.fabs(aid.qmin) < con.qtol:
flu.h = aid.hmin
self.calc_qg()
elif modelutils.fabs(aid.qmax) < con.qtol:
flu.h = aid.hmax
self.calc_qg()
elif modelutils.fabs(aid.hmax-aid.hmin) < con.htol:
flu.h = (aid.hmin+aid.hmax)/2.
self.calc_qg()
else:
while True:
flu.h = aid.hmin-aid.qmin*(aid.hmax-aid.hmin)/(aid.qmax-aid.qmin)
self.calc_qg()
aid.qtest = flu.qg-flu.qref
if modelutils.fabs(aid.qtest) < con.qtol:
return
if (((aid.qmax < 0.) and (aid.qtest < 0.)) or
((aid.qmax > 0.) and (aid.qtest > 0.))):
aid.qmin *= aid.qmax/(aid.qmax+aid.qtest)
else:
aid.hmin = aid.hmax
aid.qmin = aid.qmax
aid.hmax = flu.h
aid.qmax = aid.qtest
if modelutils.fabs(aid.hmax-aid.hmin) < con.htol:
return |
<SYSTEM_TASK:>
Calculate outflow.
<END_TASK>
<USER_TASK:>
Description:
def calc_qa_v1(self):
"""Calculate outflow.
The working equation is the analytical solution of the linear storage
equation under the assumption of constant change in inflow during
the simulation time step.
Required flux sequence:
|RK|
Required state sequence:
|QZ|
Updated state sequence:
|QA|
Basic equation:
:math:`QA_{neu} = QA_{alt} +
(QZ_{alt}-QA_{alt}) \\cdot (1-exp(-RK^{-1})) +
(QZ_{neu}-QZ_{alt}) \\cdot (1-RK\\cdot(1-exp(-RK^{-1})))`
Examples:
A normal test case:
>>> from hydpy.models.lstream import *
>>> parameterstep()
>>> fluxes.rk(0.1)
>>> states.qz.old = 2.0
>>> states.qz.new = 4.0
>>> states.qa.old = 3.0
>>> model.calc_qa_v1()
>>> states.qa
qa(3.800054)
First extreme test case (zero division is circumvented):
>>> fluxes.rk(0.0)
>>> model.calc_qa_v1()
>>> states.qa
qa(4.0)
Second extreme test case (numerical overflow is circumvented):
>>> fluxes.rk(1e201)
>>> model.calc_qa_v1()
>>> states.qa
qa(5.0)
""" |
flu = self.sequences.fluxes.fastaccess
old = self.sequences.states.fastaccess_old
new = self.sequences.states.fastaccess_new
aid = self.sequences.aides.fastaccess
if flu.rk <= 0.:
new.qa = new.qz
elif flu.rk > 1e200:
new.qa = old.qa+new.qz-old.qz
else:
aid.temp = (1.-modelutils.exp(-1./flu.rk))
new.qa = (old.qa +
(old.qz-old.qa)*aid.temp +
(new.qz-old.qz)*(1.-flu.rk*aid.temp)) |
<SYSTEM_TASK:>
Adjust the measured air temperature to the altitude of the
<END_TASK>
<USER_TASK:>
Description:
def calc_tc_v1(self):
"""Adjust the measured air temperature to the altitude of the
individual zones.
Required control parameters:
|NmbZones|
|TCAlt|
|ZoneZ|
|ZRelT|
Required input sequence:
|hland_inputs.T|
Calculated flux sequences:
|TC|
Basic equation:
:math:`TC = T - TCAlt \\cdot (ZoneZ-ZRelT)`
Examples:
Prepare two zones, the first one lying at the reference
height and the second one 200 meters above:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(2)
>>> zrelt(2.0)
>>> zonez(2.0, 4.0)
Applying the usual temperature lapse rate of 0.6°C/100m does
not affect the temperature of the first zone but reduces the
temperature of the second zone by 1.2°C:
>>> tcalt(0.6)
>>> inputs.t = 5.0
>>> model.calc_tc_v1()
>>> fluxes.tc
tc(5.0, 3.8)
""" |
con = self.parameters.control.fastaccess
inp = self.sequences.inputs.fastaccess
flu = self.sequences.fluxes.fastaccess
for k in range(con.nmbzones):
flu.tc[k] = inp.t-con.tcalt[k]*(con.zonez[k]-con.zrelt) |
<SYSTEM_TASK:>
Calculate the areal mean temperature of the subbasin.
<END_TASK>
<USER_TASK:>
Description:
def calc_tmean_v1(self):
"""Calculate the areal mean temperature of the subbasin.
Required derived parameter:
|RelZoneArea|
Required flux sequence:
|TC|
Calculated flux sequences:
|TMean|
Examples:
Prepare two zones, the first one being twice as large
as the second one:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(2)
>>> derived.relzonearea(2.0/3.0, 1.0/3.0)
With temperature values of 5°C and 8°C of the respective zones,
the mean temperature is 6°C:
>>> fluxes.tc = 5.0, 8.0
>>> model.calc_tmean_v1()
>>> fluxes.tmean
tmean(6.0)
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
flu.tmean = 0.
for k in range(con.nmbzones):
flu.tmean += der.relzonearea[k]*flu.tc[k] |
<SYSTEM_TASK:>
Apply the precipitation correction factors and adjust precipitation
<END_TASK>
<USER_TASK:>
Description:
def calc_pc_v1(self):
"""Apply the precipitation correction factors and adjust precipitation
to the altitude of the individual zones.
Required control parameters:
|NmbZones|
|PCorr|
|PCAlt|
|ZoneZ|
|ZRelP|
Required input sequence:
|P|
Required flux sequences:
|RfC|
|SfC|
Calculated flux sequences:
|PC|
Basic equation:
:math:`PC = P \\cdot PCorr
\\cdot (1+PCAlt \\cdot (ZoneZ-ZRelP))
\\cdot (RfC + SfC)`
Examples:
Five zones are at an elevation of 200 m. A precipitation value
of 5 mm has been measured at a gauge at an elevation of 300 m:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(5)
>>> zrelp(2.0)
>>> zonez(3.0)
>>> inputs.p = 5.0
The first four zones illustrate the individual precipitation
corrections due to the general precipitation correction factor
(|PCorr|, first zone), the altitude correction factor (|PCAlt|,
second zone), the rainfall related correction (|RfC|, third zone),
and the snowfall related correction factor (|SfC|, fourth zone).
The fifth zone illustrates the interaction between all corrections:
>>> pcorr(1.3, 1.0, 1.0, 1.0, 1.3)
>>> pcalt(0.0, 0.1, 0.0, 0.0, 0.1)
>>> fluxes.rfc = 0.5, 0.5, 0.4, 0.5, 0.4
>>> fluxes.sfc = 0.5, 0.5, 0.5, 0.7, 0.7
>>> model.calc_pc_v1()
>>> fluxes.pc
pc(6.5, 5.5, 4.5, 6.0, 7.865)
Usually, one would set zero or positive values for parameter |PCAlt|.
But it is also allowed to set negative values, in order to reflect
possible negative relationships between precipitation and altitude.
To prevent from calculating negative precipitation when too large
negative values are applied, a truncation is performed:
>>> pcalt(-1.0)
>>> model.calc_pc_v1()
>>> fluxes.pc
pc(0.0, 0.0, 0.0, 0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
inp = self.sequences.inputs.fastaccess
flu = self.sequences.fluxes.fastaccess
for k in range(con.nmbzones):
flu.pc[k] = inp.p*(1.+con.pcalt[k]*(con.zonez[k]-con.zrelp))
if flu.pc[k] <= 0.:
flu.pc[k] = 0.
else:
flu.pc[k] *= con.pcorr[k]*(flu.rfc[k]+flu.sfc[k]) |
<SYSTEM_TASK:>
Adjust potential norm evaporation to the actual temperature.
<END_TASK>
<USER_TASK:>
Description:
def calc_ep_v1(self):
"""Adjust potential norm evaporation to the actual temperature.
Required control parameters:
|NmbZones|
|ETF|
Required input sequence:
|EPN|
|TN|
Required flux sequence:
|TMean|
Calculated flux sequences:
|EP|
Basic equation:
:math:`EP = EPN \\cdot (1 + ETF \\cdot (TMean - TN))`
Restriction:
:math:`0 \\leq EP \\leq 2 \\cdot EPN`
Examples:
Assume four zones with different values of the temperature
related factor for the adjustment of evaporation (the
negative value of the first zone is not meaningful, but used
for illustration purporses):
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(4)
>>> etf(-0.5, 0.0, 0.1, 0.5)
>>> inputs.tn = 20.0
>>> inputs.epn = 2.0
With mean temperature equal to norm temperature, actual
(uncorrected) evaporation is equal to norm evaporation:
>>> fluxes.tmean = 20.0
>>> model.calc_ep_v1()
>>> fluxes.ep
ep(2.0, 2.0, 2.0, 2.0)
With mean temperature 5°C higher than norm temperature, potential
evaporation is increased by 1 mm for the third zone, which
possesses a very common adjustment factor. For the first zone,
potential evaporation is 0 mm (which is the smallest value
allowed), and for the fourth zone it is the double value of the
norm evaporation (which is the largest value allowed):
>>> fluxes.tmean = 25.0
>>> model.calc_ep_v1()
>>> fluxes.ep
ep(0.0, 2.0, 3.0, 4.0)
""" |
con = self.parameters.control.fastaccess
inp = self.sequences.inputs.fastaccess
flu = self.sequences.fluxes.fastaccess
for k in range(con.nmbzones):
flu.ep[k] = inp.epn*(1.+con.etf[k]*(flu.tmean-inp.tn))
flu.ep[k] = min(max(flu.ep[k], 0.), 2.*inp.epn) |
<SYSTEM_TASK:>
Apply the evaporation correction factors and adjust evaporation
<END_TASK>
<USER_TASK:>
Description:
def calc_epc_v1(self):
"""Apply the evaporation correction factors and adjust evaporation
to the altitude of the individual zones.
Calculate the areal mean of (uncorrected) potential evaporation
for the subbasin, adjust it to the individual zones in accordance
with their heights and perform some corrections, among which one
depends on the actual precipitation.
Required control parameters:
|NmbZones|
|ECorr|
|ECAlt|
|ZoneZ|
|ZRelE|
|EPF|
Required flux sequences:
|EP|
|PC|
Calculated flux sequences:
|EPC|
Basic equation:
:math:`EPC = EP \\cdot ECorr
\\cdot (1+ECAlt \\cdot (ZoneZ-ZRelE))
\\cdot exp(-EPF \\cdot PC)`
Examples:
Four zones are at an elevation of 200 m. A (uncorrected)
potential evaporation value of 2 mm and a (corrected) precipitation
value of 5 mm have been determined for each zone beforehand:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> simulationstep('12h')
>>> nmbzones(4)
>>> zrele(2.0)
>>> zonez(3.0)
>>> fluxes.ep = 2.0
>>> fluxes.pc = 5.0
The first three zones illustrate the individual evaporation
corrections due to the general evaporation correction factor
(|ECorr|, first zone), the altitude correction factor (|ECAlt|,
second zone), the precipitation related correction factor
(|EPF|, third zone). The fourth zone illustrates the interaction
between all corrections:
>>> ecorr(1.3, 1.0, 1.0, 1.3)
>>> ecalt(0.0, 0.1, 0.0, 0.1)
>>> epf(0.0, 0.0, -numpy.log(0.7)/10.0, -numpy.log(0.7)/10.0)
>>> model.calc_epc_v1()
>>> fluxes.epc
epc(2.6, 1.8, 1.4, 1.638)
To prevent from calculating negative evaporation values when too
large values for parameter |ECAlt| are set, a truncation is performed:
>>> ecalt(2.0)
>>> model.calc_epc_v1()
>>> fluxes.epc
epc(0.0, 0.0, 0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
for k in range(con.nmbzones):
flu.epc[k] = (flu.ep[k]*con.ecorr[k] *
(1. - con.ecalt[k]*(con.zonez[k]-con.zrele)))
if flu.epc[k] <= 0.:
flu.epc[k] = 0.
else:
flu.epc[k] *= modelutils.exp(-con.epf[k]*flu.pc[k]) |
<SYSTEM_TASK:>
Calculate throughfall and update the interception storage
<END_TASK>
<USER_TASK:>
Description:
def calc_tf_ic_v1(self):
"""Calculate throughfall and update the interception storage
accordingly.
Required control parameters:
|NmbZones|
|ZoneType|
|IcMax|
Required flux sequences:
|PC|
Calculated fluxes sequences:
|TF|
Updated state sequence:
|Ic|
Basic equation:
:math:`TF = \\Bigl \\lbrace
{
{PC \\ | \\ Ic = IcMax}
\\atop
{0 \\ | \\ Ic < IcMax}
}`
Examples:
Initialize six zones of different types. Assume a
generall maximum interception capacity of 2 mm. All zones receive
a 0.5 mm input of precipitation:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(6)
>>> zonetype(GLACIER, ILAKE, FIELD, FOREST, FIELD, FIELD)
>>> icmax(2.0)
>>> fluxes.pc = 0.5
>>> states.ic = 0.0, 0.0, 0.0, 0.0, 1.0, 2.0
>>> model.calc_tf_ic_v1()
For glaciers (first zone) and internal lakes (second zone) the
interception routine does not apply. Hence, all precipitation is
routed as throughfall. For fields and forests, the interception
routine is identical (usually, only larger capacities for forests
are assumed, due to their higher leaf area index). Hence, the
results of the third and the second zone are equal. The last
three zones demonstrate, that all precipitation is stored until
the interception capacity is reached; afterwards, all precepitation
is routed as throughfall. Initial storage reduces the effective
capacity of the respective simulation step:
>>> states.ic
ic(0.0, 0.0, 0.5, 0.5, 1.5, 2.0)
>>> fluxes.tf
tf(0.5, 0.5, 0.0, 0.0, 0.0, 0.5)
A zero precipitation example:
>>> fluxes.pc = 0.0
>>> states.ic = 0.0, 0.0, 0.0, 0.0, 1.0, 2.0
>>> model.calc_tf_ic_v1()
>>> states.ic
ic(0.0, 0.0, 0.0, 0.0, 1.0, 2.0)
>>> fluxes.tf
tf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
A high precipitation example:
>>> fluxes.pc = 5.0
>>> states.ic = 0.0, 0.0, 0.0, 0.0, 1.0, 2.0
>>> model.calc_tf_ic_v1()
>>> states.ic
ic(0.0, 0.0, 2.0, 2.0, 2.0, 2.0)
>>> fluxes.tf
tf(5.0, 5.0, 3.0, 3.0, 4.0, 5.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
for k in range(con.nmbzones):
if con.zonetype[k] in (FIELD, FOREST):
flu.tf[k] = max(flu.pc[k]-(con.icmax[k]-sta.ic[k]), 0.)
sta.ic[k] += flu.pc[k]-flu.tf[k]
else:
flu.tf[k] = flu.pc[k]
sta.ic[k] = 0. |
<SYSTEM_TASK:>
Add throughfall to the snow layer.
<END_TASK>
<USER_TASK:>
Description:
def calc_sp_wc_v1(self):
"""Add throughfall to the snow layer.
Required control parameters:
|NmbZones|
|ZoneType|
Required flux sequences:
|TF|
|RfC|
|SfC|
Updated state sequences:
|WC|
|SP|
Basic equations:
:math:`\\frac{dSP}{dt} = TF \\cdot \\frac{SfC}{SfC+RfC}` \n
:math:`\\frac{dWC}{dt} = TF \\cdot \\frac{RfC}{SfC+RfC}`
Exemples:
Consider the following setting, in which eight zones of
different type receive a throughfall of 10mm:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(8)
>>> zonetype(ILAKE, GLACIER, FIELD, FOREST, FIELD, FIELD, FIELD, FIELD)
>>> fluxes.tf = 10.0
>>> fluxes.sfc = 0.5, 0.5, 0.5, 0.5, 0.2, 0.8, 1.0, 4.0
>>> fluxes.rfc = 0.5, 0.5, 0.5, 0.5, 0.8, 0.2, 4.0, 1.0
>>> states.sp = 0.0
>>> states.wc = 0.0
>>> model.calc_sp_wc_v1()
>>> states.sp
sp(0.0, 5.0, 5.0, 5.0, 2.0, 8.0, 2.0, 8.0)
>>> states.wc
wc(0.0, 5.0, 5.0, 5.0, 8.0, 2.0, 8.0, 2.0)
The snow routine does not apply for internal lakes, which is why
both the ice storage and the water storage of the first zone
remain unchanged. The snow routine is identical for glaciers,
fields and forests in the current context, which is why the
results of the second, third, and fourth zone are equal. The
last four zones illustrate that the corrected snowfall fraction
as well as the corrected rainfall fraction are applied in a
relative manner, as the total amount of water yield has been
corrected in the interception module already.
When both factors are zero, the neither the water nor the ice
content of the snow layer changes:
>>> fluxes.sfc = 0.0
>>> fluxes.rfc = 0.0
>>> states.sp = 2.0
>>> states.wc = 0.0
>>> model.calc_sp_wc_v1()
>>> states.sp
sp(0.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0)
>>> states.wc
wc(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
for k in range(con.nmbzones):
if con.zonetype[k] != ILAKE:
if (flu.rfc[k]+flu.sfc[k]) > 0.:
sta.wc[k] += flu.tf[k]*flu.rfc[k]/(flu.rfc[k]+flu.sfc[k])
sta.sp[k] += flu.tf[k]*flu.sfc[k]/(flu.rfc[k]+flu.sfc[k])
else:
sta.wc[k] = 0.
sta.sp[k] = 0. |
<SYSTEM_TASK:>
Calculate refreezing of the water content within the snow layer and
<END_TASK>
<USER_TASK:>
Description:
def calc_refr_sp_wc_v1(self):
"""Calculate refreezing of the water content within the snow layer and
update both the snow layers ice and the water content.
Required control parameters:
|NmbZones|
|ZoneType|
|CFMax|
|CFR|
Required derived parameter:
|TTM|
Required flux sequences:
|TC|
Calculated fluxes sequences:
|Refr|
Required state sequence:
|WC|
Updated state sequence:
|SP|
Basic equations:
:math:`\\frac{dSP}{dt} = + Refr` \n
:math:`\\frac{dWC}{dt} = - Refr` \n
:math:`Refr = min(cfr \\cdot cfmax \\cdot (TTM-TC), WC)`
Examples:
Six zones are initialized with the same threshold
temperature, degree day factor and refreezing coefficient, but
with different zone types and initial states:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> simulationstep('12h')
>>> nmbzones(6)
>>> zonetype(ILAKE, GLACIER, FIELD, FOREST, FIELD, FIELD)
>>> cfmax(4.0)
>>> cfr(0.1)
>>> derived.ttm = 2.0
>>> states.sp = 2.0
>>> states.wc = 0.0, 1.0, 1.0, 1.0, 0.5, 0.0
Note that the assumed length of the simulation step is only
a half day. Hence the effective value of the degree day
factor is not 4 but 2:
>>> cfmax
cfmax(4.0)
>>> cfmax.values
array([ 2., 2., 2., 2., 2., 2.])
When the actual temperature is equal to the threshold
temperature for melting and refreezing, neither no refreezing
occurs and the states remain unchanged:
>>> fluxes.tc = 2.0
>>> model.calc_refr_sp_wc_v1()
>>> fluxes.refr
refr(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
>>> states.sp
sp(0.0, 2.0, 2.0, 2.0, 2.0, 2.0)
>>> states.wc
wc(0.0, 1.0, 1.0, 1.0, 0.5, 0.0)
The same holds true for an actual temperature higher than the
threshold temperature:
>>> states.sp = 2.0
>>> states.wc = 0.0, 1.0, 1.0, 1.0, 0.5, 0.0
>>> fluxes.tc = 2.0
>>> model.calc_refr_sp_wc_v1()
>>> fluxes.refr
refr(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
>>> states.sp
sp(0.0, 2.0, 2.0, 2.0, 2.0, 2.0)
>>> states.wc
wc(0.0, 1.0, 1.0, 1.0, 0.5, 0.0)
With an actual temperature 3°C above the threshold temperature,
only melting can occur. Actual melting is consistent with
potential melting, except for the first zone, which is an
internal lake, and the last two zones, for which potential
melting exceeds the available frozen water content of the
snow layer:
>>> states.sp = 2.0
>>> states.wc = 0.0, 1.0, 1.0, 1.0, 0.5, 0.0
>>> fluxes.tc = 5.0
>>> model.calc_refr_sp_wc_v1()
>>> fluxes.refr
refr(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
>>> states.sp
sp(0.0, 2.0, 2.0, 2.0, 2.0, 2.0)
>>> states.wc
wc(0.0, 1.0, 1.0, 1.0, 0.5, 0.0)
With an actual temperature 3°C below the threshold temperature,
refreezing can occur. Actual refreezing is consistent with
potential refreezing, except for the first zone, which is an
internal lake, and the last two zones, for which potential
refreezing exceeds the available liquid water content of the
snow layer:
>>> states.sp = 2.0
>>> states.wc = 0.0, 1.0, 1.0, 1.0, 0.5, 0.0
>>> fluxes.tc = -1.0
>>> model.calc_refr_sp_wc_v1()
>>> fluxes.refr
refr(0.0, 0.6, 0.6, 0.6, 0.5, 0.0)
>>> states.sp
sp(0.0, 2.6, 2.6, 2.6, 2.5, 2.0)
>>> states.wc
wc(0.0, 0.4, 0.4, 0.4, 0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
for k in range(con.nmbzones):
if con.zonetype[k] != ILAKE:
if flu.tc[k] < der.ttm[k]:
flu.refr[k] = min(con.cfr[k]*con.cfmax[k] *
(der.ttm[k]-flu.tc[k]), sta.wc[k])
sta.sp[k] += flu.refr[k]
sta.wc[k] -= flu.refr[k]
else:
flu.refr[k] = 0.
else:
flu.refr[k] = 0.
sta.wc[k] = 0.
sta.sp[k] = 0. |
<SYSTEM_TASK:>
Calculate melting from glaciers which are actually not covered by
<END_TASK>
<USER_TASK:>
Description:
def calc_glmelt_in_v1(self):
"""Calculate melting from glaciers which are actually not covered by
a snow layer and add it to the water release of the snow module.
Required control parameters:
|NmbZones|
|ZoneType|
|GMelt|
Required state sequence:
|SP|
Required flux sequence:
|TC|
Calculated fluxes sequence:
|GlMelt|
Updated flux sequence:
|In_|
Basic equation:
:math:`GlMelt = \\Bigl \\lbrace
{
{max(GMelt \\cdot (TC-TTM), 0) \\ | \\ SP = 0}
\\atop
{0 \\ | \\ SP > 0}
}`
Examples:
Seven zones are prepared, but glacier melting occurs only
in the fourth one, as the first three zones are no glaciers, the
fifth zone is covered by a snow layer and the actual temperature
of the last two zones is not above the threshold temperature:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> simulationstep('12h')
>>> nmbzones(7)
>>> zonetype(FIELD, FOREST, ILAKE, GLACIER, GLACIER, GLACIER, GLACIER)
>>> gmelt(4.)
>>> derived.ttm(2.)
>>> states.sp = 0., 0., 0., 0., .1, 0., 0.
>>> fluxes.tc = 3., 3., 3., 3., 3., 2., 1.
>>> fluxes.in_ = 3.
>>> model.calc_glmelt_in_v1()
>>> fluxes.glmelt
glmelt(0.0, 0.0, 0.0, 2.0, 0.0, 0.0, 0.0)
>>> fluxes.in_
in_(3.0, 3.0, 3.0, 5.0, 3.0, 3.0, 3.0)
Note that the assumed length of the simulation step is only
a half day. Hence the effective value of the degree day factor
is not 4 but 2:
>>> gmelt
gmelt(4.0)
>>> gmelt.values
array([ 2., 2., 2., 2., 2., 2., 2.])
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
for k in range(con.nmbzones):
if ((con.zonetype[k] == GLACIER) and
(sta.sp[k] <= 0.) and (flu.tc[k] > der.ttm[k])):
flu.glmelt[k] = con.gmelt[k]*(flu.tc[k]-der.ttm[k])
flu.in_[k] += flu.glmelt[k]
else:
flu.glmelt[k] = 0. |
<SYSTEM_TASK:>
Calculate effective precipitation and update soil moisture.
<END_TASK>
<USER_TASK:>
Description:
def calc_r_sm_v1(self):
"""Calculate effective precipitation and update soil moisture.
Required control parameters:
|NmbZones|
|ZoneType|
|FC|
|Beta|
Required fluxes sequence:
|In_|
Calculated flux sequence:
|R|
Updated state sequence:
|SM|
Basic equations:
:math:`\\frac{dSM}{dt} = IN - R` \n
:math:`R = IN \\cdot \\left(\\frac{SM}{FC}\\right)^{Beta}`
Examples:
Initialize six zones of different types. The field
capacity of all fields and forests is set to 200mm, the input
of each zone is 10mm:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(6)
>>> zonetype(ILAKE, GLACIER, FIELD, FOREST, FIELD, FIELD)
>>> fc(200.0)
>>> fluxes.in_ = 10.0
With a common nonlinearity parameter value of 2, a relative
soil moisture of 50% (zones three and four) results in a
discharge coefficient of 25%. For a soil completely dried
(zone five) or completely saturated (one six) the discharge
coefficient does not depend on the nonlinearity parameter and
is 0% and 100% respectively. Glaciers and internal lakes also
always route 100% of their input as effective precipitation:
>>> beta(2.0)
>>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0
>>> model.calc_r_sm_v1()
>>> fluxes.r
r(10.0, 10.0, 2.5, 2.5, 0.0, 10.0)
>>> states.sm
sm(0.0, 0.0, 107.5, 107.5, 10.0, 200.0)
Through decreasing the nonlinearity parameter, the discharge
coefficient increases. A parameter value of zero leads to a
discharge coefficient of 100% for any soil moisture:
>>> beta(0.0)
>>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0
>>> model.calc_r_sm_v1()
>>> fluxes.r
r(10.0, 10.0, 10.0, 10.0, 10.0, 10.0)
>>> states.sm
sm(0.0, 0.0, 100.0, 100.0, 0.0, 200.0)
With zero field capacity, the discharge coefficient also always
equates to 100%:
>>> fc(0.0)
>>> beta(2.0)
>>> states.sm = 0.0
>>> model.calc_r_sm_v1()
>>> fluxes.r
r(10.0, 10.0, 10.0, 10.0, 10.0, 10.0)
>>> states.sm
sm(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
for k in range(con.nmbzones):
if con.zonetype[k] in (FIELD, FOREST):
if con.fc[k] > 0.:
flu.r[k] = flu.in_[k]*(sta.sm[k]/con.fc[k])**con.beta[k]
flu.r[k] = max(flu.r[k], sta.sm[k]+flu.in_[k]-con.fc[k])
else:
flu.r[k] = flu.in_[k]
sta.sm[k] += flu.in_[k]-flu.r[k]
else:
flu.r[k] = flu.in_[k]
sta.sm[k] = 0. |
<SYSTEM_TASK:>
Calculate capillary flow and update soil moisture.
<END_TASK>
<USER_TASK:>
Description:
def calc_cf_sm_v1(self):
"""Calculate capillary flow and update soil moisture.
Required control parameters:
|NmbZones|
|ZoneType|
|FC|
|CFlux|
Required fluxes sequence:
|R|
Required state sequence:
|UZ|
Calculated flux sequence:
|CF|
Updated state sequence:
|SM|
Basic equations:
:math:`\\frac{dSM}{dt} = CF` \n
:math:`CF = CFLUX \\cdot (1 - \\frac{SM}{FC})`
Examples:
Initialize six zones of different types. The field
capacity of als fields and forests is set to 200mm, the maximum
capillary flow rate is 4mm/d:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> simulationstep('12h')
>>> nmbzones(6)
>>> zonetype(ILAKE, GLACIER, FIELD, FOREST, FIELD, FIELD)
>>> fc(200.0)
>>> cflux(4.0)
Note that the assumed length of the simulation step is only
a half day. Hence the maximum capillary flow per simulation
step is 2 instead of 4:
>>> cflux
cflux(4.0)
>>> cflux.values
array([ 2., 2., 2., 2., 2., 2.])
For fields and forests, the actual capillary return flow depends
on the relative soil moisture deficite, if either the upper zone
layer provides enough water...
>>> fluxes.r = 0.0
>>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0
>>> states.uz = 20.0
>>> model.calc_cf_sm_v1()
>>> fluxes.cf
cf(0.0, 0.0, 1.0, 1.0, 2.0, 0.0)
>>> states.sm
sm(0.0, 0.0, 101.0, 101.0, 2.0, 200.0)
...our enough effective precipitation is generated, which can be
rerouted directly:
>>> cflux(4.0)
>>> fluxes.r = 10.0
>>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0
>>> states.uz = 0.0
>>> model.calc_cf_sm_v1()
>>> fluxes.cf
cf(0.0, 0.0, 1.0, 1.0, 2.0, 0.0)
>>> states.sm
sm(0.0, 0.0, 101.0, 101.0, 2.0, 200.0)
If the upper zone layer is empty and no effective precipitation is
generated, capillary flow is zero:
>>> cflux(4.0)
>>> fluxes.r = 0.0
>>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0
>>> states.uz = 0.0
>>> model.calc_cf_sm_v1()
>>> fluxes.cf
cf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
>>> states.sm
sm(0.0, 0.0, 100.0, 100.0, 0.0, 200.0)
Here an example, where both the upper zone layer and effective
precipitation provide water for the capillary flow, but less then
the maximum flow rate times the relative soil moisture:
>>> cflux(4.0)
>>> fluxes.r = 0.1
>>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0
>>> states.uz = 0.2
>>> model.calc_cf_sm_v1()
>>> fluxes.cf
cf(0.0, 0.0, 0.3, 0.3, 0.3, 0.0)
>>> states.sm
sm(0.0, 0.0, 100.3, 100.3, 0.3, 200.0)
Even unrealistic high maximum capillary flow rates do not result
in overfilled soils:
>>> cflux(1000.0)
>>> fluxes.r = 200.0
>>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0
>>> states.uz = 200.0
>>> model.calc_cf_sm_v1()
>>> fluxes.cf
cf(0.0, 0.0, 100.0, 100.0, 200.0, 0.0)
>>> states.sm
sm(0.0, 0.0, 200.0, 200.0, 200.0, 200.0)
For (unrealistic) soils with zero field capacity, capillary flow
is always zero:
>>> fc(0.0)
>>> states.sm = 0.0
>>> model.calc_cf_sm_v1()
>>> fluxes.cf
cf(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
>>> states.sm
sm(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
for k in range(con.nmbzones):
if con.zonetype[k] in (FIELD, FOREST):
if con.fc[k] > 0.:
flu.cf[k] = con.cflux[k]*(1.-sta.sm[k]/con.fc[k])
flu.cf[k] = min(flu.cf[k], sta.uz+flu.r[k])
flu.cf[k] = min(flu.cf[k], con.fc[k]-sta.sm[k])
else:
flu.cf[k] = 0.
sta.sm[k] += flu.cf[k]
else:
flu.cf[k] = 0.
sta.sm[k] = 0. |
<SYSTEM_TASK:>
Calculate soil evaporation and update soil moisture.
<END_TASK>
<USER_TASK:>
Description:
def calc_ea_sm_v1(self):
"""Calculate soil evaporation and update soil moisture.
Required control parameters:
|NmbZones|
|ZoneType|
|FC|
|LP|
|ERed|
Required fluxes sequences:
|EPC|
|EI|
Required state sequence:
|SP|
Calculated flux sequence:
|EA|
Updated state sequence:
|SM|
Basic equations:
:math:`\\frac{dSM}{dt} = - EA` \n
:math:`EA_{temp} = \\biggl \\lbrace
{
{EPC \\cdot min\\left(\\frac{SM}{LP \\cdot FC}, 1\\right)
\\ | \\ SP = 0}
\\atop
{0 \\ | \\ SP > 0}
}` \n
:math:`EA = EA_{temp} - max(ERED \\cdot (EA_{temp} + EI - EPC), 0)`
Examples:
Initialize seven zones of different types. The field capacity
of all fields and forests is set to 200mm, potential evaporation
and interception evaporation are 2mm and 1mm respectively:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(7)
>>> zonetype(ILAKE, GLACIER, FIELD, FOREST, FIELD, FIELD, FIELD)
>>> fc(200.0)
>>> lp(0.0, 0.0, 0.5, 0.5, 0.0, 0.8, 1.0)
>>> ered(0.0)
>>> fluxes.epc = 2.0
>>> fluxes.ei = 1.0
>>> states.sp = 0.0
Only fields and forests include soils; for glaciers and zones (the
first two zones) no soil evaporation is performed. For fields and
forests, the underlying calculations are the same. In the following
example, the relative soil moisture is 50% in all field and forest
zones. Hence, differences in soil evaporation are related to the
different soil evaporation parameter values only:
>>> states.sm = 100.0
>>> model.calc_ea_sm_v1()
>>> fluxes.ea
ea(0.0, 0.0, 2.0, 2.0, 2.0, 1.25, 1.0)
>>> states.sm
sm(0.0, 0.0, 98.0, 98.0, 98.0, 98.75, 99.0)
In the last example, evaporation values of 2mm have been calculated
for some zones despite the fact, that these 2mm added to the actual
interception evaporation of 1mm exceed potential evaporation. This
behaviour can be reduced...
>>> states.sm = 100.0
>>> ered(0.5)
>>> model.calc_ea_sm_v1()
>>> fluxes.ea
ea(0.0, 0.0, 1.5, 1.5, 1.5, 1.125, 1.0)
>>> states.sm
sm(0.0, 0.0, 98.5, 98.5, 98.5, 98.875, 99.0)
...or be completely excluded:
>>> states.sm = 100.0
>>> ered(1.0)
>>> model.calc_ea_sm_v1()
>>> fluxes.ea
ea(0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0)
>>> states.sm
sm(0.0, 0.0, 99.0, 99.0, 99.0, 99.0, 99.0)
Any occurrence of a snow layer suppresses soil evaporation
completely:
>>> states.sp = 0.01
>>> states.sm = 100.0
>>> model.calc_ea_sm_v1()
>>> fluxes.ea
ea(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
>>> states.sm
sm(0.0, 0.0, 100.0, 100.0, 100.0, 100.0, 100.0)
For (unrealistic) soils with zero field capacity, soil evaporation
is always zero:
>>> fc(0.0)
>>> states.sm = 0.0
>>> model.calc_ea_sm_v1()
>>> fluxes.ea
ea(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
>>> states.sm
sm(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
for k in range(con.nmbzones):
if con.zonetype[k] in (FIELD, FOREST):
if sta.sp[k] <= 0.:
if (con.lp[k]*con.fc[k]) > 0.:
flu.ea[k] = flu.epc[k]*sta.sm[k]/(con.lp[k]*con.fc[k])
flu.ea[k] = min(flu.ea[k], flu.epc[k])
else:
flu.ea[k] = flu.epc[k]
flu.ea[k] -= max(con.ered[k] *
(flu.ea[k]+flu.ei[k]-flu.epc[k]), 0.)
flu.ea[k] = min(flu.ea[k], sta.sm[k])
else:
flu.ea[k] = 0.
sta.sm[k] -= flu.ea[k]
else:
flu.ea[k] = 0.
sta.sm[k] = 0. |
<SYSTEM_TASK:>
Accumulate the total inflow into the upper zone layer.
<END_TASK>
<USER_TASK:>
Description:
def calc_inuz_v1(self):
"""Accumulate the total inflow into the upper zone layer.
Required control parameters:
|NmbZones|
|ZoneType|
Required derived parameters:
|RelLandZoneArea|
Required fluxes sequences:
|R|
|CF|
Calculated flux sequence:
|InUZ|
Basic equation:
:math:`InUZ = R - CF`
Examples:
Initialize three zones of different relative `land sizes`
(area related to the total size of the subbasin except lake areas):
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(3)
>>> zonetype(FIELD, ILAKE, GLACIER)
>>> derived.rellandzonearea = 2.0/3.0, 0.0, 1.0/3.0
>>> fluxes.r = 6.0, 0.0, 2.0
>>> fluxes.cf = 2.0, 0.0, 1.0
>>> model.calc_inuz_v1()
>>> fluxes.inuz
inuz(3.0)
Internal lakes do not contribute to the upper zone layer. Hence
for a subbasin consisting only of interal lakes a zero input
value would be calculated:
>>> zonetype(ILAKE, ILAKE, ILAKE)
>>> model.calc_inuz_v1()
>>> fluxes.inuz
inuz(0.0)
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
flu.inuz = 0.
for k in range(con.nmbzones):
if con.zonetype[k] != ILAKE:
flu.inuz += der.rellandzonearea[k]*(flu.r[k]-flu.cf[k]) |
<SYSTEM_TASK:>
Determine the relative size of the contributing area of the whole
<END_TASK>
<USER_TASK:>
Description:
def calc_contriarea_v1(self):
"""Determine the relative size of the contributing area of the whole
subbasin.
Required control parameters:
|NmbZones|
|ZoneType|
|RespArea|
|FC|
|Beta|
Required derived parameter:
|RelSoilArea|
Required state sequence:
|SM|
Calculated fluxes sequences:
|ContriArea|
Basic equation:
:math:`ContriArea = \\left( \\frac{SM}{FC} \\right)^{Beta}`
Examples:
Four zones are initialized, but only the first two zones
of type field and forest are taken into account in the calculation
of the relative contributing area of the catchment (even, if also
glaciers contribute to the inflow of the upper zone layer):
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(4)
>>> zonetype(FIELD, FOREST, GLACIER, ILAKE)
>>> beta(2.0)
>>> fc(200.0)
>>> resparea(True)
>>> derived.relsoilarea(0.5)
>>> derived.relsoilzonearea(1.0/3.0, 2.0/3.0, 0.0, 0.0)
With a relative soil moisture of 100 % in the whole subbasin, the
contributing area is also estimated as 100 %,...
>>> states.sm = 200.0
>>> model.calc_contriarea_v1()
>>> fluxes.contriarea
contriarea(1.0)
...and relative soil moistures of 0% result in an contributing
area of 0 %:
>>> states.sm = 0.0
>>> model.calc_contriarea_v1()
>>> fluxes.contriarea
contriarea(0.0)
With the given value 2 of the nonlinearity parameter Beta, soil
moisture of 50 % results in a contributing area estimate of 25%:
>>> states.sm = 100.0
>>> model.calc_contriarea_v1()
>>> fluxes.contriarea
contriarea(0.25)
Setting the response area option to False,...
>>> resparea(False)
>>> model.calc_contriarea_v1()
>>> fluxes.contriarea
contriarea(1.0)
... setting the soil area (total area of all field and forest
zones in the subbasin) to zero...,
>>> resparea(True)
>>> derived.relsoilarea(0.0)
>>> model.calc_contriarea_v1()
>>> fluxes.contriarea
contriarea(1.0)
...or setting all field capacities to zero...
>>> derived.relsoilarea(0.5)
>>> fc(0.0)
>>> states.sm = 0.0
>>> model.calc_contriarea_v1()
>>> fluxes.contriarea
contriarea(1.0)
...leads to contributing area values of 100 %.
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
if con.resparea and (der.relsoilarea > 0.):
flu.contriarea = 0.
for k in range(con.nmbzones):
if con.zonetype[k] in (FIELD, FOREST):
if con.fc[k] > 0.:
flu.contriarea += (der.relsoilzonearea[k] *
(sta.sm[k]/con.fc[k])**con.beta[k])
else:
flu.contriarea += der.relsoilzonearea[k]
else:
flu.contriarea = 1. |
<SYSTEM_TASK:>
Perform the upper zone layer routine which determines percolation
<END_TASK>
<USER_TASK:>
Description:
def calc_q0_perc_uz_v1(self):
"""Perform the upper zone layer routine which determines percolation
to the lower zone layer and the fast response of the hland model.
Note that the system behaviour of this method depends strongly on the
specifications of the options |RespArea| and |RecStep|.
Required control parameters:
|RecStep|
|PercMax|
|K|
|Alpha|
Required derived parameters:
|DT|
Required fluxes sequence:
|InUZ|
Calculated fluxes sequences:
|Perc|
|Q0|
Updated state sequence:
|UZ|
Basic equations:
:math:`\\frac{dUZ}{dt} = InUZ - Perc - Q0` \n
:math:`Perc = PercMax \\cdot ContriArea` \n
:math:`Q0 = K * \\cdot \\left( \\frac{UZ}{ContriArea} \\right)^{1+Alpha}`
Examples:
The upper zone layer routine is an exception compared to
the other routines of the HydPy-H-Land model, regarding its
consideration of numerical accuracy. To increase the accuracy of
the numerical integration of the underlying ordinary differential
equation, each simulation step can be divided into substeps, which
are all solved with first order accuracy. In the first example,
this option is omitted through setting the RecStep parameter to one:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> simulationstep('12h')
>>> recstep(2)
>>> derived.dt = 1/recstep
>>> percmax(2.0)
>>> alpha(1.0)
>>> k(2.0)
>>> fluxes.contriarea = 1.0
>>> fluxes.inuz = 0.0
>>> states.uz = 1.0
>>> model.calc_q0_perc_uz_v1()
>>> fluxes.perc
perc(1.0)
>>> fluxes.q0
q0(0.0)
>>> states.uz
uz(0.0)
Due to the sequential calculation of the upper zone routine, the
upper zone storage is drained completely through percolation and
no water is left for fast discharge response. By dividing the
simulation step in 100 substeps, the results are quite different:
>>> recstep(200)
>>> derived.dt = 1.0/recstep
>>> states.uz = 1.0
>>> model.calc_q0_perc_uz_v1()
>>> fluxes.perc
perc(0.786934)
>>> fluxes.q0
q0(0.213066)
>>> states.uz
uz(0.0)
Note that the assumed length of the simulation step is only a
half day. Hence the effective values of the maximum percolation
rate and the storage coefficient is not 2 but 1:
>>> percmax
percmax(2.0)
>>> k
k(2.0)
>>> percmax.value
1.0
>>> k.value
1.0
By decreasing the contributing area one decreases percolation but
increases fast discharge response:
>>> fluxes.contriarea = 0.5
>>> states.uz = 1.0
>>> model.calc_q0_perc_uz_v1()
>>> fluxes.perc
perc(0.434108)
>>> fluxes.q0
q0(0.565892)
>>> states.uz
uz(0.0)
Resetting RecStep leads to more transparent results. Note that, due
to the large value of the storage coefficient and the low accuracy
of the numerical approximation, direct discharge drains the rest of
the upper zone storage:
>>> recstep(2)
>>> derived.dt = 1.0/recstep
>>> states.uz = 1.0
>>> model.calc_q0_perc_uz_v1()
>>> fluxes.perc
perc(0.5)
>>> fluxes.q0
q0(0.5)
>>> states.uz
uz(0.0)
Applying a more reasonable storage coefficient results in:
>>> k(0.5)
>>> states.uz = 1.0
>>> model.calc_q0_perc_uz_v1()
>>> fluxes.perc
perc(0.5)
>>> fluxes.q0
q0(0.25)
>>> states.uz
uz(0.25)
Adding an input of 0.3 mm results the same percolation value (which,
in the given example, is determined by the maximum percolation rate
only), but in an increases value of the direct response (which
always depends on the actual upper zone storage directly):
>>> fluxes.inuz = 0.3
>>> states.uz = 1.0
>>> model.calc_q0_perc_uz_v1()
>>> fluxes.perc
perc(0.5)
>>> fluxes.q0
q0(0.64)
>>> states.uz
uz(0.16)
Due to the same reasons, another increase in numerical accuracy has
no impact on percolation but decreases the direct response in the
given example:
>>> recstep(200)
>>> derived.dt = 1.0/recstep
>>> states.uz = 1.0
>>> model.calc_q0_perc_uz_v1()
>>> fluxes.perc
perc(0.5)
>>> fluxes.q0
q0(0.421708)
>>> states.uz
uz(0.378292)
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
flu.perc = 0.
flu.q0 = 0.
for dummy in range(con.recstep):
# First state update related to the upper zone input.
sta.uz += der.dt*flu.inuz
# Second state update related to percolation.
d_perc = min(der.dt*con.percmax*flu.contriarea, sta.uz)
sta.uz -= d_perc
flu.perc += d_perc
# Third state update related to fast runoff response.
if sta.uz > 0.:
if flu.contriarea > 0.:
d_q0 = (der.dt*con.k *
(sta.uz/flu.contriarea)**(1.+con.alpha))
d_q0 = min(d_q0, sta.uz)
else:
d_q0 = sta.uz
sta.uz -= d_q0
flu.q0 += d_q0
else:
d_q0 = 0. |
<SYSTEM_TASK:>
Calculate lake evaporation.
<END_TASK>
<USER_TASK:>
Description:
def calc_el_lz_v1(self):
"""Calculate lake evaporation.
Required control parameters:
|NmbZones|
|ZoneType|
|TTIce|
Required derived parameters:
|RelZoneArea|
Required fluxes sequences:
|TC|
|EPC|
Updated state sequence:
|LZ|
Basic equations:
:math:`\\frac{dLZ}{dt} = -EL` \n
:math:`EL = \\Bigl \\lbrace
{
{EPC \\ | \\ TC > TTIce}
\\atop
{0 \\ | \\ TC \\leq TTIce}
}`
Examples:
Six zones of the same size are initialized. The first three
zones are no internal lakes, they can not exhibit any lake
evaporation. Of the last three zones, which are internal lakes,
only the last one evaporates water. For zones five and six,
evaporation is suppressed due to an assumed ice layer, whenever
the associated theshold temperature is not exceeded:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(6)
>>> zonetype(FIELD, FOREST, GLACIER, ILAKE, ILAKE, ILAKE)
>>> ttice(-1.0)
>>> derived.relzonearea = 1.0/6.0
>>> fluxes.epc = 0.6
>>> fluxes.tc = 0.0, 0.0, 0.0, 0.0, -1.0, -2.0
>>> states.lz = 10.0
>>> model.calc_el_lz_v1()
>>> fluxes.el
el(0.0, 0.0, 0.0, 0.6, 0.0, 0.0)
>>> states.lz
lz(9.9)
Note that internal lakes always contain water. Hence, the
HydPy-H-Land model allows for negative values of the lower
zone storage:
>>> states.lz = 0.05
>>> model.calc_el_lz_v1()
>>> fluxes.el
el(0.0, 0.0, 0.0, 0.6, 0.0, 0.0)
>>> states.lz
lz(-0.05)
""" |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
for k in range(con.nmbzones):
if (con.zonetype[k] == ILAKE) and (flu.tc[k] > con.ttice[k]):
flu.el[k] = flu.epc[k]
sta.lz -= der.relzonearea[k]*flu.el[k]
else:
flu.el[k] = 0. |
<SYSTEM_TASK:>
Calculate the slow response of the lower zone layer.
<END_TASK>
<USER_TASK:>
Description:
def calc_q1_lz_v1(self):
"""Calculate the slow response of the lower zone layer.
Required control parameters:
|K4|
|Gamma|
Calculated fluxes sequence:
|Q1|
Updated state sequence:
|LZ|
Basic equations:
:math:`\\frac{dLZ}{dt} = -Q1` \n
:math:`Q1 = \\Bigl \\lbrace
{
{K4 \\cdot LZ^{1+Gamma} \\ | \\ LZ > 0}
\\atop
{0 \\ | \\ LZ\\leq 0}
}`
Examples:
As long as the lower zone storage is negative...
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> simulationstep('12h')
>>> k4(0.2)
>>> gamma(0.0)
>>> states.lz = -2.0
>>> model.calc_q1_lz_v1()
>>> fluxes.q1
q1(0.0)
>>> states.lz
lz(-2.0)
...or zero, no slow discharge response occurs:
>>> states.lz = 0.0
>>> model.calc_q1_lz_v1()
>>> fluxes.q1
q1(0.0)
>>> states.lz
lz(0.0)
For storage values above zero the linear...
>>> states.lz = 2.0
>>> model.calc_q1_lz_v1()
>>> fluxes.q1
q1(0.2)
>>> states.lz
lz(1.8)
...or nonlinear storage routing equation applies:
>>> gamma(1.)
>>> states.lz = 2.0
>>> model.calc_q1_lz_v1()
>>> fluxes.q1
q1(0.4)
>>> states.lz
lz(1.6)
Note that the assumed length of the simulation step is only a
half day. Hence the effective value of the storage coefficient
is not 0.2 but 0.1:
>>> k4
k4(0.2)
>>> k4.value
0.1
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
sta = self.sequences.states.fastaccess
if sta.lz > 0.:
flu.q1 = con.k4*sta.lz**(1.+con.gamma)
else:
flu.q1 = 0.
sta.lz -= flu.q1 |
<SYSTEM_TASK:>
Calculate the unit hydrograph input.
<END_TASK>
<USER_TASK:>
Description:
def calc_inuh_v1(self):
"""Calculate the unit hydrograph input.
Required derived parameters:
|RelLandArea|
Required flux sequences:
|Q0|
|Q1|
Calculated flux sequence:
|InUH|
Basic equation:
:math:`InUH = Q0 + Q1`
Example:
The unit hydrographs receives base flow from the whole subbasin
and direct flow from zones of type field, forest and glacier only.
In the following example, these occupy only one half of the
subbasin, which is why the partial input of q0 is halved:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> derived.rellandarea = 0.5
>>> fluxes.q0 = 4.0
>>> fluxes.q1 = 1.0
>>> model.calc_inuh_v1()
>>> fluxes.inuh
inuh(3.0)
""" |
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
flu.inuh = der.rellandarea*flu.q0+flu.q1 |
<SYSTEM_TASK:>
Calculate the total discharge after possible abstractions.
<END_TASK>
<USER_TASK:>
Description:
def calc_qt_v1(self):
"""Calculate the total discharge after possible abstractions.
Required control parameter:
|Abstr|
Required flux sequence:
|OutUH|
Calculated flux sequence:
|QT|
Basic equation:
:math:`QT = max(OutUH - Abstr, 0)`
Examples:
Trying to abstract less then available, as much as available and
less then available results in:
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> simulationstep('12h')
>>> abstr(2.0)
>>> fluxes.outuh = 2.0
>>> model.calc_qt_v1()
>>> fluxes.qt
qt(1.0)
>>> fluxes.outuh = 1.0
>>> model.calc_qt_v1()
>>> fluxes.qt
qt(0.0)
>>> fluxes.outuh = 0.5
>>> model.calc_qt_v1()
>>> fluxes.qt
qt(0.0)
Note that "negative abstractions" are allowed:
>>> abstr(-2.0)
>>> fluxes.outuh = 1.0
>>> model.calc_qt_v1()
>>> fluxes.qt
qt(2.0)
""" |
con = self.parameters.control.fastaccess
flu = self.sequences.fluxes.fastaccess
flu.qt = max(flu.outuh-con.abstr, 0.) |
<SYSTEM_TASK:>
Save all defined auxiliary control files.
<END_TASK>
<USER_TASK:>
Description:
def save(self, parameterstep=None, simulationstep=None):
"""Save all defined auxiliary control files.
The target path is taken from the |ControlManager| object stored
in module |pub|. Hence we initialize one and override its
|property| `currentpath` with a simple |str| object defining the
test target path:
>>> from hydpy import pub
>>> pub.projectname = 'test'
>>> from hydpy.core.filetools import ControlManager
>>> class Test(ControlManager):
... currentpath = 'test_directory'
>>> pub.controlmanager = Test()
Normally, the control files would be written to disk, of course.
But to show (and test) the results in the following doctest,
file writing is temporarily redirected via |Open|:
>>> from hydpy import dummies
>>> from hydpy import Open
>>> with Open():
... dummies.aux.save(
... parameterstep='1d',
... simulationstep='12h')
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test_directory/file1.py
-----------------------------------
# -*- coding: utf-8 -*-
<BLANKLINE>
from hydpy.models.lland_v1 import *
<BLANKLINE>
simulationstep('12h')
parameterstep('1d')
<BLANKLINE>
eqd1(200.0)
<BLANKLINE>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
test_directory/file2.py
-----------------------------------
# -*- coding: utf-8 -*-
<BLANKLINE>
from hydpy.models.lland_v2 import *
<BLANKLINE>
simulationstep('12h')
parameterstep('1d')
<BLANKLINE>
eqd1(200.0)
eqd2(100.0)
<BLANKLINE>
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
""" |
par = parametertools.Parameter
for (modelname, var2aux) in self:
for filename in var2aux.filenames:
with par.parameterstep(parameterstep), \
par.simulationstep(simulationstep):
lines = [parametertools.get_controlfileheader(
modelname, parameterstep, simulationstep)]
for par in getattr(var2aux, filename):
lines.append(repr(par) + '\n')
hydpy.pub.controlmanager.save_file(filename, ''.join(lines)) |
<SYSTEM_TASK:>
Remove the defined variables.
<END_TASK>
<USER_TASK:>
Description:
def remove(self, *values):
"""Remove the defined variables.
The variables to be removed can be selected in two ways. But the
first example shows that passing nothing or an empty iterable to
method |Variable2Auxfile.remove| does not remove any variable:
>>> from hydpy import dummies
>>> v2af = dummies.v2af
>>> v2af.remove()
>>> v2af.remove([])
>>> from hydpy import print_values
>>> print_values(v2af.filenames)
file1, file2
>>> print_values(v2af.variables, width=30)
eqb(5000.0), eqb(10000.0),
eqd1(100.0), eqd2(50.0),
eqi1(2000.0), eqi2(1000.0)
The first option is to pass auxiliary file names:
>>> v2af.remove('file1')
>>> print_values(v2af.filenames)
file2
>>> print_values(v2af.variables)
eqb(10000.0), eqd1(100.0), eqd2(50.0)
The second option is, to pass variables of the correct type
and value:
>>> v2af = dummies.v2af
>>> v2af.remove(v2af.eqb[0])
>>> print_values(v2af.filenames)
file1, file2
>>> print_values(v2af.variables)
eqb(10000.0), eqd1(100.0), eqd2(50.0), eqi1(2000.0), eqi2(1000.0)
One can pass multiple variables or iterables containing variables
at once:
>>> v2af = dummies.v2af
>>> v2af.remove(v2af.eqb, v2af.eqd1, v2af.eqd2)
>>> print_values(v2af.filenames)
file1
>>> print_values(v2af.variables)
eqi1(2000.0), eqi2(1000.0)
Passing an argument that equals neither a registered file name or a
registered variable results in the following exception:
>>> v2af.remove('test')
Traceback (most recent call last):
...
ValueError: While trying to remove the given object `test` of type \
`str` from the actual Variable2AuxFile object, the following error occurred: \
`'test'` is neither a registered filename nor a registered variable.
""" |
for value in objecttools.extract(values, (str, variabletools.Variable)):
try:
deleted_something = False
for fn2var in list(self._type2filename2variable.values()):
for fn_, var in list(fn2var.items()):
if value in (fn_, var):
del fn2var[fn_]
deleted_something = True
if not deleted_something:
raise ValueError(
f'`{repr(value)}` is neither a registered '
f'filename nor a registered variable.')
except BaseException:
objecttools.augment_excmessage(
f'While trying to remove the given object `{value}` '
f'of type `{objecttools.classname(value)}` from the '
f'actual Variable2AuxFile object') |
<SYSTEM_TASK:>
A list of all handled auxiliary file names.
<END_TASK>
<USER_TASK:>
Description:
def filenames(self):
"""A list of all handled auxiliary file names.
>>> from hydpy import dummies
>>> dummies.v2af.filenames
['file1', 'file2']
""" |
fns = set()
for fn2var in self._type2filename2variable.values():
fns.update(fn2var.keys())
return sorted(fns) |
<SYSTEM_TASK:>
Return the auxiliary file name the given variable is allocated
<END_TASK>
<USER_TASK:>
Description:
def get_filename(self, variable):
"""Return the auxiliary file name the given variable is allocated
to or |None| if the given variable is not allocated to any
auxiliary file name.
>>> from hydpy import dummies
>>> eqb = dummies.v2af.eqb[0]
>>> dummies.v2af.get_filename(eqb)
'file1'
>>> eqb += 500.0
>>> dummies.v2af.get_filename(eqb)
""" |
fn2var = self._type2filename2variable.get(type(variable), {})
for (fn_, var) in fn2var.items():
if var == variable:
return fn_
return None |
<SYSTEM_TASK:>
Calculate the smoothing parameter values.
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Calculate the smoothing parameter values.
The following example is explained in some detail in module
|smoothtools|:
>>> from hydpy import pub
>>> pub.timegrids = '2000.01.01', '2000.01.03', '1d'
>>> from hydpy.models.dam import *
>>> parameterstep()
>>> remotedischargesafety(0.0)
>>> remotedischargesafety.values[1] = 2.5
>>> derived.remotedischargesmoothpar.update()
>>> from hydpy.cythons.smoothutils import smooth_logistic1
>>> from hydpy import round_
>>> round_(smooth_logistic1(0.1, derived.remotedischargesmoothpar[0]))
1.0
>>> round_(smooth_logistic1(2.5, derived.remotedischargesmoothpar[1]))
0.99
""" |
metapar = self.subpars.pars.control.remotedischargesafety
self.shape = metapar.shape
self(tuple(smoothtools.calc_smoothpar_logistic1(mp)
for mp in metapar.values)) |
<SYSTEM_TASK:>
Execute the given command in a new process.
<END_TASK>
<USER_TASK:>
Description:
def run_subprocess(command: str, verbose: bool = True, blocking: bool = True) \
-> Optional[subprocess.Popen]:
"""Execute the given command in a new process.
Only when both `verbose` and `blocking` are |True|, |run_subprocess|
prints all responses to the current value of |sys.stdout|:
>>> from hydpy import run_subprocess
>>> import platform
>>> esc = '' if 'windows' in platform.platform().lower() else '\\\\'
>>> run_subprocess(f'python -c print{esc}(1+1{esc})')
2
With verbose being |False|, |run_subprocess| does never print out
anything:
>>> run_subprocess(f'python -c print{esc}(1+1{esc})', verbose=False)
>>> process = run_subprocess('python', blocking=False, verbose=False)
>>> process.kill()
>>> _ = process.communicate()
When `verbose` is |True| and `blocking` is |False|, |run_subprocess|
prints all responses to the console ("invisible" for doctests):
>>> process = run_subprocess('python', blocking=False)
>>> process.kill()
>>> _ = process.communicate()
""" |
if blocking:
result1 = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding='utf-8',
shell=True)
if verbose: # due to doctest replacing sys.stdout
for output in (result1.stdout, result1.stderr):
output = output.strip()
if output:
print(output)
return None
stdouterr = None if verbose else subprocess.DEVNULL
result2 = subprocess.Popen(
command,
stdout=stdouterr,
stderr=stdouterr,
encoding='utf-8',
shell=True)
return result2 |
<SYSTEM_TASK:>
Execute the given Python commands.
<END_TASK>
<USER_TASK:>
Description:
def exec_commands(commands: str, **parameters: Any) -> None:
"""Execute the given Python commands.
Function |exec_commands| is thought for testing purposes only (see
the main documentation on module |hyd|). Seperate individual commands
by semicolons and replaced whitespaces with underscores:
>>> from hydpy.exe.commandtools import exec_commands
>>> import sys
>>> exec_commands("x_=_1+1;print(x)")
Start to execute the commands ['x_=_1+1', 'print(x)'] for testing purposes.
2
|exec_commands| interprets double underscores as a single underscores:
>>> exec_commands("x_=_1;print(x.____class____)")
Start to execute the commands ['x_=_1', 'print(x.____class____)'] \
for testing purposes.
<class 'int'>
|exec_commands| evaluates additional keyword arguments before it
executes the given commands:
>>> exec_commands("e=x==y;print(e)", x=1, y=2)
Start to execute the commands ['e=x==y', 'print(e)'] for testing purposes.
False
""" |
cmdlist = commands.split(';')
print(f'Start to execute the commands {cmdlist} for testing purposes.')
for par, value in parameters.items():
exec(f'{par} = {value}')
for command in cmdlist:
command = command.replace('__', 'temptemptemp')
command = command.replace('_', ' ')
command = command.replace('temptemptemp', '_')
exec(command) |
<SYSTEM_TASK:>
Prepare an empty log file eventually and return its absolute path.
<END_TASK>
<USER_TASK:>
Description:
def prepare_logfile(filename: str) -> str:
"""Prepare an empty log file eventually and return its absolute path.
When passing the "filename" `stdout`, |prepare_logfile| does not
prepare any file and just returns `stdout`:
>>> from hydpy.exe.commandtools import prepare_logfile
>>> prepare_logfile('stdout')
'stdout'
When passing the "filename" `default`, |prepare_logfile| generates a
filename containing the actual date and time, prepares an empty file
on disk, and returns its path:
>>> from hydpy import repr_, TestIO
>>> from hydpy.core.testtools import mock_datetime_now
>>> from datetime import datetime
>>> with TestIO():
... with mock_datetime_now(datetime(2000, 1, 1, 12, 30, 0)):
... filepath = prepare_logfile('default')
>>> import os
>>> os.path.exists(filepath)
True
>>> repr_(filepath) # doctest: +ELLIPSIS
'...hydpy/tests/iotesting/hydpy_2000-01-01_12-30-00.log'
For all other strings, |prepare_logfile| does not add any date or time
information to the filename:
>>> with TestIO():
... with mock_datetime_now(datetime(2000, 1, 1, 12, 30, 0)):
... filepath = prepare_logfile('my_log_file.txt')
>>> os.path.exists(filepath)
True
>>> repr_(filepath) # doctest: +ELLIPSIS
'...hydpy/tests/iotesting/my_log_file.txt'
""" |
if filename == 'stdout':
return filename
if filename == 'default':
filename = datetime.datetime.now().strftime(
'hydpy_%Y-%m-%d_%H-%M-%S.log')
with open(filename, 'w'):
pass
return os.path.abspath(filename) |
<SYSTEM_TASK:>
Execute a HydPy script function.
<END_TASK>
<USER_TASK:>
Description:
def execute_scriptfunction() -> None:
"""Execute a HydPy script function.
Function |execute_scriptfunction| is indirectly applied and
explained in the documentation on module |hyd|.
""" |
try:
args_given = []
kwargs_given = {}
for arg in sys.argv[1:]:
if len(arg) < 3:
args_given.append(arg)
else:
try:
key, value = parse_argument(arg)
kwargs_given[key] = value
except ValueError:
args_given.append(arg)
logfilepath = prepare_logfile(kwargs_given.pop('logfile', 'stdout'))
logstyle = kwargs_given.pop('logstyle', 'plain')
try:
funcname = str(args_given.pop(0))
except IndexError:
raise ValueError(
'The first positional argument defining the function '
'to be called is missing.')
try:
func = hydpy.pub.scriptfunctions[funcname]
except KeyError:
available_funcs = objecttools.enumeration(
sorted(hydpy.pub.scriptfunctions.keys()))
raise ValueError(
f'There is no `{funcname}` function callable by `hyd.py`. '
f'Choose one of the following instead: {available_funcs}.')
args_required = inspect.getfullargspec(func).args
nmb_args_required = len(args_required)
nmb_args_given = len(args_given)
if nmb_args_given != nmb_args_required:
enum_args_given = ''
if nmb_args_given:
enum_args_given = (
f' ({objecttools.enumeration(args_given)})')
enum_args_required = ''
if nmb_args_required:
enum_args_required = (
f' ({objecttools.enumeration(args_required)})')
raise ValueError(
f'Function `{funcname}` requires `{nmb_args_required:d}` '
f'positional arguments{enum_args_required}, but '
f'`{nmb_args_given:d}` are given{enum_args_given}.')
with _activate_logfile(logfilepath, logstyle, 'info', 'warning'):
func(*args_given, **kwargs_given)
except BaseException as exc:
if logstyle not in LogFileInterface.style2infotype2string:
logstyle = 'plain'
with _activate_logfile(logfilepath, logstyle, 'exception', 'exception'):
arguments = ', '.join(sys.argv)
print(f'Invoking hyd.py with arguments `{arguments}` '
f'resulted in the following error:\n{str(exc)}\n\n'
f'See the following stack traceback for debugging:\n',
file=sys.stderr)
traceback.print_tb(sys.exc_info()[2]) |
<SYSTEM_TASK:>
Return a single value for a string understood as a positional
<END_TASK>
<USER_TASK:>
Description:
def parse_argument(string: str) -> Union[str, Tuple[str, str]]:
"""Return a single value for a string understood as a positional
argument or a |tuple| containing a keyword and its value for a
string understood as a keyword argument.
|parse_argument| is intended to be used as a helper function for
function |execute_scriptfunction| only. See the following
examples to see which types of keyword arguments |execute_scriptfunction|
covers:
>>> from hydpy.exe.commandtools import parse_argument
>>> parse_argument('x=3')
('x', '3')
>>> parse_argument('"x=3"')
'"x=3"'
>>> parse_argument("'x=3'")
"'x=3'"
>>> parse_argument('x="3==3"')
('x', '"3==3"')
>>> parse_argument("x='3==3'")
('x', "'3==3'")
""" |
idx_equal = string.find('=')
if idx_equal == -1:
return string
idx_quote = idx_equal+1
for quote in ('"', "'"):
idx = string.find(quote)
if -1 < idx < idx_quote:
idx_quote = idx
if idx_equal < idx_quote:
return string[:idx_equal], string[idx_equal+1:]
return string |
<SYSTEM_TASK:>
Print the given string and the current date and time with high
<END_TASK>
<USER_TASK:>
Description:
def print_textandtime(text: str) -> None:
"""Print the given string and the current date and time with high
precision for logging purposes.
>>> from hydpy.exe.commandtools import print_textandtime
>>> from hydpy.core.testtools import mock_datetime_now
>>> from datetime import datetime
>>> with mock_datetime_now(datetime(2000, 1, 1, 12, 30, 0, 123456)):
... print_textandtime('something happens')
something happens (2000-01-01 12:30:00.123456).
""" |
timestring = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
print(f'{text} ({timestring}).') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.