samplepaths 0.1.0__py3-none-any.whl

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 (55) hide show
  1. samplepaths/__init__.py +96 -0
  2. samplepaths/base/__init__.py +11 -0
  3. samplepaths/base/base_process.py +52 -0
  4. samplepaths/base/base_sequence_process.py +10 -0
  5. samplepaths/base/base_time_process.py +124 -0
  6. samplepaths/continuous/__init__.py +37 -0
  7. samplepaths/continuous/bessel_process.py +87 -0
  8. samplepaths/continuous/brownian_bridge.py +93 -0
  9. samplepaths/continuous/brownian_excursion.py +99 -0
  10. samplepaths/continuous/brownian_meander.py +148 -0
  11. samplepaths/continuous/brownian_motion.py +116 -0
  12. samplepaths/continuous/cauchy_process.py +106 -0
  13. samplepaths/continuous/fractional_brownian_motion.py +58 -0
  14. samplepaths/continuous/gamma_process.py +162 -0
  15. samplepaths/continuous/geometric_brownian_motion.py +166 -0
  16. samplepaths/continuous/inverse_gaussian_process.py +193 -0
  17. samplepaths/continuous/mixed_poisson_process.py +114 -0
  18. samplepaths/continuous/multifractional_brownian_motion.py +128 -0
  19. samplepaths/continuous/poisson_process.py +114 -0
  20. samplepaths/continuous/squared_bessel_process.py +61 -0
  21. samplepaths/continuous/variance_gamma_process.py +156 -0
  22. samplepaths/continuous/wiener_process.py +36 -0
  23. samplepaths/diffusion/__init__.py +17 -0
  24. samplepaths/diffusion/constant_elasticity_variance_process.py +81 -0
  25. samplepaths/diffusion/cox_ingersoll_ross_process.py +70 -0
  26. samplepaths/diffusion/diffusion_process.py +175 -0
  27. samplepaths/diffusion/extended_vasicek_process.py +72 -0
  28. samplepaths/diffusion/ornstein_uhlenbeck_process.py +61 -0
  29. samplepaths/diffusion/vasicek_process.py +66 -0
  30. samplepaths/discrete/__init__.py +17 -0
  31. samplepaths/discrete/bernoulli_process.py +78 -0
  32. samplepaths/discrete/chinese_restaurant_process.py +194 -0
  33. samplepaths/discrete/dirichlet_process.py +97 -0
  34. samplepaths/discrete/markov_chain.py +131 -0
  35. samplepaths/discrete/moran_process.py +122 -0
  36. samplepaths/discrete/random_walk.py +115 -0
  37. samplepaths/noise/__init__.py +25 -0
  38. samplepaths/noise/colored/__init__.py +19 -0
  39. samplepaths/noise/colored/blue_noise.py +32 -0
  40. samplepaths/noise/colored/brownian_noise.py +18 -0
  41. samplepaths/noise/colored/colored_noise.py +120 -0
  42. samplepaths/noise/colored/pink_noise.py +32 -0
  43. samplepaths/noise/colored/red_noise.py +32 -0
  44. samplepaths/noise/colored/violet_noise.py +32 -0
  45. samplepaths/noise/colored/white_noise.py +32 -0
  46. samplepaths/noise/fractional_gaussian_noise.py +219 -0
  47. samplepaths/noise/gaussian_noise.py +78 -0
  48. samplepaths/py.typed +0 -0
  49. samplepaths/random.py +50 -0
  50. samplepaths/utils/__init__.py +48 -0
  51. samplepaths/utils/validation.py +176 -0
  52. samplepaths-0.1.0.dist-info/METADATA +159 -0
  53. samplepaths-0.1.0.dist-info/RECORD +55 -0
  54. samplepaths-0.1.0.dist-info/WHEEL +4 -0
  55. samplepaths-0.1.0.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,32 @@
1
+ """Pink (flicker) noise."""
2
+
3
+ from numpy.random import Generator
4
+
5
+ from .colored_noise import ColoredNoise
6
+
7
+
8
+ class PinkNoise(ColoredNoise):
9
+ r"""Pink (flicker) noise.
10
+
11
+ .. image:: /_static/pink_noise.png
12
+ :scale: 50%
13
+
14
+ Colored noise, or power law noise with spectral density exponent
15
+ :math:`\beta = 1`.
16
+
17
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
18
+ for the process
19
+ :param rng: a custom random number generator
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ *,
25
+ t: float = 1.0,
26
+ rng: Generator | None = None,
27
+ ) -> None:
28
+ super().__init__(
29
+ beta=1,
30
+ t=t,
31
+ rng=rng,
32
+ )
@@ -0,0 +1,32 @@
1
+ """Red (Brownian) noise."""
2
+
3
+ from numpy.random import Generator
4
+
5
+ from .colored_noise import ColoredNoise
6
+
7
+
8
+ class RedNoise(ColoredNoise):
9
+ r"""Red (Brownian) noise.
10
+
11
+ .. image:: /_static/red_noise.png
12
+ :scale: 50%
13
+
14
+ Colored noise, or power law noise with spectral density exponent
15
+ :math:`\beta = 2`.
16
+
17
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
18
+ for the process
19
+ :param rng: a custom random number generator
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ *,
25
+ t: float = 1.0,
26
+ rng: Generator | None = None,
27
+ ) -> None:
28
+ super().__init__(
29
+ beta=2,
30
+ t=t,
31
+ rng=rng,
32
+ )
@@ -0,0 +1,32 @@
1
+ """Violet noise."""
2
+
3
+ from numpy.random import Generator
4
+
5
+ from .colored_noise import ColoredNoise
6
+
7
+
8
+ class VioletNoise(ColoredNoise):
9
+ r"""Violet noise.
10
+
11
+ .. image:: /_static/violet_noise.png
12
+ :scale: 50%
13
+
14
+ Colored noise, or power law noise with spectral density exponent
15
+ :math:`\beta = -2`.
16
+
17
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
18
+ for the process
19
+ :param rng: a custom random number generator
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ *,
25
+ t: float = 1.0,
26
+ rng: Generator | None = None,
27
+ ) -> None:
28
+ super().__init__(
29
+ beta=-2,
30
+ t=t,
31
+ rng=rng,
32
+ )
@@ -0,0 +1,32 @@
1
+ """White noise."""
2
+
3
+ from numpy.random import Generator
4
+
5
+ from .colored_noise import ColoredNoise
6
+
7
+
8
+ class WhiteNoise(ColoredNoise):
9
+ r"""White noise.
10
+
11
+ .. image:: /_static/white_noise.png
12
+ :scale: 50%
13
+
14
+ Colored noise, or power law noise with spectral density exponent
15
+ :math:`\beta = 0`.
16
+
17
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
18
+ for the process
19
+ :param rng: a custom random number generator
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ *,
25
+ t: float = 1.0,
26
+ rng: Generator | None = None,
27
+ ) -> None:
28
+ super().__init__(
29
+ beta=0,
30
+ t=t,
31
+ rng=rng,
32
+ )
@@ -0,0 +1,219 @@
1
+ """Fractional Gaussian noise process."""
2
+
3
+ from functools import lru_cache
4
+ from typing import Literal, override
5
+
6
+ import numpy as np
7
+ import numpy.typing as npt
8
+ from numpy.random import Generator
9
+
10
+ from ..base import BaseTimeProcess
11
+ from ..utils.validation import check_positive_integer
12
+
13
+
14
+ def _fgn_auto_covariance(
15
+ hurst: float,
16
+ n: int,
17
+ ) -> npt.NDArray[np.float64]:
18
+ """Autocovariance function for fGn."""
19
+ ns_2h = np.arange(n + 1) ** (2 * hurst)
20
+ return np.insert(
21
+ (ns_2h[:-2] - 2 * ns_2h[1:-1] + ns_2h[2:]) / 2,
22
+ 0,
23
+ 1,
24
+ )
25
+
26
+
27
+ def _fgn_dh_sqrt_eigen_vals(
28
+ hurst: float,
29
+ n: int,
30
+ ) -> npt.NDArray[np.float64]:
31
+ """Square-roots of normalized circulant matrix eigenvalues for fGn."""
32
+ return np.fft.irfft(_fgn_auto_covariance(hurst, n))[:n] ** (1 / 2)
33
+
34
+
35
+ class FractionalGaussianNoise(BaseTimeProcess):
36
+ """Fractional Gaussian noise process.
37
+
38
+ .. image:: /_static/fractional_gaussian_noise.png
39
+ :scale: 50%
40
+
41
+ Generate sequences of fractional Gaussian noise.
42
+
43
+ Hosking's method:
44
+
45
+ * Hosking, Jonathan RM. "Modeling persistence in hydrological time series
46
+ using fractional differencing." Water resources research 20, no. 12
47
+ (1984): 1898-1908.
48
+
49
+ Davies Harte method:
50
+
51
+ * Davies, Robert B., and D. S. Harte. "Tests for Hurst effect." Biometrika
52
+ 74, no. 1 (1987): 95-101.
53
+
54
+ :param hurst: The Hurst parameter value in :math:`(0,1)`.
55
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
56
+ for the process
57
+ :param rng: a custom random number generator
58
+ """
59
+
60
+ def __init__(
61
+ self,
62
+ *,
63
+ hurst: float = 0.5,
64
+ t: float = 1.0,
65
+ rng: Generator | None = None,
66
+ ):
67
+ super().__init__(t=t, rng=rng)
68
+
69
+ self.hurst = hurst
70
+
71
+ self.__auto_covariance = lru_cache(1)(_fgn_auto_covariance)
72
+ self.__dh_sqrt_eigen_vals = lru_cache(1)(_fgn_dh_sqrt_eigen_vals)
73
+
74
+ def __str__(self) -> str:
75
+ return f"Fractional Gaussian noise with Hurst {self.hurst} on [0, {self.t}]."
76
+
77
+ def __repr__(self) -> str:
78
+ return f"FractionalGaussianNoise(hurst={self.hurst}, t={self.t})"
79
+
80
+ @property
81
+ def hurst(self) -> float:
82
+ """Hurst parameter."""
83
+ return self.__hurst
84
+
85
+ @hurst.setter
86
+ def hurst(self, value: float) -> None:
87
+ if not isinstance(value, (float, np.floating)):
88
+ raise TypeError("Hurst value must be a number on interval (0,1).")
89
+
90
+ if value <= 0 or value >= 1:
91
+ raise ValueError("Hurst value must be in interval (0,1).")
92
+
93
+ self.__hurst = value
94
+
95
+ def _davies_harte(self, n: int) -> npt.NDArray[np.float64]:
96
+ """Generate a fractional Gaussian noise using davies-harte method.
97
+
98
+ Uses Davies and Harte method (exact method) from:
99
+ Davies, Robert B., and D. S. Harte. "Tests for Hurst effect."
100
+ Biometrika 74, no. 1 (1987): 95-101.
101
+ """
102
+ check_positive_integer(n=n, name="Number of increments")
103
+ self.set_times(n)
104
+
105
+ # For scaling to interval [0, T]
106
+ increment = self.t / n
107
+ scale = increment**self.hurst
108
+
109
+ # If H = 0.5 then just generate a standard Brownian motion, otherwise
110
+ # proceed with the Davies Harte method
111
+ if self.hurst == 0.5:
112
+ return self.rng.normal(scale=scale, size=n)
113
+
114
+ # Generate some more fGns to use power-of-two FFTs for speed.
115
+ m = 2 ** (n - 2).bit_length() + 1
116
+ sqrt_eigen_vals = self.__dh_sqrt_eigen_vals(self.hurst, m)
117
+
118
+ # irfft results will be normalized by (2(m-1))**(3/2) but we only
119
+ # want to normalize by 2(m-1)**(1/2).
120
+ scale *= 2 ** (1 / 2) * (m - 1)
121
+
122
+ w = self.rng.normal(scale=scale, size=2 * m).view(complex)
123
+ w[0] = w[0].real * 2 ** (1 / 2)
124
+ w[-1] = w[-1].real * 2 ** (1 / 2)
125
+
126
+ # Resulting z is fft of sequence w.
127
+ return np.fft.irfft(sqrt_eigen_vals * w)[:n]
128
+
129
+ def _hosking(self, n: int) -> npt.NDArray[np.float64]:
130
+ """Generate fractional Gaussian noise using Hosking's method.
131
+
132
+ Method of generation is Hosking's method (exact method) from his paper:
133
+ Hosking, J. R. (1984). Modeling persistence in hydrological time series
134
+ using fractional differencing. Water resources research, 20(12),
135
+ 1898-1908.
136
+
137
+ Hosking's method generates a fractional Gaussian noise (fGn)
138
+ realization. The cumulative sum of this realization gives a fBm.
139
+ """
140
+ check_positive_integer(n=n, name="Number of increments")
141
+ self.set_times(n)
142
+
143
+ # For scaling to interval [0, T]
144
+ increment = self.t / n
145
+ scale = increment**self.hurst
146
+
147
+ gn = self.rng.normal(0.0, 1.0, n)
148
+
149
+ # If H = 0.5 then just generate a standard Brownian motion, otherwise
150
+ # proceed with Hosking's method
151
+ if self.hurst == 0.5:
152
+ fgn = gn
153
+ else:
154
+ # Initializations
155
+ fgn = np.zeros(n)
156
+ phi = np.zeros(n)
157
+ psi = np.zeros(n)
158
+ cov = self.__auto_covariance(self.hurst, n)
159
+
160
+ # First increment from stationary distribution
161
+ fgn[0] = gn[0]
162
+ v = 1
163
+ phi[0] = 0
164
+
165
+ # Generates fgn realization with n increments of size 1
166
+ for i in range(1, n):
167
+ phi[i - 1] = cov[i]
168
+ for j in range(i - 1):
169
+ psi[j] = phi[j]
170
+ phi[i - 1] -= psi[j] * cov[i - j - 1]
171
+ phi[i - 1] /= v
172
+ for j in range(i - 1):
173
+ phi[j] = psi[j] - phi[i - 1] * psi[i - j - 2]
174
+ v *= 1 - phi[i - 1] * phi[i - 1]
175
+ for j in range(i):
176
+ fgn[i] += phi[j] * fgn[i - j - 1]
177
+ fgn[i] += np.sqrt(v) * gn[i]
178
+
179
+ # Scale to interval [0, T]
180
+ fgn *= scale
181
+
182
+ return fgn
183
+
184
+ def _sample_fractional_gaussian_noise(
185
+ self,
186
+ n: int,
187
+ algorithm: Literal["davies-harte", "hosking"],
188
+ ) -> npt.NDArray[np.float64]:
189
+ """Generate a realization of fractional Gaussian noise."""
190
+ if algorithm == "davies-harte":
191
+ return self._davies_harte(n)
192
+
193
+ if algorithm == "hosking":
194
+ return self._hosking(n)
195
+
196
+ raise ValueError("Algorithm must be 'davies-harte' or 'hosking'.")
197
+
198
+ def sample_davies_harte(self, n: int) -> npt.NDArray[np.float64]:
199
+ """Generate a realization using the Davies-Harte method.
200
+
201
+ :param n: the number of increments to generate
202
+ :returns: the realization
203
+ """
204
+ return self._sample_fractional_gaussian_noise(n, "davies-harte")
205
+
206
+ def sample_hosking(self, n: int) -> npt.NDArray[np.float64]:
207
+ """Generate a realization using Hosking's method.
208
+
209
+ :param n: the number of increments to generate
210
+ :returns: the realization
211
+ """
212
+ return self._sample_fractional_gaussian_noise(n, "hosking")
213
+
214
+ @override
215
+ def sample(
216
+ self,
217
+ n: int,
218
+ ) -> npt.NDArray[np.float64]:
219
+ return self.sample_davies_harte(n)
@@ -0,0 +1,78 @@
1
+ """Gaussian noise process."""
2
+
3
+ from typing import override
4
+
5
+ import numpy as np
6
+ import numpy.typing as npt
7
+
8
+ from ..base import BaseTimeProcess
9
+ from ..utils.validation import check_positive_integer, times_to_increments
10
+
11
+
12
+ class GaussianNoise(BaseTimeProcess):
13
+ """Gaussian noise process.
14
+
15
+ .. image:: /_static/gaussian_noise.png
16
+ :scale: 50%
17
+
18
+ Generate a sequence of Gaussian random variables.
19
+
20
+ :param t: the right hand endpoint of the time interval :math:`[0,t]`
21
+ for the process
22
+ :param rng: a custom random number generator
23
+ """
24
+
25
+ def __str__(self) -> str:
26
+ return f"Gaussian noise generator on interval [0, {self.t}]"
27
+
28
+ def __repr__(self) -> str:
29
+ return f"GaussianNoise(t={self.t})"
30
+
31
+ def _sample_gaussian_noise(self, n: int) -> npt.NDArray[np.float64]:
32
+ """Generate a realization of Gaussian noise.
33
+
34
+ Generate a Gaussian noise realization with n increments.
35
+ """
36
+ check_positive_integer(n=n, name="Number of increments")
37
+ self.set_times(n)
38
+
39
+ delta_t = 1.0 * self.t / n
40
+
41
+ noise = self.rng.normal(
42
+ scale=np.sqrt(delta_t),
43
+ size=n,
44
+ )
45
+
46
+ return noise
47
+
48
+ def _sample_gaussian_noise_at(
49
+ self,
50
+ times: npt.NDArray[np.float64],
51
+ ) -> npt.NDArray[np.float64]:
52
+ """Generate Gaussian noise increments at specified times from zero."""
53
+ if times[0] != 0:
54
+ times = np.concatenate(([0], times))
55
+
56
+ increments = times_to_increments(times=times)
57
+
58
+ noise = np.array(
59
+ [
60
+ self.rng.normal(
61
+ scale=np.sqrt(inc),
62
+ )
63
+ for inc in increments
64
+ ]
65
+ )
66
+
67
+ return noise
68
+
69
+ @override
70
+ def sample(self, n: int) -> npt.NDArray[np.float64]:
71
+ return self._sample_gaussian_noise(n)
72
+
73
+ @override
74
+ def sample_at(
75
+ self,
76
+ times: npt.NDArray[np.float64],
77
+ ) -> npt.NDArray[np.float64]:
78
+ return self._sample_gaussian_noise_at(times)
samplepaths/py.typed ADDED
File without changes
samplepaths/random.py ADDED
@@ -0,0 +1,50 @@
1
+ """Default random number generator of the package."""
2
+
3
+ import numpy as np
4
+
5
+ from .utils.validation import is_integer
6
+
7
+ _default_rng = np.random.default_rng()
8
+
9
+ #: The default random number generator
10
+ generator = _default_rng
11
+
12
+
13
+ def use_generator(
14
+ *,
15
+ rng: np.random.Generator | None = None,
16
+ ) -> None:
17
+ """Set the default random number generator.
18
+
19
+ Processes created without an ``rng`` use the default generator.
20
+
21
+ :param rng: the generator to use as the default. If not provided, the
22
+ original default generator of the package is restored.
23
+ :raises TypeError: if ``rng`` is not a :py:class:`numpy.random.Generator`
24
+ """
25
+ global generator
26
+
27
+ if rng is not None and not isinstance(rng, np.random.Generator):
28
+ raise TypeError("rng must be of type np.random.Generator")
29
+
30
+ generator = rng or _default_rng
31
+
32
+
33
+ def seed(
34
+ *,
35
+ value: int,
36
+ ) -> None:
37
+ """Seed the default random number generator.
38
+
39
+ A new default generator is created using
40
+ ``numpy.random.default_rng(value)``.
41
+
42
+ :param value: the seed
43
+ :raises TypeError: if ``value`` is not an integer
44
+ """
45
+ global generator
46
+
47
+ if not is_integer(value):
48
+ raise TypeError("Seed value must be an integer.")
49
+
50
+ generator = np.random.default_rng(seed=value)
@@ -0,0 +1,48 @@
1
+ """Helper functions."""
2
+
3
+ from collections.abc import Callable
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+ import numpy.typing as npt
8
+
9
+
10
+ def generate_times(
11
+ *,
12
+ end: float,
13
+ n: int,
14
+ ) -> npt.NDArray[np.float64]:
15
+ """Generate equally spaced time values on [0, end].
16
+
17
+ :param end: the right hand endpoint of the time interval
18
+ :param n: the number of increments
19
+ :returns: ``n + 1`` time values from zero to ``end``
20
+ """
21
+ return np.linspace(0, end, n + 1)
22
+
23
+
24
+ def single_arg_constant_function(
25
+ *,
26
+ value: float | int,
27
+ ) -> Callable[[Any], float | int]:
28
+ """Create a single argument function which returns a constant value.
29
+
30
+ :param value: the value to return
31
+ :returns: a function of one argument returning ``value``
32
+ """
33
+ return lambda x: value
34
+
35
+
36
+ def ensure_single_arg_constant_function(
37
+ *,
38
+ value: Callable[[Any], float | int] | float | int,
39
+ ) -> Callable[[Any], float | int]:
40
+ """Convert a value to a constant function unless it is callable.
41
+
42
+ :param value: a number or a single argument callable
43
+ :returns: ``value`` if it is callable, otherwise a function of one
44
+ argument returning ``value``
45
+ """
46
+ if not callable(value):
47
+ return single_arg_constant_function(value=value)
48
+ return value
@@ -0,0 +1,176 @@
1
+ """Validation of parameters and arguments."""
2
+
3
+ from collections.abc import Callable
4
+ from inspect import signature
5
+ from numbers import Integral, Real
6
+ from typing import Any
7
+
8
+ import numpy as np
9
+ import numpy.typing as npt
10
+
11
+
12
+ def is_integer(value: object) -> bool:
13
+ """Check whether a value is an integer.
14
+
15
+ Python integers and NumPy integer scalars are integers.
16
+
17
+ :param value: the value to check
18
+ :returns: ``True`` if ``value`` is an integer
19
+ """
20
+ return isinstance(value, Integral)
21
+
22
+
23
+ def is_number(value: object) -> bool:
24
+ """Check whether a value is a real number.
25
+
26
+ Python integers and floats and NumPy integer and floating point scalars
27
+ are real numbers.
28
+
29
+ :param value: the value to check
30
+ :returns: ``True`` if ``value`` is a real number
31
+ """
32
+ return isinstance(value, Real)
33
+
34
+
35
+ def check_positive_integer(
36
+ *,
37
+ n: int,
38
+ name: str = "",
39
+ ) -> None:
40
+ """Ensure that a number is a positive integer.
41
+
42
+ :param n: the number to check
43
+ :param name: the name of the number, used in the error message
44
+ :raises TypeError: if ``n`` is not an integer
45
+ :raises ValueError: if ``n`` is not positive
46
+ """
47
+ if not is_integer(n):
48
+ raise TypeError(f"{name} must be an integer; got {type(n).__name__}.")
49
+ if n <= 0:
50
+ raise ValueError(f"{name} must be positive; got {n}.")
51
+
52
+
53
+ def check_nonnegative_integer(
54
+ *,
55
+ n: int,
56
+ name: str = "",
57
+ ) -> None:
58
+ """Ensure that a number is a nonnegative integer.
59
+
60
+ :param n: the number to check
61
+ :param name: the name of the number, used in the error message
62
+ :raises TypeError: if ``n`` is not an integer
63
+ :raises ValueError: if ``n`` is negative
64
+ """
65
+ if not is_integer(n):
66
+ raise TypeError(f"{name} must be an integer; got {type(n).__name__}.")
67
+ if n < 0:
68
+ raise ValueError(f"{name} must be nonnegative; got {n}.")
69
+
70
+
71
+ def check_numeric(
72
+ *,
73
+ value: float | int,
74
+ name: str = "",
75
+ ) -> None:
76
+ """Ensure that a value is a number.
77
+
78
+ :param value: the value to check
79
+ :param name: the name of the value, used in the error message
80
+ :raises TypeError: if ``value`` is not a number
81
+ """
82
+ if not is_number(value):
83
+ raise TypeError(f"{name} value must be a number; got {type(value).__name__}.")
84
+
85
+
86
+ def check_positive_number(
87
+ *,
88
+ value: float,
89
+ name: str = "",
90
+ ) -> None:
91
+ """Ensure that a value is a positive number.
92
+
93
+ :param value: the value to check
94
+ :param name: the name of the value, used in the error message
95
+ :raises TypeError: if ``value`` is not a number
96
+ :raises ValueError: if ``value`` is not positive
97
+ """
98
+ check_numeric(value=value, name=name)
99
+ if value <= 0:
100
+ raise ValueError(f"{name} value must be positive; got {value}.")
101
+
102
+
103
+ def check_nonnegative_number(
104
+ *,
105
+ value: float,
106
+ name: str = "",
107
+ ) -> None:
108
+ """Ensure that a value is a nonnegative number.
109
+
110
+ :param value: the value to check
111
+ :param name: the name of the value, used in the error message
112
+ :raises TypeError: if ``value`` is not a number
113
+ :raises ValueError: if ``value`` is negative
114
+ """
115
+ check_numeric(value=value, name=name)
116
+ if value < 0:
117
+ raise ValueError(f"{name} value must be nonnegative; got {value}.")
118
+
119
+
120
+ def check_increments(
121
+ *,
122
+ times: npt.NDArray[np.float64] | list[float],
123
+ ) -> npt.NDArray[np.float64]:
124
+ """Ensure that time values are nonnegative and strictly increasing.
125
+
126
+ :param times: the time values to check
127
+ :returns: the increments between consecutive time values
128
+ :raises ValueError: if a time value is negative or the time values are
129
+ not strictly increasing
130
+ """
131
+ increments = np.diff(times)
132
+
133
+ if np.any([t < 0 for t in times]):
134
+ raise ValueError("Times must be nonnegative.")
135
+
136
+ if np.any([t <= 0 for t in increments]):
137
+ raise ValueError("Times must be strictly increasing.")
138
+
139
+ return increments
140
+
141
+
142
+ def times_to_increments(
143
+ *,
144
+ times: npt.NDArray[np.float64] | list[float],
145
+ ) -> npt.NDArray[np.float64]:
146
+ """Convert time values to the increments between them.
147
+
148
+ :param times: nonnegative, strictly increasing time values
149
+ :returns: the increments between consecutive time values
150
+ :raises ValueError: if a time value is negative or the time values are
151
+ not strictly increasing
152
+ """
153
+ return check_increments(times=times)
154
+
155
+
156
+ def check_numeric_or_single_arg_callable(
157
+ *,
158
+ value: Callable[[Any], float | int] | float | int,
159
+ name: str = "",
160
+ ) -> None:
161
+ """Ensure that a value is a number or a single argument callable.
162
+
163
+ :param value: the value to check
164
+ :param name: the name of the value, used in the error message
165
+ :raises TypeError: if ``value`` is neither a number nor a callable
166
+ :raises ValueError: if ``value`` is a callable which does not take
167
+ exactly one argument
168
+ """
169
+ if callable(value) and len(signature(value).parameters) != 1:
170
+ raise ValueError(
171
+ f"{name} callable must have a single argument; got {len(signature(value).parameters)}."
172
+ )
173
+ if not is_number(value) and not callable(value):
174
+ raise TypeError(
175
+ f"{name} must be numeric or a single argument callable; got {type(value).__name__}.",
176
+ )