I have a numpy array of points and want to extend my point (x
, y
and z
) in a defined direction. This is my array:
coordinates=np.array([[1., 19., 4.], [2., 19., 4.5], [1., 20., 4.],[2., 20., 4.5], [3., 20., 4.]])
These points are on two y
grids: 19
and 20
. I want to extend my points in these grid lines. First grid has two point. x
and y
coordinates of extrapolated points are fixed. y
equals the grid value (19 or 20) and x
equals one unit more that the last point of the grid. For first grid the new x
and y
of two points are (3.,19.)
and (4.,19.)
and z
should be calculated as:
z of last point + (z of last point - z of one point before the last)/2
In case of having just one point in the grid, I copy the value of that point. In the first grid, z
value of first extrapolated point is :
4.5 + (4.5-4)/2 = 4.75
and for the second point is
4.75 + (4.75-4.5)/2 = 4.875
I want to do the same for the next grid (y=20
) to finally add all four point to the existing array:
all_points=np.array([[1.,19.,4.], [1.,20.,4.], [2.,19.,4.5], [2.,20.,4.5], [3.,20.,4.],\
[3.,19.,4.75], [4.,19.,4.875], [4.,20,3.75], [5.,20, 3.625]])
I tried the following but firstly I have no idea how to generate z
value dynamically. At the moment it is calculating the same z values for the new two generated points of each grid. Another issue is that my code is not effiecient and I believe there are much faster ways to do it:
nums, counts=np.unique(coordinates[:,1],return_counts=True) # gives the y grids
new_y=nums
cum=np.cumsum(counts)-1
new_x=[]
for i in cum:
new_x.append (coordinates[i,0])
new_x=np.array(new_x)
new_x_y=[]
for m, n in zip (new_x, new_y):
new_x_y.append([m,n])
new_x_y.append([m+1,n])
new_x_y=np.array(new_x_y)
z_difference=[]
for i in cum:
z_difference.append((coordinates[i,-1]-coordinates[i-1,-1])/2)# to find the difference of last two points of each grid
new_z=[]
for i in range (len(cum)-1):
new_z.append (coordinates[cum[i],-1]+z_difference)#to find the new z of each extrapolated point
new_z=np.array(new_z)
all_z=np.repeat (new_z, repeats=new_z.shape[1], axis=1)
final_arr=np.hstack ([new_x_y, all_z.T])
In advance, I do appreciate any help to solve my problem in python.