stats-arrays 0.7.dev8__tar.gz → 1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/CHANGES.md +22 -9
  2. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/PKG-INFO +8 -5
  3. stats_arrays-1.0/docs/distributions/beta_pert.rst +9 -0
  4. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/index.rst +5 -2
  5. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/pyproject.toml +9 -6
  6. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/__init__.py +11 -5
  7. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/dataset_statistics.py +6 -5
  8. stats_arrays-1.0/src/stats_arrays/distributions/__init__.py +35 -0
  9. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/base.py +62 -28
  10. stats_arrays-1.0/src/stats_arrays/distributions/bernoulli.py +50 -0
  11. stats_arrays-1.0/src/stats_arrays/distributions/beta.py +144 -0
  12. stats_arrays-1.0/src/stats_arrays/distributions/beta_pert.py +124 -0
  13. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/discrete_uniform.py +22 -13
  14. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/extreme.py +14 -6
  15. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/gamma.py +14 -6
  16. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/geometric.py +49 -29
  17. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/lognormal.py +19 -11
  18. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/normal.py +19 -11
  19. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/student.py +14 -6
  20. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/undefined.py +14 -6
  21. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/distributions/weibull.py +14 -6
  22. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/random.py +53 -30
  23. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/uncertainty_choices.py +16 -10
  24. stats_arrays-1.0/src/stats_arrays/utils.py +113 -0
  25. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays.egg-info/PKG-INFO +8 -5
  26. stats_arrays-1.0/src/stats_arrays.egg-info/SOURCES.txt +55 -0
  27. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays.egg-info/requires.txt +2 -2
  28. stats_arrays-1.0/tests/test_base.py +274 -0
  29. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/tests/test_lhc.py +102 -8
  30. stats_arrays-1.0/tests/test_mc.py +193 -0
  31. stats_arrays-1.0/tests/test_rng.py +239 -0
  32. stats_arrays-0.7.dev8/stats_arrays/distributions/__init__.py +0 -30
  33. stats_arrays-0.7.dev8/stats_arrays/distributions/bernoulli.py +0 -45
  34. stats_arrays-0.7.dev8/stats_arrays/distributions/beta.py +0 -137
  35. stats_arrays-0.7.dev8/stats_arrays/utils.py +0 -47
  36. stats_arrays-0.7.dev8/stats_arrays.egg-info/SOURCES.txt +0 -53
  37. stats_arrays-0.7.dev8/tests/test_base.py +0 -127
  38. stats_arrays-0.7.dev8/tests/test_mc.py +0 -43
  39. stats_arrays-0.7.dev8/tests/test_rng.py +0 -89
  40. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/CODE_OF_CONDUCT.md +0 -0
  41. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/CONTRIBUTING.md +0 -0
  42. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/LICENSE +0 -0
  43. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/MANIFEST.in +0 -0
  44. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/README.md +0 -0
  45. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/base.rst +0 -0
  46. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/bernoulli.rst +0 -0
  47. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/beta.rst +0 -0
  48. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/discrete-uniform.rst +0 -0
  49. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/extreme.rst +0 -0
  50. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/gamma.rst +0 -0
  51. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/lognormal.rst +0 -0
  52. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/normal.rst +0 -0
  53. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/student.rst +0 -0
  54. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/triangular.rst +0 -0
  55. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/uniform.rst +0 -0
  56. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/distributions/weibull.rst +0 -0
  57. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/lhc.rst +0 -0
  58. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/mcrng.rst +0 -0
  59. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/docs/rng.rst +0 -0
  60. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/setup.cfg +0 -0
  61. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays/errors.py +0 -0
  62. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays.egg-info/dependency_links.txt +0 -0
  63. {stats_arrays-0.7.dev8 → stats_arrays-1.0/src}/stats_arrays.egg-info/top_level.txt +0 -0
  64. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/tests/test_choices.py +0 -0
  65. {stats_arrays-0.7.dev8 → stats_arrays-1.0}/tests/test_conversions.py +0 -0
@@ -1,43 +1,56 @@
1
1
  # stats_arrays Changelog
2
2
 
3
- # 0.7 (2024-08-19)
3
+ # 1.0 (2025-10-27)
4
+
5
+ * Added types
6
+ * **BREAKING CHANGE**: Bernoulli distribution is now correctly strictly limited to outputting 0 or 1; `minimum` and `maximum` are ignored.
7
+ * Fixed triangular distribution `.pdf` method which didn't account for the minimum to maximum range but gave values for a `(0, 1)` range.
8
+ * Added many more tests
9
+
10
+ ## 0.8 (2025-10-23)
11
+
12
+ * [#19: Add Beta PERT distribution](https://github.com/brightway-lca/stats_arrays/pull/19).
13
+ * Moved to a `src` layout.
14
+ * Switch to absolute imports
15
+
16
+ ## 0.7 (2024-08-19)
4
17
 
5
18
  * Moved to `pyproject.toml` packaging and `pytest` tests
6
19
  * Numpy 2.0 compatiblity
7
20
 
8
- ## 0.6.6 (2023-10-18)
21
+ ### 0.6.6 (2023-10-18)
9
22
 
10
23
  * Merged [PR #13](https://github.com/brightway-lca/stats_arrays/pull/13). Move argsort to save on execution time. Thanks @Loisel!
11
24
  * Merged [PR #12](https://github.com/brightway-lca/stats_arrays/pull/12). Update links in readme. Thanks @mfastudillo!
12
25
  * Merged [PR #10](https://github.com/brightway-lca/stats_arrays/pull/10). Fix flaky test on distributions::extreme.py, distributions::gama.py, and distributions::student.py. Thanks @lonly7star!
13
26
 
14
- ## 0.6.5 (2021-05-06)
27
+ ### 0.6.5 (2021-05-06)
15
28
 
16
29
  * Updates for changes in Numpy API
17
30
 
18
- ## 0.6.4 (2020-01-31)
31
+ ### 0.6.4 (2020-01-31)
19
32
 
20
33
  * Merged [PR #5](https://bitbucket.org/cmutel/stats_arrays/pull-requests/5/use-meanround-0-instead-of-round-mean/diff), fix rounding function.
21
34
 
22
- ## 0.6.3 (2019-11-29)
35
+ ### 0.6.3 (2019-11-29)
23
36
 
24
37
  * Improve speed of lognormal CDF and PPF under common conditions
25
38
 
26
- ## 0.6.2 (2019-11-13)
39
+ ### 0.6.2 (2019-11-13)
27
40
 
28
41
  * Restore Python 2.7 compatibility
29
42
 
30
- ## 0.6.1 (2019-07-29)
43
+ ### 0.6.1 (2019-07-29)
31
44
 
32
45
  * Several bug fixes from Daniel de Koning
33
46
  * Start improvement of beta distribution
34
47
 
35
- # 0.6 (2019-05-19)
48
+ ## 0.6 (2019-05-19)
36
49
 
37
50
  * Allow `MCRandomNumberGenerator` to generate multiple samples at once
38
51
  * Move tests to pytest
39
52
  * Add tests for MCRNG
40
53
 
41
- ## 0.5.1 (2019-05-11)
54
+ ### 0.5.1 (2019-05-11)
42
55
 
43
56
  * Import from `collections.abc` when possible, for Python 3.8 support.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: stats_arrays
3
- Version: 0.7.dev8
3
+ Version: 1.0
4
4
  Summary: Standard NumPy array interface for defining uncertain parameters
5
5
  Author-email: Chris Mutel <cmutel@gmail.com>
6
6
  Maintainer-email: Chris Mutel <cmutel@gmail.com>
@@ -14,14 +14,16 @@ Classifier: Programming Language :: Python :: 3.9
14
14
  Classifier: Programming Language :: Python :: 3.10
15
15
  Classifier: Programming Language :: Python :: 3.11
16
16
  Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
17
19
  Classifier: Natural Language :: English
18
20
  Classifier: Operating System :: OS Independent
19
21
  Classifier: Topic :: Scientific/Engineering
20
- Requires-Python: >=3.6
22
+ Requires-Python: >=3.9
21
23
  Description-Content-Type: text/markdown
22
24
  License-File: LICENSE
23
- Requires-Dist: numpy>=1.6.0
24
- Requires-Dist: scipy>=1.1.0
25
+ Requires-Dist: numpy
26
+ Requires-Dist: scipy
25
27
  Provides-Extra: testing
26
28
  Requires-Dist: stats_arrays; extra == "testing"
27
29
  Requires-Dist: pytest; extra == "testing"
@@ -35,6 +37,7 @@ Requires-Dist: pytest; extra == "dev"
35
37
  Requires-Dist: pytest-cov; extra == "dev"
36
38
  Requires-Dist: pytest-randomly; extra == "dev"
37
39
  Requires-Dist: setuptools; extra == "dev"
40
+ Dynamic: license-file
38
41
 
39
42
  The `stats_arrays` package provides a standard NumPy array interface for defining uncertain parameters used in models, and classes for Monte Carlo sampling. It also plays well with others.
40
43
 
@@ -0,0 +1,9 @@
1
+ .. _beta_pert:
2
+
3
+ Beta PERT
4
+ *********
5
+
6
+ .. autoclass:: stats_arrays.BetaPERTUncertainty
7
+ :members:
8
+ :inherited-members:
9
+ :show-inheritance:
@@ -118,13 +118,14 @@ No uncertainty 1 **static value**
118
118
  :ref:`normal` [#]_ 3 :math:`\boldsymbol{\mu}` :math:`\boldsymbol{\sigma}` *lower bound* *upper bound*
119
119
  :ref:`uniform` [#]_ 4 *minimum* [#]_ **maximum**
120
120
  :ref:`triangular` [#]_ 5 *mode* [#]_ *minimum* [#]_ **maximum**
121
- :ref:`bernoulli` [#]_ 6 **p** *lower bound* *upper bound*
121
+ :ref:`bernoulli` [#]_ 6 **p**
122
122
  :ref:`discreteu` [#]_ 7 *minimum* [#]_ **upper bound** [#]_
123
123
  :ref:`weibull` [#]_ 8 *offset* [#]_ :math:`\boldsymbol{\lambda}` :math:`\boldsymbol{k}`
124
124
  :ref:`gamma` [#]_ 9 *offset* [#]_ :math:`\boldsymbol{\theta}` :math:`\boldsymbol{k}`
125
125
  :ref:`beta` [#]_ 10 :math:`\boldsymbol{\alpha}` :math:`\boldsymbol{\beta}` *lower bound* *upper bound*
126
126
  :ref:`extreme` [#]_ 11 :math:`\boldsymbol{\mu}` :math:`\boldsymbol{\sigma}` :math:`\boldsymbol{\xi}`
127
127
  :ref:`students` [#]_ 12 *median* *scale* :math:`\boldsymbol{\nu}`
128
+ :ref:`beta_pert` [#]_ 13 **mean** *lambda* **minimum** **maximum**
128
129
  ======================= === =========================== ============================= =========================== =============== ===============
129
130
 
130
131
  Items in **bold** are required, items in *italics* are optional.
@@ -147,12 +148,13 @@ Items in **bold** are required, items in *italics* are optional.
147
148
  .. [#] `Beta distribution <https://en.wikipedia.org/wiki/Beta_distribution>`_
148
149
  .. [#] `Extreme value distribution <https://en.wikipedia.org/wiki/Generalized_extreme_value_distribution>`_
149
150
  .. [#] `Student's T distribution <https://en.wikipedia.org/wiki/Student%27s_t-distribution>`_
151
+ .. [#] `Beta PERT distribution <https://en.wikipedia.org/wiki/PERT_distribution>`_
150
152
 
151
153
  Unused columns can be given any value, but it is recommended that they are set to ``np.nan``.
152
154
 
153
155
  .. warning::
154
156
 
155
- Unused optional columns **must** be set to ``np.nan`` to avoid unexpected behaviour!
157
+ Optional columns without data **must** be set to ``np.nan`` to avoid unexpected behaviour!
156
158
 
157
159
  Extending parameter arrays
158
160
  --------------------------
@@ -180,6 +182,7 @@ Probability distributions
180
182
  distributions/student
181
183
  distributions/gamma
182
184
  distributions/weibull
185
+ distributions/beta_pert
183
186
 
184
187
  Random number generators
185
188
  ------------------------
@@ -23,16 +23,16 @@ classifiers = [
23
23
  "Programming Language :: Python :: 3.10",
24
24
  "Programming Language :: Python :: 3.11",
25
25
  "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Programming Language :: Python :: 3.14",
26
28
  "Natural Language :: English",
27
29
  "Operating System :: OS Independent",
28
30
  "Topic :: Scientific/Engineering"
29
31
  ]
30
- requires-python = ">=3.6"
32
+ requires-python = ">=3.9"
31
33
  dependencies = [
32
- # dependencies as strings with quotes, e.g. "foo"
33
- # You can add version requirements like "foo>2.0"
34
- "numpy>=1.6.0",
35
- "scipy>=1.1.0",
34
+ "numpy",
35
+ "scipy",
36
36
  ]
37
37
 
38
38
  [project.urls]
@@ -62,6 +62,7 @@ dev = [
62
62
  [tool.setuptools]
63
63
  license-files = ["LICENSE"]
64
64
  include-package-data = true
65
+ package-dir = {"" = "src"}
65
66
  packages = [
66
67
  "stats_arrays",
67
68
  "stats_arrays.distributions",
@@ -77,7 +78,8 @@ norecursedirs = [
77
78
  "build",
78
79
  ".tox"
79
80
  ]
80
- testpaths = ["tests/*.py", "tests/distributions/*.py"]
81
+ testpaths = ["tests"]
82
+ pythonpath = ["src"]
81
83
 
82
84
  [tool.flake8]
83
85
  # Some sane defaults for the code style checker flake8
@@ -91,6 +93,7 @@ exclude = [
91
93
  "dist",
92
94
  ".eggs",
93
95
  "docs/conf.py",
96
+ "src/stats_arrays/__pycache__",
94
97
  ]
95
98
 
96
99
  [tool.black]
@@ -1,8 +1,9 @@
1
- __version__ = "0.7.dev8"
1
+ __version__ = "1.0"
2
2
 
3
3
  __all__ = (
4
4
  "BernoulliUncertainty",
5
5
  "BetaUncertainty",
6
+ "BetaPERTUncertainty",
6
7
  "BoundedUncertaintyBase",
7
8
  "DiscreteUniform",
8
9
  "GammaUncertainty",
@@ -30,8 +31,9 @@ __all__ = (
30
31
  "WeibullUncertainty",
31
32
  )
32
33
 
33
- from .distributions import (
34
+ from stats_arrays.distributions import (
34
35
  BernoulliUncertainty,
36
+ BetaPERTUncertainty,
35
37
  BetaUncertainty,
36
38
  BoundedUncertaintyBase,
37
39
  DiscreteUniform,
@@ -47,7 +49,7 @@ from .distributions import (
47
49
  UniformUncertainty,
48
50
  WeibullUncertainty,
49
51
  )
50
- from .errors import (
52
+ from stats_arrays.errors import (
51
53
  ImproperBoundsError,
52
54
  InvalidParamsError,
53
55
  MaximumIterationsError,
@@ -57,5 +59,9 @@ from .errors import (
57
59
  UnknownUncertaintyType,
58
60
  UnreasonableBoundsError,
59
61
  )
60
- from .random import LatinHypercubeRNG, MCRandomNumberGenerator, RandomNumberGenerator
61
- from .uncertainty_choices import uncertainty_choices
62
+ from stats_arrays.random import (
63
+ LatinHypercubeRNG,
64
+ MCRandomNumberGenerator,
65
+ RandomNumberGenerator,
66
+ )
67
+ from stats_arrays.uncertainty_choices import uncertainty_choices
@@ -1,3 +1,6 @@
1
+ import numpy.typing as npt
2
+ from numpy import array
3
+
1
4
  # Weighted formulas from
2
5
  # http://en.wikipedia.org/wiki/Weighted_mean#Weighted_sample_variance
3
6
 
@@ -5,25 +8,23 @@
5
8
  # http://pygsl.sourceforge.net/reference/pygsl/node36.html
6
9
 
7
10
 
8
- def weighted_mean(values, weights):
11
+ def weighted_mean(values: npt.NDArray, weights: npt.NDArray) -> npt.NDArray:
9
12
  assert values.shape == weights.shape
10
13
  return (values * weights).sum() / weights.sum()
11
14
 
12
15
 
13
- def weighted_sample_variance(values, weights):
16
+ def weighted_sample_variance(values: npt.NDArray, weights: npt.NDArray) -> npt.NDArray:
14
17
  assert values.shape == weights.shape
15
18
  return (
16
19
  (weights * values**2).sum() * weights.sum() - ((weights * values).sum()) ** 2
17
20
  ) / ((weights.sum()) ** 2 - (weights**2).sum())
18
21
 
19
22
 
20
- def weighted_sample_stddev(values, weights):
23
+ def weighted_sample_stddev(values: npt.NDArray, weights: npt.NDArray) -> npt.NDArray:
21
24
  return weighted_sample_variance(values, weights) ** 0.5
22
25
 
23
26
 
24
27
  def test():
25
- from numpy import array
26
-
27
28
  a = array((1, 2, 3, 4))
28
29
  print(a**2)
29
30
  b = array((0.5, 0.5, 1, 1))
@@ -0,0 +1,35 @@
1
+ __all__ = (
2
+ "BernoulliUncertainty",
3
+ "BetaPERTUncertainty",
4
+ "BetaUncertainty",
5
+ "BoundedUncertaintyBase",
6
+ "DiscreteUniform",
7
+ "GammaUncertainty",
8
+ "GeneralizedExtremeValueUncertainty",
9
+ "LognormalUncertainty",
10
+ "NormalUncertainty",
11
+ "NoUncertainty",
12
+ "StudentsTUncertainty",
13
+ "TriangularUncertainty",
14
+ "UncertaintyBase",
15
+ "UndefinedUncertainty",
16
+ "UniformUncertainty",
17
+ "WeibullUncertainty",
18
+ )
19
+
20
+ from stats_arrays.distributions.base import BoundedUncertaintyBase, UncertaintyBase
21
+ from stats_arrays.distributions.bernoulli import BernoulliUncertainty
22
+ from stats_arrays.distributions.beta import BetaUncertainty
23
+ from stats_arrays.distributions.beta_pert import BetaPERTUncertainty
24
+ from stats_arrays.distributions.discrete_uniform import DiscreteUniform
25
+ from stats_arrays.distributions.extreme import GeneralizedExtremeValueUncertainty
26
+ from stats_arrays.distributions.gamma import GammaUncertainty
27
+ from stats_arrays.distributions.geometric import (
28
+ TriangularUncertainty,
29
+ UniformUncertainty,
30
+ )
31
+ from stats_arrays.distributions.lognormal import LognormalUncertainty
32
+ from stats_arrays.distributions.normal import NormalUncertainty
33
+ from stats_arrays.distributions.student import StudentsTUncertainty
34
+ from stats_arrays.distributions.undefined import NoUncertainty, UndefinedUncertainty
35
+ from stats_arrays.distributions.weibull import WeibullUncertainty
@@ -1,14 +1,21 @@
1
- from __future__ import division
1
+ from typing import Optional, Tuple
2
2
 
3
3
  import numpy as np
4
+ import numpy.typing as npt
4
5
 
5
- from ..errors import (
6
+ from stats_arrays.errors import (
6
7
  ImproperBoundsError,
7
8
  InvalidParamsError,
8
9
  MaximumIterationsError,
9
10
  UnreasonableBoundsError,
10
11
  )
11
- from ..utils import construct_params_array, one_row_params_array
12
+ from stats_arrays.utils import (
13
+ ParamsArray,
14
+ construct_params_array,
15
+ one_row_params_array,
16
+ rescale_to_unitary_interval,
17
+ rescale_vector_to_params,
18
+ )
12
19
 
13
20
  np.seterr(invalid="ignore")
14
21
 
@@ -26,12 +33,13 @@ class UncertaintyBase:
26
33
 
27
34
  """
28
35
 
36
+ id = None
29
37
  default_number_points_in_pdf = 200
30
38
  standard_deviations_in_default_range = 2.2
31
39
 
32
40
  # Conversion utilities ###
33
41
  @classmethod
34
- def from_tuples(cls, *data):
42
+ def from_tuples(cls, *data: tuple) -> ParamsArray:
35
43
  """
36
44
  Construct a :ref:`hpa` from parameter tuples.
37
45
 
@@ -72,11 +80,16 @@ class UncertaintyBase:
72
80
  """
73
81
  params = construct_params_array(len(data), True)
74
82
  for index, row in enumerate(data):
83
+ # Check if uncertainty_type is valid (must be < 256)
84
+ uncertainty_type = row[6] # uncertainty_type is the 7th element (index 6)
85
+ if uncertainty_type >= 256:
86
+ raise InvalidParamsError("`uncertainty_type` must be less than 256")
75
87
  params[index] = row
88
+
76
89
  return params
77
90
 
78
91
  @classmethod
79
- def from_dicts(cls, *dicts):
92
+ def from_dicts(cls, *dicts: dict) -> ParamsArray:
80
93
  """
81
94
  Construct a :ref:`hpa` from parameter dictionaries.
82
95
 
@@ -119,12 +132,16 @@ class UncertaintyBase:
119
132
  data = [obj.get(key, default) for key, default in LABELS]
120
133
  if "uncertainty type" in obj and "uncertainty_type" not in obj:
121
134
  data[-1] = obj["uncertainty type"]
135
+ # Check if uncertainty_type is valid (must be < 256)
136
+ uncertainty_type = data[6] # uncertainty_type is the last element
137
+ if uncertainty_type >= 256:
138
+ raise InvalidParamsError("`uncertainty_type` must be less than 256")
122
139
  params[index] = tuple(data)
123
140
  return params
124
141
 
125
142
  # Utility methods ###
126
143
  @classmethod
127
- def validate(cls, params):
144
+ def validate(cls, params: ParamsArray) -> None:
128
145
  """
129
146
  Validate the parameter array for uncertainty distribution.
130
147
 
@@ -141,7 +158,7 @@ class UncertaintyBase:
141
158
  raise ImproperBoundsError
142
159
 
143
160
  @classmethod
144
- def check_2d_inputs(cls, params, vector):
161
+ def check_2d_inputs(cls, params: ParamsArray, vector: npt.NDArray) -> npt.NDArray:
145
162
  """Convert ``vector`` to 2 dimensions if not already, and raise ``stats_arrays.InvalidParamsError`` if ``vector`` and ``params`` dimensions don't match."""
146
163
  if len(vector.shape) == 1:
147
164
  # Slices from structured arrays can't always be resized
@@ -157,7 +174,9 @@ class UncertaintyBase:
157
174
 
158
175
  @classmethod
159
176
  @one_row_params_array
160
- def check_bounds_reasonableness(cls, params, threshold=0.1):
177
+ def check_bounds_reasonableness(
178
+ cls, params: ParamsArray, threshold: float = 0.1
179
+ ) -> None:
161
180
  """
162
181
  Test if there is at least a ``threshold`` percent chance of generating random numbers within the provided bounds.
163
182
 
@@ -182,9 +201,13 @@ class UncertaintyBase:
182
201
  # Used for Monte Carlo ###
183
202
  @classmethod
184
203
  def bounded_random_variables(
185
- cls, params, size, seeded_random=None, maximum_iterations=50
186
- ):
187
- """Generate random variables repeatedly until all varaibles are within the bounds of each distribution. Raise MaximumIterationsError if this takes more that `maximum_iterations`. Uses `random_variables` for random number generation.
204
+ cls,
205
+ params: ParamsArray,
206
+ size: int,
207
+ seeded_random: Optional[np.random.RandomState] = None,
208
+ maximum_iterations: int = 50,
209
+ ) -> npt.NDArray:
210
+ """Generate random variables repeatedly until all variables are within the bounds of each distribution. Raise MaximumIterationsError if this takes more that `maximum_iterations`. Uses `random_variables` for random number generation.
188
211
 
189
212
  .. rubric:: Inputs
190
213
 
@@ -228,7 +251,12 @@ class UncertaintyBase:
228
251
  return data
229
252
 
230
253
  @classmethod
231
- def random_variables(cls, params, size, seeded_random=None):
254
+ def random_variables(
255
+ cls,
256
+ params: ParamsArray,
257
+ size: int,
258
+ seeded_random: Optional[np.random.RandomState] = None,
259
+ ) -> npt.NDArray:
232
260
  """Generate random variables for the given uncertainty. Should **not check** to ensure that random samples are with the (minimum, maximum bounds). Bounds checking is provided by the `bounded_random_variables` class method.
233
261
 
234
262
  .. rubric:: Inputs
@@ -242,9 +270,8 @@ class UncertaintyBase:
242
270
  An array of random values, with dimensions `params` rows by `size`."""
243
271
  raise NotImplementedError
244
272
 
245
- # Used for Latin Hypercube Monte Carlo ###
246
273
  @classmethod
247
- def ppf(cls, params, percentages):
274
+ def ppf(cls, params: ParamsArray, percentages: npt.NDArray) -> npt.NDArray:
248
275
  """Return percent point function (inverse of CDF, e.g. value in distribution where x percent of the distribution is less than value) for various distributions.
249
276
 
250
277
  .. rubric:: Inputs
@@ -256,11 +283,10 @@ class UncertaintyBase:
256
283
 
257
284
  An array of values within the ranges of each distribtion, with `params` rows and `percentages` columns.
258
285
  """
259
- percentages = cls.check_ppf_inputs(params, percentages)
260
286
  raise NotImplementedError
261
287
 
262
288
  @classmethod
263
- def cdf(cls, params, vector):
289
+ def cdf(cls, params: ParamsArray, vector: npt.NDArray) -> npt.NDArray:
264
290
  """Used when a distribution is bounded, to determine where to begin or end the percentages used in calculating hypercube sampling space.
265
291
 
266
292
  .. rubric:: Inputs
@@ -272,13 +298,12 @@ class UncertaintyBase:
272
298
 
273
299
  An array of cumulative densities, bounded on (0,1), with `params` rows and `vector` columns.
274
300
  """
275
- vector = cls.check_cdf_inputs(params, vector)
276
301
  raise NotImplementedError
277
302
 
278
303
  # Used for graphing ###
279
304
  @classmethod
280
305
  @one_row_params_array
281
- def statistics(cls, params):
306
+ def statistics(cls, params: ParamsArray) -> dict:
282
307
  """Build a dictionary of mean, mode, median, and 95% confidence interval upper and lower values.
283
308
 
284
309
  .. rubric:: Inputs
@@ -299,7 +324,7 @@ class UncertaintyBase:
299
324
 
300
325
  @classmethod
301
326
  @one_row_params_array
302
- def pdf(cls, params, xs=None):
327
+ def pdf(cls, params: ParamsArray, xs: Optional[npt.NDArray] = None) -> npt.NDArray:
303
328
  """Provide a standard interface to calculate the probability distribution function of a uncertainty distribution. Default is `cls.default_number_points_in_pdf` points between min to max range if bounds are present, or `cls.standard_deviations_in_default_range` standard distributions.
304
329
 
305
330
  .. rubric:: Inputs
@@ -320,7 +345,7 @@ class BoundedUncertaintyBase(UncertaintyBase):
320
345
  """An uncertainty distribution where minimum and maximum bounds are required. No bounds checking is required for these distributions, as bounds are integral inputs into the sample space generator."""
321
346
 
322
347
  @classmethod
323
- def validate(cls, params):
348
+ def validate(cls, params: ParamsArray) -> None:
324
349
  super(BoundedUncertaintyBase, cls).validate(params)
325
350
  if np.isnan(params["minimum"]).sum() or np.isnan(params["maximum"]).sum():
326
351
  raise ImproperBoundsError(
@@ -328,21 +353,30 @@ class BoundedUncertaintyBase(UncertaintyBase):
328
353
  )
329
354
 
330
355
  @classmethod
331
- def rescale(cls, params):
332
- """Rescale params to a (0,1) interval. Return adjusted_means and scale. Needed because SciPy assumes a (0,1) interval for many distributions."""
333
- scale = params["maximum"] - params["minimum"]
334
- adjusted_means = (params["loc"] - params["minimum"]) / scale
335
- return adjusted_means, scale
356
+ def rescale_to_unitary_interval(
357
+ cls, params: ParamsArray
358
+ ) -> Tuple[npt.NDArray, npt.NDArray]:
359
+ return rescale_to_unitary_interval(params=params)
360
+
361
+ @classmethod
362
+ def rescale_vector_to_params(
363
+ cls, params: npt.NDArray, vector: npt.NDArray
364
+ ) -> npt.NDArray:
365
+ return rescale_vector_to_params(params=params, vector=vector)
336
366
 
337
367
  @classmethod
338
368
  def bounded_random_variables(
339
- cls, params, size, seeded_random=None, maximum_iterations=None
340
- ):
369
+ cls,
370
+ params: ParamsArray,
371
+ size: int,
372
+ seeded_random: Optional[np.random.RandomState] = None,
373
+ maximum_iterations: Optional[int] = None,
374
+ ) -> npt.NDArray:
341
375
  """No bounds checking because the bounds do not exclude any of the distribution."""
342
376
  return cls.random_variables(params, size, seeded_random)
343
377
 
344
378
  @classmethod
345
379
  @one_row_params_array
346
- def check_bounds_reasonableness(cls, params):
380
+ def check_bounds_reasonableness(cls, params: ParamsArray) -> None:
347
381
  """Always true because the bounds do not exclude any of the distribution."""
348
382
  return
@@ -0,0 +1,50 @@
1
+ from typing import Optional
2
+
3
+ import numpy as np
4
+ import numpy.typing as npt
5
+
6
+ from stats_arrays.distributions.base import UncertaintyBase
7
+ from stats_arrays.errors import InvalidParamsError
8
+ from stats_arrays.utils import ParamsArray
9
+
10
+
11
+ class BernoulliUncertainty(UncertaintyBase):
12
+ id = 6
13
+ description = "Bernoulli uncertainty"
14
+
15
+ @classmethod
16
+ def validate(cls, params: ParamsArray) -> None:
17
+ """Validate that loc is between 0 and 1 (inclusive)."""
18
+ if (params["loc"] < 0).sum() or (params["loc"] > 1).sum():
19
+ raise InvalidParamsError(
20
+ "Bernoulli uncertainty requires loc values between 0 and 1 (inclusive)."
21
+ )
22
+
23
+ @classmethod
24
+ def random_variables(
25
+ cls,
26
+ params: ParamsArray,
27
+ size: int,
28
+ seeded_random: Optional[np.random.RandomState] = None,
29
+ ) -> npt.NDArray:
30
+ if not seeded_random:
31
+ seeded_random = np.random.RandomState()
32
+ data = np.zeros((params.shape[0], size))
33
+ mask = (
34
+ seeded_random.random_sample(size * params.shape[0]).reshape(
35
+ (params.shape[0], size)
36
+ )
37
+ <= params["loc"]
38
+ )
39
+ data[mask] = 1
40
+ return data
41
+
42
+ @classmethod
43
+ def cdf(cls, params: ParamsArray, vector: npt.NDArray) -> npt.NDArray:
44
+ vector = cls.check_2d_inputs(params, vector)
45
+ return (vector <= params["loc"].reshape(-1, 1)) * 1.0
46
+
47
+ @classmethod
48
+ def ppf(cls, params: ParamsArray, percentages: npt.NDArray) -> npt.NDArray:
49
+ percentages = cls.check_2d_inputs(params, percentages)
50
+ return (percentages <= params["loc"].reshape(-1, 1)) * 1.0