-
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathnoise.py
More file actions
302 lines (226 loc) · 9.85 KB
/
noise.py
File metadata and controls
302 lines (226 loc) · 9.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#########################################################################################
##
## TIME DOMAIN NOISE SOURCES
## (blocks/noise.py)
##
#########################################################################################
# IMPORTS ===============================================================================
import numpy as np
from ._block import Block
from ..events.schedule import Schedule
# NOISE SOURCE BLOCKS ===================================================================
class WhiteNoise(Block):
"""White noise source with Gaussian distribution.
Generates uncorrelated random samples with either constant amplitude
(``standard_deviation`` mode) or timestep-scaled amplitude for stochastic
integration (``spectral_density`` mode).
In spectral density mode, output is scaled as √(S₀/dt) so that integrating
the noise yields correct statistical properties (Wiener process).
Note
----
If ``spectral_density`` is provided, it takes precedence over ``standard_deviation``.
If ``sampling_period`` is set, noise is sampled at fixed intervals (zero-order hold).
Parameters
----------
standard_deviation : float
output standard deviation for constant-amplitude mode (default: 1.0)
spectral_density : float, optional
power spectral density S₀ in [signal²/Hz]
sampling_period : float, optional
time between samples, if None samples every timestep
seed : int, optional
random seed for reproducibility
"""
input_port_labels = {}
output_port_labels = {"out": 0}
def __init__(self, standard_deviation=1.0, spectral_density=None,
sampling_period=None, seed=None):
super().__init__()
#block parameters
self.standard_deviation = standard_deviation
self.spectral_density = spectral_density
self.sampling_period = sampling_period
#random number generator (with optional seed for reproducibility)
self._rng = np.random.default_rng(seed)
#current noise sample
self._current_sample = 0.0
#sampling produces discrete time behavior
if sampling_period is not None:
#generate initial sample for discrete mode
self._current_sample = self._generate_sample(sampling_period)
self.outputs[0] = self._current_sample
#internal scheduled event
def _set(t):
self._current_sample = self._generate_sample(self.sampling_period)
self.outputs[0] = self._current_sample
self.events = [
Schedule(
t_start=0,
t_period=sampling_period,
func_act=_set
)
]
def __len__(self):
return 0
def _generate_sample(self, dt):
"""Generate a random sample from the noise distribution.
Parameters
----------
dt : float
integration timestep (used for spectral density scaling)
"""
if self.spectral_density is not None:
#spectral density mode: scale for correct integration
return self._rng.normal(0, 1) * np.sqrt(self.spectral_density / dt)
else:
#constant amplitude mode
return self._rng.normal(0, self.standard_deviation)
def sample(self, t, dt):
"""Generate new noise sample after successful timestep.
Only generates new samples in continuous mode (sampling_period=None).
Parameters
----------
t : float
evaluation time
dt : float
integration timestep
"""
if self.sampling_period is None:
self._current_sample = self._generate_sample(dt)
self.outputs[0] = self._current_sample
def update(self, t):
pass
def to_checkpoint(self, prefix, recordings=False):
"""Serialize WhiteNoise state including current sample."""
json_data, npz_data = super().to_checkpoint(prefix, recordings=recordings)
json_data["_current_sample"] = float(self._current_sample)
return json_data, npz_data
def load_checkpoint(self, prefix, json_data, npz):
"""Restore WhiteNoise state including current sample."""
super().load_checkpoint(prefix, json_data, npz)
self._current_sample = json_data.get("_current_sample", 0.0)
class PinkNoise(Block):
"""Pink noise (1/f noise) source using the Voss-McCartney algorithm.
Generates noise with power spectral density proportional to 1/f, where
lower frequencies have more power than higher frequencies.
The algorithm maintains ``num_octaves`` independent random values representing
different frequency bands. At each sample, one octave is updated based on the
binary representation of the sample counter, creating the characteristic 1/f
spectrum through the superposition of different update rates.
Note
----
If ``spectral_density`` is provided, it takes precedence over ``standard_deviation``.
If ``sampling_period`` is set, noise is sampled at fixed intervals (zero-order hold).
Parameters
----------
standard_deviation : float
approximate output standard deviation (default: 1.0)
spectral_density : float, optional
power spectral density, output scaled as √(S₀/(N·dt))
num_octaves : int
number of frequency bands in algorithm (default: 16)
sampling_period : float, optional
time between samples, if None samples every timestep
seed : int, optional
random seed for reproducibility
"""
input_port_labels = {}
output_port_labels = {"out": 0}
def __init__(self, standard_deviation=1.0, spectral_density=None,
num_octaves=16, sampling_period=None, seed=None):
super().__init__()
#block parameters
self.standard_deviation = standard_deviation
self.spectral_density = spectral_density
self.num_octaves = num_octaves
self.sampling_period = sampling_period
#random number generator (with optional seed)
self._rng = np.random.default_rng(seed)
#algorithm state
self.n_samples = 0
self.octave_values = self._rng.normal(0, 1, self.num_octaves)
#current noise sample
self._current_sample = 0.0
#sampling produces discrete time behavior
if sampling_period is not None:
#generate initial sample for discrete mode
self._current_sample = self._generate_sample(sampling_period)
self.outputs[0] = self._current_sample
#internal scheduled event
def _set(t):
self._current_sample = self._generate_sample(self.sampling_period)
self.outputs[0] = self._current_sample
self.events = [
Schedule(
t_start=0,
t_period=sampling_period,
func_act=_set
)
]
def __len__(self):
return 0
def reset(self):
"""Reset the noise generator state.
Resets the sample counter and reinitializes all octave values.
"""
super().reset()
self.n_samples = 0
self.octave_values = self._rng.normal(0, 1, self.num_octaves)
self._current_sample = 0.0
def _generate_sample(self, dt):
"""Generate a pink noise sample using the Voss-McCartney algorithm.
Parameters
----------
dt : float
integration timestep (used for spectral density scaling)
"""
#increment sample counter
self.n_samples += 1
#find position of least significant 1-bit (trailing zeros)
#this determines which octave to update
n = self.n_samples
octave_idx = 0
while (n & 1) == 0 and octave_idx < self.num_octaves - 1:
n >>= 1
octave_idx += 1
#update the selected octave
self.octave_values[octave_idx] = self._rng.normal(0, 1)
#sum all octaves for pink noise output
pink_sample = np.sum(self.octave_values)
#scale output based on parameterization mode
if self.spectral_density is not None:
#spectral density mode
return pink_sample * np.sqrt(self.spectral_density / self.num_octaves / dt)
else:
#constant amplitude mode
#normalize by sqrt(num_octaves) since Var(sum) ≈ num_octaves
return pink_sample * self.standard_deviation / np.sqrt(self.num_octaves)
def sample(self, t, dt):
"""Generate new noise sample after successful timestep.
Only generates new samples in continuous mode (sampling_period=None).
Parameters
----------
t : float
evaluation time
dt : float
integration timestep
"""
if self.sampling_period is None:
self._current_sample = self._generate_sample(dt)
self.outputs[0] = self._current_sample
def update(self, t):
pass
def to_checkpoint(self, prefix, recordings=False):
"""Serialize PinkNoise state including algorithm state."""
json_data, npz_data = super().to_checkpoint(prefix, recordings=recordings)
json_data["n_samples"] = self.n_samples
json_data["_current_sample"] = float(self._current_sample)
npz_data[f"{prefix}/octave_values"] = self.octave_values
return json_data, npz_data
def load_checkpoint(self, prefix, json_data, npz):
"""Restore PinkNoise state including algorithm state."""
super().load_checkpoint(prefix, json_data, npz)
self.n_samples = json_data.get("n_samples", 0)
self._current_sample = json_data.get("_current_sample", 0.0)
if f"{prefix}/octave_values" in npz:
self.octave_values = npz[f"{prefix}/octave_values"]