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,175 @@
|
|
|
1
|
+
"""Generalized diffusion process."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import override
|
|
5
|
+
|
|
6
|
+
import numpy as np
|
|
7
|
+
import numpy.typing as npt
|
|
8
|
+
from numpy.random import Generator
|
|
9
|
+
|
|
10
|
+
from ..noise import GaussianNoise
|
|
11
|
+
from ..utils import ensure_single_arg_constant_function
|
|
12
|
+
from ..utils.validation import (
|
|
13
|
+
check_numeric,
|
|
14
|
+
check_numeric_or_single_arg_callable,
|
|
15
|
+
check_positive_integer,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class DiffusionProcess(GaussianNoise):
|
|
20
|
+
r"""Generalized diffusion process.
|
|
21
|
+
|
|
22
|
+
A base process for more specific diffusion processes.
|
|
23
|
+
|
|
24
|
+
The process :math:`X_t` that satisfies the following
|
|
25
|
+
stochastic differential equation with Wiener process :math:`W_t`:
|
|
26
|
+
|
|
27
|
+
.. math::
|
|
28
|
+
|
|
29
|
+
dX_t = \theta_t (\mu_t - X_t) dt + \sigma_t X_t^{\gamma_t} dW_t
|
|
30
|
+
|
|
31
|
+
Realizations are generated using the Euler-Maruyama method.
|
|
32
|
+
|
|
33
|
+
.. note::
|
|
34
|
+
|
|
35
|
+
Since the family of diffusion processes have parameters which
|
|
36
|
+
generalize to functions of ``t``, parameter attributes will be returned
|
|
37
|
+
as callables, even if they are initialized as constants. e.g. a
|
|
38
|
+
``speed`` parameter of 1 accessed from an instance attribute will
|
|
39
|
+
return a function which accepts a single argument and always returns 1.
|
|
40
|
+
|
|
41
|
+
:param speed: the speed of reversion, or :math:`\theta_t` above
|
|
42
|
+
:param mean: the mean of the process, or :math:`\mu_t` above
|
|
43
|
+
:param vol: volatility coefficient of the process, or :math:`\sigma_t`
|
|
44
|
+
above
|
|
45
|
+
:param volexp: volatility exponent of the process, or :math:`\gamma_t`
|
|
46
|
+
above
|
|
47
|
+
:param t: the right hand endpoint of the time interval :math:`[0,t]`
|
|
48
|
+
for the process
|
|
49
|
+
:param rng: a custom random number generator
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
def __init__(
|
|
53
|
+
self,
|
|
54
|
+
*,
|
|
55
|
+
speed: Callable[[float], float] | float | int = 1.0,
|
|
56
|
+
mean: Callable[[float], float] | float | int = 0.0,
|
|
57
|
+
vol: Callable[[float], float] | float | int = 1.0,
|
|
58
|
+
volexp: Callable[[float], float] | float | int = 0.0,
|
|
59
|
+
t: float = 1.0,
|
|
60
|
+
rng: Generator | None = None,
|
|
61
|
+
) -> None:
|
|
62
|
+
super().__init__(t=t, rng=rng)
|
|
63
|
+
|
|
64
|
+
self.speed = speed
|
|
65
|
+
self.mean = mean
|
|
66
|
+
self.vol = vol
|
|
67
|
+
self.volexp = volexp
|
|
68
|
+
|
|
69
|
+
def __str__(self) -> str:
|
|
70
|
+
return (
|
|
71
|
+
f"Diffusion process with speed={self.speed}, mean={self.mean}, "
|
|
72
|
+
f"vol={self.vol}, volexp={self.volexp} on [0, {self.t}]"
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
def __repr__(self) -> str:
|
|
76
|
+
return (
|
|
77
|
+
f"DiffusionProcess(speed={self.speed}, mean={self.mean}, "
|
|
78
|
+
f"vol={self.vol}, volexp={self.volexp}, t={self.t})"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def speed(self) -> Callable[[float], float]:
|
|
83
|
+
r"""Speed, or :math:`\theta_t`."""
|
|
84
|
+
return self.__speed
|
|
85
|
+
|
|
86
|
+
@speed.setter
|
|
87
|
+
def speed(self, value: Callable[[float], float] | float | int) -> None:
|
|
88
|
+
check_numeric_or_single_arg_callable(value=value, name="speed")
|
|
89
|
+
|
|
90
|
+
self.__speed = ensure_single_arg_constant_function(value=value)
|
|
91
|
+
|
|
92
|
+
@property
|
|
93
|
+
def mean(self) -> Callable[[float], float]:
|
|
94
|
+
r"""Mean, or :math:`\mu_t`."""
|
|
95
|
+
return self.__mean
|
|
96
|
+
|
|
97
|
+
@mean.setter
|
|
98
|
+
def mean(self, value: Callable[[float], float] | float | int) -> None:
|
|
99
|
+
check_numeric_or_single_arg_callable(value=value, name="mean")
|
|
100
|
+
self.__mean = ensure_single_arg_constant_function(value=value)
|
|
101
|
+
|
|
102
|
+
@property
|
|
103
|
+
def vol(self) -> Callable[[float], float]:
|
|
104
|
+
r"""Volatility, or :math:`\sigma_t`."""
|
|
105
|
+
return self.__vol
|
|
106
|
+
|
|
107
|
+
@vol.setter
|
|
108
|
+
def vol(self, value: Callable[[float], float] | float | int) -> None:
|
|
109
|
+
check_numeric_or_single_arg_callable(value=value, name="vol")
|
|
110
|
+
self.__vol = ensure_single_arg_constant_function(value=value)
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def volexp(self) -> Callable[[float], float]:
|
|
114
|
+
r"""Volatility exponent, or :math:`\gamma_t`."""
|
|
115
|
+
return self.__volexp
|
|
116
|
+
|
|
117
|
+
@volexp.setter
|
|
118
|
+
def volexp(
|
|
119
|
+
self,
|
|
120
|
+
value: Callable[[float], float] | float | int,
|
|
121
|
+
) -> None:
|
|
122
|
+
check_numeric_or_single_arg_callable(value=value, name="volexp")
|
|
123
|
+
self.__volexp = ensure_single_arg_constant_function(value=value)
|
|
124
|
+
|
|
125
|
+
def _sample(self, n: int, initial: float = 1.0) -> npt.NDArray[np.float64]:
|
|
126
|
+
"""Generate a realization of a diffusion process using Euler-Maruyama."""
|
|
127
|
+
check_positive_integer(n=n)
|
|
128
|
+
check_numeric(value=initial, name="Initial")
|
|
129
|
+
|
|
130
|
+
delta_t = 1.0 * self.t / n
|
|
131
|
+
gns = self._sample_gaussian_noise(n)
|
|
132
|
+
|
|
133
|
+
s = [initial]
|
|
134
|
+
t = 0.0
|
|
135
|
+
for k in range(n):
|
|
136
|
+
t += delta_t
|
|
137
|
+
initial += (
|
|
138
|
+
self.__speed(t) * (self.__mean(t) - initial) * delta_t
|
|
139
|
+
+ self.__vol(t) * initial ** self.__volexp(initial) * gns[k]
|
|
140
|
+
)
|
|
141
|
+
s.append(initial)
|
|
142
|
+
|
|
143
|
+
return np.array(s)
|
|
144
|
+
|
|
145
|
+
@override
|
|
146
|
+
def sample(self, n: int) -> npt.NDArray[np.float64]:
|
|
147
|
+
"""Generate a realization starting from an initial value of 1.
|
|
148
|
+
|
|
149
|
+
:param n: the number of increments to generate
|
|
150
|
+
:returns: the realization
|
|
151
|
+
"""
|
|
152
|
+
return self._sample(n, 1.0)
|
|
153
|
+
|
|
154
|
+
def sample_with_initial(
|
|
155
|
+
self,
|
|
156
|
+
n: int,
|
|
157
|
+
initial: float,
|
|
158
|
+
) -> npt.NDArray[np.float64]:
|
|
159
|
+
"""Generate a realization starting from an initial value.
|
|
160
|
+
|
|
161
|
+
:param n: the number of increments to generate
|
|
162
|
+
:param initial: the initial value of the process
|
|
163
|
+
:returns: the realization
|
|
164
|
+
"""
|
|
165
|
+
return self._sample(n, initial)
|
|
166
|
+
|
|
167
|
+
@override
|
|
168
|
+
def sample_at(
|
|
169
|
+
self,
|
|
170
|
+
times: npt.NDArray[np.float64],
|
|
171
|
+
) -> npt.NDArray[np.float64]:
|
|
172
|
+
raise NotImplementedError(
|
|
173
|
+
f"{type(self).__name__} cannot be sampled at specified times. "
|
|
174
|
+
"Use the sample method with a number of increments."
|
|
175
|
+
)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Extended Vasicek process."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
|
|
5
|
+
from numpy.random import Generator
|
|
6
|
+
|
|
7
|
+
from .diffusion_process import DiffusionProcess
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ExtendedVasicekProcess(DiffusionProcess):
|
|
11
|
+
r"""Extended Vasicek process.
|
|
12
|
+
|
|
13
|
+
A model for future interest rates.
|
|
14
|
+
|
|
15
|
+
.. image:: /_static/extended_vasicek_process.png
|
|
16
|
+
:scale: 50%
|
|
17
|
+
|
|
18
|
+
The ExtendedVasicek process :math:`X_t` that satisfies the following
|
|
19
|
+
stochastic differential equation with Wiener process :math:`W_t`:
|
|
20
|
+
|
|
21
|
+
.. math::
|
|
22
|
+
|
|
23
|
+
dX_t = \theta_t (\mu_t - X_t) dt + \sigma_t dW_t
|
|
24
|
+
|
|
25
|
+
Realizations are generated using the Euler-Maruyama method.
|
|
26
|
+
|
|
27
|
+
.. note::
|
|
28
|
+
|
|
29
|
+
Since the family of diffusion processes have parameters which
|
|
30
|
+
generalize to functions of ``t``, parameter attributes will be returned
|
|
31
|
+
as callables, even if they are initialized as constants. e.g. a
|
|
32
|
+
``speed`` parameter of 1 accessed from an instance attribute will return
|
|
33
|
+
a function which accepts a single argument and always returns 1.
|
|
34
|
+
|
|
35
|
+
:param speed: the speed of reversion, or :math:`\theta_t` above
|
|
36
|
+
:param mean: the mean of the process, or :math:`\mu_t` above
|
|
37
|
+
:param vol: volatility coefficient of the process, or :math:`\sigma_t`
|
|
38
|
+
above
|
|
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
|
+
speed: Callable[[float], float] | float | int = 1.0,
|
|
48
|
+
mean: Callable[[float], float] | float | int = 0.0,
|
|
49
|
+
vol: Callable[[float], float] | float | int = 1.0,
|
|
50
|
+
t: float = 1.0,
|
|
51
|
+
rng: Generator | None = None,
|
|
52
|
+
) -> None:
|
|
53
|
+
super().__init__(
|
|
54
|
+
speed=speed,
|
|
55
|
+
mean=mean,
|
|
56
|
+
vol=vol,
|
|
57
|
+
volexp=0.0,
|
|
58
|
+
t=t,
|
|
59
|
+
rng=rng,
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
def __str__(self) -> str:
|
|
63
|
+
return (
|
|
64
|
+
f"Extended Vasicek process with speed={self.speed}, "
|
|
65
|
+
f"mean={self.mean}, vol={self.vol} on [0, {self.t}]"
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
def __repr__(self) -> str:
|
|
69
|
+
return (
|
|
70
|
+
f"ExtendedVasicekProcess(speed={self.speed}, "
|
|
71
|
+
f"mean={self.mean}, vol={self.vol}, t={self.t})"
|
|
72
|
+
)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""Ornstein-Uhlenbeck process."""
|
|
2
|
+
|
|
3
|
+
from numpy.random import Generator
|
|
4
|
+
|
|
5
|
+
from .vasicek_process import VasicekProcess
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class OrnsteinUhlenbeckProcess(VasicekProcess):
|
|
9
|
+
r"""Ornstein-Uhlenbeck process.
|
|
10
|
+
|
|
11
|
+
.. image:: /_static/ornstein_uhlenbeck_process.png
|
|
12
|
+
:scale: 50%
|
|
13
|
+
|
|
14
|
+
The process :math:`X_t` that satisfies the following stochastic
|
|
15
|
+
differential equation with Wiener process :math:`W_t`:
|
|
16
|
+
|
|
17
|
+
.. math::
|
|
18
|
+
|
|
19
|
+
dX_t = - \theta X_t dt + \sigma dW_t
|
|
20
|
+
|
|
21
|
+
Realizations are generated using the Euler-Maruyama method.
|
|
22
|
+
|
|
23
|
+
.. note::
|
|
24
|
+
|
|
25
|
+
Since the family of diffusion processes have parameters which
|
|
26
|
+
generalize to functions of ``t``, parameter attributes will be returned
|
|
27
|
+
as callables, even if they are initialized as constants. e.g. a
|
|
28
|
+
``speed`` parameter of 1 accessed from an instance attribute will
|
|
29
|
+
return a function which accepts a single argument and always returns 1.
|
|
30
|
+
|
|
31
|
+
:param speed: the speed of reversion, or :math:`\theta` above
|
|
32
|
+
:param vol: volatility coefficient of the process, or :math:`\sigma`
|
|
33
|
+
above
|
|
34
|
+
:param t: the right hand endpoint of the time interval :math:`[0,t]`
|
|
35
|
+
for the process
|
|
36
|
+
:param rng: a custom random number generator
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
*,
|
|
42
|
+
speed: float = 1.0,
|
|
43
|
+
vol: float = 1.0,
|
|
44
|
+
t: float = 1.0,
|
|
45
|
+
rng: Generator | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
super().__init__(
|
|
48
|
+
speed=speed,
|
|
49
|
+
mean=0.0,
|
|
50
|
+
vol=vol,
|
|
51
|
+
t=t,
|
|
52
|
+
rng=rng,
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
def __str__(self) -> str:
|
|
56
|
+
return (
|
|
57
|
+
f"Ornstein-Uhlenbeck process with speed={self.speed}, vol={self.vol} on [0, {self.t}]"
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
def __repr__(self) -> str:
|
|
61
|
+
return f"OrnsteinUhlenbeckProcess(speed={self.speed}, vol={self.vol}, t={self.t})"
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Vasicek process."""
|
|
2
|
+
|
|
3
|
+
from numpy.random import Generator
|
|
4
|
+
|
|
5
|
+
from .extended_vasicek_process import ExtendedVasicekProcess
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class VasicekProcess(ExtendedVasicekProcess):
|
|
9
|
+
r"""Vasicek process.
|
|
10
|
+
|
|
11
|
+
A model for instantaneous interest rate.
|
|
12
|
+
|
|
13
|
+
.. image:: /_static/vasicek_process.png
|
|
14
|
+
:scale: 50%
|
|
15
|
+
|
|
16
|
+
The Vasicek process :math:`X_t` that satisfies the following stochastic
|
|
17
|
+
differential equation with Wiener process :math:`W_t`:
|
|
18
|
+
|
|
19
|
+
.. math::
|
|
20
|
+
|
|
21
|
+
dX_t = \theta (\mu - X_t) dt + \sigma dW_t
|
|
22
|
+
|
|
23
|
+
Realizations are generated using the Euler-Maruyama method.
|
|
24
|
+
|
|
25
|
+
.. note::
|
|
26
|
+
|
|
27
|
+
Since the family of diffusion processes have parameters which
|
|
28
|
+
generalize to functions of ``t``, parameter attributes will be returned
|
|
29
|
+
as callables, even if they are initialized as constants. e.g. a
|
|
30
|
+
``speed`` parameter of 1 accessed from an instance attribute will
|
|
31
|
+
return a function which accepts a single argument and always returns 1.
|
|
32
|
+
|
|
33
|
+
:param speed: the speed of reversion, or :math:`\theta` above
|
|
34
|
+
:param mean: the mean of the process, or :math:`\mu` above
|
|
35
|
+
:param vol: volatility coefficient of the process, or :math:`\sigma`
|
|
36
|
+
above
|
|
37
|
+
:param t: the right hand endpoint of the time interval :math:`[0,t]`
|
|
38
|
+
for the process
|
|
39
|
+
:param rng: a custom random number generator
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
*,
|
|
45
|
+
speed: float = 1.0,
|
|
46
|
+
mean: float = 1.0,
|
|
47
|
+
vol: float = 1.0,
|
|
48
|
+
t: float = 1.0,
|
|
49
|
+
rng: Generator | None = None,
|
|
50
|
+
) -> None:
|
|
51
|
+
super().__init__(
|
|
52
|
+
speed=speed,
|
|
53
|
+
mean=mean,
|
|
54
|
+
vol=vol,
|
|
55
|
+
t=t,
|
|
56
|
+
rng=rng,
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
def __str__(self) -> str:
|
|
60
|
+
return (
|
|
61
|
+
f"Vasicek process with speed={self.speed}, "
|
|
62
|
+
f"mean={self.mean}, vol={self.vol} on [0, {self.t}]"
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def __repr__(self) -> str:
|
|
66
|
+
return f"VasicekProcess(speed={self.speed}, mean={self.mean}, vol={self.vol}, t={self.t})"
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Discrete-time processes."""
|
|
2
|
+
|
|
3
|
+
from .bernoulli_process import BernoulliProcess
|
|
4
|
+
from .chinese_restaurant_process import ChineseRestaurantProcess
|
|
5
|
+
from .dirichlet_process import DirichletProcess
|
|
6
|
+
from .markov_chain import MarkovChain
|
|
7
|
+
from .moran_process import MoranProcess
|
|
8
|
+
from .random_walk import RandomWalk
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"BernoulliProcess",
|
|
12
|
+
"ChineseRestaurantProcess",
|
|
13
|
+
"DirichletProcess",
|
|
14
|
+
"MarkovChain",
|
|
15
|
+
"MoranProcess",
|
|
16
|
+
"RandomWalk",
|
|
17
|
+
]
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Bernoulli 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 ..base import BaseSequenceProcess
|
|
10
|
+
from ..utils.validation import check_positive_integer, is_number
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class BernoulliProcess(BaseSequenceProcess):
|
|
14
|
+
"""Bernoulli process.
|
|
15
|
+
|
|
16
|
+
.. image:: /_static/bernoulli_process.png
|
|
17
|
+
:scale: 50%
|
|
18
|
+
|
|
19
|
+
A Bernoulli process consists of a sequence of Bernoulli random
|
|
20
|
+
variables. A Bernoulli random variable is
|
|
21
|
+
|
|
22
|
+
* 1 with probability :math:`p`
|
|
23
|
+
* 0 with probability :math:`1-p`
|
|
24
|
+
|
|
25
|
+
:param p: in :math:`[0,1]`, the probability of success of each Bernoulli
|
|
26
|
+
random variable
|
|
27
|
+
:param rng: a custom random number generator
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
p: float = 0.5,
|
|
33
|
+
rng: Generator | None = None,
|
|
34
|
+
) -> None:
|
|
35
|
+
super().__init__(rng=rng)
|
|
36
|
+
self.p = p
|
|
37
|
+
|
|
38
|
+
def __str__(self) -> str:
|
|
39
|
+
return f"Bernoulli process with p={self.p}."
|
|
40
|
+
|
|
41
|
+
def __repr__(self) -> str:
|
|
42
|
+
return f"BernoulliProcess({self.p})"
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def p(self) -> float:
|
|
46
|
+
"""Probability of success."""
|
|
47
|
+
return self.__p
|
|
48
|
+
|
|
49
|
+
@p.setter
|
|
50
|
+
def p(self, value: float) -> None:
|
|
51
|
+
if not is_number(value):
|
|
52
|
+
raise TypeError(
|
|
53
|
+
"Probability of success must be a number between 0.0 and 1.0",
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
if value < 0.0 or value > 1.0:
|
|
57
|
+
raise ValueError(
|
|
58
|
+
"Probability of success p must be between 0.0 and 1.0",
|
|
59
|
+
)
|
|
60
|
+
|
|
61
|
+
self.__p = float(value)
|
|
62
|
+
|
|
63
|
+
def _sample_bernoulli(self, n: int) -> npt.NDArray[np.float64]:
|
|
64
|
+
"""Generate a Bernoulli process realization."""
|
|
65
|
+
check_positive_integer(n=n)
|
|
66
|
+
|
|
67
|
+
return np.array(
|
|
68
|
+
[
|
|
69
|
+
1.0 if trial < self.p else 0.0
|
|
70
|
+
for trial in self.rng.uniform(
|
|
71
|
+
size=n,
|
|
72
|
+
)
|
|
73
|
+
]
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
@override
|
|
77
|
+
def sample(self, n: int) -> npt.NDArray[np.float64]:
|
|
78
|
+
return self._sample_bernoulli(n)
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Chinese restaurant 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 ..base import BaseSequenceProcess
|
|
10
|
+
from ..utils.validation import check_numeric, check_positive_integer
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _to_partition_array(partition: list[list[int]]) -> npt.NDArray[np.object_]:
|
|
14
|
+
"""Convert the customers of each table to an array of integer arrays."""
|
|
15
|
+
tables = np.empty(len(partition), dtype=object)
|
|
16
|
+
for index, table in enumerate(partition):
|
|
17
|
+
tables[index] = np.array(table, dtype=np.int64)
|
|
18
|
+
return tables
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ChineseRestaurantProcess(BaseSequenceProcess):
|
|
22
|
+
"""Chinese restaurant process.
|
|
23
|
+
|
|
24
|
+
.. image:: /_static/chinese_restaurant_process.png
|
|
25
|
+
:scale: 50%
|
|
26
|
+
|
|
27
|
+
A Chinese restaurant process consists of a sequence of arrivals of
|
|
28
|
+
customers to a Chinese restaurant. Customers may be seated either at an
|
|
29
|
+
occupied table or a new table, there being infinitely many customers
|
|
30
|
+
and tables.
|
|
31
|
+
|
|
32
|
+
The first customer sits at the first table. The :math:`n`-th customer
|
|
33
|
+
sits at a new table with probability :math:`1/n`, and at each already
|
|
34
|
+
occupied table with probability :math:`t_k/n`, where :math:`t_k` is the
|
|
35
|
+
number of customers already seated at table :math:`k`. This is the
|
|
36
|
+
canonical process with :math:`discount=0` and :math:`strength=1`.
|
|
37
|
+
|
|
38
|
+
The generalized process gives the :math:`n`-th customer a probability of
|
|
39
|
+
:math:`(strength + T * discount) / (n - 1 + strength)` to sit at a new
|
|
40
|
+
table and a probability of :math:`(t_k - discount) / (n - 1 + strength)`
|
|
41
|
+
of sitting at table :math:`k`. :math:`T` is the number of occupied tables.
|
|
42
|
+
|
|
43
|
+
Samples provide a sequence of tables selected by a sequence of customers.
|
|
44
|
+
|
|
45
|
+
:param discount: the discount value of existing tables.
|
|
46
|
+
Must be strictly less than 1.
|
|
47
|
+
:param strength: the strength of a new table. If discount
|
|
48
|
+
is negative, strength must be a multiple of discount. If discount is
|
|
49
|
+
nonnegative, strength must be strictly greater than the
|
|
50
|
+
negative discount.
|
|
51
|
+
:param rng: a custom random number generator
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(
|
|
55
|
+
self,
|
|
56
|
+
discount: float = 0.0,
|
|
57
|
+
strength: float = 1.0,
|
|
58
|
+
rng: Generator | None = None,
|
|
59
|
+
) -> None:
|
|
60
|
+
super().__init__(rng=rng)
|
|
61
|
+
|
|
62
|
+
self.discount = discount
|
|
63
|
+
self.strength = strength
|
|
64
|
+
|
|
65
|
+
def __str__(self) -> str:
|
|
66
|
+
return (
|
|
67
|
+
f"Chinese restaurant process with discount={self.discount} and strength={self.strength}"
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
def __repr__(self) -> str:
|
|
71
|
+
return f"ChineseRestaurantProcess(discount={self.discount}, strength={self.strength})"
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def discount(self) -> float:
|
|
75
|
+
"""Discount parameter."""
|
|
76
|
+
return self.__discount
|
|
77
|
+
|
|
78
|
+
@discount.setter
|
|
79
|
+
def discount(self, value: float | int) -> None:
|
|
80
|
+
check_numeric(value=value, name="Discount")
|
|
81
|
+
|
|
82
|
+
if value >= 1.0:
|
|
83
|
+
raise ValueError(f"Discount value must be less than 1; got {value}.")
|
|
84
|
+
|
|
85
|
+
self.__discount = value
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def strength(self) -> float:
|
|
89
|
+
"""Strength parameter."""
|
|
90
|
+
return self.__strength
|
|
91
|
+
|
|
92
|
+
@strength.setter
|
|
93
|
+
def strength(self, value: float | int) -> None:
|
|
94
|
+
check_numeric(value=value, name="Strength")
|
|
95
|
+
|
|
96
|
+
if self.discount < 0:
|
|
97
|
+
strength_positive = 1.0 * value / -self.discount <= 0
|
|
98
|
+
strength_not_multiple = (1.0 * value / -self.discount) % 1 != 0
|
|
99
|
+
if strength_positive or strength_not_multiple:
|
|
100
|
+
raise ValueError(
|
|
101
|
+
"When discount is negative, strength value must be equal to a multiple of"
|
|
102
|
+
f" the discount value; got {value}."
|
|
103
|
+
)
|
|
104
|
+
elif self.discount < 1:
|
|
105
|
+
if value <= -self.discount:
|
|
106
|
+
raise ValueError(
|
|
107
|
+
"When discount is between 0 and 1, strength value must be greater than the "
|
|
108
|
+
f"negative of the discount; got {value}."
|
|
109
|
+
)
|
|
110
|
+
self.__strength = value
|
|
111
|
+
|
|
112
|
+
def _sample_chinese_restaurant(
|
|
113
|
+
self,
|
|
114
|
+
n: int,
|
|
115
|
+
) -> tuple[list[int], list[list[int]]]:
|
|
116
|
+
"""Generate a Chinese restaurant process with n customers.
|
|
117
|
+
|
|
118
|
+
:returns: the table of each customer and the customers of each table
|
|
119
|
+
"""
|
|
120
|
+
check_positive_integer(n=n)
|
|
121
|
+
|
|
122
|
+
c: list[list[int]] = [[0]]
|
|
123
|
+
s = [0]
|
|
124
|
+
num_tables = 1
|
|
125
|
+
table_range = [0, 1]
|
|
126
|
+
|
|
127
|
+
for k in range(2, n + 1):
|
|
128
|
+
p = [
|
|
129
|
+
1.0 * (len(c[t]) - self.discount) / (k - 1 + self.strength)
|
|
130
|
+
for t in table_range[:-1]
|
|
131
|
+
]
|
|
132
|
+
p.append(1.0 * (self.strength + num_tables * self.discount) / (k - 1 + self.strength))
|
|
133
|
+
table = int(self.rng.choice(table_range, p=p))
|
|
134
|
+
if table == num_tables:
|
|
135
|
+
num_tables += 1
|
|
136
|
+
table_range.append(num_tables)
|
|
137
|
+
c.append([])
|
|
138
|
+
c[table].append(k - 1)
|
|
139
|
+
s.append(table)
|
|
140
|
+
|
|
141
|
+
return s, c
|
|
142
|
+
|
|
143
|
+
@override
|
|
144
|
+
def sample(self, n: int) -> npt.NDArray[np.int64]:
|
|
145
|
+
sequence, _ = self._sample_chinese_restaurant(n)
|
|
146
|
+
return np.array(sequence, dtype=np.int64)
|
|
147
|
+
|
|
148
|
+
def sample_partition(self, n: int) -> npt.NDArray[np.object_]:
|
|
149
|
+
"""Generate a realization as a partition of the customers.
|
|
150
|
+
|
|
151
|
+
:param n: the number of customers to simulate
|
|
152
|
+
:returns: one array per table holding the indices of its customers
|
|
153
|
+
"""
|
|
154
|
+
_, partition = self._sample_chinese_restaurant(n)
|
|
155
|
+
return _to_partition_array(partition)
|
|
156
|
+
|
|
157
|
+
def sequence_to_partition(
|
|
158
|
+
self,
|
|
159
|
+
sequence: npt.NDArray[np.int64],
|
|
160
|
+
) -> npt.NDArray[np.object_]:
|
|
161
|
+
"""Convert a realization to a partition of the customers.
|
|
162
|
+
|
|
163
|
+
:param sequence: a realization, as generated by :py:meth:`sample`
|
|
164
|
+
:returns: one array per table holding the indices of its customers
|
|
165
|
+
"""
|
|
166
|
+
partition: list[list[int]] = []
|
|
167
|
+
tables = -1
|
|
168
|
+
for idx, table in enumerate(sequence):
|
|
169
|
+
if table > tables:
|
|
170
|
+
tables = int(table)
|
|
171
|
+
partition.append([])
|
|
172
|
+
partition[int(table)].append(idx)
|
|
173
|
+
|
|
174
|
+
return _to_partition_array(partition)
|
|
175
|
+
|
|
176
|
+
def partition_to_sequence(
|
|
177
|
+
self,
|
|
178
|
+
partition: npt.NDArray[np.object_],
|
|
179
|
+
) -> npt.NDArray[np.int64]:
|
|
180
|
+
"""Convert a partition of the customers to a realization.
|
|
181
|
+
|
|
182
|
+
:param partition: a partition, as generated by
|
|
183
|
+
:py:meth:`sample_partition`
|
|
184
|
+
:returns: the table index of each customer
|
|
185
|
+
"""
|
|
186
|
+
length = 0
|
|
187
|
+
for table in partition:
|
|
188
|
+
length += len(table)
|
|
189
|
+
sequence = [0] * length
|
|
190
|
+
for idx, table in enumerate(partition):
|
|
191
|
+
for c in table:
|
|
192
|
+
sequence[c] = idx
|
|
193
|
+
|
|
194
|
+
return np.array(sequence, dtype=np.int64)
|