Dear Sir,
I have written a code to calculate the magnetic field due to a current loop located in XY-plane. But the code takes 60 minutes to execute. Please help me to reduce it.
I have written a code to calculate the magnetic field due to a current loop located in XY-plane. But the code takes 60 minutes to execute. Please help me to reduce it.
import numpy as np from scipy.spatial import distance_matrix import time t1=time.time() n=20 # -------------- Poisition point of grid------------ x = np.array(np.linspace(-1,1,n)) y = np.array(np.linspace(-1,1,n)) z = np.array(np.linspace(-1,1,n)) X,Y,Z=np.meshgrid(x,y,z) #----Making array of position vector in calculation grid space----------- pos_vec=np.transpose([np.repeat(x,len(z)*len(y)),np.tile(np.repeat(y,len(z)),len(x)),np.tile(z,len(x)*len(y))]) # -------- Position Points of Loop------------ t=np.linspace(0,1,n) # n-points of wire loop in XY plane x_loop=np.sin(2*np.pi*t) y_loop=np.cos(2*np.pi*t) z_loop=np.zeros(n) loop_vec=np.transpose([x_loop,y_loop,z_loop]) # ----------- length of dl and mid point of dl----------- p_source=np.empty((n,3),float) dl=np.empty((n,3),float) for i in range(0,n-1): p_source[i]=((loop_vec[i+1,:]+loop_vec[i,:])/2) # position of Delta-1 (mid-point) dl[i]=(loop_vec[i+1,:]-loop_vec[i,:]) # Delta-1 vector R_vec=(distance_matrix(loop_vec,pos_vec)) # data set having four array, each is distance (r) from each dl point to all other points in space grid R_4point_loop=np.transpose(R_vec) # Set of four r's from four dl point to a single calculation point #################Functions ############################ ###### Normalized Vector (Unit Vector function)######## def normalize(v): norm=np.linalg.norm(v, ord=1) if norm==0: norm=np.finfo(v.dtype).eps return v/norm ###### Calculating B-field ############################ def B(dl,r_pos,r): i = 1 #Amps in the wire mu = 1.26 * 10**(-6) #Magnetic constant return ((mu/(2*np.pi))*(i/r**3))*np.cross(normalize(dl),normalize(r_pos)) #Magnitude of the vector B # -------- Making empty vectors--------- B_total=np.empty((len(x)*len(y)*len(z),3),dtype=float) B_dl=np.empty((n,3),float) B_point=np.empty((1,3),float) for r_end in pos_vec: B_dl*=0.0 B_point*=0.0 s=0 for i in range(n): B_dl[i]=np.array(B(dl[i],r_end,R_4point_loop[i][s])) s+=1 B_point+=B_dl[i] B_total[s]=B_point # Three components of data x_bfield=B_total[:,0].reshape(X.shape) y_bfield=B_total[:,1].reshape(X.shape) z_bfield=B_total[:,2].reshape(X.shape) t2=time.time() Elapsed=float(str(t2-t1)) print("Time of excecution (s):%.4f"%Elapsed)