pyjulia icon indicating copy to clipboard operation
pyjulia copied to clipboard

Python variables are reallocated when called in pyjulia

Open valentinsulzer opened this issue 5 years ago • 1 comments

e.g.

from julia import Main
from julia import Base
import numpy as np
a = np.random.rand(5)
print(a.data) # <memory at 0x7febefab91c0>
Base.println(Base.pointer(a)) # Ptr{Nothing} @0x00007febe4cd3750

This means that a function that should update a variable inplace (here dy) does not

from julia import Main
import numpy as np
f_b = Main.eval(
    """
begin
function f_b(dy,y,a,b)
    dy[1] = a*y[1]
    dy[2] = b*y[2]
    dy
end
end
"""
)
# Calling from python
dy = np.array([0,0])
y = np.array([1, 3])
print(dy) # returns [0 0]
print(f_b(dy, y, 5, 3)) # returns [5 9]
print(dy) # returns [0 0] (expected [5 9])
# Calling through Main
Main.dy = np.array([0,0])
Main.y = np.array([1,3])
print(Main.dy) # returns [0 0]
print(Main.f_b(Main.dy, Main.y, 5, 3)) # returns [5 9]
print(Main.dy) # returns [0 0] (expected [5 9])

Calling the function through Main.eval does update dy

Main.dy = np.array([0,0])
Main.y = np.array([1,3])
print(Main.dy) # returns [ 0 0 ]
Main.eval("f_b(dy, y, 5, 3)")
print(Main.dy) # returns [5 9]

valentinsulzer avatar Oct 28 '20 17:10 valentinsulzer

As I said in Slack, I'm not sure this is expected to work with non-numpy arrays. However, it seems to me that Numpy->Julia incurs a copy and Julia->Numpy does not. See the MWE below

Python-> Julia:

from julia import Main
from julia import Base
import numpy as np
a = np.random.rand(5)
print(a.data)
Base.println(Base.pointer(a))

gives

>>> a.data
<memory at 0x7febefab91c0>
>>> Base.println(Base.pointer(a))
Ptr{Nothing} @0x00007febe4cd3750

Julia-> Python

from julia import Main
from julia import Base
import numpy as np
Main.a = Base.rand(5)
a = Main.a
print(a)
a[0:] = 0
print(a)
print(Main.a)

gives

>>> print(a)
[0. 0. 0. 0. 0.]
>>> print(Main.a)
[0. 0. 0. 0. 0.]

PhilipVinc avatar Oct 28 '20 17:10 PhilipVinc