Skip to content

Commit

Permalink
load in-place
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander-Barth committed Nov 29, 2018
1 parent dc0f9fe commit 95362f0
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/NCDatasets.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1063,6 +1063,35 @@ function Base.setindex!(v::Variable,data,indexes::Union{Int,Colon,UnitRange{Int}
end



"""
load!(ncvar::Variable, data, indices)
Loads a NetCDF variables `ncvar` and puts the result in `data` along the
specified indices.
```julia
data = zeros(5,6); # must have the right shape and type
load!(ds["temp"].var,data,:,:) # loads all data
data = zeros(5); # must have the right shape and type
load!(ds["temp"].var,data,:,1) # loads the 1st column
```
"""
@inline function load!(ncvar::NCDatasets.Variable{T,N}, data, indices::Union{Integer, UnitRange, StepRange, Colon}...) where {T,N}
ind = to_indices(ncvar,indices)
start,count,stride,jlshape = ncsub(ind)
nc_get_vars!(ncvar.ncid,ncvar.varid,start,count,stride,data)
end

@inline function load!(ncvar::NCDatasets.Variable{T,2}, data, i::Colon,j::UnitRange) where T
# reversed and 0-based
start = [first(j)-1,0]
count = [length(j),size(ncvar,1)]
nc_get_vara!(ncvar.ncid,ncvar.varid,start,count,data)
end


# -----------------------------------------------------
# Variable (with applied transformations following the CF convention)

Expand Down
9 changes: 9 additions & 0 deletions test/test_variable.jl
Original file line number Diff line number Diff line change
Expand Up @@ -73,4 +73,13 @@ Dataset(filename,"c") do ds
@test eltype(ds["temp"].var) == Int32
@test ds.dim["lon"] == sz[1]
@test ds.dim["lat"] == sz[2]

# load in-place
data2 = similar(data)
NCDatasets.load!(ds["temp"].var,data2,:,:)
@test data2 == data

data2 = zeros(eltype(data),sz[1],2)
NCDatasets.load!(ds["temp"].var,data2,:,1:2)
@test data2 == data[:,1:2]
end

0 comments on commit 95362f0

Please sign in to comment.