Search code examples
arraysjulia

check if a view is contiguous in julia


I have a N-dim julia array and a view of a slice. Is there a way to check if this view is contiguous (that would be a.flags["F"] in NumPy)? It seems Base.iscontiguous is not the answer.

a = ones((1,1,1))
t = (1:1, 1:1, 1:1)
v = @view a[t...]
println(Base.iscontiguous(v))  # false
Base.iscontiguous(a[t...])  # MethodError: no method matching iscontiguous(::Array{Float64, 3}) 

Here I know the underlying data block is contiguous, but is there a way to check it for more complex views?


Solution

  • iscontiguous implementation:

    
        iscontiguous(A::SubArray) = iscontiguous(typeof(A))
        iscontiguous(::Type{<:SubArray}) = false
        iscontiguous(::Type{<:FastContiguousSubArray}) = true
    
    

    Your view is not a FastContiguousSubArray:

    
        julia> typeof(v)
        SubArray{Float64, 3, Array{Float64, 3}, Tuple{UnitRange{Int64}, UnitRange{Int64}, UnitRange{Int64}}, false}
    
    

    where

    
        help?> SubArray
        search: SubArray BitArray Array DenseArray StridedArray
        
          SubArray{T,N,P,I,L} <: AbstractArray{T,N}
        
          N-dimensional view into a parent array (of type P) with an element type T, restricted by a tuple of indices (of type
          I). L is true for types that support fast linear indexing, and false otherwise. [...]
    
    

    which you can also verify by:

    
        julia> Base.viewindexing(v.indices)
        IndexCartesian()
    
    

    Take a look at the Linear indexing section in the manual.