felixpatzelt / colorednoise

Python package to generate Gaussian (1/f)**beta noise (e.g. pink noise)
MIT License
195 stars 20 forks source link

Fix magnitude of frequencies #12

Closed onnoeberhard closed 2 years ago

onnoeberhard commented 2 years ago

Hi, I noticed a problem with the noise signals generated by this module. I am using the colored noise signals to generate random walks by integrating them (i.e. signal.cumsum(-1)). When looking at the average absolute value over many such random walks (i.e. the expected "distance to the origin"), these random walks did not behave as expected. In the figure, I have plotted this average distance for the case of integrated white noise (exponent = 0).

Unknown-1

As can be seen, the colored noise from this module ("colorednoise original") does not behave as expected ("scipy" just means generating white noise by independently sampling gaussian noise). This sort of curve is only possible if the white noise signal is correlated over time, which, by definition, it shouldn't be. After comparing the implemented algorithm with the source (Timmer and Koenig), I found an implementation detail which isn't really mentioned in the source: How to make sure the imaginary part is 0 at the DC frequency (and optionally at the highest frequency). In your implementation, you simply set si to 0 here, but this changes the magnitude of the signal at these points. As a fix, I multiplied the real part sr by sqrt(2), such that the magnitude is, on average, unchanged (as si and sr have the same magnitude in expectation at every frequency). The result is plotted in the figure and lines up with the expected curve.

Of course, this will also change things for other exponents, but I can't think of an interpretation of those changes. In most cases it probably makes little difference, but in my case, where I was integrating these signals, it does.

felixpatzelt commented 2 years ago

Thank you @onnoeberhard! It looks reasonable to me but I haven't found the time yet for testing this change thoroughly. I will try to do so the next days.