Source code for numerical.fit

#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Function and approximation.

.. module:: fit
  :platform: *nix, Windows
  :synopsis: Function and approximation.

.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
"""
from __future__ import print_function
from pylab import array, argmax, gradient, exp, sqrt, log, linspace
from scipy.optimize import curve_fit

[docs]def gauss(x, *p): """Gauss distribution function. .. math:: f(x)=ae^{-(x-b)^{2}/(2c^{2})} :param x: positions where the gauss function will be calculated :type x: int or float or list or numpy.ndarray :param p: gauss parameters [a, b, c, d]: * a -- amplitude (:math:`\int y \\,\\mathrm{d}x=1 \Leftrightarrow a=1/(c\\sqrt{2\\pi})` ) * b -- expected value :math:`\\mu` (position of maximum, default = 0) * c -- standard deviation :math:`\\sigma` (variance :math:`\\sigma^2=c^2`) * d -- vertical offset (default = 0) :type p: list :returns: gauss values at given positions x :rtype: numpy.ndarray """ x = array(x) # cast e. g. list to numpy array a, b, c, d = p return a*exp(-(x - b)**2./(2. * c**2.)) + d
[docs]def gauss_fit(x, y, e=None, x_fit=None, verbose=False): """Fit Gauss distribution function to data. :param x: positions :type x: int or float or list or numpy.ndarray :param y: values :type y: int or float or list or numpy.ndarray :param e: error values (default = None) :type e: int or float or list or numpy.ndarray :param x_fit: positions of fitted function (default = None, if None then x is used) :type x_fit: int or float or list or numpy.ndarray :param verbose: verbose information (default = False) :type verbose: bool :returns: * numpy.ndarray -- fitted values (y_fit) * numpy.ndarray -- parameters of gauss distribution function (popt: amplitude a, expected value :math:`\\mu`, standard deviation :math:`\\sigma`, vertical offset d) * numpy.float64 -- full width at half maximum (FWHM) :rtype: tuple .. seealso:: :meth:`gauss` """ x = array(x) # cast e. g. list to numpy array y = array(y) # cast e. g. list to numpy array y_max = max(y) y_max_pos = argmax(y) x_y_max = x[y_max_pos] # starting parameter p0 = [y_max, x_y_max, .1, y[0]] if verbose: print('p0:', end=' ') print(p0) if e is not None: popt, pcov = curve_fit(gauss, x, y, p0=p0, sigma=e) else: popt, pcov = curve_fit(gauss, x, y, p0=p0) if verbose: print('popt:', end=' ') print(popt) #print(pcov) FWHM = 2*sqrt(2*log(2))*popt[2] if verbose: print('FWHM', FWHM) if x_fit is None: x_fit = x y_fit = gauss(x_fit, *popt) return y_fit, popt, FWHM
if __name__ == "__main__": True