text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_controlfileheader( model: Union[str, 'modeltools.Model'], parameterstep: timetools.PeriodConstrArg = None, simulationstep: timetools.PeriodConstrArg = None) -> str: """Return the header of a regular or auxiliary parameter control file. The header contains the default coding information, the import command for the given model and the actual parameter and simulation step sizes. The first example shows that, if you pass the model argument as a string, you have to take care that this string makes sense: # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.no model class import * <BLANKLINE> simulationstep('1h') parameterstep('-1h') <BLANKLINE> <BLANKLINE> The second example shows the saver option to pass the proper model object. It also shows that function |get_controlfileheader| tries to gain the parameter and simulation step sizes from the global |Timegrids| object contained in the module |pub| when necessary: # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.lland_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('1d') <BLANKLINE> <BLANKLINE> """
with Parameter.parameterstep(parameterstep): if simulationstep is None: simulationstep = Parameter.simulationstep else: simulationstep = timetools.Period(simulationstep) return (f"# -*- coding: utf-8 -*-\n\n" f"from hydpy.models.{model} import *\n\n" f"simulationstep('{simulationstep}')\n" f"parameterstep('{Parameter.parameterstep}')\n\n")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self) -> None: """Call method |Parameter.update| of all "secondary" parameters. Directly after initialisation, neither the primary (`control`) parameters nor the secondary (`derived`) parameters of application model |hstream_v1| are ready for usage: nmbsegments(?) c1(?) c3(?) c2(?) Trying to update the values of the secondary parameters while the primary ones are still not defined, raises errors like the following: Traceback (most recent call last): AttributeError: While trying to update parameter ``nmbsegments` \ of element `?``, the following error occurred: For variable `lag`, \ no value has been defined so far. With proper values both for parameter |hstream_control.Lag| and |hstream_control.Damp|, updating the derived parameters succeeds: nmbsegments(0) c1(0.0) c3(0.0) c2(1.0) """
for subpars in self.secondary_subpars: for par in subpars: try: par.update() except BaseException: objecttools.augment_excmessage( f'While trying to update parameter ' f'`{objecttools.elementphrase(par)}`')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_controls(self, filepath: Optional[str] = None, parameterstep: timetools.PeriodConstrArg = None, simulationstep: timetools.PeriodConstrArg = None, auxfiler: 'auxfiletools.Auxfiler' = None): """Write the control parameters to file. Usually, a control file consists of a header (see the documentation on the method |get_controlfileheader|) and the string representations of the individual |Parameter| objects handled by the `control` |SubParameters| object. The main functionality of method |Parameters.save_controls| is demonstrated in the documentation on the method |HydPy.save_controls| of class |HydPy|, which one would apply to write the parameter information of complete *HydPy* projects. However, to call |Parameters.save_controls| on individual |Parameters| objects offers the advantage to choose an arbitrary file path, as shown in the following example: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ otherdir/otherfile.py # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('1d') <BLANKLINE> lag(1.0) damp(0.5) <BLANKLINE> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Without a given file path and a proper project configuration, method |Parameters.save_controls| raises the following error: Traceback (most recent call last): RuntimeError: To save the control parameters of a model to a file, \ its filename must be known. This can be done, by passing a filename to \ function `save_controls` directly. But in complete HydPy applications, \ it is usally assumed to be consistent with the name of the element \ handling the model. """
if self.control: variable2auxfile = getattr(auxfiler, str(self.model), None) lines = [get_controlfileheader( self.model, parameterstep, simulationstep)] with Parameter.parameterstep(parameterstep): for par in self.control: if variable2auxfile: auxfilename = variable2auxfile.get_filename(par) if auxfilename: lines.append( f"{par.name}(auxfile='{auxfilename}')\n") continue lines.append(repr(par) + '\n') text = ''.join(lines) if filepath: with open(filepath, mode='w', encoding='utf-8') as controlfile: controlfile.write(text) else: filename = objecttools.devicename(self) if filename == '?': raise RuntimeError( 'To save the control parameters of a model to a file, ' 'its filename must be known. This can be done, by ' 'passing a filename to function `save_controls` ' 'directly. But in complete HydPy applications, it is ' 'usally assumed to be consistent with the name of the ' 'element handling the model.') hydpy.pub.controlmanager.save_file(filename, text)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_values_from_auxiliaryfile(self, auxfile): """Try to return the parameter values from the auxiliary control file with the given name. Things are a little complicated here. To understand this method, you should first take a look at the |parameterstep| function. """
try: frame = inspect.currentframe().f_back.f_back while frame: namespace = frame.f_locals try: subnamespace = {'model': namespace['model'], 'focus': self} break except KeyError: frame = frame.f_back else: raise RuntimeError( 'Cannot determine the corresponding model. Use the ' '`auxfile` keyword in usual parameter control files only.') filetools.ControlManager.read2dict(auxfile, subnamespace) try: subself = subnamespace[self.name] except KeyError: raise RuntimeError( f'The selected file does not define value(s) for ' f'parameter {self.name}') return subself.values except BaseException: objecttools.augment_excmessage( f'While trying to extract information for parameter ' f'`{self.name}` from file `{auxfile}`')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def initinfo(self) -> Tuple[Union[float, int, bool], bool]: """The actual initial value of the given parameter. Some |Parameter| subclasses define another value for class attribute `INIT` than |None| to provide a default value. Let's define a parameter test class and prepare a function for initialising it and connecting the resulting instance to a |SubParameters| object: By default, making use of the `INIT` attribute is disabled: test(?) Enable it through setting |Options.usedefaultvalues| to |True|: test(2.0) When no `INIT` attribute is defined, enabling |Options.usedefaultvalues| has no effect, of course: test(?) For time-dependent parameter values, the `INIT` attribute is assumed to be related to a |Parameterstep| of one day: test(4.0) 1.0 """
init = self.INIT if (init is not None) and hydpy.pub.options.usedefaultvalues: with Parameter.parameterstep('1d'): return self.apply_timefactor(init), True return variabletools.TYPE2MISSINGVALUE[self.TYPE], False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_timefactor(cls) -> float: """Factor to adjust a new value of a time-dependent parameter. For a time-dependent parameter, its effective value depends on the simulation step size. Method |Parameter.get_timefactor| returns the fraction between the current simulation step size and the current parameter step size. .. testsetup:: Period() Method |Parameter.get_timefactor| raises the following error when time information is not available: Traceback (most recent call last): RuntimeError: To calculate the conversion factor for adapting the \ values of the time-dependent parameters, you need to define both a \ parameter and a simulation time step size first. One can define both time step sizes directly: 0.25 As usual, the "global" simulation step size of the |Timegrids| object of module |pub| is prefered: 0.5 """
try: parfactor = hydpy.pub.timegrids.parfactor except RuntimeError: if not (cls.parameterstep and cls.simulationstep): raise RuntimeError( f'To calculate the conversion factor for adapting ' f'the values of the time-dependent parameters, ' f'you need to define both a parameter and a simulation ' f'time step size first.') else: date1 = timetools.Date('2000.01.01') date2 = date1 + cls.simulationstep parfactor = timetools.Timegrids(timetools.Timegrid( date1, date2, cls.simulationstep)).parfactor return parfactor(cls.parameterstep)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def revert_timefactor(cls, values): """The inverse version of method |Parameter.apply_timefactor|. See the explanations on method Parameter.apply_timefactor| to understand the following examples: .. testsetup:: 4.0 16.0 1.0 """
if cls.TIME is True: return values / cls.get_timefactor() if cls.TIME is False: return values * cls.get_timefactor() return values
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def compress_repr(self) -> Optional[str]: """Try to find a compressed parameter value representation and return it. |Parameter.compress_repr| raises a |NotImplementedError| when failing to find a compressed representation. .. testsetup:: For the following examples, we define a 1-dimensional sequence handling time-dependent floating point values: Before and directly after defining the parameter shape, `nan` is returned: '?' test(?) test(?) Due to the time-dependence of the values of our test class, we need to specify a parameter and a simulation time step: Compression succeeds when all required values are identical: array([ 1., 1., 1., 1.]) '3.0' test(3.0) Method |Parameter.compress_repr| returns |None| in case the required values are not identical: test(1.0, 2.0, 3.0, 3.0) If some values are not required, indicate this by the `mask` descriptor: test(3.0, 3.0, 3.0, nan) test(3.0) For a shape of zero, the string representing includes an empty list: '[]' test([]) Method |Parameter.compress_repr| works similarly for different |Parameter| subclasses. The following examples focus on a 2-dimensional parameter handling integer values: '?' test(?) test(?) test(3) test([[3, 3, -999999], [3, 3, 3]]) test(3) test([[]]) """
if not hasattr(self, 'value'): return '?' if not self: return f"{self.NDIM * '['}{self.NDIM * ']'}" unique = numpy.unique(self[self.mask]) if sum(numpy.isnan(unique)) == len(unique.flatten()): unique = numpy.array([numpy.nan]) else: unique = self.revert_timefactor(unique) if len(unique) == 1: return objecttools.repr_(unique[0]) return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh(self) -> None: """Update the actual simulation values based on the toy-value pairs. Usually, one does not need to call refresh explicitly. The "magic" methods __call__, __setattr__, and __delattr__ invoke it automatically, when required. Instantiate a 1-dimensional |SeasonalParameter| object: When a |SeasonalParameter| object does not contain any toy-value pairs yet, the method |SeasonalParameter.refresh| sets all actual simulation values to zero: 0.0 When there is only one toy-value pair, its values are relevant for all actual simulation values: 2.0 Method |SeasonalParameter.refresh| performs a linear interpolation for the central time points of each simulation time step. Hence, in the following example, the original values of the toy-value pairs do not show up: 2.00274 3.99726 3.0 If one wants to preserve the original values in this example, one would have to set the corresponding toy instances in the middle of some simulation step intervals: 2.0 2.005479 3.994521 4.0 """
if not self: self.values[:] = 0. elif len(self) == 1: values = list(self._toy2values.values())[0] self.values[:] = self.apply_timefactor(values) else: for idx, date in enumerate( timetools.TOY.centred_timegrid(self.simulationstep)): values = self.interp(date) self.values[idx] = self.apply_timefactor(values)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def interp(self, date: timetools.Date) -> float: """Perform a linear value interpolation for the given `date` and return the result. Instantiate a 1-dimensional |SeasonalParameter| object: Define three toy-value pairs: Passing a |Date| object matching a |TOY| object exactly returns the corresponding |float| value: 2.0 5.0 4.0 For all intermediate points, |SeasonalParameter.interp| performs a linear interpolation: 2.096774 4.903226 4.997006 4.002994 Linear interpolation is also allowed between the first and the last pair when they do not capture the endpoints of the year: 3.99449 4.0 3.333333 2.666667 2.0 2.00551 The following example briefly shows interpolation performed for a 2-dimensional parameter: -1.0 1.0 """
xnew = timetools.TOY(date) xys = list(self) for idx, (x_1, y_1) in enumerate(xys): if x_1 > xnew: x_0, y_0 = xys[idx-1] break else: x_0, y_0 = xys[-1] x_1, y_1 = xys[0] return y_0+(y_1-y_0)/(x_1-x_0)*(xnew-x_0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self) -> None: """Update subclass of |RelSubweightsMixin| based on `refweights`."""
mask = self.mask weights = self.refweights[mask] self[~mask] = numpy.nan self[mask] = weights/numpy.sum(weights)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def alternative_initvalue(self) -> Union[bool, int, float]: """A user-defined value to be used instead of the value of class constant `INIT`. See the main documentation on class |SolverParameter| for more information. """
if self._alternative_initvalue is None: raise AttributeError( f'No alternative initial value for solver parameter ' f'{objecttools.elementphrase(self)} has been defined so far.') else: return self._alternative_initvalue
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self) -> None: """Reference the actual |Indexer.timeofyear| array of the |Indexer| object available in module |pub|. toyparameter(57, 58, 59, 60, 61) """
indexarray = hydpy.pub.indexer.timeofyear self.shape = indexarray.shape self.values = indexarray
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_premises_model(): """ Support for custom company premises model with developer friendly validation. """
try: app_label, model_name = PREMISES_MODEL.split('.') except ValueError: raise ImproperlyConfigured("OPENINGHOURS_PREMISES_MODEL must be of the" " form 'app_label.model_name'") premises_model = get_model(app_label=app_label, model_name=model_name) if premises_model is None: raise ImproperlyConfigured("OPENINGHOURS_PREMISES_MODEL refers to" " model '%s' that has not been installed" % PREMISES_MODEL) return premises_model
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_now(): """ Allows to access global request and read a timestamp from query. """
if not get_current_request: return datetime.datetime.now() request = get_current_request() if request: openinghours_now = request.GET.get('openinghours-now') if openinghours_now: return datetime.datetime.strptime(openinghours_now, '%Y%m%d%H%M%S') return datetime.datetime.now()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_closing_rule_for_now(location): """ Returns QuerySet of ClosingRules that are currently valid """
now = get_now() if location: return ClosingRules.objects.filter(company=location, start__lte=now, end__gte=now) return Company.objects.first().closingrules_set.filter(start__lte=now, end__gte=now)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_open(location, now=None): """ Is the company currently open? Pass "now" to test with a specific timestamp. Can be used stand-alone or as a helper. """
if now is None: now = get_now() if has_closing_rule_for_now(location): return False now_time = datetime.time(now.hour, now.minute, now.second) if location: ohs = OpeningHours.objects.filter(company=location) else: ohs = Company.objects.first().openinghours_set.all() for oh in ohs: is_open = False # start and end is on the same day if (oh.weekday == now.isoweekday() and oh.from_hour <= now_time and now_time <= oh.to_hour): is_open = oh # start and end are not on the same day and we test on the start day if (oh.weekday == now.isoweekday() and oh.from_hour <= now_time and ((oh.to_hour < oh.from_hour) and (now_time < datetime.time(23, 59, 59)))): is_open = oh # start and end are not on the same day and we test on the end day if (oh.weekday == (now.isoweekday() - 1) % 7 and oh.from_hour >= now_time and oh.to_hour >= now_time and oh.to_hour < oh.from_hour): is_open = oh # print " 'Special' case after midnight", oh if is_open is not False: return oh return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refweights(self): """A |numpy| |numpy.ndarray| with equal weights for all segment junctions.. array([ 0.2, 0.2, 0.2, 0.2, 0.2]) """
# 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def basepath(self) -> str: """Absolute path pointing to the available working directories. """
return os.path.abspath( os.path.join(self.projectdir, self.BASEDIR))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def availabledirs(self) -> Folder2Path: """Names and paths of the available working directories. Available working directories are those beeing stored in the base directory of the respective |FileManager| subclass. Folders with names starting with an underscore are ignored (use this for directories handling additional data files, if you like). Zipped directories, which can be unpacked on the fly, do also count as available directories: """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def currentdir(self) -> str: """Name of the current working directory containing the relevant files. To show most of the functionality of |property| |FileManager.currentdir| (unpacking zip files on the fly is explained in the documentation on function (|FileManager.zip_currentdir|), we first prepare a |FileManager| object corresponding to the |FileManager.basepath| `projectname/basename`: At first, the base directory is empty and asking for the current working directory results in the following error: Traceback (most recent call last): RuntimeError: The current working directory of the FileManager object \ has not been defined manually and cannot be determined automatically: \ If only one directory exists, it is considered as the current working directory automatically: 'dir1' |property| |FileManager.currentdir| memorises the name of the current working directory, even if another directory is later added to the base path: 'dir1' Set the value of |FileManager.currentdir| to |None| to let it forget the memorised directory. After that, asking for the current working directory now results in another error, as it is not clear which directory to select: Traceback (most recent call last): RuntimeError: The current working directory of the FileManager object \ has not been defined manually and cannot be determined automatically: \ (dir1 and dir2). Setting |FileManager.currentdir| manually solves the problem: 'dir1' Remove the current working directory `dir1` with the `del` statement: False |FileManager| subclasses can define a default directory name. When many directories exist and none is selected manually, the default directory is selected automatically. The following example shows an error message due to multiple directories without any having the default name: Traceback (most recent call last): RuntimeError: The current working directory of the FileManager object \ has not been defined manually and cannot be determined automatically: The \ default directory (dir3) is not among the available directories (dir1 and dir2). We can fix this by adding the required default directory manually: 'dir3' Setting the |FileManager.currentdir| to `dir4` not only overwrites the default name, but also creates the required folder: 'dir4' ['dir1', 'dir2', 'dir3', 'dir4'] Failed attempts in removing directories result in error messages like the following one: Traceback (most recent call last): AttributeError: While trying to delete the current working directory \ Then, the current working directory still exists and is remembered by |FileManager.currentdir|: 'dir4' ['dir1', 'dir2', 'dir3', 'dir4'] """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def currentpath(self) -> str: """Absolute path of the current working directory. """
return os.path.join(self.basepath, self.currentdir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filenames(self) -> List[str]: """Names of the files contained in the the current working directory. Files names starting with underscores are ignored: ['file1.txt', 'file2.npy'] """
return sorted( fn for fn in os.listdir(self.currentpath) if not fn.startswith('_'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def filepaths(self) -> List[str]: """Absolute path names of the files contained in the current working directory. Files names starting with underscores are ignored: """
path = self.currentpath return [os.path.join(path, name) for name in self.filenames]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def zip_currentdir(self) -> None: """Pack the current working directory in a `zip` file. |FileManager| subclasses allow for manual packing and automatic unpacking of working directories. The only supported format is `zip`. To avoid possible inconsistencies, origin directories and zip files are removed after packing or unpacking, respectively. As an example scenario, we prepare a |FileManager| object with the current working directory `folder` containing the files `test1.txt` and `text2.txt`: ['file1.txt', 'file2.txt'] The directories existing under the base path are identical with the ones returned by property |FileManager.availabledirs|: ['folder'] After packing the current working directory manually, it is still counted as a available directory: ['folder.zip'] Instead of the complete directory, only the contained files are packed: ['file1.txt', 'file2.txt'] The zip file is unpacked again, as soon as `folder` becomes the current working directory: ['folder'] ['file1.txt', 'file2.txt'] """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_files(self) -> selectiontools.Selections: """Read all network files of the current working directory, structure their contents in a |selectiontools.Selections| object, and return it. """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_file(self, filename): """Read and return the content of the given file. If the current directory is not defined explicitly, the directory name is constructed with the actual simulation start date. If such an directory does not exist, it is created immediately. """
_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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_file(self, filename, text): """Save the given text under the given condition filename and the current path. If the current directory is not defined explicitly, the directory name is constructed with the actual simulation end date. If such an directory does not exist, it is created immediately. """
_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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_file(self, sequence, array=None): """Write the date stored in |IOSequence.series| of the given |IOSequence| into an "external" data file. """
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_nkor_v1(self): """Adjust the given precipitation values. Required control parameters: |NHRU| |KG| Required input sequence: |Nied| Calculated flux sequence: |NKor| Basic equation: :math:`NKor = KG \\cdot Nied` Example: nkor(8.0, 10.0, 12.0) """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: 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.)))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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|: Note that the actual value of time dependend parameter |WfET0| is reduced due the difference between the given parameter and simulation time steps: 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: et0(1.6, 2.4, 1.96, 2.04) 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_evpo_v1(self): """Calculate land use and month specific values of potential evapotranspiration. Required control parameters: |NHRU| |Lnk| |FLn| Required derived parameter: |MOY| Required flux sequence: |ET0| Calculated flux sequence: |EvPo| Additional requirements: |Model.idx_sim| Basic equation: :math:`EvPo = FLn \\cdot ET0` Example: For clarity, this is more of a kind of an integration example. Parameter |FLn| both depends on time (the actual month) and space (the actual land use). Firstly, let us define a initialization time period spanning the transition from June to July: Secondly, assume that the considered subbasin is differenciated in two HRUs, one of primarily consisting of arable land and the other one of deciduous forests: Thirdly, set the |FLn| values, one for the relevant months and land use classes: Fourthly, the index array connecting the simulation time steps from the |pub| module. This can be done manually more conveniently via its update method: moy(5, 6) Finally, the actual method (with its simple equation) is applied as usual: evpo(2.598, 2.7) evpo(2.608, 2.73) Reset module |pub| to not interfere the following examples: """
con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess for k in range(con.nhru): flu.evpo[k] = con.fln[con.lnk[k]-1, der.moy[self.idx_sim]] * flu.et0[k]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: Define |KInz| values for July the selected land usages directly: 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): 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: inzp(1.5, 1.0, 0.0, 0.0, 0.0) 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: inzp(0.5, 0.5, 0.0, 0.0, 0.0) 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: inzp(0.6, 0.0, 0.0, 0.0, 0.0) 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: 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: 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: 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])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_wgtf_v1(self): """Calculate the potential snowmelt. Required control parameters: |NHRU| |Lnk| |GTF| |TRefT| |TRefN| |RSchmelz| |CPWasser| Required flux sequence: |TKor| Calculated fluxes sequence: |WGTF| Basic equation: :math:`WGTF = max(GTF \\cdot (TKor - TRefT), 0) + max(\\frac{CPWasser}{RSchmelz} \\cdot (TKor - TRefN), 0)` Examples: Initialize seven HRUs with identical degree-day factors and temperature thresholds, but different combinations of land use and air temperature: Compared to most other LARSIM parameters, the specific heat capacity and melt heat capacity of water can be seen as fixed properties: Note that the values of the degree-day factor are only half as much as the given value, due to the simulation step size being only half as long as the parameter step size: gtf(5.0) array([ 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5]) After performing the calculation, one can see that the potential melting rate is identical for the first two HRUs (|ACKER| and |LAUBW|). The land use class results in no difference, except for water areas (third and forth HRU, |FLUSS| and |SEE|), where no potential melt needs to be calculated. The last three HRUs (again |ACKER|) show the usual behaviour of the degree day method, when the actual temperature is below (fourth HRU), equal to (fifth HRU) or above (sixths zone) the threshold temperature. Additionally, the first two zones show the influence of the additional energy intake due to "warm" precipitation. Obviously, this additional term is quite negligible for common parameterizations, even if lower values for the separate threshold temperature |TRefT| would be taken into account: wgtf(5.012535, 5.012535, 0.0, 0.0, 0.0, 0.0, 2.5) """
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.))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_schm_wats_v1(self): """Calculate the actual amount of water melting within the snow cover. Required control parameters: |NHRU| |Lnk| Required flux sequences: |SBes| |WGTF| Calculated flux sequence: |Schm| Updated state sequence: |WATS| Basic equations: :math:`\\frac{dWATS}{dt} = SBes - Schm` :math:`Schm = \\Bigl \\lbrace { {WGTF \\ | \\ WATS > 0} \\atop {0 \\ | \\ WATS = 0} }` Examples: Initialize two water (|FLUSS| and |SEE|) and four arable land (|ACKER|) HRUs. Assume the same values for the initial amount of frozen water (|WATS|) and the frozen part of stand precipitation (|SBes|), but different values for potential snowmelt (|WGTF|): wats(0.0, 0.0, 3.0, 2.0, 0.0, 0.0) schm(0.0, 0.0, 0.0, 1.0, 3.0, 3.0) For the water areas, both the frozen amount of water and actual melt are set to zero. For all other land use classes, actual melt is either limited by potential melt or the available frozen water, which is the sum of initial frozen water and the frozen part of stand precipitation. """
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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qbb_v1(self): """Calculate the amount of base flow released from the soil. Required control parameters: |NHRU| |Lnk| |Beta| |FBeta| Required derived parameter: |WB| |WZ| Required state sequence: |BoWa| Calculated flux sequence: |QBB| Basic equations: :math:`Beta_{eff} = \\Bigl \\lbrace { {Beta \\ | \\ BoWa \\leq WZ} \\atop {Beta \\cdot (1+(FBeta-1)\\cdot\\frac{BoWa-WZ}{NFk-WZ}) \\|\\ BoWa > WZ} }` :math:`QBB = \\Bigl \\lbrace { {0 \\ | \\ BoWa \\leq WB} \\atop {Beta_{eff} \\cdot (BoWa - WB) \\|\\ BoWa > WB} }` Examples: For water and sealed areas, no base flow is calculated (see the first three HRUs of type |VERS|, |FLUSS|, and |SEE|). No principal distinction is made between the remaining land use classes (arable land |ACKER| has been selected for the last five HRUs arbitrarily): Note the time dependence of parameter |Beta|: beta(0.04) array([ 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02]) In the first example, the actual soil water content |BoWa| is set to low values. For values below the threshold |WB|, not percolation occurs. Above |WB| (but below |WZ|), |QBB| increases linearly by an amount defined by parameter |Beta|: qbb(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.2, 0.2) Note that for the last two HRUs the same amount of base flow generation is determined, in spite of the fact that both exhibit different relative soil moistures. It is common to modify this "pure absolute dependency" to a "mixed absolute/relative dependency" through defining the values of parameter |WB| indirectly via parameter |RelWB|. In the second example, the actual soil water content |BoWa| is set to high values. For values below threshold |WZ|, the discussion above remains valid. For values above |WZ|, percolation shows a nonlinear behaviour when factor |FBeta| is set to values larger than one: qbb(0.0, 0.0, 0.0, 1.0, 1.2, 1.866667, 3.6, 7.6) """
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]))))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qdb_v1(self): """Calculate direct runoff released from the soil. Required control parameters: |NHRU| |Lnk| |NFk| |BSf| Required state sequence: |BoWa| Required flux sequence: |WaDa| Calculated flux sequence: |QDB| Basic equations: :math:`QDB = \\Bigl \\lbrace { {max(Exz, 0) \\ | \\ SfA \\leq 0} \\atop {max(Exz + NFk \\cdot SfA^{BSf+1}, 0) \\ | \\ SfA > 0} }` :math:`SFA = (1 - \\frac{BoWa}{NFk})^\\frac{1}{BSf+1} - \\frac{WaDa}{(BSf+1) \\cdot NFk}` :math:`Exz = (BoWa + WaDa) - NFk` Examples: For water areas (|FLUSS| and |SEE|), sealed areas (|VERS|), and areas without any soil storage capacity, all water is completely routed as direct runoff |QDB| (see the first four HRUs). No principal distinction is made between the remaining land use classes (arable land |ACKER| has been selected for the last five HRUs arbitrarily): qdb(10.0, 10.0, 10.0, 10.0, 0.142039, 0.144959, 1.993649, 10.0, 10.1) With the common |BSf| value of 0.4, the discharge coefficient increases more or less exponentially with soil moisture. For soil moisture values slightly below zero or above usable field capacity, plausible amounts of generated direct runoff are ensured. """
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.)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_bowa_v1(self): """Update soil moisture and correct fluxes if necessary. Required control parameters: |NHRU| |Lnk| Required flux sequence: |WaDa| Updated state sequence: |BoWa| Required (and eventually corrected) flux sequences: |EvB| |QBB| |QIB1| |QIB2| |QDB| Basic equations: :math:`\\frac{dBoWa}{dt} = WaDa - EvB - QBB - QIB1 - QIB2 - QDB` :math:`BoWa \\geq 0` Examples: For water areas (|FLUSS| and |SEE|) and sealed areas (|VERS|), soil moisture |BoWa| is simply set to zero and no flux correction are performed (see the first three HRUs). No principal distinction is made between the remaining land use classes (arable land |ACKER| has been selected for the last four HRUs arbitrarily): bowa(0.0, 0.0, 0.0, 3.0, 1.5, 0.0, 0.0) evb(1.0, 1.0, 1.0, 0.0, 0.1, 0.2, 0.2) qbb(1.0, 1.0, 1.0, 0.0, 0.2, 0.4, 0.4) qib1(1.0, 1.0, 1.0, 0.0, 0.3, 0.6, 0.6) qib2(1.0, 1.0, 1.0, 0.0, 0.4, 0.8, 0.8) qdb(1.0, 1.0, 1.0, 0.0, 0.5, 1.0, 1.0) For the seventh HRU, the original total loss terms would result in a negative soil moisture value. Hence it is reduced to the total loss term of the sixt HRU, which results exactly in a complete emptying of the soil storage. """
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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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|: qbgz(5.0) The second example shows that large evaporation values above a HRU of type |SEE| can result in negative values of |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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qigz1_v1(self): """Aggregate the amount of the first interflow component released by all HRUs. Required control parameters: |NHRU| |FHRU| Required flux sequence: |QIB1| Calculated state sequence: |QIGZ1| Basic equation: :math:`QIGZ1 = \\Sigma(FHRU \\cdot QIB1)` Example: qigz1(2.0) """
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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qdgz_v1(self): """Aggregate the amount of total direct flow released by all HRUs. Required control parameters: |Lnk| |NHRU| |FHRU| Required flux sequence: |QDB| |NKor| |EvI| Calculated flux sequence: |QDGZ| Basic equation: :math:`QDGZ = \\Sigma(FHRU \\cdot QDB) + \\Sigma(FHRU \\cdot (NKor_{FLUSS}-EvI_{FLUSS}))` Examples: The first example shows that |QDGZ| is the area weighted sum of |QDB| from "land type" HRUs like arable land (|ACKER|) and sealed surfaces (|VERS|) as well as of |NKor|-|EvI| from water areas of type |FLUSS|. Water areas of type |WASSER| and |SEE| have no impact on |QDGZ|: qdgz(5.0) The second example shows that large evaporation values above a HRU of type |FLUSS| can result in negative values of |QDGZ|: qdgz(-3.0) """
con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess flu.qdgz = 0. for k in range(con.nhru): if con.lnk[k] == FLUSS: flu.qdgz += con.fhru[k]*(flu.nkor[k]-flu.evi[k]) elif con.lnk[k] not in (WASSER, SEE): flu.qdgz += con.fhru[k]*flu.qdb[k]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qdgz1_qdgz2_v1(self): """Seperate total direct flow into a small and a fast component. Required control parameters: |A1| |A2| Required flux sequence: |QDGZ| Calculated state sequences: |QDGZ1| |QDGZ2| Basic equation: :math:`QDGZ2 = \\frac{(QDGZ-A2)^2}{QDGZ+A1-A2}` :math:`QDGZ1 = QDGZ - QDGZ1` Examples: The formula for calculating the amount of the fast component of direct flow is borrowed from the famous curve number approach. Parameter |A2| would be the initial loss and parameter |A1| the maximum storage, but one should not take this analogy too serious. Instead, with the value of parameter |A1| set to zero, parameter |A2| just defines the maximum amount of "slow" direct runoff per time step: Let us set the value of |A2| to 4 mm/d, which is 2 mm/12h with respect to the selected simulation step size: a2(4.0) 2.0 Define a test function and let it calculate |QDGZ1| and |QDGZ1| for values of |QDGZ| ranging from -10 to 100 mm/12h: | ex. | qdgz | qdgz1 | qdgz2 | | 1 | -10.0 | -10.0 | 0.0 | | 2 | 0.0 | 0.0 | 0.0 | | 3 | 1.0 | 1.0 | 0.0 | | 4 | 2.0 | 2.0 | 0.0 | | 5 | 3.0 | 2.0 | 1.0 | | 6 | 100.0 | 2.0 | 98.0 | Setting |A2| to zero and |A1| to 4 mm/d (or 2 mm/12h) results in a smoother transition: | ex. | qdgz | qdgz1 | qdgz2 | | 1 | -10.0 | -10.0 | 0.0 | | 2 | 0.0 | 0.0 | 0.0 | | 3 | 1.0 | 0.666667 | 0.333333 | | 4 | 2.0 | 1.0 | 1.0 | | 5 | 3.0 | 1.2 | 1.8 | | 6 | 100.0 | 1.960784 | 98.039216 | Alternatively, one can mix these two configurations by setting the values of both parameters to 2 mm/h: | ex. | qdgz | qdgz1 | qdgz2 | | 1 | -10.0 | -10.0 | 0.0 | | 2 | 0.0 | 0.0 | 0.0 | | 3 | 1.0 | 1.0 | 0.0 | | 4 | 2.0 | 1.5 | 0.5 | | 5 | 3.0 | 1.666667 | 1.333333 | | 6 | 100.0 | 1.99 | 98.01 | Note the similarity of the results for very high values of total direct flow |QDGZ| in all three examples, which converge to the sum of the values of parameter |A1| and |A2|, representing the maximum value of `slow` direct flow generation per simulation step """
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: qbga(3.800054) First extreme test case (zero division is circumvented): qbga(4.0) Second extreme test case (numerical overflow is circumvented): 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qiga1_v1(self): """Perform the runoff concentration calculation for the first interflow component. 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: |KI1| Required state sequence: |QIGZ1| Calculated state sequence: |QIGA1| Basic equation: :math:`QIGA1_{neu} = QIGA1_{alt} + (QIGZ1_{alt}-QIGA1_{alt}) \\cdot (1-exp(-KI1^{-1})) + (QIGZ1_{neu}-QIGZ1_{alt}) \\cdot (1-KI1\\cdot(1-exp(-KI1^{-1})))` Examples: A normal test case: qiga1(3.800054) First extreme test case (zero division is circumvented): qiga1(4.0) Second extreme test case (numerical overflow is circumvented): qiga1(5.0) """
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qiga2_v1(self): """Perform the runoff concentration calculation for the second interflow component. 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: |KI2| Required state sequence: |QIGZ2| Calculated state sequence: |QIGA2| Basic equation: :math:`QIGA2_{neu} = QIGA2_{alt} + (QIGZ2_{alt}-QIGA2_{alt}) \\cdot (1-exp(-KI2^{-1})) + (QIGZ2_{neu}-QIGZ2_{alt}) \\cdot (1-KI2\\cdot(1-exp(-KI2^{-1})))` Examples: A normal test case: qiga2(3.800054) First extreme test case (zero division is circumvented): qiga2(4.0) Second extreme test case (numerical overflow is circumvented): qiga2(5.0) """
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: qdga1(3.800054) First extreme test case (zero division is circumvented): qdga1(4.0) Second extreme test case (numerical overflow is circumvented): 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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qdga2_v1(self): """Perform the runoff concentration calculation for "fast" 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: |KD2| Required state sequence: |QDGZ2| Calculated state sequence: |QDGA2| Basic equation: :math:`QDGA2_{neu} = QDGA2_{alt} + (QDGZ2_{alt}-QDGA2_{alt}) \\cdot (1-exp(-KD2^{-1})) + (QDGZ2_{neu}-QDGZ2_{alt}) \\cdot (1-KD2\\cdot(1-exp(-KD2^{-1})))` Examples: A normal test case: qdga2(3.800054) First extreme test case (zero division is circumvented): qdga2(4.0) Second extreme test case (numerical overflow is circumvented): qdga2(5.0) """
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))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_q_v1(self): """Calculate the final runoff. Note that, in case there are water areas, their |NKor| values are added and their |EvPo| values are subtracted from the "potential" runoff value, if possible. This hold true for |WASSER| only and is due to compatibility with the original LARSIM implementation. Using land type |WASSER| can result in problematic modifications of simulated runoff series. It seems advisable to use land type |FLUSS| and/or land type |SEE| instead. Required control parameters: |NHRU| |FHRU| |Lnk| |NegQ| Required flux sequence: |NKor| Updated flux sequence: |EvI| Required state sequences: |QBGA| |QIGA1| |QIGA2| |QDGA1| |QDGA2| Calculated flux sequence: |lland_fluxes.Q| Basic equations: :math:`Q = QBGA + QIGA1 + QIGA2 + QDGA1 + QDGA2 + NKor_{WASSER} - EvI_{WASSER}` :math:`Q \\geq 0` Examples: When there are no water areas in the respective subbasin (we choose arable land |ACKER| arbitrarily), the different runoff components are simply summed up: q(2.5) evi(4.0, 5.0, 3.0) The defined values of interception evaporation do not show any impact on the result of the given example, the predefined values for sequence |EvI| remain unchanged. But when the first HRU is assumed to be a water area (|WASSER|), its adjusted precipitaton |NKor| value and its interception evaporation |EvI| value are added to and subtracted from |lland_fluxes.Q| respectively: q(5.5) evi(4.0, 5.0, 3.0) Note that only 5 mm are added (instead of the |NKor| value 10 mm) and that only 2 mm are substracted (instead of the |EvI| value 4 mm, as the first HRU`s area only accounts for 50 % of the subbasin area. Setting also the land use class of the second HRU to land type |WASSER| and resetting |NKor| to zero would result in overdrying. To avoid this, both actual water evaporation values stored in sequence |EvI| are reduced by the same factor: q(0.0) evi(3.333333, 4.166667, 3.0) The handling from water areas of type |FLUSS| and |SEE| differs from those of type |WASSER|, as these do receive their net input before the runoff concentration routines are applied. This should be more realistic in most cases (especially for type |SEE| representing lakes not direct connected to the stream network). But it could sometimes result in negative outflow values. This is avoided by simply setting |lland_fluxes.Q| to zero and adding the truncated negative outflow value to the |EvI| value of all HRUs of type |FLUSS| and |SEE|: q(0.0) evi(2.571429, 3.571429, 3.0) This adjustment of |EvI| is only correct regarding the total water balance. Neither spatial nor temporal consistency of the resulting |EvI| values are assured. In the most extreme case, even negative |EvI| values might occur. This seems acceptable, as long as the adjustment of |EvI| is rarely triggered. When in doubt about this, check sequences |EvPo| and |EvI| of HRUs of types |FLUSS| and |SEE| for possible discrepancies. Also note that there might occur unnecessary corrections of |lland_fluxes.Q| in case landtype |WASSER| is combined with either landtype |SEE| or |FLUSS|. Eventually you might want to avoid correcting |lland_fluxes.Q|. This can be achieved by setting parameter |NegQ| to `True`: q(-1.0) evi(4.0, 5.0, 3.0) """
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.
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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`: Low discharge example (linear interpolation between the first two supporting point pairs): outputs(branch1=1.0, branch2=0.0) Medium discharge example (linear interpolation between the second two supporting point pairs): outputs(branch1=2.0, branch2=1.0) High discharge example (linear extrapolation beyond the second two supporting point pairs): outputs(branch1=2.0, branch2=3.0) Non-monotonous relationships and balance violations are allowed, e.g.: 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])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pass_outputs_v1(self): """Updates |Branched| based on |Outputs|."""
der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess for bdx in range(der.nmbbranches): out.branched[bdx][0] += flu.outputs[bdx]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """Connect the |LinkSequence| instances handled by the actual model to the |NodeSequence| instances handled by one inlet node and multiple oulet nodes. The HydPy-H-Branch model passes multiple output values to different outlet nodes. This requires additional information regarding the `direction` of each output value. Therefore, node names are used as keywords. Assume the discharge values of both nodes `inflow1` and `inflow2` shall be branched to nodes `outflow1` and `outflow2` via element `branch`: Then parameter |YPoints| relates different supporting points via its keyword arguments to the respective nodes: After connecting the model with its element the total discharge value of nodes `inflow1` and `inflow2` can be properly divided: sim(2.0) sim(4.0) In case of missing (or misspelled) outlet nodes, the following error is raised: Traceback (most recent call last): RuntimeError: Model `hbranch` of element `branch` tried to connect \ to an outlet node named `outflow1`, which is not an available outlet node \ of element `branch`. """
nodes = self.element.inlets total = self.sequences.inlets.total if total.shape != (len(nodes),): total.shape = len(nodes) for idx, node in enumerate(nodes): double = node.get_double('inlets') total.set_pointer(double, idx) for (idx, name) in enumerate(self.nodenames): try: outlet = getattr(self.element.outlets, name) double = outlet.get_double('outlets') except AttributeError: raise RuntimeError( f'Model {objecttools.elementphrase(self)} tried ' f'to connect to an outlet node named `{name}`, ' f'which is not an available outlet node of element ' f'`{self.element.name}`.') self.sequences.outlets.branched.set_pointer(double, idx)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """Determine the number of response functions. nmb(2) Note that updating parameter `nmb` sets the shape of the flux sequences |QPIn|, |QPOut|, |QMA|, and |QAR| automatically. qpin(nan, nan) qpout(nan, nan) qma(nan, nan) qar(nan, nan) """
pars = self.subpars.pars responses = pars.control.responses fluxes = pars.model.sequences.fluxes self(len(responses)) fluxes.qpin.shape = self.value fluxes.qpout.shape = self.value fluxes.qma.shape = self.value fluxes.qar.shape = self.value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """Determine the total number of AR coefficients. ar_order(2, 1) """
responses = self.subpars.pars.control.responses self.shape = len(responses) self(responses.ar_orders)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """Determine all AR coefficients. ar_coefs([[1.0, 2.0], [1.0, nan]]) Note that updating parameter `ar_coefs` sets the shape of the log sequence |LogOut| automatically. logout([[nan, nan], [nan, nan]]) """
pars = self.subpars.pars coefs = pars.control.responses.ar_coefs self.shape = coefs.shape self(coefs) pars.model.sequences.logs.logout.shape = self.shape
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """Determine all MA coefficients. ma_coefs([[1.0, nan, nan], [1.0, 2.0, 3.0]]) Note that updating parameter `ar_coefs` sets the shape of the log sequence |LogIn| automatically. login([[nan, nan, nan], [nan, nan, nan]]) """
pars = self.subpars.pars coefs = pars.control.responses.ma_coefs self.shape = coefs.shape self(coefs) pars.model.sequences.logs.login.shape = self.shape
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)}`.')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. You can pass both |Node| and |Element| objects and, optionally, the name of the newly created |Selection| object: 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")) Selection("UPSTREAM", nodes="lahn_1", elements=("land_lahn_1", "stream_lahn_1_lahn_2")) Wrong device specifications result in errors like the following: 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`. 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|: 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|: Selection("complete", nodes="lahn_3", elements=("land_lahn_3", "stream_lahn_2_lahn_3")) If necessary, include the "outlet device" manually afterwards: 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}`')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select_upstream(self, device: devicetools.Device) -> 'Selection': """Restrict the current selection to the network upstream of the given starting point, including the starting point itself. See the documentation on method |Selection.search_upstream| for additional information. """
upstream = self.search_upstream(device) self.nodes = upstream.nodes self.elements = upstream.elements return self
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. You can pass both |Model| objects and names and, as a keyword argument, the name of the newly created |Selection| object: Selection("modeltypes", nodes=(), elements=("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3")) 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: 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|: 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|: 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}`')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. Pass the (sub)strings as positional arguments and, optionally, the name of the newly created |Selection| object as a keyword argument: Selection("nodenames", nodes=("dill", "lahn_1"), elements=()) Wrong string specifications result in errors like the following: 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|: 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|: 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}`')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. Pass the (sub)strings as positional arguments and, optionally, the name of the newly created |Selection| object as a keyword argument: 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: 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|: 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|: 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}`')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self, name: str) -> 'Selection': """Return a new |Selection| object with the given name and copies of the handles |Nodes| and |Elements| objects based on method |Devices.copy|."""
return type(self)(name, copy.copy(self.nodes), copy.copy(self.elements))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_networkfile(self, filepath: Union[str, None] = None, write_nodes: bool = True) -> None: """Save the selection as a network file. 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`: # -*- 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> # -*- 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: Define the maximum discharge value of the respective response functions and their successive differences: The first six examples are performed for inflow values ranging from 0 to 12 m³/s: | 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: | 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.)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_login_v1(self): """Refresh the input log sequence for the different MA processes. Required derived parameters: |Nmb| |MA_Order| Required flux sequence: |QPIn| Updated log sequence: |LogIn| Example: Assume there are three response functions, involving one, two and three MA coefficients respectively: The "memory values" of the different MA processes are defined as follows (one row for each process): These are the new inflow discharge portions to be included into the memories of the different processes: Through applying method |calc_login_v1| all values already existing are shifted to the right ("into the past"). Values, which are no longer required due to the limited order or the different MA processes, are discarded. The new values are inserted in the first column: login([[7.0, nan, nan], [8.0, 2.0, nan], [9.0, 4.0, 5.0]]) """
der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(der.nmb): for jdx in range(der.ma_order[idx]-2, -1, -1): log.login[idx, jdx+1] = log.login[idx, jdx] for idx in range(der.nmb): log.login[idx, 0] = flu.qpin[idx]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qma_v1(self): """Calculate the discharge responses of the different MA processes. Required derived parameters: |Nmb| |MA_Order| |MA_Coefs| Required log sequence: |LogIn| Calculated flux sequence: |QMA| Examples: Assume there are three response functions, involving one, two and three MA coefficients respectively: The coefficients of the different MA processes are stored in separate rows of the 2-dimensional parameter `ma_coefs`: The "memory values" of the different MA processes are defined as follows (one row for each process). The current values are stored in first column, the values of the last time step in the second column, and so on: Applying method |calc_qma_v1| is equivalent to calculating the inner product of the different rows of both matrices: qma(1.0, 2.2, 4.7) """
der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(der.nmb): flu.qma[idx] = 0. for jdx in range(der.ma_order[idx]): flu.qma[idx] += der.ma_coefs[idx, jdx] * log.login[idx, jdx]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: 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: 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: Applying method |calc_qar_v1| is equivalent to calculating the inner product of the different rows of both matrices: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_qpout_v1(self): """Calculate the ARMA results for the different response functions. Required derived parameter: |Nmb| Required flux sequences: |QMA| |QAR| Calculated flux sequence: |QPOut| Examples: Initialize an arma model with three different response functions: Define the output values of the MA and of the AR processes associated with the three response functions and apply method |calc_qpout_v1|: qpout(5.0, 7.0, 9.0) """
der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess for idx in range(der.nmb): flu.qpout[idx] = flu.qma[idx]+flu.qar[idx]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def calc_logout_v1(self): """Refresh the log sequence for the different AR processes. Required derived parameters: |Nmb| |AR_Order| Required flux sequence: |QPOut| Updated log sequence: |LogOut| Example: Assume there are four response functions, involving zero, one, two and three AR coefficients respectively: The "memory values" of the different AR processes are defined as follows (one row for each process). Note the special case of the first AR process of zero order (first row), which is why there are no autoregressive memory values required: These are the new outflow discharge portions to be included into the memories of the different processes: Through applying method |calc_logout_v1| all values already existing are shifted to the right ("into the past"). Values, which are no longer required due to the limited order or the different AR processes, are discarded. The new values are inserted in the first column: logout([[nan, nan, nan], [7.0, nan, nan], [8.0, 1.0, nan], [9.0, 3.0, 4.0]]) """
der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(der.nmb): for jdx in range(der.ar_order[idx]-2, -1, -1): log.logout[idx, jdx+1] = log.logout[idx, jdx] for idx in range(der.nmb): if der.ar_order[idx] > 0: log.logout[idx, 0] = flu.qpout[idx]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: Define the output values of the three response functions and apply method |calc_qout_v1|: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """Determine the number of branches"""
con = self.subpars.pars.control self(con.ypoints.shape[0])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """Update value based on the actual |calc_qg_v1| method. Required derived parameter: |H| Note that the value of parameter |lstream_derived.QM| is directly related to the value of parameter |HM| and indirectly related to all parameters values relevant for method |calc_qg_v1|. Hence the complete paramter (and sequence) requirements might differ for various application models. For examples, see the documentation on method ToDo. """
mod = self.subpars.pars.model con = mod.parameters.control flu = mod.sequences.fluxes flu.h = con.hm mod.calc_qg() self(flu.qg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self): """Determines in how many segments the whole reach needs to be divided to approximate the desired lag time via integer rounding. Adjusts the shape of sequence |QJoints| additionally. Required control parameters: |Lag| Calculated derived parameters: |NmbSegments| Prepared state sequence: |QJoints| Examples: Define a lag time of 1.4 days and a simulation step size of 12 hours: Then the actual lag value for the simulation step size is 2.8 lag(1.4) 2.8 Through rounding the number of segments is determined: nmbsegments(3) The number of joints is always the number of segments plus one: (4,) """
pars = self.subpars.pars self(int(round(pars.control.lag))) pars.model.sequences.states.qjoints.shape = self+1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def gather_registries() -> Tuple[Dict, Mapping, Mapping]: """Get and clear the current |Node| and |Element| registries. Function |gather_registries| is thought to be used by class |Tester| only. """
id2devices = copy.copy(_id2devices) registry = copy.copy(_registry) selection = copy.copy(_selection) dict_ = globals() dict_['_id2devices'] = {} dict_['_registry'] = {Node: {}, Element: {}} dict_['_selection'] = {Node: {}, Element: {}} return id2devices, registry, selection
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def startswith(self, name: str) -> List[str]: """Return a list of all keywords starting with the given string. ['keyword_3', 'keyword_4'] """
return sorted(keyword for keyword in self if keyword.startswith(name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def endswith(self, name: str) -> List[str]: """Return a list of all keywords ending with the given string. ['first_keyword', 'second_keyword'] """
return sorted(keyword for keyword in self if keyword.endswith(name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contains(self, name: str) -> List[str]: """Return a list of all keywords containing the given string. ['first_keyword', 'keyword_3', 'keyword_4', 'second_keyword'] """
return sorted(keyword for keyword in self if name in keyword)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update(self, *names: Any) -> None: """Before updating, the given names are checked to be valid variable identifiers. 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 \ Note that even the first string (`test1`) is not added due to the second one (`test 2`) being invalid. Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4", "second_keyword") After correcting the second string, everything works fine: Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4", "second_keyword", "test_1", "test_2") """
_names = [str(name) for name in names] self._check_keywords(_names) super().update(_names)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add(self, name: Any) -> None: """Before adding a new name, it is checked to be valid variable identifiers. Traceback (most recent call last): ValueError: While trying to add the keyword `1_test` to device ?, \ the following error occurred: The given name string `1_test` does not \ Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4", "second_keyword") After correcting the string, everything works fine: Keywords("first_keyword", "keyboard", "keyword_3", "keyword_4", "one_test", "second_keyword") """
self._check_keywords([str(name)]) super().add(str(name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_device(self, device: Union[DeviceType, str]) -> None: """Add the given |Node| or |Element| object to the actual |Nodes| or |Elements| object. You can pass either a string or a device: Nodes("old_node") Nodes("new_node", "old_node") Method |Devices.add_device| is disabled for immutable |Nodes| and |Elements| objects: Traceback (most recent call last): RuntimeError: While trying to add the device `newest_node` to a \ Nodes object, the following error occurred: Adding devices to immutable \ Nodes objects is not allowed. """
try: if self.mutable: _device = self.get_contentclass()(device) self._name2device[_device.name] = _device _id2devices[_device][id(self)] = self else: raise RuntimeError( f'Adding devices to immutable ' f'{objecttools.classname(self)} objects is not allowed.') except BaseException: objecttools.augment_excmessage( f'While trying to add the device `{device}` to a ' f'{objecttools.classname(self)} object')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_device(self, device: Union[DeviceType, str]) -> None: """Remove the given |Node| or |Element| object from the actual |Nodes| or |Elements| object. You can pass either a string or a device: Nodes("node_x") Nodes() Traceback (most recent call last): ValueError: While trying to remove the device `node_z` from a \ Nodes object, the following error occurred: The actual Nodes object does \ not handle such a device. Method |Devices.remove_device| is disabled for immutable |Nodes| and |Elements| objects: Traceback (most recent call last): RuntimeError: While trying to remove the device `node_z` from a \ Nodes object, the following error occurred: Removing devices from \ immutable Nodes objects is not allowed. """
try: if self.mutable: _device = self.get_contentclass()(device) try: del self._name2device[_device.name] except KeyError: raise ValueError( f'The actual {objecttools.classname(self)} ' f'object does not handle such a device.') del _id2devices[_device][id(self)] else: raise RuntimeError( f'Removing devices from immutable ' f'{objecttools.classname(self)} objects is not allowed.') except BaseException: objecttools.augment_excmessage( f'While trying to remove the device `{device}` from a ' f'{objecttools.classname(self)} object')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keywords(self) -> Set[str]: """A set of all keywords of all handled devices. In addition to attribute access via device names, |Nodes| and |Elements| objects allow for attribute access via keywords, allowing for an efficient search of certain groups of devices. Let us use the example from above, where the nodes `na` and `nb` have no keywords, but each of the other three nodes both belongs to either `group_a` or `group_b` and `group_1` or `group_2`: Nodes("na", "nb", "nc", "nd", "ne") ['group_1', 'group_2', 'group_a', 'group_b'] If you are interested in inspecting all devices belonging to `group_a`, select them via this keyword: Nodes("nc", "ne") You can further restrict the search by also selecting the devices belonging to `group_b`, which holds only for node "e", in the given example: Node("ne", variable="Q", keywords=["group_1", "group_b"]) Note that the keywords already used for building a device subgroup are not informative anymore (as they hold for each device) and are thus not shown anymore: ['group_a', 'group_b'] The latter might be confusing if you intend to work with a device subgroup for a longer time. After copying the subgroup, all keywords of the contained devices are available again: ['group_1', 'group_a', 'group_b'] """
return set(keyword for device in self for keyword in device.keywords if keyword not in self._shadowed_keywords)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self: DevicesTypeBound) -> DevicesTypeBound: """Return a shallow copy of the actual |Nodes| or |Elements| object. Method |Devices.copy| returns a semi-flat copy of |Nodes| or |Elements| objects, due to their devices being not copyable: True False False True Changing the |Device.name| of a device is recognised both by the original and the copied collection objects: Node("z", variable="Q") Node("z", variable="Q") Deep copying is permitted due to the above reason: Traceback (most recent call last): NotImplementedError: Deep copying of Nodes objects is not supported, \ as it would require to make deep copies of the Node objects themselves, \ which is in conflict with using their names as identifiers. """
new = type(self)() vars(new).update(vars(self)) vars(new)['_name2device'] = copy.copy(self._name2device) vars(new)['_shadowed_keywords'].clear() for device in self: _id2devices[device][id(new)] = new return new
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_allseries(self, ramflag: bool = True) -> None: """Call methods |Node.prepare_simseries| and |Node.prepare_obsseries|."""
self.prepare_simseries(ramflag) self.prepare_obsseries(ramflag)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_simseries(self, ramflag: bool = True) -> None: """Call method |Node.prepare_simseries| of all handled |Node| objects."""
for node in printtools.progressbar(self): node.prepare_simseries(ramflag)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare_obsseries(self, ramflag: bool = True) -> None: """Call method |Node.prepare_obsseries| of all handled |Node| objects."""
for node in printtools.progressbar(self): node.prepare_obsseries(ramflag)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_models(self) -> None: """Call method |Element.init_model| of all handle |Element| objects. We show, based the `LahnH` example project, that method |Element.init_model| prepares the |Model| objects of all elements, including building the required connections and updating the derived parameters: dt(0.000833) Wrong control files result in error messages like the following: Traceback (most recent call last): ValueError: While trying to initialise the model object of element \ `land_dill`, the following error occurred: While trying to load the control \ parameter `zonetype` of element `?` is not valid. By default, missing control files result in exceptions: Traceback (most recent call last): FileNotFoundError: While trying to initialise the model object of \ element `land_dill`, the following error occurred: While trying to load the \ False When building new, still incomplete *HydPy* projects, this behaviour can be annoying. After setting the option |Options.warnmissingcontrolfile| to |False|, missing control files only result in a warning: Traceback (most recent call last): UserWarning: Due to a missing or no accessible control file, \ no model could be initialised for element `land_dill` False """
try: for element in printtools.progressbar(self): element.init_model(clear_registry=False) finally: hydpy.pub.controlmanager.clear_registry()