I have a python program that takes a bunch of values and calculates the spin of a particle as output. The program is not a function, so there are no inputs. I have been told to optimize three different values individually (only changing one value, while leaving the other two constant) to produce an optimized output of the y-component of spin of this particle. I think what I need to do it turn this program into a function, with the value I want to optimize being the input. Then I think I need to make a new function to iterate through all possible values of the input to produce my desired output. For example, I need to optimize the length of a dipole magnet. The y-component of spin should have a value of -1 in real life, but I need it to be accurate to 10 decimal places (-.9999999999). How to I optimize the value of the length of the dipole magnet to produce the value of y-spin to be accurate to 10 decimal places?
1 Answer
If I'm correct you calculate S[1], S[2] and S[3] right? Try to rewrite your code so you get something like:
def getSpin(L1,L2,d):
...all your calculations will be done here..
# return the value of S[2] minus the goal value, optimization can find 0
return S[2]-1.0
To optimise the result, use the scipy.optimize-package and evaluate on S[2]. To do so, be sure that scipy is installed on your machine. The code below is a first suggestion from my side and thus not yet tested/debugged, so please check out the documentation of the solver. In this code x0 and the bounds needs to be filled in. If you place the min and max value of a certain parameter equal to eachother, the solver will take that parameter fixed at that value and only vary the other parameter(s).
from scipy.optimize import minimize
x0=(0.203, 5.653, 0.189089089089089) # your initial guess
bounds=((l1min,l1max),(l2min,l2max),(dmin,dmax)) # the minimum and maximum values for each parameter
res=minimize(getSpin,x0,method=‘SLSQP’,args=(),bounds=bounds,tol:1e-10)
#res.x contains the optimized values for L1,L2 and d
scipy.optimizefind the optimum scipy.optimize: docs.scipy.org/doc/scipy-0.14.0/reference/optimize.html