Skip to content

Commit

Permalink
Merge pull request #275 from JuliaMath/teh/rh
Browse files Browse the repository at this point in the history
Add convenience utilities for working with WeightedIndex
  • Loading branch information
timholy committed Nov 26, 2018
2 parents d8fbd11 + 5f4b57c commit 2e1108f
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/Interpolations.jl
Original file line number Diff line number Diff line change
Expand Up @@ -212,13 +212,21 @@ WeightedIndex(indexes::NTuple{L,Integer}, weights::NTuple{L,Any}) where L =
weights(wi::WeightedIndex) = wi.weights
indexes(wi::WeightedAdjIndex) = wi.istart
indexes(wi::WeightedArbIndex) = wi.indexes
indextuple(wi::WeightedAdjIndex{L}) where L = ntuple(i->wi.istart+i-1, Val(L))
indextuple(wi::WeightedArbIndex{L}) where L = indexes(wi)

# Make them iterable just like numbers are
Base.iterate(x::WeightedIndex) = (x, nothing)
Base.iterate(x::WeightedIndex, ::Any) = nothing
Base.isempty(x::WeightedIndex) = false
Base.length(x::WeightedIndex) = 1

# Supporting arithmetic on the weights allows one to perform pre-scaling of gradient coefficients
Base.:(*)(wi::WeightedAdjIndex, x::Number) = WeightedAdjIndex(wi.istart, wi.weights .* x)
Base.:(/)(wi::WeightedAdjIndex, x::Number) = WeightedAdjIndex(wi.istart, wi.weights ./ x)
Base.:(*)(wi::WeightedArbIndex, x::Number) = WeightedArbIndex(wi.indexes, wi.weights .* x)
Base.:(/)(wi::WeightedArbIndex, x::Number) = WeightedArbIndex(wi.indexes, wi.weights ./ x)

### Indexing with WeightedIndex

# We inject indexing with `WeightedIndex` at a non-exported point in the dispatch heirarchy.
Expand Down
11 changes: 11 additions & 0 deletions test/core.jl
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using Interpolations, Test

@testset "Core" begin
A = reshape([0], 1, 1, 1, 1, 1)
wis = ntuple(d->Interpolations.WeightedAdjIndex(1, (1,)), ndims(A))
Expand All @@ -12,4 +14,13 @@
@test @inferred(A[wis...]) === 0
wis = ntuple(d->Interpolations.WeightedArbIndex((1,1), (1.0,0.0)), ndims(A))
@test @inferred(A[wis...]) === 0.0

wi = Interpolations.WeightedAdjIndex(2, (0.2, 0.8))
@test wi*2 === Interpolations.WeightedAdjIndex(2, (0.4, 1.6))
@test wi/2 === Interpolations.WeightedAdjIndex(2, (0.1, 0.4))
@test Interpolations.indextuple(wi) == (2, 3)
wi = Interpolations.WeightedArbIndex((2, -1), (0.2, 0.8))
@test wi*2 === Interpolations.WeightedArbIndex((2, -1), (0.4, 1.6))
@test wi/2 === Interpolations.WeightedArbIndex((2, -1), (0.1, 0.4))
@test Interpolations.indextuple(wi) == (2, -1)
end

0 comments on commit 2e1108f

Please sign in to comment.