sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def calc_requiredrelease_v1(self):
"""Calculate the total water release (immediately and far downstream)
required for reducing drought events.
Required control parameter:
|NearDischargeMinimumThreshold|
Required derived parameters:
|NearDischargeMinimumSmoothPar2|
|dam_derived.TOY|
... | Calculate the total water release (immediately and far downstream)
required for reducing drought events.
Required control parameter:
|NearDischargeMinimumThreshold|
Required derived parameters:
|NearDischargeMinimumSmoothPar2|
|dam_derived.TOY|
Required flux sequence:
|Require... | entailment |
def calc_requiredrelease_v2(self):
"""Calculate the water release (immediately downstream) required for
reducing drought events.
Required control parameter:
|NearDischargeMinimumThreshold|
Required derived parameter:
|dam_derived.TOY|
Calculated flux sequence:
|RequiredRelease|
... | Calculate the water release (immediately downstream) required for
reducing drought events.
Required control parameter:
|NearDischargeMinimumThreshold|
Required derived parameter:
|dam_derived.TOY|
Calculated flux sequence:
|RequiredRelease|
Basic equation:
:math:`Required... | entailment |
def calc_possibleremoterelieve_v1(self):
"""Calculate the highest possible water release that can be routed to
a remote location based on an artificial neural network describing the
relationship between possible release and water stage.
Required control parameter:
|WaterLevel2PossibleRemoteReliev... | Calculate the highest possible water release that can be routed to
a remote location based on an artificial neural network describing the
relationship between possible release and water stage.
Required control parameter:
|WaterLevel2PossibleRemoteRelieve|
Required aide sequence:
|WaterLeve... | entailment |
def calc_actualremoterelieve_v1(self):
"""Calculate the actual amount of water released to a remote location
to relieve the dam during high flow conditions.
Required control parameter:
|RemoteRelieveTolerance|
Required flux sequences:
|AllowedRemoteRelieve|
|PossibleRemoteRelieve|
... | Calculate the actual amount of water released to a remote location
to relieve the dam during high flow conditions.
Required control parameter:
|RemoteRelieveTolerance|
Required flux sequences:
|AllowedRemoteRelieve|
|PossibleRemoteRelieve|
Calculated flux sequence:
|ActualRemo... | entailment |
def calc_targetedrelease_v1(self):
"""Calculate the targeted water release for reducing drought events,
taking into account both the required water release and the actual
inflow into the dam.
Some dams are supposed to maintain a certain degree of low flow
variability downstream. In case parameter ... | Calculate the targeted water release for reducing drought events,
taking into account both the required water release and the actual
inflow into the dam.
Some dams are supposed to maintain a certain degree of low flow
variability downstream. In case parameter |RestrictTargetedRelease|
is set to `T... | entailment |
def calc_actualrelease_v1(self):
"""Calculate the actual water release that can be supplied by the
dam considering the targeted release and the given water level.
Required control parameter:
|WaterLevelMinimumThreshold|
Required derived parameters:
|WaterLevelMinimumSmoothPar|
Require... | Calculate the actual water release that can be supplied by the
dam considering the targeted release and the given water level.
Required control parameter:
|WaterLevelMinimumThreshold|
Required derived parameters:
|WaterLevelMinimumSmoothPar|
Required flux sequence:
|TargetedRelease|... | entailment |
def calc_missingremoterelease_v1(self):
"""Calculate the portion of the required remote demand that could not
be met by the actual discharge release.
Required flux sequences:
|RequiredRemoteRelease|
|ActualRelease|
Calculated flux sequence:
|MissingRemoteRelease|
Basic equation:... | Calculate the portion of the required remote demand that could not
be met by the actual discharge release.
Required flux sequences:
|RequiredRemoteRelease|
|ActualRelease|
Calculated flux sequence:
|MissingRemoteRelease|
Basic equation:
:math:`MissingRemoteRelease = max(
... | entailment |
def calc_actualremoterelease_v1(self):
"""Calculate the actual remote water release that can be supplied by the
dam considering the required remote release and the given water level.
Required control parameter:
|WaterLevelMinimumRemoteThreshold|
Required derived parameters:
|WaterLevelMini... | Calculate the actual remote water release that can be supplied by the
dam considering the required remote release and the given water level.
Required control parameter:
|WaterLevelMinimumRemoteThreshold|
Required derived parameters:
|WaterLevelMinimumRemoteSmoothPar|
Required flux sequenc... | entailment |
def update_actualremoterelieve_v1(self):
"""Constrain the actual relieve discharge to a remote location.
Required control parameter:
|HighestRemoteDischarge|
Required derived parameter:
|HighestRemoteSmoothPar|
Updated flux sequence:
|ActualRemoteRelieve|
Basic equation - disco... | Constrain the actual relieve discharge to a remote location.
Required control parameter:
|HighestRemoteDischarge|
Required derived parameter:
|HighestRemoteSmoothPar|
Updated flux sequence:
|ActualRemoteRelieve|
Basic equation - discontinous:
:math:`ActualRemoteRelieve = min(... | entailment |
def calc_flooddischarge_v1(self):
"""Calculate the discharge during and after a flood event based on an
|anntools.SeasonalANN| describing the relationship(s) between discharge
and water stage.
Required control parameter:
|WaterLevel2FloodDischarge|
Required derived parameter:
|dam_deri... | Calculate the discharge during and after a flood event based on an
|anntools.SeasonalANN| describing the relationship(s) between discharge
and water stage.
Required control parameter:
|WaterLevel2FloodDischarge|
Required derived parameter:
|dam_derived.TOY|
Required aide sequence:
... | entailment |
def calc_outflow_v1(self):
"""Calculate the total outflow of the dam.
Note that the maximum function is used to prevent from negative outflow
values, which could otherwise occur within the required level of
numerical accuracy.
Required flux sequences:
|ActualRelease|
|FloodDischarge|
... | Calculate the total outflow of the dam.
Note that the maximum function is used to prevent from negative outflow
values, which could otherwise occur within the required level of
numerical accuracy.
Required flux sequences:
|ActualRelease|
|FloodDischarge|
Calculated flux sequence:
... | entailment |
def update_watervolume_v1(self):
"""Update the actual water volume.
Required derived parameter:
|Seconds|
Required flux sequences:
|Inflow|
|Outflow|
Updated state sequence:
|WaterVolume|
Basic equation:
:math:`\\frac{d}{dt}WaterVolume = 1e-6 \\cdot (Inflow-Outflow)... | Update the actual water volume.
Required derived parameter:
|Seconds|
Required flux sequences:
|Inflow|
|Outflow|
Updated state sequence:
|WaterVolume|
Basic equation:
:math:`\\frac{d}{dt}WaterVolume = 1e-6 \\cdot (Inflow-Outflow)`
Example:
>>> from hydpy.... | entailment |
def pass_outflow_v1(self):
"""Update the outlet link sequence |dam_outlets.Q|."""
flu = self.sequences.fluxes.fastaccess
out = self.sequences.outlets.fastaccess
out.q[0] += flu.outflow | Update the outlet link sequence |dam_outlets.Q|. | entailment |
def pass_actualremoterelease_v1(self):
"""Update the outlet link sequence |dam_outlets.S|."""
flu = self.sequences.fluxes.fastaccess
out = self.sequences.outlets.fastaccess
out.s[0] += flu.actualremoterelease | Update the outlet link sequence |dam_outlets.S|. | entailment |
def pass_actualremoterelieve_v1(self):
"""Update the outlet link sequence |dam_outlets.R|."""
flu = self.sequences.fluxes.fastaccess
out = self.sequences.outlets.fastaccess
out.r[0] += flu.actualremoterelieve | Update the outlet link sequence |dam_outlets.R|. | entailment |
def pass_missingremoterelease_v1(self):
"""Update the outlet link sequence |dam_senders.D|."""
flu = self.sequences.fluxes.fastaccess
sen = self.sequences.senders.fastaccess
sen.d[0] += flu.missingremoterelease | Update the outlet link sequence |dam_senders.D|. | entailment |
def pass_allowedremoterelieve_v1(self):
"""Update the outlet link sequence |dam_outlets.R|."""
flu = self.sequences.fluxes.fastaccess
sen = self.sequences.senders.fastaccess
sen.r[0] += flu.allowedremoterelieve | Update the outlet link sequence |dam_outlets.R|. | entailment |
def pass_requiredremotesupply_v1(self):
"""Update the outlet link sequence |dam_outlets.S|."""
flu = self.sequences.fluxes.fastaccess
sen = self.sequences.senders.fastaccess
sen.s[0] += flu.requiredremotesupply | Update the outlet link sequence |dam_outlets.S|. | entailment |
def update_loggedoutflow_v1(self):
"""Log a new entry of discharge at a cross section far downstream.
Required control parameter:
|NmbLogEntries|
Required flux sequence:
|Outflow|
Calculated flux sequence:
|LoggedOutflow|
Example:
The following example shows that, with... | Log a new entry of discharge at a cross section far downstream.
Required control parameter:
|NmbLogEntries|
Required flux sequence:
|Outflow|
Calculated flux sequence:
|LoggedOutflow|
Example:
The following example shows that, with each new method call, the
three m... | entailment |
def update_coefs(self):
"""(Re)calculate the MA coefficients based on the instantaneous
unit hydrograph."""
coefs = []
sum_coefs = 0.
moment1 = self.iuh.moment1
for t in itertools.count(0., 1.):
points = (moment1 % 1,) if t <= moment1 <= (t+2.) else ()
... | (Re)calculate the MA coefficients based on the instantaneous
unit hydrograph. | entailment |
def turningpoint(self):
"""Turning point (index and value tuple) in the recession part of the
MA approximation of the instantaneous unit hydrograph."""
coefs = self.coefs
old_dc = coefs[1]-coefs[0]
for idx in range(self.order-2):
new_dc = coefs[idx+2]-coefs[idx+1]
... | Turning point (index and value tuple) in the recession part of the
MA approximation of the instantaneous unit hydrograph. | entailment |
def moments(self):
"""The first two time delay weighted statistical moments of the
MA coefficients."""
moment1 = statstools.calc_mean_time(self.delays, self.coefs)
moment2 = statstools.calc_mean_time_deviation(
self.delays, self.coefs, moment1)
return numpy.array([mom... | The first two time delay weighted statistical moments of the
MA coefficients. | entailment |
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... | 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. | entailment |
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... | 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. | entailment |
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)) | Sum of the absolute deviations between the central moments of the
instantaneous unit hydrograph and the ARMA approximation. | entailment |
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 | Multiply all coefficients by the same factor, so that their sum
becomes one. | entailment |
def sum_coefs(self):
"""The sum of all AR and MA coefficients"""
return numpy.sum(self.ar_coefs) + numpy.sum(self.ma_coefs) | The sum of all AR and MA coefficients | entailment |
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 o... | 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 ... | entailment |
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)... | 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|. | entailment |
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... | 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. | entailment |
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... | 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 t... | entailment |
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_ord... | Return the response to a standard dt impulse. | entailment |
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(
t... | The first two time delay weighted statistical moments of the
ARMA response. | entailment |
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
#... | Barplot of the ARMA response. | entailment |
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 ')'
head... | Returns the Cython method header for methods without arguments except
`self`. | entailment |
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()
... | 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. | entailment |
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... | Appends the given text line with prefixed spaces in accordance with
the given number of indentation levels. | entailment |
def pyname(self):
"""Name of the compiled module."""
if self.pymodule.endswith('__init__'):
return self.pymodule.split('.')[-2]
else:
return self.pymodule.split('.')[-1] | Name of the compiled module. | entailment |
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'):
mo... | Update the pyx file. | entailment |
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:
... | All source files of the actual models Python classes and their
respective base classes. | entailment |
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... | True if at least one of the |Cythonizer.pysourcefiles| is
newer than the compiled file under |Cythonizer.pyxfilepath|,
otherwise False. | entailment |
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(
... | Translate cython code to C code and compile it. | entailment |
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 subfo... | 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.
... | entailment |
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.arra... | Constants declaration lines. | entailment |
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'
... | Parameter declaration lines. | entailment |
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(s... | Sequence declaration lines. | entailment |
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)
lin... | Special declaration lines for the given |IOSequence| object. | entailment |
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... | Open file statements. | entailment |
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_fil... | Close file statements. | entailment |
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.a... | Load data statements. | entailment |
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:
... | Set_pointer functions for link sequences. | entailment |
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:
... | Set_pointer function for 0-dimensional link sequences. | entailment |
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.a... | Allocate memory for 1-dimensional link sequences. | entailment |
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 | Deallocate memory for 1-dimensional link sequences. | entailment |
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 subseq... | Set_pointer function for 1-dimensional link sequences. | entailment |
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(... | Numeric parameter declaration lines. | entailment |
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.ad... | Attribute declarations of the model class. | entailment |
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.updat... | Standard functions of the model class. | entailment |
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_poin... | Numerical functions of the model class. | entailment |
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... | Do (most of) it function of the model class. | entailment |
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)):
con... | Input/output functions of the model class. | entailment |
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 ='
... | Lines of model method with the same name. | entailment |
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.g... | User functions of the model class. | entailment |
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
... | 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 contain... | entailment |
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_withi... | 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)' | entailment |
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
... | 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... | entailment |
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`
... | 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 sta... | entailment |
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
... | 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)
... | entailment |
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... | 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])
>>> ... | entailment |
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.])... | 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::
... | entailment |
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 (mo... | 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 uni... | entailment |
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
... | 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_cfu... | entailment |
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 numbe... | Convenience method for `_set_year`, `_set_month`... | entailment |
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
... | 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
... | entailment |
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 you... | 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
... | entailment |
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))) | Return a |Period| instance based on a given number of seconds. | entailment |
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 ... | Guess the unit of the period as the largest one, which results in
an integer duration. | entailment |
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]),
... | Returns a |Timegrid| instance based on two date and one period
information stored in the first 13 rows of a |numpy.ndarray| object. | entailment |
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(... | 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. | entailment |
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 give... | 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, t... | entailment |
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 h... | 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
>>> timeg... | entailment |
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 `array2s... | 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
... | entailment |
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... | Raise an |ValueError| if the dates or the step size of the time
frame are inconsistent. | entailment |
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',
... ... | 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',
... ... | entailment |
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 '
... | Raise an |ValueError| it the different time grids are
inconsistent. | entailment |
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.ap... | Return a |repr| string with a prefixed assignment. | entailment |
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 ... | 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 ... | entailment |
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 2... | 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:... | entailment |
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',
'200... | 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') | entailment |
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 h... | 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
>>>... | entailment |
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 = ... | 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 | entailment |
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 ... | 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):
... ... | entailment |
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 t... | 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:
... | entailment |
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 follo... | 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 hy... | entailment |
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:... | 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 ... | entailment |
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,
... | 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 beha... | entailment |
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) + ')')
t... | 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 n... | entailment |
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(') + ')'... | 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.... | entailment |
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 += bracket... | Return a prefixed, wrapped and properly aligned bracketed string
representation of the given 2-dimensional value matrix using function
|repr|. | entailment |
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 w... | 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 ... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.