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

add interp routine #121

Merged
merged 1 commit into from
Apr 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion src/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -206,4 +206,30 @@ Generate a tuple of `N` values from either a boundary condition
function `f(i,t)` or the tuple of boundary conditions f=(fₓ,...).
"""
BCTuple(f::Function,t,N)=ntuple(i->f(i,t),N)
BCTuple(f::Tuple,t,N)=f
BCTuple(f::Tuple,t,N)=f
"""
interp(x::SVector, arr::AbstractArray)

Linear interpolation from array `arr` at index-coordinate `x`.
Note: This routine works for any number of dimensions.
"""
function interp(x::SVector{D,T}, arr::AbstractArray{T,D}) where {D,T}
# Index below the interpolation coordinate and the difference
i = floor.(Int,x); y = x.-i

# CartesianIndices around x
I = CartesianIndex(i...); R = I:I+oneunit(I)

# Linearly weighted sum over arr[R] (in serial)
s = zero(T)
@fastmath @inbounds @simd for J in R
weight = prod(@. ifelse(J.I==I.I,1-y,y))
s += arr[J]*weight
end
return s
end
function interp(x::SVector{D,T}, varr::AbstractArray{T}) where {D,T}
# Shift to align with each staggered grid component and interpolate
@inline shift(i) = SVector{D,T}(ifelse(i==j,0.5,0.) for j in 1:D)
return SVector{D,T}(interp(x+shift(i),@view(varr[..,i])) for i in 1:D)
end
8 changes: 8 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ arrays = setup_backends()
BC!(u,U,true,(1,)) #saveexit has no effect here as x-periodic
@test GPUArrays.@allowscalar all(u[1:2, :, 1] .== u[end-1:end, :, 1]) && all(u[1:2, :, 2] .== u[end-1:end, :, 2]) &&
all(u[:, 1, 2] .== U[2]) && all(u[:, 2, 2] .== U[2]) && all(u[:, end, 2] .== U[2])

# test interpolation
a = zeros(5,5,2) |> f; b = zeros(5,5) |> f
apply!((i,x)->x[i]+1.5,a); apply!(x->x[1]+1.5,b) # offset for start of grid
@test GPUArrays.@allowscalar all(WaterLily.interp(SVector(2.5,1),a) .≈ [2.5,1.])
@test GPUArrays.@allowscalar all(WaterLily.interp(SVector(3.5,3),a) .≈ [3.5,3.])
@test GPUArrays.@allowscalar WaterLily.interp(SVector(2.5,1),b) ≈ 2.5
@test GPUArrays.@allowscalar WaterLily.interp(SVector(3.5,3),b) ≈ 3.5
end
end

Expand Down