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