crflynn / stochastic

Generate realizations of stochastic processes in python.
http://stochastic.readthedocs.io/en/stable/
MIT License
451 stars 80 forks source link

Hosking method for fgn regenerates the autocovariance matrix at wrong times #26

Closed anntzer closed 4 years ago

anntzer commented 4 years ago

In FractionalGaussianNoise._hosking, there's the snippet

            if self._n != n or self._cov is None:
                self._cov = np.array([self._autocovariance(i)
                                      for i in range(n)])

which suggests that you were intending to save the calculation of self._cov for later calls. However, _hosking() never sets self._n, which remains None, so in fact that line will be run evertime fgn.sample(n, algorithm="hosking") is called, even with the same n (this can be checked by adding a print there). That specific point is just a missed optimization; however, that also means that an (admittedly slightly pathological) sequence of calls will cause a crash:

from stochastic.noise import FractionalGaussianNoise
fgn = FractionalGaussianNoise(.75)
fgn.sample(1000, algorithm="daviesharte")  # sets self._n to 1000
fgn.sample(100, algorithm="hosking")  # caches a size-100 covariance vector
fgn.sample(1000, algorithm="hosking")  # crashes: "index 100 is out of bounds for axis 0 with size 100"