Python Forum
Error in running the Elliott Fitting function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: Error in running the Elliott Fitting function (/thread-23761.html)



Error in running the Elliott Fitting function - shashisourabh - Jan-15-2020

Hi All,
I am new to the python and trying to do some curve fitting for my lab data. I have found an Elliott Fit code from Dr. Valerio D'Innocenzo's doctoral thesis and changed a bit to work for my data but it is not working. It was giving me errors like :

" RuntimeWarning: overflow encountered in cosh
return (1 / (abs(np.cosh((e-x))/ gamma)) * 2 * np.pi * np.sqrt(Eb) / (1 - np.exp(-2 * np.pi / (np.sqrt(D)))) * 1 / (1 - npc * (x - Eg)))
"

My experimental data is in 2nd column and energy values in 1st column.

Can anyone help me fix it?
Thanks,
Shashi
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
# ODEpack tool for differential equation integration
from numpy.distutils.fcompiler import none
from scipy.integrate import odeint, quad
# Optimization tool
import scipy.optimize as opt
#Interpolation tool
from scipy.interpolate import interp1d

def Elliots_fit (p, a_exp , e):
    Eb, Eg, gamma, npc, k = p
    #Descrete transitions to the excitonic states
    absex = np.zeros((e.size))
    n = np.linspace(1, 500, 500)
    for i in range(0, e.size):
        expr = 4*np.pi*(Eb**(3/2)) / (n**3)*(1/(np.cosh((e[i] - Eg + Eb/n**2) / gamma)))
        S = expr.cumsum(axis=0)
        absex[i] = S[-1]

    #Band to band absorption with Sommerfeld correction
    abseh = np.zeros((e.size))

    def fun_eh(x, e, gamma, Eb, Eg, npc):
        D = (x-Eg)/Eb
        return (1 / (abs(np.cosh((e-x))/ gamma)) * 2 * np.pi * np.sqrt(Eb) / (1 - np.exp(-2 * np.pi / (np.sqrt(D)))) * 1 / (1 - npc * (x - Eg)))

    for i in range(0, e.size):
        q = quad(fun_eh, Eg, np.inf, args=(e[i], gamma, Eb, Eg, npc))
        abseh[i] = q[0]
    #Complete Abs simulation (background added)
    abs_sim = np.zeros((e.size))
    for i in range(0, e.size):
        abs_sim[i] = (e[i] / Eb**(3/2))*(absex[i] + abseh[i])
    return (abs_sim*k-abs_exp_fit)

#Data loading
data = np.loadtxt('transmission_data.txt')
# plt.plot(e, data[:,2])
e_exp = data [:,0] # concerted from nm to eV
a_exp = data[:,1] # My data
#Intial Values
Eb = 0.030 # exciton binding energy (eV)
gamma = 0.029 # inhomogeneous line broadening (eV)
Eg = 2.402 # semiconductor bandgap (eV)
npc = -0.31 # non−parabolic coefficient
k = 0.0035
#Energy axis generation
# ix0 = np.searchsorted(e_exp ,1.58862)
# ix1 = np.searchsorted(e_exp ,1.42976)
# e = np.linspace(e_exp[ix1], e_exp[ix0-1], 500) # energy axes (eV)
e = np.linspace(e_exp[len(e_exp)-1], e_exp[0], 3440) # energy axes (eV)
p0 = np.array([Eb, Eg, gamma, npc, k],dtype=np.float64 )#b = np.array([[1,2,3,4,5],[6,7,8,9,10]],dtype=np.float64)
#Fit Calling
#Interpolating the simulated abs over the exp x−axis
f = interp1d(e_exp ,a_exp)
abs_exp_fit = f(e)
opt_out = opt.leastsq(Elliots_fit ,p0, args =( abs_exp_fit , e), full_output=1)
fitted_param = opt_out[0]
#Standard error evaluation

fitting = Elliots_fit(fitted_param, abs_exp_fit, e)

plt.plot(e, abs_exp_fit)
plt.plot(e, fitting)

if (len( abs_exp_fit ) > len(p0)) and opt_out [1] is not None:
    s_sq = (( fitting-abs_exp_fit )**2).sum()((len( abs_exp_fit )-len(p0)))
    pcov = opt_out[1] * s_sq
else:
    pcov = np.inf
error = []
for i in range(len(opt_out [0])):
    try:
        error.append( np.absolute(pcov[i][i])**0.5)
    except:
        error.append( 0.00 )
pfit_leastsq = opt_out [0]
perr_leastsq = np.array(error)



RE: Error in running the Elliott Fitting function - Larz60+ - Jan-16-2020

Please provide the actual error traceback message verbatim.
It contains very valuable information for diagnosis of problem.
Thank You


RE: Error in running the Elliott Fitting function - shashisourabh - Jan-16-2020

Error:
C:\Users\bob\AppData\Local\Programs\Python\Python37-32\python.exe "C:\Program Files\JetBrains\PyCharm Community Edition 2019.2\helpers\pydev\pydevconsole.py" --mode=client --port=52730 import sys; print('Python %s on %s' % (sys.version, sys.platform)) sys.path.extend(['F:\\Python', 'F:/Python']) Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] Type 'copyright', 'credits' or 'license' for more information IPython 7.10.2 -- An enhanced Interactive Python. Type '?' for help. PyDev console: using IPython 7.10.2 Python 3.7.4 (tags/v3.7.4:e09359112e, Jul 8 2019, 19:29:22) [MSC v.1916 32 bit (Intel)] on win32 runfile('C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py', wdir='C:/Users/bob/.PyCharmCE2019.2/config/scratches') Backend TkAgg is interactive backend. Turning interactive mode on. C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py:27: RuntimeWarning: overflow encountered in cosh return (1 / (abs(np.cosh((e-x))/ gamma)) * 2 * np.pi * np.sqrt(Eb) / (1 - np.exp(-2 * np.pi / (np.sqrt(D)))) * 1 / (1 - npc * (x - Eg))) C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py:18: RuntimeWarning: invalid value encountered in double_scalars expr = 4*np.pi*(Eb**(3/2)) / (n**3)*(1/(np.cosh((e[i] - Eg + Eb/n**2) / gamma))) C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py:30: IntegrationWarning: The occurrence of roundoff error is detected, which prevents the requested tolerance from being achieved. The error may be underestimated. q = quad(fun_eh, Eg, np.inf, args=(e[i], gamma, Eb, Eg, npc)) C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py:35: RuntimeWarning: invalid value encountered in double_scalars abs_sim[i] = (e[i] / Eb**(3/2))*(absex[i] + abseh[i]) C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py:30: IntegrationWarning: The algorithm does not converge. Roundoff error is detected in the extrapolation table. It is assumed that the requested tolerance cannot be achieved, and that the returned result (if full_output = 1) is the best which can be obtained. q = quad(fun_eh, Eg, np.inf, args=(e[i], gamma, Eb, Eg, npc)) C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py:30: IntegrationWarning: The maximum number of subdivisions (50) has been achieved. If increasing the limit yields no improvement it is advised to analyze the integrand in order to determine the difficulties. If the position of a local difficulty can be determined (singularity, discontinuity) one will probably gain from splitting up the interval and calling the integrator on the subranges. Perhaps a special-purpose integrator should be used. q = quad(fun_eh, Eg, np.inf, args=(e[i], gamma, Eb, Eg, npc)) C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py:30: IntegrationWarning: The integral is probably divergent, or slowly convergent. q = quad(fun_eh, Eg, np.inf, args=(e[i], gamma, Eb, Eg, npc)) Traceback (most recent call last): File "C:\Users\bob\AppData\Local\Programs\Python\Python37-32\lib\site-packages\IPython\core\interactiveshell.py", line 3319, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-2-e821db8486f9>", line 1, in <module> runfile('C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py', wdir='C:/Users/bob/.PyCharmCE2019.2/config/scratches') File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.2\helpers\pydev\_pydev_bundle\pydev_umd.py", line 197, in runfile pydev_imports.execfile(filename, global_vars, local_vars) # execute the script File "C:\Program Files\JetBrains\PyCharm Community Edition 2019.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile exec(compile(contents+"\n", file, 'exec'), glob, loc) File "C:/Users/bob/.PyCharmCE2019.2/config/scratches/ElliottFitting.py", line 69, in <module> s_sq = (( fitting-abs_exp_fit )**2).sum()((len( abs_exp_fit )-len(p0))) TypeError: 'numpy.float64' object is not callable plt.plot(e, abs_exp_fit) plt.plot(e, fitting) Out[3]: [<matplotlib.lines.Line2D at 0x2854030>]



RE: Error in running the Elliott Fitting function - shashisourabh - Jan-16-2020

Can anyone tell me how to fix this code?


RE: Error in running the Elliott Fitting function - Larz60+ - Jan-16-2020

Something doesn't look quite right with line 69.
It looks like perhaps parenthesis are in the wrong positions.
Do you have a link to the original D'Innocenzo's thesis?


RE: Error in running the Elliott Fitting function - scidam - Jan-16-2020

I think, you missed arithmetical symbol in (( fitting-abs_exp_fit )**2).sum()((len( abs_exp_fit )-len(p0))).

( fitting-abs_exp_fit )**2).sum() -- This is a numpy array. Further, you've used parenthesis: ( fitting-abs_exp_fit )**2).sum()(...).
That means you tried to call a numpy array.

You need to change your code to
s_sq = (( fitting-abs_exp_fit )**2).sum()<some symbol here>((len( abs_exp_fit )-len(p0)))
where <some symbol here> is either "/", "*", etc (or something else).


RE: Error in running the Elliott Fitting function - shashisourabh - Jan-17-2020

(Jan-16-2020, 10:46 PM)Larz60+ Wrote: Something doesn't look quite right with line 69.
It looks like perhaps parenthesis are in the wrong positions.
Do you have a link to the original D'Innocenzo's thesis?

Here is the link to his thesis: https://www.politesi.polimi.it/bitstream/10589/117853/5/2016_03_PhD_D%27Innocenzo.pdf.pdf


RE: Error in running the Elliott Fitting function - shashisourabh - Mar-27-2020

I fixed line 69 but still getting error with "cosh" function. Also, if anyone who is an expert in fitting can help figure out why the author(D'Innocenzo) has used "a_exp" at line 12 although he has not used the variable in the function definition.


RE: Error in running the Elliott Fitting function - Larz60+ - Mar-27-2020

Quote:still getting error
still need to see error trace


RE: Error in running the Elliott Fitting function - osvan - Nov-19-2020

Have you had any success with Elliott fitting?