julianoise

How to create noise with time dependent correlation in Julia?


I want to create real noise $\xi(t)$ which fulfills the property $E[xi_t\xi_s] = f(t, s)$ in Julia. Is there a library or function with which I could implement this? I tried the impementation with $f(t, s) = e^{-(t-s)}$ My code is not working (the noise is decreasing exponentially).

using LinearAlgebra

function generate_gaussian_noise(timesteps)
    n = length(timesteps)
    noise = zeros(n)

    for i in 1:n
        t = timesteps[i]
        noise[i] = real(randn())
    end

    return noise
end

function construct_correlated_noise(timesteps)
    n = length(timesteps)
    noise = generate_gaussian_noise(timesteps)
    correlation_matrix = zeros(n, n)

    for i in 1:n
        for j in 1:n
            correlation_matrix[i, j] = exp(-(timesteps[i] - timesteps[j]))
        end
    end

    # Perform eigenvalue decomposition
    eigenvalues, eigenvectors = eigen(correlation_matrix)
    D = Diagonal(sqrt.(eigenvalues))
    Q = eigenvectors
    L = Q * D

    correlated_noise = L * noise

    return correlated_noise
end

# Example usage
timesteps = collect(1:401)
correlated_noise = construct_correlated_noise(timesteps)

Solution

  • If I understand you correctly you want something like this?

    using Distributions
    f(t, s) = exp(-abs(t-s))
    timesteps = 1:401;
    covariance_matrix = f.(timesteps, timesteps');
    mean_vector = zeros(length(timesteps));
    d = MvNormal(mean_vector, covariance_matrix);
    x = rand(d) # this is a single sample
    

    Note that f(t,s) must have a property that f(t,s)=f(s,t) which your function did not have, that is why I have added abs. I also modelled covariance because what you defined is not correlation but covariance assuming that the expected value of the process is constant and equal to 0.