Instruction:
Here you have a function in Python 3, explain what it does
def remove_device(self, device: Union[DeviceType, str]) -> None:
        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')

Response: Remove the given device from the actual nodes or elements.


Instruction:
How would you explain what the following Python 3 function does
def copy(self: DevicesTypeBound) -> DevicesTypeBound:
        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

Response: Return a shallow copy of the actual |Nodes| or |Elements| object.


Instruction:
Write a Python 3 function that can
call methods |Node. prepare_simseries| and |Node. prepare_obsseries| and |Node. prepare_simseries| and |Node. prepare_obsseries|.

Response:
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)


Instruction:
Implement a Python 3 function for
calling method |Node. prepare_simseries| of all handled objects.

Response:
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)


Instruction:
Can you generate the documentation for the following Python 3 function
def prepare_obsseries(self, ramflag: bool = True) -> None:
        for node in printtools.progressbar(self):
            node.prepare_obsseries(ramflag)

Response:
Call method |Node. prepare_obsseries| of all handled
        objects.


Instruction:
Here you have a function in Python 3, explain what it does
def init_models(self) -> None:
        try:
            for element in printtools.progressbar(self):
                element.init_model(clear_registry=False)
        finally:
            hydpy.pub.controlmanager.clear_registry()

Response: Initializes the model objects of all elements of all handle.


Instruction:
Write a Python 3 function that can
save the control parameters of the model object handled by the Arc with the given parameterstep and simulationstep.

Response:
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)


Instruction:
Write a Python 3 function for
saving the initial conditions of the model object handled by each |Element| object.

Response:
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()


Instruction:
How would you implement a function in Python 3 that
saves the calculated conditions of the model objects handled by each |Element| object.

Response:
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()


Instruction:
Given the following Python 3 function, write the documentation
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}

Response: A nested dictionary containing the values of all currently handled models.


Instruction:
Make a summary of the following Python 3 code
def prepare_allseries(self, ramflag: bool = True) -> None:
        for element in printtools.progressbar(self):
            element.prepare_allseries(ramflag)

Response:
Call method |Element. prepare_allseries| of all handled
            objects.


Instruction:
How would you code a function in Python 3 to
call method |Element. prepare_inputseries| of all handled objects.

Response:
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)


Instruction:
Write a Python 3 function that can
call method |Element. prepare_fluxseries| of all handled objects.

Response:
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)


Instruction:
How would you explain what the following Python 3 function does
def prepare_stateseries(self, ramflag: bool = True) -> None:
        for element in printtools.progressbar(self):
            element.prepare_stateseries(ramflag)

Response:
Call method |Element. prepare_stateseries| of all handled
            objects.


Instruction:
How would you implement a function in Python 3 that
extracts all new |Node| or |Element| objects.

Response:
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


Instruction:
Can you generate the documentation for the following Python 3 function
def get_double(self, group: str) -> pointerutils.Double:
        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}`.')

Response: Return the |Double| object appropriate for the given |Element| input or output group and the actual |Node. deploymode|.


Instruction:
Given the following Python 3 function, write the documentation
def plot_simseries(self, **kwargs: Any) -> None:
        self.__plot_series([self.sequences.sim], kwargs)

Response: Plot the |IOSequence. series| of the Sim object.


Instruction:
How would you explain what the following Python 3 function does
def plot_obsseries(self, **kwargs: Any) -> None:
        self.__plot_series([self.sequences.obs], kwargs)

Response: Plot the |IOSequence. series| of the |Obs| sequence object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def assignrepr(self, prefix: str = '') -> str:
        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)

Response: Return a |repr| string with a prefixed assignment.


Instruction:
How would you explain what the following Python 3 function does
def model(self) -> 'modeltools.Model':
        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.')

Response: The model object of the actual |Element| object.


Instruction:
Given the following Python 3 function, write the documentation
def init_model(self, clear_registry: bool = True) -> None:
        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}`')

Response: Initialise the internal |Model| object of the actual |Element| object.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def variables(self) -> Set[str]:
        variables: Set[str] = set()
        for connection in self.__connections:
            variables.update(connection.variables)
        return variables

Response: A set of all different variable values of the actual |Node| object.


Instruction:
Create a Python 3 function to
prepare the |IOSequence. series| objects of all input flux and state sequences of the current element.

Response:
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)


Instruction:
Given the following Python 3 function, write the documentation
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)

Response: Plot the time series of all input sequences handled by the object.


Instruction:
Create a Python 3 function for
plotting the flux series of the handled model.

Response:
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)


Instruction:
Implement a function in Python 3 to
plot the state series of the handled model.

Response:
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)


Instruction:
Create a Python 3 function to
return a |repr| string with a prefixed assignment.

Response:
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)


Instruction:
Here you have a function in Python 3, explain what it does
def _init_methods(self):
        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)

Response:
Convert all pure Python calculation functions of the model class to
        methods and assign them to the model instance.


Instruction:
Write a Python 3 function for
naming of the model type.

Response:
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


Instruction:
Create a Python 3 function for
connecting the link sequences of the actual model to the actual node.

Response:
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)))


Instruction:
Create a Python 3 function to
apply all methods stored in the hidden attribute PART_ODE_METHODS.

Response:
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)


Instruction:
Create a Python 3 function for
getting the sum of the fluxes calculated so far.

Response:
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))


Instruction:
Create a Python 3 function for
integrating the fluxes between the two sequences.

Response:
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]))


Instruction:
How would you code a function in Python 3 to
reset the sum of the fluxes calculated so far to zero.

Response:
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.


Instruction:
Here you have a function in Python 3, explain what it does
def addup_fluxes(self):
        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_)

Response: Add up the sum of the fluxes calculated so far.


Instruction:
Can you generate the documentation for the following Python 3 function
def calculate_error(self):
        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)))

Response:
Estimate the numerical error based on the fluxes calculated
        by the current and the last method.


Instruction:
Implement a Python 3 function for
estimating the numerical error to be expected when applying all methods available.

Response:
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


Instruction:
Write a Python 3 script to
perform a HydPy simulation in agreement with the given XML configuration file.

Response:
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()


Instruction:
Given the following Python 3 function, write the documentation
def validate_xml(self) -> None:
        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}`')

Response: Raise an error if the actual XML does not agree with one of the available schema files.


Instruction:
How would you explain what the following Python 3 function does
def update_options(self) -> None:
        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

Response: Update the |Options| object available in module |pub| with the values defined in the options XML element.


Instruction:
Here you have a function in Python 3, explain what it does
def update_timegrids(self) -> None:
        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))

Response: Update the |Timegrids| object with the values defined in the timegrid XML element.


Instruction:
Explain what the following Python 3 code does
def elements(self) -> Iterator[devicetools.Element]:
        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

Response: Yield all |Element| objects returned by |XMLInterface. selections| and |XMLInterface. devices| without duplicates.


Instruction:
Explain what the following Python 3 code does
def load_conditions(self) -> None:
        hydpy.pub.conditionmanager.currentdir = strip(
            self.find('inputdir').text)
        for element in self.master.elements:
            element.model.sequences.load_conditions()

Response: Load the condition files of all |Element| objects of all |Element| objects of all |XMLInterface. elements|.


Instruction:
Given the following Python 3 function, write the documentation
def save_conditions(self) -> None:
        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()

Response: Save the conditions of the |Model| objects of all |Element| objects returned by |XMLInterface. elements|.


Instruction:
Here you have a function in Python 3, explain what it does
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)

Response: Call |XMLSubseries. prepare_series| of all |XMLSubseries| objects with the same memory |set| object.


Instruction:
Explain what the following Python 3 code does
def selections(self) -> selectiontools.Selections:
        selections = self.find('selections')
        master = self
        while selections is None:
            master = master.master
            selections = master.find('selections')
        return _query_selections(selections)

Response:
The |Selections| object defined for the respective reader or writer element of the actual XML file. ToDo
        is used.


Instruction:
Given the following Python 3 function, write the documentation
def prepare_sequencemanager(self) -> None:
        for config, convert in (
                ('filetype', lambda x: x),
                ('aggregation', lambda x: x),
                ('overwrite', lambda x: x.lower() == 'true'),
                ('dirpath', lambda x: x)):
            xml_special = self.find(config)
            xml_general = self.master.find(config)
            for name_manager, name_xml in zip(
                    ('input', 'flux', 'state', 'node'),
                    ('inputs', 'fluxes', 'states', 'nodes')):
                value = None
                for xml, attr_xml in zip(
                        (xml_special, xml_special, xml_general, xml_general),
                        (name_xml, 'general', name_xml, 'general')):
                    try:
                        value = find(xml, attr_xml).text
                    except AttributeError:
                        continue
                    break
                setattr(hydpy.pub.sequencemanager,
                        f'{name_manager}{config}',
                        convert(value))

Response:
Configure the |SequenceManager| object available in module
       .


Instruction:
Make a summary of the following Python 3 code
def prepare_series(self, memory: set) -> None:
        for sequence in self._iterate_sequences():
            if sequence not in memory:
                memory.add(sequence)
                sequence.activate_ram()

Response:
Call |IOSequence. activate_ram| of all sequences selected by
        |IOSequence. deactivate_ram| of all sequences selected by
        |IOSequence. prepare_series| of all sequences selected by
        |IOSequence. prepare_full_example_1| of the full XML file.


Instruction:
Make a summary of the following Python 3 code
def load_series(self) -> None:
        kwargs = {}
        for keyword in ('flattennetcdf', 'isolatenetcdf', 'timeaxisnetcdf'):
            argument = getattr(hydpy.pub.options, keyword, None)
            if argument is not None:
                kwargs[keyword[:-6]] = argument
        hydpy.pub.sequencemanager.open_netcdf_reader(**kwargs)
        self.prepare_sequencemanager()
        for sequence in self._iterate_sequences():
            sequence.load_ext()
        hydpy.pub.sequencemanager.close_netcdf_reader()

Response: Load time series data as defined by the actual XML reader.


Instruction:
How would you implement a function in Python 3 that
saves time series data as defined by the actual XML writer.

Response:
def save_series(self) -> None:
        """Save time series data as defined by the actual XML `writer`
        element.

        >>> from hydpy.core.examples import prepare_full_example_1
        >>> prepare_full_example_1()

        >>> from hydpy import HydPy, TestIO, XMLInterface
        >>> hp = HydPy('LahnH')
        >>> with TestIO():
        ...     hp.prepare_network()
        ...     hp.init_models()
        ...     interface = XMLInterface('single_run.xml')
        ...     interface.update_options()
        >>> interface.update_timegrids()
        >>> series_io = interface.series_io
        >>> series_io.prepare_series()
        >>> hp.elements.land_dill.model.sequences.fluxes.pc.series[2, 3] = 9.0
        >>> hp.nodes.lahn_2.sequences.sim.series[4] = 7.0
        >>> with TestIO():
        ...     series_io.save_series()
        >>> import numpy
        >>> with TestIO():
        ...     os.path.exists(
        ...         'LahnH/series/output/land_lahn_2_flux_pc.npy')
        ...     os.path.exists(
        ...         'LahnH/series/output/land_lahn_3_flux_pc.npy')
        ...     numpy.load(
        ...         'LahnH/series/output/land_dill_flux_pc.npy')[13+2, 3]
        ...     numpy.load(
        ...         'LahnH/series/output/lahn_2_sim_q_mean.npy')[13+4]
        True
        False
        9.0
        7.0
        """
        hydpy.pub.sequencemanager.open_netcdf_writer(
            flatten=hydpy.pub.options.flattennetcdf,
            isolate=hydpy.pub.options.isolatenetcdf)
        self.prepare_sequencemanager()
        for sequence in self._iterate_sequences():
            sequence.save_ext()
        hydpy.pub.sequencemanager.close_netcdf_writer()


Instruction:
Make a summary of the following Python 3 code
def item(self):
        target = f'{self.master.name}.{self.name}'
        if self.master.name == 'nodes':
            master = self.master.name
            itemgroup = self.master.master.name
        else:
            master = self.master.master.name
            itemgroup = self.master.master.master.name
        itemclass = _ITEMGROUP2ITEMCLASS[itemgroup]
        if itemgroup == 'getitems':
            return self._get_getitem(target, master, itemclass)
        return self._get_changeitem(target, master, itemclass, itemgroup)

Response:
ToDo
 is a simple example of how to get the current item.


Instruction:
Create a Python 3 function to
write the complete base schema file for hydpy.

Response:
def write_xsd(cls) -> None:
        """Write the complete base schema file `HydPyConfigBase.xsd` based
        on the template file `HydPyConfigBase.xsdt`.

        Method |XSDWriter.write_xsd| adds model specific information to the
        general information of template file `HydPyConfigBase.xsdt` regarding
        reading and writing of time series data and exchanging parameter
        and sequence values e.g. during calibration.

        The following example shows that after writing a new schema file,
        method |XMLInterface.validate_xml| does not raise an error when
        either applied on the XML configuration files `single_run.xml` or
        `multiple_runs.xml` of the `LahnH` example project:

        >>> import os
        >>> from hydpy.auxs.xmltools import XSDWriter, XMLInterface
        >>> if os.path.exists(XSDWriter.filepath_target):
        ...     os.remove(XSDWriter.filepath_target)
        >>> os.path.exists(XSDWriter.filepath_target)
        False
        >>> XSDWriter.write_xsd()
        >>> os.path.exists(XSDWriter.filepath_target)
        True

        >>> from hydpy import data
        >>> for configfile in ('single_run.xml', 'multiple_runs.xml'):
        ...     XMLInterface(configfile, data.get_path('LahnH')).validate_xml()
        """
        with open(cls.filepath_source) as file_:
            template = file_.read()
        template = template.replace(
            '<!--include model sequence groups-->', cls.get_insertion())
        template = template.replace(
            '<!--include exchange items-->', cls.get_exchangeinsertion())
        with open(cls.filepath_target, 'w') as file_:
            file_.write(template)


Instruction:
Implement a Python 3 function for
returning a sorted |list| containing all application model names.

Response:
def get_modelnames() -> List[str]:
        """Return a sorted |list| containing all application model names.

        >>> from hydpy.auxs.xmltools import XSDWriter
        >>> print(XSDWriter.get_modelnames())    # doctest: +ELLIPSIS
        [...'dam_v001', 'dam_v002', 'dam_v003', 'dam_v004', 'dam_v005',...]
        """
        return sorted(str(fn.split('.')[0])
                      for fn in os.listdir(models.__path__[0])
                      if (fn.endswith('.py') and (fn != '__init__.py')))


Instruction:
Create a Python 3 function to
return the insertion string required for the given application model.

Response:
def get_modelinsertion(cls, model, indent) -> str:
        """Return the insertion string required for the given application model.

        >>> from hydpy.auxs.xmltools import XSDWriter
        >>> from hydpy import prepare_model
        >>> model = prepare_model('hland_v1')
        >>> print(XSDWriter.get_modelinsertion(model, 1))   # doctest: +ELLIPSIS
            <element name="inputs"
                     minOccurs="0">
                <complexType>
                    <sequence>
                        <element
                            name="p"
                            minOccurs="0"/>
        ...
            </element>
            <element name="fluxes"
                     minOccurs="0">
        ...
            </element>
            <element name="states"
                     minOccurs="0">
        ...
            </element>
        """
        texts = []
        for name in ('inputs', 'fluxes', 'states'):
            subsequences = getattr(model.sequences, name, None)
            if subsequences:
                texts.append(
                    cls.get_subsequencesinsertion(subsequences, indent))
        return '\n'.join(texts)


Instruction:
Write a Python 3 script for
returning the insertion string required for the given group of sequences.

Response:
def get_subsequencesinsertion(cls, subsequences, indent) -> str:
        """Return the insertion string required for the given group of
        sequences.

        >>> from hydpy.auxs.xmltools import XSDWriter
        >>> from hydpy import prepare_model
        >>> model = prepare_model('hland_v1')
        >>> print(XSDWriter.get_subsequencesinsertion(
        ...     model.sequences.fluxes, 1))    # doctest: +ELLIPSIS
            <element name="fluxes"
                     minOccurs="0">
                <complexType>
                    <sequence>
                        <element
                            name="tmean"
                            minOccurs="0"/>
                        <element
                            name="tc"
                            minOccurs="0"/>
        ...
                        <element
                            name="qt"
                            minOccurs="0"/>
                    </sequence>
                </complexType>
            </element>

        """
        blanks = ' ' * (indent*4)
        lines = [f'{blanks}<element name="{subsequences.name}"',
                 f'{blanks}         minOccurs="0">',
                 f'{blanks}    <complexType>',
                 f'{blanks}        <sequence>']
        for sequence in subsequences:
            lines.append(cls.get_sequenceinsertion(sequence, indent + 3))
        lines.extend([f'{blanks}        </sequence>',
                      f'{blanks}    </complexType>',
                      f'{blanks}</element>'])
        return '\n'.join(lines)


Instruction:
Implement a Python 3 function for
returning the complete string related to the definition of exchange items to be inserted into the string of the template file.

Response:
def get_exchangeinsertion(cls):
        """Return the complete string related to the definition of exchange
        items to be inserted into the string of the template file.

        >>> from hydpy.auxs.xmltools import XSDWriter
        >>> print(XSDWriter.get_exchangeinsertion())    # doctest: +ELLIPSIS
            <complexType name="arma_v1_mathitemType">
        ...
            <element name="setitems">
        ...
            <complexType name="arma_v1_setitemsType">
        ...
            <element name="additems">
        ...
            <element name="getitems">
        ...
        """
        indent = 1
        subs = [cls.get_mathitemsinsertion(indent)]
        for groupname in ('setitems', 'additems', 'getitems'):
            subs.append(cls.get_itemsinsertion(groupname, indent))
            subs.append(cls.get_itemtypesinsertion(groupname, indent))
        return '\n'.join(subs)


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_mathitemsinsertion(cls, indent) -> str:
        blanks = ' ' * (indent*4)
        subs = []
        for modelname in cls.get_modelnames():
            model = importtools.prepare_model(modelname)
            subs.extend([
                f'{blanks}<complexType name="{modelname}_mathitemType">',
                f'{blanks}    <complexContent>',
                f'{blanks}        <extension base="hpcb:setitemType">',
                f'{blanks}            <choice>'])
            for subvars in cls._get_subvars(model):
                for var in subvars:
                    subs.append(
                        f'{blanks}                '
                        f'<element name="{subvars.name}.{var.name}"/>')
            subs.extend([
                    f'{blanks}            </choice>',
                    f'{blanks}        </extension>',
                    f'{blanks}    </complexContent>',
                    f'{blanks}</complexType>',
                    f''])
        return '\n'.join(subs)

Response:
Return a string defining a model specific XML type extending
       .


Instruction:
Can you generate a brief explanation for the following Python 3 code
def get_itemsinsertion(cls, itemgroup, indent) -> str:
        blanks = ' ' * (indent*4)
        subs = []
        subs.extend([
            f'{blanks}<element name="{itemgroup}">',
            f'{blanks}    <complexType>',
            f'{blanks}        <sequence>',
            f'{blanks}            <element ref="hpcb:selections"',
            f'{blanks}                     minOccurs="0"/>',
            f'{blanks}            <element ref="hpcb:devices"',
            f'{blanks}                     minOccurs="0"/>'])
        for modelname in cls.get_modelnames():
            type_ = cls._get_itemstype(modelname, itemgroup)
            subs.append(f'{blanks}            <element name="{modelname}"')
            subs.append(f'{blanks}                     type="hpcb:{type_}"')
            subs.append(f'{blanks}                     minOccurs="0"')
            subs.append(f'{blanks}                     maxOccurs="unbounded"/>')
        if itemgroup in ('setitems', 'getitems'):
            type_ = f'nodes_{itemgroup}Type'
            subs.append(f'{blanks}            <element name="nodes"')
            subs.append(f'{blanks}                     type="hpcb:{type_}"')
            subs.append(f'{blanks}                     minOccurs="0"')
            subs.append(f'{blanks}                     maxOccurs="unbounded"/>')
        subs.extend([
                f'{blanks}        </sequence>',
                f'{blanks}        <attribute name="info" type="string"/>',
                f'{blanks}    </complexType>',
                f'{blanks}</element>',
                f''])
        return '\n'.join(subs)

Response: Return a string defining the XML element for the given item group.


Instruction:
Create a Python 3 function for
returning a string defining the required types for the given item group.

Response:
def get_itemtypesinsertion(cls, itemgroup, indent) -> str:
        """Return a string defining the required types for the given
        exchange item group.

        >>> from hydpy.auxs.xmltools import XSDWriter
        >>> print(XSDWriter.get_itemtypesinsertion(
        ...     'setitems', 1))    # doctest: +ELLIPSIS
            <complexType name="arma_v1_setitemsType">
        ...
            </complexType>
        <BLANKLINE>
            <complexType name="dam_v001_setitemsType">
        ...
            <complexType name="nodes_setitemsType">
        ...
        """
        subs = []
        for modelname in cls.get_modelnames():
            subs.append(cls.get_itemtypeinsertion(itemgroup, modelname, indent))
        subs.append(cls.get_nodesitemtypeinsertion(itemgroup, indent))
        return '\n'.join(subs)


Instruction:
Create a Python 3 function for
returning a string defining the required types for the given itemgroup and an application model.

Response:
def get_itemtypeinsertion(cls, itemgroup, modelname, indent) -> str:
        """Return a string defining the required types for the given
        combination of an exchange item group and an application model.

        >>> from hydpy.auxs.xmltools import XSDWriter
        >>> print(XSDWriter.get_itemtypeinsertion(
        ...     'setitems', 'hland_v1', 1))    # doctest: +ELLIPSIS
            <complexType name="hland_v1_setitemsType">
                <sequence>
                    <element ref="hpcb:selections"
                             minOccurs="0"/>
                    <element ref="hpcb:devices"
                             minOccurs="0"/>
                    <element name="control"
                             minOccurs="0"
                             maxOccurs="unbounded">
        ...
                </sequence>
            </complexType>
        <BLANKLINE>
        """
        blanks = ' ' * (indent * 4)
        type_ = cls._get_itemstype(modelname, itemgroup)
        subs = [
            f'{blanks}<complexType name="{type_}">',
            f'{blanks}    <sequence>',
            f'{blanks}        <element ref="hpcb:selections"',
            f'{blanks}                 minOccurs="0"/>',
            f'{blanks}        <element ref="hpcb:devices"',
            f'{blanks}                 minOccurs="0"/>',
            cls.get_subgroupsiteminsertion(itemgroup, modelname, indent+2),
            f'{blanks}    </sequence>',
            f'{blanks}</complexType>',
            f'']
        return '\n'.join(subs)


Instruction:
Here you have a function in Python 3, explain what it does
def get_nodesitemtypeinsertion(cls, itemgroup, indent) -> str:
        blanks = ' ' * (indent * 4)
        subs = [
            f'{blanks}<complexType name="nodes_{itemgroup}Type">',
            f'{blanks}    <sequence>',
            f'{blanks}        <element ref="hpcb:selections"',
            f'{blanks}                 minOccurs="0"/>',
            f'{blanks}        <element ref="hpcb:devices"',
            f'{blanks}                 minOccurs="0"/>']
        type_ = 'getitemType' if itemgroup == 'getitems' else 'setitemType'
        for name in ('sim', 'obs', 'sim.series', 'obs.series'):
            subs.extend([
                f'{blanks}        <element name="{name}"',
                f'{blanks}                 type="hpcb:{type_}"',
                f'{blanks}                 minOccurs="0"',
                f'{blanks}                 maxOccurs="unbounded"/>'])
        subs.extend([
            f'{blanks}    </sequence>',
            f'{blanks}</complexType>',
            f''])
        return '\n'.join(subs)

Response: Return a string defining the required types for the given item group and |Node| objects.


Instruction:
How would you explain what the following Python 3 function does
def get_subgroupsiteminsertion(cls, itemgroup, modelname, indent) -> str:
        subs = []
        model = importtools.prepare_model(modelname)
        for subvars in cls._get_subvars(model):
            subs.append(cls.get_subgroupiteminsertion(
                    itemgroup, model, subvars, indent))
        return '\n'.join(subs)

Response: Return a string defining the required types for the given item group and an application model.


Instruction:
Explain what the following Python 3 code does
def get_subgroupiteminsertion(
            cls, itemgroup, model, subgroup, indent) -> str:
        """Return a string defining the required types for the given
        combination of an exchange item group and a specific variable
        subgroup of an application model or class |Node|.

        Note that for `setitems` and `getitems` `setitemType` and
        `getitemType` are referenced, respectively, and for all others
        the model specific `mathitemType`:

        >>> from hydpy import prepare_model
        >>> model = prepare_model('hland_v1')
        >>> from hydpy.auxs.xmltools import XSDWriter
        >>> print(XSDWriter.get_subgroupiteminsertion(    # doctest: +ELLIPSIS
        ...     'setitems', model, model.parameters.control, 1))
            <element name="control"
                     minOccurs="0"
                     maxOccurs="unbounded">
                <complexType>
                    <sequence>
                        <element ref="hpcb:selections"
                                 minOccurs="0"/>
                        <element ref="hpcb:devices"
                                 minOccurs="0"/>
                        <element name="area"
                                 type="hpcb:setitemType"
                                 minOccurs="0"
                                 maxOccurs="unbounded"/>
                        <element name="nmbzones"
        ...
                    </sequence>
                </complexType>
            </element>

        >>> print(XSDWriter.get_subgroupiteminsertion(    # doctest: +ELLIPSIS
        ...     'getitems', model, model.parameters.control, 1))
            <element name="control"
        ...
                        <element name="area"
                                 type="hpcb:getitemType"
                                 minOccurs="0"
                                 maxOccurs="unbounded"/>
        ...

        >>> print(XSDWriter.get_subgroupiteminsertion(    # doctest: +ELLIPSIS
        ...     'additems', model, model.parameters.control, 1))
            <element name="control"
        ...
                        <element name="area"
                                 type="hpcb:hland_v1_mathitemType"
                                 minOccurs="0"
                                 maxOccurs="unbounded"/>
        ...

        For sequence classes, additional "series" elements are added:

        >>> print(XSDWriter.get_subgroupiteminsertion(    # doctest: +ELLIPSIS
        ...     'setitems', model, model.sequences.fluxes, 1))
            <element name="fluxes"
        ...
                        <element name="tmean"
                                 type="hpcb:setitemType"
                                 minOccurs="0"
                                 maxOccurs="unbounded"/>
                        <element name="tmean.series"
                                 type="hpcb:setitemType"
                                 minOccurs="0"
                                 maxOccurs="unbounded"/>
                        <element name="tc"
        ...
                    </sequence>
                </complexType>
            </element>
        """
        blanks1 = ' ' * (indent * 4)
        blanks2 = ' ' * ((indent+5) * 4 + 1)
        subs = [
            f'{blanks1}<element name="{subgroup.name}"',
            f'{blanks1}         minOccurs="0"',
            f'{blanks1}         maxOccurs="unbounded">',
            f'{blanks1}    <complexType>',
            f'{blanks1}        <sequence>',
            f'{blanks1}            <element ref="hpcb:selections"',
            f'{blanks1}                     minOccurs="0"/>',
            f'{blanks1}            <element ref="hpcb:devices"',
            f'{blanks1}                     minOccurs="0"/>']
        seriesflags = (False,) if subgroup.name == 'control' else (False, True)
        for variable in subgroup:
            for series in seriesflags:
                name = f'{variable.name}.series' if series else variable.name
                subs.append(f'{blanks1}            <element name="{name}"')
                if itemgroup == 'setitems':
                    subs.append(f'{blanks2}type="hpcb:setitemType"')
                elif itemgroup == 'getitems':
                    subs.append(f'{blanks2}type="hpcb:getitemType"')
                else:
                    subs.append(
                        f'{blanks2}type="hpcb:{model.name}_mathitemType"')
                subs.append(f'{blanks2}minOccurs="0"')
                subs.append(f'{blanks2}maxOccurs="unbounded"/>')
        subs.extend([
            f'{blanks1}        </sequence>',
            f'{blanks1}    </complexType>',
            f'{blanks1}</element>'])
        return '\n'.join(subs)

Response:
Return a string defining the required types for the given item group and a specific variable
        subgroup of an application model or class |Node|.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def array2mask(cls, array=None, **kwargs):
        kwargs['dtype'] = bool
        if array is None:
            return numpy.ndarray.__new__(cls, 0, **kwargs)
        return numpy.asarray(array, **kwargs).view(cls)

Response: Create a new mask object based on the given |numpy. ndarray| and return it.


Instruction:
How would you explain what the following Python 3 function does
def new(cls, variable, **kwargs):
        return cls.array2mask(numpy.full(variable.shape, True))

Response:
Return a new |DefaultMask| object associated with the
        given |Variable| object.


Instruction:
Here you have a function in Python 3, explain what it does
def new(cls, variable, **kwargs):
        indices = cls.get_refindices(variable)
        if numpy.min(getattr(indices, 'values', 0)) < 1:
            raise RuntimeError(
                f'The mask of parameter {objecttools.elementphrase(variable)} '
                f'cannot be determined, as long as parameter `{indices.name}` '
                f'is not prepared properly.')
        mask = numpy.full(indices.shape, False, dtype=bool)
        refvalues = indices.values
        for relvalue in cls.RELEVANT_VALUES:
            mask[refvalues == relvalue] = True
        return cls.array2mask(mask, **kwargs)

Response:
Return a |IndexMask| object of the same shape as the
        parameter referenced by |Property|. The |IndexMask| object is only |True| if the respective entries of the referenced parameter are contained in the respective entries of the respective parameter.


Instruction:
Can you tell what is the following Python 3 function doing
def relevantindices(self) -> List[int]:
        return [idx for idx in numpy.unique(self.refindices.values)
                if idx in self.RELEVANT_VALUES]

Response:
A |list| of all currently relevant indices calculated as an
        intercection of the class attribute RELEVANT_VALUES and the property |IndexMask. refindices|.


Instruction:
Make a summary of the following Python 3 code
def calc_qref_v1(self):
    new = self.sequences.states.fastaccess_new
    old = self.sequences.states.fastaccess_old
    flu = self.sequences.fluxes.fastaccess
    flu.qref = (new.qz+old.qz+old.qa)/3.

Response: Determine the reference discharge within the given space - time interval.


Instruction:
Implement a function in Python 3 to
determine the actual traveling time of the water.

Response:
def calc_rk_v1(self):
    """Determine the actual traveling time of the water (not of the wave!).

    Required derived parameter:
      |Sek|

    Required flux sequences:
      |AG|
      |QRef|

    Calculated flux sequence:
      |RK|

    Basic equation:
      :math:`RK = \\frac{Laen \\cdot A}{QRef}`

    Examples:

        First, note that the traveling time is determined in the unit of the
        actual simulation step size:

        >>> from hydpy.models.lstream import *
        >>> parameterstep()
        >>> laen(25.0)
        >>> derived.sek(24*60*60)
        >>> fluxes.ag = 10.0
        >>> fluxes.qref = 1.0
        >>> model.calc_rk_v1()
        >>> fluxes.rk
        rk(2.893519)

        Second, for negative values or zero values of |AG| or |QRef|,
        the value of |RK| is set to zero:

        >>> fluxes.ag = 0.0
        >>> fluxes.qref = 1.0
        >>> model.calc_rk_v1()
        >>> fluxes.rk
        rk(0.0)

        >>> fluxes.ag = 0.0
        >>> fluxes.qref = 1.0
        >>> model.calc_rk_v1()
        >>> fluxes.rk
        rk(0.0)
    """
    con = self.parameters.control.fastaccess
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    if (flu.ag > 0.) and (flu.qref > 0.):
        flu.rk = (1000.*con.laen*flu.ag)/(der.sek*flu.qref)
    else:
        flu.rk = 0.


Instruction:
Can you tell what is the following Python 3 function doing
def calc_am_um_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    if flu.h <= 0.:
        flu.am = 0.
        flu.um = 0.
    elif flu.h < con.hm:
        flu.am = flu.h*(con.bm+flu.h*con.bnm)
        flu.um = con.bm+2.*flu.h*(1.+con.bnm**2)**.5
    else:
        flu.am = (con.hm*(con.bm+con.hm*con.bnm) +
                  ((flu.h-con.hm)*(con.bm+2.*con.hm*con.bnm)))
        flu.um = con.bm+(2.*con.hm*(1.+con.bnm**2)**.5)+(2*(flu.h-con.hm))

Response: Calculates the flown through area and the wetted perimeter of the main channel.


Instruction:
Can you tell what is the following Python 3 function doing
def calc_qm_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    if (flu.am > 0.) and (flu.um > 0.):
        flu.qm = con.ekm*con.skm*flu.am**(5./3.)/flu.um**(2./3.)*con.gef**.5
    else:
        flu.qm = 0.

Response: Calculate the discharge of the main channel after Manning - Strickler.


Instruction:
How would you code a function in Python 3 to
calculate the flown through area and wetted perimeter of the given forelands and the flown through the given area and the wetted perimeter of the given forelands.

Response:
def calc_av_uv_v1(self):
    """Calculate the flown through area and the wetted perimeter of both
    forelands.

    Note that the each foreland lies between the main channel and one
    outer embankment and that water flowing exactly above the a foreland
    is contributing to |AV|.  The theoretical surface seperating water
    above the main channel from water above the foreland is not
    contributing to |UV|, but the surface seperating water above the
    foreland from water above its outer embankment is contributing to |UV|.

    Required control parameters:
      |HM|
      |BV|
      |BNV|

    Required derived parameter:
      |HV|

    Required flux sequence:
      |H|

    Calculated flux sequence:
      |AV|
      |UV|

    Examples:

        Generally, right trapezoids are assumed.  Here, for simplicity, both
        forelands are assumed to be symmetrical.  Their smaller bases (bottoms)
        hava a length of 2 meters, their non-vertical legs show an inclination
        of 1 meter per 4 meters, and their height (depths) is 1 meter.  Both
        forelands lie 1 meter above the main channels bottom.

        >>> from hydpy.models.lstream import *
        >>> parameterstep()
        >>> hm(1.0)
        >>> bv(2.0)
        >>> bnv(4.0)
        >>> derived.hv(1.0)

        The first example deals with normal flow conditions, where water flows
        within the main channel completely (|H| < |HM|):

        >>> fluxes.h = 0.5
        >>> model.calc_av_uv_v1()
        >>> fluxes.av
        av(0.0, 0.0)
        >>> fluxes.uv
        uv(0.0, 0.0)

        The second example deals with moderate high flow conditions, where
        water flows over both forelands, but not over their embankments
        (|HM| < |H| < (|HM| + |HV|)):

        >>> fluxes.h = 1.5
        >>> model.calc_av_uv_v1()
        >>> fluxes.av
        av(1.5, 1.5)
        >>> fluxes.uv
        uv(4.061553, 4.061553)

        The third example deals with extreme high flow conditions, where
        water flows over the both foreland and their outer embankments
        ((|HM| + |HV|) < |H|):

        >>> fluxes.h = 2.5
        >>> model.calc_av_uv_v1()
        >>> fluxes.av
        av(7.0, 7.0)
        >>> fluxes.uv
        uv(6.623106, 6.623106)

        The forth example assures that zero widths or hights of the forelands
        are handled properly:

        >>> bv.left = 0.0
        >>> derived.hv.right = 0.0
        >>> model.calc_av_uv_v1()
        >>> fluxes.av
        av(4.0, 3.0)
        >>> fluxes.uv
        uv(4.623106, 3.5)
    """
    con = self.parameters.control.fastaccess
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for i in range(2):
        if flu.h <= con.hm:
            flu.av[i] = 0.
            flu.uv[i] = 0.
        elif flu.h <= (con.hm+der.hv[i]):
            flu.av[i] = (flu.h-con.hm)*(con.bv[i]+(flu.h-con.hm)*con.bnv[i]/2.)
            flu.uv[i] = con.bv[i]+(flu.h-con.hm)*(1.+con.bnv[i]**2)**.5
        else:
            flu.av[i] = (der.hv[i]*(con.bv[i]+der.hv[i]*con.bnv[i]/2.) +
                         ((flu.h-(con.hm+der.hv[i])) *
                          (con.bv[i]+der.hv[i]*con.bnv[i])))
            flu.uv[i] = ((con.bv[i])+(der.hv[i]*(1.+con.bnv[i]**2)**.5) +
                         (flu.h-(con.hm+der.hv[i])))


Instruction:
How would you code a function in Python 3 to
calculate the discharge of both forelands after Manning - Strickler.

Response:
def calc_qv_v1(self):
    """Calculate the discharge of both forelands after Manning-Strickler.

    Required control parameters:
      |EKV|
      |SKV|
      |Gef|

    Required flux sequence:
      |AV|
      |UV|

    Calculated flux sequence:
      |lstream_fluxes.QV|

    Examples:

        For appropriate strictly positive values:

        >>> from hydpy.models.lstream import *
        >>> parameterstep()
        >>> ekv(2.0)
        >>> skv(50.0)
        >>> gef(0.01)
        >>> fluxes.av = 3.0
        >>> fluxes.uv = 7.0
        >>> model.calc_qv_v1()
        >>> fluxes.qv
        qv(17.053102, 17.053102)

        For zero or negative values of the flown through surface or
        the wetted perimeter:

        >>> fluxes.av = -1.0, 3.0
        >>> fluxes.uv = 7.0, 0.0
        >>> model.calc_qv_v1()
        >>> fluxes.qv
        qv(0.0, 0.0)
    """
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for i in range(2):
        if (flu.av[i] > 0.) and (flu.uv[i] > 0.):
            flu.qv[i] = (con.ekv[i]*con.skv[i] *
                         flu.av[i]**(5./3.)/flu.uv[i]**(2./3.)*con.gef**.5)
        else:
            flu.qv[i] = 0.


Instruction:
How would you explain what the following Python 3 function does
def calc_avr_uvr_v1(self):
    con = self.parameters.control.fastaccess
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for i in range(2):
        if flu.h <= (con.hm+der.hv[i]):
            flu.avr[i] = 0.
            flu.uvr[i] = 0.
        else:
            flu.avr[i] = (flu.h-(con.hm+der.hv[i]))**2*con.bnvr[i]/2.
            flu.uvr[i] = (flu.h-(con.hm+der.hv[i]))*(1.+con.bnvr[i]**2)**.5

Response: Calculates the flown through area and the wetted perimeter of the all - water - related embankments.


Instruction:
How would you explain what the following Python 3 function does
def calc_qvr_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for i in range(2):
        if (flu.avr[i] > 0.) and (flu.uvr[i] > 0.):
            flu.qvr[i] = (con.ekv[i]*con.skv[i] *
                          flu.avr[i]**(5./3.)/flu.uvr[i]**(2./3.)*con.gef**.5)
        else:
            flu.qvr[i] = 0.

Response:
Calculate the discharge of both outer embankments after
    Manning - Strickler.


Instruction:
How would you code a function in Python 3 to
calculate the total cross section area of the total cross section.

Response:
def calc_ag_v1(self):
    """Sum the through flown area of the total cross section.

    Required flux sequences:
      |AM|
      |AV|
      |AVR|

    Calculated flux sequence:
      |AG|

    Example:

        >>> from hydpy.models.lstream import *
        >>> parameterstep()
        >>> fluxes.am = 1.0
        >>> fluxes.av= 2.0, 3.0
        >>> fluxes.avr = 4.0, 5.0
        >>> model.calc_ag_v1()
        >>> fluxes.ag
        ag(15.0)
    """
    flu = self.sequences.fluxes.fastaccess
    flu.ag = flu.am+flu.av[0]+flu.av[1]+flu.avr[0]+flu.avr[1]


Instruction:
How would you explain what the following Python 3 function does
def calc_qg_v1(self):
    flu = self.sequences.fluxes.fastaccess
    self.calc_am_um()
    self.calc_qm()
    self.calc_av_uv()
    self.calc_qv()
    self.calc_avr_uvr()
    self.calc_qvr()
    flu.qg = flu.qm+flu.qv[0]+flu.qv[1]+flu.qvr[0]+flu.qvr[1]

Response: Calculate the discharge of the total cross section.


Instruction:
Write a Python 3 script for
determining an starting interval for iteration methods as the one implemented in method |calc_h_v1|.

Response:
def calc_hmin_qmin_hmax_qmax_v1(self):
    """Determine an starting interval for iteration methods as the one
    implemented in method |calc_h_v1|.

    The resulting interval is determined in a manner, that on the
    one hand :math:`Qmin \\leq QRef \\leq Qmax` is fulfilled and on the
    other hand the results of method |calc_qg_v1| are continuous
    for :math:`Hmin \\leq H \\leq Hmax`.

    Required control parameter:
      |HM|

    Required derived parameters:
      |HV|
      |lstream_derived.QM|
      |lstream_derived.QV|

    Required flux sequence:
      |QRef|

    Calculated aide sequences:
      |HMin|
      |HMax|
      |QMin|
      |QMax|

    Besides the mentioned required parameters and sequences, those of the
    actual method for calculating the discharge of the total cross section
    might be required.  This is the case whenever water flows on both outer
    embankments.  In such occasions no previously determined upper boundary
    values are available and method |calc_hmin_qmin_hmax_qmax_v1| needs
    to increase the value of :math:`HMax` successively until the condition
    :math:`QG \\leq QMax` is met.
    """
    con = self.parameters.control.fastaccess
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    aid = self.sequences.aides.fastaccess
    if flu.qref <= der.qm:
        aid.hmin = 0.
        aid.qmin = 0.
        aid.hmax = con.hm
        aid.qmax = der.qm
    elif flu.qref <= min(der.qv[0], der.qv[1]):
        aid.hmin = con.hm
        aid.qmin = der.qm
        aid.hmax = con.hm+min(der.hv[0], der.hv[1])
        aid.qmax = min(der.qv[0], der.qv[1])
    elif flu.qref < max(der.qv[0], der.qv[1]):
        aid.hmin = con.hm+min(der.hv[0], der.hv[1])
        aid.qmin = min(der.qv[0], der.qv[1])
        aid.hmax = con.hm+max(der.hv[0], der.hv[1])
        aid.qmax = max(der.qv[0], der.qv[1])
    else:
        flu.h = con.hm+max(der.hv[0], der.hv[1])
        aid.hmin = flu.h
        aid.qmin = flu.qg
        while True:
            flu.h *= 2.
            self.calc_qg()
            if flu.qg < flu.qref:
                aid.hmin = flu.h
                aid.qmin = flu.qg
            else:
                aid.hmax = flu.h
                aid.qmax = flu.qg
                break


Instruction:
Can you write a function in Python 3 where it
calculates the approximate water stage resulting in a certain reference discarge.

Response:
def calc_h_v1(self):
    """Approximate the water stage resulting in a certain reference discarge
    with the Pegasus iteration method.

    Required control parameters:
      |QTol|
      |HTol|

    Required flux sequence:
      |QRef|

    Modified aide sequences:
      |HMin|
      |HMax|
      |QMin|
      |QMax|

    Calculated flux sequence:
      |H|

    Besides the parameters and sequences given above, those of the
    actual method for calculating the discharge of the total cross section
    are required.

    Examples:

        Essentially, the Pegasus method is a root finding algorithm which
        sequentially decreases its search radius (like the simple bisection
        algorithm) and shows superlinear convergence properties (like the
        Newton-Raphson algorithm).  Ideally, its convergence should be proved
        for each application model to be derived from HydPy-L-Stream.
        The following examples focus on the methods
        |calc_hmin_qmin_hmax_qmax_v1| and |calc_qg_v1| (including their
        submethods) only:

        >>> from hydpy.models.lstream import *
        >>> parameterstep()
        >>> model.calc_hmin_qmin_hmax_qmax = model.calc_hmin_qmin_hmax_qmax_v1
        >>> model.calc_qg = model.calc_qg_v1
        >>> model.calc_qm = model.calc_qm_v1
        >>> model.calc_av_uv = model.calc_av_uv_v1
        >>> model.calc_qv = model.calc_qv_v1
        >>> model.calc_avr_uvr = model.calc_avr_uvr_v1
        >>> model.calc_qvr = model.calc_qvr_v1

        Define the geometry and roughness values for the first test channel:

        >>> bm(2.0)
        >>> bnm(4.0)
        >>> hm(1.0)
        >>> bv(0.5, 10.0)
        >>> bbv(1.0, 2.0)
        >>> bnv(1.0, 8.0)
        >>> bnvr(20.0)
        >>> ekm(1.0)
        >>> skm(20.0)
        >>> ekv(1.0)
        >>> skv(60.0, 80.0)
        >>> gef(0.01)

        Set the error tolerances of the iteration small enough to not
        compromise the shown first six decimal places of the following
        results:

        >>> qtol(1e-10)
        >>> htol(1e-10)

        Derive the required secondary parameters:

        >>> derived.hv.update()
        >>> derived.qm.update()
        >>> derived.qv.update()

        Define a test function, accepting a reference discharge and printing
        both the approximated water stage and the related discharge value:

        >>> def test(qref):
        ...     fluxes.qref = qref
        ...     model.calc_hmin_qmin_hmax_qmax()
        ...     model.calc_h()
        ...     print(repr(fluxes.h))
        ...     print(repr(fluxes.qg))

        Zero discharge and the following discharge values are related to the
        only discontinuities of the given root finding problem:

        >>> derived.qm
        qm(8.399238)
        >>> derived.qv
        qv(left=154.463234, right=23.073584)

        The related water stages are the ones (directly or indirectly)
        defined above:

        >>> test(0.0)
        h(0.0)
        qg(0.0)
        >>> test(derived.qm)
        h(1.0)
        qg(8.399238)
        >>> test(derived.qv.left)
        h(2.0)
        qg(154.463234)
        >>> test(derived.qv.right)
        h(1.25)
        qg(23.073584)

        Test some intermediate water stages, inundating the only the main
        channel, the main channel along with the right foreland, and the
        main channel along with both forelands respectively:

        >>> test(6.0)
        h(0.859452)
        qg(6.0)
        >>> test(10.0)
        h(1.047546)
        qg(10.0)
        >>> test(100.0)
        h(1.77455)
        qg(100.0)

        Finally, test two extreme water stages, inundating both outer
        foreland embankments:

        >>> test(200.0)
        h(2.152893)
        qg(200.0)
        >>> test(2000.0)
        h(4.240063)
        qg(2000.0)

        There is a potential risk of the implemented iteration method to fail
        for special channel geometries.  To test such cases in a more
        condensed manner, the following test methods evaluates different water
        stages automatically in accordance with the example above.  An error
        message is printed only, the estimated discharge does not approximate
        the reference discharge with six decimal places:

        >>> def test():
        ...     derived.hv.update()
        ...     derived.qm.update()
        ...     derived.qv.update()
        ...     qm, qv = derived.qm, derived.qv
        ...     for qref in [0.0, qm, qv.left, qv.right,
        ...                  2.0/3.0*qm+1.0/3.0*min(qv),
        ...                  2.0/3.0*min(qv)+1.0/3.0*max(qv),
        ...                  3.0*max(qv), 30.0*max(qv)]:
        ...         fluxes.qref = qref
        ...         model.calc_hmin_qmin_hmax_qmax()
        ...         model.calc_h()
        ...         if abs(round(fluxes.qg-qref) > 0.0):
        ...             print('Error!', 'qref:', qref, 'qg:', fluxes.qg)

        Check for a triangle main channel:

        >>> bm(0.0)
        >>> test()
        >>> bm(2.0)

        Check for a completely flat main channel:

        >>> hm(0.0)
        >>> test()

        Repeat the last example but with a decreased value of |QTol|
        allowing to trigger another stopping mechanisms if the
        iteration algorithm:

        >>> qtol(0.0)
        >>> test()
        >>> hm(1.0)
        >>> qtol(1e-10)

        Check for a nonexistend main channel:

        >>> bm(0.0)
        >>> bnm(0.0)
        >>> test()
        >>> bm(2.0)
        >>> bnm(4.0)

        Check for a nonexistend forelands:

        >>> bv(0.0)
        >>> bbv(0.0)
        >>> test()
        >>> bv(0.5, 10.0)
        >>> bbv(1., 2.0)

        Check for nonexistend outer foreland embankments:

        >>> bnvr(0.0)
        >>> test()

        To take the last test as an illustrative example, one can see that
        the given reference discharge is met by the estimated total discharge,
        which consists of components related to the main channel and the
        forelands only:

        >>> fluxes.qref
        qref(3932.452785)
        >>> fluxes.qg
        qg(3932.452785)
        >>> fluxes.qm
        qm(530.074621)
        >>> fluxes.qv
        qv(113.780226, 3288.597937)
        >>> fluxes.qvr
        qvr(0.0, 0.0)
    """
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    aid = self.sequences.aides.fastaccess
    aid.qmin -= flu.qref
    aid.qmax -= flu.qref
    if modelutils.fabs(aid.qmin) < con.qtol:
        flu.h = aid.hmin
        self.calc_qg()
    elif modelutils.fabs(aid.qmax) < con.qtol:
        flu.h = aid.hmax
        self.calc_qg()
    elif modelutils.fabs(aid.hmax-aid.hmin) < con.htol:
        flu.h = (aid.hmin+aid.hmax)/2.
        self.calc_qg()
    else:
        while True:
            flu.h = aid.hmin-aid.qmin*(aid.hmax-aid.hmin)/(aid.qmax-aid.qmin)
            self.calc_qg()
            aid.qtest = flu.qg-flu.qref
            if modelutils.fabs(aid.qtest) < con.qtol:
                return
            if (((aid.qmax < 0.) and (aid.qtest < 0.)) or
                    ((aid.qmax > 0.) and (aid.qtest > 0.))):
                aid.qmin *= aid.qmax/(aid.qmax+aid.qtest)
            else:
                aid.hmin = aid.hmax
                aid.qmin = aid.qmax
            aid.hmax = flu.h
            aid.qmax = aid.qtest
            if modelutils.fabs(aid.hmax-aid.hmin) < con.htol:
                return


Instruction:
Implement a Python 3 function for
calculating the outflow of the linear storage.

Response:
def calc_qa_v1(self):
    """Calculate outflow.

    The working equation is the analytical solution of the linear storage
    equation under the assumption of constant change in inflow during
    the simulation time step.

    Required flux sequence:
      |RK|

    Required state sequence:
      |QZ|

    Updated state sequence:
      |QA|

    Basic equation:
       :math:`QA_{neu} = QA_{alt} +
       (QZ_{alt}-QA_{alt}) \\cdot (1-exp(-RK^{-1})) +
       (QZ_{neu}-QZ_{alt}) \\cdot (1-RK\\cdot(1-exp(-RK^{-1})))`

    Examples:

        A normal test case:

        >>> from hydpy.models.lstream import *
        >>> parameterstep()
        >>> fluxes.rk(0.1)
        >>> states.qz.old = 2.0
        >>> states.qz.new = 4.0
        >>> states.qa.old = 3.0
        >>> model.calc_qa_v1()
        >>> states.qa
        qa(3.800054)

        First extreme test case (zero division is circumvented):

        >>> fluxes.rk(0.0)
        >>> model.calc_qa_v1()
        >>> states.qa
        qa(4.0)

        Second extreme test case (numerical overflow is circumvented):

        >>> fluxes.rk(1e201)
        >>> model.calc_qa_v1()
        >>> states.qa
        qa(5.0)
    """
    flu = self.sequences.fluxes.fastaccess
    old = self.sequences.states.fastaccess_old
    new = self.sequences.states.fastaccess_new
    aid = self.sequences.aides.fastaccess
    if flu.rk <= 0.:
        new.qa = new.qz
    elif flu.rk > 1e200:
        new.qa = old.qa+new.qz-old.qz
    else:
        aid.temp = (1.-modelutils.exp(-1./flu.rk))
        new.qa = (old.qa +
                  (old.qz-old.qa)*aid.temp +
                  (new.qz-old.qz)*(1.-flu.rk*aid.temp))


Instruction:
How would you explain what the following Python 3 function does
def calc_tc_v1(self):
    con = self.parameters.control.fastaccess
    inp = self.sequences.inputs.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nmbzones):
        flu.tc[k] = inp.t-con.tcalt[k]*(con.zonez[k]-con.zrelt)

Response: Adjust the measured air temperature to the altitude of the individual zones.


Instruction:
Create a Python 3 function to
calculate the areal mean temperature of the subbasin.

Response:
def calc_tmean_v1(self):
    """Calculate the areal mean temperature of the subbasin.

    Required derived parameter:
      |RelZoneArea|

    Required flux sequence:
      |TC|

    Calculated flux sequences:
      |TMean|

    Examples:

        Prepare two zones, the first one being twice as large
        as the second one:

        >>> from hydpy.models.hland import *
        >>> parameterstep('1d')
        >>> nmbzones(2)
        >>> derived.relzonearea(2.0/3.0, 1.0/3.0)

        With temperature values of 5°C and 8°C  of the respective zones,
        the mean temperature is 6°C:

        >>> fluxes.tc = 5.0, 8.0
        >>> model.calc_tmean_v1()
        >>> fluxes.tmean
        tmean(6.0)
    """
    con = self.parameters.control.fastaccess
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    flu.tmean = 0.
    for k in range(con.nmbzones):
        flu.tmean += der.relzonearea[k]*flu.tc[k]


Instruction:
Write a Python 3 function that can
calculate the temperature - dependent fraction of the rainfall and the total precipitation.

Response:
def calc_fracrain_v1(self):
    """Determine the temperature-dependent fraction of (liquid) rainfall
    and (total) precipitation.

    Required control parameters:
      |NmbZones|
      |TT|,
      |TTInt|

    Required flux sequence:
      |TC|

    Calculated flux sequences:
      |FracRain|

    Basic equation:
      :math:`FracRain = \\frac{TC-(TT-\\frac{TTInt}{2})}{TTInt}`

    Restriction:
      :math:`0 \\leq FracRain \\leq 1`

    Examples:

        The threshold temperature of seven zones is 0°C and the corresponding
        temperature interval of mixed precipitation 2°C:

        >>> from hydpy.models.hland import *
        >>> parameterstep('1d')
        >>> nmbzones(7)
        >>> tt(0.0)
        >>> ttint(2.0)

        The fraction of rainfall is zero below -1°C, is one above 1°C and
        increases linearly in between:

        >>> fluxes.tc = -10.0, -1.0, -0.5, 0.0, 0.5, 1.0, 10.0
        >>> model.calc_fracrain_v1()
        >>> fluxes.fracrain
        fracrain(0.0, 0.0, 0.25, 0.5, 0.75, 1.0, 1.0)

        Note the special case of a zero temperature interval.  With a
        actual temperature being equal to the threshold temperature, the
        rainfall fraction is one:

        >>> ttint(0.0)
        >>> model.calc_fracrain_v1()
        >>> fluxes.fracrain
        fracrain(0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0)
    """
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nmbzones):
        if flu.tc[k] >= (con.tt[k]+con.ttint[k]/2.):
            flu.fracrain[k] = 1.
        elif flu.tc[k] <= (con.tt[k]-con.ttint[k]/2.):
            flu.fracrain[k] = 0.
        else:
            flu.fracrain[k] = ((flu.tc[k]-(con.tt[k]-con.ttint[k]/2.)) /
                               con.ttint[k])


Instruction:
Implement a Python 3 function for
calculating the corrected fractions rainfall and snowfall precipitation for a single base - level RAInfall and total - base - Frac - Rain.

Response:
def calc_rfc_sfc_v1(self):
    """Calculate the corrected fractions rainfall/snowfall and total
    precipitation.

    Required control parameters:
      |NmbZones|
      |RfCF|
      |SfCF|

    Calculated flux sequences:
      |RfC|
      |SfC|

    Basic equations:
      :math:`RfC = RfCF \\cdot FracRain` \n
      :math:`SfC = SfCF \\cdot (1 - FracRain)`

    Examples:

        Assume five zones with different temperatures and hence
        different fractions of rainfall and total precipitation:

        >>> from hydpy.models.hland import *
        >>> parameterstep('1d')
        >>> nmbzones(5)
        >>> fluxes.fracrain = 0.0, 0.25, 0.5, 0.75, 1.0

        With no rainfall and no snowfall correction (implied by the
        respective factors being one), the corrected fraction related
        to rainfall is identical with the original fraction and the
        corrected fraction related to snowfall behaves opposite:

        >>> rfcf(1.0)
        >>> sfcf(1.0)
        >>> model.calc_rfc_sfc_v1()
        >>> fluxes.rfc
        rfc(0.0, 0.25, 0.5, 0.75, 1.0)
        >>> fluxes.sfc
        sfc(1.0, 0.75, 0.5, 0.25, 0.0)

        With a negative rainfall correction of 20% and a positive
        snowfall correction of 20 % the corrected fractions are:

        >>> rfcf(0.8)
        >>> sfcf(1.2)
        >>> model.calc_rfc_sfc_v1()
        >>> fluxes.rfc
        rfc(0.0, 0.2, 0.4, 0.6, 0.8)
        >>> fluxes.sfc
        sfc(1.2, 0.9, 0.6, 0.3, 0.0)
    """
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nmbzones):
        flu.rfc[k] = flu.fracrain[k]*con.rfcf[k]
        flu.sfc[k] = (1.-flu.fracrain[k])*con.sfcf[k]


Instruction:
Can you create a Python 3 function that
calculates the precipitation correction factors and adjusts precipitation to the altitude of the individual zones.

Response:
def calc_pc_v1(self):
    """Apply the precipitation correction factors and adjust precipitation
    to the altitude of the individual zones.

    Required control parameters:
      |NmbZones|
      |PCorr|
      |PCAlt|
      |ZoneZ|
      |ZRelP|

    Required input sequence:
      |P|

    Required flux sequences:
      |RfC|
      |SfC|

    Calculated flux sequences:
      |PC|

    Basic equation:
      :math:`PC = P \\cdot PCorr
      \\cdot (1+PCAlt \\cdot (ZoneZ-ZRelP))
      \\cdot (RfC + SfC)`

    Examples:

        Five zones are at an elevation of 200 m.  A precipitation value
        of 5 mm has been measured at a gauge at an elevation of 300 m:

        >>> from hydpy.models.hland import *
        >>> parameterstep('1d')
        >>> nmbzones(5)
        >>> zrelp(2.0)
        >>> zonez(3.0)
        >>> inputs.p = 5.0

        The first four zones illustrate the individual precipitation
        corrections due to the general precipitation correction factor
        (|PCorr|, first zone), the altitude correction factor (|PCAlt|,
        second zone), the rainfall related correction (|RfC|, third zone),
        and the snowfall related correction factor (|SfC|, fourth zone).
        The fifth zone illustrates the interaction between all corrections:

        >>> pcorr(1.3, 1.0, 1.0, 1.0, 1.3)
        >>> pcalt(0.0, 0.1, 0.0, 0.0, 0.1)
        >>> fluxes.rfc = 0.5, 0.5, 0.4, 0.5, 0.4
        >>> fluxes.sfc = 0.5, 0.5, 0.5, 0.7, 0.7
        >>> model.calc_pc_v1()
        >>> fluxes.pc
        pc(6.5, 5.5, 4.5, 6.0, 7.865)

        Usually, one would set zero or positive values for parameter |PCAlt|.
        But it is also allowed to set negative values, in order to reflect
        possible negative relationships between precipitation and altitude.
        To prevent from calculating negative precipitation when too large
        negative values are applied, a truncation is performed:

        >>> pcalt(-1.0)
        >>> model.calc_pc_v1()
        >>> fluxes.pc
        pc(0.0, 0.0, 0.0, 0.0, 0.0)

    """
    con = self.parameters.control.fastaccess
    inp = self.sequences.inputs.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nmbzones):
        flu.pc[k] = inp.p*(1.+con.pcalt[k]*(con.zonez[k]-con.zrelp))
        if flu.pc[k] <= 0.:
            flu.pc[k] = 0.
        else:
            flu.pc[k] *= con.pcorr[k]*(flu.rfc[k]+flu.sfc[k])


Instruction:
Write a Python 3 function for
calculating the potential evaporation to the actual temperature.

Response:
def calc_ep_v1(self):
    """Adjust potential norm evaporation to the actual temperature.

    Required control parameters:
      |NmbZones|
      |ETF|

    Required input sequence:
      |EPN|
      |TN|

    Required flux sequence:
      |TMean|

    Calculated flux sequences:
      |EP|

    Basic equation:
      :math:`EP = EPN \\cdot (1 + ETF \\cdot (TMean - TN))`

    Restriction:
      :math:`0 \\leq EP \\leq 2 \\cdot EPN`

    Examples:

        Assume four zones with different values of the temperature
        related factor for the adjustment of evaporation (the
        negative value of the first zone is not meaningful, but used
        for illustration purporses):

        >>> from hydpy.models.hland import *
        >>> parameterstep('1d')
        >>> nmbzones(4)
        >>> etf(-0.5, 0.0, 0.1, 0.5)
        >>> inputs.tn = 20.0
        >>> inputs.epn = 2.0

        With mean temperature equal to norm temperature, actual
        (uncorrected) evaporation is equal to norm evaporation:

        >>> fluxes.tmean = 20.0
        >>> model.calc_ep_v1()
        >>> fluxes.ep
        ep(2.0, 2.0, 2.0, 2.0)

        With mean temperature 5°C higher than norm temperature, potential
        evaporation is increased by 1 mm for the third zone, which
        possesses a very common adjustment factor.  For the first zone,
        potential evaporation is 0 mm (which is the smallest value
        allowed), and for the fourth zone it is the double value of the
        norm evaporation (which is the largest value allowed):

        >>> fluxes.tmean  = 25.0
        >>> model.calc_ep_v1()
        >>> fluxes.ep
        ep(0.0, 2.0, 3.0, 4.0)
    """
    con = self.parameters.control.fastaccess
    inp = self.sequences.inputs.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nmbzones):
        flu.ep[k] = inp.epn*(1.+con.etf[k]*(flu.tmean-inp.tn))
        flu.ep[k] = min(max(flu.ep[k], 0.), 2.*inp.epn)


Instruction:
Can you tell what is the following Python 3 function doing
def calc_epc_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nmbzones):
        flu.epc[k] = (flu.ep[k]*con.ecorr[k] *
                      (1. - con.ecalt[k]*(con.zonez[k]-con.zrele)))
        if flu.epc[k] <= 0.:
            flu.epc[k] = 0.
        else:
            flu.epc[k] *= modelutils.exp(-con.epf[k]*flu.pc[k])

Response:
Calculates the evaporation correction factors and adjust evaporation
    to the altitude of the individual zones and perform some corrections between those two evaporation terms.


Instruction:
Here you have a function in Python 3, explain what it does
def calc_tf_ic_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nmbzones):
        if con.zonetype[k] in (FIELD, FOREST):
            flu.tf[k] = max(flu.pc[k]-(con.icmax[k]-sta.ic[k]), 0.)
            sta.ic[k] += flu.pc[k]-flu.tf[k]
        else:
            flu.tf[k] = flu.pc[k]
            sta.ic[k] = 0.

Response: Calculates throughfall and update the interception storage with the current state sequence.


Instruction:
Here you have a function in Python 3, explain what it does
def calc_ei_ic_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nmbzones):
        if con.zonetype[k] in (FIELD, FOREST):
            flu.ei[k] = min(flu.epc[k], sta.ic[k])
            sta.ic[k] -= flu.ei[k]
        else:
            flu.ei[k] = 0.
            sta.ic[k] = 0.

Response: Calculates interception evaporation and update the interception term storage accordingly.


Instruction:
Can you generate the documentation for the following Python 3 function
def calc_sp_wc_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nmbzones):
        if con.zonetype[k] != ILAKE:
            if (flu.rfc[k]+flu.sfc[k]) > 0.:
                sta.wc[k] += flu.tf[k]*flu.rfc[k]/(flu.rfc[k]+flu.sfc[k])
                sta.sp[k] += flu.tf[k]*flu.sfc[k]/(flu.rfc[k]+flu.sfc[k])
        else:
            sta.wc[k] = 0.
            sta.sp[k] = 0.

Response: Calculates the throughfall of the snow layer.


Instruction:
Make a summary of the following Python 3 code
def calc_refr_sp_wc_v1(self):
    con = self.parameters.control.fastaccess
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nmbzones):
        if con.zonetype[k] != ILAKE:
            if flu.tc[k] < der.ttm[k]:
                flu.refr[k] = min(con.cfr[k]*con.cfmax[k] *
                                  (der.ttm[k]-flu.tc[k]), sta.wc[k])
                sta.sp[k] += flu.refr[k]
                sta.wc[k] -= flu.refr[k]
            else:
                flu.refr[k] = 0.

        else:
            flu.refr[k] = 0.
            sta.wc[k] = 0.
            sta.sp[k] = 0.

Response: Calculates the refreezing of the water content within the snow layer and update both the snow layer and the water content within the snow layer and the water content within the snow layer.


Instruction:
Explain what the following Python 3 code does
def calc_in_wc_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nmbzones):
        if con.zonetype[k] != ILAKE:
            flu.in_[k] = max(sta.wc[k]-con.whc[k]*sta.sp[k], 0.)
            sta.wc[k] -= flu.in_[k]
        else:
            flu.in_[k] = flu.tf[k]
            sta.wc[k] = 0.

Response: Calculates the actual water release from the snow layer.


Instruction:
Can you generate the documentation for the following Python 3 function
def calc_glmelt_in_v1(self):
    con = self.parameters.control.fastaccess
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nmbzones):
        if ((con.zonetype[k] == GLACIER) and
                (sta.sp[k] <= 0.) and (flu.tc[k] > der.ttm[k])):
            flu.glmelt[k] = con.gmelt[k]*(flu.tc[k]-der.ttm[k])
            flu.in_[k] += flu.glmelt[k]
        else:
            flu.glmelt[k] = 0.

Response: Calculates the melting from glaciers which are actually not covered by a snow layer and adds it to the water release of the snow module.


Instruction:
Create a Python 3 function for
calculating the effective precipitation and update soil moisture.

Response:
def calc_r_sm_v1(self):
    """Calculate effective precipitation and update soil moisture.

    Required control parameters:
      |NmbZones|
      |ZoneType|
      |FC|
      |Beta|

    Required fluxes sequence:
      |In_|

    Calculated flux sequence:
      |R|

    Updated state sequence:
      |SM|

    Basic equations:
      :math:`\\frac{dSM}{dt} = IN - R` \n
      :math:`R = IN \\cdot \\left(\\frac{SM}{FC}\\right)^{Beta}`

    Examples:

        Initialize six zones of different types.  The field
        capacity of all fields and forests is set to 200mm, the input
        of each zone is 10mm:

        >>> from hydpy.models.hland import *
        >>> parameterstep('1d')
        >>> nmbzones(6)
        >>> zonetype(ILAKE, GLACIER, FIELD, FOREST, FIELD, FIELD)
        >>> fc(200.0)
        >>> fluxes.in_ = 10.0

        With a common nonlinearity parameter value of 2, a relative
        soil moisture of 50%  (zones three and four) results in a
        discharge coefficient of 25%. For a soil completely dried
        (zone five) or completely saturated (one six) the discharge
        coefficient does not depend on the nonlinearity parameter and
        is 0% and 100% respectively.  Glaciers and internal lakes also
        always route 100% of their input as effective precipitation:

        >>> beta(2.0)
        >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0
        >>> model.calc_r_sm_v1()
        >>> fluxes.r
        r(10.0, 10.0, 2.5, 2.5, 0.0, 10.0)
        >>> states.sm
        sm(0.0, 0.0, 107.5, 107.5, 10.0, 200.0)

        Through decreasing the nonlinearity parameter, the discharge
        coefficient increases.  A parameter value of zero leads to a
        discharge coefficient of 100% for any soil moisture:

        >>> beta(0.0)
        >>> states.sm = 0.0, 0.0, 100.0, 100.0, 0.0, 200.0
        >>> model.calc_r_sm_v1()
        >>> fluxes.r
        r(10.0, 10.0, 10.0, 10.0, 10.0, 10.0)
        >>> states.sm
        sm(0.0, 0.0, 100.0, 100.0, 0.0, 200.0)

        With zero field capacity, the discharge coefficient also always
        equates to 100%:

        >>> fc(0.0)
        >>> beta(2.0)
        >>> states.sm = 0.0
        >>> model.calc_r_sm_v1()
        >>> fluxes.r
        r(10.0, 10.0, 10.0, 10.0, 10.0, 10.0)
        >>> states.sm
        sm(0.0, 0.0, 0.0, 0.0, 0.0, 0.0)
    """
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nmbzones):
        if con.zonetype[k] in (FIELD, FOREST):
            if con.fc[k] > 0.:
                flu.r[k] = flu.in_[k]*(sta.sm[k]/con.fc[k])**con.beta[k]
                flu.r[k] = max(flu.r[k], sta.sm[k]+flu.in_[k]-con.fc[k])
            else:
                flu.r[k] = flu.in_[k]
            sta.sm[k] += flu.in_[k]-flu.r[k]
        else:
            flu.r[k] = flu.in_[k]
            sta.sm[k] = 0.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def calc_cf_sm_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nmbzones):
        if con.zonetype[k] in (FIELD, FOREST):
            if con.fc[k] > 0.:
                flu.cf[k] = con.cflux[k]*(1.-sta.sm[k]/con.fc[k])
                flu.cf[k] = min(flu.cf[k], sta.uz+flu.r[k])
                flu.cf[k] = min(flu.cf[k], con.fc[k]-sta.sm[k])
            else:
                flu.cf[k] = 0.
            sta.sm[k] += flu.cf[k]
        else:
            flu.cf[k] = 0.
            sta.sm[k] = 0.

Response: Calculates the capillary flow and update soil moisture for a single field and forest.