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,97 @@
|
|
|
1
|
+
"""Dirichlet 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 ..base import BaseSequenceProcess
|
|
11
|
+
from ..utils.validation import check_positive_number
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class DirichletProcess(BaseSequenceProcess):
|
|
15
|
+
r"""Dirichlet process.
|
|
16
|
+
|
|
17
|
+
.. image:: /_static/dirichlet_process.png
|
|
18
|
+
:scale: 50%
|
|
19
|
+
|
|
20
|
+
A Dirichlet process is a stochastic process in which the resulting samples
|
|
21
|
+
can be interpreted as discrete probability distributions.
|
|
22
|
+
|
|
23
|
+
For each step :math:`k \geq 1`, draw from the base distribution with
|
|
24
|
+
probability
|
|
25
|
+
|
|
26
|
+
.. math::
|
|
27
|
+
\frac{\alpha}{\alpha + k - 1}
|
|
28
|
+
|
|
29
|
+
Otherwise draw randomly from the previous steps.
|
|
30
|
+
|
|
31
|
+
:param base: a zero argument callable used as the base
|
|
32
|
+
distribution sampler. The default base distribution is Uniform(0, 1).
|
|
33
|
+
:param alpha: a non-negative value used to determine probability of
|
|
34
|
+
drawing a new value from the base distribution
|
|
35
|
+
:param rng: a custom random number generator
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
base: Callable[[], float] | None = None,
|
|
41
|
+
alpha: float = 1,
|
|
42
|
+
rng: Generator | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
super().__init__(rng=rng)
|
|
45
|
+
|
|
46
|
+
if base is None:
|
|
47
|
+
base = self.rng.uniform
|
|
48
|
+
|
|
49
|
+
self.base = base
|
|
50
|
+
self.alpha = alpha
|
|
51
|
+
|
|
52
|
+
def __str__(self) -> str:
|
|
53
|
+
return f"Dirichlet process with alpha={self.alpha} and base distribution {self.base}"
|
|
54
|
+
|
|
55
|
+
def __repr__(self) -> str:
|
|
56
|
+
return f"DirichletProcess(alpha={self.alpha}, base={self.base})"
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def base(self) -> Callable[[], float]:
|
|
60
|
+
"""The base distribution callable for sampling new step values."""
|
|
61
|
+
return self.__base
|
|
62
|
+
|
|
63
|
+
@base.setter
|
|
64
|
+
def base(self, value: Callable[[], float]) -> None:
|
|
65
|
+
if not callable(value):
|
|
66
|
+
raise TypeError("base must be callable")
|
|
67
|
+
|
|
68
|
+
self.__base = value
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def alpha(self) -> float:
|
|
72
|
+
"""Parameter for determining the probability of sampling new values."""
|
|
73
|
+
return self.__alpha
|
|
74
|
+
|
|
75
|
+
@alpha.setter
|
|
76
|
+
def alpha(self, value: float) -> None:
|
|
77
|
+
check_positive_number(value=value, name="alpha")
|
|
78
|
+
|
|
79
|
+
self.__alpha = value
|
|
80
|
+
|
|
81
|
+
def _sample(self, n: int) -> npt.NDArray[np.float64]:
|
|
82
|
+
"""Generate a realization of the Dirichlet process.
|
|
83
|
+
|
|
84
|
+
:param n: the number of steps of the Dirichlet process to generate.
|
|
85
|
+
"""
|
|
86
|
+
sequence = np.empty(n, dtype=np.float64)
|
|
87
|
+
for k in range(n):
|
|
88
|
+
p = self.alpha / (self.alpha + k)
|
|
89
|
+
if self.rng.uniform() < p:
|
|
90
|
+
sequence[k] = self.base()
|
|
91
|
+
else:
|
|
92
|
+
sequence[k] = self.rng.choice(sequence[:k])
|
|
93
|
+
return sequence
|
|
94
|
+
|
|
95
|
+
@override
|
|
96
|
+
def sample(self, n: int) -> npt.NDArray[np.float64]:
|
|
97
|
+
return self._sample(n)
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
"""Finite state Markov chain."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Iterable
|
|
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 ..base import BaseSequenceProcess
|
|
11
|
+
from ..utils.validation import check_positive_integer
|
|
12
|
+
|
|
13
|
+
DEFAULT_TRANSITION: npt.NDArray[np.float64] = np.array(
|
|
14
|
+
[[0.5, 0.5], [0.5, 0.5]],
|
|
15
|
+
dtype=np.float64,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class MarkovChain(BaseSequenceProcess):
|
|
20
|
+
"""Finite state Markov chain.
|
|
21
|
+
|
|
22
|
+
.. image:: /_static/markov_chain.png
|
|
23
|
+
:scale: 50%
|
|
24
|
+
|
|
25
|
+
A Markov Chain which changes between states according to the transition
|
|
26
|
+
matrix.
|
|
27
|
+
|
|
28
|
+
:param transition: a square matrix representing the transition
|
|
29
|
+
probabilities between states.
|
|
30
|
+
:param initial: a vector representing the initial state probabilities. If
|
|
31
|
+
not provided, each state has equal initial probability.
|
|
32
|
+
:param rng: a custom random number generator
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
def __init__(
|
|
36
|
+
self,
|
|
37
|
+
transition: Iterable[Iterable[float]] | npt.NDArray[np.float64] = DEFAULT_TRANSITION,
|
|
38
|
+
initial: Iterable[float] | npt.NDArray[np.float64] | None = None,
|
|
39
|
+
rng: Generator | None = None,
|
|
40
|
+
) -> None:
|
|
41
|
+
super().__init__(rng=rng)
|
|
42
|
+
|
|
43
|
+
self.transition = transition
|
|
44
|
+
|
|
45
|
+
if initial is None:
|
|
46
|
+
initial = [float(1.0 / len(self.transition)) for _ in self.transition]
|
|
47
|
+
|
|
48
|
+
self.initial = initial
|
|
49
|
+
|
|
50
|
+
self.__num_states = len(self.__initial)
|
|
51
|
+
|
|
52
|
+
def __str__(self) -> str:
|
|
53
|
+
return (
|
|
54
|
+
f"Markov chain with transition matrix = {self.transition} "
|
|
55
|
+
f"and initial state probabilities = {self.initial}"
|
|
56
|
+
)
|
|
57
|
+
|
|
58
|
+
def __repr__(self) -> str:
|
|
59
|
+
return f"MarkovChain(transition={self.transition}, initial={self.initial})"
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def transition(self) -> npt.NDArray[np.float64]:
|
|
63
|
+
"""Transition probability matrix."""
|
|
64
|
+
return self.__transition
|
|
65
|
+
|
|
66
|
+
@transition.setter
|
|
67
|
+
def transition(self, values: Iterable[Iterable[float]] | npt.NDArray[np.float64]) -> None:
|
|
68
|
+
values = np.asarray(values, dtype=np.float64)
|
|
69
|
+
|
|
70
|
+
if values.ndim != 2:
|
|
71
|
+
raise ValueError(
|
|
72
|
+
f"Transition matrix must be a two-dimensional array; got {values.ndim} dimensions."
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
if values.shape[0] != values.shape[1]:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
"Transition matrix must be a square matrix; "
|
|
78
|
+
f"got {values.shape[0]}x{values.shape[1]}."
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
for row in values:
|
|
82
|
+
if not np.isclose(np.sum(row), 1.0):
|
|
83
|
+
raise ValueError(
|
|
84
|
+
"Transition matrix is not a proper stochastic matrix; "
|
|
85
|
+
f"row sums to {np.sum(row)}."
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
self.__transition = values
|
|
89
|
+
|
|
90
|
+
@property
|
|
91
|
+
def initial(self) -> npt.NDArray[np.float64]:
|
|
92
|
+
"""Vector of initial state probabilities."""
|
|
93
|
+
return self.__initial
|
|
94
|
+
|
|
95
|
+
@initial.setter
|
|
96
|
+
def initial(self, values: Iterable[float] | npt.NDArray[np.float64]) -> None:
|
|
97
|
+
values = np.asarray(values, dtype=np.float64)
|
|
98
|
+
|
|
99
|
+
if values.ndim != 1:
|
|
100
|
+
raise ValueError(
|
|
101
|
+
"Initial state probabilities must be a one-dimensional vector; "
|
|
102
|
+
f"got {values.ndim} dimensions."
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
if len(values) != len(self.transition):
|
|
106
|
+
raise ValueError(
|
|
107
|
+
"Length of initial state probabilities must match the number of states in the "
|
|
108
|
+
f"transition matrix; got {len(values)} values for {len(self.transition)} states."
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
if not np.isclose(np.sum(values), 1.0):
|
|
112
|
+
raise ValueError(f"Initial state probabilities must sum to 1; got {np.sum(values)}.")
|
|
113
|
+
|
|
114
|
+
self.__initial = values
|
|
115
|
+
|
|
116
|
+
@property
|
|
117
|
+
def num_states(self) -> int:
|
|
118
|
+
"""Number of states in the Markov chain."""
|
|
119
|
+
return self.__num_states
|
|
120
|
+
|
|
121
|
+
@override
|
|
122
|
+
def sample(self, n: int) -> npt.NDArray[np.int64]:
|
|
123
|
+
check_positive_integer(n=n)
|
|
124
|
+
|
|
125
|
+
states = range(self.num_states)
|
|
126
|
+
|
|
127
|
+
markov_chain = [self.rng.choice(states, p=self.initial)]
|
|
128
|
+
for _ in range(n - 1):
|
|
129
|
+
markov_chain.append(self.rng.choice(states, p=self.transition[markov_chain[-1]]))
|
|
130
|
+
|
|
131
|
+
return np.array(markov_chain, dtype=np.int64)
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""Moran 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_integer
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _probabilities(n: int) -> npt.NDArray[np.float64]:
|
|
14
|
+
"""Generate the transition probabilities for state :math:`n`.
|
|
15
|
+
|
|
16
|
+
:param n: the current state for which to generate transition
|
|
17
|
+
probabilities.
|
|
18
|
+
"""
|
|
19
|
+
probabilities = []
|
|
20
|
+
for k in range(1, n):
|
|
21
|
+
p_down = 1.0 * (n - k) / n * k / n
|
|
22
|
+
p_up = 1.0 * k / n * (n - k) / n
|
|
23
|
+
p_same = 1.0 - p_down - p_up
|
|
24
|
+
probabilities.append([p_down, p_same, p_up])
|
|
25
|
+
|
|
26
|
+
return np.asarray(probabilities)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MoranProcess(BaseSequenceProcess):
|
|
30
|
+
"""Moran process.
|
|
31
|
+
|
|
32
|
+
.. image:: /_static/moran_process.png
|
|
33
|
+
:scale: 50%
|
|
34
|
+
|
|
35
|
+
A neutral drift Moran process, typically used to model populations. At
|
|
36
|
+
each step this process will increase by one, decrease by one, or remain
|
|
37
|
+
at the same value between values of zero and the number of
|
|
38
|
+
states, :math:`n`. The process ends when its value reaches zero or the
|
|
39
|
+
maximum valued state.
|
|
40
|
+
|
|
41
|
+
:param maximum: the maximum possible value for the process.
|
|
42
|
+
:param rng: a custom random number generator
|
|
43
|
+
"""
|
|
44
|
+
|
|
45
|
+
def __init__(
|
|
46
|
+
self,
|
|
47
|
+
maximum: int,
|
|
48
|
+
rng: Generator | None = None,
|
|
49
|
+
) -> None:
|
|
50
|
+
super().__init__(rng=rng)
|
|
51
|
+
|
|
52
|
+
self.maximum = maximum
|
|
53
|
+
self.__p = _probabilities(maximum)
|
|
54
|
+
|
|
55
|
+
def __str__(self) -> str:
|
|
56
|
+
return f"Moran process with {self.maximum} states"
|
|
57
|
+
|
|
58
|
+
def __repr__(self) -> str:
|
|
59
|
+
return f"MoranProcess(maximum={self.maximum})"
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def maximum(self) -> int:
|
|
63
|
+
"""Maximum value."""
|
|
64
|
+
return self.__maximum
|
|
65
|
+
|
|
66
|
+
@maximum.setter
|
|
67
|
+
def maximum(self, n: int) -> None:
|
|
68
|
+
check_positive_integer(n=n, name="Maximum value")
|
|
69
|
+
|
|
70
|
+
if n < 3:
|
|
71
|
+
raise ValueError(f"Number of states must be at least 3; got {n}.")
|
|
72
|
+
|
|
73
|
+
self.__maximum = n
|
|
74
|
+
|
|
75
|
+
def _sample_moran_process(
|
|
76
|
+
self,
|
|
77
|
+
n: int,
|
|
78
|
+
start: int,
|
|
79
|
+
) -> npt.NDArray[np.int64]:
|
|
80
|
+
"""Generate a realization of the Moran process.
|
|
81
|
+
|
|
82
|
+
Generate a Moran process until absorption occurs (state 0 or n) or
|
|
83
|
+
length of process reaches length :math:`maximum`.
|
|
84
|
+
"""
|
|
85
|
+
if not is_integer(start):
|
|
86
|
+
raise TypeError("Initial state must be a positive integer.")
|
|
87
|
+
|
|
88
|
+
if start < 0 or start > self.maximum:
|
|
89
|
+
raise ValueError("Initial state must be between 0 and " + str(self.maximum))
|
|
90
|
+
|
|
91
|
+
if not is_integer(n):
|
|
92
|
+
raise TypeError("Sample length must be positive integer.")
|
|
93
|
+
|
|
94
|
+
if n < 1:
|
|
95
|
+
raise ValueError("Sample length must be at least 1.")
|
|
96
|
+
|
|
97
|
+
start = int(start)
|
|
98
|
+
s = [start]
|
|
99
|
+
increments = [-1, 0, 1]
|
|
100
|
+
for _ in range(n - 1):
|
|
101
|
+
if start in (0, self.maximum):
|
|
102
|
+
break
|
|
103
|
+
start += int(self.rng.choice(increments, p=self.__p[start - 1]))
|
|
104
|
+
s.append(start)
|
|
105
|
+
|
|
106
|
+
return np.array(s, dtype=np.int64)
|
|
107
|
+
|
|
108
|
+
@override
|
|
109
|
+
def sample(self, n: int) -> npt.NDArray[np.int64]:
|
|
110
|
+
return self._sample_moran_process(n, 1)
|
|
111
|
+
|
|
112
|
+
def sample_with_start(self, n: int, start: int) -> npt.NDArray[np.int64]:
|
|
113
|
+
"""Generate a realization starting from a specified state.
|
|
114
|
+
|
|
115
|
+
The realization ends early if the process reaches zero or the maximum
|
|
116
|
+
value.
|
|
117
|
+
|
|
118
|
+
:param n: the maximum number of values to generate
|
|
119
|
+
:param start: the initial state of the process
|
|
120
|
+
:returns: the realization
|
|
121
|
+
"""
|
|
122
|
+
return self._sample_moran_process(n, start)
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Random walk."""
|
|
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 (
|
|
11
|
+
check_nonnegative_number,
|
|
12
|
+
check_numeric,
|
|
13
|
+
check_positive_integer,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RandomWalk(BaseSequenceProcess):
|
|
18
|
+
"""Random walk.
|
|
19
|
+
|
|
20
|
+
.. image:: /_static/random_walk.png
|
|
21
|
+
:scale: 50%
|
|
22
|
+
|
|
23
|
+
A random walk is a sequence of random steps taken from a set of step sizes
|
|
24
|
+
with a probability distribution. By default this object defines the steps
|
|
25
|
+
to be [-1, 1] with probability 1/2 for each possibility.
|
|
26
|
+
|
|
27
|
+
:param steps: a vector of possible deltas to apply at each step.
|
|
28
|
+
:param weights: a corresponding vector of weights associated with each
|
|
29
|
+
step value. If not provided each step has equal weight/probability.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
*,
|
|
35
|
+
steps: list[float | int] | npt.NDArray[np.float64] | None = None,
|
|
36
|
+
weights: list[float | int] | npt.NDArray[np.float64] | None = None,
|
|
37
|
+
rng: Generator | None = None,
|
|
38
|
+
) -> None:
|
|
39
|
+
super().__init__(rng=rng)
|
|
40
|
+
self.steps = steps or [-1.0, 1.0]
|
|
41
|
+
|
|
42
|
+
length = len(self.steps)
|
|
43
|
+
if length < 1:
|
|
44
|
+
raise ValueError("Steps must have at least one element.")
|
|
45
|
+
|
|
46
|
+
if weights is None:
|
|
47
|
+
self.weights = [1.0 for _ in self.steps]
|
|
48
|
+
self.p = [1.0 / length for _ in self.steps]
|
|
49
|
+
else:
|
|
50
|
+
if len(weights) != length:
|
|
51
|
+
raise ValueError("Steps and probabilities must have same length.")
|
|
52
|
+
|
|
53
|
+
self.weights = weights
|
|
54
|
+
total = sum(weights)
|
|
55
|
+
self.p = [1.0 * w / total for w in weights]
|
|
56
|
+
|
|
57
|
+
def __str__(self) -> str:
|
|
58
|
+
return f"Random walk steps = {self.steps} and weights = {self.weights}"
|
|
59
|
+
|
|
60
|
+
def __repr__(self) -> str:
|
|
61
|
+
return f"RandomWalk(steps={self.steps}, weights={self.weights})"
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def p(self) -> npt.NDArray[np.float64]:
|
|
65
|
+
"""Step probabilities, normalized from :py:attr:`weights`."""
|
|
66
|
+
return self.__p
|
|
67
|
+
|
|
68
|
+
@p.setter
|
|
69
|
+
def p(self, values: list[float] | npt.NDArray[np.float64]) -> None:
|
|
70
|
+
self.__p = np.array(values, dtype=np.float64, copy=True)
|
|
71
|
+
|
|
72
|
+
@property
|
|
73
|
+
def steps(self) -> npt.NDArray[np.float64]:
|
|
74
|
+
"""Possible steps."""
|
|
75
|
+
return self.__steps
|
|
76
|
+
|
|
77
|
+
@steps.setter
|
|
78
|
+
def steps(self, values: list[float | int] | npt.NDArray[np.float64]) -> None:
|
|
79
|
+
for i, value in enumerate(values):
|
|
80
|
+
check_numeric(value=value, name=f"Step values[{i}] = {value}")
|
|
81
|
+
|
|
82
|
+
self.__steps = np.array(values, dtype=np.float64, copy=True)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def weights(self) -> npt.NDArray[np.float64]:
|
|
86
|
+
"""Step weights provided."""
|
|
87
|
+
return self.__weights
|
|
88
|
+
|
|
89
|
+
@weights.setter
|
|
90
|
+
def weights(self, values: list[float | int] | npt.NDArray[np.float64]) -> None:
|
|
91
|
+
for i, value in enumerate(values):
|
|
92
|
+
check_nonnegative_number(value=value, name=f"Weight values[{i}] = {value}")
|
|
93
|
+
|
|
94
|
+
self.__weights = np.array(values, dtype=np.float64, copy=True)
|
|
95
|
+
|
|
96
|
+
def _sample_random_walk(self, n: int) -> npt.NDArray[np.float64]:
|
|
97
|
+
"""Generate a random walk."""
|
|
98
|
+
return np.array([0] + list(np.cumsum(self._sample_random_walk_increments(n))))
|
|
99
|
+
|
|
100
|
+
@override
|
|
101
|
+
def sample(self, n: int) -> npt.NDArray[np.float64]:
|
|
102
|
+
return self._sample_random_walk(n)
|
|
103
|
+
|
|
104
|
+
def _sample_random_walk_increments(self, n: int) -> npt.NDArray[np.float64]:
|
|
105
|
+
"""Generate a sample of random walk increments."""
|
|
106
|
+
check_positive_integer(n=n)
|
|
107
|
+
return self.rng.choice(self.steps, p=self.p, size=n)
|
|
108
|
+
|
|
109
|
+
def sample_increments(self, n: int) -> npt.NDArray[np.float64]:
|
|
110
|
+
"""Generate the increments of a realization.
|
|
111
|
+
|
|
112
|
+
:param n: the number of increments to generate
|
|
113
|
+
:returns: the increments
|
|
114
|
+
"""
|
|
115
|
+
return self._sample_random_walk_increments(n)
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Noise processes."""
|
|
2
|
+
|
|
3
|
+
from .colored import (
|
|
4
|
+
BlueNoise,
|
|
5
|
+
BrownianNoise,
|
|
6
|
+
ColoredNoise,
|
|
7
|
+
PinkNoise,
|
|
8
|
+
RedNoise,
|
|
9
|
+
VioletNoise,
|
|
10
|
+
WhiteNoise,
|
|
11
|
+
)
|
|
12
|
+
from .fractional_gaussian_noise import FractionalGaussianNoise
|
|
13
|
+
from .gaussian_noise import GaussianNoise
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"BlueNoise",
|
|
17
|
+
"BrownianNoise",
|
|
18
|
+
"ColoredNoise",
|
|
19
|
+
"FractionalGaussianNoise",
|
|
20
|
+
"GaussianNoise",
|
|
21
|
+
"PinkNoise",
|
|
22
|
+
"RedNoise",
|
|
23
|
+
"VioletNoise",
|
|
24
|
+
"WhiteNoise",
|
|
25
|
+
]
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""Colored noise processes."""
|
|
2
|
+
|
|
3
|
+
from .blue_noise import BlueNoise
|
|
4
|
+
from .brownian_noise import BrownianNoise
|
|
5
|
+
from .colored_noise import ColoredNoise
|
|
6
|
+
from .pink_noise import PinkNoise
|
|
7
|
+
from .red_noise import RedNoise
|
|
8
|
+
from .violet_noise import VioletNoise
|
|
9
|
+
from .white_noise import WhiteNoise
|
|
10
|
+
|
|
11
|
+
__all__ = [
|
|
12
|
+
"BlueNoise",
|
|
13
|
+
"BrownianNoise",
|
|
14
|
+
"ColoredNoise",
|
|
15
|
+
"PinkNoise",
|
|
16
|
+
"RedNoise",
|
|
17
|
+
"VioletNoise",
|
|
18
|
+
"WhiteNoise",
|
|
19
|
+
]
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"""Blue noise."""
|
|
2
|
+
|
|
3
|
+
from numpy.random import Generator
|
|
4
|
+
|
|
5
|
+
from .colored_noise import ColoredNoise
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class BlueNoise(ColoredNoise):
|
|
9
|
+
r"""Blue noise.
|
|
10
|
+
|
|
11
|
+
.. image:: /_static/blue_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,18 @@
|
|
|
1
|
+
"""Brownian (red) noise."""
|
|
2
|
+
|
|
3
|
+
from .red_noise import RedNoise
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class BrownianNoise(RedNoise):
|
|
7
|
+
r"""Brownian (red) noise.
|
|
8
|
+
|
|
9
|
+
.. image:: /_static/red_noise.png
|
|
10
|
+
:scale: 50%
|
|
11
|
+
|
|
12
|
+
Colored noise, or power law noise with spectral density exponent
|
|
13
|
+
:math:`\beta = 2`.
|
|
14
|
+
|
|
15
|
+
:param t: the right hand endpoint of the time interval :math:`[0,t]`
|
|
16
|
+
for the process
|
|
17
|
+
:param rng: a custom random number generator
|
|
18
|
+
"""
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""Colored noise processes."""
|
|
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 BaseTimeProcess
|
|
10
|
+
from ...utils.validation import check_numeric, check_positive_integer
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ColoredNoise(BaseTimeProcess):
|
|
14
|
+
r"""Colored noise processes.
|
|
15
|
+
|
|
16
|
+
.. image:: /_static/colored_noise.png
|
|
17
|
+
:scale: 50%
|
|
18
|
+
|
|
19
|
+
Also referred to as power law noise, colored noise refers to noise
|
|
20
|
+
processes with power law spectral density. That is, their spectral density
|
|
21
|
+
per unit bandwidth is proportional to :math:`(1/f)^\beta`, where
|
|
22
|
+
:math:`f` is frequency with exponent :math:`\beta`.
|
|
23
|
+
|
|
24
|
+
Uses the algorithm from:
|
|
25
|
+
|
|
26
|
+
* Timmer, J., and M. Koenig. "On generating power law noise."
|
|
27
|
+
Astronomy and Astrophysics 300 (1995): 707.
|
|
28
|
+
|
|
29
|
+
Generates a normalized power-law spectral noise.
|
|
30
|
+
|
|
31
|
+
:param beta: the power law exponent for the spectral density, with 0
|
|
32
|
+
being white noise, 1 being pink noise, 2 being red noise (Brownian
|
|
33
|
+
noise), -1 being blue noise, -2 being violet noise. Default is 0
|
|
34
|
+
(white noise).
|
|
35
|
+
:param t: the right hand endpoint of the time interval :math:`[0,t]`
|
|
36
|
+
for the process
|
|
37
|
+
:param rng: a custom random number generator
|
|
38
|
+
"""
|
|
39
|
+
|
|
40
|
+
def __init__(
|
|
41
|
+
self,
|
|
42
|
+
*,
|
|
43
|
+
beta: float = 0,
|
|
44
|
+
t: float = 1.0,
|
|
45
|
+
rng: Generator | None = None,
|
|
46
|
+
) -> None:
|
|
47
|
+
super().__init__(t=t, rng=rng)
|
|
48
|
+
|
|
49
|
+
self.beta = beta
|
|
50
|
+
|
|
51
|
+
self.__n: int | None = None
|
|
52
|
+
self.__half: int | None = None
|
|
53
|
+
self.__frequencies: npt.NDArray[np.float64] | None = None
|
|
54
|
+
self.__scale: npt.NDArray[np.float64] | None = None
|
|
55
|
+
|
|
56
|
+
def __str__(self) -> str:
|
|
57
|
+
return f"Colored noise generator with exponent {self.beta} on interval [0, {self.t}]"
|
|
58
|
+
|
|
59
|
+
def __repr__(self) -> str:
|
|
60
|
+
return f"ColoredNoise(beta={self.beta}, t={self.t})"
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def beta(self) -> float:
|
|
64
|
+
"""Power law exponent."""
|
|
65
|
+
return self.__beta
|
|
66
|
+
|
|
67
|
+
@beta.setter
|
|
68
|
+
def beta(self, value: float) -> None:
|
|
69
|
+
check_numeric(value=value, name="beta")
|
|
70
|
+
|
|
71
|
+
self.__beta = value
|
|
72
|
+
|
|
73
|
+
def _sample_colored_noise(self, n: int) -> npt.NDArray[np.float64]:
|
|
74
|
+
"""Generate colored noise increments at specified times from zero."""
|
|
75
|
+
check_positive_integer(n=n, name="Number of increments")
|
|
76
|
+
self.set_times(n)
|
|
77
|
+
|
|
78
|
+
if self.__n != n:
|
|
79
|
+
self.__n = n
|
|
80
|
+
|
|
81
|
+
self.__half = (n + 1) // 2
|
|
82
|
+
|
|
83
|
+
self.__frequencies = np.fft.fftfreq(
|
|
84
|
+
n,
|
|
85
|
+
self.t,
|
|
86
|
+
) # type: ignore[assignment]
|
|
87
|
+
assert self.__frequencies is not None
|
|
88
|
+
|
|
89
|
+
self.__scale = np.asarray(
|
|
90
|
+
[np.sqrt(0.5 * (1 / w) ** self.beta) for w in self.__frequencies[1 : self.__half]]
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
assert self.__frequencies is not None
|
|
94
|
+
assert self.__half is not None
|
|
95
|
+
|
|
96
|
+
gn_real = self.rng.normal(size=self.__half - 1)
|
|
97
|
+
gn_imag = self.rng.normal(size=self.__half - 1)
|
|
98
|
+
fft = self.__scale * (gn_real + 1j * gn_imag)
|
|
99
|
+
|
|
100
|
+
f: npt.NDArray[np.float64]
|
|
101
|
+
if n % 2 == 0:
|
|
102
|
+
f = np.concatenate(
|
|
103
|
+
(
|
|
104
|
+
[0],
|
|
105
|
+
fft,
|
|
106
|
+
[
|
|
107
|
+
np.sqrt(0.5 * (1 / -self.__frequencies[self.__half]) ** self.beta)
|
|
108
|
+
* self.rng.normal()
|
|
109
|
+
],
|
|
110
|
+
np.conj(fft)[::-1],
|
|
111
|
+
)
|
|
112
|
+
)
|
|
113
|
+
else:
|
|
114
|
+
f = np.concatenate(([0], fft, np.conj(fft)[::-1]))
|
|
115
|
+
|
|
116
|
+
return np.fft.ifft(f).real / np.std(f)
|
|
117
|
+
|
|
118
|
+
@override
|
|
119
|
+
def sample(self, n: int) -> npt.NDArray[np.float64]:
|
|
120
|
+
return self._sample_colored_noise(n)
|