repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
hydpy-dev/hydpy | hydpy/core/sequencetools.py | IOSequence.average_series | 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)) | python | 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)) | [
"def",
"average_series",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"InfoArray",
":",
"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.]) | [
"Average",
"the",
"actual",
"time",
"series",
"of",
"the",
"|Variable|",
"object",
"for",
"all",
"time",
"points",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1158-L1237 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | IOSequence.aggregate_series | 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))) | python | 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))) | [
"def",
"aggregate_series",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"InfoArray",
":",
"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) | [
"Aggregates",
"time",
"series",
"data",
"based",
"on",
"the",
"actual",
"|FluxSequence",
".",
"aggregation_ext|",
"attribute",
"of",
"|IOSequence|",
"subclasses",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1239-L1296 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | StateSequence.old | 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 | python | 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 | [
"def",
"old",
"(",
"self",
")",
":",
"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. | [
"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",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1523-L1538 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | Sim.load_ext | 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])) | python | 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])) | [
"def",
"load_ext",
"(",
"self",
")",
":",
"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.]) | [
"Read",
"time",
"series",
"data",
"like",
"method",
"|IOSequence",
".",
"load_ext|",
"of",
"class",
"|IOSequence|",
"but",
"with",
"special",
"handling",
"of",
"missing",
"data",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1750-L1816 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | Obs.load_ext | 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])) | python | 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])) | [
"def",
"load_ext",
"(",
"self",
")",
":",
"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 | [
"Read",
"time",
"series",
"data",
"like",
"method",
"|IOSequence",
".",
"load_ext|",
"of",
"class",
"|IOSequence|",
"but",
"with",
"special",
"handling",
"of",
"missing",
"data",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1823-L1923 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | FastAccess.open_files | 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_) | python | 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_) | [
"def",
"open_files",
"(",
"self",
",",
"idx",
")",
":",
"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. | [
"Open",
"all",
"files",
"with",
"an",
"activated",
"disk",
"flag",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1985-L1997 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | FastAccess.close_files | 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() | python | 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() | [
"def",
"close_files",
"(",
"self",
")",
":",
"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. | [
"Close",
"all",
"files",
"with",
"an",
"activated",
"disk",
"flag",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L1999-L2004 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | FastAccess.load_data | 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 | python | 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 | [
"def",
"load_data",
"(",
"self",
",",
"idx",
")",
":",
"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. | [
"Load",
"the",
"internal",
"data",
"of",
"all",
"sequences",
".",
"Load",
"from",
"file",
"if",
"the",
"corresponding",
"disk",
"flag",
"is",
"activated",
"otherwise",
"load",
"from",
"RAM",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L2006-L2034 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | FastAccess.save_data | 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 | python | 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 | [
"def",
"save_data",
"(",
"self",
",",
"idx",
")",
":",
"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. | [
"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",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L2036-L2058 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | FastAccessNode.load_simdata | 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) | python | 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) | [
"def",
"load_simdata",
"(",
"self",
",",
"idx",
":",
"int",
")",
"->",
"None",
":",
"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). | [
"Load",
"the",
"next",
"sim",
"sequence",
"value",
"(",
"of",
"the",
"given",
"index",
")",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L2100-L2106 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | FastAccessNode.save_simdata | 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) | python | 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) | [
"def",
"save_simdata",
"(",
"self",
",",
"idx",
":",
"int",
")",
"->",
"None",
":",
"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). | [
"Save",
"the",
"last",
"sim",
"sequence",
"value",
"(",
"of",
"the",
"given",
"index",
")",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L2108-L2114 | train |
hydpy-dev/hydpy | hydpy/core/sequencetools.py | FastAccessNode.load_obsdata | 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) | python | 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) | [
"def",
"load_obsdata",
"(",
"self",
",",
"idx",
":",
"int",
")",
"->",
"None",
":",
"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). | [
"Load",
"the",
"next",
"obs",
"sequence",
"value",
"(",
"of",
"the",
"given",
"index",
")",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/sequencetools.py#L2116-L2122 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | AbsFHRU.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Update",
"|AbsFHRU|",
"based",
"on",
"|FT|",
"and",
"|FHRU|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L21-L35 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | KInz.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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 | [
"Update",
"|KInz|",
"based",
"on",
"|HInz|",
"and",
"|LAI|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L43-L60 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | WB.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Update",
"|WB|",
"based",
"on",
"|RelWB|",
"and",
"|NFk|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L68-L82 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | WZ.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Update",
"|WZ|",
"based",
"on",
"|RelWZ|",
"and",
"|NFk|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L90-L104 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | KB.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Update",
"|KB|",
"based",
"on",
"|EQB|",
"and",
"|TInd|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L112-L124 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | KI1.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Update",
"|KI1|",
"based",
"on",
"|EQI1|",
"and",
"|TInd|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L132-L144 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | KI2.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Update",
"|KI2|",
"based",
"on",
"|EQI2|",
"and",
"|TInd|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L152-L164 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | KD1.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Update",
"|KD1|",
"based",
"on",
"|EQD1|",
"and",
"|TInd|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L172-L184 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | KD2.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Update",
"|KD2|",
"based",
"on",
"|EQD2|",
"and",
"|TInd|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L192-L204 | train |
hydpy-dev/hydpy | hydpy/models/lland/lland_derived.py | QFactor.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Update",
"|QFactor|",
"based",
"on",
"|FT|",
"and",
"the",
"current",
"simulation",
"step",
"size",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/lland/lland_derived.py#L211-L223 | train |
hydpy-dev/hydpy | hydpy/auxs/networktools.py | RiverBasinNumbers2Selection._router_numbers | 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()) | python | 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()) | [
"def",
"_router_numbers",
"(",
"self",
")",
":",
"return",
"tuple",
"(",
"up",
"for",
"up",
"in",
"self",
".",
"_up2down",
".",
"keys",
"(",
")",
"if",
"up",
"in",
"self",
".",
"_up2down",
".",
"values",
"(",
")",
")"
] | A tuple of the numbers of all "routing" basins. | [
"A",
"tuple",
"of",
"the",
"numbers",
"of",
"all",
"routing",
"basins",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/networktools.py#L268-L271 | train |
hydpy-dev/hydpy | hydpy/auxs/networktools.py | RiverBasinNumbers2Selection.supplier_elements | 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 | python | 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 | [
"def",
"supplier_elements",
"(",
"self",
")",
":",
"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") | [
"A",
"|Elements|",
"collection",
"of",
"all",
"supplying",
"basins",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/networktools.py#L283-L340 | train |
hydpy-dev/hydpy | hydpy/auxs/networktools.py | RiverBasinNumbers2Selection.router_elements | 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 | python | 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 | [
"def",
"router_elements",
"(",
"self",
")",
":",
"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") | [
"A",
"|Elements|",
"collection",
"of",
"all",
"routing",
"basins",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/networktools.py#L343-L394 | train |
hydpy-dev/hydpy | hydpy/auxs/networktools.py | RiverBasinNumbers2Selection.nodes | 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)) | python | 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)) | [
"def",
"nodes",
"(",
"self",
")",
":",
"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") | [
"A",
"|Nodes|",
"collection",
"of",
"all",
"required",
"nodes",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/networktools.py#L402-L427 | train |
hydpy-dev/hydpy | hydpy/auxs/networktools.py | RiverBasinNumbers2Selection.selection | 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) | python | 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) | [
"def",
"selection",
"(",
"self",
")",
":",
"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")) | [
"A",
"complete",
"|Selection|",
"object",
"of",
"all",
"supplying",
"and",
"routing",
"elements",
"and",
"required",
"nodes",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/auxs/networktools.py#L430-L460 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | str2chars | 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 | python | 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 | [
"def",
"str2chars",
"(",
"strings",
")",
"->",
"numpy",
".",
"ndarray",
":",
"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') | [
"Return",
"|numpy",
".",
"ndarray|",
"containing",
"the",
"byte",
"characters",
"(",
"second",
"axis",
")",
"of",
"all",
"given",
"strings",
"(",
"first",
"axis",
")",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L261-L284 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | chars2str | 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) | python | 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) | [
"def",
"chars2str",
"(",
"chars",
")",
"->",
"List",
"[",
"str",
"]",
":",
"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([])
[] | [
"Inversion",
"function",
"of",
"function",
"|str2chars|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L287-L308 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | create_dimension | 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))) | python | 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))) | [
"def",
"create_dimension",
"(",
"ncfile",
",",
"name",
",",
"length",
")",
"->",
"None",
":",
"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() | [
"Add",
"a",
"new",
"dimension",
"with",
"the",
"given",
"name",
"and",
"length",
"to",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L311-L343 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | create_variable | 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))) | python | 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))) | [
"def",
"create_variable",
"(",
"ncfile",
",",
"name",
",",
"datatype",
",",
"dimensions",
")",
"->",
"None",
":",
"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() | [
"Add",
"a",
"new",
"variable",
"with",
"the",
"given",
"name",
"datatype",
"and",
"dimensions",
"to",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L346-L384 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | query_variable | 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)) | python | 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)) | [
"def",
"query_variable",
"(",
"ncfile",
",",
"name",
")",
"->",
"netcdf4",
".",
"Variable",
":",
"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() | [
"Return",
"the",
"variable",
"with",
"the",
"given",
"name",
"from",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L387-L415 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | query_timegrid | 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]) | python | 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]) | [
"def",
"query_timegrid",
"(",
"ncfile",
")",
"->",
"timetools",
".",
"Timegrid",
":",
"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') | [
"Return",
"the",
"|Timegrid|",
"defined",
"by",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L418-L439 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | query_array | 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 | python | 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 | [
"def",
"query_array",
"(",
"ncfile",
",",
"name",
")",
"->",
"numpy",
".",
"ndarray",
":",
"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 | [
"Return",
"the",
"data",
"of",
"the",
"variable",
"with",
"the",
"given",
"name",
"from",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L442-L471 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFInterface.log | 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) | python | 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) | [
"def",
"log",
"(",
"self",
",",
"sequence",
",",
"infoarray",
")",
"->",
"None",
":",
"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. | [
"Prepare",
"a",
"|NetCDFFile|",
"object",
"suitable",
"for",
"the",
"given",
"|IOSequence|",
"object",
"when",
"necessary",
"and",
"pass",
"the",
"given",
"arguments",
"to",
"its",
"|NetCDFFile",
".",
"log|",
"method",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L662-L691 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFInterface.read | 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() | python | 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() | [
"def",
"read",
"(",
"self",
")",
"->",
"None",
":",
"for",
"folder",
"in",
"self",
".",
"folders",
".",
"values",
"(",
")",
":",
"for",
"file_",
"in",
"folder",
".",
"values",
"(",
")",
":",
"file_",
".",
"read",
"(",
")"
] | Call method |NetCDFFile.read| of all handled |NetCDFFile| objects. | [
"Call",
"method",
"|NetCDFFile",
".",
"read|",
"of",
"all",
"handled",
"|NetCDFFile|",
"objects",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L693-L698 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFInterface.write | 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) | python | 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) | [
"def",
"write",
"(",
"self",
")",
"->",
"None",
":",
"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. | [
"Call",
"method",
"|NetCDFFile",
".",
"write|",
"of",
"all",
"handled",
"|NetCDFFile|",
"objects",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L700-L709 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFInterface.filenames | 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()))))) | python | 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()))))) | [
"def",
"filenames",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"return",
"tuple",
"(",
"sorted",
"(",
"set",
"(",
"itertools",
".",
"chain",
"(",
"*",
"(",
"_",
".",
"keys",
"(",
")",
"for",
"_",
"in",
"self",
".",
"folders",
".",
"values",
"(",
")",
")",
")",
")",
")",
")"
] | A |tuple| of names of all handled |NetCDFFile| objects. | [
"A",
"|tuple|",
"of",
"names",
"of",
"all",
"handled",
"|NetCDFFile|",
"objects",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L718-L721 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFFile.log | 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) | python | 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) | [
"def",
"log",
"(",
"self",
",",
"sequence",
",",
"infoarray",
")",
"->",
"None",
":",
"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) | [
"Pass",
"the",
"given",
"|IoSequence|",
"to",
"a",
"suitable",
"instance",
"of",
"a",
"|NetCDFVariableBase|",
"subclass",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L845-L970 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFFile.filepath | def filepath(self) -> str:
"""The NetCDF file path."""
return os.path.join(self._dirpath, self.name + '.nc') | python | def filepath(self) -> str:
"""The NetCDF file path."""
return os.path.join(self._dirpath, self.name + '.nc') | [
"def",
"filepath",
"(",
"self",
")",
"->",
"str",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_dirpath",
",",
"self",
".",
"name",
"+",
"'.nc'",
")"
] | The NetCDF file path. | [
"The",
"NetCDF",
"file",
"path",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L973-L975 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFFile.read | 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}`') | python | 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}`') | [
"def",
"read",
"(",
"self",
")",
"->",
"None",
":",
"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. | [
"Open",
"an",
"existing",
"NetCDF",
"file",
"temporarily",
"and",
"call",
"method",
"|NetCDFVariableDeep",
".",
"read|",
"of",
"all",
"handled",
"|NetCDFVariableBase|",
"objects",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L977-L988 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFFile.write | 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) | python | 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) | [
"def",
"write",
"(",
"self",
",",
"timeunit",
",",
"timepoints",
")",
"->",
"None",
":",
"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. | [
"Open",
"a",
"new",
"NetCDF",
"file",
"temporarily",
"and",
"call",
"method",
"|NetCDFVariableBase",
".",
"write|",
"of",
"all",
"handled",
"|NetCDFVariableBase|",
"objects",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L990-L998 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | Subdevice2Index.get_index | 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)) | python | 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)) | [
"def",
"get_index",
"(",
"self",
",",
"name_subdevice",
")",
"->",
"int",
":",
"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. | [
"Item",
"access",
"to",
"the",
"wrapped",
"|dict|",
"object",
"with",
"a",
"specialized",
"error",
"message",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1046-L1057 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableBase.log | 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 | python | 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 | [
"def",
"log",
"(",
"self",
",",
"sequence",
",",
"infoarray",
")",
"->",
"None",
":",
"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`. | [
"Log",
"the",
"given",
"|IOSequence|",
"object",
"either",
"for",
"reading",
"or",
"writing",
"data",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1096-L1130 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableBase.insert_subdevices | 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 | python | 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 | [
"def",
"insert_subdevices",
"(",
"self",
",",
"ncfile",
")",
"->",
"None",
":",
"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() | [
"Insert",
"a",
"variable",
"of",
"the",
"names",
"of",
"the",
"(",
"sub",
")",
"devices",
"of",
"the",
"logged",
"sequences",
"into",
"the",
"given",
"NetCDF",
"file"
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1168-L1223 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableBase.query_subdevices | 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) | python | 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) | [
"def",
"query_subdevices",
"(",
"self",
",",
"ncfile",
")",
"->",
"List",
"[",
"str",
"]",
":",
"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() | [
"Query",
"the",
"names",
"of",
"the",
"(",
"sub",
")",
"devices",
"of",
"the",
"logged",
"sequences",
"from",
"the",
"given",
"NetCDF",
"file"
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1225-L1274 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableBase.query_subdevice2index | 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)) | python | 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)) | [
"def",
"query_subdevice2index",
"(",
"self",
",",
"ncfile",
")",
"->",
"Subdevice2Index",
":",
"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() | [
"Return",
"a",
"|Subdevice2Index|",
"that",
"maps",
"the",
"(",
"sub",
")",
"device",
"names",
"to",
"their",
"position",
"within",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1276-L1322 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableBase.sort_timeplaceentries | 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 | python | 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 | [
"def",
"sort_timeplaceentries",
"(",
"self",
",",
"timeentry",
",",
"placeentry",
")",
"->",
"Tuple",
"[",
"Any",
",",
"Any",
"]",
":",
"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') | [
"Return",
"a",
"|tuple|",
"containing",
"the",
"given",
"timeentry",
"and",
"placeentry",
"sorted",
"in",
"agreement",
"with",
"the",
"currently",
"selected",
"timeaxis",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1335-L1351 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableBase.get_timeplaceslice | 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)) | python | 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)) | [
"def",
"get_timeplaceslice",
"(",
"self",
",",
"placeindex",
")",
"->",
"Union",
"[",
"Tuple",
"[",
"slice",
",",
"int",
"]",
",",
"Tuple",
"[",
"int",
",",
"slice",
"]",
"]",
":",
"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) | [
"Return",
"a",
"|tuple|",
"for",
"indexing",
"a",
"complete",
"time",
"series",
"of",
"a",
"certain",
"location",
"available",
"in",
"|NetCDFVariableBase",
".",
"array|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1353-L1368 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | DeepAndAggMixin.subdevicenames | def subdevicenames(self) -> Tuple[str, ...]:
"""A |tuple| containing the device names."""
self: NetCDFVariableBase
return tuple(self.sequences.keys()) | python | def subdevicenames(self) -> Tuple[str, ...]:
"""A |tuple| containing the device names."""
self: NetCDFVariableBase
return tuple(self.sequences.keys()) | [
"def",
"subdevicenames",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"self",
":",
"NetCDFVariableBase",
"return",
"tuple",
"(",
"self",
".",
"sequences",
".",
"keys",
"(",
")",
")"
] | A |tuple| containing the device names. | [
"A",
"|tuple|",
"containing",
"the",
"device",
"names",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1396-L1399 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | DeepAndAggMixin.write | 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 | python | 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 | [
"def",
"write",
"(",
"self",
",",
"ncfile",
")",
"->",
"None",
":",
"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. | [
"Write",
"the",
"data",
"to",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1401-L1414 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | AggAndFlatMixin.dimensions | 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'])) | python | 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'])) | [
"def",
"dimensions",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"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') | [
"The",
"dimension",
"names",
"of",
"the",
"NetCDF",
"variable",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1421-L1455 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableDeep.get_slices | 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) | python | 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) | [
"def",
"get_slices",
"(",
"self",
",",
"idx",
",",
"shape",
")",
"->",
"Tuple",
"[",
"IntOrSlice",
",",
"...",
"]",
":",
"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)) | [
"Return",
"a",
"|tuple|",
"of",
"one",
"|int|",
"and",
"some",
"|slice|",
"objects",
"to",
"accesses",
"all",
"values",
"of",
"a",
"certain",
"device",
"within",
"|NetCDFVariableDeep",
".",
"array|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1584-L1602 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableDeep.shape | 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 | python | 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 | [
"def",
"shape",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"...",
"]",
":",
"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) | [
"Required",
"shape",
"of",
"|NetCDFVariableDeep",
".",
"array|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1605-L1649 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableDeep.array | 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 | python | 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 | [
"def",
"array",
"(",
"self",
")",
"->",
"numpy",
".",
"ndarray",
":",
"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]]) | [
"The",
"series",
"data",
"of",
"all",
"logged",
"|IOSequence|",
"objects",
"contained",
"in",
"one",
"single",
"|numpy",
".",
"ndarray|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1652-L1705 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableDeep.dimensions | 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) | python | 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) | [
"def",
"dimensions",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"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') | [
"The",
"dimension",
"names",
"of",
"the",
"NetCDF",
"variable",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1708-L1745 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableDeep.read | 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) | python | 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) | [
"def",
"read",
"(",
"self",
",",
"ncfile",
",",
"timegrid_data",
")",
"->",
"None",
":",
"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. | [
"Read",
"the",
"data",
"from",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1747-L1762 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableAgg.shape | 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)) | python | 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)) | [
"def",
"shape",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"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) | [
"Required",
"shape",
"of",
"|NetCDFVariableAgg",
".",
"array|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1824-L1850 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableAgg.array | 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 | python | 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 | [
"def",
"array",
"(",
"self",
")",
"->",
"numpy",
".",
"ndarray",
":",
"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. ]]) | [
"The",
"aggregated",
"data",
"of",
"all",
"logged",
"|IOSequence|",
"objects",
"contained",
"in",
"one",
"single",
"|numpy",
".",
"ndarray|",
"object",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1853-L1891 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableFlat.shape | 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())) | python | 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())) | [
"def",
"shape",
"(",
"self",
")",
"->",
"Tuple",
"[",
"int",
",",
"int",
"]",
":",
"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) | [
"Required",
"shape",
"of",
"|NetCDFVariableFlat",
".",
"array|",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L1979-L2019 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableFlat.array | 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 | python | 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 | [
"def",
"array",
"(",
"self",
")",
"->",
"numpy",
".",
"ndarray",
":",
"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.]]) | [
"The",
"series",
"data",
"of",
"all",
"logged",
"|IOSequence|",
"objects",
"contained",
"in",
"one",
"single",
"|numpy",
".",
"ndarray|",
"object",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L2022-L2081 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableFlat.subdevicenames | 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) | python | 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) | [
"def",
"subdevicenames",
"(",
"self",
")",
"->",
"Tuple",
"[",
"str",
",",
"...",
"]",
":",
"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') | [
"A",
"|tuple|",
"containing",
"the",
"(",
"sub",
")",
"device",
"names",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L2084-L2123 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableFlat._product | 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)) | python | 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)) | [
"def",
"_product",
"(",
"shape",
")",
"->",
"Iterator",
"[",
"Tuple",
"[",
"int",
",",
"...",
"]",
"]",
":",
"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) | [
"Should",
"return",
"all",
"subdevice",
"index",
"combinations",
"for",
"sequences",
"with",
"arbitrary",
"dimensions",
":"
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L2126-L2141 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableFlat.read | 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) | python | 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) | [
"def",
"read",
"(",
"self",
",",
"ncfile",
",",
"timegrid_data",
")",
"->",
"None",
":",
"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. | [
"Read",
"the",
"data",
"from",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L2143-L2170 | train |
hydpy-dev/hydpy | hydpy/core/netcdftools.py | NetCDFVariableFlat.write | 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 | python | 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 | [
"def",
"write",
"(",
"self",
",",
"ncfile",
")",
"->",
"None",
":",
"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. | [
"Write",
"the",
"data",
"to",
"the",
"given",
"NetCDF",
"file",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/netcdftools.py#L2172-L2180 | train |
hydpy-dev/hydpy | hydpy/models/llake/llake_derived.py | NmbSubsteps.update | 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) | python | 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) | [
"def",
"update",
"(",
"self",
")",
":",
"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) | [
"Determine",
"the",
"number",
"of",
"substeps",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/llake/llake_derived.py#L25-L67 | train |
hydpy-dev/hydpy | hydpy/models/llake/llake_derived.py | VQ.update | 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() | python | 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() | [
"def",
"update",
"(",
"self",
")",
":",
"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]) | [
"Calulate",
"the",
"auxilary",
"term",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/models/llake/llake_derived.py#L74-L95 | train |
hydpy-dev/hydpy | hydpy/core/examples.py | prepare_io_example_1 | 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 | python | 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 | [
"def",
"prepare_io_example_1",
"(",
")",
"->",
"Tuple",
"[",
"devicetools",
".",
"Nodes",
",",
"devicetools",
".",
"Elements",
"]",
":",
"# noinspection PyUnresolvedReferences",
"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) | [
"Prepare",
"an",
"IO",
"example",
"configuration",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/examples.py#L17-L156 | train |
hydpy-dev/hydpy | hydpy/core/examples.py | prepare_full_example_1 | 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)) | python | 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)) | [
"def",
"prepare_full_example_1",
"(",
")",
"->",
"None",
":",
"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. | [
"Prepare",
"the",
"complete",
"LahnH",
"project",
"for",
"testing",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/examples.py#L159-L184 | train |
hydpy-dev/hydpy | hydpy/core/examples.py | prepare_full_example_2 | 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 | python | 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 | [
"def",
"prepare_full_example_2",
"(",
"lastdate",
"=",
"'1996-01-05'",
")",
"->",
"(",
"hydpytools",
".",
"HydPy",
",",
"hydpy",
".",
"pub",
",",
"testtools",
".",
"TestIO",
")",
":",
"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')) | [
"Prepare",
"the",
"complete",
"LahnH",
"project",
"for",
"testing",
"."
] | 1bc6a82cf30786521d86b36e27900c6717d3348d | https://github.com/hydpy-dev/hydpy/blob/1bc6a82cf30786521d86b36e27900c6717d3348d/hydpy/core/examples.py#L187-L224 | train |
inkjet/pypostalcode | pypostalcode/__init__.py | PostalCodeDatabase.get_postalcodes_around_radius | 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]
))) | python | 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]
))) | [
"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",
")",
"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 | [
"Bounding",
"box",
"calculations",
"updated",
"from",
"pyzipcode"
] | 077c0085a57c2d24a0bb2596af56d701091fb9f4 | https://github.com/inkjet/pypostalcode/blob/077c0085a57c2d24a0bb2596af56d701091fb9f4/pypostalcode/__init__.py#L71-L99 | train |
savvastj/nbashots | nbashots/api.py | get_all_player_ids | 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) | python | 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) | [
"def",
"get_all_player_ids",
"(",
"ids",
"=",
"\"shots\"",
")",
":",
"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. | [
"Returns",
"a",
"pandas",
"DataFrame",
"containing",
"the",
"player",
"IDs",
"used",
"in",
"the",
"stats",
".",
"nba",
".",
"com",
"API",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L251-L320 | train |
savvastj/nbashots | nbashots/api.py | get_player_id | 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 | python | 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 | [
"def",
"get_player_id",
"(",
"player",
")",
":",
"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). | [
"Returns",
"the",
"player",
"ID",
"(",
"s",
")",
"associated",
"with",
"the",
"player",
"name",
"that",
"is",
"passed",
"in",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L323-L350 | train |
savvastj/nbashots | nbashots/api.py | get_all_team_ids | 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 | python | 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 | [
"def",
"get_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 | [
"Returns",
"a",
"pandas",
"DataFrame",
"with",
"all",
"Team",
"IDs"
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L353-L358 | train |
savvastj/nbashots | nbashots/api.py | get_team_id | 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 | python | 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 | [
"def",
"get_team_id",
"(",
"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. | [
"Returns",
"the",
"team",
"ID",
"associated",
"with",
"the",
"team",
"name",
"that",
"is",
"passed",
"in",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L361-L383 | train |
savvastj/nbashots | nbashots/api.py | get_player_img | 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 | python | 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 | [
"def",
"get_player_img",
"(",
"player_id",
")",
":",
"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. | [
"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",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L386-L406 | train |
savvastj/nbashots | nbashots/api.py | TeamLog.get_game_logs | 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 | python | 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 | [
"def",
"get_game_logs",
"(",
"self",
")",
":",
"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 | [
"Returns",
"team",
"game",
"logs",
"as",
"a",
"pandas",
"DataFrame"
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L36-L42 | train |
savvastj/nbashots | nbashots/api.py | TeamLog.get_game_id | 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 | python | 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 | [
"def",
"get_game_id",
"(",
"self",
",",
"date",
")",
":",
"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. | [
"Returns",
"the",
"Game",
"ID",
"associated",
"with",
"the",
"date",
"that",
"is",
"passed",
"in",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L44-L62 | train |
savvastj/nbashots | nbashots/api.py | TeamLog.update_params | def update_params(self, parameters):
"""Pass in a dictionary to update url parameters for NBA stats API
Parameters
----------
parameters : dict
A dict containing key, value pairs that correspond with NBA stats
API parameters.
Returns
-------
self : TeamLog
The TeamLog object containing the updated NBA stats API
parameters.
"""
self.url_paramaters.update(parameters)
self.response = requests.get(self.base_url, params=self.url_paramaters,
headers=HEADERS)
# raise error if status code is not 200
self.response.raise_for_status()
return self | python | def update_params(self, parameters):
"""Pass in a dictionary to update url parameters for NBA stats API
Parameters
----------
parameters : dict
A dict containing key, value pairs that correspond with NBA stats
API parameters.
Returns
-------
self : TeamLog
The TeamLog object containing the updated NBA stats API
parameters.
"""
self.url_paramaters.update(parameters)
self.response = requests.get(self.base_url, params=self.url_paramaters,
headers=HEADERS)
# raise error if status code is not 200
self.response.raise_for_status()
return self | [
"def",
"update_params",
"(",
"self",
",",
"parameters",
")",
":",
"self",
".",
"url_paramaters",
".",
"update",
"(",
"parameters",
")",
"self",
".",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base_url",
",",
"params",
"=",
"self",
".",
"url_paramaters",
",",
"headers",
"=",
"HEADERS",
")",
"# raise error if status code is not 200",
"self",
".",
"response",
".",
"raise_for_status",
"(",
")",
"return",
"self"
] | Pass in a dictionary to update url parameters for NBA stats API
Parameters
----------
parameters : dict
A dict containing key, value pairs that correspond with NBA stats
API parameters.
Returns
-------
self : TeamLog
The TeamLog object containing the updated NBA stats API
parameters. | [
"Pass",
"in",
"a",
"dictionary",
"to",
"update",
"url",
"parameters",
"for",
"NBA",
"stats",
"API"
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L64-L84 | train |
savvastj/nbashots | nbashots/api.py | Shots.get_shots | def get_shots(self):
"""Returns the shot chart data as a pandas DataFrame."""
shots = self.response.json()['resultSets'][0]['rowSet']
headers = self.response.json()['resultSets'][0]['headers']
return pd.DataFrame(shots, columns=headers) | python | def get_shots(self):
"""Returns the shot chart data as a pandas DataFrame."""
shots = self.response.json()['resultSets'][0]['rowSet']
headers = self.response.json()['resultSets'][0]['headers']
return pd.DataFrame(shots, columns=headers) | [
"def",
"get_shots",
"(",
"self",
")",
":",
"shots",
"=",
"self",
".",
"response",
".",
"json",
"(",
")",
"[",
"'resultSets'",
"]",
"[",
"0",
"]",
"[",
"'rowSet'",
"]",
"headers",
"=",
"self",
".",
"response",
".",
"json",
"(",
")",
"[",
"'resultSets'",
"]",
"[",
"0",
"]",
"[",
"'headers'",
"]",
"return",
"pd",
".",
"DataFrame",
"(",
"shots",
",",
"columns",
"=",
"headers",
")"
] | Returns the shot chart data as a pandas DataFrame. | [
"Returns",
"the",
"shot",
"chart",
"data",
"as",
"a",
"pandas",
"DataFrame",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/api.py#L218-L222 | train |
mcuadros/pynats | pynats/connection.py | Connection.connect | def connect(self):
"""
Connect will attempt to connect to the NATS server. The url can
contain username/password semantics.
"""
self._build_socket()
self._connect_socket()
self._build_file_socket()
self._send_connect_msg() | python | def connect(self):
"""
Connect will attempt to connect to the NATS server. The url can
contain username/password semantics.
"""
self._build_socket()
self._connect_socket()
self._build_file_socket()
self._send_connect_msg() | [
"def",
"connect",
"(",
"self",
")",
":",
"self",
".",
"_build_socket",
"(",
")",
"self",
".",
"_connect_socket",
"(",
")",
"self",
".",
"_build_file_socket",
"(",
")",
"self",
".",
"_send_connect_msg",
"(",
")"
] | Connect will attempt to connect to the NATS server. The url can
contain username/password semantics. | [
"Connect",
"will",
"attempt",
"to",
"connect",
"to",
"the",
"NATS",
"server",
".",
"The",
"url",
"can",
"contain",
"username",
"/",
"password",
"semantics",
"."
] | afbf0766c5546f9b8e7b54ddc89abd2602883b6c | https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L45-L53 | train |
mcuadros/pynats | pynats/connection.py | Connection.subscribe | def subscribe(self, subject, callback, queue=''):
"""
Subscribe will express interest in the given subject. The subject can
have wildcards (partial:*, full:>). Messages will be delivered to the
associated callback.
Args:
subject (string): a string with the subject
callback (function): callback to be called
"""
s = Subscription(
sid=self._next_sid,
subject=subject,
queue=queue,
callback=callback,
connetion=self
)
self._subscriptions[s.sid] = s
self._send('SUB %s %s %d' % (s.subject, s.queue, s.sid))
self._next_sid += 1
return s | python | def subscribe(self, subject, callback, queue=''):
"""
Subscribe will express interest in the given subject. The subject can
have wildcards (partial:*, full:>). Messages will be delivered to the
associated callback.
Args:
subject (string): a string with the subject
callback (function): callback to be called
"""
s = Subscription(
sid=self._next_sid,
subject=subject,
queue=queue,
callback=callback,
connetion=self
)
self._subscriptions[s.sid] = s
self._send('SUB %s %s %d' % (s.subject, s.queue, s.sid))
self._next_sid += 1
return s | [
"def",
"subscribe",
"(",
"self",
",",
"subject",
",",
"callback",
",",
"queue",
"=",
"''",
")",
":",
"s",
"=",
"Subscription",
"(",
"sid",
"=",
"self",
".",
"_next_sid",
",",
"subject",
"=",
"subject",
",",
"queue",
"=",
"queue",
",",
"callback",
"=",
"callback",
",",
"connetion",
"=",
"self",
")",
"self",
".",
"_subscriptions",
"[",
"s",
".",
"sid",
"]",
"=",
"s",
"self",
".",
"_send",
"(",
"'SUB %s %s %d'",
"%",
"(",
"s",
".",
"subject",
",",
"s",
".",
"queue",
",",
"s",
".",
"sid",
")",
")",
"self",
".",
"_next_sid",
"+=",
"1",
"return",
"s"
] | Subscribe will express interest in the given subject. The subject can
have wildcards (partial:*, full:>). Messages will be delivered to the
associated callback.
Args:
subject (string): a string with the subject
callback (function): callback to be called | [
"Subscribe",
"will",
"express",
"interest",
"in",
"the",
"given",
"subject",
".",
"The",
"subject",
"can",
"have",
"wildcards",
"(",
"partial",
":",
"*",
"full",
":",
">",
")",
".",
"Messages",
"will",
"be",
"delivered",
"to",
"the",
"associated",
"callback",
"."
] | afbf0766c5546f9b8e7b54ddc89abd2602883b6c | https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L93-L115 | train |
mcuadros/pynats | pynats/connection.py | Connection.unsubscribe | def unsubscribe(self, subscription, max=None):
"""
Unsubscribe will remove interest in the given subject. If max is
provided an automatic Unsubscribe that is processed by the server
when max messages have been received
Args:
subscription (pynats.Subscription): a Subscription object
max (int=None): number of messages
"""
if max is None:
self._send('UNSUB %d' % subscription.sid)
self._subscriptions.pop(subscription.sid)
else:
subscription.max = max
self._send('UNSUB %d %s' % (subscription.sid, max)) | python | def unsubscribe(self, subscription, max=None):
"""
Unsubscribe will remove interest in the given subject. If max is
provided an automatic Unsubscribe that is processed by the server
when max messages have been received
Args:
subscription (pynats.Subscription): a Subscription object
max (int=None): number of messages
"""
if max is None:
self._send('UNSUB %d' % subscription.sid)
self._subscriptions.pop(subscription.sid)
else:
subscription.max = max
self._send('UNSUB %d %s' % (subscription.sid, max)) | [
"def",
"unsubscribe",
"(",
"self",
",",
"subscription",
",",
"max",
"=",
"None",
")",
":",
"if",
"max",
"is",
"None",
":",
"self",
".",
"_send",
"(",
"'UNSUB %d'",
"%",
"subscription",
".",
"sid",
")",
"self",
".",
"_subscriptions",
".",
"pop",
"(",
"subscription",
".",
"sid",
")",
"else",
":",
"subscription",
".",
"max",
"=",
"max",
"self",
".",
"_send",
"(",
"'UNSUB %d %s'",
"%",
"(",
"subscription",
".",
"sid",
",",
"max",
")",
")"
] | Unsubscribe will remove interest in the given subject. If max is
provided an automatic Unsubscribe that is processed by the server
when max messages have been received
Args:
subscription (pynats.Subscription): a Subscription object
max (int=None): number of messages | [
"Unsubscribe",
"will",
"remove",
"interest",
"in",
"the",
"given",
"subject",
".",
"If",
"max",
"is",
"provided",
"an",
"automatic",
"Unsubscribe",
"that",
"is",
"processed",
"by",
"the",
"server",
"when",
"max",
"messages",
"have",
"been",
"received"
] | afbf0766c5546f9b8e7b54ddc89abd2602883b6c | https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L117-L132 | train |
mcuadros/pynats | pynats/connection.py | Connection.publish | def publish(self, subject, msg, reply=None):
"""
Publish publishes the data argument to the given subject.
Args:
subject (string): a string with the subject
msg (string): payload string
reply (string): subject used in the reply
"""
if msg is None:
msg = ''
if reply is None:
command = 'PUB %s %d' % (subject, len(msg))
else:
command = 'PUB %s %s %d' % (subject, reply, len(msg))
self._send(command)
self._send(msg) | python | def publish(self, subject, msg, reply=None):
"""
Publish publishes the data argument to the given subject.
Args:
subject (string): a string with the subject
msg (string): payload string
reply (string): subject used in the reply
"""
if msg is None:
msg = ''
if reply is None:
command = 'PUB %s %d' % (subject, len(msg))
else:
command = 'PUB %s %s %d' % (subject, reply, len(msg))
self._send(command)
self._send(msg) | [
"def",
"publish",
"(",
"self",
",",
"subject",
",",
"msg",
",",
"reply",
"=",
"None",
")",
":",
"if",
"msg",
"is",
"None",
":",
"msg",
"=",
"''",
"if",
"reply",
"is",
"None",
":",
"command",
"=",
"'PUB %s %d'",
"%",
"(",
"subject",
",",
"len",
"(",
"msg",
")",
")",
"else",
":",
"command",
"=",
"'PUB %s %s %d'",
"%",
"(",
"subject",
",",
"reply",
",",
"len",
"(",
"msg",
")",
")",
"self",
".",
"_send",
"(",
"command",
")",
"self",
".",
"_send",
"(",
"msg",
")"
] | Publish publishes the data argument to the given subject.
Args:
subject (string): a string with the subject
msg (string): payload string
reply (string): subject used in the reply | [
"Publish",
"publishes",
"the",
"data",
"argument",
"to",
"the",
"given",
"subject",
"."
] | afbf0766c5546f9b8e7b54ddc89abd2602883b6c | https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L134-L152 | train |
mcuadros/pynats | pynats/connection.py | Connection.request | def request(self, subject, callback, msg=None):
"""
ublish a message with an implicit inbox listener as the reply.
Message is optional.
Args:
subject (string): a string with the subject
callback (function): callback to be called
msg (string=None): payload string
"""
inbox = self._build_inbox()
s = self.subscribe(inbox, callback)
self.unsubscribe(s, 1)
self.publish(subject, msg, inbox)
return s | python | def request(self, subject, callback, msg=None):
"""
ublish a message with an implicit inbox listener as the reply.
Message is optional.
Args:
subject (string): a string with the subject
callback (function): callback to be called
msg (string=None): payload string
"""
inbox = self._build_inbox()
s = self.subscribe(inbox, callback)
self.unsubscribe(s, 1)
self.publish(subject, msg, inbox)
return s | [
"def",
"request",
"(",
"self",
",",
"subject",
",",
"callback",
",",
"msg",
"=",
"None",
")",
":",
"inbox",
"=",
"self",
".",
"_build_inbox",
"(",
")",
"s",
"=",
"self",
".",
"subscribe",
"(",
"inbox",
",",
"callback",
")",
"self",
".",
"unsubscribe",
"(",
"s",
",",
"1",
")",
"self",
".",
"publish",
"(",
"subject",
",",
"msg",
",",
"inbox",
")",
"return",
"s"
] | ublish a message with an implicit inbox listener as the reply.
Message is optional.
Args:
subject (string): a string with the subject
callback (function): callback to be called
msg (string=None): payload string | [
"ublish",
"a",
"message",
"with",
"an",
"implicit",
"inbox",
"listener",
"as",
"the",
"reply",
".",
"Message",
"is",
"optional",
"."
] | afbf0766c5546f9b8e7b54ddc89abd2602883b6c | https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L154-L169 | train |
mcuadros/pynats | pynats/connection.py | Connection.wait | def wait(self, duration=None, count=0):
"""
Publish publishes the data argument to the given subject.
Args:
duration (float): will wait for the given number of seconds
count (count): stop of wait after n messages from any subject
"""
start = time.time()
total = 0
while True:
type, result = self._recv(MSG, PING, OK)
if type is MSG:
total += 1
if self._handle_msg(result) is False:
break
if count and total >= count:
break
elif type is PING:
self._handle_ping()
if duration and time.time() - start > duration:
break | python | def wait(self, duration=None, count=0):
"""
Publish publishes the data argument to the given subject.
Args:
duration (float): will wait for the given number of seconds
count (count): stop of wait after n messages from any subject
"""
start = time.time()
total = 0
while True:
type, result = self._recv(MSG, PING, OK)
if type is MSG:
total += 1
if self._handle_msg(result) is False:
break
if count and total >= count:
break
elif type is PING:
self._handle_ping()
if duration and time.time() - start > duration:
break | [
"def",
"wait",
"(",
"self",
",",
"duration",
"=",
"None",
",",
"count",
"=",
"0",
")",
":",
"start",
"=",
"time",
".",
"time",
"(",
")",
"total",
"=",
"0",
"while",
"True",
":",
"type",
",",
"result",
"=",
"self",
".",
"_recv",
"(",
"MSG",
",",
"PING",
",",
"OK",
")",
"if",
"type",
"is",
"MSG",
":",
"total",
"+=",
"1",
"if",
"self",
".",
"_handle_msg",
"(",
"result",
")",
"is",
"False",
":",
"break",
"if",
"count",
"and",
"total",
">=",
"count",
":",
"break",
"elif",
"type",
"is",
"PING",
":",
"self",
".",
"_handle_ping",
"(",
")",
"if",
"duration",
"and",
"time",
".",
"time",
"(",
")",
"-",
"start",
">",
"duration",
":",
"break"
] | Publish publishes the data argument to the given subject.
Args:
duration (float): will wait for the given number of seconds
count (count): stop of wait after n messages from any subject | [
"Publish",
"publishes",
"the",
"data",
"argument",
"to",
"the",
"given",
"subject",
"."
] | afbf0766c5546f9b8e7b54ddc89abd2602883b6c | https://github.com/mcuadros/pynats/blob/afbf0766c5546f9b8e7b54ddc89abd2602883b6c/pynats/connection.py#L175-L199 | train |
savvastj/nbashots | nbashots/charts.py | draw_court | def draw_court(ax=None, color='gray', lw=1, outer_lines=False):
"""Returns an axes with a basketball court drawn onto to it.
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0,0) coordinate. Twenty-two feet from the left of
the center of the hoop in is represented by the (-220,0) coordinates.
So one foot equals +/-10 units on the x and y-axis.
Parameters
----------
ax : Axes, optional
The Axes object to plot the court onto.
color : matplotlib color, optional
The color of the court lines.
lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If `True` it draws the out of bound lines in same style as the rest of
the court.
Returns
-------
ax : Axes
The Axes object with the court on it.
"""
if ax is None:
ax = plt.gca()
# Create the various parts of an NBA basketball court
# Create the basketball hoop
hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False)
# Create backboard
backboard = Rectangle((-30, -12.5), 60, 0, linewidth=lw, color=color)
# The paint
# Create the outer box 0f the paint, width=16ft, height=19ft
outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color,
fill=False)
# Create the inner box of the paint, widt=12ft, height=19ft
inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color,
fill=False)
# Create free throw top arc
top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180,
linewidth=lw, color=color, fill=False)
# Create free throw bottom arc
bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0,
linewidth=lw, color=color, linestyle='dashed')
# Restricted Zone, it is an arc with 4ft radius from center of the hoop
restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw,
color=color)
# Three point line
# Create the right side 3pt lines, it's 14ft long before it arcs
corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=lw,
color=color)
# Create the right side 3pt lines, it's 14ft long before it arcs
corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=lw, color=color)
# 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop
three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw,
color=color)
# Center Court
center_outer_arc = Arc((0, 422.5), 120, 120, theta1=180, theta2=0,
linewidth=lw, color=color)
center_inner_arc = Arc((0, 422.5), 40, 40, theta1=180, theta2=0,
linewidth=lw, color=color)
# List of the court elements to be plotted onto the axes
court_elements = [hoop, backboard, outer_box, inner_box, top_free_throw,
bottom_free_throw, restricted, corner_three_a,
corner_three_b, three_arc, center_outer_arc,
center_inner_arc]
if outer_lines:
# Draw the half court line, baseline and side out bound lines
outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw,
color=color, fill=False)
court_elements.append(outer_lines)
# Add the court elements onto the axes
for element in court_elements:
ax.add_patch(element)
return ax | python | def draw_court(ax=None, color='gray', lw=1, outer_lines=False):
"""Returns an axes with a basketball court drawn onto to it.
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0,0) coordinate. Twenty-two feet from the left of
the center of the hoop in is represented by the (-220,0) coordinates.
So one foot equals +/-10 units on the x and y-axis.
Parameters
----------
ax : Axes, optional
The Axes object to plot the court onto.
color : matplotlib color, optional
The color of the court lines.
lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If `True` it draws the out of bound lines in same style as the rest of
the court.
Returns
-------
ax : Axes
The Axes object with the court on it.
"""
if ax is None:
ax = plt.gca()
# Create the various parts of an NBA basketball court
# Create the basketball hoop
hoop = Circle((0, 0), radius=7.5, linewidth=lw, color=color, fill=False)
# Create backboard
backboard = Rectangle((-30, -12.5), 60, 0, linewidth=lw, color=color)
# The paint
# Create the outer box 0f the paint, width=16ft, height=19ft
outer_box = Rectangle((-80, -47.5), 160, 190, linewidth=lw, color=color,
fill=False)
# Create the inner box of the paint, widt=12ft, height=19ft
inner_box = Rectangle((-60, -47.5), 120, 190, linewidth=lw, color=color,
fill=False)
# Create free throw top arc
top_free_throw = Arc((0, 142.5), 120, 120, theta1=0, theta2=180,
linewidth=lw, color=color, fill=False)
# Create free throw bottom arc
bottom_free_throw = Arc((0, 142.5), 120, 120, theta1=180, theta2=0,
linewidth=lw, color=color, linestyle='dashed')
# Restricted Zone, it is an arc with 4ft radius from center of the hoop
restricted = Arc((0, 0), 80, 80, theta1=0, theta2=180, linewidth=lw,
color=color)
# Three point line
# Create the right side 3pt lines, it's 14ft long before it arcs
corner_three_a = Rectangle((-220, -47.5), 0, 140, linewidth=lw,
color=color)
# Create the right side 3pt lines, it's 14ft long before it arcs
corner_three_b = Rectangle((220, -47.5), 0, 140, linewidth=lw, color=color)
# 3pt arc - center of arc will be the hoop, arc is 23'9" away from hoop
three_arc = Arc((0, 0), 475, 475, theta1=22, theta2=158, linewidth=lw,
color=color)
# Center Court
center_outer_arc = Arc((0, 422.5), 120, 120, theta1=180, theta2=0,
linewidth=lw, color=color)
center_inner_arc = Arc((0, 422.5), 40, 40, theta1=180, theta2=0,
linewidth=lw, color=color)
# List of the court elements to be plotted onto the axes
court_elements = [hoop, backboard, outer_box, inner_box, top_free_throw,
bottom_free_throw, restricted, corner_three_a,
corner_three_b, three_arc, center_outer_arc,
center_inner_arc]
if outer_lines:
# Draw the half court line, baseline and side out bound lines
outer_lines = Rectangle((-250, -47.5), 500, 470, linewidth=lw,
color=color, fill=False)
court_elements.append(outer_lines)
# Add the court elements onto the axes
for element in court_elements:
ax.add_patch(element)
return ax | [
"def",
"draw_court",
"(",
"ax",
"=",
"None",
",",
"color",
"=",
"'gray'",
",",
"lw",
"=",
"1",
",",
"outer_lines",
"=",
"False",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"# Create the various parts of an NBA basketball court",
"# Create the basketball hoop",
"hoop",
"=",
"Circle",
"(",
"(",
"0",
",",
"0",
")",
",",
"radius",
"=",
"7.5",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
",",
"fill",
"=",
"False",
")",
"# Create backboard",
"backboard",
"=",
"Rectangle",
"(",
"(",
"-",
"30",
",",
"-",
"12.5",
")",
",",
"60",
",",
"0",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
")",
"# The paint",
"# Create the outer box 0f the paint, width=16ft, height=19ft",
"outer_box",
"=",
"Rectangle",
"(",
"(",
"-",
"80",
",",
"-",
"47.5",
")",
",",
"160",
",",
"190",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
",",
"fill",
"=",
"False",
")",
"# Create the inner box of the paint, widt=12ft, height=19ft",
"inner_box",
"=",
"Rectangle",
"(",
"(",
"-",
"60",
",",
"-",
"47.5",
")",
",",
"120",
",",
"190",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
",",
"fill",
"=",
"False",
")",
"# Create free throw top arc",
"top_free_throw",
"=",
"Arc",
"(",
"(",
"0",
",",
"142.5",
")",
",",
"120",
",",
"120",
",",
"theta1",
"=",
"0",
",",
"theta2",
"=",
"180",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
",",
"fill",
"=",
"False",
")",
"# Create free throw bottom arc",
"bottom_free_throw",
"=",
"Arc",
"(",
"(",
"0",
",",
"142.5",
")",
",",
"120",
",",
"120",
",",
"theta1",
"=",
"180",
",",
"theta2",
"=",
"0",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
",",
"linestyle",
"=",
"'dashed'",
")",
"# Restricted Zone, it is an arc with 4ft radius from center of the hoop",
"restricted",
"=",
"Arc",
"(",
"(",
"0",
",",
"0",
")",
",",
"80",
",",
"80",
",",
"theta1",
"=",
"0",
",",
"theta2",
"=",
"180",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
")",
"# Three point line",
"# Create the right side 3pt lines, it's 14ft long before it arcs",
"corner_three_a",
"=",
"Rectangle",
"(",
"(",
"-",
"220",
",",
"-",
"47.5",
")",
",",
"0",
",",
"140",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
")",
"# Create the right side 3pt lines, it's 14ft long before it arcs",
"corner_three_b",
"=",
"Rectangle",
"(",
"(",
"220",
",",
"-",
"47.5",
")",
",",
"0",
",",
"140",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
")",
"# 3pt arc - center of arc will be the hoop, arc is 23'9\" away from hoop",
"three_arc",
"=",
"Arc",
"(",
"(",
"0",
",",
"0",
")",
",",
"475",
",",
"475",
",",
"theta1",
"=",
"22",
",",
"theta2",
"=",
"158",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
")",
"# Center Court",
"center_outer_arc",
"=",
"Arc",
"(",
"(",
"0",
",",
"422.5",
")",
",",
"120",
",",
"120",
",",
"theta1",
"=",
"180",
",",
"theta2",
"=",
"0",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
")",
"center_inner_arc",
"=",
"Arc",
"(",
"(",
"0",
",",
"422.5",
")",
",",
"40",
",",
"40",
",",
"theta1",
"=",
"180",
",",
"theta2",
"=",
"0",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
")",
"# List of the court elements to be plotted onto the axes",
"court_elements",
"=",
"[",
"hoop",
",",
"backboard",
",",
"outer_box",
",",
"inner_box",
",",
"top_free_throw",
",",
"bottom_free_throw",
",",
"restricted",
",",
"corner_three_a",
",",
"corner_three_b",
",",
"three_arc",
",",
"center_outer_arc",
",",
"center_inner_arc",
"]",
"if",
"outer_lines",
":",
"# Draw the half court line, baseline and side out bound lines",
"outer_lines",
"=",
"Rectangle",
"(",
"(",
"-",
"250",
",",
"-",
"47.5",
")",
",",
"500",
",",
"470",
",",
"linewidth",
"=",
"lw",
",",
"color",
"=",
"color",
",",
"fill",
"=",
"False",
")",
"court_elements",
".",
"append",
"(",
"outer_lines",
")",
"# Add the court elements onto the axes",
"for",
"element",
"in",
"court_elements",
":",
"ax",
".",
"add_patch",
"(",
"element",
")",
"return",
"ax"
] | Returns an axes with a basketball court drawn onto to it.
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0,0) coordinate. Twenty-two feet from the left of
the center of the hoop in is represented by the (-220,0) coordinates.
So one foot equals +/-10 units on the x and y-axis.
Parameters
----------
ax : Axes, optional
The Axes object to plot the court onto.
color : matplotlib color, optional
The color of the court lines.
lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If `True` it draws the out of bound lines in same style as the rest of
the court.
Returns
-------
ax : Axes
The Axes object with the court on it. | [
"Returns",
"an",
"axes",
"with",
"a",
"basketball",
"court",
"drawn",
"onto",
"to",
"it",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L15-L103 | train |
savvastj/nbashots | nbashots/charts.py | shot_chart | def shot_chart(x, y, kind="scatter", title="", color="b", cmap=None,
xlim=(-250, 250), ylim=(422.5, -47.5),
court_color="gray", court_lw=1, outer_lines=False,
flip_court=False, kde_shade=True, gridsize=None, ax=None,
despine=False, **kwargs):
"""
Returns an Axes object with player shots plotted.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as columns from the pandas
DataFrame passed into ``data``.
data : DataFrame, optional
DataFrame containing shots where ``x`` and ``y`` represent the
shot location coordinates.
kind : { "scatter", "kde", "hex" }, optional
The kind of shot chart to create.
title : str, optional
The title for the plot.
color : matplotlib color, optional
Color used to plot the shots
cmap : matplotlib Colormap object or name, optional
Colormap for the range of data values. If one isn't provided, the
colormap is derived from the valuue passed to ``color``. Used for KDE
and Hexbin plots.
{x, y}lim : two-tuples, optional
The axis limits of the plot.
court_color : matplotlib color, optional
The color of the court lines.
court_lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If ``True`` the out of bound lines are drawn in as a matplotlib
Rectangle.
flip_court : boolean, optional
If ``True`` orients the hoop towards the bottom of the plot. Default
is ``False``, which orients the court where the hoop is towards the top
of the plot.
kde_shade : boolean, optional
Default is ``True``, which shades in the KDE contours.
gridsize : int, optional
Number of hexagons in the x-direction. The default is calculated using
the Freedman-Diaconis method.
ax : Axes, optional
The Axes object to plot the court onto.
despine : boolean, optional
If ``True``, removes the spines.
kwargs : key, value pairs
Keyword arguments for matplotlib Collection properties or seaborn plots.
Returns
-------
ax : Axes
The Axes object with the shot chart plotted on it.
"""
if ax is None:
ax = plt.gca()
if cmap is None:
cmap = sns.light_palette(color, as_cmap=True)
if not flip_court:
ax.set_xlim(xlim)
ax.set_ylim(ylim)
else:
ax.set_xlim(xlim[::-1])
ax.set_ylim(ylim[::-1])
ax.tick_params(labelbottom="off", labelleft="off")
ax.set_title(title, fontsize=18)
draw_court(ax, color=court_color, lw=court_lw, outer_lines=outer_lines)
if kind == "scatter":
ax.scatter(x, y, c=color, **kwargs)
elif kind == "kde":
sns.kdeplot(x, y, shade=kde_shade, cmap=cmap, ax=ax, **kwargs)
ax.set_xlabel('')
ax.set_ylabel('')
elif kind == "hex":
if gridsize is None:
# Get the number of bins for hexbin using Freedman-Diaconis rule
# This is idea was taken from seaborn, which got the calculation
# from http://stats.stackexchange.com/questions/798/
from seaborn.distributions import _freedman_diaconis_bins
x_bin = _freedman_diaconis_bins(x)
y_bin = _freedman_diaconis_bins(y)
gridsize = int(np.mean([x_bin, y_bin]))
ax.hexbin(x, y, gridsize=gridsize, cmap=cmap, **kwargs)
else:
raise ValueError("kind must be 'scatter', 'kde', or 'hex'.")
# Set the spines to match the rest of court lines, makes outer_lines
# somewhate unnecessary
for spine in ax.spines:
ax.spines[spine].set_lw(court_lw)
ax.spines[spine].set_color(court_color)
if despine:
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
return ax | python | def shot_chart(x, y, kind="scatter", title="", color="b", cmap=None,
xlim=(-250, 250), ylim=(422.5, -47.5),
court_color="gray", court_lw=1, outer_lines=False,
flip_court=False, kde_shade=True, gridsize=None, ax=None,
despine=False, **kwargs):
"""
Returns an Axes object with player shots plotted.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as columns from the pandas
DataFrame passed into ``data``.
data : DataFrame, optional
DataFrame containing shots where ``x`` and ``y`` represent the
shot location coordinates.
kind : { "scatter", "kde", "hex" }, optional
The kind of shot chart to create.
title : str, optional
The title for the plot.
color : matplotlib color, optional
Color used to plot the shots
cmap : matplotlib Colormap object or name, optional
Colormap for the range of data values. If one isn't provided, the
colormap is derived from the valuue passed to ``color``. Used for KDE
and Hexbin plots.
{x, y}lim : two-tuples, optional
The axis limits of the plot.
court_color : matplotlib color, optional
The color of the court lines.
court_lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If ``True`` the out of bound lines are drawn in as a matplotlib
Rectangle.
flip_court : boolean, optional
If ``True`` orients the hoop towards the bottom of the plot. Default
is ``False``, which orients the court where the hoop is towards the top
of the plot.
kde_shade : boolean, optional
Default is ``True``, which shades in the KDE contours.
gridsize : int, optional
Number of hexagons in the x-direction. The default is calculated using
the Freedman-Diaconis method.
ax : Axes, optional
The Axes object to plot the court onto.
despine : boolean, optional
If ``True``, removes the spines.
kwargs : key, value pairs
Keyword arguments for matplotlib Collection properties or seaborn plots.
Returns
-------
ax : Axes
The Axes object with the shot chart plotted on it.
"""
if ax is None:
ax = plt.gca()
if cmap is None:
cmap = sns.light_palette(color, as_cmap=True)
if not flip_court:
ax.set_xlim(xlim)
ax.set_ylim(ylim)
else:
ax.set_xlim(xlim[::-1])
ax.set_ylim(ylim[::-1])
ax.tick_params(labelbottom="off", labelleft="off")
ax.set_title(title, fontsize=18)
draw_court(ax, color=court_color, lw=court_lw, outer_lines=outer_lines)
if kind == "scatter":
ax.scatter(x, y, c=color, **kwargs)
elif kind == "kde":
sns.kdeplot(x, y, shade=kde_shade, cmap=cmap, ax=ax, **kwargs)
ax.set_xlabel('')
ax.set_ylabel('')
elif kind == "hex":
if gridsize is None:
# Get the number of bins for hexbin using Freedman-Diaconis rule
# This is idea was taken from seaborn, which got the calculation
# from http://stats.stackexchange.com/questions/798/
from seaborn.distributions import _freedman_diaconis_bins
x_bin = _freedman_diaconis_bins(x)
y_bin = _freedman_diaconis_bins(y)
gridsize = int(np.mean([x_bin, y_bin]))
ax.hexbin(x, y, gridsize=gridsize, cmap=cmap, **kwargs)
else:
raise ValueError("kind must be 'scatter', 'kde', or 'hex'.")
# Set the spines to match the rest of court lines, makes outer_lines
# somewhate unnecessary
for spine in ax.spines:
ax.spines[spine].set_lw(court_lw)
ax.spines[spine].set_color(court_color)
if despine:
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
return ax | [
"def",
"shot_chart",
"(",
"x",
",",
"y",
",",
"kind",
"=",
"\"scatter\"",
",",
"title",
"=",
"\"\"",
",",
"color",
"=",
"\"b\"",
",",
"cmap",
"=",
"None",
",",
"xlim",
"=",
"(",
"-",
"250",
",",
"250",
")",
",",
"ylim",
"=",
"(",
"422.5",
",",
"-",
"47.5",
")",
",",
"court_color",
"=",
"\"gray\"",
",",
"court_lw",
"=",
"1",
",",
"outer_lines",
"=",
"False",
",",
"flip_court",
"=",
"False",
",",
"kde_shade",
"=",
"True",
",",
"gridsize",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"despine",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"if",
"cmap",
"is",
"None",
":",
"cmap",
"=",
"sns",
".",
"light_palette",
"(",
"color",
",",
"as_cmap",
"=",
"True",
")",
"if",
"not",
"flip_court",
":",
"ax",
".",
"set_xlim",
"(",
"xlim",
")",
"ax",
".",
"set_ylim",
"(",
"ylim",
")",
"else",
":",
"ax",
".",
"set_xlim",
"(",
"xlim",
"[",
":",
":",
"-",
"1",
"]",
")",
"ax",
".",
"set_ylim",
"(",
"ylim",
"[",
":",
":",
"-",
"1",
"]",
")",
"ax",
".",
"tick_params",
"(",
"labelbottom",
"=",
"\"off\"",
",",
"labelleft",
"=",
"\"off\"",
")",
"ax",
".",
"set_title",
"(",
"title",
",",
"fontsize",
"=",
"18",
")",
"draw_court",
"(",
"ax",
",",
"color",
"=",
"court_color",
",",
"lw",
"=",
"court_lw",
",",
"outer_lines",
"=",
"outer_lines",
")",
"if",
"kind",
"==",
"\"scatter\"",
":",
"ax",
".",
"scatter",
"(",
"x",
",",
"y",
",",
"c",
"=",
"color",
",",
"*",
"*",
"kwargs",
")",
"elif",
"kind",
"==",
"\"kde\"",
":",
"sns",
".",
"kdeplot",
"(",
"x",
",",
"y",
",",
"shade",
"=",
"kde_shade",
",",
"cmap",
"=",
"cmap",
",",
"ax",
"=",
"ax",
",",
"*",
"*",
"kwargs",
")",
"ax",
".",
"set_xlabel",
"(",
"''",
")",
"ax",
".",
"set_ylabel",
"(",
"''",
")",
"elif",
"kind",
"==",
"\"hex\"",
":",
"if",
"gridsize",
"is",
"None",
":",
"# Get the number of bins for hexbin using Freedman-Diaconis rule",
"# This is idea was taken from seaborn, which got the calculation",
"# from http://stats.stackexchange.com/questions/798/",
"from",
"seaborn",
".",
"distributions",
"import",
"_freedman_diaconis_bins",
"x_bin",
"=",
"_freedman_diaconis_bins",
"(",
"x",
")",
"y_bin",
"=",
"_freedman_diaconis_bins",
"(",
"y",
")",
"gridsize",
"=",
"int",
"(",
"np",
".",
"mean",
"(",
"[",
"x_bin",
",",
"y_bin",
"]",
")",
")",
"ax",
".",
"hexbin",
"(",
"x",
",",
"y",
",",
"gridsize",
"=",
"gridsize",
",",
"cmap",
"=",
"cmap",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"kind must be 'scatter', 'kde', or 'hex'.\"",
")",
"# Set the spines to match the rest of court lines, makes outer_lines",
"# somewhate unnecessary",
"for",
"spine",
"in",
"ax",
".",
"spines",
":",
"ax",
".",
"spines",
"[",
"spine",
"]",
".",
"set_lw",
"(",
"court_lw",
")",
"ax",
".",
"spines",
"[",
"spine",
"]",
".",
"set_color",
"(",
"court_color",
")",
"if",
"despine",
":",
"ax",
".",
"spines",
"[",
"\"top\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"spines",
"[",
"\"bottom\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"spines",
"[",
"\"right\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"spines",
"[",
"\"left\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"return",
"ax"
] | Returns an Axes object with player shots plotted.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as columns from the pandas
DataFrame passed into ``data``.
data : DataFrame, optional
DataFrame containing shots where ``x`` and ``y`` represent the
shot location coordinates.
kind : { "scatter", "kde", "hex" }, optional
The kind of shot chart to create.
title : str, optional
The title for the plot.
color : matplotlib color, optional
Color used to plot the shots
cmap : matplotlib Colormap object or name, optional
Colormap for the range of data values. If one isn't provided, the
colormap is derived from the valuue passed to ``color``. Used for KDE
and Hexbin plots.
{x, y}lim : two-tuples, optional
The axis limits of the plot.
court_color : matplotlib color, optional
The color of the court lines.
court_lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If ``True`` the out of bound lines are drawn in as a matplotlib
Rectangle.
flip_court : boolean, optional
If ``True`` orients the hoop towards the bottom of the plot. Default
is ``False``, which orients the court where the hoop is towards the top
of the plot.
kde_shade : boolean, optional
Default is ``True``, which shades in the KDE contours.
gridsize : int, optional
Number of hexagons in the x-direction. The default is calculated using
the Freedman-Diaconis method.
ax : Axes, optional
The Axes object to plot the court onto.
despine : boolean, optional
If ``True``, removes the spines.
kwargs : key, value pairs
Keyword arguments for matplotlib Collection properties or seaborn plots.
Returns
-------
ax : Axes
The Axes object with the shot chart plotted on it. | [
"Returns",
"an",
"Axes",
"object",
"with",
"player",
"shots",
"plotted",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L106-L219 | train |
savvastj/nbashots | nbashots/charts.py | shot_chart_jointgrid | def shot_chart_jointgrid(x, y, data=None, joint_type="scatter", title="",
joint_color="b", cmap=None, xlim=(-250, 250),
ylim=(422.5, -47.5), court_color="gray", court_lw=1,
outer_lines=False, flip_court=False,
joint_kde_shade=True, gridsize=None,
marginals_color="b", marginals_type="both",
marginals_kde_shade=True, size=(12, 11), space=0,
despine=False, joint_kws=None, marginal_kws=None,
**kwargs):
"""
Returns a JointGrid object containing the shot chart.
This function allows for more flexibility in customizing your shot chart
than the ``shot_chart_jointplot`` function.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as columns from the pandas
DataFrame passed into ``data``.
data : DataFrame, optional
DataFrame containing shots where ``x`` and ``y`` represent the shot
location coordinates.
joint_type : { "scatter", "kde", "hex" }, optional
The type of shot chart for the joint plot.
title : str, optional
The title for the plot.
joint_color : matplotlib color, optional
Color used to plot the shots on the joint plot.
cmap : matplotlib Colormap object or name, optional
Colormap for the range of data values. If one isn't provided, the
colormap is derived from the value passed to ``color``. Used for KDE
and Hexbin joint plots.
{x, y}lim : two-tuples, optional
The axis limits of the plot. The defaults represent the out of bounds
lines and half court line.
court_color : matplotlib color, optional
The color of the court lines.
court_lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If ``True`` the out of bound lines are drawn in as a matplotlib
Rectangle.
flip_court : boolean, optional
If ``True`` orients the hoop towards the bottom of the plot. Default is
``False``, which orients the court where the hoop is towards the top of
the plot.
joint_kde_shade : boolean, optional
Default is ``True``, which shades in the KDE contours on the joint plot.
gridsize : int, optional
Number of hexagons in the x-direction. The default is calculated using
the Freedman-Diaconis method.
marginals_color : matplotlib color, optional
Color used to plot the shots on the marginal plots.
marginals_type : { "both", "hist", "kde"}, optional
The type of plot for the marginal plots.
marginals_kde_shade : boolean, optional
Default is ``True``, which shades in the KDE contours on the marginal
plots.
size : tuple, optional
The width and height of the plot in inches.
space : numeric, optional
The space between the joint and marginal plots.
despine : boolean, optional
If ``True``, removes the spines.
{joint, marginal}_kws : dicts
Additional kewyord arguments for joint and marginal plot components.
kwargs : key, value pairs
Keyword arguments for matplotlib Collection properties or seaborn plots.
Returns
-------
grid : JointGrid
The JointGrid object with the shot chart plotted on it.
"""
# The joint_kws and marginal_kws idea was taken from seaborn
# Create the default empty kwargs for joint and marginal plots
if joint_kws is None:
joint_kws = {}
joint_kws.update(kwargs)
if marginal_kws is None:
marginal_kws = {}
# If a colormap is not provided, then it is based off of the joint_color
if cmap is None:
cmap = sns.light_palette(joint_color, as_cmap=True)
# Flip the court so that the hoop is by the bottom of the plot
if flip_court:
xlim = xlim[::-1]
ylim = ylim[::-1]
# Create the JointGrid to draw the shot chart plots onto
grid = sns.JointGrid(x=x, y=y, data=data, xlim=xlim, ylim=ylim,
space=space)
# Joint Plot
# Create the main plot of the joint shot chart
if joint_type == "scatter":
grid = grid.plot_joint(plt.scatter, color=joint_color, **joint_kws)
elif joint_type == "kde":
grid = grid.plot_joint(sns.kdeplot, cmap=cmap,
shade=joint_kde_shade, **joint_kws)
elif joint_type == "hex":
if gridsize is None:
# Get the number of bins for hexbin using Freedman-Diaconis rule
# This is idea was taken from seaborn, which got the calculation
# from http://stats.stackexchange.com/questions/798/
from seaborn.distributions import _freedman_diaconis_bins
x_bin = _freedman_diaconis_bins(x)
y_bin = _freedman_diaconis_bins(y)
gridsize = int(np.mean([x_bin, y_bin]))
grid = grid.plot_joint(plt.hexbin, gridsize=gridsize, cmap=cmap,
**joint_kws)
else:
raise ValueError("joint_type must be 'scatter', 'kde', or 'hex'.")
# Marginal plots
# Create the plots on the axis of the main plot of the joint shot chart.
if marginals_type == "both":
grid = grid.plot_marginals(sns.distplot, color=marginals_color,
**marginal_kws)
elif marginals_type == "hist":
grid = grid.plot_marginals(sns.distplot, color=marginals_color,
kde=False, **marginal_kws)
elif marginals_type == "kde":
grid = grid.plot_marginals(sns.kdeplot, color=marginals_color,
shade=marginals_kde_shade, **marginal_kws)
else:
raise ValueError("marginals_type must be 'both', 'hist', or 'kde'.")
# Set the size of the joint shot chart
grid.fig.set_size_inches(size)
# Extract the the first axes, which is the main plot of the
# joint shot chart, and draw the court onto it
ax = grid.fig.get_axes()[0]
draw_court(ax, color=court_color, lw=court_lw, outer_lines=outer_lines)
# Get rid of the axis labels
grid.set_axis_labels(xlabel="", ylabel="")
# Get rid of all tick labels
ax.tick_params(labelbottom="off", labelleft="off")
# Set the title above the top marginal plot
ax.set_title(title, y=1.2, fontsize=18)
# Set the spines to match the rest of court lines, makes outer_lines
# somewhate unnecessary
for spine in ax.spines:
ax.spines[spine].set_lw(court_lw)
ax.spines[spine].set_color(court_color)
# set the marginal spines to be the same as the rest of the spines
grid.ax_marg_x.spines[spine].set_lw(court_lw)
grid.ax_marg_x.spines[spine].set_color(court_color)
grid.ax_marg_y.spines[spine].set_lw(court_lw)
grid.ax_marg_y.spines[spine].set_color(court_color)
if despine:
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
return grid | python | def shot_chart_jointgrid(x, y, data=None, joint_type="scatter", title="",
joint_color="b", cmap=None, xlim=(-250, 250),
ylim=(422.5, -47.5), court_color="gray", court_lw=1,
outer_lines=False, flip_court=False,
joint_kde_shade=True, gridsize=None,
marginals_color="b", marginals_type="both",
marginals_kde_shade=True, size=(12, 11), space=0,
despine=False, joint_kws=None, marginal_kws=None,
**kwargs):
"""
Returns a JointGrid object containing the shot chart.
This function allows for more flexibility in customizing your shot chart
than the ``shot_chart_jointplot`` function.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as columns from the pandas
DataFrame passed into ``data``.
data : DataFrame, optional
DataFrame containing shots where ``x`` and ``y`` represent the shot
location coordinates.
joint_type : { "scatter", "kde", "hex" }, optional
The type of shot chart for the joint plot.
title : str, optional
The title for the plot.
joint_color : matplotlib color, optional
Color used to plot the shots on the joint plot.
cmap : matplotlib Colormap object or name, optional
Colormap for the range of data values. If one isn't provided, the
colormap is derived from the value passed to ``color``. Used for KDE
and Hexbin joint plots.
{x, y}lim : two-tuples, optional
The axis limits of the plot. The defaults represent the out of bounds
lines and half court line.
court_color : matplotlib color, optional
The color of the court lines.
court_lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If ``True`` the out of bound lines are drawn in as a matplotlib
Rectangle.
flip_court : boolean, optional
If ``True`` orients the hoop towards the bottom of the plot. Default is
``False``, which orients the court where the hoop is towards the top of
the plot.
joint_kde_shade : boolean, optional
Default is ``True``, which shades in the KDE contours on the joint plot.
gridsize : int, optional
Number of hexagons in the x-direction. The default is calculated using
the Freedman-Diaconis method.
marginals_color : matplotlib color, optional
Color used to plot the shots on the marginal plots.
marginals_type : { "both", "hist", "kde"}, optional
The type of plot for the marginal plots.
marginals_kde_shade : boolean, optional
Default is ``True``, which shades in the KDE contours on the marginal
plots.
size : tuple, optional
The width and height of the plot in inches.
space : numeric, optional
The space between the joint and marginal plots.
despine : boolean, optional
If ``True``, removes the spines.
{joint, marginal}_kws : dicts
Additional kewyord arguments for joint and marginal plot components.
kwargs : key, value pairs
Keyword arguments for matplotlib Collection properties or seaborn plots.
Returns
-------
grid : JointGrid
The JointGrid object with the shot chart plotted on it.
"""
# The joint_kws and marginal_kws idea was taken from seaborn
# Create the default empty kwargs for joint and marginal plots
if joint_kws is None:
joint_kws = {}
joint_kws.update(kwargs)
if marginal_kws is None:
marginal_kws = {}
# If a colormap is not provided, then it is based off of the joint_color
if cmap is None:
cmap = sns.light_palette(joint_color, as_cmap=True)
# Flip the court so that the hoop is by the bottom of the plot
if flip_court:
xlim = xlim[::-1]
ylim = ylim[::-1]
# Create the JointGrid to draw the shot chart plots onto
grid = sns.JointGrid(x=x, y=y, data=data, xlim=xlim, ylim=ylim,
space=space)
# Joint Plot
# Create the main plot of the joint shot chart
if joint_type == "scatter":
grid = grid.plot_joint(plt.scatter, color=joint_color, **joint_kws)
elif joint_type == "kde":
grid = grid.plot_joint(sns.kdeplot, cmap=cmap,
shade=joint_kde_shade, **joint_kws)
elif joint_type == "hex":
if gridsize is None:
# Get the number of bins for hexbin using Freedman-Diaconis rule
# This is idea was taken from seaborn, which got the calculation
# from http://stats.stackexchange.com/questions/798/
from seaborn.distributions import _freedman_diaconis_bins
x_bin = _freedman_diaconis_bins(x)
y_bin = _freedman_diaconis_bins(y)
gridsize = int(np.mean([x_bin, y_bin]))
grid = grid.plot_joint(plt.hexbin, gridsize=gridsize, cmap=cmap,
**joint_kws)
else:
raise ValueError("joint_type must be 'scatter', 'kde', or 'hex'.")
# Marginal plots
# Create the plots on the axis of the main plot of the joint shot chart.
if marginals_type == "both":
grid = grid.plot_marginals(sns.distplot, color=marginals_color,
**marginal_kws)
elif marginals_type == "hist":
grid = grid.plot_marginals(sns.distplot, color=marginals_color,
kde=False, **marginal_kws)
elif marginals_type == "kde":
grid = grid.plot_marginals(sns.kdeplot, color=marginals_color,
shade=marginals_kde_shade, **marginal_kws)
else:
raise ValueError("marginals_type must be 'both', 'hist', or 'kde'.")
# Set the size of the joint shot chart
grid.fig.set_size_inches(size)
# Extract the the first axes, which is the main plot of the
# joint shot chart, and draw the court onto it
ax = grid.fig.get_axes()[0]
draw_court(ax, color=court_color, lw=court_lw, outer_lines=outer_lines)
# Get rid of the axis labels
grid.set_axis_labels(xlabel="", ylabel="")
# Get rid of all tick labels
ax.tick_params(labelbottom="off", labelleft="off")
# Set the title above the top marginal plot
ax.set_title(title, y=1.2, fontsize=18)
# Set the spines to match the rest of court lines, makes outer_lines
# somewhate unnecessary
for spine in ax.spines:
ax.spines[spine].set_lw(court_lw)
ax.spines[spine].set_color(court_color)
# set the marginal spines to be the same as the rest of the spines
grid.ax_marg_x.spines[spine].set_lw(court_lw)
grid.ax_marg_x.spines[spine].set_color(court_color)
grid.ax_marg_y.spines[spine].set_lw(court_lw)
grid.ax_marg_y.spines[spine].set_color(court_color)
if despine:
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
return grid | [
"def",
"shot_chart_jointgrid",
"(",
"x",
",",
"y",
",",
"data",
"=",
"None",
",",
"joint_type",
"=",
"\"scatter\"",
",",
"title",
"=",
"\"\"",
",",
"joint_color",
"=",
"\"b\"",
",",
"cmap",
"=",
"None",
",",
"xlim",
"=",
"(",
"-",
"250",
",",
"250",
")",
",",
"ylim",
"=",
"(",
"422.5",
",",
"-",
"47.5",
")",
",",
"court_color",
"=",
"\"gray\"",
",",
"court_lw",
"=",
"1",
",",
"outer_lines",
"=",
"False",
",",
"flip_court",
"=",
"False",
",",
"joint_kde_shade",
"=",
"True",
",",
"gridsize",
"=",
"None",
",",
"marginals_color",
"=",
"\"b\"",
",",
"marginals_type",
"=",
"\"both\"",
",",
"marginals_kde_shade",
"=",
"True",
",",
"size",
"=",
"(",
"12",
",",
"11",
")",
",",
"space",
"=",
"0",
",",
"despine",
"=",
"False",
",",
"joint_kws",
"=",
"None",
",",
"marginal_kws",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# The joint_kws and marginal_kws idea was taken from seaborn",
"# Create the default empty kwargs for joint and marginal plots",
"if",
"joint_kws",
"is",
"None",
":",
"joint_kws",
"=",
"{",
"}",
"joint_kws",
".",
"update",
"(",
"kwargs",
")",
"if",
"marginal_kws",
"is",
"None",
":",
"marginal_kws",
"=",
"{",
"}",
"# If a colormap is not provided, then it is based off of the joint_color",
"if",
"cmap",
"is",
"None",
":",
"cmap",
"=",
"sns",
".",
"light_palette",
"(",
"joint_color",
",",
"as_cmap",
"=",
"True",
")",
"# Flip the court so that the hoop is by the bottom of the plot",
"if",
"flip_court",
":",
"xlim",
"=",
"xlim",
"[",
":",
":",
"-",
"1",
"]",
"ylim",
"=",
"ylim",
"[",
":",
":",
"-",
"1",
"]",
"# Create the JointGrid to draw the shot chart plots onto",
"grid",
"=",
"sns",
".",
"JointGrid",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"data",
"=",
"data",
",",
"xlim",
"=",
"xlim",
",",
"ylim",
"=",
"ylim",
",",
"space",
"=",
"space",
")",
"# Joint Plot",
"# Create the main plot of the joint shot chart",
"if",
"joint_type",
"==",
"\"scatter\"",
":",
"grid",
"=",
"grid",
".",
"plot_joint",
"(",
"plt",
".",
"scatter",
",",
"color",
"=",
"joint_color",
",",
"*",
"*",
"joint_kws",
")",
"elif",
"joint_type",
"==",
"\"kde\"",
":",
"grid",
"=",
"grid",
".",
"plot_joint",
"(",
"sns",
".",
"kdeplot",
",",
"cmap",
"=",
"cmap",
",",
"shade",
"=",
"joint_kde_shade",
",",
"*",
"*",
"joint_kws",
")",
"elif",
"joint_type",
"==",
"\"hex\"",
":",
"if",
"gridsize",
"is",
"None",
":",
"# Get the number of bins for hexbin using Freedman-Diaconis rule",
"# This is idea was taken from seaborn, which got the calculation",
"# from http://stats.stackexchange.com/questions/798/",
"from",
"seaborn",
".",
"distributions",
"import",
"_freedman_diaconis_bins",
"x_bin",
"=",
"_freedman_diaconis_bins",
"(",
"x",
")",
"y_bin",
"=",
"_freedman_diaconis_bins",
"(",
"y",
")",
"gridsize",
"=",
"int",
"(",
"np",
".",
"mean",
"(",
"[",
"x_bin",
",",
"y_bin",
"]",
")",
")",
"grid",
"=",
"grid",
".",
"plot_joint",
"(",
"plt",
".",
"hexbin",
",",
"gridsize",
"=",
"gridsize",
",",
"cmap",
"=",
"cmap",
",",
"*",
"*",
"joint_kws",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"joint_type must be 'scatter', 'kde', or 'hex'.\"",
")",
"# Marginal plots",
"# Create the plots on the axis of the main plot of the joint shot chart.",
"if",
"marginals_type",
"==",
"\"both\"",
":",
"grid",
"=",
"grid",
".",
"plot_marginals",
"(",
"sns",
".",
"distplot",
",",
"color",
"=",
"marginals_color",
",",
"*",
"*",
"marginal_kws",
")",
"elif",
"marginals_type",
"==",
"\"hist\"",
":",
"grid",
"=",
"grid",
".",
"plot_marginals",
"(",
"sns",
".",
"distplot",
",",
"color",
"=",
"marginals_color",
",",
"kde",
"=",
"False",
",",
"*",
"*",
"marginal_kws",
")",
"elif",
"marginals_type",
"==",
"\"kde\"",
":",
"grid",
"=",
"grid",
".",
"plot_marginals",
"(",
"sns",
".",
"kdeplot",
",",
"color",
"=",
"marginals_color",
",",
"shade",
"=",
"marginals_kde_shade",
",",
"*",
"*",
"marginal_kws",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"marginals_type must be 'both', 'hist', or 'kde'.\"",
")",
"# Set the size of the joint shot chart",
"grid",
".",
"fig",
".",
"set_size_inches",
"(",
"size",
")",
"# Extract the the first axes, which is the main plot of the",
"# joint shot chart, and draw the court onto it",
"ax",
"=",
"grid",
".",
"fig",
".",
"get_axes",
"(",
")",
"[",
"0",
"]",
"draw_court",
"(",
"ax",
",",
"color",
"=",
"court_color",
",",
"lw",
"=",
"court_lw",
",",
"outer_lines",
"=",
"outer_lines",
")",
"# Get rid of the axis labels",
"grid",
".",
"set_axis_labels",
"(",
"xlabel",
"=",
"\"\"",
",",
"ylabel",
"=",
"\"\"",
")",
"# Get rid of all tick labels",
"ax",
".",
"tick_params",
"(",
"labelbottom",
"=",
"\"off\"",
",",
"labelleft",
"=",
"\"off\"",
")",
"# Set the title above the top marginal plot",
"ax",
".",
"set_title",
"(",
"title",
",",
"y",
"=",
"1.2",
",",
"fontsize",
"=",
"18",
")",
"# Set the spines to match the rest of court lines, makes outer_lines",
"# somewhate unnecessary",
"for",
"spine",
"in",
"ax",
".",
"spines",
":",
"ax",
".",
"spines",
"[",
"spine",
"]",
".",
"set_lw",
"(",
"court_lw",
")",
"ax",
".",
"spines",
"[",
"spine",
"]",
".",
"set_color",
"(",
"court_color",
")",
"# set the marginal spines to be the same as the rest of the spines",
"grid",
".",
"ax_marg_x",
".",
"spines",
"[",
"spine",
"]",
".",
"set_lw",
"(",
"court_lw",
")",
"grid",
".",
"ax_marg_x",
".",
"spines",
"[",
"spine",
"]",
".",
"set_color",
"(",
"court_color",
")",
"grid",
".",
"ax_marg_y",
".",
"spines",
"[",
"spine",
"]",
".",
"set_lw",
"(",
"court_lw",
")",
"grid",
".",
"ax_marg_y",
".",
"spines",
"[",
"spine",
"]",
".",
"set_color",
"(",
"court_color",
")",
"if",
"despine",
":",
"ax",
".",
"spines",
"[",
"\"top\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"spines",
"[",
"\"bottom\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"spines",
"[",
"\"right\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"spines",
"[",
"\"left\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"return",
"grid"
] | Returns a JointGrid object containing the shot chart.
This function allows for more flexibility in customizing your shot chart
than the ``shot_chart_jointplot`` function.
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as columns from the pandas
DataFrame passed into ``data``.
data : DataFrame, optional
DataFrame containing shots where ``x`` and ``y`` represent the shot
location coordinates.
joint_type : { "scatter", "kde", "hex" }, optional
The type of shot chart for the joint plot.
title : str, optional
The title for the plot.
joint_color : matplotlib color, optional
Color used to plot the shots on the joint plot.
cmap : matplotlib Colormap object or name, optional
Colormap for the range of data values. If one isn't provided, the
colormap is derived from the value passed to ``color``. Used for KDE
and Hexbin joint plots.
{x, y}lim : two-tuples, optional
The axis limits of the plot. The defaults represent the out of bounds
lines and half court line.
court_color : matplotlib color, optional
The color of the court lines.
court_lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If ``True`` the out of bound lines are drawn in as a matplotlib
Rectangle.
flip_court : boolean, optional
If ``True`` orients the hoop towards the bottom of the plot. Default is
``False``, which orients the court where the hoop is towards the top of
the plot.
joint_kde_shade : boolean, optional
Default is ``True``, which shades in the KDE contours on the joint plot.
gridsize : int, optional
Number of hexagons in the x-direction. The default is calculated using
the Freedman-Diaconis method.
marginals_color : matplotlib color, optional
Color used to plot the shots on the marginal plots.
marginals_type : { "both", "hist", "kde"}, optional
The type of plot for the marginal plots.
marginals_kde_shade : boolean, optional
Default is ``True``, which shades in the KDE contours on the marginal
plots.
size : tuple, optional
The width and height of the plot in inches.
space : numeric, optional
The space between the joint and marginal plots.
despine : boolean, optional
If ``True``, removes the spines.
{joint, marginal}_kws : dicts
Additional kewyord arguments for joint and marginal plot components.
kwargs : key, value pairs
Keyword arguments for matplotlib Collection properties or seaborn plots.
Returns
-------
grid : JointGrid
The JointGrid object with the shot chart plotted on it. | [
"Returns",
"a",
"JointGrid",
"object",
"containing",
"the",
"shot",
"chart",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L222-L398 | train |
savvastj/nbashots | nbashots/charts.py | shot_chart_jointplot | def shot_chart_jointplot(x, y, data=None, kind="scatter", title="", color="b",
cmap=None, xlim=(-250, 250), ylim=(422.5, -47.5),
court_color="gray", court_lw=1, outer_lines=False,
flip_court=False, size=(12, 11), space=0,
despine=False, joint_kws=None, marginal_kws=None,
**kwargs):
"""
Returns a seaborn JointGrid using sns.jointplot
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as column names from the pandas
DataFrame passed into ``data``.
data : DataFrame, optional
DataFrame containing shots where ``x`` and ``y`` represent the
shot location coordinates.
kind : { "scatter", "kde", "hex" }, optional
The kind of shot chart to create.
title : str, optional
The title for the plot.
color : matplotlib color, optional
Color used to plot the shots
cmap : matplotlib Colormap object or name, optional
Colormap for the range of data values. If one isn't provided, the
colormap is derived from the valuue passed to ``color``. Used for KDE
and Hexbin joint plots.
{x, y}lim : two-tuples, optional
The axis limits of the plot. The defaults represent the out of bounds
lines and half court line.
court_color : matplotlib color, optional
The color of the court lines.
court_lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If ``True`` the out of bound lines are drawn in as a matplotlib
Rectangle.
flip_court : boolean, optional
If ``True`` orients the hoop towards the bottom of the plot. Default
is ``False``, which orients the court where the hoop is towards the top
of the plot.
gridsize : int, optional
Number of hexagons in the x-direction. The default is calculated using
the Freedman-Diaconis method.
size : tuple, optional
The width and height of the plot in inches.
space : numeric, optional
The space between the joint and marginal plots.
{joint, marginal}_kws : dicts
Additional kewyord arguments for joint and marginal plot components.
kwargs : key, value pairs
Keyword arguments for matplotlib Collection properties or seaborn plots.
Returns
-------
grid : JointGrid
The JointGrid object with the shot chart plotted on it.
"""
# If a colormap is not provided, then it is based off of the color
if cmap is None:
cmap = sns.light_palette(color, as_cmap=True)
if kind not in ["scatter", "kde", "hex"]:
raise ValueError("kind must be 'scatter', 'kde', or 'hex'.")
grid = sns.jointplot(x=x, y=y, data=data, stat_func=None, kind=kind,
space=0, color=color, cmap=cmap, joint_kws=joint_kws,
marginal_kws=marginal_kws, **kwargs)
grid.fig.set_size_inches(size)
# A joint plot has 3 Axes, the first one called ax_joint
# is the one we want to draw our court onto and adjust some other settings
ax = grid.ax_joint
if not flip_court:
ax.set_xlim(xlim)
ax.set_ylim(ylim)
else:
ax.set_xlim(xlim[::-1])
ax.set_ylim(ylim[::-1])
draw_court(ax, color=court_color, lw=court_lw, outer_lines=outer_lines)
# Get rid of axis labels and tick marks
ax.set_xlabel('')
ax.set_ylabel('')
ax.tick_params(labelbottom='off', labelleft='off')
# Add a title
ax.set_title(title, y=1.2, fontsize=18)
# Set the spines to match the rest of court lines, makes outer_lines
# somewhate unnecessary
for spine in ax.spines:
ax.spines[spine].set_lw(court_lw)
ax.spines[spine].set_color(court_color)
# set the margin joint spines to be same as the rest of the plot
grid.ax_marg_x.spines[spine].set_lw(court_lw)
grid.ax_marg_x.spines[spine].set_color(court_color)
grid.ax_marg_y.spines[spine].set_lw(court_lw)
grid.ax_marg_y.spines[spine].set_color(court_color)
if despine:
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
return grid | python | def shot_chart_jointplot(x, y, data=None, kind="scatter", title="", color="b",
cmap=None, xlim=(-250, 250), ylim=(422.5, -47.5),
court_color="gray", court_lw=1, outer_lines=False,
flip_court=False, size=(12, 11), space=0,
despine=False, joint_kws=None, marginal_kws=None,
**kwargs):
"""
Returns a seaborn JointGrid using sns.jointplot
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as column names from the pandas
DataFrame passed into ``data``.
data : DataFrame, optional
DataFrame containing shots where ``x`` and ``y`` represent the
shot location coordinates.
kind : { "scatter", "kde", "hex" }, optional
The kind of shot chart to create.
title : str, optional
The title for the plot.
color : matplotlib color, optional
Color used to plot the shots
cmap : matplotlib Colormap object or name, optional
Colormap for the range of data values. If one isn't provided, the
colormap is derived from the valuue passed to ``color``. Used for KDE
and Hexbin joint plots.
{x, y}lim : two-tuples, optional
The axis limits of the plot. The defaults represent the out of bounds
lines and half court line.
court_color : matplotlib color, optional
The color of the court lines.
court_lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If ``True`` the out of bound lines are drawn in as a matplotlib
Rectangle.
flip_court : boolean, optional
If ``True`` orients the hoop towards the bottom of the plot. Default
is ``False``, which orients the court where the hoop is towards the top
of the plot.
gridsize : int, optional
Number of hexagons in the x-direction. The default is calculated using
the Freedman-Diaconis method.
size : tuple, optional
The width and height of the plot in inches.
space : numeric, optional
The space between the joint and marginal plots.
{joint, marginal}_kws : dicts
Additional kewyord arguments for joint and marginal plot components.
kwargs : key, value pairs
Keyword arguments for matplotlib Collection properties or seaborn plots.
Returns
-------
grid : JointGrid
The JointGrid object with the shot chart plotted on it.
"""
# If a colormap is not provided, then it is based off of the color
if cmap is None:
cmap = sns.light_palette(color, as_cmap=True)
if kind not in ["scatter", "kde", "hex"]:
raise ValueError("kind must be 'scatter', 'kde', or 'hex'.")
grid = sns.jointplot(x=x, y=y, data=data, stat_func=None, kind=kind,
space=0, color=color, cmap=cmap, joint_kws=joint_kws,
marginal_kws=marginal_kws, **kwargs)
grid.fig.set_size_inches(size)
# A joint plot has 3 Axes, the first one called ax_joint
# is the one we want to draw our court onto and adjust some other settings
ax = grid.ax_joint
if not flip_court:
ax.set_xlim(xlim)
ax.set_ylim(ylim)
else:
ax.set_xlim(xlim[::-1])
ax.set_ylim(ylim[::-1])
draw_court(ax, color=court_color, lw=court_lw, outer_lines=outer_lines)
# Get rid of axis labels and tick marks
ax.set_xlabel('')
ax.set_ylabel('')
ax.tick_params(labelbottom='off', labelleft='off')
# Add a title
ax.set_title(title, y=1.2, fontsize=18)
# Set the spines to match the rest of court lines, makes outer_lines
# somewhate unnecessary
for spine in ax.spines:
ax.spines[spine].set_lw(court_lw)
ax.spines[spine].set_color(court_color)
# set the margin joint spines to be same as the rest of the plot
grid.ax_marg_x.spines[spine].set_lw(court_lw)
grid.ax_marg_x.spines[spine].set_color(court_color)
grid.ax_marg_y.spines[spine].set_lw(court_lw)
grid.ax_marg_y.spines[spine].set_color(court_color)
if despine:
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)
return grid | [
"def",
"shot_chart_jointplot",
"(",
"x",
",",
"y",
",",
"data",
"=",
"None",
",",
"kind",
"=",
"\"scatter\"",
",",
"title",
"=",
"\"\"",
",",
"color",
"=",
"\"b\"",
",",
"cmap",
"=",
"None",
",",
"xlim",
"=",
"(",
"-",
"250",
",",
"250",
")",
",",
"ylim",
"=",
"(",
"422.5",
",",
"-",
"47.5",
")",
",",
"court_color",
"=",
"\"gray\"",
",",
"court_lw",
"=",
"1",
",",
"outer_lines",
"=",
"False",
",",
"flip_court",
"=",
"False",
",",
"size",
"=",
"(",
"12",
",",
"11",
")",
",",
"space",
"=",
"0",
",",
"despine",
"=",
"False",
",",
"joint_kws",
"=",
"None",
",",
"marginal_kws",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# If a colormap is not provided, then it is based off of the color",
"if",
"cmap",
"is",
"None",
":",
"cmap",
"=",
"sns",
".",
"light_palette",
"(",
"color",
",",
"as_cmap",
"=",
"True",
")",
"if",
"kind",
"not",
"in",
"[",
"\"scatter\"",
",",
"\"kde\"",
",",
"\"hex\"",
"]",
":",
"raise",
"ValueError",
"(",
"\"kind must be 'scatter', 'kde', or 'hex'.\"",
")",
"grid",
"=",
"sns",
".",
"jointplot",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"data",
"=",
"data",
",",
"stat_func",
"=",
"None",
",",
"kind",
"=",
"kind",
",",
"space",
"=",
"0",
",",
"color",
"=",
"color",
",",
"cmap",
"=",
"cmap",
",",
"joint_kws",
"=",
"joint_kws",
",",
"marginal_kws",
"=",
"marginal_kws",
",",
"*",
"*",
"kwargs",
")",
"grid",
".",
"fig",
".",
"set_size_inches",
"(",
"size",
")",
"# A joint plot has 3 Axes, the first one called ax_joint",
"# is the one we want to draw our court onto and adjust some other settings",
"ax",
"=",
"grid",
".",
"ax_joint",
"if",
"not",
"flip_court",
":",
"ax",
".",
"set_xlim",
"(",
"xlim",
")",
"ax",
".",
"set_ylim",
"(",
"ylim",
")",
"else",
":",
"ax",
".",
"set_xlim",
"(",
"xlim",
"[",
":",
":",
"-",
"1",
"]",
")",
"ax",
".",
"set_ylim",
"(",
"ylim",
"[",
":",
":",
"-",
"1",
"]",
")",
"draw_court",
"(",
"ax",
",",
"color",
"=",
"court_color",
",",
"lw",
"=",
"court_lw",
",",
"outer_lines",
"=",
"outer_lines",
")",
"# Get rid of axis labels and tick marks",
"ax",
".",
"set_xlabel",
"(",
"''",
")",
"ax",
".",
"set_ylabel",
"(",
"''",
")",
"ax",
".",
"tick_params",
"(",
"labelbottom",
"=",
"'off'",
",",
"labelleft",
"=",
"'off'",
")",
"# Add a title",
"ax",
".",
"set_title",
"(",
"title",
",",
"y",
"=",
"1.2",
",",
"fontsize",
"=",
"18",
")",
"# Set the spines to match the rest of court lines, makes outer_lines",
"# somewhate unnecessary",
"for",
"spine",
"in",
"ax",
".",
"spines",
":",
"ax",
".",
"spines",
"[",
"spine",
"]",
".",
"set_lw",
"(",
"court_lw",
")",
"ax",
".",
"spines",
"[",
"spine",
"]",
".",
"set_color",
"(",
"court_color",
")",
"# set the margin joint spines to be same as the rest of the plot",
"grid",
".",
"ax_marg_x",
".",
"spines",
"[",
"spine",
"]",
".",
"set_lw",
"(",
"court_lw",
")",
"grid",
".",
"ax_marg_x",
".",
"spines",
"[",
"spine",
"]",
".",
"set_color",
"(",
"court_color",
")",
"grid",
".",
"ax_marg_y",
".",
"spines",
"[",
"spine",
"]",
".",
"set_lw",
"(",
"court_lw",
")",
"grid",
".",
"ax_marg_y",
".",
"spines",
"[",
"spine",
"]",
".",
"set_color",
"(",
"court_color",
")",
"if",
"despine",
":",
"ax",
".",
"spines",
"[",
"\"top\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"spines",
"[",
"\"bottom\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"spines",
"[",
"\"right\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"ax",
".",
"spines",
"[",
"\"left\"",
"]",
".",
"set_visible",
"(",
"False",
")",
"return",
"grid"
] | Returns a seaborn JointGrid using sns.jointplot
Parameters
----------
x, y : strings or vector
The x and y coordinates of the shots taken. They can be passed in as
vectors (such as a pandas Series) or as column names from the pandas
DataFrame passed into ``data``.
data : DataFrame, optional
DataFrame containing shots where ``x`` and ``y`` represent the
shot location coordinates.
kind : { "scatter", "kde", "hex" }, optional
The kind of shot chart to create.
title : str, optional
The title for the plot.
color : matplotlib color, optional
Color used to plot the shots
cmap : matplotlib Colormap object or name, optional
Colormap for the range of data values. If one isn't provided, the
colormap is derived from the valuue passed to ``color``. Used for KDE
and Hexbin joint plots.
{x, y}lim : two-tuples, optional
The axis limits of the plot. The defaults represent the out of bounds
lines and half court line.
court_color : matplotlib color, optional
The color of the court lines.
court_lw : float, optional
The linewidth the of the court lines.
outer_lines : boolean, optional
If ``True`` the out of bound lines are drawn in as a matplotlib
Rectangle.
flip_court : boolean, optional
If ``True`` orients the hoop towards the bottom of the plot. Default
is ``False``, which orients the court where the hoop is towards the top
of the plot.
gridsize : int, optional
Number of hexagons in the x-direction. The default is calculated using
the Freedman-Diaconis method.
size : tuple, optional
The width and height of the plot in inches.
space : numeric, optional
The space between the joint and marginal plots.
{joint, marginal}_kws : dicts
Additional kewyord arguments for joint and marginal plot components.
kwargs : key, value pairs
Keyword arguments for matplotlib Collection properties or seaborn plots.
Returns
-------
grid : JointGrid
The JointGrid object with the shot chart plotted on it. | [
"Returns",
"a",
"seaborn",
"JointGrid",
"using",
"sns",
".",
"jointplot"
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L401-L514 | train |
savvastj/nbashots | nbashots/charts.py | heatmap | def heatmap(x, y, z, title="", cmap=plt.cm.YlOrRd, bins=20,
xlim=(-250, 250), ylim=(422.5, -47.5),
facecolor='lightgray', facecolor_alpha=0.4,
court_color="black", court_lw=0.5, outer_lines=False,
flip_court=False, ax=None, **kwargs):
"""
Returns an AxesImage object that contains a heatmap.
TODO: Redo some code and explain parameters
"""
# Bin the FGA (x, y) and Calculcate the mean number of times shot was
# made (z) within each bin
# mean is the calculated FG percentage for each bin
mean, xedges, yedges, binnumber = binned_statistic_2d(x=x, y=y,
values=z,
statistic='mean',
bins=bins)
if ax is None:
ax = plt.gca()
if not flip_court:
ax.set_xlim(xlim)
ax.set_ylim(ylim)
else:
ax.set_xlim(xlim[::-1])
ax.set_ylim(ylim[::-1])
ax.tick_params(labelbottom="off", labelleft="off")
ax.set_title(title, fontsize=18)
ax.patch.set_facecolor(facecolor)
ax.patch.set_alpha(facecolor_alpha)
draw_court(ax, color=court_color, lw=court_lw, outer_lines=outer_lines)
heatmap = ax.imshow(mean.T, origin='lower', extent=[xedges[0], xedges[-1],
yedges[0], yedges[-1]], interpolation='nearest',
cmap=cmap)
return heatmap | python | def heatmap(x, y, z, title="", cmap=plt.cm.YlOrRd, bins=20,
xlim=(-250, 250), ylim=(422.5, -47.5),
facecolor='lightgray', facecolor_alpha=0.4,
court_color="black", court_lw=0.5, outer_lines=False,
flip_court=False, ax=None, **kwargs):
"""
Returns an AxesImage object that contains a heatmap.
TODO: Redo some code and explain parameters
"""
# Bin the FGA (x, y) and Calculcate the mean number of times shot was
# made (z) within each bin
# mean is the calculated FG percentage for each bin
mean, xedges, yedges, binnumber = binned_statistic_2d(x=x, y=y,
values=z,
statistic='mean',
bins=bins)
if ax is None:
ax = plt.gca()
if not flip_court:
ax.set_xlim(xlim)
ax.set_ylim(ylim)
else:
ax.set_xlim(xlim[::-1])
ax.set_ylim(ylim[::-1])
ax.tick_params(labelbottom="off", labelleft="off")
ax.set_title(title, fontsize=18)
ax.patch.set_facecolor(facecolor)
ax.patch.set_alpha(facecolor_alpha)
draw_court(ax, color=court_color, lw=court_lw, outer_lines=outer_lines)
heatmap = ax.imshow(mean.T, origin='lower', extent=[xedges[0], xedges[-1],
yedges[0], yedges[-1]], interpolation='nearest',
cmap=cmap)
return heatmap | [
"def",
"heatmap",
"(",
"x",
",",
"y",
",",
"z",
",",
"title",
"=",
"\"\"",
",",
"cmap",
"=",
"plt",
".",
"cm",
".",
"YlOrRd",
",",
"bins",
"=",
"20",
",",
"xlim",
"=",
"(",
"-",
"250",
",",
"250",
")",
",",
"ylim",
"=",
"(",
"422.5",
",",
"-",
"47.5",
")",
",",
"facecolor",
"=",
"'lightgray'",
",",
"facecolor_alpha",
"=",
"0.4",
",",
"court_color",
"=",
"\"black\"",
",",
"court_lw",
"=",
"0.5",
",",
"outer_lines",
"=",
"False",
",",
"flip_court",
"=",
"False",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Bin the FGA (x, y) and Calculcate the mean number of times shot was",
"# made (z) within each bin",
"# mean is the calculated FG percentage for each bin",
"mean",
",",
"xedges",
",",
"yedges",
",",
"binnumber",
"=",
"binned_statistic_2d",
"(",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"values",
"=",
"z",
",",
"statistic",
"=",
"'mean'",
",",
"bins",
"=",
"bins",
")",
"if",
"ax",
"is",
"None",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"if",
"not",
"flip_court",
":",
"ax",
".",
"set_xlim",
"(",
"xlim",
")",
"ax",
".",
"set_ylim",
"(",
"ylim",
")",
"else",
":",
"ax",
".",
"set_xlim",
"(",
"xlim",
"[",
":",
":",
"-",
"1",
"]",
")",
"ax",
".",
"set_ylim",
"(",
"ylim",
"[",
":",
":",
"-",
"1",
"]",
")",
"ax",
".",
"tick_params",
"(",
"labelbottom",
"=",
"\"off\"",
",",
"labelleft",
"=",
"\"off\"",
")",
"ax",
".",
"set_title",
"(",
"title",
",",
"fontsize",
"=",
"18",
")",
"ax",
".",
"patch",
".",
"set_facecolor",
"(",
"facecolor",
")",
"ax",
".",
"patch",
".",
"set_alpha",
"(",
"facecolor_alpha",
")",
"draw_court",
"(",
"ax",
",",
"color",
"=",
"court_color",
",",
"lw",
"=",
"court_lw",
",",
"outer_lines",
"=",
"outer_lines",
")",
"heatmap",
"=",
"ax",
".",
"imshow",
"(",
"mean",
".",
"T",
",",
"origin",
"=",
"'lower'",
",",
"extent",
"=",
"[",
"xedges",
"[",
"0",
"]",
",",
"xedges",
"[",
"-",
"1",
"]",
",",
"yedges",
"[",
"0",
"]",
",",
"yedges",
"[",
"-",
"1",
"]",
"]",
",",
"interpolation",
"=",
"'nearest'",
",",
"cmap",
"=",
"cmap",
")",
"return",
"heatmap"
] | Returns an AxesImage object that contains a heatmap.
TODO: Redo some code and explain parameters | [
"Returns",
"an",
"AxesImage",
"object",
"that",
"contains",
"a",
"heatmap",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L517-L559 | train |
savvastj/nbashots | nbashots/charts.py | bokeh_draw_court | def bokeh_draw_court(figure, line_color='gray', line_width=1):
"""Returns a figure with the basketball court lines drawn onto it
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0,0) coordinate. Twenty-two feet from the left of
the center of the hoop in is represented by the (-220,0) coordinates.
So one foot equals +/-10 units on the x and y-axis.
Parameters
----------
figure : Bokeh figure object
The Axes object to plot the court onto.
line_color : str, optional
The color of the court lines. Can be a a Hex value.
line_width : float, optional
The linewidth the of the court lines in pixels.
Returns
-------
figure : Figure
The Figure object with the court on it.
"""
# hoop
figure.circle(x=0, y=0, radius=7.5, fill_alpha=0,
line_color=line_color, line_width=line_width)
# backboard
figure.line(x=range(-30, 31), y=-12.5, line_color=line_color)
# The paint
# outerbox
figure.rect(x=0, y=47.5, width=160, height=190, fill_alpha=0,
line_color=line_color, line_width=line_width)
# innerbox
# left inner box line
figure.line(x=-60, y=np.arange(-47.5, 143.5), line_color=line_color,
line_width=line_width)
# right inner box line
figure.line(x=60, y=np.arange(-47.5, 143.5), line_color=line_color,
line_width=line_width)
# Restricted Zone
figure.arc(x=0, y=0, radius=40, start_angle=pi, end_angle=0,
line_color=line_color, line_width=line_width)
# top free throw arc
figure.arc(x=0, y=142.5, radius=60, start_angle=pi, end_angle=0,
line_color=line_color)
# bottome free throw arc
figure.arc(x=0, y=142.5, radius=60, start_angle=0, end_angle=pi,
line_color=line_color, line_dash="dashed")
# Three point line
# corner three point lines
figure.line(x=-220, y=np.arange(-47.5, 92.5), line_color=line_color,
line_width=line_width)
figure.line(x=220, y=np.arange(-47.5, 92.5), line_color=line_color,
line_width=line_width)
# # three point arc
figure.arc(x=0, y=0, radius=237.5, start_angle=3.528, end_angle=-0.3863,
line_color=line_color, line_width=line_width)
# add center court
# outer center arc
figure.arc(x=0, y=422.5, radius=60, start_angle=0, end_angle=pi,
line_color=line_color, line_width=line_width)
# inner center arct
figure.arc(x=0, y=422.5, radius=20, start_angle=0, end_angle=pi,
line_color=line_color, line_width=line_width)
# outer lines, consistting of half court lines and out of bounds lines
figure.rect(x=0, y=187.5, width=500, height=470, fill_alpha=0,
line_color=line_color, line_width=line_width)
return figure | python | def bokeh_draw_court(figure, line_color='gray', line_width=1):
"""Returns a figure with the basketball court lines drawn onto it
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0,0) coordinate. Twenty-two feet from the left of
the center of the hoop in is represented by the (-220,0) coordinates.
So one foot equals +/-10 units on the x and y-axis.
Parameters
----------
figure : Bokeh figure object
The Axes object to plot the court onto.
line_color : str, optional
The color of the court lines. Can be a a Hex value.
line_width : float, optional
The linewidth the of the court lines in pixels.
Returns
-------
figure : Figure
The Figure object with the court on it.
"""
# hoop
figure.circle(x=0, y=0, radius=7.5, fill_alpha=0,
line_color=line_color, line_width=line_width)
# backboard
figure.line(x=range(-30, 31), y=-12.5, line_color=line_color)
# The paint
# outerbox
figure.rect(x=0, y=47.5, width=160, height=190, fill_alpha=0,
line_color=line_color, line_width=line_width)
# innerbox
# left inner box line
figure.line(x=-60, y=np.arange(-47.5, 143.5), line_color=line_color,
line_width=line_width)
# right inner box line
figure.line(x=60, y=np.arange(-47.5, 143.5), line_color=line_color,
line_width=line_width)
# Restricted Zone
figure.arc(x=0, y=0, radius=40, start_angle=pi, end_angle=0,
line_color=line_color, line_width=line_width)
# top free throw arc
figure.arc(x=0, y=142.5, radius=60, start_angle=pi, end_angle=0,
line_color=line_color)
# bottome free throw arc
figure.arc(x=0, y=142.5, radius=60, start_angle=0, end_angle=pi,
line_color=line_color, line_dash="dashed")
# Three point line
# corner three point lines
figure.line(x=-220, y=np.arange(-47.5, 92.5), line_color=line_color,
line_width=line_width)
figure.line(x=220, y=np.arange(-47.5, 92.5), line_color=line_color,
line_width=line_width)
# # three point arc
figure.arc(x=0, y=0, radius=237.5, start_angle=3.528, end_angle=-0.3863,
line_color=line_color, line_width=line_width)
# add center court
# outer center arc
figure.arc(x=0, y=422.5, radius=60, start_angle=0, end_angle=pi,
line_color=line_color, line_width=line_width)
# inner center arct
figure.arc(x=0, y=422.5, radius=20, start_angle=0, end_angle=pi,
line_color=line_color, line_width=line_width)
# outer lines, consistting of half court lines and out of bounds lines
figure.rect(x=0, y=187.5, width=500, height=470, fill_alpha=0,
line_color=line_color, line_width=line_width)
return figure | [
"def",
"bokeh_draw_court",
"(",
"figure",
",",
"line_color",
"=",
"'gray'",
",",
"line_width",
"=",
"1",
")",
":",
"# hoop",
"figure",
".",
"circle",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"radius",
"=",
"7.5",
",",
"fill_alpha",
"=",
"0",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"# backboard",
"figure",
".",
"line",
"(",
"x",
"=",
"range",
"(",
"-",
"30",
",",
"31",
")",
",",
"y",
"=",
"-",
"12.5",
",",
"line_color",
"=",
"line_color",
")",
"# The paint",
"# outerbox",
"figure",
".",
"rect",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"47.5",
",",
"width",
"=",
"160",
",",
"height",
"=",
"190",
",",
"fill_alpha",
"=",
"0",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"# innerbox",
"# left inner box line",
"figure",
".",
"line",
"(",
"x",
"=",
"-",
"60",
",",
"y",
"=",
"np",
".",
"arange",
"(",
"-",
"47.5",
",",
"143.5",
")",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"# right inner box line",
"figure",
".",
"line",
"(",
"x",
"=",
"60",
",",
"y",
"=",
"np",
".",
"arange",
"(",
"-",
"47.5",
",",
"143.5",
")",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"# Restricted Zone",
"figure",
".",
"arc",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"radius",
"=",
"40",
",",
"start_angle",
"=",
"pi",
",",
"end_angle",
"=",
"0",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"# top free throw arc",
"figure",
".",
"arc",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"142.5",
",",
"radius",
"=",
"60",
",",
"start_angle",
"=",
"pi",
",",
"end_angle",
"=",
"0",
",",
"line_color",
"=",
"line_color",
")",
"# bottome free throw arc",
"figure",
".",
"arc",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"142.5",
",",
"radius",
"=",
"60",
",",
"start_angle",
"=",
"0",
",",
"end_angle",
"=",
"pi",
",",
"line_color",
"=",
"line_color",
",",
"line_dash",
"=",
"\"dashed\"",
")",
"# Three point line",
"# corner three point lines",
"figure",
".",
"line",
"(",
"x",
"=",
"-",
"220",
",",
"y",
"=",
"np",
".",
"arange",
"(",
"-",
"47.5",
",",
"92.5",
")",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"figure",
".",
"line",
"(",
"x",
"=",
"220",
",",
"y",
"=",
"np",
".",
"arange",
"(",
"-",
"47.5",
",",
"92.5",
")",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"# # three point arc",
"figure",
".",
"arc",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"0",
",",
"radius",
"=",
"237.5",
",",
"start_angle",
"=",
"3.528",
",",
"end_angle",
"=",
"-",
"0.3863",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"# add center court",
"# outer center arc",
"figure",
".",
"arc",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"422.5",
",",
"radius",
"=",
"60",
",",
"start_angle",
"=",
"0",
",",
"end_angle",
"=",
"pi",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"# inner center arct",
"figure",
".",
"arc",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"422.5",
",",
"radius",
"=",
"20",
",",
"start_angle",
"=",
"0",
",",
"end_angle",
"=",
"pi",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"# outer lines, consistting of half court lines and out of bounds lines",
"figure",
".",
"rect",
"(",
"x",
"=",
"0",
",",
"y",
"=",
"187.5",
",",
"width",
"=",
"500",
",",
"height",
"=",
"470",
",",
"fill_alpha",
"=",
"0",
",",
"line_color",
"=",
"line_color",
",",
"line_width",
"=",
"line_width",
")",
"return",
"figure"
] | Returns a figure with the basketball court lines drawn onto it
This function draws a court based on the x and y-axis values that the NBA
stats API provides for the shot chart data. For example the center of the
hoop is located at the (0,0) coordinate. Twenty-two feet from the left of
the center of the hoop in is represented by the (-220,0) coordinates.
So one foot equals +/-10 units on the x and y-axis.
Parameters
----------
figure : Bokeh figure object
The Axes object to plot the court onto.
line_color : str, optional
The color of the court lines. Can be a a Hex value.
line_width : float, optional
The linewidth the of the court lines in pixels.
Returns
-------
figure : Figure
The Figure object with the court on it. | [
"Returns",
"a",
"figure",
"with",
"the",
"basketball",
"court",
"lines",
"drawn",
"onto",
"it"
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L563-L641 | train |
savvastj/nbashots | nbashots/charts.py | bokeh_shot_chart | def bokeh_shot_chart(data, x="LOC_X", y="LOC_Y", fill_color="#1f77b4",
scatter_size=10, fill_alpha=0.4, line_alpha=0.4,
court_line_color='gray', court_line_width=1,
hover_tool=False, tooltips=None, **kwargs):
# TODO: Settings for hover tooltip
"""
Returns a figure with both FGA and basketball court lines drawn onto it.
This function expects data to be a ColumnDataSource with the x and y values
named "LOC_X" and "LOC_Y". Otherwise specify x and y.
Parameters
----------
data : DataFrame
The DataFrame that contains the shot chart data.
x, y : str, optional
The x and y coordinates of the shots taken.
fill_color : str, optional
The fill color of the shots. Can be a a Hex value.
scatter_size : int, optional
The size of the dots for the scatter plot.
fill_alpha : float, optional
Alpha value for the shots. Must be a floating point value between 0
(transparent) to 1 (opaque).
line_alpha : float, optiona
Alpha value for the outer lines of the plotted shots. Must be a
floating point value between 0 (transparent) to 1 (opaque).
court_line_color : str, optional
The color of the court lines. Can be a a Hex value.
court_line_width : float, optional
The linewidth the of the court lines in pixels.
hover_tool : boolean, optional
If ``True``, creates hover tooltip for the plot.
tooltips : List of tuples, optional
Provides the information for the the hover tooltip.
Returns
-------
fig : Figure
The Figure object with the shot chart plotted on it.
"""
source = ColumnDataSource(data)
fig = figure(width=700, height=658, x_range=[-250, 250],
y_range=[422.5, -47.5], min_border=0, x_axis_type=None,
y_axis_type=None, outline_line_color="black", **kwargs)
fig.scatter(x, y, source=source, size=scatter_size, color=fill_color,
alpha=fill_alpha, line_alpha=line_alpha)
bokeh_draw_court(fig, line_color=court_line_color,
line_width=court_line_width)
if hover_tool:
hover = HoverTool(renderers=[fig.renderers[0]], tooltips=tooltips)
fig.add_tools(hover)
return fig | python | def bokeh_shot_chart(data, x="LOC_X", y="LOC_Y", fill_color="#1f77b4",
scatter_size=10, fill_alpha=0.4, line_alpha=0.4,
court_line_color='gray', court_line_width=1,
hover_tool=False, tooltips=None, **kwargs):
# TODO: Settings for hover tooltip
"""
Returns a figure with both FGA and basketball court lines drawn onto it.
This function expects data to be a ColumnDataSource with the x and y values
named "LOC_X" and "LOC_Y". Otherwise specify x and y.
Parameters
----------
data : DataFrame
The DataFrame that contains the shot chart data.
x, y : str, optional
The x and y coordinates of the shots taken.
fill_color : str, optional
The fill color of the shots. Can be a a Hex value.
scatter_size : int, optional
The size of the dots for the scatter plot.
fill_alpha : float, optional
Alpha value for the shots. Must be a floating point value between 0
(transparent) to 1 (opaque).
line_alpha : float, optiona
Alpha value for the outer lines of the plotted shots. Must be a
floating point value between 0 (transparent) to 1 (opaque).
court_line_color : str, optional
The color of the court lines. Can be a a Hex value.
court_line_width : float, optional
The linewidth the of the court lines in pixels.
hover_tool : boolean, optional
If ``True``, creates hover tooltip for the plot.
tooltips : List of tuples, optional
Provides the information for the the hover tooltip.
Returns
-------
fig : Figure
The Figure object with the shot chart plotted on it.
"""
source = ColumnDataSource(data)
fig = figure(width=700, height=658, x_range=[-250, 250],
y_range=[422.5, -47.5], min_border=0, x_axis_type=None,
y_axis_type=None, outline_line_color="black", **kwargs)
fig.scatter(x, y, source=source, size=scatter_size, color=fill_color,
alpha=fill_alpha, line_alpha=line_alpha)
bokeh_draw_court(fig, line_color=court_line_color,
line_width=court_line_width)
if hover_tool:
hover = HoverTool(renderers=[fig.renderers[0]], tooltips=tooltips)
fig.add_tools(hover)
return fig | [
"def",
"bokeh_shot_chart",
"(",
"data",
",",
"x",
"=",
"\"LOC_X\"",
",",
"y",
"=",
"\"LOC_Y\"",
",",
"fill_color",
"=",
"\"#1f77b4\"",
",",
"scatter_size",
"=",
"10",
",",
"fill_alpha",
"=",
"0.4",
",",
"line_alpha",
"=",
"0.4",
",",
"court_line_color",
"=",
"'gray'",
",",
"court_line_width",
"=",
"1",
",",
"hover_tool",
"=",
"False",
",",
"tooltips",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# TODO: Settings for hover tooltip",
"source",
"=",
"ColumnDataSource",
"(",
"data",
")",
"fig",
"=",
"figure",
"(",
"width",
"=",
"700",
",",
"height",
"=",
"658",
",",
"x_range",
"=",
"[",
"-",
"250",
",",
"250",
"]",
",",
"y_range",
"=",
"[",
"422.5",
",",
"-",
"47.5",
"]",
",",
"min_border",
"=",
"0",
",",
"x_axis_type",
"=",
"None",
",",
"y_axis_type",
"=",
"None",
",",
"outline_line_color",
"=",
"\"black\"",
",",
"*",
"*",
"kwargs",
")",
"fig",
".",
"scatter",
"(",
"x",
",",
"y",
",",
"source",
"=",
"source",
",",
"size",
"=",
"scatter_size",
",",
"color",
"=",
"fill_color",
",",
"alpha",
"=",
"fill_alpha",
",",
"line_alpha",
"=",
"line_alpha",
")",
"bokeh_draw_court",
"(",
"fig",
",",
"line_color",
"=",
"court_line_color",
",",
"line_width",
"=",
"court_line_width",
")",
"if",
"hover_tool",
":",
"hover",
"=",
"HoverTool",
"(",
"renderers",
"=",
"[",
"fig",
".",
"renderers",
"[",
"0",
"]",
"]",
",",
"tooltips",
"=",
"tooltips",
")",
"fig",
".",
"add_tools",
"(",
"hover",
")",
"return",
"fig"
] | Returns a figure with both FGA and basketball court lines drawn onto it.
This function expects data to be a ColumnDataSource with the x and y values
named "LOC_X" and "LOC_Y". Otherwise specify x and y.
Parameters
----------
data : DataFrame
The DataFrame that contains the shot chart data.
x, y : str, optional
The x and y coordinates of the shots taken.
fill_color : str, optional
The fill color of the shots. Can be a a Hex value.
scatter_size : int, optional
The size of the dots for the scatter plot.
fill_alpha : float, optional
Alpha value for the shots. Must be a floating point value between 0
(transparent) to 1 (opaque).
line_alpha : float, optiona
Alpha value for the outer lines of the plotted shots. Must be a
floating point value between 0 (transparent) to 1 (opaque).
court_line_color : str, optional
The color of the court lines. Can be a a Hex value.
court_line_width : float, optional
The linewidth the of the court lines in pixels.
hover_tool : boolean, optional
If ``True``, creates hover tooltip for the plot.
tooltips : List of tuples, optional
Provides the information for the the hover tooltip.
Returns
-------
fig : Figure
The Figure object with the shot chart plotted on it. | [
"Returns",
"a",
"figure",
"with",
"both",
"FGA",
"and",
"basketball",
"court",
"lines",
"drawn",
"onto",
"it",
"."
] | 76ece28d717f10b25eb0fc681b317df6ef6b5157 | https://github.com/savvastj/nbashots/blob/76ece28d717f10b25eb0fc681b317df6ef6b5157/nbashots/charts.py#L644-L704 | train |
vmirly/pyclust | pyclust/_kmedoids.py | _update_centers | def _update_centers(X, membs, n_clusters, distance):
""" Update Cluster Centers:
calculate the mean of feature vectors for each cluster.
distance can be a string or callable.
"""
centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float)
sse = np.empty(shape=n_clusters, dtype=float)
for clust_id in range(n_clusters):
memb_ids = np.where(membs == clust_id)[0]
X_clust = X[memb_ids,:]
dist = np.empty(shape=memb_ids.shape[0], dtype=float)
for i,x in enumerate(X_clust):
dist[i] = np.sum(scipy.spatial.distance.cdist(X_clust, np.array([x]), distance))
inx_min = np.argmin(dist)
centers[clust_id,:] = X_clust[inx_min,:]
sse[clust_id] = dist[inx_min]
return(centers, sse) | python | def _update_centers(X, membs, n_clusters, distance):
""" Update Cluster Centers:
calculate the mean of feature vectors for each cluster.
distance can be a string or callable.
"""
centers = np.empty(shape=(n_clusters, X.shape[1]), dtype=float)
sse = np.empty(shape=n_clusters, dtype=float)
for clust_id in range(n_clusters):
memb_ids = np.where(membs == clust_id)[0]
X_clust = X[memb_ids,:]
dist = np.empty(shape=memb_ids.shape[0], dtype=float)
for i,x in enumerate(X_clust):
dist[i] = np.sum(scipy.spatial.distance.cdist(X_clust, np.array([x]), distance))
inx_min = np.argmin(dist)
centers[clust_id,:] = X_clust[inx_min,:]
sse[clust_id] = dist[inx_min]
return(centers, sse) | [
"def",
"_update_centers",
"(",
"X",
",",
"membs",
",",
"n_clusters",
",",
"distance",
")",
":",
"centers",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"(",
"n_clusters",
",",
"X",
".",
"shape",
"[",
"1",
"]",
")",
",",
"dtype",
"=",
"float",
")",
"sse",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"n_clusters",
",",
"dtype",
"=",
"float",
")",
"for",
"clust_id",
"in",
"range",
"(",
"n_clusters",
")",
":",
"memb_ids",
"=",
"np",
".",
"where",
"(",
"membs",
"==",
"clust_id",
")",
"[",
"0",
"]",
"X_clust",
"=",
"X",
"[",
"memb_ids",
",",
":",
"]",
"dist",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"memb_ids",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"float",
")",
"for",
"i",
",",
"x",
"in",
"enumerate",
"(",
"X_clust",
")",
":",
"dist",
"[",
"i",
"]",
"=",
"np",
".",
"sum",
"(",
"scipy",
".",
"spatial",
".",
"distance",
".",
"cdist",
"(",
"X_clust",
",",
"np",
".",
"array",
"(",
"[",
"x",
"]",
")",
",",
"distance",
")",
")",
"inx_min",
"=",
"np",
".",
"argmin",
"(",
"dist",
")",
"centers",
"[",
"clust_id",
",",
":",
"]",
"=",
"X_clust",
"[",
"inx_min",
",",
":",
"]",
"sse",
"[",
"clust_id",
"]",
"=",
"dist",
"[",
"inx_min",
"]",
"return",
"(",
"centers",
",",
"sse",
")"
] | Update Cluster Centers:
calculate the mean of feature vectors for each cluster.
distance can be a string or callable. | [
"Update",
"Cluster",
"Centers",
":",
"calculate",
"the",
"mean",
"of",
"feature",
"vectors",
"for",
"each",
"cluster",
"."
] | bdb12be4649e70c6c90da2605bc5f4b314e2d07e | https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmedoids.py#L8-L27 | train |
vmirly/pyclust | pyclust/_kmedoids.py | _kmedoids_run | def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng):
""" Run a single trial of k-medoids clustering
on dataset X, and given number of clusters
"""
membs = np.empty(shape=X.shape[0], dtype=int)
centers = kmeans._kmeans_init(X, n_clusters, method='', rng=rng)
sse_last = 9999.9
n_iter = 0
for it in range(1,max_iter):
membs = kmeans._assign_clusters(X, centers)
centers,sse_arr = _update_centers(X, membs, n_clusters, distance)
sse_total = np.sum(sse_arr)
if np.abs(sse_total - sse_last) < tol:
n_iter = it
break
sse_last = sse_total
return(centers, membs, sse_total, sse_arr, n_iter) | python | def _kmedoids_run(X, n_clusters, distance, max_iter, tol, rng):
""" Run a single trial of k-medoids clustering
on dataset X, and given number of clusters
"""
membs = np.empty(shape=X.shape[0], dtype=int)
centers = kmeans._kmeans_init(X, n_clusters, method='', rng=rng)
sse_last = 9999.9
n_iter = 0
for it in range(1,max_iter):
membs = kmeans._assign_clusters(X, centers)
centers,sse_arr = _update_centers(X, membs, n_clusters, distance)
sse_total = np.sum(sse_arr)
if np.abs(sse_total - sse_last) < tol:
n_iter = it
break
sse_last = sse_total
return(centers, membs, sse_total, sse_arr, n_iter) | [
"def",
"_kmedoids_run",
"(",
"X",
",",
"n_clusters",
",",
"distance",
",",
"max_iter",
",",
"tol",
",",
"rng",
")",
":",
"membs",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"int",
")",
"centers",
"=",
"kmeans",
".",
"_kmeans_init",
"(",
"X",
",",
"n_clusters",
",",
"method",
"=",
"''",
",",
"rng",
"=",
"rng",
")",
"sse_last",
"=",
"9999.9",
"n_iter",
"=",
"0",
"for",
"it",
"in",
"range",
"(",
"1",
",",
"max_iter",
")",
":",
"membs",
"=",
"kmeans",
".",
"_assign_clusters",
"(",
"X",
",",
"centers",
")",
"centers",
",",
"sse_arr",
"=",
"_update_centers",
"(",
"X",
",",
"membs",
",",
"n_clusters",
",",
"distance",
")",
"sse_total",
"=",
"np",
".",
"sum",
"(",
"sse_arr",
")",
"if",
"np",
".",
"abs",
"(",
"sse_total",
"-",
"sse_last",
")",
"<",
"tol",
":",
"n_iter",
"=",
"it",
"break",
"sse_last",
"=",
"sse_total",
"return",
"(",
"centers",
",",
"membs",
",",
"sse_total",
",",
"sse_arr",
",",
"n_iter",
")"
] | Run a single trial of k-medoids clustering
on dataset X, and given number of clusters | [
"Run",
"a",
"single",
"trial",
"of",
"k",
"-",
"medoids",
"clustering",
"on",
"dataset",
"X",
"and",
"given",
"number",
"of",
"clusters"
] | bdb12be4649e70c6c90da2605bc5f4b314e2d07e | https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmedoids.py#L31-L49 | train |
vmirly/pyclust | pyclust/_kmedoids.py | KMedoids.fit | def fit(self, X):
""" Apply KMeans Clustering
X: dataset with feature vectors
"""
self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \
_kmedoids(X, self.n_clusters, self.distance, self.max_iter, self.n_trials, self.tol, self.rng) | python | def fit(self, X):
""" Apply KMeans Clustering
X: dataset with feature vectors
"""
self.centers_, self.labels_, self.sse_arr_, self.n_iter_ = \
_kmedoids(X, self.n_clusters, self.distance, self.max_iter, self.n_trials, self.tol, self.rng) | [
"def",
"fit",
"(",
"self",
",",
"X",
")",
":",
"self",
".",
"centers_",
",",
"self",
".",
"labels_",
",",
"self",
".",
"sse_arr_",
",",
"self",
".",
"n_iter_",
"=",
"_kmedoids",
"(",
"X",
",",
"self",
".",
"n_clusters",
",",
"self",
".",
"distance",
",",
"self",
".",
"max_iter",
",",
"self",
".",
"n_trials",
",",
"self",
".",
"tol",
",",
"self",
".",
"rng",
")"
] | Apply KMeans Clustering
X: dataset with feature vectors | [
"Apply",
"KMeans",
"Clustering",
"X",
":",
"dataset",
"with",
"feature",
"vectors"
] | bdb12be4649e70c6c90da2605bc5f4b314e2d07e | https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kmedoids.py#L129-L134 | train |
vmirly/pyclust | pyclust/_kernel_kmeans.py | _kernelized_dist2centers | def _kernelized_dist2centers(K, n_clusters, wmemb, kernel_dist):
""" Computin the distance in transformed feature space to
cluster centers.
K is the kernel gram matrix.
wmemb contains cluster assignment. {0,1}
Assume j is the cluster id:
||phi(x_i) - Phi_center_j|| = K_ii - 2 sum w_jh K_ih +
sum_r sum_s w_jr w_js K_rs
"""
n_samples = K.shape[0]
for j in range(n_clusters):
memb_j = np.where(wmemb == j)[0]
size_j = memb_j.shape[0]
K_sub_j = K[memb_j][:, memb_j]
kernel_dist[:,j] = 1 + np.sum(K_sub_j) /(size_j*size_j)
kernel_dist[:,j] -= 2 * np.sum(K[:, memb_j], axis=1) / size_j
return | python | def _kernelized_dist2centers(K, n_clusters, wmemb, kernel_dist):
""" Computin the distance in transformed feature space to
cluster centers.
K is the kernel gram matrix.
wmemb contains cluster assignment. {0,1}
Assume j is the cluster id:
||phi(x_i) - Phi_center_j|| = K_ii - 2 sum w_jh K_ih +
sum_r sum_s w_jr w_js K_rs
"""
n_samples = K.shape[0]
for j in range(n_clusters):
memb_j = np.where(wmemb == j)[0]
size_j = memb_j.shape[0]
K_sub_j = K[memb_j][:, memb_j]
kernel_dist[:,j] = 1 + np.sum(K_sub_j) /(size_j*size_j)
kernel_dist[:,j] -= 2 * np.sum(K[:, memb_j], axis=1) / size_j
return | [
"def",
"_kernelized_dist2centers",
"(",
"K",
",",
"n_clusters",
",",
"wmemb",
",",
"kernel_dist",
")",
":",
"n_samples",
"=",
"K",
".",
"shape",
"[",
"0",
"]",
"for",
"j",
"in",
"range",
"(",
"n_clusters",
")",
":",
"memb_j",
"=",
"np",
".",
"where",
"(",
"wmemb",
"==",
"j",
")",
"[",
"0",
"]",
"size_j",
"=",
"memb_j",
".",
"shape",
"[",
"0",
"]",
"K_sub_j",
"=",
"K",
"[",
"memb_j",
"]",
"[",
":",
",",
"memb_j",
"]",
"kernel_dist",
"[",
":",
",",
"j",
"]",
"=",
"1",
"+",
"np",
".",
"sum",
"(",
"K_sub_j",
")",
"/",
"(",
"size_j",
"*",
"size_j",
")",
"kernel_dist",
"[",
":",
",",
"j",
"]",
"-=",
"2",
"*",
"np",
".",
"sum",
"(",
"K",
"[",
":",
",",
"memb_j",
"]",
",",
"axis",
"=",
"1",
")",
"/",
"size_j",
"return"
] | Computin the distance in transformed feature space to
cluster centers.
K is the kernel gram matrix.
wmemb contains cluster assignment. {0,1}
Assume j is the cluster id:
||phi(x_i) - Phi_center_j|| = K_ii - 2 sum w_jh K_ih +
sum_r sum_s w_jr w_js K_rs | [
"Computin",
"the",
"distance",
"in",
"transformed",
"feature",
"space",
"to",
"cluster",
"centers",
".",
"K",
"is",
"the",
"kernel",
"gram",
"matrix",
".",
"wmemb",
"contains",
"cluster",
"assignment",
".",
"{",
"0",
"1",
"}"
] | bdb12be4649e70c6c90da2605bc5f4b314e2d07e | https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_kernel_kmeans.py#L29-L51 | train |
vmirly/pyclust | pyclust/_gaussian_mixture_model.py | _init_mixture_params | def _init_mixture_params(X, n_mixtures, init_method):
"""
Initialize mixture density parameters with
equal priors
random means
identity covariance matrices
"""
init_priors = np.ones(shape=n_mixtures, dtype=float) / n_mixtures
if init_method == 'kmeans':
km = _kmeans.KMeans(n_clusters = n_mixtures, n_trials=20)
km.fit(X)
init_means = km.centers_
else:
inx_rand = np.random.choice(X.shape[0], size=n_mixtures)
init_means = X[inx_rand,:]
if np.any(np.isnan(init_means)):
raise ValueError("Init means are NaN! ")
n_features = X.shape[1]
init_covars = np.empty(shape=(n_mixtures, n_features, n_features), dtype=float)
for i in range(n_mixtures):
init_covars[i] = np.eye(n_features)
return(init_priors, init_means, init_covars) | python | def _init_mixture_params(X, n_mixtures, init_method):
"""
Initialize mixture density parameters with
equal priors
random means
identity covariance matrices
"""
init_priors = np.ones(shape=n_mixtures, dtype=float) / n_mixtures
if init_method == 'kmeans':
km = _kmeans.KMeans(n_clusters = n_mixtures, n_trials=20)
km.fit(X)
init_means = km.centers_
else:
inx_rand = np.random.choice(X.shape[0], size=n_mixtures)
init_means = X[inx_rand,:]
if np.any(np.isnan(init_means)):
raise ValueError("Init means are NaN! ")
n_features = X.shape[1]
init_covars = np.empty(shape=(n_mixtures, n_features, n_features), dtype=float)
for i in range(n_mixtures):
init_covars[i] = np.eye(n_features)
return(init_priors, init_means, init_covars) | [
"def",
"_init_mixture_params",
"(",
"X",
",",
"n_mixtures",
",",
"init_method",
")",
":",
"init_priors",
"=",
"np",
".",
"ones",
"(",
"shape",
"=",
"n_mixtures",
",",
"dtype",
"=",
"float",
")",
"/",
"n_mixtures",
"if",
"init_method",
"==",
"'kmeans'",
":",
"km",
"=",
"_kmeans",
".",
"KMeans",
"(",
"n_clusters",
"=",
"n_mixtures",
",",
"n_trials",
"=",
"20",
")",
"km",
".",
"fit",
"(",
"X",
")",
"init_means",
"=",
"km",
".",
"centers_",
"else",
":",
"inx_rand",
"=",
"np",
".",
"random",
".",
"choice",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
",",
"size",
"=",
"n_mixtures",
")",
"init_means",
"=",
"X",
"[",
"inx_rand",
",",
":",
"]",
"if",
"np",
".",
"any",
"(",
"np",
".",
"isnan",
"(",
"init_means",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"Init means are NaN! \"",
")",
"n_features",
"=",
"X",
".",
"shape",
"[",
"1",
"]",
"init_covars",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"(",
"n_mixtures",
",",
"n_features",
",",
"n_features",
")",
",",
"dtype",
"=",
"float",
")",
"for",
"i",
"in",
"range",
"(",
"n_mixtures",
")",
":",
"init_covars",
"[",
"i",
"]",
"=",
"np",
".",
"eye",
"(",
"n_features",
")",
"return",
"(",
"init_priors",
",",
"init_means",
",",
"init_covars",
")"
] | Initialize mixture density parameters with
equal priors
random means
identity covariance matrices | [
"Initialize",
"mixture",
"density",
"parameters",
"with",
"equal",
"priors",
"random",
"means",
"identity",
"covariance",
"matrices"
] | bdb12be4649e70c6c90da2605bc5f4b314e2d07e | https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L8-L35 | train |
vmirly/pyclust | pyclust/_gaussian_mixture_model.py | __log_density_single | def __log_density_single(x, mean, covar):
""" This is just a test function to calculate
the normal density at x given mean and covariance matrix.
Note: this function is not efficient, so
_log_multivariate_density is recommended for use.
"""
n_dim = mean.shape[0]
dx = x - mean
covar_inv = scipy.linalg.inv(covar)
covar_det = scipy.linalg.det(covar)
den = np.dot(np.dot(dx.T, covar_inv), dx) + n_dim*np.log(2*np.pi) + np.log(covar_det)
return(-1/2 * den) | python | def __log_density_single(x, mean, covar):
""" This is just a test function to calculate
the normal density at x given mean and covariance matrix.
Note: this function is not efficient, so
_log_multivariate_density is recommended for use.
"""
n_dim = mean.shape[0]
dx = x - mean
covar_inv = scipy.linalg.inv(covar)
covar_det = scipy.linalg.det(covar)
den = np.dot(np.dot(dx.T, covar_inv), dx) + n_dim*np.log(2*np.pi) + np.log(covar_det)
return(-1/2 * den) | [
"def",
"__log_density_single",
"(",
"x",
",",
"mean",
",",
"covar",
")",
":",
"n_dim",
"=",
"mean",
".",
"shape",
"[",
"0",
"]",
"dx",
"=",
"x",
"-",
"mean",
"covar_inv",
"=",
"scipy",
".",
"linalg",
".",
"inv",
"(",
"covar",
")",
"covar_det",
"=",
"scipy",
".",
"linalg",
".",
"det",
"(",
"covar",
")",
"den",
"=",
"np",
".",
"dot",
"(",
"np",
".",
"dot",
"(",
"dx",
".",
"T",
",",
"covar_inv",
")",
",",
"dx",
")",
"+",
"n_dim",
"*",
"np",
".",
"log",
"(",
"2",
"*",
"np",
".",
"pi",
")",
"+",
"np",
".",
"log",
"(",
"covar_det",
")",
"return",
"(",
"-",
"1",
"/",
"2",
"*",
"den",
")"
] | This is just a test function to calculate
the normal density at x given mean and covariance matrix.
Note: this function is not efficient, so
_log_multivariate_density is recommended for use. | [
"This",
"is",
"just",
"a",
"test",
"function",
"to",
"calculate",
"the",
"normal",
"density",
"at",
"x",
"given",
"mean",
"and",
"covariance",
"matrix",
"."
] | bdb12be4649e70c6c90da2605bc5f4b314e2d07e | https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L39-L54 | train |
vmirly/pyclust | pyclust/_gaussian_mixture_model.py | _log_multivariate_density | def _log_multivariate_density(X, means, covars):
"""
Class conditional density:
P(x | mu, Sigma) = 1/((2pi)^d/2 * |Sigma|^1/2) * exp(-1/2 * (x-mu)^T * Sigma^-1 * (x-mu))
log of class conditional density:
log P(x | mu, Sigma) = -1/2*(d*log(2pi) + log(|Sigma|) + (x-mu)^T * Sigma^-1 * (x-mu))
"""
n_samples, n_dim = X.shape
n_components = means.shape[0]
assert(means.shape[0] == covars.shape[0])
log_proba = np.empty(shape=(n_samples, n_components), dtype=float)
for i, (mu, cov) in enumerate(zip(means, covars)):
try:
cov_chol = scipy.linalg.cholesky(cov, lower=True)
except scipy.linalg.LinAlgError:
try:
cov_chol = scipy.linalg.cholesky(cov + Lambda*np.eye(n_dim), lower=True)
except:
raise ValueError("Triangular Matrix Decomposition not performed!\n")
cov_log_det = 2 * np.sum(np.log(np.diagonal(cov_chol)))
try:
cov_solve = scipy.linalg.solve_triangular(cov_chol, (X - mu).T, lower=True).T
except:
raise ValueError("Solve_triangular not perormed!\n")
log_proba[:, i] = -0.5 * (np.sum(cov_solve ** 2, axis=1) + \
n_dim * np.log(2 * np.pi) + cov_log_det)
return(log_proba) | python | def _log_multivariate_density(X, means, covars):
"""
Class conditional density:
P(x | mu, Sigma) = 1/((2pi)^d/2 * |Sigma|^1/2) * exp(-1/2 * (x-mu)^T * Sigma^-1 * (x-mu))
log of class conditional density:
log P(x | mu, Sigma) = -1/2*(d*log(2pi) + log(|Sigma|) + (x-mu)^T * Sigma^-1 * (x-mu))
"""
n_samples, n_dim = X.shape
n_components = means.shape[0]
assert(means.shape[0] == covars.shape[0])
log_proba = np.empty(shape=(n_samples, n_components), dtype=float)
for i, (mu, cov) in enumerate(zip(means, covars)):
try:
cov_chol = scipy.linalg.cholesky(cov, lower=True)
except scipy.linalg.LinAlgError:
try:
cov_chol = scipy.linalg.cholesky(cov + Lambda*np.eye(n_dim), lower=True)
except:
raise ValueError("Triangular Matrix Decomposition not performed!\n")
cov_log_det = 2 * np.sum(np.log(np.diagonal(cov_chol)))
try:
cov_solve = scipy.linalg.solve_triangular(cov_chol, (X - mu).T, lower=True).T
except:
raise ValueError("Solve_triangular not perormed!\n")
log_proba[:, i] = -0.5 * (np.sum(cov_solve ** 2, axis=1) + \
n_dim * np.log(2 * np.pi) + cov_log_det)
return(log_proba) | [
"def",
"_log_multivariate_density",
"(",
"X",
",",
"means",
",",
"covars",
")",
":",
"n_samples",
",",
"n_dim",
"=",
"X",
".",
"shape",
"n_components",
"=",
"means",
".",
"shape",
"[",
"0",
"]",
"assert",
"(",
"means",
".",
"shape",
"[",
"0",
"]",
"==",
"covars",
".",
"shape",
"[",
"0",
"]",
")",
"log_proba",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"(",
"n_samples",
",",
"n_components",
")",
",",
"dtype",
"=",
"float",
")",
"for",
"i",
",",
"(",
"mu",
",",
"cov",
")",
"in",
"enumerate",
"(",
"zip",
"(",
"means",
",",
"covars",
")",
")",
":",
"try",
":",
"cov_chol",
"=",
"scipy",
".",
"linalg",
".",
"cholesky",
"(",
"cov",
",",
"lower",
"=",
"True",
")",
"except",
"scipy",
".",
"linalg",
".",
"LinAlgError",
":",
"try",
":",
"cov_chol",
"=",
"scipy",
".",
"linalg",
".",
"cholesky",
"(",
"cov",
"+",
"Lambda",
"*",
"np",
".",
"eye",
"(",
"n_dim",
")",
",",
"lower",
"=",
"True",
")",
"except",
":",
"raise",
"ValueError",
"(",
"\"Triangular Matrix Decomposition not performed!\\n\"",
")",
"cov_log_det",
"=",
"2",
"*",
"np",
".",
"sum",
"(",
"np",
".",
"log",
"(",
"np",
".",
"diagonal",
"(",
"cov_chol",
")",
")",
")",
"try",
":",
"cov_solve",
"=",
"scipy",
".",
"linalg",
".",
"solve_triangular",
"(",
"cov_chol",
",",
"(",
"X",
"-",
"mu",
")",
".",
"T",
",",
"lower",
"=",
"True",
")",
".",
"T",
"except",
":",
"raise",
"ValueError",
"(",
"\"Solve_triangular not perormed!\\n\"",
")",
"log_proba",
"[",
":",
",",
"i",
"]",
"=",
"-",
"0.5",
"*",
"(",
"np",
".",
"sum",
"(",
"cov_solve",
"**",
"2",
",",
"axis",
"=",
"1",
")",
"+",
"n_dim",
"*",
"np",
".",
"log",
"(",
"2",
"*",
"np",
".",
"pi",
")",
"+",
"cov_log_det",
")",
"return",
"(",
"log_proba",
")"
] | Class conditional density:
P(x | mu, Sigma) = 1/((2pi)^d/2 * |Sigma|^1/2) * exp(-1/2 * (x-mu)^T * Sigma^-1 * (x-mu))
log of class conditional density:
log P(x | mu, Sigma) = -1/2*(d*log(2pi) + log(|Sigma|) + (x-mu)^T * Sigma^-1 * (x-mu)) | [
"Class",
"conditional",
"density",
":",
"P",
"(",
"x",
"|",
"mu",
"Sigma",
")",
"=",
"1",
"/",
"((",
"2pi",
")",
"^d",
"/",
"2",
"*",
"|Sigma|^1",
"/",
"2",
")",
"*",
"exp",
"(",
"-",
"1",
"/",
"2",
"*",
"(",
"x",
"-",
"mu",
")",
"^T",
"*",
"Sigma^",
"-",
"1",
"*",
"(",
"x",
"-",
"mu",
"))"
] | bdb12be4649e70c6c90da2605bc5f4b314e2d07e | https://github.com/vmirly/pyclust/blob/bdb12be4649e70c6c90da2605bc5f4b314e2d07e/pyclust/_gaussian_mixture_model.py#L57-L90 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.