Passing 3d array to function creates view, not copy? (And how to improve code efficiency if repeatedly passing the same 3d array to function)

Viewed 22

Newbie to Python/numpy. I've got two questions in one for you guys on the code below.

1.) What is the best way to prevent bigArray from being modified? I have done some research and read over "view vs. copy" in Numpy docs but am still somewhat unsure about how people resolve this in practice.

2.) My actual simulation function does some basic linear/matrix algebra. Not even solving, just scalar multiplication, matrix addition, stuff like that. The only thing that changes from simulation to simulation is that some things depend on D which is stochastic. Do you expect it to be computationally costly to pass bigArray to my function thousands of times? Should I think about implementing this differently?

import numpy as np

# Constants
N = 100
K = 50
# T is something like 50k in actual code
T = 10

# Data
np.random.seed(0)
A = np.random.rand(N, K)
B = np.random.rand(N, K)
C = np.random.rand(N, K)
# (plus D, E, F, G in my actual code)
bigArray = np.array([A, B, C])

# Central function
def mySimulation(bigArray, D):
    localC = bigArray[2]
    # This changes bigArray!!!!
    localC[D] = 0.
    return localC

beforeC = bigArray[2].copy()
for t in range(T):
    # D is a mask that changes randomly from simulation to simulation
    D = np.random.choice([False, True], size=(N, K), p=[0.95, 0.05])
    resultingC = mySimulation(bigArray, D)

# I expected this to be all zeros
print(np.abs(bigArray[2]-beforeC))
0 Answers
Related