Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resolve type stability of evaluation of KernelSum #459

Merged
merged 12 commits into from
Sep 26, 2022
13 changes: 8 additions & 5 deletions src/kernels/kernelsum.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,22 +43,25 @@ end

Base.length(k::KernelSum) = length(k.kernels)

(κ::KernelSum)(x, y) = sum(k(x, y) for k in κ.kernels)
_sum(f::Tf, x::Tuple) where {Tf} = f(x[1]) + _sum(f, Base.tail(x))
_sum(f::Tf, x::Tuple{Tx}) where {Tf, Tx} = f(x[1])
simsurace marked this conversation as resolved.
Show resolved Hide resolved

(κ::KernelSum)(x, y) = _sum(k -> k(x, y), κ.kernels)

function kernelmatrix(κ::KernelSum, x::AbstractVector)
return sum(kernelmatrix(k, x) for k in κ.kernels)
return _sum(Base.Fix2(kernelmatrix, x), κ.kernels)
end

function kernelmatrix(κ::KernelSum, x::AbstractVector, y::AbstractVector)
return sum(kernelmatrix(k, x, y) for k in κ.kernels)
return _sum(k -> kernelmatrix(k, x, y), κ.kernels)
end

function kernelmatrix_diag(κ::KernelSum, x::AbstractVector)
return sum(kernelmatrix_diag(k, x) for k in κ.kernels)
return _sum(Base.Fix2(kernelmatrix_diag, x), κ.kernels)
end

function kernelmatrix_diag(κ::KernelSum, x::AbstractVector, y::AbstractVector)
return sum(kernelmatrix_diag(k, x, y) for k in κ.kernels)
return _sum(k -> kernelmatrix_diag(k, x, y), κ.kernels)
end

function Base.show(io::IO, κ::KernelSum)
Expand Down
19 changes: 19 additions & 0 deletions test/kernels/kernelsum.jl
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,23 @@
end

test_params(k1 + k2, (k1, k2))

@testset "Type stability" begin
simsurace marked this conversation as resolved.
Show resolved Hide resolved
function check_type_stability(k)
@inferred k(0.1, 0.2)
x = rand(10)
y = rand(10)
@inferred kernelmatrix(k, x)
@inferred kernelmatrix(k, x, y)
@inferred kernelmatrix_diag(k, x)
@inferred kernelmatrix_diag(k, x, y)
end
@testset for k in (
RBFKernel() + RBFKernel() * LinearKernel(),
RBFKernel() + RBFKernel() * ExponentialKernel(),
RBFKernel() * (LinearKernel() + ExponentialKernel())
simsurace marked this conversation as resolved.
Show resolved Hide resolved
)
check_type_stability(k)
end
end
end