pyjulia icon indicating copy to clipboard operation
pyjulia copied to clipboard

Usage of SparseArrays with pyjulia?

Open mengxixi opened this issue 6 years ago • 1 comments

It seems like objects from the SparseArrays package get automatically converted to generic Array objects when returned by a Julia call via pyjulia, and hence the returned object cannot be passed into a subsequent Julia function that takes in a SparseVector/SparseMatrixCSC/etc. as input. As an example,

>>> from julia import SparseArrays
>>> SparseArrays.nnz(SparseArrays.sparse([1,2,3],[1,2,3],[1,1,1]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
RuntimeError: Julia exception: MethodError: no method matching nnz(::Array{Int64,2})
Closest candidates are:
  nnz(!Matched::SparseArrays.SparseMatrixCSC) at /Users/osx/buildbot/slave/package_osx64/build/usr/share/julia/stdlib/v1.1/SparseArrays/src/sparsematrix.jl:73
  nnz(!Matched::Base.ReshapedArray{T,1,#s623,MI} where MI<:Tuple{Vararg{Base.MultiplicativeInverses.SignedMultiplicativeInverse{Int64},N} where N} where #s623<:SparseArrays.SparseMatrixCSC) where T at /Users/osx/buildbot/slave/package_osx64/build/usr/share/julia/stdlib/v1.1/SparseArrays/src/sparsematrix.jl:74
  nnz(!Matched::SparseArrays.SparseVector) at /Users/osx/buildbot/slave/package_osx64/build/usr/share/julia/stdlib/v1.1/SparseArrays/src/sparsevector.jl:42
  ...
Stacktrace:
 [1] #invokelatest#1(::Base.Iterators.Pairs{Union{},Union{},Tuple{},NamedTuple{(),Tuple{}}}, ::Function, ::Any, ::Any, ::Vararg{Any,N} where N) at ./essentials.jl:742
 [2] invokelatest(::Any, ::Any, ::Vararg{Any,N} where N) at ./essentials.jl:741
 [3] _pyjlwrap_call(::Function, ::Ptr{PyCall.PyObject_struct}, ::Ptr{PyCall.PyObject_struct}) at /Users/siyimeng/.julia/packages/PyCall/ttONZ/src/callback.jl:28
 [4] pyjlwrap_call(::Ptr{PyCall.PyObject_struct}, ::Ptr{PyCall.PyObject_struct}, ::Ptr{PyCall.PyObject_struct}) at /Users/siyimeng/.julia/packages/PyCall/ttONZ/src/callback.jl:49

Is the SparseArrays package supported by pyjulia or am I not handling it correctly? Thanks!

mengxixi avatar May 29 '19 06:05 mengxixi

This would be fixed once https://github.com/JuliaPy/PyCall.jl/issues/617 is done.

Meanwhile, you can always do Main.eval. A powerful pattern is to create "adapter" functions in Julia using Main.eval or Main.include and call it from Python.

tkf avatar May 29 '19 07:05 tkf