sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
|---|---|---|
def extract(values, types, skip=False):
"""Return a generator that extracts certain objects from `values`.
This function is thought for supporting the definition of functions
with arguments, that can be objects of of contain types or that can
be iterables containing these objects.
The following examples show that function |extract|
basically implements a type specific flattening mechanism:
>>> from hydpy.core.objecttools import extract
>>> tuple(extract('str1', (str, int)))
('str1',)
>>> tuple(extract(['str1', 'str2'], (str, int)))
('str1', 'str2')
>>> tuple(extract((['str1', 'str2'], [1,]), (str, int)))
('str1', 'str2', 1)
If an object is neither iterable nor of the required type, the
following exception is raised:
>>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int)))
Traceback (most recent call last):
...
TypeError: The given value `None` is neither iterable nor \
an instance of the following classes: str and int.
Optionally, |None| values can be skipped:
>>> tuple(extract(None, (str, int), True))
()
>>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int), True))
('str1', 'str2', 1)
"""
if isinstance(values, types):
yield values
elif skip and (values is None):
return
else:
try:
for value in values:
for subvalue in extract(value, types, skip):
yield subvalue
except TypeError as exc:
if exc.args[0].startswith('The given value'):
raise exc
else:
raise TypeError(
f'The given value `{repr(values)}` is neither iterable '
f'nor an instance of the following classes: '
f'{enumeration(types, converter=instancename)}.')
|
Return a generator that extracts certain objects from `values`.
This function is thought for supporting the definition of functions
with arguments, that can be objects of of contain types or that can
be iterables containing these objects.
The following examples show that function |extract|
basically implements a type specific flattening mechanism:
>>> from hydpy.core.objecttools import extract
>>> tuple(extract('str1', (str, int)))
('str1',)
>>> tuple(extract(['str1', 'str2'], (str, int)))
('str1', 'str2')
>>> tuple(extract((['str1', 'str2'], [1,]), (str, int)))
('str1', 'str2', 1)
If an object is neither iterable nor of the required type, the
following exception is raised:
>>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int)))
Traceback (most recent call last):
...
TypeError: The given value `None` is neither iterable nor \
an instance of the following classes: str and int.
Optionally, |None| values can be skipped:
>>> tuple(extract(None, (str, int), True))
()
>>> tuple(extract((['str1', 'str2'], [None, 1]), (str, int), True))
('str1', 'str2', 1)
|
entailment
|
def enumeration(values, converter=str, default=''):
"""Return an enumeration string based on the given values.
The following four examples show the standard output of function
|enumeration|:
>>> from hydpy.core.objecttools import enumeration
>>> enumeration(('text', 3, []))
'text, 3, and []'
>>> enumeration(('text', 3))
'text and 3'
>>> enumeration(('text',))
'text'
>>> enumeration(())
''
All given objects are converted to strings by function |str|, as shown
by the first two examples. This behaviour can be changed by another
function expecting a single argument and returning a string:
>>> from hydpy.core.objecttools import classname
>>> enumeration(('text', 3, []), converter=classname)
'str, int, and list'
Furthermore, you can define a default string that is returned
in case an empty iterable is given:
>>> enumeration((), default='nothing')
'nothing'
"""
values = tuple(converter(value) for value in values)
if not values:
return default
if len(values) == 1:
return values[0]
if len(values) == 2:
return ' and '.join(values)
return ', and '.join((', '.join(values[:-1]), values[-1]))
|
Return an enumeration string based on the given values.
The following four examples show the standard output of function
|enumeration|:
>>> from hydpy.core.objecttools import enumeration
>>> enumeration(('text', 3, []))
'text, 3, and []'
>>> enumeration(('text', 3))
'text and 3'
>>> enumeration(('text',))
'text'
>>> enumeration(())
''
All given objects are converted to strings by function |str|, as shown
by the first two examples. This behaviour can be changed by another
function expecting a single argument and returning a string:
>>> from hydpy.core.objecttools import classname
>>> enumeration(('text', 3, []), converter=classname)
'str, int, and list'
Furthermore, you can define a default string that is returned
in case an empty iterable is given:
>>> enumeration((), default='nothing')
'nothing'
|
entailment
|
def trim(self, lower=None, upper=None):
"""Trim upper values in accordance with :math:`IC \\leq ICMAX`.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(5)
>>> icmax(2.0)
>>> states.ic(-1.0, 0.0, 1.0, 2.0, 3.0)
>>> states.ic
ic(0.0, 0.0, 1.0, 2.0, 2.0)
"""
if upper is None:
control = self.subseqs.seqs.model.parameters.control
upper = control.icmax
hland_sequences.State1DSequence.trim(self, lower, upper)
|
Trim upper values in accordance with :math:`IC \\leq ICMAX`.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(5)
>>> icmax(2.0)
>>> states.ic(-1.0, 0.0, 1.0, 2.0, 3.0)
>>> states.ic
ic(0.0, 0.0, 1.0, 2.0, 2.0)
|
entailment
|
def trim(self, lower=None, upper=None):
"""Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(7)
>>> whc(0.1)
>>> states.wc.values = -1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0
>>> states.sp(-1., 0., 0., 5., 5., 5., 5.)
>>> states.sp
sp(0.0, 0.0, 10.0, 5.0, 5.0, 5.0, 10.0)
"""
whc = self.subseqs.seqs.model.parameters.control.whc
wc = self.subseqs.wc
if lower is None:
if wc.values is not None:
with numpy.errstate(divide='ignore', invalid='ignore'):
lower = numpy.clip(wc.values / whc.values, 0., numpy.inf)
else:
lower = 0.
hland_sequences.State1DSequence.trim(self, lower, upper)
|
Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(7)
>>> whc(0.1)
>>> states.wc.values = -1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0
>>> states.sp(-1., 0., 0., 5., 5., 5., 5.)
>>> states.sp
sp(0.0, 0.0, 10.0, 5.0, 5.0, 5.0, 10.0)
|
entailment
|
def trim(self, lower=None, upper=None):
"""Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(7)
>>> whc(0.1)
>>> states.sp = 0.0, 0.0, 0.0, 5.0, 5.0, 5.0, 5.0
>>> states.wc(-1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0)
>>> states.wc
wc(0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5)
"""
whc = self.subseqs.seqs.model.parameters.control.whc
sp = self.subseqs.sp
if (upper is None) and (sp.values is not None):
upper = whc*sp
hland_sequences.State1DSequence.trim(self, lower, upper)
|
Trim values in accordance with :math:`WC \\leq WHC \\cdot SP`.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(7)
>>> whc(0.1)
>>> states.sp = 0.0, 0.0, 0.0, 5.0, 5.0, 5.0, 5.0
>>> states.wc(-1.0, 0.0, 1.0, -1.0, 0.0, 0.5, 1.0)
>>> states.wc
wc(0.0, 0.0, 0.0, 0.0, 0.0, 0.5, 0.5)
|
entailment
|
def trim(self, lower=None, upper=None):
"""Trim negative value whenever there is no internal lake within
the respective subbasin.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(2)
>>> zonetype(FIELD, ILAKE)
>>> states.lz(-1.0)
>>> states.lz
lz(-1.0)
>>> zonetype(FIELD, FOREST)
>>> states.lz(-1.0)
>>> states.lz
lz(0.0)
>>> states.lz(1.0)
>>> states.lz
lz(1.0)
"""
if upper is None:
control = self.subseqs.seqs.model.parameters.control
if not any(control.zonetype.values == ILAKE):
lower = 0.
sequencetools.StateSequence.trim(self, lower, upper)
|
Trim negative value whenever there is no internal lake within
the respective subbasin.
>>> from hydpy.models.hland import *
>>> parameterstep('1d')
>>> nmbzones(2)
>>> zonetype(FIELD, ILAKE)
>>> states.lz(-1.0)
>>> states.lz
lz(-1.0)
>>> zonetype(FIELD, FOREST)
>>> states.lz(-1.0)
>>> states.lz
lz(0.0)
>>> states.lz(1.0)
>>> states.lz
lz(1.0)
|
entailment
|
def load_data(self, idx):
"""Call method |InputSequences.load_data| of all handled
|InputSequences| objects."""
for subseqs in self:
if isinstance(subseqs, abctools.InputSequencesABC):
subseqs.load_data(idx)
|
Call method |InputSequences.load_data| of all handled
|InputSequences| objects.
|
entailment
|
def save_data(self, idx):
"""Call method `save_data|` of all handled |IOSequences|
objects registered under |OutputSequencesABC|."""
for subseqs in self:
if isinstance(subseqs, abctools.OutputSequencesABC):
subseqs.save_data(idx)
|
Call method `save_data|` of all handled |IOSequences|
objects registered under |OutputSequencesABC|.
|
entailment
|
def conditions(self) -> Dict[str, Dict[str, Union[float, numpy.ndarray]]]:
"""Nested dictionary containing the values of all condition
sequences.
See the documentation on property |HydPy.conditions| for further
information.
"""
conditions = {}
for subname in NAMES_CONDITIONSEQUENCES:
subseqs = getattr(self, subname, ())
subconditions = {seq.name: copy.deepcopy(seq.values)
for seq in subseqs}
if subconditions:
conditions[subname] = subconditions
return conditions
|
Nested dictionary containing the values of all condition
sequences.
See the documentation on property |HydPy.conditions| for further
information.
|
entailment
|
def load_conditions(self, filename=None):
"""Read the initial conditions from a file and assign them to the
respective |StateSequence| and/or |LogSequence| objects handled by
the actual |Sequences| object.
If no filename or dirname is passed, the ones defined by the
|ConditionManager| stored in module |pub| are used.
"""
if self.hasconditions:
if not filename:
filename = self._conditiondefaultfilename
namespace = locals()
for seq in self.conditionsequences:
namespace[seq.name] = seq
namespace['model'] = self
code = hydpy.pub.conditionmanager.load_file(filename)
try:
# ToDo: raises an escape sequence deprecation sometimes
# ToDo: use runpy instead?
# ToDo: Move functionality to filetools.py?
exec(code)
except BaseException:
objecttools.augment_excmessage(
'While trying to gather initial conditions of element %s'
% objecttools.devicename(self))
|
Read the initial conditions from a file and assign them to the
respective |StateSequence| and/or |LogSequence| objects handled by
the actual |Sequences| object.
If no filename or dirname is passed, the ones defined by the
|ConditionManager| stored in module |pub| are used.
|
entailment
|
def save_conditions(self, filename=None):
"""Query the actual conditions of the |StateSequence| and/or
|LogSequence| objects handled by the actual |Sequences| object and
write them into a initial condition file.
If no filename or dirname is passed, the ones defined by the
|ConditionManager| stored in module |pub| are used.
"""
if self.hasconditions:
if filename is None:
filename = self._conditiondefaultfilename
con = hydpy.pub.controlmanager
lines = ['# -*- coding: utf-8 -*-\n\n',
'from hydpy.models.%s import *\n\n' % self.model,
'controlcheck(projectdir="%s", controldir="%s")\n\n'
% (con.projectdir, con.currentdir)]
for seq in self.conditionsequences:
lines.append(repr(seq) + '\n')
hydpy.pub.conditionmanager.save_file(filename, ''.join(lines))
|
Query the actual conditions of the |StateSequence| and/or
|LogSequence| objects handled by the actual |Sequences| object and
write them into a initial condition file.
If no filename or dirname is passed, the ones defined by the
|ConditionManager| stored in module |pub| are used.
|
entailment
|
def dirpath_int(self):
"""Absolute path of the directory of the internal data file.
Normally, each sequence queries its current "internal" directory
path from the |SequenceManager| object stored in module |pub|:
>>> from hydpy import pub, repr_, TestIO
>>> from hydpy.core.filetools import SequenceManager
>>> pub.sequencemanager = SequenceManager()
We overwrite |FileManager.basepath| and prepare a folder in teh
`iotesting` directory to simplify the following examples:
>>> basepath = SequenceManager.basepath
>>> SequenceManager.basepath = 'test'
>>> TestIO.clear()
>>> import os
>>> with TestIO():
... os.makedirs('test/temp')
Generally, |SequenceManager.tempdirpath| is queried:
>>> from hydpy.core import sequencetools as st
>>> seq = st.InputSequence(None)
>>> with TestIO():
... repr_(seq.dirpath_int)
'test/temp'
Alternatively, you can specify |IOSequence.dirpath_int| for each
sequence object individually:
>>> seq.dirpath_int = 'path'
>>> os.path.split(seq.dirpath_int)
('', 'path')
>>> del seq.dirpath_int
>>> with TestIO():
... os.path.split(seq.dirpath_int)
('test', 'temp')
If neither an individual definition nor |SequenceManager| is
available, the following error is raised:
>>> del pub.sequencemanager
>>> seq.dirpath_int
Traceback (most recent call last):
...
RuntimeError: For sequence `inputsequence` the directory of \
the internal data file cannot be determined. Either set it manually \
or prepare `pub.sequencemanager` correctly.
Remove the `basepath` mock:
>>> SequenceManager.basepath = basepath
"""
try:
return hydpy.pub.sequencemanager.tempdirpath
except RuntimeError:
raise RuntimeError(
f'For sequence {objecttools.devicephrase(self)} '
f'the directory of the internal data file cannot '
f'be determined. Either set it manually or prepare '
f'`pub.sequencemanager` correctly.')
|
Absolute path of the directory of the internal data file.
Normally, each sequence queries its current "internal" directory
path from the |SequenceManager| object stored in module |pub|:
>>> from hydpy import pub, repr_, TestIO
>>> from hydpy.core.filetools import SequenceManager
>>> pub.sequencemanager = SequenceManager()
We overwrite |FileManager.basepath| and prepare a folder in teh
`iotesting` directory to simplify the following examples:
>>> basepath = SequenceManager.basepath
>>> SequenceManager.basepath = 'test'
>>> TestIO.clear()
>>> import os
>>> with TestIO():
... os.makedirs('test/temp')
Generally, |SequenceManager.tempdirpath| is queried:
>>> from hydpy.core import sequencetools as st
>>> seq = st.InputSequence(None)
>>> with TestIO():
... repr_(seq.dirpath_int)
'test/temp'
Alternatively, you can specify |IOSequence.dirpath_int| for each
sequence object individually:
>>> seq.dirpath_int = 'path'
>>> os.path.split(seq.dirpath_int)
('', 'path')
>>> del seq.dirpath_int
>>> with TestIO():
... os.path.split(seq.dirpath_int)
('test', 'temp')
If neither an individual definition nor |SequenceManager| is
available, the following error is raised:
>>> del pub.sequencemanager
>>> seq.dirpath_int
Traceback (most recent call last):
...
RuntimeError: For sequence `inputsequence` the directory of \
the internal data file cannot be determined. Either set it manually \
or prepare `pub.sequencemanager` correctly.
Remove the `basepath` mock:
>>> SequenceManager.basepath = basepath
|
entailment
|
def disk2ram(self):
"""Move internal data from disk to RAM."""
values = self.series
self.deactivate_disk()
self.ramflag = True
self.__set_array(values)
self.update_fastaccess()
|
Move internal data from disk to RAM.
|
entailment
|
def ram2disk(self):
"""Move internal data from RAM to disk."""
values = self.series
self.deactivate_ram()
self.diskflag = True
self._save_int(values)
self.update_fastaccess()
|
Move internal data from RAM to disk.
|
entailment
|
def seriesshape(self):
"""Shape of the whole time series (time being the first dimension)."""
seriesshape = [len(hydpy.pub.timegrids.init)]
seriesshape.extend(self.shape)
return tuple(seriesshape)
|
Shape of the whole time series (time being the first dimension).
|
entailment
|
def numericshape(self):
"""Shape of the array of temporary values required for the numerical
solver actually being selected."""
try:
numericshape = [self.subseqs.seqs.model.numconsts.nmb_stages]
except AttributeError:
objecttools.augment_excmessage(
'The `numericshape` of a sequence like `%s` depends on the '
'configuration of the actual integration algorithm. '
'While trying to query the required configuration data '
'`nmb_stages` of the model associated with element `%s`'
% (self.name, objecttools.devicename(self)))
# noinspection PyUnboundLocalVariable
numericshape.extend(self.shape)
return tuple(numericshape)
|
Shape of the array of temporary values required for the numerical
solver actually being selected.
|
entailment
|
def series(self) -> InfoArray:
"""Internal time series data within an |numpy.ndarray|."""
if self.diskflag:
array = self._load_int()
elif self.ramflag:
array = self.__get_array()
else:
raise AttributeError(
f'Sequence {objecttools.devicephrase(self)} is not requested '
f'to make any internal data available to the user.')
return InfoArray(array, info={'type': 'unmodified'})
|
Internal time series data within an |numpy.ndarray|.
|
entailment
|
def load_ext(self):
"""Read the internal data from an external data file."""
try:
sequencemanager = hydpy.pub.sequencemanager
except AttributeError:
raise RuntimeError(
'The time series of sequence %s cannot be loaded. Firstly, '
'you have to prepare `pub.sequencemanager` correctly.'
% objecttools.devicephrase(self))
sequencemanager.load_file(self)
|
Read the internal data from an external data file.
|
entailment
|
def adjust_short_series(self, timegrid, values):
"""Adjust a short time series to a longer timegrid.
Normally, time series data to be read from a external data files
should span (at least) the whole initialization time period of a
HydPy project. However, for some variables which are only used
for comparison (e.g. observed runoff used for calibration),
incomplete time series might also be helpful. This method it
thought for adjusting such incomplete series to the public
initialization time grid stored in module |pub|. It is
automatically called in method |IOSequence.adjust_series| when
necessary provided that the option |Options.checkseries| is
disabled.
Assume the initialization time period of a HydPy project spans
five day:
>>> from hydpy import pub
>>> pub.timegrids = '2000.01.10', '2000.01.15', '1d'
Prepare a node series object for observational data:
>>> from hydpy.core.sequencetools import Obs
>>> obs = Obs(None)
Prepare a test function that expects the timegrid of the
data and the data itself, which returns the ajdusted array by
means of calling method |IOSequence.adjust_short_series|:
>>> import numpy
>>> def test(timegrid):
... values = numpy.ones(len(timegrid))
... return obs.adjust_short_series(timegrid, values)
The following calls to the test function shows the arrays
returned for different kinds of misalignments:
>>> from hydpy import Timegrid
>>> test(Timegrid('2000.01.05', '2000.01.20', '1d'))
array([ 1., 1., 1., 1., 1.])
>>> test(Timegrid('2000.01.12', '2000.01.15', '1d'))
array([ nan, nan, 1., 1., 1.])
>>> test(Timegrid('2000.01.12', '2000.01.17', '1d'))
array([ nan, nan, 1., 1., 1.])
>>> test(Timegrid('2000.01.10', '2000.01.13', '1d'))
array([ 1., 1., 1., nan, nan])
>>> test(Timegrid('2000.01.08', '2000.01.13', '1d'))
array([ 1., 1., 1., nan, nan])
>>> test(Timegrid('2000.01.12', '2000.01.13', '1d'))
array([ nan, nan, 1., nan, nan])
>>> test(Timegrid('2000.01.05', '2000.01.10', '1d'))
array([ nan, nan, nan, nan, nan])
>>> test(Timegrid('2000.01.05', '2000.01.08', '1d'))
array([ nan, nan, nan, nan, nan])
>>> test(Timegrid('2000.01.15', '2000.01.18', '1d'))
array([ nan, nan, nan, nan, nan])
>>> test(Timegrid('2000.01.16', '2000.01.18', '1d'))
array([ nan, nan, nan, nan, nan])
Through enabling option |Options.usedefaultvalues| the missing
values are initialised with zero instead of nan:
>>> with pub.options.usedefaultvalues(True):
... test(Timegrid('2000.01.12', '2000.01.17', '1d'))
array([ 0., 0., 1., 1., 1.])
"""
idxs = [timegrid[hydpy.pub.timegrids.init.firstdate],
timegrid[hydpy.pub.timegrids.init.lastdate]]
valcopy = values
values = numpy.full(self.seriesshape, self.initinfo[0])
len_ = len(valcopy)
jdxs = []
for idx in idxs:
if idx < 0:
jdxs.append(0)
elif idx <= len_:
jdxs.append(idx)
else:
jdxs.append(len_)
valcopy = valcopy[jdxs[0]:jdxs[1]]
zdx1 = max(-idxs[0], 0)
zdx2 = zdx1+jdxs[1]-jdxs[0]
values[zdx1:zdx2] = valcopy
return values
|
Adjust a short time series to a longer timegrid.
Normally, time series data to be read from a external data files
should span (at least) the whole initialization time period of a
HydPy project. However, for some variables which are only used
for comparison (e.g. observed runoff used for calibration),
incomplete time series might also be helpful. This method it
thought for adjusting such incomplete series to the public
initialization time grid stored in module |pub|. It is
automatically called in method |IOSequence.adjust_series| when
necessary provided that the option |Options.checkseries| is
disabled.
Assume the initialization time period of a HydPy project spans
five day:
>>> from hydpy import pub
>>> pub.timegrids = '2000.01.10', '2000.01.15', '1d'
Prepare a node series object for observational data:
>>> from hydpy.core.sequencetools import Obs
>>> obs = Obs(None)
Prepare a test function that expects the timegrid of the
data and the data itself, which returns the ajdusted array by
means of calling method |IOSequence.adjust_short_series|:
>>> import numpy
>>> def test(timegrid):
... values = numpy.ones(len(timegrid))
... return obs.adjust_short_series(timegrid, values)
The following calls to the test function shows the arrays
returned for different kinds of misalignments:
>>> from hydpy import Timegrid
>>> test(Timegrid('2000.01.05', '2000.01.20', '1d'))
array([ 1., 1., 1., 1., 1.])
>>> test(Timegrid('2000.01.12', '2000.01.15', '1d'))
array([ nan, nan, 1., 1., 1.])
>>> test(Timegrid('2000.01.12', '2000.01.17', '1d'))
array([ nan, nan, 1., 1., 1.])
>>> test(Timegrid('2000.01.10', '2000.01.13', '1d'))
array([ 1., 1., 1., nan, nan])
>>> test(Timegrid('2000.01.08', '2000.01.13', '1d'))
array([ 1., 1., 1., nan, nan])
>>> test(Timegrid('2000.01.12', '2000.01.13', '1d'))
array([ nan, nan, 1., nan, nan])
>>> test(Timegrid('2000.01.05', '2000.01.10', '1d'))
array([ nan, nan, nan, nan, nan])
>>> test(Timegrid('2000.01.05', '2000.01.08', '1d'))
array([ nan, nan, nan, nan, nan])
>>> test(Timegrid('2000.01.15', '2000.01.18', '1d'))
array([ nan, nan, nan, nan, nan])
>>> test(Timegrid('2000.01.16', '2000.01.18', '1d'))
array([ nan, nan, nan, nan, nan])
Through enabling option |Options.usedefaultvalues| the missing
values are initialised with zero instead of nan:
>>> with pub.options.usedefaultvalues(True):
... test(Timegrid('2000.01.12', '2000.01.17', '1d'))
array([ 0., 0., 1., 1., 1.])
|
entailment
|
def check_completeness(self):
"""Raise a |RuntimeError| if the |IOSequence.series| contains at
least one |numpy.nan| value, if option |Options.checkseries| is
enabled.
>>> from hydpy import pub
>>> pub.timegrids = '2000-01-01', '2000-01-11', '1d'
>>> from hydpy.core.sequencetools import IOSequence
>>> class Seq(IOSequence):
... NDIM = 0
>>> seq = Seq(None)
>>> seq.activate_ram()
>>> seq.check_completeness()
Traceback (most recent call last):
...
RuntimeError: The series array of sequence `seq` contains 10 nan values.
>>> seq.series = 1.0
>>> seq.check_completeness()
>>> seq.series[3] = numpy.nan
>>> seq.check_completeness()
Traceback (most recent call last):
...
RuntimeError: The series array of sequence `seq` contains 1 nan value.
>>> with pub.options.checkseries(False):
... seq.check_completeness()
"""
if hydpy.pub.options.checkseries:
isnan = numpy.isnan(self.series)
if numpy.any(isnan):
nmb = numpy.sum(isnan)
valuestring = 'value' if nmb == 1 else 'values'
raise RuntimeError(
f'The series array of sequence '
f'{objecttools.devicephrase(self)} contains '
f'{nmb} nan {valuestring}.')
|
Raise a |RuntimeError| if the |IOSequence.series| contains at
least one |numpy.nan| value, if option |Options.checkseries| is
enabled.
>>> from hydpy import pub
>>> pub.timegrids = '2000-01-01', '2000-01-11', '1d'
>>> from hydpy.core.sequencetools import IOSequence
>>> class Seq(IOSequence):
... NDIM = 0
>>> seq = Seq(None)
>>> seq.activate_ram()
>>> seq.check_completeness()
Traceback (most recent call last):
...
RuntimeError: The series array of sequence `seq` contains 10 nan values.
>>> seq.series = 1.0
>>> seq.check_completeness()
>>> seq.series[3] = numpy.nan
>>> seq.check_completeness()
Traceback (most recent call last):
...
RuntimeError: The series array of sequence `seq` contains 1 nan value.
>>> with pub.options.checkseries(False):
... seq.check_completeness()
|
entailment
|
def save_ext(self):
"""Write the internal data into an external data file."""
try:
sequencemanager = hydpy.pub.sequencemanager
except AttributeError:
raise RuntimeError(
'The time series of sequence %s cannot be saved. Firstly,'
'you have to prepare `pub.sequencemanager` correctly.'
% objecttools.devicephrase(self))
sequencemanager.save_file(self)
|
Write the internal data into an external data file.
|
entailment
|
def _load_int(self):
"""Load internal data from file and return it."""
values = numpy.fromfile(self.filepath_int)
if self.NDIM > 0:
values = values.reshape(self.seriesshape)
return values
|
Load internal data from file and return it.
|
entailment
|
def average_series(self, *args, **kwargs) -> InfoArray:
"""Average the actual time series of the |Variable| object for all
time points.
Method |IOSequence.average_series| works similarly as method
|Variable.average_values| of class |Variable|, from which we
borrow some examples. However, firstly, we have to prepare a
|Timegrids| object to define the |IOSequence.series| length:
>>> from hydpy import pub
>>> pub.timegrids = '2000-01-01', '2000-01-04', '1d'
As shown for method |Variable.average_values|, for 0-dimensional
|IOSequence| objects the result of |IOSequence.average_series|
equals |IOSequence.series| itself:
>>> from hydpy.core.sequencetools import IOSequence
>>> class SoilMoisture(IOSequence):
... NDIM = 0
>>> sm = SoilMoisture(None)
>>> sm.activate_ram()
>>> import numpy
>>> sm.series = numpy.array([190.0, 200.0, 210.0])
>>> sm.average_series()
InfoArray([ 190., 200., 210.])
For |IOSequence| objects with an increased dimensionality, a
weighting parameter is required, again:
>>> SoilMoisture.NDIM = 1
>>> sm.shape = 3
>>> sm.activate_ram()
>>> sm.series = (
... [190.0, 390.0, 490.0],
... [200.0, 400.0, 500.0],
... [210.0, 410.0, 510.0])
>>> from hydpy.core.parametertools import Parameter
>>> class Area(Parameter):
... NDIM = 1
... shape = (3,)
... value = numpy.array([1.0, 1.0, 2.0])
>>> area = Area(None)
>>> SoilMoisture.refweights = property(lambda self: area)
>>> sm.average_series()
InfoArray([ 390., 400., 410.])
The documentation on method |Variable.average_values| provides
many examples on how to use different masks in different ways.
Here we restrict ourselves to the first example, where a new
mask enforces that |IOSequence.average_series| takes only the
first two columns of the `series` into account:
>>> from hydpy.core.masktools import DefaultMask
>>> class Soil(DefaultMask):
... @classmethod
... def new(cls, variable, **kwargs):
... return cls.array2mask([True, True, False])
>>> SoilMoisture.mask = Soil()
>>> sm.average_series()
InfoArray([ 290., 300., 310.])
"""
try:
if not self.NDIM:
array = self.series
else:
mask = self.get_submask(*args, **kwargs)
if numpy.any(mask):
weights = self.refweights[mask]
weights /= numpy.sum(weights)
series = self.series[:, mask]
axes = tuple(range(1, self.NDIM+1))
array = numpy.sum(weights*series, axis=axes)
else:
return numpy.nan
return InfoArray(array, info={'type': 'mean'})
except BaseException:
objecttools.augment_excmessage(
'While trying to calculate the mean value of '
'the internal time series of sequence %s'
% objecttools.devicephrase(self))
|
Average the actual time series of the |Variable| object for all
time points.
Method |IOSequence.average_series| works similarly as method
|Variable.average_values| of class |Variable|, from which we
borrow some examples. However, firstly, we have to prepare a
|Timegrids| object to define the |IOSequence.series| length:
>>> from hydpy import pub
>>> pub.timegrids = '2000-01-01', '2000-01-04', '1d'
As shown for method |Variable.average_values|, for 0-dimensional
|IOSequence| objects the result of |IOSequence.average_series|
equals |IOSequence.series| itself:
>>> from hydpy.core.sequencetools import IOSequence
>>> class SoilMoisture(IOSequence):
... NDIM = 0
>>> sm = SoilMoisture(None)
>>> sm.activate_ram()
>>> import numpy
>>> sm.series = numpy.array([190.0, 200.0, 210.0])
>>> sm.average_series()
InfoArray([ 190., 200., 210.])
For |IOSequence| objects with an increased dimensionality, a
weighting parameter is required, again:
>>> SoilMoisture.NDIM = 1
>>> sm.shape = 3
>>> sm.activate_ram()
>>> sm.series = (
... [190.0, 390.0, 490.0],
... [200.0, 400.0, 500.0],
... [210.0, 410.0, 510.0])
>>> from hydpy.core.parametertools import Parameter
>>> class Area(Parameter):
... NDIM = 1
... shape = (3,)
... value = numpy.array([1.0, 1.0, 2.0])
>>> area = Area(None)
>>> SoilMoisture.refweights = property(lambda self: area)
>>> sm.average_series()
InfoArray([ 390., 400., 410.])
The documentation on method |Variable.average_values| provides
many examples on how to use different masks in different ways.
Here we restrict ourselves to the first example, where a new
mask enforces that |IOSequence.average_series| takes only the
first two columns of the `series` into account:
>>> from hydpy.core.masktools import DefaultMask
>>> class Soil(DefaultMask):
... @classmethod
... def new(cls, variable, **kwargs):
... return cls.array2mask([True, True, False])
>>> SoilMoisture.mask = Soil()
>>> sm.average_series()
InfoArray([ 290., 300., 310.])
|
entailment
|
def aggregate_series(self, *args, **kwargs) -> InfoArray:
"""Aggregates time series data based on the actual
|FluxSequence.aggregation_ext| attribute of |IOSequence|
subclasses.
We prepare some nodes and elements with the help of
method |prepare_io_example_1| and select a 1-dimensional
flux sequence of type |lland_fluxes.NKor| as an example:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> seq = elements.element3.model.sequences.fluxes.nkor
If no |FluxSequence.aggregation_ext| is `none`, the
original time series values are returned:
>>> seq.aggregation_ext
'none'
>>> seq.aggregate_series()
InfoArray([[ 24., 25., 26.],
[ 27., 28., 29.],
[ 30., 31., 32.],
[ 33., 34., 35.]])
If no |FluxSequence.aggregation_ext| is `mean`, function
|IOSequence.aggregate_series| is called:
>>> seq.aggregation_ext = 'mean'
>>> seq.aggregate_series()
InfoArray([ 25., 28., 31., 34.])
In case the state of the sequence is invalid:
>>> seq.aggregation_ext = 'nonexistent'
>>> seq.aggregate_series()
Traceback (most recent call last):
...
RuntimeError: Unknown aggregation mode `nonexistent` for \
sequence `nkor` of element `element3`.
The following technical test confirms that all potential
positional and keyword arguments are passed properly:
>>> seq.aggregation_ext = 'mean'
>>> from unittest import mock
>>> seq.average_series = mock.MagicMock()
>>> _ = seq.aggregate_series(1, x=2)
>>> seq.average_series.assert_called_with(1, x=2)
"""
mode = self.aggregation_ext
if mode == 'none':
return self.series
elif mode == 'mean':
return self.average_series(*args, **kwargs)
else:
raise RuntimeError(
'Unknown aggregation mode `%s` for sequence %s.'
% (mode, objecttools.devicephrase(self)))
|
Aggregates time series data based on the actual
|FluxSequence.aggregation_ext| attribute of |IOSequence|
subclasses.
We prepare some nodes and elements with the help of
method |prepare_io_example_1| and select a 1-dimensional
flux sequence of type |lland_fluxes.NKor| as an example:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> seq = elements.element3.model.sequences.fluxes.nkor
If no |FluxSequence.aggregation_ext| is `none`, the
original time series values are returned:
>>> seq.aggregation_ext
'none'
>>> seq.aggregate_series()
InfoArray([[ 24., 25., 26.],
[ 27., 28., 29.],
[ 30., 31., 32.],
[ 33., 34., 35.]])
If no |FluxSequence.aggregation_ext| is `mean`, function
|IOSequence.aggregate_series| is called:
>>> seq.aggregation_ext = 'mean'
>>> seq.aggregate_series()
InfoArray([ 25., 28., 31., 34.])
In case the state of the sequence is invalid:
>>> seq.aggregation_ext = 'nonexistent'
>>> seq.aggregate_series()
Traceback (most recent call last):
...
RuntimeError: Unknown aggregation mode `nonexistent` for \
sequence `nkor` of element `element3`.
The following technical test confirms that all potential
positional and keyword arguments are passed properly:
>>> seq.aggregation_ext = 'mean'
>>> from unittest import mock
>>> seq.average_series = mock.MagicMock()
>>> _ = seq.aggregate_series(1, x=2)
>>> seq.average_series.assert_called_with(1, x=2)
|
entailment
|
def old(self):
"""Assess to the state value(s) at beginning of the time step, which
has been processed most recently. When using *HydPy* in the
normal manner. But it can be helpful for demonstration and debugging
purposes.
"""
value = getattr(self.fastaccess_old, self.name, None)
if value is None:
raise RuntimeError(
'No value/values of sequence %s has/have '
'not been defined so far.'
% objecttools.elementphrase(self))
else:
if self.NDIM:
value = numpy.asarray(value)
return value
|
Assess to the state value(s) at beginning of the time step, which
has been processed most recently. When using *HydPy* in the
normal manner. But it can be helpful for demonstration and debugging
purposes.
|
entailment
|
def load_ext(self):
"""Read time series data like method |IOSequence.load_ext| of class
|IOSequence|, but with special handling of missing data.
The method's "special handling" is to convert errors to warnings.
We explain the reasons in the documentation on method |Obs.load_ext|
of class |Obs|, from which we borrow the following examples.
The only differences are that method |Sim.load_ext| of class |Sim|
does not disable property |IOSequence.memoryflag| and uses option
|Options.warnmissingsimfile| instead of |Options.warnmissingobsfile|:
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, pub, TestIO
>>> hp = HydPy('LahnH')
>>> pub.timegrids = '1996-01-01', '1996-01-06', '1d'
>>> with TestIO():
... hp.prepare_network()
... hp.init_models()
... hp.prepare_simseries()
>>> sim = hp.nodes.dill.sequences.sim
>>> with TestIO():
... sim.load_ext() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
UserWarning: While trying to load the external data of sequence \
`sim` of node `dill`, the following error occurred: [Errno 2] No such file \
or directory: '...dill_sim_q.asc'
>>> sim.series
InfoArray([ nan, nan, nan, nan, nan])
>>> sim.series = 1.0
>>> with TestIO():
... sim.save_ext()
>>> sim.series = 0.0
>>> with TestIO():
... sim.load_ext()
>>> sim.series
InfoArray([ 1., 1., 1., 1., 1.])
>>> import numpy
>>> sim.series[2] = numpy.nan
>>> with TestIO():
... pub.sequencemanager.nodeoverwrite = True
... sim.save_ext()
>>> with TestIO():
... sim.load_ext()
Traceback (most recent call last):
...
UserWarning: While trying to load the external data of sequence `sim` \
of node `dill`, the following error occurred: The series array of sequence \
`sim` of node `dill` contains 1 nan value.
>>> sim.series
InfoArray([ 1., 1., nan, 1., 1.])
>>> sim.series = 0.0
>>> with TestIO():
... with pub.options.warnmissingsimfile(False):
... sim.load_ext()
>>> sim.series
InfoArray([ 1., 1., nan, 1., 1.])
"""
try:
super().load_ext()
except BaseException:
if hydpy.pub.options.warnmissingsimfile:
warnings.warn(str(sys.exc_info()[1]))
|
Read time series data like method |IOSequence.load_ext| of class
|IOSequence|, but with special handling of missing data.
The method's "special handling" is to convert errors to warnings.
We explain the reasons in the documentation on method |Obs.load_ext|
of class |Obs|, from which we borrow the following examples.
The only differences are that method |Sim.load_ext| of class |Sim|
does not disable property |IOSequence.memoryflag| and uses option
|Options.warnmissingsimfile| instead of |Options.warnmissingobsfile|:
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, pub, TestIO
>>> hp = HydPy('LahnH')
>>> pub.timegrids = '1996-01-01', '1996-01-06', '1d'
>>> with TestIO():
... hp.prepare_network()
... hp.init_models()
... hp.prepare_simseries()
>>> sim = hp.nodes.dill.sequences.sim
>>> with TestIO():
... sim.load_ext() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
UserWarning: While trying to load the external data of sequence \
`sim` of node `dill`, the following error occurred: [Errno 2] No such file \
or directory: '...dill_sim_q.asc'
>>> sim.series
InfoArray([ nan, nan, nan, nan, nan])
>>> sim.series = 1.0
>>> with TestIO():
... sim.save_ext()
>>> sim.series = 0.0
>>> with TestIO():
... sim.load_ext()
>>> sim.series
InfoArray([ 1., 1., 1., 1., 1.])
>>> import numpy
>>> sim.series[2] = numpy.nan
>>> with TestIO():
... pub.sequencemanager.nodeoverwrite = True
... sim.save_ext()
>>> with TestIO():
... sim.load_ext()
Traceback (most recent call last):
...
UserWarning: While trying to load the external data of sequence `sim` \
of node `dill`, the following error occurred: The series array of sequence \
`sim` of node `dill` contains 1 nan value.
>>> sim.series
InfoArray([ 1., 1., nan, 1., 1.])
>>> sim.series = 0.0
>>> with TestIO():
... with pub.options.warnmissingsimfile(False):
... sim.load_ext()
>>> sim.series
InfoArray([ 1., 1., nan, 1., 1.])
|
entailment
|
def load_ext(self):
"""Read time series data like method |IOSequence.load_ext| of class
|IOSequence|, but with special handling of missing data.
When reading incomplete time series data, *HydPy* usually raises
a |RuntimeError| to prevent from performing erroneous calculations.
For instance, this makes sense for meteorological input data, being a
definite requirement for hydrological simulations. However, the
same often does not hold for the time series of |Obs| sequences,
e.g. representing measured discharge. Measured discharge is often
handled as an optional input value, or even used for comparison
purposes only.
According to this reasoning, *HydPy* raises (at most) a |UserWarning|
in case of missing or incomplete external time series data of |Obs|
sequences. The following examples show this based on the `LahnH`
project, mainly focussing on the |Obs| sequence of node `dill`,
which is ready for handling time series data at the end of the
following steps:
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, pub, TestIO
>>> hp = HydPy('LahnH')
>>> pub.timegrids = '1996-01-01', '1996-01-06', '1d'
>>> with TestIO():
... hp.prepare_network()
... hp.init_models()
... hp.prepare_obsseries()
>>> obs = hp.nodes.dill.sequences.obs
>>> obs.ramflag
True
Trying to read non-existing data raises the following warning
and disables the sequence's ability to handle time series data:
>>> with TestIO():
... hp.load_obsseries() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
UserWarning: The `memory flag` of sequence `obs` of node `dill` had \
to be set to `False` due to the following problem: While trying to load the \
external data of sequence `obs` of node `dill`, the following error occurred: \
[Errno 2] No such file or directory: '...dill_obs_q.asc'
>>> obs.ramflag
False
After writing a complete external data fine, everything works fine:
>>> obs.activate_ram()
>>> obs.series = 1.0
>>> with TestIO():
... obs.save_ext()
>>> obs.series = 0.0
>>> with TestIO():
... obs.load_ext()
>>> obs.series
InfoArray([ 1., 1., 1., 1., 1.])
Reading incomplete data also results in a warning message, but does
not disable the |IOSequence.memoryflag|:
>>> import numpy
>>> obs.series[2] = numpy.nan
>>> with TestIO():
... pub.sequencemanager.nodeoverwrite = True
... obs.save_ext()
>>> with TestIO():
... obs.load_ext()
Traceback (most recent call last):
...
UserWarning: While trying to load the external data of sequence `obs` \
of node `dill`, the following error occurred: The series array of sequence \
`obs` of node `dill` contains 1 nan value.
>>> obs.memoryflag
True
Option |Options.warnmissingobsfile| allows disabling the warning
messages without altering the functionalities described above:
>>> hp.prepare_obsseries()
>>> with TestIO():
... with pub.options.warnmissingobsfile(False):
... hp.load_obsseries()
>>> obs.series
InfoArray([ 1., 1., nan, 1., 1.])
>>> hp.nodes.lahn_1.sequences.obs.memoryflag
False
"""
try:
super().load_ext()
except OSError:
del self.memoryflag
if hydpy.pub.options.warnmissingobsfile:
warnings.warn(
f'The `memory flag` of sequence '
f'{objecttools.nodephrase(self)} had to be set to `False` '
f'due to the following problem: {sys.exc_info()[1]}')
except BaseException:
if hydpy.pub.options.warnmissingobsfile:
warnings.warn(str(sys.exc_info()[1]))
|
Read time series data like method |IOSequence.load_ext| of class
|IOSequence|, but with special handling of missing data.
When reading incomplete time series data, *HydPy* usually raises
a |RuntimeError| to prevent from performing erroneous calculations.
For instance, this makes sense for meteorological input data, being a
definite requirement for hydrological simulations. However, the
same often does not hold for the time series of |Obs| sequences,
e.g. representing measured discharge. Measured discharge is often
handled as an optional input value, or even used for comparison
purposes only.
According to this reasoning, *HydPy* raises (at most) a |UserWarning|
in case of missing or incomplete external time series data of |Obs|
sequences. The following examples show this based on the `LahnH`
project, mainly focussing on the |Obs| sequence of node `dill`,
which is ready for handling time series data at the end of the
following steps:
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import HydPy, pub, TestIO
>>> hp = HydPy('LahnH')
>>> pub.timegrids = '1996-01-01', '1996-01-06', '1d'
>>> with TestIO():
... hp.prepare_network()
... hp.init_models()
... hp.prepare_obsseries()
>>> obs = hp.nodes.dill.sequences.obs
>>> obs.ramflag
True
Trying to read non-existing data raises the following warning
and disables the sequence's ability to handle time series data:
>>> with TestIO():
... hp.load_obsseries() # doctest: +ELLIPSIS
Traceback (most recent call last):
...
UserWarning: The `memory flag` of sequence `obs` of node `dill` had \
to be set to `False` due to the following problem: While trying to load the \
external data of sequence `obs` of node `dill`, the following error occurred: \
[Errno 2] No such file or directory: '...dill_obs_q.asc'
>>> obs.ramflag
False
After writing a complete external data fine, everything works fine:
>>> obs.activate_ram()
>>> obs.series = 1.0
>>> with TestIO():
... obs.save_ext()
>>> obs.series = 0.0
>>> with TestIO():
... obs.load_ext()
>>> obs.series
InfoArray([ 1., 1., 1., 1., 1.])
Reading incomplete data also results in a warning message, but does
not disable the |IOSequence.memoryflag|:
>>> import numpy
>>> obs.series[2] = numpy.nan
>>> with TestIO():
... pub.sequencemanager.nodeoverwrite = True
... obs.save_ext()
>>> with TestIO():
... obs.load_ext()
Traceback (most recent call last):
...
UserWarning: While trying to load the external data of sequence `obs` \
of node `dill`, the following error occurred: The series array of sequence \
`obs` of node `dill` contains 1 nan value.
>>> obs.memoryflag
True
Option |Options.warnmissingobsfile| allows disabling the warning
messages without altering the functionalities described above:
>>> hp.prepare_obsseries()
>>> with TestIO():
... with pub.options.warnmissingobsfile(False):
... hp.load_obsseries()
>>> obs.series
InfoArray([ 1., 1., nan, 1., 1.])
>>> hp.nodes.lahn_1.sequences.obs.memoryflag
False
|
entailment
|
def open_files(self, idx):
"""Open all files with an activated disk flag."""
for name in self:
if getattr(self, '_%s_diskflag' % name):
path = getattr(self, '_%s_path' % name)
file_ = open(path, 'rb+')
ndim = getattr(self, '_%s_ndim' % name)
position = 8*idx
for idim in range(ndim):
length = getattr(self, '_%s_length_%d' % (name, idim))
position *= length
file_.seek(position)
setattr(self, '_%s_file' % name, file_)
|
Open all files with an activated disk flag.
|
entailment
|
def close_files(self):
"""Close all files with an activated disk flag."""
for name in self:
if getattr(self, '_%s_diskflag' % name):
file_ = getattr(self, '_%s_file' % name)
file_.close()
|
Close all files with an activated disk flag.
|
entailment
|
def load_data(self, idx):
"""Load the internal data of all sequences. Load from file if the
corresponding disk flag is activated, otherwise load from RAM."""
for name in self:
ndim = getattr(self, '_%s_ndim' % name)
diskflag = getattr(self, '_%s_diskflag' % name)
ramflag = getattr(self, '_%s_ramflag' % name)
if diskflag:
file_ = getattr(self, '_%s_file' % name)
length_tot = 1
shape = []
for jdx in range(ndim):
length = getattr(self, '_%s_length_%s' % (name, jdx))
length_tot *= length
shape.append(length)
raw = file_.read(length_tot*8)
values = struct.unpack(length_tot*'d', raw)
if ndim:
values = numpy.array(values).reshape(shape)
else:
values = values[0]
elif ramflag:
array = getattr(self, '_%s_array' % name)
values = array[idx]
if diskflag or ramflag:
if ndim == 0:
setattr(self, name, values)
else:
getattr(self, name)[:] = values
|
Load the internal data of all sequences. Load from file if the
corresponding disk flag is activated, otherwise load from RAM.
|
entailment
|
def save_data(self, idx):
"""Save the internal data of all sequences with an activated flag.
Write to file if the corresponding disk flag is activated; store
in working memory if the corresponding ram flag is activated."""
for name in self:
actual = getattr(self, name)
diskflag = getattr(self, '_%s_diskflag' % name)
ramflag = getattr(self, '_%s_ramflag' % name)
if diskflag:
file_ = getattr(self, '_%s_file' % name)
ndim = getattr(self, '_%s_ndim' % name)
length_tot = 1
for jdx in range(ndim):
length = getattr(self, '_%s_length_%s' % (name, jdx))
length_tot *= length
if ndim:
raw = struct.pack(length_tot*'d', *actual.flatten())
else:
raw = struct.pack('d', actual)
file_.write(raw)
elif ramflag:
array = getattr(self, '_%s_array' % name)
array[idx] = actual
|
Save the internal data of all sequences with an activated flag.
Write to file if the corresponding disk flag is activated; store
in working memory if the corresponding ram flag is activated.
|
entailment
|
def load_simdata(self, idx: int) -> None:
"""Load the next sim sequence value (of the given index)."""
if self._sim_ramflag:
self.sim[0] = self._sim_array[idx]
elif self._sim_diskflag:
raw = self._sim_file.read(8)
self.sim[0] = struct.unpack('d', raw)
|
Load the next sim sequence value (of the given index).
|
entailment
|
def save_simdata(self, idx: int) -> None:
"""Save the last sim sequence value (of the given index)."""
if self._sim_ramflag:
self._sim_array[idx] = self.sim[0]
elif self._sim_diskflag:
raw = struct.pack('d', self.sim[0])
self._sim_file.write(raw)
|
Save the last sim sequence value (of the given index).
|
entailment
|
def load_obsdata(self, idx: int) -> None:
"""Load the next obs sequence value (of the given index)."""
if self._obs_ramflag:
self.obs[0] = self._obs_array[idx]
elif self._obs_diskflag:
raw = self._obs_file.read(8)
self.obs[0] = struct.unpack('d', raw)
|
Load the next obs sequence value (of the given index).
|
entailment
|
def update(self):
"""Update |AbsFHRU| based on |FT| and |FHRU|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> lnk(ACKER)
>>> ft(100.0)
>>> fhru(0.2, 0.8)
>>> derived.absfhru.update()
>>> derived.absfhru
absfhru(20.0, 80.0)
"""
control = self.subpars.pars.control
self(control.ft*control.fhru)
|
Update |AbsFHRU| based on |FT| and |FHRU|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> lnk(ACKER)
>>> ft(100.0)
>>> fhru(0.2, 0.8)
>>> derived.absfhru.update()
>>> derived.absfhru
absfhru(20.0, 80.0)
|
entailment
|
def update(self):
"""Update |KInz| based on |HInz| and |LAI|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> hinz(0.2)
>>> lai.acker_jun = 1.0
>>> lai.vers_dec = 2.0
>>> derived.kinz.update()
>>> from hydpy import round_
>>> round_(derived.kinz.acker_jun)
0.2
>>> round_(derived.kinz.vers_dec)
0.4
"""
con = self.subpars.pars.control
self(con.hinz*con.lai)
|
Update |KInz| based on |HInz| and |LAI|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> hinz(0.2)
>>> lai.acker_jun = 1.0
>>> lai.vers_dec = 2.0
>>> derived.kinz.update()
>>> from hydpy import round_
>>> round_(derived.kinz.acker_jun)
0.2
>>> round_(derived.kinz.vers_dec)
0.4
|
entailment
|
def update(self):
"""Update |WB| based on |RelWB| and |NFk|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> lnk(ACKER)
>>> relwb(0.2)
>>> nfk(100.0, 200.0)
>>> derived.wb.update()
>>> derived.wb
wb(20.0, 40.0)
"""
con = self.subpars.pars.control
self(con.relwb*con.nfk)
|
Update |WB| based on |RelWB| and |NFk|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> lnk(ACKER)
>>> relwb(0.2)
>>> nfk(100.0, 200.0)
>>> derived.wb.update()
>>> derived.wb
wb(20.0, 40.0)
|
entailment
|
def update(self):
"""Update |WZ| based on |RelWZ| and |NFk|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> lnk(ACKER)
>>> relwz(0.8)
>>> nfk(100.0, 200.0)
>>> derived.wz.update()
>>> derived.wz
wz(80.0, 160.0)
"""
con = self.subpars.pars.control
self(con.relwz*con.nfk)
|
Update |WZ| based on |RelWZ| and |NFk|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> nhru(2)
>>> lnk(ACKER)
>>> relwz(0.8)
>>> nfk(100.0, 200.0)
>>> derived.wz.update()
>>> derived.wz
wz(80.0, 160.0)
|
entailment
|
def update(self):
"""Update |KB| based on |EQB| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqb(10.0)
>>> tind.value = 10.0
>>> derived.kb.update()
>>> derived.kb
kb(100.0)
"""
con = self.subpars.pars.control
self(con.eqb*con.tind)
|
Update |KB| based on |EQB| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqb(10.0)
>>> tind.value = 10.0
>>> derived.kb.update()
>>> derived.kb
kb(100.0)
|
entailment
|
def update(self):
"""Update |KI1| based on |EQI1| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi1(5.0)
>>> tind.value = 10.0
>>> derived.ki1.update()
>>> derived.ki1
ki1(50.0)
"""
con = self.subpars.pars.control
self(con.eqi1*con.tind)
|
Update |KI1| based on |EQI1| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi1(5.0)
>>> tind.value = 10.0
>>> derived.ki1.update()
>>> derived.ki1
ki1(50.0)
|
entailment
|
def update(self):
"""Update |KI2| based on |EQI2| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi2(1.0)
>>> tind.value = 10.0
>>> derived.ki2.update()
>>> derived.ki2
ki2(10.0)
"""
con = self.subpars.pars.control
self(con.eqi2*con.tind)
|
Update |KI2| based on |EQI2| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqi2(1.0)
>>> tind.value = 10.0
>>> derived.ki2.update()
>>> derived.ki2
ki2(10.0)
|
entailment
|
def update(self):
"""Update |KD1| based on |EQD1| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqd1(0.5)
>>> tind.value = 10.0
>>> derived.kd1.update()
>>> derived.kd1
kd1(5.0)
"""
con = self.subpars.pars.control
self(con.eqd1*con.tind)
|
Update |KD1| based on |EQD1| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqd1(0.5)
>>> tind.value = 10.0
>>> derived.kd1.update()
>>> derived.kd1
kd1(5.0)
|
entailment
|
def update(self):
"""Update |KD2| based on |EQD2| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqd2(0.1)
>>> tind.value = 10.0
>>> derived.kd2.update()
>>> derived.kd2
kd2(1.0)
"""
con = self.subpars.pars.control
self(con.eqd2*con.tind)
|
Update |KD2| based on |EQD2| and |TInd|.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> eqd2(0.1)
>>> tind.value = 10.0
>>> derived.kd2.update()
>>> derived.kd2
kd2(1.0)
|
entailment
|
def update(self):
"""Update |QFactor| based on |FT| and the current simulation step size.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> simulationstep('1d')
>>> ft(10.0)
>>> derived.qfactor.update()
>>> derived.qfactor
qfactor(0.115741)
"""
con = self.subpars.pars.control
self(con.ft*1000./self.simulationstep.seconds)
|
Update |QFactor| based on |FT| and the current simulation step size.
>>> from hydpy.models.lland import *
>>> parameterstep('1d')
>>> simulationstep('1d')
>>> ft(10.0)
>>> derived.qfactor.update()
>>> derived.qfactor
qfactor(0.115741)
|
entailment
|
def _router_numbers(self):
"""A tuple of the numbers of all "routing" basins."""
return tuple(up for up in self._up2down.keys()
if up in self._up2down.values())
|
A tuple of the numbers of all "routing" basins.
|
entailment
|
def supplier_elements(self):
"""A |Elements| collection of all "supplying" basins.
(All river basins are assumed to supply something to the downstream
basin.)
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... (111, 113, 1129, 11269, 1125, 11261,
... 11262, 1123, 1124, 1122, 1121))
The following elements are properly connected to the required
outlet nodes already:
>>> for element in rbns2s.supplier_elements:
... print(repr(element))
Element("land_111",
outlets="node_113")
Element("land_1121",
outlets="node_1123")
Element("land_1122",
outlets="node_1123")
Element("land_1123",
outlets="node_1125")
Element("land_1124",
outlets="node_1125")
Element("land_1125",
outlets="node_1129")
Element("land_11261",
outlets="node_11269")
Element("land_11262",
outlets="node_11269")
Element("land_11269",
outlets="node_1129")
Element("land_1129",
outlets="node_113")
Element("land_113",
outlets="node_outlet")
It is both possible to change the prefix names of the elements
and nodes, as long as it results in a valid variable name (e.g.
does not start with a number):
>>> rbns2s.supplier_prefix = 'a_'
>>> rbns2s.node_prefix = 'b_'
>>> rbns2s.supplier_elements
Elements("a_111", "a_1121", "a_1122", "a_1123", "a_1124", "a_1125",
"a_11261", "a_11262", "a_11269", "a_1129", "a_113")
"""
elements = devicetools.Elements()
for supplier in self._supplier_numbers:
element = self._get_suppliername(supplier)
try:
outlet = self._get_nodename(self._up2down[supplier])
except TypeError:
outlet = self.last_node
elements += devicetools.Element(element, outlets=outlet)
return elements
|
A |Elements| collection of all "supplying" basins.
(All river basins are assumed to supply something to the downstream
basin.)
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... (111, 113, 1129, 11269, 1125, 11261,
... 11262, 1123, 1124, 1122, 1121))
The following elements are properly connected to the required
outlet nodes already:
>>> for element in rbns2s.supplier_elements:
... print(repr(element))
Element("land_111",
outlets="node_113")
Element("land_1121",
outlets="node_1123")
Element("land_1122",
outlets="node_1123")
Element("land_1123",
outlets="node_1125")
Element("land_1124",
outlets="node_1125")
Element("land_1125",
outlets="node_1129")
Element("land_11261",
outlets="node_11269")
Element("land_11262",
outlets="node_11269")
Element("land_11269",
outlets="node_1129")
Element("land_1129",
outlets="node_113")
Element("land_113",
outlets="node_outlet")
It is both possible to change the prefix names of the elements
and nodes, as long as it results in a valid variable name (e.g.
does not start with a number):
>>> rbns2s.supplier_prefix = 'a_'
>>> rbns2s.node_prefix = 'b_'
>>> rbns2s.supplier_elements
Elements("a_111", "a_1121", "a_1122", "a_1123", "a_1124", "a_1125",
"a_11261", "a_11262", "a_11269", "a_1129", "a_113")
|
entailment
|
def router_elements(self):
"""A |Elements| collection of all "routing" basins.
(Only river basins with a upstream basin are assumed to route
something to the downstream basin.)
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... (111, 113, 1129, 11269, 1125, 11261,
... 11262, 1123, 1124, 1122, 1121))
The following elements are properly connected to the required
inlet and outlet nodes already:
>>> for element in rbns2s.router_elements:
... print(repr(element))
Element("stream_1123",
inlets="node_1123",
outlets="node_1125")
Element("stream_1125",
inlets="node_1125",
outlets="node_1129")
Element("stream_11269",
inlets="node_11269",
outlets="node_1129")
Element("stream_1129",
inlets="node_1129",
outlets="node_113")
Element("stream_113",
inlets="node_113",
outlets="node_outlet")
It is both possible to change the prefix names of the elements
and nodes, as long as it results in a valid variable name (e.g.
does not start with a number):
>>> rbns2s.router_prefix = 'c_'
>>> rbns2s.node_prefix = 'd_'
>>> rbns2s.router_elements
Elements("c_1123", "c_1125", "c_11269", "c_1129", "c_113")
"""
elements = devicetools.Elements()
for router in self._router_numbers:
element = self._get_routername(router)
inlet = self._get_nodename(router)
try:
outlet = self._get_nodename(self._up2down[router])
except TypeError:
outlet = self.last_node
elements += devicetools.Element(
element, inlets=inlet, outlets=outlet)
return elements
|
A |Elements| collection of all "routing" basins.
(Only river basins with a upstream basin are assumed to route
something to the downstream basin.)
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... (111, 113, 1129, 11269, 1125, 11261,
... 11262, 1123, 1124, 1122, 1121))
The following elements are properly connected to the required
inlet and outlet nodes already:
>>> for element in rbns2s.router_elements:
... print(repr(element))
Element("stream_1123",
inlets="node_1123",
outlets="node_1125")
Element("stream_1125",
inlets="node_1125",
outlets="node_1129")
Element("stream_11269",
inlets="node_11269",
outlets="node_1129")
Element("stream_1129",
inlets="node_1129",
outlets="node_113")
Element("stream_113",
inlets="node_113",
outlets="node_outlet")
It is both possible to change the prefix names of the elements
and nodes, as long as it results in a valid variable name (e.g.
does not start with a number):
>>> rbns2s.router_prefix = 'c_'
>>> rbns2s.node_prefix = 'd_'
>>> rbns2s.router_elements
Elements("c_1123", "c_1125", "c_11269", "c_1129", "c_113")
|
entailment
|
def nodes(self):
"""A |Nodes| collection of all required nodes.
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... (111, 113, 1129, 11269, 1125, 11261,
... 11262, 1123, 1124, 1122, 1121))
Note that the required outlet node is added:
>>> rbns2s.nodes
Nodes("node_1123", "node_1125", "node_11269", "node_1129", "node_113",
"node_outlet")
It is both possible to change the prefix names of the nodes and
the name of the outlet node separately:
>>> rbns2s.node_prefix = 'b_'
>>> rbns2s.last_node = 'l_node'
>>> rbns2s.nodes
Nodes("b_1123", "b_1125", "b_11269", "b_1129", "b_113", "l_node")
"""
return (
devicetools.Nodes(
self.node_prefix+routers for routers in self._router_numbers) +
devicetools.Node(self.last_node))
|
A |Nodes| collection of all required nodes.
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... (111, 113, 1129, 11269, 1125, 11261,
... 11262, 1123, 1124, 1122, 1121))
Note that the required outlet node is added:
>>> rbns2s.nodes
Nodes("node_1123", "node_1125", "node_11269", "node_1129", "node_113",
"node_outlet")
It is both possible to change the prefix names of the nodes and
the name of the outlet node separately:
>>> rbns2s.node_prefix = 'b_'
>>> rbns2s.last_node = 'l_node'
>>> rbns2s.nodes
Nodes("b_1123", "b_1125", "b_11269", "b_1129", "b_113", "l_node")
|
entailment
|
def selection(self):
"""A complete |Selection| object of all "supplying" and "routing"
elements and required nodes.
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... (111, 113, 1129, 11269, 1125, 11261,
... 11262, 1123, 1124, 1122, 1121))
>>> rbns2s.selection
Selection("complete",
nodes=("node_1123", "node_1125", "node_11269", "node_1129",
"node_113", "node_outlet"),
elements=("land_111", "land_1121", "land_1122", "land_1123",
"land_1124", "land_1125", "land_11261",
"land_11262", "land_11269", "land_1129",
"land_113", "stream_1123", "stream_1125",
"stream_11269", "stream_1129", "stream_113"))
Besides the possible modifications on the names of the different
nodes and elements, the name of the selection can be set differently:
>>> rbns2s.selection_name = 'sel'
>>> from hydpy import pub
>>> with pub.options.ellipsis(1):
... print(repr(rbns2s.selection))
Selection("sel",
nodes=("node_1123", ...,"node_outlet"),
elements=("land_111", ...,"stream_113"))
"""
return selectiontools.Selection(
self.selection_name, self.nodes, self.elements)
|
A complete |Selection| object of all "supplying" and "routing"
elements and required nodes.
>>> from hydpy import RiverBasinNumbers2Selection
>>> rbns2s = RiverBasinNumbers2Selection(
... (111, 113, 1129, 11269, 1125, 11261,
... 11262, 1123, 1124, 1122, 1121))
>>> rbns2s.selection
Selection("complete",
nodes=("node_1123", "node_1125", "node_11269", "node_1129",
"node_113", "node_outlet"),
elements=("land_111", "land_1121", "land_1122", "land_1123",
"land_1124", "land_1125", "land_11261",
"land_11262", "land_11269", "land_1129",
"land_113", "stream_1123", "stream_1125",
"stream_11269", "stream_1129", "stream_113"))
Besides the possible modifications on the names of the different
nodes and elements, the name of the selection can be set differently:
>>> rbns2s.selection_name = 'sel'
>>> from hydpy import pub
>>> with pub.options.ellipsis(1):
... print(repr(rbns2s.selection))
Selection("sel",
nodes=("node_1123", ...,"node_outlet"),
elements=("land_111", ...,"stream_113"))
|
entailment
|
def str2chars(strings) -> numpy.ndarray:
"""Return |numpy.ndarray| containing the byte characters (second axis)
of all given strings (first axis).
>>> from hydpy.core.netcdftools import str2chars
>>> str2chars(['zeros', 'ones'])
array([[b'z', b'e', b'r', b'o', b's'],
[b'o', b'n', b'e', b's', b'']],
dtype='|S1')
>>> str2chars([])
array([], shape=(0, 0),
dtype='|S1')
"""
maxlen = 0
for name in strings:
maxlen = max(maxlen, len(name))
# noinspection PyTypeChecker
chars = numpy.full(
(len(strings), maxlen), b'', dtype='|S1')
for idx, name in enumerate(strings):
for jdx, char in enumerate(name):
chars[idx, jdx] = char.encode('utf-8')
return chars
|
Return |numpy.ndarray| containing the byte characters (second axis)
of all given strings (first axis).
>>> from hydpy.core.netcdftools import str2chars
>>> str2chars(['zeros', 'ones'])
array([[b'z', b'e', b'r', b'o', b's'],
[b'o', b'n', b'e', b's', b'']],
dtype='|S1')
>>> str2chars([])
array([], shape=(0, 0),
dtype='|S1')
|
entailment
|
def chars2str(chars) -> List[str]:
"""Inversion function of function |str2chars|.
>>> from hydpy.core.netcdftools import chars2str
>>> chars2str([[b'z', b'e', b'r', b'o', b's'],
... [b'o', b'n', b'e', b's', b'']])
['zeros', 'ones']
>>> chars2str([])
[]
"""
strings = collections.deque()
for subchars in chars:
substrings = collections.deque()
for char in subchars:
if char:
substrings.append(char.decode('utf-8'))
else:
substrings.append('')
strings.append(''.join(substrings))
return list(strings)
|
Inversion function of function |str2chars|.
>>> from hydpy.core.netcdftools import chars2str
>>> chars2str([[b'z', b'e', b'r', b'o', b's'],
... [b'o', b'n', b'e', b's', b'']])
['zeros', 'ones']
>>> chars2str([])
[]
|
entailment
|
def create_dimension(ncfile, name, length) -> None:
"""Add a new dimension with the given name and length to the given
NetCDF file.
Essentially, |create_dimension| just calls the equally named method
of the NetCDF library, but adds information to possible error messages:
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... ncfile = netcdf4.Dataset('test.nc', 'w')
>>> from hydpy.core.netcdftools import create_dimension
>>> create_dimension(ncfile, 'dim1', 5)
>>> dim = ncfile.dimensions['dim1']
>>> dim.size if hasattr(dim, 'size') else dim
5
>>> try:
... create_dimension(ncfile, 'dim1', 5)
... except BaseException as exc:
... print(exc) # doctest: +ELLIPSIS
While trying to add dimension `dim1` with length `5` \
to the NetCDF file `test.nc`, the following error occurred: ...
>>> ncfile.close()
"""
try:
ncfile.createDimension(name, length)
except BaseException:
objecttools.augment_excmessage(
'While trying to add dimension `%s` with length `%d` '
'to the NetCDF file `%s`'
% (name, length, get_filepath(ncfile)))
|
Add a new dimension with the given name and length to the given
NetCDF file.
Essentially, |create_dimension| just calls the equally named method
of the NetCDF library, but adds information to possible error messages:
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... ncfile = netcdf4.Dataset('test.nc', 'w')
>>> from hydpy.core.netcdftools import create_dimension
>>> create_dimension(ncfile, 'dim1', 5)
>>> dim = ncfile.dimensions['dim1']
>>> dim.size if hasattr(dim, 'size') else dim
5
>>> try:
... create_dimension(ncfile, 'dim1', 5)
... except BaseException as exc:
... print(exc) # doctest: +ELLIPSIS
While trying to add dimension `dim1` with length `5` \
to the NetCDF file `test.nc`, the following error occurred: ...
>>> ncfile.close()
|
entailment
|
def create_variable(ncfile, name, datatype, dimensions) -> None:
"""Add a new variable with the given name, datatype, and dimensions
to the given NetCDF file.
Essentially, |create_variable| just calls the equally named method
of the NetCDF library, but adds information to possible error messages:
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... ncfile = netcdf4.Dataset('test.nc', 'w')
>>> from hydpy.core.netcdftools import create_variable
>>> try:
... create_variable(ncfile, 'var1', 'f8', ('dim1',))
... except BaseException as exc:
... print(str(exc).strip('"')) # doctest: +ELLIPSIS
While trying to add variable `var1` with datatype `f8` and \
dimensions `('dim1',)` to the NetCDF file `test.nc`, the following error \
occurred: ...
>>> from hydpy.core.netcdftools import create_dimension
>>> create_dimension(ncfile, 'dim1', 5)
>>> create_variable(ncfile, 'var1', 'f8', ('dim1',))
>>> import numpy
>>> numpy.array(ncfile['var1'][:])
array([ nan, nan, nan, nan, nan])
>>> ncfile.close()
"""
default = fillvalue if (datatype == 'f8') else None
try:
ncfile.createVariable(
name, datatype, dimensions=dimensions, fill_value=default)
ncfile[name].long_name = name
except BaseException:
objecttools.augment_excmessage(
'While trying to add variable `%s` with datatype `%s` '
'and dimensions `%s` to the NetCDF file `%s`'
% (name, datatype, dimensions, get_filepath(ncfile)))
|
Add a new variable with the given name, datatype, and dimensions
to the given NetCDF file.
Essentially, |create_variable| just calls the equally named method
of the NetCDF library, but adds information to possible error messages:
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... ncfile = netcdf4.Dataset('test.nc', 'w')
>>> from hydpy.core.netcdftools import create_variable
>>> try:
... create_variable(ncfile, 'var1', 'f8', ('dim1',))
... except BaseException as exc:
... print(str(exc).strip('"')) # doctest: +ELLIPSIS
While trying to add variable `var1` with datatype `f8` and \
dimensions `('dim1',)` to the NetCDF file `test.nc`, the following error \
occurred: ...
>>> from hydpy.core.netcdftools import create_dimension
>>> create_dimension(ncfile, 'dim1', 5)
>>> create_variable(ncfile, 'var1', 'f8', ('dim1',))
>>> import numpy
>>> numpy.array(ncfile['var1'][:])
array([ nan, nan, nan, nan, nan])
>>> ncfile.close()
|
entailment
|
def query_variable(ncfile, name) -> netcdf4.Variable:
"""Return the variable with the given name from the given NetCDF file.
Essentially, |query_variable| just performs a key assess via the
used NetCDF library, but adds information to possible error messages:
>>> from hydpy.core.netcdftools import query_variable
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... file_ = netcdf4.Dataset('model.nc', 'w')
>>> query_variable(file_, 'flux_prec')
Traceback (most recent call last):
...
OSError: NetCDF file `model.nc` does not contain variable `flux_prec`.
>>> from hydpy.core.netcdftools import create_variable
>>> create_variable(file_, 'flux_prec', 'f8', ())
>>> isinstance(query_variable(file_, 'flux_prec'), netcdf4.Variable)
True
>>> file_.close()
"""
try:
return ncfile[name]
except (IndexError, KeyError):
raise OSError(
'NetCDF file `%s` does not contain variable `%s`.'
% (get_filepath(ncfile), name))
|
Return the variable with the given name from the given NetCDF file.
Essentially, |query_variable| just performs a key assess via the
used NetCDF library, but adds information to possible error messages:
>>> from hydpy.core.netcdftools import query_variable
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... file_ = netcdf4.Dataset('model.nc', 'w')
>>> query_variable(file_, 'flux_prec')
Traceback (most recent call last):
...
OSError: NetCDF file `model.nc` does not contain variable `flux_prec`.
>>> from hydpy.core.netcdftools import create_variable
>>> create_variable(file_, 'flux_prec', 'f8', ())
>>> isinstance(query_variable(file_, 'flux_prec'), netcdf4.Variable)
True
>>> file_.close()
|
entailment
|
def query_timegrid(ncfile) -> timetools.Timegrid:
"""Return the |Timegrid| defined by the given NetCDF file.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> from hydpy.core.netcdftools import query_timegrid
>>> filepath = 'LahnH/series/input/hland_v1_input_t.nc'
>>> with TestIO():
... with netcdf4.Dataset(filepath) as ncfile:
... query_timegrid(ncfile)
Timegrid('1996-01-01 00:00:00',
'2007-01-01 00:00:00',
'1d')
"""
timepoints = ncfile[varmapping['timepoints']]
refdate = timetools.Date.from_cfunits(timepoints.units)
return timetools.Timegrid.from_timepoints(
timepoints=timepoints[:],
refdate=refdate,
unit=timepoints.units.strip().split()[0])
|
Return the |Timegrid| defined by the given NetCDF file.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> from hydpy.core.netcdftools import query_timegrid
>>> filepath = 'LahnH/series/input/hland_v1_input_t.nc'
>>> with TestIO():
... with netcdf4.Dataset(filepath) as ncfile:
... query_timegrid(ncfile)
Timegrid('1996-01-01 00:00:00',
'2007-01-01 00:00:00',
'1d')
|
entailment
|
def query_array(ncfile, name) -> numpy.ndarray:
"""Return the data of the variable with the given name from the given
NetCDF file.
The following example shows that |query_array| returns |nan| entries
to represent missing values even when the respective NetCDF variable
defines a different fill value:
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> from hydpy.core import netcdftools
>>> netcdftools.fillvalue = -999.0
>>> with TestIO():
... with netcdf4.Dataset('test.nc', 'w') as ncfile:
... netcdftools.create_dimension(ncfile, 'dim1', 5)
... netcdftools.create_variable(ncfile, 'var1', 'f8', ('dim1',))
... ncfile = netcdf4.Dataset('test.nc', 'r')
>>> netcdftools.query_variable(ncfile, 'var1')[:].data
array([-999., -999., -999., -999., -999.])
>>> netcdftools.query_array(ncfile, 'var1')
array([ nan, nan, nan, nan, nan])
>>> import numpy
>>> netcdftools.fillvalue = numpy.nan
"""
variable = query_variable(ncfile, name)
maskedarray = variable[:]
fillvalue_ = getattr(variable, '_FillValue', numpy.nan)
if not numpy.isnan(fillvalue_):
maskedarray[maskedarray.mask] = numpy.nan
return maskedarray.data
|
Return the data of the variable with the given name from the given
NetCDF file.
The following example shows that |query_array| returns |nan| entries
to represent missing values even when the respective NetCDF variable
defines a different fill value:
>>> from hydpy import TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> from hydpy.core import netcdftools
>>> netcdftools.fillvalue = -999.0
>>> with TestIO():
... with netcdf4.Dataset('test.nc', 'w') as ncfile:
... netcdftools.create_dimension(ncfile, 'dim1', 5)
... netcdftools.create_variable(ncfile, 'var1', 'f8', ('dim1',))
... ncfile = netcdf4.Dataset('test.nc', 'r')
>>> netcdftools.query_variable(ncfile, 'var1')[:].data
array([-999., -999., -999., -999., -999.])
>>> netcdftools.query_array(ncfile, 'var1')
array([ nan, nan, nan, nan, nan])
>>> import numpy
>>> netcdftools.fillvalue = numpy.nan
|
entailment
|
def log(self, sequence, infoarray) -> None:
"""Prepare a |NetCDFFile| object suitable for the given |IOSequence|
object, when necessary, and pass the given arguments to its
|NetCDFFile.log| method."""
if isinstance(sequence, sequencetools.ModelSequence):
descr = sequence.descr_model
else:
descr = 'node'
if self._isolate:
descr = '%s_%s' % (descr, sequence.descr_sequence)
if ((infoarray is not None) and
(infoarray.info['type'] != 'unmodified')):
descr = '%s_%s' % (descr, infoarray.info['type'])
dirpath = sequence.dirpath_ext
try:
files = self.folders[dirpath]
except KeyError:
files: Dict[str, 'NetCDFFile'] = collections.OrderedDict()
self.folders[dirpath] = files
try:
file_ = files[descr]
except KeyError:
file_ = NetCDFFile(
name=descr,
flatten=self._flatten,
isolate=self._isolate,
timeaxis=self._timeaxis,
dirpath=dirpath)
files[descr] = file_
file_.log(sequence, infoarray)
|
Prepare a |NetCDFFile| object suitable for the given |IOSequence|
object, when necessary, and pass the given arguments to its
|NetCDFFile.log| method.
|
entailment
|
def read(self) -> None:
"""Call method |NetCDFFile.read| of all handled |NetCDFFile| objects.
"""
for folder in self.folders.values():
for file_ in folder.values():
file_.read()
|
Call method |NetCDFFile.read| of all handled |NetCDFFile| objects.
|
entailment
|
def write(self) -> None:
"""Call method |NetCDFFile.write| of all handled |NetCDFFile| objects.
"""
if self.folders:
init = hydpy.pub.timegrids.init
timeunits = init.firstdate.to_cfunits('hours')
timepoints = init.to_timepoints('hours')
for folder in self.folders.values():
for file_ in folder.values():
file_.write(timeunits, timepoints)
|
Call method |NetCDFFile.write| of all handled |NetCDFFile| objects.
|
entailment
|
def filenames(self) -> Tuple[str, ...]:
"""A |tuple| of names of all handled |NetCDFFile| objects."""
return tuple(sorted(set(itertools.chain(
*(_.keys() for _ in self.folders.values())))))
|
A |tuple| of names of all handled |NetCDFFile| objects.
|
entailment
|
def log(self, sequence, infoarray) -> None:
"""Pass the given |IoSequence| to a suitable instance of
a |NetCDFVariableBase| subclass.
When writing data, the second argument should be an |InfoArray|.
When reading data, this argument is ignored. Simply pass |None|.
(1) We prepare some devices handling some sequences by applying
function |prepare_io_example_1|. We limit our attention to the
returned elements, which handle the more diverse sequences:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, (element1, element2, element3) = prepare_io_example_1()
(2) We define some shortcuts for the sequences used in the
following examples:
>>> nied1 = element1.model.sequences.inputs.nied
>>> nied2 = element2.model.sequences.inputs.nied
>>> nkor2 = element2.model.sequences.fluxes.nkor
>>> nkor3 = element3.model.sequences.fluxes.nkor
(3) We define a function that logs these example sequences
to a given |NetCDFFile| object and prints some information
about the resulting object structure. Note that sequence
`nkor2` is logged twice, the first time with its original
time series data, the second time with averaged values:
>>> from hydpy import classname
>>> def test(ncfile):
... ncfile.log(nied1, nied1.series)
... ncfile.log(nied2, nied2.series)
... ncfile.log(nkor2, nkor2.series)
... ncfile.log(nkor2, nkor2.average_series())
... ncfile.log(nkor3, nkor3.average_series())
... for name, variable in ncfile.variables.items():
... print(name, classname(variable), variable.subdevicenames)
(4) We prepare a |NetCDFFile| object with both options
`flatten` and `isolate` being disabled:
>>> from hydpy.core.netcdftools import NetCDFFile
>>> ncfile = NetCDFFile(
... 'model', flatten=False, isolate=False, timeaxis=1, dirpath='')
(5) We log all test sequences results in two |NetCDFVariableDeep|
and one |NetCDFVariableAgg| objects. To keep both NetCDF variables
related to |lland_fluxes.NKor| distinguishable, the name
`flux_nkor_mean` includes information about the kind of aggregation
performed:
>>> test(ncfile)
input_nied NetCDFVariableDeep ('element1', 'element2')
flux_nkor NetCDFVariableDeep ('element2',)
flux_nkor_mean NetCDFVariableAgg ('element2', 'element3')
(6) We confirm that the |NetCDFVariableBase| objects received
the required information:
>>> ncfile.flux_nkor.element2.sequence.descr_device
'element2'
>>> ncfile.flux_nkor.element2.array
InfoArray([[ 16., 17.],
[ 18., 19.],
[ 20., 21.],
[ 22., 23.]])
>>> ncfile.flux_nkor_mean.element2.sequence.descr_device
'element2'
>>> ncfile.flux_nkor_mean.element2.array
InfoArray([ 16.5, 18.5, 20.5, 22.5])
(7) We again prepare a |NetCDFFile| object, but now with both
options `flatten` and `isolate` being enabled. To log test
sequences with their original time series data does now trigger
the initialisation of class |NetCDFVariableFlat|. When passing
aggregated data, nothing changes:
>>> ncfile = NetCDFFile(
... 'model', flatten=True, isolate=True, timeaxis=1, dirpath='')
>>> test(ncfile)
input_nied NetCDFVariableFlat ('element1', 'element2')
flux_nkor NetCDFVariableFlat ('element2_0', 'element2_1')
flux_nkor_mean NetCDFVariableAgg ('element2', 'element3')
>>> ncfile.flux_nkor.element2.sequence.descr_device
'element2'
>>> ncfile.flux_nkor.element2.array
InfoArray([[ 16., 17.],
[ 18., 19.],
[ 20., 21.],
[ 22., 23.]])
>>> ncfile.flux_nkor_mean.element2.sequence.descr_device
'element2'
>>> ncfile.flux_nkor_mean.element2.array
InfoArray([ 16.5, 18.5, 20.5, 22.5])
(8) We technically confirm that the `isolate` argument is passed
to the constructor of subclasses of |NetCDFVariableBase| correctly:
>>> from unittest.mock import patch
>>> with patch('hydpy.core.netcdftools.NetCDFVariableFlat') as mock:
... ncfile = NetCDFFile(
... 'model', flatten=True, isolate=False, timeaxis=0,
... dirpath='')
... ncfile.log(nied1, nied1.series)
... mock.assert_called_once_with(
... name='input_nied', timeaxis=0, isolate=False)
"""
aggregated = ((infoarray is not None) and
(infoarray.info['type'] != 'unmodified'))
descr = sequence.descr_sequence
if aggregated:
descr = '_'.join([descr, infoarray.info['type']])
if descr in self.variables:
var_ = self.variables[descr]
else:
if aggregated:
cls = NetCDFVariableAgg
elif self._flatten:
cls = NetCDFVariableFlat
else:
cls = NetCDFVariableDeep
var_ = cls(name=descr,
isolate=self._isolate,
timeaxis=self._timeaxis)
self.variables[descr] = var_
var_.log(sequence, infoarray)
|
Pass the given |IoSequence| to a suitable instance of
a |NetCDFVariableBase| subclass.
When writing data, the second argument should be an |InfoArray|.
When reading data, this argument is ignored. Simply pass |None|.
(1) We prepare some devices handling some sequences by applying
function |prepare_io_example_1|. We limit our attention to the
returned elements, which handle the more diverse sequences:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, (element1, element2, element3) = prepare_io_example_1()
(2) We define some shortcuts for the sequences used in the
following examples:
>>> nied1 = element1.model.sequences.inputs.nied
>>> nied2 = element2.model.sequences.inputs.nied
>>> nkor2 = element2.model.sequences.fluxes.nkor
>>> nkor3 = element3.model.sequences.fluxes.nkor
(3) We define a function that logs these example sequences
to a given |NetCDFFile| object and prints some information
about the resulting object structure. Note that sequence
`nkor2` is logged twice, the first time with its original
time series data, the second time with averaged values:
>>> from hydpy import classname
>>> def test(ncfile):
... ncfile.log(nied1, nied1.series)
... ncfile.log(nied2, nied2.series)
... ncfile.log(nkor2, nkor2.series)
... ncfile.log(nkor2, nkor2.average_series())
... ncfile.log(nkor3, nkor3.average_series())
... for name, variable in ncfile.variables.items():
... print(name, classname(variable), variable.subdevicenames)
(4) We prepare a |NetCDFFile| object with both options
`flatten` and `isolate` being disabled:
>>> from hydpy.core.netcdftools import NetCDFFile
>>> ncfile = NetCDFFile(
... 'model', flatten=False, isolate=False, timeaxis=1, dirpath='')
(5) We log all test sequences results in two |NetCDFVariableDeep|
and one |NetCDFVariableAgg| objects. To keep both NetCDF variables
related to |lland_fluxes.NKor| distinguishable, the name
`flux_nkor_mean` includes information about the kind of aggregation
performed:
>>> test(ncfile)
input_nied NetCDFVariableDeep ('element1', 'element2')
flux_nkor NetCDFVariableDeep ('element2',)
flux_nkor_mean NetCDFVariableAgg ('element2', 'element3')
(6) We confirm that the |NetCDFVariableBase| objects received
the required information:
>>> ncfile.flux_nkor.element2.sequence.descr_device
'element2'
>>> ncfile.flux_nkor.element2.array
InfoArray([[ 16., 17.],
[ 18., 19.],
[ 20., 21.],
[ 22., 23.]])
>>> ncfile.flux_nkor_mean.element2.sequence.descr_device
'element2'
>>> ncfile.flux_nkor_mean.element2.array
InfoArray([ 16.5, 18.5, 20.5, 22.5])
(7) We again prepare a |NetCDFFile| object, but now with both
options `flatten` and `isolate` being enabled. To log test
sequences with their original time series data does now trigger
the initialisation of class |NetCDFVariableFlat|. When passing
aggregated data, nothing changes:
>>> ncfile = NetCDFFile(
... 'model', flatten=True, isolate=True, timeaxis=1, dirpath='')
>>> test(ncfile)
input_nied NetCDFVariableFlat ('element1', 'element2')
flux_nkor NetCDFVariableFlat ('element2_0', 'element2_1')
flux_nkor_mean NetCDFVariableAgg ('element2', 'element3')
>>> ncfile.flux_nkor.element2.sequence.descr_device
'element2'
>>> ncfile.flux_nkor.element2.array
InfoArray([[ 16., 17.],
[ 18., 19.],
[ 20., 21.],
[ 22., 23.]])
>>> ncfile.flux_nkor_mean.element2.sequence.descr_device
'element2'
>>> ncfile.flux_nkor_mean.element2.array
InfoArray([ 16.5, 18.5, 20.5, 22.5])
(8) We technically confirm that the `isolate` argument is passed
to the constructor of subclasses of |NetCDFVariableBase| correctly:
>>> from unittest.mock import patch
>>> with patch('hydpy.core.netcdftools.NetCDFVariableFlat') as mock:
... ncfile = NetCDFFile(
... 'model', flatten=True, isolate=False, timeaxis=0,
... dirpath='')
... ncfile.log(nied1, nied1.series)
... mock.assert_called_once_with(
... name='input_nied', timeaxis=0, isolate=False)
|
entailment
|
def filepath(self) -> str:
"""The NetCDF file path."""
return os.path.join(self._dirpath, self.name + '.nc')
|
The NetCDF file path.
|
entailment
|
def read(self) -> None:
"""Open an existing NetCDF file temporarily and call method
|NetCDFVariableDeep.read| of all handled |NetCDFVariableBase|
objects."""
try:
with netcdf4.Dataset(self.filepath, "r") as ncfile:
timegrid = query_timegrid(ncfile)
for variable in self.variables.values():
variable.read(ncfile, timegrid)
except BaseException:
objecttools.augment_excmessage(
f'While trying to read data from NetCDF file `{self.filepath}`')
|
Open an existing NetCDF file temporarily and call method
|NetCDFVariableDeep.read| of all handled |NetCDFVariableBase|
objects.
|
entailment
|
def write(self, timeunit, timepoints) -> None:
"""Open a new NetCDF file temporarily and call method
|NetCDFVariableBase.write| of all handled |NetCDFVariableBase|
objects."""
with netcdf4.Dataset(self.filepath, "w") as ncfile:
ncfile.Conventions = 'CF-1.6'
self._insert_timepoints(ncfile, timepoints, timeunit)
for variable in self.variables.values():
variable.write(ncfile)
|
Open a new NetCDF file temporarily and call method
|NetCDFVariableBase.write| of all handled |NetCDFVariableBase|
objects.
|
entailment
|
def get_index(self, name_subdevice) -> int:
"""Item access to the wrapped |dict| object with a specialized
error message."""
try:
return self.dict_[name_subdevice]
except KeyError:
raise OSError(
'No data for sequence `%s` and (sub)device `%s` '
'in NetCDF file `%s` available.'
% (self.name_sequence,
name_subdevice,
self.name_ncfile))
|
Item access to the wrapped |dict| object with a specialized
error message.
|
entailment
|
def log(self, sequence, infoarray) -> None:
"""Log the given |IOSequence| object either for reading or writing
data.
The optional `array` argument allows for passing alternative data
in an |InfoArray| object replacing the series of the |IOSequence|
object, which is useful for writing modified (e.g. spatially
averaged) time series.
Logged time series data is available via attribute access:
>>> from hydpy.core.netcdftools import NetCDFVariableBase
>>> from hydpy import make_abc_testable
>>> NCVar = make_abc_testable(NetCDFVariableBase)
>>> ncvar = NCVar('flux_nkor', isolate=True, timeaxis=1)
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> nkor = elements.element1.model.sequences.fluxes.nkor
>>> ncvar.log(nkor, nkor.series)
>>> 'element1' in dir(ncvar)
True
>>> ncvar.element1.sequence is nkor
True
>>> 'element2' in dir(ncvar)
False
>>> ncvar.element2
Traceback (most recent call last):
...
AttributeError: The NetCDFVariable object `flux_nkor` does \
neither handle time series data under the (sub)device name `element2` \
nor does it define a member named `element2`.
"""
descr_device = sequence.descr_device
self.sequences[descr_device] = sequence
self.arrays[descr_device] = infoarray
|
Log the given |IOSequence| object either for reading or writing
data.
The optional `array` argument allows for passing alternative data
in an |InfoArray| object replacing the series of the |IOSequence|
object, which is useful for writing modified (e.g. spatially
averaged) time series.
Logged time series data is available via attribute access:
>>> from hydpy.core.netcdftools import NetCDFVariableBase
>>> from hydpy import make_abc_testable
>>> NCVar = make_abc_testable(NetCDFVariableBase)
>>> ncvar = NCVar('flux_nkor', isolate=True, timeaxis=1)
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> nkor = elements.element1.model.sequences.fluxes.nkor
>>> ncvar.log(nkor, nkor.series)
>>> 'element1' in dir(ncvar)
True
>>> ncvar.element1.sequence is nkor
True
>>> 'element2' in dir(ncvar)
False
>>> ncvar.element2
Traceback (most recent call last):
...
AttributeError: The NetCDFVariable object `flux_nkor` does \
neither handle time series data under the (sub)device name `element2` \
nor does it define a member named `element2`.
|
entailment
|
def insert_subdevices(self, ncfile) -> None:
"""Insert a variable of the names of the (sub)devices of the logged
sequences into the given NetCDF file
(1) We prepare a |NetCDFVariableBase| subclass with fixed
(sub)device names:
>>> from hydpy.core.netcdftools import NetCDFVariableBase, chars2str
>>> from hydpy import make_abc_testable, TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> Var = make_abc_testable(NetCDFVariableBase)
>>> Var.subdevicenames = 'element1', 'element_2'
(2) Without isolating variables,
|NetCDFVariableBase.insert_subdevices| prefixes the name of the
|NetCDFVariableBase| object to the name of the inserted variable
and its dimensions. The first dimension corresponds to the
number of (sub)devices, the second dimension to the number of
characters of the longest (sub)device name:
>>> var1 = Var('var1', isolate=False, timeaxis=1)
>>> with TestIO():
... file1 = netcdf4.Dataset('model1.nc', 'w')
>>> var1.insert_subdevices(file1)
>>> file1['var1_station_id'].dimensions
('var1_stations', 'var1_char_leng_name')
>>> file1['var1_station_id'].shape
(2, 9)
>>> chars2str(file1['var1_station_id'][:])
['element1', 'element_2']
>>> file1.close()
(3) When isolating variables, we omit the prefix:
>>> var2 = Var('var2', isolate=True, timeaxis=1)
>>> with TestIO():
... file2 = netcdf4.Dataset('model2.nc', 'w')
>>> var2.insert_subdevices(file2)
>>> file2['station_id'].dimensions
('stations', 'char_leng_name')
>>> file2['station_id'].shape
(2, 9)
>>> chars2str(file2['station_id'][:])
['element1', 'element_2']
>>> file2.close()
"""
prefix = self.prefix
nmb_subdevices = '%s%s' % (prefix, dimmapping['nmb_subdevices'])
nmb_characters = '%s%s' % (prefix, dimmapping['nmb_characters'])
subdevices = '%s%s' % (prefix, varmapping['subdevices'])
statchars = str2chars(self.subdevicenames)
create_dimension(ncfile, nmb_subdevices, statchars.shape[0])
create_dimension(ncfile, nmb_characters, statchars.shape[1])
create_variable(
ncfile, subdevices, 'S1', (nmb_subdevices, nmb_characters))
ncfile[subdevices][:, :] = statchars
|
Insert a variable of the names of the (sub)devices of the logged
sequences into the given NetCDF file
(1) We prepare a |NetCDFVariableBase| subclass with fixed
(sub)device names:
>>> from hydpy.core.netcdftools import NetCDFVariableBase, chars2str
>>> from hydpy import make_abc_testable, TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> Var = make_abc_testable(NetCDFVariableBase)
>>> Var.subdevicenames = 'element1', 'element_2'
(2) Without isolating variables,
|NetCDFVariableBase.insert_subdevices| prefixes the name of the
|NetCDFVariableBase| object to the name of the inserted variable
and its dimensions. The first dimension corresponds to the
number of (sub)devices, the second dimension to the number of
characters of the longest (sub)device name:
>>> var1 = Var('var1', isolate=False, timeaxis=1)
>>> with TestIO():
... file1 = netcdf4.Dataset('model1.nc', 'w')
>>> var1.insert_subdevices(file1)
>>> file1['var1_station_id'].dimensions
('var1_stations', 'var1_char_leng_name')
>>> file1['var1_station_id'].shape
(2, 9)
>>> chars2str(file1['var1_station_id'][:])
['element1', 'element_2']
>>> file1.close()
(3) When isolating variables, we omit the prefix:
>>> var2 = Var('var2', isolate=True, timeaxis=1)
>>> with TestIO():
... file2 = netcdf4.Dataset('model2.nc', 'w')
>>> var2.insert_subdevices(file2)
>>> file2['station_id'].dimensions
('stations', 'char_leng_name')
>>> file2['station_id'].shape
(2, 9)
>>> chars2str(file2['station_id'][:])
['element1', 'element_2']
>>> file2.close()
|
entailment
|
def query_subdevices(self, ncfile) -> List[str]:
"""Query the names of the (sub)devices of the logged sequences
from the given NetCDF file
(1) We apply function |NetCDFVariableBase.query_subdevices| on
an empty NetCDF file. The error message shows that the method
tries to query the (sub)device names both under the assumptions
that variables have been isolated or not:
>>> from hydpy.core.netcdftools import NetCDFVariableBase
>>> from hydpy import make_abc_testable, TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... ncfile = netcdf4.Dataset('model.nc', 'w')
>>> Var = make_abc_testable(NetCDFVariableBase)
>>> Var.subdevicenames = 'element1', 'element_2'
>>> var = Var('flux_prec', isolate=False, timeaxis=1)
>>> var.query_subdevices(ncfile)
Traceback (most recent call last):
...
OSError: NetCDF file `model.nc` does neither contain a variable \
named `flux_prec_station_id` nor `station_id` for defining the \
coordinate locations of variable `flux_prec`.
(2) After inserting the (sub)device name, they can be queried
and returned:
>>> var.insert_subdevices(ncfile)
>>> Var('flux_prec', isolate=False, timeaxis=1).query_subdevices(ncfile)
['element1', 'element_2']
>>> Var('flux_prec', isolate=True, timeaxis=1).query_subdevices(ncfile)
['element1', 'element_2']
>>> ncfile.close()
"""
tests = ['%s%s' % (prefix, varmapping['subdevices'])
for prefix in ('%s_' % self.name, '')]
for subdevices in tests:
try:
chars = ncfile[subdevices][:]
break
except (IndexError, KeyError):
pass
else:
raise IOError(
'NetCDF file `%s` does neither contain a variable '
'named `%s` nor `%s` for defining the coordinate '
'locations of variable `%s`.'
% (get_filepath(ncfile), tests[0], tests[1], self.name))
return chars2str(chars)
|
Query the names of the (sub)devices of the logged sequences
from the given NetCDF file
(1) We apply function |NetCDFVariableBase.query_subdevices| on
an empty NetCDF file. The error message shows that the method
tries to query the (sub)device names both under the assumptions
that variables have been isolated or not:
>>> from hydpy.core.netcdftools import NetCDFVariableBase
>>> from hydpy import make_abc_testable, TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... ncfile = netcdf4.Dataset('model.nc', 'w')
>>> Var = make_abc_testable(NetCDFVariableBase)
>>> Var.subdevicenames = 'element1', 'element_2'
>>> var = Var('flux_prec', isolate=False, timeaxis=1)
>>> var.query_subdevices(ncfile)
Traceback (most recent call last):
...
OSError: NetCDF file `model.nc` does neither contain a variable \
named `flux_prec_station_id` nor `station_id` for defining the \
coordinate locations of variable `flux_prec`.
(2) After inserting the (sub)device name, they can be queried
and returned:
>>> var.insert_subdevices(ncfile)
>>> Var('flux_prec', isolate=False, timeaxis=1).query_subdevices(ncfile)
['element1', 'element_2']
>>> Var('flux_prec', isolate=True, timeaxis=1).query_subdevices(ncfile)
['element1', 'element_2']
>>> ncfile.close()
|
entailment
|
def query_subdevice2index(self, ncfile) -> Subdevice2Index:
"""Return a |Subdevice2Index| that maps the (sub)device names to
their position within the given NetCDF file.
Method |NetCDFVariableBase.query_subdevice2index| is based on
|NetCDFVariableBase.query_subdevices|. The returned
|Subdevice2Index| object remembers the NetCDF file the
(sub)device names stem from, allowing for clear error messages:
>>> from hydpy.core.netcdftools import NetCDFVariableBase, str2chars
>>> from hydpy import make_abc_testable, TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... ncfile = netcdf4.Dataset('model.nc', 'w')
>>> Var = make_abc_testable(NetCDFVariableBase)
>>> Var.subdevicenames = [
... 'element3', 'element1', 'element1_1', 'element2']
>>> var = Var('flux_prec', isolate=True, timeaxis=1)
>>> var.insert_subdevices(ncfile)
>>> subdevice2index = var.query_subdevice2index(ncfile)
>>> subdevice2index.get_index('element1_1')
2
>>> subdevice2index.get_index('element3')
0
>>> subdevice2index.get_index('element5')
Traceback (most recent call last):
...
OSError: No data for sequence `flux_prec` and (sub)device \
`element5` in NetCDF file `model.nc` available.
Additionally, |NetCDFVariableBase.query_subdevice2index|
checks for duplicates:
>>> ncfile['station_id'][:] = str2chars(
... ['element3', 'element1', 'element1_1', 'element1'])
>>> var.query_subdevice2index(ncfile)
Traceback (most recent call last):
...
OSError: The NetCDF file `model.nc` contains duplicate (sub)device \
names for variable `flux_prec` (the first found duplicate is `element1`).
>>> ncfile.close()
"""
subdevices = self.query_subdevices(ncfile)
self._test_duplicate_exists(ncfile, subdevices)
subdev2index = {subdev: idx for (idx, subdev) in enumerate(subdevices)}
return Subdevice2Index(subdev2index, self.name, get_filepath(ncfile))
|
Return a |Subdevice2Index| that maps the (sub)device names to
their position within the given NetCDF file.
Method |NetCDFVariableBase.query_subdevice2index| is based on
|NetCDFVariableBase.query_subdevices|. The returned
|Subdevice2Index| object remembers the NetCDF file the
(sub)device names stem from, allowing for clear error messages:
>>> from hydpy.core.netcdftools import NetCDFVariableBase, str2chars
>>> from hydpy import make_abc_testable, TestIO
>>> from hydpy.core.netcdftools import netcdf4
>>> with TestIO():
... ncfile = netcdf4.Dataset('model.nc', 'w')
>>> Var = make_abc_testable(NetCDFVariableBase)
>>> Var.subdevicenames = [
... 'element3', 'element1', 'element1_1', 'element2']
>>> var = Var('flux_prec', isolate=True, timeaxis=1)
>>> var.insert_subdevices(ncfile)
>>> subdevice2index = var.query_subdevice2index(ncfile)
>>> subdevice2index.get_index('element1_1')
2
>>> subdevice2index.get_index('element3')
0
>>> subdevice2index.get_index('element5')
Traceback (most recent call last):
...
OSError: No data for sequence `flux_prec` and (sub)device \
`element5` in NetCDF file `model.nc` available.
Additionally, |NetCDFVariableBase.query_subdevice2index|
checks for duplicates:
>>> ncfile['station_id'][:] = str2chars(
... ['element3', 'element1', 'element1_1', 'element1'])
>>> var.query_subdevice2index(ncfile)
Traceback (most recent call last):
...
OSError: The NetCDF file `model.nc` contains duplicate (sub)device \
names for variable `flux_prec` (the first found duplicate is `element1`).
>>> ncfile.close()
|
entailment
|
def sort_timeplaceentries(self, timeentry, placeentry) -> Tuple[Any, Any]:
"""Return a |tuple| containing the given `timeentry` and `placeentry`
sorted in agreement with the currently selected `timeaxis`.
>>> from hydpy.core.netcdftools import NetCDFVariableBase
>>> from hydpy import make_abc_testable
>>> NCVar = make_abc_testable(NetCDFVariableBase)
>>> ncvar = NCVar('flux_nkor', isolate=True, timeaxis=1)
>>> ncvar.sort_timeplaceentries('time', 'place')
('place', 'time')
>>> ncvar = NetCDFVariableDeep('test', isolate=False, timeaxis=0)
>>> ncvar.sort_timeplaceentries('time', 'place')
('time', 'place')
"""
if self._timeaxis:
return placeentry, timeentry
return timeentry, placeentry
|
Return a |tuple| containing the given `timeentry` and `placeentry`
sorted in agreement with the currently selected `timeaxis`.
>>> from hydpy.core.netcdftools import NetCDFVariableBase
>>> from hydpy import make_abc_testable
>>> NCVar = make_abc_testable(NetCDFVariableBase)
>>> ncvar = NCVar('flux_nkor', isolate=True, timeaxis=1)
>>> ncvar.sort_timeplaceentries('time', 'place')
('place', 'time')
>>> ncvar = NetCDFVariableDeep('test', isolate=False, timeaxis=0)
>>> ncvar.sort_timeplaceentries('time', 'place')
('time', 'place')
|
entailment
|
def get_timeplaceslice(self, placeindex) -> \
Union[Tuple[slice, int], Tuple[int, slice]]:
"""Return a |tuple| for indexing a complete time series of a certain
location available in |NetCDFVariableBase.array|.
>>> from hydpy.core.netcdftools import NetCDFVariableBase
>>> from hydpy import make_abc_testable
>>> NCVar = make_abc_testable(NetCDFVariableBase)
>>> ncvar = NCVar('flux_nkor', isolate=True, timeaxis=1)
>>> ncvar.get_timeplaceslice(2)
(2, slice(None, None, None))
>>> ncvar = NetCDFVariableDeep('test', isolate=False, timeaxis=0)
>>> ncvar.get_timeplaceslice(2)
(slice(None, None, None), 2)
"""
return self.sort_timeplaceentries(slice(None), int(placeindex))
|
Return a |tuple| for indexing a complete time series of a certain
location available in |NetCDFVariableBase.array|.
>>> from hydpy.core.netcdftools import NetCDFVariableBase
>>> from hydpy import make_abc_testable
>>> NCVar = make_abc_testable(NetCDFVariableBase)
>>> ncvar = NCVar('flux_nkor', isolate=True, timeaxis=1)
>>> ncvar.get_timeplaceslice(2)
(2, slice(None, None, None))
>>> ncvar = NetCDFVariableDeep('test', isolate=False, timeaxis=0)
>>> ncvar.get_timeplaceslice(2)
(slice(None, None, None), 2)
|
entailment
|
def subdevicenames(self) -> Tuple[str, ...]:
"""A |tuple| containing the device names."""
self: NetCDFVariableBase
return tuple(self.sequences.keys())
|
A |tuple| containing the device names.
|
entailment
|
def write(self, ncfile) -> None:
"""Write the data to the given NetCDF file.
See the general documentation on classes |NetCDFVariableDeep|
and |NetCDFVariableAgg| for some examples.
"""
self: NetCDFVariableBase
self.insert_subdevices(ncfile)
dimensions = self.dimensions
array = self.array
for dimension, length in zip(dimensions[2:], array.shape[2:]):
create_dimension(ncfile, dimension, length)
create_variable(ncfile, self.name, 'f8', dimensions)
ncfile[self.name][:] = array
|
Write the data to the given NetCDF file.
See the general documentation on classes |NetCDFVariableDeep|
and |NetCDFVariableAgg| for some examples.
|
entailment
|
def dimensions(self) -> Tuple[str, ...]:
"""The dimension names of the NetCDF variable.
Usually, the string defined by property |IOSequence.descr_sequence|
prefixes the first dimension name related to the location, which
allows storing different sequences types in one NetCDF file:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableAgg
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=1)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('flux_nkor_stations', 'time')
But when isolating variables into separate NetCDF files, the
variable specific suffix is omitted:
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=True, timeaxis=1)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('stations', 'time')
When using the first axis as the "timeaxis", the order of the
dimension names turns:
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=True, timeaxis=0)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('time', 'stations')
"""
self: NetCDFVariableBase
return self.sort_timeplaceentries(
dimmapping['nmb_timepoints'],
'%s%s' % (self.prefix, dimmapping['nmb_subdevices']))
|
The dimension names of the NetCDF variable.
Usually, the string defined by property |IOSequence.descr_sequence|
prefixes the first dimension name related to the location, which
allows storing different sequences types in one NetCDF file:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableAgg
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=1)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('flux_nkor_stations', 'time')
But when isolating variables into separate NetCDF files, the
variable specific suffix is omitted:
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=True, timeaxis=1)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('stations', 'time')
When using the first axis as the "timeaxis", the order of the
dimension names turns:
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=True, timeaxis=0)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('time', 'stations')
|
entailment
|
def get_slices(self, idx, shape) -> Tuple[IntOrSlice, ...]:
"""Return a |tuple| of one |int| and some |slice| objects to
accesses all values of a certain device within
|NetCDFVariableDeep.array|.
>>> from hydpy.core.netcdftools import NetCDFVariableDeep
>>> ncvar = NetCDFVariableDeep('test', isolate=False, timeaxis=1)
>>> ncvar.get_slices(2, [3])
(2, slice(None, None, None), slice(0, 3, None))
>>> ncvar.get_slices(4, (1, 2))
(4, slice(None, None, None), slice(0, 1, None), slice(0, 2, None))
>>> ncvar = NetCDFVariableDeep('test', isolate=False, timeaxis=0)
>>> ncvar.get_slices(4, (1, 2))
(slice(None, None, None), 4, slice(0, 1, None), slice(0, 2, None))
"""
slices = list(self.get_timeplaceslice(idx))
for length in shape:
slices.append(slice(0, length))
return tuple(slices)
|
Return a |tuple| of one |int| and some |slice| objects to
accesses all values of a certain device within
|NetCDFVariableDeep.array|.
>>> from hydpy.core.netcdftools import NetCDFVariableDeep
>>> ncvar = NetCDFVariableDeep('test', isolate=False, timeaxis=1)
>>> ncvar.get_slices(2, [3])
(2, slice(None, None, None), slice(0, 3, None))
>>> ncvar.get_slices(4, (1, 2))
(4, slice(None, None, None), slice(0, 1, None), slice(0, 2, None))
>>> ncvar = NetCDFVariableDeep('test', isolate=False, timeaxis=0)
>>> ncvar.get_slices(4, (1, 2))
(slice(None, None, None), 4, slice(0, 1, None), slice(0, 2, None))
|
entailment
|
def shape(self) -> Tuple[int, ...]:
"""Required shape of |NetCDFVariableDeep.array|.
For the default configuration, the first axis corresponds to the
number of devices, and the second one to the number of timesteps.
We show this for the 0-dimensional input sequence |lland_inputs.Nied|:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableDeep
>>> ncvar = NetCDFVariableDeep('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.inputs.nied, None)
>>> ncvar.shape
(3, 4)
For higher dimensional sequences, each new entry corresponds
to the maximum number of fields the respective sequences require.
In the next example, we select the 1-dimensional sequence
|lland_fluxes.NKor|. The maximum number 3 (last value of the
returned |tuple|) is due to the third element defining three
hydrological response units:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(3, 4, 3)
When using the first axis for time (`timeaxis=0`) the order of the
first two |tuple| entries turns:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(4, 3, 3)
"""
nmb_place = len(self.sequences)
nmb_time = len(hydpy.pub.timegrids.init)
nmb_others = collections.deque()
for sequence in self.sequences.values():
nmb_others.append(sequence.shape)
nmb_others_max = tuple(numpy.max(nmb_others, axis=0))
return self.sort_timeplaceentries(nmb_time, nmb_place) + nmb_others_max
|
Required shape of |NetCDFVariableDeep.array|.
For the default configuration, the first axis corresponds to the
number of devices, and the second one to the number of timesteps.
We show this for the 0-dimensional input sequence |lland_inputs.Nied|:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableDeep
>>> ncvar = NetCDFVariableDeep('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.inputs.nied, None)
>>> ncvar.shape
(3, 4)
For higher dimensional sequences, each new entry corresponds
to the maximum number of fields the respective sequences require.
In the next example, we select the 1-dimensional sequence
|lland_fluxes.NKor|. The maximum number 3 (last value of the
returned |tuple|) is due to the third element defining three
hydrological response units:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(3, 4, 3)
When using the first axis for time (`timeaxis=0`) the order of the
first two |tuple| entries turns:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(4, 3, 3)
|
entailment
|
def array(self) -> numpy.ndarray:
"""The series data of all logged |IOSequence| objects contained
in one single |numpy.ndarray|.
The documentation on |NetCDFVariableDeep.shape| explains how
|NetCDFVariableDeep.array| is structured. The first example
confirms that, for the default configuration, the first axis
definces the location, while the second one defines time:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableDeep
>>> ncvar = NetCDFVariableDeep('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... nied1 = element.model.sequences.inputs.nied
... ncvar.log(nied1, nied1.series)
>>> ncvar.array
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
For higher dimensional sequences, |NetCDFVariableDeep.array|
can contain missing values. Such missing values show up for
some fiels of the second example element, which defines only
two hydrological response units instead of three:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.array[1]
array([[ 16., 17., nan],
[ 18., 19., nan],
[ 20., 21., nan],
[ 22., 23., nan]])
When using the first axis for time (`timeaxis=0`) the same data
can be accessed with slightly different indexing:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.array[:, 1]
array([[ 16., 17., nan],
[ 18., 19., nan],
[ 20., 21., nan],
[ 22., 23., nan]])
"""
array = numpy.full(self.shape, fillvalue, dtype=float)
for idx, (descr, subarray) in enumerate(self.arrays.items()):
sequence = self.sequences[descr]
array[self.get_slices(idx, sequence.shape)] = subarray
return array
|
The series data of all logged |IOSequence| objects contained
in one single |numpy.ndarray|.
The documentation on |NetCDFVariableDeep.shape| explains how
|NetCDFVariableDeep.array| is structured. The first example
confirms that, for the default configuration, the first axis
definces the location, while the second one defines time:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableDeep
>>> ncvar = NetCDFVariableDeep('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... nied1 = element.model.sequences.inputs.nied
... ncvar.log(nied1, nied1.series)
>>> ncvar.array
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
For higher dimensional sequences, |NetCDFVariableDeep.array|
can contain missing values. Such missing values show up for
some fiels of the second example element, which defines only
two hydrological response units instead of three:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.array[1]
array([[ 16., 17., nan],
[ 18., 19., nan],
[ 20., 21., nan],
[ 22., 23., nan]])
When using the first axis for time (`timeaxis=0`) the same data
can be accessed with slightly different indexing:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.array[:, 1]
array([[ 16., 17., nan],
[ 18., 19., nan],
[ 20., 21., nan],
[ 22., 23., nan]])
|
entailment
|
def dimensions(self) -> Tuple[str, ...]:
"""The dimension names of the NetCDF variable.
Usually, the string defined by property |IOSequence.descr_sequence|
prefixes all dimension names except the second one related to time,
which allows storing different sequences in one NetCDF file:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableDeep
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=1)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('flux_nkor_stations', 'time', 'flux_nkor_axis3')
However, when isolating variables into separate NetCDF files, the
sequence-specific suffix is omitted:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=True, timeaxis=1)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('stations', 'time', 'axis3')
When using the first axis as the "timeaxis", the order of the
first two dimension names turns:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=True, timeaxis=0)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('time', 'stations', 'axis3')
"""
nmb_timepoints = dimmapping['nmb_timepoints']
nmb_subdevices = '%s%s' % (self.prefix, dimmapping['nmb_subdevices'])
dimensions = list(self.sort_timeplaceentries(
nmb_timepoints, nmb_subdevices))
for idx in range(list(self.sequences.values())[0].NDIM):
dimensions.append('%saxis%d' % (self.prefix, idx + 3))
return tuple(dimensions)
|
The dimension names of the NetCDF variable.
Usually, the string defined by property |IOSequence.descr_sequence|
prefixes all dimension names except the second one related to time,
which allows storing different sequences in one NetCDF file:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableDeep
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=False, timeaxis=1)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('flux_nkor_stations', 'time', 'flux_nkor_axis3')
However, when isolating variables into separate NetCDF files, the
sequence-specific suffix is omitted:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=True, timeaxis=1)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('stations', 'time', 'axis3')
When using the first axis as the "timeaxis", the order of the
first two dimension names turns:
>>> ncvar = NetCDFVariableDeep('flux_nkor', isolate=True, timeaxis=0)
>>> ncvar.log(elements.element1.model.sequences.fluxes.nkor, None)
>>> ncvar.dimensions
('time', 'stations', 'axis3')
|
entailment
|
def read(self, ncfile, timegrid_data) -> None:
"""Read the data from the given NetCDF file.
The argument `timegrid_data` defines the data period of the
given NetCDF file.
See the general documentation on class |NetCDFVariableDeep|
for some examples.
"""
array = query_array(ncfile, self.name)
subdev2index = self.query_subdevice2index(ncfile)
for subdevice, sequence in self.sequences.items():
idx = subdev2index.get_index(subdevice)
values = array[self.get_slices(idx, sequence.shape)]
sequence.series = sequence.adjust_series(
timegrid_data, values)
|
Read the data from the given NetCDF file.
The argument `timegrid_data` defines the data period of the
given NetCDF file.
See the general documentation on class |NetCDFVariableDeep|
for some examples.
|
entailment
|
def shape(self) -> Tuple[int, int]:
"""Required shape of |NetCDFVariableAgg.array|.
For the default configuration, the first axis corresponds to the
number of devices, and the second one to the number of timesteps.
We show this for the 1-dimensional input sequence |lland_fluxes.NKor|:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableAgg
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(3, 4)
When using the first axis as the "timeaxis", the order of |tuple|
entries turns:
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(4, 3)
"""
return self.sort_timeplaceentries(
len(hydpy.pub.timegrids.init), len(self.sequences))
|
Required shape of |NetCDFVariableAgg.array|.
For the default configuration, the first axis corresponds to the
number of devices, and the second one to the number of timesteps.
We show this for the 1-dimensional input sequence |lland_fluxes.NKor|:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableAgg
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(3, 4)
When using the first axis as the "timeaxis", the order of |tuple|
entries turns:
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(4, 3)
|
entailment
|
def array(self) -> numpy.ndarray:
"""The aggregated data of all logged |IOSequence| objects contained
in one single |numpy.ndarray| object.
The documentation on |NetCDFVariableAgg.shape| explains how
|NetCDFVariableAgg.array| is structured. This first example
confirms that, under default configuration (`timeaxis=1`),
the first axis corresponds to the location, while the second
one corresponds to time:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableAgg
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.average_series())
>>> ncvar.array
array([[ 12. , 13. , 14. , 15. ],
[ 16.5, 18.5, 20.5, 22.5],
[ 25. , 28. , 31. , 34. ]])
When using the first axis as the "timeaxis", the resulting
|NetCDFVariableAgg.array| is the transposed:
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.average_series())
>>> ncvar.array
array([[ 12. , 16.5, 25. ],
[ 13. , 18.5, 28. ],
[ 14. , 20.5, 31. ],
[ 15. , 22.5, 34. ]])
"""
array = numpy.full(self.shape, fillvalue, dtype=float)
for idx, subarray in enumerate(self.arrays.values()):
array[self.get_timeplaceslice(idx)] = subarray
return array
|
The aggregated data of all logged |IOSequence| objects contained
in one single |numpy.ndarray| object.
The documentation on |NetCDFVariableAgg.shape| explains how
|NetCDFVariableAgg.array| is structured. This first example
confirms that, under default configuration (`timeaxis=1`),
the first axis corresponds to the location, while the second
one corresponds to time:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableAgg
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.average_series())
>>> ncvar.array
array([[ 12. , 13. , 14. , 15. ],
[ 16.5, 18.5, 20.5, 22.5],
[ 25. , 28. , 31. , 34. ]])
When using the first axis as the "timeaxis", the resulting
|NetCDFVariableAgg.array| is the transposed:
>>> ncvar = NetCDFVariableAgg('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.average_series())
>>> ncvar.array
array([[ 12. , 16.5, 25. ],
[ 13. , 18.5, 28. ],
[ 14. , 20.5, 31. ],
[ 15. , 22.5, 34. ]])
|
entailment
|
def shape(self) -> Tuple[int, int]:
"""Required shape of |NetCDFVariableFlat.array|.
For 0-dimensional sequences like |lland_inputs.Nied| and for the
default configuration (`timeaxis=1`), the first axis corresponds
to the number of devices, and the second one two the number of
timesteps:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableFlat
>>> ncvar = NetCDFVariableFlat('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.inputs.nied, None)
>>> ncvar.shape
(3, 4)
For higher dimensional sequences, the first axis corresponds
to "subdevices", e.g. hydrological response units within
different elements. The 1-dimensional sequence |lland_fluxes.NKor|
is logged for three elements with one, two, and three response
units respectively, making up a sum of six subdevices:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(6, 4)
When using the first axis as the "timeaxis", the order of |tuple|
entries turns:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(4, 6)
"""
return self.sort_timeplaceentries(
len(hydpy.pub.timegrids.init),
sum(len(seq) for seq in self.sequences.values()))
|
Required shape of |NetCDFVariableFlat.array|.
For 0-dimensional sequences like |lland_inputs.Nied| and for the
default configuration (`timeaxis=1`), the first axis corresponds
to the number of devices, and the second one two the number of
timesteps:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableFlat
>>> ncvar = NetCDFVariableFlat('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.inputs.nied, None)
>>> ncvar.shape
(3, 4)
For higher dimensional sequences, the first axis corresponds
to "subdevices", e.g. hydrological response units within
different elements. The 1-dimensional sequence |lland_fluxes.NKor|
is logged for three elements with one, two, and three response
units respectively, making up a sum of six subdevices:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(6, 4)
When using the first axis as the "timeaxis", the order of |tuple|
entries turns:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... ncvar.log(element.model.sequences.fluxes.nkor, None)
>>> ncvar.shape
(4, 6)
|
entailment
|
def array(self) -> numpy.ndarray:
"""The series data of all logged |IOSequence| objects contained in
one single |numpy.ndarray| object.
The documentation on |NetCDFVariableAgg.shape| explains how
|NetCDFVariableAgg.array| is structured. The first example
confirms that, under default configuration (`timeaxis=1`), the
first axis corresponds to the location, while the second one
corresponds to time:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableFlat
>>> ncvar = NetCDFVariableFlat('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... nied1 = element.model.sequences.inputs.nied
... ncvar.log(nied1, nied1.series)
>>> ncvar.array
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
Due to the flattening of higher dimensional sequences,
their individual time series (e.g. of different hydrological
response units) are spread over the rows of the array.
For the 1-dimensional sequence |lland_fluxes.NKor|, the
individual time series of the second element are stored
in row two and three:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.array[1:3]
array([[ 16., 18., 20., 22.],
[ 17., 19., 21., 23.]])
When using the first axis as the "timeaxis", the individual time
series of the second element are stored in column two and three:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.array[:, 1:3]
array([[ 16., 17.],
[ 18., 19.],
[ 20., 21.],
[ 22., 23.]])
"""
array = numpy.full(self.shape, fillvalue, dtype=float)
idx0 = 0
idxs: List[Any] = [slice(None)]
for seq, subarray in zip(self.sequences.values(),
self.arrays.values()):
for prod in self._product(seq.shape):
subsubarray = subarray[tuple(idxs + list(prod))]
array[self.get_timeplaceslice(idx0)] = subsubarray
idx0 += 1
return array
|
The series data of all logged |IOSequence| objects contained in
one single |numpy.ndarray| object.
The documentation on |NetCDFVariableAgg.shape| explains how
|NetCDFVariableAgg.array| is structured. The first example
confirms that, under default configuration (`timeaxis=1`), the
first axis corresponds to the location, while the second one
corresponds to time:
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableFlat
>>> ncvar = NetCDFVariableFlat('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... nied1 = element.model.sequences.inputs.nied
... ncvar.log(nied1, nied1.series)
>>> ncvar.array
array([[ 0., 1., 2., 3.],
[ 4., 5., 6., 7.],
[ 8., 9., 10., 11.]])
Due to the flattening of higher dimensional sequences,
their individual time series (e.g. of different hydrological
response units) are spread over the rows of the array.
For the 1-dimensional sequence |lland_fluxes.NKor|, the
individual time series of the second element are stored
in row two and three:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.array[1:3]
array([[ 16., 18., 20., 22.],
[ 17., 19., 21., 23.]])
When using the first axis as the "timeaxis", the individual time
series of the second element are stored in column two and three:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=0)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.array[:, 1:3]
array([[ 16., 17.],
[ 18., 19.],
[ 20., 21.],
[ 22., 23.]])
|
entailment
|
def subdevicenames(self) -> Tuple[str, ...]:
"""A |tuple| containing the (sub)device names.
Property |NetCDFVariableFlat.subdevicenames| clarifies which
row of |NetCDFVariableAgg.array| contains which time series.
For 0-dimensional series like |lland_inputs.Nied|, the plain
device names are returned
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableFlat
>>> ncvar = NetCDFVariableFlat('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... nied1 = element.model.sequences.inputs.nied
... ncvar.log(nied1, nied1.series)
>>> ncvar.subdevicenames
('element1', 'element2', 'element3')
For higher dimensional sequences like |lland_fluxes.NKor|, an
additional suffix defines the index of the respective subdevice.
For example contains the third row of |NetCDFVariableAgg.array|
the time series of the first hydrological response unit of the
second element:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.subdevicenames[1:3]
('element2_0', 'element2_1')
"""
stats: List[str] = collections.deque()
for devicename, seq in self.sequences.items():
if seq.NDIM:
temp = devicename + '_'
for prod in self._product(seq.shape):
stats.append(temp + '_'.join(str(idx) for idx in prod))
else:
stats.append(devicename)
return tuple(stats)
|
A |tuple| containing the (sub)device names.
Property |NetCDFVariableFlat.subdevicenames| clarifies which
row of |NetCDFVariableAgg.array| contains which time series.
For 0-dimensional series like |lland_inputs.Nied|, the plain
device names are returned
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
>>> from hydpy.core.netcdftools import NetCDFVariableFlat
>>> ncvar = NetCDFVariableFlat('input_nied', isolate=False, timeaxis=1)
>>> for element in elements:
... nied1 = element.model.sequences.inputs.nied
... ncvar.log(nied1, nied1.series)
>>> ncvar.subdevicenames
('element1', 'element2', 'element3')
For higher dimensional sequences like |lland_fluxes.NKor|, an
additional suffix defines the index of the respective subdevice.
For example contains the third row of |NetCDFVariableAgg.array|
the time series of the first hydrological response unit of the
second element:
>>> ncvar = NetCDFVariableFlat('flux_nkor', isolate=False, timeaxis=1)
>>> for element in elements:
... nkor1 = element.model.sequences.fluxes.nkor
... ncvar.log(nkor1, nkor1.series)
>>> ncvar.subdevicenames[1:3]
('element2_0', 'element2_1')
|
entailment
|
def _product(shape) -> Iterator[Tuple[int, ...]]:
"""Should return all "subdevice index combinations" for sequences
with arbitrary dimensions:
>>> from hydpy.core.netcdftools import NetCDFVariableFlat
>>> _product = NetCDFVariableFlat.__dict__['_product'].__func__
>>> for comb in _product([1, 2, 3]):
... print(comb)
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
"""
return itertools.product(*(range(nmb) for nmb in shape))
|
Should return all "subdevice index combinations" for sequences
with arbitrary dimensions:
>>> from hydpy.core.netcdftools import NetCDFVariableFlat
>>> _product = NetCDFVariableFlat.__dict__['_product'].__func__
>>> for comb in _product([1, 2, 3]):
... print(comb)
(0, 0, 0)
(0, 0, 1)
(0, 0, 2)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
|
entailment
|
def read(self, ncfile, timegrid_data) -> None:
"""Read the data from the given NetCDF file.
The argument `timegrid_data` defines the data period of the
given NetCDF file.
See the general documentation on class |NetCDFVariableFlat|
for some examples.
"""
array = query_array(ncfile, self.name)
idxs: Tuple[Any] = (slice(None),)
subdev2index = self.query_subdevice2index(ncfile)
for devicename, seq in self.sequences.items():
if seq.NDIM:
if self._timeaxis:
subshape = (array.shape[1],) + seq.shape
else:
subshape = (array.shape[0],) + seq.shape
subarray = numpy.empty(subshape)
temp = devicename + '_'
for prod in self._product(seq.shape):
station = temp + '_'.join(str(idx) for idx in prod)
idx0 = subdev2index.get_index(station)
subarray[idxs+prod] = array[self.get_timeplaceslice(idx0)]
else:
idx = subdev2index.get_index(devicename)
subarray = array[self.get_timeplaceslice(idx)]
seq.series = seq.adjust_series(timegrid_data, subarray)
|
Read the data from the given NetCDF file.
The argument `timegrid_data` defines the data period of the
given NetCDF file.
See the general documentation on class |NetCDFVariableFlat|
for some examples.
|
entailment
|
def write(self, ncfile) -> None:
"""Write the data to the given NetCDF file.
See the general documentation on class |NetCDFVariableFlat|
for some examples.
"""
self.insert_subdevices(ncfile)
create_variable(ncfile, self.name, 'f8', self.dimensions)
ncfile[self.name][:] = self.array
|
Write the data to the given NetCDF file.
See the general documentation on class |NetCDFVariableFlat|
for some examples.
|
entailment
|
def update(self):
"""Determine the number of substeps.
Initialize a llake model and assume a simulation step size of 12 hours:
>>> from hydpy.models.llake import *
>>> parameterstep('1d')
>>> simulationstep('12h')
If the maximum internal step size is also set to 12 hours, there is
only one internal calculation step per outer simulation step:
>>> maxdt('12h')
>>> derived.nmbsubsteps.update()
>>> derived.nmbsubsteps
nmbsubsteps(1)
Assigning smaller values to `maxdt` increases `nmbstepsize`:
>>> maxdt('1h')
>>> derived.nmbsubsteps.update()
>>> derived.nmbsubsteps
nmbsubsteps(12)
In case the simulationstep is not a whole multiple of `dwmax`,
the value of `nmbsubsteps` is rounded up:
>>> maxdt('59m')
>>> derived.nmbsubsteps.update()
>>> derived.nmbsubsteps
nmbsubsteps(13)
Even for `maxdt` values exceeding the simulationstep, the value
of `numbsubsteps` does not become smaller than one:
>>> maxdt('2d')
>>> derived.nmbsubsteps.update()
>>> derived.nmbsubsteps
nmbsubsteps(1)
"""
maxdt = self.subpars.pars.control.maxdt
seconds = self.simulationstep.seconds
self.value = numpy.ceil(seconds/maxdt)
|
Determine the number of substeps.
Initialize a llake model and assume a simulation step size of 12 hours:
>>> from hydpy.models.llake import *
>>> parameterstep('1d')
>>> simulationstep('12h')
If the maximum internal step size is also set to 12 hours, there is
only one internal calculation step per outer simulation step:
>>> maxdt('12h')
>>> derived.nmbsubsteps.update()
>>> derived.nmbsubsteps
nmbsubsteps(1)
Assigning smaller values to `maxdt` increases `nmbstepsize`:
>>> maxdt('1h')
>>> derived.nmbsubsteps.update()
>>> derived.nmbsubsteps
nmbsubsteps(12)
In case the simulationstep is not a whole multiple of `dwmax`,
the value of `nmbsubsteps` is rounded up:
>>> maxdt('59m')
>>> derived.nmbsubsteps.update()
>>> derived.nmbsubsteps
nmbsubsteps(13)
Even for `maxdt` values exceeding the simulationstep, the value
of `numbsubsteps` does not become smaller than one:
>>> maxdt('2d')
>>> derived.nmbsubsteps.update()
>>> derived.nmbsubsteps
nmbsubsteps(1)
|
entailment
|
def update(self):
"""Calulate the auxilary term.
>>> from hydpy.models.llake import *
>>> parameterstep('1d')
>>> simulationstep('12h')
>>> n(3)
>>> v(0., 1e5, 1e6)
>>> q(_1=[0., 1., 2.], _7=[0., 2., 5.])
>>> maxdt('12h')
>>> derived.seconds.update()
>>> derived.nmbsubsteps.update()
>>> derived.vq.update()
>>> derived.vq
vq(toy_1_1_0_0_0=[0.0, 243200.0, 2086400.0],
toy_7_1_0_0_0=[0.0, 286400.0, 2216000.0])
"""
con = self.subpars.pars.control
der = self.subpars
for (toy, qs) in con.q:
setattr(self, str(toy), 2.*con.v+der.seconds/der.nmbsubsteps*qs)
self.refresh()
|
Calulate the auxilary term.
>>> from hydpy.models.llake import *
>>> parameterstep('1d')
>>> simulationstep('12h')
>>> n(3)
>>> v(0., 1e5, 1e6)
>>> q(_1=[0., 1., 2.], _7=[0., 2., 5.])
>>> maxdt('12h')
>>> derived.seconds.update()
>>> derived.nmbsubsteps.update()
>>> derived.vq.update()
>>> derived.vq
vq(toy_1_1_0_0_0=[0.0, 243200.0, 2086400.0],
toy_7_1_0_0_0=[0.0, 286400.0, 2216000.0])
|
entailment
|
def prepare_io_example_1() -> Tuple[devicetools.Nodes, devicetools.Elements]:
# noinspection PyUnresolvedReferences
"""Prepare an IO example configuration.
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
(1) Prepares a short initialisation period of five days:
>>> from hydpy import pub
>>> pub.timegrids
Timegrids(Timegrid('2000-01-01 00:00:00',
'2000-01-05 00:00:00',
'1d'))
(2) Prepares a plain IO testing directory structure:
>>> pub.sequencemanager.inputdirpath
'inputpath'
>>> pub.sequencemanager.fluxdirpath
'outputpath'
>>> pub.sequencemanager.statedirpath
'outputpath'
>>> pub.sequencemanager.nodedirpath
'nodepath'
>>> import os
>>> from hydpy import TestIO
>>> with TestIO():
... print(sorted(filename for filename in os.listdir('.')
... if not filename.startswith('_')))
['inputpath', 'nodepath', 'outputpath']
(3) Returns three |Element| objects handling either application model
|lland_v1| or |lland_v2|, and two |Node| objects handling variables
`Q` and `T`:
>>> for element in elements:
... print(element.name, element.model)
element1 lland_v1
element2 lland_v1
element3 lland_v2
>>> for node in nodes:
... print(node.name, node.variable)
node1 Q
node2 T
(4) Prepares the time series data of the input sequence
|lland_inputs.Nied|, flux sequence |lland_fluxes.NKor|, and state
sequence |lland_states.BoWa| for each model instance, and |Sim| for
each node instance (all values are different), e.g.:
>>> nied1 = elements.element1.model.sequences.inputs.nied
>>> nied1.series
InfoArray([ 0., 1., 2., 3.])
>>> nkor1 = elements.element1.model.sequences.fluxes.nkor
>>> nkor1.series
InfoArray([[ 12.],
[ 13.],
[ 14.],
[ 15.]])
>>> bowa3 = elements.element3.model.sequences.states.bowa
>>> bowa3.series
InfoArray([[ 48., 49., 50.],
[ 51., 52., 53.],
[ 54., 55., 56.],
[ 57., 58., 59.]])
>>> sim2 = nodes.node2.sequences.sim
>>> sim2.series
InfoArray([ 64., 65., 66., 67.])
(5) All sequences carry |numpy.ndarray| objects with (deep) copies
of the time series data for testing:
>>> import numpy
>>> (numpy.all(nied1.series == nied1.testarray) and
... numpy.all(nkor1.series == nkor1.testarray) and
... numpy.all(bowa3.series == bowa3.testarray) and
... numpy.all(sim2.series == sim2.testarray))
InfoArray(True, dtype=bool)
>>> bowa3.series[1, 2] = -999.0
>>> numpy.all(bowa3.series == bowa3.testarray)
InfoArray(False, dtype=bool)
"""
from hydpy import TestIO
TestIO.clear()
from hydpy.core.filetools import SequenceManager
hydpy.pub.sequencemanager = SequenceManager()
with TestIO():
hydpy.pub.sequencemanager.inputdirpath = 'inputpath'
hydpy.pub.sequencemanager.fluxdirpath = 'outputpath'
hydpy.pub.sequencemanager.statedirpath = 'outputpath'
hydpy.pub.sequencemanager.nodedirpath = 'nodepath'
hydpy.pub.timegrids = '2000-01-01', '2000-01-05', '1d'
from hydpy import Node, Nodes, Element, Elements, prepare_model
node1 = Node('node1')
node2 = Node('node2', variable='T')
nodes = Nodes(node1, node2)
element1 = Element('element1', outlets=node1)
element2 = Element('element2', outlets=node1)
element3 = Element('element3', outlets=node1)
elements = Elements(element1, element2, element3)
from hydpy.models import lland_v1, lland_v2
element1.model = prepare_model(lland_v1)
element2.model = prepare_model(lland_v1)
element3.model = prepare_model(lland_v2)
from hydpy.models.lland import ACKER
for idx, element in enumerate(elements):
parameters = element.model.parameters
parameters.control.nhru(idx+1)
parameters.control.lnk(ACKER)
parameters.derived.absfhru(10.0)
with hydpy.pub.options.printprogress(False):
nodes.prepare_simseries()
elements.prepare_inputseries()
elements.prepare_fluxseries()
elements.prepare_stateseries()
def init_values(seq, value1_):
value2_ = value1_ + len(seq.series.flatten())
values_ = numpy.arange(value1_, value2_, dtype=float)
seq.testarray = values_.reshape(seq.seriesshape)
seq.series = seq.testarray.copy()
return value2_
import numpy
value1 = 0
for subname, seqname in zip(['inputs', 'fluxes', 'states'],
['nied', 'nkor', 'bowa']):
for element in elements:
subseqs = getattr(element.model.sequences, subname)
value1 = init_values(getattr(subseqs, seqname), value1)
for node in nodes:
value1 = init_values(node.sequences.sim, value1)
return nodes, elements
|
Prepare an IO example configuration.
>>> from hydpy.core.examples import prepare_io_example_1
>>> nodes, elements = prepare_io_example_1()
(1) Prepares a short initialisation period of five days:
>>> from hydpy import pub
>>> pub.timegrids
Timegrids(Timegrid('2000-01-01 00:00:00',
'2000-01-05 00:00:00',
'1d'))
(2) Prepares a plain IO testing directory structure:
>>> pub.sequencemanager.inputdirpath
'inputpath'
>>> pub.sequencemanager.fluxdirpath
'outputpath'
>>> pub.sequencemanager.statedirpath
'outputpath'
>>> pub.sequencemanager.nodedirpath
'nodepath'
>>> import os
>>> from hydpy import TestIO
>>> with TestIO():
... print(sorted(filename for filename in os.listdir('.')
... if not filename.startswith('_')))
['inputpath', 'nodepath', 'outputpath']
(3) Returns three |Element| objects handling either application model
|lland_v1| or |lland_v2|, and two |Node| objects handling variables
`Q` and `T`:
>>> for element in elements:
... print(element.name, element.model)
element1 lland_v1
element2 lland_v1
element3 lland_v2
>>> for node in nodes:
... print(node.name, node.variable)
node1 Q
node2 T
(4) Prepares the time series data of the input sequence
|lland_inputs.Nied|, flux sequence |lland_fluxes.NKor|, and state
sequence |lland_states.BoWa| for each model instance, and |Sim| for
each node instance (all values are different), e.g.:
>>> nied1 = elements.element1.model.sequences.inputs.nied
>>> nied1.series
InfoArray([ 0., 1., 2., 3.])
>>> nkor1 = elements.element1.model.sequences.fluxes.nkor
>>> nkor1.series
InfoArray([[ 12.],
[ 13.],
[ 14.],
[ 15.]])
>>> bowa3 = elements.element3.model.sequences.states.bowa
>>> bowa3.series
InfoArray([[ 48., 49., 50.],
[ 51., 52., 53.],
[ 54., 55., 56.],
[ 57., 58., 59.]])
>>> sim2 = nodes.node2.sequences.sim
>>> sim2.series
InfoArray([ 64., 65., 66., 67.])
(5) All sequences carry |numpy.ndarray| objects with (deep) copies
of the time series data for testing:
>>> import numpy
>>> (numpy.all(nied1.series == nied1.testarray) and
... numpy.all(nkor1.series == nkor1.testarray) and
... numpy.all(bowa3.series == bowa3.testarray) and
... numpy.all(sim2.series == sim2.testarray))
InfoArray(True, dtype=bool)
>>> bowa3.series[1, 2] = -999.0
>>> numpy.all(bowa3.series == bowa3.testarray)
InfoArray(False, dtype=bool)
|
entailment
|
def prepare_full_example_1() -> None:
"""Prepare the complete `LahnH` project for testing.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import TestIO
>>> import os
>>> with TestIO():
... print('root:', *sorted(os.listdir('.')))
... for folder in ('control', 'conditions', 'series'):
... print(f'LahnH/{folder}:',
... *sorted(os.listdir(f'LahnH/{folder}')))
root: LahnH __init__.py
LahnH/control: default
LahnH/conditions: init_1996_01_01
LahnH/series: input node output temp
ToDo: Improve, test, and explain this example data set.
"""
testtools.TestIO.clear()
shutil.copytree(
os.path.join(data.__path__[0], 'LahnH'),
os.path.join(iotesting.__path__[0], 'LahnH'))
seqpath = os.path.join(iotesting.__path__[0], 'LahnH', 'series')
for folder in ('output', 'node', 'temp'):
os.makedirs(os.path.join(seqpath, folder))
|
Prepare the complete `LahnH` project for testing.
>>> from hydpy.core.examples import prepare_full_example_1
>>> prepare_full_example_1()
>>> from hydpy import TestIO
>>> import os
>>> with TestIO():
... print('root:', *sorted(os.listdir('.')))
... for folder in ('control', 'conditions', 'series'):
... print(f'LahnH/{folder}:',
... *sorted(os.listdir(f'LahnH/{folder}')))
root: LahnH __init__.py
LahnH/control: default
LahnH/conditions: init_1996_01_01
LahnH/series: input node output temp
ToDo: Improve, test, and explain this example data set.
|
entailment
|
def prepare_full_example_2(lastdate='1996-01-05') -> (
hydpytools.HydPy, hydpy.pub, testtools.TestIO):
"""Prepare the complete `LahnH` project for testing.
|prepare_full_example_2| calls |prepare_full_example_1|, but also
returns a readily prepared |HydPy| instance, as well as module
|pub| and class |TestIO|, for convenience:
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, TestIO = prepare_full_example_2()
>>> hp.nodes
Nodes("dill", "lahn_1", "lahn_2", "lahn_3")
>>> hp.elements
Elements("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3",
"stream_dill_lahn_2", "stream_lahn_1_lahn_2",
"stream_lahn_2_lahn_3")
>>> pub.timegrids
Timegrids(Timegrid('1996-01-01 00:00:00',
'1996-01-05 00:00:00',
'1d'))
>>> from hydpy import classname
>>> classname(TestIO)
'TestIO'
The last date of the initialisation period is configurable:
>>> hp, pub, TestIO = prepare_full_example_2('1996-02-01')
>>> pub.timegrids
Timegrids(Timegrid('1996-01-01 00:00:00',
'1996-02-01 00:00:00',
'1d'))
"""
prepare_full_example_1()
with testtools.TestIO():
hp = hydpytools.HydPy('LahnH')
hydpy.pub.timegrids = '1996-01-01', lastdate, '1d'
hp.prepare_everything()
return hp, hydpy.pub, testtools.TestIO
|
Prepare the complete `LahnH` project for testing.
|prepare_full_example_2| calls |prepare_full_example_1|, but also
returns a readily prepared |HydPy| instance, as well as module
|pub| and class |TestIO|, for convenience:
>>> from hydpy.core.examples import prepare_full_example_2
>>> hp, pub, TestIO = prepare_full_example_2()
>>> hp.nodes
Nodes("dill", "lahn_1", "lahn_2", "lahn_3")
>>> hp.elements
Elements("land_dill", "land_lahn_1", "land_lahn_2", "land_lahn_3",
"stream_dill_lahn_2", "stream_lahn_1_lahn_2",
"stream_lahn_2_lahn_3")
>>> pub.timegrids
Timegrids(Timegrid('1996-01-01 00:00:00',
'1996-01-05 00:00:00',
'1d'))
>>> from hydpy import classname
>>> classname(TestIO)
'TestIO'
The last date of the initialisation period is configurable:
>>> hp, pub, TestIO = prepare_full_example_2('1996-02-01')
>>> pub.timegrids
Timegrids(Timegrid('1996-01-01 00:00:00',
'1996-02-01 00:00:00',
'1d'))
|
entailment
|
def get_postalcodes_around_radius(self, pc, radius):
postalcodes = self.get(pc)
if postalcodes is None:
raise PostalCodeNotFoundException("Could not find postal code you're searching for.")
else:
pc = postalcodes[0]
radius = float(radius)
'''
Bounding box calculations updated from pyzipcode
'''
earth_radius = 6371
dlat = radius / earth_radius
dlon = asin(sin(dlat) / cos(radians(pc.latitude)))
lat_delta = degrees(dlat)
lon_delta = degrees(dlon)
if lat_delta < 0:
lat_range = (pc.latitude + lat_delta, pc.latitude - lat_delta)
else:
lat_range = (pc.latitude - lat_delta, pc.latitude + lat_delta)
long_range = (pc.longitude - lat_delta, pc.longitude + lon_delta)
return format_result(self.conn_manager.query(PC_RANGE_QUERY % (
long_range[0], long_range[1],
lat_range[0], lat_range[1]
)))
|
Bounding box calculations updated from pyzipcode
|
entailment
|
def get_all_player_ids(ids="shots"):
"""
Returns a pandas DataFrame containing the player IDs used in the
stats.nba.com API.
Parameters
----------
ids : { "shots" | "all_players" | "all_data" }, optional
Passing in "shots" returns a DataFrame that contains the player IDs of
all players have shot chart data. It is the default parameter value.
Passing in "all_players" returns a DataFrame that contains
all the player IDs used in the stats.nba.com API.
Passing in "all_data" returns a DataFrame that contains all the data
accessed from the JSON at the following url:
http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=0&LeagueID=00&Season=2015-16
The column information for this DataFrame is as follows:
PERSON_ID: The player ID for that player
DISPLAY_LAST_COMMA_FIRST: The player's name.
ROSTERSTATUS: 0 means player is not on a roster, 1 means he's on a
roster
FROM_YEAR: The first year the player played.
TO_YEAR: The last year the player played.
PLAYERCODE: A code representing the player. Unsure of its use.
Returns
-------
df : pandas DataFrame
The pandas DataFrame object that contains the player IDs for the
stats.nba.com API.
"""
url = "http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=0&LeagueID=00&Season=2015-16"
# get the web page
response = requests.get(url, headers=HEADERS)
response.raise_for_status()
# access 'resultSets', which is a list containing the dict with all the data
# The 'header' key accesses the headers
headers = response.json()['resultSets'][0]['headers']
# The 'rowSet' key contains the player data along with their IDs
players = response.json()['resultSets'][0]['rowSet']
# Create dataframe with proper numeric types
df = pd.DataFrame(players, columns=headers)
# Dealing with different means of converision for pandas 0.17.0 or 0.17.1
# and 0.15.0 or loweer
if '0.17' in pd.__version__:
# alternative to convert_objects() to numeric to get rid of warning
# as convert_objects() is deprecated in pandas 0.17.0+
df = df.apply(pd.to_numeric, args=('ignore',))
else:
df = df.convert_objects(convert_numeric=True)
if ids == "shots":
df = df.query("(FROM_YEAR >= 2001) or (TO_YEAR >= 2001)")
df = df.reset_index(drop=True)
# just keep the player ids and names
df = df.iloc[:, 0:2]
return df
if ids == "all_players":
df = df.iloc[:, 0:2]
return df
if ids == "all_data":
return df
else:
er = "Invalid 'ids' value. It must be 'shots', 'all_shots', or 'all_data'."
raise ValueError(er)
|
Returns a pandas DataFrame containing the player IDs used in the
stats.nba.com API.
Parameters
----------
ids : { "shots" | "all_players" | "all_data" }, optional
Passing in "shots" returns a DataFrame that contains the player IDs of
all players have shot chart data. It is the default parameter value.
Passing in "all_players" returns a DataFrame that contains
all the player IDs used in the stats.nba.com API.
Passing in "all_data" returns a DataFrame that contains all the data
accessed from the JSON at the following url:
http://stats.nba.com/stats/commonallplayers?IsOnlyCurrentSeason=0&LeagueID=00&Season=2015-16
The column information for this DataFrame is as follows:
PERSON_ID: The player ID for that player
DISPLAY_LAST_COMMA_FIRST: The player's name.
ROSTERSTATUS: 0 means player is not on a roster, 1 means he's on a
roster
FROM_YEAR: The first year the player played.
TO_YEAR: The last year the player played.
PLAYERCODE: A code representing the player. Unsure of its use.
Returns
-------
df : pandas DataFrame
The pandas DataFrame object that contains the player IDs for the
stats.nba.com API.
|
entailment
|
def get_player_id(player):
"""
Returns the player ID(s) associated with the player name that is passed in.
There are instances where players have the same name so there are multiple
player IDs associated with it.
Parameters
----------
player : str
The desired player's name in 'Last Name, First Name' format. Passing in
a single name returns a numpy array containing all the player IDs
associated with that name.
Returns
-------
player_id : numpy array
The numpy array that contains the player ID(s).
"""
players_df = get_all_player_ids("all_data")
player = players_df[players_df.DISPLAY_LAST_COMMA_FIRST == player]
# if there are no plyaers by the given name, raise an a error
if len(player) == 0:
er = "Invalid player name passed or there is no player with that name."
raise ValueError(er)
player_id = player.PERSON_ID.values
return player_id
|
Returns the player ID(s) associated with the player name that is passed in.
There are instances where players have the same name so there are multiple
player IDs associated with it.
Parameters
----------
player : str
The desired player's name in 'Last Name, First Name' format. Passing in
a single name returns a numpy array containing all the player IDs
associated with that name.
Returns
-------
player_id : numpy array
The numpy array that contains the player ID(s).
|
entailment
|
def get_all_team_ids():
"""Returns a pandas DataFrame with all Team IDs"""
df = get_all_player_ids("all_data")
df = pd.DataFrame({"TEAM_NAME": df.TEAM_NAME.unique(),
"TEAM_ID": df.TEAM_ID.unique()})
return df
|
Returns a pandas DataFrame with all Team IDs
|
entailment
|
def get_team_id(team_name):
""" Returns the team ID associated with the team name that is passed in.
Parameters
----------
team_name : str
The team name whose ID we want. NOTE: Only pass in the team name
(e.g. "Lakers"), not the city, or city and team name, or the team
abbreviation.
Returns
-------
team_id : int
The team ID associated with the team name.
"""
df = get_all_team_ids()
df = df[df.TEAM_NAME == team_name]
if len(df) == 0:
er = "Invalid team name or there is no team with that name."
raise ValueError(er)
team_id = df.TEAM_ID.iloc[0]
return team_id
|
Returns the team ID associated with the team name that is passed in.
Parameters
----------
team_name : str
The team name whose ID we want. NOTE: Only pass in the team name
(e.g. "Lakers"), not the city, or city and team name, or the team
abbreviation.
Returns
-------
team_id : int
The team ID associated with the team name.
|
entailment
|
def get_player_img(player_id):
"""
Returns the image of the player from stats.nba.com as a numpy array and
saves the image as PNG file in the current directory.
Parameters
----------
player_id: int
The player ID used to find the image.
Returns
-------
player_img: ndarray
The multidimensional numpy array of the player image, which matplotlib
can plot.
"""
url = "http://stats.nba.com/media/players/230x185/"+str(player_id)+".png"
img_file = str(player_id) + ".png"
pic = urlretrieve(url, img_file)
player_img = plt.imread(pic[0])
return player_img
|
Returns the image of the player from stats.nba.com as a numpy array and
saves the image as PNG file in the current directory.
Parameters
----------
player_id: int
The player ID used to find the image.
Returns
-------
player_img: ndarray
The multidimensional numpy array of the player image, which matplotlib
can plot.
|
entailment
|
def get_game_logs(self):
"""Returns team game logs as a pandas DataFrame"""
logs = self.response.json()['resultSets'][0]['rowSet']
headers = self.response.json()['resultSets'][0]['headers']
df = pd.DataFrame(logs, columns=headers)
df.GAME_DATE = pd.to_datetime(df.GAME_DATE)
return df
|
Returns team game logs as a pandas DataFrame
|
entailment
|
def get_game_id(self, date):
"""Returns the Game ID associated with the date that is passed in.
Parameters
----------
date : str
The date associated with the game whose Game ID. The date that is
passed in can take on a numeric format of MM/DD/YY (like "01/06/16"
or "01/06/2016") or the expanded Month Day, Year format (like
"Jan 06, 2016" or "January 06, 2016").
Returns
-------
game_id : str
The desired Game ID.
"""
df = self.get_game_logs()
game_id = df[df.GAME_DATE == date].Game_ID.values[0]
return game_id
|
Returns the Game ID associated with the date that is passed in.
Parameters
----------
date : str
The date associated with the game whose Game ID. The date that is
passed in can take on a numeric format of MM/DD/YY (like "01/06/16"
or "01/06/2016") or the expanded Month Day, Year format (like
"Jan 06, 2016" or "January 06, 2016").
Returns
-------
game_id : str
The desired Game ID.
|
entailment
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.