sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def trim(self, lower=None, upper=None):
"""Trim upper values in accordance with
:math:`EQI2 \\leq EQI1 \\leq EQB`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqb.value = 3.0
>>> eqi2.value = 1.0
>>> eqi1(0.0)
>>> eqi1
eqi1(1.... | Trim upper values in accordance with
:math:`EQI2 \\leq EQI1 \\leq EQB`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqb.value = 3.0
>>> eqi2.value = 1.0
>>> eqi1(0.0)
>>> eqi1
eqi1(1.0)
>>> eqi1(1.0)
>>> eqi1
e... | entailment |
def time_choices():
"""Return digital time choices every half hour from 00:00 to 23:30."""
hours = list(range(0, 24))
times = []
for h in hours:
hour = str(h).zfill(2)
times.append(hour+':00')
times.append(hour+':30')
return list(zip(times, times)) | Return digital time choices every half hour from 00:00 to 23:30. | entailment |
def _add_lines(specification, module):
"""Return autodoc commands for a basemodels docstring.
Note that `collection classes` (e.g. `Model`, `ControlParameters`,
`InputSequences` are placed on top of the respective section and the
`contained classes` (e.g. model methods, `ControlParameter` instances,
... | Return autodoc commands for a basemodels docstring.
Note that `collection classes` (e.g. `Model`, `ControlParameters`,
`InputSequences` are placed on top of the respective section and the
`contained classes` (e.g. model methods, `ControlParameter` instances,
`InputSequence` instances at the bottom. Th... | entailment |
def autodoc_basemodel(module):
"""Add an exhaustive docstring to the given module of a basemodel.
Works onlye when all modules of the basemodel are named in the
standard way, e.g. `lland_model`, `lland_control`, `lland_inputs`.
"""
autodoc_tuple2doc(module)
namespace = module.__dict__
doc =... | Add an exhaustive docstring to the given module of a basemodel.
Works onlye when all modules of the basemodel are named in the
standard way, e.g. `lland_model`, `lland_control`, `lland_inputs`. | entailment |
def autodoc_applicationmodel(module):
"""Improves the docstrings of application models when called
at the bottom of the respective module.
|autodoc_applicationmodel| requires, similar to
|autodoc_basemodel|, that both the application model and its
base model are defined in the conventional way.
... | Improves the docstrings of application models when called
at the bottom of the respective module.
|autodoc_applicationmodel| requires, similar to
|autodoc_basemodel|, that both the application model and its
base model are defined in the conventional way. | entailment |
def prepare_mainsubstituter():
"""Prepare and return a |Substituter| object for the main `__init__`
file of *HydPy*."""
substituter = Substituter()
for module in (builtins, numpy, datetime, unittest, doctest, inspect, io,
os, sys, time, collections, itertools, subprocess, scipy,
... | Prepare and return a |Substituter| object for the main `__init__`
file of *HydPy*. | entailment |
def _number_of_line(member_tuple):
"""Try to return the number of the first line of the definition of a
member of a module."""
member = member_tuple[1]
try:
return member.__code__.co_firstlineno
except AttributeError:
pass
try:
return inspect.findsource(member)[1]
exc... | Try to return the number of the first line of the definition of a
member of a module. | entailment |
def autodoc_module(module):
"""Add a short summary of all implemented members to a modules docstring.
"""
doc = getattr(module, '__doc__')
if doc is None:
doc = ''
members = []
for name, member in inspect.getmembers(module):
if ((not name.startswith('_')) and
(ins... | Add a short summary of all implemented members to a modules docstring. | entailment |
def autodoc_tuple2doc(module):
"""Include tuples as `CLASSES` of `ControlParameters` and `RUN_METHODS`
of `Models` into the respective docstring."""
modulename = module.__name__
for membername, member in inspect.getmembers(module):
for tuplename, descr in _name2descr.items():
tuple_ ... | Include tuples as `CLASSES` of `ControlParameters` and `RUN_METHODS`
of `Models` into the respective docstring. | entailment |
def consider_member(name_member, member, module, class_=None):
"""Return |True| if the given member should be added to the
substitutions. If not return |False|.
Some examples based on the site-package |numpy|:
>>> from hydpy.core.autodoctools import Substituter
>>> import numpy... | Return |True| if the given member should be added to the
substitutions. If not return |False|.
Some examples based on the site-package |numpy|:
>>> from hydpy.core.autodoctools import Substituter
>>> import numpy
A constant like |nan| should be added:
>>> Substituter.... | entailment |
def get_role(member, cython=False):
"""Return the reStructuredText role `func`, `class`, or `const`
best describing the given member.
Some examples based on the site-package |numpy|. |numpy.clip|
is a function:
>>> from hydpy.core.autodoctools import Substituter
>>> im... | Return the reStructuredText role `func`, `class`, or `const`
best describing the given member.
Some examples based on the site-package |numpy|. |numpy.clip|
is a function:
>>> from hydpy.core.autodoctools import Substituter
>>> import numpy
>>> Substituter.get_role(num... | entailment |
def add_substitution(self, short, medium, long, module):
"""Add the given substitutions both as a `short2long` and a
`medium2long` mapping.
Assume `variable1` is defined in the hydpy module `module1` and the
short and medium descriptions are `var1` and `mod1.var1`:
>>> import t... | Add the given substitutions both as a `short2long` and a
`medium2long` mapping.
Assume `variable1` is defined in the hydpy module `module1` and the
short and medium descriptions are `var1` and `mod1.var1`:
>>> import types
>>> module1 = types.ModuleType('hydpy.module1')
... | entailment |
def add_module(self, module, cython=False):
"""Add the given module, its members, and their submembers.
The first examples are based on the site-package |numpy|: which
is passed to method |Substituter.add_module|:
>>> from hydpy.core.autodoctools import Substituter
>>> substitu... | Add the given module, its members, and their submembers.
The first examples are based on the site-package |numpy|: which
is passed to method |Substituter.add_module|:
>>> from hydpy.core.autodoctools import Substituter
>>> substituter = Substituter()
>>> import numpy
>>... | entailment |
def add_modules(self, package):
"""Add the modules of the given package without their members."""
for name in os.listdir(package.__path__[0]):
if name.startswith('_'):
continue
name = name.split('.')[0]
short = '|%s|' % name
long = ':mod:`~... | Add the modules of the given package without their members. | entailment |
def update_masters(self):
"""Update all `master` |Substituter| objects.
If a |Substituter| object is passed to the constructor of another
|Substituter| object, they become `master` and `slave`:
>>> from hydpy.core.autodoctools import Substituter
>>> sub1 = Substituter()
... | Update all `master` |Substituter| objects.
If a |Substituter| object is passed to the constructor of another
|Substituter| object, they become `master` and `slave`:
>>> from hydpy.core.autodoctools import Substituter
>>> sub1 = Substituter()
>>> from hydpy.core import devicetoo... | entailment |
def update_slaves(self):
"""Update all `slave` |Substituter| objects.
See method |Substituter.update_masters| for further information.
"""
for slave in self.slaves:
slave._medium2long.update(self._medium2long)
slave.update_slaves() | Update all `slave` |Substituter| objects.
See method |Substituter.update_masters| for further information. | entailment |
def get_commands(self, source=None):
"""Return a string containing multiple `reStructuredText`
replacements with the substitutions currently defined.
Some examples based on the subpackage |optiontools|:
>>> from hydpy.core.autodoctools import Substituter
>>> substituter = Subst... | Return a string containing multiple `reStructuredText`
replacements with the substitutions currently defined.
Some examples based on the subpackage |optiontools|:
>>> from hydpy.core.autodoctools import Substituter
>>> substituter = Substituter()
>>> from hydpy.core import opti... | entailment |
def find(self, text):
"""Print all substitutions that include the given text string."""
for key, value in self:
if (text in key) or (text in value):
print(key, value) | Print all substitutions that include the given text string. | entailment |
def print_progress(wrapped, _=None, args=None, kwargs=None):
"""Add print commands time to the given function informing about
execution time.
To show how the |print_progress| decorator works, we need to modify the
functions used by |print_progress| to gain system time information
available in modu... | Add print commands time to the given function informing about
execution time.
To show how the |print_progress| decorator works, we need to modify the
functions used by |print_progress| to gain system time information
available in module |time|.
First, we mock the functions |time.strftime| and |ti... | entailment |
def progressbar(iterable, length=23):
"""Print a simple progress bar while processing the given iterable.
Function |progressbar| does print the progress bar when option
`printprogress` is activted:
>>> from hydpy import pub
>>> pub.options.printprogress = True
You can pass an iterable object.... | Print a simple progress bar while processing the given iterable.
Function |progressbar| does print the progress bar when option
`printprogress` is activted:
>>> from hydpy import pub
>>> pub.options.printprogress = True
You can pass an iterable object. Say you want to calculate the the sum
o... | entailment |
def start_server(socket, projectname, xmlfilename: str) -> None:
"""Start the *HydPy* server using the given socket.
The folder with the given `projectname` must be available within the
current working directory. The XML configuration file must be placed
within the project folder unless `xmlfilename` ... | Start the *HydPy* server using the given socket.
The folder with the given `projectname` must be available within the
current working directory. The XML configuration file must be placed
within the project folder unless `xmlfilename` is an absolute file path.
The XML configuration file must be valid c... | entailment |
def await_server(port, seconds):
"""Block the current process until either the *HydPy* server is responding
on the given `port` or the given number of `seconds` elapsed.
>>> from hydpy import run_subprocess, TestIO
>>> with TestIO(): # doctest: +ELLIPSIS
... run_subprocess('hyd.py await_serv... | Block the current process until either the *HydPy* server is responding
on the given `port` or the given number of `seconds` elapsed.
>>> from hydpy import run_subprocess, TestIO
>>> with TestIO(): # doctest: +ELLIPSIS
... run_subprocess('hyd.py await_server 8080 0.1')
Invoking hyd.py with a... | entailment |
def initialise(self, projectname: str, xmlfile: str) -> None:
"""Initialise a *HydPy* project based on the given XML configuration
file agreeing with `HydPyConfigMultipleRuns.xsd`.
We use the `LahnH` project and its rather complex XML configuration
file `multiple_runs.xml` as an example... | Initialise a *HydPy* project based on the given XML configuration
file agreeing with `HydPyConfigMultipleRuns.xsd`.
We use the `LahnH` project and its rather complex XML configuration
file `multiple_runs.xml` as an example (module |xmltools| provides
information on interpreting this fil... | entailment |
def POST_evaluate(self) -> None:
"""Evaluate any valid Python expression with the *HydPy* server
process and get its result.
Method |HydPyServer.POST_evaluate| serves to test and debug, primarily.
The main documentation on module |servertools| explains its usage.
"""
for... | Evaluate any valid Python expression with the *HydPy* server
process and get its result.
Method |HydPyServer.POST_evaluate| serves to test and debug, primarily.
The main documentation on module |servertools| explains its usage. | entailment |
def GET_close_server(self) -> None:
"""Stop and close the *HydPy* server."""
def _close_server():
self.server.shutdown()
self.server.server_close()
shutter = threading.Thread(target=_close_server)
shutter.deamon = True
shutter.start() | Stop and close the *HydPy* server. | entailment |
def GET_parameteritemtypes(self) -> None:
"""Get the types of all current exchange items supposed to change
the values of |Parameter| objects."""
for item in state.parameteritems:
self._outputs[item.name] = self._get_itemtype(item) | Get the types of all current exchange items supposed to change
the values of |Parameter| objects. | entailment |
def GET_conditionitemtypes(self) -> None:
"""Get the types of all current exchange items supposed to change
the values of |StateSequence| or |LogSequence| objects."""
for item in state.conditionitems:
self._outputs[item.name] = self._get_itemtype(item) | Get the types of all current exchange items supposed to change
the values of |StateSequence| or |LogSequence| objects. | entailment |
def GET_getitemtypes(self) -> None:
"""Get the types of all current exchange items supposed to return
the values of |Parameter| or |Sequence| objects or the time series
of |IOSequence| objects."""
for item in state.getitems:
type_ = self._get_itemtype(item)
for na... | Get the types of all current exchange items supposed to return
the values of |Parameter| or |Sequence| objects or the time series
of |IOSequence| objects. | entailment |
def POST_timegrid(self) -> None:
"""Change the current simulation |Timegrid|."""
init = hydpy.pub.timegrids.init
sim = hydpy.pub.timegrids.sim
sim.firstdate = self._inputs['firstdate']
sim.lastdate = self._inputs['lastdate']
state.idx1 = init[sim.firstdate]
state.... | Change the current simulation |Timegrid|. | entailment |
def GET_parameteritemvalues(self) -> None:
"""Get the values of all |ChangeItem| objects handling |Parameter|
objects."""
for item in state.parameteritems:
self._outputs[item.name] = item.value | Get the values of all |ChangeItem| objects handling |Parameter|
objects. | entailment |
def GET_conditionitemvalues(self) -> None:
"""Get the values of all |ChangeItem| objects handling |StateSequence|
or |LogSequence| objects."""
for item in state.conditionitems:
self._outputs[item.name] = item.value | Get the values of all |ChangeItem| objects handling |StateSequence|
or |LogSequence| objects. | entailment |
def GET_getitemvalues(self) -> None:
"""Get the values of all |Variable| objects observed by the
current |GetItem| objects.
For |GetItem| objects observing time series,
|HydPyServer.GET_getitemvalues| returns only the values within
the current simulation period.
"""
... | Get the values of all |Variable| objects observed by the
current |GetItem| objects.
For |GetItem| objects observing time series,
|HydPyServer.GET_getitemvalues| returns only the values within
the current simulation period. | entailment |
def GET_load_conditionvalues(self) -> None:
"""Assign the |StateSequence| or |LogSequence| object values available
for the current simulation start point to the current |HydPy| instance.
When the simulation start point is identical with the initialisation
time point and you did not save... | Assign the |StateSequence| or |LogSequence| object values available
for the current simulation start point to the current |HydPy| instance.
When the simulation start point is identical with the initialisation
time point and you did not save conditions for it beforehand, the
"original" i... | entailment |
def GET_save_conditionvalues(self) -> None:
"""Save the |StateSequence| and |LogSequence| object values of the
current |HydPy| instance for the current simulation endpoint."""
state.conditions[self._id] = state.conditions.get(self._id, {})
state.conditions[self._id][state.idx2] = state.h... | Save the |StateSequence| and |LogSequence| object values of the
current |HydPy| instance for the current simulation endpoint. | entailment |
def GET_save_parameteritemvalues(self) -> None:
"""Save the values of those |ChangeItem| objects which are
handling |Parameter| objects."""
for item in state.parameteritems:
state.parameteritemvalues[self._id][item.name] = item.value.copy() | Save the values of those |ChangeItem| objects which are
handling |Parameter| objects. | entailment |
def GET_savedparameteritemvalues(self) -> None:
"""Get the previously saved values of those |ChangeItem| objects
which are handling |Parameter| objects."""
dict_ = state.parameteritemvalues.get(self._id)
if dict_ is None:
self.GET_parameteritemvalues()
else:
... | Get the previously saved values of those |ChangeItem| objects
which are handling |Parameter| objects. | entailment |
def GET_save_modifiedconditionitemvalues(self) -> None:
"""ToDo: extend functionality and add tests"""
for item in state.conditionitems:
state.modifiedconditionitemvalues[self._id][item.name] = \
list(item.device2target.values())[0].value | ToDo: extend functionality and add tests | entailment |
def GET_savedmodifiedconditionitemvalues(self) -> None:
"""ToDo: extend functionality and add tests"""
dict_ = state.modifiedconditionitemvalues.get(self._id)
if dict_ is None:
self.GET_conditionitemvalues()
else:
for name, value in dict_.items():
... | ToDo: extend functionality and add tests | entailment |
def GET_save_getitemvalues(self) -> None:
"""Save the values of all current |GetItem| objects."""
for item in state.getitems:
for name, value in item.yield_name2value(state.idx1, state.idx2):
state.getitemvalues[self._id][name] = value | Save the values of all current |GetItem| objects. | entailment |
def GET_savedgetitemvalues(self) -> None:
"""Get the previously saved values of all |GetItem| objects."""
dict_ = state.getitemvalues.get(self._id)
if dict_ is None:
self.GET_getitemvalues()
else:
for name, value in dict_.items():
self._outputs[nam... | Get the previously saved values of all |GetItem| objects. | entailment |
def GET_save_timegrid(self) -> None:
"""Save the current simulation period."""
state.timegrids[self._id] = copy.deepcopy(hydpy.pub.timegrids.sim) | Save the current simulation period. | entailment |
def GET_savedtimegrid(self) -> None:
"""Get the previously saved simulation period."""
try:
self._write_timegrid(state.timegrids[self._id])
except KeyError:
self._write_timegrid(hydpy.pub.timegrids.init) | Get the previously saved simulation period. | entailment |
def trim(self: 'Variable', lower=None, upper=None) -> None:
"""Trim the value(s) of a |Variable| instance.
Usually, users do not need to apply function |trim| directly.
Instead, some |Variable| subclasses implement their own `trim`
methods relying on function |trim|. Model developers should
implem... | Trim the value(s) of a |Variable| instance.
Usually, users do not need to apply function |trim| directly.
Instead, some |Variable| subclasses implement their own `trim`
methods relying on function |trim|. Model developers should
implement individual `trim` methods for their |Parameter| or
|Sequenc... | entailment |
def _get_tolerance(values):
"""Return some "numerical accuracy" to be expected for the
given floating point value(s) (see method |trim|)."""
tolerance = numpy.abs(values*1e-15)
if hasattr(tolerance, '__setitem__'):
tolerance[numpy.isinf(tolerance)] = 0.
elif numpy.isinf(tolerance):
t... | Return some "numerical accuracy" to be expected for the
given floating point value(s) (see method |trim|). | entailment |
def _compare_variables_function_generator(
method_string, aggregation_func):
"""Return a function usable as a comparison method for class |Variable|.
Pass the specific method (e.g. `__eq__`) and the corresponding
operator (e.g. `==`) as strings. Also pass either |numpy.all| or
|numpy.any| for... | Return a function usable as a comparison method for class |Variable|.
Pass the specific method (e.g. `__eq__`) and the corresponding
operator (e.g. `==`) as strings. Also pass either |numpy.all| or
|numpy.any| for aggregating multiple boolean values. | entailment |
def to_repr(self: Variable, values, brackets1d: Optional[bool] = False) \
-> str:
"""Return a valid string representation for the given |Variable|
object.
Function |to_repr| it thought for internal purposes only, more
specifically for defining string representations of subclasses
of class |... | Return a valid string representation for the given |Variable|
object.
Function |to_repr| it thought for internal purposes only, more
specifically for defining string representations of subclasses
of class |Variable| like the following:
>>> from hydpy.core.variabletools import to_repr, Variable
... | entailment |
def verify(self) -> None:
"""Raises a |RuntimeError| if at least one of the required values
of a |Variable| object is |None| or |numpy.nan|. The descriptor
`mask` defines, which values are considered to be necessary.
Example on a 0-dimensional |Variable|:
>>> from hydpy.core.va... | Raises a |RuntimeError| if at least one of the required values
of a |Variable| object is |None| or |numpy.nan|. The descriptor
`mask` defines, which values are considered to be necessary.
Example on a 0-dimensional |Variable|:
>>> from hydpy.core.variabletools import Variable
>... | entailment |
def average_values(self, *args, **kwargs) -> float:
"""Average the actual values of the |Variable| object.
For 0-dimensional |Variable| objects, the result of method
|Variable.average_values| equals |Variable.value|. The
following example shows this for the sloppily defined class
... | Average the actual values of the |Variable| object.
For 0-dimensional |Variable| objects, the result of method
|Variable.average_values| equals |Variable.value|. The
following example shows this for the sloppily defined class
`SoilMoisture`:
>>> from hydpy.core.variabletools i... | entailment |
def get_submask(self, *args, **kwargs) -> masktools.CustomMask:
"""Get a sub-mask of the mask handled by the actual |Variable| object
based on the given arguments.
See the documentation on method |Variable.average_values| for
further information.
"""
if args or kwargs:
... | Get a sub-mask of the mask handled by the actual |Variable| object
based on the given arguments.
See the documentation on method |Variable.average_values| for
further information. | entailment |
def commentrepr(self) -> List[str]:
"""A list with comments for making string representations
more informative.
With option |Options.reprcomments| being disabled,
|Variable.commentrepr| is empty.
"""
if hydpy.pub.options.reprcomments:
return [f'# {line}' for ... | A list with comments for making string representations
more informative.
With option |Options.reprcomments| being disabled,
|Variable.commentrepr| is empty. | entailment |
def AddTable(p_workSheet = None, p_headerDict = None, p_startColumn = 1, p_startRow = 1, p_headerHeight = None, p_data = None, p_mainTable = False, p_conditionalFormatting = None, p_tableStyleInfo = None, p_withFilters = True):
"""Insert a table in a given worksheet.
Args:
p_workSheet (openpyxl... | Insert a table in a given worksheet.
Args:
p_workSheet (openpyxl.worksheet.worksheet.Worksheet): the worksheet where the table will be inserted. Defaults to None.
p_headerDict (collections.OrderedDict): an ordered dict that contains table header columns.
Notes:
... | entailment |
def get_controlfileheader(
model: Union[str, 'modeltools.Model'],
parameterstep: timetools.PeriodConstrArg = None,
simulationstep: timetools.PeriodConstrArg = None) -> str:
"""Return the header of a regular or auxiliary parameter control file.
The header contains the default coding info... | Return the header of a regular or auxiliary parameter control file.
The header contains the default coding information, the import command
for the given model and the actual parameter and simulation step sizes.
The first example shows that, if you pass the model argument as a
string, you have to take ... | entailment |
def _prepare_docstrings(self, frame):
"""Assign docstrings to the constants handled by |Constants|
to make them available in the interactive mode of Python."""
if config.USEAUTODOC:
filename = inspect.getsourcefile(frame)
with open(filename) as file_:
sour... | Assign docstrings to the constants handled by |Constants|
to make them available in the interactive mode of Python. | entailment |
def update(self) -> None:
"""Call method |Parameter.update| of all "secondary" parameters.
Directly after initialisation, neither the primary (`control`)
parameters nor the secondary (`derived`) parameters of
application model |hstream_v1| are ready for usage:
>>> from hydpy.m... | Call method |Parameter.update| of all "secondary" parameters.
Directly after initialisation, neither the primary (`control`)
parameters nor the secondary (`derived`) parameters of
application model |hstream_v1| are ready for usage:
>>> from hydpy.models.hstream_v1 import *
>>>... | entailment |
def save_controls(self, filepath: Optional[str] = None,
parameterstep: timetools.PeriodConstrArg = None,
simulationstep: timetools.PeriodConstrArg = None,
auxfiler: 'auxfiletools.Auxfiler' = None):
"""Write the control parameters to file.
... | Write the control parameters to file.
Usually, a control file consists of a header (see the documentation
on the method |get_controlfileheader|) and the string representations
of the individual |Parameter| objects handled by the `control`
|SubParameters| object.
The main functi... | entailment |
def _get_values_from_auxiliaryfile(self, auxfile):
"""Try to return the parameter values from the auxiliary control file
with the given name.
Things are a little complicated here. To understand this method, you
should first take a look at the |parameterstep| function.
"""
... | Try to return the parameter values from the auxiliary control file
with the given name.
Things are a little complicated here. To understand this method, you
should first take a look at the |parameterstep| function. | entailment |
def initinfo(self) -> Tuple[Union[float, int, bool], bool]:
"""The actual initial value of the given parameter.
Some |Parameter| subclasses define another value for class
attribute `INIT` than |None| to provide a default value.
Let's define a parameter test class and prepare a function... | The actual initial value of the given parameter.
Some |Parameter| subclasses define another value for class
attribute `INIT` than |None| to provide a default value.
Let's define a parameter test class and prepare a function for
initialising it and connecting the resulting instance to a... | entailment |
def get_timefactor(cls) -> float:
"""Factor to adjust a new value of a time-dependent parameter.
For a time-dependent parameter, its effective value depends on the
simulation step size. Method |Parameter.get_timefactor| returns
the fraction between the current simulation step size and ... | Factor to adjust a new value of a time-dependent parameter.
For a time-dependent parameter, its effective value depends on the
simulation step size. Method |Parameter.get_timefactor| returns
the fraction between the current simulation step size and the
current parameter step size.
... | entailment |
def apply_timefactor(cls, values):
"""Change and return the given value(s) in accordance with
|Parameter.get_timefactor| and the type of time-dependence
of the actual parameter subclass.
.. testsetup::
>>> from hydpy import pub
>>> del pub.timegrids
For... | Change and return the given value(s) in accordance with
|Parameter.get_timefactor| and the type of time-dependence
of the actual parameter subclass.
.. testsetup::
>>> from hydpy import pub
>>> del pub.timegrids
For the same conversion factor returned by method... | entailment |
def revert_timefactor(cls, values):
"""The inverse version of method |Parameter.apply_timefactor|.
See the explanations on method Parameter.apply_timefactor| to
understand the following examples:
.. testsetup::
>>> from hydpy import pub
>>> del pub.timegrids
... | The inverse version of method |Parameter.apply_timefactor|.
See the explanations on method Parameter.apply_timefactor| to
understand the following examples:
.. testsetup::
>>> from hydpy import pub
>>> del pub.timegrids
>>> from hydpy.core.parametertools impor... | entailment |
def compress_repr(self) -> Optional[str]:
"""Try to find a compressed parameter value representation and
return it.
|Parameter.compress_repr| raises a |NotImplementedError| when
failing to find a compressed representation.
.. testsetup::
>>> from hydpy import pub
... | Try to find a compressed parameter value representation and
return it.
|Parameter.compress_repr| raises a |NotImplementedError| when
failing to find a compressed representation.
.. testsetup::
>>> from hydpy import pub
>>> del pub.timegrids
For the fol... | entailment |
def compress_repr(self) -> str:
"""Works as |Parameter.compress_repr|, but returns a
string with constant names instead of constant values.
See the main documentation on class |NameParameter| for
further information.
"""
string = super().compress_repr()
if string... | Works as |Parameter.compress_repr|, but returns a
string with constant names instead of constant values.
See the main documentation on class |NameParameter| for
further information. | entailment |
def compress_repr(self) -> Optional[str]:
"""Works as |Parameter.compress_repr|, but alternatively
tries to compress by following an external classification.
See the main documentation on class |ZipParameter| for
further information.
"""
string = super().compress_repr()
... | Works as |Parameter.compress_repr|, but alternatively
tries to compress by following an external classification.
See the main documentation on class |ZipParameter| for
further information. | entailment |
def refresh(self) -> None:
"""Update the actual simulation values based on the toy-value pairs.
Usually, one does not need to call refresh explicitly. The
"magic" methods __call__, __setattr__, and __delattr__ invoke
it automatically, when required.
Instantiate a 1-dimensional... | Update the actual simulation values based on the toy-value pairs.
Usually, one does not need to call refresh explicitly. The
"magic" methods __call__, __setattr__, and __delattr__ invoke
it automatically, when required.
Instantiate a 1-dimensional |SeasonalParameter| object:
... | entailment |
def interp(self, date: timetools.Date) -> float:
"""Perform a linear value interpolation for the given `date` and
return the result.
Instantiate a 1-dimensional |SeasonalParameter| object:
>>> from hydpy.core.parametertools import SeasonalParameter
>>> class Par(SeasonalParamet... | Perform a linear value interpolation for the given `date` and
return the result.
Instantiate a 1-dimensional |SeasonalParameter| object:
>>> from hydpy.core.parametertools import SeasonalParameter
>>> class Par(SeasonalParameter):
... NDIM = 1
... TYPE = float
... | entailment |
def update(self) -> None:
"""Update subclass of |RelSubweightsMixin| based on `refweights`."""
mask = self.mask
weights = self.refweights[mask]
self[~mask] = numpy.nan
self[mask] = weights/numpy.sum(weights) | Update subclass of |RelSubweightsMixin| based on `refweights`. | entailment |
def alternative_initvalue(self) -> Union[bool, int, float]:
"""A user-defined value to be used instead of the value of class
constant `INIT`.
See the main documentation on class |SolverParameter| for more
information.
"""
if self._alternative_initvalue is None:
... | A user-defined value to be used instead of the value of class
constant `INIT`.
See the main documentation on class |SolverParameter| for more
information. | entailment |
def update(self) -> None:
"""Reference the actual |Indexer.timeofyear| array of the
|Indexer| object available in module |pub|.
>>> from hydpy import pub
>>> pub.timegrids = '27.02.2004', '3.03.2004', '1d'
>>> from hydpy.core.parametertools import TOYParameter
>>> toypar... | Reference the actual |Indexer.timeofyear| array of the
|Indexer| object available in module |pub|.
>>> from hydpy import pub
>>> pub.timegrids = '27.02.2004', '3.03.2004', '1d'
>>> from hydpy.core.parametertools import TOYParameter
>>> toyparameter = TOYParameter(None)
>... | entailment |
def get_premises_model():
"""
Support for custom company premises model
with developer friendly validation.
"""
try:
app_label, model_name = PREMISES_MODEL.split('.')
except ValueError:
raise ImproperlyConfigured("OPENINGHOURS_PREMISES_MODEL must be of the"
... | Support for custom company premises model
with developer friendly validation. | entailment |
def get_now():
"""
Allows to access global request and read a timestamp from query.
"""
if not get_current_request:
return datetime.datetime.now()
request = get_current_request()
if request:
openinghours_now = request.GET.get('openinghours-now')
if openinghours_now:
... | Allows to access global request and read a timestamp from query. | entailment |
def get_closing_rule_for_now(location):
"""
Returns QuerySet of ClosingRules that are currently valid
"""
now = get_now()
if location:
return ClosingRules.objects.filter(company=location,
start__lte=now, end__gte=now)
return Company.objects.fi... | Returns QuerySet of ClosingRules that are currently valid | entailment |
def is_open(location, now=None):
"""
Is the company currently open? Pass "now" to test with a specific
timestamp. Can be used stand-alone or as a helper.
"""
if now is None:
now = get_now()
if has_closing_rule_for_now(location):
return False
now_time = datetime.time(now.hou... | Is the company currently open? Pass "now" to test with a specific
timestamp. Can be used stand-alone or as a helper. | entailment |
def next_time_open(location):
"""
Returns the next possible opening hours object, or (False, None)
if location is currently open or there is no such object
I.e. when is the company open for the next time?
"""
if not is_open(location):
now = get_now()
now_time = datetime.time(now.... | Returns the next possible opening hours object, or (False, None)
if location is currently open or there is no such object
I.e. when is the company open for the next time? | entailment |
def refweights(self):
"""A |numpy| |numpy.ndarray| with equal weights for all segment
junctions..
>>> from hydpy.models.hstream import *
>>> parameterstep('1d')
>>> states.qjoints.shape = 5
>>> states.qjoints.refweights
array([ 0.2, 0.2, 0.2, 0.2, 0.2])
... | A |numpy| |numpy.ndarray| with equal weights for all segment
junctions..
>>> from hydpy.models.hstream import *
>>> parameterstep('1d')
>>> states.qjoints.shape = 5
>>> states.qjoints.refweights
array([ 0.2, 0.2, 0.2, 0.2, 0.2]) | entailment |
def add(self, directory, path=None) -> None:
"""Add a directory and optionally its path."""
objecttools.valid_variable_identifier(directory)
if path is None:
path = directory
setattr(self, directory, path) | Add a directory and optionally its path. | entailment |
def basepath(self) -> str:
"""Absolute path pointing to the available working directories.
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectdir = 'projectname'
>>> from hydpy impo... | Absolute path pointing to the available working directories.
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectdir = 'projectname'
>>> from hydpy import repr_, TestIO
>>> with Test... | entailment |
def availabledirs(self) -> Folder2Path:
"""Names and paths of the available working directories.
Available working directories are those beeing stored in the
base directory of the respective |FileManager| subclass.
Folders with names starting with an underscore are ignored
(use ... | Names and paths of the available working directories.
Available working directories are those beeing stored in the
base directory of the respective |FileManager| subclass.
Folders with names starting with an underscore are ignored
(use this for directories handling additional data files... | entailment |
def currentdir(self) -> str:
"""Name of the current working directory containing the relevant files.
To show most of the functionality of |property|
|FileManager.currentdir| (unpacking zip files on the fly is
explained in the documentation on function
(|FileManager.zip_currentdi... | Name of the current working directory containing the relevant files.
To show most of the functionality of |property|
|FileManager.currentdir| (unpacking zip files on the fly is
explained in the documentation on function
(|FileManager.zip_currentdir|), we first prepare a |FileManager|
... | entailment |
def currentpath(self) -> str:
"""Absolute path of the current working directory.
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectdir = 'projectname'
>>> from hydpy import repr_, ... | Absolute path of the current working directory.
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectdir = 'projectname'
>>> from hydpy import repr_, TestIO
>>> with TestIO():
... | entailment |
def filenames(self) -> List[str]:
"""Names of the files contained in the the current working directory.
Files names starting with underscores are ignored:
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
... | Names of the files contained in the the current working directory.
Files names starting with underscores are ignored:
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectdir = 'projectname'... | entailment |
def filepaths(self) -> List[str]:
"""Absolute path names of the files contained in the current
working directory.
Files names starting with underscores are ignored:
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR ... | Absolute path names of the files contained in the current
working directory.
Files names starting with underscores are ignored:
>>> from hydpy.core.filetools import FileManager
>>> filemanager = FileManager()
>>> filemanager.BASEDIR = 'basename'
>>> filemanager.projectd... | entailment |
def zip_currentdir(self) -> None:
"""Pack the current working directory in a `zip` file.
|FileManager| subclasses allow for manual packing and automatic
unpacking of working directories. The only supported format is `zip`.
To avoid possible inconsistencies, origin directories and zip
... | Pack the current working directory in a `zip` file.
|FileManager| subclasses allow for manual packing and automatic
unpacking of working directories. The only supported format is `zip`.
To avoid possible inconsistencies, origin directories and zip
files are removed after packing or unp... | entailment |
def load_files(self) -> selectiontools.Selections:
"""Read all network files of the current working directory, structure
their contents in a |selectiontools.Selections| object, and return it.
"""
devicetools.Node.clear_all()
devicetools.Element.clear_all()
selections = se... | Read all network files of the current working directory, structure
their contents in a |selectiontools.Selections| object, and return it. | entailment |
def save_files(self, selections) -> None:
"""Save the |Selection| objects contained in the given |Selections|
instance to separate network files."""
try:
currentpath = self.currentpath
selections = selectiontools.Selections(selections)
for selection in selecti... | Save the |Selection| objects contained in the given |Selections|
instance to separate network files. | entailment |
def delete_files(self, selections) -> None:
"""Delete the network files corresponding to the given selections
(e.g. a |list| of |str| objects or a |Selections| object)."""
try:
currentpath = self.currentpath
for selection in selections:
name = str(selectio... | Delete the network files corresponding to the given selections
(e.g. a |list| of |str| objects or a |Selections| object). | entailment |
def load_file(self, element=None, filename=None, clear_registry=True):
"""Return the namespace of the given file (and eventually of its
corresponding auxiliary subfiles) as a |dict|.
By default, the internal registry is cleared when a control file and
all its corresponding auxiliary fil... | Return the namespace of the given file (and eventually of its
corresponding auxiliary subfiles) as a |dict|.
By default, the internal registry is cleared when a control file and
all its corresponding auxiliary files have been loaded. You can
change this behaviour by passing `False` for... | entailment |
def read2dict(cls, filename, info):
"""Read the control parameters from the given path (and its
auxiliary paths, where appropriate) and store them in the given
|dict| object `info`.
Note that the |dict| `info` can be used to feed information
into the execution of control files. ... | Read the control parameters from the given path (and its
auxiliary paths, where appropriate) and store them in the given
|dict| object `info`.
Note that the |dict| `info` can be used to feed information
into the execution of control files. Use this method only if you
are comple... | entailment |
def save_file(self, filename, text):
"""Save the given text under the given control filename and the
current path."""
if not filename.endswith('.py'):
filename += '.py'
path = os.path.join(self.currentpath, filename)
with open(path, 'w', encoding="utf-8") as file_:
... | Save the given text under the given control filename and the
current path. | entailment |
def load_file(self, filename):
"""Read and return the content of the given file.
If the current directory is not defined explicitly, the directory
name is constructed with the actual simulation start date. If
such an directory does not exist, it is created immediately.
"""
... | Read and return the content of the given file.
If the current directory is not defined explicitly, the directory
name is constructed with the actual simulation start date. If
such an directory does not exist, it is created immediately. | entailment |
def save_file(self, filename, text):
"""Save the given text under the given condition filename and the
current path.
If the current directory is not defined explicitly, the directory
name is constructed with the actual simulation end date. If
such an directory does not exist, i... | Save the given text under the given condition filename and the
current path.
If the current directory is not defined explicitly, the directory
name is constructed with the actual simulation end date. If
such an directory does not exist, it is created immediately. | entailment |
def load_file(self, sequence):
"""Load data from an "external" data file an pass it to
the given |IOSequence|."""
try:
if sequence.filetype_ext == 'npy':
sequence.series = sequence.adjust_series(
*self._load_npy(sequence))
elif sequence... | Load data from an "external" data file an pass it to
the given |IOSequence|. | entailment |
def save_file(self, sequence, array=None):
"""Write the date stored in |IOSequence.series| of the given
|IOSequence| into an "external" data file. """
if array is None:
array = sequence.aggregate_series()
try:
if sequence.filetype_ext == 'nc':
self... | Write the date stored in |IOSequence.series| of the given
|IOSequence| into an "external" data file. | entailment |
def open_netcdf_reader(self, flatten=False, isolate=False, timeaxis=1):
"""Prepare a new |NetCDFInterface| object for reading data."""
self._netcdf_reader = netcdftools.NetCDFInterface(
flatten=bool(flatten),
isolate=bool(isolate),
timeaxis=int(timeaxis)) | Prepare a new |NetCDFInterface| object for reading data. | entailment |
def open_netcdf_writer(self, flatten=False, isolate=False, timeaxis=1):
"""Prepare a new |NetCDFInterface| object for writing data."""
self._netcdf_writer = netcdftools.NetCDFInterface(
flatten=bool(flatten),
isolate=bool(isolate),
timeaxis=int(timeaxis)) | Prepare a new |NetCDFInterface| object for writing data. | entailment |
def calc_nkor_v1(self):
"""Adjust the given precipitation values.
Required control parameters:
|NHRU|
|KG|
Required input sequence:
|Nied|
Calculated flux sequence:
|NKor|
Basic equation:
:math:`NKor = KG \\cdot Nied`
Example:
>>> from hydpy.models.lla... | Adjust the given precipitation values.
Required control parameters:
|NHRU|
|KG|
Required input sequence:
|Nied|
Calculated flux sequence:
|NKor|
Basic equation:
:math:`NKor = KG \\cdot Nied`
Example:
>>> from hydpy.models.lland import *
>>> paramet... | entailment |
def calc_tkor_v1(self):
"""Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:
>>> from hydpy.models.lland ... | Adjust the given air temperature values.
Required control parameters:
|NHRU|
|KT|
Required input sequence:
|TemL|
Calculated flux sequence:
|TKor|
Basic equation:
:math:`TKor = KT + TemL`
Example:
>>> from hydpy.models.lland import *
>>> parameters... | entailment |
def calc_et0_v1(self):
"""Calculate reference evapotranspiration after Turc-Wendling.
Required control parameters:
|NHRU|
|KE|
|KF|
|HNN|
Required input sequence:
|Glob|
Required flux sequence:
|TKor|
Calculated flux sequence:
|ET0|
Basic equation:
... | Calculate reference evapotranspiration after Turc-Wendling.
Required control parameters:
|NHRU|
|KE|
|KF|
|HNN|
Required input sequence:
|Glob|
Required flux sequence:
|TKor|
Calculated flux sequence:
|ET0|
Basic equation:
:math:`ET0 = KE \\cdot
... | entailment |
def calc_et0_wet0_v1(self):
"""Correct the given reference evapotranspiration and update the
corresponding log sequence.
Required control parameters:
|NHRU|
|KE|
|WfET0|
Required input sequence:
|PET|
Calculated flux sequence:
|ET0|
Updated log sequence:
|... | Correct the given reference evapotranspiration and update the
corresponding log sequence.
Required control parameters:
|NHRU|
|KE|
|WfET0|
Required input sequence:
|PET|
Calculated flux sequence:
|ET0|
Updated log sequence:
|WET0|
Basic equations:
:... | entailment |
def calc_evpo_v1(self):
"""Calculate land use and month specific values of potential
evapotranspiration.
Required control parameters:
|NHRU|
|Lnk|
|FLn|
Required derived parameter:
|MOY|
Required flux sequence:
|ET0|
Calculated flux sequence:
|EvPo|
A... | Calculate land use and month specific values of potential
evapotranspiration.
Required control parameters:
|NHRU|
|Lnk|
|FLn|
Required derived parameter:
|MOY|
Required flux sequence:
|ET0|
Calculated flux sequence:
|EvPo|
Additional requirements:
|... | entailment |
def calc_nbes_inzp_v1(self):
"""Calculate stand precipitation and update the interception storage
accordingly.
Required control parameters:
|NHRU|
|Lnk|
Required derived parameter:
|KInz|
Required flux sequence:
|NKor|
Calculated flux sequence:
|NBes|
Updat... | Calculate stand precipitation and update the interception storage
accordingly.
Required control parameters:
|NHRU|
|Lnk|
Required derived parameter:
|KInz|
Required flux sequence:
|NKor|
Calculated flux sequence:
|NBes|
Updated state sequence:
|Inzp|
... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.