I am trying to reduce lines of code because I realized that I am repeating the same equations every time. I am programming a contour map and putting several sources of intensity into it. Until now I put 3 sources, but in the future I want to put more, and that will increase the lines a lot. So I want to see if it is possible to reduce the lines of "source positions" and "Intensity equations". As you can see the last equation is a logaritmic summation of z1, z2 and z3, is it possible to reduce that, any idea?
import numpy as np
import matplotlib.pyplot as plt
def run():
# mesh
N = 100
x = np.linspace(-N, N)
y = np.linspace(-N, N)
X,Y = np.meshgrid(x,y)
# sources coordinates
p1 = [-5,-1]
p2 = [6 , 0]
p3 = [-10 , -8]
# sources postions
R1 = np.sqrt((((p1[0]-X)**2)+((p1[1]-Y)**2)))
R2 = np.sqrt((((p2[0]-X)**2)+((p2[1]-Y)**2)))
R3 = np.sqrt((((p3[0]-X)**2)+((p3[1]-Y)**2)))
# # Intensity Equation
z1 = np.round(10 * np.log10((((((R1/(1000**(1/3)))**-1.45) * 516)/(20**(-3)))**2)),0)
z2 = np.round(10 * np.log10((((((R2/(1000**(1/3)))**-1.45) * 516)/(20**(-3)))**2)),0)
z3 = np.round(10 * np.log10((((((R3/(4000**(1/3)))**-1.45) * 516)/(20**(-3)))**2)),0)
z_total = 10*np.log10((10**(z1/10))+(10**(z2/10)+(10**(z3/10))))
# # Ploting
Z = np.array(z_total).reshape(len(y),len(x))
cs = plt.contourf(X,Y,Z,10)
plt.colorbar()
plt.show()
if __name__ =='__main__':
run()
You could iterate over certain parts in a loop.
I tried to keep the same format overall and just rearranged the code to show how you might do it.
import numpy as np
import matplotlib.pyplot as plt
def run():
# mesh
N = 100
x = np.linspace(-N, N)
y = np.linspace(-N, N)
X,Y = np.meshgrid(x,y)
# sources coordinates
p = [
[-5,-1],
[6 , 0],
[-10 , -8],
]
# sources postions + intensity Equation
z_log = 0
for px, py in p:
r = np.sqrt((((px-X)**2)+((py-Y)**2)))
z = np.round(10 * np.log10((((((r/(1000**(1/3)))**-1.45) * 516)/(20**(-3)))**2)),0)
z_log += 10**(z/10)
z_total = 10*np.log10(z_log)
# # Ploting
Z = np.array(z_total).reshape(len(y),len(x))
cs = plt.contourf(X,Y,Z,10)
plt.colorbar()
plt.show()
if __name__ =='__main__':
run()
A recommendation I'd have is spread out operators (x + y * 2
is preferred over x+y*2
), give your variables descriptive names (eg. coordinates
and not p
), and split your calculations into more parts. There are so many brackets in z
for example that I'd hate to try and debug if something was not working correctly.