text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve_dv_dt_v1(self):
"""Solve the differential equation of HydPy-L. At the moment, HydPy-L only implements a simple numerical solution of its underlying ordinary differential equation. To increase the accuracy (or sometimes even to prevent instability) of this approximation, one can set the value of parameter |MaxDT| to a value smaller than the actual simulation step size. Method |solve_dv_dt_v1| then applies the methods related to the numerical approximation multiple times and aggregates the results. Note that the order of convergence is one only. It is hard to tell how short the internal simulation step needs to be to ensure a certain degree of accuracy. In most cases one hour or very often even one day should be sufficient to gain acceptable results. However, this strongly depends on the given water stage-volume-discharge relationship. Hence it seems advisable to always define a few test waves and apply the llake model with different |MaxDT| values. Afterwards, select a |MaxDT| value lower than one which results in acceptable approximations for all test waves. The computation time of the llake mode per substep is rather small, so always include a safety factor. Of course, an adaptive step size determination would be much more Required derived parameter: |NmbSubsteps| Used aide sequence: |llake_aides.V| |llake_aides.QA| Updated state sequence: |llake_states.V| Calculated flux sequence: |llake_fluxes.QA| Note that method |solve_dv_dt_v1| calls the versions of `calc_vq`, `interp_qa` and `calc_v_qa` selected by the respective application model. Hence, also their parameter and sequence specifications need to be considered. Basic equation: :math:`\\frac{dV}{dt}= QZ - QA(V)` """ |
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
old = self.sequences.states.fastaccess_old
new = self.sequences.states.fastaccess_new
aid = self.sequences.aides.fastaccess
flu.qa = 0.
aid.v = old.v
for _ in range(der.nmbsubsteps):
self.calc_vq()
self.interp_qa()
self.calc_v_qa()
flu.qa += aid.qa
flu.qa /= der.nmbsubsteps
new.v = aid.v |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_vq_v1(self):
"""Calculate the auxiliary term. Required derived parameters: |Seconds| |NmbSubsteps| Required flux sequence: |QZ| Required aide sequence: |llake_aides.V| Calculated aide sequence: |llake_aides.VQ| Basic equation: :math:`VQ = 2 \\cdot V + \\frac{Seconds}{NmbSubsteps} \\cdot QZ` Example: The following example shows that the auxiliary term `vq` does not depend on the (outer) simulation step size but on the (inner) calculation step size defined by parameter `maxdt`: vq(243200.0) """ |
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
aid = self.sequences.aides.fastaccess
aid.vq = 2.*aid.v+der.seconds/der.nmbsubsteps*flu.qz |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interp_qa_v1(self):
"""Calculate the lake outflow based on linear interpolation. Required control parameters: |N| |llake_control.Q| Required derived parameters: |llake_derived.TOY| |llake_derived.VQ| Required aide sequence: |llake_aides.VQ| Calculated aide sequence: |llake_aides.QA| Examples: In preparation for the following examples, define a short simulation time period with a simulation step size of 12 hours and initialize the required model object: Next, for the sake of brevity, define a test function: The following three relationships between the auxiliary term `vq` and the tabulated discharge `q` are taken as examples. Each one is valid for one of the first three days in January and is defined via five nodes: In the first example, discharge does not depend on the actual value of the auxiliary term and is always zero: vq(0.0) qa(0.0) vq(0.75) qa(0.0) vq(1.0) qa(0.0) vq(1.333333) qa(0.0) vq(2.0) qa(0.0) vq(2.333333) qa(0.0) vq(3.0) qa(0.0) vq(3.333333) qa(0.0) The seconds example demonstrates that relationships are allowed to contain jumps, which is the case for the (`vq`,`q`) pairs (2,6) and (2,7). Also it demonstrates that when the highest `vq` value is exceeded linear extrapolation based on the two highest (`vq`,`q`) pairs is performed: vq(0.0) qa(0.0) vq(0.75) qa(1.5) vq(1.0) qa(2.0) vq(1.333333) qa(3.0) vq(2.0) qa(5.0) vq(2.333333) qa(7.0) vq(3.0) qa(9.0) vq(3.333333) qa(10.0) The third example shows that the relationships do not need to be arranged monotonously increasing. Particualarly for the extrapolation range, this could result in negative values of `qa`, which is avoided by setting it to zero in such cases: vq(0.5) qa(1.0) vq(1.5) qa(1.5) vq(2.5) qa(2.0) vq(3.5) qa(2.5) vq(4.5) qa(1.5) vq(10.0) qa(0.0) """ |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
aid = self.sequences.aides.fastaccess
idx = der.toy[self.idx_sim]
for jdx in range(1, con.n):
if der.vq[idx, jdx] >= aid.vq:
break
aid.qa = ((aid.vq-der.vq[idx, jdx-1]) *
(con.q[idx, jdx]-con.q[idx, jdx-1]) /
(der.vq[idx, jdx]-der.vq[idx, jdx-1]) +
con.q[idx, jdx-1])
aid.qa = max(aid.qa, 0.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_v_qa_v1(self):
"""Update the stored water volume based on the equation of continuity. Note that for too high outflow values, which would result in overdraining the lake, the outflow is trimmed. Required derived parameters: |Seconds| |NmbSubsteps| Required flux sequence: |QZ| Updated aide sequences: |llake_aides.QA| |llake_aides.V| Basic Equation: :math:`\\frac{dV}{dt}= QZ - QA` Examples: Prepare a lake model with an initial storage of 100.000 m³ and an inflow of 2 m³/s and a (potential) outflow of 6 m³/s: Through calling method `calc_v_qa_v1` three times with the same inflow and outflow values, the storage is emptied after the second step and outflow is equal to inflow after the third step: v(13600.0) qa(6.0) v(0.0) qa(2.62963) v(0.0) qa(2.0) Note that the results of method |calc_v_qa_v1| are not based depend on the (outer) simulation step size but on the (inner) calculation step size defined by parameter `maxdt`. """ |
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
aid = self.sequences.aides.fastaccess
aid.qa = min(aid.qa, flu.qz+der.nmbsubsteps/der.seconds*aid.v)
aid.v = max(aid.v+der.seconds/der.nmbsubsteps*(flu.qz-aid.qa), 0.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def interp_w_v1(self):
"""Calculate the actual water stage based on linear interpolation. Required control parameters: |N| |llake_control.V| |llake_control.W| Required state sequence: |llake_states.V| Calculated state sequence: |llake_states.W| Examples: Prepare a model object: For the sake of brevity, define a test function: Define a simple `w`-`v` relationship consisting of three nodes and calculate the water stages for different volumes: Perform the interpolation for a few test points: v(0.0) w(-1.0) v(0.5) w(-0.5) v(2.0) w(1.0) v(3.0) w(1.5) v(4.0) w(2.0) v(5.0) w(2.5) The reference water stage of the relationship can be selected arbitrarily. Even negative water stages are returned, as is demonstrated by the first two calculations. For volumes outside the range of the (`v`,`w`) pairs, the outer two highest pairs are used for linear extrapolation. """ |
con = self.parameters.control.fastaccess
new = self.sequences.states.fastaccess_new
for jdx in range(1, con.n):
if con.v[jdx] >= new.v:
break
new.w = ((new.v-con.v[jdx-1]) *
(con.w[jdx]-con.w[jdx-1]) /
(con.v[jdx]-con.v[jdx-1]) +
con.w[jdx-1]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def corr_dw_v1(self):
"""Adjust the water stage drop to the highest value allowed and correct the associated fluxes. Note that method |corr_dw_v1| calls the method `interp_v` of the respective application model. Hence the requirements of the actual `interp_v` need to be considered additionally. Required control parameter: |MaxDW| Required derived parameters: |llake_derived.TOY| |Seconds| Required flux sequence: |QZ| Updated flux sequence: |llake_fluxes.QA| Updated state sequences: |llake_states.W| |llake_states.V| Basic Restriction: :math:`W_{old} - W_{new} \\leq MaxDW` Examples: In preparation for the following examples, define a short simulation time period with a simulation step size of 12 hours and initialize the required model object: Select the first half of the second day of January as the simulation step relevant for the following examples: The following tests are based on method |interp_v_v1| for the interpolation of the stored water volume based on the corrected water stage: For the sake of simplicity, the underlying `w`-`v` relationship is assumed to be linear: The maximum drop in water stage for the first half of the second day of January is set to 0.4 m/d. Note that, due to the difference between the parameter step size and the simulation step size, the actual value used for calculation is 0.2 m/12h: maxdw(toy_1_1_18_0_0=0.1, toy_1_2_6_0_0=0.4, toy_1_2_18_0_0=0.1) 0.2 Define old and new water stages and volumes in agreement with the given linear relationship: Also define an inflow and an outflow value. Note the that the latter is set to zero, which is inconsistent with the actual water stage drop defined above, but done for didactic reasons: Calling the |corr_dw_v1| method does not change the values of either of following sequences, as the actual drop (0.1 m/12h) is smaller than the allowed drop (0.2 m/12h):
w(0.9) v(900000.0) qa(0.0) Note that the values given above are not recalculated, which can clearly be seen for the lake outflow, which is still zero. Through setting the new value of the water stage to 0.6 m, the actual drop (0.4 m/12h) exceeds the allowed drop (0.2 m/12h). Hence the water stage is trimmed and the other values are recalculated: w(0.8) v(800000.0) qa(5.62963) Through setting the maximum water stage drop to zero, method |corr_dw_v1| is effectively disabled. Regardless of the actual change in water stage, no trimming or recalculating is performed: w(0.6) v(800000.0) qa(5.62963) """ |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
old = self.sequences.states.fastaccess_old
new = self.sequences.states.fastaccess_new
idx = der.toy[self.idx_sim]
if (con.maxdw[idx] > 0.) and ((old.w-new.w) > con.maxdw[idx]):
new.w = old.w-con.maxdw[idx]
self.interp_v()
flu.qa = flu.qz+(old.v-new.v)/der.seconds |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def modify_qa_v1(self):
"""Add water to or remove water from the calculated lake outflow. Required control parameter: |Verzw| Required derived parameter: |llake_derived.TOY| Updated flux sequence: |llake_fluxes.QA| Basic Equation: :math:`QA = QA* - Verzw` Examples: In preparation for the following examples, define a short simulation time period with a simulation step size of 12 hours and initialize the required model object: Select the first half of the second day of January as the simulation step relevant for the following examples: Assume that, in accordance with previous calculations, the original outflow value is 3 m³/s: Prepare the shape of parameter `verzw` (usually, this is done automatically when calling parameter `n`):
Set the value of the abstraction on the first half of the second day of January to 2 m³/s: In the first example `verzw` is simply subtracted from `qa`: qa(1.0) In the second example `verzw` exceeds `qa`, resulting in a zero outflow value: qa(0.0) The last example demonstrates, that "negative abstractions" are allowed, resulting in an increase in simulated outflow: qa(2.0) """ |
con = self.parameters.control.fastaccess
der = self.parameters.derived.fastaccess
flu = self.sequences.fluxes.fastaccess
idx = der.toy[self.idx_sim]
flu.qa = max(flu.qa-con.verzw[idx], 0.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def thresholds(self):
"""Threshold values of the response functions.""" |
return numpy.array(
sorted(self._key2float(key) for key in self._coefs), dtype=float) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_arrays(sim=None, obs=None, node=None, skip_nan=False):
"""Prepare and return two |numpy| arrays based on the given arguments. Note that many functions provided by module |statstools| apply function |prepare_arrays| internally (e.g. |nse|). But you can also apply it manually, as shown in the following examples. Function |prepare_arrays| can extract time series data from |Node| objects. To set up an example for this, we define a initialization time period and prepare a |Node| object: Next, we assign values the `simulation` and the `observation` sequences (to do so for the `observation` sequence requires a little trick, as its values are normally supposed to be read from a file):
Now we can pass the node object to function |prepare_arrays| and get the (unmodified) time series data: 1.0, nan, nan, nan, 2.0, 3.0 4.0, 5.0, nan, nan, nan, 6.0 Alternatively, we can pass directly any iterables (e.g. |list| and |tuple| objects) containing the `simulated` and `observed` data: 1.0, nan, nan, nan, 2.0, 3.0 4.0, 5.0, nan, nan, nan, 6.0 The optional `skip_nan` flag allows to skip all values, which are no numbers. Note that only those pairs of `simulated` and `observed` values are returned which do not contain any `nan`: 1.0, 3.0 4.0, 6.0 The final examples show the error messages returned in case of invalid combinations of input arguments: Traceback (most recent call last):
ValueError: Neither a `Node` object is passed to argument `node` nor \ are arrays passed to arguments `sim` and `obs`. Traceback (most recent call last):
ValueError: Values are passed to both arguments `sim` and `node`, \ which is not allowed. Traceback (most recent call last):
ValueError: Values are passed to both arguments `obs` and `node`, \ which is not allowed. Traceback (most recent call last):
ValueError: A value is passed to argument `sim` but \ no value is passed to argument `obs`. Traceback (most recent call last):
ValueError: A value is passed to argument `obs` but \ no value is passed to argument `sim`. """ |
if node:
if sim is not None:
raise ValueError(
'Values are passed to both arguments `sim` and `node`, '
'which is not allowed.')
if obs is not None:
raise ValueError(
'Values are passed to both arguments `obs` and `node`, '
'which is not allowed.')
sim = node.sequences.sim.series
obs = node.sequences.obs.series
elif (sim is not None) and (obs is None):
raise ValueError(
'A value is passed to argument `sim` '
'but no value is passed to argument `obs`.')
elif (obs is not None) and (sim is None):
raise ValueError(
'A value is passed to argument `obs` '
'but no value is passed to argument `sim`.')
elif (sim is None) and (obs is None):
raise ValueError(
'Neither a `Node` object is passed to argument `node` nor '
'are arrays passed to arguments `sim` and `obs`.')
sim = numpy.asarray(sim)
obs = numpy.asarray(obs)
if skip_nan:
idxs = ~numpy.isnan(sim) * ~numpy.isnan(obs)
sim = sim[idxs]
obs = obs[idxs]
return sim, obs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nse(sim=None, obs=None, node=None, skip_nan=False):
"""Calculate the efficiency criteria after Nash & Sutcliffe. If the simulated values predict the observed values as well as the average observed value (regarding the the mean square error), the NSE value is zero: 0.0 0.0 For worse and better simulated values the NSE is negative or positive, respectively: -3.0 0.5 The highest possible value is one: 1.0 See the documentation on function |prepare_arrays| for some additional instructions for use of function |nse|. """ |
sim, obs = prepare_arrays(sim, obs, node, skip_nan)
return 1.-numpy.sum((sim-obs)**2)/numpy.sum((obs-numpy.mean(obs))**2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def bias_abs(sim=None, obs=None, node=None, skip_nan=False):
"""Calculate the absolute difference between the means of the simulated and the observed values. 0.0 1.0 -1.0 See the documentation on function |prepare_arrays| for some additional instructions for use of function |bias_abs|. """ |
sim, obs = prepare_arrays(sim, obs, node, skip_nan)
return numpy.mean(sim-obs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def std_ratio(sim=None, obs=None, node=None, skip_nan=False):
"""Calculate the ratio between the standard deviation of the simulated and the observed values. 0.0 -1.0 2.0 See the documentation on function |prepare_arrays| for some additional instructions for use of function |std_ratio|. """ |
sim, obs = prepare_arrays(sim, obs, node, skip_nan)
return numpy.std(sim)/numpy.std(obs)-1. |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def corr(sim=None, obs=None, node=None, skip_nan=False):
"""Calculate the product-moment correlation coefficient after Pearson. 1.0 -1.0 0.0 See the documentation on function |prepare_arrays| for some additional instructions for use of function |corr|. """ |
sim, obs = prepare_arrays(sim, obs, node, skip_nan)
return numpy.corrcoef(sim, obs)[0, 1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def hsepd_pdf(sigma1, sigma2, xi, beta, sim=None, obs=None, node=None, skip_nan=False):
"""Calculate the probability densities based on the heteroskedastic skewed exponential power distribution. For convenience, the required parameters of the probability density function as well as the simulated and observed values are stored in a dictonary: The following test function allows the variation of one parameter and prints some and plots all of probability density values corresponding to different simulated values: When varying parameter `beta`, the resulting probabilities correspond to the Laplace distribution (1.0), normal distribution (0.0), and the uniform distribution (-1.0), respectively. Note that we use -0.99 instead of -1.0 for approximating the uniform distribution to prevent from running into numerical problems, which are not solved yet: 10.0, 0.002032, 0.000886, 0.0 15.0, 0.008359, 0.010798, 0.0 20.0, 0.034382, 0.048394, 0.057739 25.0, 0.141421, 0.079788, 0.057739 30.0, 0.034382, 0.048394, 0.057739 35.0, 0.008359, 0.010798, 0.0 40.0, 0.002032, 0.000886, 0.0 .. testsetup:: When varying parameter `xi`, the resulting density is negatively skewed (0.2), symmetric (1.0), and positively skewed (5.0), respectively: 10.0, 0.0, 0.000886, 0.003175 15.0, 0.0, 0.010798, 0.012957 20.0, 0.092845, 0.048394, 0.036341 25.0, 0.070063, 0.079788, 0.070063 30.0, 0.036341, 0.048394, 0.092845 35.0, 0.012957, 0.010798, 0.0 40.0, 0.003175, 0.000886, 0.0 .. testsetup:: In the above examples, the actual `sigma` (5.0) is calculated by multiplying `sigma1` (0.2) with the mean simulated value (25.0), internally. This can be done for modelling homoscedastic errors. Instead, `sigma2` is multiplied with the individual simulated values to account for heteroscedastic errors. With increasing values of `sigma2`, the resulting densities are modified as follows: 10.0, 0.000886, 0.002921, 0.005737 15.0, 0.010798, 0.018795, 0.022831 20.0, 0.048394, 0.044159, 0.037988 25.0, 0.079788, 0.053192, 0.039894 30.0, 0.048394, 0.04102, 0.032708 35.0, 0.010798, 0.023493, 0.023493 40.0, 0.000886, 0.011053, 0.015771 .. testsetup:: """ |
sim, obs = prepare_arrays(sim, obs, node, skip_nan)
sigmas = _pars_h(sigma1, sigma2, sim)
mu_xi, sigma_xi, w_beta, c_beta = _pars_sepd(xi, beta)
x, mu = obs, sim
a = (x-mu)/sigmas
a_xi = numpy.empty(a.shape)
idxs = mu_xi+sigma_xi*a < 0.
a_xi[idxs] = numpy.absolute(xi*(mu_xi+sigma_xi*a[idxs]))
a_xi[~idxs] = numpy.absolute(1./xi*(mu_xi+sigma_xi*a[~idxs]))
ps = (2.*sigma_xi/(xi+1./xi)*w_beta *
numpy.exp(-c_beta*a_xi**(2./(1.+beta))))/sigmas
return ps |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_mean_time(timepoints, weights):
"""Return the weighted mean of the given timepoints. With equal given weights, the result is simply the mean of the given time points: 5.0 With different weights, the resulting mean time is shifted to the larger ones: 6.0 Or, in the most extreme case: 7.0 There will be some checks for input plausibility perfomed, e.g.: Traceback (most recent call last):
ValueError: While trying to calculate the weighted mean time, \ the following error occurred: For the following objects, at least \ one value is negative: weights. """ |
timepoints = numpy.array(timepoints)
weights = numpy.array(weights)
validtools.test_equal_shape(timepoints=timepoints, weights=weights)
validtools.test_non_negative(weights=weights)
return numpy.dot(timepoints, weights)/numpy.sum(weights) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_mean_time_deviation(timepoints, weights, mean_time=None):
"""Return the weighted deviation of the given timepoints from their mean time. With equal given weights, the is simply the standard deviation of the given time points: 2.0 One can pass a precalculated or alternate mean time: 2.236068 1.732051 Or, in the most extreme case: 0.0 There will be some checks for input plausibility perfomed, e.g.: Traceback (most recent call last):
ValueError: While trying to calculate the weighted time deviation \ from mean time, the following error occurred: For the following objects, \ at least one value is negative: weights. """ |
timepoints = numpy.array(timepoints)
weights = numpy.array(weights)
validtools.test_equal_shape(timepoints=timepoints, weights=weights)
validtools.test_non_negative(weights=weights)
if mean_time is None:
mean_time = calc_mean_time(timepoints, weights)
return (numpy.sqrt(numpy.dot(weights, (timepoints-mean_time)**2) /
numpy.sum(weights))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluationtable(nodes, criteria, nodenames=None, critnames=None, skip_nan=False):
"""Return a table containing the results of the given evaluation criteria for the given |Node| objects. First, we define two nodes with different simulation and observation data (see function |prepare_arrays| for some explanations):
Selecting functions |corr| and |bias_abs| as evaluation criteria, function |evaluationtable| returns the following table (which is actually a pandas data frame):
corr bias_abs test1 1.0 -3.0 test2 NaN NaN One can pass alternative names for both the node objects and the criteria functions. Also, `nan` values can be skipped: corrcoef bias first node 1.0 -3.0 second node -1.0 0.0 The number of assigned node objects and criteria functions must match the number of givern alternative names: Traceback (most recent call last):
ValueError: While trying to evaluate the simulation results of some \ node objects, the following error occurred: 2 node objects are given \ which does not match with number of given alternative names beeing 1. Traceback (most recent call last):
ValueError: While trying to evaluate the simulation results of some \ node objects, the following error occurred: 2 criteria functions are given \ which does not match with number of given alternative names beeing 1. """ |
if nodenames:
if len(nodes) != len(nodenames):
raise ValueError(
'%d node objects are given which does not match with '
'number of given alternative names beeing %s.'
% (len(nodes), len(nodenames)))
else:
nodenames = [node.name for node in nodes]
if critnames:
if len(criteria) != len(critnames):
raise ValueError(
'%d criteria functions are given which does not match '
'with number of given alternative names beeing %s.'
% (len(criteria), len(critnames)))
else:
critnames = [crit.__name__ for crit in criteria]
data = numpy.empty((len(nodes), len(criteria)), dtype=float)
for idx, node in enumerate(nodes):
sim, obs = prepare_arrays(None, None, node, skip_nan)
for jdx, criterion in enumerate(criteria):
data[idx, jdx] = criterion(sim, obs)
table = pandas.DataFrame(
data=data, index=nodenames, columns=critnames)
return table |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_primary_parameters(self, **kwargs):
"""Set all primary parameters at once.""" |
given = sorted(kwargs.keys())
required = sorted(self._PRIMARY_PARAMETERS)
if given == required:
for (key, value) in kwargs.items():
setattr(self, key, value)
else:
raise ValueError(
'When passing primary parameter values as initialization '
'arguments of the instantaneous unit hydrograph class `%s`, '
'or when using method `set_primary_parameters, one has to '
'to define all values at once via keyword arguments. '
'But instead of the primary parameter names `%s` the '
'following keywords were given: %s.'
% (objecttools.classname(self),
', '.join(required), ', '.join(given))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_secondary_parameters(self):
"""Determine the value of the secondary parameter `c`.""" |
self.c = 1./(self.k*special.gamma(self.n)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(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,
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: Zero damping is achieved through the following coefficients: For initialization, assume a base flow of 2m³/s: 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: qjoints(5.0, 2.0, 2.0, 2.0, 2.0) qjoints(8.0, 5.0, 2.0, 2.0, 2.0) qjoints(6.0, 8.0, 5.0, 2.0, 2.0) With the maximum damping allowed, the values of the derived parameters are: Assuming again a base flow of 2m³/s and the same input values results in: qjoints(5.0, 3.5, 2.75, 2.375, 2.1875) qjoints(8.0, 5.75, 4.25, 3.3125, 2.75) 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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pick_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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pass_q_v1(self):
"""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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. Assume you wildcard import the first version of HydPy-L-Land (|lland_v1|):
This for example adds the collection class for handling control parameters of `lland_v1` into the local namespace: control Calling function |parameterstep| for example prepares the control parameter object |lland_control.NHRU|: nhru(?) Calling function |reverse_model_wildcard_import| removes both objects (and many more, but not all) from the local namespace: Traceback (most recent call last):
NameError: name 'ControlParameters' is not defined 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: 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. 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: 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: (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: Traceback (most recent call last):
FileNotFoundError: While trying to load the control file \ 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |RelSoilArea| based on |Area|, |ZoneArea|, and |ZoneType|. 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |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: (1,) 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: (1,) 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: (2,) uh(0.5) 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: (3,) 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: (4,) 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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self):
"""Update |QFactor| based on |Area| and the current simulation step size. qfactor(1.157407) """ |
self(self.subpars.pars.control.area*1000. /
self.subpars.qfactor.simulationstep.seconds) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""Number of neurons of the hidden layers. (2, 1) (3,) 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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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):
(2, 4, 3) (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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nmb_weights_hidden(self) -> int: """Number of hidden weights. 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def verify(self) -> None: """Raise a |RuntimeError| if the network's shape is not defined completely. 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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refresh(self) -> None: """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: (2, 3) (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: (2, 3) (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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: (2, 3) (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: 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() 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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""The shape of array |anntools.SeasonalANN.ratios|.""" |
return tuple(int(sub) for sub in self.ratios.shape) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
"""A sorted |tuple| of all contained |TOY| objects.""" |
return tuple(toy for (toy, _) in self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def specstring(self):
"""The string corresponding to the current values of `subgroup`, `state`, and `variable`. 'fluxes.qt' 'fluxes.qt.series' '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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: We change the type of a specific application model to the type of its base model for reasons explained later: We prepare a |SetItem| as an example, handling all |hland_states.Ic| sequences corresponding to any application models derived from |hland|: ExchangeSpecification('hland', 'states.ic') Applying method |ExchangeItem.collect_variables| connects the |SetItem| object with all four relevant |hland_states.Ic| objects: True 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):
land_dill land_lahn_1 land_lahn_2 Selecting a series of a variable instead of the variable itself only affects the `targetspec` attribute: ExchangeSpecification('hland_v1', 'inputs.t.series') True It is both possible to address sequences of |Node| objects, as well as their time series, by arguments "node" and "nodes": ExchangeSpecification('node', 'sim') True dill lahn_1 lahn_2 lahn_3 ExchangeSpecification('nodes', 'sim.series') dill lahn_1 lahn_2 lahn_3 """ |
self.insert_variables(self.device2target, self.targetspecs, selections) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def 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: In the first example, a 0-dimensional |SetItem| changes the value of the 0-dimensional parameter |hland_control.Alpha|: SetItem('alpha', 'hland_v1', 'control.alpha', 0) True alpha(1.0) array(2.0) alpha(1.0) alpha(2.0) In the second example, a 0-dimensional |SetItem| changes the values of the 1-dimensional parameter |hland_control.FC|: fc(278.0) fc(200.0) In the third example, a 1-dimensional |SetItem| changes the values of the 1-dimensional sequence |hland_states.Ic|: ic(nan, nan, nan, nan, nan) ic(2.0, 2.0, 2.0, 2.0, 2.0) 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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. True True land_dill land_lahn_1 land_lahn_2 land_lahn_3 """ |
super().collect_variables(selections)
self.insert_variables(self.device2base, self.basespecs, selections) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_variables(self) -> None: """Add the general |ChangeItem.value| with the |Device| specific base variable and assign the result to the respective target variable. sfcf(?) sfcf(1.0, 1.1, 1.2) 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 \ """ |
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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: 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 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] When querying time series, one can restrict the span of interest by passing index values: dill_sim_series [1.0, 2.0, 3.0, 4.0] 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_open(location=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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_controls(self, parameterstep=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: At first, there is only one control subfolder named "default", containing the seven control files used in the step above: ['default'] Next, we use the |ControlManager| to create a new directory and dump all control file into it: ['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: lag(0.583) damp(0.0) The corresponding written control file defines the same values: # -*- 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|: 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: 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: # -*- 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: # -*- 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: # -*- 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: # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('2d') <BLANKLINE> lag(auxfile='stream') damp(auxfile='stream') <BLANKLINE> # -*- coding: utf-8 -*- <BLANKLINE> from hydpy.models.hstream_v1 import * <BLANKLINE> simulationstep('1h') parameterstep('2d') <BLANKLINE> damp(0.0) lag(0.2915) <BLANKLINE> # -*- 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def variables(self):
"""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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: Prepare a very simple relationship based on one single neuron: At least in the water volume range used in the following examples, the shape of the relationship looks acceptable: | 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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: 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) The following test function is supposed to calculate |AllowedRemoteRelieve| for values of |WaterLevel| ranging from 0 and 8 m: 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|):
| 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|: | 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])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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):
| ex. | waterlevel | requiredremotesupply | | 3 | 1.0 | 1.0 | | 4 | 2.0 | 1.0 | | 5 | 3.0 | 0.0 | | 6 | 4.0 | 0.0 | | 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])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: 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: 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. |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: Prepare the dam model: 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: 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: On April 1, the required discharge is 2 m³/s: | 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: | 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.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: Now we prepare a dam model with log sequences memorizing three values: Again, the required discharge is 2 m³/s in summer and 0 m³/s in winter: 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: This means that for the April 1 there would have been an averaged shortfall of 1 m³/s: 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": 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]] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: Prepare the dam model: Define a safety factor of 0.5 m³/s for the summer months and no safety factor at all for the winter months: Assume the actual demand at the cross section downsstream has actually been estimated to be 2 m³/s: 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: On May 31, the safety factor is 0 m³/s. Hence no discharge is added to the estimated remote demand of 2 m³/s: | 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: | 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]])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: requiredremoterelease(3.0) """ |
flu = self.sequences.fluxes.fastaccess
log = self.sequences.logs.fastaccess
flu.requiredremoterelease = log.loggedrequiredremoterelease[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: allowedremoterelieve(2.0) """ |
flu = self.sequences.fluxes.fastaccess
log = self.sequences.logs.fastaccess
flu.allowedremoterelieve = log.loggedallowedremoterelieve[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: | 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] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: Prepare a test function object that performs seven examples with |PossibleRemoteRelieve| ranging from -1 to 5 m³/s: We begin with a |AllowedRemoteRelieve| value of 3 m³/s: 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: | 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: | 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: | 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: | 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: | 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.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: Prepare the dam model: We start with enabling |RestrictTargetedRelease|: 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: Also define related tolerance values that are 1 m³/s in summer and 0 m³/s in winter: 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: Firstly, assume the required release of water for reducing droughts has already been determined to be 10 m³/s: 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: | 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: | 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 On May 31, the relationship between targeted release and inflow is again highly discontinous: | 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: | 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: | 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: | 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|: | 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: Assume the required release has previously been estimated to be 2 m³/s: Prepare a test function, that calculates the targeted water release for water levels ranging between -1 and 5 m: .. _dam_calc_actualrelease_v1_ex01: **Example 1** Firstly, we define a sharp minimum water level of 0 m: 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: | 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: 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: | 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: 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: | 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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: missingremoterelease(1.0) missingremoterelease(0.0) """ |
flu = self.sequences.fluxes.fastaccess
flu.missingremoterelease = max(
flu.requiredremoterelease-flu.actualrelease, 0.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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. :ref:`Recalculation of example 1 <dam_calc_actualrelease_v1_ex01>` | 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>` | 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>` | 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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_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: 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: 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: | 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: | 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.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_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: outflow(5.0) outflow(0.0) """ |
flu = self.sequences.fluxes.fastaccess
flu.outflow = max(flu.actualrelease + flu.flooddischarge, 0.) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_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: 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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pass_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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pass_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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def effective_max_ar_order(self):
"""The maximum number of AR coefficients that shall or can be determined. It is the minimum of |ARMA.max_ar_order| and the number of coefficients of the pure |MA| after their turning point. """ |
return min(self.max_ar_order, self.ma.order-self.ma.turningpoint[0]-1) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_ar_coefs(self):
"""Determine the AR coefficients. The number of AR coefficients is subsequently increased until the required precision |ARMA.max_rel_rmse| is reached. Otherwise, a |RuntimeError| is raised. """ |
del self.ar_coefs
for ar_order in range(1, self.effective_max_ar_order+1):
self.calc_all_ar_coefs(ar_order, self.ma)
if self._rel_rmse < self.max_rel_rmse:
break
else:
with hydpy.pub.options.reprdigits(12):
raise RuntimeError(
f'Method `update_ar_coefs` is not able to determine '
f'the AR coefficients of the ARMA model with the desired '
f'accuracy. You can either set the tolerance value '
f'`max_rel_rmse` to a higher value or increase the '
f'allowed `max_ar_order`. An accuracy of `'
f'{objecttools.repr_(self._rel_rmse)}` has been reached '
f'using `{self.effective_max_ar_order}` coefficients.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dev_moments(self):
"""Sum of the absolute deviations between the central moments of the instantaneous unit hydrograph and the ARMA approximation.""" |
return numpy.sum(numpy.abs(self.moments-self.ma.moments)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def norm_coefs(self):
"""Multiply all coefficients by the same factor, so that their sum becomes one.""" |
sum_coefs = self.sum_coefs
self.ar_coefs /= sum_coefs
self.ma_coefs /= sum_coefs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sum_coefs(self):
"""The sum of all AR and MA coefficients""" |
return numpy.sum(self.ar_coefs) + numpy.sum(self.ma_coefs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def calc_all_ar_coefs(self, ar_order, ma_model):
"""Determine the AR coeffcients based on a least squares approach. The argument `ar_order` defines the number of AR coefficients to be determined. The argument `ma_order` defines a pure |MA| model. The least squares approach is applied on all those coefficents of the pure MA model, which are associated with the part of the recession curve behind its turning point. The attribute |ARMA.rel_rmse| is updated with the resulting relative root mean square error. """ |
turning_idx, _ = ma_model.turningpoint
values = ma_model.coefs[turning_idx:]
self.ar_coefs, residuals = numpy.linalg.lstsq(
self.get_a(values, ar_order),
self.get_b(values, ar_order),
rcond=-1)[:2]
if len(residuals) == 1:
self._rel_rmse = numpy.sqrt(residuals[0])/numpy.sum(values)
else:
self._rel_rmse = 0. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.