Instruction:
Here you have a function in Python 3, explain what it does
def next_time_open(location):
    if not is_open(location):
        now = get_now()
        now_time = datetime.time(now.hour, now.minute, now.second)
        found_opening_hours = False
        for i in range(8):
            l_weekday = (now.isoweekday() + i) % 7
            ohs = OpeningHours.objects.filter(company=location,
                                              weekday=l_weekday
                                              ).order_by('weekday',
                                                         'from_hour')

            if ohs.count():
                for oh in ohs:
                    future_now = now + datetime.timedelta(days=i)
                    # same day issue
                    tmp_now = datetime.datetime(future_now.year,
                                                future_now.month,
                                                future_now.day,
                                                oh.from_hour.hour,
                                                oh.from_hour.minute,
                                                oh.from_hour.second)
                    if tmp_now < now:
                        tmp_now = now  # be sure to set the bound correctly...
                    if is_open(location, now=tmp_now):
                        found_opening_hours = oh
                        break
                if found_opening_hours is not False:
                    return found_opening_hours, tmp_now
    return False, None

Response: Returns the next possible opening hours object for the given company location.


Instruction:
Here you have a function in Python 3, explain what it does
def refweights(self):
        # pylint: disable=unsubscriptable-object
        # due to a pylint bug (see https://github.com/PyCQA/pylint/issues/870)
        return numpy.full(self.shape, 1./self.shape[0], dtype=float)

Response:
A |numpy| |numpy. ndarray| with equal weights for all segment
        junctions..


Instruction:
How would you implement a function in Python 3 that
adds a directory and optionally its path.

Response:
def add(self, directory, path=None) -> None:
        """Add a directory and optionally its path."""
        objecttools.valid_variable_identifier(directory)
        if path is None:
            path = directory
        setattr(self, directory, path)


Instruction:
Explain what the following Python 3 code does
def basepath(self) -> str:
        return os.path.abspath(
            os.path.join(self.projectdir, self.BASEDIR))

Response: Absolute path pointing to the available working directories.


Instruction:
How would you explain what the following Python 3 function does
def availabledirs(self) -> Folder2Path:
        directories = Folder2Path()
        for directory in os.listdir(self.basepath):
            if not directory.startswith('_'):
                path = os.path.join(self.basepath, directory)
                if os.path.isdir(path):
                    directories.add(directory, path)
                elif directory.endswith('.zip'):
                    directories.add(directory[:-4], path)
        return directories

Response: Returns a Folder2Path object containing the names and paths of the available working directories.


Instruction:
Here you have a function in Python 3, explain what it does
def currentdir(self) -> str:
        if self._currentdir is None:
            directories = self.availabledirs.folders
            if len(directories) == 1:
                self.currentdir = directories[0]
            elif self.DEFAULTDIR in directories:
                self.currentdir = self.DEFAULTDIR
            else:
                prefix = (f'The current working directory of the '
                          f'{objecttools.classname(self)} object '
                          f'has not been defined manually and cannot '
                          f'be determined automatically:')
                if not directories:
                    raise RuntimeError(
                        f'{prefix} `{objecttools.repr_(self.basepath)}` '
                        f'does not contain any available directories.')
                if self.DEFAULTDIR is None:
                    raise RuntimeError(
                        f'{prefix} `{objecttools.repr_(self.basepath)}` '
                        f'does contain multiple available directories '
                        f'({objecttools.enumeration(directories)}).')
                raise RuntimeError(
                    f'{prefix} The default directory ({self.DEFAULTDIR}) '
                    f'is not among the available directories '
                    f'({objecttools.enumeration(directories)}).')
        return self._currentdir

Response: Return the name of the current working directory of the file manager object.


Instruction:
Write a Python 3 function that can
return a list of the filenames contained in the current working directory.

Response:
def filenames(self) -> List[str]:
        """Names of the files contained in the the current working directory.

        Files names starting with underscores are ignored:

        >>> from hydpy.core.filetools import FileManager
        >>> filemanager = FileManager()
        >>> filemanager.BASEDIR = 'basename'
        >>> filemanager.projectdir = 'projectname'
        >>> from hydpy import TestIO
        >>> with TestIO():
        ...     filemanager.currentdir = 'testdir'
        ...     open('projectname/basename/testdir/file1.txt', 'w').close()
        ...     open('projectname/basename/testdir/file2.npy', 'w').close()
        ...     open('projectname/basename/testdir/_file1.nc', 'w').close()
        ...     filemanager.filenames
        ['file1.txt', 'file2.npy']
        """
        return sorted(
            fn for fn in os.listdir(self.currentpath)
            if not fn.startswith('_'))


Instruction:
Given the following Python 3 function, write the documentation
def filepaths(self) -> List[str]:
        path = self.currentpath
        return [os.path.join(path, name) for name in self.filenames]

Response:
Absolute path names of the files contained in the current
        working directory.


Instruction:
Can you tell what is the following Python 3 function doing
def zip_currentdir(self) -> None:
        with zipfile.ZipFile(f'{self.currentpath}.zip', 'w') as zipfile_:
            for filepath, filename in zip(self.filepaths, self.filenames):
                zipfile_.write(filename=filepath, arcname=filename)
        del self.currentdir

Response: Pack the current working directory in a zip file.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def load_files(self) -> selectiontools.Selections:
        devicetools.Node.clear_all()
        devicetools.Element.clear_all()
        selections = selectiontools.Selections()
        for (filename, path) in zip(self.filenames, self.filepaths):
            # Ensure both `Node` and `Element`start with a `fresh` memory.
            devicetools.Node.extract_new()
            devicetools.Element.extract_new()
            try:
                info = runpy.run_path(path)
            except BaseException:
                objecttools.augment_excmessage(
                    f'While trying to load the network file `{path}`')
            try:
                node: devicetools.Node = info['Node']
                element: devicetools.Element = info['Element']
                selections += selectiontools.Selection(
                    filename.split('.')[0],
                    node.extract_new(),
                    element.extract_new())
            except KeyError as exc:
                raise RuntimeError(
                    f'The class {exc.args[0]} cannot be loaded from the '
                    f'network file `{path}`.')

        selections += selectiontools.Selection(
            'complete',
            info['Node'].query_all(),
            info['Element'].query_all())
        return selections

Response: Load all network files of the current working directory and return a |selectiontools. Selection| object.


Instruction:
Implement a function in Python 3 to
save the |Selections| objects contained in the given |Selections| instance to separate network files.

Response:
def save_files(self, selections) -> None:
        """Save the |Selection| objects contained in the given |Selections|
        instance to separate network files."""
        try:
            currentpath = self.currentpath
            selections = selectiontools.Selections(selections)
            for selection in selections:
                if selection.name == 'complete':
                    continue
                path = os.path.join(currentpath, selection.name+'.py')
                selection.save_networkfile(filepath=path)
        except BaseException:
            objecttools.augment_excmessage(
                'While trying to save selections `%s` into network files'
                % selections)


Instruction:
Write a Python 3 script for
deleting the files corresponding to the given selections.

Response:
def delete_files(self, selections) -> None:
        """Delete the network files corresponding to the given selections
        (e.g. a |list| of |str| objects or a |Selections| object)."""
        try:
            currentpath = self.currentpath
            for selection in selections:
                name = str(selection)
                if name == 'complete':
                    continue
                if not name.endswith('.py'):
                    name += '.py'
                path = os.path.join(currentpath, name)
                os.remove(path)
        except BaseException:
            objecttools.augment_excmessage(
                f'While trying to remove the network files of '
                f'selections `{selections}`')


Instruction:
Can you implement a function in Python 3 that
loads the given file into the internal registry.

Response:
def load_file(self, element=None, filename=None, clear_registry=True):
        """Return the namespace of the given file (and eventually of its
        corresponding auxiliary subfiles) as a |dict|.

        By default, the internal registry is cleared when a control file and
        all its corresponding auxiliary files have been loaded.  You can
        change this behaviour by passing `False` for the `clear_registry`
        argument.  This might decrease model initialization times
        significantly.  But then it is your own responsibility to call
        method |ControlManager.clear_registry| when necessary (before
        reloading a changed control file).
        """
        if not filename:
            filename = element.name
        type(self)._workingpath = self.currentpath
        info = {}
        if element:
            info['element'] = element
        try:
            self.read2dict(filename, info)
        finally:
            type(self)._workingpath = '.'
            if clear_registry:
                self._registry.clear()
        return info


Instruction:
Here you have a function in Python 3, explain what it does
def read2dict(cls, filename, info):
        if not filename.endswith('.py'):
            filename += '.py'
        path = os.path.join(cls._workingpath, filename)
        try:
            if path not in cls._registry:
                with open(path) as file_:
                    cls._registry[path] = file_.read()
            exec(cls._registry[path], {}, info)
        except BaseException:
            objecttools.augment_excmessage(
                'While trying to load the control file `%s`'
                % path)
        if 'model' not in info:
            raise IOError(
                'Model parameters cannot be loaded from control file `%s`.  '
                'Please refer to the HydPy documentation on how to prepare '
                'control files properly.'
                % path)

Response: Read the control parameters from the given file and store them in the given |dict| object info.


Instruction:
How would you implement a function in Python 3 that
saves the given text under the given control filename and the the current path.

Response:
def save_file(self, filename, text):
        """Save the given text under the given control filename and the
        current path."""
        if not filename.endswith('.py'):
            filename += '.py'
        path = os.path.join(self.currentpath, filename)
        with open(path, 'w', encoding="utf-8") as file_:
            file_.write(text)


Instruction:
Explain what the following Python 3 code does
def load_file(self, filename):
        _defaultdir = self.DEFAULTDIR
        try:
            if not filename.endswith('.py'):
                filename += '.py'
            try:
                self.DEFAULTDIR = (
                    'init_' + hydpy.pub.timegrids.sim.firstdate.to_string('os'))
            except KeyError:
                pass
            filepath = os.path.join(self.currentpath, filename)
            with open(filepath) as file_:
                return file_.read()
        except BaseException:
            objecttools.augment_excmessage(
                'While trying to read the conditions file `%s`'
                % filename)
        finally:
            self.DEFAULTDIR = _defaultdir

Response: Read and return the content of the given file.


Instruction:
Can you tell what is the following Python 3 function doing
def save_file(self, filename, text):
        _defaultdir = self.DEFAULTDIR
        try:
            if not filename.endswith('.py'):
                filename += '.py'
            try:
                self.DEFAULTDIR = (
                    'init_' + hydpy.pub.timegrids.sim.lastdate.to_string('os'))
            except AttributeError:
                pass
            path = os.path.join(self.currentpath, filename)
            with open(path, 'w', encoding="utf-8") as file_:
                file_.write(text)
        except BaseException:
            objecttools.augment_excmessage(
                'While trying to write the conditions file `%s`'
                % filename)
        finally:
            self.DEFAULTDIR = _defaultdir

Response: Save the given text under the given filename and the current path.


Instruction:
Write a Python 3 function for
loading data from an external data file an pass it to the given |IOSequence|.

Response:
def load_file(self, sequence):
        """Load data from an "external" data file an pass it to
        the given |IOSequence|."""
        try:
            if sequence.filetype_ext == 'npy':
                sequence.series = sequence.adjust_series(
                    *self._load_npy(sequence))
            elif sequence.filetype_ext == 'asc':
                sequence.series = sequence.adjust_series(
                    *self._load_asc(sequence))
            elif sequence.filetype_ext == 'nc':
                self._load_nc(sequence)
        except BaseException:
            objecttools.augment_excmessage(
                'While trying to load the external data of sequence %s'
                % objecttools.devicephrase(sequence))


Instruction:
Explain what the following Python 3 code does
def save_file(self, sequence, array=None):
        if array is None:
            array = sequence.aggregate_series()
        try:
            if sequence.filetype_ext == 'nc':
                self._save_nc(sequence, array)
            else:
                filepath = sequence.filepath_ext
                if ((array is not None) and
                        (array.info['type'] != 'unmodified')):
                    filepath = (f'{filepath[:-4]}_{array.info["type"]}'
                                f'{filepath[-4:]}')
                if not sequence.overwrite_ext and os.path.exists(filepath):
                    raise OSError(
                        f'Sequence {objecttools.devicephrase(sequence)} '
                        f'is not allowed to overwrite the existing file '
                        f'`{sequence.filepath_ext}`.')
                if sequence.filetype_ext == 'npy':
                    self._save_npy(array, filepath)
                elif sequence.filetype_ext == 'asc':
                    self._save_asc(array, filepath)
        except BaseException:
            objecttools.augment_excmessage(
                'While trying to save the external data of sequence %s'
                % objecttools.devicephrase(sequence))

Response: Write the date stored in |IOSequence. series| into an external data file.


Instruction:
How would you code a function in Python 3 to
prepare a new |NetCDFInterface| object for reading data.

Response:
def open_netcdf_reader(self, flatten=False, isolate=False, timeaxis=1):
        """Prepare a new |NetCDFInterface| object for reading data."""
        self._netcdf_reader = netcdftools.NetCDFInterface(
            flatten=bool(flatten),
            isolate=bool(isolate),
            timeaxis=int(timeaxis))


Instruction:
Can you implement a function in Python 3 that
opens a new |NetCDFInterface| object for writing data.

Response:
def open_netcdf_writer(self, flatten=False, isolate=False, timeaxis=1):
        """Prepare a new |NetCDFInterface| object for writing data."""
        self._netcdf_writer = netcdftools.NetCDFInterface(
            flatten=bool(flatten),
            isolate=bool(isolate),
            timeaxis=int(timeaxis))


Instruction:
Can you tell what is the following Python 3 function doing
def calc_nkor_v1(self):
    con = self.parameters.control.fastaccess
    inp = self.sequences.inputs.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nhru):
        flu.nkor[k] = con.kg[k] * inp.nied

Response: Adjust the precipitation values of the next non - zero precipitation.


Instruction:
Can you write a function in Python 3 where it
adjusts the given air temperature values.

Response:
def calc_tkor_v1(self):
    """Adjust the given air temperature values.

    Required control parameters:
      |NHRU|
      |KT|

    Required input sequence:
      |TemL|

    Calculated flux sequence:
      |TKor|

    Basic equation:
      :math:`TKor = KT + TemL`

    Example:

        >>> from hydpy.models.lland import *
        >>> parameterstep('1d')
        >>> nhru(3)
        >>> kt(-2.0, 0.0, 2.0)
        >>> inputs.teml(1.)
        >>> model.calc_tkor_v1()
        >>> fluxes.tkor
        tkor(-1.0, 1.0, 3.0)
    """
    con = self.parameters.control.fastaccess
    inp = self.sequences.inputs.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nhru):
        flu.tkor[k] = con.kt[k] + inp.teml


Instruction:
Can you create a Python 3 function that
calculates the reference evapotranspiration after Turc - Wendling.

Response:
def calc_et0_v1(self):
    """Calculate reference evapotranspiration after Turc-Wendling.

    Required control parameters:
      |NHRU|
      |KE|
      |KF|
      |HNN|

    Required input sequence:
      |Glob|

    Required flux sequence:
      |TKor|

    Calculated flux sequence:
      |ET0|

    Basic equation:
      :math:`ET0 = KE \\cdot
      \\frac{(8.64 \\cdot Glob+93 \\cdot KF) \\cdot (TKor+22)}
      {165 \\cdot (TKor+123) \\cdot (1 + 0.00019 \\cdot min(HNN, 600))}`

    Example:

        >>> from hydpy.models.lland import *
        >>> parameterstep('1d')
        >>> simulationstep('12h')
        >>> nhru(3)
        >>> ke(1.1)
        >>> kf(0.6)
        >>> hnn(200.0, 600.0, 1000.0)
        >>> inputs.glob = 200.0
        >>> fluxes.tkor = 15.0
        >>> model.calc_et0_v1()
        >>> fluxes.et0
        et0(3.07171, 2.86215, 2.86215)
    """
    con = self.parameters.control.fastaccess
    inp = self.sequences.inputs.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nhru):
        flu.et0[k] = (con.ke[k]*(((8.64*inp.glob+93.*con.kf[k]) *
                                  (flu.tkor[k]+22.)) /
                                 (165.*(flu.tkor[k]+123.) *
                                  (1.+0.00019*min(con.hnn[k], 600.)))))


Instruction:
Write a Python 3 function that can
correct the given reference evapotranspiration and update the corresponding log sequence.

Response:
def calc_et0_wet0_v1(self):
    """Correct the given reference evapotranspiration and update the
    corresponding log sequence.

    Required control parameters:
      |NHRU|
      |KE|
      |WfET0|

    Required input sequence:
      |PET|

    Calculated flux sequence:
      |ET0|

    Updated log sequence:
      |WET0|

    Basic equations:
      :math:`ET0_{new} = WfET0 \\cdot KE \\cdot PET +
      (1-WfET0) \\cdot ET0_{alt}`

    Example:

        Prepare four hydrological response units with different value
        combinations of parameters |KE| and |WfET0|:

        >>> from hydpy.models.lland import *
        >>> parameterstep('1d')
        >>> simulationstep('12h')
        >>> nhru(4)
        >>> ke(0.8, 1.2, 0.8, 1.2)
        >>> wfet0(2.0, 2.0, 0.2, 0.2)

        Note that the actual value of time dependend parameter |WfET0|
        is reduced due the difference between the given parameter and
        simulation time steps:

        >>> from hydpy import round_
        >>> round_(wfet0.values)
        1.0, 1.0, 0.1, 0.1

        For the first two hydrological response units, the given |PET|
        value is modified by -0.4 mm and +0.4 mm, respectively.  For the
        other two response units, which weight the "new" evaporation
        value with 10 %, |ET0| does deviate from the old value of |WET0|
        by -0.04 mm and +0.04 mm only:

        >>> inputs.pet = 2.0
        >>> logs.wet0 = 2.0
        >>> model.calc_et0_wet0_v1()
        >>> fluxes.et0
        et0(1.6, 2.4, 1.96, 2.04)
        >>> logs.wet0
        wet0([[1.6, 2.4, 1.96, 2.04]])
    """
    con = self.parameters.control.fastaccess
    inp = self.sequences.inputs.fastaccess
    flu = self.sequences.fluxes.fastaccess
    log = self.sequences.logs.fastaccess
    for k in range(con.nhru):
        flu.et0[k] = (con.wfet0[k]*con.ke[k]*inp.pet +
                      (1.-con.wfet0[k])*log.wet0[0, k])
        log.wet0[0, k] = flu.et0[k]


Instruction:
Implement a function in Python 3 to
calculate the stand precipitation and update the interception storage with the new state sequence.

Response:
def calc_nbes_inzp_v1(self):
    """Calculate stand precipitation and update the interception storage
    accordingly.

    Required control parameters:
      |NHRU|
      |Lnk|

    Required derived parameter:
      |KInz|

    Required flux sequence:
      |NKor|

    Calculated flux sequence:
      |NBes|

    Updated state sequence:
      |Inzp|

    Additional requirements:
      |Model.idx_sim|

    Basic equation:
      :math:`NBes = \\Bigl \\lbrace
      {
      {PKor \\ | \\ Inzp = KInz}
      \\atop
      {0 \\ | \\ Inzp < KInz}
      }`

    Examples:

        Initialize five HRUs with different land usages:

        >>> from hydpy.models.lland import *
        >>> parameterstep('1d')
        >>> nhru(5)
        >>> lnk(SIED_D, FEUCHT, GLETS, FLUSS, SEE)

        Define |KInz| values for July the selected land usages directly:

        >>> derived.kinz.sied_d_jul = 2.0
        >>> derived.kinz.feucht_jul = 1.0
        >>> derived.kinz.glets_jul = 0.0
        >>> derived.kinz.fluss_jul = 1.0
        >>> derived.kinz.see_jul = 1.0

        Now we prepare a |MOY| object, that assumes that the first, second,
        and third simulation time steps are in June, July, and August
        respectively (we make use of the value defined above for July, but
        setting the values of parameter |MOY| this way allows for a more
        rigorous testing of proper indexing):

        >>> derived.moy.shape = 3
        >>> derived.moy = 5, 6, 7
        >>> model.idx_sim = 1

        The dense settlement (|SIED_D|), the wetland area (|FEUCHT|), and
        both water areas (|FLUSS| and |SEE|) start with a initial interception
        storage of 1/2 mm, the glacier (|GLETS|) and water areas (|FLUSS| and
        |SEE|) start with 0 mm.  In the first example, actual precipition
        is 1 mm:

        >>> states.inzp = 0.5, 0.5, 0.0, 1.0, 1.0
        >>> fluxes.nkor = 1.0
        >>> model.calc_nbes_inzp_v1()
        >>> states.inzp
        inzp(1.5, 1.0, 0.0, 0.0, 0.0)
        >>> fluxes.nbes
        nbes(0.0, 0.5, 1.0, 0.0, 0.0)

        Only for the settled area, interception capacity is not exceeded,
        meaning no stand precipitation occurs.  Note that it is common in
        define zero interception capacities for glacier areas, but not
        mandatory.  Also note that the |KInz|, |Inzp| and |NKor| values
        given for both water areas are ignored completely, and |Inzp|
        and |NBes| are simply set to zero.

        If there is no precipitation, there is of course also no stand
        precipitation and interception storage remains unchanged:

        >>> states.inzp = 0.5, 0.5, 0.0, 0.0, 0.0
        >>> fluxes.nkor = 0.
        >>> model.calc_nbes_inzp_v1()
        >>> states.inzp
        inzp(0.5, 0.5, 0.0, 0.0, 0.0)
        >>> fluxes.nbes
        nbes(0.0, 0.0, 0.0, 0.0, 0.0)

        Interception capacities change discontinuously between consecutive
        months.  This can result in little stand precipitation events in
        periods without precipitation:

        >>> states.inzp = 1.0, 0.0, 0.0, 0.0, 0.0
        >>> derived.kinz.sied_d_jul = 0.6
        >>> fluxes.nkor = 0.0
        >>> model.calc_nbes_inzp_v1()
        >>> states.inzp
        inzp(0.6, 0.0, 0.0, 0.0, 0.0)
        >>> fluxes.nbes
        nbes(0.4, 0.0, 0.0, 0.0, 0.0)
    """
    con = self.parameters.control.fastaccess
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nhru):
        if con.lnk[k] in (WASSER, FLUSS, SEE):
            flu.nbes[k] = 0.
            sta.inzp[k] = 0.
        else:
            flu.nbes[k] = \
                max(flu.nkor[k]+sta.inzp[k] -
                    der.kinz[con.lnk[k]-1, der.moy[self.idx_sim]], 0.)
            sta.inzp[k] += flu.nkor[k]-flu.nbes[k]


Instruction:
Make a summary of the following Python 3 code
def calc_evi_inzp_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nhru):
        if con.lnk[k] in (WASSER, FLUSS, SEE):
            flu.evi[k] = flu.evpo[k]
            sta.inzp[k] = 0.
        else:
            flu.evi[k] = min(flu.evpo[k], sta.inzp[k])
            sta.inzp[k] -= flu.evi[k]

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


Instruction:
Write a Python 3 function that can
calculate the frozen part of stand precipitation.

Response:
def calc_sbes_v1(self):
    """Calculate the frozen part of stand precipitation.

    Required control parameters:
      |NHRU|
      |TGr|
      |TSp|

    Required flux sequences:
      |TKor|
      |NBes|

    Calculated flux sequence:
      |SBes|

    Examples:

        In the first example, the threshold temperature of seven hydrological
        response units is 0 °C and the corresponding temperature interval of
        mixed precipitation 2 °C:

        >>> from hydpy.models.lland import *
        >>> parameterstep('1d')
        >>> nhru(7)
        >>> tgr(0.0)
        >>> tsp(2.0)

        The value of |NBes| is zero above 1 °C and equal to the value of
        |NBes| below -1 °C.  Between these temperature values, |NBes|
        decreases linearly:

        >>> fluxes.nbes = 4.0
        >>> fluxes.tkor = -10.0, -1.0, -0.5, 0.0, 0.5, 1.0, 10.0
        >>> model.calc_sbes_v1()
        >>> fluxes.sbes
        sbes(4.0, 4.0, 3.0, 2.0, 1.0, 0.0, 0.0)

        Note the special case of a zero temperature interval.  With the
        actual temperature being equal to the threshold temperature, the
        the value of `sbes` is zero:

        >>> tsp(0.)
        >>> model.calc_sbes_v1()
        >>> fluxes.sbes
        sbes(4.0, 4.0, 4.0, 0.0, 0.0, 0.0, 0.0)
    """
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nhru):
        if flu.nbes[k] <= 0.:
            flu.sbes[k] = 0.
        elif flu.tkor[k] >= (con.tgr[k]+con.tsp[k]/2.):
            flu.sbes[k] = 0.
        elif flu.tkor[k] <= (con.tgr[k]-con.tsp[k]/2.):
            flu.sbes[k] = flu.nbes[k]
        else:
            flu.sbes[k] = ((((con.tgr[k]+con.tsp[k]/2.)-flu.tkor[k]) /
                            con.tsp[k])*flu.nbes[k])


Instruction:
Make a summary of the following Python 3 code
def calc_wgtf_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for k in range(con.nhru):
        if con.lnk[k] in (WASSER, FLUSS, SEE):
            flu.wgtf[k] = 0.
        else:
            flu.wgtf[k] = (
                max(con.gtf[k]*(flu.tkor[k]-con.treft[k]), 0) +
                max(con.cpwasser/con.rschmelz*(flu.tkor[k]-con.trefn[k]), 0.))

Response: Calculates the potential snowmelt.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def calc_schm_wats_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nhru):
        if con.lnk[k] in (WASSER, FLUSS, SEE):
            sta.wats[k] = 0.
            flu.schm[k] = 0.
        else:
            sta.wats[k] += flu.sbes[k]
            flu.schm[k] = min(flu.wgtf[k], sta.wats[k])
            sta.wats[k] -= flu.schm[k]

Response: Calculates the actual amount of water melting within the snow cover.


Instruction:
Write a Python 3 script for
calculating the actual water release from the snow cover.

Response:
def calc_wada_waes_v1(self):
    """Calculate the actual water release from the snow cover.

    Required control parameters:
      |NHRU|
      |Lnk|
      |PWMax|

    Required flux sequences:
      |NBes|

    Calculated flux sequence:
      |WaDa|

    Updated state sequence:
      |WAeS|

    Basic equations:
      :math:`\\frac{dWAeS}{dt} = NBes - WaDa`
      :math:`WAeS \\leq PWMax \\cdot WATS`

    Examples:

        For simplicity, the threshold parameter |PWMax| is set to a value
        of two for each of the six initialized HRUs.  Thus, snow cover can
        hold as much liquid water as it contains frozen water.  Stand
        precipitation is also always set to the same value, but the initial
        conditions of the snow cover are varied:

        >>> from hydpy.models.lland import *
        >>> parameterstep('1d')
        >>> nhru(6)
        >>> lnk(FLUSS, SEE, ACKER, ACKER, ACKER, ACKER)
        >>> pwmax(2.0)
        >>> fluxes.nbes = 1.0
        >>> states.wats = 0.0, 0.0, 0.0, 1.0, 1.0, 1.0
        >>> states.waes = 1.0, 1.0, 0.0, 1.0, 1.5, 2.0
        >>> model.calc_wada_waes_v1()
        >>> states.waes
        waes(0.0, 0.0, 0.0, 2.0, 2.0, 2.0)
        >>> fluxes.wada
        wada(1.0, 1.0, 1.0, 0.0, 0.5, 1.0)

        Note the special cases of the first two HRUs of type |FLUSS| and
        |SEE|.  For water areas, stand precipitaton |NBes| is generally
        passed to |WaDa| and |WAeS| is set to zero.  For all other land
        use classes (of which only |ACKER| is selected), only the amount
        of |NBes| exceeding the actual snow holding capacity is passed
        to |WaDa|.
    """
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nhru):
        if con.lnk[k] in (WASSER, FLUSS, SEE):
            sta.waes[k] = 0.
            flu.wada[k] = flu.nbes[k]
        else:
            sta.waes[k] += flu.nbes[k]
            flu.wada[k] = max(sta.waes[k]-con.pwmax[k]*sta.wats[k], 0.)
            sta.waes[k] -= flu.wada[k]


Instruction:
Given the following Python 3 function, write the documentation
def calc_evb_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    for k in range(con.nhru):
        if (con.lnk[k] in (VERS, WASSER, FLUSS, SEE)) or (con.nfk[k] <= 0.):
            flu.evb[k] = 0.
        else:
            d_temp = modelutils.exp(-con.grasref_r *
                                    sta.bowa[k]/con.nfk[k])
            flu.evb[k] = ((flu.evpo[k]-flu.evi[k]) * (1.-d_temp) /
                          (1.+d_temp-2.*modelutils.exp(-con.grasref_r)))

Response: Calculates the actual evaporation from the snow cover.


Instruction:
How would you explain what the following Python 3 function does
def calc_qbb_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.nhru):
        if ((con.lnk[k] in (VERS, WASSER, FLUSS, SEE)) or
                (sta.bowa[k] <= der.wb[k]) or (con.nfk[k] <= 0.)):
            flu.qbb[k] = 0.
        elif sta.bowa[k] <= der.wz[k]:
            flu.qbb[k] = con.beta[k]*(sta.bowa[k]-der.wb[k])
        else:
            flu.qbb[k] = (con.beta[k]*(sta.bowa[k]-der.wb[k]) *
                          (1.+(con.fbeta[k]-1.)*((sta.bowa[k]-der.wz[k]) /
                                                 (con.nfk[k]-der.wz[k]))))

Response: Calculates the amount of base flow released from the soil.


Instruction:
Implement a function in Python 3 to
calculate the first inflow component released from the soil.

Response:
def calc_qib1_v1(self):
    """Calculate the first inflow component released from the soil.

    Required control parameters:
      |NHRU|
      |Lnk|
      |NFk|
      |DMin|

    Required derived parameter:
      |WB|

    Required state sequence:
      |BoWa|

    Calculated flux sequence:
      |QIB1|

    Basic equation:
      :math:`QIB1 = DMin \\cdot \\frac{BoWa}{NFk}`

    Examples:

        For water and sealed areas, no interflow is calculated (the first
        three HRUs are of type |FLUSS|, |SEE|, and |VERS|, respectively).
        No principal distinction is made between the remaining land use
        classes (arable land |ACKER| has been selected for the last five
        HRUs arbitrarily):

        >>> from hydpy.models.lland import *
        >>> parameterstep('1d')
        >>> simulationstep('12h')
        >>> nhru(8)
        >>> lnk(FLUSS, SEE, VERS, ACKER, ACKER, ACKER, ACKER, ACKER)
        >>> dmax(10.0)
        >>> dmin(4.0)
        >>> nfk(101.0, 101.0, 101.0, 0.0, 101.0, 101.0, 101.0, 202.0)
        >>> derived.wb(10.0)
        >>> states.bowa = 10.1, 10.1, 10.1, 0.0, 0.0, 10.0, 10.1, 10.1

        Note the time dependence of parameter |DMin|:

        >>> dmin
        dmin(4.0)
        >>> dmin.values
        array([ 2.,  2.,  2.,  2.,  2.,  2.,  2.,  2.])

        Compared to the calculation of |QBB|, the following results show
        some relevant differences:

        >>> model.calc_qib1_v1()
        >>> fluxes.qib1
        qib1(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 0.1)

        Firstly, as demonstrated with the help of the seventh and the
        eight HRU, the generation of the first interflow component |QIB1|
        depends on relative soil moisture.  Secondly, as demonstrated with
        the help the sixth and seventh HRU, it starts abruptly whenever
        the slightest exceedance of the threshold  parameter |WB| occurs.
        Such sharp discontinuouties are a potential source of trouble.
    """
    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.nhru):
        if ((con.lnk[k] in (VERS, WASSER, FLUSS, SEE)) or
                (sta.bowa[k] <= der.wb[k])):
            flu.qib1[k] = 0.
        else:
            flu.qib1[k] = con.dmin[k]*(sta.bowa[k]/con.nfk[k])


Instruction:
Can you generate a brief explanation for the following Python 3 code
def calc_qib2_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.nhru):
        if ((con.lnk[k] in (VERS, WASSER, FLUSS, SEE)) or
                (sta.bowa[k] <= der.wz[k]) or (con.nfk[k] <= der.wz[k])):
            flu.qib2[k] = 0.
        else:
            flu.qib2[k] = ((con.dmax[k]-con.dmin[k]) *
                           ((sta.bowa[k]-der.wz[k]) /
                            (con.nfk[k]-der.wz[k]))**1.5)

Response: Calculates the first inflow component released from the soil.


Instruction:
Given the following Python 3 function, write the documentation
def calc_qdb_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    aid = self.sequences.aides.fastaccess
    for k in range(con.nhru):
        if con.lnk[k] == WASSER:
            flu.qdb[k] = 0.
        elif ((con.lnk[k] in (VERS, FLUSS, SEE)) or
              (con.nfk[k] <= 0.)):
            flu.qdb[k] = flu.wada[k]
        else:
            if sta.bowa[k] < con.nfk[k]:
                aid.sfa[k] = (
                    (1.-sta.bowa[k]/con.nfk[k])**(1./(con.bsf[k]+1.)) -
                    (flu.wada[k]/((con.bsf[k]+1.)*con.nfk[k])))
            else:
                aid.sfa[k] = 0.
            aid.exz[k] = sta.bowa[k]+flu.wada[k]-con.nfk[k]
            flu.qdb[k] = aid.exz[k]
            if aid.sfa[k] > 0.:
                flu.qdb[k] += aid.sfa[k]**(con.bsf[k]+1.)*con.nfk[k]
            flu.qdb[k] = max(flu.qdb[k], 0.)

Response: Calculates the QDB for the first four HRUs of the current state sequence and flux.


Instruction:
Can you tell what is the following Python 3 function doing
def calc_bowa_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    aid = self.sequences.aides.fastaccess
    for k in range(con.nhru):
        if con.lnk[k] in (VERS, WASSER, FLUSS, SEE):
            sta.bowa[k] = 0.
        else:
            aid.bvl[k] = (
                flu.evb[k]+flu.qbb[k]+flu.qib1[k]+flu.qib2[k]+flu.qdb[k])
            aid.mvl[k] = sta.bowa[k]+flu.wada[k]
            if aid.bvl[k] > aid.mvl[k]:
                aid.rvl[k] = aid.mvl[k]/aid.bvl[k]
                flu.evb[k] *= aid.rvl[k]
                flu.qbb[k] *= aid.rvl[k]
                flu.qib1[k] *= aid.rvl[k]
                flu.qib2[k] *= aid.rvl[k]
                flu.qdb[k] *= aid.rvl[k]
                sta.bowa[k] = 0.
            else:
                sta.bowa[k] = aid.mvl[k]-aid.bvl[k]

Response: Calculates the Bowa state sequence and correct fluxes if necessary.


Instruction:
Can you write a function in Python 3 where it
calculates the sum of the base flow released by all soil types and the stream network.

Response:
def calc_qbgz_v1(self):
    """Aggregate the amount of base flow released by all "soil type" HRUs
    and the "net precipitation" above water areas of type |SEE|.

    Water areas of type |SEE| are assumed to be directly connected with
    groundwater, but not with the stream network.  This is modelled by
    adding their (positive or negative) "net input" (|NKor|-|EvI|) to the
    "percolation output" of the soil containing HRUs.

    Required control parameters:
      |Lnk|
      |NHRU|
      |FHRU|

    Required flux sequences:
      |QBB|
      |NKor|
      |EvI|

    Calculated state sequence:
      |QBGZ|

    Basic equation:
       :math:`QBGZ = \\Sigma(FHRU \\cdot QBB) +
       \\Sigma(FHRU \\cdot (NKor_{SEE}-EvI_{SEE}))`

    Examples:

        The first example shows that |QBGZ| is the area weighted sum of
        |QBB| from "soil type" HRUs like arable land (|ACKER|) and of
        |NKor|-|EvI| from water areas of type |SEE|.  All other water
        areas (|WASSER| and |FLUSS|) and also sealed surfaces (|VERS|)
        have no impact on |QBGZ|:

        >>> from hydpy.models.lland import *
        >>> parameterstep()
        >>> nhru(6)
        >>> lnk(ACKER, ACKER, VERS, WASSER, FLUSS, SEE)
        >>> fhru(0.1, 0.2, 0.1, 0.1, 0.1, 0.4)
        >>> fluxes.qbb = 2., 4.0, 300.0, 300.0, 300.0, 300.0
        >>> fluxes.nkor = 200.0, 200.0, 200.0, 200.0, 200.0, 20.0
        >>> fluxes.evi = 100.0, 100.0, 100.0, 100.0, 100.0, 10.0
        >>> model.calc_qbgz_v1()
        >>> states.qbgz
        qbgz(5.0)

        The second example shows that large evaporation values above a
        HRU of type |SEE| can result in negative values of |QBGZ|:

        >>> fluxes.evi[5] = 30
        >>> model.calc_qbgz_v1()
        >>> states.qbgz
        qbgz(-3.0)
    """
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    sta.qbgz = 0.
    for k in range(con.nhru):
        if con.lnk[k] == SEE:
            sta.qbgz += con.fhru[k]*(flu.nkor[k]-flu.evi[k])
        elif con.lnk[k] not in (WASSER, FLUSS, VERS):
            sta.qbgz += con.fhru[k]*flu.qbb[k]


Instruction:
Can you generate the documentation for the following Python 3 function
def calc_qigz1_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    sta.qigz1 = 0.
    for k in range(con.nhru):
        sta.qigz1 += con.fhru[k]*flu.qib1[k]

Response: Calculates the sum of the amount of the first interflow component released by all HRUs.


Instruction:
Can you write a function in Python 3 where it
calculates the sum of the second interflow component released by all HRUs.

Response:
def calc_qigz2_v1(self):
    """Aggregate the amount of the second interflow component released
    by all HRUs.

    Required control parameters:
      |NHRU|
      |FHRU|

    Required flux sequence:
      |QIB2|

    Calculated state sequence:
      |QIGZ2|

    Basic equation:
       :math:`QIGZ2 = \\Sigma(FHRU \\cdot QIB2)`

    Example:

        >>> from hydpy.models.lland import *
        >>> parameterstep()
        >>> nhru(2)
        >>> fhru(0.75, 0.25)
        >>> fluxes.qib2 = 1.0, 5.0
        >>> model.calc_qigz2_v1()
        >>> states.qigz2
        qigz2(2.0)
    """
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    sta.qigz2 = 0.
    for k in range(con.nhru):
        sta.qigz2 += con.fhru[k]*flu.qib2[k]


Instruction:
Here you have a function in Python 3, explain what it does
def calc_qdgz1_qdgz2_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    if flu.qdgz > con.a2:
        sta.qdgz2 = (flu.qdgz-con.a2)**2/(flu.qdgz+con.a1-con.a2)
        sta.qdgz1 = flu.qdgz-sta.qdgz2
    else:
        sta.qdgz2 = 0.
        sta.qdgz1 = flu.qdgz

Response: Calculates the total direct flow into a small and a fast component.


Instruction:
Implement a function in Python 3 to
perform the runoff concentration calculation for base flow.

Response:
def calc_qbga_v1(self):
    """Perform the runoff concentration calculation for base flow.

    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 derived parameter:
      |KB|

    Required flux sequence:
      |QBGZ|

    Calculated state sequence:
      |QBGA|

    Basic equation:
       :math:`QBGA_{neu} = QBGA_{alt} +
       (QBGZ_{alt}-QBGA_{alt}) \\cdot (1-exp(-KB^{-1})) +
       (QBGZ_{neu}-QBGZ_{alt}) \\cdot (1-KB\\cdot(1-exp(-KB^{-1})))`

    Examples:

        A normal test case:

        >>> from hydpy.models.lland import *
        >>> parameterstep()
        >>> derived.kb(0.1)
        >>> states.qbgz.old = 2.0
        >>> states.qbgz.new = 4.0
        >>> states.qbga.old = 3.0
        >>> model.calc_qbga_v1()
        >>> states.qbga
        qbga(3.800054)

        First extreme test case (zero division is circumvented):

        >>> derived.kb(0.0)
        >>> model.calc_qbga_v1()
        >>> states.qbga
        qbga(4.0)

        Second extreme test case (numerical overflow is circumvented):

        >>> derived.kb(1e500)
        >>> model.calc_qbga_v1()
        >>> states.qbga
        qbga(5.0)
    """
    der = self.parameters.derived.fastaccess
    old = self.sequences.states.fastaccess_old
    new = self.sequences.states.fastaccess_new
    if der.kb <= 0.:
        new.qbga = new.qbgz
    elif der.kb > 1e200:
        new.qbga = old.qbga+new.qbgz-old.qbgz
    else:
        d_temp = (1.-modelutils.exp(-1./der.kb))
        new.qbga = (old.qbga +
                    (old.qbgz-old.qbga)*d_temp +
                    (new.qbgz-old.qbgz)*(1.-der.kb*d_temp))


Instruction:
Can you generate the documentation for the following Python 3 function
def calc_qiga1_v1(self):
    der = self.parameters.derived.fastaccess
    old = self.sequences.states.fastaccess_old
    new = self.sequences.states.fastaccess_new
    if der.ki1 <= 0.:
        new.qiga1 = new.qigz1
    elif der.ki1 > 1e200:
        new.qiga1 = old.qiga1+new.qigz1-old.qigz1
    else:
        d_temp = (1.-modelutils.exp(-1./der.ki1))
        new.qiga1 = (old.qiga1 +
                     (old.qigz1-old.qiga1)*d_temp +
                     (new.qigz1-old.qigz1)*(1.-der.ki1*d_temp))

Response: Perform the runoff concentration calculation for the first interflow component.


Instruction:
How would you explain what the following Python 3 function does
def calc_qiga2_v1(self):
    der = self.parameters.derived.fastaccess
    old = self.sequences.states.fastaccess_old
    new = self.sequences.states.fastaccess_new
    if der.ki2 <= 0.:
        new.qiga2 = new.qigz2
    elif der.ki2 > 1e200:
        new.qiga2 = old.qiga2+new.qigz2-old.qigz2
    else:
        d_temp = (1.-modelutils.exp(-1./der.ki2))
        new.qiga2 = (old.qiga2 +
                     (old.qigz2-old.qiga2)*d_temp +
                     (new.qigz2-old.qigz2)*(1.-der.ki2*d_temp))

Response:
Perform the runoff concentration calculation for the second
    interflow component.


Instruction:
Write a Python 3 function that can
perform the runoff concentration calculation for slow direct runoff.

Response:
def calc_qdga1_v1(self):
    """Perform the runoff concentration calculation for "slow" direct runoff.

    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 derived parameter:
      |KD1|

    Required state sequence:
      |QDGZ1|

    Calculated state sequence:
      |QDGA1|

    Basic equation:
       :math:`QDGA1_{neu} = QDGA1_{alt} +
       (QDGZ1_{alt}-QDGA1_{alt}) \\cdot (1-exp(-KD1^{-1})) +
       (QDGZ1_{neu}-QDGZ1_{alt}) \\cdot (1-KD1\\cdot(1-exp(-KD1^{-1})))`

    Examples:

        A normal test case:

        >>> from hydpy.models.lland import *
        >>> parameterstep()
        >>> derived.kd1(0.1)
        >>> states.qdgz1.old = 2.0
        >>> states.qdgz1.new = 4.0
        >>> states.qdga1.old = 3.0
        >>> model.calc_qdga1_v1()
        >>> states.qdga1
        qdga1(3.800054)

        First extreme test case (zero division is circumvented):

        >>> derived.kd1(0.0)
        >>> model.calc_qdga1_v1()
        >>> states.qdga1
        qdga1(4.0)

        Second extreme test case (numerical overflow is circumvented):

        >>> derived.kd1(1e500)
        >>> model.calc_qdga1_v1()
        >>> states.qdga1
        qdga1(5.0)
    """
    der = self.parameters.derived.fastaccess
    old = self.sequences.states.fastaccess_old
    new = self.sequences.states.fastaccess_new
    if der.kd1 <= 0.:
        new.qdga1 = new.qdgz1
    elif der.kd1 > 1e200:
        new.qdga1 = old.qdga1+new.qdgz1-old.qdgz1
    else:
        d_temp = (1.-modelutils.exp(-1./der.kd1))
        new.qdga1 = (old.qdga1 +
                     (old.qdgz1-old.qdga1)*d_temp +
                     (new.qdgz1-old.qdgz1)*(1.-der.kd1*d_temp))


Instruction:
Make a summary of the following Python 3 code
def calc_qdga2_v1(self):
    der = self.parameters.derived.fastaccess
    old = self.sequences.states.fastaccess_old
    new = self.sequences.states.fastaccess_new
    if der.kd2 <= 0.:
        new.qdga2 = new.qdgz2
    elif der.kd2 > 1e200:
        new.qdga2 = old.qdga2+new.qdgz2-old.qdgz2
    else:
        d_temp = (1.-modelutils.exp(-1./der.kd2))
        new.qdga2 = (old.qdga2 +
                     (old.qdgz2-old.qdga2)*d_temp +
                     (new.qdgz2-old.qdgz2)*(1.-der.kd2*d_temp))

Response: Perform the runoff concentration calculation for fast direct runoff.


Instruction:
Explain what the following Python 3 code does
def calc_q_v1(self):
    con = self.parameters.control.fastaccess
    flu = self.sequences.fluxes.fastaccess
    sta = self.sequences.states.fastaccess
    aid = self.sequences.aides.fastaccess
    flu.q = sta.qbga+sta.qiga1+sta.qiga2+sta.qdga1+sta.qdga2
    if (not con.negq) and (flu.q < 0.):
        d_area = 0.
        for k in range(con.nhru):
            if con.lnk[k] in (FLUSS, SEE):
                d_area += con.fhru[k]
        if d_area > 0.:
            for k in range(con.nhru):
                if con.lnk[k] in (FLUSS, SEE):
                    flu.evi[k] += flu.q/d_area
        flu.q = 0.
    aid.epw = 0.
    for k in range(con.nhru):
        if con.lnk[k] == WASSER:
            flu.q += con.fhru[k]*flu.nkor[k]
            aid.epw += con.fhru[k]*flu.evi[k]
    if (flu.q > aid.epw) or con.negq:
        flu.q -= aid.epw
    elif aid.epw > 0.:
        for k in range(con.nhru):
            if con.lnk[k] == WASSER:
                flu.evi[k] *= flu.q/aid.epw
        flu.q = 0.

Response: Calculates the final runoff of the water areas in the current runoff tree.


Instruction:
Can you generate a brief explanation for the following Python 3 code
def pass_q_v1(self):
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    out = self.sequences.outlets.fastaccess
    out.q[0] += der.qfactor*flu.q

Response: Update the outlet link sequence.


Instruction:
Write a Python 3 function that can
calculate the actual interpolation or extrapolation of the flux sequence.

Response:
def calc_outputs_v1(self):
    """Performs the actual interpolation or extrapolation.

    Required control parameters:
      |XPoints|
      |YPoints|

    Required derived parameter:
      |NmbPoints|
      |NmbBranches|

    Required flux sequence:
      |Input|

    Calculated flux sequence:
      |Outputs|

    Examples:

        As a simple example, assume a weir directing all discharge into
        `branch1` until the capacity limit of 2 m³/s is reached.  The
        discharge exceeding this threshold is directed into `branch2`:

        >>> from hydpy.models.hbranch import *
        >>> parameterstep()
        >>> xpoints(0., 2., 4.)
        >>> ypoints(branch1=[0., 2., 2.],
        ...         branch2=[0., 0., 2.])
        >>> model.parameters.update()

        Low discharge example (linear interpolation between the first two
        supporting point pairs):

        >>> fluxes.input = 1.
        >>> model.calc_outputs_v1()
        >>> fluxes.outputs
        outputs(branch1=1.0,
                branch2=0.0)

        Medium discharge example (linear interpolation between the second
        two supporting point pairs):

        >>> fluxes.input = 3.
        >>> model.calc_outputs_v1()
        >>> print(fluxes.outputs)
        outputs(branch1=2.0,
                branch2=1.0)

        High discharge example (linear extrapolation beyond the second two
        supporting point pairs):

        >>> fluxes.input = 5.
        >>> model.calc_outputs_v1()
        >>> fluxes.outputs
        outputs(branch1=2.0,
                branch2=3.0)

        Non-monotonous relationships and balance violations are allowed,
        e.g.:

        >>> xpoints(0., 2., 4., 6.)
        >>> ypoints(branch1=[0., 2., 0., 0.],
        ...         branch2=[0., 0., 2., 4.])
        >>> model.parameters.update()
        >>> fluxes.input = 7.
        >>> model.calc_outputs_v1()
        >>> fluxes.outputs
        outputs(branch1=0.0,
                branch2=5.0)
    """
    con = self.parameters.control.fastaccess
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    # Search for the index of the two relevant x points...
    for pdx in range(1, der.nmbpoints):
        if con.xpoints[pdx] > flu.input:
            break
    # ...and use it for linear interpolation (or extrapolation).
    for bdx in range(der.nmbbranches):
        flu.outputs[bdx] = (
            (flu.input-con.xpoints[pdx-1]) *
            (con.ypoints[bdx, pdx]-con.ypoints[bdx, pdx-1]) /
            (con.xpoints[pdx]-con.xpoints[pdx-1]) +
            con.ypoints[bdx, pdx-1])


Instruction:
Can you create a Python 3 function that
updates |Input| based on |Total|.

Response:
def pick_input_v1(self):
    """Updates |Input| based on |Total|."""
    flu = self.sequences.fluxes.fastaccess
    inl = self.sequences.inlets.fastaccess
    flu.input = 0.
    for idx in range(inl.len_total):
        flu.input += inl.total[idx][0]


Instruction:
Can you tell what is the following Python 3 function doing
def pass_outputs_v1(self):
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    out = self.sequences.outlets.fastaccess
    for bdx in range(der.nmbbranches):
        out.branched[bdx][0] += flu.outputs[bdx]

Response: Update |Branched| based on |Outputs|.


Instruction:
Explain what the following Python 3 code does
def connect(self):
        nodes = self.element.inlets
        total = self.sequences.inlets.total
        if total.shape != (len(nodes),):
            total.shape = len(nodes)
        for idx, node in enumerate(nodes):
            double = node.get_double('inlets')
            total.set_pointer(double, idx)
        for (idx, name) in enumerate(self.nodenames):
            try:
                outlet = getattr(self.element.outlets, name)
                double = outlet.get_double('outlets')
            except AttributeError:
                raise RuntimeError(
                    f'Model {objecttools.elementphrase(self)} tried '
                    f'to connect to an outlet node named `{name}`, '
                    f'which is not an available outlet node of element '
                    f'`{self.element.name}`.')
            self.sequences.outlets.branched.set_pointer(double, idx)

Response:
Connect the |LinkSequence| instances handled by one inlet node and the actual model
        multiple oulet nodes.


Instruction:
Make a summary of the following Python 3 code
def update(self):
        responses = self.subpars.pars.control.responses
        self.shape = len(responses)
        self(responses.ar_orders)

Response: Update the internal structure of the object.


Instruction:
Make a summary of the following Python 3 code
def update(self):
        pars = self.subpars.pars
        coefs = pars.control.responses.ar_coefs
        self.shape = coefs.shape
        self(coefs)
        pars.model.sequences.logs.logout.shape = self.shape

Response: Update the log - related AR coefficients.


Instruction:
Given the following Python 3 function, write the documentation
def update(self):
        pars = self.subpars.pars
        coefs = pars.control.responses.ma_coefs
        self.shape = coefs.shape
        self(coefs)
        pars.model.sequences.logs.login.shape = self.shape

Response: Update the log - in and log - in terms of the MA coefficients.


Instruction:
Can you generate the documentation for the following Python 3 function
def _prepare_docstrings():
    if config.USEAUTODOC:
        source = inspect.getsource(Options)
        docstrings = source.split('"""')[3::2]
        attributes = [line.strip().split()[0] for line in source.split('\n')
                      if '_Option(' in line]
        for attribute, docstring in zip(attributes, docstrings):
            Options.__dict__[attribute].__doc__ = docstring

Response: Assign docstrings to the corresponding attributes of class Options to make them available in the interactive mode of Python.


Instruction:
How would you code a function in Python 3 to
try to convert the given argument to a list of articles and return it.

Response:
def __getiterable(value):   # ToDo: refactor
        """Try to convert the given argument to a |list| of  |Selection|
        objects and return it.
        """
        if isinstance(value, Selection):
            return [value]
        try:
            for selection in value:
                if not isinstance(selection, Selection):
                    raise TypeError
            return list(value)
        except TypeError:
            raise TypeError(
                f'Binary operations on Selections objects are defined for '
                f'other Selections objects, single Selection objects, or '
                f'iterables containing `Selection` objects, but the type of '
                f'the given argument is `{objecttools.classname(value)}`.')


Instruction:
Can you generate a brief explanation for the following Python 3 code
def assignrepr(self, prefix='') -> str:
        with objecttools.repr_.preserve_strings(True):
            with hydpy.pub.options.ellipsis(2, optional=True):
                prefix += '%s(' % objecttools.classname(self)
                repr_ = objecttools.assignrepr_values(
                    sorted(self.names), prefix, 70)
                return repr_ + ')'

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


Instruction:
Write a Python 3 script to
return the upstream network of the given starting point.

Response:
def search_upstream(self, device: devicetools.Device,
                        name: str = 'upstream') -> 'Selection':
        """Return the network upstream of the given starting point, including
        the starting point itself.

        >>> from hydpy.core.examples import prepare_full_example_2
        >>> hp, pub, _ = prepare_full_example_2()

        You can pass both |Node| and |Element| objects and, optionally,
        the name of the newly created |Selection| object:

        >>> test = pub.selections.complete.copy('test')
        >>> test.search_upstream(hp.nodes.lahn_2)
        Selection("upstream",
                  nodes=("dill", "lahn_1", "lahn_2"),
                  elements=("land_dill", "land_lahn_1", "land_lahn_2",
                            "stream_dill_lahn_2", "stream_lahn_1_lahn_2"))
        >>> test.search_upstream(
        ...     hp.elements.stream_lahn_1_lahn_2, 'UPSTREAM')
        Selection("UPSTREAM",
                  nodes="lahn_1",
                  elements=("land_lahn_1", "stream_lahn_1_lahn_2"))

        Wrong device specifications result in errors like the following:

        >>> test.search_upstream(1)
        Traceback (most recent call last):
        ...
        TypeError: While trying to determine the upstream network of \
selection `test`, the following error occurred: Either a `Node` or \
an `Element` object is required as the "outlet device", but the given \
`device` value is of type `int`.

        >>> pub.selections.headwaters.search_upstream(hp.nodes.lahn_3)
        Traceback (most recent call last):
        ...
        KeyError: "While trying to determine the upstream network of \
selection `headwaters`, the following error occurred: 'No node named \
`lahn_3` available.'"

        Method |Selection.select_upstream| restricts the current selection
        to the one determined with the method |Selection.search_upstream|:

        >>> test.select_upstream(hp.nodes.lahn_2)
        Selection("test",
                  nodes=("dill", "lahn_1", "lahn_2"),
                  elements=("land_dill", "land_lahn_1", "land_lahn_2",
                            "stream_dill_lahn_2", "stream_lahn_1_lahn_2"))

        On the contrary, the method |Selection.deselect_upstream| restricts
        the current selection to all devices not determined by method
        |Selection.search_upstream|:

        >>> complete = pub.selections.complete.deselect_upstream(
        ...     hp.nodes.lahn_2)
        >>> complete
        Selection("complete",
                  nodes="lahn_3",
                  elements=("land_lahn_3", "stream_lahn_2_lahn_3"))

        If necessary, include the "outlet device" manually afterwards:

        >>> complete.nodes += hp.nodes.lahn_2
        >>> complete
        Selection("complete",
                  nodes=("lahn_2", "lahn_3"),
                  elements=("land_lahn_3", "stream_lahn_2_lahn_3"))
        """
        try:
            selection = Selection(name)
            if isinstance(device, devicetools.Node):
                node = self.nodes[device.name]
                return self.__get_nextnode(node, selection)
            if isinstance(device, devicetools.Element):
                element = self.elements[device.name]
                return self.__get_nextelement(element, selection)
            raise TypeError(
                f'Either a `Node` or an `Element` object is required '
                f'as the "outlet device", but the given `device` value '
                f'is of type `{objecttools.classname(device)}`.')
        except BaseException:
            objecttools.augment_excmessage(
                f'While trying to determine the upstream network of '
                f'selection `{self.name}`')


Instruction:
Explain what the following Python 3 code does
def select_upstream(self, device: devicetools.Device) -> 'Selection':
        upstream = self.search_upstream(device)
        self.nodes = upstream.nodes
        self.elements = upstream.elements
        return self

Response: Restrict the current selection to the network upstream of the given devicetools. Device.


Instruction:
Write a Python 3 script to
return a new |Selection| object containing only the elements of the given models of the given types.

Response:
def search_modeltypes(self, *models: ModelTypesArg,
                          name: str = 'modeltypes') -> 'Selection':
        """Return a |Selection| object containing only the elements
        currently handling models of the given types.

        >>> from hydpy.core.examples import prepare_full_example_2
        >>> hp, pub, _ = prepare_full_example_2()

        You can pass both |Model| objects and names and, as a keyword
        argument, the name of the newly created |Selection| object:

        >>> test = pub.selections.complete.copy('test')
        >>> from hydpy import prepare_model
        >>> hland_v1 = prepare_model('hland_v1')

        >>> test.search_modeltypes(hland_v1)
        Selection("modeltypes",
                  nodes=(),
                  elements=("land_dill", "land_lahn_1", "land_lahn_2",
                            "land_lahn_3"))
        >>> test.search_modeltypes(
        ...     hland_v1, 'hstream_v1', 'lland_v1', name='MODELTYPES')
        Selection("MODELTYPES",
                  nodes=(),
                  elements=("land_dill", "land_lahn_1", "land_lahn_2",
                            "land_lahn_3", "stream_dill_lahn_2",
                            "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3"))

        Wrong model specifications result in errors like the following:

        >>> test.search_modeltypes('wrong')
        Traceback (most recent call last):
        ...
        ModuleNotFoundError: While trying to determine the elements of \
selection `test` handling the model defined by the argument(s) `wrong` \
of type(s) `str`, the following error occurred: \
No module named 'hydpy.models.wrong'

        Method |Selection.select_modeltypes| restricts the current selection to
        the one determined with the method the |Selection.search_modeltypes|:

        >>> test.select_modeltypes(hland_v1)
        Selection("test",
                  nodes=(),
                  elements=("land_dill", "land_lahn_1", "land_lahn_2",
                            "land_lahn_3"))

        On the contrary, the method |Selection.deselect_upstream| restricts
        the current selection to all devices not determined by method the
        |Selection.search_upstream|:

        >>> pub.selections.complete.deselect_modeltypes(hland_v1)
        Selection("complete",
                  nodes=(),
                  elements=("stream_dill_lahn_2", "stream_lahn_1_lahn_2",
                            "stream_lahn_2_lahn_3"))
        """
        try:
            typelist = []
            for model in models:
                if not isinstance(model, modeltools.Model):
                    model = importtools.prepare_model(model)
                typelist.append(type(model))
            typetuple = tuple(typelist)
            selection = Selection(name)
            for element in self.elements:
                if isinstance(element.model, typetuple):
                    selection.elements += element
            return selection
        except BaseException:
            values = objecttools.enumeration(models)
            classes = objecttools.enumeration(
                objecttools.classname(model) for model in models)
            objecttools.augment_excmessage(
                f'While trying to determine the elements of selection '
                f'`{self.name}` handling the model defined by the '
                f'argument(s) `{values}` of type(s) `{classes}`')


Instruction:
Can you generate the documentation for the following Python 3 function
def select_modeltypes(self, *models: ModelTypesArg) -> 'Selection':
        self.nodes = devicetools.Nodes()
        self.elements = self.search_modeltypes(*models).elements
        return self

Response: Restrict the current |Selection| object to all elements containing the given model types.


Instruction:
Make a summary of the following Python 3 code
def search_nodenames(self, *substrings: str, name: str = 'nodenames') -> \
            'Selection':
        """Return a new selection containing all nodes of the current
        selection with a name containing at least one of the given substrings.

        >>> from hydpy.core.examples import prepare_full_example_2
        >>> hp, pub, _ = prepare_full_example_2()

        Pass the (sub)strings as positional arguments and, optionally, the
        name of the newly created |Selection| object as a keyword argument:

        >>> test = pub.selections.complete.copy('test')
        >>> from hydpy import prepare_model
        >>> test.search_nodenames('dill', 'lahn_1')
        Selection("nodenames",
                  nodes=("dill", "lahn_1"),
                  elements=())

        Wrong string specifications result in errors like the following:

        >>> test.search_nodenames(['dill', 'lahn_1'])
        Traceback (most recent call last):
        ...
        TypeError: While trying to determine the nodes of selection \
`test` with names containing at least one of the given substrings \
`['dill', 'lahn_1']`, the following error occurred: 'in <string>' \
requires string as left operand, not list

        Method |Selection.select_nodenames| restricts the current selection
        to the one determined with the the method |Selection.search_nodenames|:

        >>> test.select_nodenames('dill', 'lahn_1')
        Selection("test",
                  nodes=("dill", "lahn_1"),
                  elements=("land_dill", "land_lahn_1", "land_lahn_2",
                            "land_lahn_3", "stream_dill_lahn_2",
                            "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3"))

        On the contrary, the method |Selection.deselect_nodenames| restricts
        the current selection to all devices not determined by the method
        |Selection.search_nodenames|:

        >>> pub.selections.complete.deselect_nodenames('dill', 'lahn_1')
        Selection("complete",
                  nodes=("lahn_2", "lahn_3"),
                  elements=("land_dill", "land_lahn_1", "land_lahn_2",
                            "land_lahn_3", "stream_dill_lahn_2",
                            "stream_lahn_1_lahn_2", "stream_lahn_2_lahn_3"))
        """
        try:
            selection = Selection(name)
            for node in self.nodes:
                for substring in substrings:
                    if substring in node.name:
                        selection.nodes += node
                        break
            return selection
        except BaseException:
            values = objecttools.enumeration(substrings)
            objecttools.augment_excmessage(
                f'While trying to determine the nodes of selection '
                f'`{self.name}` with names containing at least one '
                f'of the given substrings `{values}`')

Response: Return a new selection containing all nodes of the current selection with a name containing at least one of the given substrings.


Instruction:
Create a Python 3 function for
restricting the current selection to all nodes with a name containing at least one of the given substrings.

Response:
def select_nodenames(self, *substrings: str) -> 'Selection':
        """Restrict the current selection to all nodes with a name
        containing at least one of the given substrings  (does not
        affect any elements).

        See the documentation on method |Selection.search_nodenames| for
        additional information.
        """
        self.nodes = self.search_nodenames(*substrings).nodes
        return self


Instruction:
Can you tell what is the following Python 3 function doing
def deselect_nodenames(self, *substrings: str) -> 'Selection':
        self.nodes -= self.search_nodenames(*substrings).nodes
        return self

Response:
Restrict the current selection to all nodes with a name
        not containing at least one of the given substrings.


Instruction:
Given the following Python 3 function, write the documentation
def search_elementnames(self, *substrings: str,
                            name: str = 'elementnames') -> 'Selection':
        """Return a new selection containing all elements of the current
        selection with a name containing at least one of the given substrings.

        >>> from hydpy.core.examples import prepare_full_example_2
        >>> hp, pub, _ = prepare_full_example_2()

        Pass the (sub)strings as positional arguments and, optionally, the
        name of the newly created |Selection| object as a keyword argument:

        >>> test = pub.selections.complete.copy('test')
        >>> from hydpy import prepare_model
        >>> test.search_elementnames('dill', 'lahn_1')
        Selection("elementnames",
                  nodes=(),
                  elements=("land_dill", "land_lahn_1", "stream_dill_lahn_2",
                            "stream_lahn_1_lahn_2"))

        Wrong string specifications result in errors like the following:

        >>> test.search_elementnames(['dill', 'lahn_1'])
        Traceback (most recent call last):
        ...
        TypeError: While trying to determine the elements of selection \
`test` with names containing at least one of the given substrings \
`['dill', 'lahn_1']`, the following error occurred: 'in <string>' \
requires string as left operand, not list

        Method |Selection.select_elementnames| restricts the current selection
        to the one determined with the method |Selection.search_elementnames|:

        >>> test.select_elementnames('dill', 'lahn_1')
        Selection("test",
                  nodes=("dill", "lahn_1", "lahn_2", "lahn_3"),
                  elements=("land_dill", "land_lahn_1", "stream_dill_lahn_2",
                            "stream_lahn_1_lahn_2"))

        On the contrary, the method |Selection.deselect_elementnames|
        restricts the current selection to all devices not determined
        by the method |Selection.search_elementnames|:

        >>> pub.selections.complete.deselect_elementnames('dill', 'lahn_1')
        Selection("complete",
                  nodes=("dill", "lahn_1", "lahn_2", "lahn_3"),
                  elements=("land_lahn_2", "land_lahn_3",
                            "stream_lahn_2_lahn_3"))
        """
        try:
            selection = Selection(name)
            for element in self.elements:
                for substring in substrings:
                    if substring in element.name:
                        selection.elements += element
                        break
            return selection
        except BaseException:
            values = objecttools.enumeration(substrings)
            objecttools.augment_excmessage(
                f'While trying to determine the elements of selection '
                f'`{self.name}` with names containing at least one '
                f'of the given substrings `{values}`')

Response: Return a new selection containing all elements of the current selection with a name containing at least one of the given substrings.


Instruction:
Write a Python 3 script to
restrict the current selection to all elements with a name containing at least one of the given substrings.

Response:
def select_elementnames(self, *substrings: str) -> 'Selection':
        """Restrict the current selection to all elements with a name
        containing at least one of the given substrings (does not
        affect any nodes).

        See the documentation on method |Selection.search_elementnames| for
        additional information.
        """
        self.elements = self.search_elementnames(*substrings).elements
        return self


Instruction:
Write a Python 3 function for
restricting the current selection to all elements with a name not containing at least one of the given substrings.

Response:
def deselect_elementnames(self, *substrings: str) -> 'Selection':
        """Restrict the current selection to all elements with a name
        not containing at least one of the given substrings.   (does
        not affect any nodes).

        See the documentation on method |Selection.search_elementnames| for
        additional information.
        """
        self.elements -= self.search_elementnames(*substrings).elements
        return self


Instruction:
How would you explain what the following Python 3 function does
def copy(self, name: str) -> 'Selection':
        return type(self)(name, copy.copy(self.nodes), copy.copy(self.elements))

Response:
Return a new |Selection| object with the given name and copies
        of the handles |Nodes| and |Elements| objects based on method
        |Devices. copy|.


Instruction:
Write a Python 3 function for
saving the selection as a network file.

Response:
def save_networkfile(self, filepath: Union[str, None] = None,
                         write_nodes: bool = True) -> None:
        """Save the selection as a network file.

        >>> from hydpy.core.examples import prepare_full_example_2
        >>> _, pub, TestIO = prepare_full_example_2()

        In most cases, one should conveniently write network files via method
        |NetworkManager.save_files| of class |NetworkManager|.  However,
        using the method |Selection.save_networkfile| allows for additional
        configuration via the arguments `filepath` and `write_nodes`:

        >>> with TestIO():
        ...     pub.selections.headwaters.save_networkfile()
        ...     with open('headwaters.py') as networkfile:
        ...         print(networkfile.read())
        # -*- coding: utf-8 -*-
        <BLANKLINE>
        from hydpy import Node, Element
        <BLANKLINE>
        <BLANKLINE>
        Node("dill", variable="Q",
             keywords="gauge")
        <BLANKLINE>
        Node("lahn_1", variable="Q",
             keywords="gauge")
        <BLANKLINE>
        <BLANKLINE>
        Element("land_dill",
                outlets="dill",
                keywords="catchment")
        <BLANKLINE>
        Element("land_lahn_1",
                outlets="lahn_1",
                keywords="catchment")
        <BLANKLINE>

        >>> with TestIO():
        ...     pub.selections.headwaters.save_networkfile('test.py', False)
        ...     with open('test.py') as networkfile:
        ...         print(networkfile.read())
        # -*- coding: utf-8 -*-
        <BLANKLINE>
        from hydpy import Node, Element
        <BLANKLINE>
        <BLANKLINE>
        Element("land_dill",
                outlets="dill",
                keywords="catchment")
        <BLANKLINE>
        Element("land_lahn_1",
                outlets="lahn_1",
                keywords="catchment")
        <BLANKLINE>
        """
        if filepath is None:
            filepath = self.name + '.py'
        with open(filepath, 'w', encoding="utf-8") as file_:
            file_.write('# -*- coding: utf-8 -*-\n')
            file_.write('\nfrom hydpy import Node, Element\n\n')
            if write_nodes:
                for node in self.nodes:
                    file_.write('\n' + repr(node) + '\n')
                file_.write('\n')
            for element in self.elements:
                file_.write('\n' + repr(element) + '\n')


Instruction:
Make a summary of the following Python 3 code
def assignrepr(self, prefix: str) -> str:
        with objecttools.repr_.preserve_strings(True):
            with hydpy.pub.options.ellipsis(2, optional=True):
                with objecttools.assignrepr_tuple.always_bracketed(False):
                    classname = objecttools.classname(self)
                    blanks = ' ' * (len(prefix+classname) + 1)
                    nodestr = objecttools.assignrepr_tuple(
                        self.nodes.names, blanks+'nodes=', 70)
                    elementstr = objecttools.assignrepr_tuple(
                        self.elements.names, blanks + 'elements=', 70)
                    return (f'{prefix}{classname}("{self.name}",\n'
                            f'{nodestr},\n'
                            f'{elementstr})')

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


Instruction:
How would you implement a function in Python 3 that
calculates the input discharge portions of the different response functions and the corresponding flux sequences.

Response:
def calc_qpin_v1(self):
    """Calculate the input discharge portions of the different response
    functions.

    Required derived parameters:
      |Nmb|
      |MaxQ|
      |DiffQ|

    Required flux sequence:
      |QIn|

    Calculated flux sequences:
      |QPIn|

    Examples:

        Initialize an arma model with three different response functions:

        >>> from hydpy.models.arma import *
        >>> parameterstep()
        >>> derived.nmb = 3
        >>> derived.maxq.shape = 3
        >>> derived.diffq.shape = 2
        >>> fluxes.qpin.shape = 3

        Define the maximum discharge value of the respective response
        functions and their successive differences:

        >>> derived.maxq(0.0, 2.0, 6.0)
        >>> derived.diffq(2., 4.)

        The first six examples are performed for inflow values ranging from
        0 to 12 m³/s:

        >>> from hydpy import UnitTest
        >>> test = UnitTest(
        ...     model, model.calc_qpin_v1,
        ...     last_example=6,
        ...     parseqs=(fluxes.qin, fluxes.qpin))
        >>> test.nexts.qin = 0., 1., 2., 4., 6., 12.
        >>> test()
        | ex. |  qin |           qpin |
        -------------------------------
        |   1 |  0.0 | 0.0  0.0   0.0 |
        |   2 |  1.0 | 1.0  0.0   0.0 |
        |   3 |  2.0 | 2.0  0.0   0.0 |
        |   4 |  4.0 | 2.0  2.0   0.0 |
        |   5 |  6.0 | 2.0  4.0   0.0 |
        |   6 | 12.0 | 2.0  4.0   6.0 |

        The following two additional examples are just supposed to
        demonstrate method |calc_qpin_v1| also functions properly if
        there is only one response function, wherefore total discharge
        does not need to be divided:

        >>> derived.nmb = 1
        >>> derived.maxq.shape = 1
        >>> derived.diffq.shape = 0
        >>> fluxes.qpin.shape = 1
        >>> derived.maxq(0.)

        >>> test = UnitTest(
        ...     model, model.calc_qpin_v1,
        ...     first_example=7, last_example=8,
        ...                 parseqs=(fluxes.qin,
        ...                          fluxes.qpin))
        >>> test.nexts.qin = 0., 12.
        >>> test()
        | ex. |  qin | qpin |
        ---------------------
        |   7 |  0.0 |  0.0 |
        |   8 | 12.0 | 12.0 |

    """
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for idx in range(der.nmb-1):
        if flu.qin < der.maxq[idx]:
            flu.qpin[idx] = 0.
        elif flu.qin < der.maxq[idx+1]:
            flu.qpin[idx] = flu.qin-der.maxq[idx]
        else:
            flu.qpin[idx] = der.diffq[idx]
    flu.qpin[der.nmb-1] = max(flu.qin-der.maxq[der.nmb-1], 0.)


Instruction:
Can you tell what is the following Python 3 function doing
def calc_login_v1(self):
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    log = self.sequences.logs.fastaccess
    for idx in range(der.nmb):
        for jdx in range(der.ma_order[idx]-2, -1, -1):
            log.login[idx, jdx+1] = log.login[idx, jdx]
    for idx in range(der.nmb):
        log.login[idx, 0] = flu.qpin[idx]

Response: Refresh the input log sequence for the different MA processes.


Instruction:
Can you generate the documentation for the following Python 3 function
def calc_qma_v1(self):
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    log = self.sequences.logs.fastaccess
    for idx in range(der.nmb):
        flu.qma[idx] = 0.
        for jdx in range(der.ma_order[idx]):
            flu.qma[idx] += der.ma_coefs[idx, jdx] * log.login[idx, jdx]

Response: Calculate the discharge responses of the different MA processes.


Instruction:
Write a Python 3 function that can
calculate the discharge responses of the different AR processes and the fluxes of the different AR processes.

Response:
def calc_qar_v1(self):
    """Calculate the discharge responses of the different AR processes.

    Required derived parameters:
      |Nmb|
      |AR_Order|
      |AR_Coefs|

    Required log sequence:
      |LogOut|

    Calculated flux sequence:
      |QAR|

    Examples:

        Assume there are four response functions, involving zero, one, two,
        and three AR coefficients respectively:

        >>> from hydpy.models.arma import *
        >>> parameterstep()
        >>> derived.nmb(4)
        >>> derived.ar_order.shape = 4
        >>> derived.ar_order = 0, 1, 2, 3
        >>> derived.ar_coefs.shape = (4, 3)
        >>> logs.logout.shape = (4, 3)
        >>> fluxes.qar.shape = 4

        The coefficients of the different AR processes are stored in
        separate rows of the 2-dimensional parameter `ma_coefs`.
        Note the special case of the first AR process of zero order
        (first row), which involves no autoregressive memory at all:

        >>> derived.ar_coefs = ((nan, nan, nan),
        ...                     (1.0, nan, nan),
        ...                     (0.8, 0.2, nan),
        ...                     (0.5, 0.3, 0.2))

        The "memory values" of the different AR processes are defined as
        follows (one row for each process).  The values of the last time
        step are stored in first column, the values of the last time step
        in the second column, and so on:

        >>> logs.logout = ((nan, nan, nan),
        ...                (1.0, nan, nan),
        ...                (2.0, 3.0, nan),
        ...                (4.0, 5.0, 6.0))

        Applying method |calc_qar_v1| is equivalent to calculating the
        inner product of the different rows of both matrices:

        >>> model.calc_qar_v1()
        >>> fluxes.qar
        qar(0.0, 1.0, 2.2, 4.7)

    """
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    log = self.sequences.logs.fastaccess
    for idx in range(der.nmb):
        flu.qar[idx] = 0.
        for jdx in range(der.ar_order[idx]):
            flu.qar[idx] += der.ar_coefs[idx, jdx] * log.logout[idx, jdx]


Instruction:
Can you generate the documentation for the following Python 3 function
def calc_qpout_v1(self):
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    for idx in range(der.nmb):
        flu.qpout[idx] = flu.qma[idx]+flu.qar[idx]

Response: Calculate the ARMA results for the different response functions.


Instruction:
Make a summary of the following Python 3 code
def calc_logout_v1(self):
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    log = self.sequences.logs.fastaccess
    for idx in range(der.nmb):
        for jdx in range(der.ar_order[idx]-2, -1, -1):
            log.logout[idx, jdx+1] = log.logout[idx, jdx]
    for idx in range(der.nmb):
        if der.ar_order[idx] > 0:
            log.logout[idx, 0] = flu.qpout[idx]

Response: Refresh the log sequence for the different AR processes.


Instruction:
Write a Python 3 script for
calculating the sum of the results of the different response functions and add them to the fluxes.

Response:
def calc_qout_v1(self):
    """Sum up the results of the different response functions.

    Required derived parameter:
      |Nmb|

    Required flux sequences:
      |QPOut|

    Calculated flux sequence:
      |QOut|

    Examples:

        Initialize an arma model with three different response functions:

        >>> from hydpy.models.arma import *
        >>> parameterstep()
        >>> derived.nmb(3)
        >>> fluxes.qpout.shape = 3

        Define the output values of the three response functions and
        apply method |calc_qout_v1|:

        >>> fluxes.qpout = 1.0, 2.0, 3.0
        >>> model.calc_qout_v1()
        >>> fluxes.qout
        qout(6.0)
    """
    der = self.parameters.derived.fastaccess
    flu = self.sequences.fluxes.fastaccess
    flu.qout = 0.
    for idx in range(der.nmb):
        flu.qout += flu.qpout[idx]


Instruction:
Can you tell what is the following Python 3 function doing
def pick_q_v1(self):
    flu = self.sequences.fluxes.fastaccess
    inl = self.sequences.inlets.fastaccess
    flu.qin = 0.
    for idx in range(inl.len_q):
        flu.qin += inl.q[idx][0]

Response: Update inflow based on the number of inlets.


Instruction:
Explain what the following Python 3 code does
def update(self):
        con = self.subpars.pars.control
        self(con.ypoints.shape[0])

Response: Update the internal variable self based on the number of branches in the control set.


Instruction:
Can you tell what is the following Python 3 function doing
def update(self):
        con = self.subpars.pars.control
        self(0.)
        for idx in range(2):
            if (con.bbv[idx] > 0.) and (con.bnv[idx] > 0.):
                self.values[idx] = con.bbv[idx]/con.bnv[idx]

Response: Update value based on : math : HV = BBV / BNV.


Instruction:
Can you generate the documentation for the following Python 3 function
def update(self):
        mod = self.subpars.pars.model
        con = mod.parameters.control
        flu = mod.sequences.fluxes
        flu.h = con.hm
        mod.calc_qg()
        self(flu.qg)

Response: Update the value of the internal object with the current value of the internal object.


Instruction:
Given the following Python 3 function, write the documentation
def update(self):
        pars = self.subpars.pars
        self(int(round(pars.control.lag)))
        pars.model.sequences.states.qjoints.shape = self+1

Response: Updates the internal state of the object with the current state of the current state.


Instruction:
Can you generate the documentation for the following Python 3 function
def update(self):
        damp = self.subpars.pars.control.damp
        self(numpy.clip(damp/(1.+damp), 0., .5))

Response: Update |C1| based on |Damp}{1 + Damp|.


Instruction:
Can you tell what is the following Python 3 function doing
def update(self):
        der = self.subpars
        self(numpy.clip(1. - der.c1 - der.c3, 0., 1.))

Response: Update |C2| based on |1. - c_1 - c_3|.


Instruction:
Can you generate the documentation for the following Python 3 function
def view(data, enc=None, start_pos=None, delimiter=None, hdr_rows=None,
         idx_cols=None, sheet_index=0, transpose=False, wait=None,
         recycle=None, detach=None, metavar=None, title=None):
    """View the supplied data in an interactive, graphical table widget.

    data: When a valid path or IO object, read it as a tabular text file. When
          a valid URI, a Blaze object is constructed and visualized. Any other
          supported datatype is visualized directly and incrementally *without
          copying*.

    enc: File encoding (such as "utf-8", normally autodetected).

    delimiter: Text file delimiter (normally autodetected).

    hdr_rows: For files or lists of lists, specify the number of header rows.
              For files only, a default of one header line is assumed.

    idx_cols: For files or lists of lists, specify the number of index columns.
              By default, no index is assumed.

    sheet_index: For multi-table files (such as xls[x]), specify the sheet
                 index to read, starting from 0. Defaults to the first.

    start_pos: A tuple of the form (y, x) specifying the initial cursor
               position. Negative offsets count from the end of the dataset.

    transpose: Transpose the resulting view.

    metavar: name of the variable being shown for display purposes (inferred
             automatically when possible).

    title: title of the data window.

    wait: Wait for the user to close the view before returning. By default, try
          to match the behavior of ``matplotlib.is_interactive()``. If
          matplotlib is not loaded, wait only if ``detach`` is also False. The
          default value can also be set through ``gtabview.WAIT``.

    recycle: Recycle the previous window instead of creating a new one. The
             default is True, and can also be set through ``gtabview.RECYCLE``.

    detach: Create a fully detached GUI thread for interactive use (note: this
            is *not* necessary if matplotlib is loaded). The default is False,
            and can also be set through ``gtabview.DETACH``.
    """
    global WAIT, RECYCLE, DETACH, VIEW

    model = read_model(data, enc=enc, delimiter=delimiter, hdr_rows=hdr_rows,
                       idx_cols=idx_cols, sheet_index=sheet_index,
                       transpose=transpose)
    if model is None:
        warnings.warn("cannot visualize the supplied data type: {}".format(type(data)),
                      category=RuntimeWarning)
        return None

    # setup defaults
    if wait is None: wait = WAIT
    if recycle is None: recycle = RECYCLE
    if detach is None: detach = DETACH
    if wait is None:
        if 'matplotlib' not in sys.modules:
            wait = not bool(detach)
        else:
            import matplotlib.pyplot as plt
            wait = not plt.isinteractive()

    # try to fetch the variable name in the upper stack
    if metavar is None:
        if isinstance(data, basestring):
            metavar = data
        else:
            metavar = _varname_in_stack(data, 1)

    # create a view controller
    if VIEW is None:
        if not detach:
            VIEW = ViewController()
        else:
            VIEW = DetachedViewController()
            VIEW.setDaemon(True)
            VIEW.start()
            if VIEW.is_detached():
                atexit.register(VIEW.exit)
            else:
                VIEW = None
                return None

    # actually show the data
    view_kwargs = {'hdr_rows': hdr_rows, 'idx_cols': idx_cols,
                   'start_pos': start_pos, 'metavar': metavar, 'title': title}
    VIEW.view(model, view_kwargs, wait=wait, recycle=recycle)
    return VIEW

Response: View the supplied data in an interactive graphical table widget.


Instruction:
Can you tell what is the following Python 3 function doing
def gather_registries() -> Tuple[Dict, Mapping, Mapping]:
    id2devices = copy.copy(_id2devices)
    registry = copy.copy(_registry)
    selection = copy.copy(_selection)
    dict_ = globals()
    dict_['_id2devices'] = {}
    dict_['_registry'] = {Node: {}, Element: {}}
    dict_['_selection'] = {Node: {}, Element: {}}
    return id2devices, registry, selection

Response: Get and clear the current node and element registries.


Instruction:
Implement a function in Python 3 to
reset the current |Node| and |Element| registries.

Response:
def reset_registries(dicts: Tuple[Dict, Mapping, Mapping]):
    """Reset the current |Node| and |Element| registries.

    Function |reset_registries| is thought to be used by class |Tester| only.
    """
    dict_ = globals()
    dict_['_id2devices'] = dicts[0]
    dict_['_registry'] = dicts[1]
    dict_['_selection'] = dicts[2]


Instruction:
Can you write a function in Python 3 where it
returns a pandas index for the current date range.

Response:
def _get_pandasindex():
    """
    >>> from hydpy import pub
    >>> pub.timegrids = '2004.01.01', '2005.01.01', '1d'
    >>> from hydpy.core.devicetools import _get_pandasindex
    >>> _get_pandasindex()   # doctest: +ELLIPSIS
    DatetimeIndex(['2004-01-01 12:00:00', '2004-01-02 12:00:00',
    ...
                   '2004-12-30 12:00:00', '2004-12-31 12:00:00'],
                  dtype='datetime64[ns]', length=366, freq=None)
    """
    tg = hydpy.pub.timegrids.init
    shift = tg.stepsize / 2
    index = pandas.date_range(
        (tg.firstdate + shift).datetime,
        (tg.lastdate - shift).datetime,
        (tg.lastdate - tg.firstdate - tg.stepsize) / tg.stepsize + 1)
    return index


Instruction:
Implement a function in Python 3 to
return a list of all keywords starting with the given string.

Response:
def startswith(self, name: str) -> List[str]:
        """Return a list of all keywords starting with the given string.

        >>> from hydpy.core.devicetools import Keywords
        >>> keywords = Keywords('first_keyword', 'second_keyword',
        ...                     'keyword_3', 'keyword_4',
        ...                     'keyboard')
        >>> keywords.startswith('keyword')
        ['keyword_3', 'keyword_4']
        """
        return sorted(keyword for keyword in self if keyword.startswith(name))


Instruction:
How would you code a function in Python 3 to
return a list of all keywords ending with the given string.

Response:
def endswith(self, name: str) -> List[str]:
        """Return a list of all keywords ending with the given string.

        >>> from hydpy.core.devicetools import Keywords
        >>> keywords = Keywords('first_keyword', 'second_keyword',
        ...                     'keyword_3', 'keyword_4',
        ...                     'keyboard')
        >>> keywords.endswith('keyword')
        ['first_keyword', 'second_keyword']
        """
        return sorted(keyword for keyword in self if keyword.endswith(name))


Instruction:
Write a Python 3 script for
returning a list of all keywords containing the given string.

Response:
def contains(self, name: str) -> List[str]:
        """Return a list of all keywords containing the given string.

        >>> from hydpy.core.devicetools import Keywords
        >>> keywords = Keywords('first_keyword', 'second_keyword',
        ...                     'keyword_3', 'keyword_4',
        ...                     'keyboard')
        >>> keywords.contains('keyword')
        ['first_keyword', 'keyword_3', 'keyword_4', 'second_keyword']
        """
        return sorted(keyword for keyword in self if name in keyword)


Instruction:
Can you write a function in Python 3 where it
updates the set of variable identifiers.

Response:
def update(self, *names: Any) -> None:
        """Before updating, the given names are checked to be valid
        variable identifiers.

        >>> from hydpy.core.devicetools import Keywords
        >>> keywords = Keywords('first_keyword', 'second_keyword',
        ...                     'keyword_3', 'keyword_4',
        ...                     'keyboard')
        >>> keywords.update('test_1', 'test 2')   # doctest: +ELLIPSIS
        Traceback (most recent call last):
        ...
        ValueError: While trying to add the keyword `test 2` to device ?, \
the following error occurred: The given name string `test 2` does not \
define a valid variable identifier.  ...

        Note that even the first string (`test1`) is not added due to the
        second one (`test 2`) being invalid.

        >>> keywords
        Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4",
                 "second_keyword")

        After correcting the second string, everything works fine:

        >>> keywords.update('test_1', 'test_2')
        >>> keywords
        Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4",
                 "second_keyword", "test_1", "test_2")
        """
        _names = [str(name) for name in names]
        self._check_keywords(_names)
        super().update(_names)


Instruction:
Here you have a function in Python 3, explain what it does
def add(self, name: Any) -> None:
        self._check_keywords([str(name)])
        super().add(str(name))

Response: Add a new name to the set.


Instruction:
Create a Python 3 function for
adding the given device to the actual nodes or elements.

Response:
def add_device(self, device: Union[DeviceType, str]) -> None:
        """Add the given |Node| or |Element| object to the actual
        |Nodes| or |Elements| object.

        You can pass either a string or a device:

        >>> from hydpy import Nodes
        >>> nodes = Nodes()
        >>> nodes.add_device('old_node')
        >>> nodes
        Nodes("old_node")
        >>> nodes.add_device('new_node')
        >>> nodes
        Nodes("new_node", "old_node")

        Method |Devices.add_device| is disabled for immutable |Nodes|
        and |Elements| objects:

        >>> nodes.mutable = False
        >>> nodes.add_device('newest_node')
        Traceback (most recent call last):
        ...
        RuntimeError: While trying to add the device `newest_node` to a \
Nodes object, the following error occurred: Adding devices to immutable \
Nodes objects is not allowed.
        """
        try:
            if self.mutable:
                _device = self.get_contentclass()(device)
                self._name2device[_device.name] = _device
                _id2devices[_device][id(self)] = self
            else:
                raise RuntimeError(
                    f'Adding devices to immutable '
                    f'{objecttools.classname(self)} objects is not allowed.')
        except BaseException:
            objecttools.augment_excmessage(
                f'While trying to add the device `{device}` to a '
                f'{objecttools.classname(self)} object')