Skip to content

Commit

Permalink
ndarray: copy(AbstractArray, context) (#367)
Browse files Browse the repository at this point in the history
julia> copy(1:4, mx.cpu())
4 mx.NDArray{Int64,1} @ CPU0:
 1
 2
 3
 4

julia> copy(1.:4, mx.cpu())
4 mx.NDArray{Float64,1} @ CPU0:
 1.0
 2.0
 3.0
 4.0
  • Loading branch information
iblislin authored and pluskid committed Dec 10, 2017
1 parent 2ca5565 commit 12198f0
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 6 deletions.
18 changes: 18 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,24 @@

```

* `copy(AbstractArray, context)` is implemented now. (#TBD)

```julia
julia> copy(1:4, mx.cpu())
4 mx.NDArray{Int64,1} @ CPU0:
1
2
3
4

julia> copy(1.:4, mx.cpu())
4 mx.NDArray{Float64,1} @ CPU0:
1.0
2.0
3.0
4.0
```

## API Changes

### `NDArray`
Expand Down
11 changes: 5 additions & 6 deletions src/ndarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -401,19 +401,15 @@ which furthur translates into
create a **copy** of the sub-array for Julia `Array`, while for `NDArray`, this is
a *slice* that shares the memory.
"""
function getindex(arr::NDArray, ::Colon)
return arr
end
getindex(arr::NDArray, ::Colon) = arr

"""
Shortcut for [`slice`](@ref).
**NOTE** the behavior for Julia's built-in index slicing is to create a
copy of the sub-array, while here we simply call `slice`,
which shares the underlying memory.
"""
function getindex(arr::NDArray, idx::UnitRange{Int})
slice(arr, idx)
end
getindex(arr::NDArray, idx::UnitRange{Int}) = slice(arr, idx)

getindex(arr::NDArray) = _first(arr)

Expand Down Expand Up @@ -503,6 +499,9 @@ copy(x::NDArray{T,D}, ctx::Context) where {T,D} =
copy(x::Array{T}, ctx::Context) where {T<:DType} =
copy!(empty(T, size(x), ctx), x)

copy(x::AbstractArray, ctx::Context) =
copy!(empty(eltype(x), size(x), ctx), collect(x))

"""
convert(::Type{Array{<:Real}}, x::NDArray)
Expand Down
11 changes: 11 additions & 0 deletions test/unittest/ndarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ function test_copy()
array2 = copy(array, mx.cpu())
tensor2 = copy(array2)
@test tensor tensor2

info("NDArray::copy::AbstractArray")
let x = copy(1:4, mx.cpu())
@test eltype(x) == Int
@test copy(x) == [1, 2, 3, 4]
end

let x = copy(1.:4, mx.cpu())
@test eltype(x) == Float64
@test copy(x) [1., 2, 3, 4]
end
end

function test_deepcopy()
Expand Down

0 comments on commit 12198f0

Please sign in to comment.