Skip to content

Commit 6a1cec8

Browse files
authored
Remove allocations from random fourier surrogates (#160)
* remove allocations from random fourier * add correctness test for random fourier * bump version
1 parent 2f0077f commit 6a1cec8

File tree

3 files changed

+18
-8
lines changed

3 files changed

+18
-8
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ name = "TimeseriesSurrogates"
22
uuid = "c804724b-8c18-5caa-8579-6025a0767c70"
33
authors = ["Kristian Agasøster Haaga <kahaaga@gmail.com>", "George Datseris"]
44
repo = "https://github.com/JuliaDynamics/TimeseriesSurrogates.jl.git"
5-
version = "2.6.3"
5+
version = "2.6.4"
66

77
[deps]
88
AbstractFFTs = "621f4979-c628-5d54-868e-fcf4e3e8185c"

src/methods/randomfourier.jl

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1+
using Random
2+
using LinearAlgebra
3+
14
export RandomFourier, FT
25

6+
37
"""
48
RandomFourier(phases = true)
59
@@ -36,26 +40,27 @@ function surrogenerator(x::AbstractVector, rf::RandomFourier, rng = Random.defau
3640
r = abs.(𝓕)
3741
ϕ = angle.(𝓕)
3842
coeffs = zero(r)
39-
40-
init = (inverse = inverse, m = m, coeffs = coeffs, n = n, r = r,
43+
44+
init = (inverse = inverse, m = m, coeffs = coeffs, n = n, r = r,
4145
ϕ = ϕ, shuffled𝓕 = shuffled𝓕)
4246
return SurrogateGenerator(rf, x, s, init, rng)
4347
end
4448

4549
function (sg::SurrogateGenerator{<:RandomFourier})()
46-
inverse, m, coeffs, n, r, ϕ, shuffled𝓕 =
47-
getfield.(Ref(sg.init),
50+
inverse, m, coeffs, n, r, ϕ, shuffled𝓕 =
51+
getfield.(Ref(sg.init),
4852
(:inverse, :m, :coeffs, :n, :r, , :shuffled𝓕))
4953
s, rng, phases = sg.s, sg.rng, sg.method.phases
5054

5155
if phases
52-
coeffs .= rand(rng, Uniform(0, 2π), n)
56+
rand!(rng, Uniform(0, 2π), coeffs)
5357
shuffled𝓕 .= r .* exp.(coeffs .* 1im)
5458
else
5559
coeffs .= r .* rand(rng, Uniform(0, 2π), n)
5660
shuffled𝓕 .= coeffs .* exp.(ϕ .* 1im)
5761
end
58-
s .= inverse * shuffled𝓕 .+ m
62+
mul!(s, inverse, shuffled𝓕)
63+
s .+= m
5964
return s
6065
end
6166

test/all_method_tests.jl

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ using TimeseriesSurrogates
33
using TimeseriesSurrogates.AbstractFFTs
44
using TimeseriesSurrogates.Statistics
55
using TimeseriesSurrogates.Random
6-
ENV["GKSwstype"] = "100"
76

87
N = 500
98
ts = cumsum(randn(N))
@@ -248,6 +247,12 @@ end
248247
s = surrogate(x, rf)
249248

250249
@test length(s) == length(x)
250+
# test that power spectrum is conserved
251+
psx = abs2.(rfft(x))
252+
pss = abs2.(rfft(s))
253+
# For some reason I don't understand the last element of the spectrum
254+
# is way off what is should be.
255+
@test all(isapprox.(psx[1:end-1], pss[1:end-1]; atol = 1e-8))
251256
end
252257

253258
@testset "random amplitudes" begin

0 commit comments

Comments
 (0)