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

.. only:: html

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

        Click :ref:`here <sphx_glr_download_examples_nodoc_example_emcee_Model_interface.py>`
        to download the full example code

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

.. _sphx_glr_examples_nodoc_example_emcee_Model_interface.py:


Emcee and the Model Interface
=============================

.. GENERATED FROM PYTHON SOURCE LINES 6-13

.. code-block:: default

    import corner
    import matplotlib.pyplot as plt
    import numpy as np

    import lmfit



.. GENERATED FROM PYTHON SOURCE LINES 14-15

Set up a double-exponential function and create a Model:

.. GENERATED FROM PYTHON SOURCE LINES 15-21

.. code-block:: default

    def double_exp(x, a1, t1, a2, t2):
        return a1*np.exp(-x/t1) + a2*np.exp(-(x-0.1) / t2)


    model = lmfit.Model(double_exp)


.. GENERATED FROM PYTHON SOURCE LINES 22-23

Generate some fake data from the model with added noise:

.. GENERATED FROM PYTHON SOURCE LINES 23-28

.. code-block:: default

    truths = (3.0, 2.0, -5.0, 10.0)
    x = np.linspace(1, 10, 250)
    np.random.seed(0)
    y = double_exp(x, *truths)+0.1*np.random.randn(x.size)


.. GENERATED FROM PYTHON SOURCE LINES 29-30

Create model parameters and give them initial values:

.. GENERATED FROM PYTHON SOURCE LINES 30-32

.. code-block:: default

    p = model.make_params(a1=4, t1=3, a2=4, t2=3)


.. GENERATED FROM PYTHON SOURCE LINES 33-34

Fit the model using a traditional minimizer, and show the output:

.. GENERATED FROM PYTHON SOURCE LINES 34-39

.. code-block:: default

    result = model.fit(data=y, params=p, x=x, method='Nelder', nan_policy='omit')

    lmfit.report_fit(result)
    result.plot()


.. GENERATED FROM PYTHON SOURCE LINES 40-45

Calculate parameter covariance using ``emcee``:

 - start the walkers out at the best-fit values
 - set ``is_weighted`` to ``False`` to estimate the noise weights
 - set some sensible priors on the uncertainty to keep the MCMC in check

.. GENERATED FROM PYTHON SOURCE LINES 45-51

.. code-block:: default


    emcee_kws = dict(steps=5000, burn=500, thin=20, is_weighted=False,
                     progress=False)
    emcee_params = result.params.copy()
    emcee_params.add('__lnsigma', value=np.log(0.1), min=np.log(0.001), max=np.log(2.0))


.. GENERATED FROM PYTHON SOURCE LINES 52-53

run the MCMC algorithm and show the results:

.. GENERATED FROM PYTHON SOURCE LINES 53-56

.. code-block:: default

    result_emcee = model.fit(data=y, x=x, params=emcee_params, method='emcee',
                             nan_policy='omit', fit_kws=emcee_kws)


.. GENERATED FROM PYTHON SOURCE LINES 57-59

.. code-block:: default

    lmfit.report_fit(result_emcee)


.. GENERATED FROM PYTHON SOURCE LINES 60-64

.. code-block:: default

    result_emcee.plot_fit()
    plt.plot(x, model.eval(params=result.params, x=x), '--', label='Nelder')
    plt.legend()


.. GENERATED FROM PYTHON SOURCE LINES 65-66

Check the acceptance fraction to see whether ``emcee`` performed well:

.. GENERATED FROM PYTHON SOURCE LINES 66-70

.. code-block:: default

    plt.plot(result_emcee.acceptance_fraction, 'o')
    plt.xlabel('walker')
    plt.ylabel('acceptance fraction')


.. GENERATED FROM PYTHON SOURCE LINES 71-72

Try to compute the autocorrelation time:

.. GENERATED FROM PYTHON SOURCE LINES 72-78

.. code-block:: default

    if hasattr(result_emcee, "acor"):
        print("Autocorrelation time for the parameters:")
        print("----------------------------------------")
        for i, p in enumerate(result.params):
            print(f'{p} = {result_emcee.acor[i]:.3f}')


.. GENERATED FROM PYTHON SOURCE LINES 79-80

Plot the parameter covariances returned by ``emcee`` using ``corner``:

.. GENERATED FROM PYTHON SOURCE LINES 80-83

.. code-block:: default

    emcee_corner = corner.corner(result_emcee.flatchain, labels=result_emcee.var_names,
                                 truths=list(result_emcee.params.valuesdict().values()))


.. GENERATED FROM PYTHON SOURCE LINES 84-88

.. code-block:: default

    print("\nmedian of posterior probability distribution")
    print('--------------------------------------------')
    lmfit.report_fit(result_emcee.params)


.. GENERATED FROM PYTHON SOURCE LINES 89-90

Find the maximum likelihood solution:

.. GENERATED FROM PYTHON SOURCE LINES 90-101

.. code-block:: default

    highest_prob = np.argmax(result_emcee.lnprob)
    hp_loc = np.unravel_index(highest_prob, result_emcee.lnprob.shape)
    mle_soln = result_emcee.chain[hp_loc]
    print("\nMaximum Likelihood Estimation (MLE):")
    print('----------------------------------')
    for ix, param in enumerate(emcee_params):
        print(f"{param}: {mle_soln[ix]:.3f}")

    quantiles = np.percentile(result_emcee.flatchain['t1'], [2.28, 15.9, 50, 84.2, 97.7])
    print(f"\n\n1 sigma spread = {0.5 * (quantiles[3] - quantiles[1]):.3f}")
    print(f"2 sigma spread = {0.5 * (quantiles[4] - quantiles[0]):.3f}")


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

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


.. _sphx_glr_download_examples_nodoc_example_emcee_Model_interface.py:


.. only :: html

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



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

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



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

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


.. only:: html

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

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