text
stringlengths
81
112k
Update the outlet link sequence. Required derived parameter: |QFactor| Required flux sequences: |lland_fluxes.Q| Calculated flux sequence: |lland_outlets.Q| Basic equation: :math:`Q_{outlets} = QFactor \\cdot Q_{fluxes}` def pass_q_v1(self): """Update the outlet link sequence. Required derived parameter: |QFactor| Required flux sequences: |lland_fluxes.Q| Calculated flux sequence: |lland_outlets.Q| Basic equation: :math:`Q_{outlets} = QFactor \\cdot Q_{fluxes}` """ der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.q[0] += der.qfactor*flu.q
Performs the actual interpolation or extrapolation. Required control parameters: |XPoints| |YPoints| Required derived parameter: |NmbPoints| |NmbBranches| Required flux sequence: |Input| Calculated flux sequence: |Outputs| Examples: As a simple example, assume a weir directing all discharge into `branch1` until the capacity limit of 2 m³/s is reached. The discharge exceeding this threshold is directed into `branch2`: >>> from hydpy.models.hbranch import * >>> parameterstep() >>> xpoints(0., 2., 4.) >>> ypoints(branch1=[0., 2., 2.], ... branch2=[0., 0., 2.]) >>> model.parameters.update() Low discharge example (linear interpolation between the first two supporting point pairs): >>> fluxes.input = 1. >>> model.calc_outputs_v1() >>> fluxes.outputs outputs(branch1=1.0, branch2=0.0) Medium discharge example (linear interpolation between the second two supporting point pairs): >>> fluxes.input = 3. >>> model.calc_outputs_v1() >>> print(fluxes.outputs) outputs(branch1=2.0, branch2=1.0) High discharge example (linear extrapolation beyond the second two supporting point pairs): >>> fluxes.input = 5. >>> model.calc_outputs_v1() >>> fluxes.outputs outputs(branch1=2.0, branch2=3.0) Non-monotonous relationships and balance violations are allowed, e.g.: >>> xpoints(0., 2., 4., 6.) >>> ypoints(branch1=[0., 2., 0., 0.], ... branch2=[0., 0., 2., 4.]) >>> model.parameters.update() >>> fluxes.input = 7. >>> model.calc_outputs_v1() >>> fluxes.outputs outputs(branch1=0.0, branch2=5.0) def calc_outputs_v1(self): """Performs the actual interpolation or extrapolation. Required control parameters: |XPoints| |YPoints| Required derived parameter: |NmbPoints| |NmbBranches| Required flux sequence: |Input| Calculated flux sequence: |Outputs| Examples: As a simple example, assume a weir directing all discharge into `branch1` until the capacity limit of 2 m³/s is reached. The discharge exceeding this threshold is directed into `branch2`: >>> from hydpy.models.hbranch import * >>> parameterstep() >>> xpoints(0., 2., 4.) >>> ypoints(branch1=[0., 2., 2.], ... branch2=[0., 0., 2.]) >>> model.parameters.update() Low discharge example (linear interpolation between the first two supporting point pairs): >>> fluxes.input = 1. >>> model.calc_outputs_v1() >>> fluxes.outputs outputs(branch1=1.0, branch2=0.0) Medium discharge example (linear interpolation between the second two supporting point pairs): >>> fluxes.input = 3. >>> model.calc_outputs_v1() >>> print(fluxes.outputs) outputs(branch1=2.0, branch2=1.0) High discharge example (linear extrapolation beyond the second two supporting point pairs): >>> fluxes.input = 5. >>> model.calc_outputs_v1() >>> fluxes.outputs outputs(branch1=2.0, branch2=3.0) Non-monotonous relationships and balance violations are allowed, e.g.: >>> xpoints(0., 2., 4., 6.) >>> ypoints(branch1=[0., 2., 0., 0.], ... branch2=[0., 0., 2., 4.]) >>> model.parameters.update() >>> fluxes.input = 7. >>> model.calc_outputs_v1() >>> fluxes.outputs outputs(branch1=0.0, branch2=5.0) """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess # Search for the index of the two relevant x points... for pdx in range(1, der.nmbpoints): if con.xpoints[pdx] > flu.input: break # ...and use it for linear interpolation (or extrapolation). for bdx in range(der.nmbbranches): flu.outputs[bdx] = ( (flu.input-con.xpoints[pdx-1]) * (con.ypoints[bdx, pdx]-con.ypoints[bdx, pdx-1]) / (con.xpoints[pdx]-con.xpoints[pdx-1]) + con.ypoints[bdx, pdx-1])
Updates |Input| based on |Total|. def pick_input_v1(self): """Updates |Input| based on |Total|.""" flu = self.sequences.fluxes.fastaccess inl = self.sequences.inlets.fastaccess flu.input = 0. for idx in range(inl.len_total): flu.input += inl.total[idx][0]
Updates |Branched| based on |Outputs|. def pass_outputs_v1(self): """Updates |Branched| based on |Outputs|.""" der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess for bdx in range(der.nmbbranches): out.branched[bdx][0] += flu.outputs[bdx]
Connect the |LinkSequence| instances handled by the actual model to the |NodeSequence| instances handled by one inlet node and multiple oulet nodes. The HydPy-H-Branch model passes multiple output values to different outlet nodes. This requires additional information regarding the `direction` of each output value. Therefore, node names are used as keywords. Assume the discharge values of both nodes `inflow1` and `inflow2` shall be branched to nodes `outflow1` and `outflow2` via element `branch`: >>> from hydpy import * >>> branch = Element('branch', ... inlets=['inflow1', 'inflow2'], ... outlets=['outflow1', 'outflow2']) Then parameter |YPoints| relates different supporting points via its keyword arguments to the respective nodes: >>> from hydpy.models.hbranch import * >>> parameterstep() >>> xpoints(0.0, 3.0) >>> ypoints(outflow1=[0.0, 1.0], outflow2=[0.0, 2.0]) >>> parameters.update() After connecting the model with its element the total discharge value of nodes `inflow1` and `inflow2` can be properly divided: >>> branch.model = model >>> branch.inlets.inflow1.sequences.sim = 1.0 >>> branch.inlets.inflow2.sequences.sim = 5.0 >>> model.doit(0) >>> print(branch.outlets.outflow1.sequences.sim) sim(2.0) >>> print(branch.outlets.outflow2.sequences.sim) sim(4.0) In case of missing (or misspelled) outlet nodes, the following error is raised: >>> branch.outlets.mutable = True >>> del branch.outlets.outflow1 >>> parameters.update() >>> model.connect() Traceback (most recent call last): ... RuntimeError: Model `hbranch` of element `branch` tried to connect \ to an outlet node named `outflow1`, which is not an available outlet node \ of element `branch`. def connect(self): """Connect the |LinkSequence| instances handled by the actual model to the |NodeSequence| instances handled by one inlet node and multiple oulet nodes. The HydPy-H-Branch model passes multiple output values to different outlet nodes. This requires additional information regarding the `direction` of each output value. Therefore, node names are used as keywords. Assume the discharge values of both nodes `inflow1` and `inflow2` shall be branched to nodes `outflow1` and `outflow2` via element `branch`: >>> from hydpy import * >>> branch = Element('branch', ... inlets=['inflow1', 'inflow2'], ... outlets=['outflow1', 'outflow2']) Then parameter |YPoints| relates different supporting points via its keyword arguments to the respective nodes: >>> from hydpy.models.hbranch import * >>> parameterstep() >>> xpoints(0.0, 3.0) >>> ypoints(outflow1=[0.0, 1.0], outflow2=[0.0, 2.0]) >>> parameters.update() After connecting the model with its element the total discharge value of nodes `inflow1` and `inflow2` can be properly divided: >>> branch.model = model >>> branch.inlets.inflow1.sequences.sim = 1.0 >>> branch.inlets.inflow2.sequences.sim = 5.0 >>> model.doit(0) >>> print(branch.outlets.outflow1.sequences.sim) sim(2.0) >>> print(branch.outlets.outflow2.sequences.sim) sim(4.0) In case of missing (or misspelled) outlet nodes, the following error is raised: >>> branch.outlets.mutable = True >>> del branch.outlets.outflow1 >>> parameters.update() >>> model.connect() Traceback (most recent call last): ... RuntimeError: Model `hbranch` of element `branch` tried to connect \ to an outlet node named `outflow1`, which is not an available outlet node \ of element `branch`. """ nodes = self.element.inlets total = self.sequences.inlets.total if total.shape != (len(nodes),): total.shape = len(nodes) for idx, node in enumerate(nodes): double = node.get_double('inlets') total.set_pointer(double, idx) for (idx, name) in enumerate(self.nodenames): try: outlet = getattr(self.element.outlets, name) double = outlet.get_double('outlets') except AttributeError: raise RuntimeError( f'Model {objecttools.elementphrase(self)} tried ' f'to connect to an outlet node named `{name}`, ' f'which is not an available outlet node of element ' f'`{self.element.name}`.') self.sequences.outlets.branched.set_pointer(double, idx)
Determine the number of response functions. >>> from hydpy.models.arma import * >>> parameterstep('1d') >>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.))) >>> derived.nmb.update() >>> derived.nmb nmb(2) Note that updating parameter `nmb` sets the shape of the flux sequences |QPIn|, |QPOut|, |QMA|, and |QAR| automatically. >>> fluxes.qpin qpin(nan, nan) >>> fluxes.qpout qpout(nan, nan) >>> fluxes.qma qma(nan, nan) >>> fluxes.qar qar(nan, nan) def update(self): """Determine the number of response functions. >>> from hydpy.models.arma import * >>> parameterstep('1d') >>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.))) >>> derived.nmb.update() >>> derived.nmb nmb(2) Note that updating parameter `nmb` sets the shape of the flux sequences |QPIn|, |QPOut|, |QMA|, and |QAR| automatically. >>> fluxes.qpin qpin(nan, nan) >>> fluxes.qpout qpout(nan, nan) >>> fluxes.qma qma(nan, nan) >>> fluxes.qar qar(nan, nan) """ pars = self.subpars.pars responses = pars.control.responses fluxes = pars.model.sequences.fluxes self(len(responses)) fluxes.qpin.shape = self.value fluxes.qpout.shape = self.value fluxes.qma.shape = self.value fluxes.qar.shape = self.value
Determine the total number of AR coefficients. >>> from hydpy.models.arma import * >>> parameterstep('1d') >>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.))) >>> derived.ar_order.update() >>> derived.ar_order ar_order(2, 1) def update(self): """Determine the total number of AR coefficients. >>> from hydpy.models.arma import * >>> parameterstep('1d') >>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.))) >>> derived.ar_order.update() >>> derived.ar_order ar_order(2, 1) """ responses = self.subpars.pars.control.responses self.shape = len(responses) self(responses.ar_orders)
Determine all AR coefficients. >>> from hydpy.models.arma import * >>> parameterstep('1d') >>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.))) >>> derived.ar_coefs.update() >>> derived.ar_coefs ar_coefs([[1.0, 2.0], [1.0, nan]]) Note that updating parameter `ar_coefs` sets the shape of the log sequence |LogOut| automatically. >>> logs.logout logout([[nan, nan], [nan, nan]]) def update(self): """Determine all AR coefficients. >>> from hydpy.models.arma import * >>> parameterstep('1d') >>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.))) >>> derived.ar_coefs.update() >>> derived.ar_coefs ar_coefs([[1.0, 2.0], [1.0, nan]]) Note that updating parameter `ar_coefs` sets the shape of the log sequence |LogOut| automatically. >>> logs.logout logout([[nan, nan], [nan, nan]]) """ pars = self.subpars.pars coefs = pars.control.responses.ar_coefs self.shape = coefs.shape self(coefs) pars.model.sequences.logs.logout.shape = self.shape
Determine all MA coefficients. >>> from hydpy.models.arma import * >>> parameterstep('1d') >>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.))) >>> derived.ma_coefs.update() >>> derived.ma_coefs ma_coefs([[1.0, nan, nan], [1.0, 2.0, 3.0]]) Note that updating parameter `ar_coefs` sets the shape of the log sequence |LogIn| automatically. >>> logs.login login([[nan, nan, nan], [nan, nan, nan]]) def update(self): """Determine all MA coefficients. >>> from hydpy.models.arma import * >>> parameterstep('1d') >>> responses(((1., 2.), (1.,)), th_3=((1.,), (1., 2., 3.))) >>> derived.ma_coefs.update() >>> derived.ma_coefs ma_coefs([[1.0, nan, nan], [1.0, 2.0, 3.0]]) Note that updating parameter `ar_coefs` sets the shape of the log sequence |LogIn| automatically. >>> logs.login login([[nan, nan, nan], [nan, nan, nan]]) """ pars = self.subpars.pars coefs = pars.control.responses.ma_coefs self.shape = coefs.shape self(coefs) pars.model.sequences.logs.login.shape = self.shape
Assign docstrings to the corresponding attributes of class `Options` to make them available in the interactive mode of Python. def _prepare_docstrings(): """Assign docstrings to the corresponding attributes of class `Options` to make them available in the interactive mode of Python.""" if config.USEAUTODOC: source = inspect.getsource(Options) docstrings = source.split('"""')[3::2] attributes = [line.strip().split()[0] for line in source.split('\n') if '_Option(' in line] for attribute, docstring in zip(attributes, docstrings): Options.__dict__[attribute].__doc__ = docstring
A |set| containing the |Node| objects of all handled |Selection| objects. >>> from hydpy import Selection, Selections >>> selections = Selections( ... Selection('sel1', ['node1', 'node2'], ['element1']), ... Selection('sel2', ['node1', 'node3'], ['element2'])) >>> selections.nodes Nodes("node1", "node2", "node3") def nodes(self) -> devicetools.Nodes: """A |set| containing the |Node| objects of all handled |Selection| objects. >>> from hydpy import Selection, Selections >>> selections = Selections( ... Selection('sel1', ['node1', 'node2'], ['element1']), ... Selection('sel2', ['node1', 'node3'], ['element2'])) >>> selections.nodes Nodes("node1", "node2", "node3") """ nodes = devicetools.Nodes() for selection in self: nodes += selection.nodes return nodes
A |set| containing the |Node| objects of all handled |Selection| objects. >>> from hydpy import Selection, Selections >>> selections = Selections( ... Selection('sel1', ['node1'], ['element1']), ... Selection('sel2', ['node1'], ['element2', 'element3'])) >>> selections.elements Elements("element1", "element2", "element3") def elements(self) -> devicetools.Elements: """A |set| containing the |Node| objects of all handled |Selection| objects. >>> from hydpy import Selection, Selections >>> selections = Selections( ... Selection('sel1', ['node1'], ['element1']), ... Selection('sel2', ['node1'], ['element2', 'element3'])) >>> selections.elements Elements("element1", "element2", "element3") """ elements = devicetools.Elements() for selection in self: elements += selection.elements return elements
Try to convert the given argument to a |list| of |Selection| objects and return it. def __getiterable(value): # ToDo: refactor """Try to convert the given argument to a |list| of |Selection| objects and return it. """ if isinstance(value, Selection): return [value] try: for selection in value: if not isinstance(selection, Selection): raise TypeError return list(value) except TypeError: raise TypeError( f'Binary operations on Selections objects are defined for ' f'other Selections objects, single Selection objects, or ' f'iterables containing `Selection` objects, but the type of ' f'the given argument is `{objecttools.classname(value)}`.')
Return a |repr| string with a prefixed assignment. def assignrepr(self, prefix='') -> str: """Return a |repr| string with a prefixed assignment.""" with objecttools.repr_.preserve_strings(True): with hydpy.pub.options.ellipsis(2, optional=True): prefix += '%s(' % objecttools.classname(self) repr_ = objecttools.assignrepr_values( sorted(self.names), prefix, 70) return repr_ + ')'
Return the network upstream of the given starting point, including the starting point itself. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() You can pass both |Node| and |Element| objects and, optionally, the name of the newly created |Selection| object: >>> test = pub.selections.complete.copy('test') >>> test.search_upstream(hp.nodes.lahn_2) Selection("upstream", nodes=("dill", "lahn_1", "lahn_2"), elements=("land_dill", "land_lahn_1", "land_lahn_2", "stream_dill_lahn_2", "stream_lahn_1_lahn_2")) >>> test.search_upstream( ... hp.elements.stream_lahn_1_lahn_2, 'UPSTREAM') Selection("UPSTREAM", nodes="lahn_1", elements=("land_lahn_1", "stream_lahn_1_lahn_2")) Wrong device specifications result in errors like the following: >>> test.search_upstream(1) Traceback (most recent call last): ... TypeError: While trying to determine the upstream network of \ selection `test`, the following error occurred: Either a `Node` or \ an `Element` object is required as the "outlet device", but the given \ `device` value is of type `int`. >>> pub.selections.headwaters.search_upstream(hp.nodes.lahn_3) Traceback (most recent call last): ... KeyError: "While trying to determine the upstream network of \ selection `headwaters`, the following error occurred: 'No node named \ `lahn_3` available.'" Method |Selection.select_upstream| restricts the current selection to the one determined with the method |Selection.search_upstream|: >>> test.select_upstream(hp.nodes.lahn_2) Selection("test", nodes=("dill", "lahn_1", "lahn_2"), elements=("land_dill", "land_lahn_1", "land_lahn_2", "stream_dill_lahn_2", "stream_lahn_1_lahn_2")) On the contrary, the method |Selection.deselect_upstream| restricts the current selection to all devices not determined by method |Selection.search_upstream|: >>> complete = pub.selections.complete.deselect_upstream( ... hp.nodes.lahn_2) >>> complete Selection("complete", nodes="lahn_3", elements=("land_lahn_3", "stream_lahn_2_lahn_3")) If necessary, include the "outlet device" manually afterwards: >>> complete.nodes += hp.nodes.lahn_2 >>> complete Selection("complete", nodes=("lahn_2", "lahn_3"), elements=("land_lahn_3", "stream_lahn_2_lahn_3")) def search_upstream(self, device: devicetools.Device, name: str = 'upstream') -> 'Selection': """Return the network upstream of the given starting point, including the starting point itself. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() You can pass both |Node| and |Element| objects and, optionally, the name of the newly created |Selection| object: >>> test = pub.selections.complete.copy('test') >>> test.search_upstream(hp.nodes.lahn_2) Selection("upstream", nodes=("dill", "lahn_1", "lahn_2"), elements=("land_dill", "land_lahn_1", "land_lahn_2", "stream_dill_lahn_2", "stream_lahn_1_lahn_2")) >>> test.search_upstream( ... hp.elements.stream_lahn_1_lahn_2, 'UPSTREAM') Selection("UPSTREAM", nodes="lahn_1", elements=("land_lahn_1", "stream_lahn_1_lahn_2")) Wrong device specifications result in errors like the following: >>> test.search_upstream(1) Traceback (most recent call last): ... TypeError: While trying to determine the upstream network of \ selection `test`, the following error occurred: Either a `Node` or \ an `Element` object is required as the "outlet device", but the given \ `device` value is of type `int`. >>> pub.selections.headwaters.search_upstream(hp.nodes.lahn_3) Traceback (most recent call last): ... KeyError: "While trying to determine the upstream network of \ selection `headwaters`, the following error occurred: 'No node named \ `lahn_3` available.'" Method |Selection.select_upstream| restricts the current selection to the one determined with the method |Selection.search_upstream|: >>> test.select_upstream(hp.nodes.lahn_2) Selection("test", nodes=("dill", "lahn_1", "lahn_2"), elements=("land_dill", "land_lahn_1", "land_lahn_2", "stream_dill_lahn_2", "stream_lahn_1_lahn_2")) On the contrary, the method |Selection.deselect_upstream| restricts the current selection to all devices not determined by method |Selection.search_upstream|: >>> complete = pub.selections.complete.deselect_upstream( ... hp.nodes.lahn_2) >>> complete Selection("complete", nodes="lahn_3", elements=("land_lahn_3", "stream_lahn_2_lahn_3")) If necessary, include the "outlet device" manually afterwards: >>> complete.nodes += hp.nodes.lahn_2 >>> complete Selection("complete", nodes=("lahn_2", "lahn_3"), elements=("land_lahn_3", "stream_lahn_2_lahn_3")) """ try: selection = Selection(name) if isinstance(device, devicetools.Node): node = self.nodes[device.name] return self.__get_nextnode(node, selection) if isinstance(device, devicetools.Element): element = self.elements[device.name] return self.__get_nextelement(element, selection) raise TypeError( f'Either a `Node` or an `Element` object is required ' f'as the "outlet device", but the given `device` value ' f'is of type `{objecttools.classname(device)}`.') except BaseException: objecttools.augment_excmessage( f'While trying to determine the upstream network of ' f'selection `{self.name}`')
Restrict the current selection to the network upstream of the given starting point, including the starting point itself. See the documentation on method |Selection.search_upstream| for additional information. def select_upstream(self, device: devicetools.Device) -> 'Selection': """Restrict the current selection to the network upstream of the given starting point, including the starting point itself. See the documentation on method |Selection.search_upstream| for additional information. """ upstream = self.search_upstream(device) self.nodes = upstream.nodes self.elements = upstream.elements return self
Return a |Selection| object containing only the elements currently handling models of the given types. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() You can pass both |Model| objects and names and, as a keyword argument, the name of the newly created |Selection| object: >>> test = pub.selections.complete.copy('test') >>> from hydpy import prepare_model >>> hland_v1 = prepare_model('hland_v1') >>> test.search_modeltypes(hland_v1) Selection("modeltypes", nodes=(), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3")) >>> test.search_modeltypes( ... hland_v1, 'hstream_v1', 'lland_v1', name='MODELTYPES') Selection("MODELTYPES", nodes=(), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3", "stream_dill_lahn_2", "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3")) Wrong model specifications result in errors like the following: >>> test.search_modeltypes('wrong') Traceback (most recent call last): ... ModuleNotFoundError: While trying to determine the elements of \ selection `test` handling the model defined by the argument(s) `wrong` \ of type(s) `str`, the following error occurred: \ No module named 'hydpy.models.wrong' Method |Selection.select_modeltypes| restricts the current selection to the one determined with the method the |Selection.search_modeltypes|: >>> test.select_modeltypes(hland_v1) Selection("test", nodes=(), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3")) On the contrary, the method |Selection.deselect_upstream| restricts the current selection to all devices not determined by method the |Selection.search_upstream|: >>> pub.selections.complete.deselect_modeltypes(hland_v1) Selection("complete", nodes=(), elements=("stream_dill_lahn_2", "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3")) def search_modeltypes(self, *models: ModelTypesArg, name: str = 'modeltypes') -> 'Selection': """Return a |Selection| object containing only the elements currently handling models of the given types. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() You can pass both |Model| objects and names and, as a keyword argument, the name of the newly created |Selection| object: >>> test = pub.selections.complete.copy('test') >>> from hydpy import prepare_model >>> hland_v1 = prepare_model('hland_v1') >>> test.search_modeltypes(hland_v1) Selection("modeltypes", nodes=(), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3")) >>> test.search_modeltypes( ... hland_v1, 'hstream_v1', 'lland_v1', name='MODELTYPES') Selection("MODELTYPES", nodes=(), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3", "stream_dill_lahn_2", "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3")) Wrong model specifications result in errors like the following: >>> test.search_modeltypes('wrong') Traceback (most recent call last): ... ModuleNotFoundError: While trying to determine the elements of \ selection `test` handling the model defined by the argument(s) `wrong` \ of type(s) `str`, the following error occurred: \ No module named 'hydpy.models.wrong' Method |Selection.select_modeltypes| restricts the current selection to the one determined with the method the |Selection.search_modeltypes|: >>> test.select_modeltypes(hland_v1) Selection("test", nodes=(), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3")) On the contrary, the method |Selection.deselect_upstream| restricts the current selection to all devices not determined by method the |Selection.search_upstream|: >>> pub.selections.complete.deselect_modeltypes(hland_v1) Selection("complete", nodes=(), elements=("stream_dill_lahn_2", "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3")) """ try: typelist = [] for model in models: if not isinstance(model, modeltools.Model): model = importtools.prepare_model(model) typelist.append(type(model)) typetuple = tuple(typelist) selection = Selection(name) for element in self.elements: if isinstance(element.model, typetuple): selection.elements += element return selection except BaseException: values = objecttools.enumeration(models) classes = objecttools.enumeration( objecttools.classname(model) for model in models) objecttools.augment_excmessage( f'While trying to determine the elements of selection ' f'`{self.name}` handling the model defined by the ' f'argument(s) `{values}` of type(s) `{classes}`')
Restrict the current |Selection| object to all elements containing the given model types (removes all nodes). See the documentation on method |Selection.search_modeltypes| for additional information. def select_modeltypes(self, *models: ModelTypesArg) -> 'Selection': """Restrict the current |Selection| object to all elements containing the given model types (removes all nodes). See the documentation on method |Selection.search_modeltypes| for additional information. """ self.nodes = devicetools.Nodes() self.elements = self.search_modeltypes(*models).elements return self
Return a new selection containing all nodes of the current selection with a name containing at least one of the given substrings. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() Pass the (sub)strings as positional arguments and, optionally, the name of the newly created |Selection| object as a keyword argument: >>> test = pub.selections.complete.copy('test') >>> from hydpy import prepare_model >>> test.search_nodenames('dill', 'lahn_1') Selection("nodenames", nodes=("dill", "lahn_1"), elements=()) Wrong string specifications result in errors like the following: >>> test.search_nodenames(['dill', 'lahn_1']) Traceback (most recent call last): ... TypeError: While trying to determine the nodes of selection \ `test` with names containing at least one of the given substrings \ `['dill', 'lahn_1']`, the following error occurred: 'in <string>' \ requires string as left operand, not list Method |Selection.select_nodenames| restricts the current selection to the one determined with the the method |Selection.search_nodenames|: >>> test.select_nodenames('dill', 'lahn_1') Selection("test", nodes=("dill", "lahn_1"), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3", "stream_dill_lahn_2", "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3")) On the contrary, the method |Selection.deselect_nodenames| restricts the current selection to all devices not determined by the method |Selection.search_nodenames|: >>> pub.selections.complete.deselect_nodenames('dill', 'lahn_1') Selection("complete", nodes=("lahn_2", "lahn_3"), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3", "stream_dill_lahn_2", "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3")) def search_nodenames(self, *substrings: str, name: str = 'nodenames') -> \ 'Selection': """Return a new selection containing all nodes of the current selection with a name containing at least one of the given substrings. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() Pass the (sub)strings as positional arguments and, optionally, the name of the newly created |Selection| object as a keyword argument: >>> test = pub.selections.complete.copy('test') >>> from hydpy import prepare_model >>> test.search_nodenames('dill', 'lahn_1') Selection("nodenames", nodes=("dill", "lahn_1"), elements=()) Wrong string specifications result in errors like the following: >>> test.search_nodenames(['dill', 'lahn_1']) Traceback (most recent call last): ... TypeError: While trying to determine the nodes of selection \ `test` with names containing at least one of the given substrings \ `['dill', 'lahn_1']`, the following error occurred: 'in <string>' \ requires string as left operand, not list Method |Selection.select_nodenames| restricts the current selection to the one determined with the the method |Selection.search_nodenames|: >>> test.select_nodenames('dill', 'lahn_1') Selection("test", nodes=("dill", "lahn_1"), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3", "stream_dill_lahn_2", "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3")) On the contrary, the method |Selection.deselect_nodenames| restricts the current selection to all devices not determined by the method |Selection.search_nodenames|: >>> pub.selections.complete.deselect_nodenames('dill', 'lahn_1') Selection("complete", nodes=("lahn_2", "lahn_3"), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3", "stream_dill_lahn_2", "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3")) """ try: selection = Selection(name) for node in self.nodes: for substring in substrings: if substring in node.name: selection.nodes += node break return selection except BaseException: values = objecttools.enumeration(substrings) objecttools.augment_excmessage( f'While trying to determine the nodes of selection ' f'`{self.name}` with names containing at least one ' f'of the given substrings `{values}`')
Restrict the current selection to all nodes with a name containing at least one of the given substrings (does not affect any elements). See the documentation on method |Selection.search_nodenames| for additional information. def select_nodenames(self, *substrings: str) -> 'Selection': """Restrict the current selection to all nodes with a name containing at least one of the given substrings (does not affect any elements). See the documentation on method |Selection.search_nodenames| for additional information. """ self.nodes = self.search_nodenames(*substrings).nodes return self
Restrict the current selection to all nodes with a name not containing at least one of the given substrings (does not affect any elements). See the documentation on method |Selection.search_nodenames| for additional information. def deselect_nodenames(self, *substrings: str) -> 'Selection': """Restrict the current selection to all nodes with a name not containing at least one of the given substrings (does not affect any elements). See the documentation on method |Selection.search_nodenames| for additional information. """ self.nodes -= self.search_nodenames(*substrings).nodes return self
Return a new selection containing all elements of the current selection with a name containing at least one of the given substrings. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() Pass the (sub)strings as positional arguments and, optionally, the name of the newly created |Selection| object as a keyword argument: >>> test = pub.selections.complete.copy('test') >>> from hydpy import prepare_model >>> test.search_elementnames('dill', 'lahn_1') Selection("elementnames", nodes=(), elements=("land_dill", "land_lahn_1", "stream_dill_lahn_2", "stream_lahn_1_lahn_2")) Wrong string specifications result in errors like the following: >>> test.search_elementnames(['dill', 'lahn_1']) Traceback (most recent call last): ... TypeError: While trying to determine the elements of selection \ `test` with names containing at least one of the given substrings \ `['dill', 'lahn_1']`, the following error occurred: 'in <string>' \ requires string as left operand, not list Method |Selection.select_elementnames| restricts the current selection to the one determined with the method |Selection.search_elementnames|: >>> test.select_elementnames('dill', 'lahn_1') Selection("test", nodes=("dill", "lahn_1", "lahn_2", "lahn_3"), elements=("land_dill", "land_lahn_1", "stream_dill_lahn_2", "stream_lahn_1_lahn_2")) On the contrary, the method |Selection.deselect_elementnames| restricts the current selection to all devices not determined by the method |Selection.search_elementnames|: >>> pub.selections.complete.deselect_elementnames('dill', 'lahn_1') Selection("complete", nodes=("dill", "lahn_1", "lahn_2", "lahn_3"), elements=("land_lahn_2", "land_lahn_3", "stream_lahn_2_lahn_3")) def search_elementnames(self, *substrings: str, name: str = 'elementnames') -> 'Selection': """Return a new selection containing all elements of the current selection with a name containing at least one of the given substrings. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, _ = prepare_full_example_2() Pass the (sub)strings as positional arguments and, optionally, the name of the newly created |Selection| object as a keyword argument: >>> test = pub.selections.complete.copy('test') >>> from hydpy import prepare_model >>> test.search_elementnames('dill', 'lahn_1') Selection("elementnames", nodes=(), elements=("land_dill", "land_lahn_1", "stream_dill_lahn_2", "stream_lahn_1_lahn_2")) Wrong string specifications result in errors like the following: >>> test.search_elementnames(['dill', 'lahn_1']) Traceback (most recent call last): ... TypeError: While trying to determine the elements of selection \ `test` with names containing at least one of the given substrings \ `['dill', 'lahn_1']`, the following error occurred: 'in <string>' \ requires string as left operand, not list Method |Selection.select_elementnames| restricts the current selection to the one determined with the method |Selection.search_elementnames|: >>> test.select_elementnames('dill', 'lahn_1') Selection("test", nodes=("dill", "lahn_1", "lahn_2", "lahn_3"), elements=("land_dill", "land_lahn_1", "stream_dill_lahn_2", "stream_lahn_1_lahn_2")) On the contrary, the method |Selection.deselect_elementnames| restricts the current selection to all devices not determined by the method |Selection.search_elementnames|: >>> pub.selections.complete.deselect_elementnames('dill', 'lahn_1') Selection("complete", nodes=("dill", "lahn_1", "lahn_2", "lahn_3"), elements=("land_lahn_2", "land_lahn_3", "stream_lahn_2_lahn_3")) """ try: selection = Selection(name) for element in self.elements: for substring in substrings: if substring in element.name: selection.elements += element break return selection except BaseException: values = objecttools.enumeration(substrings) objecttools.augment_excmessage( f'While trying to determine the elements of selection ' f'`{self.name}` with names containing at least one ' f'of the given substrings `{values}`')
Restrict the current selection to all elements with a name containing at least one of the given substrings (does not affect any nodes). See the documentation on method |Selection.search_elementnames| for additional information. def select_elementnames(self, *substrings: str) -> 'Selection': """Restrict the current selection to all elements with a name containing at least one of the given substrings (does not affect any nodes). See the documentation on method |Selection.search_elementnames| for additional information. """ self.elements = self.search_elementnames(*substrings).elements return self
Restrict the current selection to all elements with a name not containing at least one of the given substrings. (does not affect any nodes). See the documentation on method |Selection.search_elementnames| for additional information. def deselect_elementnames(self, *substrings: str) -> 'Selection': """Restrict the current selection to all elements with a name not containing at least one of the given substrings. (does not affect any nodes). See the documentation on method |Selection.search_elementnames| for additional information. """ self.elements -= self.search_elementnames(*substrings).elements return self
Return a new |Selection| object with the given name and copies of the handles |Nodes| and |Elements| objects based on method |Devices.copy|. def copy(self, name: str) -> 'Selection': """Return a new |Selection| object with the given name and copies of the handles |Nodes| and |Elements| objects based on method |Devices.copy|.""" return type(self)(name, copy.copy(self.nodes), copy.copy(self.elements))
Save the selection as a network file. >>> from hydpy.core.examples import prepare_full_example_2 >>> _, pub, TestIO = prepare_full_example_2() In most cases, one should conveniently write network files via method |NetworkManager.save_files| of class |NetworkManager|. However, using the method |Selection.save_networkfile| allows for additional configuration via the arguments `filepath` and `write_nodes`: >>> with TestIO(): ... pub.selections.headwaters.save_networkfile() ... with open('headwaters.py') as networkfile: ... print(networkfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy import Node, Element <BLANKLINE> <BLANKLINE> Node("dill", variable="Q", keywords="gauge") <BLANKLINE> Node("lahn_1", variable="Q", keywords="gauge") <BLANKLINE> <BLANKLINE> Element("land_dill", outlets="dill", keywords="catchment") <BLANKLINE> Element("land_lahn_1", outlets="lahn_1", keywords="catchment") <BLANKLINE> >>> with TestIO(): ... pub.selections.headwaters.save_networkfile('test.py', False) ... with open('test.py') as networkfile: ... print(networkfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy import Node, Element <BLANKLINE> <BLANKLINE> Element("land_dill", outlets="dill", keywords="catchment") <BLANKLINE> Element("land_lahn_1", outlets="lahn_1", keywords="catchment") <BLANKLINE> def save_networkfile(self, filepath: Union[str, None] = None, write_nodes: bool = True) -> None: """Save the selection as a network file. >>> from hydpy.core.examples import prepare_full_example_2 >>> _, pub, TestIO = prepare_full_example_2() In most cases, one should conveniently write network files via method |NetworkManager.save_files| of class |NetworkManager|. However, using the method |Selection.save_networkfile| allows for additional configuration via the arguments `filepath` and `write_nodes`: >>> with TestIO(): ... pub.selections.headwaters.save_networkfile() ... with open('headwaters.py') as networkfile: ... print(networkfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy import Node, Element <BLANKLINE> <BLANKLINE> Node("dill", variable="Q", keywords="gauge") <BLANKLINE> Node("lahn_1", variable="Q", keywords="gauge") <BLANKLINE> <BLANKLINE> Element("land_dill", outlets="dill", keywords="catchment") <BLANKLINE> Element("land_lahn_1", outlets="lahn_1", keywords="catchment") <BLANKLINE> >>> with TestIO(): ... pub.selections.headwaters.save_networkfile('test.py', False) ... with open('test.py') as networkfile: ... print(networkfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy import Node, Element <BLANKLINE> <BLANKLINE> Element("land_dill", outlets="dill", keywords="catchment") <BLANKLINE> Element("land_lahn_1", outlets="lahn_1", keywords="catchment") <BLANKLINE> """ if filepath is None: filepath = self.name + '.py' with open(filepath, 'w', encoding="utf-8") as file_: file_.write('# -*- coding: utf-8 -*-\n') file_.write('\nfrom hydpy import Node, Element\n\n') if write_nodes: for node in self.nodes: file_.write('\n' + repr(node) + '\n') file_.write('\n') for element in self.elements: file_.write('\n' + repr(element) + '\n')
Return a |repr| string with a prefixed assignment. def assignrepr(self, prefix: str) -> str: """Return a |repr| string with a prefixed assignment.""" with objecttools.repr_.preserve_strings(True): with hydpy.pub.options.ellipsis(2, optional=True): with objecttools.assignrepr_tuple.always_bracketed(False): classname = objecttools.classname(self) blanks = ' ' * (len(prefix+classname) + 1) nodestr = objecttools.assignrepr_tuple( self.nodes.names, blanks+'nodes=', 70) elementstr = objecttools.assignrepr_tuple( self.elements.names, blanks + 'elements=', 70) return (f'{prefix}{classname}("{self.name}",\n' f'{nodestr},\n' f'{elementstr})')
Calculate the input discharge portions of the different response functions. Required derived parameters: |Nmb| |MaxQ| |DiffQ| Required flux sequence: |QIn| Calculated flux sequences: |QPIn| Examples: Initialize an arma model with three different response functions: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb = 3 >>> derived.maxq.shape = 3 >>> derived.diffq.shape = 2 >>> fluxes.qpin.shape = 3 Define the maximum discharge value of the respective response functions and their successive differences: >>> derived.maxq(0.0, 2.0, 6.0) >>> derived.diffq(2., 4.) The first six examples are performed for inflow values ranging from 0 to 12 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest( ... model, model.calc_qpin_v1, ... last_example=6, ... parseqs=(fluxes.qin, fluxes.qpin)) >>> test.nexts.qin = 0., 1., 2., 4., 6., 12. >>> test() | ex. | qin | qpin | ------------------------------- | 1 | 0.0 | 0.0 0.0 0.0 | | 2 | 1.0 | 1.0 0.0 0.0 | | 3 | 2.0 | 2.0 0.0 0.0 | | 4 | 4.0 | 2.0 2.0 0.0 | | 5 | 6.0 | 2.0 4.0 0.0 | | 6 | 12.0 | 2.0 4.0 6.0 | The following two additional examples are just supposed to demonstrate method |calc_qpin_v1| also functions properly if there is only one response function, wherefore total discharge does not need to be divided: >>> derived.nmb = 1 >>> derived.maxq.shape = 1 >>> derived.diffq.shape = 0 >>> fluxes.qpin.shape = 1 >>> derived.maxq(0.) >>> test = UnitTest( ... model, model.calc_qpin_v1, ... first_example=7, last_example=8, ... parseqs=(fluxes.qin, ... fluxes.qpin)) >>> test.nexts.qin = 0., 12. >>> test() | ex. | qin | qpin | --------------------- | 7 | 0.0 | 0.0 | | 8 | 12.0 | 12.0 | def calc_qpin_v1(self): """Calculate the input discharge portions of the different response functions. Required derived parameters: |Nmb| |MaxQ| |DiffQ| Required flux sequence: |QIn| Calculated flux sequences: |QPIn| Examples: Initialize an arma model with three different response functions: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb = 3 >>> derived.maxq.shape = 3 >>> derived.diffq.shape = 2 >>> fluxes.qpin.shape = 3 Define the maximum discharge value of the respective response functions and their successive differences: >>> derived.maxq(0.0, 2.0, 6.0) >>> derived.diffq(2., 4.) The first six examples are performed for inflow values ranging from 0 to 12 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest( ... model, model.calc_qpin_v1, ... last_example=6, ... parseqs=(fluxes.qin, fluxes.qpin)) >>> test.nexts.qin = 0., 1., 2., 4., 6., 12. >>> test() | ex. | qin | qpin | ------------------------------- | 1 | 0.0 | 0.0 0.0 0.0 | | 2 | 1.0 | 1.0 0.0 0.0 | | 3 | 2.0 | 2.0 0.0 0.0 | | 4 | 4.0 | 2.0 2.0 0.0 | | 5 | 6.0 | 2.0 4.0 0.0 | | 6 | 12.0 | 2.0 4.0 6.0 | The following two additional examples are just supposed to demonstrate method |calc_qpin_v1| also functions properly if there is only one response function, wherefore total discharge does not need to be divided: >>> derived.nmb = 1 >>> derived.maxq.shape = 1 >>> derived.diffq.shape = 0 >>> fluxes.qpin.shape = 1 >>> derived.maxq(0.) >>> test = UnitTest( ... model, model.calc_qpin_v1, ... first_example=7, last_example=8, ... parseqs=(fluxes.qin, ... fluxes.qpin)) >>> test.nexts.qin = 0., 12. >>> test() | ex. | qin | qpin | --------------------- | 7 | 0.0 | 0.0 | | 8 | 12.0 | 12.0 | """ der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess for idx in range(der.nmb-1): if flu.qin < der.maxq[idx]: flu.qpin[idx] = 0. elif flu.qin < der.maxq[idx+1]: flu.qpin[idx] = flu.qin-der.maxq[idx] else: flu.qpin[idx] = der.diffq[idx] flu.qpin[der.nmb-1] = max(flu.qin-der.maxq[der.nmb-1], 0.)
Refresh the input log sequence for the different MA processes. Required derived parameters: |Nmb| |MA_Order| Required flux sequence: |QPIn| Updated log sequence: |LogIn| Example: Assume there are three response functions, involving one, two and three MA coefficients respectively: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(3) >>> derived.ma_order.shape = 3 >>> derived.ma_order = 1, 2, 3 >>> fluxes.qpin.shape = 3 >>> logs.login.shape = (3, 3) The "memory values" of the different MA processes are defined as follows (one row for each process): >>> logs.login = ((1.0, nan, nan), ... (2.0, 3.0, nan), ... (4.0, 5.0, 6.0)) These are the new inflow discharge portions to be included into the memories of the different processes: >>> fluxes.qpin = 7.0, 8.0, 9.0 Through applying method |calc_login_v1| all values already existing are shifted to the right ("into the past"). Values, which are no longer required due to the limited order or the different MA processes, are discarded. The new values are inserted in the first column: >>> model.calc_login_v1() >>> logs.login login([[7.0, nan, nan], [8.0, 2.0, nan], [9.0, 4.0, 5.0]]) def calc_login_v1(self): """Refresh the input log sequence for the different MA processes. Required derived parameters: |Nmb| |MA_Order| Required flux sequence: |QPIn| Updated log sequence: |LogIn| Example: Assume there are three response functions, involving one, two and three MA coefficients respectively: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(3) >>> derived.ma_order.shape = 3 >>> derived.ma_order = 1, 2, 3 >>> fluxes.qpin.shape = 3 >>> logs.login.shape = (3, 3) The "memory values" of the different MA processes are defined as follows (one row for each process): >>> logs.login = ((1.0, nan, nan), ... (2.0, 3.0, nan), ... (4.0, 5.0, 6.0)) These are the new inflow discharge portions to be included into the memories of the different processes: >>> fluxes.qpin = 7.0, 8.0, 9.0 Through applying method |calc_login_v1| all values already existing are shifted to the right ("into the past"). Values, which are no longer required due to the limited order or the different MA processes, are discarded. The new values are inserted in the first column: >>> model.calc_login_v1() >>> logs.login login([[7.0, nan, nan], [8.0, 2.0, nan], [9.0, 4.0, 5.0]]) """ der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(der.nmb): for jdx in range(der.ma_order[idx]-2, -1, -1): log.login[idx, jdx+1] = log.login[idx, jdx] for idx in range(der.nmb): log.login[idx, 0] = flu.qpin[idx]
Calculate the discharge responses of the different MA processes. Required derived parameters: |Nmb| |MA_Order| |MA_Coefs| Required log sequence: |LogIn| Calculated flux sequence: |QMA| Examples: Assume there are three response functions, involving one, two and three MA coefficients respectively: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(3) >>> derived.ma_order.shape = 3 >>> derived.ma_order = 1, 2, 3 >>> derived.ma_coefs.shape = (3, 3) >>> logs.login.shape = (3, 3) >>> fluxes.qma.shape = 3 The coefficients of the different MA processes are stored in separate rows of the 2-dimensional parameter `ma_coefs`: >>> derived.ma_coefs = ((1.0, nan, nan), ... (0.8, 0.2, nan), ... (0.5, 0.3, 0.2)) The "memory values" of the different MA processes are defined as follows (one row for each process). The current values are stored in first column, the values of the last time step in the second column, and so on: >>> logs.login = ((1.0, nan, nan), ... (2.0, 3.0, nan), ... (4.0, 5.0, 6.0)) Applying method |calc_qma_v1| is equivalent to calculating the inner product of the different rows of both matrices: >>> model.calc_qma_v1() >>> fluxes.qma qma(1.0, 2.2, 4.7) def calc_qma_v1(self): """Calculate the discharge responses of the different MA processes. Required derived parameters: |Nmb| |MA_Order| |MA_Coefs| Required log sequence: |LogIn| Calculated flux sequence: |QMA| Examples: Assume there are three response functions, involving one, two and three MA coefficients respectively: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(3) >>> derived.ma_order.shape = 3 >>> derived.ma_order = 1, 2, 3 >>> derived.ma_coefs.shape = (3, 3) >>> logs.login.shape = (3, 3) >>> fluxes.qma.shape = 3 The coefficients of the different MA processes are stored in separate rows of the 2-dimensional parameter `ma_coefs`: >>> derived.ma_coefs = ((1.0, nan, nan), ... (0.8, 0.2, nan), ... (0.5, 0.3, 0.2)) The "memory values" of the different MA processes are defined as follows (one row for each process). The current values are stored in first column, the values of the last time step in the second column, and so on: >>> logs.login = ((1.0, nan, nan), ... (2.0, 3.0, nan), ... (4.0, 5.0, 6.0)) Applying method |calc_qma_v1| is equivalent to calculating the inner product of the different rows of both matrices: >>> model.calc_qma_v1() >>> fluxes.qma qma(1.0, 2.2, 4.7) """ der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(der.nmb): flu.qma[idx] = 0. for jdx in range(der.ma_order[idx]): flu.qma[idx] += der.ma_coefs[idx, jdx] * log.login[idx, jdx]
Calculate the discharge responses of the different AR processes. Required derived parameters: |Nmb| |AR_Order| |AR_Coefs| Required log sequence: |LogOut| Calculated flux sequence: |QAR| Examples: Assume there are four response functions, involving zero, one, two, and three AR coefficients respectively: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(4) >>> derived.ar_order.shape = 4 >>> derived.ar_order = 0, 1, 2, 3 >>> derived.ar_coefs.shape = (4, 3) >>> logs.logout.shape = (4, 3) >>> fluxes.qar.shape = 4 The coefficients of the different AR processes are stored in separate rows of the 2-dimensional parameter `ma_coefs`. Note the special case of the first AR process of zero order (first row), which involves no autoregressive memory at all: >>> derived.ar_coefs = ((nan, nan, nan), ... (1.0, nan, nan), ... (0.8, 0.2, nan), ... (0.5, 0.3, 0.2)) The "memory values" of the different AR processes are defined as follows (one row for each process). The values of the last time step are stored in first column, the values of the last time step in the second column, and so on: >>> logs.logout = ((nan, nan, nan), ... (1.0, nan, nan), ... (2.0, 3.0, nan), ... (4.0, 5.0, 6.0)) Applying method |calc_qar_v1| is equivalent to calculating the inner product of the different rows of both matrices: >>> model.calc_qar_v1() >>> fluxes.qar qar(0.0, 1.0, 2.2, 4.7) def calc_qar_v1(self): """Calculate the discharge responses of the different AR processes. Required derived parameters: |Nmb| |AR_Order| |AR_Coefs| Required log sequence: |LogOut| Calculated flux sequence: |QAR| Examples: Assume there are four response functions, involving zero, one, two, and three AR coefficients respectively: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(4) >>> derived.ar_order.shape = 4 >>> derived.ar_order = 0, 1, 2, 3 >>> derived.ar_coefs.shape = (4, 3) >>> logs.logout.shape = (4, 3) >>> fluxes.qar.shape = 4 The coefficients of the different AR processes are stored in separate rows of the 2-dimensional parameter `ma_coefs`. Note the special case of the first AR process of zero order (first row), which involves no autoregressive memory at all: >>> derived.ar_coefs = ((nan, nan, nan), ... (1.0, nan, nan), ... (0.8, 0.2, nan), ... (0.5, 0.3, 0.2)) The "memory values" of the different AR processes are defined as follows (one row for each process). The values of the last time step are stored in first column, the values of the last time step in the second column, and so on: >>> logs.logout = ((nan, nan, nan), ... (1.0, nan, nan), ... (2.0, 3.0, nan), ... (4.0, 5.0, 6.0)) Applying method |calc_qar_v1| is equivalent to calculating the inner product of the different rows of both matrices: >>> model.calc_qar_v1() >>> fluxes.qar qar(0.0, 1.0, 2.2, 4.7) """ der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(der.nmb): flu.qar[idx] = 0. for jdx in range(der.ar_order[idx]): flu.qar[idx] += der.ar_coefs[idx, jdx] * log.logout[idx, jdx]
Calculate the ARMA results for the different response functions. Required derived parameter: |Nmb| Required flux sequences: |QMA| |QAR| Calculated flux sequence: |QPOut| Examples: Initialize an arma model with three different response functions: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(3) >>> fluxes.qma.shape = 3 >>> fluxes.qar.shape = 3 >>> fluxes.qpout.shape = 3 Define the output values of the MA and of the AR processes associated with the three response functions and apply method |calc_qpout_v1|: >>> fluxes.qar = 4.0, 5.0, 6.0 >>> fluxes.qma = 1.0, 2.0, 3.0 >>> model.calc_qpout_v1() >>> fluxes.qpout qpout(5.0, 7.0, 9.0) def calc_qpout_v1(self): """Calculate the ARMA results for the different response functions. Required derived parameter: |Nmb| Required flux sequences: |QMA| |QAR| Calculated flux sequence: |QPOut| Examples: Initialize an arma model with three different response functions: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(3) >>> fluxes.qma.shape = 3 >>> fluxes.qar.shape = 3 >>> fluxes.qpout.shape = 3 Define the output values of the MA and of the AR processes associated with the three response functions and apply method |calc_qpout_v1|: >>> fluxes.qar = 4.0, 5.0, 6.0 >>> fluxes.qma = 1.0, 2.0, 3.0 >>> model.calc_qpout_v1() >>> fluxes.qpout qpout(5.0, 7.0, 9.0) """ der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess for idx in range(der.nmb): flu.qpout[idx] = flu.qma[idx]+flu.qar[idx]
Refresh the log sequence for the different AR processes. Required derived parameters: |Nmb| |AR_Order| Required flux sequence: |QPOut| Updated log sequence: |LogOut| Example: Assume there are four response functions, involving zero, one, two and three AR coefficients respectively: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(4) >>> derived.ar_order.shape = 4 >>> derived.ar_order = 0, 1, 2, 3 >>> fluxes.qpout.shape = 4 >>> logs.logout.shape = (4, 3) The "memory values" of the different AR processes are defined as follows (one row for each process). Note the special case of the first AR process of zero order (first row), which is why there are no autoregressive memory values required: >>> logs.logout = ((nan, nan, nan), ... (0.0, nan, nan), ... (1.0, 2.0, nan), ... (3.0, 4.0, 5.0)) These are the new outflow discharge portions to be included into the memories of the different processes: >>> fluxes.qpout = 6.0, 7.0, 8.0, 9.0 Through applying method |calc_logout_v1| all values already existing are shifted to the right ("into the past"). Values, which are no longer required due to the limited order or the different AR processes, are discarded. The new values are inserted in the first column: >>> model.calc_logout_v1() >>> logs.logout logout([[nan, nan, nan], [7.0, nan, nan], [8.0, 1.0, nan], [9.0, 3.0, 4.0]]) def calc_logout_v1(self): """Refresh the log sequence for the different AR processes. Required derived parameters: |Nmb| |AR_Order| Required flux sequence: |QPOut| Updated log sequence: |LogOut| Example: Assume there are four response functions, involving zero, one, two and three AR coefficients respectively: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(4) >>> derived.ar_order.shape = 4 >>> derived.ar_order = 0, 1, 2, 3 >>> fluxes.qpout.shape = 4 >>> logs.logout.shape = (4, 3) The "memory values" of the different AR processes are defined as follows (one row for each process). Note the special case of the first AR process of zero order (first row), which is why there are no autoregressive memory values required: >>> logs.logout = ((nan, nan, nan), ... (0.0, nan, nan), ... (1.0, 2.0, nan), ... (3.0, 4.0, 5.0)) These are the new outflow discharge portions to be included into the memories of the different processes: >>> fluxes.qpout = 6.0, 7.0, 8.0, 9.0 Through applying method |calc_logout_v1| all values already existing are shifted to the right ("into the past"). Values, which are no longer required due to the limited order or the different AR processes, are discarded. The new values are inserted in the first column: >>> model.calc_logout_v1() >>> logs.logout logout([[nan, nan, nan], [7.0, nan, nan], [8.0, 1.0, nan], [9.0, 3.0, 4.0]]) """ der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(der.nmb): for jdx in range(der.ar_order[idx]-2, -1, -1): log.logout[idx, jdx+1] = log.logout[idx, jdx] for idx in range(der.nmb): if der.ar_order[idx] > 0: log.logout[idx, 0] = flu.qpout[idx]
Sum up the results of the different response functions. Required derived parameter: |Nmb| Required flux sequences: |QPOut| Calculated flux sequence: |QOut| Examples: Initialize an arma model with three different response functions: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(3) >>> fluxes.qpout.shape = 3 Define the output values of the three response functions and apply method |calc_qout_v1|: >>> fluxes.qpout = 1.0, 2.0, 3.0 >>> model.calc_qout_v1() >>> fluxes.qout qout(6.0) def calc_qout_v1(self): """Sum up the results of the different response functions. Required derived parameter: |Nmb| Required flux sequences: |QPOut| Calculated flux sequence: |QOut| Examples: Initialize an arma model with three different response functions: >>> from hydpy.models.arma import * >>> parameterstep() >>> derived.nmb(3) >>> fluxes.qpout.shape = 3 Define the output values of the three response functions and apply method |calc_qout_v1|: >>> fluxes.qpout = 1.0, 2.0, 3.0 >>> model.calc_qout_v1() >>> fluxes.qout qout(6.0) """ der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess flu.qout = 0. for idx in range(der.nmb): flu.qout += flu.qpout[idx]
Update inflow. def pick_q_v1(self): """Update inflow.""" flu = self.sequences.fluxes.fastaccess inl = self.sequences.inlets.fastaccess flu.qin = 0. for idx in range(inl.len_q): flu.qin += inl.q[idx][0]
Determine the number of branches def update(self): """Determine the number of branches""" con = self.subpars.pars.control self(con.ypoints.shape[0])
Update value based on :math:`HV=BBV/BNV`. Required Parameters: |BBV| |BNV| Examples: >>> from hydpy.models.lstream import * >>> parameterstep('1d') >>> bbv(left=10., right=40.) >>> bnv(left=10., right=20.) >>> derived.hv.update() >>> derived.hv hv(left=1.0, right=2.0) >>> bbv(left=10., right=0.) >>> bnv(left=0., right=20.) >>> derived.hv.update() >>> derived.hv hv(0.0) def update(self): """Update value based on :math:`HV=BBV/BNV`. Required Parameters: |BBV| |BNV| Examples: >>> from hydpy.models.lstream import * >>> parameterstep('1d') >>> bbv(left=10., right=40.) >>> bnv(left=10., right=20.) >>> derived.hv.update() >>> derived.hv hv(left=1.0, right=2.0) >>> bbv(left=10., right=0.) >>> bnv(left=0., right=20.) >>> derived.hv.update() >>> derived.hv hv(0.0) """ con = self.subpars.pars.control self(0.) for idx in range(2): if (con.bbv[idx] > 0.) and (con.bnv[idx] > 0.): self.values[idx] = con.bbv[idx]/con.bnv[idx]
Update value based on the actual |calc_qg_v1| method. Required derived parameter: |H| Note that the value of parameter |lstream_derived.QM| is directly related to the value of parameter |HM| and indirectly related to all parameters values relevant for method |calc_qg_v1|. Hence the complete paramter (and sequence) requirements might differ for various application models. For examples, see the documentation on method ToDo. def update(self): """Update value based on the actual |calc_qg_v1| method. Required derived parameter: |H| Note that the value of parameter |lstream_derived.QM| is directly related to the value of parameter |HM| and indirectly related to all parameters values relevant for method |calc_qg_v1|. Hence the complete paramter (and sequence) requirements might differ for various application models. For examples, see the documentation on method ToDo. """ mod = self.subpars.pars.model con = mod.parameters.control flu = mod.sequences.fluxes flu.h = con.hm mod.calc_qg() self(flu.qg)
Determines in how many segments the whole reach needs to be divided to approximate the desired lag time via integer rounding. Adjusts the shape of sequence |QJoints| additionally. Required control parameters: |Lag| Calculated derived parameters: |NmbSegments| Prepared state sequence: |QJoints| Examples: Define a lag time of 1.4 days and a simulation step size of 12 hours: >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> simulationstep('12h') >>> lag(1.4) Then the actual lag value for the simulation step size is 2.8 >>> lag lag(1.4) >>> lag.value 2.8 Through rounding the number of segments is determined: >>> derived.nmbsegments.update() >>> derived.nmbsegments nmbsegments(3) The number of joints is always the number of segments plus one: >>> states.qjoints.shape (4,) def update(self): """Determines in how many segments the whole reach needs to be divided to approximate the desired lag time via integer rounding. Adjusts the shape of sequence |QJoints| additionally. Required control parameters: |Lag| Calculated derived parameters: |NmbSegments| Prepared state sequence: |QJoints| Examples: Define a lag time of 1.4 days and a simulation step size of 12 hours: >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> simulationstep('12h') >>> lag(1.4) Then the actual lag value for the simulation step size is 2.8 >>> lag lag(1.4) >>> lag.value 2.8 Through rounding the number of segments is determined: >>> derived.nmbsegments.update() >>> derived.nmbsegments nmbsegments(3) The number of joints is always the number of segments plus one: >>> states.qjoints.shape (4,) """ pars = self.subpars.pars self(int(round(pars.control.lag))) pars.model.sequences.states.qjoints.shape = self+1
Update |C1| based on :math:`c_1 = \\frac{Damp}{1+Damp}`. Examples: The first examples show the calculated value of |C1| for the lowest possible value of |Lag|, the lowest possible value, and an intermediate value: >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> damp(0.0) >>> derived.c1.update() >>> derived.c1 c1(0.0) >>> damp(1.0) >>> derived.c1.update() >>> derived.c1 c1(0.5) >>> damp(0.25) >>> derived.c1.update() >>> derived.c1 c1(0.2) For to low and to high values of |Lag|, clipping is performed: >>> damp.value = -0.1 >>> derived.c1.update() >>> derived.c1 c1(0.0) >>> damp.value = 1.1 >>> derived.c1.update() >>> derived.c1 c1(0.5) def update(self): """Update |C1| based on :math:`c_1 = \\frac{Damp}{1+Damp}`. Examples: The first examples show the calculated value of |C1| for the lowest possible value of |Lag|, the lowest possible value, and an intermediate value: >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> damp(0.0) >>> derived.c1.update() >>> derived.c1 c1(0.0) >>> damp(1.0) >>> derived.c1.update() >>> derived.c1 c1(0.5) >>> damp(0.25) >>> derived.c1.update() >>> derived.c1 c1(0.2) For to low and to high values of |Lag|, clipping is performed: >>> damp.value = -0.1 >>> derived.c1.update() >>> derived.c1 c1(0.0) >>> damp.value = 1.1 >>> derived.c1.update() >>> derived.c1 c1(0.5) """ damp = self.subpars.pars.control.damp self(numpy.clip(damp/(1.+damp), 0., .5))
Update |C2| based on :math:`c_2 = 1.-c_1-c_3`. Examples: The following examples show the calculated value of |C2| are clipped when to low or to high: >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> derived.c1 = 0.6 >>> derived.c3 = 0.1 >>> derived.c2.update() >>> derived.c2 c2(0.3) >>> derived.c1 = 1.6 >>> derived.c2.update() >>> derived.c2 c2(0.0) >>> derived.c1 = -1.6 >>> derived.c2.update() >>> derived.c2 c2(1.0) def update(self): """Update |C2| based on :math:`c_2 = 1.-c_1-c_3`. Examples: The following examples show the calculated value of |C2| are clipped when to low or to high: >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> derived.c1 = 0.6 >>> derived.c3 = 0.1 >>> derived.c2.update() >>> derived.c2 c2(0.3) >>> derived.c1 = 1.6 >>> derived.c2.update() >>> derived.c2 c2(0.0) >>> derived.c1 = -1.6 >>> derived.c2.update() >>> derived.c2 c2(1.0) """ der = self.subpars self(numpy.clip(1. - der.c1 - der.c3, 0., 1.))
View the supplied data in an interactive, graphical table widget. data: When a valid path or IO object, read it as a tabular text file. When a valid URI, a Blaze object is constructed and visualized. Any other supported datatype is visualized directly and incrementally *without copying*. enc: File encoding (such as "utf-8", normally autodetected). delimiter: Text file delimiter (normally autodetected). hdr_rows: For files or lists of lists, specify the number of header rows. For files only, a default of one header line is assumed. idx_cols: For files or lists of lists, specify the number of index columns. By default, no index is assumed. sheet_index: For multi-table files (such as xls[x]), specify the sheet index to read, starting from 0. Defaults to the first. start_pos: A tuple of the form (y, x) specifying the initial cursor position. Negative offsets count from the end of the dataset. transpose: Transpose the resulting view. metavar: name of the variable being shown for display purposes (inferred automatically when possible). title: title of the data window. wait: Wait for the user to close the view before returning. By default, try to match the behavior of ``matplotlib.is_interactive()``. If matplotlib is not loaded, wait only if ``detach`` is also False. The default value can also be set through ``gtabview.WAIT``. recycle: Recycle the previous window instead of creating a new one. The default is True, and can also be set through ``gtabview.RECYCLE``. detach: Create a fully detached GUI thread for interactive use (note: this is *not* necessary if matplotlib is loaded). The default is False, and can also be set through ``gtabview.DETACH``. def view(data, enc=None, start_pos=None, delimiter=None, hdr_rows=None, idx_cols=None, sheet_index=0, transpose=False, wait=None, recycle=None, detach=None, metavar=None, title=None): """View the supplied data in an interactive, graphical table widget. data: When a valid path or IO object, read it as a tabular text file. When a valid URI, a Blaze object is constructed and visualized. Any other supported datatype is visualized directly and incrementally *without copying*. enc: File encoding (such as "utf-8", normally autodetected). delimiter: Text file delimiter (normally autodetected). hdr_rows: For files or lists of lists, specify the number of header rows. For files only, a default of one header line is assumed. idx_cols: For files or lists of lists, specify the number of index columns. By default, no index is assumed. sheet_index: For multi-table files (such as xls[x]), specify the sheet index to read, starting from 0. Defaults to the first. start_pos: A tuple of the form (y, x) specifying the initial cursor position. Negative offsets count from the end of the dataset. transpose: Transpose the resulting view. metavar: name of the variable being shown for display purposes (inferred automatically when possible). title: title of the data window. wait: Wait for the user to close the view before returning. By default, try to match the behavior of ``matplotlib.is_interactive()``. If matplotlib is not loaded, wait only if ``detach`` is also False. The default value can also be set through ``gtabview.WAIT``. recycle: Recycle the previous window instead of creating a new one. The default is True, and can also be set through ``gtabview.RECYCLE``. detach: Create a fully detached GUI thread for interactive use (note: this is *not* necessary if matplotlib is loaded). The default is False, and can also be set through ``gtabview.DETACH``. """ global WAIT, RECYCLE, DETACH, VIEW model = read_model(data, enc=enc, delimiter=delimiter, hdr_rows=hdr_rows, idx_cols=idx_cols, sheet_index=sheet_index, transpose=transpose) if model is None: warnings.warn("cannot visualize the supplied data type: {}".format(type(data)), category=RuntimeWarning) return None # setup defaults if wait is None: wait = WAIT if recycle is None: recycle = RECYCLE if detach is None: detach = DETACH if wait is None: if 'matplotlib' not in sys.modules: wait = not bool(detach) else: import matplotlib.pyplot as plt wait = not plt.isinteractive() # try to fetch the variable name in the upper stack if metavar is None: if isinstance(data, basestring): metavar = data else: metavar = _varname_in_stack(data, 1) # create a view controller if VIEW is None: if not detach: VIEW = ViewController() else: VIEW = DetachedViewController() VIEW.setDaemon(True) VIEW.start() if VIEW.is_detached(): atexit.register(VIEW.exit) else: VIEW = None return None # actually show the data view_kwargs = {'hdr_rows': hdr_rows, 'idx_cols': idx_cols, 'start_pos': start_pos, 'metavar': metavar, 'title': title} VIEW.view(model, view_kwargs, wait=wait, recycle=recycle) return VIEW
Get and clear the current |Node| and |Element| registries. Function |gather_registries| is thought to be used by class |Tester| only. def gather_registries() -> Tuple[Dict, Mapping, Mapping]: """Get and clear the current |Node| and |Element| registries. Function |gather_registries| is thought to be used by class |Tester| only. """ id2devices = copy.copy(_id2devices) registry = copy.copy(_registry) selection = copy.copy(_selection) dict_ = globals() dict_['_id2devices'] = {} dict_['_registry'] = {Node: {}, Element: {}} dict_['_selection'] = {Node: {}, Element: {}} return id2devices, registry, selection
Reset the current |Node| and |Element| registries. Function |reset_registries| is thought to be used by class |Tester| only. def reset_registries(dicts: Tuple[Dict, Mapping, Mapping]): """Reset the current |Node| and |Element| registries. Function |reset_registries| is thought to be used by class |Tester| only. """ dict_ = globals() dict_['_id2devices'] = dicts[0] dict_['_registry'] = dicts[1] dict_['_selection'] = dicts[2]
>>> from hydpy import pub >>> pub.timegrids = '2004.01.01', '2005.01.01', '1d' >>> from hydpy.core.devicetools import _get_pandasindex >>> _get_pandasindex() # doctest: +ELLIPSIS DatetimeIndex(['2004-01-01 12:00:00', '2004-01-02 12:00:00', ... '2004-12-30 12:00:00', '2004-12-31 12:00:00'], dtype='datetime64[ns]', length=366, freq=None) def _get_pandasindex(): """ >>> from hydpy import pub >>> pub.timegrids = '2004.01.01', '2005.01.01', '1d' >>> from hydpy.core.devicetools import _get_pandasindex >>> _get_pandasindex() # doctest: +ELLIPSIS DatetimeIndex(['2004-01-01 12:00:00', '2004-01-02 12:00:00', ... '2004-12-30 12:00:00', '2004-12-31 12:00:00'], dtype='datetime64[ns]', length=366, freq=None) """ tg = hydpy.pub.timegrids.init shift = tg.stepsize / 2 index = pandas.date_range( (tg.firstdate + shift).datetime, (tg.lastdate - shift).datetime, (tg.lastdate - tg.firstdate - tg.stepsize) / tg.stepsize + 1) return index
Return a list of all keywords starting with the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... 'keyboard') >>> keywords.startswith('keyword') ['keyword_3', 'keyword_4'] def startswith(self, name: str) -> List[str]: """Return a list of all keywords starting with the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... 'keyboard') >>> keywords.startswith('keyword') ['keyword_3', 'keyword_4'] """ return sorted(keyword for keyword in self if keyword.startswith(name))
Return a list of all keywords ending with the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... 'keyboard') >>> keywords.endswith('keyword') ['first_keyword', 'second_keyword'] def endswith(self, name: str) -> List[str]: """Return a list of all keywords ending with the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... 'keyboard') >>> keywords.endswith('keyword') ['first_keyword', 'second_keyword'] """ return sorted(keyword for keyword in self if keyword.endswith(name))
Return a list of all keywords containing the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... 'keyboard') >>> keywords.contains('keyword') ['first_keyword', 'keyword_3', 'keyword_4', 'second_keyword'] def contains(self, name: str) -> List[str]: """Return a list of all keywords containing the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... 'keyboard') >>> keywords.contains('keyword') ['first_keyword', 'keyword_3', 'keyword_4', 'second_keyword'] """ return sorted(keyword for keyword in self if name in keyword)
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") 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)
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") 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))
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. 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')
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. 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')
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'] 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)
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. 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
Call methods |Node.prepare_simseries| and |Node.prepare_obsseries|. def prepare_allseries(self, ramflag: bool = True) -> None: """Call methods |Node.prepare_simseries| and |Node.prepare_obsseries|.""" self.prepare_simseries(ramflag) self.prepare_obsseries(ramflag)
Call method |Node.prepare_simseries| of all handled |Node| objects. def prepare_simseries(self, ramflag: bool = True) -> None: """Call method |Node.prepare_simseries| of all handled |Node| objects.""" for node in printtools.progressbar(self): node.prepare_simseries(ramflag)
Call method |Node.prepare_obsseries| of all handled |Node| objects. def prepare_obsseries(self, ramflag: bool = True) -> None: """Call method |Node.prepare_obsseries| of all handled |Node| objects.""" for node in printtools.progressbar(self): node.prepare_obsseries(ramflag)
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 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()
Save the control parameters of the |Model| object handled by each |Element| object and eventually the ones handled by the given |Auxfiler| object. 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)
Save the initial conditions of the |Model| object handled by each |Element| object. 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()
Save the calculated conditions of the |Model| object handled by each |Element| object. 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()
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. 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}
Call method |Element.prepare_allseries| of all handled |Element| objects. def prepare_allseries(self, ramflag: bool = True) -> None: """Call method |Element.prepare_allseries| of all handled |Element| objects.""" for element in printtools.progressbar(self): element.prepare_allseries(ramflag)
Call method |Element.prepare_inputseries| of all handled |Element| objects. def prepare_inputseries(self, ramflag: bool = True) -> None: """Call method |Element.prepare_inputseries| of all handled |Element| objects.""" for element in printtools.progressbar(self): element.prepare_inputseries(ramflag)
Call method |Element.prepare_fluxseries| of all handled |Element| objects. def prepare_fluxseries(self, ramflag: bool = True) -> None: """Call method |Element.prepare_fluxseries| of all handled |Element| objects.""" for element in printtools.progressbar(self): element.prepare_fluxseries(ramflag)
Call method |Element.prepare_stateseries| of all handled |Element| objects. def prepare_stateseries(self, ramflag: bool = True) -> None: """Call method |Element.prepare_stateseries| of all handled |Element| objects.""" for element in printtools.progressbar(self): element.prepare_stateseries(ramflag)
Gather all "new" |Node| or |Element| objects. See the main documentation on module |devicetools| for further information. 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
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`. 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}`.')
Plot the |IOSequence.series| of the |Sim| sequence object. See method |Node.plot_allseries| for further information. 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)
Plot the |IOSequence.series| of the |Obs| sequence object. See method |Node.plot_allseries| for further information. 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)
Return a |repr| string with a prefixed assignment. def assignrepr(self, prefix: str = '') -> str: """Return a |repr| string with a prefixed assignment.""" lines = ['%sNode("%s", variable="%s",' % (prefix, self.name, self.variable)] if self.keywords: subprefix = '%skeywords=' % (' '*(len(prefix)+5)) with objecttools.repr_.preserve_strings(True): with objecttools.assignrepr_tuple.always_bracketed(False): line = objecttools.assignrepr_list( sorted(self.keywords), subprefix, width=70) lines.append(line + ',') lines[-1] = lines[-1][:-1]+')' return '\n'.join(lines)
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) 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.')
Load the control file of the actual |Element| object, initialise its |Model| object, build the required connections via (an eventually overridden version of) method |Model.connect| of class |Model|, and update its derived parameter values via calling (an eventually overridden version) of method |Parameters.update| of class |Parameters|. See method |HydPy.init_models| of class |HydPy| and property |model| of class |Element| fur further information. def init_model(self, clear_registry: bool = True) -> None: """Load the control file of the actual |Element| object, initialise its |Model| object, build the required connections via (an eventually overridden version of) method |Model.connect| of class |Model|, and update its derived parameter values via calling (an eventually overridden version) of method |Parameters.update| of class |Parameters|. See method |HydPy.init_models| of class |HydPy| and property |model| of class |Element| fur further information. """ try: with hydpy.pub.options.warnsimulationstep(False): info = hydpy.pub.controlmanager.load_file( element=self, clear_registry=clear_registry) self.model = info['model'] self.model.parameters.update() except OSError: if hydpy.pub.options.warnmissingcontrolfile: warnings.warn( f'Due to a missing or no accessible control file, no ' f'model could be initialised for element `{self.name}`') else: objecttools.augment_excmessage( f'While trying to initialise the model ' f'object of element `{self.name}`') except BaseException: objecttools.augment_excmessage( f'While trying to initialise the model ' f'object of element `{self.name}`')
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'] 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
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. 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)
Plot (the selected) |InputSequence| |IOSequence.series| values. We demonstrate the functionalities of method |Element.plot_inputseries| based on the `Lahn` example project: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, _, _ = prepare_full_example_2(lastdate='1997-01-01') Without any arguments, |Element.plot_inputseries| prints the time series of all input sequences handled by its |Model| object directly to the screen (in the given example, |hland_inputs.P|, |hland_inputs.T|, |hland_inputs.TN|, and |hland_inputs.EPN| of application model |hland_v1|): >>> land = hp.elements.land_dill >>> land.plot_inputseries() You can use the `pyplot` API of `matplotlib` to modify the figure or to save it to disk (or print it to the screen, in case the interactive mode of `matplotlib` is disabled): >>> from matplotlib import pyplot >>> from hydpy.docs import figs >>> pyplot.savefig(figs.__path__[0] + '/Element_plot_inputseries.png') >>> pyplot.close() .. image:: Element_plot_inputseries.png Methods |Element.plot_fluxseries| and |Element.plot_stateseries| work in the same manner. Before applying them, one has at first to calculate the time series of the |FluxSequence| and |StateSequence| objects: >>> hp.doit() All three methods allow to select certain sequences by passing their names (here, flux sequences |hland_fluxes.Q0| and |hland_fluxes.Q1| of |hland_v1|). Additionally, you can pass the keyword arguments supported by `matplotlib` for modifying the line style: >>> land.plot_fluxseries(['q0', 'q1'], linewidth=2) >>> pyplot.savefig(figs.__path__[0] + '/Element_plot_fluxseries.png') >>> pyplot.close() .. image:: Element_plot_fluxseries.png For 1-dimensional |IOSequence| objects, all three methods plot the individual time series in the same colour (here, from the state sequences |hland_states.SP| and |hland_states.WC| of |hland_v1|): >>> land.plot_stateseries(['sp', 'wc']) >>> pyplot.savefig(figs.__path__[0] + '/Element_plot_stateseries1.png') >>> pyplot.close() .. image:: Element_plot_stateseries1.png Alternatively, you can print the averaged time series through passing |True| to the method `average` argument (demonstrated for the state sequence |hland_states.SM|): >>> land.plot_stateseries(['sm'], color='grey') >>> land.plot_stateseries( ... ['sm'], average=True, color='black', linewidth=3) >>> pyplot.savefig(figs.__path__[0] + '/Element_plot_stateseries2.png') >>> pyplot.close() .. image:: Element_plot_stateseries2.png def plot_inputseries( self, names: Optional[Iterable[str]] = None, average: bool = False, **kwargs: Any) \ -> None: """Plot (the selected) |InputSequence| |IOSequence.series| values. We demonstrate the functionalities of method |Element.plot_inputseries| based on the `Lahn` example project: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, _, _ = prepare_full_example_2(lastdate='1997-01-01') Without any arguments, |Element.plot_inputseries| prints the time series of all input sequences handled by its |Model| object directly to the screen (in the given example, |hland_inputs.P|, |hland_inputs.T|, |hland_inputs.TN|, and |hland_inputs.EPN| of application model |hland_v1|): >>> land = hp.elements.land_dill >>> land.plot_inputseries() You can use the `pyplot` API of `matplotlib` to modify the figure or to save it to disk (or print it to the screen, in case the interactive mode of `matplotlib` is disabled): >>> from matplotlib import pyplot >>> from hydpy.docs import figs >>> pyplot.savefig(figs.__path__[0] + '/Element_plot_inputseries.png') >>> pyplot.close() .. image:: Element_plot_inputseries.png Methods |Element.plot_fluxseries| and |Element.plot_stateseries| work in the same manner. Before applying them, one has at first to calculate the time series of the |FluxSequence| and |StateSequence| objects: >>> hp.doit() All three methods allow to select certain sequences by passing their names (here, flux sequences |hland_fluxes.Q0| and |hland_fluxes.Q1| of |hland_v1|). Additionally, you can pass the keyword arguments supported by `matplotlib` for modifying the line style: >>> land.plot_fluxseries(['q0', 'q1'], linewidth=2) >>> pyplot.savefig(figs.__path__[0] + '/Element_plot_fluxseries.png') >>> pyplot.close() .. image:: Element_plot_fluxseries.png For 1-dimensional |IOSequence| objects, all three methods plot the individual time series in the same colour (here, from the state sequences |hland_states.SP| and |hland_states.WC| of |hland_v1|): >>> land.plot_stateseries(['sp', 'wc']) >>> pyplot.savefig(figs.__path__[0] + '/Element_plot_stateseries1.png') >>> pyplot.close() .. image:: Element_plot_stateseries1.png Alternatively, you can print the averaged time series through passing |True| to the method `average` argument (demonstrated for the state sequence |hland_states.SM|): >>> land.plot_stateseries(['sm'], color='grey') >>> land.plot_stateseries( ... ['sm'], average=True, color='black', linewidth=3) >>> pyplot.savefig(figs.__path__[0] + '/Element_plot_stateseries2.png') >>> pyplot.close() .. image:: Element_plot_stateseries2.png """ self.__plot(self.model.sequences.inputs, names, average, kwargs)
Plot the `flux` series of the handled model. See the documentation on method |Element.plot_inputseries| for additional information. 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)
Plot the `state` series of the handled model. See the documentation on method |Element.plot_inputseries| for additional information. 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)
Return a |repr| string with a prefixed assignment. def assignrepr(self, prefix: str) -> str: """Return a |repr| string with a prefixed assignment.""" with objecttools.repr_.preserve_strings(True): with objecttools.assignrepr_tuple.always_bracketed(False): blanks = ' ' * (len(prefix) + 8) lines = ['%sElement("%s",' % (prefix, self.name)] for groupname in ('inlets', 'outlets', 'receivers', 'senders'): group = getattr(self, groupname, Node) if group: subprefix = '%s%s=' % (blanks, groupname) # pylint: disable=not-an-iterable # because pylint is wrong nodes = [str(node) for node in group] # pylint: enable=not-an-iterable line = objecttools.assignrepr_list( nodes, subprefix, width=70) lines.append(line + ',') if self.keywords: subprefix = '%skeywords=' % blanks line = objecttools.assignrepr_list( sorted(self.keywords), subprefix, width=70) lines.append(line + ',') lines[-1] = lines[-1][:-1]+')' return '\n'.join(lines)
Convert all pure Python calculation functions of the model class to methods and assign them to the model instance. 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)
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' 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
Connect the link sequences of the actual model. 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)))
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) 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)
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) 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))
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) 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]))
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 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.
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 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_)
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 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)))
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 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
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|. 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()
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 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}`')
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 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
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')) 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))
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 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
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")) 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
Load the condition files of the |Model| objects of all |Element| objects returned by |XMLInterface.elements|: >>> 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() ... interface.find('selections').text = 'headwaters' ... interface.conditions_io.load_conditions() >>> hp.elements.land_lahn_1.model.sequences.states.lz lz(8.18711) >>> hp.elements.land_lahn_2.model.sequences.states.lz lz(nan) def load_conditions(self) -> None: """Load the condition files of the |Model| objects of all |Element| objects returned by |XMLInterface.elements|: >>> 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() ... interface.find('selections').text = 'headwaters' ... interface.conditions_io.load_conditions() >>> hp.elements.land_lahn_1.model.sequences.states.lz lz(8.18711) >>> hp.elements.land_lahn_2.model.sequences.states.lz lz(nan) """ hydpy.pub.conditionmanager.currentdir = strip( self.find('inputdir').text) for element in self.master.elements: element.model.sequences.load_conditions()
Save the condition files of the |Model| objects of all |Element| objects returned by |XMLInterface.elements|: >>> from hydpy.core.examples import prepare_full_example_1 >>> prepare_full_example_1() >>> import os >>> from hydpy import HydPy, TestIO, XMLInterface, pub >>> hp = HydPy('LahnH') >>> with TestIO(): ... hp.prepare_network() ... hp.init_models() ... hp.elements.land_dill.model.sequences.states.lz = 999.0 ... interface = XMLInterface('single_run.xml') ... interface.update_timegrids() ... interface.find('selections').text = 'headwaters' ... interface.conditions_io.save_conditions() ... dirpath = 'LahnH/conditions/init_1996_01_06' ... with open(os.path.join(dirpath, 'land_dill.py')) as file_: ... print(file_.readlines()[11].strip()) ... os.path.exists(os.path.join(dirpath, 'land_lahn_2.py')) lz(999.0) False def save_conditions(self) -> None: """Save the condition files of the |Model| objects of all |Element| objects returned by |XMLInterface.elements|: >>> from hydpy.core.examples import prepare_full_example_1 >>> prepare_full_example_1() >>> import os >>> from hydpy import HydPy, TestIO, XMLInterface, pub >>> hp = HydPy('LahnH') >>> with TestIO(): ... hp.prepare_network() ... hp.init_models() ... hp.elements.land_dill.model.sequences.states.lz = 999.0 ... interface = XMLInterface('single_run.xml') ... interface.update_timegrids() ... interface.find('selections').text = 'headwaters' ... interface.conditions_io.save_conditions() ... dirpath = 'LahnH/conditions/init_1996_01_06' ... with open(os.path.join(dirpath, 'land_dill.py')) as file_: ... print(file_.readlines()[11].strip()) ... os.path.exists(os.path.join(dirpath, 'land_lahn_2.py')) lz(999.0) False """ hydpy.pub.conditionmanager.currentdir = strip( self.find('outputdir').text) for element in self.master.elements: element.model.sequences.save_conditions() if strip(self.find('zip').text) == 'true': hydpy.pub.conditionmanager.zip_currentdir()
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 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)
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',) 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)
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() 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)