-
Notifications
You must be signed in to change notification settings - Fork 78
Expand file tree
/
Copy patharray.jl
More file actions
385 lines (368 loc) · 12.4 KB
/
array.jl
File metadata and controls
385 lines (368 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
const pyjlarraytype = pynew()
function pyjl_getaxisindex(x::AbstractUnitRange{<:Integer}, k::Py)
if pyisslice(k)
a = @pyconvert Union{Int,Nothing} k.start begin
errset(pybuiltins.TypeError, "slice components must be integers")
pythrow()
end
b = @pyconvert Union{Int,Nothing} k.step begin
errset(pybuiltins.TypeError, "slice components must be integers")
pythrow()
end
c = @pyconvert Union{Int,Nothing} k.stop begin
errset(pybuiltins.TypeError, "slice components must be integers")
pythrow()
end
# step defaults to 1
b′ = b === nothing ? 1 : b
if a === nothing && c === nothing
# when neither is specified, start and stop default to the full range,
# which is reversed when the step is negative
if b′ > 0
a′ = Int(first(x))
c′ = Int(last(x))
elseif b′ < 0
a′ = Int(last(x))
c′ = Int(first(x))
else
errset(pybuiltins.ValueError, "step must be non-zero")
pythrow()
end
else
# start defaults
a′ = Int(a === nothing ? first(x) : a < 0 ? (last(x) + a + 1) : (first(x) + a))
c′ = Int(
c === nothing ? last(x) :
c < 0 ? (last(x) + 1 + c - sign(b′)) : (first(x) + c - sign(b′)),
)
end
r = StepRange{Int,Int}(a′, b′, c′)
if checkbounds(Bool, x, r)
return r
else
errset(pybuiltins.IndexError, "array index out of bounds")
pythrow()
end
else
j = @pyconvert Int k begin
errset(
pybuiltins.TypeError,
"index must be slice or integer, got '$(pytype(k).__name__)'",
)
pythrow()
end
r = Int(j < 0 ? (last(x) + j + 1) : (first(x) + j))
if checkbounds(Bool, x, r)
return r
else
errset(pybuiltins.IndexError, "array index out of bounds")
pythrow()
end
end
end
function pyjl_getarrayindices(x::AbstractArray{T,N}, ks::Py) where {T,N}
if pyistuple(ks)
if pylen(ks) == N
return ntuple(N) do i
k = pytuple_getitem(ks, i - 1)
ans = pyjl_getaxisindex(axes(x, i), k)
pydel!(k)
return ans
end
else
errset(pybuiltins.TypeError, "expecting $N indices, got $(pylen(ks))")
pythrow()
end
elseif N == 1
return (pyjl_getaxisindex(axes(x, 1), ks),)
else
errset(pybuiltins.TypeError, "expecting $N indices, got 1")
end
end
function pyjlarray_getitem(x::AbstractArray{T,N}, k_::Py) where {T,N}
k = pyjl_getarrayindices(x, k_)
pydel!(k_)
if k isa NTuple{N,Int}
return Py(x[k...])
else
return Py(view(x, k...))
end
end
function pyjlarray_setitem(x::AbstractArray{T,N}, k_::Py, v_::Py) where {T,N}
k = pyjl_getarrayindices(x, k_)
pydel!(k_)
if k isa NTuple{N,Int}
v = pyconvertarg(T, v_, "value")
x[k...] = v
else
v = pyconvertarg(Any, v_, "value")
x[k...] .= v
end
return Py(nothing)
end
function pyjlarray_delitem(x::AbstractArray{T,N}, k_::Py) where {T,N}
if N == 1
k = pyjl_getarrayindices(x, k_)
pydel!(k_)
deleteat!(x, k...)
else
errset(pybuiltins.TypeError, "can only delete from 1D arrays")
pythrow()
end
return Py(nothing)
end
pyjl_handle_error_type(::typeof(pyjlarray_delitem), x, exc::MethodError) =
exc.f === deleteat! ? pybuiltins.TypeError : PyNULL
function pyjlarray_reshape(x::AbstractArray, shape_::Py)
shape = pyconvertarg(Union{Int,Vector{Int}}, shape_, "shape")
pydel!(shape_)
return Py(reshape(x, shape...))
end
pyjlarray_isbufferabletype(::Type{T}) where {T} = T in (
Int8,
Int16,
Int32,
Int64,
UInt8,
UInt16,
UInt32,
UInt64,
Float16,
Float32,
Float64,
Complex{Float16},
Complex{Float32},
Complex{Float64},
Bool,
Ptr{Cvoid},
)
pyjlarray_isbufferabletype(::Type{T}) where {T<:Tuple} =
isconcretetype(T) &&
allocatedinline(T) &&
all(pyjlarray_isbufferabletype, fieldtypes(T))
pyjlarray_isbufferabletype(::Type{NamedTuple{names,T}}) where {names,T} =
pyjlarray_isbufferabletype(T)
function pyjlarray_buffer_info(x::AbstractArray{T,N}) where {T,N}
if pyjlarray_isbufferabletype(T)
Cjl.PyBufferInfo{N}(
ptr = Base.unsafe_convert(Ptr{T}, x),
readonly = !Utils.ismutablearray(x),
itemsize = sizeof(T),
format = pybufferformat(T),
shape = size(x),
strides = strides(x) .* Base.aligned_sizeof(T),
)
else
error("element type is not bufferable")
end
end
const PYBUFFERFORMAT = IdDict{Type,String}()
pybufferformat(::Type{T}) where {T} =
get!(PYBUFFERFORMAT, T) do
T == Cchar ? "b" :
T == Cuchar ? "B" :
T == Cshort ? "h" :
T == Cushort ? "H" :
T == Cint ? "i" :
T == Cuint ? "I" :
T == Clong ? "l" :
T == Culong ? "L" :
T == Clonglong ? "q" :
T == Culonglong ? "Q" :
T == Float16 ? "e" :
T == Cfloat ? "f" :
T == Cdouble ? "d" :
T == Complex{Float16} ? "Ze" :
T == Complex{Cfloat} ? "Zf" :
T == Complex{Cdouble} ? "Zd" :
T == Bool ? "?" :
T == Ptr{Cvoid} ? "P" :
if (T <: Union{Tuple,NamedTuple}) && isstructtype(T) && isconcretetype(T) && allocatedinline(T)
n = fieldcount(T)
flds = []
for i = 1:n
nm = fieldname(T, i)
tp = fieldtype(T, i)
push!(flds, string(pybufferformat(tp), nm isa Symbol ? ":$nm:" : ""))
d =
(i == n ? sizeof(T) : fieldoffset(T, i + 1)) -
(fieldoffset(T, i) + sizeof(tp))
@assert d ≥ 0
d > 0 && push!(flds, "$(d)x")
end
string("T{", join(flds, " "), "}")
else
"$(sizeof(T))x"
end
end
pyjlarray_isarrayabletype(::Type{T}) where {T} = T in (
UInt8,
Int8,
UInt16,
Int16,
UInt32,
Int32,
UInt64,
Int64,
Bool,
Float16,
Float32,
Float64,
Complex{Float16},
Complex{Float32},
Complex{Float64},
)
pyjlarray_isarrayabletype(::Type{NumpyDates.InlineDateTime64{U}}) where {U} = true
pyjlarray_isarrayabletype(::Type{NumpyDates.InlineTimeDelta64{U}}) where {U} = true
pyjlarray_isarrayabletype(::Type{T}) where {T<:Tuple} =
isconcretetype(T) &&
Base.allocatedinline(T) &&
all(pyjlarray_isarrayabletype, T.parameters)
pyjlarray_isarrayabletype(::Type{NamedTuple{names,types}}) where {names,types} =
pyjlarray_isarrayabletype(types)
const PYTYPESTRDESCR = IdDict{Type,Tuple{String,Py}}()
function pytypestrdescr(::Type{T}) where {T}
get!(PYTYPESTRDESCR, T) do
c = Utils.islittleendian() ? '<' : '>'
if T == Bool
("$(c)b$(sizeof(Bool))", PyNULL)
elseif T == Int8
("$(c)i1", PyNULL)
elseif T == UInt8
("$(c)u1", PyNULL)
elseif T == Int16
("$(c)i2", PyNULL)
elseif T == UInt16
("$(c)u2", PyNULL)
elseif T == Int32
("$(c)i4", PyNULL)
elseif T == UInt32
("$(c)u4", PyNULL)
elseif T == Int64
("$(c)i8", PyNULL)
elseif T == UInt64
("$(c)u8", PyNULL)
elseif T == Float16
("$(c)f2", PyNULL)
elseif T == Float32
("$(c)f4", PyNULL)
elseif T == Float64
("$(c)f8", PyNULL)
elseif T == Complex{Float16}
("$(c)c4", PyNULL)
elseif T == Complex{Float32}
("$(c)c8", PyNULL)
elseif T == Complex{Float64}
("$(c)c16", PyNULL)
elseif isconcretetype(T) &&
T <: Union{NumpyDates.InlineDateTime64,NumpyDates.InlineTimeDelta64}
u, m = NumpyDates.unitpair(T)
tc = T <: NumpyDates.InlineDateTime64 ? 'M' : 'm'
us =
u == NumpyDates.UNBOUND_UNITS ? "" :
m == 1 ? "[$(Symbol(u))]" : "[$(m)$(Symbol(u))]"
("$(c)$(tc)8$(us)", PyNULL)
elseif (T <: Union{Tuple,NamedTuple}) && isstructtype(T) && isconcretetype(T) && Base.allocatedinline(T)
n = fieldcount(T)
flds = []
for i = 1:n
nm = fieldname(T, i)
tp = fieldtype(T, i)
ts, ds = pytypestrdescr(tp)
isempty(ts) && return ("", PyNULL)
push!(
flds,
(nm isa Integer ? "f$(nm-1)" : string(nm), pyisnull(ds) ? ts : ds),
)
d =
(i == n ? sizeof(T) : fieldoffset(T, i + 1)) -
(fieldoffset(T, i) + sizeof(tp))
@assert d ≥ 0
d > 0 && push!(flds, ("", "|V$(d)"))
end
("|$(sizeof(T))V", pylist(flds))
else
("", PyNULL)
end
end
end
pyjlarray_array__array(x::AbstractArray) = x isa Array ? Py(nothing) : pyjl(Array(x))
pyjlarray_array__pyobjectarray(x::AbstractArray) = pyjl(PyObjectArray(x))
function pyjlarray_array_interface(x::AbstractArray{T,N}) where {T,N}
if pyjlarray_isarrayabletype(eltype(x))
data = (UInt(Base.unsafe_convert(Ptr{T}, x)), !Utils.ismutablearray(x))
typestr, descr = pytypestrdescr(T)
if !isempty(typestr)
d = pydict()
d["shape"] = size(x)
d["typestr"] = typestr
d["data"] = data
d["strides"] = strides(x) .* Base.aligned_sizeof(T)
d["version"] = 3
if !pyisnull(descr)
d["descr"] = descr
end
return d
end
end
errset(pybuiltins.AttributeError, "__array_interface__")
return PyNULL
end
pyjl_handle_error_type(::typeof(pyjlarray_array_interface), x, exc) =
pybuiltins.AttributeError
function init_array()
jl = pyjuliacallmodule
pybuiltins.exec(
pybuiltins.compile(
"""
$("\n"^(@__LINE__()-1))
class ArrayValue(AnyValue):
__slots__ = ()
_jl_buffer_info = $(pyjl_methodnum(pyjlarray_buffer_info))
@property
def ndim(self):
return self._jl_callmethod($(pyjl_methodnum(Py ∘ ndims)))
@property
def shape(self):
return self._jl_callmethod($(pyjl_methodnum(Py ∘ size)))
def copy(self):
return self._jl_callmethod($(pyjl_methodnum(Py ∘ copy)))
def reshape(self, shape):
return self._jl_callmethod($(pyjl_methodnum(pyjlarray_reshape)), shape)
def __bool__(self):
return bool(len(self))
def __getitem__(self, k):
return self._jl_callmethod($(pyjl_methodnum(pyjlarray_getitem)), k)
def __setitem__(self, k, v):
self._jl_callmethod($(pyjl_methodnum(pyjlarray_setitem)), k, v)
def __delitem__(self, k):
self._jl_callmethod($(pyjl_methodnum(pyjlarray_delitem)), k)
@property
def __array_interface__(self):
return self._jl_callmethod($(pyjl_methodnum(pyjlarray_array_interface)))
def __array__(self, dtype=None, copy=None):
import numpy
# convert to an array-like object
arr = self
if not (hasattr(arr, "__array_interface__") or hasattr(arr, "__array_struct__")):
if copy is False:
raise ValueError("copy=False is not supported when collecting ArrayValue data")
# the first attempt collects into an Array
arr = self._jl_callmethod($(pyjl_methodnum(pyjlarray_array__array)))
if not (hasattr(arr, "__array_interface__") or hasattr(arr, "__array_struct__")):
# the second attempt collects into a PyObjectArray
arr = self._jl_callmethod($(pyjl_methodnum(pyjlarray_array__pyobjectarray)))
# convert to a numpy array if numpy is available
return numpy.array(arr, dtype=dtype, copy=copy)
def to_numpy(self, dtype=None, copy=True, order="K"):
import numpy
return numpy.array(self, dtype=dtype, copy=copy, order=order)
""",
@__FILE__(),
"exec",
),
jl.__dict__,
)
pycopy!(pyjlarraytype, jl.ArrayValue)
end
pyjltype(::AbstractArray) = pyjlarraytype