samplepaths 0.1.1__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. {samplepaths-0.1.1 → samplepaths-0.2.0}/PKG-INFO +1 -1
  2. {samplepaths-0.1.1 → samplepaths-0.2.0}/pyproject.toml +1 -1
  3. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/bessel_process.py +7 -4
  4. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/brownian_excursion.py +4 -12
  5. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/brownian_motion.py +1 -1
  6. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/cauchy_process.py +29 -17
  7. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/gamma_process.py +6 -7
  8. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/inverse_gaussian_process.py +5 -19
  9. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/multifractional_brownian_motion.py +14 -21
  10. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/poisson_process.py +1 -3
  11. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/squared_bessel_process.py +6 -4
  12. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/variance_gamma_process.py +1 -10
  13. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/discrete/bernoulli_process.py +1 -8
  14. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/discrete/chinese_restaurant_process.py +20 -8
  15. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/discrete/dirichlet_process.py +11 -6
  16. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/discrete/markov_chain.py +20 -5
  17. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/discrete/moran_process.py +15 -4
  18. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/discrete/random_walk.py +2 -1
  19. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/colored/colored_noise.py +9 -13
  20. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/fractional_gaussian_noise.py +11 -12
  21. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/gaussian_noise.py +1 -10
  22. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/utils/validation.py +4 -3
  23. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_cauchy_process.py +14 -0
  24. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/discrete/test_moran_process.py +10 -0
  25. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/colored/test_colored_noise.py +15 -0
  26. {samplepaths-0.1.1 → samplepaths-0.2.0}/.gitignore +0 -0
  27. {samplepaths-0.1.1 → samplepaths-0.2.0}/LICENSE +0 -0
  28. {samplepaths-0.1.1 → samplepaths-0.2.0}/README.md +0 -0
  29. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/__init__.py +0 -0
  30. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/base/__init__.py +0 -0
  31. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/base/base_process.py +0 -0
  32. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/base/base_sequence_process.py +0 -0
  33. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/base/base_time_process.py +0 -0
  34. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/__init__.py +0 -0
  35. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/brownian_bridge.py +0 -0
  36. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/brownian_meander.py +0 -0
  37. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/fractional_brownian_motion.py +0 -0
  38. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/geometric_brownian_motion.py +0 -0
  39. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/mixed_poisson_process.py +0 -0
  40. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/continuous/wiener_process.py +0 -0
  41. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/diffusion/__init__.py +0 -0
  42. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/diffusion/constant_elasticity_variance_process.py +0 -0
  43. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/diffusion/cox_ingersoll_ross_process.py +0 -0
  44. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/diffusion/diffusion_process.py +0 -0
  45. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/diffusion/extended_vasicek_process.py +0 -0
  46. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/diffusion/ornstein_uhlenbeck_process.py +0 -0
  47. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/diffusion/vasicek_process.py +0 -0
  48. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/discrete/__init__.py +0 -0
  49. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/__init__.py +0 -0
  50. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/colored/__init__.py +0 -0
  51. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/colored/blue_noise.py +0 -0
  52. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/colored/brownian_noise.py +0 -0
  53. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/colored/pink_noise.py +0 -0
  54. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/colored/red_noise.py +0 -0
  55. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/colored/violet_noise.py +0 -0
  56. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/noise/colored/white_noise.py +0 -0
  57. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/py.typed +0 -0
  58. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/random.py +0 -0
  59. {samplepaths-0.1.1 → samplepaths-0.2.0}/src/samplepaths/utils/__init__.py +0 -0
  60. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/__init__.py +0 -0
  61. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/base/__init__.py +0 -0
  62. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/base/test_base_process.py +0 -0
  63. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/base/test_base_sequence_process.py +0 -0
  64. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/base/test_base_time_process.py +0 -0
  65. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/__init__.py +0 -0
  66. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_bessel_process.py +0 -0
  67. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_brownian_bridge.py +0 -0
  68. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_brownian_excursion.py +0 -0
  69. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_brownian_meander.py +0 -0
  70. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_brownian_motion.py +0 -0
  71. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_fractional_brownian_motion.py +0 -0
  72. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_gamma_process.py +0 -0
  73. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_geometric_brownian_motion.py +0 -0
  74. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_inverse_gaussian_process.py +0 -0
  75. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_mixed_poisson_process.py +0 -0
  76. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_multifractional_brownian_motion.py +0 -0
  77. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_poisson_process.py +0 -0
  78. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_squared_bessel_process.py +0 -0
  79. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_variance_gamma_process.py +0 -0
  80. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/continuous/test_wiener_process.py +0 -0
  81. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/diffusion/__init__.py +0 -0
  82. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/diffusion/test_constant_elasticity_variance_process.py +0 -0
  83. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/diffusion/test_cox_ingersoll_ross_process.py +0 -0
  84. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/diffusion/test_diffusion_process.py +0 -0
  85. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/diffusion/test_extended_vasicek_process.py +0 -0
  86. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/diffusion/test_ornstein_uhlenbeck_process.py +0 -0
  87. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/diffusion/test_vasicek_process.py +0 -0
  88. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/discrete/__init__.py +0 -0
  89. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/discrete/test_bernoulli_process.py +0 -0
  90. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/discrete/test_chinese_restaurant_process.py +0 -0
  91. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/discrete/test_dirichlet_process.py +0 -0
  92. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/discrete/test_markov_chain.py +0 -0
  93. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/discrete/test_random_walk.py +0 -0
  94. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/__init__.py +0 -0
  95. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/colored/__init__.py +0 -0
  96. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/colored/test_blue_noise.py +0 -0
  97. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/colored/test_brownian_noise.py +0 -0
  98. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/colored/test_pink_noise.py +0 -0
  99. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/colored/test_red_noise.py +0 -0
  100. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/colored/test_violet_noise.py +0 -0
  101. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/colored/test_white_noise.py +0 -0
  102. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/test_fractional_gaussian_noise.py +0 -0
  103. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/noise/test_gaussian_noise.py +0 -0
  104. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/test_import.py +0 -0
  105. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/test_random.py +0 -0
  106. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/test_times.py +0 -0
  107. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/utils/__init__.py +0 -0
  108. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/utils/test_utils.py +0 -0
  109. {samplepaths-0.1.1 → samplepaths-0.2.0}/tests/utils/test_validation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: samplepaths
3
- Version: 0.1.1
3
+ Version: 0.2.0
4
4
  Summary: Generate realizations of stochastic processes
5
5
  Project-URL: Homepage, https://github.com/samplepaths/samplepaths
6
6
  Project-URL: Documentation, https://samplepaths.readthedocs.io/
@@ -110,7 +110,7 @@ convention = "pep257"
110
110
  [tool.ruff.lint.per-file-ignores]
111
111
  "tests/**" = ["D"]
112
112
  "docs/conf.py" = ["D"]
113
- "docs/scripts/make_images.py" = ["T20"]
113
+ "docs/scripts/*.py" = ["T20"]
114
114
 
115
115
 
116
116
  [tool.mypy]
@@ -63,17 +63,20 @@ class BesselProcess(BrownianMotion):
63
63
  """Generate a realization of a Bessel process."""
64
64
  check_positive_integer(n=n, name="Number of increments")
65
65
 
66
- samples = [self._sample_brownian_motion(n) for _ in range(self.dim)]
66
+ samples = np.array([self._sample_brownian_motion(n) for _ in range(self.dim)])
67
67
 
68
- return np.array([np.linalg.norm(coord) for coord in zip(*samples, strict=True)])
68
+ norms: npt.NDArray[np.float64] = np.sqrt(np.sum(np.square(samples), axis=0))
69
+ return norms
69
70
 
70
71
  def _sample_bessel_process_at(
71
72
  self,
72
73
  times: npt.NDArray[np.float64],
73
74
  ) -> npt.NDArray[np.float64]:
74
75
  """Generate a realization of a Bessel process."""
75
- samples = [self._sample_brownian_motion_at(times) for _ in range(self.dim)]
76
- return np.array([np.linalg.norm(coord) for coord in zip(*samples, strict=True)])
76
+ samples = np.array([self._sample_brownian_motion_at(times) for _ in range(self.dim)])
77
+
78
+ norms: npt.NDArray[np.float64] = np.sqrt(np.sum(np.square(samples), axis=0))
79
+ return norms
77
80
 
78
81
  @override
79
82
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -53,12 +53,8 @@ class BrownianExcursion(BrownianBridge):
53
53
  """Generate a Brownian excursion."""
54
54
  brownian_bridge = self._sample_brownian_bridge(n)
55
55
  idx_min = np.argmin(brownian_bridge)
56
- s = np.array(
57
- [
58
- brownian_bridge[(idx_min + idx) % n] - brownian_bridge[idx_min]
59
- for idx in range(n + 1)
60
- ]
61
- )
56
+ indices = (idx_min + np.arange(n + 1)) % n
57
+ s: npt.NDArray[np.float64] = brownian_bridge[indices] - brownian_bridge[idx_min]
62
58
  return s
63
59
 
64
60
  def _sample_brownian_excursion_at(
@@ -75,12 +71,8 @@ class BrownianExcursion(BrownianBridge):
75
71
  brownian_bridge = self._sample_brownian_bridge_at(times)
76
72
  idx_min = np.argmin(brownian_bridge)
77
73
  n = len(brownian_bridge)
78
- s = np.array(
79
- [
80
- brownian_bridge[(idx_min + idx) % (n - 1)] - brownian_bridge[idx_min]
81
- for idx in range(n)
82
- ]
83
- )
74
+ indices = (idx_min + np.arange(n)) % (n - 1)
75
+ s: npt.NDArray[np.float64] = brownian_bridge[indices] - brownian_bridge[idx_min]
84
76
 
85
77
  if zero:
86
78
  return s
@@ -104,7 +104,7 @@ class BrownianMotion(GaussianNoise):
104
104
  bm = np.insert(bm, 0, [0])
105
105
 
106
106
  if self.drift != 0:
107
- bm += [self.drift * t for t in times]
107
+ bm += self.drift * np.asarray(times, dtype=np.float64)
108
108
 
109
109
  return bm
110
110
 
@@ -7,7 +7,7 @@ import numpy.typing as npt
7
7
  from numpy.random import Generator
8
8
  from scipy.stats import levy
9
9
 
10
- from ..utils.validation import check_positive_integer
10
+ from ..utils.validation import check_positive_integer, times_to_increments
11
11
  from .brownian_motion import BrownianMotion
12
12
 
13
13
 
@@ -51,17 +51,30 @@ class CauchyProcess(BrownianMotion):
51
51
 
52
52
  delta_t = 1.0 * self.t / n
53
53
 
54
- times = np.cumsum(
54
+ levys = np.asarray(
55
55
  levy.rvs(
56
56
  loc=0,
57
57
  scale=delta_t**2 / 2,
58
58
  size=n,
59
59
  random_state=self.rng,
60
- )
60
+ ),
61
+ dtype=np.float64,
61
62
  )
62
63
 
63
- times = np.insert(times, 0, [0])
64
- return self._sample_brownian_motion_at(times)
64
+ return np.insert(self._subordinate(levys), 0, 0.0)
65
+
66
+ def _subordinate(self, levys: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
67
+ """Evaluate the Brownian motion over the increments of the subordinator.
68
+
69
+ The Brownian increments are generated from the increments of the Levy
70
+ subordinator directly. Accumulating the subordinator first and taking
71
+ differences loses the small increments next to a large one.
72
+ """
73
+ samples = np.cumsum(self.scale * self.rng.normal(scale=np.sqrt(levys)))
74
+ if self.drift != 0:
75
+ samples += self.drift * np.cumsum(levys)
76
+
77
+ return samples
65
78
 
66
79
  def _sample_cauchy_process_at(
67
80
  self,
@@ -74,25 +87,24 @@ class CauchyProcess(BrownianMotion):
74
87
  else:
75
88
  zero = True
76
89
 
77
- deltas = np.diff(times)
78
- levys = [
90
+ deltas = times_to_increments(times=times)
91
+ # Standard Levy variates, scaled per increment.
92
+ standard = np.asarray(
79
93
  levy.rvs(
80
94
  loc=0,
81
- scale=d**2 / 2,
82
- size=1,
95
+ scale=1.0,
96
+ size=len(deltas),
83
97
  random_state=self.rng,
84
- )
85
- for d in deltas
86
- ]
87
-
88
- ts: npt.NDArray[np.float64] = np.cumsum(
89
- levys, # type: ignore[arg-type]
98
+ ),
99
+ dtype=np.float64,
90
100
  )
101
+ levys = standard * (deltas**2 / 2)
91
102
 
103
+ samples = self._subordinate(levys)
92
104
  if zero:
93
- ts = np.insert(ts, 0, [0])
105
+ samples = np.insert(samples, 0, 0.0)
94
106
 
95
- return self._sample_brownian_motion_at(ts)
107
+ return samples
96
108
 
97
109
  @override
98
110
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -138,20 +138,19 @@ class GammaProcess(BaseTimeProcess):
138
138
 
139
139
  def _sample_gamma_process_at(self, times: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
140
140
  """Sample a Gamma process at specific times."""
141
- s = []
142
- if times[0] != 0:
141
+ zero = times[0] == 0
142
+ if not zero:
143
143
  times = np.insert(times, 0, [0])
144
- else:
145
- s.append(0)
146
144
  increments = times_to_increments(times=times)
147
145
 
148
146
  scale = self.variance / self.mean
149
147
  shape_coef = self.mean**2 / self.variance
150
148
 
151
- for inc in increments:
152
- s.append(self.rng.gamma(shape=shape_coef * inc, scale=scale))
149
+ samples = np.cumsum(self.rng.gamma(shape=shape_coef * increments, scale=scale))
150
+ if zero:
151
+ samples = np.concatenate(([0.0], samples))
153
152
 
154
- return np.cumsum(s)
153
+ return samples
155
154
 
156
155
  @override
157
156
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -122,7 +122,7 @@ class InverseGaussianProcess(BaseTimeProcess):
122
122
  )
123
123
 
124
124
  assert self.__ms is not None
125
- ls = np.array([self.scale * m**2 for m in self.__ms])
125
+ ls = self.scale * self.__ms**2
126
126
 
127
127
  gn = self.rng.normal(size=n)
128
128
  ys = gn**2
@@ -135,16 +135,9 @@ class InverseGaussianProcess(BaseTimeProcess):
135
135
 
136
136
  zs = self.rng.uniform(size=n)
137
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)
138
+ ign = np.where(zs <= self.__ms / (self.__ms + xs), xs, self.__ms**2 / xs)
144
139
 
145
- ig = np.array(ign).cumsum()
146
- ig = np.insert(ig, [0], 0)
147
- return ig
140
+ return np.concatenate(([0.0], np.cumsum(ign)))
148
141
 
149
142
  @override
150
143
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -163,7 +156,7 @@ class InverseGaussianProcess(BaseTimeProcess):
163
156
  for k in range(n):
164
157
  ms[k] = self._check_mean(times[k], times[k + 1])
165
158
 
166
- ls = np.array([self.scale * m**2 for m in ms])
159
+ ls = self.scale * ms**2
167
160
 
168
161
  gn = self.rng.normal(size=n)
169
162
  ys = gn**2
@@ -172,14 +165,7 @@ class InverseGaussianProcess(BaseTimeProcess):
172
165
 
173
166
  zs = self.rng.uniform(size=n)
174
167
 
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()
168
+ ig = np.cumsum(np.where(zs <= ms / (ms + xs), xs, ms**2 / xs))
183
169
  if times[0] == 0:
184
170
  ig = np.insert(ig, 0, [0])
185
171
 
@@ -91,20 +91,6 @@ class MultifractionalBrownianMotion(BaseTimeProcess):
91
91
 
92
92
  return hs
93
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
94
  def _sample_multifractional_brownian_motion(self, n: int) -> npt.NDArray[np.float64]:
109
95
  """Generate Riemann-Liouville mBm."""
110
96
  gn = self.rng.normal(0.0, 1.0, n)
@@ -113,15 +99,22 @@ class MultifractionalBrownianMotion(BaseTimeProcess):
113
99
  dt = 1.0 * self.t / self.n
114
100
  hs = self._get_hurst(self.hurst)
115
101
 
116
- mbm = [0]
117
- coefs = [(g / np.sqrt(dt)) * dt for g in gn]
102
+ coefs = (gn / np.sqrt(dt)) * dt
103
+ times = self.times
118
104
 
105
+ mbm = np.zeros(self.n + 1)
119
106
  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)
107
+ # The weights of the Riemann-Liouville method for the Hurst value
108
+ # at time k, for the times 1 to k, applied to the increments in
109
+ # reverse order.
110
+ hurst = hs[k]
111
+ elapsed = times[1 : k + 1]
112
+ weights = np.sqrt(
113
+ (elapsed ** (2 * hurst) - (elapsed - dt) ** (2 * hurst)) / (2 * hurst * dt)
114
+ ) / gamma(hurst + 0.5)
115
+ mbm[k] = coefs[:k] @ weights[::-1]
116
+
117
+ return mbm
125
118
 
126
119
  @override
127
120
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -75,9 +75,7 @@ class PoissonProcess(BaseProcess):
75
75
  size=n,
76
76
  )
77
77
 
78
- s = np.array([0.0] + list(np.cumsum(exponentials)))
79
-
80
- return s
78
+ return np.concatenate(([0.0], np.cumsum(exponentials)))
81
79
 
82
80
  if length is not None:
83
81
  check_positive_number(value=length, name="Sample length")
@@ -39,18 +39,20 @@ class SquaredBesselProcess(BesselProcess):
39
39
  """Generate a realization of a squared Bessel process."""
40
40
  check_positive_integer(n=n)
41
41
 
42
- samples = [self._sample_brownian_motion(n) for _ in range(self.dim)]
42
+ samples = np.array([self._sample_brownian_motion(n) for _ in range(self.dim)])
43
43
 
44
- return np.array([sum(map(lambda x: x**2, coord)) for coord in zip(*samples, strict=True)])
44
+ squares: npt.NDArray[np.float64] = np.sum(np.square(samples), axis=0)
45
+ return squares
45
46
 
46
47
  def _sample_squared_bessel_process_at(
47
48
  self,
48
49
  times: npt.NDArray[np.float64],
49
50
  ) -> npt.NDArray[np.float64]:
50
51
  """Generate a realization of a squared Bessel process."""
51
- samples = [self._sample_brownian_motion_at(times) for _ in range(self.dim)]
52
+ samples = np.array([self._sample_brownian_motion_at(times) for _ in range(self.dim)])
52
53
 
53
- return np.array([sum(map(lambda x: x**2, coord)) for coord in zip(*samples, strict=True)])
54
+ squares: npt.NDArray[np.float64] = np.sum(np.square(samples), axis=0)
55
+ return squares
54
56
 
55
57
  @override
56
58
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -128,16 +128,7 @@ class VarianceGammaProcess(GaussianNoise):
128
128
  shapes = np.diff(times) / self.variance
129
129
  scale = self.variance
130
130
 
131
- gammas = np.array(
132
- [
133
- self.rng.gamma(
134
- shape=shape,
135
- scale=scale,
136
- size=1,
137
- )[0]
138
- for shape in shapes
139
- ]
140
- )
131
+ gammas = self.rng.gamma(shape=shapes, scale=scale)
141
132
  gn = super().sample_at(times)
142
133
 
143
134
  increments = self.drift * gammas + self.scale * np.sqrt(gammas) * gn
@@ -64,14 +64,7 @@ class BernoulliProcess(BaseSequenceProcess):
64
64
  """Generate a Bernoulli process realization."""
65
65
  check_positive_integer(n=n)
66
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
- )
67
+ return (self.rng.uniform(size=n) < self.p).astype(np.float64)
75
68
 
76
69
  @override
77
70
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -1,5 +1,7 @@
1
1
  """Chinese restaurant process."""
2
2
 
3
+ from bisect import bisect_right
4
+ from itertools import accumulate
3
5
  from typing import override
4
6
 
5
7
  import numpy as np
@@ -121,20 +123,30 @@ class ChineseRestaurantProcess(BaseSequenceProcess):
121
123
 
122
124
  c: list[list[int]] = [[0]]
123
125
  s = [0]
126
+ sizes = [1]
124
127
  num_tables = 1
125
- table_range = [0, 1]
126
128
 
129
+ discount = self.discount
130
+ strength = self.strength
131
+ random = self.rng.random
132
+
133
+ # Each customer inverts the cumulative distribution over the tables at
134
+ # a uniform variate, which is what Generator.choice does, without its
135
+ # overhead per call.
127
136
  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))
137
+ denominator = k - 1 + strength
138
+ cumulative = list(accumulate(1.0 * (size - discount) / denominator for size in sizes))
139
+ cumulative.append(
140
+ cumulative[-1] + 1.0 * (strength + num_tables * discount) / denominator
141
+ )
142
+ total = cumulative[-1]
143
+
144
+ table = bisect_right([value / total for value in cumulative], random())
134
145
  if table == num_tables:
135
146
  num_tables += 1
136
- table_range.append(num_tables)
147
+ sizes.append(0)
137
148
  c.append([])
149
+ sizes[table] += 1
138
150
  c[table].append(k - 1)
139
151
  s.append(table)
140
152
 
@@ -83,14 +83,19 @@ class DirichletProcess(BaseSequenceProcess):
83
83
 
84
84
  :param n: the number of steps of the Dirichlet process to generate.
85
85
  """
86
- sequence = np.empty(n, dtype=np.float64)
86
+ alpha = self.alpha
87
+ base = self.base
88
+ uniform = self.rng.uniform
89
+ integers = self.rng.integers
90
+
91
+ sequence: list[float] = []
87
92
  for k in range(n):
88
- p = self.alpha / (self.alpha + k)
89
- if self.rng.uniform() < p:
90
- sequence[k] = self.base()
93
+ if uniform() < alpha / (alpha + k):
94
+ sequence.append(base())
91
95
  else:
92
- sequence[k] = self.rng.choice(sequence[:k])
93
- return sequence
96
+ # Repeat one of the previous values, chosen uniformly.
97
+ sequence.append(sequence[integers(0, k)])
98
+ return np.array(sequence, dtype=np.float64)
94
99
 
95
100
  @override
96
101
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -1,5 +1,6 @@
1
1
  """Finite state Markov chain."""
2
2
 
3
+ from bisect import bisect_right
3
4
  from collections.abc import Iterable
4
5
  from typing import override
5
6
 
@@ -16,6 +17,13 @@ DEFAULT_TRANSITION: npt.NDArray[np.float64] = np.array(
16
17
  )
17
18
 
18
19
 
20
+ def _cumulative(probabilities: npt.NDArray[np.float64]) -> npt.NDArray[np.float64]:
21
+ """Compute a normalized cumulative distribution, as Generator.choice does."""
22
+ cumulative = np.cumsum(probabilities, dtype=np.float64)
23
+ cumulative /= cumulative[-1]
24
+ return cumulative
25
+
26
+
19
27
  class MarkovChain(BaseSequenceProcess):
20
28
  """Finite state Markov chain.
21
29
 
@@ -122,10 +130,17 @@ class MarkovChain(BaseSequenceProcess):
122
130
  def sample(self, n: int) -> npt.NDArray[np.int64]:
123
131
  check_positive_integer(n=n)
124
132
 
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]]))
133
+ # Each step inverts the cumulative distribution of the current state
134
+ # at a uniform variate, which is what Generator.choice does, without
135
+ # its overhead per call.
136
+ initial = _cumulative(self.initial).tolist()
137
+ transition = [_cumulative(row).tolist() for row in self.transition]
138
+ uniforms = self.rng.random(n).tolist()
139
+
140
+ state = bisect_right(initial, uniforms[0])
141
+ markov_chain = [state]
142
+ for uniform in uniforms[1:]:
143
+ state = bisect_right(transition[state], uniform)
144
+ markov_chain.append(state)
130
145
 
131
146
  return np.array(markov_chain, dtype=np.int64)
@@ -1,5 +1,6 @@
1
1
  """Moran process."""
2
2
 
3
+ from bisect import bisect_right
3
4
  from typing import override
4
5
 
5
6
  import numpy as np
@@ -50,7 +51,6 @@ class MoranProcess(BaseSequenceProcess):
50
51
  super().__init__(rng=rng)
51
52
 
52
53
  self.maximum = maximum
53
- self.__p = _probabilities(maximum)
54
54
 
55
55
  def __str__(self) -> str:
56
56
  return f"Moran process with {self.maximum} states"
@@ -72,6 +72,11 @@ class MoranProcess(BaseSequenceProcess):
72
72
 
73
73
  self.__maximum = n
74
74
 
75
+ # Cumulative distributions of the increment (-1, 0 or 1) per state.
76
+ cumulative = np.cumsum(_probabilities(n), axis=1)
77
+ cumulative /= cumulative[:, -1:]
78
+ self.__cumulative: list[list[float]] = cumulative.tolist()
79
+
75
80
  def _sample_moran_process(
76
81
  self,
77
82
  n: int,
@@ -96,11 +101,17 @@ class MoranProcess(BaseSequenceProcess):
96
101
 
97
102
  start = int(start)
98
103
  s = [start]
99
- increments = [-1, 0, 1]
104
+ # Each step inverts the cumulative distribution of the increment at a
105
+ # uniform variate, which is what Generator.choice does, without its
106
+ # overhead per call. The variates are drawn one at a time because the
107
+ # realization may stop early.
108
+ cumulative = self.__cumulative
109
+ random = self.rng.random
110
+ maximum = self.maximum
100
111
  for _ in range(n - 1):
101
- if start in (0, self.maximum):
112
+ if start in (0, maximum):
102
113
  break
103
- start += int(self.rng.choice(increments, p=self.__p[start - 1]))
114
+ start += bisect_right(cumulative[start - 1], random()) - 1
104
115
  s.append(start)
105
116
 
106
117
  return np.array(s, dtype=np.int64)
@@ -95,7 +95,8 @@ class RandomWalk(BaseSequenceProcess):
95
95
 
96
96
  def _sample_random_walk(self, n: int) -> npt.NDArray[np.float64]:
97
97
  """Generate a random walk."""
98
- return np.array([0] + list(np.cumsum(self._sample_random_walk_increments(n))))
98
+ increments = self._sample_random_walk_increments(n)
99
+ return np.concatenate((np.zeros(1, dtype=increments.dtype), np.cumsum(increments)))
99
100
 
100
101
  @override
101
102
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -48,7 +48,7 @@ class ColoredNoise(BaseTimeProcess):
48
48
 
49
49
  self.beta = beta
50
50
 
51
- self.__n: int | None = None
51
+ self.__key: tuple[int, float, float] | None = None
52
52
  self.__half: int | None = None
53
53
  self.__frequencies: npt.NDArray[np.float64] | None = None
54
54
  self.__scale: npt.NDArray[np.float64] | None = None
@@ -75,20 +75,16 @@ class ColoredNoise(BaseTimeProcess):
75
75
  check_positive_integer(n=n, name="Number of increments")
76
76
  self.set_times(n)
77
77
 
78
- if self.__n != n:
79
- self.__n = n
78
+ # The frequencies and their scale depend on n, beta and t only, so
79
+ # they are reused by consecutive realizations.
80
+ key = (n, self.beta, self.t)
81
+ if self.__key != key:
82
+ self.__key = key
80
83
 
84
+ frequencies = np.asarray(np.fft.fftfreq(n, self.t), dtype=np.float64)
81
85
  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
- )
86
+ self.__frequencies = frequencies
87
+ self.__scale = np.sqrt(0.5 * (1 / frequencies[1 : self.__half]) ** self.beta)
92
88
 
93
89
  assert self.__frequencies is not None
94
90
  assert self.__half is not None
@@ -162,19 +162,18 @@ class FractionalGaussianNoise(BaseTimeProcess):
162
162
  v = 1
163
163
  phi[0] = 0
164
164
 
165
- # Generates fgn realization with n increments of size 1
165
+ # Generates fgn realization with n increments of size 1. Each
166
+ # step of the Durbin-Levinson recursion updates the partial
167
+ # autocorrelations phi with vector operations.
166
168
  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]
169
+ psi[: i - 1] = phi[: i - 1]
170
+ # cov[i - 1], ..., cov[1] and psi[i - 2], ..., psi[0]
171
+ reflection = (cov[i] - psi[: i - 1] @ cov[i - 1 : 0 : -1]) / v
172
+ phi[: i - 1] = psi[: i - 1] - reflection * psi[i - 2 :: -1][: i - 1]
173
+ phi[i - 1] = reflection
174
+ v *= 1 - reflection * reflection
175
+ # fgn[i - 1], ..., fgn[0]
176
+ fgn[i] = phi[:i] @ fgn[i - 1 :: -1][:i] + np.sqrt(v) * gn[i]
178
177
 
179
178
  # Scale to interval [0, T]
180
179
  fgn *= scale
@@ -55,16 +55,7 @@ class GaussianNoise(BaseTimeProcess):
55
55
 
56
56
  increments = times_to_increments(times=times)
57
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
58
+ return self.rng.normal(scale=np.sqrt(increments))
68
59
 
69
60
  @override
70
61
  def sample(self, n: int) -> npt.NDArray[np.float64]:
@@ -128,12 +128,13 @@ def check_increments(
128
128
  :raises ValueError: if a time value is negative or the time values are
129
129
  not strictly increasing
130
130
  """
131
- increments = np.diff(times)
131
+ values = np.asarray(times, dtype=np.float64)
132
+ increments = np.diff(values)
132
133
 
133
- if np.any([t < 0 for t in times]):
134
+ if np.any(values < 0):
134
135
  raise ValueError("Times must be nonnegative.")
135
136
 
136
- if np.any([t <= 0 for t in increments]):
137
+ if np.any(increments <= 0):
137
138
  raise ValueError("Times must be strictly increasing.")
138
139
 
139
140
  return increments
@@ -50,3 +50,17 @@ def test_cauchy_process_sample_values(
50
50
 
51
51
  samples = instance.sample(n=n)
52
52
  np.testing.assert_allclose(samples, expected, rtol=1e-6)
53
+
54
+
55
+ @pytest.mark.parametrize("seed", [683, 824, 1057, 1074, 2099])
56
+ def test_cauchy_process_sample_at_heavy_tails(seed: int) -> None:
57
+ # The subordinator has very heavy tails. For these seeds one of its
58
+ # increments is many orders of magnitude larger than the others, which
59
+ # used to make the accumulated times not strictly increasing.
60
+ instance = ProcessType(rng=np.random.default_rng(seed))
61
+ times = np.concatenate(([0.0], np.sort(np.random.default_rng(5).uniform(0.01, 4.0, 200))))
62
+
63
+ samples = instance.sample_at(times=times)
64
+
65
+ assert samples.shape == times.shape
66
+ assert np.all(np.isfinite(samples))
@@ -85,3 +85,13 @@ def test_moran_process_sample_values(
85
85
 
86
86
  samples = instance.sample_with_start(n=n, start=start)
87
87
  np.testing.assert_allclose(samples, expected, rtol=1e-6)
88
+
89
+
90
+ def test_moran_process_maximum_change_after_construction() -> None:
91
+ instance = ProcessType(maximum=5, rng=np.random.default_rng(3))
92
+
93
+ instance.maximum = 50
94
+ samples = instance.sample_with_start(n=40, start=25)
95
+
96
+ fresh = ProcessType(maximum=50, rng=np.random.default_rng(3))
97
+ np.testing.assert_array_equal(samples, fresh.sample_with_start(n=40, start=25))
@@ -66,3 +66,18 @@ def test_colored_noise_sample_values(
66
66
  samples = instance.sample(n=n)
67
67
 
68
68
  assert np.allclose(samples, expected, atol=1e-5)
69
+
70
+
71
+ def test_colored_noise_parameter_change_after_sampling() -> None:
72
+ # The frequencies and their scale are cached between realizations and
73
+ # must be recomputed when beta or t changes.
74
+ instance = ProcessType(beta=0.0, t=1.0, rng=np.random.default_rng(7))
75
+ instance.sample(n=16)
76
+
77
+ instance.beta = 2.0
78
+ instance.t = 3.0
79
+ instance.rng = np.random.default_rng(11)
80
+ samples = instance.sample(n=16)
81
+
82
+ fresh = ProcessType(beta=2.0, t=3.0, rng=np.random.default_rng(11))
83
+ np.testing.assert_allclose(samples, fresh.sample(n=16))
File without changes
File without changes
File without changes