Skip to content

Commit 95362f0

Browse files
load in-place
1 parent dc0f9fe commit 95362f0

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/NCDatasets.jl

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1063,6 +1063,35 @@ function Base.setindex!(v::Variable,data,indexes::Union{Int,Colon,UnitRange{Int}
10631063
end
10641064

10651065

1066+
1067+
"""
1068+
load!(ncvar::Variable, data, indices)
1069+
1070+
Loads a NetCDF variables `ncvar` and puts the result in `data` along the
1071+
specified indices.
1072+
1073+
```julia
1074+
data = zeros(5,6); # must have the right shape and type
1075+
load!(ds["temp"].var,data,:,:) # loads all data
1076+
1077+
data = zeros(5); # must have the right shape and type
1078+
load!(ds["temp"].var,data,:,1) # loads the 1st column
1079+
```
1080+
"""
1081+
@inline function load!(ncvar::NCDatasets.Variable{T,N}, data, indices::Union{Integer, UnitRange, StepRange, Colon}...) where {T,N}
1082+
ind = to_indices(ncvar,indices)
1083+
start,count,stride,jlshape = ncsub(ind)
1084+
nc_get_vars!(ncvar.ncid,ncvar.varid,start,count,stride,data)
1085+
end
1086+
1087+
@inline function load!(ncvar::NCDatasets.Variable{T,2}, data, i::Colon,j::UnitRange) where T
1088+
# reversed and 0-based
1089+
start = [first(j)-1,0]
1090+
count = [length(j),size(ncvar,1)]
1091+
nc_get_vara!(ncvar.ncid,ncvar.varid,start,count,data)
1092+
end
1093+
1094+
10661095
# -----------------------------------------------------
10671096
# Variable (with applied transformations following the CF convention)
10681097

test/test_variable.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,13 @@ Dataset(filename,"c") do ds
7373
@test eltype(ds["temp"].var) == Int32
7474
@test ds.dim["lon"] == sz[1]
7575
@test ds.dim["lat"] == sz[2]
76+
77+
# load in-place
78+
data2 = similar(data)
79+
NCDatasets.load!(ds["temp"].var,data2,:,:)
80+
@test data2 == data
81+
82+
data2 = zeros(eltype(data),sz[1],2)
83+
NCDatasets.load!(ds["temp"].var,data2,:,1:2)
84+
@test data2 == data[:,1:2]
7685
end

0 commit comments

Comments
 (0)