Solving a complex BVP problem with scipy solve_bvp - python

I have a complex BVP problem (almost Shrodinger equation). My code works but the solution is completely wrong or just equal to zero. What am I doing wrong?
I also have obtained right solution by Maple, there was no problem. Also I don't understand why there is no problem with plot when it has to be complex-valued function.
import numpy as np
from scipy.integrate import odeint
from scipy.integrate import solve_bvp as bvp
import matplotlib.pyplot as plt
mp = 938.2720813
mn = 939.5654133
mu = (mn + mp)/4
h2m = hbar**2/(2*mu)
V0 = 20
Rv = 1.5
Q0 = 1.5
Rq = 4.5
EIm = 0.3
ERe = 1
V = lambda x : -V0*np.exp(-x/Rv)
Q = lambda x : -Q0*np.exp(-x/Rq)
def fun(x, y):
return np.vstack((y[1], -( Q(x)/ h2m ) - ((ERe + 1j * EIm) *y[0]/ h2m ) + V(x)*y[0]/h2m - (2/y[0])* y[1]))
def bc(ya, yb):
return np.array([ya[0], yb[0]])
x = np.linspace(0, 1000, 10000)
y_a = np.zeros((2, x.size), dtype=np.complex)
# print(x.size)
i = 0
while i < x.size - 1:
i = i + 1
y_a[0, i] = 1000* 1j
y_a[1, i] = 1j
from scipy.integrate import solve_bvp
res_a = solve_bvp(fun, bc, x, y_a)
x_plot = np.linspace(0, 1000, 10000)
y_plot_a = res_a.sol(x_plot)[0]
import matplotlib.pyplot as plt
plt.plot(x_plot, y_plot_a, label='y_a')
plt.legend()
plt.xlabel("x")
plt.ylabel("y")
plt.show()
Upd: I fixed a mistake in the equation.
Result is still wrong. But there is another error - division by zero. How to avoid it? If I choose x = np.linspace(0.1, 1000, 10000) for example it doesn't help.

Related

Python: how to integrate functions with two unknown parameters numerically

Now I have two functions respectively are
rho(u) = np.exp( (-2.0 / 0.2) * (u**0.2-1.0) )
psi( w(x-u) ) = (1/(4.0 * math.sqrt(np.pi))) * np.exp(- ((w * (x-u))**2) / 4.0) * (2.0 - (w * (x-u))**2)
And then I want to integrate 'rho(u) * psi( w(x-u) )' with respect to 'u'. So that the integral result can be one function with respect to 'w' and 'x'.
Here's my Python code snippet as I try to solve this integral.
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy import integrate
x = np.linspace(0,10,1000)
w = np.linspace(0,10,500)
u = np.linspace(0,10,1000)
rho = np.exp((-2.0/0.2)*(u**0.2-1.0))
value = np.zeros((500,1000),dtype="float32")
# Integrate the products of rho with
# (1/(4.0*math.sqrt(np.pi)))*np.exp(- ((w[i]*(x[j]-u))**2) / 4.0)*(2.0 - (w[i]*(x[j]-u))**2)
for i in range(len(w)):
for j in range(len(x)):
value[i,j] =value[i,j]+ integrate.simps(rho*(1/(4.0*math.sqrt(np.pi)))*np.exp(- ((w[i]*(x[j]-u))**2) / 4.0)*(2.0 - (w[i]*(x[j]-u))**2),u)
plt.imshow(value,origin='lower')
plt.colorbar()
As illustrated above, when I do the integration, I used nesting for loops. We all know that such a way is inefficient.
So I want to ask whether there are methods not using for loop.
Here is a possibility using scipy.integrate.quad_vec. It executes in 6 seconds on my machine, which I believe is acceptable. It is true, however, that I have used a step of 0.1 only for both x and w, but such a resolution seems to be a good compromise on a single core.
from functools import partial
import matplotlib.pyplot as plt
from numpy import empty, exp, linspace, pi, sqrt
from scipy.integrate import quad_vec
from time import perf_counter
def func(u, x):
rho = exp(-10 * (u ** 0.2 - 1))
var = w * (x - u)
psi = exp(-var ** 2 / 4) * (2 - var ** 2) / 4 / sqrt(pi)
return rho * psi
begin = perf_counter()
x = linspace(0, 10, 101)
w = linspace(0, 10, 101)
res = empty((x.size, w.size))
for i, xVal in enumerate(x):
res[i], err = quad_vec(partial(func, x=xVal), 0, 10)
print(f'{perf_counter() - begin} s')
plt.contourf(w, x, res)
plt.colorbar()
plt.xlabel('w')
plt.ylabel('x')
plt.show()
UPDATE
I had not realised, but one can also work with a multi-dimensional array in quad_vec. The updated approach below enables to increase the resolution by a factor of 2 for both x and w, and keep an execution time of around 7 seconds. Additionally, no more visible for loops.
import matplotlib.pyplot as plt
from numpy import exp, mgrid, pi, sqrt
from scipy.integrate import quad_vec
from time import perf_counter
def func(u):
rho = exp(-10 * (u ** 0.2 - 1))
var = w * (x - u)
psi = exp(-var ** 2 / 4) * (2 - var ** 2) / 4 / sqrt(pi)
return rho * psi
begin = perf_counter()
x, w = mgrid[0:10:201j, 0:10:201j]
res, err = quad_vec(func, 0, 10)
print(f'{perf_counter() - begin} s')
plt.contourf(w, x, res)
plt.colorbar()
plt.xlabel('w')
plt.ylabel('x')
plt.show()
Addressing the comment
Just add the following lines before plt.show() to have both axes scale logarithmically.
plt.gca().set_xlim(0.05, 10)
plt.gca().set_ylim(0.05, 10)
plt.gca().set_xscale('log')
plt.gca().set_yscale('log')

How to guess the numerical Solution for Mathieu's Equation

am trying to predict the exact solution for the mathieu's equation y"+(lambda - 2qcos(2x))y = 0. I have been able to get five eigenvalues for the equation using numerical approximation and I want to find for each eigenvalues a guessed exact solution. I would be greatfull if someone helps. Thank you. Below is one of the codes for the fourth Eigenvalue
from scipy.integrate import solve_bvp
import numpy as np
import matplotlib.pyplot as plt
Definition of Mathieu's Equation
q = 5.0
def func(x,u,p):
lambd = p[0]
# y'' + (lambda - 2qcos(2x))y = 0
ODE = [u[1],-(lambd - 2.0*q*np.cos(2.0*x))*u[0]]
return np.array(ODE)
Definition of Boundary conditions(BC)
def bc(ua,ub,p):
return np.array([ua[0]-1., ua[1], ub[1]])
A guess solution of the mathieu's Equation
def guess(x):
return np.cos(4*x-6)
Nx = 100
x = np.linspace(0, np.pi, Nx)
u = np.zeros((2,x.size))
u[0] = -x
res = solve_bvp(func, bc, x, u, p=[16], tol=1e-7)
sol = guess(x)
print res.p[0]
x_plot = np.linspace(0, np.pi, Nx)
u_plot = res.sol(x_plot)[0]
plt.plot(x_plot, u_plot, 'r-', label='u')
plt.plot(x, sol, color = 'black', label='Guess')
plt.legend()
plt.xlabel("x")
plt.ylabel("y")
plt.title("Mathieu's Equation for Guess$= \cos(3x) \quad \lambda_4 = %g$" % res.p )
plt.grid()
plt.show()
[Plot of the Fourth Eigenvalues][2]
To compute the first five eigenpairs, thus, pairs of eigenvalues and eigenfunctions, of the Mathieu's equation Y" + (λ − 2q cos(2x))y = 0, on the interval [0, π] with boundary conditions:
y'(0) = 0, and y'(π) = 0 when q = 5.
The solution is normalized so that y(0) = 1. Though all the initial values are known at x = 0, the problem requires finding a value for the parameters that allows the boundary condition y'(π) = 0 to be satisfied.
Therefore the guess or exact solution of Mathieu's equation is cos(k*x) where k ∈ ℕ.
from scipy.integrate import solve_bvp
import numpy as np
import matplotlib.pyplot as plt
q = 5.0
# Definition of Mathieu's Equation
def func(x,u,p):
lambd = p[0]
# y'' + (lambda - 2qcos(2x))y = 0 can be rewritten as u2'= - (lambda - 2qcos(2x))u1
ODE = [u[1],-(lambd - 2.0*q*np.cos(2.0*x))*u[0]]
return np.array(ODE)
# Definition of Boundary conditions(BC)
def bc(ua,ub,p):
return np.array([ua[0]-1., ua[1], ub[1]])
# A guess solution of the mathieu's Equation
def guess(x):
return np.cos(5*x) # for k=5
Nx = 100
x = np.linspace(0, np.pi, Nx)
u = np.zeros((2,x.size))
u[0] = -x # initial guess
res = solve_bvp(func, bc, x, u, p=[20], tol=1e-9)
sol = guess(x)
print res.p[0]
x_plot = np.linspace(0, np.pi, Nx)
u_plot = res.sol(x_plot)[0]
plt.plot(x_plot, u_plot, 'r-', label='u')
plt.plot(x, sol, linestyle='--', color='k', label='Guess')
plt.legend(loc='best')
plt.xlabel("x")
plt.ylabel("y")
plt.title("Mathieu's Equation $\lambda_5 = %g$" % res.p)
plt.grid()
plt.savefig('Eigenpair_5v1.png')
plt.show()
Solution of Mathieu Equation

Minimizing a function using python for data fitting

I have a function as the following
q = 1 / sqrt( ((1+z)**2 * (1+0.01*o_m*z) - z*(2+z)*(1-o_m)) )
h = 5 * log10( (1+z)*q ) + 43.1601
I have experimental answers of above equation and once I must to put some data into above function and solve equation below
chi=(q_exp-q_theo)**2/err**2 # this function is a sigma, sigma chi from z=0 to z=1.4 (in the data file)
z, err and q_exp are in the data file(2.txt). Now I have to choose a range for o_m (0.2 to 0.4) and find in what o_m, the chi function will be minimized.
my code is:
from math import *
from scipy.integrate import quad
min = None
l = None
a = None
b = None
c = 0
def ant(z,om,od):
return 1/sqrt( (1+z)**2 * (1+0.01*o_m*z) - z*(2+z)*o_d )
for o_m in range(20,40,1):
o_d=1-0.01*o_m
with open('2.txt') as fp:
for line in fp:
n = list( map(float, line.split()) )
q = quad(ant,n[0],n[1],args=(o_m,o_d))[0]
h = 5.0 * log10( (1+n[1])*q ) + 43.1601
chi = (n[2]-h)**2 / n[3]**2
c = c + chi
if min is None or min>c:
min = c
l = o_m
print('chi=',q,'o_m=',0.01*l)
n[1],n[2],n[3],n[4] are z1, z2, q_exp and err, respectively in the data file. and z1 and z2 are the integration range.
I need your help and I appreciate your time and your attention.
Please do not rate a negative value. I need your answers.
Here is my understanding of the problem.
First I generate some data by the following code
import numpy as np
from scipy.integrate import quad
from random import random
def boxmuller(x0,sigma):
u1=random()
u2=random()
ll=np.sqrt(-2*np.log(u1))
z0=ll*np.cos(2*np.pi*u2)
z1=ll*np.cos(2*np.pi*u2)
return sigma*z0+x0, sigma*z1+x0
def q_func(z, oM, oD):
den= np.sqrt( (1.0 + z)**2 * (1+0.01 * oM * z) - z * (2+z) * (1-oD) )
return 1.0/den
def h_func(z,q):
out = 5 * np.log10( (1.0 + z) * q ) + .25#43.1601
return out
def q_Int(z1,z2,oM,oD):
out=quad(q_func, z1,z2,args=(oM,oD))
return out
ooMM=0.3
ooDD=1.0-ooMM
dataList=[]
for z in np.linspace(.3,20,60):
z1=.1+.1*z*.01*z**2
z2=z1+3.0+.08+z**2
q=q_Int(z1,z2,ooMM,ooDD)[0]
h=h_func(z,q)
sigma=np.fabs(.01*h)
h=boxmuller(h,sigma)[0]
dataList+=[[z,z1,z2,h,sigma]]
dataList=np.array(dataList)
np.savetxt("data.txt",dataList)
which I would then fit in the following way
import matplotlib
matplotlib.use('Qt5Agg')
from matplotlib import pyplot as plt
import numpy as np
from scipy.integrate import quad
from scipy.optimize import leastsq
def q_func(z, oM, oD):
den= np.sqrt( (1.0 + z)**2 * (1+0.01 * oM * z) - z * (2+z) * (1-oD) )
return 1.0/den
def h_func(z,q):
out = 5 * np.log10( (1.0 + z) * q ) + .25#43.1601
return out
def q_Int(z1,z2,oM,oD):
out=quad(q_func, z1,z2,args=(oM,oD))
return out
def residuals(parameters,data):
om,od=parameters
zList=data[:,0]
yList=data[:,3]
errList=data[:,4]
qList=np.fromiter( (q_Int(z1,z2, om,od)[0] for z1,z2 in data[ :,[1,2] ]), np.float)
hList=np.fromiter( (h_func(z,q) for z,q in zip(zList,qList)), np.float)
diffList=np.fromiter( ( (y-h)/e for y,h,e in zip(yList,hList,errList) ), np.float)
return diffList
dataList=np.loadtxt("data.txt")
###fitting
startGuess=[.4,.8]
bestFitValues, cov,info,mesg, ier = leastsq(residuals, startGuess , args=( dataList,),full_output=1)
print bestFitValues,cov
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
ax.plot(dataList[:,0],dataList[:,3],marker='x')
###fitresult
fqList=[q_Int(z1,z2,bestFitValues[0], bestFitValues[1])[0] for z1,z2 in zip(dataList[:,1],dataList[:,2])]
fhList=[h_func(z,q) for z,q in zip(dataList[:,0],fqList)]
ax.plot(dataList[:,0],fhList,marker='+')
plt.show()
giving output
>>[ 0.31703574 0.69572673]
>>[[ 1.38135263e-03 -2.06088258e-04]
>> [ -2.06088258e-04 7.33485166e-05]]
and the graph
Note that for leastsq the covariance matrix is in reduced form and needs to be rescaled.
Unconcsiosely, this question overlap my other question. The correct answer is:
from math import *
import numpy as np
from scipy.integrate import quad
min=l=a=b=chi=None
c=0
z,mo,err=np.genfromtxt('Union2.1_z_dm_err.txt',unpack=True)
def ant(z,o_m): #0.01*o_m is steps of o_m
return 1/sqrt(((1+z)**2*(1+0.01*o_m*z)-z*(2+z)*(1-0.01*o_m)))
for o_m in range(20,40):
c=0
for i in range(len(z)):
q=quad(ant,0,z[i],args=(o_m,))[0] #Integration o to z
h=5*log10((1+z[i])*(299000/70)*q)+25 #function of dL
chi=(mo[i]-h)**2/err[i]**2 #chi^2 test function
c=c+chi
l=o_m
print('chi^2=',c,'Om=',0.01*l,'OD=',1-0.01*l)

python partial derivatives, I can't use this with numeric

I have a function who I neeed to make to it partial derivatives dependent on a parameter and to use this in another function, and then to solve an ODE system, The function who I need to derivate is anizotropy_energy with respect of theta and phi
import sympy
import numpy as np
from sympy import Symbol, diff, sin, cos
theta = Symbol('theta')
phi = Symbol('phi')
theta_k = Symbol('theta_k')
phi_k = Symbol('phi_k')
def anizotropy_energy(theta, phi, theta_k, phi_k):
u_rx = sin(theta)*sin(phi)
u_ry = sin(theta)*sin(phi)
u_rz = cos(theta)
u_kx = sin(theta_k)*cos(phi_k)
u_ky = sin(theta_k)*sin(phi_k)
u_kz = cos(theta_k)
u_kx*u_rx + u_ky*u_ry + u_kz*u_rz
diff((u_kx*u_rx + u_ky*u_ry + u_kz*u_rz)**2, theta)
I made it with sympy, but I can't use these derrivates in odeint
I have an intermediate function where I a have to add to a structure with theta and phi this derrivates and then to use this function in the main program with Ode
Intermediate function:
import math
import numpy as np
from anisotropy_energy import anizotropy_energy
def thetafunc_anisotropy(alpha,theta,phi, hx, hy, hz, theta_k, phi_k):
return alpha*(hx*np.cos(theta)*np.cos(phi) + hy*np.cos(theta)*np.sin(phi)- \
hz*np.sin(theta) + \
anizotropy_energy(theta, phi, theta_k, phi_k) + \
(-hx*np.sin(phi) + hy*np.cos(phi))
# diff(anizotropy_energy(theta, phi, theta_k, phi_k), phi) )
The main programme:
import matplotlib as mpl
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import thetafunc_anizotropy
from thetafunc_anizotropy import thetafunc_anisotropy
import phifunc_anizotropy
from phifunc_anizotropy import phifunc_anisotropy
import sympy
def LLG(y, t, alpha, hx, hy, hz, theta_k, phi_k):
theta, phi = y
dydt = [thetafunc_anisotropy(alpha,theta,phi, hx, hy, hz, theta_k, phi_k), thetafunc_anisotropy(alpha,theta,phi, hx, hy, hz, theta_k, phi_k)]
return dydt
alpha = 0.1
H = 1.0
t0 = 60.0*np.pi/180.0
p0 = 0.0*np.pi/180.0
hx = H*np.sin(t0)*np.cos(p0)
hy = H*np.sin(t0)*np.sin(p0)
hz = H*np.cos(t0)
theta_k = 60.0*np.pi/180.0
phi_k = 60.0*np.pi/180.0
y0 = [np.pi, -0*np.pi]
t = np.linspace(0, 1000, 10000)
sol = odeint(LLG, y0, t, args=(alpha,hx, hy, hz, theta_k, phi_k ))
print sol
mpl.rcParams['legend.fontsize'] = 10
#
fig = plt.figure()
ax = fig.gca(projection='3d')
#x = np.sol[:, 0]
#y = sol[:, 1]
#ax.plot(x, y, label='parametric curve')
#ax.legend()
x = np.sin(sol[:, 0])*np.cos(sol[:, 1])
y = np.sin(sol[:, 0])*np.sin(sol[:, 1])
z = np.cos(sol[:, 0])
ax.plot(x, y, z, label='parametric curve')
ax.legend()
#plt.show()
#plt.axes(projection='3d')
#plt.plot(t, sol[:, 0], 'b', label='$\\theta(t)$')
#plt.plot(t,sol[:,1], 'r', label='$\\varphi(t)$')
#
#plt.legend(loc='best')
#plt.xlabel('t')
#
#plt.grid()
#plt.show()
Your error is in anizotropy_energy.py. You have global variables with the same name as function parameters.
In this case you have a global named theta and phi AND function parameters named theta and phi. You must rename one pair of them.
I labeled the function parameters theta and phi to in_theta and in_phi. You should really rename them.
Also, Note that in some places you say anisotropy and some you say anizotropy.
import sympy
import numpy as np
from sympy import Symbol, diff, sin, cos
theta = Symbol('theta')
phi = Symbol('phi')
theta_k = Symbol('theta_k')
phi_k = Symbol('phi_k')
def anizotropy_energy(in_theta, in_phi, theta_k, phi_k):
u_rx = sin(in_theta)*sin(in_phi)
u_ry = sin(in_theta)*sin(in_phi)
u_rz = cos(in_theta)
u_kx = sin(theta_k)*cos(phi_k)
u_ky = sin(theta_k)*sin(phi_k)
u_kz = cos(theta_k)
u_kx*u_rx + u_ky*u_ry + u_kz*u_rz
return diff((u_kx*u_rx + u_ky*u_ry + u_kz*u_rz)**2, theta)

Still having trouble with curve fitting

I already opened a question on this topic, but I wasn't sure, if I should post it there, so I opened a new question here.
I have trouble again when fitting two or more peaks. First problem occurs with a calculated example function.
xg = np.random.uniform(0,1000,500)
mu1 = 200
sigma1 = 20
I1 = -2
mu2 = 800
sigma2 = 20
I2 = -1
yg3 = 0.0001*xg
yg1 = (I1 / (sigma1 * np.sqrt(2 * np.pi))) * np.exp( - (xg - mu1)**2 / (2 * sigma1**2) )
yg2 = (I2 / (sigma2 * np.sqrt(2 * np.pi))) * np.exp( - (xg - mu2)**2 / (2 * sigma2**2) )
yg=yg1+yg2+yg3
plt.figure(0, figsize=(8,8))
plt.plot(xg, yg, 'r.')
I tried two different approaches, I found in the documentation, which are shown below (modified for my data), but both give me wrong fitting data and a messy chaos of graphs (I guess one line per fitting step).
1st attempt:
import numpy as np
from lmfit.models import PseudoVoigtModel, LinearModel, GaussianModel, LorentzianModel
import sys
import matplotlib.pyplot as plt
gauss1 = PseudoVoigtModel(prefix='g1_')
pars.update(gauss1.make_params())
pars['g1_center'].set(200)
pars['g1_sigma'].set(15, min=3)
pars['g1_amplitude'].set(-0.5)
pars['g1_fwhm'].set(20, vary=True)
#pars['g1_fraction'].set(0, vary=True)
gauss2 = PseudoVoigtModel(prefix='g2_')
pars.update(gauss2.make_params())
pars['g2_center'].set(800)
pars['g2_sigma'].set(15)
pars['g2_amplitude'].set(-0.4)
pars['g2_fwhm'].set(20, vary=True)
#pars['g2_fraction'].set(0, vary=True)
mod = gauss1 + gauss2 + LinearModel()
pars.add('intercept', value=0, vary=True)
pars.add('slope', value=0.0001, vary=True)
init = mod.eval(pars, x=xg)
out = mod.fit(yg, pars, x=xg)
print(out.fit_report(min_correl=0.5))
plt.figure(5, figsize=(8,8))
out.plot_fit()
When I include the 'fraction'-parameter, I often get
'NameError: name 'pv1_fraction' is not defined in expr='<_ast.Module object at 0x00000000165E03C8>'.
although it should be defined. I get this Error for real data with this approach, too.
2nd attempt:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import lmfit
def gauss(x, sigma, mu, A):
return A*np.exp(-(x-mu)**2/(2*sigma**2))
def linear(x, m, n):
return m*x + n
peak1 = lmfit.model.Model(gauss, prefix='p1_')
peak2 = lmfit.model.Model(gauss, prefix='p2_')
lin = lmfit.model.Model(linear, prefix='l_')
model = peak1 + lin + peak2
params = model.make_params()
params['p1_mu'] = lmfit.Parameter(value=200, min=100, max=250)
params['p2_mu'] = lmfit.Parameter(value=800, min=100, max=1000)
params['p1_sigma'] = lmfit.Parameter(value=15, min=0.01)
params['p2_sigma'] = lmfit.Parameter(value=20, min=0.01)
params['p1_A'] = lmfit.Parameter(value=-2, min=-3)
params['p2_A'] = lmfit.Parameter(value=-2, min=-3)
params['l_m'] = lmfit.Parameter(value=0)
params['l_n'] = lmfit.Parameter(value=0)
out = model.fit(yg, params, x=xg)
print out.fit_report()
plt.figure(8, figsize=(8,8))
out.plot_fit()
So the result looks like this, in both cases. It seems to plot all fitting attempts, but never solves it correctly. The best fitted parameters are in the range that I gave it.
Anyone knows this type of error? Or has any solutions for this? And does anyone know how to avoid the NameError when calling a model function from lmfit with those approaches?
I have a somewhat tolerable solution for you. Since I don't know how variable your data is, I cannot say that it will work in a general sense but should get you started. If your data is along 0-1000 and has two peaks or dips along a line as you showed, then it should work.
I used the scipy curve_fit and put all of the components of the function together into one function. One can pass starting locations into the curve_fit function. (you can probably do this with the lib you're using but I'm not familiar with it) There is a loop in loop where I vary the mu parameters to find the ones with the lowest squared error. If you are needing to fit your data many times or in some real-time scenario then this is not for you but if you just need to fit some data, launch this code and grab a coffee.
from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt
import pylab
from matplotlib import cm as cm
import time
def my_function_big(x, m, n, #lin vars
sigma1, mu1, I1, #gaussian 1
sigma2, mu2, I2): #gaussian 2
y = m * x + n + (I1 / (sigma1 * np.sqrt(2 * np.pi))) * np.exp( - (x - mu1)**2 / (2 * sigma1**2) ) + (I2 / (sigma2 * np.sqrt(2 * np.pi))) * np.exp( - (x - mu2)**2 / (2 * sigma2**2) )
return y
#make some data
xs = np.random.uniform(0,1000,500)
mu1 = 200
sigma1 = 20
I1 = -2
mu2 = 800
sigma2 = 20
I2 = -1
yg3 = 0.0001 * xs
yg1 = (I1 / (sigma1 * np.sqrt(2 * np.pi))) * np.exp( - (xs - mu1)**2 / (2 * sigma1**2) )
yg2 = (I2 / (sigma2 * np.sqrt(2 * np.pi))) * np.exp( - (xs - mu2)**2 / (2 * sigma2**2) )
ys = yg1 + yg2 + yg3
xs = np.array(xs)
ys = np.array(ys)
#done making data
#start a double loop...very expensive but this is quick and dirty
#it would seem that the regular optimizer has trouble finding the minima so i
#found that having the near proper mu values helped it zero in much better
start = time.time()
serr = []
_x = []
_y = []
for x in np.linspace(0, 1000, 61):
for y in np.linspace(0, 1000, 61):
cfiti = curve_fit(my_function_big, xs, ys, p0=[0, 0, 1, x, 1, 1, y, 1], maxfev=20000000)
serr.append(np.sum((my_function_big(xs, *cfiti[0]) - ys) ** 2))
_x.append(x)
_y.append(y)
serr = np.array(serr)
_x = np.array(_x)
_y = np.array(_y)
print 'done loop in loop fitting'
print 'time: %0.1f' % (time.time() - start)
gridsize=20
plt.subplot(111)
plt.hexbin(_x, _y, C=serr, gridsize=gridsize, cmap=cm.jet, bins=None)
plt.axis([_x.min(), _x.max(), _y.min(), _y.max()])
cb = plt.colorbar()
cb.set_label('SE')
plt.show()
ix = np.argmin(serr.ravel())
mustart1 = _x.ravel()[ix]
mustart2 = _y.ravel()[ix]
print mustart1
print mustart2
cfit = curve_fit(my_function_big, xs, ys, p0=[0, 0, 1, mustart1, 1, 1, mustart2, 1], maxfev=2000000000)
xp = np.linspace(0, 1000, 1001)
plt.figure()
plt.scatter(xs, ys) #plot synthetic dat
plt.plot(xp, my_function_big(xp, *cfit[0]), '-', label='fit function') #plot data evaluated along 0-1000
plt.legend(loc=3, numpoints=1, prop={'size':12})
plt.show()
pylab.close()
Good luck!
In your first attempt:
pars['g1_fraction'].set(0, vary=True)
The fraction must be a value between 0 and 1, but I believe that cannot be zero. Try to put something like 0.000001, and it will work.

Categories