text
stringlengths
81
112k
Delete the coefficients of the pure MA model and also all MA and AR coefficients of the ARMA model. Also calculate or delete the values of all secondary iuh parameters, depending on the completeness of the values of the primary parameters. def update(self): """Delete the coefficients of the pure MA model and also all MA and AR coefficients of the ARMA model. Also calculate or delete the values of all secondary iuh parameters, depending on the completeness of the values of the primary parameters. """ del self.ma.coefs del self.arma.ma_coefs del self.arma.ar_coefs if self.primary_parameters_complete: self.calc_secondary_parameters() else: for secpar in self._SECONDARY_PARAMETERS.values(): secpar.__delete__(self)
A tuple of two numpy arrays, which hold the time delays and the associated iuh values respectively. def delay_response_series(self): """A tuple of two numpy arrays, which hold the time delays and the associated iuh values respectively.""" delays = [] responses = [] sum_responses = 0. for t in itertools.count(self.dt_response/2., self.dt_response): delays.append(t) response = self(t) responses.append(response) sum_responses += self.dt_response*response if (sum_responses > .9) and (response < self.smallest_response): break return numpy.array(delays), numpy.array(responses)
Plot the instanteneous unit hydrograph. The optional argument allows for defining a threshold of the cumulative sum uf the hydrograph, used to adjust the largest value of the x-axis. It must be a value between zero and one. def plot(self, threshold=None, **kwargs): """Plot the instanteneous unit hydrograph. The optional argument allows for defining a threshold of the cumulative sum uf the hydrograph, used to adjust the largest value of the x-axis. It must be a value between zero and one. """ delays, responses = self.delay_response_series pyplot.plot(delays, responses, **kwargs) pyplot.xlabel('time') pyplot.ylabel('response') if threshold is not None: threshold = numpy.clip(threshold, 0., 1.) cumsum = numpy.cumsum(responses) idx = numpy.where(cumsum >= threshold*cumsum[-1])[0][0] pyplot.xlim(0., delays[idx])
The first time delay weighted statistical moment of the instantaneous unit hydrograph. def moment1(self): """The first time delay weighted statistical moment of the instantaneous unit hydrograph.""" delays, response = self.delay_response_series return statstools.calc_mean_time(delays, response)
The second time delay weighted statistical momens of the instantaneous unit hydrograph. def moment2(self): """The second time delay weighted statistical momens of the instantaneous unit hydrograph.""" moment1 = self.moment1 delays, response = self.delay_response_series return statstools.calc_mean_time_deviation( delays, response, moment1)
Determine the values of the secondary parameters `a` and `b`. def calc_secondary_parameters(self): """Determine the values of the secondary parameters `a` and `b`.""" self.a = self.x/(2.*self.d**.5) self.b = self.u/(2.*self.d**.5)
Determine the value of the secondary parameter `c`. def calc_secondary_parameters(self): """Determine the value of the secondary parameter `c`.""" self.c = 1./(self.k*special.gamma(self.n))
Trim values in accordance with :math:`WAeS \\leq PWMax \\cdot WATS`, or at least in accordance with if :math:`WATS \\geq 0`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(7) >>> pwmax(2.0) >>> states.waes = -1., 0., 1., -1., 5., 10., 20. >>> states.wats(-1., 0., 0., 5., 5., 5., 5.) >>> states.wats wats(0.0, 0.0, 0.5, 5.0, 5.0, 5.0, 10.0) def trim(self, lower=None, upper=None): """Trim values in accordance with :math:`WAeS \\leq PWMax \\cdot WATS`, or at least in accordance with if :math:`WATS \\geq 0`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(7) >>> pwmax(2.0) >>> states.waes = -1., 0., 1., -1., 5., 10., 20. >>> states.wats(-1., 0., 0., 5., 5., 5., 5.) >>> states.wats wats(0.0, 0.0, 0.5, 5.0, 5.0, 5.0, 10.0) """ pwmax = self.subseqs.seqs.model.parameters.control.pwmax waes = self.subseqs.waes if lower is None: lower = numpy.clip(waes/pwmax, 0., numpy.inf) lower[numpy.isnan(lower)] = 0.0 lland_sequences.State1DSequence.trim(self, lower, upper)
Trim values in accordance with :math:`WAeS \\leq PWMax \\cdot WATS`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(7) >>> pwmax(2.) >>> states.wats = 0., 0., 0., 5., 5., 5., 5. >>> states.waes(-1., 0., 1., -1., 5., 10., 20.) >>> states.waes waes(0.0, 0.0, 0.0, 0.0, 5.0, 10.0, 10.0) def trim(self, lower=None, upper=None): """Trim values in accordance with :math:`WAeS \\leq PWMax \\cdot WATS`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(7) >>> pwmax(2.) >>> states.wats = 0., 0., 0., 5., 5., 5., 5. >>> states.waes(-1., 0., 1., -1., 5., 10., 20.) >>> states.waes waes(0.0, 0.0, 0.0, 0.0, 5.0, 10.0, 10.0) """ pwmax = self.subseqs.seqs.model.parameters.control.pwmax wats = self.subseqs.wats if upper is None: upper = pwmax*wats lland_sequences.State1DSequence.trim(self, lower, upper)
Trim values in accordance with :math:`BoWa \\leq NFk`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(5) >>> nfk(200.) >>> states.bowa(-100.,0., 100., 200., 300.) >>> states.bowa bowa(0.0, 0.0, 100.0, 200.0, 200.0) def trim(self, lower=None, upper=None): """Trim values in accordance with :math:`BoWa \\leq NFk`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> nhru(5) >>> nfk(200.) >>> states.bowa(-100.,0., 100., 200., 300.) >>> states.bowa bowa(0.0, 0.0, 100.0, 200.0, 200.0) """ if upper is None: upper = self.subseqs.seqs.model.parameters.control.nfk lland_sequences.State1DSequence.trim(self, lower, upper)
Clean the data and save opening hours in the database. Old opening hours are purged before new ones are saved. def post(self, request, pk): """ Clean the data and save opening hours in the database. Old opening hours are purged before new ones are saved. """ location = self.get_object() # open days, disabled widget data won't make it into request.POST present_prefixes = [x.split('-')[0] for x in request.POST.keys()] day_forms = OrderedDict() for day_no, day_name in WEEKDAYS: for slot_no in (1, 2): prefix = self.form_prefix(day_no, slot_no) # skip closed day as it would be invalid form due to no data if prefix not in present_prefixes: continue day_forms[prefix] = (day_no, Slot(request.POST, prefix=prefix)) if all([day_form[1].is_valid() for pre, day_form in day_forms.items()]): OpeningHours.objects.filter(company=location).delete() for prefix, day_form in day_forms.items(): day, form = day_form opens, shuts = [str_to_time(form.cleaned_data[x]) for x in ('opens', 'shuts')] if opens != shuts: OpeningHours(from_hour=opens, to_hour=shuts, company=location, weekday=day).save() return redirect(request.path_info)
Initialize the editing form 1. Build opening_hours, a lookup dictionary to populate the form slots: keys are day numbers, values are lists of opening hours for that day. 2. Build days, a list of days with 2 slot forms each. 3. Build form initials for the 2 slots padding/trimming opening_hours to end up with exactly 2 slots even if it's just None values. def get(self, request, pk): """ Initialize the editing form 1. Build opening_hours, a lookup dictionary to populate the form slots: keys are day numbers, values are lists of opening hours for that day. 2. Build days, a list of days with 2 slot forms each. 3. Build form initials for the 2 slots padding/trimming opening_hours to end up with exactly 2 slots even if it's just None values. """ location = self.get_object() two_sets = False closed = None opening_hours = {} for o in OpeningHours.objects.filter(company=location): opening_hours.setdefault(o.weekday, []).append(o) days = [] for day_no, day_name in WEEKDAYS: if day_no not in opening_hours.keys(): if opening_hours: closed = True ini1, ini2 = [None, None] else: closed = False ini = [{'opens': time_to_str(oh.from_hour), 'shuts': time_to_str(oh.to_hour)} for oh in opening_hours[day_no]] ini += [None] * (2 - len(ini[:2])) # pad ini1, ini2 = ini[:2] # trim if ini2: two_sets = True days.append({ 'name': day_name, 'number': day_no, 'slot1': Slot(prefix=self.form_prefix(day_no, 1), initial=ini1), 'slot2': Slot(prefix=self.form_prefix(day_no, 2), initial=ini2), 'closed': closed }) return render(request, self.template_name, { 'days': days, 'two_sets': two_sets, 'location': location, })
Apply the routing equation. Required derived parameters: |NmbSegments| |C1| |C2| |C3| Updated state sequence: |QJoints| Basic equation: :math:`Q_{space+1,time+1} = c1 \\cdot Q_{space,time+1} + c2 \\cdot Q_{space,time} + c3 \\cdot Q_{space+1,time}` Examples: Firstly, define a reach divided into four segments: >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> derived.nmbsegments(4) >>> states.qjoints.shape = 5 Zero damping is achieved through the following coefficients: >>> derived.c1(0.0) >>> derived.c2(1.0) >>> derived.c3(0.0) For initialization, assume a base flow of 2m³/s: >>> states.qjoints.old = 2.0 >>> states.qjoints.new = 2.0 Through successive assignements of different discharge values to the upper junction one can see that these discharge values are simply shifted from each junction to the respective lower junction at each time step: >>> states.qjoints[0] = 5.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(5.0, 2.0, 2.0, 2.0, 2.0) >>> states.qjoints[0] = 8.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(8.0, 5.0, 2.0, 2.0, 2.0) >>> states.qjoints[0] = 6.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(6.0, 8.0, 5.0, 2.0, 2.0) With the maximum damping allowed, the values of the derived parameters are: >>> derived.c1(0.5) >>> derived.c2(0.0) >>> derived.c3(0.5) Assuming again a base flow of 2m³/s and the same input values results in: >>> states.qjoints.old = 2.0 >>> states.qjoints.new = 2.0 >>> states.qjoints[0] = 5.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(5.0, 3.5, 2.75, 2.375, 2.1875) >>> states.qjoints[0] = 8.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(8.0, 5.75, 4.25, 3.3125, 2.75) >>> states.qjoints[0] = 6.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(6.0, 5.875, 5.0625, 4.1875, 3.46875) def calc_qjoints_v1(self): """Apply the routing equation. Required derived parameters: |NmbSegments| |C1| |C2| |C3| Updated state sequence: |QJoints| Basic equation: :math:`Q_{space+1,time+1} = c1 \\cdot Q_{space,time+1} + c2 \\cdot Q_{space,time} + c3 \\cdot Q_{space+1,time}` Examples: Firstly, define a reach divided into four segments: >>> from hydpy.models.hstream import * >>> parameterstep('1d') >>> derived.nmbsegments(4) >>> states.qjoints.shape = 5 Zero damping is achieved through the following coefficients: >>> derived.c1(0.0) >>> derived.c2(1.0) >>> derived.c3(0.0) For initialization, assume a base flow of 2m³/s: >>> states.qjoints.old = 2.0 >>> states.qjoints.new = 2.0 Through successive assignements of different discharge values to the upper junction one can see that these discharge values are simply shifted from each junction to the respective lower junction at each time step: >>> states.qjoints[0] = 5.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(5.0, 2.0, 2.0, 2.0, 2.0) >>> states.qjoints[0] = 8.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(8.0, 5.0, 2.0, 2.0, 2.0) >>> states.qjoints[0] = 6.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(6.0, 8.0, 5.0, 2.0, 2.0) With the maximum damping allowed, the values of the derived parameters are: >>> derived.c1(0.5) >>> derived.c2(0.0) >>> derived.c3(0.5) Assuming again a base flow of 2m³/s and the same input values results in: >>> states.qjoints.old = 2.0 >>> states.qjoints.new = 2.0 >>> states.qjoints[0] = 5.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(5.0, 3.5, 2.75, 2.375, 2.1875) >>> states.qjoints[0] = 8.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(8.0, 5.75, 4.25, 3.3125, 2.75) >>> states.qjoints[0] = 6.0 >>> model.calc_qjoints_v1() >>> model.new2old() >>> states.qjoints qjoints(6.0, 5.875, 5.0625, 4.1875, 3.46875) """ der = self.parameters.derived.fastaccess new = self.sequences.states.fastaccess_new old = self.sequences.states.fastaccess_old for j in range(der.nmbsegments): new.qjoints[j+1] = (der.c1*new.qjoints[j] + der.c2*old.qjoints[j] + der.c3*old.qjoints[j+1])
Assign the actual value of the inlet sequence to the upper joint of the subreach upstream. def pick_q_v1(self): """Assign the actual value of the inlet sequence to the upper joint of the subreach upstream.""" inl = self.sequences.inlets.fastaccess new = self.sequences.states.fastaccess_new new.qjoints[0] = 0. for idx in range(inl.len_q): new.qjoints[0] += inl.q[idx][0]
Assing the actual value of the lower joint of of the subreach downstream to the outlet sequence. def pass_q_v1(self): """Assing the actual value of the lower joint of of the subreach downstream to the outlet sequence.""" der = self.parameters.derived.fastaccess new = self.sequences.states.fastaccess_new out = self.sequences.outlets.fastaccess out.q[0] += new.qjoints[der.nmbsegments]
Return the default system encoding. If data is passed, try to decode the data with the default system encoding or from a short list of encoding types to test. Args: data - list of lists Returns: enc - system encoding def _detect_encoding(data=None): """Return the default system encoding. If data is passed, try to decode the data with the default system encoding or from a short list of encoding types to test. Args: data - list of lists Returns: enc - system encoding """ import locale enc_list = ['utf-8', 'latin-1', 'iso8859-1', 'iso8859-2', 'utf-16', 'cp720'] code = locale.getpreferredencoding(False) if data is None: return code if code.lower() not in enc_list: enc_list.insert(0, code.lower()) for c in enc_list: try: for line in data: line.decode(c) except (UnicodeDecodeError, UnicodeError, AttributeError): continue return c print("Encoding not detected. Please pass encoding value manually")
Define a parameter time step size within a parameter control file. Argument: * timestep(|Period|): Time step size. Function parameterstep should usually be be applied in a line immediately behind the model import. Defining the step size of time dependent parameters is a prerequisite to access any model specific parameter. Note that parameterstep implements some namespace magic by means of the module |inspect|. This makes things a little complicated for framework developers, but it eases the definition of parameter control files for framework users. def parameterstep(timestep=None): """Define a parameter time step size within a parameter control file. Argument: * timestep(|Period|): Time step size. Function parameterstep should usually be be applied in a line immediately behind the model import. Defining the step size of time dependent parameters is a prerequisite to access any model specific parameter. Note that parameterstep implements some namespace magic by means of the module |inspect|. This makes things a little complicated for framework developers, but it eases the definition of parameter control files for framework users. """ if timestep is not None: parametertools.Parameter.parameterstep(timestep) namespace = inspect.currentframe().f_back.f_locals model = namespace.get('model') if model is None: model = namespace['Model']() namespace['model'] = model if hydpy.pub.options.usecython and 'cythonizer' in namespace: cythonizer = namespace['cythonizer'] namespace['cythonmodule'] = cythonizer.cymodule model.cymodel = cythonizer.cymodule.Model() namespace['cymodel'] = model.cymodel model.cymodel.parameters = cythonizer.cymodule.Parameters() model.cymodel.sequences = cythonizer.cymodule.Sequences() for numpars_name in ('NumConsts', 'NumVars'): if hasattr(cythonizer.cymodule, numpars_name): numpars_new = getattr(cythonizer.cymodule, numpars_name)() numpars_old = getattr(model, numpars_name.lower()) for (name_numpar, numpar) in vars(numpars_old).items(): setattr(numpars_new, name_numpar, numpar) setattr(model.cymodel, numpars_name.lower(), numpars_new) for name in dir(model.cymodel): if (not name.startswith('_')) and hasattr(model, name): setattr(model, name, getattr(model.cymodel, name)) if 'Parameters' not in namespace: namespace['Parameters'] = parametertools.Parameters model.parameters = namespace['Parameters'](namespace) if 'Sequences' not in namespace: namespace['Sequences'] = sequencetools.Sequences model.sequences = namespace['Sequences'](**namespace) namespace['parameters'] = model.parameters for pars in model.parameters: namespace[pars.name] = pars namespace['sequences'] = model.sequences for seqs in model.sequences: namespace[seqs.name] = seqs if 'Masks' in namespace: model.masks = namespace['Masks'](model) namespace['masks'] = model.masks try: namespace.update(namespace['CONSTANTS']) except KeyError: pass focus = namespace.get('focus') for par in model.parameters.control: try: if (focus is None) or (par is focus): namespace[par.name] = par else: namespace[par.name] = lambda *args, **kwargs: None except AttributeError: pass
Clear the local namespace from a model wildcard import. Calling this method should remove the critical imports into the local namespace due the last wildcard import of a certain application model. It is thought for securing the successive preperation of different types of models via wildcard imports. See the following example, on how it can be applied. >>> from hydpy import reverse_model_wildcard_import Assume you wildcard import the first version of HydPy-L-Land (|lland_v1|): >>> from hydpy.models.lland_v1 import * This for example adds the collection class for handling control parameters of `lland_v1` into the local namespace: >>> print(ControlParameters(None).name) control Calling function |parameterstep| for example prepares the control parameter object |lland_control.NHRU|: >>> parameterstep('1d') >>> nhru nhru(?) Calling function |reverse_model_wildcard_import| removes both objects (and many more, but not all) from the local namespace: >>> reverse_model_wildcard_import() >>> ControlParameters Traceback (most recent call last): ... NameError: name 'ControlParameters' is not defined >>> nhru Traceback (most recent call last): ... NameError: name 'nhru' is not defined def reverse_model_wildcard_import(): """Clear the local namespace from a model wildcard import. Calling this method should remove the critical imports into the local namespace due the last wildcard import of a certain application model. It is thought for securing the successive preperation of different types of models via wildcard imports. See the following example, on how it can be applied. >>> from hydpy import reverse_model_wildcard_import Assume you wildcard import the first version of HydPy-L-Land (|lland_v1|): >>> from hydpy.models.lland_v1 import * This for example adds the collection class for handling control parameters of `lland_v1` into the local namespace: >>> print(ControlParameters(None).name) control Calling function |parameterstep| for example prepares the control parameter object |lland_control.NHRU|: >>> parameterstep('1d') >>> nhru nhru(?) Calling function |reverse_model_wildcard_import| removes both objects (and many more, but not all) from the local namespace: >>> reverse_model_wildcard_import() >>> ControlParameters Traceback (most recent call last): ... NameError: name 'ControlParameters' is not defined >>> nhru Traceback (most recent call last): ... NameError: name 'nhru' is not defined """ namespace = inspect.currentframe().f_back.f_locals model = namespace.get('model') if model is not None: for subpars in model.parameters: for par in subpars: namespace.pop(par.name, None) namespace.pop(objecttools.classname(par), None) namespace.pop(subpars.name, None) namespace.pop(objecttools.classname(subpars), None) for subseqs in model.sequences: for seq in subseqs: namespace.pop(seq.name, None) namespace.pop(objecttools.classname(seq), None) namespace.pop(subseqs.name, None) namespace.pop(objecttools.classname(subseqs), None) for name in ('parameters', 'sequences', 'masks', 'model', 'Parameters', 'Sequences', 'Masks', 'Model', 'cythonizer', 'cymodel', 'cythonmodule'): namespace.pop(name, None) for key in list(namespace.keys()): try: if namespace[key].__module__ == model.__module__: del namespace[key] except AttributeError: pass
Prepare and return the model of the given module. In usual HydPy projects, each hydrological model instance is prepared in an individual control file. This allows for "polluting" the namespace with different model attributes. There is no danger of name conflicts, as long as no other (wildcard) imports are performed. However, there are situations when different models are to be loaded into the same namespace. Then it is advisable to use function |prepare_model|, which just returns a reference to the model and nothing else. See the documentation of |dam_v001| on how to apply function |prepare_model| properly. def prepare_model(module: Union[types.ModuleType, str], timestep: PeriodABC.ConstrArg = None): """Prepare and return the model of the given module. In usual HydPy projects, each hydrological model instance is prepared in an individual control file. This allows for "polluting" the namespace with different model attributes. There is no danger of name conflicts, as long as no other (wildcard) imports are performed. However, there are situations when different models are to be loaded into the same namespace. Then it is advisable to use function |prepare_model|, which just returns a reference to the model and nothing else. See the documentation of |dam_v001| on how to apply function |prepare_model| properly. """ if timestep is not None: parametertools.Parameter.parameterstep(timetools.Period(timestep)) try: model = module.Model() except AttributeError: module = importlib.import_module(f'hydpy.models.{module}') model = module.Model() if hydpy.pub.options.usecython and hasattr(module, 'cythonizer'): cymodule = module.cythonizer.cymodule cymodel = cymodule.Model() cymodel.parameters = cymodule.Parameters() cymodel.sequences = cymodule.Sequences() model.cymodel = cymodel for numpars_name in ('NumConsts', 'NumVars'): if hasattr(cymodule, numpars_name): numpars_new = getattr(cymodule, numpars_name)() numpars_old = getattr(model, numpars_name.lower()) for (name_numpar, numpar) in vars(numpars_old).items(): setattr(numpars_new, name_numpar, numpar) setattr(cymodel, numpars_name.lower(), numpars_new) for name in dir(cymodel): if (not name.startswith('_')) and hasattr(model, name): setattr(model, name, getattr(cymodel, name)) dict_ = {'cythonmodule': cymodule, 'cymodel': cymodel} else: dict_ = {} dict_.update(vars(module)) dict_['model'] = model if hasattr(module, 'Parameters'): model.parameters = module.Parameters(dict_) else: model.parameters = parametertools.Parameters(dict_) if hasattr(module, 'Sequences'): model.sequences = module.Sequences(**dict_) else: model.sequences = sequencetools.Sequences(**dict_) if hasattr(module, 'Masks'): model.masks = module.Masks(model) return model
Define a simulation time step size for testing purposes within a parameter control file. Using |simulationstep| only affects the values of time dependent parameters, when `pub.timegrids.stepsize` is not defined. It thus has no influence on usual hydpy simulations at all. Use it just to check your parameter control files. Write it in a line immediately behind the one calling |parameterstep|. To clarify its purpose, executing raises a warning, when executing it from within a control file: >>> from hydpy import pub >>> with pub.options.warnsimulationstep(True): ... from hydpy.models.hland_v1 import * ... parameterstep('1d') ... simulationstep('1h') Traceback (most recent call last): ... UserWarning: Note that the applied function `simulationstep` is intended \ for testing purposes only. When doing a HydPy simulation, parameter values \ are initialised based on the actual simulation time step as defined under \ `pub.timegrids.stepsize` and the value given to `simulationstep` is ignored. >>> k4.simulationstep Period('1h') def simulationstep(timestep): """ Define a simulation time step size for testing purposes within a parameter control file. Using |simulationstep| only affects the values of time dependent parameters, when `pub.timegrids.stepsize` is not defined. It thus has no influence on usual hydpy simulations at all. Use it just to check your parameter control files. Write it in a line immediately behind the one calling |parameterstep|. To clarify its purpose, executing raises a warning, when executing it from within a control file: >>> from hydpy import pub >>> with pub.options.warnsimulationstep(True): ... from hydpy.models.hland_v1 import * ... parameterstep('1d') ... simulationstep('1h') Traceback (most recent call last): ... UserWarning: Note that the applied function `simulationstep` is intended \ for testing purposes only. When doing a HydPy simulation, parameter values \ are initialised based on the actual simulation time step as defined under \ `pub.timegrids.stepsize` and the value given to `simulationstep` is ignored. >>> k4.simulationstep Period('1h') """ if hydpy.pub.options.warnsimulationstep: warnings.warn( 'Note that the applied function `simulationstep` is intended for ' 'testing purposes only. When doing a HydPy simulation, parameter ' 'values are initialised based on the actual simulation time step ' 'as defined under `pub.timegrids.stepsize` and the value given ' 'to `simulationstep` is ignored.') parametertools.Parameter.simulationstep(timestep)
Define the corresponding control file within a condition file. Function |controlcheck| serves similar purposes as function |parameterstep|. It is the reason why one can interactively access the state and/or the log sequences within condition files as `land_dill.py` of the example project `LahnH`. It is called `controlcheck` due to its implicite feature to check upon the execution of the condition file if eventual specifications within both files disagree. The following test, where we write a number of soil moisture values (|hland_states.SM|) into condition file `land_dill.py` which does not agree with the number of hydrological response units (|hland_control.NmbZones|) defined in control file `land_dill.py`, verifies that this actually works within a new Python process: >>> from hydpy.core.examples import prepare_full_example_1 >>> prepare_full_example_1() >>> import os, subprocess >>> from hydpy import TestIO >>> cwd = os.path.join('LahnH', 'conditions', 'init_1996_01_01') >>> with TestIO(): ... os.chdir(cwd) ... with open('land_dill.py') as file_: ... lines = file_.readlines() ... lines[10:12] = 'sm(185.13164, 181.18755)', '' ... with open('land_dill.py', 'w') as file_: ... _ = file_.write('\\n'.join(lines)) ... result = subprocess.run( ... 'python land_dill.py', ... stdout=subprocess.PIPE, ... stderr=subprocess.PIPE, ... universal_newlines=True, ... shell=True) >>> print(result.stderr.split('ValueError:')[-1].strip()) While trying to set the value(s) of variable `sm`, the following error \ occurred: While trying to convert the value(s) `(185.13164, 181.18755)` to \ a numpy ndarray with shape `(12,)` and type `float`, the following error \ occurred: could not broadcast input array from shape (2) into shape (12) With a little trick, we can fake to be "inside" condition file `land_dill.py`. Calling |controlcheck| then e.g. prepares the shape of sequence |hland_states.Ic| as specified by the value of parameter |hland_control.NmbZones| given in the corresponding control file: >>> from hydpy.models.hland_v1 import * >>> __file__ = 'land_dill.py' # ToDo: undo? >>> with TestIO(): ... os.chdir(cwd) ... controlcheck() >>> ic.shape (12,) In the above example, the standard names for the project directory (the one containing the executed condition file) and the control directory (`default`) are used. The following example shows how to change them: >>> del model >>> with TestIO(): # doctest: +ELLIPSIS ... os.chdir(cwd) ... controlcheck(projectdir='somewhere', controldir='nowhere') Traceback (most recent call last): ... FileNotFoundError: While trying to load the control file \ `...hydpy...tests...iotesting...control...nowhere...land_dill.py`, the \ following error occurred: [Errno 2] No such file or directory: '...land_dill.py' Note that the functionalities of function |controlcheck| are disabled when there is already a `model` variable in the namespace, which is the case when a condition file is executed within the context of a complete HydPy project. def controlcheck(controldir='default', projectdir=None, controlfile=None): """Define the corresponding control file within a condition file. Function |controlcheck| serves similar purposes as function |parameterstep|. It is the reason why one can interactively access the state and/or the log sequences within condition files as `land_dill.py` of the example project `LahnH`. It is called `controlcheck` due to its implicite feature to check upon the execution of the condition file if eventual specifications within both files disagree. The following test, where we write a number of soil moisture values (|hland_states.SM|) into condition file `land_dill.py` which does not agree with the number of hydrological response units (|hland_control.NmbZones|) defined in control file `land_dill.py`, verifies that this actually works within a new Python process: >>> from hydpy.core.examples import prepare_full_example_1 >>> prepare_full_example_1() >>> import os, subprocess >>> from hydpy import TestIO >>> cwd = os.path.join('LahnH', 'conditions', 'init_1996_01_01') >>> with TestIO(): ... os.chdir(cwd) ... with open('land_dill.py') as file_: ... lines = file_.readlines() ... lines[10:12] = 'sm(185.13164, 181.18755)', '' ... with open('land_dill.py', 'w') as file_: ... _ = file_.write('\\n'.join(lines)) ... result = subprocess.run( ... 'python land_dill.py', ... stdout=subprocess.PIPE, ... stderr=subprocess.PIPE, ... universal_newlines=True, ... shell=True) >>> print(result.stderr.split('ValueError:')[-1].strip()) While trying to set the value(s) of variable `sm`, the following error \ occurred: While trying to convert the value(s) `(185.13164, 181.18755)` to \ a numpy ndarray with shape `(12,)` and type `float`, the following error \ occurred: could not broadcast input array from shape (2) into shape (12) With a little trick, we can fake to be "inside" condition file `land_dill.py`. Calling |controlcheck| then e.g. prepares the shape of sequence |hland_states.Ic| as specified by the value of parameter |hland_control.NmbZones| given in the corresponding control file: >>> from hydpy.models.hland_v1 import * >>> __file__ = 'land_dill.py' # ToDo: undo? >>> with TestIO(): ... os.chdir(cwd) ... controlcheck() >>> ic.shape (12,) In the above example, the standard names for the project directory (the one containing the executed condition file) and the control directory (`default`) are used. The following example shows how to change them: >>> del model >>> with TestIO(): # doctest: +ELLIPSIS ... os.chdir(cwd) ... controlcheck(projectdir='somewhere', controldir='nowhere') Traceback (most recent call last): ... FileNotFoundError: While trying to load the control file \ `...hydpy...tests...iotesting...control...nowhere...land_dill.py`, the \ following error occurred: [Errno 2] No such file or directory: '...land_dill.py' Note that the functionalities of function |controlcheck| are disabled when there is already a `model` variable in the namespace, which is the case when a condition file is executed within the context of a complete HydPy project. """ namespace = inspect.currentframe().f_back.f_locals model = namespace.get('model') if model is None: if not controlfile: controlfile = os.path.split(namespace['__file__'])[-1] if projectdir is None: projectdir = ( os.path.split( os.path.split( os.path.split(os.getcwd())[0])[0])[-1]) dirpath = os.path.abspath(os.path.join( '..', '..', '..', projectdir, 'control', controldir)) class CM(filetools.ControlManager): currentpath = dirpath model = CM().load_file(filename=controlfile)['model'] model.parameters.update() namespace['model'] = model for name in ('states', 'logs'): subseqs = getattr(model.sequences, name, None) if subseqs is not None: for seq in subseqs: namespace[seq.name] = seq
Update |RelSoilArea| based on |Area|, |ZoneArea|, and |ZoneType|. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(4) >>> zonetype(FIELD, FOREST, GLACIER, ILAKE) >>> area(100.0) >>> zonearea(10.0, 20.0, 30.0, 40.0) >>> derived.relsoilarea.update() >>> derived.relsoilarea relsoilarea(0.3) def update(self): """Update |RelSoilArea| based on |Area|, |ZoneArea|, and |ZoneType|. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(4) >>> zonetype(FIELD, FOREST, GLACIER, ILAKE) >>> area(100.0) >>> zonearea(10.0, 20.0, 30.0, 40.0) >>> derived.relsoilarea.update() >>> derived.relsoilarea relsoilarea(0.3) """ con = self.subpars.pars.control temp = con.zonearea.values.copy() temp[con.zonetype.values == GLACIER] = 0. temp[con.zonetype.values == ILAKE] = 0. self(numpy.sum(temp)/con.area)
Update |TTM| based on :math:`TTM = TT+DTTM`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(1) >>> zonetype(FIELD) >>> tt(1.0) >>> dttm(-2.0) >>> derived.ttm.update() >>> derived.ttm ttm(-1.0) def update(self): """Update |TTM| based on :math:`TTM = TT+DTTM`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(1) >>> zonetype(FIELD) >>> tt(1.0) >>> dttm(-2.0) >>> derived.ttm.update() >>> derived.ttm ttm(-1.0) """ con = self.subpars.pars.control self(con.tt+con.dttm)
Update |UH| based on |MaxBaz|. .. note:: This method also updates the shape of log sequence |QUH|. |MaxBaz| determines the end point of the triangle. A value of |MaxBaz| being not larger than the simulation step size is identical with applying no unit hydrograph at all: >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> simulationstep('12h') >>> maxbaz(0.0) >>> derived.uh.update() >>> logs.quh.shape (1,) >>> derived.uh uh(1.0) Note that, due to difference of the parameter and the simulation step size in the given example, the largest assignment resulting in a `inactive` unit hydrograph is 1/2: >>> maxbaz(0.5) >>> derived.uh.update() >>> logs.quh.shape (1,) >>> derived.uh uh(1.0) When |MaxBaz| is in accordance with two simulation steps, both unit hydrograph ordinats must be 1/2 due to symmetry of the triangle: >>> maxbaz(1.0) >>> derived.uh.update() >>> logs.quh.shape (2,) >>> derived.uh uh(0.5) >>> derived.uh.values array([ 0.5, 0.5]) A |MaxBaz| value in accordance with three simulation steps results in the ordinate values 2/9, 5/9, and 2/9: >>> maxbaz(1.5) >>> derived.uh.update() >>> logs.quh.shape (3,) >>> derived.uh uh(0.222222, 0.555556, 0.222222) And a final example, where the end of the triangle lies within a simulation step, resulting in the fractions 8/49, 23/49, 16/49, and 2/49: >>> maxbaz(1.75) >>> derived.uh.update() >>> logs.quh.shape (4,) >>> derived.uh uh(0.163265, 0.469388, 0.326531, 0.040816) def update(self): """Update |UH| based on |MaxBaz|. .. note:: This method also updates the shape of log sequence |QUH|. |MaxBaz| determines the end point of the triangle. A value of |MaxBaz| being not larger than the simulation step size is identical with applying no unit hydrograph at all: >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> simulationstep('12h') >>> maxbaz(0.0) >>> derived.uh.update() >>> logs.quh.shape (1,) >>> derived.uh uh(1.0) Note that, due to difference of the parameter and the simulation step size in the given example, the largest assignment resulting in a `inactive` unit hydrograph is 1/2: >>> maxbaz(0.5) >>> derived.uh.update() >>> logs.quh.shape (1,) >>> derived.uh uh(1.0) When |MaxBaz| is in accordance with two simulation steps, both unit hydrograph ordinats must be 1/2 due to symmetry of the triangle: >>> maxbaz(1.0) >>> derived.uh.update() >>> logs.quh.shape (2,) >>> derived.uh uh(0.5) >>> derived.uh.values array([ 0.5, 0.5]) A |MaxBaz| value in accordance with three simulation steps results in the ordinate values 2/9, 5/9, and 2/9: >>> maxbaz(1.5) >>> derived.uh.update() >>> logs.quh.shape (3,) >>> derived.uh uh(0.222222, 0.555556, 0.222222) And a final example, where the end of the triangle lies within a simulation step, resulting in the fractions 8/49, 23/49, 16/49, and 2/49: >>> maxbaz(1.75) >>> derived.uh.update() >>> logs.quh.shape (4,) >>> derived.uh uh(0.163265, 0.469388, 0.326531, 0.040816) """ maxbaz = self.subpars.pars.control.maxbaz.value quh = self.subpars.pars.model.sequences.logs.quh # Determine UH parameters... if maxbaz <= 1.: # ...when MaxBaz smaller than or equal to the simulation time step. self.shape = 1 self(1.) quh.shape = 1 else: # ...when MaxBaz is greater than the simulation time step. # Define some shortcuts for the following calculations. full = maxbaz # Now comes a terrible trick due to rounding problems coming from # the conversation of the SMHI parameter set to the HydPy # parameter set. Time to get rid of it... if (full % 1.) < 1e-4: full //= 1. full_f = int(numpy.floor(full)) full_c = int(numpy.ceil(full)) half = full/2. half_f = int(numpy.floor(half)) half_c = int(numpy.ceil(half)) full_2 = full**2. # Calculate the triangle ordinate(s)... self.shape = full_c uh = self.values quh.shape = full_c # ...of the rising limb. points = numpy.arange(1, half_f+1) uh[:half_f] = (2.*points-1.)/(2.*full_2) # ...around the peak (if it exists). if numpy.mod(half, 1.) != 0.: uh[half_f] = ( (half_c-half)/full + (2*half**2.-half_f**2.-half_c**2.)/(2.*full_2)) # ...of the falling limb (eventually except the last one). points = numpy.arange(half_c+1., full_f+1.) uh[half_c:full_f] = 1./full-(2.*points-1.)/(2.*full_2) # ...at the end (if not already done). if numpy.mod(full, 1.) != 0.: uh[full_f] = ( (full-full_f)/full-(full_2-full_f**2.)/(2.*full_2)) # Normalize the ordinates. self(uh/numpy.sum(uh))
Update |QFactor| based on |Area| and the current simulation step size. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> simulationstep('12h') >>> area(50.0) >>> derived.qfactor.update() >>> derived.qfactor qfactor(1.157407) def update(self): """Update |QFactor| based on |Area| and the current simulation step size. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> simulationstep('12h') >>> area(50.0) >>> derived.qfactor.update() >>> derived.qfactor qfactor(1.157407) """ self(self.subpars.pars.control.area*1000. / self.subpars.qfactor.simulationstep.seconds)
Number of neurons of the hidden layers. >>> from hydpy import ANN >>> ann = ANN(None) >>> ann(nmb_inputs=2, nmb_neurons=(2, 1), nmb_outputs=3) >>> ann.nmb_neurons (2, 1) >>> ann.nmb_neurons = (3,) >>> ann.nmb_neurons (3,) >>> del ann.nmb_neurons >>> ann.nmb_neurons Traceback (most recent call last): ... hydpy.core.exceptiontools.AttributeNotReady: Attribute `nmb_neurons` \ of object `ann` has not been prepared so far. def nmb_neurons(self) -> Tuple[int, ...]: """Number of neurons of the hidden layers. >>> from hydpy import ANN >>> ann = ANN(None) >>> ann(nmb_inputs=2, nmb_neurons=(2, 1), nmb_outputs=3) >>> ann.nmb_neurons (2, 1) >>> ann.nmb_neurons = (3,) >>> ann.nmb_neurons (3,) >>> del ann.nmb_neurons >>> ann.nmb_neurons Traceback (most recent call last): ... hydpy.core.exceptiontools.AttributeNotReady: Attribute `nmb_neurons` \ of object `ann` has not been prepared so far. """ return tuple(numpy.asarray(self._cann.nmb_neurons))
Shape of the array containing the activation of the hidden neurons. The first integer value is the number of connection between the hidden layers, the second integer value is maximum number of neurons of all hidden layers feeding information into another hidden layer (all except the last one), and the third integer value is the maximum number of the neurons of all hidden layers receiving information from another hidden layer (all except the first one): >>> from hydpy import ANN >>> ann = ANN(None) >>> ann(nmb_inputs=6, nmb_neurons=(4, 3, 2), nmb_outputs=6) >>> ann.shape_weights_hidden (2, 4, 3) >>> ann(nmb_inputs=6, nmb_neurons=(4,), nmb_outputs=6) >>> ann.shape_weights_hidden (0, 0, 0) def shape_weights_hidden(self) -> Tuple[int, int, int]: """Shape of the array containing the activation of the hidden neurons. The first integer value is the number of connection between the hidden layers, the second integer value is maximum number of neurons of all hidden layers feeding information into another hidden layer (all except the last one), and the third integer value is the maximum number of the neurons of all hidden layers receiving information from another hidden layer (all except the first one): >>> from hydpy import ANN >>> ann = ANN(None) >>> ann(nmb_inputs=6, nmb_neurons=(4, 3, 2), nmb_outputs=6) >>> ann.shape_weights_hidden (2, 4, 3) >>> ann(nmb_inputs=6, nmb_neurons=(4,), nmb_outputs=6) >>> ann.shape_weights_hidden (0, 0, 0) """ if self.nmb_layers > 1: nmb_neurons = self.nmb_neurons return (self.nmb_layers-1, max(nmb_neurons[:-1]), max(nmb_neurons[1:])) return 0, 0, 0
Number of hidden weights. >>> from hydpy import ANN >>> ann = ANN(None) >>> ann(nmb_inputs=2, nmb_neurons=(4, 3, 2), nmb_outputs=3) >>> ann.nmb_weights_hidden 18 def nmb_weights_hidden(self) -> int: """Number of hidden weights. >>> from hydpy import ANN >>> ann = ANN(None) >>> ann(nmb_inputs=2, nmb_neurons=(4, 3, 2), nmb_outputs=3) >>> ann.nmb_weights_hidden 18 """ nmb = 0 for idx_layer in range(self.nmb_layers-1): nmb += self.nmb_neurons[idx_layer] * self.nmb_neurons[idx_layer+1] return nmb
Raise a |RuntimeError| if the network's shape is not defined completely. >>> from hydpy import ANN >>> ANN(None).verify() Traceback (most recent call last): ... RuntimeError: The shape of the the artificial neural network \ parameter `ann` of element `?` has not been defined so far. def verify(self) -> None: """Raise a |RuntimeError| if the network's shape is not defined completely. >>> from hydpy import ANN >>> ANN(None).verify() Traceback (most recent call last): ... RuntimeError: The shape of the the artificial neural network \ parameter `ann` of element `?` has not been defined so far. """ if not self.__protectedproperties.allready(self): raise RuntimeError( 'The shape of the the artificial neural network ' 'parameter %s has not been defined so far.' % objecttools.elementphrase(self))
Return a string representation of the actual |anntools.ANN| object that is prefixed with the given string. def assignrepr(self, prefix) -> str: """Return a string representation of the actual |anntools.ANN| object that is prefixed with the given string.""" prefix = '%s%s(' % (prefix, self.name) blanks = len(prefix)*' ' lines = [ objecttools.assignrepr_value( self.nmb_inputs, '%snmb_inputs=' % prefix)+',', objecttools.assignrepr_tuple( self.nmb_neurons, '%snmb_neurons=' % blanks)+',', objecttools.assignrepr_value( self.nmb_outputs, '%snmb_outputs=' % blanks)+',', objecttools.assignrepr_list2( self.weights_input, '%sweights_input=' % blanks)+','] if self.nmb_layers > 1: lines.append(objecttools.assignrepr_list3( self.weights_hidden, '%sweights_hidden=' % blanks)+',') lines.append(objecttools.assignrepr_list2( self.weights_output, '%sweights_output=' % blanks)+',') lines.append(objecttools.assignrepr_list2( self.intercepts_hidden, '%sintercepts_hidden=' % blanks)+',') lines.append(objecttools.assignrepr_list( self.intercepts_output, '%sintercepts_output=' % blanks)+')') return '\n'.join(lines)
Plot the relationship between a certain input (`idx_input`) and a certain output (`idx_output`) variable described by the actual |anntools.ANN| object. Define the lower and the upper bound of the x axis via arguments `xmin` and `xmax`. The number of plotting points can be modified by argument `points`. Additional `matplotlib` plotting arguments can be passed as keyword arguments. def plot(self, xmin, xmax, idx_input=0, idx_output=0, points=100, **kwargs) -> None: """Plot the relationship between a certain input (`idx_input`) and a certain output (`idx_output`) variable described by the actual |anntools.ANN| object. Define the lower and the upper bound of the x axis via arguments `xmin` and `xmax`. The number of plotting points can be modified by argument `points`. Additional `matplotlib` plotting arguments can be passed as keyword arguments. """ xs_ = numpy.linspace(xmin, xmax, points) ys_ = numpy.zeros(xs_.shape) for idx, x__ in enumerate(xs_): self.inputs[idx_input] = x__ self.process_actual_input() ys_[idx] = self.outputs[idx_output] pyplot.plot(xs_, ys_, **kwargs)
Prepare the actual |anntools.SeasonalANN| object for calculations. Dispite all automated refreshings explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the inner consistency of a |anntools.SeasonalANN| instance, as it stores its |anntools.ANN| objects by reference. This is shown by the following example: >>> from hydpy import SeasonalANN, ann >>> seasonalann = SeasonalANN(None) >>> seasonalann.simulationstep = '1d' >>> jan = ann(nmb_inputs=1, nmb_neurons=(1,), nmb_outputs=1, ... weights_input=0.0, weights_output=0.0, ... intercepts_hidden=0.0, intercepts_output=1.0) >>> seasonalann(_1_1_12=jan) >>> jan.nmb_inputs, jan.nmb_outputs = 2, 3 >>> jan.nmb_inputs, jan.nmb_outputs (2, 3) >>> seasonalann.nmb_inputs, seasonalann.nmb_outputs (1, 1) Due to the C level implementation of the mathematical core of both |anntools.ANN| and |anntools.SeasonalANN| in module |annutils|, such an inconsistency might result in a program crash without any informative error message. Whenever you are afraid some inconsistency might have crept in, and you want to repair it, call method |anntools.SeasonalANN.refresh| explicitly: >>> seasonalann.refresh() >>> jan.nmb_inputs, jan.nmb_outputs (2, 3) >>> seasonalann.nmb_inputs, seasonalann.nmb_outputs (2, 3) def refresh(self) -> None: """Prepare the actual |anntools.SeasonalANN| object for calculations. Dispite all automated refreshings explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the inner consistency of a |anntools.SeasonalANN| instance, as it stores its |anntools.ANN| objects by reference. This is shown by the following example: >>> from hydpy import SeasonalANN, ann >>> seasonalann = SeasonalANN(None) >>> seasonalann.simulationstep = '1d' >>> jan = ann(nmb_inputs=1, nmb_neurons=(1,), nmb_outputs=1, ... weights_input=0.0, weights_output=0.0, ... intercepts_hidden=0.0, intercepts_output=1.0) >>> seasonalann(_1_1_12=jan) >>> jan.nmb_inputs, jan.nmb_outputs = 2, 3 >>> jan.nmb_inputs, jan.nmb_outputs (2, 3) >>> seasonalann.nmb_inputs, seasonalann.nmb_outputs (1, 1) Due to the C level implementation of the mathematical core of both |anntools.ANN| and |anntools.SeasonalANN| in module |annutils|, such an inconsistency might result in a program crash without any informative error message. Whenever you are afraid some inconsistency might have crept in, and you want to repair it, call method |anntools.SeasonalANN.refresh| explicitly: >>> seasonalann.refresh() >>> jan.nmb_inputs, jan.nmb_outputs (2, 3) >>> seasonalann.nmb_inputs, seasonalann.nmb_outputs (2, 3) """ # pylint: disable=unsupported-assignment-operation if self._do_refresh: if self.anns: self.__sann = annutils.SeasonalANN(self.anns) setattr(self.fastaccess, self.name, self._sann) self._set_shape((None, self._sann.nmb_anns)) if self._sann.nmb_anns > 1: self._interp() else: self._sann.ratios[:, 0] = 1. self.verify() else: self.__sann = None
Raise a |RuntimeError| and removes all handled neural networks, if the they are defined inconsistently. Dispite all automated safety checks explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the inner consistency of a |anntools.SeasonalANN| instance, as it stores its |anntools.ANN| objects by reference. This is shown by the following example: >>> from hydpy import SeasonalANN, ann >>> seasonalann = SeasonalANN(None) >>> seasonalann.simulationstep = '1d' >>> jan = ann(nmb_inputs=1, nmb_neurons=(1,), nmb_outputs=1, ... weights_input=0.0, weights_output=0.0, ... intercepts_hidden=0.0, intercepts_output=1.0) >>> seasonalann(_1_1_12=jan) >>> jan.nmb_inputs, jan.nmb_outputs = 2, 3 >>> jan.nmb_inputs, jan.nmb_outputs (2, 3) >>> seasonalann.nmb_inputs, seasonalann.nmb_outputs (1, 1) Due to the C level implementation of the mathematical core of both |anntools.ANN| and |anntools.SeasonalANN| in module |annutils|, such an inconsistency might result in a program crash without any informative error message. Whenever you are afraid some inconsistency might have crept in, and you want to find out if this is actually the case, call method |anntools.SeasonalANN.verify| explicitly: >>> seasonalann.verify() Traceback (most recent call last): ... RuntimeError: The number of input and output values of all neural \ networks contained by a seasonal neural network collection must be \ identical and be known by the containing object. But the seasonal \ neural network collection `seasonalann` of element `?` assumes `1` input \ and `1` output values, while the network corresponding to the time of \ year `toy_1_1_12_0_0` requires `2` input and `3` output values. >>> seasonalann seasonalann() >>> seasonalann.verify() Traceback (most recent call last): ... RuntimeError: Seasonal artificial neural network collections need \ to handle at least one "normal" single neural network, but for the seasonal \ neural network `seasonalann` of element `?` none has been defined so far. def verify(self) -> None: """Raise a |RuntimeError| and removes all handled neural networks, if the they are defined inconsistently. Dispite all automated safety checks explained in the general documentation on class |anntools.SeasonalANN|, it is still possible to destroy the inner consistency of a |anntools.SeasonalANN| instance, as it stores its |anntools.ANN| objects by reference. This is shown by the following example: >>> from hydpy import SeasonalANN, ann >>> seasonalann = SeasonalANN(None) >>> seasonalann.simulationstep = '1d' >>> jan = ann(nmb_inputs=1, nmb_neurons=(1,), nmb_outputs=1, ... weights_input=0.0, weights_output=0.0, ... intercepts_hidden=0.0, intercepts_output=1.0) >>> seasonalann(_1_1_12=jan) >>> jan.nmb_inputs, jan.nmb_outputs = 2, 3 >>> jan.nmb_inputs, jan.nmb_outputs (2, 3) >>> seasonalann.nmb_inputs, seasonalann.nmb_outputs (1, 1) Due to the C level implementation of the mathematical core of both |anntools.ANN| and |anntools.SeasonalANN| in module |annutils|, such an inconsistency might result in a program crash without any informative error message. Whenever you are afraid some inconsistency might have crept in, and you want to find out if this is actually the case, call method |anntools.SeasonalANN.verify| explicitly: >>> seasonalann.verify() Traceback (most recent call last): ... RuntimeError: The number of input and output values of all neural \ networks contained by a seasonal neural network collection must be \ identical and be known by the containing object. But the seasonal \ neural network collection `seasonalann` of element `?` assumes `1` input \ and `1` output values, while the network corresponding to the time of \ year `toy_1_1_12_0_0` requires `2` input and `3` output values. >>> seasonalann seasonalann() >>> seasonalann.verify() Traceback (most recent call last): ... RuntimeError: Seasonal artificial neural network collections need \ to handle at least one "normal" single neural network, but for the seasonal \ neural network `seasonalann` of element `?` none has been defined so far. """ if not self.anns: self._toy2ann.clear() raise RuntimeError( 'Seasonal artificial neural network collections need ' 'to handle at least one "normal" single neural network, ' 'but for the seasonal neural network `%s` of element ' '`%s` none has been defined so far.' % (self.name, objecttools.devicename(self))) for toy, ann_ in self: ann_.verify() if ((self.nmb_inputs != ann_.nmb_inputs) or (self.nmb_outputs != ann_.nmb_outputs)): self._toy2ann.clear() raise RuntimeError( 'The number of input and output values of all neural ' 'networks contained by a seasonal neural network ' 'collection must be identical and be known by the ' 'containing object. But the seasonal neural ' 'network collection `%s` of element `%s` assumes ' '`%d` input and `%d` output values, while the network ' 'corresponding to the time of year `%s` requires ' '`%d` input and `%d` output values.' % (self.name, objecttools.devicename(self), self.nmb_inputs, self.nmb_outputs, toy, ann_.nmb_inputs, ann_.nmb_outputs))
The shape of array |anntools.SeasonalANN.ratios|. def shape(self) -> Tuple[int, ...]: """The shape of array |anntools.SeasonalANN.ratios|.""" return tuple(int(sub) for sub in self.ratios.shape)
Private on purpose. def _set_shape(self, shape): """Private on purpose.""" try: shape = (int(shape),) except TypeError: pass shp = list(shape) shp[0] = timetools.Period('366d')/self.simulationstep shp[0] = int(numpy.ceil(round(shp[0], 10))) getattr(self.fastaccess, self.name).ratios = numpy.zeros( shp, dtype=float)
A sorted |tuple| of all contained |TOY| objects. def toys(self) -> Tuple[timetools.TOY, ...]: """A sorted |tuple| of all contained |TOY| objects.""" return tuple(toy for (toy, _) in self)
Call method |anntools.ANN.plot| of all |anntools.ANN| objects handled by the actual |anntools.SeasonalANN| object. def plot(self, xmin, xmax, idx_input=0, idx_output=0, points=100, **kwargs) -> None: """Call method |anntools.ANN.plot| of all |anntools.ANN| objects handled by the actual |anntools.SeasonalANN| object. """ for toy, ann_ in self: ann_.plot(xmin, xmax, idx_input=idx_input, idx_output=idx_output, points=points, label=str(toy), **kwargs) pyplot.legend()
The string corresponding to the current values of `subgroup`, `state`, and `variable`. >>> from hydpy.core.itemtools import ExchangeSpecification >>> spec = ExchangeSpecification('hland_v1', 'fluxes.qt') >>> spec.specstring 'fluxes.qt' >>> spec.series = True >>> spec.specstring 'fluxes.qt.series' >>> spec.subgroup = None >>> spec.specstring 'qt.series' def specstring(self): """The string corresponding to the current values of `subgroup`, `state`, and `variable`. >>> from hydpy.core.itemtools import ExchangeSpecification >>> spec = ExchangeSpecification('hland_v1', 'fluxes.qt') >>> spec.specstring 'fluxes.qt' >>> spec.series = True >>> spec.specstring 'fluxes.qt.series' >>> spec.subgroup = None >>> spec.specstring 'qt.series' """ if self.subgroup is None: variable = self.variable else: variable = f'{self.subgroup}.{self.variable}' if self.series: variable = f'{variable}.series' return variable
Apply method |ExchangeItem.insert_variables| to collect the relevant target variables handled by the devices of the given |Selections| object. We prepare the `LahnH` example project to be able to use its |Selections| object: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() We change the type of a specific application model to the type of its base model for reasons explained later: >>> from hydpy.models.hland import Model >>> hp.elements.land_lahn_3.model.__class__ = Model We prepare a |SetItem| as an example, handling all |hland_states.Ic| sequences corresponding to any application models derived from |hland|: >>> from hydpy import SetItem >>> item = SetItem('ic', 'hland', 'states.ic', 0) >>> item.targetspecs ExchangeSpecification('hland', 'states.ic') Applying method |ExchangeItem.collect_variables| connects the |SetItem| object with all four relevant |hland_states.Ic| objects: >>> item.collect_variables(pub.selections) >>> land_dill = hp.elements.land_dill >>> sequence = land_dill.model.sequences.states.ic >>> item.device2target[land_dill] is sequence True >>> for element in sorted(item.device2target, key=lambda x: x.name): ... print(element) land_dill land_lahn_1 land_lahn_2 land_lahn_3 Asking for |hland_states.Ic| objects corresponding to application model |hland_v1| only, results in skipping the |Element| `land_lahn_3` (handling the |hland| base model due to the hack above): >>> item = SetItem('ic', 'hland_v1', 'states.ic', 0) >>> item.collect_variables(pub.selections) >>> for element in sorted(item.device2target, key=lambda x: x.name): ... print(element) land_dill land_lahn_1 land_lahn_2 Selecting a series of a variable instead of the variable itself only affects the `targetspec` attribute: >>> item = SetItem('t', 'hland_v1', 'inputs.t.series', 0) >>> item.collect_variables(pub.selections) >>> item.targetspecs ExchangeSpecification('hland_v1', 'inputs.t.series') >>> sequence = land_dill.model.sequences.inputs.t >>> item.device2target[land_dill] is sequence True It is both possible to address sequences of |Node| objects, as well as their time series, by arguments "node" and "nodes": >>> item = SetItem('sim', 'node', 'sim', 0) >>> item.collect_variables(pub.selections) >>> dill = hp.nodes.dill >>> item.targetspecs ExchangeSpecification('node', 'sim') >>> item.device2target[dill] is dill.sequences.sim True >>> for node in sorted(item.device2target, key=lambda x: x.name): ... print(node) dill lahn_1 lahn_2 lahn_3 >>> item = SetItem('sim', 'nodes', 'sim.series', 0) >>> item.collect_variables(pub.selections) >>> item.targetspecs ExchangeSpecification('nodes', 'sim.series') >>> for node in sorted(item.device2target, key=lambda x: x.name): ... print(node) dill lahn_1 lahn_2 lahn_3 def collect_variables(self, selections) -> None: """Apply method |ExchangeItem.insert_variables| to collect the relevant target variables handled by the devices of the given |Selections| object. We prepare the `LahnH` example project to be able to use its |Selections| object: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() We change the type of a specific application model to the type of its base model for reasons explained later: >>> from hydpy.models.hland import Model >>> hp.elements.land_lahn_3.model.__class__ = Model We prepare a |SetItem| as an example, handling all |hland_states.Ic| sequences corresponding to any application models derived from |hland|: >>> from hydpy import SetItem >>> item = SetItem('ic', 'hland', 'states.ic', 0) >>> item.targetspecs ExchangeSpecification('hland', 'states.ic') Applying method |ExchangeItem.collect_variables| connects the |SetItem| object with all four relevant |hland_states.Ic| objects: >>> item.collect_variables(pub.selections) >>> land_dill = hp.elements.land_dill >>> sequence = land_dill.model.sequences.states.ic >>> item.device2target[land_dill] is sequence True >>> for element in sorted(item.device2target, key=lambda x: x.name): ... print(element) land_dill land_lahn_1 land_lahn_2 land_lahn_3 Asking for |hland_states.Ic| objects corresponding to application model |hland_v1| only, results in skipping the |Element| `land_lahn_3` (handling the |hland| base model due to the hack above): >>> item = SetItem('ic', 'hland_v1', 'states.ic', 0) >>> item.collect_variables(pub.selections) >>> for element in sorted(item.device2target, key=lambda x: x.name): ... print(element) land_dill land_lahn_1 land_lahn_2 Selecting a series of a variable instead of the variable itself only affects the `targetspec` attribute: >>> item = SetItem('t', 'hland_v1', 'inputs.t.series', 0) >>> item.collect_variables(pub.selections) >>> item.targetspecs ExchangeSpecification('hland_v1', 'inputs.t.series') >>> sequence = land_dill.model.sequences.inputs.t >>> item.device2target[land_dill] is sequence True It is both possible to address sequences of |Node| objects, as well as their time series, by arguments "node" and "nodes": >>> item = SetItem('sim', 'node', 'sim', 0) >>> item.collect_variables(pub.selections) >>> dill = hp.nodes.dill >>> item.targetspecs ExchangeSpecification('node', 'sim') >>> item.device2target[dill] is dill.sequences.sim True >>> for node in sorted(item.device2target, key=lambda x: x.name): ... print(node) dill lahn_1 lahn_2 lahn_3 >>> item = SetItem('sim', 'nodes', 'sim.series', 0) >>> item.collect_variables(pub.selections) >>> item.targetspecs ExchangeSpecification('nodes', 'sim.series') >>> for node in sorted(item.device2target, key=lambda x: x.name): ... print(node) dill lahn_1 lahn_2 lahn_3 """ self.insert_variables(self.device2target, self.targetspecs, selections)
Determine the relevant target or base variables (as defined by the given |ExchangeSpecification| object ) handled by the given |Selections| object and insert them into the given `device2variable` dictionary. def insert_variables( self, device2variable, exchangespec, selections) -> None: """Determine the relevant target or base variables (as defined by the given |ExchangeSpecification| object ) handled by the given |Selections| object and insert them into the given `device2variable` dictionary.""" if self.targetspecs.master in ('node', 'nodes'): for node in selections.nodes: variable = self._query_nodevariable(node, exchangespec) device2variable[node] = variable else: for element in self._iter_relevantelements(selections): variable = self._query_elementvariable(element, exchangespec) device2variable[element] = variable
Assign the given value(s) to the given target or base variable. If the assignment fails, |ChangeItem.update_variable| raises an error like the following: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> item = SetItem('alpha', 'hland_v1', 'control.alpha', 0) >>> item.collect_variables(pub.selections) >>> item.update_variables() # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: When trying to update a target variable of SetItem `alpha` \ with the value(s) `None`, the following error occurred: While trying to set \ the value(s) of variable `alpha` of element `...`, the following error \ occurred: The given value `None` cannot be converted to type `float`. def update_variable(self, variable, value) -> None: """Assign the given value(s) to the given target or base variable. If the assignment fails, |ChangeItem.update_variable| raises an error like the following: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> item = SetItem('alpha', 'hland_v1', 'control.alpha', 0) >>> item.collect_variables(pub.selections) >>> item.update_variables() # doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: When trying to update a target variable of SetItem `alpha` \ with the value(s) `None`, the following error occurred: While trying to set \ the value(s) of variable `alpha` of element `...`, the following error \ occurred: The given value `None` cannot be converted to type `float`. """ try: variable(value) except BaseException: objecttools.augment_excmessage( f'When trying to update a target variable of ' f'{objecttools.classname(self)} `{self.name}` ' f'with the value(s) `{value}`')
Assign the current objects |ChangeItem.value| to the values of the target variables. We use the `LahnH` project in the following: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() In the first example, a 0-dimensional |SetItem| changes the value of the 0-dimensional parameter |hland_control.Alpha|: >>> from hydpy.core.itemtools import SetItem >>> item = SetItem('alpha', 'hland_v1', 'control.alpha', 0) >>> item SetItem('alpha', 'hland_v1', 'control.alpha', 0) >>> item.collect_variables(pub.selections) >>> item.value is None True >>> land_dill = hp.elements.land_dill >>> land_dill.model.parameters.control.alpha alpha(1.0) >>> item.value = 2.0 >>> item.value array(2.0) >>> land_dill.model.parameters.control.alpha alpha(1.0) >>> item.update_variables() >>> land_dill.model.parameters.control.alpha alpha(2.0) In the second example, a 0-dimensional |SetItem| changes the values of the 1-dimensional parameter |hland_control.FC|: >>> item = SetItem('fc', 'hland_v1', 'control.fc', 0) >>> item.collect_variables(pub.selections) >>> item.value = 200.0 >>> land_dill.model.parameters.control.fc fc(278.0) >>> item.update_variables() >>> land_dill.model.parameters.control.fc fc(200.0) In the third example, a 1-dimensional |SetItem| changes the values of the 1-dimensional sequence |hland_states.Ic|: >>> for element in hp.elements.catchment: ... element.model.parameters.control.nmbzones(5) ... element.model.parameters.control.icmax(4.0) >>> item = SetItem('ic', 'hland_v1', 'states.ic', 1) >>> item.collect_variables(pub.selections) >>> land_dill.model.sequences.states.ic ic(nan, nan, nan, nan, nan) >>> item.value = 2.0 >>> item.update_variables() >>> land_dill.model.sequences.states.ic ic(2.0, 2.0, 2.0, 2.0, 2.0) >>> item.value = 1.0, 2.0, 3.0, 4.0, 5.0 >>> item.update_variables() >>> land_dill.model.sequences.states.ic ic(1.0, 2.0, 3.0, 4.0, 4.0) def update_variables(self) -> None: """Assign the current objects |ChangeItem.value| to the values of the target variables. We use the `LahnH` project in the following: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() In the first example, a 0-dimensional |SetItem| changes the value of the 0-dimensional parameter |hland_control.Alpha|: >>> from hydpy.core.itemtools import SetItem >>> item = SetItem('alpha', 'hland_v1', 'control.alpha', 0) >>> item SetItem('alpha', 'hland_v1', 'control.alpha', 0) >>> item.collect_variables(pub.selections) >>> item.value is None True >>> land_dill = hp.elements.land_dill >>> land_dill.model.parameters.control.alpha alpha(1.0) >>> item.value = 2.0 >>> item.value array(2.0) >>> land_dill.model.parameters.control.alpha alpha(1.0) >>> item.update_variables() >>> land_dill.model.parameters.control.alpha alpha(2.0) In the second example, a 0-dimensional |SetItem| changes the values of the 1-dimensional parameter |hland_control.FC|: >>> item = SetItem('fc', 'hland_v1', 'control.fc', 0) >>> item.collect_variables(pub.selections) >>> item.value = 200.0 >>> land_dill.model.parameters.control.fc fc(278.0) >>> item.update_variables() >>> land_dill.model.parameters.control.fc fc(200.0) In the third example, a 1-dimensional |SetItem| changes the values of the 1-dimensional sequence |hland_states.Ic|: >>> for element in hp.elements.catchment: ... element.model.parameters.control.nmbzones(5) ... element.model.parameters.control.icmax(4.0) >>> item = SetItem('ic', 'hland_v1', 'states.ic', 1) >>> item.collect_variables(pub.selections) >>> land_dill.model.sequences.states.ic ic(nan, nan, nan, nan, nan) >>> item.value = 2.0 >>> item.update_variables() >>> land_dill.model.sequences.states.ic ic(2.0, 2.0, 2.0, 2.0, 2.0) >>> item.value = 1.0, 2.0, 3.0, 4.0, 5.0 >>> item.update_variables() >>> land_dill.model.sequences.states.ic ic(1.0, 2.0, 3.0, 4.0, 4.0) """ value = self.value for variable in self.device2target.values(): self.update_variable(variable, value)
Apply method |ChangeItem.collect_variables| of the base class |ChangeItem| and also apply method |ExchangeItem.insert_variables| of class |ExchangeItem| to collect the relevant base variables handled by the devices of the given |Selections| object. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> from hydpy import AddItem >>> item = AddItem( ... 'alpha', 'hland_v1', 'control.sfcf', 'control.rfcf', 0) >>> item.collect_variables(pub.selections) >>> land_dill = hp.elements.land_dill >>> control = land_dill.model.parameters.control >>> item.device2target[land_dill] is control.sfcf True >>> item.device2base[land_dill] is control.rfcf True >>> for device in sorted(item.device2base, key=lambda x: x.name): ... print(device) land_dill land_lahn_1 land_lahn_2 land_lahn_3 def collect_variables(self, selections) -> None: """Apply method |ChangeItem.collect_variables| of the base class |ChangeItem| and also apply method |ExchangeItem.insert_variables| of class |ExchangeItem| to collect the relevant base variables handled by the devices of the given |Selections| object. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> from hydpy import AddItem >>> item = AddItem( ... 'alpha', 'hland_v1', 'control.sfcf', 'control.rfcf', 0) >>> item.collect_variables(pub.selections) >>> land_dill = hp.elements.land_dill >>> control = land_dill.model.parameters.control >>> item.device2target[land_dill] is control.sfcf True >>> item.device2base[land_dill] is control.rfcf True >>> for device in sorted(item.device2base, key=lambda x: x.name): ... print(device) land_dill land_lahn_1 land_lahn_2 land_lahn_3 """ super().collect_variables(selections) self.insert_variables(self.device2base, self.basespecs, selections)
Add the general |ChangeItem.value| with the |Device| specific base variable and assign the result to the respective target variable. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> from hydpy.models.hland_v1 import FIELD >>> for element in hp.elements.catchment: ... control = element.model.parameters.control ... control.nmbzones(3) ... control.zonetype(FIELD) ... control.rfcf(1.1) >>> from hydpy.core.itemtools import AddItem >>> item = AddItem( ... 'sfcf', 'hland_v1', 'control.sfcf', 'control.rfcf', 1) >>> item.collect_variables(pub.selections) >>> land_dill = hp.elements.land_dill >>> land_dill.model.parameters.control.sfcf sfcf(?) >>> item.value = -0.1, 0.0, 0.1 >>> item.update_variables() >>> land_dill.model.parameters.control.sfcf sfcf(1.0, 1.1, 1.2) >>> land_dill.model.parameters.control.rfcf.shape = 2 >>> land_dill.model.parameters.control.rfcf = 1.1 >>> item.update_variables() # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: When trying to add the value(s) `[-0.1 0. 0.1]` of \ AddItem `sfcf` and the value(s) `[ 1.1 1.1]` of variable `rfcf` of element \ `land_dill`, the following error occurred: operands could not be broadcast \ together with shapes (2,) (3,)... def update_variables(self) -> None: """Add the general |ChangeItem.value| with the |Device| specific base variable and assign the result to the respective target variable. >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> from hydpy.models.hland_v1 import FIELD >>> for element in hp.elements.catchment: ... control = element.model.parameters.control ... control.nmbzones(3) ... control.zonetype(FIELD) ... control.rfcf(1.1) >>> from hydpy.core.itemtools import AddItem >>> item = AddItem( ... 'sfcf', 'hland_v1', 'control.sfcf', 'control.rfcf', 1) >>> item.collect_variables(pub.selections) >>> land_dill = hp.elements.land_dill >>> land_dill.model.parameters.control.sfcf sfcf(?) >>> item.value = -0.1, 0.0, 0.1 >>> item.update_variables() >>> land_dill.model.parameters.control.sfcf sfcf(1.0, 1.1, 1.2) >>> land_dill.model.parameters.control.rfcf.shape = 2 >>> land_dill.model.parameters.control.rfcf = 1.1 >>> item.update_variables() # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: When trying to add the value(s) `[-0.1 0. 0.1]` of \ AddItem `sfcf` and the value(s) `[ 1.1 1.1]` of variable `rfcf` of element \ `land_dill`, the following error occurred: operands could not be broadcast \ together with shapes (2,) (3,)... """ value = self.value for device, target in self.device2target.items(): base = self.device2base[device] try: result = base.value + value except BaseException: raise objecttools.augment_excmessage( f'When trying to add the value(s) `{value}` of ' f'AddItem `{self.name}` and the value(s) `{base.value}` ' f'of variable {objecttools.devicephrase(base)}') self.update_variable(target, result)
Apply method |ExchangeItem.collect_variables| of the base class |ExchangeItem| and determine the `ndim` attribute of the current |ChangeItem| object afterwards. The value of `ndim` depends on whether the values of the target variable or its time series is of interest: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> from hydpy.core.itemtools import SetItem >>> for target in ('states.lz', 'states.lz.series', ... 'states.sm', 'states.sm.series'): ... item = GetItem('hland_v1', target) ... item.collect_variables(pub.selections) ... print(item, item.ndim) GetItem('hland_v1', 'states.lz') 0 GetItem('hland_v1', 'states.lz.series') 1 GetItem('hland_v1', 'states.sm') 1 GetItem('hland_v1', 'states.sm.series') 2 def collect_variables(self, selections) -> None: """Apply method |ExchangeItem.collect_variables| of the base class |ExchangeItem| and determine the `ndim` attribute of the current |ChangeItem| object afterwards. The value of `ndim` depends on whether the values of the target variable or its time series is of interest: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> from hydpy.core.itemtools import SetItem >>> for target in ('states.lz', 'states.lz.series', ... 'states.sm', 'states.sm.series'): ... item = GetItem('hland_v1', target) ... item.collect_variables(pub.selections) ... print(item, item.ndim) GetItem('hland_v1', 'states.lz') 0 GetItem('hland_v1', 'states.lz.series') 1 GetItem('hland_v1', 'states.sm') 1 GetItem('hland_v1', 'states.sm.series') 2 """ super().collect_variables(selections) for device in sorted(self.device2target.keys(), key=lambda x: x.name): self._device2name[device] = f'{device.name}_{self.target}' for target in self.device2target.values(): self.ndim = target.NDIM if self.targetspecs.series: self.ndim += 1 break
Sequentially return name-value-pairs describing the current state of the target variables. The names are automatically generated and contain both the name of the |Device| of the respective |Variable| object and the target description: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> from hydpy.core.itemtools import SetItem >>> item = GetItem('hland_v1', 'states.lz') >>> item.collect_variables(pub.selections) >>> hp.elements.land_dill.model.sequences.states.lz = 100.0 >>> for name, value in item.yield_name2value(): ... print(name, value) land_dill_states_lz 100.0 land_lahn_1_states_lz 8.18711 land_lahn_2_states_lz 10.14007 land_lahn_3_states_lz 7.52648 >>> item = GetItem('hland_v1', 'states.sm') >>> item.collect_variables(pub.selections) >>> hp.elements.land_dill.model.sequences.states.sm = 2.0 >>> for name, value in item.yield_name2value(): ... print(name, value) # doctest: +ELLIPSIS land_dill_states_sm [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, \ 2.0, 2.0, 2.0, 2.0] land_lahn_1_states_sm [99.27505, ..., 142.84148] ... When querying time series, one can restrict the span of interest by passing index values: >>> item = GetItem('nodes', 'sim.series') >>> item.collect_variables(pub.selections) >>> hp.nodes.dill.sequences.sim.series = 1.0, 2.0, 3.0, 4.0 >>> for name, value in item.yield_name2value(): ... print(name, value) # doctest: +ELLIPSIS dill_sim_series [1.0, 2.0, 3.0, 4.0] lahn_1_sim_series [nan, ... ... >>> for name, value in item.yield_name2value(2, 3): ... print(name, value) # doctest: +ELLIPSIS dill_sim_series [3.0] lahn_1_sim_series [nan] ... def yield_name2value(self, idx1=None, idx2=None) \ -> Iterator[Tuple[str, str]]: """Sequentially return name-value-pairs describing the current state of the target variables. The names are automatically generated and contain both the name of the |Device| of the respective |Variable| object and the target description: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() >>> from hydpy.core.itemtools import SetItem >>> item = GetItem('hland_v1', 'states.lz') >>> item.collect_variables(pub.selections) >>> hp.elements.land_dill.model.sequences.states.lz = 100.0 >>> for name, value in item.yield_name2value(): ... print(name, value) land_dill_states_lz 100.0 land_lahn_1_states_lz 8.18711 land_lahn_2_states_lz 10.14007 land_lahn_3_states_lz 7.52648 >>> item = GetItem('hland_v1', 'states.sm') >>> item.collect_variables(pub.selections) >>> hp.elements.land_dill.model.sequences.states.sm = 2.0 >>> for name, value in item.yield_name2value(): ... print(name, value) # doctest: +ELLIPSIS land_dill_states_sm [2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, 2.0, \ 2.0, 2.0, 2.0, 2.0] land_lahn_1_states_sm [99.27505, ..., 142.84148] ... When querying time series, one can restrict the span of interest by passing index values: >>> item = GetItem('nodes', 'sim.series') >>> item.collect_variables(pub.selections) >>> hp.nodes.dill.sequences.sim.series = 1.0, 2.0, 3.0, 4.0 >>> for name, value in item.yield_name2value(): ... print(name, value) # doctest: +ELLIPSIS dill_sim_series [1.0, 2.0, 3.0, 4.0] lahn_1_sim_series [nan, ... ... >>> for name, value in item.yield_name2value(2, 3): ... print(name, value) # doctest: +ELLIPSIS dill_sim_series [3.0] lahn_1_sim_series [nan] ... """ for device, name in self._device2name.items(): target = self.device2target[device] if self.targetspecs.series: values = target.series[idx1:idx2] else: values = target.values if self.ndim == 0: values = objecttools.repr_(float(values)) else: values = objecttools.repr_list(values.tolist()) yield name, values
Returns the weekday's name given a ISO weekday number; "today" if today is the same weekday. def iso_day_to_weekday(d): """ Returns the weekday's name given a ISO weekday number; "today" if today is the same weekday. """ if int(d) == utils.get_now().isoweekday(): return _("today") for w in WEEKDAYS: if w[0] == int(d): return w[1]
Returns False if the location is closed, or the OpeningHours object to show the location is currently open. def is_open(location=None, attr=None): """ Returns False if the location is closed, or the OpeningHours object to show the location is currently open. """ obj = utils.is_open(location) if obj is False: return False if attr is not None: return getattr(obj, attr) return obj
Returns False if the location is closed, or the OpeningHours object to show the location is currently open. Same as `is_open` but passes `now` to `utils.is_open` to bypass `get_now()`. def is_open_now(location=None, attr=None): """ Returns False if the location is closed, or the OpeningHours object to show the location is currently open. Same as `is_open` but passes `now` to `utils.is_open` to bypass `get_now()`. """ obj = utils.is_open(location, now=datetime.datetime.now()) if obj is False: return False if attr is not None: return getattr(obj, attr) return obj
Creates a rendered listing of hours. def opening_hours(location=None, concise=False): """ Creates a rendered listing of hours. """ template_name = 'openinghours/opening_hours_list.html' days = [] # [{'hours': '9:00am to 5:00pm', 'name': u'Monday'}, {'hours... # Without `location`, choose the first company. if location: ohrs = OpeningHours.objects.filter(company=location) else: try: Location = utils.get_premises_model() ohrs = Location.objects.first().openinghours_set.all() except AttributeError: raise Exception("You must define some opening hours" " to use the opening hours tags.") ohrs.order_by('weekday', 'from_hour') for o in ohrs: days.append({ 'day_number': o.weekday, 'name': o.get_weekday_display(), 'from_hour': o.from_hour, 'to_hour': o.to_hour, 'hours': '%s%s to %s%s' % ( o.from_hour.strftime('%I:%M').lstrip('0'), o.from_hour.strftime('%p').lower(), o.to_hour.strftime('%I:%M').lstrip('0'), o.to_hour.strftime('%p').lower() ) }) open_days = [o.weekday for o in ohrs] for day_number, day_name in WEEKDAYS: if day_number not in open_days: days.append({ 'day_number': day_number, 'name': day_name, 'hours': 'Closed' }) days = sorted(days, key=lambda k: k['day_number']) if concise: # [{'hours': '9:00am to 5:00pm', 'day_names': u'Monday to Friday'}, # {'hours':... template_name = 'openinghours/opening_hours_list_concise.html' concise_days = [] current_set = {} for day in days: if 'hours' not in current_set.keys(): current_set = {'day_names': [day['name']], 'hours': day['hours']} elif day['hours'] != current_set['hours']: concise_days.append(current_set) current_set = {'day_names': [day['name']], 'hours': day['hours']} else: current_set['day_names'].append(day['name']) concise_days.append(current_set) for day_set in concise_days: if len(day_set['day_names']) > 2: day_set['day_names'] = '%s to %s' % (day_set['day_names'][0], day_set['day_names'][-1]) elif len(day_set['day_names']) > 1: day_set['day_names'] = '%s and %s' % (day_set['day_names'][0], day_set['day_names'][-1]) else: day_set['day_names'] = '%s' % day_set['day_names'][0] days = concise_days template = get_template(template_name) return template.render({'days': days})
Convenience method to make the actual |HydPy| instance runable. def prepare_everything(self): """Convenience method to make the actual |HydPy| instance runable.""" self.prepare_network() self.init_models() self.load_conditions() with hydpy.pub.options.warnmissingobsfile(False): self.prepare_nodeseries() self.prepare_modelseries() self.load_inputseries()
Load all network files as |Selections| (stored in module |pub|) and assign the "complete" selection to the |HydPy| object. def prepare_network(self): """Load all network files as |Selections| (stored in module |pub|) and assign the "complete" selection to the |HydPy| object.""" hydpy.pub.selections = selectiontools.Selections() hydpy.pub.selections += hydpy.pub.networkmanager.load_files() self.update_devices(hydpy.pub.selections.complete)
Call method |Elements.save_controls| of the |Elements| object currently handled by the |HydPy| object. We use the `LahnH` example project to demonstrate how to write a complete set parameter control files. For convenience, we let function |prepare_full_example_2| prepare a fully functional |HydPy| object, handling seven |Element| objects controlling four |hland_v1| and three |hstream_v1| application models: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() At first, there is only one control subfolder named "default", containing the seven control files used in the step above: >>> import os >>> with TestIO(): ... os.listdir('LahnH/control') ['default'] Next, we use the |ControlManager| to create a new directory and dump all control file into it: >>> with TestIO(): ... pub.controlmanager.currentdir = 'newdir' ... hp.save_controls() ... sorted(os.listdir('LahnH/control')) ['default', 'newdir'] We focus our examples on the (smaller) control files of application model |hstream_v1|. The values of parameter |hstream_control.Lag| and |hstream_control.Damp| for the river channel connecting the outlets of subcatchment `lahn_1` and `lahn_2` are 0.583 days and 0.0, respectively: >>> model = hp.elements.stream_lahn_1_lahn_2.model >>> model.parameters.control lag(0.583) damp(0.0) The corresponding written control file defines the same values: >>> dir_ = 'LahnH/control/newdir/' >>> with TestIO(): ... with open(dir_ + 'stream_lahn_1_lahn_2.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1d') parameterstep('1d') <BLANKLINE> lag(0.583) damp(0.0) <BLANKLINE> Its name equals the element name and the time step information is taken for the |Timegrid| object available via |pub|: >>> pub.timegrids.stepsize Period('1d') Use the |Auxfiler| class To avoid redefining the same parameter values in multiple control files. Here, we prepare an |Auxfiler| object which handles the two parameters of the model discussed above: >>> from hydpy import Auxfiler >>> aux = Auxfiler() >>> aux += 'hstream_v1' >>> aux.hstream_v1.stream = model.parameters.control.damp >>> aux.hstream_v1.stream = model.parameters.control.lag When passing the |Auxfiler| object to |HydPy.save_controls|, both parameters the control file of element `stream_lahn_1_lahn_2` do not define their values on their own, but reference the auxiliary file `stream.py` instead: >>> with TestIO(): ... pub.controlmanager.currentdir = 'newdir' ... hp.save_controls(auxfiler=aux) ... with open(dir_ + 'stream_lahn_1_lahn_2.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1d') parameterstep('1d') <BLANKLINE> lag(auxfile='stream') damp(auxfile='stream') <BLANKLINE> `stream.py` contains the actual value definitions: >>> with TestIO(): ... with open(dir_ + 'stream.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1d') parameterstep('1d') <BLANKLINE> damp(0.0) lag(0.583) <BLANKLINE> The |hstream_v1| model of element `stream_lahn_2_lahn_3` defines the same value for parameter |hstream_control.Damp| but a different one for parameter |hstream_control.Lag|. Hence, only |hstream_control.Damp| can reference control file `stream.py` without distorting data: >>> with TestIO(): ... with open(dir_ + 'stream_lahn_2_lahn_3.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1d') parameterstep('1d') <BLANKLINE> lag(0.417) damp(auxfile='stream') <BLANKLINE> Another option is to pass alternative step size information. The `simulationstep` information, which is not really required in control files but useful for testing them, has no impact on the written data. However, passing an alternative `parameterstep` information changes the written values of time dependent parameters both in the primary and the auxiliary control files, as to be expected: >>> with TestIO(): ... pub.controlmanager.currentdir = 'newdir' ... hp.save_controls( ... auxfiler=aux, parameterstep='2d', simulationstep='1h') ... with open(dir_ + 'stream_lahn_1_lahn_2.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('2d') <BLANKLINE> lag(auxfile='stream') damp(auxfile='stream') <BLANKLINE> >>> with TestIO(): ... with open(dir_ + 'stream.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('2d') <BLANKLINE> damp(0.0) lag(0.2915) <BLANKLINE> >>> with TestIO(): ... with open(dir_ + 'stream_lahn_2_lahn_3.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('2d') <BLANKLINE> lag(0.2085) damp(auxfile='stream') <BLANKLINE> def save_controls(self, parameterstep=None, simulationstep=None, auxfiler=None): """Call method |Elements.save_controls| of the |Elements| object currently handled by the |HydPy| object. We use the `LahnH` example project to demonstrate how to write a complete set parameter control files. For convenience, we let function |prepare_full_example_2| prepare a fully functional |HydPy| object, handling seven |Element| objects controlling four |hland_v1| and three |hstream_v1| application models: >>> from hydpy.core.examples import prepare_full_example_2 >>> hp, pub, TestIO = prepare_full_example_2() At first, there is only one control subfolder named "default", containing the seven control files used in the step above: >>> import os >>> with TestIO(): ... os.listdir('LahnH/control') ['default'] Next, we use the |ControlManager| to create a new directory and dump all control file into it: >>> with TestIO(): ... pub.controlmanager.currentdir = 'newdir' ... hp.save_controls() ... sorted(os.listdir('LahnH/control')) ['default', 'newdir'] We focus our examples on the (smaller) control files of application model |hstream_v1|. The values of parameter |hstream_control.Lag| and |hstream_control.Damp| for the river channel connecting the outlets of subcatchment `lahn_1` and `lahn_2` are 0.583 days and 0.0, respectively: >>> model = hp.elements.stream_lahn_1_lahn_2.model >>> model.parameters.control lag(0.583) damp(0.0) The corresponding written control file defines the same values: >>> dir_ = 'LahnH/control/newdir/' >>> with TestIO(): ... with open(dir_ + 'stream_lahn_1_lahn_2.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1d') parameterstep('1d') <BLANKLINE> lag(0.583) damp(0.0) <BLANKLINE> Its name equals the element name and the time step information is taken for the |Timegrid| object available via |pub|: >>> pub.timegrids.stepsize Period('1d') Use the |Auxfiler| class To avoid redefining the same parameter values in multiple control files. Here, we prepare an |Auxfiler| object which handles the two parameters of the model discussed above: >>> from hydpy import Auxfiler >>> aux = Auxfiler() >>> aux += 'hstream_v1' >>> aux.hstream_v1.stream = model.parameters.control.damp >>> aux.hstream_v1.stream = model.parameters.control.lag When passing the |Auxfiler| object to |HydPy.save_controls|, both parameters the control file of element `stream_lahn_1_lahn_2` do not define their values on their own, but reference the auxiliary file `stream.py` instead: >>> with TestIO(): ... pub.controlmanager.currentdir = 'newdir' ... hp.save_controls(auxfiler=aux) ... with open(dir_ + 'stream_lahn_1_lahn_2.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1d') parameterstep('1d') <BLANKLINE> lag(auxfile='stream') damp(auxfile='stream') <BLANKLINE> `stream.py` contains the actual value definitions: >>> with TestIO(): ... with open(dir_ + 'stream.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1d') parameterstep('1d') <BLANKLINE> damp(0.0) lag(0.583) <BLANKLINE> The |hstream_v1| model of element `stream_lahn_2_lahn_3` defines the same value for parameter |hstream_control.Damp| but a different one for parameter |hstream_control.Lag|. Hence, only |hstream_control.Damp| can reference control file `stream.py` without distorting data: >>> with TestIO(): ... with open(dir_ + 'stream_lahn_2_lahn_3.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1d') parameterstep('1d') <BLANKLINE> lag(0.417) damp(auxfile='stream') <BLANKLINE> Another option is to pass alternative step size information. The `simulationstep` information, which is not really required in control files but useful for testing them, has no impact on the written data. However, passing an alternative `parameterstep` information changes the written values of time dependent parameters both in the primary and the auxiliary control files, as to be expected: >>> with TestIO(): ... pub.controlmanager.currentdir = 'newdir' ... hp.save_controls( ... auxfiler=aux, parameterstep='2d', simulationstep='1h') ... with open(dir_ + 'stream_lahn_1_lahn_2.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('2d') <BLANKLINE> lag(auxfile='stream') damp(auxfile='stream') <BLANKLINE> >>> with TestIO(): ... with open(dir_ + 'stream.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('2d') <BLANKLINE> damp(0.0) lag(0.2915) <BLANKLINE> >>> with TestIO(): ... with open(dir_ + 'stream_lahn_2_lahn_3.py') as controlfile: ... print(controlfile.read()) # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('2d') <BLANKLINE> lag(0.2085) damp(auxfile='stream') <BLANKLINE> """ self.elements.save_controls(parameterstep=parameterstep, simulationstep=simulationstep, auxfiler=auxfiler)
Print out some properties of the network defined by the |Node| and |Element| objects currently handled by the |HydPy| object. def networkproperties(self): """Print out some properties of the network defined by the |Node| and |Element| objects currently handled by the |HydPy| object.""" print('Number of nodes: %d' % len(self.nodes)) print('Number of elements: %d' % len(self.elements)) print('Number of end nodes: %d' % len(self.endnodes)) print('Number of distinct networks: %d' % len(self.numberofnetworks)) print('Applied node variables: %s' % ', '.join(self.variables))
The number of distinct networks defined by the|Node| and |Element| objects currently handled by the |HydPy| object. def numberofnetworks(self): """The number of distinct networks defined by the|Node| and |Element| objects currently handled by the |HydPy| object.""" sels1 = selectiontools.Selections() sels2 = selectiontools.Selections() complete = selectiontools.Selection('complete', self.nodes, self.elements) for node in self.endnodes: sel = complete.copy(node.name).select_upstream(node) sels1 += sel sels2 += sel.copy(node.name) for sel1 in sels1: for sel2 in sels2: if sel1.name != sel2.name: sel1 -= sel2 for name in list(sels1.names): if not sels1[name].elements: del sels1[name] return sels1
|Nodes| object containing all |Node| objects currently handled by the |HydPy| object which define a downstream end point of a network. def endnodes(self): """|Nodes| object containing all |Node| objects currently handled by the |HydPy| object which define a downstream end point of a network.""" endnodes = devicetools.Nodes() for node in self.nodes: for element in node.exits: if ((element in self.elements) and (node not in element.receivers)): break else: endnodes += node return endnodes
Sorted list of strings summarizing all variables handled by the |Node| objects def variables(self): """Sorted list of strings summarizing all variables handled by the |Node| objects""" variables = set([]) for node in self.nodes: variables.add(node.variable) return sorted(variables)
Tuple containing the start and end index of the simulation period regarding the initialization period defined by the |Timegrids| object stored in module |pub|. def simindices(self): """Tuple containing the start and end index of the simulation period regarding the initialization period defined by the |Timegrids| object stored in module |pub|.""" return (hydpy.pub.timegrids.init[hydpy.pub.timegrids.sim.firstdate], hydpy.pub.timegrids.init[hydpy.pub.timegrids.sim.lastdate])
Call method |Devices.open_files| of the |Nodes| and |Elements| objects currently handled by the |HydPy| object. def open_files(self, idx=0): """Call method |Devices.open_files| of the |Nodes| and |Elements| objects currently handled by the |HydPy| object.""" self.elements.open_files(idx=idx) self.nodes.open_files(idx=idx)
Determines the order, in which the |Node| and |Element| objects currently handled by the |HydPy| objects need to be processed during a simulation time step. Optionally, a |Selection| object for defining new |Node| and |Element| objects can be passed. def update_devices(self, selection=None): """Determines the order, in which the |Node| and |Element| objects currently handled by the |HydPy| objects need to be processed during a simulation time step. Optionally, a |Selection| object for defining new |Node| and |Element| objects can be passed.""" if selection is not None: self.nodes = selection.nodes self.elements = selection.elements self._update_deviceorder()
A list containing all methods of all |Node| and |Element| objects that need to be processed during a simulation time step in the order they must be called. def methodorder(self): """A list containing all methods of all |Node| and |Element| objects that need to be processed during a simulation time step in the order they must be called.""" funcs = [] for node in self.nodes: if node.deploymode == 'oldsim': funcs.append(node.sequences.fastaccess.load_simdata) elif node.deploymode == 'obs': funcs.append(node.sequences.fastaccess.load_obsdata) for node in self.nodes: if node.deploymode != 'oldsim': funcs.append(node.reset) for device in self.deviceorder: if isinstance(device, devicetools.Element): funcs.append(device.model.doit) for element in self.elements: if element.senders: funcs.append(element.model.update_senders) for element in self.elements: if element.receivers: funcs.append(element.model.update_receivers) for element in self.elements: funcs.append(element.model.save_data) for node in self.nodes: if node.deploymode != 'oldsim': funcs.append(node.sequences.fastaccess.save_simdata) return funcs
Perform a simulation run over the actual simulation time period defined by the |Timegrids| object stored in module |pub|. def doit(self): """Perform a simulation run over the actual simulation time period defined by the |Timegrids| object stored in module |pub|.""" idx_start, idx_end = self.simindices self.open_files(idx_start) methodorder = self.methodorder for idx in printtools.progressbar(range(idx_start, idx_end)): for func in methodorder: func(idx) self.close_files()
Update the inlet link sequence. Required inlet sequence: |dam_inlets.Q| Calculated flux sequence: |Inflow| Basic equation: :math:`Inflow = Q` def pic_inflow_v1(self): """Update the inlet link sequence. Required inlet sequence: |dam_inlets.Q| Calculated flux sequence: |Inflow| Basic equation: :math:`Inflow = Q` """ flu = self.sequences.fluxes.fastaccess inl = self.sequences.inlets.fastaccess flu.inflow = inl.q[0]
Update the inlet link sequences. Required inlet sequences: |dam_inlets.Q| |dam_inlets.S| |dam_inlets.R| Calculated flux sequence: |Inflow| Basic equation: :math:`Inflow = Q + S + R` def pic_inflow_v2(self): """Update the inlet link sequences. Required inlet sequences: |dam_inlets.Q| |dam_inlets.S| |dam_inlets.R| Calculated flux sequence: |Inflow| Basic equation: :math:`Inflow = Q + S + R` """ flu = self.sequences.fluxes.fastaccess inl = self.sequences.inlets.fastaccess flu.inflow = inl.q[0]+inl.s[0]+inl.r[0]
Update the receiver link sequence. def pic_totalremotedischarge_v1(self): """Update the receiver link sequence.""" flu = self.sequences.fluxes.fastaccess rec = self.sequences.receivers.fastaccess flu.totalremotedischarge = rec.q[0]
Update the receiver link sequence. def pic_loggedrequiredremoterelease_v1(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedrequiredremoterelease[0] = rec.d[0]
Update the receiver link sequence. def pic_loggedrequiredremoterelease_v2(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedrequiredremoterelease[0] = rec.s[0]
Update the receiver link sequence. def pic_loggedallowedremoterelieve_v1(self): """Update the receiver link sequence.""" log = self.sequences.logs.fastaccess rec = self.sequences.receivers.fastaccess log.loggedallowedremoterelieve[0] = rec.r[0]
Log a new entry of discharge at a cross section far downstream. Required control parameter: |NmbLogEntries| Required flux sequence: |TotalRemoteDischarge| Calculated flux sequence: |LoggedTotalRemoteDischarge| Example: The following example shows that, with each new method call, the three memorized values are successively moved to the right and the respective new value is stored on the bare left position: >>> from hydpy.models.dam import * >>> parameterstep() >>> nmblogentries(3) >>> logs.loggedtotalremotedischarge = 0.0 >>> from hydpy import UnitTest >>> test = UnitTest(model, model.update_loggedtotalremotedischarge_v1, ... last_example=4, ... parseqs=(fluxes.totalremotedischarge, ... logs.loggedtotalremotedischarge)) >>> test.nexts.totalremotedischarge = [1., 3., 2., 4] >>> del test.inits.loggedtotalremotedischarge >>> test() | ex. | totalremotedischarge | loggedtotalremotedischarge | --------------------------------------------------------------------- | 1 | 1.0 | 1.0 0.0 0.0 | | 2 | 3.0 | 3.0 1.0 0.0 | | 3 | 2.0 | 2.0 3.0 1.0 | | 4 | 4.0 | 4.0 2.0 3.0 | def update_loggedtotalremotedischarge_v1(self): """Log a new entry of discharge at a cross section far downstream. Required control parameter: |NmbLogEntries| Required flux sequence: |TotalRemoteDischarge| Calculated flux sequence: |LoggedTotalRemoteDischarge| Example: The following example shows that, with each new method call, the three memorized values are successively moved to the right and the respective new value is stored on the bare left position: >>> from hydpy.models.dam import * >>> parameterstep() >>> nmblogentries(3) >>> logs.loggedtotalremotedischarge = 0.0 >>> from hydpy import UnitTest >>> test = UnitTest(model, model.update_loggedtotalremotedischarge_v1, ... last_example=4, ... parseqs=(fluxes.totalremotedischarge, ... logs.loggedtotalremotedischarge)) >>> test.nexts.totalremotedischarge = [1., 3., 2., 4] >>> del test.inits.loggedtotalremotedischarge >>> test() | ex. | totalremotedischarge | loggedtotalremotedischarge | --------------------------------------------------------------------- | 1 | 1.0 | 1.0 0.0 0.0 | | 2 | 3.0 | 3.0 1.0 0.0 | | 3 | 2.0 | 2.0 3.0 1.0 | | 4 | 4.0 | 4.0 2.0 3.0 | """ con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(con.nmblogentries-1, 0, -1): log.loggedtotalremotedischarge[idx] = \ log.loggedtotalremotedischarge[idx-1] log.loggedtotalremotedischarge[0] = flu.totalremotedischarge
Determine the water level based on an artificial neural network describing the relationship between water level and water stage. Required control parameter: |WaterVolume2WaterLevel| Required state sequence: |WaterVolume| Calculated aide sequence: |WaterLevel| Example: Prepare a dam model: >>> from hydpy.models.dam import * >>> parameterstep() Prepare a very simple relationship based on one single neuron: >>> watervolume2waterlevel( ... nmb_inputs=1, nmb_neurons=(1,), nmb_outputs=1, ... weights_input=0.5, weights_output=1.0, ... intercepts_hidden=0.0, intercepts_output=-0.5) At least in the water volume range used in the following examples, the shape of the relationship looks acceptable: >>> from hydpy import UnitTest >>> test = UnitTest( ... model, model.calc_waterlevel_v1, ... last_example=10, ... parseqs=(states.watervolume, aides.waterlevel)) >>> test.nexts.watervolume = range(10) >>> test() | ex. | watervolume | waterlevel | ---------------------------------- | 1 | 0.0 | 0.0 | | 2 | 1.0 | 0.122459 | | 3 | 2.0 | 0.231059 | | 4 | 3.0 | 0.317574 | | 5 | 4.0 | 0.380797 | | 6 | 5.0 | 0.424142 | | 7 | 6.0 | 0.452574 | | 8 | 7.0 | 0.470688 | | 9 | 8.0 | 0.482014 | | 10 | 9.0 | 0.489013 | For more realistic approximations of measured relationships between water level and volume, larger neural networks are required. def calc_waterlevel_v1(self): """Determine the water level based on an artificial neural network describing the relationship between water level and water stage. Required control parameter: |WaterVolume2WaterLevel| Required state sequence: |WaterVolume| Calculated aide sequence: |WaterLevel| Example: Prepare a dam model: >>> from hydpy.models.dam import * >>> parameterstep() Prepare a very simple relationship based on one single neuron: >>> watervolume2waterlevel( ... nmb_inputs=1, nmb_neurons=(1,), nmb_outputs=1, ... weights_input=0.5, weights_output=1.0, ... intercepts_hidden=0.0, intercepts_output=-0.5) At least in the water volume range used in the following examples, the shape of the relationship looks acceptable: >>> from hydpy import UnitTest >>> test = UnitTest( ... model, model.calc_waterlevel_v1, ... last_example=10, ... parseqs=(states.watervolume, aides.waterlevel)) >>> test.nexts.watervolume = range(10) >>> test() | ex. | watervolume | waterlevel | ---------------------------------- | 1 | 0.0 | 0.0 | | 2 | 1.0 | 0.122459 | | 3 | 2.0 | 0.231059 | | 4 | 3.0 | 0.317574 | | 5 | 4.0 | 0.380797 | | 6 | 5.0 | 0.424142 | | 7 | 6.0 | 0.452574 | | 8 | 7.0 | 0.470688 | | 9 | 8.0 | 0.482014 | | 10 | 9.0 | 0.489013 | For more realistic approximations of measured relationships between water level and volume, larger neural networks are required. """ con = self.parameters.control.fastaccess new = self.sequences.states.fastaccess_new aid = self.sequences.aides.fastaccess con.watervolume2waterlevel.inputs[0] = new.watervolume con.watervolume2waterlevel.process_actual_input() aid.waterlevel = con.watervolume2waterlevel.outputs[0]
Calculate the allowed maximum relieve another location is allowed to discharge into the dam. Required control parameters: |HighestRemoteRelieve| |WaterLevelRelieveThreshold| Required derived parameter: |WaterLevelRelieveSmoothPar| Required aide sequence: |WaterLevel| Calculated flux sequence: |AllowedRemoteRelieve| Basic equation: :math:`ActualRemoteRelease = HighestRemoteRelease \\cdot smooth_{logistic1}(WaterLevelRelieveThreshold-WaterLevel, WaterLevelRelieveSmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: All control parameters that are involved in the calculation of |AllowedRemoteRelieve| are derived from |SeasonalParameter|. This allows to simulate seasonal dam control schemes. To show how this works, we first define a short simulation time period of only two days: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Now we prepare the dam model and define two different control schemes for the hydrological summer (April to October) and winter month (November to May) >>> from hydpy.models.dam import * >>> parameterstep() >>> highestremoterelieve(_11_1_12=1.0, _03_31_12=1.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> waterlevelrelievethreshold(_11_1_12=3.0, _03_31_12=2.0, ... _04_1_12=4.0, _10_31_12=4.0) >>> waterlevelrelievetolerance(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=1.0, _10_31_12=1.0) >>> derived.waterlevelrelievesmoothpar.update() >>> derived.toy.update() The following test function is supposed to calculate |AllowedRemoteRelieve| for values of |WaterLevel| ranging from 0 and 8 m: >>> from hydpy import UnitTest >>> test = UnitTest(model, ... model.calc_allowedremoterelieve_v2, ... last_example=9, ... parseqs=(aides.waterlevel, ... fluxes.allowedremoterelieve)) >>> test.nexts.waterlevel = range(9) On March 30 (which is the last day of the winter month and the first day of the simulation period), the value of |WaterLevelRelieveSmoothPar| is zero. Hence, |AllowedRemoteRelieve| drops abruptly from 1 m³/s (the value of |HighestRemoteRelieve|) to 0 m³/s, as soon as |WaterLevel| reaches 3 m (the value of |WaterLevelRelieveThreshold|): >>> model.idx_sim = pub.timegrids.init['2001.03.30'] >>> test(first_example=2, last_example=6) | ex. | waterlevel | allowedremoterelieve | ------------------------------------------- | 3 | 1.0 | 1.0 | | 4 | 2.0 | 1.0 | | 5 | 3.0 | 0.0 | | 6 | 4.0 | 0.0 | On April 1 (which is the first day of the sommer month and the last day of the simulation period), all parameter values are increased. The value of parameter |WaterLevelRelieveSmoothPar| is 1 m. Hence, loosely speaking, |AllowedRemoteRelieve| approaches the "discontinuous extremes (2 m³/s -- which is the value of |HighestRemoteRelieve| -- and 0 m³/s) to 99 % within a span of 2 m³/s around the original threshold value of 4 m³/s defined by |WaterLevelRelieveThreshold|: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | waterlevel | allowedremoterelieve | ------------------------------------------- | 1 | 0.0 | 2.0 | | 2 | 1.0 | 1.999998 | | 3 | 2.0 | 1.999796 | | 4 | 3.0 | 1.98 | | 5 | 4.0 | 1.0 | | 6 | 5.0 | 0.02 | | 7 | 6.0 | 0.000204 | | 8 | 7.0 | 0.000002 | | 9 | 8.0 | 0.0 | def calc_allowedremoterelieve_v2(self): """Calculate the allowed maximum relieve another location is allowed to discharge into the dam. Required control parameters: |HighestRemoteRelieve| |WaterLevelRelieveThreshold| Required derived parameter: |WaterLevelRelieveSmoothPar| Required aide sequence: |WaterLevel| Calculated flux sequence: |AllowedRemoteRelieve| Basic equation: :math:`ActualRemoteRelease = HighestRemoteRelease \\cdot smooth_{logistic1}(WaterLevelRelieveThreshold-WaterLevel, WaterLevelRelieveSmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: All control parameters that are involved in the calculation of |AllowedRemoteRelieve| are derived from |SeasonalParameter|. This allows to simulate seasonal dam control schemes. To show how this works, we first define a short simulation time period of only two days: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Now we prepare the dam model and define two different control schemes for the hydrological summer (April to October) and winter month (November to May) >>> from hydpy.models.dam import * >>> parameterstep() >>> highestremoterelieve(_11_1_12=1.0, _03_31_12=1.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> waterlevelrelievethreshold(_11_1_12=3.0, _03_31_12=2.0, ... _04_1_12=4.0, _10_31_12=4.0) >>> waterlevelrelievetolerance(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=1.0, _10_31_12=1.0) >>> derived.waterlevelrelievesmoothpar.update() >>> derived.toy.update() The following test function is supposed to calculate |AllowedRemoteRelieve| for values of |WaterLevel| ranging from 0 and 8 m: >>> from hydpy import UnitTest >>> test = UnitTest(model, ... model.calc_allowedremoterelieve_v2, ... last_example=9, ... parseqs=(aides.waterlevel, ... fluxes.allowedremoterelieve)) >>> test.nexts.waterlevel = range(9) On March 30 (which is the last day of the winter month and the first day of the simulation period), the value of |WaterLevelRelieveSmoothPar| is zero. Hence, |AllowedRemoteRelieve| drops abruptly from 1 m³/s (the value of |HighestRemoteRelieve|) to 0 m³/s, as soon as |WaterLevel| reaches 3 m (the value of |WaterLevelRelieveThreshold|): >>> model.idx_sim = pub.timegrids.init['2001.03.30'] >>> test(first_example=2, last_example=6) | ex. | waterlevel | allowedremoterelieve | ------------------------------------------- | 3 | 1.0 | 1.0 | | 4 | 2.0 | 1.0 | | 5 | 3.0 | 0.0 | | 6 | 4.0 | 0.0 | On April 1 (which is the first day of the sommer month and the last day of the simulation period), all parameter values are increased. The value of parameter |WaterLevelRelieveSmoothPar| is 1 m. Hence, loosely speaking, |AllowedRemoteRelieve| approaches the "discontinuous extremes (2 m³/s -- which is the value of |HighestRemoteRelieve| -- and 0 m³/s) to 99 % within a span of 2 m³/s around the original threshold value of 4 m³/s defined by |WaterLevelRelieveThreshold|: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | waterlevel | allowedremoterelieve | ------------------------------------------- | 1 | 0.0 | 2.0 | | 2 | 1.0 | 1.999998 | | 3 | 2.0 | 1.999796 | | 4 | 3.0 | 1.98 | | 5 | 4.0 | 1.0 | | 6 | 5.0 | 0.02 | | 7 | 6.0 | 0.000204 | | 8 | 7.0 | 0.000002 | | 9 | 8.0 | 0.0 | """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess aid = self.sequences.aides.fastaccess toy = der.toy[self.idx_sim] flu.allowedremoterelieve = ( con.highestremoterelieve[toy] * smoothutils.smooth_logistic1( con.waterlevelrelievethreshold[toy]-aid.waterlevel, der.waterlevelrelievesmoothpar[toy]))
Calculate the required maximum supply from another location that can be discharged into the dam. Required control parameters: |HighestRemoteSupply| |WaterLevelSupplyThreshold| Required derived parameter: |WaterLevelSupplySmoothPar| Required aide sequence: |WaterLevel| Calculated flux sequence: |RequiredRemoteSupply| Basic equation: :math:`RequiredRemoteSupply = HighestRemoteSupply \\cdot smooth_{logistic1}(WaterLevelSupplyThreshold-WaterLevel, WaterLevelSupplySmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: Method |calc_requiredremotesupply_v1| is functionally identical with method |calc_allowedremoterelieve_v2|. Hence the following examples serve for testing purposes only (see the documentation on function |calc_allowedremoterelieve_v2| for more detailed information): >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' >>> from hydpy.models.dam import * >>> parameterstep() >>> highestremotesupply(_11_1_12=1.0, _03_31_12=1.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> waterlevelsupplythreshold(_11_1_12=3.0, _03_31_12=2.0, ... _04_1_12=4.0, _10_31_12=4.0) >>> waterlevelsupplytolerance(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=1.0, _10_31_12=1.0) >>> derived.waterlevelsupplysmoothpar.update() >>> derived.toy.update() >>> from hydpy import UnitTest >>> test = UnitTest(model, ... model.calc_requiredremotesupply_v1, ... last_example=9, ... parseqs=(aides.waterlevel, ... fluxes.requiredremotesupply)) >>> test.nexts.waterlevel = range(9) >>> model.idx_sim = pub.timegrids.init['2001.03.30'] >>> test(first_example=2, last_example=6) | ex. | waterlevel | requiredremotesupply | ------------------------------------------- | 3 | 1.0 | 1.0 | | 4 | 2.0 | 1.0 | | 5 | 3.0 | 0.0 | | 6 | 4.0 | 0.0 | >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | waterlevel | requiredremotesupply | ------------------------------------------- | 1 | 0.0 | 2.0 | | 2 | 1.0 | 1.999998 | | 3 | 2.0 | 1.999796 | | 4 | 3.0 | 1.98 | | 5 | 4.0 | 1.0 | | 6 | 5.0 | 0.02 | | 7 | 6.0 | 0.000204 | | 8 | 7.0 | 0.000002 | | 9 | 8.0 | 0.0 | def calc_requiredremotesupply_v1(self): """Calculate the required maximum supply from another location that can be discharged into the dam. Required control parameters: |HighestRemoteSupply| |WaterLevelSupplyThreshold| Required derived parameter: |WaterLevelSupplySmoothPar| Required aide sequence: |WaterLevel| Calculated flux sequence: |RequiredRemoteSupply| Basic equation: :math:`RequiredRemoteSupply = HighestRemoteSupply \\cdot smooth_{logistic1}(WaterLevelSupplyThreshold-WaterLevel, WaterLevelSupplySmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: Method |calc_requiredremotesupply_v1| is functionally identical with method |calc_allowedremoterelieve_v2|. Hence the following examples serve for testing purposes only (see the documentation on function |calc_allowedremoterelieve_v2| for more detailed information): >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' >>> from hydpy.models.dam import * >>> parameterstep() >>> highestremotesupply(_11_1_12=1.0, _03_31_12=1.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> waterlevelsupplythreshold(_11_1_12=3.0, _03_31_12=2.0, ... _04_1_12=4.0, _10_31_12=4.0) >>> waterlevelsupplytolerance(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=1.0, _10_31_12=1.0) >>> derived.waterlevelsupplysmoothpar.update() >>> derived.toy.update() >>> from hydpy import UnitTest >>> test = UnitTest(model, ... model.calc_requiredremotesupply_v1, ... last_example=9, ... parseqs=(aides.waterlevel, ... fluxes.requiredremotesupply)) >>> test.nexts.waterlevel = range(9) >>> model.idx_sim = pub.timegrids.init['2001.03.30'] >>> test(first_example=2, last_example=6) | ex. | waterlevel | requiredremotesupply | ------------------------------------------- | 3 | 1.0 | 1.0 | | 4 | 2.0 | 1.0 | | 5 | 3.0 | 0.0 | | 6 | 4.0 | 0.0 | >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | waterlevel | requiredremotesupply | ------------------------------------------- | 1 | 0.0 | 2.0 | | 2 | 1.0 | 1.999998 | | 3 | 2.0 | 1.999796 | | 4 | 3.0 | 1.98 | | 5 | 4.0 | 1.0 | | 6 | 5.0 | 0.02 | | 7 | 6.0 | 0.000204 | | 8 | 7.0 | 0.000002 | | 9 | 8.0 | 0.0 | """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess aid = self.sequences.aides.fastaccess toy = der.toy[self.idx_sim] flu.requiredremotesupply = ( con.highestremotesupply[toy] * smoothutils.smooth_logistic1( con.waterlevelsupplythreshold[toy]-aid.waterlevel, der.waterlevelsupplysmoothpar[toy]))
Try to estimate the natural discharge of a cross section far downstream based on the last few simulation steps. Required control parameter: |NmbLogEntries| Required log sequences: |LoggedTotalRemoteDischarge| |LoggedOutflow| Calculated flux sequence: |NaturalRemoteDischarge| Basic equation: :math:`RemoteDemand = max(\\frac{\\Sigma(LoggedTotalRemoteDischarge - LoggedOutflow)} {NmbLogEntries}), 0)` Examples: Usually, the mean total remote flow should be larger than the mean dam outflows. Then the estimated natural remote discharge is simply the difference of both mean values: >>> from hydpy.models.dam import * >>> parameterstep() >>> nmblogentries(3) >>> logs.loggedtotalremotedischarge(2.5, 2.0, 1.5) >>> logs.loggedoutflow(2.0, 1.0, 0.0) >>> model.calc_naturalremotedischarge_v1() >>> fluxes.naturalremotedischarge naturalremotedischarge(1.0) Due to the wave travel times, the difference between remote discharge and dam outflow mights sometimes be negative. To avoid negative estimates of natural discharge, it its value is set to zero in such cases: >>> logs.loggedoutflow(4.0, 3.0, 5.0) >>> model.calc_naturalremotedischarge_v1() >>> fluxes.naturalremotedischarge naturalremotedischarge(0.0) def calc_naturalremotedischarge_v1(self): """Try to estimate the natural discharge of a cross section far downstream based on the last few simulation steps. Required control parameter: |NmbLogEntries| Required log sequences: |LoggedTotalRemoteDischarge| |LoggedOutflow| Calculated flux sequence: |NaturalRemoteDischarge| Basic equation: :math:`RemoteDemand = max(\\frac{\\Sigma(LoggedTotalRemoteDischarge - LoggedOutflow)} {NmbLogEntries}), 0)` Examples: Usually, the mean total remote flow should be larger than the mean dam outflows. Then the estimated natural remote discharge is simply the difference of both mean values: >>> from hydpy.models.dam import * >>> parameterstep() >>> nmblogentries(3) >>> logs.loggedtotalremotedischarge(2.5, 2.0, 1.5) >>> logs.loggedoutflow(2.0, 1.0, 0.0) >>> model.calc_naturalremotedischarge_v1() >>> fluxes.naturalremotedischarge naturalremotedischarge(1.0) Due to the wave travel times, the difference between remote discharge and dam outflow mights sometimes be negative. To avoid negative estimates of natural discharge, it its value is set to zero in such cases: >>> logs.loggedoutflow(4.0, 3.0, 5.0) >>> model.calc_naturalremotedischarge_v1() >>> fluxes.naturalremotedischarge naturalremotedischarge(0.0) """ con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess flu.naturalremotedischarge = 0. for idx in range(con.nmblogentries): flu.naturalremotedischarge += ( log.loggedtotalremotedischarge[idx] - log.loggedoutflow[idx]) if flu.naturalremotedischarge > 0.: flu.naturalremotedischarge /= con.nmblogentries else: flu.naturalremotedischarge = 0.
Estimate the discharge demand of a cross section far downstream. Required control parameter: |RemoteDischargeMinimum| Required derived parameters: |dam_derived.TOY| Required flux sequence: |dam_derived.TOY| Calculated flux sequence: |RemoteDemand| Basic equation: :math:`RemoteDemand = max(RemoteDischargeMinimum - NaturalRemoteDischarge, 0` Examples: Low water elevation is often restricted to specific month of the year. Sometimes the pursued lowest discharge value varies over the year to allow for a low flow variability that is in some agreement with the natural flow regime. The HydPy-Dam model supports such variations. Hence we define a short simulation time period first. This enables us to show how the related parameters values can be defined and how the calculation of the `remote` water demand throughout the year actually works: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() Assume the required discharge at a gauge downstream being 2 m³/s in the hydrological summer half-year (April to October). In the winter month (November to May), there is no such requirement: >>> remotedischargeminimum(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> derived.toy.update() Prepare a test function, that calculates the remote discharge demand based on the parameter values defined above and for natural remote discharge values ranging between 0 and 3 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_remotedemand_v1, last_example=4, ... parseqs=(fluxes.naturalremotedischarge, ... fluxes.remotedemand)) >>> test.nexts.naturalremotedischarge = range(4) On April 1, the required discharge is 2 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | naturalremotedischarge | remotedemand | ----------------------------------------------- | 1 | 0.0 | 2.0 | | 2 | 1.0 | 1.0 | | 3 | 2.0 | 0.0 | | 4 | 3.0 | 0.0 | On May 31, the required discharge is 0 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | naturalremotedischarge | remotedemand | ----------------------------------------------- | 1 | 0.0 | 0.0 | | 2 | 1.0 | 0.0 | | 3 | 2.0 | 0.0 | | 4 | 3.0 | 0.0 | def calc_remotedemand_v1(self): """Estimate the discharge demand of a cross section far downstream. Required control parameter: |RemoteDischargeMinimum| Required derived parameters: |dam_derived.TOY| Required flux sequence: |dam_derived.TOY| Calculated flux sequence: |RemoteDemand| Basic equation: :math:`RemoteDemand = max(RemoteDischargeMinimum - NaturalRemoteDischarge, 0` Examples: Low water elevation is often restricted to specific month of the year. Sometimes the pursued lowest discharge value varies over the year to allow for a low flow variability that is in some agreement with the natural flow regime. The HydPy-Dam model supports such variations. Hence we define a short simulation time period first. This enables us to show how the related parameters values can be defined and how the calculation of the `remote` water demand throughout the year actually works: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() Assume the required discharge at a gauge downstream being 2 m³/s in the hydrological summer half-year (April to October). In the winter month (November to May), there is no such requirement: >>> remotedischargeminimum(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> derived.toy.update() Prepare a test function, that calculates the remote discharge demand based on the parameter values defined above and for natural remote discharge values ranging between 0 and 3 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_remotedemand_v1, last_example=4, ... parseqs=(fluxes.naturalremotedischarge, ... fluxes.remotedemand)) >>> test.nexts.naturalremotedischarge = range(4) On April 1, the required discharge is 2 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | naturalremotedischarge | remotedemand | ----------------------------------------------- | 1 | 0.0 | 2.0 | | 2 | 1.0 | 1.0 | | 3 | 2.0 | 0.0 | | 4 | 3.0 | 0.0 | On May 31, the required discharge is 0 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | naturalremotedischarge | remotedemand | ----------------------------------------------- | 1 | 0.0 | 0.0 | | 2 | 1.0 | 0.0 | | 3 | 2.0 | 0.0 | | 4 | 3.0 | 0.0 | """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess flu.remotedemand = max(con.remotedischargeminimum[der.toy[self.idx_sim]] - flu.naturalremotedischarge, 0.)
Estimate the shortfall of actual discharge under the required discharge of a cross section far downstream. Required control parameters: |NmbLogEntries| |RemoteDischargeMinimum| Required derived parameters: |dam_derived.TOY| Required log sequence: |LoggedTotalRemoteDischarge| Calculated flux sequence: |RemoteFailure| Basic equation: :math:`RemoteFailure = \\frac{\\Sigma(LoggedTotalRemoteDischarge)}{NmbLogEntries} - RemoteDischargeMinimum` Examples: As explained in the documentation on method |calc_remotedemand_v1|, we have to define a simulation period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Now we prepare a dam model with log sequences memorizing three values: >>> from hydpy.models.dam import * >>> parameterstep() >>> nmblogentries(3) Again, the required discharge is 2 m³/s in summer and 0 m³/s in winter: >>> remotedischargeminimum(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> derived.toy.update() Let it be supposed that the actual discharge at the remote cross section droped from 2 m³/s to 0 m³/s over the last three days: >>> logs.loggedtotalremotedischarge(0.0, 1.0, 2.0) This means that for the April 1 there would have been an averaged shortfall of 1 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> model.calc_remotefailure_v1() >>> fluxes.remotefailure remotefailure(1.0) Instead for May 31 there would have been an excess of 1 m³/s, which is interpreted to be a "negative failure": >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> model.calc_remotefailure_v1() >>> fluxes.remotefailure remotefailure(-1.0) def calc_remotefailure_v1(self): """Estimate the shortfall of actual discharge under the required discharge of a cross section far downstream. Required control parameters: |NmbLogEntries| |RemoteDischargeMinimum| Required derived parameters: |dam_derived.TOY| Required log sequence: |LoggedTotalRemoteDischarge| Calculated flux sequence: |RemoteFailure| Basic equation: :math:`RemoteFailure = \\frac{\\Sigma(LoggedTotalRemoteDischarge)}{NmbLogEntries} - RemoteDischargeMinimum` Examples: As explained in the documentation on method |calc_remotedemand_v1|, we have to define a simulation period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Now we prepare a dam model with log sequences memorizing three values: >>> from hydpy.models.dam import * >>> parameterstep() >>> nmblogentries(3) Again, the required discharge is 2 m³/s in summer and 0 m³/s in winter: >>> remotedischargeminimum(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> derived.toy.update() Let it be supposed that the actual discharge at the remote cross section droped from 2 m³/s to 0 m³/s over the last three days: >>> logs.loggedtotalremotedischarge(0.0, 1.0, 2.0) This means that for the April 1 there would have been an averaged shortfall of 1 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> model.calc_remotefailure_v1() >>> fluxes.remotefailure remotefailure(1.0) Instead for May 31 there would have been an excess of 1 m³/s, which is interpreted to be a "negative failure": >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> model.calc_remotefailure_v1() >>> fluxes.remotefailure remotefailure(-1.0) """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess flu.remotefailure = 0 for idx in range(con.nmblogentries): flu.remotefailure -= log.loggedtotalremotedischarge[idx] flu.remotefailure /= con.nmblogentries flu.remotefailure += con.remotedischargeminimum[der.toy[self.idx_sim]]
Guess the required release necessary to not fall below the threshold value at a cross section far downstream with a certain level of certainty. Required control parameter: |RemoteDischargeSafety| Required derived parameters: |RemoteDischargeSmoothPar| |dam_derived.TOY| Required flux sequence: |RemoteDemand| |RemoteFailure| Calculated flux sequence: |RequiredRemoteRelease| Basic equation: :math:`RequiredRemoteRelease = RemoteDemand + RemoteDischargeSafety \\cdot smooth_{logistic1}(RemoteFailure, RemoteDischargeSmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: As in the examples above, define a short simulation time period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.toy.update() Define a safety factor of 0.5 m³/s for the summer months and no safety factor at all for the winter months: >>> remotedischargesafety(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=1.0, _10_31_12=1.0) >>> derived.remotedischargesmoothpar.update() Assume the actual demand at the cross section downsstream has actually been estimated to be 2 m³/s: >>> fluxes.remotedemand = 2.0 Prepare a test function, that calculates the required discharge based on the parameter values defined above and for a "remote failure" values ranging between -4 and 4 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_requiredremoterelease_v1, ... last_example=9, ... parseqs=(fluxes.remotefailure, ... fluxes.requiredremoterelease)) >>> test.nexts.remotefailure = range(-4, 5) On May 31, the safety factor is 0 m³/s. Hence no discharge is added to the estimated remote demand of 2 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | remotefailure | requiredremoterelease | ----------------------------------------------- | 1 | -4.0 | 2.0 | | 2 | -3.0 | 2.0 | | 3 | -2.0 | 2.0 | | 4 | -1.0 | 2.0 | | 5 | 0.0 | 2.0 | | 6 | 1.0 | 2.0 | | 7 | 2.0 | 2.0 | | 8 | 3.0 | 2.0 | | 9 | 4.0 | 2.0 | On April 1, the safety factor is 1 m³/s. If the remote failure was exactly zero in the past, meaning the control of the dam was perfect, only 0.5 m³/s are added to the estimated remote demand of 2 m³/s. If the actual recharge did actually fall below the threshold value, up to 1 m³/s is added. If the the actual discharge exceeded the threshold value by 2 or 3 m³/s, virtually nothing is added: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | remotefailure | requiredremoterelease | ----------------------------------------------- | 1 | -4.0 | 2.0 | | 2 | -3.0 | 2.000001 | | 3 | -2.0 | 2.000102 | | 4 | -1.0 | 2.01 | | 5 | 0.0 | 2.5 | | 6 | 1.0 | 2.99 | | 7 | 2.0 | 2.999898 | | 8 | 3.0 | 2.999999 | | 9 | 4.0 | 3.0 | def calc_requiredremoterelease_v1(self): """Guess the required release necessary to not fall below the threshold value at a cross section far downstream with a certain level of certainty. Required control parameter: |RemoteDischargeSafety| Required derived parameters: |RemoteDischargeSmoothPar| |dam_derived.TOY| Required flux sequence: |RemoteDemand| |RemoteFailure| Calculated flux sequence: |RequiredRemoteRelease| Basic equation: :math:`RequiredRemoteRelease = RemoteDemand + RemoteDischargeSafety \\cdot smooth_{logistic1}(RemoteFailure, RemoteDischargeSmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: As in the examples above, define a short simulation time period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.toy.update() Define a safety factor of 0.5 m³/s for the summer months and no safety factor at all for the winter months: >>> remotedischargesafety(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=1.0, _10_31_12=1.0) >>> derived.remotedischargesmoothpar.update() Assume the actual demand at the cross section downsstream has actually been estimated to be 2 m³/s: >>> fluxes.remotedemand = 2.0 Prepare a test function, that calculates the required discharge based on the parameter values defined above and for a "remote failure" values ranging between -4 and 4 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_requiredremoterelease_v1, ... last_example=9, ... parseqs=(fluxes.remotefailure, ... fluxes.requiredremoterelease)) >>> test.nexts.remotefailure = range(-4, 5) On May 31, the safety factor is 0 m³/s. Hence no discharge is added to the estimated remote demand of 2 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | remotefailure | requiredremoterelease | ----------------------------------------------- | 1 | -4.0 | 2.0 | | 2 | -3.0 | 2.0 | | 3 | -2.0 | 2.0 | | 4 | -1.0 | 2.0 | | 5 | 0.0 | 2.0 | | 6 | 1.0 | 2.0 | | 7 | 2.0 | 2.0 | | 8 | 3.0 | 2.0 | | 9 | 4.0 | 2.0 | On April 1, the safety factor is 1 m³/s. If the remote failure was exactly zero in the past, meaning the control of the dam was perfect, only 0.5 m³/s are added to the estimated remote demand of 2 m³/s. If the actual recharge did actually fall below the threshold value, up to 1 m³/s is added. If the the actual discharge exceeded the threshold value by 2 or 3 m³/s, virtually nothing is added: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | remotefailure | requiredremoterelease | ----------------------------------------------- | 1 | -4.0 | 2.0 | | 2 | -3.0 | 2.000001 | | 3 | -2.0 | 2.000102 | | 4 | -1.0 | 2.01 | | 5 | 0.0 | 2.5 | | 6 | 1.0 | 2.99 | | 7 | 2.0 | 2.999898 | | 8 | 3.0 | 2.999999 | | 9 | 4.0 | 3.0 | """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess flu.requiredremoterelease = ( flu.remotedemand+con.remotedischargesafety[der.toy[self.idx_sim]] * smoothutils.smooth_logistic1( flu.remotefailure, der.remotedischargesmoothpar[der.toy[self.idx_sim]]))
Get the required remote release of the last simulation step. Required log sequence: |LoggedRequiredRemoteRelease| Calculated flux sequence: |RequiredRemoteRelease| Basic equation: :math:`RequiredRemoteRelease = LoggedRequiredRemoteRelease` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> logs.loggedrequiredremoterelease = 3.0 >>> model.calc_requiredremoterelease_v2() >>> fluxes.requiredremoterelease requiredremoterelease(3.0) def calc_requiredremoterelease_v2(self): """Get the required remote release of the last simulation step. Required log sequence: |LoggedRequiredRemoteRelease| Calculated flux sequence: |RequiredRemoteRelease| Basic equation: :math:`RequiredRemoteRelease = LoggedRequiredRemoteRelease` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> logs.loggedrequiredremoterelease = 3.0 >>> model.calc_requiredremoterelease_v2() >>> fluxes.requiredremoterelease requiredremoterelease(3.0) """ flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess flu.requiredremoterelease = log.loggedrequiredremoterelease[0]
Get the allowed remote relieve of the last simulation step. Required log sequence: |LoggedAllowedRemoteRelieve| Calculated flux sequence: |AllowedRemoteRelieve| Basic equation: :math:`AllowedRemoteRelieve = LoggedAllowedRemoteRelieve` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> logs.loggedallowedremoterelieve = 2.0 >>> model.calc_allowedremoterelieve_v1() >>> fluxes.allowedremoterelieve allowedremoterelieve(2.0) def calc_allowedremoterelieve_v1(self): """Get the allowed remote relieve of the last simulation step. Required log sequence: |LoggedAllowedRemoteRelieve| Calculated flux sequence: |AllowedRemoteRelieve| Basic equation: :math:`AllowedRemoteRelieve = LoggedAllowedRemoteRelieve` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> logs.loggedallowedremoterelieve = 2.0 >>> model.calc_allowedremoterelieve_v1() >>> fluxes.allowedremoterelieve allowedremoterelieve(2.0) """ flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess flu.allowedremoterelieve = log.loggedallowedremoterelieve[0]
Calculate the total water release (immediately and far downstream) required for reducing drought events. Required control parameter: |NearDischargeMinimumThreshold| Required derived parameters: |NearDischargeMinimumSmoothPar2| |dam_derived.TOY| Required flux sequence: |RequiredRemoteRelease| Calculated flux sequence: |RequiredRelease| Basic equation: :math:`RequiredRelease = RequiredRemoteRelease \\cdot smooth_{logistic2}( RequiredRemoteRelease-NearDischargeMinimumThreshold, NearDischargeMinimumSmoothPar2)` Used auxiliary method: |smooth_logistic2| Examples: As in the examples above, define a short simulation time period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.toy.update() Define a minimum discharge value for a cross section immediately downstream of 4 m³/s for the summer months and of 0 m³/s for the winter months: >>> neardischargeminimumthreshold(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=4.0, _10_31_12=4.0) Also define related tolerance values that are 1 m³/s in summer and 0 m³/s in winter: >>> neardischargeminimumtolerance(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=1.0, _10_31_12=1.0) >>> derived.neardischargeminimumsmoothpar2.update() Prepare a test function, that calculates the required total discharge based on the parameter values defined above and for a required value for a cross section far downstream ranging from 0 m³/s to 8 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_requiredrelease_v1, ... last_example=9, ... parseqs=(fluxes.requiredremoterelease, ... fluxes.requiredrelease)) >>> test.nexts.requiredremoterelease = range(9) On May 31, both the threshold and the tolerance value are 0 m³/s. Hence the required total and the required remote release are equal: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | requiredremoterelease | requiredrelease | ------------------------------------------------- | 1 | 0.0 | 0.0 | | 2 | 1.0 | 1.0 | | 3 | 2.0 | 2.0 | | 4 | 3.0 | 3.0 | | 5 | 4.0 | 4.0 | | 6 | 5.0 | 5.0 | | 7 | 6.0 | 6.0 | | 8 | 7.0 | 7.0 | | 9 | 8.0 | 8.0 | On April 1, the threshold value is 4 m³/s and the tolerance value is 1 m³/s. For low values of the required remote release, the required total release approximates the threshold value. For large values, it approximates the required remote release itself. Around the threshold value, due to the tolerance value of 1 m³/s, the required total release is a little larger than both the treshold value and the required remote release value: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | requiredremoterelease | requiredrelease | ------------------------------------------------- | 1 | 0.0 | 4.0 | | 2 | 1.0 | 4.000012 | | 3 | 2.0 | 4.000349 | | 4 | 3.0 | 4.01 | | 5 | 4.0 | 4.205524 | | 6 | 5.0 | 5.01 | | 7 | 6.0 | 6.000349 | | 8 | 7.0 | 7.000012 | | 9 | 8.0 | 8.0 | def calc_requiredrelease_v1(self): """Calculate the total water release (immediately and far downstream) required for reducing drought events. Required control parameter: |NearDischargeMinimumThreshold| Required derived parameters: |NearDischargeMinimumSmoothPar2| |dam_derived.TOY| Required flux sequence: |RequiredRemoteRelease| Calculated flux sequence: |RequiredRelease| Basic equation: :math:`RequiredRelease = RequiredRemoteRelease \\cdot smooth_{logistic2}( RequiredRemoteRelease-NearDischargeMinimumThreshold, NearDischargeMinimumSmoothPar2)` Used auxiliary method: |smooth_logistic2| Examples: As in the examples above, define a short simulation time period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.toy.update() Define a minimum discharge value for a cross section immediately downstream of 4 m³/s for the summer months and of 0 m³/s for the winter months: >>> neardischargeminimumthreshold(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=4.0, _10_31_12=4.0) Also define related tolerance values that are 1 m³/s in summer and 0 m³/s in winter: >>> neardischargeminimumtolerance(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=1.0, _10_31_12=1.0) >>> derived.neardischargeminimumsmoothpar2.update() Prepare a test function, that calculates the required total discharge based on the parameter values defined above and for a required value for a cross section far downstream ranging from 0 m³/s to 8 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_requiredrelease_v1, ... last_example=9, ... parseqs=(fluxes.requiredremoterelease, ... fluxes.requiredrelease)) >>> test.nexts.requiredremoterelease = range(9) On May 31, both the threshold and the tolerance value are 0 m³/s. Hence the required total and the required remote release are equal: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | requiredremoterelease | requiredrelease | ------------------------------------------------- | 1 | 0.0 | 0.0 | | 2 | 1.0 | 1.0 | | 3 | 2.0 | 2.0 | | 4 | 3.0 | 3.0 | | 5 | 4.0 | 4.0 | | 6 | 5.0 | 5.0 | | 7 | 6.0 | 6.0 | | 8 | 7.0 | 7.0 | | 9 | 8.0 | 8.0 | On April 1, the threshold value is 4 m³/s and the tolerance value is 1 m³/s. For low values of the required remote release, the required total release approximates the threshold value. For large values, it approximates the required remote release itself. Around the threshold value, due to the tolerance value of 1 m³/s, the required total release is a little larger than both the treshold value and the required remote release value: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | requiredremoterelease | requiredrelease | ------------------------------------------------- | 1 | 0.0 | 4.0 | | 2 | 1.0 | 4.000012 | | 3 | 2.0 | 4.000349 | | 4 | 3.0 | 4.01 | | 5 | 4.0 | 4.205524 | | 6 | 5.0 | 5.01 | | 7 | 6.0 | 6.000349 | | 8 | 7.0 | 7.000012 | | 9 | 8.0 | 8.0 | """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess flu.requiredrelease = con.neardischargeminimumthreshold[ der.toy[self.idx_sim]] flu.requiredrelease = ( flu.requiredrelease + smoothutils.smooth_logistic2( flu.requiredremoterelease-flu.requiredrelease, der.neardischargeminimumsmoothpar2[ der.toy[self.idx_sim]]))
Calculate the water release (immediately downstream) required for reducing drought events. Required control parameter: |NearDischargeMinimumThreshold| Required derived parameter: |dam_derived.TOY| Calculated flux sequence: |RequiredRelease| Basic equation: :math:`RequiredRelease = NearDischargeMinimumThreshold` Examples: As in the examples above, define a short simulation time period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.toy.update() Define a minimum discharge value for a cross section immediately downstream of 4 m³/s for the summer months and of 0 m³/s for the winter months: >>> neardischargeminimumthreshold(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=4.0, _10_31_12=4.0) As to be expected, the calculated required release is 0.0 m³/s on May 31 and 4.0 m³/s on April 1: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> model.calc_requiredrelease_v2() >>> fluxes.requiredrelease requiredrelease(0.0) >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> model.calc_requiredrelease_v2() >>> fluxes.requiredrelease requiredrelease(4.0) def calc_requiredrelease_v2(self): """Calculate the water release (immediately downstream) required for reducing drought events. Required control parameter: |NearDischargeMinimumThreshold| Required derived parameter: |dam_derived.TOY| Calculated flux sequence: |RequiredRelease| Basic equation: :math:`RequiredRelease = NearDischargeMinimumThreshold` Examples: As in the examples above, define a short simulation time period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.toy.update() Define a minimum discharge value for a cross section immediately downstream of 4 m³/s for the summer months and of 0 m³/s for the winter months: >>> neardischargeminimumthreshold(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=4.0, _10_31_12=4.0) As to be expected, the calculated required release is 0.0 m³/s on May 31 and 4.0 m³/s on April 1: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> model.calc_requiredrelease_v2() >>> fluxes.requiredrelease requiredrelease(0.0) >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> model.calc_requiredrelease_v2() >>> fluxes.requiredrelease requiredrelease(4.0) """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess flu.requiredrelease = con.neardischargeminimumthreshold[ der.toy[self.idx_sim]]
Calculate the highest possible water release that can be routed to a remote location based on an artificial neural network describing the relationship between possible release and water stage. Required control parameter: |WaterLevel2PossibleRemoteRelieve| Required aide sequence: |WaterLevel| Calculated flux sequence: |PossibleRemoteRelieve| Example: For simplicity, the example of method |calc_flooddischarge_v1| is reused. See the documentation on the mentioned method for further information: >>> from hydpy.models.dam import * >>> parameterstep() >>> waterlevel2possibleremoterelieve( ... nmb_inputs=1, ... nmb_neurons=(2,), ... nmb_outputs=1, ... weights_input=[[50., 4]], ... weights_output=[[2.], [30]], ... intercepts_hidden=[[-13000, -1046]], ... intercepts_output=[0.]) >>> from hydpy import UnitTest >>> test = UnitTest( ... model, model.calc_possibleremoterelieve_v1, ... last_example=21, ... parseqs=(aides.waterlevel, fluxes.possibleremoterelieve)) >>> test.nexts.waterlevel = numpy.arange(257, 261.1, 0.2) >>> test() | ex. | waterlevel | possibleremoterelieve | -------------------------------------------- | 1 | 257.0 | 0.0 | | 2 | 257.2 | 0.000001 | | 3 | 257.4 | 0.000002 | | 4 | 257.6 | 0.000005 | | 5 | 257.8 | 0.000011 | | 6 | 258.0 | 0.000025 | | 7 | 258.2 | 0.000056 | | 8 | 258.4 | 0.000124 | | 9 | 258.6 | 0.000275 | | 10 | 258.8 | 0.000612 | | 11 | 259.0 | 0.001362 | | 12 | 259.2 | 0.003031 | | 13 | 259.4 | 0.006745 | | 14 | 259.6 | 0.015006 | | 15 | 259.8 | 0.033467 | | 16 | 260.0 | 1.074179 | | 17 | 260.2 | 2.164498 | | 18 | 260.4 | 2.363853 | | 19 | 260.6 | 2.79791 | | 20 | 260.8 | 3.719725 | | 21 | 261.0 | 5.576088 | def calc_possibleremoterelieve_v1(self): """Calculate the highest possible water release that can be routed to a remote location based on an artificial neural network describing the relationship between possible release and water stage. Required control parameter: |WaterLevel2PossibleRemoteRelieve| Required aide sequence: |WaterLevel| Calculated flux sequence: |PossibleRemoteRelieve| Example: For simplicity, the example of method |calc_flooddischarge_v1| is reused. See the documentation on the mentioned method for further information: >>> from hydpy.models.dam import * >>> parameterstep() >>> waterlevel2possibleremoterelieve( ... nmb_inputs=1, ... nmb_neurons=(2,), ... nmb_outputs=1, ... weights_input=[[50., 4]], ... weights_output=[[2.], [30]], ... intercepts_hidden=[[-13000, -1046]], ... intercepts_output=[0.]) >>> from hydpy import UnitTest >>> test = UnitTest( ... model, model.calc_possibleremoterelieve_v1, ... last_example=21, ... parseqs=(aides.waterlevel, fluxes.possibleremoterelieve)) >>> test.nexts.waterlevel = numpy.arange(257, 261.1, 0.2) >>> test() | ex. | waterlevel | possibleremoterelieve | -------------------------------------------- | 1 | 257.0 | 0.0 | | 2 | 257.2 | 0.000001 | | 3 | 257.4 | 0.000002 | | 4 | 257.6 | 0.000005 | | 5 | 257.8 | 0.000011 | | 6 | 258.0 | 0.000025 | | 7 | 258.2 | 0.000056 | | 8 | 258.4 | 0.000124 | | 9 | 258.6 | 0.000275 | | 10 | 258.8 | 0.000612 | | 11 | 259.0 | 0.001362 | | 12 | 259.2 | 0.003031 | | 13 | 259.4 | 0.006745 | | 14 | 259.6 | 0.015006 | | 15 | 259.8 | 0.033467 | | 16 | 260.0 | 1.074179 | | 17 | 260.2 | 2.164498 | | 18 | 260.4 | 2.363853 | | 19 | 260.6 | 2.79791 | | 20 | 260.8 | 3.719725 | | 21 | 261.0 | 5.576088 | """ con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess aid = self.sequences.aides.fastaccess con.waterlevel2possibleremoterelieve.inputs[0] = aid.waterlevel con.waterlevel2possibleremoterelieve.process_actual_input() flu.possibleremoterelieve = con.waterlevel2possibleremoterelieve.outputs[0]
Calculate the actual amount of water released to a remote location to relieve the dam during high flow conditions. Required control parameter: |RemoteRelieveTolerance| Required flux sequences: |AllowedRemoteRelieve| |PossibleRemoteRelieve| Calculated flux sequence: |ActualRemoteRelieve| Basic equation - discontinous: :math:`ActualRemoteRelease = min(PossibleRemoteRelease, AllowedRemoteRelease)` Basic equation - continous: :math:`ActualRemoteRelease = smooth_min1(PossibleRemoteRelease, AllowedRemoteRelease, RemoteRelieveTolerance)` Used auxiliary methods: |smooth_min1| |smooth_max1| Note that the given continous basic equation is a simplification of the complete algorithm to calculate |ActualRemoteRelieve|, which also makes use of |smooth_max1| to prevent from gaining negative values in a smooth manner. Examples: Prepare a dam model: >>> from hydpy.models.dam import * >>> parameterstep() Prepare a test function object that performs seven examples with |PossibleRemoteRelieve| ranging from -1 to 5 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_actualremoterelieve_v1, ... last_example=7, ... parseqs=(fluxes.possibleremoterelieve, ... fluxes.actualremoterelieve)) >>> test.nexts.possibleremoterelieve = range(-1, 6) We begin with a |AllowedRemoteRelieve| value of 3 m³/s: >>> fluxes.allowedremoterelieve = 3.0 Through setting the value of |RemoteRelieveTolerance| to the lowest possible value, there is no smoothing. Instead, the relationship between |ActualRemoteRelieve| and |PossibleRemoteRelieve| follows the simple discontinous minimum function: >>> remoterelievetolerance(0.0) >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 1.0 | | 4 | 2.0 | 2.0 | | 5 | 3.0 | 3.0 | | 6 | 4.0 | 3.0 | | 7 | 5.0 | 3.0 | Increasing the value of parameter |RemoteRelieveTolerance| to a sensible value results in a moderate smoothing: >>> remoterelievetolerance(0.2) >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.970639 | | 4 | 2.0 | 1.89588 | | 5 | 3.0 | 2.584112 | | 6 | 4.0 | 2.896195 | | 7 | 5.0 | 2.978969 | Even when setting a very large smoothing parameter value, the actual remote relieve does not fall below 0 m³/s: >>> remoterelievetolerance(1.0) >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.306192 | | 4 | 2.0 | 0.634882 | | 5 | 3.0 | 1.037708 | | 6 | 4.0 | 1.436494 | | 7 | 5.0 | 1.788158 | Now we repeat the last example with a allowed remote relieve of only 0.03 m³/s instead of 3 m³/s: >>> fluxes.allowedremoterelieve = 0.03 >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.03 | | 4 | 2.0 | 0.03 | | 5 | 3.0 | 0.03 | | 6 | 4.0 | 0.03 | | 7 | 5.0 | 0.03 | The result above is as expected, but the smooth part of the relationship is not resolved. By increasing the resolution we see a relationship that corresponds to the one shown above for an allowed relieve of 3 m³/s. This points out, that the degree of smoothing is releative to the allowed relieve: >>> import numpy >>> test.nexts.possibleremoterelieve = numpy.arange(-0.01, 0.06, 0.01) >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -0.01 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 0.01 | 0.003062 | | 4 | 0.02 | 0.006349 | | 5 | 0.03 | 0.010377 | | 6 | 0.04 | 0.014365 | | 7 | 0.05 | 0.017882 | One can reperform the shown experiments with an even higher resolution to see that the relationship between |ActualRemoteRelieve| and |PossibleRemoteRelieve| is (at least in most cases) in fact very smooth. But a more analytical approach would possibly be favourable regarding the smoothness in some edge cases and computational efficiency. def calc_actualremoterelieve_v1(self): """Calculate the actual amount of water released to a remote location to relieve the dam during high flow conditions. Required control parameter: |RemoteRelieveTolerance| Required flux sequences: |AllowedRemoteRelieve| |PossibleRemoteRelieve| Calculated flux sequence: |ActualRemoteRelieve| Basic equation - discontinous: :math:`ActualRemoteRelease = min(PossibleRemoteRelease, AllowedRemoteRelease)` Basic equation - continous: :math:`ActualRemoteRelease = smooth_min1(PossibleRemoteRelease, AllowedRemoteRelease, RemoteRelieveTolerance)` Used auxiliary methods: |smooth_min1| |smooth_max1| Note that the given continous basic equation is a simplification of the complete algorithm to calculate |ActualRemoteRelieve|, which also makes use of |smooth_max1| to prevent from gaining negative values in a smooth manner. Examples: Prepare a dam model: >>> from hydpy.models.dam import * >>> parameterstep() Prepare a test function object that performs seven examples with |PossibleRemoteRelieve| ranging from -1 to 5 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_actualremoterelieve_v1, ... last_example=7, ... parseqs=(fluxes.possibleremoterelieve, ... fluxes.actualremoterelieve)) >>> test.nexts.possibleremoterelieve = range(-1, 6) We begin with a |AllowedRemoteRelieve| value of 3 m³/s: >>> fluxes.allowedremoterelieve = 3.0 Through setting the value of |RemoteRelieveTolerance| to the lowest possible value, there is no smoothing. Instead, the relationship between |ActualRemoteRelieve| and |PossibleRemoteRelieve| follows the simple discontinous minimum function: >>> remoterelievetolerance(0.0) >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 1.0 | | 4 | 2.0 | 2.0 | | 5 | 3.0 | 3.0 | | 6 | 4.0 | 3.0 | | 7 | 5.0 | 3.0 | Increasing the value of parameter |RemoteRelieveTolerance| to a sensible value results in a moderate smoothing: >>> remoterelievetolerance(0.2) >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.970639 | | 4 | 2.0 | 1.89588 | | 5 | 3.0 | 2.584112 | | 6 | 4.0 | 2.896195 | | 7 | 5.0 | 2.978969 | Even when setting a very large smoothing parameter value, the actual remote relieve does not fall below 0 m³/s: >>> remoterelievetolerance(1.0) >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.306192 | | 4 | 2.0 | 0.634882 | | 5 | 3.0 | 1.037708 | | 6 | 4.0 | 1.436494 | | 7 | 5.0 | 1.788158 | Now we repeat the last example with a allowed remote relieve of only 0.03 m³/s instead of 3 m³/s: >>> fluxes.allowedremoterelieve = 0.03 >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.03 | | 4 | 2.0 | 0.03 | | 5 | 3.0 | 0.03 | | 6 | 4.0 | 0.03 | | 7 | 5.0 | 0.03 | The result above is as expected, but the smooth part of the relationship is not resolved. By increasing the resolution we see a relationship that corresponds to the one shown above for an allowed relieve of 3 m³/s. This points out, that the degree of smoothing is releative to the allowed relieve: >>> import numpy >>> test.nexts.possibleremoterelieve = numpy.arange(-0.01, 0.06, 0.01) >>> test() | ex. | possibleremoterelieve | actualremoterelieve | ----------------------------------------------------- | 1 | -0.01 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 0.01 | 0.003062 | | 4 | 0.02 | 0.006349 | | 5 | 0.03 | 0.010377 | | 6 | 0.04 | 0.014365 | | 7 | 0.05 | 0.017882 | One can reperform the shown experiments with an even higher resolution to see that the relationship between |ActualRemoteRelieve| and |PossibleRemoteRelieve| is (at least in most cases) in fact very smooth. But a more analytical approach would possibly be favourable regarding the smoothness in some edge cases and computational efficiency. """ con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess d_smoothpar = con.remoterelievetolerance*flu.allowedremoterelieve flu.actualremoterelieve = smoothutils.smooth_min1( flu.possibleremoterelieve, flu.allowedremoterelieve, d_smoothpar) for dummy in range(5): d_smoothpar /= 5. flu.actualremoterelieve = smoothutils.smooth_max1( flu.actualremoterelieve, 0., d_smoothpar) d_smoothpar /= 5. flu.actualremoterelieve = smoothutils.smooth_min1( flu.actualremoterelieve, flu.possibleremoterelieve, d_smoothpar) flu.actualremoterelieve = min(flu.actualremoterelieve, flu.possibleremoterelieve) flu.actualremoterelieve = min(flu.actualremoterelieve, flu.allowedremoterelieve) flu.actualremoterelieve = max(flu.actualremoterelieve, 0.)
Calculate the targeted water release for reducing drought events, taking into account both the required water release and the actual inflow into the dam. Some dams are supposed to maintain a certain degree of low flow variability downstream. In case parameter |RestrictTargetedRelease| is set to `True`, method |calc_targetedrelease_v1| simulates this by (approximately) passing inflow as outflow whenever inflow is below the value of the threshold parameter |NearDischargeMinimumThreshold|. If parameter |RestrictTargetedRelease| is set to `False`, does nothing except assigning the value of sequence |RequiredRelease| to sequence |TargetedRelease|. Required control parameter: |RestrictTargetedRelease| |NearDischargeMinimumThreshold| Required derived parameters: |NearDischargeMinimumSmoothPar1| |dam_derived.TOY| Required flux sequence: |RequiredRelease| Calculated flux sequence: |TargetedRelease| Used auxiliary method: |smooth_logistic1| Basic equation: :math:`TargetedRelease = w \\cdot RequiredRelease + (1-w) \\cdot Inflow` :math:`w = smooth_{logistic1}( Inflow-NearDischargeMinimumThreshold, NearDischargeMinimumSmoothPar1)` Examples: As in the examples above, define a short simulation time period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.toy.update() We start with enabling |RestrictTargetedRelease|: >>> restricttargetedrelease(True) Define a minimum discharge value for a cross section immediately downstream of 6 m³/s for the summer months and of 4 m³/s for the winter months: >>> neardischargeminimumthreshold(_11_1_12=6.0, _03_31_12=6.0, ... _04_1_12=4.0, _10_31_12=4.0) Also define related tolerance values that are 1 m³/s in summer and 0 m³/s in winter: >>> neardischargeminimumtolerance(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> derived.neardischargeminimumsmoothpar1.update() Prepare a test function that calculates the targeted water release based on the parameter values defined above and for inflows into the dam ranging from 0 m³/s to 10 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_targetedrelease_v1, ... last_example=21, ... parseqs=(fluxes.inflow, ... fluxes.targetedrelease)) >>> test.nexts.inflow = numpy.arange(0.0, 10.5, .5) Firstly, assume the required release of water for reducing droughts has already been determined to be 10 m³/s: >>> fluxes.requiredrelease = 10. On May 31, the tolerance value is 0 m³/s. Hence the targeted release jumps from the inflow value to the required release when exceeding the threshold value of 6 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.0 | | 2 | 0.5 | 0.5 | | 3 | 1.0 | 1.0 | | 4 | 1.5 | 1.5 | | 5 | 2.0 | 2.0 | | 6 | 2.5 | 2.5 | | 7 | 3.0 | 3.0 | | 8 | 3.5 | 3.5 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.5 | | 11 | 5.0 | 5.0 | | 12 | 5.5 | 5.5 | | 13 | 6.0 | 8.0 | | 14 | 6.5 | 10.0 | | 15 | 7.0 | 10.0 | | 16 | 7.5 | 10.0 | | 17 | 8.0 | 10.0 | | 18 | 8.5 | 10.0 | | 19 | 9.0 | 10.0 | | 20 | 9.5 | 10.0 | | 21 | 10.0 | 10.0 | On April 1, the threshold value is 4 m³/s and the tolerance value is 2 m³/s. Hence there is a smooth transition for inflows ranging between 2 m³/s and 6 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.00102 | | 2 | 0.5 | 0.503056 | | 3 | 1.0 | 1.009127 | | 4 | 1.5 | 1.527132 | | 5 | 2.0 | 2.08 | | 6 | 2.5 | 2.731586 | | 7 | 3.0 | 3.639277 | | 8 | 3.5 | 5.064628 | | 9 | 4.0 | 7.0 | | 10 | 4.5 | 8.676084 | | 11 | 5.0 | 9.543374 | | 12 | 5.5 | 9.861048 | | 13 | 6.0 | 9.96 | | 14 | 6.5 | 9.988828 | | 15 | 7.0 | 9.996958 | | 16 | 7.5 | 9.999196 | | 17 | 8.0 | 9.999796 | | 18 | 8.5 | 9.999951 | | 19 | 9.0 | 9.99999 | | 20 | 9.5 | 9.999998 | | 21 | 10.0 | 10.0 | An required release substantially below the threshold value is a rather unlikely scenario, but is at least instructive regarding the functioning of the method (when plotting the results graphically...): >>> fluxes.requiredrelease = 2. On May 31, the relationship between targeted release and inflow is again highly discontinous: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.0 | | 2 | 0.5 | 0.5 | | 3 | 1.0 | 1.0 | | 4 | 1.5 | 1.5 | | 5 | 2.0 | 2.0 | | 6 | 2.5 | 2.5 | | 7 | 3.0 | 3.0 | | 8 | 3.5 | 3.5 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.5 | | 11 | 5.0 | 5.0 | | 12 | 5.5 | 5.5 | | 13 | 6.0 | 4.0 | | 14 | 6.5 | 2.0 | | 15 | 7.0 | 2.0 | | 16 | 7.5 | 2.0 | | 17 | 8.0 | 2.0 | | 18 | 8.5 | 2.0 | | 19 | 9.0 | 2.0 | | 20 | 9.5 | 2.0 | | 21 | 10.0 | 2.0 | And on April 1, it is again absolutely smooth: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.000204 | | 2 | 0.5 | 0.500483 | | 3 | 1.0 | 1.001014 | | 4 | 1.5 | 1.501596 | | 5 | 2.0 | 2.0 | | 6 | 2.5 | 2.484561 | | 7 | 3.0 | 2.908675 | | 8 | 3.5 | 3.138932 | | 9 | 4.0 | 3.0 | | 10 | 4.5 | 2.60178 | | 11 | 5.0 | 2.273976 | | 12 | 5.5 | 2.108074 | | 13 | 6.0 | 2.04 | | 14 | 6.5 | 2.014364 | | 15 | 7.0 | 2.005071 | | 16 | 7.5 | 2.00177 | | 17 | 8.0 | 2.000612 | | 18 | 8.5 | 2.00021 | | 19 | 9.0 | 2.000072 | | 20 | 9.5 | 2.000024 | | 21 | 10.0 | 2.000008 | For required releases equal with the threshold value, there is generally no jump in the relationship. But on May 31, there remains a discontinuity in the first derivative: >>> fluxes.requiredrelease = 6. >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.0 | | 2 | 0.5 | 0.5 | | 3 | 1.0 | 1.0 | | 4 | 1.5 | 1.5 | | 5 | 2.0 | 2.0 | | 6 | 2.5 | 2.5 | | 7 | 3.0 | 3.0 | | 8 | 3.5 | 3.5 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.5 | | 11 | 5.0 | 5.0 | | 12 | 5.5 | 5.5 | | 13 | 6.0 | 6.0 | | 14 | 6.5 | 6.0 | | 15 | 7.0 | 6.0 | | 16 | 7.5 | 6.0 | | 17 | 8.0 | 6.0 | | 18 | 8.5 | 6.0 | | 19 | 9.0 | 6.0 | | 20 | 9.5 | 6.0 | | 21 | 10.0 | 6.0 | On April 1, this second order discontinuity is smoothed with the help of a little hump around the threshold: >>> fluxes.requiredrelease = 4. >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.000408 | | 2 | 0.5 | 0.501126 | | 3 | 1.0 | 1.003042 | | 4 | 1.5 | 1.50798 | | 5 | 2.0 | 2.02 | | 6 | 2.5 | 2.546317 | | 7 | 3.0 | 3.091325 | | 8 | 3.5 | 3.620356 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.120356 | | 11 | 5.0 | 4.091325 | | 12 | 5.5 | 4.046317 | | 13 | 6.0 | 4.02 | | 14 | 6.5 | 4.00798 | | 15 | 7.0 | 4.003042 | | 16 | 7.5 | 4.001126 | | 17 | 8.0 | 4.000408 | | 18 | 8.5 | 4.000146 | | 19 | 9.0 | 4.000051 | | 20 | 9.5 | 4.000018 | | 21 | 10.0 | 4.000006 | Repeating the above example with the |RestrictTargetedRelease| flag disabled results in identical values for sequences |RequiredRelease| and |TargetedRelease|: >>> restricttargetedrelease(False) >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 4.0 | | 2 | 0.5 | 4.0 | | 3 | 1.0 | 4.0 | | 4 | 1.5 | 4.0 | | 5 | 2.0 | 4.0 | | 6 | 2.5 | 4.0 | | 7 | 3.0 | 4.0 | | 8 | 3.5 | 4.0 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.0 | | 11 | 5.0 | 4.0 | | 12 | 5.5 | 4.0 | | 13 | 6.0 | 4.0 | | 14 | 6.5 | 4.0 | | 15 | 7.0 | 4.0 | | 16 | 7.5 | 4.0 | | 17 | 8.0 | 4.0 | | 18 | 8.5 | 4.0 | | 19 | 9.0 | 4.0 | | 20 | 9.5 | 4.0 | | 21 | 10.0 | 4.0 | def calc_targetedrelease_v1(self): """Calculate the targeted water release for reducing drought events, taking into account both the required water release and the actual inflow into the dam. Some dams are supposed to maintain a certain degree of low flow variability downstream. In case parameter |RestrictTargetedRelease| is set to `True`, method |calc_targetedrelease_v1| simulates this by (approximately) passing inflow as outflow whenever inflow is below the value of the threshold parameter |NearDischargeMinimumThreshold|. If parameter |RestrictTargetedRelease| is set to `False`, does nothing except assigning the value of sequence |RequiredRelease| to sequence |TargetedRelease|. Required control parameter: |RestrictTargetedRelease| |NearDischargeMinimumThreshold| Required derived parameters: |NearDischargeMinimumSmoothPar1| |dam_derived.TOY| Required flux sequence: |RequiredRelease| Calculated flux sequence: |TargetedRelease| Used auxiliary method: |smooth_logistic1| Basic equation: :math:`TargetedRelease = w \\cdot RequiredRelease + (1-w) \\cdot Inflow` :math:`w = smooth_{logistic1}( Inflow-NearDischargeMinimumThreshold, NearDischargeMinimumSmoothPar1)` Examples: As in the examples above, define a short simulation time period first: >>> from hydpy import pub >>> pub.timegrids = '2001.03.30', '2001.04.03', '1d' Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.toy.update() We start with enabling |RestrictTargetedRelease|: >>> restricttargetedrelease(True) Define a minimum discharge value for a cross section immediately downstream of 6 m³/s for the summer months and of 4 m³/s for the winter months: >>> neardischargeminimumthreshold(_11_1_12=6.0, _03_31_12=6.0, ... _04_1_12=4.0, _10_31_12=4.0) Also define related tolerance values that are 1 m³/s in summer and 0 m³/s in winter: >>> neardischargeminimumtolerance(_11_1_12=0.0, _03_31_12=0.0, ... _04_1_12=2.0, _10_31_12=2.0) >>> derived.neardischargeminimumsmoothpar1.update() Prepare a test function that calculates the targeted water release based on the parameter values defined above and for inflows into the dam ranging from 0 m³/s to 10 m³/s: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_targetedrelease_v1, ... last_example=21, ... parseqs=(fluxes.inflow, ... fluxes.targetedrelease)) >>> test.nexts.inflow = numpy.arange(0.0, 10.5, .5) Firstly, assume the required release of water for reducing droughts has already been determined to be 10 m³/s: >>> fluxes.requiredrelease = 10. On May 31, the tolerance value is 0 m³/s. Hence the targeted release jumps from the inflow value to the required release when exceeding the threshold value of 6 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.0 | | 2 | 0.5 | 0.5 | | 3 | 1.0 | 1.0 | | 4 | 1.5 | 1.5 | | 5 | 2.0 | 2.0 | | 6 | 2.5 | 2.5 | | 7 | 3.0 | 3.0 | | 8 | 3.5 | 3.5 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.5 | | 11 | 5.0 | 5.0 | | 12 | 5.5 | 5.5 | | 13 | 6.0 | 8.0 | | 14 | 6.5 | 10.0 | | 15 | 7.0 | 10.0 | | 16 | 7.5 | 10.0 | | 17 | 8.0 | 10.0 | | 18 | 8.5 | 10.0 | | 19 | 9.0 | 10.0 | | 20 | 9.5 | 10.0 | | 21 | 10.0 | 10.0 | On April 1, the threshold value is 4 m³/s and the tolerance value is 2 m³/s. Hence there is a smooth transition for inflows ranging between 2 m³/s and 6 m³/s: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.00102 | | 2 | 0.5 | 0.503056 | | 3 | 1.0 | 1.009127 | | 4 | 1.5 | 1.527132 | | 5 | 2.0 | 2.08 | | 6 | 2.5 | 2.731586 | | 7 | 3.0 | 3.639277 | | 8 | 3.5 | 5.064628 | | 9 | 4.0 | 7.0 | | 10 | 4.5 | 8.676084 | | 11 | 5.0 | 9.543374 | | 12 | 5.5 | 9.861048 | | 13 | 6.0 | 9.96 | | 14 | 6.5 | 9.988828 | | 15 | 7.0 | 9.996958 | | 16 | 7.5 | 9.999196 | | 17 | 8.0 | 9.999796 | | 18 | 8.5 | 9.999951 | | 19 | 9.0 | 9.99999 | | 20 | 9.5 | 9.999998 | | 21 | 10.0 | 10.0 | An required release substantially below the threshold value is a rather unlikely scenario, but is at least instructive regarding the functioning of the method (when plotting the results graphically...): >>> fluxes.requiredrelease = 2. On May 31, the relationship between targeted release and inflow is again highly discontinous: >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.0 | | 2 | 0.5 | 0.5 | | 3 | 1.0 | 1.0 | | 4 | 1.5 | 1.5 | | 5 | 2.0 | 2.0 | | 6 | 2.5 | 2.5 | | 7 | 3.0 | 3.0 | | 8 | 3.5 | 3.5 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.5 | | 11 | 5.0 | 5.0 | | 12 | 5.5 | 5.5 | | 13 | 6.0 | 4.0 | | 14 | 6.5 | 2.0 | | 15 | 7.0 | 2.0 | | 16 | 7.5 | 2.0 | | 17 | 8.0 | 2.0 | | 18 | 8.5 | 2.0 | | 19 | 9.0 | 2.0 | | 20 | 9.5 | 2.0 | | 21 | 10.0 | 2.0 | And on April 1, it is again absolutely smooth: >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.000204 | | 2 | 0.5 | 0.500483 | | 3 | 1.0 | 1.001014 | | 4 | 1.5 | 1.501596 | | 5 | 2.0 | 2.0 | | 6 | 2.5 | 2.484561 | | 7 | 3.0 | 2.908675 | | 8 | 3.5 | 3.138932 | | 9 | 4.0 | 3.0 | | 10 | 4.5 | 2.60178 | | 11 | 5.0 | 2.273976 | | 12 | 5.5 | 2.108074 | | 13 | 6.0 | 2.04 | | 14 | 6.5 | 2.014364 | | 15 | 7.0 | 2.005071 | | 16 | 7.5 | 2.00177 | | 17 | 8.0 | 2.000612 | | 18 | 8.5 | 2.00021 | | 19 | 9.0 | 2.000072 | | 20 | 9.5 | 2.000024 | | 21 | 10.0 | 2.000008 | For required releases equal with the threshold value, there is generally no jump in the relationship. But on May 31, there remains a discontinuity in the first derivative: >>> fluxes.requiredrelease = 6. >>> model.idx_sim = pub.timegrids.init['2001.03.31'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.0 | | 2 | 0.5 | 0.5 | | 3 | 1.0 | 1.0 | | 4 | 1.5 | 1.5 | | 5 | 2.0 | 2.0 | | 6 | 2.5 | 2.5 | | 7 | 3.0 | 3.0 | | 8 | 3.5 | 3.5 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.5 | | 11 | 5.0 | 5.0 | | 12 | 5.5 | 5.5 | | 13 | 6.0 | 6.0 | | 14 | 6.5 | 6.0 | | 15 | 7.0 | 6.0 | | 16 | 7.5 | 6.0 | | 17 | 8.0 | 6.0 | | 18 | 8.5 | 6.0 | | 19 | 9.0 | 6.0 | | 20 | 9.5 | 6.0 | | 21 | 10.0 | 6.0 | On April 1, this second order discontinuity is smoothed with the help of a little hump around the threshold: >>> fluxes.requiredrelease = 4. >>> model.idx_sim = pub.timegrids.init['2001.04.01'] >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 0.000408 | | 2 | 0.5 | 0.501126 | | 3 | 1.0 | 1.003042 | | 4 | 1.5 | 1.50798 | | 5 | 2.0 | 2.02 | | 6 | 2.5 | 2.546317 | | 7 | 3.0 | 3.091325 | | 8 | 3.5 | 3.620356 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.120356 | | 11 | 5.0 | 4.091325 | | 12 | 5.5 | 4.046317 | | 13 | 6.0 | 4.02 | | 14 | 6.5 | 4.00798 | | 15 | 7.0 | 4.003042 | | 16 | 7.5 | 4.001126 | | 17 | 8.0 | 4.000408 | | 18 | 8.5 | 4.000146 | | 19 | 9.0 | 4.000051 | | 20 | 9.5 | 4.000018 | | 21 | 10.0 | 4.000006 | Repeating the above example with the |RestrictTargetedRelease| flag disabled results in identical values for sequences |RequiredRelease| and |TargetedRelease|: >>> restricttargetedrelease(False) >>> test() | ex. | inflow | targetedrelease | ---------------------------------- | 1 | 0.0 | 4.0 | | 2 | 0.5 | 4.0 | | 3 | 1.0 | 4.0 | | 4 | 1.5 | 4.0 | | 5 | 2.0 | 4.0 | | 6 | 2.5 | 4.0 | | 7 | 3.0 | 4.0 | | 8 | 3.5 | 4.0 | | 9 | 4.0 | 4.0 | | 10 | 4.5 | 4.0 | | 11 | 5.0 | 4.0 | | 12 | 5.5 | 4.0 | | 13 | 6.0 | 4.0 | | 14 | 6.5 | 4.0 | | 15 | 7.0 | 4.0 | | 16 | 7.5 | 4.0 | | 17 | 8.0 | 4.0 | | 18 | 8.5 | 4.0 | | 19 | 9.0 | 4.0 | | 20 | 9.5 | 4.0 | | 21 | 10.0 | 4.0 | """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess if con.restricttargetedrelease: flu.targetedrelease = smoothutils.smooth_logistic1( flu.inflow-con.neardischargeminimumthreshold[ der.toy[self.idx_sim]], der.neardischargeminimumsmoothpar1[der.toy[self.idx_sim]]) flu.targetedrelease = (flu.targetedrelease * flu.requiredrelease + (1.-flu.targetedrelease) * flu.inflow) else: flu.targetedrelease = flu.requiredrelease
Calculate the actual water release that can be supplied by the dam considering the targeted release and the given water level. Required control parameter: |WaterLevelMinimumThreshold| Required derived parameters: |WaterLevelMinimumSmoothPar| Required flux sequence: |TargetedRelease| Required aide sequence: |WaterLevel| Calculated flux sequence: |ActualRelease| Basic equation: :math:`ActualRelease = TargetedRelease \\cdot smooth_{logistic1}(WaterLevelMinimumThreshold-WaterLevel, WaterLevelMinimumSmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() Assume the required release has previously been estimated to be 2 m³/s: >>> fluxes.targetedrelease = 2.0 Prepare a test function, that calculates the targeted water release for water levels ranging between -1 and 5 m: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_actualrelease_v1, ... last_example=7, ... parseqs=(aides.waterlevel, ... fluxes.actualrelease)) >>> test.nexts.waterlevel = range(-1, 6) .. _dam_calc_actualrelease_v1_ex01: **Example 1** Firstly, we define a sharp minimum water level of 0 m: >>> waterlevelminimumthreshold(0.) >>> waterlevelminimumtolerance(0.) >>> derived.waterlevelminimumsmoothpar.update() The following test results show that the water releae is reduced to 0 m³/s for water levels (even slightly) lower than 0 m and is identical with the required value of 2 m³/s (even slighlty) above 0 m: >>> test() | ex. | waterlevel | actualrelease | ------------------------------------ | 1 | -1.0 | 0.0 | | 2 | 0.0 | 1.0 | | 3 | 1.0 | 2.0 | | 4 | 2.0 | 2.0 | | 5 | 3.0 | 2.0 | | 6 | 4.0 | 2.0 | | 7 | 5.0 | 2.0 | One may have noted that in the above example the calculated water release is 1 m³/s (which is exactly the half of the targeted release) at a water level of 1 m. This looks suspiciously lake a flaw but is not of any importance considering the fact, that numerical integration algorithms will approximate the analytical solution of a complete emptying of a dam emtying (which is a water level of 0 m), only with a certain accuracy. .. _dam_calc_actualrelease_v1_ex02: **Example 2** Nonetheless, it can (besides some other possible advantages) dramatically increase the speed of numerical integration algorithms to define a smooth transition area instead of sharp threshold value, like in the following example: >>> waterlevelminimumthreshold(4.) >>> waterlevelminimumtolerance(1.) >>> derived.waterlevelminimumsmoothpar.update() Now, 98 % of the variation of the total range from 0 m³/s to 2 m³/s occurs between a water level of 3 m and 5 m: >>> test() | ex. | waterlevel | actualrelease | ------------------------------------ | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.000002 | | 4 | 2.0 | 0.000204 | | 5 | 3.0 | 0.02 | | 6 | 4.0 | 1.0 | | 7 | 5.0 | 1.98 | .. _dam_calc_actualrelease_v1_ex03: **Example 3** Note that it is possible to set both parameters in a manner that might result in negative water stages beyond numerical inaccuracy: >>> waterlevelminimumthreshold(1.) >>> waterlevelminimumtolerance(2.) >>> derived.waterlevelminimumsmoothpar.update() Here, the actual water release is 0.18 m³/s for a water level of 0 m. Hence water stages in the range of 0 m to -1 m or even -2 m might occur during the simulation of long drought events: >>> test() | ex. | waterlevel | actualrelease | ------------------------------------ | 1 | -1.0 | 0.02 | | 2 | 0.0 | 0.18265 | | 3 | 1.0 | 1.0 | | 4 | 2.0 | 1.81735 | | 5 | 3.0 | 1.98 | | 6 | 4.0 | 1.997972 | | 7 | 5.0 | 1.999796 | def calc_actualrelease_v1(self): """Calculate the actual water release that can be supplied by the dam considering the targeted release and the given water level. Required control parameter: |WaterLevelMinimumThreshold| Required derived parameters: |WaterLevelMinimumSmoothPar| Required flux sequence: |TargetedRelease| Required aide sequence: |WaterLevel| Calculated flux sequence: |ActualRelease| Basic equation: :math:`ActualRelease = TargetedRelease \\cdot smooth_{logistic1}(WaterLevelMinimumThreshold-WaterLevel, WaterLevelMinimumSmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: Prepare the dam model: >>> from hydpy.models.dam import * >>> parameterstep() Assume the required release has previously been estimated to be 2 m³/s: >>> fluxes.targetedrelease = 2.0 Prepare a test function, that calculates the targeted water release for water levels ranging between -1 and 5 m: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_actualrelease_v1, ... last_example=7, ... parseqs=(aides.waterlevel, ... fluxes.actualrelease)) >>> test.nexts.waterlevel = range(-1, 6) .. _dam_calc_actualrelease_v1_ex01: **Example 1** Firstly, we define a sharp minimum water level of 0 m: >>> waterlevelminimumthreshold(0.) >>> waterlevelminimumtolerance(0.) >>> derived.waterlevelminimumsmoothpar.update() The following test results show that the water releae is reduced to 0 m³/s for water levels (even slightly) lower than 0 m and is identical with the required value of 2 m³/s (even slighlty) above 0 m: >>> test() | ex. | waterlevel | actualrelease | ------------------------------------ | 1 | -1.0 | 0.0 | | 2 | 0.0 | 1.0 | | 3 | 1.0 | 2.0 | | 4 | 2.0 | 2.0 | | 5 | 3.0 | 2.0 | | 6 | 4.0 | 2.0 | | 7 | 5.0 | 2.0 | One may have noted that in the above example the calculated water release is 1 m³/s (which is exactly the half of the targeted release) at a water level of 1 m. This looks suspiciously lake a flaw but is not of any importance considering the fact, that numerical integration algorithms will approximate the analytical solution of a complete emptying of a dam emtying (which is a water level of 0 m), only with a certain accuracy. .. _dam_calc_actualrelease_v1_ex02: **Example 2** Nonetheless, it can (besides some other possible advantages) dramatically increase the speed of numerical integration algorithms to define a smooth transition area instead of sharp threshold value, like in the following example: >>> waterlevelminimumthreshold(4.) >>> waterlevelminimumtolerance(1.) >>> derived.waterlevelminimumsmoothpar.update() Now, 98 % of the variation of the total range from 0 m³/s to 2 m³/s occurs between a water level of 3 m and 5 m: >>> test() | ex. | waterlevel | actualrelease | ------------------------------------ | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.000002 | | 4 | 2.0 | 0.000204 | | 5 | 3.0 | 0.02 | | 6 | 4.0 | 1.0 | | 7 | 5.0 | 1.98 | .. _dam_calc_actualrelease_v1_ex03: **Example 3** Note that it is possible to set both parameters in a manner that might result in negative water stages beyond numerical inaccuracy: >>> waterlevelminimumthreshold(1.) >>> waterlevelminimumtolerance(2.) >>> derived.waterlevelminimumsmoothpar.update() Here, the actual water release is 0.18 m³/s for a water level of 0 m. Hence water stages in the range of 0 m to -1 m or even -2 m might occur during the simulation of long drought events: >>> test() | ex. | waterlevel | actualrelease | ------------------------------------ | 1 | -1.0 | 0.02 | | 2 | 0.0 | 0.18265 | | 3 | 1.0 | 1.0 | | 4 | 2.0 | 1.81735 | | 5 | 3.0 | 1.98 | | 6 | 4.0 | 1.997972 | | 7 | 5.0 | 1.999796 | """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess aid = self.sequences.aides.fastaccess flu.actualrelease = (flu.targetedrelease * smoothutils.smooth_logistic1( aid.waterlevel-con.waterlevelminimumthreshold, der.waterlevelminimumsmoothpar))
Calculate the portion of the required remote demand that could not be met by the actual discharge release. Required flux sequences: |RequiredRemoteRelease| |ActualRelease| Calculated flux sequence: |MissingRemoteRelease| Basic equation: :math:`MissingRemoteRelease = max( RequiredRemoteRelease-ActualRelease, 0)` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> fluxes.requiredremoterelease = 2.0 >>> fluxes.actualrelease = 1.0 >>> model.calc_missingremoterelease_v1() >>> fluxes.missingremoterelease missingremoterelease(1.0) >>> fluxes.actualrelease = 3.0 >>> model.calc_missingremoterelease_v1() >>> fluxes.missingremoterelease missingremoterelease(0.0) def calc_missingremoterelease_v1(self): """Calculate the portion of the required remote demand that could not be met by the actual discharge release. Required flux sequences: |RequiredRemoteRelease| |ActualRelease| Calculated flux sequence: |MissingRemoteRelease| Basic equation: :math:`MissingRemoteRelease = max( RequiredRemoteRelease-ActualRelease, 0)` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> fluxes.requiredremoterelease = 2.0 >>> fluxes.actualrelease = 1.0 >>> model.calc_missingremoterelease_v1() >>> fluxes.missingremoterelease missingremoterelease(1.0) >>> fluxes.actualrelease = 3.0 >>> model.calc_missingremoterelease_v1() >>> fluxes.missingremoterelease missingremoterelease(0.0) """ flu = self.sequences.fluxes.fastaccess flu.missingremoterelease = max( flu.requiredremoterelease-flu.actualrelease, 0.)
Calculate the actual remote water release that can be supplied by the dam considering the required remote release and the given water level. Required control parameter: |WaterLevelMinimumRemoteThreshold| Required derived parameters: |WaterLevelMinimumRemoteSmoothPar| Required flux sequence: |RequiredRemoteRelease| Required aide sequence: |WaterLevel| Calculated flux sequence: |ActualRemoteRelease| Basic equation: :math:`ActualRemoteRelease = RequiredRemoteRelease \\cdot smooth_{logistic1}(WaterLevelMinimumRemoteThreshold-WaterLevel, WaterLevelMinimumRemoteSmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: Note that method |calc_actualremoterelease_v1| is functionally identical with method |calc_actualrelease_v1|. This is why we omit to explain the following examples, as they are just repetitions of the ones of method |calc_actualremoterelease_v1| with partly different variable names. Please follow the links to read the corresponding explanations. >>> from hydpy.models.dam import * >>> parameterstep() >>> fluxes.requiredremoterelease = 2.0 >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_actualremoterelease_v1, ... last_example=7, ... parseqs=(aides.waterlevel, ... fluxes.actualremoterelease)) >>> test.nexts.waterlevel = range(-1, 6) :ref:`Recalculation of example 1 <dam_calc_actualrelease_v1_ex01>` >>> waterlevelminimumremotethreshold(0.) >>> waterlevelminimumremotetolerance(0.) >>> derived.waterlevelminimumremotesmoothpar.update() >>> test() | ex. | waterlevel | actualremoterelease | ------------------------------------------ | 1 | -1.0 | 0.0 | | 2 | 0.0 | 1.0 | | 3 | 1.0 | 2.0 | | 4 | 2.0 | 2.0 | | 5 | 3.0 | 2.0 | | 6 | 4.0 | 2.0 | | 7 | 5.0 | 2.0 | :ref:`Recalculation of example 2 <dam_calc_actualrelease_v1_ex02>` >>> waterlevelminimumremotethreshold(4.) >>> waterlevelminimumremotetolerance(1.) >>> derived.waterlevelminimumremotesmoothpar.update() >>> test() | ex. | waterlevel | actualremoterelease | ------------------------------------------ | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.000002 | | 4 | 2.0 | 0.000204 | | 5 | 3.0 | 0.02 | | 6 | 4.0 | 1.0 | | 7 | 5.0 | 1.98 | :ref:`Recalculation of example 3 <dam_calc_actualrelease_v1_ex03>` >>> waterlevelminimumremotethreshold(1.) >>> waterlevelminimumremotetolerance(2.) >>> derived.waterlevelminimumremotesmoothpar.update() >>> test() | ex. | waterlevel | actualremoterelease | ------------------------------------------ | 1 | -1.0 | 0.02 | | 2 | 0.0 | 0.18265 | | 3 | 1.0 | 1.0 | | 4 | 2.0 | 1.81735 | | 5 | 3.0 | 1.98 | | 6 | 4.0 | 1.997972 | | 7 | 5.0 | 1.999796 | def calc_actualremoterelease_v1(self): """Calculate the actual remote water release that can be supplied by the dam considering the required remote release and the given water level. Required control parameter: |WaterLevelMinimumRemoteThreshold| Required derived parameters: |WaterLevelMinimumRemoteSmoothPar| Required flux sequence: |RequiredRemoteRelease| Required aide sequence: |WaterLevel| Calculated flux sequence: |ActualRemoteRelease| Basic equation: :math:`ActualRemoteRelease = RequiredRemoteRelease \\cdot smooth_{logistic1}(WaterLevelMinimumRemoteThreshold-WaterLevel, WaterLevelMinimumRemoteSmoothPar)` Used auxiliary method: |smooth_logistic1| Examples: Note that method |calc_actualremoterelease_v1| is functionally identical with method |calc_actualrelease_v1|. This is why we omit to explain the following examples, as they are just repetitions of the ones of method |calc_actualremoterelease_v1| with partly different variable names. Please follow the links to read the corresponding explanations. >>> from hydpy.models.dam import * >>> parameterstep() >>> fluxes.requiredremoterelease = 2.0 >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_actualremoterelease_v1, ... last_example=7, ... parseqs=(aides.waterlevel, ... fluxes.actualremoterelease)) >>> test.nexts.waterlevel = range(-1, 6) :ref:`Recalculation of example 1 <dam_calc_actualrelease_v1_ex01>` >>> waterlevelminimumremotethreshold(0.) >>> waterlevelminimumremotetolerance(0.) >>> derived.waterlevelminimumremotesmoothpar.update() >>> test() | ex. | waterlevel | actualremoterelease | ------------------------------------------ | 1 | -1.0 | 0.0 | | 2 | 0.0 | 1.0 | | 3 | 1.0 | 2.0 | | 4 | 2.0 | 2.0 | | 5 | 3.0 | 2.0 | | 6 | 4.0 | 2.0 | | 7 | 5.0 | 2.0 | :ref:`Recalculation of example 2 <dam_calc_actualrelease_v1_ex02>` >>> waterlevelminimumremotethreshold(4.) >>> waterlevelminimumremotetolerance(1.) >>> derived.waterlevelminimumremotesmoothpar.update() >>> test() | ex. | waterlevel | actualremoterelease | ------------------------------------------ | 1 | -1.0 | 0.0 | | 2 | 0.0 | 0.0 | | 3 | 1.0 | 0.000002 | | 4 | 2.0 | 0.000204 | | 5 | 3.0 | 0.02 | | 6 | 4.0 | 1.0 | | 7 | 5.0 | 1.98 | :ref:`Recalculation of example 3 <dam_calc_actualrelease_v1_ex03>` >>> waterlevelminimumremotethreshold(1.) >>> waterlevelminimumremotetolerance(2.) >>> derived.waterlevelminimumremotesmoothpar.update() >>> test() | ex. | waterlevel | actualremoterelease | ------------------------------------------ | 1 | -1.0 | 0.02 | | 2 | 0.0 | 0.18265 | | 3 | 1.0 | 1.0 | | 4 | 2.0 | 1.81735 | | 5 | 3.0 | 1.98 | | 6 | 4.0 | 1.997972 | | 7 | 5.0 | 1.999796 | """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess aid = self.sequences.aides.fastaccess flu.actualremoterelease = ( flu.requiredremoterelease * smoothutils.smooth_logistic1( aid.waterlevel-con.waterlevelminimumremotethreshold, der.waterlevelminimumremotesmoothpar))
Constrain the actual relieve discharge to a remote location. Required control parameter: |HighestRemoteDischarge| Required derived parameter: |HighestRemoteSmoothPar| Updated flux sequence: |ActualRemoteRelieve| Basic equation - discontinous: :math:`ActualRemoteRelieve = min(ActualRemoteRelease, HighestRemoteDischarge)` Basic equation - continous: :math:`ActualRemoteRelieve = smooth_min1(ActualRemoteRelieve, HighestRemoteDischarge, HighestRemoteSmoothPar)` Used auxiliary methods: |smooth_min1| |smooth_max1| Note that the given continous basic equation is a simplification of the complete algorithm to update |ActualRemoteRelieve|, which also makes use of |smooth_max1| to prevent from gaining negative values in a smooth manner. Examples: Prepare a dam model: >>> from hydpy.models.dam import * >>> parameterstep() Prepare a test function object that performs eight examples with |ActualRemoteRelieve| ranging from 0 to 8 m³/s and a fixed initial value of parameter |HighestRemoteDischarge| of 4 m³/s: >>> highestremotedischarge(4.0) >>> from hydpy import UnitTest >>> test = UnitTest(model, model.update_actualremoterelieve_v1, ... last_example=8, ... parseqs=(fluxes.actualremoterelieve,)) >>> test.nexts.actualremoterelieve = range(8) Through setting the value of |HighestRemoteTolerance| to the lowest possible value, there is no smoothing. Instead, the shown relationship agrees with a combination of the discontinuous minimum and maximum function: >>> highestremotetolerance(0.0) >>> derived.highestremotesmoothpar.update() >>> test() | ex. | actualremoterelieve | ----------------------------- | 1 | 0.0 | | 2 | 1.0 | | 3 | 2.0 | | 4 | 3.0 | | 5 | 4.0 | | 6 | 4.0 | | 7 | 4.0 | | 8 | 4.0 | Setting a sensible |HighestRemoteTolerance| value results in a moderate smoothing: >>> highestremotetolerance(0.1) >>> derived.highestremotesmoothpar.update() >>> test() | ex. | actualremoterelieve | ----------------------------- | 1 | 0.0 | | 2 | 0.999999 | | 3 | 1.99995 | | 4 | 2.996577 | | 5 | 3.836069 | | 6 | 3.991578 | | 7 | 3.993418 | | 8 | 3.993442 | Method |update_actualremoterelieve_v1| is defined in a similar way as method |calc_actualremoterelieve_v1|. Please read the documentation on |calc_actualremoterelieve_v1| for further information. def update_actualremoterelieve_v1(self): """Constrain the actual relieve discharge to a remote location. Required control parameter: |HighestRemoteDischarge| Required derived parameter: |HighestRemoteSmoothPar| Updated flux sequence: |ActualRemoteRelieve| Basic equation - discontinous: :math:`ActualRemoteRelieve = min(ActualRemoteRelease, HighestRemoteDischarge)` Basic equation - continous: :math:`ActualRemoteRelieve = smooth_min1(ActualRemoteRelieve, HighestRemoteDischarge, HighestRemoteSmoothPar)` Used auxiliary methods: |smooth_min1| |smooth_max1| Note that the given continous basic equation is a simplification of the complete algorithm to update |ActualRemoteRelieve|, which also makes use of |smooth_max1| to prevent from gaining negative values in a smooth manner. Examples: Prepare a dam model: >>> from hydpy.models.dam import * >>> parameterstep() Prepare a test function object that performs eight examples with |ActualRemoteRelieve| ranging from 0 to 8 m³/s and a fixed initial value of parameter |HighestRemoteDischarge| of 4 m³/s: >>> highestremotedischarge(4.0) >>> from hydpy import UnitTest >>> test = UnitTest(model, model.update_actualremoterelieve_v1, ... last_example=8, ... parseqs=(fluxes.actualremoterelieve,)) >>> test.nexts.actualremoterelieve = range(8) Through setting the value of |HighestRemoteTolerance| to the lowest possible value, there is no smoothing. Instead, the shown relationship agrees with a combination of the discontinuous minimum and maximum function: >>> highestremotetolerance(0.0) >>> derived.highestremotesmoothpar.update() >>> test() | ex. | actualremoterelieve | ----------------------------- | 1 | 0.0 | | 2 | 1.0 | | 3 | 2.0 | | 4 | 3.0 | | 5 | 4.0 | | 6 | 4.0 | | 7 | 4.0 | | 8 | 4.0 | Setting a sensible |HighestRemoteTolerance| value results in a moderate smoothing: >>> highestremotetolerance(0.1) >>> derived.highestremotesmoothpar.update() >>> test() | ex. | actualremoterelieve | ----------------------------- | 1 | 0.0 | | 2 | 0.999999 | | 3 | 1.99995 | | 4 | 2.996577 | | 5 | 3.836069 | | 6 | 3.991578 | | 7 | 3.993418 | | 8 | 3.993442 | Method |update_actualremoterelieve_v1| is defined in a similar way as method |calc_actualremoterelieve_v1|. Please read the documentation on |calc_actualremoterelieve_v1| for further information. """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess d_smooth = der.highestremotesmoothpar d_highest = con.highestremotedischarge d_value = smoothutils.smooth_min1( flu.actualremoterelieve, d_highest, d_smooth) for dummy in range(5): d_smooth /= 5. d_value = smoothutils.smooth_max1( d_value, 0., d_smooth) d_smooth /= 5. d_value = smoothutils.smooth_min1( d_value, d_highest, d_smooth) d_value = min(d_value, flu.actualremoterelieve) d_value = min(d_value, d_highest) flu.actualremoterelieve = max(d_value, 0.)
Calculate the discharge during and after a flood event based on an |anntools.SeasonalANN| describing the relationship(s) between discharge and water stage. Required control parameter: |WaterLevel2FloodDischarge| Required derived parameter: |dam_derived.TOY| Required aide sequence: |WaterLevel| Calculated flux sequence: |FloodDischarge| Example: The control parameter |WaterLevel2FloodDischarge| is derived from |SeasonalParameter|. This allows to simulate different seasonal dam control schemes. To show that the seasonal selection mechanism is implemented properly, we define a short simulation period of three days: >>> from hydpy import pub >>> pub.timegrids = '2001.01.01', '2001.01.04', '1d' Now we prepare a dam model and define two different relationships between water level and flood discharge. The first relatively simple relationship (for January, 2) is based on two neurons contained in a single hidden layer and is used in the following example. The second neural network (for January, 3) is not applied at all, which is why we do not need to assign any parameter values to it: >>> from hydpy.models.dam import * >>> parameterstep() >>> waterlevel2flooddischarge( ... _01_02_12 = ann(nmb_inputs=1, ... nmb_neurons=(2,), ... nmb_outputs=1, ... weights_input=[[50., 4]], ... weights_output=[[2.], [30]], ... intercepts_hidden=[[-13000, -1046]], ... intercepts_output=[0.]), ... _01_03_12 = ann(nmb_inputs=1, ... nmb_neurons=(2,), ... nmb_outputs=1)) >>> derived.toy.update() >>> model.idx_sim = pub.timegrids.sim['2001.01.02'] The following example shows two distinct effects of both neurons in the first network. One neuron describes a relatively sharp increase between 259.8 and 260.2 meters from about 0 to 2 m³/s. This could describe a release of water through a bottom outlet controlled by a valve. The add something like an exponential increase between 260 and 261 meters, which could describe the uncontrolled flow over a spillway: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_flooddischarge_v1, ... last_example=21, ... parseqs=(aides.waterlevel, ... fluxes.flooddischarge)) >>> test.nexts.waterlevel = numpy.arange(257, 261.1, 0.2) >>> test() | ex. | waterlevel | flooddischarge | ------------------------------------- | 1 | 257.0 | 0.0 | | 2 | 257.2 | 0.000001 | | 3 | 257.4 | 0.000002 | | 4 | 257.6 | 0.000005 | | 5 | 257.8 | 0.000011 | | 6 | 258.0 | 0.000025 | | 7 | 258.2 | 0.000056 | | 8 | 258.4 | 0.000124 | | 9 | 258.6 | 0.000275 | | 10 | 258.8 | 0.000612 | | 11 | 259.0 | 0.001362 | | 12 | 259.2 | 0.003031 | | 13 | 259.4 | 0.006745 | | 14 | 259.6 | 0.015006 | | 15 | 259.8 | 0.033467 | | 16 | 260.0 | 1.074179 | | 17 | 260.2 | 2.164498 | | 18 | 260.4 | 2.363853 | | 19 | 260.6 | 2.79791 | | 20 | 260.8 | 3.719725 | | 21 | 261.0 | 5.576088 | def calc_flooddischarge_v1(self): """Calculate the discharge during and after a flood event based on an |anntools.SeasonalANN| describing the relationship(s) between discharge and water stage. Required control parameter: |WaterLevel2FloodDischarge| Required derived parameter: |dam_derived.TOY| Required aide sequence: |WaterLevel| Calculated flux sequence: |FloodDischarge| Example: The control parameter |WaterLevel2FloodDischarge| is derived from |SeasonalParameter|. This allows to simulate different seasonal dam control schemes. To show that the seasonal selection mechanism is implemented properly, we define a short simulation period of three days: >>> from hydpy import pub >>> pub.timegrids = '2001.01.01', '2001.01.04', '1d' Now we prepare a dam model and define two different relationships between water level and flood discharge. The first relatively simple relationship (for January, 2) is based on two neurons contained in a single hidden layer and is used in the following example. The second neural network (for January, 3) is not applied at all, which is why we do not need to assign any parameter values to it: >>> from hydpy.models.dam import * >>> parameterstep() >>> waterlevel2flooddischarge( ... _01_02_12 = ann(nmb_inputs=1, ... nmb_neurons=(2,), ... nmb_outputs=1, ... weights_input=[[50., 4]], ... weights_output=[[2.], [30]], ... intercepts_hidden=[[-13000, -1046]], ... intercepts_output=[0.]), ... _01_03_12 = ann(nmb_inputs=1, ... nmb_neurons=(2,), ... nmb_outputs=1)) >>> derived.toy.update() >>> model.idx_sim = pub.timegrids.sim['2001.01.02'] The following example shows two distinct effects of both neurons in the first network. One neuron describes a relatively sharp increase between 259.8 and 260.2 meters from about 0 to 2 m³/s. This could describe a release of water through a bottom outlet controlled by a valve. The add something like an exponential increase between 260 and 261 meters, which could describe the uncontrolled flow over a spillway: >>> from hydpy import UnitTest >>> test = UnitTest(model, model.calc_flooddischarge_v1, ... last_example=21, ... parseqs=(aides.waterlevel, ... fluxes.flooddischarge)) >>> test.nexts.waterlevel = numpy.arange(257, 261.1, 0.2) >>> test() | ex. | waterlevel | flooddischarge | ------------------------------------- | 1 | 257.0 | 0.0 | | 2 | 257.2 | 0.000001 | | 3 | 257.4 | 0.000002 | | 4 | 257.6 | 0.000005 | | 5 | 257.8 | 0.000011 | | 6 | 258.0 | 0.000025 | | 7 | 258.2 | 0.000056 | | 8 | 258.4 | 0.000124 | | 9 | 258.6 | 0.000275 | | 10 | 258.8 | 0.000612 | | 11 | 259.0 | 0.001362 | | 12 | 259.2 | 0.003031 | | 13 | 259.4 | 0.006745 | | 14 | 259.6 | 0.015006 | | 15 | 259.8 | 0.033467 | | 16 | 260.0 | 1.074179 | | 17 | 260.2 | 2.164498 | | 18 | 260.4 | 2.363853 | | 19 | 260.6 | 2.79791 | | 20 | 260.8 | 3.719725 | | 21 | 261.0 | 5.576088 | """ con = self.parameters.control.fastaccess der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess aid = self.sequences.aides.fastaccess con.waterlevel2flooddischarge.inputs[0] = aid.waterlevel con.waterlevel2flooddischarge.process_actual_input(der.toy[self.idx_sim]) flu.flooddischarge = con.waterlevel2flooddischarge.outputs[0]
Calculate the total outflow of the dam. Note that the maximum function is used to prevent from negative outflow values, which could otherwise occur within the required level of numerical accuracy. Required flux sequences: |ActualRelease| |FloodDischarge| Calculated flux sequence: |Outflow| Basic equation: :math:`Outflow = max(ActualRelease + FloodDischarge, 0.)` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> fluxes.actualrelease = 2.0 >>> fluxes.flooddischarge = 3.0 >>> model.calc_outflow_v1() >>> fluxes.outflow outflow(5.0) >>> fluxes.flooddischarge = -3.0 >>> model.calc_outflow_v1() >>> fluxes.outflow outflow(0.0) def calc_outflow_v1(self): """Calculate the total outflow of the dam. Note that the maximum function is used to prevent from negative outflow values, which could otherwise occur within the required level of numerical accuracy. Required flux sequences: |ActualRelease| |FloodDischarge| Calculated flux sequence: |Outflow| Basic equation: :math:`Outflow = max(ActualRelease + FloodDischarge, 0.)` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> fluxes.actualrelease = 2.0 >>> fluxes.flooddischarge = 3.0 >>> model.calc_outflow_v1() >>> fluxes.outflow outflow(5.0) >>> fluxes.flooddischarge = -3.0 >>> model.calc_outflow_v1() >>> fluxes.outflow outflow(0.0) """ flu = self.sequences.fluxes.fastaccess flu.outflow = max(flu.actualrelease + flu.flooddischarge, 0.)
Update the actual water volume. Required derived parameter: |Seconds| Required flux sequences: |Inflow| |Outflow| Updated state sequence: |WaterVolume| Basic equation: :math:`\\frac{d}{dt}WaterVolume = 1e-6 \\cdot (Inflow-Outflow)` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.seconds = 2e6 >>> states.watervolume.old = 5.0 >>> fluxes.inflow = 2.0 >>> fluxes.outflow = 3.0 >>> model.update_watervolume_v1() >>> states.watervolume watervolume(3.0) def update_watervolume_v1(self): """Update the actual water volume. Required derived parameter: |Seconds| Required flux sequences: |Inflow| |Outflow| Updated state sequence: |WaterVolume| Basic equation: :math:`\\frac{d}{dt}WaterVolume = 1e-6 \\cdot (Inflow-Outflow)` Example: >>> from hydpy.models.dam import * >>> parameterstep() >>> derived.seconds = 2e6 >>> states.watervolume.old = 5.0 >>> fluxes.inflow = 2.0 >>> fluxes.outflow = 3.0 >>> model.update_watervolume_v1() >>> states.watervolume watervolume(3.0) """ der = self.parameters.derived.fastaccess flu = self.sequences.fluxes.fastaccess old = self.sequences.states.fastaccess_old new = self.sequences.states.fastaccess_new new.watervolume = (old.watervolume + der.seconds*(flu.inflow-flu.outflow)/1e6)
Update the outlet link sequence |dam_outlets.Q|. def pass_outflow_v1(self): """Update the outlet link sequence |dam_outlets.Q|.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.q[0] += flu.outflow
Update the outlet link sequence |dam_outlets.S|. def pass_actualremoterelease_v1(self): """Update the outlet link sequence |dam_outlets.S|.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.s[0] += flu.actualremoterelease
Update the outlet link sequence |dam_outlets.R|. def pass_actualremoterelieve_v1(self): """Update the outlet link sequence |dam_outlets.R|.""" flu = self.sequences.fluxes.fastaccess out = self.sequences.outlets.fastaccess out.r[0] += flu.actualremoterelieve
Update the outlet link sequence |dam_senders.D|. def pass_missingremoterelease_v1(self): """Update the outlet link sequence |dam_senders.D|.""" flu = self.sequences.fluxes.fastaccess sen = self.sequences.senders.fastaccess sen.d[0] += flu.missingremoterelease
Update the outlet link sequence |dam_outlets.R|. def pass_allowedremoterelieve_v1(self): """Update the outlet link sequence |dam_outlets.R|.""" flu = self.sequences.fluxes.fastaccess sen = self.sequences.senders.fastaccess sen.r[0] += flu.allowedremoterelieve
Update the outlet link sequence |dam_outlets.S|. def pass_requiredremotesupply_v1(self): """Update the outlet link sequence |dam_outlets.S|.""" flu = self.sequences.fluxes.fastaccess sen = self.sequences.senders.fastaccess sen.s[0] += flu.requiredremotesupply
Log a new entry of discharge at a cross section far downstream. Required control parameter: |NmbLogEntries| Required flux sequence: |Outflow| Calculated flux sequence: |LoggedOutflow| Example: The following example shows that, with each new method call, the three memorized values are successively moved to the right and the respective new value is stored on the bare left position: >>> from hydpy.models.dam import * >>> parameterstep() >>> nmblogentries(3) >>> logs.loggedoutflow = 0.0 >>> from hydpy import UnitTest >>> test = UnitTest(model, model.update_loggedoutflow_v1, ... last_example=4, ... parseqs=(fluxes.outflow, ... logs.loggedoutflow)) >>> test.nexts.outflow = [1.0, 3.0, 2.0, 4.0] >>> del test.inits.loggedoutflow >>> test() | ex. | outflow | loggedoutflow | ------------------------------------------- | 1 | 1.0 | 1.0 0.0 0.0 | | 2 | 3.0 | 3.0 1.0 0.0 | | 3 | 2.0 | 2.0 3.0 1.0 | | 4 | 4.0 | 4.0 2.0 3.0 | def update_loggedoutflow_v1(self): """Log a new entry of discharge at a cross section far downstream. Required control parameter: |NmbLogEntries| Required flux sequence: |Outflow| Calculated flux sequence: |LoggedOutflow| Example: The following example shows that, with each new method call, the three memorized values are successively moved to the right and the respective new value is stored on the bare left position: >>> from hydpy.models.dam import * >>> parameterstep() >>> nmblogentries(3) >>> logs.loggedoutflow = 0.0 >>> from hydpy import UnitTest >>> test = UnitTest(model, model.update_loggedoutflow_v1, ... last_example=4, ... parseqs=(fluxes.outflow, ... logs.loggedoutflow)) >>> test.nexts.outflow = [1.0, 3.0, 2.0, 4.0] >>> del test.inits.loggedoutflow >>> test() | ex. | outflow | loggedoutflow | ------------------------------------------- | 1 | 1.0 | 1.0 0.0 0.0 | | 2 | 3.0 | 3.0 1.0 0.0 | | 3 | 2.0 | 2.0 3.0 1.0 | | 4 | 4.0 | 4.0 2.0 3.0 | """ con = self.parameters.control.fastaccess flu = self.sequences.fluxes.fastaccess log = self.sequences.logs.fastaccess for idx in range(con.nmblogentries-1, 0, -1): log.loggedoutflow[idx] = log.loggedoutflow[idx-1] log.loggedoutflow[0] = flu.outflow
(Re)calculate the MA coefficients based on the instantaneous unit hydrograph. def update_coefs(self): """(Re)calculate the MA coefficients based on the instantaneous unit hydrograph.""" coefs = [] sum_coefs = 0. moment1 = self.iuh.moment1 for t in itertools.count(0., 1.): points = (moment1 % 1,) if t <= moment1 <= (t+2.) else () try: coef = integrate.quad( self._quad, 0., 1., args=(t,), points=points)[0] except integrate.IntegrationWarning: idx = int(moment1) coefs = numpy.zeros(idx+2, dtype=float) weight = (moment1-idx) coefs[idx] = (1.-weight) coefs[idx+1] = weight self.coefs = coefs warnings.warn( 'During the determination of the MA coefficients ' 'corresponding to the instantaneous unit hydrograph ' '`%s` a numerical integration problem occurred. ' 'Please check the calculated coefficients: %s.' % (repr(self.iuh), objecttools.repr_values(coefs))) break # pragma: no cover sum_coefs += coef if (sum_coefs > .9) and (coef < self.smallest_coeff): coefs = numpy.array(coefs) coefs /= numpy.sum(coefs) self.coefs = coefs break else: coefs.append(coef)
Turning point (index and value tuple) in the recession part of the MA approximation of the instantaneous unit hydrograph. def turningpoint(self): """Turning point (index and value tuple) in the recession part of the MA approximation of the instantaneous unit hydrograph.""" coefs = self.coefs old_dc = coefs[1]-coefs[0] for idx in range(self.order-2): new_dc = coefs[idx+2]-coefs[idx+1] if (old_dc < 0.) and (new_dc > old_dc): return idx, coefs[idx] old_dc = new_dc raise RuntimeError( 'Not able to detect a turning point in the impulse response ' 'defined by the MA coefficients %s.' % objecttools.repr_values(coefs))
The first two time delay weighted statistical moments of the MA coefficients. def moments(self): """The first two time delay weighted statistical moments of the MA coefficients.""" moment1 = statstools.calc_mean_time(self.delays, self.coefs) moment2 = statstools.calc_mean_time_deviation( self.delays, self.coefs, moment1) return numpy.array([moment1, moment2])