Fit points to a Lorentzian curve and find center and half maximum bandwidth in Python
Question: I am using a python program to pull discreet values from a network analyzer.
It pulls 401 y-axis values and calculates the corresponding x-axis values, and
I wish to fit them to a lorentzian curve and find the x-axis value of the
y-axis maximum and the half y-axis maximum width.  
The lorentzian function I wish to fit these points to is

    
    
    (1/pi)(a/((x-x0)^2+(a)^2))
    

and I must find `a` and `x0` given the `x` and `y` values returned from the
network analyzer. Is there a simple way to do this using `scipy` or `numpy`? I
usually try and post any attempt I have made, but I'm not sure where to even
start. Thank you!


Answer: As Zhenya I would suggest using
[curve_fit](http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.curve_fit.html).
If `xdata` and `ydata` are your values you can do

    
    
    import numpy as np
    import scipy as sp
    from scipy.optimize import curve_fit
    
    def lorentzian(x, a, x0):
        return a / ((x-x0)**2 + a**2) / np.pi
    
    # Obtain xdata and ydata
    ...
    
    # Initial guess of the parameters (you must find them some way!)
    pguess = [a_guess, x0_guess]
    
    # Fit the data
    popt, pcov = curve_fit(lorentzian, xdata, ydata, p0 = pguess)
    
    # Results
    a, x0 = popt[0], popt[1]
    

A suggestion to make the initial guess could be:

    
    
    a_guess = 1 / (np.pi * max(ydata))
    x0_guess = sum(xdata * ydata) / sum(ydata)
    

I have not tested the code, but in principle it should work.

