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 ex... | 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|
basical... | 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 []'
... | 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'
>>> en... | 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.... | 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
>>> stat... | 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.)
>>> stat... | 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.... | 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)
>>> state... | 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)
>... | 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(... | 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 NAME... | 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
|ConditionMa... | 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
|Condi... | 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.filet... | 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
... | 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(
... | 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.devic... | 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... | 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 on... | 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 fo... | 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.sequ... | 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
>>> c... | 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 ... | 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.... | 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 ... | 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-dime... | 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 examp... | 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.n... | 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|
... | 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 ... | 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.
F... | 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 f... | 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)
... | 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)
... | 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)
... | 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
absfh... | 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 rou... | 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_(derive... | 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)... | 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... | 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.contr... | 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.c... | 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.c... | 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.co... | 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.co... | 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)... | 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(
... ... | 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... | 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(
.... | 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, 11... | 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... | 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 ... | 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,
... | 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,
... ... | 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... | 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')
>>> str2... | 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 = col... | 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 Test... | 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
>... | 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:
... | 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 ... | 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 que... | 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 hyd... | 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.ne... | 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... | 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... | 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.... | 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.desc... | 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 ... | 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... | 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
... | 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)
... | 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._... | 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` '
... | 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 wr... | 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 s... | 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 NetCDFVariab... | 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... | 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... | 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
th... | 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
... | 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
(s... | 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 ma... | 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)
>>> ... | 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
>>> fro... | 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 = NCV... | 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.dim... | 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:
... | 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_e... | 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 = NetCDFVariabl... | 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... | 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|:
... | 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 pr... | 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 defau... | 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
defi... | 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:
... | 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_i... | 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 = ... | 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|:
... | 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 pre... | 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, und... | 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`),
... | 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
t... | 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... | 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 de... | 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
... | 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
devi... | 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.examp... | 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 i... | 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... | 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 = ... | 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.na... | 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 hou... | 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... | 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.updat... | 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.nmbsu... | 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 peri... | 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',
... | 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('.')))
... | 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', 'conditi... | 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 ... | 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, Test... | 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 | 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 ... | 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 ... | 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... | 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
... | 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
abbrevia... | 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
-------
t... | 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
... | 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 t... | 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)
... | 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"
... | 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 expa... | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.