-
Notifications
You must be signed in to change notification settings - Fork 438
InputOutputSystem.copy
makes shallow copies
#728
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Good catch. My sense is that if someone calls the Some other situations we should also think about:
|
The answer is "it's complicated"; for arrays of immutable types (e.g., numbers), n [5]: a = np.array([1,2,3])
In [6]: b = a.copy()
In [7]: b[0] = 100
In [8]: a[0]
Out[8]: 1 but for mutable array elements, with dtype=object, you can see the copies are actually shallow: n [11]: c = np.array([{'a':23},{'b':99}],dtype=object)
In [12]: c[0]
Out[12]: {'a': 23}
In [13]: d = c.copy()
In [14]: d[0]['b'] = 100
In [15]: c[0]
Out[15]: {'a': 23, 'b': 100}
I don't think this is right for
I think deep, so that if you fiddle with entries of one (scaling with a gain, say), you don't affect the others. |
@roryyorke I agree with your assessment. With regards to If shallow copies are to be kept, I think it will be useful to have a disclaimer for in-place operations like A,B,C,D = [np.eye(2) for _ in range(4)]
sys = control.ss(A,B,C,D)
sys_copy = sys.copy()
# in-place operations modify original
sys_copy.A *= 2
print('Copy (in-place assignment)\n', sys_copy.A)
print('Original sys (after copy)\n', sys.A)
print('Actual matrix (after copy)\n', A)
print()
sys = control.ss(A,B,C,D)
sys_copy = sys.copy()
# Re-assigning matrices does not modify original:
sys_copy.A = sys_copy.A * 2
print('Copy (re-Assignment)\n', sys_copy.A)
print('Original sys (after copy)\n', sys.A)
print('Actual matrix (after copy)\n', A) |
In NumPy and SciPy copying is a bit easier since the main issue is the underlying memory buffer (direct or indirect) and the rest is just some meta pepper. Once the buffer is copied and if the dtype is suitable, it is quite easy to copy the rest. For objects it's the I wouldn't bother with object arrays since many consider it to be an historical overzealous inclusion. For generic use, it is fair to assume that NumPy and SciPy favors deep copy, but again, the shallow copy for NumPy arrays is just assignment Here indeed the copies should be deep but copying user-defined classes is always a pain. |
This is may be by design, but I found it unexpected (see below). If it is by design, it would help to add "shallow" to the doctring.
One way to deep copy is to use
control.ss
; continuing from above:The text was updated successfully, but these errors were encountered: