INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Executes Blurr BTS with the given records. old_state_rdd can be provided to load an older state from a previous run. | def execute(self, identity_records: 'RDD', old_state_rdd: Optional['RDD'] = None) -> 'RDD':
"""
Executes Blurr BTS with the given records. old_state_rdd can be provided to load an older
state from a previous run.
:param identity_records: RDD of the form Tuple[Identity, List[TimeAndRecor... |
Reads the data from the given json_files path and converts them into the Record s format for processing. data_processor is used to process the per event data in those files to convert them into Record. | def get_record_rdd_from_json_files(self,
json_files: List[str],
data_processor: DataProcessor = SimpleJsonDataProcessor(),
spark_session: Optional['SparkSession'] = None) -> 'RDD':
"""
Re... |
Converts a RDD of raw events into the Record s format for processing. data_processor is used to process the per row data to convert them into Record. | def get_record_rdd_from_rdd(
self,
rdd: 'RDD',
data_processor: DataProcessor = SimpleDictionaryDataProcessor(),
) -> 'RDD':
"""
Converts a RDD of raw events into the `Record`s format for processing. `data_processor` is
used to process the per row data to c... |
Basic helper function to persist data to disk. | def write_output_file(self,
path: str,
per_identity_data: 'RDD',
spark_session: Optional['SparkSession'] = None) -> None:
"""
Basic helper function to persist data to disk.
If window BTS was provided then the window B... |
Basic helper function to write data to stdout. If window BTS was provided then the window BTS output is written otherwise the streaming BTS output is written to stdout. | def print_output(self, per_identity_data: 'RDD') -> None:
"""
Basic helper function to write data to stdout. If window BTS was provided then the window
BTS output is written, otherwise, the streaming BTS output is written to stdout.
WARNING - For large datasets this will be extremely sl... |
As distutils. spawn. find_executable but on Windows look up every extension declared in PATHEXT instead of just. exe | def find_executable(executable, path=None):
"""
As distutils.spawn.find_executable, but on Windows, look up
every extension declared in PATHEXT instead of just `.exe`
"""
if sys.platform != 'win32':
return distutils.spawn.find_executable(executable, path)
if path is None:
path =... |
Create and return a copy of os. environ with the specified overrides | def create_environment_dict(overrides):
"""
Create and return a copy of os.environ with the specified overrides
"""
result = os.environ.copy()
result.update(overrides or {})
return result |
Retrieve credentials for server. If no credentials are found a StoreError will be raised. | def get(self, server):
""" Retrieve credentials for `server`. If no credentials are found,
a `StoreError` will be raised.
"""
if not isinstance(server, six.binary_type):
server = server.encode('utf-8')
data = self._execute('get', server)
result = json.load... |
Store credentials for server. Raises a StoreError if an error occurs. | def store(self, server, username, secret):
""" Store credentials for `server`. Raises a `StoreError` if an error
occurs.
"""
data_input = json.dumps({
'ServerURL': server,
'Username': username,
'Secret': secret
}).encode('utf-8')
re... |
Erase credentials for server. Raises a StoreError if an error occurs. | def erase(self, server):
""" Erase credentials for `server`. Raises a `StoreError` if an error
occurs.
"""
if not isinstance(server, six.binary_type):
server = server.encode('utf-8')
self._execute('erase', server) |
Evaluates and returns the identity as specified in the schema.: param record: Record which is used to determine the identity.: return: The evaluated identity: raises: IdentityError if identity cannot be determined. | def get_identity(self, record: Record) -> str:
"""
Evaluates and returns the identity as specified in the schema.
:param record: Record which is used to determine the identity.
:return: The evaluated identity
:raises: IdentityError if identity cannot be determined.
"""
... |
Evaluates and updates data in the StreamingTransformer.: param record: The source record used for the update.: raises: IdentityError if identity is different from the one used during initialization. | def run_evaluate(self, record: Record):
"""
Evaluates and updates data in the StreamingTransformer.
:param record: The 'source' record used for the update.
:raises: IdentityError if identity is different from the one used during
initialization.
"""
record_identity... |
Injects the identity field | def extend_schema_spec(self) -> None:
""" Injects the identity field """
super().extend_schema_spec()
identity_field = {
'Name': '_identity',
'Type': BtsType.STRING,
'Value': 'identity',
ATTRIBUTE_INTERNAL: True
}
if self.ATTRIBUT... |
Persists the current data group | def _persist(self) -> None:
"""
Persists the current data group
"""
if self._store:
self._store.save(self._key, self._snapshot) |
Add a schema dictionary to the schema loader. The given schema is stored against fully_qualified_parent_name + ITEM_SEPARATOR (. ) + schema. name.: param spec: Schema specification.: param fully_qualified_parent_name: Full qualified name of the parent. If None is passed then the schema is stored against the schema name... | def add_schema_spec(self, spec: Dict[str, Any],
fully_qualified_parent_name: str = None) -> Optional[str]:
"""
Add a schema dictionary to the schema loader. The given schema is stored
against fully_qualified_parent_name + ITEM_SEPARATOR('.') + schema.name.
:param ... |
Adds errors to the error store for the schema | def add_errors(self, *errors: Union[BaseSchemaError, SchemaErrorCollection]) -> None:
""" Adds errors to the error store for the schema """
for error in errors:
self._error_cache.add(error) |
Used to generate a schema object from the given fully_qualified_name.: param fully_qualified_name: The fully qualified name of the object needed.: return: An initialized schema object | def get_schema_object(self, fully_qualified_name: str) -> 'BaseSchema':
"""
Used to generate a schema object from the given fully_qualified_name.
:param fully_qualified_name: The fully qualified name of the object needed.
:return: An initialized schema object
"""
if full... |
Used to generate a store object from the given fully_qualified_name.: param fully_qualified_name: The fully qualified name of the store object needed.: return: An initialized store object | def get_store(self, fully_qualified_name: str) -> Optional['Store']:
"""
Used to generate a store object from the given fully_qualified_name.
:param fully_qualified_name: The fully qualified name of the store object needed.
:return: An initialized store object
"""
if ful... |
Used to generate a schema object from the given fully_qualified_parent_name and the nested_item_name.: param fully_qualified_parent_name: The fully qualified name of the parent.: param nested_item_name: The nested item name.: return: An initialized schema object of the nested item. | def get_nested_schema_object(self, fully_qualified_parent_name: str,
nested_item_name: str) -> Optional['BaseSchema']:
"""
Used to generate a schema object from the given fully_qualified_parent_name
and the nested_item_name.
:param fully_qualified_parent_... |
Returns the fully qualified name by combining the fully_qualified_parent_name and nested_item_name.: param fully_qualified_parent_name: The fully qualified name of the parent.: param nested_item_name: The nested item name.: return: The fully qualified name of the nested item. | def get_fully_qualified_name(fully_qualified_parent_name: str, nested_item_name: str) -> str:
"""
Returns the fully qualified name by combining the fully_qualified_parent_name
and nested_item_name.
:param fully_qualified_parent_name: The fully qualified name of the parent.
:param... |
Used to retrieve the specifications of the schema from the given fully_qualified_name of schema.: param fully_qualified_name: The fully qualified name of the schema needed.: return: Schema dictionary. | def get_schema_spec(self, fully_qualified_name: str) -> Dict[str, Any]:
"""
Used to retrieve the specifications of the schema from the given
fully_qualified_name of schema.
:param fully_qualified_name: The fully qualified name of the schema needed.
:return: Schema dictionary.
... |
Returns a list of fully qualified names and schema dictionary tuples for the schema types provided.: param schema_types: Schema types.: return: List of fully qualified names and schema dictionary tuples. | def get_schema_specs_of_type(self, *schema_types: Type) -> Dict[str, Dict[str, Any]]:
"""
Returns a list of fully qualified names and schema dictionary tuples for
the schema types provided.
:param schema_types: Schema types.
:return: List of fully qualified names and schema dicti... |
Adds a key and value to the global dictionary | def global_add(self, key: str, value: Any) -> None:
"""
Adds a key and value to the global dictionary
"""
self.global_context[key] = value |
Merges the provided evaluation context to the current evaluation context.: param evaluation_context: Evaluation context to merge. | def merge(self, evaluation_context: 'EvaluationContext') -> None:
"""
Merges the provided evaluation context to the current evaluation context.
:param evaluation_context: Evaluation context to merge.
"""
self.global_context.merge(evaluation_context.global_context)
self.lo... |
Evaluates the expression with the context provided. If the execution results in failure an ExpressionEvaluationException encapsulating the underlying exception is raised.: param evaluation_context: Global and local context dictionary to be passed for evaluation | def evaluate(self, evaluation_context: EvaluationContext) -> Any:
"""
Evaluates the expression with the context provided. If the execution
results in failure, an ExpressionEvaluationException encapsulating the
underlying exception is raised.
:param evaluation_context: Global and... |
Copy all the files in source directory to target. | def _copy_files(source, target):
"""
Copy all the files in source directory to target.
Ignores subdirectories.
"""
source_files = listdir(source)
if not exists(target):
makedirs(target)
for filename in source_files:
full_filename = join(source, filename)
if isfile(fu... |
Initialises a temporary directory structure and copy of MAGICC configuration files and binary. | def create_copy(self):
"""
Initialises a temporary directory structure and copy of MAGICC
configuration files and binary.
"""
if self.executable is None or not isfile(self.executable):
raise FileNotFoundError(
"Could not find MAGICC{} executable: {}".f... |
Run MAGICC and parse the output. | def run(self, scenario=None, only=None, **kwargs):
"""
Run MAGICC and parse the output.
As a reminder, putting ``out_parameters=1`` will cause MAGICC to write out its
parameters into ``out/PARAMETERS.OUT`` and they will then be read into
``output.metadata["parameters"]`` where `... |
Check that our MAGICC. CFG files are set to safely work with PYMAGICC | def check_config(self):
"""Check that our MAGICC ``.CFG`` files are set to safely work with PYMAGICC
For further detail about why this is required, please see :ref:`MAGICC flags`.
Raises
------
ValueError
If we are not certain that the config written by PYMAGICC wil... |
Write an input file to disk | def write(self, mdata, name):
"""Write an input file to disk
Parameters
----------
mdata : :obj:`pymagicc.io.MAGICCData`
A MAGICCData instance with the data to write
name : str
The name of the file to write. The file will be written to the MAGICC
... |
Read a parameters. out file | def read_parameters(self):
"""
Read a parameters.out file
Returns
-------
dict
A dictionary containing all the configuration used by MAGICC
"""
param_fname = join(self.out_dir, "PARAMETERS.OUT")
if not exists(param_fname):
raise F... |
Removes a temporary copy of the MAGICC version shipped with Pymagicc. | def remove_temp_copy(self):
"""
Removes a temporary copy of the MAGICC version shipped with Pymagicc.
"""
if self.is_temp and self.root_dir is not None:
shutil.rmtree(self.root_dir)
self.root_dir = None |
Create a configuration file for MAGICC. | def set_config(
self, filename="MAGTUNE_PYMAGICC.CFG", top_level_key="nml_allcfgs", **kwargs
):
"""
Create a configuration file for MAGICC.
Writes a fortran namelist in run_dir.
Parameters
----------
filename : str
Name of configuration file to w... |
Updates a configuration file for MAGICC | def update_config(
self, filename="MAGTUNE_PYMAGICC.CFG", top_level_key="nml_allcfgs", **kwargs
):
"""Updates a configuration file for MAGICC
Updates the contents of a fortran namelist in the run directory,
creating a new namelist if none exists.
Parameters
--------... |
Set config such that radiative forcing and temperature output will be zero | def set_zero_config(self):
"""Set config such that radiative forcing and temperature output will be zero
This method is intended as a convenience only, it does not handle everything in
an obvious way. Adjusting the parameter settings still requires great care and
may behave unepexctedly... |
Set the start and end dates of the simulations. | def set_years(self, startyear=1765, endyear=2100):
"""
Set the start and end dates of the simulations.
Parameters
----------
startyear : int
Start year of the simulation
endyear : int
End year of the simulation
Returns
-------
... |
Set the output configuration minimising output as much as possible | def set_output_variables(self, write_ascii=True, write_binary=False, **kwargs):
"""Set the output configuration, minimising output as much as possible
There are a number of configuration parameters which control which variables
are written to file and in which format. Limiting the variables tha... |
Diagnose TCR and ECS | def diagnose_tcr_ecs(self, **kwargs):
"""Diagnose TCR and ECS
The transient climate response (TCR), is the global-mean temperature response
at time at which atmopsheric |CO2| concentrations double in a scenario where
atmospheric |CO2| concentrations are increased at 1% per year from
... |
Set the emissions flags correctly. | def set_emission_scenario_setup(self, scenario, config_dict):
"""Set the emissions flags correctly.
Parameters
----------
scenario : :obj:`pymagicc.io.MAGICCData`
Scenario to run.
config_dict : dict
Dictionary with current input configurations which is t... |
Checks if a type is defined | def contains(value: Union[str, 'Type']) -> bool:
""" Checks if a type is defined """
if isinstance(value, str):
return any(value.lower() == i.value for i in Type)
return any(value == i for i in Type) |
Read the content of an XML template file ( XMLT ) apply the given replacements to its substitution markers and write the result into an XML file with the same name but ending with xml instead of xmlt. | def xml_replace(filename, **replacements):
"""Read the content of an XML template file (XMLT), apply the given
`replacements` to its substitution markers, and write the result into
an XML file with the same name but ending with `xml` instead of `xmlt`.
First, we write an XMLT file, containing a regula... |
Return the required indexes based on the given lambda function and the |Timegrids| object handled by module |pub|. Raise a |RuntimeError| if the latter is not available. | def _calcidxs(func):
"""Return the required indexes based on the given lambda function
and the |Timegrids| object handled by module |pub|. Raise a
|RuntimeError| if the latter is not available.
"""
timegrids = hydpy.pub.get('timegrids')
if timegrids is None:
... |
Day of the year index ( the first of January = 0... ). | def dayofyear(self):
"""Day of the year index (the first of January = 0...).
For reasons of consistency between leap years and non-leap years,
assuming a daily time step, index 59 is always associated with the
29th of February. Hence, it is missing in non-leap years:
>>> from ... |
Time of the year index ( first simulation step of each year = 0... ). | def timeofyear(self):
"""Time of the year index (first simulation step of each year = 0...).
The property |Indexer.timeofyear| is best explained through
comparing it with property |Indexer.dayofyear|:
Let us reconsider one of the examples of the documentation on
property |Index... |
Assign the given docstring to the property instance and if possible to the __test__ dictionary of the module of its owner class. | def set_doc(self, doc: str):
"""Assign the given docstring to the property instance and, if
possible, to the `__test__` dictionary of the module of its
owner class."""
self.__doc__ = doc
if hasattr(self, 'module'):
ref = f'{self.objtype.__name__}.{self.name}'
... |
Add the given getter function and its docstring to the property and return it. | def getter_(self, fget) -> 'BaseProperty':
"""Add the given getter function and its docstring to the
property and return it."""
self.fget = fget
self.set_doc(fget.__doc__)
return self |
Return |True| or |False| to indicate if the protected property is ready for the given object. If the object is unknow |ProtectedProperty| returns |False|. | def isready(self, obj) -> bool:
"""Return |True| or |False| to indicate if the protected
property is ready for the given object. If the object is
unknow, |ProtectedProperty| returns |False|."""
return vars(obj).get(self.name, False) |
Return |True| or |False| to indicate whether all protected properties are ready or not. | def allready(self, obj) -> bool:
"""Return |True| or |False| to indicate whether all protected
properties are ready or not."""
for prop in self.__properties:
if not prop.isready(obj):
return False
return True |
Return the predefined custom value when available otherwise the value defined by the getter function. | def call_fget(self, obj) -> Any:
"""Return the predefined custom value when available, otherwise,
the value defined by the getter function."""
custom = vars(obj).get(self.name)
if custom is None:
return self.fget(obj)
return custom |
Store the given custom value and call the setter function. | def call_fset(self, obj, value) -> None:
"""Store the given custom value and call the setter function."""
vars(obj)[self.name] = self.fset(obj, value) |
Remove the predefined custom value and call the delete function. | def call_fdel(self, obj) -> None:
"""Remove the predefined custom value and call the delete function."""
self.fdel(obj)
try:
del vars(obj)[self.name]
except KeyError:
pass |
Trim upper values in accordance with: math: RelWB \\ leq RelWZ. | def trim(self, lower=None, upper=None):
"""Trim upper values in accordance with :math:`RelWB \\leq RelWZ`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(3)
>>> lnk(ACKER)
>>> relwb.values = 0.5
>>> relwz(0.2, 0.5, 0.8)
>>> relwz
... |
Trim upper values in accordance with: math: RelWB \\ leq RelWZ. | def trim(self, lower=None, upper=None):
"""Trim upper values in accordance with :math:`RelWB \\leq RelWZ`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(3)
>>> lnk(ACKER)
>>> relwz.values = 0.5
>>> relwb(0.2, 0.5, 0.8)
>>> relwb
... |
Trim upper values in accordance with: math: EQI1 \\ leq EQB. | def trim(self, lower=None, upper=None):
"""Trim upper values in accordance with :math:`EQI1 \\leq EQB`.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi1.value = 2.0
>>> eqb(1.0)
>>> eqb
eqb(2.0)
>>> eqb(2.0)
>>> eqb
eq... |
Trim upper values in accordance with: math: EQI2 \\ leq EQI1 \\ leq EQB. | 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.... |
Return digital time choices every half hour from 00: 00 to 23: 30. | 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 autodoc commands for a basemodels docstring. | 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,
... |
Add an exhaustive docstring to the given module of a basemodel. | 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 =... |
Improves the docstrings of application models when called at the bottom of the respective module. | 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.
... |
Prepare and return a |Substituter| object for the main __init__ file of * HydPy *. | 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,
... |
Try to return the number of the first line of the definition of a member of a module. | 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... |
Add a short summary of all implemented members to a modules docstring. | 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... |
Include tuples as CLASSES of ControlParameters and RUN_METHODS of Models into the respective docstring. | 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_ ... |
Return |True| if the given member should be added to the substitutions. If not return |False|. | 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 the reStructuredText role func class or const best describing the given member. | 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... |
Add the given substitutions both as a short2long and a medium2long mapping. | 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 module its members and their submembers. | 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 modules of the given package without their members. | 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:`~... |
Update all master |Substituter| objects. | 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 slave |Substituter| objects. | 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() |
Return a string containing multiple reStructuredText replacements with the substitutions currently defined. | 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... |
Print all substitutions that include the given text string. | 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) |
Add print commands time to the given function informing about execution time. | 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... |
Print a simple progress bar while processing the given iterable. | 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.... |
Start the * HydPy * server using the given socket. | 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` ... |
Block the current process until either the * HydPy * server is responding on the given port or the given number of seconds elapsed. | 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... |
Initialise a * HydPy * project based on the given XML configuration file agreeing with HydPyConfigMultipleRuns. xsd. | 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... |
Evaluate any valid Python expression with the * HydPy * server process and get its result. | 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... |
Stop and close the * HydPy * server. | 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() |
Get the types of all current exchange items supposed to change the values of |Parameter| objects. | 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 |StateSequence| or |LogSequence| objects. | 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 return the values of |Parameter| or |Sequence| objects or the time series of |IOSequence| objects. | 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... |
Change the current simulation |Timegrid|. | 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.... |
Get the values of all |ChangeItem| objects handling |Parameter| objects. | 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 |StateSequence| or |LogSequence| objects. | 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 |Variable| objects observed by the current |GetItem| objects. | 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.
"""
... |
Assign the |StateSequence| or |LogSequence| object values available for the current simulation start point to the current |HydPy| instance. | 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... |
Save the |StateSequence| and |LogSequence| object values of the current |HydPy| instance for the current simulation endpoint. | 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 values of those |ChangeItem| objects which are handling |Parameter| objects. | 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() |
Get the previously saved values of those |ChangeItem| objects which are handling |Parameter| objects. | 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:
... |
ToDo: extend functionality and add tests | 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 | 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():
... |
Save the values of all current |GetItem| objects. | 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 |
Get the previously saved values of all |GetItem| objects. | 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... |
Save the current simulation period. | def GET_save_timegrid(self) -> None:
"""Save the current simulation period."""
state.timegrids[self._id] = copy.deepcopy(hydpy.pub.timegrids.sim) |
Get the previously saved simulation period. | 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) |
Trim the value ( s ) of a |Variable| instance. | 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... |
Return some numerical accuracy to be expected for the given floating point value ( s ) ( see method |trim| ). | 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 a function usable as a comparison method for class |Variable|. | 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 valid string representation for the given |Variable| object. | 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 |... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.