'Grid from a set of arrays - how to cut execution time?

I have a wide set of splines, and at each point (x,z) of these splines is associated to a field value. I need to map all these points and relevant field values on a grid/matrix.

Here, I simplified the situation that I have. The problem is that, with nested for loops, the execution time for my real case is way too much.

Is there any solution to make it faster (at least 10 times) Thank you,

import matplotlib.pyplot as plt
import numpy as np
import time
start_time = time.time()

# Spline1
x1 = np.array([1,3,5,6,7])
z1 = np.array([10,20,30,40,50])
field1 = np.array([5,7,9,13,15])
# Spline2
x2 = np.array([2,4,6])
z2 = np.array([10,20,30])
field2 = np.array([0.3, 0.5, 0.7])

# all coords together - with reps
x_all = np.concatenate((x1,x2),0)
z_all = np.concatenate((z1,z2),0)
field_all = np.concatenate((field1,field2),0)
# all coords together - no reps
x_new = np.unique(np.concatenate((x1,x2),0))
z_new = np.unique(np.concatenate((z1,z2),0))
field_new = np.zeros((len(z_new), len(x_new)))

xs, zs = np.meshgrid(x_new, z_new, sparse=True)
zs_t = zs.T

for x_coord, z_coord, field in zip(x_all, z_all, field_all):
    for idx, x in enumerate (xs[0]):
        for idz, z in enumerate (zs_t[0]):
            if x_coord==x and z_coord==z:
                field_new[idz, idx] = field

xs.shape, zs.shape, field_new.shape

plt.contourf(x_new, z_new, field_new)
plt.axis('scaled')
plt.colorbar()
plt.show()


print("--- %s seconds ---" % (time.time() - start_time))


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source