1

I am trying to create an array np.zeros((3, 3)) outside a function and use it inside a function over and over again. The reason for that is numba's cuda implementation, which does not support array creation inside functions that are to be run on a gpu. So I create aforementioned array ar_ref , and pass it as argument to function. ar creates a copy of ar_ref (this is supposed to be used as "fresh" np.zeros((3, 3)) copy). Then I perform some changes to ar and return it. But in the process ar_ref gets overwritten inside the function by the last iteration of ar. How do I start every new iteration of the function with ar = np.zeros((3, 3)) without having to call np.zeros inside the function?

import numpy as np

def function(ar_ref=None):
    for n in range(3):
        print(n)
        ar = ar_ref
        print(ar)
        for i in range(3):
            ar[i] = 1
        print(ar)
    return ar

ar_ref = np.zeros((3, 3))
function(ar_ref=ar_ref)

Output:

0
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
1
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
2
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
Artur Müller Romanov
  • 4,417
  • 10
  • 73
  • 132
  • 1
    Does this answer your question? [List changes unexpectedly after assignment. How do I clone or copy it to prevent this?](https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-how-do-i-clone-or-copy-it-to-prevent) – Pavneet_Singh Jul 10 '20 at 12:51
  • use copy methods . https://stackoverflow.com/questions/19676538/numpy-array-assignment-with-copy – Pavneet_Singh Jul 10 '20 at 12:52
  • @Pavneet_Singh although `np.copy` works, I am not sure if it is supported by the `numba.cuda` API. Is there a way to make a `slice copy` of an `array`? `ar = ar_ref[:]` produces the wrong result. – Artur Müller Romanov Jul 10 '20 at 13:07
  • you can try `numpy.copy`, from the [second comment](https://stackoverflow.com/questions/62834697/copy-of-array-gets-overwritten-in-function?noredirect=1#comment111115574_62834697) – Pavneet_Singh Jul 10 '20 at 13:16

1 Answers1

2

simple assignment will only assign pointer, so when you change ar, ar_ref changes too. try to use shallow copy for this issue

import numpy as np
import copy 

def function(ar_ref=None):
    for n in range(3):
        print(n)
        ar = copy.copy(ar_ref)
        print(ar)
        for i in range(3):
            ar[i] = 1
        print(ar)
    return ar

ar_ref = np.zeros((3, 3))
function(ar_ref=ar_ref)

output:

0
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
1
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
2
[[0. 0. 0.]
 [0. 0. 0.]
 [0. 0. 0.]]
[[1. 1. 1.]
 [1. 1. 1.]
 [1. 1. 1.]]
mjrezaee
  • 1,100
  • 5
  • 9