pymycobot
pymycobot copied to clipboard
Using colon does not copy an array with latest Numpy
Describe the bug
In file demo/myCobot_280_demo/280_draw_gcode.py, the function process_gcode uses colon to copy a Numpy array, which only creates a view in latest Numpy (1.26.4)
Toy Example To Reproduce Steps to reproduce the behavior:
import numpy as np
if __name__ == '__main__':
data_coords = []
last_coords = np.zeros(shape=(6,))
for i in range(10):
coords = last_coords[:] # Copy the previous valid coordinates
coords[0] += 1
last_coords = coords
data_coords.append(coords) # Add coordinates to list and save
print(data_coords)
Result:
[array([10., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.])]
solution
You can use coords = last_coords.copy() to create a deep copy of last_coords instead of a shallow copy. Change coords = last_coords[:] in the code to coords = last_coords.copy()
Code reproduction
import numpy as np
if __name__ == '__main__':
data_coords = []
last_coords = np.zeros(shape=(6,))
for i in range(10):
coords = last_coords.copy() # Copy the previous valid coordinates
coords[0] += 1
last_coords = coords
data_coords.append(coords) # Add coordinates to list and save
print(data_coords)
Result:
[array([1., 0., 0., 0., 0., 0.]), array([2., 0., 0., 0., 0., 0.]), array([3., 0., 0., 0., 0., 0.]), array([4., 0., 0., 0., 0., 0.]), array([5., 0., 0., 0., 0., 0.]), array([6., 0., 0., 0., 0., 0.]), array([7., 0., 0., 0., 0., 0.]), array([8., 0., 0., 0., 0., 0.]), array([9., 0., 0., 0., 0., 0.]), array([10., 0., 0., 0., 0., 0.])]