Find nearest value in AxisArray

I am playing around with AxisArrays, as it seems like a great package for adding axis with geographical locations to gridded data. What I would like is to let AxisArray give me the value of the nearest location, without having to specify the tolerance each time. Is it somehow possible?

using AxisArrays

x = 0:10:100 |> collect
a = AxisArray(rand(length(x)); x=x)

println(a[x=29..33])
println(a[x=30..30])
println(a[atvalue(29; atol=5)])
println(a[atvalue(29)]) # Does not work.

Fails with

ERROR: LoadError: BoundsError: attempt to access 11-element Vector{Int64} at index

This looks like a bug to me. Maybe you should file an issue against AxisArrays?

I think it is because the default tolerance seems to be zero. I would prefer the default tolerance to be very large. I would like to use it for gridded data and get the nearest value to an arbitrary coordinate.

I can understand that, but an issue might be better place to discuss this?

Will do:

1 Like

Also, note that just having the tolerance be very large wouldn’t do what you want - it doesn’t get the nearest index to what we specify, it seems to be getting the smallest index within the tolerance:


julia> println(a[atvalue(29; atol=10)])
0.9605168735870881

julia> println(a[x=30..30])
[0.02237417395875274]

julia> println(a[x=20..20])
[0.9605168735870881]

julia> println(a[atvalue(29; atol=100)])
0.9605168735870881

julia> println(a[x=10..10])
[0.9994774509360341]

julia> println(a[x=0..0])
[0.5920127185825809]

So not really the smallest index either, that would have given the x=0..0th value here. I’m not sure what it’s actually doing.

Is there a way to return a default value such as NaN or 0 instead of throwing a BoundsError when there is no value within array a in the vicinity of a given index along x? Similar to the behvaiour of DefaultDict and DefaultOrderedDict · DataStructures.jl