repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.effective_max_ar_order
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)
python
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)
[ "def", "effective_max_ar_order", "(", "self", ")", ":", "return", "min", "(", "self", ".", "max_ar_order", ",", "self", ".", "ma", ".", "order", "-", "self", ".", "ma", ".", "turningpoint", "[", "0", "]", "-", "1", ")" ]
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.
[ "The", "maximum", "number", "of", "AR", "coefficients", "that", "shall", "or", "can", "be", "determined", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L548-L555
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.update_ar_coefs
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.')
python
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.')
[ "def", "update_ar_coefs", "(", "self", ")", ":", "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.'", ")" ]
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.
[ "Determine", "the", "AR", "coefficients", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L557-L578
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.dev_moments
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))
python
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))
[ "def", "dev_moments", "(", "self", ")", ":", "return", "numpy", ".", "sum", "(", "numpy", ".", "abs", "(", "self", ".", "moments", "-", "self", ".", "ma", ".", "moments", ")", ")" ]
Sum of the absolute deviations between the central moments of the instantaneous unit hydrograph and the ARMA approximation.
[ "Sum", "of", "the", "absolute", "deviations", "between", "the", "central", "moments", "of", "the", "instantaneous", "unit", "hydrograph", "and", "the", "ARMA", "approximation", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L581-L584
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.norm_coefs
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
python
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
[ "def", "norm_coefs", "(", "self", ")", ":", "sum_coefs", "=", "self", ".", "sum_coefs", "self", ".", "ar_coefs", "/=", "sum_coefs", "self", ".", "ma_coefs", "/=", "sum_coefs" ]
Multiply all coefficients by the same factor, so that their sum becomes one.
[ "Multiply", "all", "coefficients", "by", "the", "same", "factor", "so", "that", "their", "sum", "becomes", "one", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L586-L591
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.sum_coefs
def sum_coefs(self): """The sum of all AR and MA coefficients""" return numpy.sum(self.ar_coefs) + numpy.sum(self.ma_coefs)
python
def sum_coefs(self): """The sum of all AR and MA coefficients""" return numpy.sum(self.ar_coefs) + numpy.sum(self.ma_coefs)
[ "def", "sum_coefs", "(", "self", ")", ":", "return", "numpy", ".", "sum", "(", "self", ".", "ar_coefs", ")", "+", "numpy", ".", "sum", "(", "self", ".", "ma_coefs", ")" ]
The sum of all AR and MA coefficients
[ "The", "sum", "of", "all", "AR", "and", "MA", "coefficients" ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L594-L596
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.calc_all_ar_coefs
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.
python
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.
[ "def", "calc_all_ar_coefs", "(", "self", ",", "ar_order", ",", "ma_model", ")", ":", "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." ]
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.
[ "Determine", "the", "AR", "coeffcients", "based", "on", "a", "least", "squares", "approach", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L603-L624
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.get_a
def get_a(values, n): """Extract the independent variables of the given values and return them as a matrix with n columns in a form suitable for the least squares approach applied in method |ARMA.update_ar_coefs|. """ m = len(values)-n a = numpy.empty((m, n), dtype=float) for i in range(m): i0 = i-1 if i > 0 else None i1 = i+n-1 a[i] = values[i1:i0:-1] return numpy.array(a)
python
def get_a(values, n): """Extract the independent variables of the given values and return them as a matrix with n columns in a form suitable for the least squares approach applied in method |ARMA.update_ar_coefs|. """ m = len(values)-n a = numpy.empty((m, n), dtype=float) for i in range(m): i0 = i-1 if i > 0 else None i1 = i+n-1 a[i] = values[i1:i0:-1] return numpy.array(a)
[ "def", "get_a", "(", "values", ",", "n", ")", ":", "m", "=", "len", "(", "values", ")", "-", "n", "a", "=", "numpy", ".", "empty", "(", "(", "m", ",", "n", ")", ",", "dtype", "=", "float", ")", "for", "i", "in", "range", "(", "m", ")", ":", "i0", "=", "i", "-", "1", "if", "i", ">", "0", "else", "None", "i1", "=", "i", "+", "n", "-", "1", "a", "[", "i", "]", "=", "values", "[", "i1", ":", "i0", ":", "-", "1", "]", "return", "numpy", ".", "array", "(", "a", ")" ]
Extract the independent variables of the given values and return them as a matrix with n columns in a form suitable for the least squares approach applied in method |ARMA.update_ar_coefs|.
[ "Extract", "the", "independent", "variables", "of", "the", "given", "values", "and", "return", "them", "as", "a", "matrix", "with", "n", "columns", "in", "a", "form", "suitable", "for", "the", "least", "squares", "approach", "applied", "in", "method", "|ARMA", ".", "update_ar_coefs|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L627-L638
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.update_ma_coefs
def update_ma_coefs(self): """Determine the MA coefficients. The number of MA coefficients is subsequently increased until the required precision |ARMA.max_dev_coefs| is reached. Otherwise, a |RuntimeError| is raised. """ self.ma_coefs = [] for ma_order in range(1, self.ma.order+1): self.calc_next_ma_coef(ma_order, self.ma) if self.dev_coefs < self.max_dev_coefs: self.norm_coefs() break else: with hydpy.pub.options.reprdigits(12): raise RuntimeError( f'Method `update_ma_coefs` is not able to determine the ' f'MA coefficients of the ARMA model with the desired ' f'accuracy. You can set the tolerance value ' f'´max_dev_coefs` to a higher value. An accuracy of ' f'`{objecttools.repr_(self.dev_coefs)}` has been reached ' f'using `{self.ma.order}` MA coefficients.') if numpy.min(self.response) < 0.: warnings.warn( 'Note that the smallest response to a standard impulse of the ' 'determined ARMA model is negative (`%s`).' % objecttools.repr_(numpy.min(self.response)))
python
def update_ma_coefs(self): """Determine the MA coefficients. The number of MA coefficients is subsequently increased until the required precision |ARMA.max_dev_coefs| is reached. Otherwise, a |RuntimeError| is raised. """ self.ma_coefs = [] for ma_order in range(1, self.ma.order+1): self.calc_next_ma_coef(ma_order, self.ma) if self.dev_coefs < self.max_dev_coefs: self.norm_coefs() break else: with hydpy.pub.options.reprdigits(12): raise RuntimeError( f'Method `update_ma_coefs` is not able to determine the ' f'MA coefficients of the ARMA model with the desired ' f'accuracy. You can set the tolerance value ' f'´max_dev_coefs` to a higher value. An accuracy of ' f'`{objecttools.repr_(self.dev_coefs)}` has been reached ' f'using `{self.ma.order}` MA coefficients.') if numpy.min(self.response) < 0.: warnings.warn( 'Note that the smallest response to a standard impulse of the ' 'determined ARMA model is negative (`%s`).' % objecttools.repr_(numpy.min(self.response)))
[ "def", "update_ma_coefs", "(", "self", ")", ":", "self", ".", "ma_coefs", "=", "[", "]", "for", "ma_order", "in", "range", "(", "1", ",", "self", ".", "ma", ".", "order", "+", "1", ")", ":", "self", ".", "calc_next_ma_coef", "(", "ma_order", ",", "self", ".", "ma", ")", "if", "self", ".", "dev_coefs", "<", "self", ".", "max_dev_coefs", ":", "self", ".", "norm_coefs", "(", ")", "break", "else", ":", "with", "hydpy", ".", "pub", ".", "options", ".", "reprdigits", "(", "12", ")", ":", "raise", "RuntimeError", "(", "f'Method `update_ma_coefs` is not able to determine the '", "f'MA coefficients of the ARMA model with the desired '", "f'accuracy. You can set the tolerance value '", "f'´max_dev_coefs` to a higher value. An accuracy of '", "f'`{objecttools.repr_(self.dev_coefs)}` has been reached '", "f'using `{self.ma.order}` MA coefficients.'", ")", "if", "numpy", ".", "min", "(", "self", ".", "response", ")", "<", "0.", ":", "warnings", ".", "warn", "(", "'Note that the smallest response to a standard impulse of the '", "'determined ARMA model is negative (`%s`).'", "%", "objecttools", ".", "repr_", "(", "numpy", ".", "min", "(", "self", ".", "response", ")", ")", ")" ]
Determine the MA coefficients. The number of MA coefficients is subsequently increased until the required precision |ARMA.max_dev_coefs| is reached. Otherwise, a |RuntimeError| is raised.
[ "Determine", "the", "MA", "coefficients", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L648-L674
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.calc_next_ma_coef
def calc_next_ma_coef(self, ma_order, ma_model): """Determine the MA coefficients of the ARMA model based on its predetermined AR coefficients and the MA ordinates of the given |MA| model. The MA coefficients are determined one at a time, beginning with the first one. Each ARMA MA coefficient in set in a manner that allows for the exact reproduction of the equivalent pure MA coefficient with all relevant ARMA coefficients. """ idx = ma_order-1 coef = ma_model.coefs[idx] for jdx, ar_coef in enumerate(self.ar_coefs): zdx = idx-jdx-1 if zdx >= 0: coef -= ar_coef*ma_model.coefs[zdx] self.ma_coefs = numpy.concatenate((self.ma_coefs, [coef]))
python
def calc_next_ma_coef(self, ma_order, ma_model): """Determine the MA coefficients of the ARMA model based on its predetermined AR coefficients and the MA ordinates of the given |MA| model. The MA coefficients are determined one at a time, beginning with the first one. Each ARMA MA coefficient in set in a manner that allows for the exact reproduction of the equivalent pure MA coefficient with all relevant ARMA coefficients. """ idx = ma_order-1 coef = ma_model.coefs[idx] for jdx, ar_coef in enumerate(self.ar_coefs): zdx = idx-jdx-1 if zdx >= 0: coef -= ar_coef*ma_model.coefs[zdx] self.ma_coefs = numpy.concatenate((self.ma_coefs, [coef]))
[ "def", "calc_next_ma_coef", "(", "self", ",", "ma_order", ",", "ma_model", ")", ":", "idx", "=", "ma_order", "-", "1", "coef", "=", "ma_model", ".", "coefs", "[", "idx", "]", "for", "jdx", ",", "ar_coef", "in", "enumerate", "(", "self", ".", "ar_coefs", ")", ":", "zdx", "=", "idx", "-", "jdx", "-", "1", "if", "zdx", ">=", "0", ":", "coef", "-=", "ar_coef", "*", "ma_model", ".", "coefs", "[", "zdx", "]", "self", ".", "ma_coefs", "=", "numpy", ".", "concatenate", "(", "(", "self", ".", "ma_coefs", ",", "[", "coef", "]", ")", ")" ]
Determine the MA coefficients of the ARMA model based on its predetermined AR coefficients and the MA ordinates of the given |MA| model. The MA coefficients are determined one at a time, beginning with the first one. Each ARMA MA coefficient in set in a manner that allows for the exact reproduction of the equivalent pure MA coefficient with all relevant ARMA coefficients.
[ "Determine", "the", "MA", "coefficients", "of", "the", "ARMA", "model", "based", "on", "its", "predetermined", "AR", "coefficients", "and", "the", "MA", "ordinates", "of", "the", "given", "|MA|", "model", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L676-L692
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.response
def response(self): """Return the response to a standard dt impulse.""" values = [] sum_values = 0. ma_coefs = self.ma_coefs ar_coefs = self.ar_coefs ma_order = self.ma_order for idx in range(len(self.ma.delays)): value = 0. if idx < ma_order: value += ma_coefs[idx] for jdx, ar_coef in enumerate(ar_coefs): zdx = idx-jdx-1 if zdx >= 0: value += ar_coef*values[zdx] values.append(value) sum_values += value return numpy.array(values)
python
def response(self): """Return the response to a standard dt impulse.""" values = [] sum_values = 0. ma_coefs = self.ma_coefs ar_coefs = self.ar_coefs ma_order = self.ma_order for idx in range(len(self.ma.delays)): value = 0. if idx < ma_order: value += ma_coefs[idx] for jdx, ar_coef in enumerate(ar_coefs): zdx = idx-jdx-1 if zdx >= 0: value += ar_coef*values[zdx] values.append(value) sum_values += value return numpy.array(values)
[ "def", "response", "(", "self", ")", ":", "values", "=", "[", "]", "sum_values", "=", "0.", "ma_coefs", "=", "self", ".", "ma_coefs", "ar_coefs", "=", "self", ".", "ar_coefs", "ma_order", "=", "self", ".", "ma_order", "for", "idx", "in", "range", "(", "len", "(", "self", ".", "ma", ".", "delays", ")", ")", ":", "value", "=", "0.", "if", "idx", "<", "ma_order", ":", "value", "+=", "ma_coefs", "[", "idx", "]", "for", "jdx", ",", "ar_coef", "in", "enumerate", "(", "ar_coefs", ")", ":", "zdx", "=", "idx", "-", "jdx", "-", "1", "if", "zdx", ">=", "0", ":", "value", "+=", "ar_coef", "*", "values", "[", "zdx", "]", "values", ".", "append", "(", "value", ")", "sum_values", "+=", "value", "return", "numpy", ".", "array", "(", "values", ")" ]
Return the response to a standard dt impulse.
[ "Return", "the", "response", "to", "a", "standard", "dt", "impulse", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L695-L712
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.moments
def moments(self): """The first two time delay weighted statistical moments of the ARMA response.""" timepoints = self.ma.delays response = self.response moment1 = statstools.calc_mean_time(timepoints, response) moment2 = statstools.calc_mean_time_deviation( timepoints, response, moment1) return numpy.array([moment1, moment2])
python
def moments(self): """The first two time delay weighted statistical moments of the ARMA response.""" timepoints = self.ma.delays response = self.response moment1 = statstools.calc_mean_time(timepoints, response) moment2 = statstools.calc_mean_time_deviation( timepoints, response, moment1) return numpy.array([moment1, moment2])
[ "def", "moments", "(", "self", ")", ":", "timepoints", "=", "self", ".", "ma", ".", "delays", "response", "=", "self", ".", "response", "moment1", "=", "statstools", ".", "calc_mean_time", "(", "timepoints", ",", "response", ")", "moment2", "=", "statstools", ".", "calc_mean_time_deviation", "(", "timepoints", ",", "response", ",", "moment1", ")", "return", "numpy", ".", "array", "(", "[", "moment1", ",", "moment2", "]", ")" ]
The first two time delay weighted statistical moments of the ARMA response.
[ "The", "first", "two", "time", "delay", "weighted", "statistical", "moments", "of", "the", "ARMA", "response", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L715-L723
train
hydpy-dev/hydpy
hydpy/auxs/armatools.py
ARMA.plot
def plot(self, threshold=None, **kwargs): """Barplot of the ARMA response.""" try: # Works under matplotlib 3. pyplot.bar(x=self.ma.delays+.5, height=self.response, width=1., fill=False, **kwargs) except TypeError: # pragma: no cover # Works under matplotlib 2. pyplot.bar(left=self.ma.delays+.5, height=self.response, width=1., fill=False, **kwargs) pyplot.xlabel('time') pyplot.ylabel('response') if threshold is not None: cumsum = numpy.cumsum(self.response) idx = numpy.where(cumsum > threshold*cumsum[-1])[0][0] pyplot.xlim(0., idx)
python
def plot(self, threshold=None, **kwargs): """Barplot of the ARMA response.""" try: # Works under matplotlib 3. pyplot.bar(x=self.ma.delays+.5, height=self.response, width=1., fill=False, **kwargs) except TypeError: # pragma: no cover # Works under matplotlib 2. pyplot.bar(left=self.ma.delays+.5, height=self.response, width=1., fill=False, **kwargs) pyplot.xlabel('time') pyplot.ylabel('response') if threshold is not None: cumsum = numpy.cumsum(self.response) idx = numpy.where(cumsum > threshold*cumsum[-1])[0][0] pyplot.xlim(0., idx)
[ "def", "plot", "(", "self", ",", "threshold", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "# Works under matplotlib 3.", "pyplot", ".", "bar", "(", "x", "=", "self", ".", "ma", ".", "delays", "+", ".5", ",", "height", "=", "self", ".", "response", ",", "width", "=", "1.", ",", "fill", "=", "False", ",", "*", "*", "kwargs", ")", "except", "TypeError", ":", "# pragma: no cover", "# Works under matplotlib 2.", "pyplot", ".", "bar", "(", "left", "=", "self", ".", "ma", ".", "delays", "+", ".5", ",", "height", "=", "self", ".", "response", ",", "width", "=", "1.", ",", "fill", "=", "False", ",", "*", "*", "kwargs", ")", "pyplot", ".", "xlabel", "(", "'time'", ")", "pyplot", ".", "ylabel", "(", "'response'", ")", "if", "threshold", "is", "not", "None", ":", "cumsum", "=", "numpy", ".", "cumsum", "(", "self", ".", "response", ")", "idx", "=", "numpy", ".", "where", "(", "cumsum", ">", "threshold", "*", "cumsum", "[", "-", "1", "]", ")", "[", "0", "]", "[", "0", "]", "pyplot", ".", "xlim", "(", "0.", ",", "idx", ")" ]
Barplot of the ARMA response.
[ "Barplot", "of", "the", "ARMA", "response", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/armatools.py#L725-L740
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
method_header
def method_header(method_name, nogil=False, idx_as_arg=False): """Returns the Cython method header for methods without arguments except `self`.""" if not config.FASTCYTHON: nogil = False header = 'cpdef inline void %s(self' % method_name header += ', int idx)' if idx_as_arg else ')' header += ' nogil:' if nogil else ':' return header
python
def method_header(method_name, nogil=False, idx_as_arg=False): """Returns the Cython method header for methods without arguments except `self`.""" if not config.FASTCYTHON: nogil = False header = 'cpdef inline void %s(self' % method_name header += ', int idx)' if idx_as_arg else ')' header += ' nogil:' if nogil else ':' return header
[ "def", "method_header", "(", "method_name", ",", "nogil", "=", "False", ",", "idx_as_arg", "=", "False", ")", ":", "if", "not", "config", ".", "FASTCYTHON", ":", "nogil", "=", "False", "header", "=", "'cpdef inline void %s(self'", "%", "method_name", "header", "+=", "', int idx)'", "if", "idx_as_arg", "else", "')'", "header", "+=", "' nogil:'", "if", "nogil", "else", "':'", "return", "header" ]
Returns the Cython method header for methods without arguments except `self`.
[ "Returns", "the", "Cython", "method", "header", "for", "methods", "without", "arguments", "except", "self", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L80-L88
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
decorate_method
def decorate_method(wrapped): """The decorated method will return a |Lines| object including a method header. However, the |Lines| object will be empty if the respective model does not implement a method with the same name as the wrapped method. """ def wrapper(self): lines = Lines() if hasattr(self.model, wrapped.__name__): print(' . %s' % wrapped.__name__) lines.add(1, method_header(wrapped.__name__, nogil=True)) for line in wrapped(self): lines.add(2, line) return lines functools.update_wrapper(wrapper, wrapped) wrapper.__doc__ = 'Lines of model method %s.' % wrapped.__name__ return property(wrapper)
python
def decorate_method(wrapped): """The decorated method will return a |Lines| object including a method header. However, the |Lines| object will be empty if the respective model does not implement a method with the same name as the wrapped method. """ def wrapper(self): lines = Lines() if hasattr(self.model, wrapped.__name__): print(' . %s' % wrapped.__name__) lines.add(1, method_header(wrapped.__name__, nogil=True)) for line in wrapped(self): lines.add(2, line) return lines functools.update_wrapper(wrapper, wrapped) wrapper.__doc__ = 'Lines of model method %s.' % wrapped.__name__ return property(wrapper)
[ "def", "decorate_method", "(", "wrapped", ")", ":", "def", "wrapper", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "if", "hasattr", "(", "self", ".", "model", ",", "wrapped", ".", "__name__", ")", ":", "print", "(", "' . %s'", "%", "wrapped", ".", "__name__", ")", "lines", ".", "add", "(", "1", ",", "method_header", "(", "wrapped", ".", "__name__", ",", "nogil", "=", "True", ")", ")", "for", "line", "in", "wrapped", "(", "self", ")", ":", "lines", ".", "add", "(", "2", ",", "line", ")", "return", "lines", "functools", ".", "update_wrapper", "(", "wrapper", ",", "wrapped", ")", "wrapper", ".", "__doc__", "=", "'Lines of model method %s.'", "%", "wrapped", ".", "__name__", "return", "property", "(", "wrapper", ")" ]
The decorated method will return a |Lines| object including a method header. However, the |Lines| object will be empty if the respective model does not implement a method with the same name as the wrapped method.
[ "The", "decorated", "method", "will", "return", "a", "|Lines|", "object", "including", "a", "method", "header", ".", "However", "the", "|Lines|", "object", "will", "be", "empty", "if", "the", "respective", "model", "does", "not", "implement", "a", "method", "with", "the", "same", "name", "as", "the", "wrapped", "method", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L91-L107
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
Lines.add
def add(self, indent, line): """Appends the given text line with prefixed spaces in accordance with the given number of indentation levels. """ if isinstance(line, str): list.append(self, indent*4*' ' + line) else: for subline in line: list.append(self, indent*4*' ' + subline)
python
def add(self, indent, line): """Appends the given text line with prefixed spaces in accordance with the given number of indentation levels. """ if isinstance(line, str): list.append(self, indent*4*' ' + line) else: for subline in line: list.append(self, indent*4*' ' + subline)
[ "def", "add", "(", "self", ",", "indent", ",", "line", ")", ":", "if", "isinstance", "(", "line", ",", "str", ")", ":", "list", ".", "append", "(", "self", ",", "indent", "*", "4", "*", "' '", "+", "line", ")", "else", ":", "for", "subline", "in", "line", ":", "list", ".", "append", "(", "self", ",", "indent", "*", "4", "*", "' '", "+", "subline", ")" ]
Appends the given text line with prefixed spaces in accordance with the given number of indentation levels.
[ "Appends", "the", "given", "text", "line", "with", "prefixed", "spaces", "in", "accordance", "with", "the", "given", "number", "of", "indentation", "levels", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L66-L74
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
Cythonizer.pyname
def pyname(self): """Name of the compiled module.""" if self.pymodule.endswith('__init__'): return self.pymodule.split('.')[-2] else: return self.pymodule.split('.')[-1]
python
def pyname(self): """Name of the compiled module.""" if self.pymodule.endswith('__init__'): return self.pymodule.split('.')[-2] else: return self.pymodule.split('.')[-1]
[ "def", "pyname", "(", "self", ")", ":", "if", "self", ".", "pymodule", ".", "endswith", "(", "'__init__'", ")", ":", "return", "self", ".", "pymodule", ".", "split", "(", "'.'", ")", "[", "-", "2", "]", "else", ":", "return", "self", ".", "pymodule", ".", "split", "(", "'.'", ")", "[", "-", "1", "]" ]
Name of the compiled module.
[ "Name", "of", "the", "compiled", "module", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L147-L152
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
Cythonizer.pyxwriter
def pyxwriter(self): """Update the pyx file.""" model = self.Model() if hasattr(self, 'Parameters'): model.parameters = self.Parameters(vars(self)) else: model.parameters = parametertools.Parameters(vars(self)) if hasattr(self, 'Sequences'): model.sequences = self.Sequences(model=model, **vars(self)) else: model.sequences = sequencetools.Sequences(model=model, **vars(self)) return PyxWriter(self, model, self.pyxfilepath)
python
def pyxwriter(self): """Update the pyx file.""" model = self.Model() if hasattr(self, 'Parameters'): model.parameters = self.Parameters(vars(self)) else: model.parameters = parametertools.Parameters(vars(self)) if hasattr(self, 'Sequences'): model.sequences = self.Sequences(model=model, **vars(self)) else: model.sequences = sequencetools.Sequences(model=model, **vars(self)) return PyxWriter(self, model, self.pyxfilepath)
[ "def", "pyxwriter", "(", "self", ")", ":", "model", "=", "self", ".", "Model", "(", ")", "if", "hasattr", "(", "self", ",", "'Parameters'", ")", ":", "model", ".", "parameters", "=", "self", ".", "Parameters", "(", "vars", "(", "self", ")", ")", "else", ":", "model", ".", "parameters", "=", "parametertools", ".", "Parameters", "(", "vars", "(", "self", ")", ")", "if", "hasattr", "(", "self", ",", "'Sequences'", ")", ":", "model", ".", "sequences", "=", "self", ".", "Sequences", "(", "model", "=", "model", ",", "*", "*", "vars", "(", "self", ")", ")", "else", ":", "model", ".", "sequences", "=", "sequencetools", ".", "Sequences", "(", "model", "=", "model", ",", "*", "*", "vars", "(", "self", ")", ")", "return", "PyxWriter", "(", "self", ",", "model", ",", "self", ".", "pyxfilepath", ")" ]
Update the pyx file.
[ "Update", "the", "pyx", "file", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L185-L197
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
Cythonizer.pysourcefiles
def pysourcefiles(self): """All source files of the actual models Python classes and their respective base classes.""" sourcefiles = set() for (name, child) in vars(self).items(): try: parents = inspect.getmro(child) except AttributeError: continue for parent in parents: try: sourcefile = inspect.getfile(parent) except TypeError: break sourcefiles.add(sourcefile) return Lines(*sourcefiles)
python
def pysourcefiles(self): """All source files of the actual models Python classes and their respective base classes.""" sourcefiles = set() for (name, child) in vars(self).items(): try: parents = inspect.getmro(child) except AttributeError: continue for parent in parents: try: sourcefile = inspect.getfile(parent) except TypeError: break sourcefiles.add(sourcefile) return Lines(*sourcefiles)
[ "def", "pysourcefiles", "(", "self", ")", ":", "sourcefiles", "=", "set", "(", ")", "for", "(", "name", ",", "child", ")", "in", "vars", "(", "self", ")", ".", "items", "(", ")", ":", "try", ":", "parents", "=", "inspect", ".", "getmro", "(", "child", ")", "except", "AttributeError", ":", "continue", "for", "parent", "in", "parents", ":", "try", ":", "sourcefile", "=", "inspect", ".", "getfile", "(", "parent", ")", "except", "TypeError", ":", "break", "sourcefiles", ".", "add", "(", "sourcefile", ")", "return", "Lines", "(", "*", "sourcefiles", ")" ]
All source files of the actual models Python classes and their respective base classes.
[ "All", "source", "files", "of", "the", "actual", "models", "Python", "classes", "and", "their", "respective", "base", "classes", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L200-L215
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
Cythonizer.outdated
def outdated(self): """True if at least one of the |Cythonizer.pysourcefiles| is newer than the compiled file under |Cythonizer.pyxfilepath|, otherwise False. """ if hydpy.pub.options.forcecompiling: return True if os.path.split(hydpy.__path__[0])[-2].endswith('-packages'): return False if not os.path.exists(self.dllfilepath): return True cydate = os.stat(self.dllfilepath).st_mtime for pysourcefile in self.pysourcefiles: pydate = os.stat(pysourcefile).st_mtime if pydate > cydate: return True return False
python
def outdated(self): """True if at least one of the |Cythonizer.pysourcefiles| is newer than the compiled file under |Cythonizer.pyxfilepath|, otherwise False. """ if hydpy.pub.options.forcecompiling: return True if os.path.split(hydpy.__path__[0])[-2].endswith('-packages'): return False if not os.path.exists(self.dllfilepath): return True cydate = os.stat(self.dllfilepath).st_mtime for pysourcefile in self.pysourcefiles: pydate = os.stat(pysourcefile).st_mtime if pydate > cydate: return True return False
[ "def", "outdated", "(", "self", ")", ":", "if", "hydpy", ".", "pub", ".", "options", ".", "forcecompiling", ":", "return", "True", "if", "os", ".", "path", ".", "split", "(", "hydpy", ".", "__path__", "[", "0", "]", ")", "[", "-", "2", "]", ".", "endswith", "(", "'-packages'", ")", ":", "return", "False", "if", "not", "os", ".", "path", ".", "exists", "(", "self", ".", "dllfilepath", ")", ":", "return", "True", "cydate", "=", "os", ".", "stat", "(", "self", ".", "dllfilepath", ")", ".", "st_mtime", "for", "pysourcefile", "in", "self", ".", "pysourcefiles", ":", "pydate", "=", "os", ".", "stat", "(", "pysourcefile", ")", ".", "st_mtime", "if", "pydate", ">", "cydate", ":", "return", "True", "return", "False" ]
True if at least one of the |Cythonizer.pysourcefiles| is newer than the compiled file under |Cythonizer.pyxfilepath|, otherwise False.
[ "True", "if", "at", "least", "one", "of", "the", "|Cythonizer", ".", "pysourcefiles|", "is", "newer", "than", "the", "compiled", "file", "under", "|Cythonizer", ".", "pyxfilepath|", "otherwise", "False", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L218-L234
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
Cythonizer.compile_
def compile_(self): """Translate cython code to C code and compile it.""" from Cython import Build argv = copy.deepcopy(sys.argv) sys.argv = [sys.argv[0], 'build_ext', '--build-lib='+self.buildpath] exc_modules = [ distutils.extension.Extension( 'hydpy.cythons.autogen.'+self.cyname, [self.pyxfilepath], extra_compile_args=['-O2'])] distutils.core.setup(ext_modules=Build.cythonize(exc_modules), include_dirs=[numpy.get_include()]) sys.argv = argv
python
def compile_(self): """Translate cython code to C code and compile it.""" from Cython import Build argv = copy.deepcopy(sys.argv) sys.argv = [sys.argv[0], 'build_ext', '--build-lib='+self.buildpath] exc_modules = [ distutils.extension.Extension( 'hydpy.cythons.autogen.'+self.cyname, [self.pyxfilepath], extra_compile_args=['-O2'])] distutils.core.setup(ext_modules=Build.cythonize(exc_modules), include_dirs=[numpy.get_include()]) sys.argv = argv
[ "def", "compile_", "(", "self", ")", ":", "from", "Cython", "import", "Build", "argv", "=", "copy", ".", "deepcopy", "(", "sys", ".", "argv", ")", "sys", ".", "argv", "=", "[", "sys", ".", "argv", "[", "0", "]", ",", "'build_ext'", ",", "'--build-lib='", "+", "self", ".", "buildpath", "]", "exc_modules", "=", "[", "distutils", ".", "extension", ".", "Extension", "(", "'hydpy.cythons.autogen.'", "+", "self", ".", "cyname", ",", "[", "self", ".", "pyxfilepath", "]", ",", "extra_compile_args", "=", "[", "'-O2'", "]", ")", "]", "distutils", ".", "core", ".", "setup", "(", "ext_modules", "=", "Build", ".", "cythonize", "(", "exc_modules", ")", ",", "include_dirs", "=", "[", "numpy", ".", "get_include", "(", ")", "]", ")", "sys", ".", "argv", "=", "argv" ]
Translate cython code to C code and compile it.
[ "Translate", "cython", "code", "to", "C", "code", "and", "compile", "it", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L236-L247
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
Cythonizer.move_dll
def move_dll(self): """Try to find the resulting dll file and to move it into the `cythons` package. Things to be aware of: * The file extension either `pyd` (Window) or `so` (Linux). * The folder containing the dll file is system dependent, but is always a subfolder of the `cythons` package. * Under Linux, the filename might contain system information, e.g. ...cpython-36m-x86_64-linux-gnu.so. """ dirinfos = os.walk(self.buildpath) next(dirinfos) system_dependent_filename = None for dirinfo in dirinfos: for filename in dirinfo[2]: if (filename.startswith(self.cyname) and filename.endswith(dllextension)): system_dependent_filename = filename break if system_dependent_filename: try: shutil.move(os.path.join(dirinfo[0], system_dependent_filename), os.path.join(self.cydirpath, self.cyname+dllextension)) break except BaseException: prefix = ('After trying to cythonize module %s, when ' 'trying to move the final cython module %s ' 'from directory %s to directory %s' % (self.pyname, system_dependent_filename, self.buildpath, self.cydirpath)) suffix = ('A likely error cause is that the cython module ' '%s does already exist in this directory and is ' 'currently blocked by another Python process. ' 'Maybe it helps to close all Python processes ' 'and restart the cyhonization afterwards.' % self.cyname+dllextension) objecttools.augment_excmessage(prefix, suffix) else: raise IOError('After trying to cythonize module %s, the resulting ' 'file %s could neither be found in directory %s nor ' 'its subdirectories. The distul report should tell ' 'whether the file has been stored somewhere else,' 'is named somehow else, or could not be build at ' 'all.' % self.buildpath)
python
def move_dll(self): """Try to find the resulting dll file and to move it into the `cythons` package. Things to be aware of: * The file extension either `pyd` (Window) or `so` (Linux). * The folder containing the dll file is system dependent, but is always a subfolder of the `cythons` package. * Under Linux, the filename might contain system information, e.g. ...cpython-36m-x86_64-linux-gnu.so. """ dirinfos = os.walk(self.buildpath) next(dirinfos) system_dependent_filename = None for dirinfo in dirinfos: for filename in dirinfo[2]: if (filename.startswith(self.cyname) and filename.endswith(dllextension)): system_dependent_filename = filename break if system_dependent_filename: try: shutil.move(os.path.join(dirinfo[0], system_dependent_filename), os.path.join(self.cydirpath, self.cyname+dllextension)) break except BaseException: prefix = ('After trying to cythonize module %s, when ' 'trying to move the final cython module %s ' 'from directory %s to directory %s' % (self.pyname, system_dependent_filename, self.buildpath, self.cydirpath)) suffix = ('A likely error cause is that the cython module ' '%s does already exist in this directory and is ' 'currently blocked by another Python process. ' 'Maybe it helps to close all Python processes ' 'and restart the cyhonization afterwards.' % self.cyname+dllextension) objecttools.augment_excmessage(prefix, suffix) else: raise IOError('After trying to cythonize module %s, the resulting ' 'file %s could neither be found in directory %s nor ' 'its subdirectories. The distul report should tell ' 'whether the file has been stored somewhere else,' 'is named somehow else, or could not be build at ' 'all.' % self.buildpath)
[ "def", "move_dll", "(", "self", ")", ":", "dirinfos", "=", "os", ".", "walk", "(", "self", ".", "buildpath", ")", "next", "(", "dirinfos", ")", "system_dependent_filename", "=", "None", "for", "dirinfo", "in", "dirinfos", ":", "for", "filename", "in", "dirinfo", "[", "2", "]", ":", "if", "(", "filename", ".", "startswith", "(", "self", ".", "cyname", ")", "and", "filename", ".", "endswith", "(", "dllextension", ")", ")", ":", "system_dependent_filename", "=", "filename", "break", "if", "system_dependent_filename", ":", "try", ":", "shutil", ".", "move", "(", "os", ".", "path", ".", "join", "(", "dirinfo", "[", "0", "]", ",", "system_dependent_filename", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "cydirpath", ",", "self", ".", "cyname", "+", "dllextension", ")", ")", "break", "except", "BaseException", ":", "prefix", "=", "(", "'After trying to cythonize module %s, when '", "'trying to move the final cython module %s '", "'from directory %s to directory %s'", "%", "(", "self", ".", "pyname", ",", "system_dependent_filename", ",", "self", ".", "buildpath", ",", "self", ".", "cydirpath", ")", ")", "suffix", "=", "(", "'A likely error cause is that the cython module '", "'%s does already exist in this directory and is '", "'currently blocked by another Python process. '", "'Maybe it helps to close all Python processes '", "'and restart the cyhonization afterwards.'", "%", "self", ".", "cyname", "+", "dllextension", ")", "objecttools", ".", "augment_excmessage", "(", "prefix", ",", "suffix", ")", "else", ":", "raise", "IOError", "(", "'After trying to cythonize module %s, the resulting '", "'file %s could neither be found in directory %s nor '", "'its subdirectories. The distul report should tell '", "'whether the file has been stored somewhere else,'", "'is named somehow else, or could not be build at '", "'all.'", "%", "self", ".", "buildpath", ")" ]
Try to find the resulting dll file and to move it into the `cythons` package. Things to be aware of: * The file extension either `pyd` (Window) or `so` (Linux). * The folder containing the dll file is system dependent, but is always a subfolder of the `cythons` package. * Under Linux, the filename might contain system information, e.g. ...cpython-36m-x86_64-linux-gnu.so.
[ "Try", "to", "find", "the", "resulting", "dll", "file", "and", "to", "move", "it", "into", "the", "cythons", "package", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L249-L295
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.constants
def constants(self): """Constants declaration lines.""" lines = Lines() for (name, member) in vars(self.cythonizer).items(): if (name.isupper() and (not inspect.isclass(member)) and (type(member) in TYPE2STR)): ndim = numpy.array(member).ndim ctype = TYPE2STR[type(member)] + NDIM2STR[ndim] lines.add(0, 'cdef public %s %s = %s' % (ctype, name, member)) return lines
python
def constants(self): """Constants declaration lines.""" lines = Lines() for (name, member) in vars(self.cythonizer).items(): if (name.isupper() and (not inspect.isclass(member)) and (type(member) in TYPE2STR)): ndim = numpy.array(member).ndim ctype = TYPE2STR[type(member)] + NDIM2STR[ndim] lines.add(0, 'cdef public %s %s = %s' % (ctype, name, member)) return lines
[ "def", "constants", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "for", "(", "name", ",", "member", ")", "in", "vars", "(", "self", ".", "cythonizer", ")", ".", "items", "(", ")", ":", "if", "(", "name", ".", "isupper", "(", ")", "and", "(", "not", "inspect", ".", "isclass", "(", "member", ")", ")", "and", "(", "type", "(", "member", ")", "in", "TYPE2STR", ")", ")", ":", "ndim", "=", "numpy", ".", "array", "(", "member", ")", ".", "ndim", "ctype", "=", "TYPE2STR", "[", "type", "(", "member", ")", "]", "+", "NDIM2STR", "[", "ndim", "]", "lines", ".", "add", "(", "0", ",", "'cdef public %s %s = %s'", "%", "(", "ctype", ",", "name", ",", "member", ")", ")", "return", "lines" ]
Constants declaration lines.
[ "Constants", "declaration", "lines", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L361-L372
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.parameters
def parameters(self): """Parameter declaration lines.""" lines = Lines() lines.add(0, '@cython.final') lines.add(0, 'cdef class Parameters(object):') for subpars in self.model.parameters: if subpars: lines.add(1, 'cdef public %s %s' % (objecttools.classname(subpars), subpars.name)) for subpars in self.model.parameters: if subpars: print(' - %s' % subpars.name) lines.add(0, '@cython.final') lines.add(0, 'cdef class %s(object):' % objecttools.classname(subpars)) for par in subpars: try: ctype = TYPE2STR[par.TYPE] + NDIM2STR[par.NDIM] except KeyError: ctype = par.TYPE + NDIM2STR[par.NDIM] lines.add(1, 'cdef public %s %s' % (ctype, par.name)) return lines
python
def parameters(self): """Parameter declaration lines.""" lines = Lines() lines.add(0, '@cython.final') lines.add(0, 'cdef class Parameters(object):') for subpars in self.model.parameters: if subpars: lines.add(1, 'cdef public %s %s' % (objecttools.classname(subpars), subpars.name)) for subpars in self.model.parameters: if subpars: print(' - %s' % subpars.name) lines.add(0, '@cython.final') lines.add(0, 'cdef class %s(object):' % objecttools.classname(subpars)) for par in subpars: try: ctype = TYPE2STR[par.TYPE] + NDIM2STR[par.NDIM] except KeyError: ctype = par.TYPE + NDIM2STR[par.NDIM] lines.add(1, 'cdef public %s %s' % (ctype, par.name)) return lines
[ "def", "parameters", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "0", ",", "'@cython.final'", ")", "lines", ".", "add", "(", "0", ",", "'cdef class Parameters(object):'", ")", "for", "subpars", "in", "self", ".", "model", ".", "parameters", ":", "if", "subpars", ":", "lines", ".", "add", "(", "1", ",", "'cdef public %s %s'", "%", "(", "objecttools", ".", "classname", "(", "subpars", ")", ",", "subpars", ".", "name", ")", ")", "for", "subpars", "in", "self", ".", "model", ".", "parameters", ":", "if", "subpars", ":", "print", "(", "' - %s'", "%", "subpars", ".", "name", ")", "lines", ".", "add", "(", "0", ",", "'@cython.final'", ")", "lines", ".", "add", "(", "0", ",", "'cdef class %s(object):'", "%", "objecttools", ".", "classname", "(", "subpars", ")", ")", "for", "par", "in", "subpars", ":", "try", ":", "ctype", "=", "TYPE2STR", "[", "par", ".", "TYPE", "]", "+", "NDIM2STR", "[", "par", ".", "NDIM", "]", "except", "KeyError", ":", "ctype", "=", "par", ".", "TYPE", "+", "NDIM2STR", "[", "par", ".", "NDIM", "]", "lines", ".", "add", "(", "1", ",", "'cdef public %s %s'", "%", "(", "ctype", ",", "par", ".", "name", ")", ")", "return", "lines" ]
Parameter declaration lines.
[ "Parameter", "declaration", "lines", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L375-L396
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.sequences
def sequences(self): """Sequence declaration lines.""" lines = Lines() lines.add(0, '@cython.final') lines.add(0, 'cdef class Sequences(object):') for subseqs in self.model.sequences: lines.add(1, 'cdef public %s %s' % (objecttools.classname(subseqs), subseqs.name)) if getattr(self.model.sequences, 'states', None) is not None: lines.add(1, 'cdef public StateSequences old_states') lines.add(1, 'cdef public StateSequences new_states') for subseqs in self.model.sequences: print(' - %s' % subseqs.name) lines.add(0, '@cython.final') lines.add(0, 'cdef class %s(object):' % objecttools.classname(subseqs)) for seq in subseqs: ctype = 'double' + NDIM2STR[seq.NDIM] if isinstance(subseqs, sequencetools.LinkSequences): if seq.NDIM == 0: lines.add(1, 'cdef double *%s' % seq.name) elif seq.NDIM == 1: lines.add(1, 'cdef double **%s' % seq.name) lines.add(1, 'cdef public int len_%s' % seq.name) else: lines.add(1, 'cdef public %s %s' % (ctype, seq.name)) lines.add(1, 'cdef public int _%s_ndim' % seq.name) lines.add(1, 'cdef public int _%s_length' % seq.name) for idx in range(seq.NDIM): lines.add(1, 'cdef public int _%s_length_%d' % (seq.name, idx)) if seq.NUMERIC: ctype_numeric = 'double' + NDIM2STR[seq.NDIM+1] lines.add(1, 'cdef public %s _%s_points' % (ctype_numeric, seq.name)) lines.add(1, 'cdef public %s _%s_results' % (ctype_numeric, seq.name)) if isinstance(subseqs, sequencetools.FluxSequences): lines.add(1, 'cdef public %s _%s_integrals' % (ctype_numeric, seq.name)) lines.add(1, 'cdef public %s _%s_sum' % (ctype, seq.name)) if isinstance(subseqs, sequencetools.IOSequences): lines.extend(self.iosequence(seq)) if isinstance(subseqs, sequencetools.InputSequences): lines.extend(self.load_data(subseqs)) if isinstance(subseqs, sequencetools.IOSequences): lines.extend(self.open_files(subseqs)) lines.extend(self.close_files(subseqs)) if not isinstance(subseqs, sequencetools.InputSequence): lines.extend(self.save_data(subseqs)) if isinstance(subseqs, sequencetools.LinkSequences): lines.extend(self.set_pointer(subseqs)) return lines
python
def sequences(self): """Sequence declaration lines.""" lines = Lines() lines.add(0, '@cython.final') lines.add(0, 'cdef class Sequences(object):') for subseqs in self.model.sequences: lines.add(1, 'cdef public %s %s' % (objecttools.classname(subseqs), subseqs.name)) if getattr(self.model.sequences, 'states', None) is not None: lines.add(1, 'cdef public StateSequences old_states') lines.add(1, 'cdef public StateSequences new_states') for subseqs in self.model.sequences: print(' - %s' % subseqs.name) lines.add(0, '@cython.final') lines.add(0, 'cdef class %s(object):' % objecttools.classname(subseqs)) for seq in subseqs: ctype = 'double' + NDIM2STR[seq.NDIM] if isinstance(subseqs, sequencetools.LinkSequences): if seq.NDIM == 0: lines.add(1, 'cdef double *%s' % seq.name) elif seq.NDIM == 1: lines.add(1, 'cdef double **%s' % seq.name) lines.add(1, 'cdef public int len_%s' % seq.name) else: lines.add(1, 'cdef public %s %s' % (ctype, seq.name)) lines.add(1, 'cdef public int _%s_ndim' % seq.name) lines.add(1, 'cdef public int _%s_length' % seq.name) for idx in range(seq.NDIM): lines.add(1, 'cdef public int _%s_length_%d' % (seq.name, idx)) if seq.NUMERIC: ctype_numeric = 'double' + NDIM2STR[seq.NDIM+1] lines.add(1, 'cdef public %s _%s_points' % (ctype_numeric, seq.name)) lines.add(1, 'cdef public %s _%s_results' % (ctype_numeric, seq.name)) if isinstance(subseqs, sequencetools.FluxSequences): lines.add(1, 'cdef public %s _%s_integrals' % (ctype_numeric, seq.name)) lines.add(1, 'cdef public %s _%s_sum' % (ctype, seq.name)) if isinstance(subseqs, sequencetools.IOSequences): lines.extend(self.iosequence(seq)) if isinstance(subseqs, sequencetools.InputSequences): lines.extend(self.load_data(subseqs)) if isinstance(subseqs, sequencetools.IOSequences): lines.extend(self.open_files(subseqs)) lines.extend(self.close_files(subseqs)) if not isinstance(subseqs, sequencetools.InputSequence): lines.extend(self.save_data(subseqs)) if isinstance(subseqs, sequencetools.LinkSequences): lines.extend(self.set_pointer(subseqs)) return lines
[ "def", "sequences", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "0", ",", "'@cython.final'", ")", "lines", ".", "add", "(", "0", ",", "'cdef class Sequences(object):'", ")", "for", "subseqs", "in", "self", ".", "model", ".", "sequences", ":", "lines", ".", "add", "(", "1", ",", "'cdef public %s %s'", "%", "(", "objecttools", ".", "classname", "(", "subseqs", ")", ",", "subseqs", ".", "name", ")", ")", "if", "getattr", "(", "self", ".", "model", ".", "sequences", ",", "'states'", ",", "None", ")", "is", "not", "None", ":", "lines", ".", "add", "(", "1", ",", "'cdef public StateSequences old_states'", ")", "lines", ".", "add", "(", "1", ",", "'cdef public StateSequences new_states'", ")", "for", "subseqs", "in", "self", ".", "model", ".", "sequences", ":", "print", "(", "' - %s'", "%", "subseqs", ".", "name", ")", "lines", ".", "add", "(", "0", ",", "'@cython.final'", ")", "lines", ".", "add", "(", "0", ",", "'cdef class %s(object):'", "%", "objecttools", ".", "classname", "(", "subseqs", ")", ")", "for", "seq", "in", "subseqs", ":", "ctype", "=", "'double'", "+", "NDIM2STR", "[", "seq", ".", "NDIM", "]", "if", "isinstance", "(", "subseqs", ",", "sequencetools", ".", "LinkSequences", ")", ":", "if", "seq", ".", "NDIM", "==", "0", ":", "lines", ".", "add", "(", "1", ",", "'cdef double *%s'", "%", "seq", ".", "name", ")", "elif", "seq", ".", "NDIM", "==", "1", ":", "lines", ".", "add", "(", "1", ",", "'cdef double **%s'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "1", ",", "'cdef public int len_%s'", "%", "seq", ".", "name", ")", "else", ":", "lines", ".", "add", "(", "1", ",", "'cdef public %s %s'", "%", "(", "ctype", ",", "seq", ".", "name", ")", ")", "lines", ".", "add", "(", "1", ",", "'cdef public int _%s_ndim'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "1", ",", "'cdef public int _%s_length'", "%", "seq", ".", "name", ")", "for", "idx", "in", "range", "(", "seq", ".", "NDIM", ")", ":", "lines", ".", "add", "(", "1", ",", "'cdef public int _%s_length_%d'", "%", "(", "seq", ".", "name", ",", "idx", ")", ")", "if", "seq", ".", "NUMERIC", ":", "ctype_numeric", "=", "'double'", "+", "NDIM2STR", "[", "seq", ".", "NDIM", "+", "1", "]", "lines", ".", "add", "(", "1", ",", "'cdef public %s _%s_points'", "%", "(", "ctype_numeric", ",", "seq", ".", "name", ")", ")", "lines", ".", "add", "(", "1", ",", "'cdef public %s _%s_results'", "%", "(", "ctype_numeric", ",", "seq", ".", "name", ")", ")", "if", "isinstance", "(", "subseqs", ",", "sequencetools", ".", "FluxSequences", ")", ":", "lines", ".", "add", "(", "1", ",", "'cdef public %s _%s_integrals'", "%", "(", "ctype_numeric", ",", "seq", ".", "name", ")", ")", "lines", ".", "add", "(", "1", ",", "'cdef public %s _%s_sum'", "%", "(", "ctype", ",", "seq", ".", "name", ")", ")", "if", "isinstance", "(", "subseqs", ",", "sequencetools", ".", "IOSequences", ")", ":", "lines", ".", "extend", "(", "self", ".", "iosequence", "(", "seq", ")", ")", "if", "isinstance", "(", "subseqs", ",", "sequencetools", ".", "InputSequences", ")", ":", "lines", ".", "extend", "(", "self", ".", "load_data", "(", "subseqs", ")", ")", "if", "isinstance", "(", "subseqs", ",", "sequencetools", ".", "IOSequences", ")", ":", "lines", ".", "extend", "(", "self", ".", "open_files", "(", "subseqs", ")", ")", "lines", ".", "extend", "(", "self", ".", "close_files", "(", "subseqs", ")", ")", "if", "not", "isinstance", "(", "subseqs", ",", "sequencetools", ".", "InputSequence", ")", ":", "lines", ".", "extend", "(", "self", ".", "save_data", "(", "subseqs", ")", ")", "if", "isinstance", "(", "subseqs", ",", "sequencetools", ".", "LinkSequences", ")", ":", "lines", ".", "extend", "(", "self", ".", "set_pointer", "(", "subseqs", ")", ")", "return", "lines" ]
Sequence declaration lines.
[ "Sequence", "declaration", "lines", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L399-L452
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.iosequence
def iosequence(seq): """Special declaration lines for the given |IOSequence| object. """ lines = Lines() lines.add(1, 'cdef public bint _%s_diskflag' % seq.name) lines.add(1, 'cdef public str _%s_path' % seq.name) lines.add(1, 'cdef FILE *_%s_file' % seq.name) lines.add(1, 'cdef public bint _%s_ramflag' % seq.name) ctype = 'double' + NDIM2STR[seq.NDIM+1] lines.add(1, 'cdef public %s _%s_array' % (ctype, seq.name)) return lines
python
def iosequence(seq): """Special declaration lines for the given |IOSequence| object. """ lines = Lines() lines.add(1, 'cdef public bint _%s_diskflag' % seq.name) lines.add(1, 'cdef public str _%s_path' % seq.name) lines.add(1, 'cdef FILE *_%s_file' % seq.name) lines.add(1, 'cdef public bint _%s_ramflag' % seq.name) ctype = 'double' + NDIM2STR[seq.NDIM+1] lines.add(1, 'cdef public %s _%s_array' % (ctype, seq.name)) return lines
[ "def", "iosequence", "(", "seq", ")", ":", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cdef public bint _%s_diskflag'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "1", ",", "'cdef public str _%s_path'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "1", ",", "'cdef FILE *_%s_file'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "1", ",", "'cdef public bint _%s_ramflag'", "%", "seq", ".", "name", ")", "ctype", "=", "'double'", "+", "NDIM2STR", "[", "seq", ".", "NDIM", "+", "1", "]", "lines", ".", "add", "(", "1", ",", "'cdef public %s _%s_array'", "%", "(", "ctype", ",", "seq", ".", "name", ")", ")", "return", "lines" ]
Special declaration lines for the given |IOSequence| object.
[ "Special", "declaration", "lines", "for", "the", "given", "|IOSequence|", "object", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L455-L465
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.open_files
def open_files(subseqs): """Open file statements.""" print(' . open_files') lines = Lines() lines.add(1, 'cpdef open_files(self, int idx):') for seq in subseqs: lines.add(2, 'if self._%s_diskflag:' % seq.name) lines.add(3, 'self._%s_file = fopen(str(self._%s_path).encode(), ' '"rb+")' % (2*(seq.name,))) if seq.NDIM == 0: lines.add(3, 'fseek(self._%s_file, idx*8, SEEK_SET)' % seq.name) else: lines.add(3, 'fseek(self._%s_file, idx*self._%s_length*8, ' 'SEEK_SET)' % (2*(seq.name,))) return lines
python
def open_files(subseqs): """Open file statements.""" print(' . open_files') lines = Lines() lines.add(1, 'cpdef open_files(self, int idx):') for seq in subseqs: lines.add(2, 'if self._%s_diskflag:' % seq.name) lines.add(3, 'self._%s_file = fopen(str(self._%s_path).encode(), ' '"rb+")' % (2*(seq.name,))) if seq.NDIM == 0: lines.add(3, 'fseek(self._%s_file, idx*8, SEEK_SET)' % seq.name) else: lines.add(3, 'fseek(self._%s_file, idx*self._%s_length*8, ' 'SEEK_SET)' % (2*(seq.name,))) return lines
[ "def", "open_files", "(", "subseqs", ")", ":", "print", "(", "' . open_files'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef open_files(self, int idx):'", ")", "for", "seq", "in", "subseqs", ":", "lines", ".", "add", "(", "2", ",", "'if self._%s_diskflag:'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "3", ",", "'self._%s_file = fopen(str(self._%s_path).encode(), '", "'\"rb+\")'", "%", "(", "2", "*", "(", "seq", ".", "name", ",", ")", ")", ")", "if", "seq", ".", "NDIM", "==", "0", ":", "lines", ".", "add", "(", "3", ",", "'fseek(self._%s_file, idx*8, SEEK_SET)'", "%", "seq", ".", "name", ")", "else", ":", "lines", ".", "add", "(", "3", ",", "'fseek(self._%s_file, idx*self._%s_length*8, '", "'SEEK_SET)'", "%", "(", "2", "*", "(", "seq", ".", "name", ",", ")", ")", ")", "return", "lines" ]
Open file statements.
[ "Open", "file", "statements", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L468-L483
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.close_files
def close_files(subseqs): """Close file statements.""" print(' . close_files') lines = Lines() lines.add(1, 'cpdef inline close_files(self):') for seq in subseqs: lines.add(2, 'if self._%s_diskflag:' % seq.name) lines.add(3, 'fclose(self._%s_file)' % seq.name) return lines
python
def close_files(subseqs): """Close file statements.""" print(' . close_files') lines = Lines() lines.add(1, 'cpdef inline close_files(self):') for seq in subseqs: lines.add(2, 'if self._%s_diskflag:' % seq.name) lines.add(3, 'fclose(self._%s_file)' % seq.name) return lines
[ "def", "close_files", "(", "subseqs", ")", ":", "print", "(", "' . close_files'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline close_files(self):'", ")", "for", "seq", "in", "subseqs", ":", "lines", ".", "add", "(", "2", ",", "'if self._%s_diskflag:'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "3", ",", "'fclose(self._%s_file)'", "%", "seq", ".", "name", ")", "return", "lines" ]
Close file statements.
[ "Close", "file", "statements", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L486-L494
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.load_data
def load_data(subseqs): """Load data statements.""" print(' . load_data') lines = Lines() lines.add(1, 'cpdef inline void load_data(self, int idx) %s:' % _nogil) lines.add(2, 'cdef int jdx0, jdx1, jdx2, jdx3, jdx4, jdx5') for seq in subseqs: lines.add(2, 'if self._%s_diskflag:' % seq.name) if seq.NDIM == 0: lines.add(3, 'fread(&self.%s, 8, 1, self._%s_file)' % (2*(seq.name,))) else: lines.add(3, 'fread(&self.%s[0], 8, self._%s_length, ' 'self._%s_file)' % (3*(seq.name,))) lines.add(2, 'elif self._%s_ramflag:' % seq.name) if seq.NDIM == 0: lines.add(3, 'self.%s = self._%s_array[idx]' % (2*(seq.name,))) else: indexing = '' for idx in range(seq.NDIM): lines.add(3+idx, 'for jdx%d in range(self._%s_length_%d):' % (idx, seq.name, idx)) indexing += 'jdx%d,' % idx indexing = indexing[:-1] lines.add(3+seq.NDIM, 'self.%s[%s] = self._%s_array[idx,%s]' % (2*(seq.name, indexing))) return lines
python
def load_data(subseqs): """Load data statements.""" print(' . load_data') lines = Lines() lines.add(1, 'cpdef inline void load_data(self, int idx) %s:' % _nogil) lines.add(2, 'cdef int jdx0, jdx1, jdx2, jdx3, jdx4, jdx5') for seq in subseqs: lines.add(2, 'if self._%s_diskflag:' % seq.name) if seq.NDIM == 0: lines.add(3, 'fread(&self.%s, 8, 1, self._%s_file)' % (2*(seq.name,))) else: lines.add(3, 'fread(&self.%s[0], 8, self._%s_length, ' 'self._%s_file)' % (3*(seq.name,))) lines.add(2, 'elif self._%s_ramflag:' % seq.name) if seq.NDIM == 0: lines.add(3, 'self.%s = self._%s_array[idx]' % (2*(seq.name,))) else: indexing = '' for idx in range(seq.NDIM): lines.add(3+idx, 'for jdx%d in range(self._%s_length_%d):' % (idx, seq.name, idx)) indexing += 'jdx%d,' % idx indexing = indexing[:-1] lines.add(3+seq.NDIM, 'self.%s[%s] = self._%s_array[idx,%s]' % (2*(seq.name, indexing))) return lines
[ "def", "load_data", "(", "subseqs", ")", ":", "print", "(", "' . load_data'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline void load_data(self, int idx) %s:'", "%", "_nogil", ")", "lines", ".", "add", "(", "2", ",", "'cdef int jdx0, jdx1, jdx2, jdx3, jdx4, jdx5'", ")", "for", "seq", "in", "subseqs", ":", "lines", ".", "add", "(", "2", ",", "'if self._%s_diskflag:'", "%", "seq", ".", "name", ")", "if", "seq", ".", "NDIM", "==", "0", ":", "lines", ".", "add", "(", "3", ",", "'fread(&self.%s, 8, 1, self._%s_file)'", "%", "(", "2", "*", "(", "seq", ".", "name", ",", ")", ")", ")", "else", ":", "lines", ".", "add", "(", "3", ",", "'fread(&self.%s[0], 8, self._%s_length, '", "'self._%s_file)'", "%", "(", "3", "*", "(", "seq", ".", "name", ",", ")", ")", ")", "lines", ".", "add", "(", "2", ",", "'elif self._%s_ramflag:'", "%", "seq", ".", "name", ")", "if", "seq", ".", "NDIM", "==", "0", ":", "lines", ".", "add", "(", "3", ",", "'self.%s = self._%s_array[idx]'", "%", "(", "2", "*", "(", "seq", ".", "name", ",", ")", ")", ")", "else", ":", "indexing", "=", "''", "for", "idx", "in", "range", "(", "seq", ".", "NDIM", ")", ":", "lines", ".", "add", "(", "3", "+", "idx", ",", "'for jdx%d in range(self._%s_length_%d):'", "%", "(", "idx", ",", "seq", ".", "name", ",", "idx", ")", ")", "indexing", "+=", "'jdx%d,'", "%", "idx", "indexing", "=", "indexing", "[", ":", "-", "1", "]", "lines", ".", "add", "(", "3", "+", "seq", ".", "NDIM", ",", "'self.%s[%s] = self._%s_array[idx,%s]'", "%", "(", "2", "*", "(", "seq", ".", "name", ",", "indexing", ")", ")", ")", "return", "lines" ]
Load data statements.
[ "Load", "data", "statements", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L497-L523
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.set_pointer
def set_pointer(self, subseqs): """Set_pointer functions for link sequences.""" lines = Lines() for seq in subseqs: if seq.NDIM == 0: lines.extend(self.set_pointer0d(subseqs)) break for seq in subseqs: if seq.NDIM == 1: lines.extend(self.alloc(subseqs)) lines.extend(self.dealloc(subseqs)) lines.extend(self.set_pointer1d(subseqs)) break return lines
python
def set_pointer(self, subseqs): """Set_pointer functions for link sequences.""" lines = Lines() for seq in subseqs: if seq.NDIM == 0: lines.extend(self.set_pointer0d(subseqs)) break for seq in subseqs: if seq.NDIM == 1: lines.extend(self.alloc(subseqs)) lines.extend(self.dealloc(subseqs)) lines.extend(self.set_pointer1d(subseqs)) break return lines
[ "def", "set_pointer", "(", "self", ",", "subseqs", ")", ":", "lines", "=", "Lines", "(", ")", "for", "seq", "in", "subseqs", ":", "if", "seq", ".", "NDIM", "==", "0", ":", "lines", ".", "extend", "(", "self", ".", "set_pointer0d", "(", "subseqs", ")", ")", "break", "for", "seq", "in", "subseqs", ":", "if", "seq", ".", "NDIM", "==", "1", ":", "lines", ".", "extend", "(", "self", ".", "alloc", "(", "subseqs", ")", ")", "lines", ".", "extend", "(", "self", ".", "dealloc", "(", "subseqs", ")", ")", "lines", ".", "extend", "(", "self", ".", "set_pointer1d", "(", "subseqs", ")", ")", "break", "return", "lines" ]
Set_pointer functions for link sequences.
[ "Set_pointer", "functions", "for", "link", "sequences", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L554-L567
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.set_pointer0d
def set_pointer0d(subseqs): """Set_pointer function for 0-dimensional link sequences.""" print(' . set_pointer0d') lines = Lines() lines.add(1, 'cpdef inline set_pointer0d' '(self, str name, pointerutils.PDouble value):') for seq in subseqs: lines.add(2, 'if name == "%s":' % seq.name) lines.add(3, 'self.%s = value.p_value' % seq.name) return lines
python
def set_pointer0d(subseqs): """Set_pointer function for 0-dimensional link sequences.""" print(' . set_pointer0d') lines = Lines() lines.add(1, 'cpdef inline set_pointer0d' '(self, str name, pointerutils.PDouble value):') for seq in subseqs: lines.add(2, 'if name == "%s":' % seq.name) lines.add(3, 'self.%s = value.p_value' % seq.name) return lines
[ "def", "set_pointer0d", "(", "subseqs", ")", ":", "print", "(", "' . set_pointer0d'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline set_pointer0d'", "'(self, str name, pointerutils.PDouble value):'", ")", "for", "seq", "in", "subseqs", ":", "lines", ".", "add", "(", "2", ",", "'if name == \"%s\":'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "3", ",", "'self.%s = value.p_value'", "%", "seq", ".", "name", ")", "return", "lines" ]
Set_pointer function for 0-dimensional link sequences.
[ "Set_pointer", "function", "for", "0", "-", "dimensional", "link", "sequences", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L570-L579
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.alloc
def alloc(subseqs): """Allocate memory for 1-dimensional link sequences.""" print(' . setlength') lines = Lines() lines.add(1, 'cpdef inline alloc(self, name, int length):') for seq in subseqs: lines.add(2, 'if name == "%s":' % seq.name) lines.add(3, 'self._%s_length_0 = length' % seq.name) lines.add(3, 'self.%s = <double**> ' 'PyMem_Malloc(length * sizeof(double*))' % seq.name) return lines
python
def alloc(subseqs): """Allocate memory for 1-dimensional link sequences.""" print(' . setlength') lines = Lines() lines.add(1, 'cpdef inline alloc(self, name, int length):') for seq in subseqs: lines.add(2, 'if name == "%s":' % seq.name) lines.add(3, 'self._%s_length_0 = length' % seq.name) lines.add(3, 'self.%s = <double**> ' 'PyMem_Malloc(length * sizeof(double*))' % seq.name) return lines
[ "def", "alloc", "(", "subseqs", ")", ":", "print", "(", "' . setlength'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline alloc(self, name, int length):'", ")", "for", "seq", "in", "subseqs", ":", "lines", ".", "add", "(", "2", ",", "'if name == \"%s\":'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "3", ",", "'self._%s_length_0 = length'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "3", ",", "'self.%s = <double**> '", "'PyMem_Malloc(length * sizeof(double*))'", "%", "seq", ".", "name", ")", "return", "lines" ]
Allocate memory for 1-dimensional link sequences.
[ "Allocate", "memory", "for", "1", "-", "dimensional", "link", "sequences", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L582-L592
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.dealloc
def dealloc(subseqs): """Deallocate memory for 1-dimensional link sequences.""" print(' . dealloc') lines = Lines() lines.add(1, 'cpdef inline dealloc(self):') for seq in subseqs: lines.add(2, 'PyMem_Free(self.%s)' % seq.name) return lines
python
def dealloc(subseqs): """Deallocate memory for 1-dimensional link sequences.""" print(' . dealloc') lines = Lines() lines.add(1, 'cpdef inline dealloc(self):') for seq in subseqs: lines.add(2, 'PyMem_Free(self.%s)' % seq.name) return lines
[ "def", "dealloc", "(", "subseqs", ")", ":", "print", "(", "' . dealloc'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline dealloc(self):'", ")", "for", "seq", "in", "subseqs", ":", "lines", ".", "add", "(", "2", ",", "'PyMem_Free(self.%s)'", "%", "seq", ".", "name", ")", "return", "lines" ]
Deallocate memory for 1-dimensional link sequences.
[ "Deallocate", "memory", "for", "1", "-", "dimensional", "link", "sequences", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L595-L602
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.set_pointer1d
def set_pointer1d(subseqs): """Set_pointer function for 1-dimensional link sequences.""" print(' . set_pointer1d') lines = Lines() lines.add(1, 'cpdef inline set_pointer1d' '(self, str name, pointerutils.PDouble value, int idx):') for seq in subseqs: lines.add(2, 'if name == "%s":' % seq.name) lines.add(3, 'self.%s[idx] = value.p_value' % seq.name) return lines
python
def set_pointer1d(subseqs): """Set_pointer function for 1-dimensional link sequences.""" print(' . set_pointer1d') lines = Lines() lines.add(1, 'cpdef inline set_pointer1d' '(self, str name, pointerutils.PDouble value, int idx):') for seq in subseqs: lines.add(2, 'if name == "%s":' % seq.name) lines.add(3, 'self.%s[idx] = value.p_value' % seq.name) return lines
[ "def", "set_pointer1d", "(", "subseqs", ")", ":", "print", "(", "' . set_pointer1d'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline set_pointer1d'", "'(self, str name, pointerutils.PDouble value, int idx):'", ")", "for", "seq", "in", "subseqs", ":", "lines", ".", "add", "(", "2", ",", "'if name == \"%s\":'", "%", "seq", ".", "name", ")", "lines", ".", "add", "(", "3", ",", "'self.%s[idx] = value.p_value'", "%", "seq", ".", "name", ")", "return", "lines" ]
Set_pointer function for 1-dimensional link sequences.
[ "Set_pointer", "function", "for", "1", "-", "dimensional", "link", "sequences", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L605-L614
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.numericalparameters
def numericalparameters(self): """Numeric parameter declaration lines.""" lines = Lines() if self.model.NUMERICAL: lines.add(0, '@cython.final') lines.add(0, 'cdef class NumConsts(object):') for name in ('nmb_methods', 'nmb_stages'): lines.add(1, 'cdef public %s %s' % (TYPE2STR[int], name)) for name in ('dt_increase', 'dt_decrease'): lines.add(1, 'cdef public %s %s' % (TYPE2STR[float], name)) lines.add(1, 'cdef public configutils.Config pub') lines.add(1, 'cdef public double[:, :, :] a_coefs') lines.add(0, 'cdef class NumVars(object):') for name in ('nmb_calls', 'idx_method', 'idx_stage'): lines.add(1, 'cdef public %s %s' % (TYPE2STR[int], name)) for name in ('t0', 't1', 'dt', 'dt_est', 'error', 'last_error', 'extrapolated_error'): lines.add(1, 'cdef public %s %s' % (TYPE2STR[float], name)) lines.add(1, 'cdef public %s f0_ready' % TYPE2STR[bool]) return lines
python
def numericalparameters(self): """Numeric parameter declaration lines.""" lines = Lines() if self.model.NUMERICAL: lines.add(0, '@cython.final') lines.add(0, 'cdef class NumConsts(object):') for name in ('nmb_methods', 'nmb_stages'): lines.add(1, 'cdef public %s %s' % (TYPE2STR[int], name)) for name in ('dt_increase', 'dt_decrease'): lines.add(1, 'cdef public %s %s' % (TYPE2STR[float], name)) lines.add(1, 'cdef public configutils.Config pub') lines.add(1, 'cdef public double[:, :, :] a_coefs') lines.add(0, 'cdef class NumVars(object):') for name in ('nmb_calls', 'idx_method', 'idx_stage'): lines.add(1, 'cdef public %s %s' % (TYPE2STR[int], name)) for name in ('t0', 't1', 'dt', 'dt_est', 'error', 'last_error', 'extrapolated_error'): lines.add(1, 'cdef public %s %s' % (TYPE2STR[float], name)) lines.add(1, 'cdef public %s f0_ready' % TYPE2STR[bool]) return lines
[ "def", "numericalparameters", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "if", "self", ".", "model", ".", "NUMERICAL", ":", "lines", ".", "add", "(", "0", ",", "'@cython.final'", ")", "lines", ".", "add", "(", "0", ",", "'cdef class NumConsts(object):'", ")", "for", "name", "in", "(", "'nmb_methods'", ",", "'nmb_stages'", ")", ":", "lines", ".", "add", "(", "1", ",", "'cdef public %s %s'", "%", "(", "TYPE2STR", "[", "int", "]", ",", "name", ")", ")", "for", "name", "in", "(", "'dt_increase'", ",", "'dt_decrease'", ")", ":", "lines", ".", "add", "(", "1", ",", "'cdef public %s %s'", "%", "(", "TYPE2STR", "[", "float", "]", ",", "name", ")", ")", "lines", ".", "add", "(", "1", ",", "'cdef public configutils.Config pub'", ")", "lines", ".", "add", "(", "1", ",", "'cdef public double[:, :, :] a_coefs'", ")", "lines", ".", "add", "(", "0", ",", "'cdef class NumVars(object):'", ")", "for", "name", "in", "(", "'nmb_calls'", ",", "'idx_method'", ",", "'idx_stage'", ")", ":", "lines", ".", "add", "(", "1", ",", "'cdef public %s %s'", "%", "(", "TYPE2STR", "[", "int", "]", ",", "name", ")", ")", "for", "name", "in", "(", "'t0'", ",", "'t1'", ",", "'dt'", ",", "'dt_est'", ",", "'error'", ",", "'last_error'", ",", "'extrapolated_error'", ")", ":", "lines", ".", "add", "(", "1", ",", "'cdef public %s %s'", "%", "(", "TYPE2STR", "[", "float", "]", ",", "name", ")", ")", "lines", ".", "add", "(", "1", ",", "'cdef public %s f0_ready'", "%", "TYPE2STR", "[", "bool", "]", ")", "return", "lines" ]
Numeric parameter declaration lines.
[ "Numeric", "parameter", "declaration", "lines", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L617-L636
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.modeldeclarations
def modeldeclarations(self): """Attribute declarations of the model class.""" lines = Lines() lines.add(0, '@cython.final') lines.add(0, 'cdef class Model(object):') lines.add(1, 'cdef public int idx_sim') lines.add(1, 'cdef public Parameters parameters') lines.add(1, 'cdef public Sequences sequences') if hasattr(self.model, 'numconsts'): lines.add(1, 'cdef public NumConsts numconsts') if hasattr(self.model, 'numvars'): lines.add(1, 'cdef public NumVars numvars') return lines
python
def modeldeclarations(self): """Attribute declarations of the model class.""" lines = Lines() lines.add(0, '@cython.final') lines.add(0, 'cdef class Model(object):') lines.add(1, 'cdef public int idx_sim') lines.add(1, 'cdef public Parameters parameters') lines.add(1, 'cdef public Sequences sequences') if hasattr(self.model, 'numconsts'): lines.add(1, 'cdef public NumConsts numconsts') if hasattr(self.model, 'numvars'): lines.add(1, 'cdef public NumVars numvars') return lines
[ "def", "modeldeclarations", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "0", ",", "'@cython.final'", ")", "lines", ".", "add", "(", "0", ",", "'cdef class Model(object):'", ")", "lines", ".", "add", "(", "1", ",", "'cdef public int idx_sim'", ")", "lines", ".", "add", "(", "1", ",", "'cdef public Parameters parameters'", ")", "lines", ".", "add", "(", "1", ",", "'cdef public Sequences sequences'", ")", "if", "hasattr", "(", "self", ".", "model", ",", "'numconsts'", ")", ":", "lines", ".", "add", "(", "1", ",", "'cdef public NumConsts numconsts'", ")", "if", "hasattr", "(", "self", ".", "model", ",", "'numvars'", ")", ":", "lines", ".", "add", "(", "1", ",", "'cdef public NumVars numvars'", ")", "return", "lines" ]
Attribute declarations of the model class.
[ "Attribute", "declarations", "of", "the", "model", "class", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L639-L651
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.modelstandardfunctions
def modelstandardfunctions(self): """Standard functions of the model class.""" lines = Lines() lines.extend(self.doit) lines.extend(self.iofunctions) lines.extend(self.new2old) lines.extend(self.run) lines.extend(self.update_inlets) lines.extend(self.update_outlets) lines.extend(self.update_receivers) lines.extend(self.update_senders) return lines
python
def modelstandardfunctions(self): """Standard functions of the model class.""" lines = Lines() lines.extend(self.doit) lines.extend(self.iofunctions) lines.extend(self.new2old) lines.extend(self.run) lines.extend(self.update_inlets) lines.extend(self.update_outlets) lines.extend(self.update_receivers) lines.extend(self.update_senders) return lines
[ "def", "modelstandardfunctions", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "lines", ".", "extend", "(", "self", ".", "doit", ")", "lines", ".", "extend", "(", "self", ".", "iofunctions", ")", "lines", ".", "extend", "(", "self", ".", "new2old", ")", "lines", ".", "extend", "(", "self", ".", "run", ")", "lines", ".", "extend", "(", "self", ".", "update_inlets", ")", "lines", ".", "extend", "(", "self", ".", "update_outlets", ")", "lines", ".", "extend", "(", "self", ".", "update_receivers", ")", "lines", ".", "extend", "(", "self", ".", "update_senders", ")", "return", "lines" ]
Standard functions of the model class.
[ "Standard", "functions", "of", "the", "model", "class", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L654-L665
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.modelnumericfunctions
def modelnumericfunctions(self): """Numerical functions of the model class.""" lines = Lines() lines.extend(self.solve) lines.extend(self.calculate_single_terms) lines.extend(self.calculate_full_terms) lines.extend(self.get_point_states) lines.extend(self.set_point_states) lines.extend(self.set_result_states) lines.extend(self.get_sum_fluxes) lines.extend(self.set_point_fluxes) lines.extend(self.set_result_fluxes) lines.extend(self.integrate_fluxes) lines.extend(self.reset_sum_fluxes) lines.extend(self.addup_fluxes) lines.extend(self.calculate_error) lines.extend(self.extrapolate_error) return lines
python
def modelnumericfunctions(self): """Numerical functions of the model class.""" lines = Lines() lines.extend(self.solve) lines.extend(self.calculate_single_terms) lines.extend(self.calculate_full_terms) lines.extend(self.get_point_states) lines.extend(self.set_point_states) lines.extend(self.set_result_states) lines.extend(self.get_sum_fluxes) lines.extend(self.set_point_fluxes) lines.extend(self.set_result_fluxes) lines.extend(self.integrate_fluxes) lines.extend(self.reset_sum_fluxes) lines.extend(self.addup_fluxes) lines.extend(self.calculate_error) lines.extend(self.extrapolate_error) return lines
[ "def", "modelnumericfunctions", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "lines", ".", "extend", "(", "self", ".", "solve", ")", "lines", ".", "extend", "(", "self", ".", "calculate_single_terms", ")", "lines", ".", "extend", "(", "self", ".", "calculate_full_terms", ")", "lines", ".", "extend", "(", "self", ".", "get_point_states", ")", "lines", ".", "extend", "(", "self", ".", "set_point_states", ")", "lines", ".", "extend", "(", "self", ".", "set_result_states", ")", "lines", ".", "extend", "(", "self", ".", "get_sum_fluxes", ")", "lines", ".", "extend", "(", "self", ".", "set_point_fluxes", ")", "lines", ".", "extend", "(", "self", ".", "set_result_fluxes", ")", "lines", ".", "extend", "(", "self", ".", "integrate_fluxes", ")", "lines", ".", "extend", "(", "self", ".", "reset_sum_fluxes", ")", "lines", ".", "extend", "(", "self", ".", "addup_fluxes", ")", "lines", ".", "extend", "(", "self", ".", "calculate_error", ")", "lines", ".", "extend", "(", "self", ".", "extrapolate_error", ")", "return", "lines" ]
Numerical functions of the model class.
[ "Numerical", "functions", "of", "the", "model", "class", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L668-L685
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.doit
def doit(self): """Do (most of) it function of the model class.""" print(' . doit') lines = Lines() lines.add(1, 'cpdef inline void doit(self, int idx) %s:' % _nogil) lines.add(2, 'self.idx_sim = idx') if getattr(self.model.sequences, 'inputs', None) is not None: lines.add(2, 'self.load_data()') if self.model.INLET_METHODS: lines.add(2, 'self.update_inlets()') if hasattr(self.model, 'solve'): lines.add(2, 'self.solve()') else: lines.add(2, 'self.run()') if getattr(self.model.sequences, 'states', None) is not None: lines.add(2, 'self.new2old()') if self.model.OUTLET_METHODS: lines.add(2, 'self.update_outlets()') return lines
python
def doit(self): """Do (most of) it function of the model class.""" print(' . doit') lines = Lines() lines.add(1, 'cpdef inline void doit(self, int idx) %s:' % _nogil) lines.add(2, 'self.idx_sim = idx') if getattr(self.model.sequences, 'inputs', None) is not None: lines.add(2, 'self.load_data()') if self.model.INLET_METHODS: lines.add(2, 'self.update_inlets()') if hasattr(self.model, 'solve'): lines.add(2, 'self.solve()') else: lines.add(2, 'self.run()') if getattr(self.model.sequences, 'states', None) is not None: lines.add(2, 'self.new2old()') if self.model.OUTLET_METHODS: lines.add(2, 'self.update_outlets()') return lines
[ "def", "doit", "(", "self", ")", ":", "print", "(", "' . doit'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline void doit(self, int idx) %s:'", "%", "_nogil", ")", "lines", ".", "add", "(", "2", ",", "'self.idx_sim = idx'", ")", "if", "getattr", "(", "self", ".", "model", ".", "sequences", ",", "'inputs'", ",", "None", ")", "is", "not", "None", ":", "lines", ".", "add", "(", "2", ",", "'self.load_data()'", ")", "if", "self", ".", "model", ".", "INLET_METHODS", ":", "lines", ".", "add", "(", "2", ",", "'self.update_inlets()'", ")", "if", "hasattr", "(", "self", ".", "model", ",", "'solve'", ")", ":", "lines", ".", "add", "(", "2", ",", "'self.solve()'", ")", "else", ":", "lines", ".", "add", "(", "2", ",", "'self.run()'", ")", "if", "getattr", "(", "self", ".", "model", ".", "sequences", ",", "'states'", ",", "None", ")", "is", "not", "None", ":", "lines", ".", "add", "(", "2", ",", "'self.new2old()'", ")", "if", "self", ".", "model", ".", "OUTLET_METHODS", ":", "lines", ".", "add", "(", "2", ",", "'self.update_outlets()'", ")", "return", "lines" ]
Do (most of) it function of the model class.
[ "Do", "(", "most", "of", ")", "it", "function", "of", "the", "model", "class", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L688-L706
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.iofunctions
def iofunctions(self): """Input/output functions of the model class.""" lines = Lines() for func in ('open_files', 'close_files', 'load_data', 'save_data'): if ((func == 'load_data') and (getattr(self.model.sequences, 'inputs', None) is None)): continue if ((func == 'save_data') and ((getattr(self.model.sequences, 'fluxes', None) is None) and (getattr(self.model.sequences, 'states', None) is None))): continue print(' . %s' % func) nogil = func in ('load_data', 'save_data') idx_as_arg = func == 'save_data' lines.add(1, method_header( func, nogil=nogil, idx_as_arg=idx_as_arg)) for subseqs in self.model.sequences: if func == 'load_data': applyfuncs = ('inputs',) elif func == 'save_data': applyfuncs = ('fluxes', 'states') else: applyfuncs = ('inputs', 'fluxes', 'states') if subseqs.name in applyfuncs: if func == 'close_files': lines.add(2, 'self.sequences.%s.%s()' % (subseqs.name, func)) else: lines.add(2, 'self.sequences.%s.%s(self.idx_sim)' % (subseqs.name, func)) return lines
python
def iofunctions(self): """Input/output functions of the model class.""" lines = Lines() for func in ('open_files', 'close_files', 'load_data', 'save_data'): if ((func == 'load_data') and (getattr(self.model.sequences, 'inputs', None) is None)): continue if ((func == 'save_data') and ((getattr(self.model.sequences, 'fluxes', None) is None) and (getattr(self.model.sequences, 'states', None) is None))): continue print(' . %s' % func) nogil = func in ('load_data', 'save_data') idx_as_arg = func == 'save_data' lines.add(1, method_header( func, nogil=nogil, idx_as_arg=idx_as_arg)) for subseqs in self.model.sequences: if func == 'load_data': applyfuncs = ('inputs',) elif func == 'save_data': applyfuncs = ('fluxes', 'states') else: applyfuncs = ('inputs', 'fluxes', 'states') if subseqs.name in applyfuncs: if func == 'close_files': lines.add(2, 'self.sequences.%s.%s()' % (subseqs.name, func)) else: lines.add(2, 'self.sequences.%s.%s(self.idx_sim)' % (subseqs.name, func)) return lines
[ "def", "iofunctions", "(", "self", ")", ":", "lines", "=", "Lines", "(", ")", "for", "func", "in", "(", "'open_files'", ",", "'close_files'", ",", "'load_data'", ",", "'save_data'", ")", ":", "if", "(", "(", "func", "==", "'load_data'", ")", "and", "(", "getattr", "(", "self", ".", "model", ".", "sequences", ",", "'inputs'", ",", "None", ")", "is", "None", ")", ")", ":", "continue", "if", "(", "(", "func", "==", "'save_data'", ")", "and", "(", "(", "getattr", "(", "self", ".", "model", ".", "sequences", ",", "'fluxes'", ",", "None", ")", "is", "None", ")", "and", "(", "getattr", "(", "self", ".", "model", ".", "sequences", ",", "'states'", ",", "None", ")", "is", "None", ")", ")", ")", ":", "continue", "print", "(", "' . %s'", "%", "func", ")", "nogil", "=", "func", "in", "(", "'load_data'", ",", "'save_data'", ")", "idx_as_arg", "=", "func", "==", "'save_data'", "lines", ".", "add", "(", "1", ",", "method_header", "(", "func", ",", "nogil", "=", "nogil", ",", "idx_as_arg", "=", "idx_as_arg", ")", ")", "for", "subseqs", "in", "self", ".", "model", ".", "sequences", ":", "if", "func", "==", "'load_data'", ":", "applyfuncs", "=", "(", "'inputs'", ",", ")", "elif", "func", "==", "'save_data'", ":", "applyfuncs", "=", "(", "'fluxes'", ",", "'states'", ")", "else", ":", "applyfuncs", "=", "(", "'inputs'", ",", "'fluxes'", ",", "'states'", ")", "if", "subseqs", ".", "name", "in", "applyfuncs", ":", "if", "func", "==", "'close_files'", ":", "lines", ".", "add", "(", "2", ",", "'self.sequences.%s.%s()'", "%", "(", "subseqs", ".", "name", ",", "func", ")", ")", "else", ":", "lines", ".", "add", "(", "2", ",", "'self.sequences.%s.%s(self.idx_sim)'", "%", "(", "subseqs", ".", "name", ",", "func", ")", ")", "return", "lines" ]
Input/output functions of the model class.
[ "Input", "/", "output", "functions", "of", "the", "model", "class", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L709-L739
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.calculate_single_terms
def calculate_single_terms(self): """Lines of model method with the same name.""" lines = self._call_methods('calculate_single_terms', self.model.PART_ODE_METHODS) if lines: lines.insert(1, (' self.numvars.nmb_calls =' 'self.numvars.nmb_calls+1')) return lines
python
def calculate_single_terms(self): """Lines of model method with the same name.""" lines = self._call_methods('calculate_single_terms', self.model.PART_ODE_METHODS) if lines: lines.insert(1, (' self.numvars.nmb_calls =' 'self.numvars.nmb_calls+1')) return lines
[ "def", "calculate_single_terms", "(", "self", ")", ":", "lines", "=", "self", ".", "_call_methods", "(", "'calculate_single_terms'", ",", "self", ".", "model", ".", "PART_ODE_METHODS", ")", "if", "lines", ":", "lines", ".", "insert", "(", "1", ",", "(", "' self.numvars.nmb_calls ='", "'self.numvars.nmb_calls+1'", ")", ")", "return", "lines" ]
Lines of model method with the same name.
[ "Lines", "of", "model", "method", "with", "the", "same", "name", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L818-L825
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
PyxWriter.listofmodeluserfunctions
def listofmodeluserfunctions(self): """User functions of the model class.""" lines = [] for (name, member) in vars(self.model.__class__).items(): if (inspect.isfunction(member) and (name not in ('run', 'new2old')) and ('fastaccess' in inspect.getsource(member))): lines.append((name, member)) run = vars(self.model.__class__).get('run') if run is not None: lines.append(('run', run)) for (name, member) in vars(self.model).items(): if (inspect.ismethod(member) and ('fastaccess' in inspect.getsource(member))): lines.append((name, member)) return lines
python
def listofmodeluserfunctions(self): """User functions of the model class.""" lines = [] for (name, member) in vars(self.model.__class__).items(): if (inspect.isfunction(member) and (name not in ('run', 'new2old')) and ('fastaccess' in inspect.getsource(member))): lines.append((name, member)) run = vars(self.model.__class__).get('run') if run is not None: lines.append(('run', run)) for (name, member) in vars(self.model).items(): if (inspect.ismethod(member) and ('fastaccess' in inspect.getsource(member))): lines.append((name, member)) return lines
[ "def", "listofmodeluserfunctions", "(", "self", ")", ":", "lines", "=", "[", "]", "for", "(", "name", ",", "member", ")", "in", "vars", "(", "self", ".", "model", ".", "__class__", ")", ".", "items", "(", ")", ":", "if", "(", "inspect", ".", "isfunction", "(", "member", ")", "and", "(", "name", "not", "in", "(", "'run'", ",", "'new2old'", ")", ")", "and", "(", "'fastaccess'", "in", "inspect", ".", "getsource", "(", "member", ")", ")", ")", ":", "lines", ".", "append", "(", "(", "name", ",", "member", ")", ")", "run", "=", "vars", "(", "self", ".", "model", ".", "__class__", ")", ".", "get", "(", "'run'", ")", "if", "run", "is", "not", "None", ":", "lines", ".", "append", "(", "(", "'run'", ",", "run", ")", ")", "for", "(", "name", ",", "member", ")", "in", "vars", "(", "self", ".", "model", ")", ".", "items", "(", ")", ":", "if", "(", "inspect", ".", "ismethod", "(", "member", ")", "and", "(", "'fastaccess'", "in", "inspect", ".", "getsource", "(", "member", ")", ")", ")", ":", "lines", ".", "append", "(", "(", "name", ",", "member", ")", ")", "return", "lines" ]
User functions of the model class.
[ "User", "functions", "of", "the", "model", "class", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L834-L849
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
FuncConverter.cleanlines
def cleanlines(self): """Cleaned code lines. Implemented cleanups: * eventually remove method version * remove docstrings * remove comments * remove empty lines * remove line brackes within brackets * replace `modelutils` with nothing * remove complete lines containing `fastaccess` * replace shortcuts with complete references """ code = inspect.getsource(self.func) code = '\n'.join(code.split('"""')[::2]) code = code.replace('modelutils.', '') for (name, shortcut) in zip(self.collectornames, self.collectorshortcuts): code = code.replace('%s.' % shortcut, 'self.%s.' % name) code = self.remove_linebreaks_within_equations(code) lines = code.splitlines() self.remove_imath_operators(lines) lines[0] = 'def %s(self):' % self.funcname lines = [l.split('#')[0] for l in lines] lines = [l for l in lines if 'fastaccess' not in l] lines = [l.rstrip() for l in lines if l.rstrip()] return Lines(*lines)
python
def cleanlines(self): """Cleaned code lines. Implemented cleanups: * eventually remove method version * remove docstrings * remove comments * remove empty lines * remove line brackes within brackets * replace `modelutils` with nothing * remove complete lines containing `fastaccess` * replace shortcuts with complete references """ code = inspect.getsource(self.func) code = '\n'.join(code.split('"""')[::2]) code = code.replace('modelutils.', '') for (name, shortcut) in zip(self.collectornames, self.collectorshortcuts): code = code.replace('%s.' % shortcut, 'self.%s.' % name) code = self.remove_linebreaks_within_equations(code) lines = code.splitlines() self.remove_imath_operators(lines) lines[0] = 'def %s(self):' % self.funcname lines = [l.split('#')[0] for l in lines] lines = [l for l in lines if 'fastaccess' not in l] lines = [l.rstrip() for l in lines if l.rstrip()] return Lines(*lines)
[ "def", "cleanlines", "(", "self", ")", ":", "code", "=", "inspect", ".", "getsource", "(", "self", ".", "func", ")", "code", "=", "'\\n'", ".", "join", "(", "code", ".", "split", "(", "'\"\"\"'", ")", "[", ":", ":", "2", "]", ")", "code", "=", "code", ".", "replace", "(", "'modelutils.'", ",", "''", ")", "for", "(", "name", ",", "shortcut", ")", "in", "zip", "(", "self", ".", "collectornames", ",", "self", ".", "collectorshortcuts", ")", ":", "code", "=", "code", ".", "replace", "(", "'%s.'", "%", "shortcut", ",", "'self.%s.'", "%", "name", ")", "code", "=", "self", ".", "remove_linebreaks_within_equations", "(", "code", ")", "lines", "=", "code", ".", "splitlines", "(", ")", "self", ".", "remove_imath_operators", "(", "lines", ")", "lines", "[", "0", "]", "=", "'def %s(self):'", "%", "self", ".", "funcname", "lines", "=", "[", "l", ".", "split", "(", "'#'", ")", "[", "0", "]", "for", "l", "in", "lines", "]", "lines", "=", "[", "l", "for", "l", "in", "lines", "if", "'fastaccess'", "not", "in", "l", "]", "lines", "=", "[", "l", ".", "rstrip", "(", ")", "for", "l", "in", "lines", "if", "l", ".", "rstrip", "(", ")", "]", "return", "Lines", "(", "*", "lines", ")" ]
Cleaned code lines. Implemented cleanups: * eventually remove method version * remove docstrings * remove comments * remove empty lines * remove line brackes within brackets * replace `modelutils` with nothing * remove complete lines containing `fastaccess` * replace shortcuts with complete references
[ "Cleaned", "code", "lines", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L1142-L1168
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
FuncConverter.remove_linebreaks_within_equations
def remove_linebreaks_within_equations(code): r"""Remove line breaks within equations. This is not a exhaustive test, but shows how the method works: >>> code = 'asdf = \\\n(a\n+b)' >>> from hydpy.cythons.modelutils import FuncConverter >>> FuncConverter.remove_linebreaks_within_equations(code) 'asdf = (a+b)' """ code = code.replace('\\\n', '') chars = [] counter = 0 for char in code: if char in ('(', '[', '{'): counter += 1 elif char in (')', ']', '}'): counter -= 1 if not (counter and (char == '\n')): chars.append(char) return ''.join(chars)
python
def remove_linebreaks_within_equations(code): r"""Remove line breaks within equations. This is not a exhaustive test, but shows how the method works: >>> code = 'asdf = \\\n(a\n+b)' >>> from hydpy.cythons.modelutils import FuncConverter >>> FuncConverter.remove_linebreaks_within_equations(code) 'asdf = (a+b)' """ code = code.replace('\\\n', '') chars = [] counter = 0 for char in code: if char in ('(', '[', '{'): counter += 1 elif char in (')', ']', '}'): counter -= 1 if not (counter and (char == '\n')): chars.append(char) return ''.join(chars)
[ "def", "remove_linebreaks_within_equations", "(", "code", ")", ":", "code", "=", "code", ".", "replace", "(", "'\\\\\\n'", ",", "''", ")", "chars", "=", "[", "]", "counter", "=", "0", "for", "char", "in", "code", ":", "if", "char", "in", "(", "'('", ",", "'['", ",", "'{'", ")", ":", "counter", "+=", "1", "elif", "char", "in", "(", "')'", ",", "']'", ",", "'}'", ")", ":", "counter", "-=", "1", "if", "not", "(", "counter", "and", "(", "char", "==", "'\\n'", ")", ")", ":", "chars", ".", "append", "(", "char", ")", "return", "''", ".", "join", "(", "chars", ")" ]
r"""Remove line breaks within equations. This is not a exhaustive test, but shows how the method works: >>> code = 'asdf = \\\n(a\n+b)' >>> from hydpy.cythons.modelutils import FuncConverter >>> FuncConverter.remove_linebreaks_within_equations(code) 'asdf = (a+b)'
[ "r", "Remove", "line", "breaks", "within", "equations", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L1171-L1191
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
FuncConverter.remove_imath_operators
def remove_imath_operators(lines): """Remove mathematical expressions that require Pythons global interpreter locking mechanism. This is not a exhaustive test, but shows how the method works: >>> lines = [' x += 1*1'] >>> from hydpy.cythons.modelutils import FuncConverter >>> FuncConverter.remove_imath_operators(lines) >>> lines [' x = x + (1*1)'] """ for idx, line in enumerate(lines): for operator in ('+=', '-=', '**=', '*=', '//=', '/=', '%='): sublines = line.split(operator) if len(sublines) > 1: indent = line.count(' ') - line.lstrip().count(' ') sublines = [sl.strip() for sl in sublines] line = ('%s%s = %s %s (%s)' % (indent*' ', sublines[0], sublines[0], operator[:-1], sublines[1])) lines[idx] = line
python
def remove_imath_operators(lines): """Remove mathematical expressions that require Pythons global interpreter locking mechanism. This is not a exhaustive test, but shows how the method works: >>> lines = [' x += 1*1'] >>> from hydpy.cythons.modelutils import FuncConverter >>> FuncConverter.remove_imath_operators(lines) >>> lines [' x = x + (1*1)'] """ for idx, line in enumerate(lines): for operator in ('+=', '-=', '**=', '*=', '//=', '/=', '%='): sublines = line.split(operator) if len(sublines) > 1: indent = line.count(' ') - line.lstrip().count(' ') sublines = [sl.strip() for sl in sublines] line = ('%s%s = %s %s (%s)' % (indent*' ', sublines[0], sublines[0], operator[:-1], sublines[1])) lines[idx] = line
[ "def", "remove_imath_operators", "(", "lines", ")", ":", "for", "idx", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "for", "operator", "in", "(", "'+='", ",", "'-='", ",", "'**='", ",", "'*='", ",", "'//='", ",", "'/='", ",", "'%='", ")", ":", "sublines", "=", "line", ".", "split", "(", "operator", ")", "if", "len", "(", "sublines", ")", ">", "1", ":", "indent", "=", "line", ".", "count", "(", "' '", ")", "-", "line", ".", "lstrip", "(", ")", ".", "count", "(", "' '", ")", "sublines", "=", "[", "sl", ".", "strip", "(", ")", "for", "sl", "in", "sublines", "]", "line", "=", "(", "'%s%s = %s %s (%s)'", "%", "(", "indent", "*", "' '", ",", "sublines", "[", "0", "]", ",", "sublines", "[", "0", "]", ",", "operator", "[", ":", "-", "1", "]", ",", "sublines", "[", "1", "]", ")", ")", "lines", "[", "idx", "]", "=", "line" ]
Remove mathematical expressions that require Pythons global interpreter locking mechanism. This is not a exhaustive test, but shows how the method works: >>> lines = [' x += 1*1'] >>> from hydpy.cythons.modelutils import FuncConverter >>> FuncConverter.remove_imath_operators(lines) >>> lines [' x = x + (1*1)']
[ "Remove", "mathematical", "expressions", "that", "require", "Pythons", "global", "interpreter", "locking", "mechanism", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L1194-L1215
train
hydpy-dev/hydpy
hydpy/cythons/modelutils.py
FuncConverter.pyxlines
def pyxlines(self): """Cython code lines. Assumptions: * Function shall be a method * Method shall be inlined * Method returns nothing * Method arguments are of type `int` (except self) * Local variables are generally of type `int` but of type `double` when their name starts with `d_` """ lines = [' '+line for line in self.cleanlines] lines[0] = lines[0].replace('def ', 'cpdef inline void ') lines[0] = lines[0].replace('):', ') %s:' % _nogil) for name in self.untypedarguments: lines[0] = lines[0].replace(', %s ' % name, ', int %s ' % name) lines[0] = lines[0].replace(', %s)' % name, ', int %s)' % name) for name in self.untypedinternalvarnames: if name.startswith('d_'): lines.insert(1, ' cdef double ' + name) else: lines.insert(1, ' cdef int ' + name) return Lines(*lines)
python
def pyxlines(self): """Cython code lines. Assumptions: * Function shall be a method * Method shall be inlined * Method returns nothing * Method arguments are of type `int` (except self) * Local variables are generally of type `int` but of type `double` when their name starts with `d_` """ lines = [' '+line for line in self.cleanlines] lines[0] = lines[0].replace('def ', 'cpdef inline void ') lines[0] = lines[0].replace('):', ') %s:' % _nogil) for name in self.untypedarguments: lines[0] = lines[0].replace(', %s ' % name, ', int %s ' % name) lines[0] = lines[0].replace(', %s)' % name, ', int %s)' % name) for name in self.untypedinternalvarnames: if name.startswith('d_'): lines.insert(1, ' cdef double ' + name) else: lines.insert(1, ' cdef int ' + name) return Lines(*lines)
[ "def", "pyxlines", "(", "self", ")", ":", "lines", "=", "[", "' '", "+", "line", "for", "line", "in", "self", ".", "cleanlines", "]", "lines", "[", "0", "]", "=", "lines", "[", "0", "]", ".", "replace", "(", "'def '", ",", "'cpdef inline void '", ")", "lines", "[", "0", "]", "=", "lines", "[", "0", "]", ".", "replace", "(", "'):'", ",", "') %s:'", "%", "_nogil", ")", "for", "name", "in", "self", ".", "untypedarguments", ":", "lines", "[", "0", "]", "=", "lines", "[", "0", "]", ".", "replace", "(", "', %s '", "%", "name", ",", "', int %s '", "%", "name", ")", "lines", "[", "0", "]", "=", "lines", "[", "0", "]", ".", "replace", "(", "', %s)'", "%", "name", ",", "', int %s)'", "%", "name", ")", "for", "name", "in", "self", ".", "untypedinternalvarnames", ":", "if", "name", ".", "startswith", "(", "'d_'", ")", ":", "lines", ".", "insert", "(", "1", ",", "' cdef double '", "+", "name", ")", "else", ":", "lines", ".", "insert", "(", "1", ",", "' cdef int '", "+", "name", ")", "return", "Lines", "(", "*", "lines", ")" ]
Cython code lines. Assumptions: * Function shall be a method * Method shall be inlined * Method returns nothing * Method arguments are of type `int` (except self) * Local variables are generally of type `int` but of type `double` when their name starts with `d_`
[ "Cython", "code", "lines", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/cythons/modelutils.py#L1218-L1240
train
hydpy-dev/hydpy
hydpy/auxs/smoothtools.py
calc_smoothpar_logistic2
def calc_smoothpar_logistic2(metapar): """Return the smoothing parameter corresponding to the given meta parameter when using |smooth_logistic2|. Calculate the smoothing parameter value corresponding the meta parameter value 2.5: >>> from hydpy.auxs.smoothtools import calc_smoothpar_logistic2 >>> smoothpar = calc_smoothpar_logistic2(2.5) Using this smoothing parameter value, the output of function |smooth_logistic2| differs by 1 % from the related `true` discontinuous step function for the input values -2.5 and 2.5 (which are located at a distance of 2.5 from the position of the discontinuity): >>> from hydpy.cythons import smoothutils >>> from hydpy import round_ >>> round_(smoothutils.smooth_logistic2(-2.5, smoothpar)) 0.01 >>> round_(smoothutils.smooth_logistic2(2.5, smoothpar)) 2.51 For zero or negative meta parameter values, a zero smoothing parameter value is returned: >>> round_(calc_smoothpar_logistic2(0.0)) 0.0 >>> round_(calc_smoothpar_logistic2(-1.0)) 0.0 """ if metapar <= 0.: return 0. return optimize.newton(_error_smoothpar_logistic2, .3 * metapar**.84, _smooth_logistic2_derivative, args=(metapar,))
python
def calc_smoothpar_logistic2(metapar): """Return the smoothing parameter corresponding to the given meta parameter when using |smooth_logistic2|. Calculate the smoothing parameter value corresponding the meta parameter value 2.5: >>> from hydpy.auxs.smoothtools import calc_smoothpar_logistic2 >>> smoothpar = calc_smoothpar_logistic2(2.5) Using this smoothing parameter value, the output of function |smooth_logistic2| differs by 1 % from the related `true` discontinuous step function for the input values -2.5 and 2.5 (which are located at a distance of 2.5 from the position of the discontinuity): >>> from hydpy.cythons import smoothutils >>> from hydpy import round_ >>> round_(smoothutils.smooth_logistic2(-2.5, smoothpar)) 0.01 >>> round_(smoothutils.smooth_logistic2(2.5, smoothpar)) 2.51 For zero or negative meta parameter values, a zero smoothing parameter value is returned: >>> round_(calc_smoothpar_logistic2(0.0)) 0.0 >>> round_(calc_smoothpar_logistic2(-1.0)) 0.0 """ if metapar <= 0.: return 0. return optimize.newton(_error_smoothpar_logistic2, .3 * metapar**.84, _smooth_logistic2_derivative, args=(metapar,))
[ "def", "calc_smoothpar_logistic2", "(", "metapar", ")", ":", "if", "metapar", "<=", "0.", ":", "return", "0.", "return", "optimize", ".", "newton", "(", "_error_smoothpar_logistic2", ",", ".3", "*", "metapar", "**", ".84", ",", "_smooth_logistic2_derivative", ",", "args", "=", "(", "metapar", ",", ")", ")" ]
Return the smoothing parameter corresponding to the given meta parameter when using |smooth_logistic2|. Calculate the smoothing parameter value corresponding the meta parameter value 2.5: >>> from hydpy.auxs.smoothtools import calc_smoothpar_logistic2 >>> smoothpar = calc_smoothpar_logistic2(2.5) Using this smoothing parameter value, the output of function |smooth_logistic2| differs by 1 % from the related `true` discontinuous step function for the input values -2.5 and 2.5 (which are located at a distance of 2.5 from the position of the discontinuity): >>> from hydpy.cythons import smoothutils >>> from hydpy import round_ >>> round_(smoothutils.smooth_logistic2(-2.5, smoothpar)) 0.01 >>> round_(smoothutils.smooth_logistic2(2.5, smoothpar)) 2.51 For zero or negative meta parameter values, a zero smoothing parameter value is returned: >>> round_(calc_smoothpar_logistic2(0.0)) 0.0 >>> round_(calc_smoothpar_logistic2(-1.0)) 0.0
[ "Return", "the", "smoothing", "parameter", "corresponding", "to", "the", "given", "meta", "parameter", "when", "using", "|smooth_logistic2|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/smoothtools.py#L78-L114
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Date.from_array
def from_array(cls, array): """Return a |Date| instance based on date information (year, month, day, hour, minute, second) stored as the first entries of the successive rows of a |numpy.ndarray|. >>> from hydpy import Date >>> import numpy >>> array1d = numpy.array([1992, 10, 8, 15, 15, 42, 999]) >>> Date.from_array(array1d) Date('1992-10-08 15:15:42') >>> array3d = numpy.zeros((7, 2, 2)) >>> array3d[:, 0, 0] = array1d >>> Date.from_array(array3d) Date('1992-10-08 15:15:42') .. note:: The date defined by the given |numpy.ndarray| cannot include any time zone information and corresponds to |Options.utcoffset|, which defaults to UTC+01:00. """ intarray = numpy.array(array, dtype=int) for dummy in range(1, array.ndim): intarray = intarray[:, 0] return cls(datetime.datetime(*intarray[:6]))
python
def from_array(cls, array): """Return a |Date| instance based on date information (year, month, day, hour, minute, second) stored as the first entries of the successive rows of a |numpy.ndarray|. >>> from hydpy import Date >>> import numpy >>> array1d = numpy.array([1992, 10, 8, 15, 15, 42, 999]) >>> Date.from_array(array1d) Date('1992-10-08 15:15:42') >>> array3d = numpy.zeros((7, 2, 2)) >>> array3d[:, 0, 0] = array1d >>> Date.from_array(array3d) Date('1992-10-08 15:15:42') .. note:: The date defined by the given |numpy.ndarray| cannot include any time zone information and corresponds to |Options.utcoffset|, which defaults to UTC+01:00. """ intarray = numpy.array(array, dtype=int) for dummy in range(1, array.ndim): intarray = intarray[:, 0] return cls(datetime.datetime(*intarray[:6]))
[ "def", "from_array", "(", "cls", ",", "array", ")", ":", "intarray", "=", "numpy", ".", "array", "(", "array", ",", "dtype", "=", "int", ")", "for", "dummy", "in", "range", "(", "1", ",", "array", ".", "ndim", ")", ":", "intarray", "=", "intarray", "[", ":", ",", "0", "]", "return", "cls", "(", "datetime", ".", "datetime", "(", "*", "intarray", "[", ":", "6", "]", ")", ")" ]
Return a |Date| instance based on date information (year, month, day, hour, minute, second) stored as the first entries of the successive rows of a |numpy.ndarray|. >>> from hydpy import Date >>> import numpy >>> array1d = numpy.array([1992, 10, 8, 15, 15, 42, 999]) >>> Date.from_array(array1d) Date('1992-10-08 15:15:42') >>> array3d = numpy.zeros((7, 2, 2)) >>> array3d[:, 0, 0] = array1d >>> Date.from_array(array3d) Date('1992-10-08 15:15:42') .. note:: The date defined by the given |numpy.ndarray| cannot include any time zone information and corresponds to |Options.utcoffset|, which defaults to UTC+01:00.
[ "Return", "a", "|Date|", "instance", "based", "on", "date", "information", "(", "year", "month", "day", "hour", "minute", "second", ")", "stored", "as", "the", "first", "entries", "of", "the", "successive", "rows", "of", "a", "|numpy", ".", "ndarray|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L256-L281
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Date.to_array
def to_array(self): """Return a 1-dimensional |numpy| |numpy.ndarray| with six entries defining the actual date (year, month, day, hour, minute, second). >>> from hydpy import Date >>> Date('1992-10-8 15:15:42').to_array() array([ 1992., 10., 8., 15., 15., 42.]) .. note:: The date defined by the returned |numpy.ndarray| does not include any time zone information and corresponds to |Options.utcoffset|, which defaults to UTC+01:00. """ return numpy.array([self.year, self.month, self.day, self.hour, self.minute, self.second], dtype=float)
python
def to_array(self): """Return a 1-dimensional |numpy| |numpy.ndarray| with six entries defining the actual date (year, month, day, hour, minute, second). >>> from hydpy import Date >>> Date('1992-10-8 15:15:42').to_array() array([ 1992., 10., 8., 15., 15., 42.]) .. note:: The date defined by the returned |numpy.ndarray| does not include any time zone information and corresponds to |Options.utcoffset|, which defaults to UTC+01:00. """ return numpy.array([self.year, self.month, self.day, self.hour, self.minute, self.second], dtype=float)
[ "def", "to_array", "(", "self", ")", ":", "return", "numpy", ".", "array", "(", "[", "self", ".", "year", ",", "self", ".", "month", ",", "self", ".", "day", ",", "self", ".", "hour", ",", "self", ".", "minute", ",", "self", ".", "second", "]", ",", "dtype", "=", "float", ")" ]
Return a 1-dimensional |numpy| |numpy.ndarray| with six entries defining the actual date (year, month, day, hour, minute, second). >>> from hydpy import Date >>> Date('1992-10-8 15:15:42').to_array() array([ 1992., 10., 8., 15., 15., 42.]) .. note:: The date defined by the returned |numpy.ndarray| does not include any time zone information and corresponds to |Options.utcoffset|, which defaults to UTC+01:00.
[ "Return", "a", "1", "-", "dimensional", "|numpy|", "|numpy", ".", "ndarray|", "with", "six", "entries", "defining", "the", "actual", "date", "(", "year", "month", "day", "hour", "minute", "second", ")", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L283-L298
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Date.from_cfunits
def from_cfunits(cls, units) -> 'Date': """Return a |Date| object representing the reference date of the given `units` string agreeing with the NetCDF-CF conventions. The following example string is taken from the `Time Coordinate`_ chapter of the NetCDF-CF conventions documentation (modified). Note that the first entry (the unit) is ignored: >>> from hydpy import Date >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42 -6:00') Date('1992-10-08 22:15:42') >>> Date.from_cfunits(' day since 1992-10-8 15:15:00') Date('1992-10-08 15:15:00') >>> Date.from_cfunits('seconds since 1992-10-8 -6:00') Date('1992-10-08 07:00:00') >>> Date.from_cfunits('m since 1992-10-8') Date('1992-10-08 00:00:00') Without modification, when "0" is included as the decimal fractions of a second, the example string from `Time Coordinate`_ can also be passed. However, fractions different from "0" result in an error: >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.') Date('1992-10-08 15:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.00') Date('1992-10-08 15:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42. -6:00') Date('1992-10-08 22:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.0 -6:00') Date('1992-10-08 22:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.005 -6:00') Traceback (most recent call last): ... ValueError: While trying to parse the date of the NetCDF-CF "units" \ string `seconds since 1992-10-8 15:15:42.005 -6:00`, the following error \ occurred: No other decimal fraction of a second than "0" allowed. """ try: string = units[units.find('since')+6:] idx = string.find('.') if idx != -1: jdx = None for jdx, char in enumerate(string[idx+1:]): if not char.isnumeric(): break if char != '0': raise ValueError( 'No other decimal fraction of a second ' 'than "0" allowed.') else: if jdx is None: jdx = idx+1 else: jdx += 1 string = f'{string[:idx]}{string[idx+jdx+1:]}' return cls(string) except BaseException: objecttools.augment_excmessage( f'While trying to parse the date of the NetCDF-CF "units" ' f'string `{units}`')
python
def from_cfunits(cls, units) -> 'Date': """Return a |Date| object representing the reference date of the given `units` string agreeing with the NetCDF-CF conventions. The following example string is taken from the `Time Coordinate`_ chapter of the NetCDF-CF conventions documentation (modified). Note that the first entry (the unit) is ignored: >>> from hydpy import Date >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42 -6:00') Date('1992-10-08 22:15:42') >>> Date.from_cfunits(' day since 1992-10-8 15:15:00') Date('1992-10-08 15:15:00') >>> Date.from_cfunits('seconds since 1992-10-8 -6:00') Date('1992-10-08 07:00:00') >>> Date.from_cfunits('m since 1992-10-8') Date('1992-10-08 00:00:00') Without modification, when "0" is included as the decimal fractions of a second, the example string from `Time Coordinate`_ can also be passed. However, fractions different from "0" result in an error: >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.') Date('1992-10-08 15:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.00') Date('1992-10-08 15:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42. -6:00') Date('1992-10-08 22:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.0 -6:00') Date('1992-10-08 22:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.005 -6:00') Traceback (most recent call last): ... ValueError: While trying to parse the date of the NetCDF-CF "units" \ string `seconds since 1992-10-8 15:15:42.005 -6:00`, the following error \ occurred: No other decimal fraction of a second than "0" allowed. """ try: string = units[units.find('since')+6:] idx = string.find('.') if idx != -1: jdx = None for jdx, char in enumerate(string[idx+1:]): if not char.isnumeric(): break if char != '0': raise ValueError( 'No other decimal fraction of a second ' 'than "0" allowed.') else: if jdx is None: jdx = idx+1 else: jdx += 1 string = f'{string[:idx]}{string[idx+jdx+1:]}' return cls(string) except BaseException: objecttools.augment_excmessage( f'While trying to parse the date of the NetCDF-CF "units" ' f'string `{units}`')
[ "def", "from_cfunits", "(", "cls", ",", "units", ")", "->", "'Date'", ":", "try", ":", "string", "=", "units", "[", "units", ".", "find", "(", "'since'", ")", "+", "6", ":", "]", "idx", "=", "string", ".", "find", "(", "'.'", ")", "if", "idx", "!=", "-", "1", ":", "jdx", "=", "None", "for", "jdx", ",", "char", "in", "enumerate", "(", "string", "[", "idx", "+", "1", ":", "]", ")", ":", "if", "not", "char", ".", "isnumeric", "(", ")", ":", "break", "if", "char", "!=", "'0'", ":", "raise", "ValueError", "(", "'No other decimal fraction of a second '", "'than \"0\" allowed.'", ")", "else", ":", "if", "jdx", "is", "None", ":", "jdx", "=", "idx", "+", "1", "else", ":", "jdx", "+=", "1", "string", "=", "f'{string[:idx]}{string[idx+jdx+1:]}'", "return", "cls", "(", "string", ")", "except", "BaseException", ":", "objecttools", ".", "augment_excmessage", "(", "f'While trying to parse the date of the NetCDF-CF \"units\" '", "f'string `{units}`'", ")" ]
Return a |Date| object representing the reference date of the given `units` string agreeing with the NetCDF-CF conventions. The following example string is taken from the `Time Coordinate`_ chapter of the NetCDF-CF conventions documentation (modified). Note that the first entry (the unit) is ignored: >>> from hydpy import Date >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42 -6:00') Date('1992-10-08 22:15:42') >>> Date.from_cfunits(' day since 1992-10-8 15:15:00') Date('1992-10-08 15:15:00') >>> Date.from_cfunits('seconds since 1992-10-8 -6:00') Date('1992-10-08 07:00:00') >>> Date.from_cfunits('m since 1992-10-8') Date('1992-10-08 00:00:00') Without modification, when "0" is included as the decimal fractions of a second, the example string from `Time Coordinate`_ can also be passed. However, fractions different from "0" result in an error: >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.') Date('1992-10-08 15:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.00') Date('1992-10-08 15:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42. -6:00') Date('1992-10-08 22:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.0 -6:00') Date('1992-10-08 22:15:42') >>> Date.from_cfunits('seconds since 1992-10-8 15:15:42.005 -6:00') Traceback (most recent call last): ... ValueError: While trying to parse the date of the NetCDF-CF "units" \ string `seconds since 1992-10-8 15:15:42.005 -6:00`, the following error \ occurred: No other decimal fraction of a second than "0" allowed.
[ "Return", "a", "|Date|", "object", "representing", "the", "reference", "date", "of", "the", "given", "units", "string", "agreeing", "with", "the", "NetCDF", "-", "CF", "conventions", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L301-L361
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Date.to_cfunits
def to_cfunits(self, unit='hours', utcoffset=None): """Return a `units` string agreeing with the NetCDF-CF conventions. By default, |Date.to_cfunits| takes `hours` as time unit, and the the actual value of |Options.utcoffset| as time zone information: >>> from hydpy import Date >>> date = Date('1992-10-08 15:15:42') >>> date.to_cfunits() 'hours since 1992-10-08 15:15:42 +01:00' Other time units are allowed (no checks are performed, so select something useful): >>> date.to_cfunits(unit='minutes') 'minutes since 1992-10-08 15:15:42 +01:00' For changing the time zone, pass the corresponding offset in minutes: >>> date.to_cfunits(unit='sec', utcoffset=-60) 'sec since 1992-10-08 13:15:42 -01:00' """ if utcoffset is None: utcoffset = hydpy.pub.options.utcoffset string = self.to_string('iso2', utcoffset) string = ' '.join((string[:-6], string[-6:])) return f'{unit} since {string}'
python
def to_cfunits(self, unit='hours', utcoffset=None): """Return a `units` string agreeing with the NetCDF-CF conventions. By default, |Date.to_cfunits| takes `hours` as time unit, and the the actual value of |Options.utcoffset| as time zone information: >>> from hydpy import Date >>> date = Date('1992-10-08 15:15:42') >>> date.to_cfunits() 'hours since 1992-10-08 15:15:42 +01:00' Other time units are allowed (no checks are performed, so select something useful): >>> date.to_cfunits(unit='minutes') 'minutes since 1992-10-08 15:15:42 +01:00' For changing the time zone, pass the corresponding offset in minutes: >>> date.to_cfunits(unit='sec', utcoffset=-60) 'sec since 1992-10-08 13:15:42 -01:00' """ if utcoffset is None: utcoffset = hydpy.pub.options.utcoffset string = self.to_string('iso2', utcoffset) string = ' '.join((string[:-6], string[-6:])) return f'{unit} since {string}'
[ "def", "to_cfunits", "(", "self", ",", "unit", "=", "'hours'", ",", "utcoffset", "=", "None", ")", ":", "if", "utcoffset", "is", "None", ":", "utcoffset", "=", "hydpy", ".", "pub", ".", "options", ".", "utcoffset", "string", "=", "self", ".", "to_string", "(", "'iso2'", ",", "utcoffset", ")", "string", "=", "' '", ".", "join", "(", "(", "string", "[", ":", "-", "6", "]", ",", "string", "[", "-", "6", ":", "]", ")", ")", "return", "f'{unit} since {string}'" ]
Return a `units` string agreeing with the NetCDF-CF conventions. By default, |Date.to_cfunits| takes `hours` as time unit, and the the actual value of |Options.utcoffset| as time zone information: >>> from hydpy import Date >>> date = Date('1992-10-08 15:15:42') >>> date.to_cfunits() 'hours since 1992-10-08 15:15:42 +01:00' Other time units are allowed (no checks are performed, so select something useful): >>> date.to_cfunits(unit='minutes') 'minutes since 1992-10-08 15:15:42 +01:00' For changing the time zone, pass the corresponding offset in minutes: >>> date.to_cfunits(unit='sec', utcoffset=-60) 'sec since 1992-10-08 13:15:42 -01:00'
[ "Return", "a", "units", "string", "agreeing", "with", "the", "NetCDF", "-", "CF", "conventions", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L363-L389
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Date._set_thing
def _set_thing(self, thing, value): """Convenience method for `_set_year`, `_set_month`...""" try: value = int(value) except (TypeError, ValueError): raise TypeError( f'Changing the {thing} of a `Date` instance is only ' f'allowed via numbers, but the given value `{value}` ' f'is of type `{type(value)}` instead.') kwargs = {} for unit in ('year', 'month', 'day', 'hour', 'minute', 'second'): kwargs[unit] = getattr(self, unit) kwargs[thing] = value self.datetime = datetime.datetime(**kwargs)
python
def _set_thing(self, thing, value): """Convenience method for `_set_year`, `_set_month`...""" try: value = int(value) except (TypeError, ValueError): raise TypeError( f'Changing the {thing} of a `Date` instance is only ' f'allowed via numbers, but the given value `{value}` ' f'is of type `{type(value)}` instead.') kwargs = {} for unit in ('year', 'month', 'day', 'hour', 'minute', 'second'): kwargs[unit] = getattr(self, unit) kwargs[thing] = value self.datetime = datetime.datetime(**kwargs)
[ "def", "_set_thing", "(", "self", ",", "thing", ",", "value", ")", ":", "try", ":", "value", "=", "int", "(", "value", ")", "except", "(", "TypeError", ",", "ValueError", ")", ":", "raise", "TypeError", "(", "f'Changing the {thing} of a `Date` instance is only '", "f'allowed via numbers, but the given value `{value}` '", "f'is of type `{type(value)}` instead.'", ")", "kwargs", "=", "{", "}", "for", "unit", "in", "(", "'year'", ",", "'month'", ",", "'day'", ",", "'hour'", ",", "'minute'", ",", "'second'", ")", ":", "kwargs", "[", "unit", "]", "=", "getattr", "(", "self", ",", "unit", ")", "kwargs", "[", "thing", "]", "=", "value", "self", ".", "datetime", "=", "datetime", ".", "datetime", "(", "*", "*", "kwargs", ")" ]
Convenience method for `_set_year`, `_set_month`...
[ "Convenience", "method", "for", "_set_year", "_set_month", "..." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L455-L468
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Date.wateryear
def wateryear(self): """The actual hydrological year according to the selected reference month. The reference mont reference |Date.refmonth| defaults to November: >>> october = Date('1996.10.01') >>> november = Date('1996.11.01') >>> october.wateryear 1996 >>> november.wateryear 1997 Note that changing |Date.refmonth| affects all |Date| objects: >>> october.refmonth = 10 >>> october.wateryear 1997 >>> november.wateryear 1997 >>> october.refmonth = 'November' >>> october.wateryear 1996 >>> november.wateryear 1997 """ if self.month < self._firstmonth_wateryear: return self.year return self.year + 1
python
def wateryear(self): """The actual hydrological year according to the selected reference month. The reference mont reference |Date.refmonth| defaults to November: >>> october = Date('1996.10.01') >>> november = Date('1996.11.01') >>> october.wateryear 1996 >>> november.wateryear 1997 Note that changing |Date.refmonth| affects all |Date| objects: >>> october.refmonth = 10 >>> october.wateryear 1997 >>> november.wateryear 1997 >>> october.refmonth = 'November' >>> october.wateryear 1996 >>> november.wateryear 1997 """ if self.month < self._firstmonth_wateryear: return self.year return self.year + 1
[ "def", "wateryear", "(", "self", ")", ":", "if", "self", ".", "month", "<", "self", ".", "_firstmonth_wateryear", ":", "return", "self", ".", "year", "return", "self", ".", "year", "+", "1" ]
The actual hydrological year according to the selected reference month. The reference mont reference |Date.refmonth| defaults to November: >>> october = Date('1996.10.01') >>> november = Date('1996.11.01') >>> october.wateryear 1996 >>> november.wateryear 1997 Note that changing |Date.refmonth| affects all |Date| objects: >>> october.refmonth = 10 >>> october.wateryear 1997 >>> november.wateryear 1997 >>> october.refmonth = 'November' >>> october.wateryear 1996 >>> november.wateryear 1997
[ "The", "actual", "hydrological", "year", "according", "to", "the", "selected", "reference", "month", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L582-L610
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Date.to_string
def to_string(self, style=None, utcoffset=None): """Return a |str| object representing the actual date in accordance with the given style and the eventually given UTC offset (in minutes). Without any input arguments, the actual |Date.style| is used to return a date string in your local time zone: >>> from hydpy import Date >>> date = Date('01.11.1997 00:00:00') >>> date.to_string() '01.11.1997 00:00:00' Passing a style string affects the returned |str| object, but not the |Date.style| property: >>> date.style 'din1' >>> date.to_string(style='iso2') '1997-11-01 00:00:00' >>> date.style 'din1' When passing the `utcoffset` in minutes, the offset string is appended: >>> date.to_string(style='iso2', utcoffset=60) '1997-11-01 00:00:00+01:00' If the given offset does not correspond to your local offset defined by |Options.utcoffset| (which defaults to UTC+01:00), the date string is adapted: >>> date.to_string(style='iso1', utcoffset=0) '1997-10-31T23:00:00+00:00' """ if not style: style = self.style if utcoffset is None: string = '' date = self.datetime else: sign = '+' if utcoffset >= 0 else '-' hours = abs(utcoffset // 60) minutes = abs(utcoffset % 60) string = f'{sign}{hours:02d}:{minutes:02d}' offset = utcoffset-hydpy.pub.options.utcoffset date = self.datetime + datetime.timedelta(minutes=offset) return date.strftime(self._formatstrings[style]) + string
python
def to_string(self, style=None, utcoffset=None): """Return a |str| object representing the actual date in accordance with the given style and the eventually given UTC offset (in minutes). Without any input arguments, the actual |Date.style| is used to return a date string in your local time zone: >>> from hydpy import Date >>> date = Date('01.11.1997 00:00:00') >>> date.to_string() '01.11.1997 00:00:00' Passing a style string affects the returned |str| object, but not the |Date.style| property: >>> date.style 'din1' >>> date.to_string(style='iso2') '1997-11-01 00:00:00' >>> date.style 'din1' When passing the `utcoffset` in minutes, the offset string is appended: >>> date.to_string(style='iso2', utcoffset=60) '1997-11-01 00:00:00+01:00' If the given offset does not correspond to your local offset defined by |Options.utcoffset| (which defaults to UTC+01:00), the date string is adapted: >>> date.to_string(style='iso1', utcoffset=0) '1997-10-31T23:00:00+00:00' """ if not style: style = self.style if utcoffset is None: string = '' date = self.datetime else: sign = '+' if utcoffset >= 0 else '-' hours = abs(utcoffset // 60) minutes = abs(utcoffset % 60) string = f'{sign}{hours:02d}:{minutes:02d}' offset = utcoffset-hydpy.pub.options.utcoffset date = self.datetime + datetime.timedelta(minutes=offset) return date.strftime(self._formatstrings[style]) + string
[ "def", "to_string", "(", "self", ",", "style", "=", "None", ",", "utcoffset", "=", "None", ")", ":", "if", "not", "style", ":", "style", "=", "self", ".", "style", "if", "utcoffset", "is", "None", ":", "string", "=", "''", "date", "=", "self", ".", "datetime", "else", ":", "sign", "=", "'+'", "if", "utcoffset", ">=", "0", "else", "'-'", "hours", "=", "abs", "(", "utcoffset", "//", "60", ")", "minutes", "=", "abs", "(", "utcoffset", "%", "60", ")", "string", "=", "f'{sign}{hours:02d}:{minutes:02d}'", "offset", "=", "utcoffset", "-", "hydpy", ".", "pub", ".", "options", ".", "utcoffset", "date", "=", "self", ".", "datetime", "+", "datetime", ".", "timedelta", "(", "minutes", "=", "offset", ")", "return", "date", ".", "strftime", "(", "self", ".", "_formatstrings", "[", "style", "]", ")", "+", "string" ]
Return a |str| object representing the actual date in accordance with the given style and the eventually given UTC offset (in minutes). Without any input arguments, the actual |Date.style| is used to return a date string in your local time zone: >>> from hydpy import Date >>> date = Date('01.11.1997 00:00:00') >>> date.to_string() '01.11.1997 00:00:00' Passing a style string affects the returned |str| object, but not the |Date.style| property: >>> date.style 'din1' >>> date.to_string(style='iso2') '1997-11-01 00:00:00' >>> date.style 'din1' When passing the `utcoffset` in minutes, the offset string is appended: >>> date.to_string(style='iso2', utcoffset=60) '1997-11-01 00:00:00+01:00' If the given offset does not correspond to your local offset defined by |Options.utcoffset| (which defaults to UTC+01:00), the date string is adapted: >>> date.to_string(style='iso1', utcoffset=0) '1997-10-31T23:00:00+00:00'
[ "Return", "a", "|str|", "object", "representing", "the", "actual", "date", "in", "accordance", "with", "the", "given", "style", "and", "the", "eventually", "given", "UTC", "offset", "(", "in", "minutes", ")", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L686-L734
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Period.fromseconds
def fromseconds(cls, seconds): """Return a |Period| instance based on a given number of seconds.""" try: seconds = int(seconds) except TypeError: seconds = int(seconds.flatten()[0]) return cls(datetime.timedelta(0, int(seconds)))
python
def fromseconds(cls, seconds): """Return a |Period| instance based on a given number of seconds.""" try: seconds = int(seconds) except TypeError: seconds = int(seconds.flatten()[0]) return cls(datetime.timedelta(0, int(seconds)))
[ "def", "fromseconds", "(", "cls", ",", "seconds", ")", ":", "try", ":", "seconds", "=", "int", "(", "seconds", ")", "except", "TypeError", ":", "seconds", "=", "int", "(", "seconds", ".", "flatten", "(", ")", "[", "0", "]", ")", "return", "cls", "(", "datetime", ".", "timedelta", "(", "0", ",", "int", "(", "seconds", ")", ")", ")" ]
Return a |Period| instance based on a given number of seconds.
[ "Return", "a", "|Period|", "instance", "based", "on", "a", "given", "number", "of", "seconds", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L945-L951
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Period._guessunit
def _guessunit(self): """Guess the unit of the period as the largest one, which results in an integer duration. """ if not self.days % 1: return 'd' elif not self.hours % 1: return 'h' elif not self.minutes % 1: return 'm' elif not self.seconds % 1: return 's' else: raise ValueError( 'The stepsize is not a multiple of one ' 'second, which is not allowed.')
python
def _guessunit(self): """Guess the unit of the period as the largest one, which results in an integer duration. """ if not self.days % 1: return 'd' elif not self.hours % 1: return 'h' elif not self.minutes % 1: return 'm' elif not self.seconds % 1: return 's' else: raise ValueError( 'The stepsize is not a multiple of one ' 'second, which is not allowed.')
[ "def", "_guessunit", "(", "self", ")", ":", "if", "not", "self", ".", "days", "%", "1", ":", "return", "'d'", "elif", "not", "self", ".", "hours", "%", "1", ":", "return", "'h'", "elif", "not", "self", ".", "minutes", "%", "1", ":", "return", "'m'", "elif", "not", "self", ".", "seconds", "%", "1", ":", "return", "'s'", "else", ":", "raise", "ValueError", "(", "'The stepsize is not a multiple of one '", "'second, which is not allowed.'", ")" ]
Guess the unit of the period as the largest one, which results in an integer duration.
[ "Guess", "the", "unit", "of", "the", "period", "as", "the", "largest", "one", "which", "results", "in", "an", "integer", "duration", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L972-L987
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Timegrid.from_array
def from_array(cls, array): """Returns a |Timegrid| instance based on two date and one period information stored in the first 13 rows of a |numpy.ndarray| object. """ try: return cls(Date.from_array(array[:6]), Date.from_array(array[6:12]), Period.fromseconds(array[12])) except IndexError: raise IndexError( f'To define a Timegrid instance via an array, 13 ' f'numbers are required. However, the given array ' f'consist of {len(array)} entries/rows only.')
python
def from_array(cls, array): """Returns a |Timegrid| instance based on two date and one period information stored in the first 13 rows of a |numpy.ndarray| object. """ try: return cls(Date.from_array(array[:6]), Date.from_array(array[6:12]), Period.fromseconds(array[12])) except IndexError: raise IndexError( f'To define a Timegrid instance via an array, 13 ' f'numbers are required. However, the given array ' f'consist of {len(array)} entries/rows only.')
[ "def", "from_array", "(", "cls", ",", "array", ")", ":", "try", ":", "return", "cls", "(", "Date", ".", "from_array", "(", "array", "[", ":", "6", "]", ")", ",", "Date", ".", "from_array", "(", "array", "[", "6", ":", "12", "]", ")", ",", "Period", ".", "fromseconds", "(", "array", "[", "12", "]", ")", ")", "except", "IndexError", ":", "raise", "IndexError", "(", "f'To define a Timegrid instance via an array, 13 '", "f'numbers are required. However, the given array '", "f'consist of {len(array)} entries/rows only.'", ")" ]
Returns a |Timegrid| instance based on two date and one period information stored in the first 13 rows of a |numpy.ndarray| object.
[ "Returns", "a", "|Timegrid|", "instance", "based", "on", "two", "date", "and", "one", "period", "information", "stored", "in", "the", "first", "13", "rows", "of", "a", "|numpy", ".", "ndarray|", "object", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L1285-L1297
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Timegrid.to_array
def to_array(self): """Returns a 1-dimensional |numpy| |numpy.ndarray| with thirteen entries first defining the start date, secondly defining the end date and thirdly the step size in seconds. """ values = numpy.empty(13, dtype=float) values[:6] = self.firstdate.to_array() values[6:12] = self.lastdate.to_array() values[12] = self.stepsize.seconds return values
python
def to_array(self): """Returns a 1-dimensional |numpy| |numpy.ndarray| with thirteen entries first defining the start date, secondly defining the end date and thirdly the step size in seconds. """ values = numpy.empty(13, dtype=float) values[:6] = self.firstdate.to_array() values[6:12] = self.lastdate.to_array() values[12] = self.stepsize.seconds return values
[ "def", "to_array", "(", "self", ")", ":", "values", "=", "numpy", ".", "empty", "(", "13", ",", "dtype", "=", "float", ")", "values", "[", ":", "6", "]", "=", "self", ".", "firstdate", ".", "to_array", "(", ")", "values", "[", "6", ":", "12", "]", "=", "self", ".", "lastdate", ".", "to_array", "(", ")", "values", "[", "12", "]", "=", "self", ".", "stepsize", ".", "seconds", "return", "values" ]
Returns a 1-dimensional |numpy| |numpy.ndarray| with thirteen entries first defining the start date, secondly defining the end date and thirdly the step size in seconds.
[ "Returns", "a", "1", "-", "dimensional", "|numpy|", "|numpy", ".", "ndarray|", "with", "thirteen", "entries", "first", "defining", "the", "start", "date", "secondly", "defining", "the", "end", "date", "and", "thirdly", "the", "step", "size", "in", "seconds", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L1299-L1308
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Timegrid.from_timepoints
def from_timepoints(cls, timepoints, refdate, unit='hours'): """Return a |Timegrid| object representing the given starting `timepoints` in relation to the given `refdate`. The following examples identical with the ones of |Timegrid.to_timepoints| but reversed. At least two given time points must be increasing and equidistant. By default, they are assumed in hours since the given reference date: >>> from hydpy import Timegrid >>> Timegrid.from_timepoints( ... [0.0, 6.0, 12.0, 18.0], '01.01.2000') Timegrid('01.01.2000 00:00:00', '02.01.2000 00:00:00', '6h') >>> Timegrid.from_timepoints( ... [24.0, 30.0, 36.0, 42.0], '1999-12-31') Timegrid('2000-01-01 00:00:00', '2000-01-02 00:00:00', '6h') Other time units (`days` or `min`) must be passed explicitely (only the first character counts): >>> Timegrid.from_timepoints( ... [0.0, 0.25, 0.5, 0.75], '01.01.2000', unit='d') Timegrid('01.01.2000 00:00:00', '02.01.2000 00:00:00', '6h') >>> Timegrid.from_timepoints( ... [1.0, 1.25, 1.5, 1.75], '1999-12-31', unit='day') Timegrid('2000-01-01 00:00:00', '2000-01-02 00:00:00', '6h') """ refdate = Date(refdate) unit = Period.from_cfunits(unit) delta = timepoints[1]-timepoints[0] firstdate = refdate+timepoints[0]*unit lastdate = refdate+(timepoints[-1]+delta)*unit stepsize = (lastdate-firstdate)/len(timepoints) return cls(firstdate, lastdate, stepsize)
python
def from_timepoints(cls, timepoints, refdate, unit='hours'): """Return a |Timegrid| object representing the given starting `timepoints` in relation to the given `refdate`. The following examples identical with the ones of |Timegrid.to_timepoints| but reversed. At least two given time points must be increasing and equidistant. By default, they are assumed in hours since the given reference date: >>> from hydpy import Timegrid >>> Timegrid.from_timepoints( ... [0.0, 6.0, 12.0, 18.0], '01.01.2000') Timegrid('01.01.2000 00:00:00', '02.01.2000 00:00:00', '6h') >>> Timegrid.from_timepoints( ... [24.0, 30.0, 36.0, 42.0], '1999-12-31') Timegrid('2000-01-01 00:00:00', '2000-01-02 00:00:00', '6h') Other time units (`days` or `min`) must be passed explicitely (only the first character counts): >>> Timegrid.from_timepoints( ... [0.0, 0.25, 0.5, 0.75], '01.01.2000', unit='d') Timegrid('01.01.2000 00:00:00', '02.01.2000 00:00:00', '6h') >>> Timegrid.from_timepoints( ... [1.0, 1.25, 1.5, 1.75], '1999-12-31', unit='day') Timegrid('2000-01-01 00:00:00', '2000-01-02 00:00:00', '6h') """ refdate = Date(refdate) unit = Period.from_cfunits(unit) delta = timepoints[1]-timepoints[0] firstdate = refdate+timepoints[0]*unit lastdate = refdate+(timepoints[-1]+delta)*unit stepsize = (lastdate-firstdate)/len(timepoints) return cls(firstdate, lastdate, stepsize)
[ "def", "from_timepoints", "(", "cls", ",", "timepoints", ",", "refdate", ",", "unit", "=", "'hours'", ")", ":", "refdate", "=", "Date", "(", "refdate", ")", "unit", "=", "Period", ".", "from_cfunits", "(", "unit", ")", "delta", "=", "timepoints", "[", "1", "]", "-", "timepoints", "[", "0", "]", "firstdate", "=", "refdate", "+", "timepoints", "[", "0", "]", "*", "unit", "lastdate", "=", "refdate", "+", "(", "timepoints", "[", "-", "1", "]", "+", "delta", ")", "*", "unit", "stepsize", "=", "(", "lastdate", "-", "firstdate", ")", "/", "len", "(", "timepoints", ")", "return", "cls", "(", "firstdate", ",", "lastdate", ",", "stepsize", ")" ]
Return a |Timegrid| object representing the given starting `timepoints` in relation to the given `refdate`. The following examples identical with the ones of |Timegrid.to_timepoints| but reversed. At least two given time points must be increasing and equidistant. By default, they are assumed in hours since the given reference date: >>> from hydpy import Timegrid >>> Timegrid.from_timepoints( ... [0.0, 6.0, 12.0, 18.0], '01.01.2000') Timegrid('01.01.2000 00:00:00', '02.01.2000 00:00:00', '6h') >>> Timegrid.from_timepoints( ... [24.0, 30.0, 36.0, 42.0], '1999-12-31') Timegrid('2000-01-01 00:00:00', '2000-01-02 00:00:00', '6h') Other time units (`days` or `min`) must be passed explicitely (only the first character counts): >>> Timegrid.from_timepoints( ... [0.0, 0.25, 0.5, 0.75], '01.01.2000', unit='d') Timegrid('01.01.2000 00:00:00', '02.01.2000 00:00:00', '6h') >>> Timegrid.from_timepoints( ... [1.0, 1.25, 1.5, 1.75], '1999-12-31', unit='day') Timegrid('2000-01-01 00:00:00', '2000-01-02 00:00:00', '6h')
[ "Return", "a", "|Timegrid|", "object", "representing", "the", "given", "starting", "timepoints", "in", "relation", "to", "the", "given", "refdate", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L1311-L1354
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Timegrid.to_timepoints
def to_timepoints(self, unit='hours', offset=None): """Return an |numpy.ndarray| representing the starting time points of the |Timegrid| object. The following examples identical with the ones of |Timegrid.from_timepoints| but reversed. By default, the time points are given in hours: >>> from hydpy import Timegrid >>> timegrid = Timegrid('2000-01-01', '2000-01-02', '6h') >>> timegrid.to_timepoints() array([ 0., 6., 12., 18.]) Other time units (`days` or `min`) can be defined (only the first character counts): >>> timegrid.to_timepoints(unit='d') array([ 0. , 0.25, 0.5 , 0.75]) Additionally, one can pass an `offset` that must be of type |int| or an valid |Period| initialization argument: >>> timegrid.to_timepoints(offset=24) array([ 24., 30., 36., 42.]) >>> timegrid.to_timepoints(offset='1d') array([ 24., 30., 36., 42.]) >>> timegrid.to_timepoints(unit='day', offset='1d') array([ 1. , 1.25, 1.5 , 1.75]) """ unit = Period.from_cfunits(unit) if offset is None: offset = 0. else: try: offset = Period(offset)/unit except TypeError: offset = offset step = self.stepsize/unit nmb = len(self) variable = numpy.linspace(offset, offset+step*(nmb-1), nmb) return variable
python
def to_timepoints(self, unit='hours', offset=None): """Return an |numpy.ndarray| representing the starting time points of the |Timegrid| object. The following examples identical with the ones of |Timegrid.from_timepoints| but reversed. By default, the time points are given in hours: >>> from hydpy import Timegrid >>> timegrid = Timegrid('2000-01-01', '2000-01-02', '6h') >>> timegrid.to_timepoints() array([ 0., 6., 12., 18.]) Other time units (`days` or `min`) can be defined (only the first character counts): >>> timegrid.to_timepoints(unit='d') array([ 0. , 0.25, 0.5 , 0.75]) Additionally, one can pass an `offset` that must be of type |int| or an valid |Period| initialization argument: >>> timegrid.to_timepoints(offset=24) array([ 24., 30., 36., 42.]) >>> timegrid.to_timepoints(offset='1d') array([ 24., 30., 36., 42.]) >>> timegrid.to_timepoints(unit='day', offset='1d') array([ 1. , 1.25, 1.5 , 1.75]) """ unit = Period.from_cfunits(unit) if offset is None: offset = 0. else: try: offset = Period(offset)/unit except TypeError: offset = offset step = self.stepsize/unit nmb = len(self) variable = numpy.linspace(offset, offset+step*(nmb-1), nmb) return variable
[ "def", "to_timepoints", "(", "self", ",", "unit", "=", "'hours'", ",", "offset", "=", "None", ")", ":", "unit", "=", "Period", ".", "from_cfunits", "(", "unit", ")", "if", "offset", "is", "None", ":", "offset", "=", "0.", "else", ":", "try", ":", "offset", "=", "Period", "(", "offset", ")", "/", "unit", "except", "TypeError", ":", "offset", "=", "offset", "step", "=", "self", ".", "stepsize", "/", "unit", "nmb", "=", "len", "(", "self", ")", "variable", "=", "numpy", ".", "linspace", "(", "offset", ",", "offset", "+", "step", "*", "(", "nmb", "-", "1", ")", ",", "nmb", ")", "return", "variable" ]
Return an |numpy.ndarray| representing the starting time points of the |Timegrid| object. The following examples identical with the ones of |Timegrid.from_timepoints| but reversed. By default, the time points are given in hours: >>> from hydpy import Timegrid >>> timegrid = Timegrid('2000-01-01', '2000-01-02', '6h') >>> timegrid.to_timepoints() array([ 0., 6., 12., 18.]) Other time units (`days` or `min`) can be defined (only the first character counts): >>> timegrid.to_timepoints(unit='d') array([ 0. , 0.25, 0.5 , 0.75]) Additionally, one can pass an `offset` that must be of type |int| or an valid |Period| initialization argument: >>> timegrid.to_timepoints(offset=24) array([ 24., 30., 36., 42.]) >>> timegrid.to_timepoints(offset='1d') array([ 24., 30., 36., 42.]) >>> timegrid.to_timepoints(unit='day', offset='1d') array([ 1. , 1.25, 1.5 , 1.75])
[ "Return", "an", "|numpy", ".", "ndarray|", "representing", "the", "starting", "time", "points", "of", "the", "|Timegrid|", "object", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L1356-L1397
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Timegrid.array2series
def array2series(self, array): """Prefix the information of the actual Timegrid object to the given array and return it. The Timegrid information is stored in the first thirteen values of the first axis of the returned series. Initialize a Timegrid object and apply its `array2series` method on a simple list containing numbers: >>> from hydpy import Timegrid >>> timegrid = Timegrid('2000-11-01 00:00', '2000-11-01 04:00', '1h') >>> series = timegrid.array2series([1, 2, 3.5, '5.0']) The first six entries contain the first date of the timegrid (year, month, day, hour, minute, second): >>> from hydpy import round_ >>> round_(series[:6]) 2000.0, 11.0, 1.0, 0.0, 0.0, 0.0 The six subsequent entries contain the last date: >>> round_(series[6:12]) 2000.0, 11.0, 1.0, 4.0, 0.0, 0.0 The thirteens value is the step size in seconds: >>> round_(series[12]) 3600.0 The last four value are the ones of the given vector: >>> round_(series[-4:]) 1.0, 2.0, 3.5, 5.0 The given array can have an arbitrary number of dimensions: >>> import numpy >>> array = numpy.eye(4) >>> series = timegrid.array2series(array) Now the timegrid information is stored in the first column: >>> round_(series[:13, 0]) 2000.0, 11.0, 1.0, 0.0, 0.0, 0.0, 2000.0, 11.0, 1.0, 4.0, 0.0, 0.0, \ 3600.0 All other columns of the first thirteen rows contain nan values, e.g.: >>> round_(series[12, :]) 3600.0, nan, nan, nan The original values are stored in the last four rows, e.g.: >>> round_(series[13, :]) 1.0, 0.0, 0.0, 0.0 Inappropriate array objects result in error messages like: >>> timegrid.array2series([[1, 2], [3]]) Traceback (most recent call last): ... ValueError: While trying to prefix timegrid information to the given \ array, the following error occurred: setting an array element with a sequence. If the given array does not fit to the defined timegrid, a special error message is returned: >>> timegrid.array2series([[1, 2], [3, 4]]) Traceback (most recent call last): ... ValueError: When converting an array to a sequence, the lengths of \ the timegrid and the given array must be equal, but the length of the \ timegrid object is `4` and the length of the array object is `2`. """ try: array = numpy.array(array, dtype=float) except BaseException: objecttools.augment_excmessage( 'While trying to prefix timegrid information to the ' 'given array') if len(array) != len(self): raise ValueError( f'When converting an array to a sequence, the lengths of the ' f'timegrid and the given array must be equal, but the length ' f'of the timegrid object is `{len(self)}` and the length of ' f'the array object is `{len(array)}`.') shape = list(array.shape) shape[0] += 13 series = numpy.full(shape, numpy.nan) slices = [slice(0, 13)] subshape = [13] for dummy in range(1, series.ndim): slices.append(slice(0, 1)) subshape.append(1) series[tuple(slices)] = self.to_array().reshape(subshape) series[13:] = array return series
python
def array2series(self, array): """Prefix the information of the actual Timegrid object to the given array and return it. The Timegrid information is stored in the first thirteen values of the first axis of the returned series. Initialize a Timegrid object and apply its `array2series` method on a simple list containing numbers: >>> from hydpy import Timegrid >>> timegrid = Timegrid('2000-11-01 00:00', '2000-11-01 04:00', '1h') >>> series = timegrid.array2series([1, 2, 3.5, '5.0']) The first six entries contain the first date of the timegrid (year, month, day, hour, minute, second): >>> from hydpy import round_ >>> round_(series[:6]) 2000.0, 11.0, 1.0, 0.0, 0.0, 0.0 The six subsequent entries contain the last date: >>> round_(series[6:12]) 2000.0, 11.0, 1.0, 4.0, 0.0, 0.0 The thirteens value is the step size in seconds: >>> round_(series[12]) 3600.0 The last four value are the ones of the given vector: >>> round_(series[-4:]) 1.0, 2.0, 3.5, 5.0 The given array can have an arbitrary number of dimensions: >>> import numpy >>> array = numpy.eye(4) >>> series = timegrid.array2series(array) Now the timegrid information is stored in the first column: >>> round_(series[:13, 0]) 2000.0, 11.0, 1.0, 0.0, 0.0, 0.0, 2000.0, 11.0, 1.0, 4.0, 0.0, 0.0, \ 3600.0 All other columns of the first thirteen rows contain nan values, e.g.: >>> round_(series[12, :]) 3600.0, nan, nan, nan The original values are stored in the last four rows, e.g.: >>> round_(series[13, :]) 1.0, 0.0, 0.0, 0.0 Inappropriate array objects result in error messages like: >>> timegrid.array2series([[1, 2], [3]]) Traceback (most recent call last): ... ValueError: While trying to prefix timegrid information to the given \ array, the following error occurred: setting an array element with a sequence. If the given array does not fit to the defined timegrid, a special error message is returned: >>> timegrid.array2series([[1, 2], [3, 4]]) Traceback (most recent call last): ... ValueError: When converting an array to a sequence, the lengths of \ the timegrid and the given array must be equal, but the length of the \ timegrid object is `4` and the length of the array object is `2`. """ try: array = numpy.array(array, dtype=float) except BaseException: objecttools.augment_excmessage( 'While trying to prefix timegrid information to the ' 'given array') if len(array) != len(self): raise ValueError( f'When converting an array to a sequence, the lengths of the ' f'timegrid and the given array must be equal, but the length ' f'of the timegrid object is `{len(self)}` and the length of ' f'the array object is `{len(array)}`.') shape = list(array.shape) shape[0] += 13 series = numpy.full(shape, numpy.nan) slices = [slice(0, 13)] subshape = [13] for dummy in range(1, series.ndim): slices.append(slice(0, 1)) subshape.append(1) series[tuple(slices)] = self.to_array().reshape(subshape) series[13:] = array return series
[ "def", "array2series", "(", "self", ",", "array", ")", ":", "try", ":", "array", "=", "numpy", ".", "array", "(", "array", ",", "dtype", "=", "float", ")", "except", "BaseException", ":", "objecttools", ".", "augment_excmessage", "(", "'While trying to prefix timegrid information to the '", "'given array'", ")", "if", "len", "(", "array", ")", "!=", "len", "(", "self", ")", ":", "raise", "ValueError", "(", "f'When converting an array to a sequence, the lengths of the '", "f'timegrid and the given array must be equal, but the length '", "f'of the timegrid object is `{len(self)}` and the length of '", "f'the array object is `{len(array)}`.'", ")", "shape", "=", "list", "(", "array", ".", "shape", ")", "shape", "[", "0", "]", "+=", "13", "series", "=", "numpy", ".", "full", "(", "shape", ",", "numpy", ".", "nan", ")", "slices", "=", "[", "slice", "(", "0", ",", "13", ")", "]", "subshape", "=", "[", "13", "]", "for", "dummy", "in", "range", "(", "1", ",", "series", ".", "ndim", ")", ":", "slices", ".", "append", "(", "slice", "(", "0", ",", "1", ")", ")", "subshape", ".", "append", "(", "1", ")", "series", "[", "tuple", "(", "slices", ")", "]", "=", "self", ".", "to_array", "(", ")", ".", "reshape", "(", "subshape", ")", "series", "[", "13", ":", "]", "=", "array", "return", "series" ]
Prefix the information of the actual Timegrid object to the given array and return it. The Timegrid information is stored in the first thirteen values of the first axis of the returned series. Initialize a Timegrid object and apply its `array2series` method on a simple list containing numbers: >>> from hydpy import Timegrid >>> timegrid = Timegrid('2000-11-01 00:00', '2000-11-01 04:00', '1h') >>> series = timegrid.array2series([1, 2, 3.5, '5.0']) The first six entries contain the first date of the timegrid (year, month, day, hour, minute, second): >>> from hydpy import round_ >>> round_(series[:6]) 2000.0, 11.0, 1.0, 0.0, 0.0, 0.0 The six subsequent entries contain the last date: >>> round_(series[6:12]) 2000.0, 11.0, 1.0, 4.0, 0.0, 0.0 The thirteens value is the step size in seconds: >>> round_(series[12]) 3600.0 The last four value are the ones of the given vector: >>> round_(series[-4:]) 1.0, 2.0, 3.5, 5.0 The given array can have an arbitrary number of dimensions: >>> import numpy >>> array = numpy.eye(4) >>> series = timegrid.array2series(array) Now the timegrid information is stored in the first column: >>> round_(series[:13, 0]) 2000.0, 11.0, 1.0, 0.0, 0.0, 0.0, 2000.0, 11.0, 1.0, 4.0, 0.0, 0.0, \ 3600.0 All other columns of the first thirteen rows contain nan values, e.g.: >>> round_(series[12, :]) 3600.0, nan, nan, nan The original values are stored in the last four rows, e.g.: >>> round_(series[13, :]) 1.0, 0.0, 0.0, 0.0 Inappropriate array objects result in error messages like: >>> timegrid.array2series([[1, 2], [3]]) Traceback (most recent call last): ... ValueError: While trying to prefix timegrid information to the given \ array, the following error occurred: setting an array element with a sequence. If the given array does not fit to the defined timegrid, a special error message is returned: >>> timegrid.array2series([[1, 2], [3, 4]]) Traceback (most recent call last): ... ValueError: When converting an array to a sequence, the lengths of \ the timegrid and the given array must be equal, but the length of the \ timegrid object is `4` and the length of the array object is `2`.
[ "Prefix", "the", "information", "of", "the", "actual", "Timegrid", "object", "to", "the", "given", "array", "and", "return", "it", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L1399-L1496
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Timegrid.verify
def verify(self): """Raise an |ValueError| if the dates or the step size of the time frame are inconsistent. """ if self.firstdate >= self.lastdate: raise ValueError( f'Unplausible timegrid. The first given date ' f'{self.firstdate}, the second given date is {self.lastdate}.') if (self.lastdate-self.firstdate) % self.stepsize: raise ValueError( f'Unplausible timegrid. The period span between the given ' f'dates {self.firstdate} and {self.lastdate} is not ' f'a multiple of the given step size {self.stepsize}.')
python
def verify(self): """Raise an |ValueError| if the dates or the step size of the time frame are inconsistent. """ if self.firstdate >= self.lastdate: raise ValueError( f'Unplausible timegrid. The first given date ' f'{self.firstdate}, the second given date is {self.lastdate}.') if (self.lastdate-self.firstdate) % self.stepsize: raise ValueError( f'Unplausible timegrid. The period span between the given ' f'dates {self.firstdate} and {self.lastdate} is not ' f'a multiple of the given step size {self.stepsize}.')
[ "def", "verify", "(", "self", ")", ":", "if", "self", ".", "firstdate", ">=", "self", ".", "lastdate", ":", "raise", "ValueError", "(", "f'Unplausible timegrid. The first given date '", "f'{self.firstdate}, the second given date is {self.lastdate}.'", ")", "if", "(", "self", ".", "lastdate", "-", "self", ".", "firstdate", ")", "%", "self", ".", "stepsize", ":", "raise", "ValueError", "(", "f'Unplausible timegrid. The period span between the given '", "f'dates {self.firstdate} and {self.lastdate} is not '", "f'a multiple of the given step size {self.stepsize}.'", ")" ]
Raise an |ValueError| if the dates or the step size of the time frame are inconsistent.
[ "Raise", "an", "|ValueError|", "if", "the", "dates", "or", "the", "step", "size", "of", "the", "time", "frame", "are", "inconsistent", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L1498-L1510
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Timegrid.assignrepr
def assignrepr(self, prefix, style=None, utcoffset=None): """Return a |repr| string with an prefixed assignement. Without option arguments given, printing the returned string looks like: >>> from hydpy import Timegrid >>> timegrid = Timegrid('1996-11-01 00:00:00', ... '1997-11-01 00:00:00', ... '1d') >>> print(timegrid.assignrepr(prefix='timegrid = ')) timegrid = Timegrid('1996-11-01 00:00:00', '1997-11-01 00:00:00', '1d') The optional arguments are passed to method |Date.to_repr| without any modifications: >>> print(timegrid.assignrepr( ... prefix='', style='iso1', utcoffset=120)) Timegrid('1996-11-01T01:00:00+02:00', '1997-11-01T01:00:00+02:00', '1d') """ skip = len(prefix) + 9 blanks = ' ' * skip return (f"{prefix}Timegrid('" f"{self.firstdate.to_string(style, utcoffset)}',\n" f"{blanks}'{self.lastdate.to_string(style, utcoffset)}',\n" f"{blanks}'{str(self.stepsize)}')")
python
def assignrepr(self, prefix, style=None, utcoffset=None): """Return a |repr| string with an prefixed assignement. Without option arguments given, printing the returned string looks like: >>> from hydpy import Timegrid >>> timegrid = Timegrid('1996-11-01 00:00:00', ... '1997-11-01 00:00:00', ... '1d') >>> print(timegrid.assignrepr(prefix='timegrid = ')) timegrid = Timegrid('1996-11-01 00:00:00', '1997-11-01 00:00:00', '1d') The optional arguments are passed to method |Date.to_repr| without any modifications: >>> print(timegrid.assignrepr( ... prefix='', style='iso1', utcoffset=120)) Timegrid('1996-11-01T01:00:00+02:00', '1997-11-01T01:00:00+02:00', '1d') """ skip = len(prefix) + 9 blanks = ' ' * skip return (f"{prefix}Timegrid('" f"{self.firstdate.to_string(style, utcoffset)}',\n" f"{blanks}'{self.lastdate.to_string(style, utcoffset)}',\n" f"{blanks}'{str(self.stepsize)}')")
[ "def", "assignrepr", "(", "self", ",", "prefix", ",", "style", "=", "None", ",", "utcoffset", "=", "None", ")", ":", "skip", "=", "len", "(", "prefix", ")", "+", "9", "blanks", "=", "' '", "*", "skip", "return", "(", "f\"{prefix}Timegrid('\"", "f\"{self.firstdate.to_string(style, utcoffset)}',\\n\"", "f\"{blanks}'{self.lastdate.to_string(style, utcoffset)}',\\n\"", "f\"{blanks}'{str(self.stepsize)}')\"", ")" ]
Return a |repr| string with an prefixed assignement. Without option arguments given, printing the returned string looks like: >>> from hydpy import Timegrid >>> timegrid = Timegrid('1996-11-01 00:00:00', ... '1997-11-01 00:00:00', ... '1d') >>> print(timegrid.assignrepr(prefix='timegrid = ')) timegrid = Timegrid('1996-11-01 00:00:00', '1997-11-01 00:00:00', '1d') The optional arguments are passed to method |Date.to_repr| without any modifications: >>> print(timegrid.assignrepr( ... prefix='', style='iso1', utcoffset=120)) Timegrid('1996-11-01T01:00:00+02:00', '1997-11-01T01:00:00+02:00', '1d')
[ "Return", "a", "|repr|", "string", "with", "an", "prefixed", "assignement", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L1562-L1591
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Timegrids.verify
def verify(self): """Raise an |ValueError| it the different time grids are inconsistent.""" self.init.verify() self.sim.verify() if self.init.firstdate > self.sim.firstdate: raise ValueError( f'The first date of the initialisation period ' f'({self.init.firstdate}) must not be later ' f'than the first date of the simulation period ' f'({self.sim.firstdate}).') elif self.init.lastdate < self.sim.lastdate: raise ValueError( f'The last date of the initialisation period ' f'({self.init.lastdate}) must not be earlier ' f'than the last date of the simulation period ' f'({self.sim.lastdate}).') elif self.init.stepsize != self.sim.stepsize: raise ValueError( f'The initialization stepsize ({self.init.stepsize}) ' f'must be identical with the simulation stepsize ' f'({self.sim.stepsize}).') else: try: self.init[self.sim.firstdate] except ValueError: raise ValueError( 'The simulation time grid is not properly ' 'alligned on the initialization time grid.')
python
def verify(self): """Raise an |ValueError| it the different time grids are inconsistent.""" self.init.verify() self.sim.verify() if self.init.firstdate > self.sim.firstdate: raise ValueError( f'The first date of the initialisation period ' f'({self.init.firstdate}) must not be later ' f'than the first date of the simulation period ' f'({self.sim.firstdate}).') elif self.init.lastdate < self.sim.lastdate: raise ValueError( f'The last date of the initialisation period ' f'({self.init.lastdate}) must not be earlier ' f'than the last date of the simulation period ' f'({self.sim.lastdate}).') elif self.init.stepsize != self.sim.stepsize: raise ValueError( f'The initialization stepsize ({self.init.stepsize}) ' f'must be identical with the simulation stepsize ' f'({self.sim.stepsize}).') else: try: self.init[self.sim.firstdate] except ValueError: raise ValueError( 'The simulation time grid is not properly ' 'alligned on the initialization time grid.')
[ "def", "verify", "(", "self", ")", ":", "self", ".", "init", ".", "verify", "(", ")", "self", ".", "sim", ".", "verify", "(", ")", "if", "self", ".", "init", ".", "firstdate", ">", "self", ".", "sim", ".", "firstdate", ":", "raise", "ValueError", "(", "f'The first date of the initialisation period '", "f'({self.init.firstdate}) must not be later '", "f'than the first date of the simulation period '", "f'({self.sim.firstdate}).'", ")", "elif", "self", ".", "init", ".", "lastdate", "<", "self", ".", "sim", ".", "lastdate", ":", "raise", "ValueError", "(", "f'The last date of the initialisation period '", "f'({self.init.lastdate}) must not be earlier '", "f'than the last date of the simulation period '", "f'({self.sim.lastdate}).'", ")", "elif", "self", ".", "init", ".", "stepsize", "!=", "self", ".", "sim", ".", "stepsize", ":", "raise", "ValueError", "(", "f'The initialization stepsize ({self.init.stepsize}) '", "f'must be identical with the simulation stepsize '", "f'({self.sim.stepsize}).'", ")", "else", ":", "try", ":", "self", ".", "init", "[", "self", ".", "sim", ".", "firstdate", "]", "except", "ValueError", ":", "raise", "ValueError", "(", "'The simulation time grid is not properly '", "'alligned on the initialization time grid.'", ")" ]
Raise an |ValueError| it the different time grids are inconsistent.
[ "Raise", "an", "|ValueError|", "it", "the", "different", "time", "grids", "are", "inconsistent", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L1786-L1814
train
hydpy-dev/hydpy
hydpy/core/timetools.py
Timegrids.assignrepr
def assignrepr(self, prefix): """Return a |repr| string with a prefixed assignment.""" caller = 'Timegrids(' blanks = ' ' * (len(prefix) + len(caller)) prefix = f'{prefix}{caller}' lines = [f'{self.init.assignrepr(prefix)},'] if self.sim != self.init: lines.append(f'{self.sim.assignrepr(blanks)},') lines[-1] = lines[-1][:-1] + ')' return '\n'.join(lines)
python
def assignrepr(self, prefix): """Return a |repr| string with a prefixed assignment.""" caller = 'Timegrids(' blanks = ' ' * (len(prefix) + len(caller)) prefix = f'{prefix}{caller}' lines = [f'{self.init.assignrepr(prefix)},'] if self.sim != self.init: lines.append(f'{self.sim.assignrepr(blanks)},') lines[-1] = lines[-1][:-1] + ')' return '\n'.join(lines)
[ "def", "assignrepr", "(", "self", ",", "prefix", ")", ":", "caller", "=", "'Timegrids('", "blanks", "=", "' '", "*", "(", "len", "(", "prefix", ")", "+", "len", "(", "caller", ")", ")", "prefix", "=", "f'{prefix}{caller}'", "lines", "=", "[", "f'{self.init.assignrepr(prefix)},'", "]", "if", "self", ".", "sim", "!=", "self", ".", "init", ":", "lines", ".", "append", "(", "f'{self.sim.assignrepr(blanks)},'", ")", "lines", "[", "-", "1", "]", "=", "lines", "[", "-", "1", "]", "[", ":", "-", "1", "]", "+", "')'", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
Return a |repr| string with a prefixed assignment.
[ "Return", "a", "|repr|", "string", "with", "a", "prefixed", "assignment", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L1847-L1856
train
hydpy-dev/hydpy
hydpy/core/timetools.py
TOY.seconds_passed
def seconds_passed(self): """Amount of time passed in seconds since the beginning of the year. In the first example, the year is only one minute and thirty seconds old: >>> from hydpy.core.timetools import TOY >>> TOY('1_1_0_1_30').seconds_passed 90 The second example shows that the 29th February is generally included: >>> TOY('3').seconds_passed 5184000 """ return int((Date(self).datetime - self._STARTDATE.datetime).total_seconds())
python
def seconds_passed(self): """Amount of time passed in seconds since the beginning of the year. In the first example, the year is only one minute and thirty seconds old: >>> from hydpy.core.timetools import TOY >>> TOY('1_1_0_1_30').seconds_passed 90 The second example shows that the 29th February is generally included: >>> TOY('3').seconds_passed 5184000 """ return int((Date(self).datetime - self._STARTDATE.datetime).total_seconds())
[ "def", "seconds_passed", "(", "self", ")", ":", "return", "int", "(", "(", "Date", "(", "self", ")", ".", "datetime", "-", "self", ".", "_STARTDATE", ".", "datetime", ")", ".", "total_seconds", "(", ")", ")" ]
Amount of time passed in seconds since the beginning of the year. In the first example, the year is only one minute and thirty seconds old: >>> from hydpy.core.timetools import TOY >>> TOY('1_1_0_1_30').seconds_passed 90 The second example shows that the 29th February is generally included: >>> TOY('3').seconds_passed 5184000
[ "Amount", "of", "time", "passed", "in", "seconds", "since", "the", "beginning", "of", "the", "year", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L2080-L2096
train
hydpy-dev/hydpy
hydpy/core/timetools.py
TOY.seconds_left
def seconds_left(self): """Remaining part of the year in seconds. In the first example, only one minute and thirty seconds of the year remain: >>> from hydpy.core.timetools import TOY >>> TOY('12_31_23_58_30').seconds_left 90 The second example shows that the 29th February is generally included: >>> TOY('2').seconds_left 28944000 """ return int((self._ENDDATE.datetime - Date(self).datetime).total_seconds())
python
def seconds_left(self): """Remaining part of the year in seconds. In the first example, only one minute and thirty seconds of the year remain: >>> from hydpy.core.timetools import TOY >>> TOY('12_31_23_58_30').seconds_left 90 The second example shows that the 29th February is generally included: >>> TOY('2').seconds_left 28944000 """ return int((self._ENDDATE.datetime - Date(self).datetime).total_seconds())
[ "def", "seconds_left", "(", "self", ")", ":", "return", "int", "(", "(", "self", ".", "_ENDDATE", ".", "datetime", "-", "Date", "(", "self", ")", ".", "datetime", ")", ".", "total_seconds", "(", ")", ")" ]
Remaining part of the year in seconds. In the first example, only one minute and thirty seconds of the year remain: >>> from hydpy.core.timetools import TOY >>> TOY('12_31_23_58_30').seconds_left 90 The second example shows that the 29th February is generally included: >>> TOY('2').seconds_left 28944000
[ "Remaining", "part", "of", "the", "year", "in", "seconds", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L2099-L2115
train
hydpy-dev/hydpy
hydpy/core/timetools.py
TOY.centred_timegrid
def centred_timegrid(cls, simulationstep): """Return a |Timegrid| object defining the central time points of the year 2000 for the given simulation step. >>> from hydpy.core.timetools import TOY >>> TOY.centred_timegrid('1d') Timegrid('2000-01-01 12:00:00', '2001-01-01 12:00:00', '1d') """ simulationstep = Period(simulationstep) return Timegrid( cls._STARTDATE+simulationstep/2, cls._ENDDATE+simulationstep/2, simulationstep)
python
def centred_timegrid(cls, simulationstep): """Return a |Timegrid| object defining the central time points of the year 2000 for the given simulation step. >>> from hydpy.core.timetools import TOY >>> TOY.centred_timegrid('1d') Timegrid('2000-01-01 12:00:00', '2001-01-01 12:00:00', '1d') """ simulationstep = Period(simulationstep) return Timegrid( cls._STARTDATE+simulationstep/2, cls._ENDDATE+simulationstep/2, simulationstep)
[ "def", "centred_timegrid", "(", "cls", ",", "simulationstep", ")", ":", "simulationstep", "=", "Period", "(", "simulationstep", ")", "return", "Timegrid", "(", "cls", ".", "_STARTDATE", "+", "simulationstep", "/", "2", ",", "cls", ".", "_ENDDATE", "+", "simulationstep", "/", "2", ",", "simulationstep", ")" ]
Return a |Timegrid| object defining the central time points of the year 2000 for the given simulation step. >>> from hydpy.core.timetools import TOY >>> TOY.centred_timegrid('1d') Timegrid('2000-01-01 12:00:00', '2001-01-01 12:00:00', '1d')
[ "Return", "a", "|Timegrid|", "object", "defining", "the", "central", "time", "points", "of", "the", "year", "2000", "for", "the", "given", "simulation", "step", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/timetools.py#L2118-L2132
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
dir_
def dir_(self): """The prefered way for HydPy objects to respond to |dir|. Note the depencence on the `pub.options.dirverbose`. If this option is set `True`, all attributes and methods of the given instance and its class (including those inherited from the parent classes) are returned: >>> from hydpy import pub >>> pub.options.dirverbose = True >>> from hydpy.core.objecttools import dir_ >>> class Test(object): ... only_public_attribute = None >>> print(len(dir_(Test())) > 1) # Long list, try it yourself... True If the option is set to `False`, only the `public` attributes and methods (which do need begin with `_`) are returned: >>> pub.options.dirverbose = False >>> print(dir_(Test())) # Short list with one single entry... ['only_public_attribute'] If none of those does exists, |dir_| returns a list with a single string containing a single empty space (which seems to work better for most IDEs than returning an emtpy list): >>> del Test.only_public_attribute >>> print(dir_(Test())) [' '] """ names = set() for thing in list(inspect.getmro(type(self))) + [self]: for key in vars(thing).keys(): if hydpy.pub.options.dirverbose or not key.startswith('_'): names.add(key) if names: names = list(names) else: names = [' '] return names
python
def dir_(self): """The prefered way for HydPy objects to respond to |dir|. Note the depencence on the `pub.options.dirverbose`. If this option is set `True`, all attributes and methods of the given instance and its class (including those inherited from the parent classes) are returned: >>> from hydpy import pub >>> pub.options.dirverbose = True >>> from hydpy.core.objecttools import dir_ >>> class Test(object): ... only_public_attribute = None >>> print(len(dir_(Test())) > 1) # Long list, try it yourself... True If the option is set to `False`, only the `public` attributes and methods (which do need begin with `_`) are returned: >>> pub.options.dirverbose = False >>> print(dir_(Test())) # Short list with one single entry... ['only_public_attribute'] If none of those does exists, |dir_| returns a list with a single string containing a single empty space (which seems to work better for most IDEs than returning an emtpy list): >>> del Test.only_public_attribute >>> print(dir_(Test())) [' '] """ names = set() for thing in list(inspect.getmro(type(self))) + [self]: for key in vars(thing).keys(): if hydpy.pub.options.dirverbose or not key.startswith('_'): names.add(key) if names: names = list(names) else: names = [' '] return names
[ "def", "dir_", "(", "self", ")", ":", "names", "=", "set", "(", ")", "for", "thing", "in", "list", "(", "inspect", ".", "getmro", "(", "type", "(", "self", ")", ")", ")", "+", "[", "self", "]", ":", "for", "key", "in", "vars", "(", "thing", ")", ".", "keys", "(", ")", ":", "if", "hydpy", ".", "pub", ".", "options", ".", "dirverbose", "or", "not", "key", ".", "startswith", "(", "'_'", ")", ":", "names", ".", "add", "(", "key", ")", "if", "names", ":", "names", "=", "list", "(", "names", ")", "else", ":", "names", "=", "[", "' '", "]", "return", "names" ]
The prefered way for HydPy objects to respond to |dir|. Note the depencence on the `pub.options.dirverbose`. If this option is set `True`, all attributes and methods of the given instance and its class (including those inherited from the parent classes) are returned: >>> from hydpy import pub >>> pub.options.dirverbose = True >>> from hydpy.core.objecttools import dir_ >>> class Test(object): ... only_public_attribute = None >>> print(len(dir_(Test())) > 1) # Long list, try it yourself... True If the option is set to `False`, only the `public` attributes and methods (which do need begin with `_`) are returned: >>> pub.options.dirverbose = False >>> print(dir_(Test())) # Short list with one single entry... ['only_public_attribute'] If none of those does exists, |dir_| returns a list with a single string containing a single empty space (which seems to work better for most IDEs than returning an emtpy list): >>> del Test.only_public_attribute >>> print(dir_(Test())) [' ']
[ "The", "prefered", "way", "for", "HydPy", "objects", "to", "respond", "to", "|dir|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L20-L59
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
classname
def classname(self): """Return the class name of the given instance object or class. >>> from hydpy.core.objecttools import classname >>> from hydpy import pub >>> print(classname(float)) float >>> print(classname(pub.options)) Options """ if inspect.isclass(self): string = str(self) else: string = str(type(self)) try: string = string.split("'")[1] except IndexError: pass return string.split('.')[-1]
python
def classname(self): """Return the class name of the given instance object or class. >>> from hydpy.core.objecttools import classname >>> from hydpy import pub >>> print(classname(float)) float >>> print(classname(pub.options)) Options """ if inspect.isclass(self): string = str(self) else: string = str(type(self)) try: string = string.split("'")[1] except IndexError: pass return string.split('.')[-1]
[ "def", "classname", "(", "self", ")", ":", "if", "inspect", ".", "isclass", "(", "self", ")", ":", "string", "=", "str", "(", "self", ")", "else", ":", "string", "=", "str", "(", "type", "(", "self", ")", ")", "try", ":", "string", "=", "string", ".", "split", "(", "\"'\"", ")", "[", "1", "]", "except", "IndexError", ":", "pass", "return", "string", ".", "split", "(", "'.'", ")", "[", "-", "1", "]" ]
Return the class name of the given instance object or class. >>> from hydpy.core.objecttools import classname >>> from hydpy import pub >>> print(classname(float)) float >>> print(classname(pub.options)) Options
[ "Return", "the", "class", "name", "of", "the", "given", "instance", "object", "or", "class", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L62-L80
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
name
def name(self): """Name of the class of the given instance in lower case letters. This function is thought to be implemented as a property. Otherwise it would violate the principle not to access or manipulate private attributes ("_name"): >>> from hydpy.core.objecttools import name >>> class Test(object): ... name = property(name) >>> test1 = Test() >>> test1.name 'test' >>> test1._name 'test' The private attribute is added for performance reasons only. Note that it is a class attribute: >>> test2 = Test() >>> test2._name 'test' """ cls = type(self) try: return cls.__dict__['_name'] except KeyError: setattr(cls, '_name', instancename(self)) return cls.__dict__['_name']
python
def name(self): """Name of the class of the given instance in lower case letters. This function is thought to be implemented as a property. Otherwise it would violate the principle not to access or manipulate private attributes ("_name"): >>> from hydpy.core.objecttools import name >>> class Test(object): ... name = property(name) >>> test1 = Test() >>> test1.name 'test' >>> test1._name 'test' The private attribute is added for performance reasons only. Note that it is a class attribute: >>> test2 = Test() >>> test2._name 'test' """ cls = type(self) try: return cls.__dict__['_name'] except KeyError: setattr(cls, '_name', instancename(self)) return cls.__dict__['_name']
[ "def", "name", "(", "self", ")", ":", "cls", "=", "type", "(", "self", ")", "try", ":", "return", "cls", ".", "__dict__", "[", "'_name'", "]", "except", "KeyError", ":", "setattr", "(", "cls", ",", "'_name'", ",", "instancename", "(", "self", ")", ")", "return", "cls", ".", "__dict__", "[", "'_name'", "]" ]
Name of the class of the given instance in lower case letters. This function is thought to be implemented as a property. Otherwise it would violate the principle not to access or manipulate private attributes ("_name"): >>> from hydpy.core.objecttools import name >>> class Test(object): ... name = property(name) >>> test1 = Test() >>> test1.name 'test' >>> test1._name 'test' The private attribute is added for performance reasons only. Note that it is a class attribute: >>> test2 = Test() >>> test2._name 'test'
[ "Name", "of", "the", "class", "of", "the", "given", "instance", "in", "lower", "case", "letters", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L109-L137
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
valid_variable_identifier
def valid_variable_identifier(string): """Raises an |ValueError| if the given name is not a valid Python identifier. For example, the string `test_1` (with underscore) is valid... >>> from hydpy.core.objecttools import valid_variable_identifier >>> valid_variable_identifier('test_1') ...but the string `test 1` (with white space) is not: >>> valid_variable_identifier('test 1') Traceback (most recent call last): ... ValueError: The given name string `test 1` does not define a valid \ variable identifier. Valid identifiers do not contain characters like \ `-` or empty spaces, do not start with numbers, cannot be mistaken with \ Python built-ins like `for`...) Also, names of Python built ins are not allowed: >>> valid_variable_identifier('print') # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: The given name string `print` does not define... """ string = str(string) try: exec('%s = None' % string) if string in dir(builtins): raise SyntaxError() except SyntaxError: raise ValueError( 'The given name string `%s` does not define a valid variable ' 'identifier. Valid identifiers do not contain characters like ' '`-` or empty spaces, do not start with numbers, cannot be ' 'mistaken with Python built-ins like `for`...)' % string)
python
def valid_variable_identifier(string): """Raises an |ValueError| if the given name is not a valid Python identifier. For example, the string `test_1` (with underscore) is valid... >>> from hydpy.core.objecttools import valid_variable_identifier >>> valid_variable_identifier('test_1') ...but the string `test 1` (with white space) is not: >>> valid_variable_identifier('test 1') Traceback (most recent call last): ... ValueError: The given name string `test 1` does not define a valid \ variable identifier. Valid identifiers do not contain characters like \ `-` or empty spaces, do not start with numbers, cannot be mistaken with \ Python built-ins like `for`...) Also, names of Python built ins are not allowed: >>> valid_variable_identifier('print') # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: The given name string `print` does not define... """ string = str(string) try: exec('%s = None' % string) if string in dir(builtins): raise SyntaxError() except SyntaxError: raise ValueError( 'The given name string `%s` does not define a valid variable ' 'identifier. Valid identifiers do not contain characters like ' '`-` or empty spaces, do not start with numbers, cannot be ' 'mistaken with Python built-ins like `for`...)' % string)
[ "def", "valid_variable_identifier", "(", "string", ")", ":", "string", "=", "str", "(", "string", ")", "try", ":", "exec", "(", "'%s = None'", "%", "string", ")", "if", "string", "in", "dir", "(", "builtins", ")", ":", "raise", "SyntaxError", "(", ")", "except", "SyntaxError", ":", "raise", "ValueError", "(", "'The given name string `%s` does not define a valid variable '", "'identifier. Valid identifiers do not contain characters like '", "'`-` or empty spaces, do not start with numbers, cannot be '", "'mistaken with Python built-ins like `for`...)'", "%", "string", ")" ]
Raises an |ValueError| if the given name is not a valid Python identifier. For example, the string `test_1` (with underscore) is valid... >>> from hydpy.core.objecttools import valid_variable_identifier >>> valid_variable_identifier('test_1') ...but the string `test 1` (with white space) is not: >>> valid_variable_identifier('test 1') Traceback (most recent call last): ... ValueError: The given name string `test 1` does not define a valid \ variable identifier. Valid identifiers do not contain characters like \ `-` or empty spaces, do not start with numbers, cannot be mistaken with \ Python built-ins like `for`...) Also, names of Python built ins are not allowed: >>> valid_variable_identifier('print') # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: The given name string `print` does not define...
[ "Raises", "an", "|ValueError|", "if", "the", "given", "name", "is", "not", "a", "valid", "Python", "identifier", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L272-L309
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
augment_excmessage
def augment_excmessage(prefix=None, suffix=None) -> NoReturn: """Augment an exception message with additional information while keeping the original traceback. You can prefix and/or suffix text. If you prefix something (which happens much more often in the HydPy framework), the sub-clause ', the following error occurred:' is automatically included: >>> from hydpy.core import objecttools >>> import textwrap >>> try: ... 1 + '1' ... except BaseException: ... prefix = 'While showing how prefixing works' ... suffix = '(This is a final remark.)' ... objecttools.augment_excmessage(prefix, suffix) Traceback (most recent call last): ... TypeError: While showing how prefixing works, the following error \ occurred: unsupported operand type(s) for +: 'int' and 'str' \ (This is a final remark.) Some exceptions derived by site-packages do not support exception chaining due to requiring multiple initialisation arguments. In such cases, |augment_excmessage| generates an exception with the same name on the fly and raises it afterwards, which is pointed out by the exception name mentioning to the "objecttools" module: >>> class WrongError(BaseException): ... def __init__(self, arg1, arg2): ... pass >>> try: ... raise WrongError('info 1', 'info 2') ... except BaseException: ... objecttools.augment_excmessage( ... 'While showing how prefixing works') Traceback (most recent call last): ... hydpy.core.objecttools.hydpy.core.objecttools.WrongError: While showing \ how prefixing works, the following error occurred: ('info 1', 'info 2') """ exc_old = sys.exc_info()[1] message = str(exc_old) if prefix is not None: message = f'{prefix}, the following error occurred: {message}' if suffix is not None: message = f'{message} {suffix}' try: exc_new = type(exc_old)(message) except BaseException: exc_name = str(type(exc_old)).split("'")[1] exc_type = type(exc_name, (BaseException,), {}) exc_type.__module = exc_old.__module__ raise exc_type(message) from exc_old raise exc_new from exc_old
python
def augment_excmessage(prefix=None, suffix=None) -> NoReturn: """Augment an exception message with additional information while keeping the original traceback. You can prefix and/or suffix text. If you prefix something (which happens much more often in the HydPy framework), the sub-clause ', the following error occurred:' is automatically included: >>> from hydpy.core import objecttools >>> import textwrap >>> try: ... 1 + '1' ... except BaseException: ... prefix = 'While showing how prefixing works' ... suffix = '(This is a final remark.)' ... objecttools.augment_excmessage(prefix, suffix) Traceback (most recent call last): ... TypeError: While showing how prefixing works, the following error \ occurred: unsupported operand type(s) for +: 'int' and 'str' \ (This is a final remark.) Some exceptions derived by site-packages do not support exception chaining due to requiring multiple initialisation arguments. In such cases, |augment_excmessage| generates an exception with the same name on the fly and raises it afterwards, which is pointed out by the exception name mentioning to the "objecttools" module: >>> class WrongError(BaseException): ... def __init__(self, arg1, arg2): ... pass >>> try: ... raise WrongError('info 1', 'info 2') ... except BaseException: ... objecttools.augment_excmessage( ... 'While showing how prefixing works') Traceback (most recent call last): ... hydpy.core.objecttools.hydpy.core.objecttools.WrongError: While showing \ how prefixing works, the following error occurred: ('info 1', 'info 2') """ exc_old = sys.exc_info()[1] message = str(exc_old) if prefix is not None: message = f'{prefix}, the following error occurred: {message}' if suffix is not None: message = f'{message} {suffix}' try: exc_new = type(exc_old)(message) except BaseException: exc_name = str(type(exc_old)).split("'")[1] exc_type = type(exc_name, (BaseException,), {}) exc_type.__module = exc_old.__module__ raise exc_type(message) from exc_old raise exc_new from exc_old
[ "def", "augment_excmessage", "(", "prefix", "=", "None", ",", "suffix", "=", "None", ")", "->", "NoReturn", ":", "exc_old", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "message", "=", "str", "(", "exc_old", ")", "if", "prefix", "is", "not", "None", ":", "message", "=", "f'{prefix}, the following error occurred: {message}'", "if", "suffix", "is", "not", "None", ":", "message", "=", "f'{message} {suffix}'", "try", ":", "exc_new", "=", "type", "(", "exc_old", ")", "(", "message", ")", "except", "BaseException", ":", "exc_name", "=", "str", "(", "type", "(", "exc_old", ")", ")", ".", "split", "(", "\"'\"", ")", "[", "1", "]", "exc_type", "=", "type", "(", "exc_name", ",", "(", "BaseException", ",", ")", ",", "{", "}", ")", "exc_type", ".", "__module", "=", "exc_old", ".", "__module__", "raise", "exc_type", "(", "message", ")", "from", "exc_old", "raise", "exc_new", "from", "exc_old" ]
Augment an exception message with additional information while keeping the original traceback. You can prefix and/or suffix text. If you prefix something (which happens much more often in the HydPy framework), the sub-clause ', the following error occurred:' is automatically included: >>> from hydpy.core import objecttools >>> import textwrap >>> try: ... 1 + '1' ... except BaseException: ... prefix = 'While showing how prefixing works' ... suffix = '(This is a final remark.)' ... objecttools.augment_excmessage(prefix, suffix) Traceback (most recent call last): ... TypeError: While showing how prefixing works, the following error \ occurred: unsupported operand type(s) for +: 'int' and 'str' \ (This is a final remark.) Some exceptions derived by site-packages do not support exception chaining due to requiring multiple initialisation arguments. In such cases, |augment_excmessage| generates an exception with the same name on the fly and raises it afterwards, which is pointed out by the exception name mentioning to the "objecttools" module: >>> class WrongError(BaseException): ... def __init__(self, arg1, arg2): ... pass >>> try: ... raise WrongError('info 1', 'info 2') ... except BaseException: ... objecttools.augment_excmessage( ... 'While showing how prefixing works') Traceback (most recent call last): ... hydpy.core.objecttools.hydpy.core.objecttools.WrongError: While showing \ how prefixing works, the following error occurred: ('info 1', 'info 2')
[ "Augment", "an", "exception", "message", "with", "additional", "information", "while", "keeping", "the", "original", "traceback", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L312-L366
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
excmessage_decorator
def excmessage_decorator(description) -> Callable: """Wrap a function with |augment_excmessage|. Function |excmessage_decorator| is a means to apply function |augment_excmessage| more efficiently. Suppose you would apply function |augment_excmessage| in a function that adds and returns to numbers: >>> from hydpy.core import objecttools >>> def add(x, y): ... try: ... return x + y ... except BaseException: ... objecttools.augment_excmessage( ... 'While trying to add `x` and `y`') This works as excepted... >>> add(1, 2) 3 >>> add(1, []) Traceback (most recent call last): ... TypeError: While trying to add `x` and `y`, the following error \ occurred: unsupported operand type(s) for +: 'int' and 'list' ...but can be achieved with much less code using |excmessage_decorator|: >>> @objecttools.excmessage_decorator( ... 'add `x` and `y`') ... def add(x, y): ... return x+y >>> add(1, 2) 3 >>> add(1, []) Traceback (most recent call last): ... TypeError: While trying to add `x` and `y`, the following error \ occurred: unsupported operand type(s) for +: 'int' and 'list' Additionally, exception messages related to wrong function calls are now also augmented: >>> add(1) Traceback (most recent call last): ... TypeError: While trying to add `x` and `y`, the following error \ occurred: add() missing 1 required positional argument: 'y' |excmessage_decorator| evaluates the given string like an f-string, allowing to mention the argument values of the called function and to make use of all string modification functions provided by modules |objecttools|: >>> @objecttools.excmessage_decorator( ... 'add `x` ({repr_(x, 2)}) and `y` ({repr_(y, 2)})') ... def add(x, y): ... return x+y >>> add(1.1111, 'wrong') Traceback (most recent call last): ... TypeError: While trying to add `x` (1.11) and `y` (wrong), the following \ error occurred: unsupported operand type(s) for +: 'float' and 'str' >>> add(1) Traceback (most recent call last): ... TypeError: While trying to add `x` (1) and `y` (?), the following error \ occurred: add() missing 1 required positional argument: 'y' >>> add(y=1) Traceback (most recent call last): ... TypeError: While trying to add `x` (?) and `y` (1), the following error \ occurred: add() missing 1 required positional argument: 'x' Apply |excmessage_decorator| on methods also works fine: >>> class Adder: ... def __init__(self): ... self.value = 0 ... @objecttools.excmessage_decorator( ... 'add an instance of class `{classname(self)}` with value ' ... '`{repr_(other, 2)}` of type `{classname(other)}`') ... def __iadd__(self, other): ... self.value += other ... return self >>> adder = Adder() >>> adder += 1 >>> adder.value 1 >>> adder += 'wrong' Traceback (most recent call last): ... TypeError: While trying to add an instance of class `Adder` with value \ `wrong` of type `str`, the following error occurred: unsupported operand \ type(s) for +=: 'int' and 'str' It is made sure that no information of the decorated function is lost: >>> add.__name__ 'add' """ @wrapt.decorator def wrapper(wrapped, instance, args, kwargs): """Apply |augment_excmessage| when the wrapped function fails.""" # pylint: disable=unused-argument try: return wrapped(*args, **kwargs) except BaseException: info = kwargs.copy() info['self'] = instance argnames = inspect.getfullargspec(wrapped).args if argnames[0] == 'self': argnames = argnames[1:] for argname, arg in zip(argnames, args): info[argname] = arg for argname in argnames: if argname not in info: info[argname] = '?' message = eval( f"f'While trying to {description}'", globals(), info) augment_excmessage(message) return wrapper
python
def excmessage_decorator(description) -> Callable: """Wrap a function with |augment_excmessage|. Function |excmessage_decorator| is a means to apply function |augment_excmessage| more efficiently. Suppose you would apply function |augment_excmessage| in a function that adds and returns to numbers: >>> from hydpy.core import objecttools >>> def add(x, y): ... try: ... return x + y ... except BaseException: ... objecttools.augment_excmessage( ... 'While trying to add `x` and `y`') This works as excepted... >>> add(1, 2) 3 >>> add(1, []) Traceback (most recent call last): ... TypeError: While trying to add `x` and `y`, the following error \ occurred: unsupported operand type(s) for +: 'int' and 'list' ...but can be achieved with much less code using |excmessage_decorator|: >>> @objecttools.excmessage_decorator( ... 'add `x` and `y`') ... def add(x, y): ... return x+y >>> add(1, 2) 3 >>> add(1, []) Traceback (most recent call last): ... TypeError: While trying to add `x` and `y`, the following error \ occurred: unsupported operand type(s) for +: 'int' and 'list' Additionally, exception messages related to wrong function calls are now also augmented: >>> add(1) Traceback (most recent call last): ... TypeError: While trying to add `x` and `y`, the following error \ occurred: add() missing 1 required positional argument: 'y' |excmessage_decorator| evaluates the given string like an f-string, allowing to mention the argument values of the called function and to make use of all string modification functions provided by modules |objecttools|: >>> @objecttools.excmessage_decorator( ... 'add `x` ({repr_(x, 2)}) and `y` ({repr_(y, 2)})') ... def add(x, y): ... return x+y >>> add(1.1111, 'wrong') Traceback (most recent call last): ... TypeError: While trying to add `x` (1.11) and `y` (wrong), the following \ error occurred: unsupported operand type(s) for +: 'float' and 'str' >>> add(1) Traceback (most recent call last): ... TypeError: While trying to add `x` (1) and `y` (?), the following error \ occurred: add() missing 1 required positional argument: 'y' >>> add(y=1) Traceback (most recent call last): ... TypeError: While trying to add `x` (?) and `y` (1), the following error \ occurred: add() missing 1 required positional argument: 'x' Apply |excmessage_decorator| on methods also works fine: >>> class Adder: ... def __init__(self): ... self.value = 0 ... @objecttools.excmessage_decorator( ... 'add an instance of class `{classname(self)}` with value ' ... '`{repr_(other, 2)}` of type `{classname(other)}`') ... def __iadd__(self, other): ... self.value += other ... return self >>> adder = Adder() >>> adder += 1 >>> adder.value 1 >>> adder += 'wrong' Traceback (most recent call last): ... TypeError: While trying to add an instance of class `Adder` with value \ `wrong` of type `str`, the following error occurred: unsupported operand \ type(s) for +=: 'int' and 'str' It is made sure that no information of the decorated function is lost: >>> add.__name__ 'add' """ @wrapt.decorator def wrapper(wrapped, instance, args, kwargs): """Apply |augment_excmessage| when the wrapped function fails.""" # pylint: disable=unused-argument try: return wrapped(*args, **kwargs) except BaseException: info = kwargs.copy() info['self'] = instance argnames = inspect.getfullargspec(wrapped).args if argnames[0] == 'self': argnames = argnames[1:] for argname, arg in zip(argnames, args): info[argname] = arg for argname in argnames: if argname not in info: info[argname] = '?' message = eval( f"f'While trying to {description}'", globals(), info) augment_excmessage(message) return wrapper
[ "def", "excmessage_decorator", "(", "description", ")", "->", "Callable", ":", "@", "wrapt", ".", "decorator", "def", "wrapper", "(", "wrapped", ",", "instance", ",", "args", ",", "kwargs", ")", ":", "\"\"\"Apply |augment_excmessage| when the wrapped function fails.\"\"\"", "# pylint: disable=unused-argument", "try", ":", "return", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "BaseException", ":", "info", "=", "kwargs", ".", "copy", "(", ")", "info", "[", "'self'", "]", "=", "instance", "argnames", "=", "inspect", ".", "getfullargspec", "(", "wrapped", ")", ".", "args", "if", "argnames", "[", "0", "]", "==", "'self'", ":", "argnames", "=", "argnames", "[", "1", ":", "]", "for", "argname", ",", "arg", "in", "zip", "(", "argnames", ",", "args", ")", ":", "info", "[", "argname", "]", "=", "arg", "for", "argname", "in", "argnames", ":", "if", "argname", "not", "in", "info", ":", "info", "[", "argname", "]", "=", "'?'", "message", "=", "eval", "(", "f\"f'While trying to {description}'\"", ",", "globals", "(", ")", ",", "info", ")", "augment_excmessage", "(", "message", ")", "return", "wrapper" ]
Wrap a function with |augment_excmessage|. Function |excmessage_decorator| is a means to apply function |augment_excmessage| more efficiently. Suppose you would apply function |augment_excmessage| in a function that adds and returns to numbers: >>> from hydpy.core import objecttools >>> def add(x, y): ... try: ... return x + y ... except BaseException: ... objecttools.augment_excmessage( ... 'While trying to add `x` and `y`') This works as excepted... >>> add(1, 2) 3 >>> add(1, []) Traceback (most recent call last): ... TypeError: While trying to add `x` and `y`, the following error \ occurred: unsupported operand type(s) for +: 'int' and 'list' ...but can be achieved with much less code using |excmessage_decorator|: >>> @objecttools.excmessage_decorator( ... 'add `x` and `y`') ... def add(x, y): ... return x+y >>> add(1, 2) 3 >>> add(1, []) Traceback (most recent call last): ... TypeError: While trying to add `x` and `y`, the following error \ occurred: unsupported operand type(s) for +: 'int' and 'list' Additionally, exception messages related to wrong function calls are now also augmented: >>> add(1) Traceback (most recent call last): ... TypeError: While trying to add `x` and `y`, the following error \ occurred: add() missing 1 required positional argument: 'y' |excmessage_decorator| evaluates the given string like an f-string, allowing to mention the argument values of the called function and to make use of all string modification functions provided by modules |objecttools|: >>> @objecttools.excmessage_decorator( ... 'add `x` ({repr_(x, 2)}) and `y` ({repr_(y, 2)})') ... def add(x, y): ... return x+y >>> add(1.1111, 'wrong') Traceback (most recent call last): ... TypeError: While trying to add `x` (1.11) and `y` (wrong), the following \ error occurred: unsupported operand type(s) for +: 'float' and 'str' >>> add(1) Traceback (most recent call last): ... TypeError: While trying to add `x` (1) and `y` (?), the following error \ occurred: add() missing 1 required positional argument: 'y' >>> add(y=1) Traceback (most recent call last): ... TypeError: While trying to add `x` (?) and `y` (1), the following error \ occurred: add() missing 1 required positional argument: 'x' Apply |excmessage_decorator| on methods also works fine: >>> class Adder: ... def __init__(self): ... self.value = 0 ... @objecttools.excmessage_decorator( ... 'add an instance of class `{classname(self)}` with value ' ... '`{repr_(other, 2)}` of type `{classname(other)}`') ... def __iadd__(self, other): ... self.value += other ... return self >>> adder = Adder() >>> adder += 1 >>> adder.value 1 >>> adder += 'wrong' Traceback (most recent call last): ... TypeError: While trying to add an instance of class `Adder` with value \ `wrong` of type `str`, the following error occurred: unsupported operand \ type(s) for +=: 'int' and 'str' It is made sure that no information of the decorated function is lost: >>> add.__name__ 'add'
[ "Wrap", "a", "function", "with", "|augment_excmessage|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L369-L494
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
print_values
def print_values(values, width=70): """Print the given values in multiple lines with a certain maximum width. By default, each line contains at most 70 characters: >>> from hydpy import print_values >>> print_values(range(21)) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 You can change this default behaviour by passing an alternative number of characters: >>> print_values(range(21), width=30) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 """ for line in textwrap.wrap(repr_values(values), width=width): print(line)
python
def print_values(values, width=70): """Print the given values in multiple lines with a certain maximum width. By default, each line contains at most 70 characters: >>> from hydpy import print_values >>> print_values(range(21)) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 You can change this default behaviour by passing an alternative number of characters: >>> print_values(range(21), width=30) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 """ for line in textwrap.wrap(repr_values(values), width=width): print(line)
[ "def", "print_values", "(", "values", ",", "width", "=", "70", ")", ":", "for", "line", "in", "textwrap", ".", "wrap", "(", "repr_values", "(", "values", ")", ",", "width", "=", "width", ")", ":", "print", "(", "line", ")" ]
Print the given values in multiple lines with a certain maximum width. By default, each line contains at most 70 characters: >>> from hydpy import print_values >>> print_values(range(21)) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 You can change this default behaviour by passing an alternative number of characters: >>> print_values(range(21), width=30) 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
[ "Print", "the", "given", "values", "in", "multiple", "lines", "with", "a", "certain", "maximum", "width", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L801-L820
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
assignrepr_values
def assignrepr_values(values, prefix, width=None, _fakeend=0): """Return a prefixed, wrapped and properly aligned string representation of the given values using function |repr|. >>> from hydpy.core.objecttools import assignrepr_values >>> print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) If no width is given, no wrapping is performed: >>> print(assignrepr_values(range(1, 13), 'test(') + ')') test(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) To circumvent defining too long string representations, make use of the ellipsis option: >>> from hydpy import pub >>> with pub.options.ellipsis(1): ... print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, ...,12) >>> with pub.options.ellipsis(5): ... print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, 2, 3, 4, 5, ...,8, 9, 10, 11, 12) >>> with pub.options.ellipsis(6): ... print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) """ ellipsis_ = hydpy.pub.options.ellipsis if (ellipsis_ > 0) and (len(values) > 2*ellipsis_): string = (repr_values(values[:ellipsis_]) + ', ...,' + repr_values(values[-ellipsis_:])) else: string = repr_values(values) blanks = ' '*len(prefix) if width is None: wrapped = [string] _fakeend = 0 else: width -= len(prefix) wrapped = textwrap.wrap(string+'_'*_fakeend, width) if not wrapped: wrapped = [''] lines = [] for (idx, line) in enumerate(wrapped): if idx == 0: lines.append('%s%s' % (prefix, line)) else: lines.append('%s%s' % (blanks, line)) string = '\n'.join(lines) return string[:len(string)-_fakeend]
python
def assignrepr_values(values, prefix, width=None, _fakeend=0): """Return a prefixed, wrapped and properly aligned string representation of the given values using function |repr|. >>> from hydpy.core.objecttools import assignrepr_values >>> print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) If no width is given, no wrapping is performed: >>> print(assignrepr_values(range(1, 13), 'test(') + ')') test(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) To circumvent defining too long string representations, make use of the ellipsis option: >>> from hydpy import pub >>> with pub.options.ellipsis(1): ... print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, ...,12) >>> with pub.options.ellipsis(5): ... print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, 2, 3, 4, 5, ...,8, 9, 10, 11, 12) >>> with pub.options.ellipsis(6): ... print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) """ ellipsis_ = hydpy.pub.options.ellipsis if (ellipsis_ > 0) and (len(values) > 2*ellipsis_): string = (repr_values(values[:ellipsis_]) + ', ...,' + repr_values(values[-ellipsis_:])) else: string = repr_values(values) blanks = ' '*len(prefix) if width is None: wrapped = [string] _fakeend = 0 else: width -= len(prefix) wrapped = textwrap.wrap(string+'_'*_fakeend, width) if not wrapped: wrapped = [''] lines = [] for (idx, line) in enumerate(wrapped): if idx == 0: lines.append('%s%s' % (prefix, line)) else: lines.append('%s%s' % (blanks, line)) string = '\n'.join(lines) return string[:len(string)-_fakeend]
[ "def", "assignrepr_values", "(", "values", ",", "prefix", ",", "width", "=", "None", ",", "_fakeend", "=", "0", ")", ":", "ellipsis_", "=", "hydpy", ".", "pub", ".", "options", ".", "ellipsis", "if", "(", "ellipsis_", ">", "0", ")", "and", "(", "len", "(", "values", ")", ">", "2", "*", "ellipsis_", ")", ":", "string", "=", "(", "repr_values", "(", "values", "[", ":", "ellipsis_", "]", ")", "+", "', ...,'", "+", "repr_values", "(", "values", "[", "-", "ellipsis_", ":", "]", ")", ")", "else", ":", "string", "=", "repr_values", "(", "values", ")", "blanks", "=", "' '", "*", "len", "(", "prefix", ")", "if", "width", "is", "None", ":", "wrapped", "=", "[", "string", "]", "_fakeend", "=", "0", "else", ":", "width", "-=", "len", "(", "prefix", ")", "wrapped", "=", "textwrap", ".", "wrap", "(", "string", "+", "'_'", "*", "_fakeend", ",", "width", ")", "if", "not", "wrapped", ":", "wrapped", "=", "[", "''", "]", "lines", "=", "[", "]", "for", "(", "idx", ",", "line", ")", "in", "enumerate", "(", "wrapped", ")", ":", "if", "idx", "==", "0", ":", "lines", ".", "append", "(", "'%s%s'", "%", "(", "prefix", ",", "line", ")", ")", "else", ":", "lines", ".", "append", "(", "'%s%s'", "%", "(", "blanks", ",", "line", ")", ")", "string", "=", "'\\n'", ".", "join", "(", "lines", ")", "return", "string", "[", ":", "len", "(", "string", ")", "-", "_fakeend", "]" ]
Return a prefixed, wrapped and properly aligned string representation of the given values using function |repr|. >>> from hydpy.core.objecttools import assignrepr_values >>> print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) If no width is given, no wrapping is performed: >>> print(assignrepr_values(range(1, 13), 'test(') + ')') test(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) To circumvent defining too long string representations, make use of the ellipsis option: >>> from hydpy import pub >>> with pub.options.ellipsis(1): ... print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, ...,12) >>> with pub.options.ellipsis(5): ... print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, 2, 3, 4, 5, ...,8, 9, 10, 11, 12) >>> with pub.options.ellipsis(6): ... print(assignrepr_values(range(1, 13), 'test(', 20) + ')') test(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
[ "Return", "a", "prefixed", "wrapped", "and", "properly", "aligned", "string", "representation", "of", "the", "given", "values", "using", "function", "|repr|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L871-L930
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
assignrepr_values2
def assignrepr_values2(values, prefix): """Return a prefixed and properly aligned string representation of the given 2-dimensional value matrix using function |repr|. >>> from hydpy.core.objecttools import assignrepr_values2 >>> import numpy >>> print(assignrepr_values2(numpy.eye(3), 'test(') + ')') test(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) Functions |assignrepr_values2| works also on empty iterables: >>> print(assignrepr_values2([[]], 'test(') + ')') test() """ lines = [] blanks = ' '*len(prefix) for (idx, subvalues) in enumerate(values): if idx == 0: lines.append('%s%s,' % (prefix, repr_values(subvalues))) else: lines.append('%s%s,' % (blanks, repr_values(subvalues))) lines[-1] = lines[-1][:-1] return '\n'.join(lines)
python
def assignrepr_values2(values, prefix): """Return a prefixed and properly aligned string representation of the given 2-dimensional value matrix using function |repr|. >>> from hydpy.core.objecttools import assignrepr_values2 >>> import numpy >>> print(assignrepr_values2(numpy.eye(3), 'test(') + ')') test(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) Functions |assignrepr_values2| works also on empty iterables: >>> print(assignrepr_values2([[]], 'test(') + ')') test() """ lines = [] blanks = ' '*len(prefix) for (idx, subvalues) in enumerate(values): if idx == 0: lines.append('%s%s,' % (prefix, repr_values(subvalues))) else: lines.append('%s%s,' % (blanks, repr_values(subvalues))) lines[-1] = lines[-1][:-1] return '\n'.join(lines)
[ "def", "assignrepr_values2", "(", "values", ",", "prefix", ")", ":", "lines", "=", "[", "]", "blanks", "=", "' '", "*", "len", "(", "prefix", ")", "for", "(", "idx", ",", "subvalues", ")", "in", "enumerate", "(", "values", ")", ":", "if", "idx", "==", "0", ":", "lines", ".", "append", "(", "'%s%s,'", "%", "(", "prefix", ",", "repr_values", "(", "subvalues", ")", ")", ")", "else", ":", "lines", ".", "append", "(", "'%s%s,'", "%", "(", "blanks", ",", "repr_values", "(", "subvalues", ")", ")", ")", "lines", "[", "-", "1", "]", "=", "lines", "[", "-", "1", "]", "[", ":", "-", "1", "]", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
Return a prefixed and properly aligned string representation of the given 2-dimensional value matrix using function |repr|. >>> from hydpy.core.objecttools import assignrepr_values2 >>> import numpy >>> print(assignrepr_values2(numpy.eye(3), 'test(') + ')') test(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0) Functions |assignrepr_values2| works also on empty iterables: >>> print(assignrepr_values2([[]], 'test(') + ')') test()
[ "Return", "a", "prefixed", "and", "properly", "aligned", "string", "representation", "of", "the", "given", "2", "-", "dimensional", "value", "matrix", "using", "function", "|repr|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L1050-L1074
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
_assignrepr_bracketed2
def _assignrepr_bracketed2(assignrepr_bracketed1, values, prefix, width=None): """Return a prefixed, wrapped and properly aligned bracketed string representation of the given 2-dimensional value matrix using function |repr|.""" brackets = getattr(assignrepr_bracketed1, '_brackets') prefix += brackets[0] lines = [] blanks = ' '*len(prefix) for (idx, subvalues) in enumerate(values): if idx == 0: lines.append(assignrepr_bracketed1(subvalues, prefix, width)) else: lines.append(assignrepr_bracketed1(subvalues, blanks, width)) lines[-1] += ',' if (len(values) > 1) or (brackets != '()'): lines[-1] = lines[-1][:-1] lines[-1] += brackets[1] return '\n'.join(lines)
python
def _assignrepr_bracketed2(assignrepr_bracketed1, values, prefix, width=None): """Return a prefixed, wrapped and properly aligned bracketed string representation of the given 2-dimensional value matrix using function |repr|.""" brackets = getattr(assignrepr_bracketed1, '_brackets') prefix += brackets[0] lines = [] blanks = ' '*len(prefix) for (idx, subvalues) in enumerate(values): if idx == 0: lines.append(assignrepr_bracketed1(subvalues, prefix, width)) else: lines.append(assignrepr_bracketed1(subvalues, blanks, width)) lines[-1] += ',' if (len(values) > 1) or (brackets != '()'): lines[-1] = lines[-1][:-1] lines[-1] += brackets[1] return '\n'.join(lines)
[ "def", "_assignrepr_bracketed2", "(", "assignrepr_bracketed1", ",", "values", ",", "prefix", ",", "width", "=", "None", ")", ":", "brackets", "=", "getattr", "(", "assignrepr_bracketed1", ",", "'_brackets'", ")", "prefix", "+=", "brackets", "[", "0", "]", "lines", "=", "[", "]", "blanks", "=", "' '", "*", "len", "(", "prefix", ")", "for", "(", "idx", ",", "subvalues", ")", "in", "enumerate", "(", "values", ")", ":", "if", "idx", "==", "0", ":", "lines", ".", "append", "(", "assignrepr_bracketed1", "(", "subvalues", ",", "prefix", ",", "width", ")", ")", "else", ":", "lines", ".", "append", "(", "assignrepr_bracketed1", "(", "subvalues", ",", "blanks", ",", "width", ")", ")", "lines", "[", "-", "1", "]", "+=", "','", "if", "(", "len", "(", "values", ")", ">", "1", ")", "or", "(", "brackets", "!=", "'()'", ")", ":", "lines", "[", "-", "1", "]", "=", "lines", "[", "-", "1", "]", "[", ":", "-", "1", "]", "lines", "[", "-", "1", "]", "+=", "brackets", "[", "1", "]", "return", "'\\n'", ".", "join", "(", "lines", ")" ]
Return a prefixed, wrapped and properly aligned bracketed string representation of the given 2-dimensional value matrix using function |repr|.
[ "Return", "a", "prefixed", "wrapped", "and", "properly", "aligned", "bracketed", "string", "representation", "of", "the", "given", "2", "-", "dimensional", "value", "matrix", "using", "function", "|repr|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L1077-L1094
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
round_
def round_(values, decimals=None, width=0, lfill=None, rfill=None, **kwargs): """Prints values with a maximum number of digits in doctests. See the documentation on function |repr| for more details. And note thate the option keyword arguments are passed to the print function. Usually one would apply function |round_| on a single or a vector of numbers: >>> from hydpy import round_ >>> round_(1./3., decimals=6) 0.333333 >>> round_((1./2., 1./3., 1./4.), decimals=4) 0.5, 0.3333, 0.25 Additionally, one can supply a `width` and a `rfill` argument: >>> round_(1.0, width=6, rfill='0') 1.0000 Alternatively, one can use the `lfill` arguments, which might e.g. be usefull for aligning different strings: >>> round_('test', width=6, lfill='_') __test Using both the `lfill` and the `rfill` argument raises an error: >>> round_(1.0, lfill='_', rfill='0') Traceback (most recent call last): ... ValueError: For function `round_` values are passed for both \ arguments `lfill` and `rfill`. This is not allowed. """ if decimals is None: decimals = hydpy.pub.options.reprdigits with hydpy.pub.options.reprdigits(decimals): if isinstance(values, abctools.IterableNonStringABC): string = repr_values(values) else: string = repr_(values) if (lfill is not None) and (rfill is not None): raise ValueError( 'For function `round_` values are passed for both arguments ' '`lfill` and `rfill`. This is not allowed.') if (lfill is not None) or (rfill is not None): width = max(width, len(string)) if lfill is not None: string = string.rjust(width, lfill) else: string = string.ljust(width, rfill) print(string, **kwargs)
python
def round_(values, decimals=None, width=0, lfill=None, rfill=None, **kwargs): """Prints values with a maximum number of digits in doctests. See the documentation on function |repr| for more details. And note thate the option keyword arguments are passed to the print function. Usually one would apply function |round_| on a single or a vector of numbers: >>> from hydpy import round_ >>> round_(1./3., decimals=6) 0.333333 >>> round_((1./2., 1./3., 1./4.), decimals=4) 0.5, 0.3333, 0.25 Additionally, one can supply a `width` and a `rfill` argument: >>> round_(1.0, width=6, rfill='0') 1.0000 Alternatively, one can use the `lfill` arguments, which might e.g. be usefull for aligning different strings: >>> round_('test', width=6, lfill='_') __test Using both the `lfill` and the `rfill` argument raises an error: >>> round_(1.0, lfill='_', rfill='0') Traceback (most recent call last): ... ValueError: For function `round_` values are passed for both \ arguments `lfill` and `rfill`. This is not allowed. """ if decimals is None: decimals = hydpy.pub.options.reprdigits with hydpy.pub.options.reprdigits(decimals): if isinstance(values, abctools.IterableNonStringABC): string = repr_values(values) else: string = repr_(values) if (lfill is not None) and (rfill is not None): raise ValueError( 'For function `round_` values are passed for both arguments ' '`lfill` and `rfill`. This is not allowed.') if (lfill is not None) or (rfill is not None): width = max(width, len(string)) if lfill is not None: string = string.rjust(width, lfill) else: string = string.ljust(width, rfill) print(string, **kwargs)
[ "def", "round_", "(", "values", ",", "decimals", "=", "None", ",", "width", "=", "0", ",", "lfill", "=", "None", ",", "rfill", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "decimals", "is", "None", ":", "decimals", "=", "hydpy", ".", "pub", ".", "options", ".", "reprdigits", "with", "hydpy", ".", "pub", ".", "options", ".", "reprdigits", "(", "decimals", ")", ":", "if", "isinstance", "(", "values", ",", "abctools", ".", "IterableNonStringABC", ")", ":", "string", "=", "repr_values", "(", "values", ")", "else", ":", "string", "=", "repr_", "(", "values", ")", "if", "(", "lfill", "is", "not", "None", ")", "and", "(", "rfill", "is", "not", "None", ")", ":", "raise", "ValueError", "(", "'For function `round_` values are passed for both arguments '", "'`lfill` and `rfill`. This is not allowed.'", ")", "if", "(", "lfill", "is", "not", "None", ")", "or", "(", "rfill", "is", "not", "None", ")", ":", "width", "=", "max", "(", "width", ",", "len", "(", "string", ")", ")", "if", "lfill", "is", "not", "None", ":", "string", "=", "string", ".", "rjust", "(", "width", ",", "lfill", ")", "else", ":", "string", "=", "string", ".", "ljust", "(", "width", ",", "rfill", ")", "print", "(", "string", ",", "*", "*", "kwargs", ")" ]
Prints values with a maximum number of digits in doctests. See the documentation on function |repr| for more details. And note thate the option keyword arguments are passed to the print function. Usually one would apply function |round_| on a single or a vector of numbers: >>> from hydpy import round_ >>> round_(1./3., decimals=6) 0.333333 >>> round_((1./2., 1./3., 1./4.), decimals=4) 0.5, 0.3333, 0.25 Additionally, one can supply a `width` and a `rfill` argument: >>> round_(1.0, width=6, rfill='0') 1.0000 Alternatively, one can use the `lfill` arguments, which might e.g. be usefull for aligning different strings: >>> round_('test', width=6, lfill='_') __test Using both the `lfill` and the `rfill` argument raises an error: >>> round_(1.0, lfill='_', rfill='0') Traceback (most recent call last): ... ValueError: For function `round_` values are passed for both \ arguments `lfill` and `rfill`. This is not allowed.
[ "Prints", "values", "with", "a", "maximum", "number", "of", "digits", "in", "doctests", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L1324-L1375
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
extract
def extract(values, types, skip=False): """Return a generator that extracts certain objects from `values`. This function is thought for supporting the definition of functions with arguments, that can be objects of of contain types or that can be iterables containing these objects. The following examples show that function |extract| basically implements a type specific flattening mechanism: >>> from hydpy.core.objecttools import extract >>> tuple(extract('str1', (str, int))) ('str1',) >>> tuple(extract(['str1', 'str2'], (str, int))) ('str1', 'str2') >>> tuple(extract((['str1', 'str2'], [1,]), (str, int))) ('str1', 'str2', 1) If an object is neither iterable nor of the required type, the following exception is raised: >>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int))) Traceback (most recent call last): ... TypeError: The given value `None` is neither iterable nor \ an instance of the following classes: str and int. Optionally, |None| values can be skipped: >>> tuple(extract(None, (str, int), True)) () >>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int), True)) ('str1', 'str2', 1) """ if isinstance(values, types): yield values elif skip and (values is None): return else: try: for value in values: for subvalue in extract(value, types, skip): yield subvalue except TypeError as exc: if exc.args[0].startswith('The given value'): raise exc else: raise TypeError( f'The given value `{repr(values)}` is neither iterable ' f'nor an instance of the following classes: ' f'{enumeration(types, converter=instancename)}.')
python
def extract(values, types, skip=False): """Return a generator that extracts certain objects from `values`. This function is thought for supporting the definition of functions with arguments, that can be objects of of contain types or that can be iterables containing these objects. The following examples show that function |extract| basically implements a type specific flattening mechanism: >>> from hydpy.core.objecttools import extract >>> tuple(extract('str1', (str, int))) ('str1',) >>> tuple(extract(['str1', 'str2'], (str, int))) ('str1', 'str2') >>> tuple(extract((['str1', 'str2'], [1,]), (str, int))) ('str1', 'str2', 1) If an object is neither iterable nor of the required type, the following exception is raised: >>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int))) Traceback (most recent call last): ... TypeError: The given value `None` is neither iterable nor \ an instance of the following classes: str and int. Optionally, |None| values can be skipped: >>> tuple(extract(None, (str, int), True)) () >>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int), True)) ('str1', 'str2', 1) """ if isinstance(values, types): yield values elif skip and (values is None): return else: try: for value in values: for subvalue in extract(value, types, skip): yield subvalue except TypeError as exc: if exc.args[0].startswith('The given value'): raise exc else: raise TypeError( f'The given value `{repr(values)}` is neither iterable ' f'nor an instance of the following classes: ' f'{enumeration(types, converter=instancename)}.')
[ "def", "extract", "(", "values", ",", "types", ",", "skip", "=", "False", ")", ":", "if", "isinstance", "(", "values", ",", "types", ")", ":", "yield", "values", "elif", "skip", "and", "(", "values", "is", "None", ")", ":", "return", "else", ":", "try", ":", "for", "value", "in", "values", ":", "for", "subvalue", "in", "extract", "(", "value", ",", "types", ",", "skip", ")", ":", "yield", "subvalue", "except", "TypeError", "as", "exc", ":", "if", "exc", ".", "args", "[", "0", "]", ".", "startswith", "(", "'The given value'", ")", ":", "raise", "exc", "else", ":", "raise", "TypeError", "(", "f'The given value `{repr(values)}` is neither iterable '", "f'nor an instance of the following classes: '", "f'{enumeration(types, converter=instancename)}.'", ")" ]
Return a generator that extracts certain objects from `values`. This function is thought for supporting the definition of functions with arguments, that can be objects of of contain types or that can be iterables containing these objects. The following examples show that function |extract| basically implements a type specific flattening mechanism: >>> from hydpy.core.objecttools import extract >>> tuple(extract('str1', (str, int))) ('str1',) >>> tuple(extract(['str1', 'str2'], (str, int))) ('str1', 'str2') >>> tuple(extract((['str1', 'str2'], [1,]), (str, int))) ('str1', 'str2', 1) If an object is neither iterable nor of the required type, the following exception is raised: >>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int))) Traceback (most recent call last): ... TypeError: The given value `None` is neither iterable nor \ an instance of the following classes: str and int. Optionally, |None| values can be skipped: >>> tuple(extract(None, (str, int), True)) () >>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int), True)) ('str1', 'str2', 1)
[ "Return", "a", "generator", "that", "extracts", "certain", "objects", "from", "values", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L1378-L1428
train
hydpy-dev/hydpy
hydpy/core/objecttools.py
enumeration
def enumeration(values, converter=str, default=''): """Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3, and []' >>> enumeration(('text', 3)) 'text and 3' >>> enumeration(('text',)) 'text' >>> enumeration(()) '' All given objects are converted to strings by function |str|, as shown by the first two examples. This behaviour can be changed by another function expecting a single argument and returning a string: >>> from hydpy.core.objecttools import classname >>> enumeration(('text', 3, []), converter=classname) 'str, int, and list' Furthermore, you can define a default string that is returned in case an empty iterable is given: >>> enumeration((), default='nothing') 'nothing' """ values = tuple(converter(value) for value in values) if not values: return default if len(values) == 1: return values[0] if len(values) == 2: return ' and '.join(values) return ', and '.join((', '.join(values[:-1]), values[-1]))
python
def enumeration(values, converter=str, default=''): """Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3, and []' >>> enumeration(('text', 3)) 'text and 3' >>> enumeration(('text',)) 'text' >>> enumeration(()) '' All given objects are converted to strings by function |str|, as shown by the first two examples. This behaviour can be changed by another function expecting a single argument and returning a string: >>> from hydpy.core.objecttools import classname >>> enumeration(('text', 3, []), converter=classname) 'str, int, and list' Furthermore, you can define a default string that is returned in case an empty iterable is given: >>> enumeration((), default='nothing') 'nothing' """ values = tuple(converter(value) for value in values) if not values: return default if len(values) == 1: return values[0] if len(values) == 2: return ' and '.join(values) return ', and '.join((', '.join(values[:-1]), values[-1]))
[ "def", "enumeration", "(", "values", ",", "converter", "=", "str", ",", "default", "=", "''", ")", ":", "values", "=", "tuple", "(", "converter", "(", "value", ")", "for", "value", "in", "values", ")", "if", "not", "values", ":", "return", "default", "if", "len", "(", "values", ")", "==", "1", ":", "return", "values", "[", "0", "]", "if", "len", "(", "values", ")", "==", "2", ":", "return", "' and '", ".", "join", "(", "values", ")", "return", "', and '", ".", "join", "(", "(", "', '", ".", "join", "(", "values", "[", ":", "-", "1", "]", ")", ",", "values", "[", "-", "1", "]", ")", ")" ]
Return an enumeration string based on the given values. The following four examples show the standard output of function |enumeration|: >>> from hydpy.core.objecttools import enumeration >>> enumeration(('text', 3, [])) 'text, 3, and []' >>> enumeration(('text', 3)) 'text and 3' >>> enumeration(('text',)) 'text' >>> enumeration(()) '' All given objects are converted to strings by function |str|, as shown by the first two examples. This behaviour can be changed by another function expecting a single argument and returning a string: >>> from hydpy.core.objecttools import classname >>> enumeration(('text', 3, []), converter=classname) 'str, int, and list' Furthermore, you can define a default string that is returned in case an empty iterable is given: >>> enumeration((), default='nothing') 'nothing'
[ "Return", "an", "enumeration", "string", "based", "on", "the", "given", "values", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/objecttools.py#L1431-L1468
train
hydpy-dev/hydpy
hydpy/models/hland/hland_states.py
Ic.trim
def trim(self, lower=None, upper=None): """Trim upper values in accordance with :math:`IC \\leq ICMAX`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(5) >>> icmax(2.0) >>> states.ic(-1.0, 0.0, 1.0, 2.0, 3.0) >>> states.ic ic(0.0, 0.0, 1.0, 2.0, 2.0) """ if upper is None: control = self.subseqs.seqs.model.parameters.control upper = control.icmax hland_sequences.State1DSequence.trim(self, lower, upper)
python
def trim(self, lower=None, upper=None): """Trim upper values in accordance with :math:`IC \\leq ICMAX`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(5) >>> icmax(2.0) >>> states.ic(-1.0, 0.0, 1.0, 2.0, 3.0) >>> states.ic ic(0.0, 0.0, 1.0, 2.0, 2.0) """ if upper is None: control = self.subseqs.seqs.model.parameters.control upper = control.icmax hland_sequences.State1DSequence.trim(self, lower, upper)
[ "def", "trim", "(", "self", ",", "lower", "=", "None", ",", "upper", "=", "None", ")", ":", "if", "upper", "is", "None", ":", "control", "=", "self", ".", "subseqs", ".", "seqs", ".", "model", ".", "parameters", ".", "control", "upper", "=", "control", ".", "icmax", "hland_sequences", ".", "State1DSequence", ".", "trim", "(", "self", ",", "lower", ",", "upper", ")" ]
Trim upper values in accordance with :math:`IC \\leq ICMAX`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(5) >>> icmax(2.0) >>> states.ic(-1.0, 0.0, 1.0, 2.0, 3.0) >>> states.ic ic(0.0, 0.0, 1.0, 2.0, 2.0)
[ "Trim", "upper", "values", "in", "accordance", "with", ":", "math", ":", "IC", "\\\\", "leq", "ICMAX", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/hland/hland_states.py#L20-L34
train
hydpy-dev/hydpy
hydpy/models/hland/hland_states.py
SP.trim
def trim(self, lower=None, upper=None): """Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(7) >>> whc(0.1) >>> states.wc.values = -1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0 >>> states.sp(-1., 0., 0., 5., 5., 5., 5.) >>> states.sp sp(0.0, 0.0, 10.0, 5.0, 5.0, 5.0, 10.0) """ whc = self.subseqs.seqs.model.parameters.control.whc wc = self.subseqs.wc if lower is None: if wc.values is not None: with numpy.errstate(divide='ignore', invalid='ignore'): lower = numpy.clip(wc.values / whc.values, 0., numpy.inf) else: lower = 0. hland_sequences.State1DSequence.trim(self, lower, upper)
python
def trim(self, lower=None, upper=None): """Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(7) >>> whc(0.1) >>> states.wc.values = -1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0 >>> states.sp(-1., 0., 0., 5., 5., 5., 5.) >>> states.sp sp(0.0, 0.0, 10.0, 5.0, 5.0, 5.0, 10.0) """ whc = self.subseqs.seqs.model.parameters.control.whc wc = self.subseqs.wc if lower is None: if wc.values is not None: with numpy.errstate(divide='ignore', invalid='ignore'): lower = numpy.clip(wc.values / whc.values, 0., numpy.inf) else: lower = 0. hland_sequences.State1DSequence.trim(self, lower, upper)
[ "def", "trim", "(", "self", ",", "lower", "=", "None", ",", "upper", "=", "None", ")", ":", "whc", "=", "self", ".", "subseqs", ".", "seqs", ".", "model", ".", "parameters", ".", "control", ".", "whc", "wc", "=", "self", ".", "subseqs", ".", "wc", "if", "lower", "is", "None", ":", "if", "wc", ".", "values", "is", "not", "None", ":", "with", "numpy", ".", "errstate", "(", "divide", "=", "'ignore'", ",", "invalid", "=", "'ignore'", ")", ":", "lower", "=", "numpy", ".", "clip", "(", "wc", ".", "values", "/", "whc", ".", "values", ",", "0.", ",", "numpy", ".", "inf", ")", "else", ":", "lower", "=", "0.", "hland_sequences", ".", "State1DSequence", ".", "trim", "(", "self", ",", "lower", ",", "upper", ")" ]
Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(7) >>> whc(0.1) >>> states.wc.values = -1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0 >>> states.sp(-1., 0., 0., 5., 5., 5., 5.) >>> states.sp sp(0.0, 0.0, 10.0, 5.0, 5.0, 5.0, 10.0)
[ "Trim", "values", "in", "accordance", "with", ":", "math", ":", "WC", "\\\\", "leq", "WHC", "\\\\", "cdot", "SP", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/hland/hland_states.py#L42-L62
train
hydpy-dev/hydpy
hydpy/models/hland/hland_states.py
WC.trim
def trim(self, lower=None, upper=None): """Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(7) >>> whc(0.1) >>> states.sp = 0.0, 0.0, 0.0, 5.0, 5.0, 5.0, 5.0 >>> states.wc(-1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0) >>> states.wc wc(0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5) """ whc = self.subseqs.seqs.model.parameters.control.whc sp = self.subseqs.sp if (upper is None) and (sp.values is not None): upper = whc*sp hland_sequences.State1DSequence.trim(self, lower, upper)
python
def trim(self, lower=None, upper=None): """Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(7) >>> whc(0.1) >>> states.sp = 0.0, 0.0, 0.0, 5.0, 5.0, 5.0, 5.0 >>> states.wc(-1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0) >>> states.wc wc(0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5) """ whc = self.subseqs.seqs.model.parameters.control.whc sp = self.subseqs.sp if (upper is None) and (sp.values is not None): upper = whc*sp hland_sequences.State1DSequence.trim(self, lower, upper)
[ "def", "trim", "(", "self", ",", "lower", "=", "None", ",", "upper", "=", "None", ")", ":", "whc", "=", "self", ".", "subseqs", ".", "seqs", ".", "model", ".", "parameters", ".", "control", ".", "whc", "sp", "=", "self", ".", "subseqs", ".", "sp", "if", "(", "upper", "is", "None", ")", "and", "(", "sp", ".", "values", "is", "not", "None", ")", ":", "upper", "=", "whc", "*", "sp", "hland_sequences", ".", "State1DSequence", ".", "trim", "(", "self", ",", "lower", ",", "upper", ")" ]
Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(7) >>> whc(0.1) >>> states.sp = 0.0, 0.0, 0.0, 5.0, 5.0, 5.0, 5.0 >>> states.wc(-1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0) >>> states.wc wc(0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5)
[ "Trim", "values", "in", "accordance", "with", ":", "math", ":", "WC", "\\\\", "leq", "WHC", "\\\\", "cdot", "SP", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/hland/hland_states.py#L70-L86
train
hydpy-dev/hydpy
hydpy/models/hland/hland_states.py
LZ.trim
def trim(self, lower=None, upper=None): """Trim negative value whenever there is no internal lake within the respective subbasin. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(2) >>> zonetype(FIELD, ILAKE) >>> states.lz(-1.0) >>> states.lz lz(-1.0) >>> zonetype(FIELD, FOREST) >>> states.lz(-1.0) >>> states.lz lz(0.0) >>> states.lz(1.0) >>> states.lz lz(1.0) """ if upper is None: control = self.subseqs.seqs.model.parameters.control if not any(control.zonetype.values == ILAKE): lower = 0. sequencetools.StateSequence.trim(self, lower, upper)
python
def trim(self, lower=None, upper=None): """Trim negative value whenever there is no internal lake within the respective subbasin. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(2) >>> zonetype(FIELD, ILAKE) >>> states.lz(-1.0) >>> states.lz lz(-1.0) >>> zonetype(FIELD, FOREST) >>> states.lz(-1.0) >>> states.lz lz(0.0) >>> states.lz(1.0) >>> states.lz lz(1.0) """ if upper is None: control = self.subseqs.seqs.model.parameters.control if not any(control.zonetype.values == ILAKE): lower = 0. sequencetools.StateSequence.trim(self, lower, upper)
[ "def", "trim", "(", "self", ",", "lower", "=", "None", ",", "upper", "=", "None", ")", ":", "if", "upper", "is", "None", ":", "control", "=", "self", ".", "subseqs", ".", "seqs", ".", "model", ".", "parameters", ".", "control", "if", "not", "any", "(", "control", ".", "zonetype", ".", "values", "==", "ILAKE", ")", ":", "lower", "=", "0.", "sequencetools", ".", "StateSequence", ".", "trim", "(", "self", ",", "lower", ",", "upper", ")" ]
Trim negative value whenever there is no internal lake within the respective subbasin. >>> from hydpy.models.hland import * >>> parameterstep('1d') >>> nmbzones(2) >>> zonetype(FIELD, ILAKE) >>> states.lz(-1.0) >>> states.lz lz(-1.0) >>> zonetype(FIELD, FOREST) >>> states.lz(-1.0) >>> states.lz lz(0.0) >>> states.lz(1.0) >>> states.lz lz(1.0)
[ "Trim", "negative", "value", "whenever", "there", "is", "no", "internal", "lake", "within", "the", "respective", "subbasin", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/hland/hland_states.py#L119-L142
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
Sequences.load_data
def load_data(self, idx): """Call method |InputSequences.load_data| of all handled |InputSequences| objects.""" for subseqs in self: if isinstance(subseqs, abctools.InputSequencesABC): subseqs.load_data(idx)
python
def load_data(self, idx): """Call method |InputSequences.load_data| of all handled |InputSequences| objects.""" for subseqs in self: if isinstance(subseqs, abctools.InputSequencesABC): subseqs.load_data(idx)
[ "def", "load_data", "(", "self", ",", "idx", ")", ":", "for", "subseqs", "in", "self", ":", "if", "isinstance", "(", "subseqs", ",", "abctools", ".", "InputSequencesABC", ")", ":", "subseqs", ".", "load_data", "(", "idx", ")" ]
Call method |InputSequences.load_data| of all handled |InputSequences| objects.
[ "Call", "method", "|InputSequences", ".", "load_data|", "of", "all", "handled", "|InputSequences|", "objects", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L113-L118
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
Sequences.save_data
def save_data(self, idx): """Call method `save_data|` of all handled |IOSequences| objects registered under |OutputSequencesABC|.""" for subseqs in self: if isinstance(subseqs, abctools.OutputSequencesABC): subseqs.save_data(idx)
python
def save_data(self, idx): """Call method `save_data|` of all handled |IOSequences| objects registered under |OutputSequencesABC|.""" for subseqs in self: if isinstance(subseqs, abctools.OutputSequencesABC): subseqs.save_data(idx)
[ "def", "save_data", "(", "self", ",", "idx", ")", ":", "for", "subseqs", "in", "self", ":", "if", "isinstance", "(", "subseqs", ",", "abctools", ".", "OutputSequencesABC", ")", ":", "subseqs", ".", "save_data", "(", "idx", ")" ]
Call method `save_data|` of all handled |IOSequences| objects registered under |OutputSequencesABC|.
[ "Call", "method", "save_data|", "of", "all", "handled", "|IOSequences|", "objects", "registered", "under", "|OutputSequencesABC|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L120-L125
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
Sequences.conditions
def conditions(self) -> Dict[str, Dict[str, Union[float, numpy.ndarray]]]: """Nested dictionary containing the values of all condition sequences. See the documentation on property |HydPy.conditions| for further information. """ conditions = {} for subname in NAMES_CONDITIONSEQUENCES: subseqs = getattr(self, subname, ()) subconditions = {seq.name: copy.deepcopy(seq.values) for seq in subseqs} if subconditions: conditions[subname] = subconditions return conditions
python
def conditions(self) -> Dict[str, Dict[str, Union[float, numpy.ndarray]]]: """Nested dictionary containing the values of all condition sequences. See the documentation on property |HydPy.conditions| for further information. """ conditions = {} for subname in NAMES_CONDITIONSEQUENCES: subseqs = getattr(self, subname, ()) subconditions = {seq.name: copy.deepcopy(seq.values) for seq in subseqs} if subconditions: conditions[subname] = subconditions return conditions
[ "def", "conditions", "(", "self", ")", "->", "Dict", "[", "str", ",", "Dict", "[", "str", ",", "Union", "[", "float", ",", "numpy", ".", "ndarray", "]", "]", "]", ":", "conditions", "=", "{", "}", "for", "subname", "in", "NAMES_CONDITIONSEQUENCES", ":", "subseqs", "=", "getattr", "(", "self", ",", "subname", ",", "(", ")", ")", "subconditions", "=", "{", "seq", ".", "name", ":", "copy", ".", "deepcopy", "(", "seq", ".", "values", ")", "for", "seq", "in", "subseqs", "}", "if", "subconditions", ":", "conditions", "[", "subname", "]", "=", "subconditions", "return", "conditions" ]
Nested dictionary containing the values of all condition sequences. See the documentation on property |HydPy.conditions| for further information.
[ "Nested", "dictionary", "containing", "the", "values", "of", "all", "condition", "sequences", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L149-L163
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
Sequences.load_conditions
def load_conditions(self, filename=None): """Read the initial conditions from a file and assign them to the respective |StateSequence| and/or |LogSequence| objects handled by the actual |Sequences| object. If no filename or dirname is passed, the ones defined by the |ConditionManager| stored in module |pub| are used. """ if self.hasconditions: if not filename: filename = self._conditiondefaultfilename namespace = locals() for seq in self.conditionsequences: namespace[seq.name] = seq namespace['model'] = self code = hydpy.pub.conditionmanager.load_file(filename) try: # ToDo: raises an escape sequence deprecation sometimes # ToDo: use runpy instead? # ToDo: Move functionality to filetools.py? exec(code) except BaseException: objecttools.augment_excmessage( 'While trying to gather initial conditions of element %s' % objecttools.devicename(self))
python
def load_conditions(self, filename=None): """Read the initial conditions from a file and assign them to the respective |StateSequence| and/or |LogSequence| objects handled by the actual |Sequences| object. If no filename or dirname is passed, the ones defined by the |ConditionManager| stored in module |pub| are used. """ if self.hasconditions: if not filename: filename = self._conditiondefaultfilename namespace = locals() for seq in self.conditionsequences: namespace[seq.name] = seq namespace['model'] = self code = hydpy.pub.conditionmanager.load_file(filename) try: # ToDo: raises an escape sequence deprecation sometimes # ToDo: use runpy instead? # ToDo: Move functionality to filetools.py? exec(code) except BaseException: objecttools.augment_excmessage( 'While trying to gather initial conditions of element %s' % objecttools.devicename(self))
[ "def", "load_conditions", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "self", ".", "hasconditions", ":", "if", "not", "filename", ":", "filename", "=", "self", ".", "_conditiondefaultfilename", "namespace", "=", "locals", "(", ")", "for", "seq", "in", "self", ".", "conditionsequences", ":", "namespace", "[", "seq", ".", "name", "]", "=", "seq", "namespace", "[", "'model'", "]", "=", "self", "code", "=", "hydpy", ".", "pub", ".", "conditionmanager", ".", "load_file", "(", "filename", ")", "try", ":", "# ToDo: raises an escape sequence deprecation sometimes", "# ToDo: use runpy instead?", "# ToDo: Move functionality to filetools.py?", "exec", "(", "code", ")", "except", "BaseException", ":", "objecttools", ".", "augment_excmessage", "(", "'While trying to gather initial conditions of element %s'", "%", "objecttools", ".", "devicename", "(", "self", ")", ")" ]
Read the initial conditions from a file and assign them to the respective |StateSequence| and/or |LogSequence| objects handled by the actual |Sequences| object. If no filename or dirname is passed, the ones defined by the |ConditionManager| stored in module |pub| are used.
[ "Read", "the", "initial", "conditions", "from", "a", "file", "and", "assign", "them", "to", "the", "respective", "|StateSequence|", "and", "/", "or", "|LogSequence|", "objects", "handled", "by", "the", "actual", "|Sequences|", "object", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L198-L222
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
Sequences.save_conditions
def save_conditions(self, filename=None): """Query the actual conditions of the |StateSequence| and/or |LogSequence| objects handled by the actual |Sequences| object and write them into a initial condition file. If no filename or dirname is passed, the ones defined by the |ConditionManager| stored in module |pub| are used. """ if self.hasconditions: if filename is None: filename = self._conditiondefaultfilename con = hydpy.pub.controlmanager lines = ['# -*- coding: utf-8 -*-\n\n', 'from hydpy.models.%s import *\n\n' % self.model, 'controlcheck(projectdir="%s", controldir="%s")\n\n' % (con.projectdir, con.currentdir)] for seq in self.conditionsequences: lines.append(repr(seq) + '\n') hydpy.pub.conditionmanager.save_file(filename, ''.join(lines))
python
def save_conditions(self, filename=None): """Query the actual conditions of the |StateSequence| and/or |LogSequence| objects handled by the actual |Sequences| object and write them into a initial condition file. If no filename or dirname is passed, the ones defined by the |ConditionManager| stored in module |pub| are used. """ if self.hasconditions: if filename is None: filename = self._conditiondefaultfilename con = hydpy.pub.controlmanager lines = ['# -*- coding: utf-8 -*-\n\n', 'from hydpy.models.%s import *\n\n' % self.model, 'controlcheck(projectdir="%s", controldir="%s")\n\n' % (con.projectdir, con.currentdir)] for seq in self.conditionsequences: lines.append(repr(seq) + '\n') hydpy.pub.conditionmanager.save_file(filename, ''.join(lines))
[ "def", "save_conditions", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "self", ".", "hasconditions", ":", "if", "filename", "is", "None", ":", "filename", "=", "self", ".", "_conditiondefaultfilename", "con", "=", "hydpy", ".", "pub", ".", "controlmanager", "lines", "=", "[", "'# -*- coding: utf-8 -*-\\n\\n'", ",", "'from hydpy.models.%s import *\\n\\n'", "%", "self", ".", "model", ",", "'controlcheck(projectdir=\"%s\", controldir=\"%s\")\\n\\n'", "%", "(", "con", ".", "projectdir", ",", "con", ".", "currentdir", ")", "]", "for", "seq", "in", "self", ".", "conditionsequences", ":", "lines", ".", "append", "(", "repr", "(", "seq", ")", "+", "'\\n'", ")", "hydpy", ".", "pub", ".", "conditionmanager", ".", "save_file", "(", "filename", ",", "''", ".", "join", "(", "lines", ")", ")" ]
Query the actual conditions of the |StateSequence| and/or |LogSequence| objects handled by the actual |Sequences| object and write them into a initial condition file. If no filename or dirname is passed, the ones defined by the |ConditionManager| stored in module |pub| are used.
[ "Query", "the", "actual", "conditions", "of", "the", "|StateSequence|", "and", "/", "or", "|LogSequence|", "objects", "handled", "by", "the", "actual", "|Sequences|", "object", "and", "write", "them", "into", "a", "initial", "condition", "file", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L224-L242
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.dirpath_int
def dirpath_int(self): """Absolute path of the directory of the internal data file. Normally, each sequence queries its current "internal" directory path from the |SequenceManager| object stored in module |pub|: >>> from hydpy import pub, repr_, TestIO >>> from hydpy.core.filetools import SequenceManager >>> pub.sequencemanager = SequenceManager() We overwrite |FileManager.basepath| and prepare a folder in teh `iotesting` directory to simplify the following examples: >>> basepath = SequenceManager.basepath >>> SequenceManager.basepath = 'test' >>> TestIO.clear() >>> import os >>> with TestIO(): ... os.makedirs('test/temp') Generally, |SequenceManager.tempdirpath| is queried: >>> from hydpy.core import sequencetools as st >>> seq = st.InputSequence(None) >>> with TestIO(): ... repr_(seq.dirpath_int) 'test/temp' Alternatively, you can specify |IOSequence.dirpath_int| for each sequence object individually: >>> seq.dirpath_int = 'path' >>> os.path.split(seq.dirpath_int) ('', 'path') >>> del seq.dirpath_int >>> with TestIO(): ... os.path.split(seq.dirpath_int) ('test', 'temp') If neither an individual definition nor |SequenceManager| is available, the following error is raised: >>> del pub.sequencemanager >>> seq.dirpath_int Traceback (most recent call last): ... RuntimeError: For sequence `inputsequence` the directory of \ the internal data file cannot be determined. Either set it manually \ or prepare `pub.sequencemanager` correctly. Remove the `basepath` mock: >>> SequenceManager.basepath = basepath """ try: return hydpy.pub.sequencemanager.tempdirpath except RuntimeError: raise RuntimeError( f'For sequence {objecttools.devicephrase(self)} ' f'the directory of the internal data file cannot ' f'be determined. Either set it manually or prepare ' f'`pub.sequencemanager` correctly.')
python
def dirpath_int(self): """Absolute path of the directory of the internal data file. Normally, each sequence queries its current "internal" directory path from the |SequenceManager| object stored in module |pub|: >>> from hydpy import pub, repr_, TestIO >>> from hydpy.core.filetools import SequenceManager >>> pub.sequencemanager = SequenceManager() We overwrite |FileManager.basepath| and prepare a folder in teh `iotesting` directory to simplify the following examples: >>> basepath = SequenceManager.basepath >>> SequenceManager.basepath = 'test' >>> TestIO.clear() >>> import os >>> with TestIO(): ... os.makedirs('test/temp') Generally, |SequenceManager.tempdirpath| is queried: >>> from hydpy.core import sequencetools as st >>> seq = st.InputSequence(None) >>> with TestIO(): ... repr_(seq.dirpath_int) 'test/temp' Alternatively, you can specify |IOSequence.dirpath_int| for each sequence object individually: >>> seq.dirpath_int = 'path' >>> os.path.split(seq.dirpath_int) ('', 'path') >>> del seq.dirpath_int >>> with TestIO(): ... os.path.split(seq.dirpath_int) ('test', 'temp') If neither an individual definition nor |SequenceManager| is available, the following error is raised: >>> del pub.sequencemanager >>> seq.dirpath_int Traceback (most recent call last): ... RuntimeError: For sequence `inputsequence` the directory of \ the internal data file cannot be determined. Either set it manually \ or prepare `pub.sequencemanager` correctly. Remove the `basepath` mock: >>> SequenceManager.basepath = basepath """ try: return hydpy.pub.sequencemanager.tempdirpath except RuntimeError: raise RuntimeError( f'For sequence {objecttools.devicephrase(self)} ' f'the directory of the internal data file cannot ' f'be determined. Either set it manually or prepare ' f'`pub.sequencemanager` correctly.')
[ "def", "dirpath_int", "(", "self", ")", ":", "try", ":", "return", "hydpy", ".", "pub", ".", "sequencemanager", ".", "tempdirpath", "except", "RuntimeError", ":", "raise", "RuntimeError", "(", "f'For sequence {objecttools.devicephrase(self)} '", "f'the directory of the internal data file cannot '", "f'be determined. Either set it manually or prepare '", "f'`pub.sequencemanager` correctly.'", ")" ]
Absolute path of the directory of the internal data file. Normally, each sequence queries its current "internal" directory path from the |SequenceManager| object stored in module |pub|: >>> from hydpy import pub, repr_, TestIO >>> from hydpy.core.filetools import SequenceManager >>> pub.sequencemanager = SequenceManager() We overwrite |FileManager.basepath| and prepare a folder in teh `iotesting` directory to simplify the following examples: >>> basepath = SequenceManager.basepath >>> SequenceManager.basepath = 'test' >>> TestIO.clear() >>> import os >>> with TestIO(): ... os.makedirs('test/temp') Generally, |SequenceManager.tempdirpath| is queried: >>> from hydpy.core import sequencetools as st >>> seq = st.InputSequence(None) >>> with TestIO(): ... repr_(seq.dirpath_int) 'test/temp' Alternatively, you can specify |IOSequence.dirpath_int| for each sequence object individually: >>> seq.dirpath_int = 'path' >>> os.path.split(seq.dirpath_int) ('', 'path') >>> del seq.dirpath_int >>> with TestIO(): ... os.path.split(seq.dirpath_int) ('test', 'temp') If neither an individual definition nor |SequenceManager| is available, the following error is raised: >>> del pub.sequencemanager >>> seq.dirpath_int Traceback (most recent call last): ... RuntimeError: For sequence `inputsequence` the directory of \ the internal data file cannot be determined. Either set it manually \ or prepare `pub.sequencemanager` correctly. Remove the `basepath` mock: >>> SequenceManager.basepath = basepath
[ "Absolute", "path", "of", "the", "directory", "of", "the", "internal", "data", "file", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L677-L738
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.disk2ram
def disk2ram(self): """Move internal data from disk to RAM.""" values = self.series self.deactivate_disk() self.ramflag = True self.__set_array(values) self.update_fastaccess()
python
def disk2ram(self): """Move internal data from disk to RAM.""" values = self.series self.deactivate_disk() self.ramflag = True self.__set_array(values) self.update_fastaccess()
[ "def", "disk2ram", "(", "self", ")", ":", "values", "=", "self", ".", "series", "self", ".", "deactivate_disk", "(", ")", "self", ".", "ramflag", "=", "True", "self", ".", "__set_array", "(", "values", ")", "self", ".", "update_fastaccess", "(", ")" ]
Move internal data from disk to RAM.
[ "Move", "internal", "data", "from", "disk", "to", "RAM", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L856-L862
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.ram2disk
def ram2disk(self): """Move internal data from RAM to disk.""" values = self.series self.deactivate_ram() self.diskflag = True self._save_int(values) self.update_fastaccess()
python
def ram2disk(self): """Move internal data from RAM to disk.""" values = self.series self.deactivate_ram() self.diskflag = True self._save_int(values) self.update_fastaccess()
[ "def", "ram2disk", "(", "self", ")", ":", "values", "=", "self", ".", "series", "self", ".", "deactivate_ram", "(", ")", "self", ".", "diskflag", "=", "True", "self", ".", "_save_int", "(", "values", ")", "self", ".", "update_fastaccess", "(", ")" ]
Move internal data from RAM to disk.
[ "Move", "internal", "data", "from", "RAM", "to", "disk", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L864-L870
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.seriesshape
def seriesshape(self): """Shape of the whole time series (time being the first dimension).""" seriesshape = [len(hydpy.pub.timegrids.init)] seriesshape.extend(self.shape) return tuple(seriesshape)
python
def seriesshape(self): """Shape of the whole time series (time being the first dimension).""" seriesshape = [len(hydpy.pub.timegrids.init)] seriesshape.extend(self.shape) return tuple(seriesshape)
[ "def", "seriesshape", "(", "self", ")", ":", "seriesshape", "=", "[", "len", "(", "hydpy", ".", "pub", ".", "timegrids", ".", "init", ")", "]", "seriesshape", ".", "extend", "(", "self", ".", "shape", ")", "return", "tuple", "(", "seriesshape", ")" ]
Shape of the whole time series (time being the first dimension).
[ "Shape", "of", "the", "whole", "time", "series", "(", "time", "being", "the", "first", "dimension", ")", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L910-L914
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.numericshape
def numericshape(self): """Shape of the array of temporary values required for the numerical solver actually being selected.""" try: numericshape = [self.subseqs.seqs.model.numconsts.nmb_stages] except AttributeError: objecttools.augment_excmessage( 'The `numericshape` of a sequence like `%s` depends on the ' 'configuration of the actual integration algorithm. ' 'While trying to query the required configuration data ' '`nmb_stages` of the model associated with element `%s`' % (self.name, objecttools.devicename(self))) # noinspection PyUnboundLocalVariable numericshape.extend(self.shape) return tuple(numericshape)
python
def numericshape(self): """Shape of the array of temporary values required for the numerical solver actually being selected.""" try: numericshape = [self.subseqs.seqs.model.numconsts.nmb_stages] except AttributeError: objecttools.augment_excmessage( 'The `numericshape` of a sequence like `%s` depends on the ' 'configuration of the actual integration algorithm. ' 'While trying to query the required configuration data ' '`nmb_stages` of the model associated with element `%s`' % (self.name, objecttools.devicename(self))) # noinspection PyUnboundLocalVariable numericshape.extend(self.shape) return tuple(numericshape)
[ "def", "numericshape", "(", "self", ")", ":", "try", ":", "numericshape", "=", "[", "self", ".", "subseqs", ".", "seqs", ".", "model", ".", "numconsts", ".", "nmb_stages", "]", "except", "AttributeError", ":", "objecttools", ".", "augment_excmessage", "(", "'The `numericshape` of a sequence like `%s` depends on the '", "'configuration of the actual integration algorithm. '", "'While trying to query the required configuration data '", "'`nmb_stages` of the model associated with element `%s`'", "%", "(", "self", ".", "name", ",", "objecttools", ".", "devicename", "(", "self", ")", ")", ")", "# noinspection PyUnboundLocalVariable", "numericshape", ".", "extend", "(", "self", ".", "shape", ")", "return", "tuple", "(", "numericshape", ")" ]
Shape of the array of temporary values required for the numerical solver actually being selected.
[ "Shape", "of", "the", "array", "of", "temporary", "values", "required", "for", "the", "numerical", "solver", "actually", "being", "selected", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L917-L931
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.series
def series(self) -> InfoArray: """Internal time series data within an |numpy.ndarray|.""" if self.diskflag: array = self._load_int() elif self.ramflag: array = self.__get_array() else: raise AttributeError( f'Sequence {objecttools.devicephrase(self)} is not requested ' f'to make any internal data available to the user.') return InfoArray(array, info={'type': 'unmodified'})
python
def series(self) -> InfoArray: """Internal time series data within an |numpy.ndarray|.""" if self.diskflag: array = self._load_int() elif self.ramflag: array = self.__get_array() else: raise AttributeError( f'Sequence {objecttools.devicephrase(self)} is not requested ' f'to make any internal data available to the user.') return InfoArray(array, info={'type': 'unmodified'})
[ "def", "series", "(", "self", ")", "->", "InfoArray", ":", "if", "self", ".", "diskflag", ":", "array", "=", "self", ".", "_load_int", "(", ")", "elif", "self", ".", "ramflag", ":", "array", "=", "self", ".", "__get_array", "(", ")", "else", ":", "raise", "AttributeError", "(", "f'Sequence {objecttools.devicephrase(self)} is not requested '", "f'to make any internal data available to the user.'", ")", "return", "InfoArray", "(", "array", ",", "info", "=", "{", "'type'", ":", "'unmodified'", "}", ")" ]
Internal time series data within an |numpy.ndarray|.
[ "Internal", "time", "series", "data", "within", "an", "|numpy", ".", "ndarray|", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L934-L944
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.load_ext
def load_ext(self): """Read the internal data from an external data file.""" try: sequencemanager = hydpy.pub.sequencemanager except AttributeError: raise RuntimeError( 'The time series of sequence %s cannot be loaded. Firstly, ' 'you have to prepare `pub.sequencemanager` correctly.' % objecttools.devicephrase(self)) sequencemanager.load_file(self)
python
def load_ext(self): """Read the internal data from an external data file.""" try: sequencemanager = hydpy.pub.sequencemanager except AttributeError: raise RuntimeError( 'The time series of sequence %s cannot be loaded. Firstly, ' 'you have to prepare `pub.sequencemanager` correctly.' % objecttools.devicephrase(self)) sequencemanager.load_file(self)
[ "def", "load_ext", "(", "self", ")", ":", "try", ":", "sequencemanager", "=", "hydpy", ".", "pub", ".", "sequencemanager", "except", "AttributeError", ":", "raise", "RuntimeError", "(", "'The time series of sequence %s cannot be loaded. Firstly, '", "'you have to prepare `pub.sequencemanager` correctly.'", "%", "objecttools", ".", "devicephrase", "(", "self", ")", ")", "sequencemanager", ".", "load_file", "(", "self", ")" ]
Read the internal data from an external data file.
[ "Read", "the", "internal", "data", "from", "an", "external", "data", "file", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L966-L975
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.adjust_short_series
def adjust_short_series(self, timegrid, values): """Adjust a short time series to a longer timegrid. Normally, time series data to be read from a external data files should span (at least) the whole initialization time period of a HydPy project. However, for some variables which are only used for comparison (e.g. observed runoff used for calibration), incomplete time series might also be helpful. This method it thought for adjusting such incomplete series to the public initialization time grid stored in module |pub|. It is automatically called in method |IOSequence.adjust_series| when necessary provided that the option |Options.checkseries| is disabled. Assume the initialization time period of a HydPy project spans five day: >>> from hydpy import pub >>> pub.timegrids = '2000.01.10', '2000.01.15', '1d' Prepare a node series object for observational data: >>> from hydpy.core.sequencetools import Obs >>> obs = Obs(None) Prepare a test function that expects the timegrid of the data and the data itself, which returns the ajdusted array by means of calling method |IOSequence.adjust_short_series|: >>> import numpy >>> def test(timegrid): ... values = numpy.ones(len(timegrid)) ... return obs.adjust_short_series(timegrid, values) The following calls to the test function shows the arrays returned for different kinds of misalignments: >>> from hydpy import Timegrid >>> test(Timegrid('2000.01.05', '2000.01.20', '1d')) array([ 1., 1., 1., 1., 1.]) >>> test(Timegrid('2000.01.12', '2000.01.15', '1d')) array([ nan, nan, 1., 1., 1.]) >>> test(Timegrid('2000.01.12', '2000.01.17', '1d')) array([ nan, nan, 1., 1., 1.]) >>> test(Timegrid('2000.01.10', '2000.01.13', '1d')) array([ 1., 1., 1., nan, nan]) >>> test(Timegrid('2000.01.08', '2000.01.13', '1d')) array([ 1., 1., 1., nan, nan]) >>> test(Timegrid('2000.01.12', '2000.01.13', '1d')) array([ nan, nan, 1., nan, nan]) >>> test(Timegrid('2000.01.05', '2000.01.10', '1d')) array([ nan, nan, nan, nan, nan]) >>> test(Timegrid('2000.01.05', '2000.01.08', '1d')) array([ nan, nan, nan, nan, nan]) >>> test(Timegrid('2000.01.15', '2000.01.18', '1d')) array([ nan, nan, nan, nan, nan]) >>> test(Timegrid('2000.01.16', '2000.01.18', '1d')) array([ nan, nan, nan, nan, nan]) Through enabling option |Options.usedefaultvalues| the missing values are initialised with zero instead of nan: >>> with pub.options.usedefaultvalues(True): ... test(Timegrid('2000.01.12', '2000.01.17', '1d')) array([ 0., 0., 1., 1., 1.]) """ idxs = [timegrid[hydpy.pub.timegrids.init.firstdate], timegrid[hydpy.pub.timegrids.init.lastdate]] valcopy = values values = numpy.full(self.seriesshape, self.initinfo[0]) len_ = len(valcopy) jdxs = [] for idx in idxs: if idx < 0: jdxs.append(0) elif idx <= len_: jdxs.append(idx) else: jdxs.append(len_) valcopy = valcopy[jdxs[0]:jdxs[1]] zdx1 = max(-idxs[0], 0) zdx2 = zdx1+jdxs[1]-jdxs[0] values[zdx1:zdx2] = valcopy return values
python
def adjust_short_series(self, timegrid, values): """Adjust a short time series to a longer timegrid. Normally, time series data to be read from a external data files should span (at least) the whole initialization time period of a HydPy project. However, for some variables which are only used for comparison (e.g. observed runoff used for calibration), incomplete time series might also be helpful. This method it thought for adjusting such incomplete series to the public initialization time grid stored in module |pub|. It is automatically called in method |IOSequence.adjust_series| when necessary provided that the option |Options.checkseries| is disabled. Assume the initialization time period of a HydPy project spans five day: >>> from hydpy import pub >>> pub.timegrids = '2000.01.10', '2000.01.15', '1d' Prepare a node series object for observational data: >>> from hydpy.core.sequencetools import Obs >>> obs = Obs(None) Prepare a test function that expects the timegrid of the data and the data itself, which returns the ajdusted array by means of calling method |IOSequence.adjust_short_series|: >>> import numpy >>> def test(timegrid): ... values = numpy.ones(len(timegrid)) ... return obs.adjust_short_series(timegrid, values) The following calls to the test function shows the arrays returned for different kinds of misalignments: >>> from hydpy import Timegrid >>> test(Timegrid('2000.01.05', '2000.01.20', '1d')) array([ 1., 1., 1., 1., 1.]) >>> test(Timegrid('2000.01.12', '2000.01.15', '1d')) array([ nan, nan, 1., 1., 1.]) >>> test(Timegrid('2000.01.12', '2000.01.17', '1d')) array([ nan, nan, 1., 1., 1.]) >>> test(Timegrid('2000.01.10', '2000.01.13', '1d')) array([ 1., 1., 1., nan, nan]) >>> test(Timegrid('2000.01.08', '2000.01.13', '1d')) array([ 1., 1., 1., nan, nan]) >>> test(Timegrid('2000.01.12', '2000.01.13', '1d')) array([ nan, nan, 1., nan, nan]) >>> test(Timegrid('2000.01.05', '2000.01.10', '1d')) array([ nan, nan, nan, nan, nan]) >>> test(Timegrid('2000.01.05', '2000.01.08', '1d')) array([ nan, nan, nan, nan, nan]) >>> test(Timegrid('2000.01.15', '2000.01.18', '1d')) array([ nan, nan, nan, nan, nan]) >>> test(Timegrid('2000.01.16', '2000.01.18', '1d')) array([ nan, nan, nan, nan, nan]) Through enabling option |Options.usedefaultvalues| the missing values are initialised with zero instead of nan: >>> with pub.options.usedefaultvalues(True): ... test(Timegrid('2000.01.12', '2000.01.17', '1d')) array([ 0., 0., 1., 1., 1.]) """ idxs = [timegrid[hydpy.pub.timegrids.init.firstdate], timegrid[hydpy.pub.timegrids.init.lastdate]] valcopy = values values = numpy.full(self.seriesshape, self.initinfo[0]) len_ = len(valcopy) jdxs = [] for idx in idxs: if idx < 0: jdxs.append(0) elif idx <= len_: jdxs.append(idx) else: jdxs.append(len_) valcopy = valcopy[jdxs[0]:jdxs[1]] zdx1 = max(-idxs[0], 0) zdx2 = zdx1+jdxs[1]-jdxs[0] values[zdx1:zdx2] = valcopy return values
[ "def", "adjust_short_series", "(", "self", ",", "timegrid", ",", "values", ")", ":", "idxs", "=", "[", "timegrid", "[", "hydpy", ".", "pub", ".", "timegrids", ".", "init", ".", "firstdate", "]", ",", "timegrid", "[", "hydpy", ".", "pub", ".", "timegrids", ".", "init", ".", "lastdate", "]", "]", "valcopy", "=", "values", "values", "=", "numpy", ".", "full", "(", "self", ".", "seriesshape", ",", "self", ".", "initinfo", "[", "0", "]", ")", "len_", "=", "len", "(", "valcopy", ")", "jdxs", "=", "[", "]", "for", "idx", "in", "idxs", ":", "if", "idx", "<", "0", ":", "jdxs", ".", "append", "(", "0", ")", "elif", "idx", "<=", "len_", ":", "jdxs", ".", "append", "(", "idx", ")", "else", ":", "jdxs", ".", "append", "(", "len_", ")", "valcopy", "=", "valcopy", "[", "jdxs", "[", "0", "]", ":", "jdxs", "[", "1", "]", "]", "zdx1", "=", "max", "(", "-", "idxs", "[", "0", "]", ",", "0", ")", "zdx2", "=", "zdx1", "+", "jdxs", "[", "1", "]", "-", "jdxs", "[", "0", "]", "values", "[", "zdx1", ":", "zdx2", "]", "=", "valcopy", "return", "values" ]
Adjust a short time series to a longer timegrid. Normally, time series data to be read from a external data files should span (at least) the whole initialization time period of a HydPy project. However, for some variables which are only used for comparison (e.g. observed runoff used for calibration), incomplete time series might also be helpful. This method it thought for adjusting such incomplete series to the public initialization time grid stored in module |pub|. It is automatically called in method |IOSequence.adjust_series| when necessary provided that the option |Options.checkseries| is disabled. Assume the initialization time period of a HydPy project spans five day: >>> from hydpy import pub >>> pub.timegrids = '2000.01.10', '2000.01.15', '1d' Prepare a node series object for observational data: >>> from hydpy.core.sequencetools import Obs >>> obs = Obs(None) Prepare a test function that expects the timegrid of the data and the data itself, which returns the ajdusted array by means of calling method |IOSequence.adjust_short_series|: >>> import numpy >>> def test(timegrid): ... values = numpy.ones(len(timegrid)) ... return obs.adjust_short_series(timegrid, values) The following calls to the test function shows the arrays returned for different kinds of misalignments: >>> from hydpy import Timegrid >>> test(Timegrid('2000.01.05', '2000.01.20', '1d')) array([ 1., 1., 1., 1., 1.]) >>> test(Timegrid('2000.01.12', '2000.01.15', '1d')) array([ nan, nan, 1., 1., 1.]) >>> test(Timegrid('2000.01.12', '2000.01.17', '1d')) array([ nan, nan, 1., 1., 1.]) >>> test(Timegrid('2000.01.10', '2000.01.13', '1d')) array([ 1., 1., 1., nan, nan]) >>> test(Timegrid('2000.01.08', '2000.01.13', '1d')) array([ 1., 1., 1., nan, nan]) >>> test(Timegrid('2000.01.12', '2000.01.13', '1d')) array([ nan, nan, 1., nan, nan]) >>> test(Timegrid('2000.01.05', '2000.01.10', '1d')) array([ nan, nan, nan, nan, nan]) >>> test(Timegrid('2000.01.05', '2000.01.08', '1d')) array([ nan, nan, nan, nan, nan]) >>> test(Timegrid('2000.01.15', '2000.01.18', '1d')) array([ nan, nan, nan, nan, nan]) >>> test(Timegrid('2000.01.16', '2000.01.18', '1d')) array([ nan, nan, nan, nan, nan]) Through enabling option |Options.usedefaultvalues| the missing values are initialised with zero instead of nan: >>> with pub.options.usedefaultvalues(True): ... test(Timegrid('2000.01.12', '2000.01.17', '1d')) array([ 0., 0., 1., 1., 1.])
[ "Adjust", "a", "short", "time", "series", "to", "a", "longer", "timegrid", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1005-L1088
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.check_completeness
def check_completeness(self): """Raise a |RuntimeError| if the |IOSequence.series| contains at least one |numpy.nan| value, if option |Options.checkseries| is enabled. >>> from hydpy import pub >>> pub.timegrids = '2000-01-01', '2000-01-11', '1d' >>> from hydpy.core.sequencetools import IOSequence >>> class Seq(IOSequence): ... NDIM = 0 >>> seq = Seq(None) >>> seq.activate_ram() >>> seq.check_completeness() Traceback (most recent call last): ... RuntimeError: The series array of sequence `seq` contains 10 nan values. >>> seq.series = 1.0 >>> seq.check_completeness() >>> seq.series[3] = numpy.nan >>> seq.check_completeness() Traceback (most recent call last): ... RuntimeError: The series array of sequence `seq` contains 1 nan value. >>> with pub.options.checkseries(False): ... seq.check_completeness() """ if hydpy.pub.options.checkseries: isnan = numpy.isnan(self.series) if numpy.any(isnan): nmb = numpy.sum(isnan) valuestring = 'value' if nmb == 1 else 'values' raise RuntimeError( f'The series array of sequence ' f'{objecttools.devicephrase(self)} contains ' f'{nmb} nan {valuestring}.')
python
def check_completeness(self): """Raise a |RuntimeError| if the |IOSequence.series| contains at least one |numpy.nan| value, if option |Options.checkseries| is enabled. >>> from hydpy import pub >>> pub.timegrids = '2000-01-01', '2000-01-11', '1d' >>> from hydpy.core.sequencetools import IOSequence >>> class Seq(IOSequence): ... NDIM = 0 >>> seq = Seq(None) >>> seq.activate_ram() >>> seq.check_completeness() Traceback (most recent call last): ... RuntimeError: The series array of sequence `seq` contains 10 nan values. >>> seq.series = 1.0 >>> seq.check_completeness() >>> seq.series[3] = numpy.nan >>> seq.check_completeness() Traceback (most recent call last): ... RuntimeError: The series array of sequence `seq` contains 1 nan value. >>> with pub.options.checkseries(False): ... seq.check_completeness() """ if hydpy.pub.options.checkseries: isnan = numpy.isnan(self.series) if numpy.any(isnan): nmb = numpy.sum(isnan) valuestring = 'value' if nmb == 1 else 'values' raise RuntimeError( f'The series array of sequence ' f'{objecttools.devicephrase(self)} contains ' f'{nmb} nan {valuestring}.')
[ "def", "check_completeness", "(", "self", ")", ":", "if", "hydpy", ".", "pub", ".", "options", ".", "checkseries", ":", "isnan", "=", "numpy", ".", "isnan", "(", "self", ".", "series", ")", "if", "numpy", ".", "any", "(", "isnan", ")", ":", "nmb", "=", "numpy", ".", "sum", "(", "isnan", ")", "valuestring", "=", "'value'", "if", "nmb", "==", "1", "else", "'values'", "raise", "RuntimeError", "(", "f'The series array of sequence '", "f'{objecttools.devicephrase(self)} contains '", "f'{nmb} nan {valuestring}.'", ")" ]
Raise a |RuntimeError| if the |IOSequence.series| contains at least one |numpy.nan| value, if option |Options.checkseries| is enabled. >>> from hydpy import pub >>> pub.timegrids = '2000-01-01', '2000-01-11', '1d' >>> from hydpy.core.sequencetools import IOSequence >>> class Seq(IOSequence): ... NDIM = 0 >>> seq = Seq(None) >>> seq.activate_ram() >>> seq.check_completeness() Traceback (most recent call last): ... RuntimeError: The series array of sequence `seq` contains 10 nan values. >>> seq.series = 1.0 >>> seq.check_completeness() >>> seq.series[3] = numpy.nan >>> seq.check_completeness() Traceback (most recent call last): ... RuntimeError: The series array of sequence `seq` contains 1 nan value. >>> with pub.options.checkseries(False): ... seq.check_completeness()
[ "Raise", "a", "|RuntimeError|", "if", "the", "|IOSequence", ".", "series|", "contains", "at", "least", "one", "|numpy", ".", "nan|", "value", "if", "option", "|Options", ".", "checkseries|", "is", "enabled", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1090-L1127
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence.save_ext
def save_ext(self): """Write the internal data into an external data file.""" try: sequencemanager = hydpy.pub.sequencemanager except AttributeError: raise RuntimeError( 'The time series of sequence %s cannot be saved. Firstly,' 'you have to prepare `pub.sequencemanager` correctly.' % objecttools.devicephrase(self)) sequencemanager.save_file(self)
python
def save_ext(self): """Write the internal data into an external data file.""" try: sequencemanager = hydpy.pub.sequencemanager except AttributeError: raise RuntimeError( 'The time series of sequence %s cannot be saved. Firstly,' 'you have to prepare `pub.sequencemanager` correctly.' % objecttools.devicephrase(self)) sequencemanager.save_file(self)
[ "def", "save_ext", "(", "self", ")", ":", "try", ":", "sequencemanager", "=", "hydpy", ".", "pub", ".", "sequencemanager", "except", "AttributeError", ":", "raise", "RuntimeError", "(", "'The time series of sequence %s cannot be saved. Firstly,'", "'you have to prepare `pub.sequencemanager` correctly.'", "%", "objecttools", ".", "devicephrase", "(", "self", ")", ")", "sequencemanager", ".", "save_file", "(", "self", ")" ]
Write the internal data into an external data file.
[ "Write", "the", "internal", "data", "into", "an", "external", "data", "file", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1129-L1138
train
hydpy-dev/hydpy
hydpy/core/sequencetools.py
IOSequence._load_int
def _load_int(self): """Load internal data from file and return it.""" values = numpy.fromfile(self.filepath_int) if self.NDIM > 0: values = values.reshape(self.seriesshape) return values
python
def _load_int(self): """Load internal data from file and return it.""" values = numpy.fromfile(self.filepath_int) if self.NDIM > 0: values = values.reshape(self.seriesshape) return values
[ "def", "_load_int", "(", "self", ")", ":", "values", "=", "numpy", ".", "fromfile", "(", "self", ".", "filepath_int", ")", "if", "self", ".", "NDIM", ">", "0", ":", "values", "=", "values", ".", "reshape", "(", "self", ".", "seriesshape", ")", "return", "values" ]
Load internal data from file and return it.
[ "Load", "internal", "data", "from", "file", "and", "return", "it", "." ]
1bc6a82cf30786521d86b36e27900c6717d3348d
https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1148-L1153
train