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.
- samplepaths/__init__.py +96 -0
- samplepaths/base/__init__.py +11 -0
- samplepaths/base/base_process.py +52 -0
- samplepaths/base/base_sequence_process.py +10 -0
- samplepaths/base/base_time_process.py +124 -0
- samplepaths/continuous/__init__.py +37 -0
- samplepaths/continuous/bessel_process.py +87 -0
- samplepaths/continuous/brownian_bridge.py +93 -0
- samplepaths/continuous/brownian_excursion.py +99 -0
- samplepaths/continuous/brownian_meander.py +148 -0
- samplepaths/continuous/brownian_motion.py +116 -0
- samplepaths/continuous/cauchy_process.py +106 -0
- samplepaths/continuous/fractional_brownian_motion.py +58 -0
- samplepaths/continuous/gamma_process.py +162 -0
- samplepaths/continuous/geometric_brownian_motion.py +166 -0
- samplepaths/continuous/inverse_gaussian_process.py +193 -0
- samplepaths/continuous/mixed_poisson_process.py +114 -0
- samplepaths/continuous/multifractional_brownian_motion.py +128 -0
- samplepaths/continuous/poisson_process.py +114 -0
- samplepaths/continuous/squared_bessel_process.py +61 -0
- samplepaths/continuous/variance_gamma_process.py +156 -0
- samplepaths/continuous/wiener_process.py +36 -0
- samplepaths/diffusion/__init__.py +17 -0
- samplepaths/diffusion/constant_elasticity_variance_process.py +81 -0
- samplepaths/diffusion/cox_ingersoll_ross_process.py +70 -0
- samplepaths/diffusion/diffusion_process.py +175 -0
- samplepaths/diffusion/extended_vasicek_process.py +72 -0
- samplepaths/diffusion/ornstein_uhlenbeck_process.py +61 -0
- samplepaths/diffusion/vasicek_process.py +66 -0
- samplepaths/discrete/__init__.py +17 -0
- samplepaths/discrete/bernoulli_process.py +78 -0
- samplepaths/discrete/chinese_restaurant_process.py +194 -0
- samplepaths/discrete/dirichlet_process.py +97 -0
- samplepaths/discrete/markov_chain.py +131 -0
- samplepaths/discrete/moran_process.py +122 -0
- samplepaths/discrete/random_walk.py +115 -0
- samplepaths/noise/__init__.py +25 -0
- samplepaths/noise/colored/__init__.py +19 -0
- samplepaths/noise/colored/blue_noise.py +32 -0
- samplepaths/noise/colored/brownian_noise.py +18 -0
- samplepaths/noise/colored/colored_noise.py +120 -0
- samplepaths/noise/colored/pink_noise.py +32 -0
- samplepaths/noise/colored/red_noise.py +32 -0
- samplepaths/noise/colored/violet_noise.py +32 -0
- samplepaths/noise/colored/white_noise.py +32 -0
- samplepaths/noise/fractional_gaussian_noise.py +219 -0
- samplepaths/noise/gaussian_noise.py +78 -0
- samplepaths/py.typed +0 -0
- samplepaths/random.py +50 -0
- samplepaths/utils/__init__.py +48 -0
- samplepaths/utils/validation.py +176 -0
- samplepaths-0.1.0.dist-info/METADATA +159 -0
- samplepaths-0.1.0.dist-info/RECORD +55 -0
- samplepaths-0.1.0.dist-info/WHEEL +4 -0
- samplepaths-0.1.0.dist-info/licenses/LICENSE +22 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Geometric Brownian motion process."""
|
|
2
|
+
|
|
3
|
+
from typing import override
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import numpy.typing as npt
|
|
7
|
+
from numpy.random import Generator
|
|
8
|
+
|
|
9
|
+
from ..utils.validation import (
|
|
10
|
+
check_numeric,
|
|
11
|
+
check_positive_integer,
|
|
12
|
+
check_positive_number,
|
|
13
|
+
)
|
|
14
|
+
from .brownian_motion import BrownianMotion
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class GeometricBrownianMotion(BrownianMotion):
|
|
18
|
+
r"""Geometric Brownian motion process.
|
|
19
|
+
|
|
20
|
+
.. image:: /_static/geometric_brownian_motion.png
|
|
21
|
+
:scale: 50%
|
|
22
|
+
|
|
23
|
+
A geometric Brownian motion :math:`S_t` is the analytic solution to the
|
|
24
|
+
stochastic differential equation with Wiener process :math:`W_t`:
|
|
25
|
+
|
|
26
|
+
.. math::
|
|
27
|
+
|
|
28
|
+
dS_t = \mu S_t dt + \sigma S_t dW_t
|
|
29
|
+
|
|
30
|
+
and can be represented with initial value :math:`S_0` in the form:
|
|
31
|
+
|
|
32
|
+
.. math::
|
|
33
|
+
|
|
34
|
+
S_t = S_0 \exp \left( \left( \mu - \frac{\sigma^2}{2} \right) t +
|
|
35
|
+
\sigma W_t \right)
|
|
36
|
+
|
|
37
|
+
:param drift: the parameter :math:`\mu`
|
|
38
|
+
:param volatility: the parameter :math:`\sigma`
|
|
39
|
+
:param t: the right hand endpoint of the time interval :math:`[0,t]`
|
|
40
|
+
for the process
|
|
41
|
+
:param rng: a custom random number generator
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
*,
|
|
47
|
+
drift: float = 0,
|
|
48
|
+
volatility: float = 1,
|
|
49
|
+
t: float = 1.0,
|
|
50
|
+
rng: Generator | None = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
super().__init__(t=t, rng=rng)
|
|
53
|
+
|
|
54
|
+
self.drift = drift
|
|
55
|
+
self.volatility = volatility
|
|
56
|
+
|
|
57
|
+
def __str__(self) -> str:
|
|
58
|
+
return (
|
|
59
|
+
f"Geometric Brownian motion with drift {self.drift} "
|
|
60
|
+
f"and volatility {self.volatility} on [0, {self.t}]."
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
def __repr__(self) -> str:
|
|
64
|
+
return (
|
|
65
|
+
f"GeometricBrownianMotion(drift={self.drift}, volatility={self.volatility}, t={self.t})"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def drift(self) -> float:
|
|
70
|
+
"""Geometric Brownian motion drift parameter."""
|
|
71
|
+
return self.__drift
|
|
72
|
+
|
|
73
|
+
@drift.setter
|
|
74
|
+
def drift(self, value: float) -> None:
|
|
75
|
+
check_numeric(value=value, name="Drift")
|
|
76
|
+
|
|
77
|
+
self.__drift = value
|
|
78
|
+
|
|
79
|
+
@property
|
|
80
|
+
def volatility(self) -> float:
|
|
81
|
+
"""Geometric Brownian motion volatility parameter."""
|
|
82
|
+
return self.__volatility
|
|
83
|
+
|
|
84
|
+
@volatility.setter
|
|
85
|
+
def volatility(self, value: float) -> None:
|
|
86
|
+
check_positive_number(value=value, name="Volatility")
|
|
87
|
+
|
|
88
|
+
self.__volatility = value
|
|
89
|
+
|
|
90
|
+
def _sample_geometric_brownian_motion(
|
|
91
|
+
self,
|
|
92
|
+
n: int,
|
|
93
|
+
initial: float = 1.0,
|
|
94
|
+
) -> npt.NDArray[np.float64]:
|
|
95
|
+
"""Generate a realization of geometric Brownian motion."""
|
|
96
|
+
check_positive_integer(n=n)
|
|
97
|
+
check_positive_number(value=initial, name="Initial")
|
|
98
|
+
|
|
99
|
+
# The drift enters through the exponent only, so the driving process
|
|
100
|
+
# is a driftless Wiener process.
|
|
101
|
+
wiener = np.cumsum(self._sample_gaussian_noise(n))
|
|
102
|
+
wiener = np.insert(wiener, [0], 0)
|
|
103
|
+
|
|
104
|
+
line = (self.drift - self.volatility**2 / 2.0) * self.times
|
|
105
|
+
ret = initial * np.exp(line + self.volatility * wiener)
|
|
106
|
+
assert isinstance(ret, np.ndarray)
|
|
107
|
+
|
|
108
|
+
return ret
|
|
109
|
+
|
|
110
|
+
def _sample_geometric_brownian_motion_at(
|
|
111
|
+
self,
|
|
112
|
+
times: npt.NDArray[np.float64],
|
|
113
|
+
initial: float = 1.0,
|
|
114
|
+
) -> npt.NDArray[np.float64]:
|
|
115
|
+
"""Generate a realization of geometric Brownian motion."""
|
|
116
|
+
check_positive_number(value=initial, name="Initial")
|
|
117
|
+
|
|
118
|
+
# The drift enters through the exponent only, so the driving process
|
|
119
|
+
# is a driftless Wiener process.
|
|
120
|
+
wiener = np.cumsum(self._sample_gaussian_noise_at(times))
|
|
121
|
+
if times[0] == 0:
|
|
122
|
+
wiener = np.insert(wiener, 0, [0])
|
|
123
|
+
|
|
124
|
+
line = (self.drift - self.volatility**2 / 2.0) * np.asarray(times)
|
|
125
|
+
ret = initial * np.exp(line + self.volatility * wiener)
|
|
126
|
+
assert isinstance(ret, np.ndarray)
|
|
127
|
+
|
|
128
|
+
return ret
|
|
129
|
+
|
|
130
|
+
@override
|
|
131
|
+
def sample(self, n: int) -> npt.NDArray[np.float64]:
|
|
132
|
+
return self._sample_geometric_brownian_motion(n, 1.0)
|
|
133
|
+
|
|
134
|
+
@override
|
|
135
|
+
def sample_at(
|
|
136
|
+
self,
|
|
137
|
+
times: npt.NDArray[np.float64],
|
|
138
|
+
) -> npt.NDArray[np.float64]:
|
|
139
|
+
return self._sample_geometric_brownian_motion_at(times, 1.0)
|
|
140
|
+
|
|
141
|
+
def sample_with_initial(
|
|
142
|
+
self,
|
|
143
|
+
n: int,
|
|
144
|
+
initial: float = 1.0,
|
|
145
|
+
) -> npt.NDArray[np.float64]:
|
|
146
|
+
"""Generate a realization starting from an initial value.
|
|
147
|
+
|
|
148
|
+
:param n: the number of increments to generate
|
|
149
|
+
:param initial: the initial value of the process :math:`S_0`
|
|
150
|
+
:returns: the realization
|
|
151
|
+
"""
|
|
152
|
+
return self._sample_geometric_brownian_motion(n, initial)
|
|
153
|
+
|
|
154
|
+
def sample_at_with_initial(
|
|
155
|
+
self,
|
|
156
|
+
times: npt.NDArray[np.float64],
|
|
157
|
+
initial: float = 1.0,
|
|
158
|
+
) -> npt.NDArray[np.float64]:
|
|
159
|
+
"""Generate a realization at specified times from an initial value.
|
|
160
|
+
|
|
161
|
+
:param times: a vector of increasing time values at which to generate
|
|
162
|
+
the realization
|
|
163
|
+
:param initial: the initial value of the process :math:`S_0`
|
|
164
|
+
:returns: the realization
|
|
165
|
+
"""
|
|
166
|
+
return self._sample_geometric_brownian_motion_at(times, initial)
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
"""Inverse Gaussian process."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import override
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import numpy.typing as npt
|
|
9
|
+
from numpy.random import Generator
|
|
10
|
+
|
|
11
|
+
from samplepaths.utils.validation import check_positive_number
|
|
12
|
+
|
|
13
|
+
from ..base import BaseTimeProcess
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class InverseGaussianProcess(BaseTimeProcess):
|
|
17
|
+
r"""Inverse Gaussian process.
|
|
18
|
+
|
|
19
|
+
.. image:: /_static/inverse_gaussian.png
|
|
20
|
+
:scale: 50%
|
|
21
|
+
|
|
22
|
+
An inverse Gaussian process has independent increments which follow an
|
|
23
|
+
inverse Gaussian distribution with parameters defined by a monotonically
|
|
24
|
+
increasing function, :math:`\Gamma(t)`. E.g. for increment :math:`[s, t]`:
|
|
25
|
+
|
|
26
|
+
:math:`\mathcal{IG}(\Gamma(t) - \Gamma(s), \eta(\Gamma(t) - \Gamma(s))^2)`
|
|
27
|
+
|
|
28
|
+
Uses a method for generating inverse Gaussian variates from:
|
|
29
|
+
|
|
30
|
+
* Michael, John R., William R. Schucany, and Roy W. Haas. "Generating
|
|
31
|
+
random variates using transformations with multiple roots." The
|
|
32
|
+
American Statistician 30, no. 2 (1976): 88-90.
|
|
33
|
+
|
|
34
|
+
:param mean: a callable with one argument :math:`\Gamma(t)` such
|
|
35
|
+
that :math:`\Gamma(t') > \Gamma(t) \forall t' > t`. Default is the
|
|
36
|
+
identity function.
|
|
37
|
+
:param scale: scale factor of the shape parameter of the inverse
|
|
38
|
+
gaussian, or :math:`\eta` from the above equation.
|
|
39
|
+
:param t: the right hand endpoint of the time interval :math:`[0,t]`
|
|
40
|
+
for the process
|
|
41
|
+
:param rng: a custom random number generator
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def __init__(
|
|
45
|
+
self,
|
|
46
|
+
*,
|
|
47
|
+
mean: Callable[[float], float] = lambda x: x,
|
|
48
|
+
scale: float = 1.0,
|
|
49
|
+
t: float = 1.0,
|
|
50
|
+
rng: Generator | None = None,
|
|
51
|
+
) -> None:
|
|
52
|
+
super().__init__(t=t, rng=rng)
|
|
53
|
+
|
|
54
|
+
self.mean = mean
|
|
55
|
+
self.scale = scale
|
|
56
|
+
|
|
57
|
+
self.__ms: npt.NDArray[np.float64] | None = None
|
|
58
|
+
|
|
59
|
+
def __str__(self) -> str:
|
|
60
|
+
return (
|
|
61
|
+
f"Inverse Gaussian process with mean {self.mean.__name__} "
|
|
62
|
+
f"and scale {self.scale} on interval [0, {self.t}]."
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def __repr__(self) -> str:
|
|
66
|
+
return f"InverseGaussianProcess(mean={self.mean.__name__}, scale={self.scale}, t={self.t})"
|
|
67
|
+
|
|
68
|
+
@property
|
|
69
|
+
def mean(self) -> Callable[[float], float]:
|
|
70
|
+
"""Mean function."""
|
|
71
|
+
return self.__mean
|
|
72
|
+
|
|
73
|
+
@mean.setter
|
|
74
|
+
def mean(self, value: Callable[[float], float]) -> None:
|
|
75
|
+
if not callable(value):
|
|
76
|
+
raise TypeError(f"Mean must be a callable function; got {type(value)}.")
|
|
77
|
+
|
|
78
|
+
try:
|
|
79
|
+
num_args = len(inspect.signature(value).parameters)
|
|
80
|
+
except Exception as e:
|
|
81
|
+
raise TypeError("Mean must be an inspectable callable.") from e
|
|
82
|
+
|
|
83
|
+
if num_args != 1:
|
|
84
|
+
raise ValueError("Mean must be a function of one argument.")
|
|
85
|
+
|
|
86
|
+
self.__mean = value
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def scale(self) -> float:
|
|
90
|
+
"""Scale parameter."""
|
|
91
|
+
return self.__scale
|
|
92
|
+
|
|
93
|
+
@scale.setter
|
|
94
|
+
def scale(self, value: float) -> None:
|
|
95
|
+
check_positive_number(value=value, name="Scale")
|
|
96
|
+
|
|
97
|
+
self.__scale = value
|
|
98
|
+
|
|
99
|
+
def _check_mean(self, left: float, right: float) -> float:
|
|
100
|
+
"""Check the validity of the mean function."""
|
|
101
|
+
delta = self.mean(right) - self.mean(left)
|
|
102
|
+
|
|
103
|
+
if delta <= 0:
|
|
104
|
+
raise ValueError("Mean must be monotonically increasing.")
|
|
105
|
+
|
|
106
|
+
return delta
|
|
107
|
+
|
|
108
|
+
def _sample_inverse_gaussian_process(
|
|
109
|
+
self,
|
|
110
|
+
n: int,
|
|
111
|
+
) -> npt.NDArray[np.float64]:
|
|
112
|
+
"""Generate a realization of the inverse Gaussian process.
|
|
113
|
+
|
|
114
|
+
Generate an inverse Gaussian process realization with n increments.
|
|
115
|
+
"""
|
|
116
|
+
if self.set_times(n):
|
|
117
|
+
self.__ms = np.zeros(n)
|
|
118
|
+
for k in range(n):
|
|
119
|
+
self.__ms[k] = self._check_mean(
|
|
120
|
+
self.times[k],
|
|
121
|
+
self.times[k + 1],
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
assert self.__ms is not None
|
|
125
|
+
ls = np.array([self.scale * m**2 for m in self.__ms])
|
|
126
|
+
|
|
127
|
+
gn = self.rng.normal(size=n)
|
|
128
|
+
ys = gn**2
|
|
129
|
+
|
|
130
|
+
xs = (
|
|
131
|
+
self.__ms
|
|
132
|
+
+ self.__ms**2 * ys / 2 / ls
|
|
133
|
+
- self.__ms / 2 / ys * np.sqrt(4 * self.__ms * ls * ys + self.__ms**2 * ys**2)
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
zs = self.rng.uniform(size=n)
|
|
137
|
+
|
|
138
|
+
ign = []
|
|
139
|
+
for z, x, m in zip(zs, xs, self.__ms, strict=True):
|
|
140
|
+
if z <= m / (m + x):
|
|
141
|
+
ign.append(x)
|
|
142
|
+
else:
|
|
143
|
+
ign.append(m**2 / x)
|
|
144
|
+
|
|
145
|
+
ig = np.array(ign).cumsum()
|
|
146
|
+
ig = np.insert(ig, [0], 0)
|
|
147
|
+
return ig
|
|
148
|
+
|
|
149
|
+
@override
|
|
150
|
+
def sample(self, n: int) -> npt.NDArray[np.float64]:
|
|
151
|
+
return self._sample_inverse_gaussian_process(n)
|
|
152
|
+
|
|
153
|
+
def _sample_inverse_gaussian_process_at(
|
|
154
|
+
self,
|
|
155
|
+
times: npt.NDArray[np.float64],
|
|
156
|
+
) -> npt.NDArray[np.float64]:
|
|
157
|
+
"""Generate an inverse Gaussian process at specified times."""
|
|
158
|
+
n = len(times) - 1
|
|
159
|
+
if times[0] != 0:
|
|
160
|
+
times = np.concatenate(([0], times))
|
|
161
|
+
|
|
162
|
+
ms = np.zeros(n)
|
|
163
|
+
for k in range(n):
|
|
164
|
+
ms[k] = self._check_mean(times[k], times[k + 1])
|
|
165
|
+
|
|
166
|
+
ls = np.array([self.scale * m**2 for m in ms])
|
|
167
|
+
|
|
168
|
+
gn = self.rng.normal(size=n)
|
|
169
|
+
ys = gn**2
|
|
170
|
+
|
|
171
|
+
xs = ms + ms**2 * ys / 2 / ls - ms / 2 / ys * np.sqrt(4 * ms * ls * ys + ms**2 * ys**2)
|
|
172
|
+
|
|
173
|
+
zs = self.rng.uniform(size=n)
|
|
174
|
+
|
|
175
|
+
ign = []
|
|
176
|
+
for z, x, m in zip(zs, xs, ms, strict=True):
|
|
177
|
+
if z <= m / (m + x):
|
|
178
|
+
ign.append(x)
|
|
179
|
+
else:
|
|
180
|
+
ign.append(m**2 / x)
|
|
181
|
+
|
|
182
|
+
ig = np.array(ign).cumsum()
|
|
183
|
+
if times[0] == 0:
|
|
184
|
+
ig = np.insert(ig, 0, [0])
|
|
185
|
+
|
|
186
|
+
return ig
|
|
187
|
+
|
|
188
|
+
@override
|
|
189
|
+
def sample_at(
|
|
190
|
+
self,
|
|
191
|
+
times: npt.NDArray[np.float64],
|
|
192
|
+
) -> npt.NDArray[np.float64]:
|
|
193
|
+
return self._sample_inverse_gaussian_process_at(times)
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Mixed poisson process."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import Any, override
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import numpy.typing as npt
|
|
8
|
+
from numpy.random import Generator
|
|
9
|
+
|
|
10
|
+
from .poisson_process import PoissonProcess
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class MixedPoissonProcess(PoissonProcess):
|
|
14
|
+
r"""Mixed poisson process.
|
|
15
|
+
|
|
16
|
+
.. image:: /_static/mixed_poisson_process.png
|
|
17
|
+
:scale: 50%
|
|
18
|
+
|
|
19
|
+
A mixed poisson process is a Poisson process for which the rate is
|
|
20
|
+
a scalar random variate. The sample method will generate a random variate
|
|
21
|
+
for the rate before generating a Poisson process realization with the rate.
|
|
22
|
+
A Poisson process with rate :math:`\lambda`
|
|
23
|
+
is a count of occurrences of i.i.d. exponential random
|
|
24
|
+
variables with mean :math:`1/\lambda`. Use the ``rate`` attribute to get
|
|
25
|
+
the most recently generated random rate.
|
|
26
|
+
|
|
27
|
+
:param rate_func: a callable to generate variates of the random
|
|
28
|
+
rate
|
|
29
|
+
:param rate_args: positional args for ``rate_func``
|
|
30
|
+
:param rate_kwargs: keyword args for ``rate_func``
|
|
31
|
+
:param rng: a custom random number generator
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(
|
|
35
|
+
self,
|
|
36
|
+
*,
|
|
37
|
+
rate_func: Callable[..., float],
|
|
38
|
+
rate_args: tuple[float, ...] | None = None,
|
|
39
|
+
rate_kwargs: dict[str, Any] | None = None,
|
|
40
|
+
rng: Generator | None = None,
|
|
41
|
+
) -> None:
|
|
42
|
+
super().__init__(
|
|
43
|
+
rate=1.0,
|
|
44
|
+
rng=rng,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
self.rate_func = rate_func
|
|
48
|
+
self.rate_args = rate_args or tuple()
|
|
49
|
+
self.rate_kwargs = rate_kwargs or {}
|
|
50
|
+
|
|
51
|
+
def __str__(self) -> str:
|
|
52
|
+
return "Mixed Poisson process with random rate."
|
|
53
|
+
|
|
54
|
+
def __repr__(self) -> str:
|
|
55
|
+
return (
|
|
56
|
+
f"MixedPoissonProcess(rate_func={self.rate_func}, "
|
|
57
|
+
f"rate_args={self.rate_args}, rate_kwargs={self.rate_kwargs})"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
@property
|
|
61
|
+
def rate_func(self) -> Callable[..., float]:
|
|
62
|
+
"""Current rate's distribution."""
|
|
63
|
+
return self.__rate_func
|
|
64
|
+
|
|
65
|
+
@rate_func.setter
|
|
66
|
+
def rate_func(self, value: Callable[..., float]) -> None:
|
|
67
|
+
if not callable(value):
|
|
68
|
+
raise TypeError("Rate function must be a callable.")
|
|
69
|
+
self.__rate_func = value
|
|
70
|
+
|
|
71
|
+
@property
|
|
72
|
+
def rate_args(self) -> tuple[float, ...]:
|
|
73
|
+
"""Positional arguments for the rate function."""
|
|
74
|
+
return self.__rate_args
|
|
75
|
+
|
|
76
|
+
@rate_args.setter
|
|
77
|
+
def rate_args(self, value: tuple[float, ...]) -> None:
|
|
78
|
+
if not isinstance(value, (list, tuple)):
|
|
79
|
+
raise TypeError("Rate args must be a list or tuple.")
|
|
80
|
+
self.__rate_args = tuple(value)
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def rate_kwargs(self) -> dict[str, Any]:
|
|
84
|
+
"""Keyword arguments for the rate function."""
|
|
85
|
+
return self.__rate_kwargs
|
|
86
|
+
|
|
87
|
+
@rate_kwargs.setter
|
|
88
|
+
def rate_kwargs(self, value: dict[str, Any]) -> None:
|
|
89
|
+
if not isinstance(value, dict):
|
|
90
|
+
raise TypeError("Rate kwargs must be a dict.")
|
|
91
|
+
self.__rate_kwargs = value
|
|
92
|
+
|
|
93
|
+
def _sample_rate(self) -> float:
|
|
94
|
+
"""Generate a rate variate."""
|
|
95
|
+
return self.rate_func(
|
|
96
|
+
*self.rate_args,
|
|
97
|
+
**self.rate_kwargs,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
@override
|
|
101
|
+
def sample(
|
|
102
|
+
self,
|
|
103
|
+
n: int,
|
|
104
|
+
) -> npt.NDArray[np.float64]:
|
|
105
|
+
self.rate = self._sample_rate()
|
|
106
|
+
return self._sample_poisson_process(n=n)
|
|
107
|
+
|
|
108
|
+
@override
|
|
109
|
+
def sample_with_length(
|
|
110
|
+
self,
|
|
111
|
+
length: float,
|
|
112
|
+
) -> npt.NDArray[np.float64]:
|
|
113
|
+
self.rate = self._sample_rate()
|
|
114
|
+
return self._sample_poisson_process(length=length)
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Multifractional Brownian motion process."""
|
|
2
|
+
|
|
3
|
+
import inspect
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from typing import override
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
import numpy.typing as npt
|
|
9
|
+
from numpy.random import Generator
|
|
10
|
+
from scipy.special import gamma
|
|
11
|
+
|
|
12
|
+
from ..base import BaseTimeProcess
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MultifractionalBrownianMotion(BaseTimeProcess):
|
|
16
|
+
r"""Multifractional Brownian motion process.
|
|
17
|
+
|
|
18
|
+
.. image:: /_static/multifractional_brownian_motion.png
|
|
19
|
+
:scale: 50%
|
|
20
|
+
|
|
21
|
+
A multifractional Brownian motion generalizes a fractional Brownian
|
|
22
|
+
motion with a Hurst parameter which is a function of time,
|
|
23
|
+
:math:`h(t)`. If the Hurst is constant, the process is a fractional
|
|
24
|
+
Brownian motion. If Hurst is constant equal to 0.5, the process is a
|
|
25
|
+
Brownian motion.
|
|
26
|
+
|
|
27
|
+
Approximate method originally proposed for fBm in
|
|
28
|
+
|
|
29
|
+
* Rambaldi, Sandro, and Ombretta Pinazza. "An accurate fractional Brownian
|
|
30
|
+
motion generator." Physica A: Statistical Mechanics and its Applications
|
|
31
|
+
208, no. 1 (1994): 21-30.
|
|
32
|
+
|
|
33
|
+
Adapted to approximate mBm in
|
|
34
|
+
|
|
35
|
+
* Muniandy, S. V., and S. C. Lim. "Modeling of locally self-similar
|
|
36
|
+
processes using multifractional Brownian motion of Riemann-Liouville
|
|
37
|
+
type." Physical Review E 63, no. 4 (2001): 046104.
|
|
38
|
+
|
|
39
|
+
:param Callable[[float], float] hurst: a callable with one argument :math:`h(t)` such that
|
|
40
|
+
:math:`h(t') \in (0, 1) \forall t' \in [0, t]`. Default is
|
|
41
|
+
:math:`h(t) = 0.5`.
|
|
42
|
+
:param t: the right hand endpoint of the time interval :math:`[0,t]`
|
|
43
|
+
for the process
|
|
44
|
+
:param rng: a custom random number generator
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
def __init__(
|
|
48
|
+
self,
|
|
49
|
+
*,
|
|
50
|
+
hurst: Callable[[float], float] | None = None,
|
|
51
|
+
t: float = 1.0,
|
|
52
|
+
rng: Generator | None = None,
|
|
53
|
+
) -> None:
|
|
54
|
+
super().__init__(t=t, rng=rng)
|
|
55
|
+
|
|
56
|
+
self.hurst = hurst if hurst is not None else lambda x: 0.5
|
|
57
|
+
|
|
58
|
+
def __str__(self) -> str:
|
|
59
|
+
return (
|
|
60
|
+
f"Multifractional Brownian motion with Hurst function {self.hurst.__name__} "
|
|
61
|
+
f"on [0, {self.t}]."
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
def __repr__(self) -> str:
|
|
65
|
+
return f"MultifractionalBrownianMotion(hurst={self.hurst.__name__}, t={self.t})"
|
|
66
|
+
|
|
67
|
+
@property
|
|
68
|
+
def hurst(self) -> Callable[[float], float]:
|
|
69
|
+
"""Hurst function."""
|
|
70
|
+
return self._hurst
|
|
71
|
+
|
|
72
|
+
@hurst.setter
|
|
73
|
+
def hurst(self, value: Callable[[float], float]) -> None:
|
|
74
|
+
try:
|
|
75
|
+
num_args = len(inspect.signature(value).parameters)
|
|
76
|
+
except Exception as e:
|
|
77
|
+
raise TypeError("Hurst parameter must be an inspectable function.") from e
|
|
78
|
+
|
|
79
|
+
if not callable(value) or num_args != 1:
|
|
80
|
+
raise TypeError("Hurst parameter must be a function of one argument.")
|
|
81
|
+
|
|
82
|
+
self._hurst = value
|
|
83
|
+
|
|
84
|
+
def _get_hurst(self, value: Callable[[float], float]) -> list[float]:
|
|
85
|
+
hs = [0.0] * len(self.times)
|
|
86
|
+
for i, t in enumerate(self.times):
|
|
87
|
+
h = value(t)
|
|
88
|
+
if h <= 0 or h >= 1:
|
|
89
|
+
raise ValueError(f"Hurst range must be on interval (0, 1). Got {h} for t={t}.")
|
|
90
|
+
hs[i] = h
|
|
91
|
+
|
|
92
|
+
return hs
|
|
93
|
+
|
|
94
|
+
def _w(
|
|
95
|
+
self,
|
|
96
|
+
t: float,
|
|
97
|
+
hurst: float,
|
|
98
|
+
dt: float,
|
|
99
|
+
) -> float:
|
|
100
|
+
"""Get the Riemann-Liouville method weight for time t."""
|
|
101
|
+
w = float(
|
|
102
|
+
1.0
|
|
103
|
+
/ gamma(hurst + 0.5)
|
|
104
|
+
* np.sqrt((t ** (2 * hurst) - (t - dt) ** (2 * hurst)) / (2 * hurst * dt))
|
|
105
|
+
)
|
|
106
|
+
return w
|
|
107
|
+
|
|
108
|
+
def _sample_multifractional_brownian_motion(self, n: int) -> npt.NDArray[np.float64]:
|
|
109
|
+
"""Generate Riemann-Liouville mBm."""
|
|
110
|
+
gn = self.rng.normal(0.0, 1.0, n)
|
|
111
|
+
self.set_times(n)
|
|
112
|
+
|
|
113
|
+
dt = 1.0 * self.t / self.n
|
|
114
|
+
hs = self._get_hurst(self.hurst)
|
|
115
|
+
|
|
116
|
+
mbm = [0]
|
|
117
|
+
coefs = [(g / np.sqrt(dt)) * dt for g in gn]
|
|
118
|
+
|
|
119
|
+
for k in range(1, self.n + 1):
|
|
120
|
+
weights = [self._w(t, hs[k], dt) for t in self.times[1 : k + 1]]
|
|
121
|
+
seq = [coefs[i - 1] * weights[k - i] for i in range(1, k + 1)]
|
|
122
|
+
mbm.append(sum(seq))
|
|
123
|
+
|
|
124
|
+
return np.array(mbm)
|
|
125
|
+
|
|
126
|
+
@override
|
|
127
|
+
def sample(self, n: int) -> npt.NDArray[np.float64]:
|
|
128
|
+
return self._sample_multifractional_brownian_motion(n)
|