
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "examples/example_fit_with_derivfunc.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_examples_example_fit_with_derivfunc.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_examples_example_fit_with_derivfunc.py:


Fit Specifying a Function to Compute the Jacobian
=================================================

Specifying an analytical function to calculate the Jacobian can speed-up the
fitting procedure.

.. GENERATED FROM PYTHON SOURCE LINES 9-44

.. code-block:: Python

    import matplotlib.pyplot as plt
    import numpy as np

    from lmfit import Minimizer, Parameters


    def func(pars, x, data=None):
        a, b, c = pars['a'], pars['b'], pars['c']
        model = a * np.exp(-b*x) + c
        if data is None:
            return model
        return model - data


    def dfunc(pars, x, data=None):
        a, b = pars['a'], pars['b']
        v = np.exp(-b*x)
        return np.array([v, -a*x*v, np.ones(len(x))])


    def f(var, x):
        return var[0] * np.exp(-var[1]*x) + var[2]


    params = Parameters()
    params.add('a', value=10)
    params.add('b', value=10)
    params.add('c', value=10)

    a, b, c = 2.5, 1.3, 0.8
    x = np.linspace(0, 4, 50)
    y = f([a, b, c], x)
    np.random.seed(2021)
    data = y + 0.15*np.random.normal(size=x.size)








.. GENERATED FROM PYTHON SOURCE LINES 45-46

Fit without analytic derivative:

.. GENERATED FROM PYTHON SOURCE LINES 46-50

.. code-block:: Python

    min1 = Minimizer(func, params, fcn_args=(x,), fcn_kws={'data': data})
    out1 = min1.leastsq()
    fit1 = func(out1.params, x)








.. GENERATED FROM PYTHON SOURCE LINES 51-52

Fit with analytic derivative:

.. GENERATED FROM PYTHON SOURCE LINES 52-56

.. code-block:: Python

    min2 = Minimizer(func, params, fcn_args=(x,), fcn_kws={'data': data})
    out2 = min2.leastsq(Dfun=dfunc, col_deriv=1)
    fit2 = func(out2.params, x)








.. GENERATED FROM PYTHON SOURCE LINES 57-59

Comparison of fit to exponential decay with/without analytical derivatives
to model = a*exp(-b*x) + c:

.. GENERATED FROM PYTHON SOURCE LINES 59-70

.. code-block:: Python

    print(f'"true" parameters are: a = {a:.3f}, b = {b:.3f}, c = {c:.3f}\n\n'
          '|=========================================\n'
          '| Statistic/Parameter | Without | With   |\n'
          '|-----------------------------------------\n'
          f'|  N Function Calls   | {out1.nfev:d}      | {out2.nfev:d}     |\n'
          f'|     Chi-square      | {out1.chisqr:.4f}  | {out2.chisqr:.4f} |\n'
          f"|         a           | {out1.params['a'].value:.4f}  | {out2.params['a'].value:.4f} |\n"
          f"|         b           | {out1.params['b'].value:.4f}  | {out2.params['b'].value:.4f} |\n"
          f"|         c           | {out1.params['c'].value:.4f}  | {out2.params['c'].value:.4f} |\n"
          '------------------------------------------')





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    "true" parameters are: a = 2.500, b = 1.300, c = 0.800

    |=========================================
    | Statistic/Parameter | Without | With   |
    |-----------------------------------------
    |  N Function Calls   | 39      | 12     |
    |     Chi-square      | 1.0920  | 1.0920 |
    |         a           | 2.5635  | 2.5635 |
    |         b           | 1.3585  | 1.3585 |
    |         c           | 0.8241  | 0.8241 |
    ------------------------------------------




.. GENERATED FROM PYTHON SOURCE LINES 71-73

and the best-fit to the synthetic data (with added noise) is the same for
both methods:

.. GENERATED FROM PYTHON SOURCE LINES 73-77

.. code-block:: Python

    plt.plot(x, data, 'o', label='data')
    plt.plot(x, fit1, label='with analytical derivative')
    plt.plot(x, fit2, '--', label='without analytical derivative')
    plt.legend()



.. image-sg:: /examples/images/sphx_glr_example_fit_with_derivfunc_001.png
   :alt: example fit with derivfunc
   :srcset: /examples/images/sphx_glr_example_fit_with_derivfunc_001.png, /examples/images/sphx_glr_example_fit_with_derivfunc_001_3_00x.png 3.00x
   :class: sphx-glr-single-img






.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 0.267 seconds)


.. _sphx_glr_download_examples_example_fit_with_derivfunc.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: example_fit_with_derivfunc.ipynb <example_fit_with_derivfunc.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: example_fit_with_derivfunc.py <example_fit_with_derivfunc.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: example_fit_with_derivfunc.zip <example_fit_with_derivfunc.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
