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

.. only:: html

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

        :ref:`Go to the end <sphx_glr_download_.._.._docs_source__gallery_curve_fitting.py>`
        to download the full example code.

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

.. _sphx_glr_.._.._docs_source__gallery_curve_fitting.py:


.. _sphx_glr__gallery_curve_fitting.py:

Curve fitting
==================================

This example shows how to use pysolve-gn package.

We will fit an exponential curve to noisy data.

.. GENERATED FROM PYTHON SOURCE LINES 13-26

Define the model function
--------------------------

Lets consider the following exponential model.

.. math::

    y = a \cdot e^{b x}

We generate a small and noisy dataset. In this situation, the fitted
parameters can deviate significantly from the true parameters.

The parameters :math:`a` and :math:`b` will be estimated from the noisy data.

.. GENERATED FROM PYTHON SOURCE LINES 26-51

.. code-block:: Python



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

    np.random.seed(0)


    def model(params, x):
        a, b = params
        return a * np.exp(b * x)


    n_points = 100
    x_data = np.linspace(0, 3, n_points)

    true_params = np.array([2.5, 0.5])

    y_true = model(true_params, x_data)

    # Add a relatively strong noise to the observations.
    y_data = y_true + 1.0 * np.random.normal(size=y_true.shape)









.. GENERATED FROM PYTHON SOURCE LINES 52-78

Create the data term
--------------------

The data term represents the residuals between the observations and
the model predictions.

.. math::

    r_j(\mathbf{p}) =
    a e^{b x_j} - y_j

The Jacobian is:

.. math::

    \frac{\partial r_j}{\partial a} = e^{b x_j}

.. math::

    \frac{\partial r_j}{\partial b}
    = a x_j e^{b x_j}

.. seealso::

    The class :class:`pysolvegn.Term` to store the residual and jacobian functions.


.. GENERATED FROM PYTHON SOURCE LINES 78-103

.. code-block:: Python



    def residual_function(params):
        return model(params, x_data) - y_data


    def jacobian_function(params):
        a, b = params

        J = np.zeros((len(x_data), len(params)))

        J[:, 0] = np.exp(b * x_data)
        J[:, 1] = a * x_data * np.exp(b * x_data)

        return J


    data_term = pysolvegn.Term.from_rJ(
        residual_func=residual_function,
        jacobian_func=jacobian_function,
        loss="linear",
        weight=1.0,
    )









.. GENERATED FROM PYTHON SOURCE LINES 104-115

Performing optimization
---------------------------

We solve the problem using only the :func:`pysolvegn.solve` function.
This function takes the data term, an initialisation and convergence criteria.

The function returns a :class:`pysolvegn.SolveResult` object containing the
optimized parameters (``result.parameters``) and information about the
optimization: ``result.success`` indicates whether a convergence criterion
was satisfied, and ``result.message`` describes why the optimization stopped.


.. GENERATED FROM PYTHON SOURCE LINES 115-129

.. code-block:: Python


    initial_params = np.array([1.0, 1.0])

    result = pysolvegn.solve(
        terms=data_term,
        p0=initial_params,
        max_iteration=100,
        xtol=1e-8,
        ftol=1e-8,
        verbosity=2,
    )

    optimized_parameters = result.parameters





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

 .. code-block:: none


    Individual costs [rJ term]: C_i = 0.5 * ρ(||r_i||^2) 
    Cost: C = sum(w_i * C_i) 
    Step norm: ||Δp|| 
    Optimality: ||g|| 

    Iteration  Total time (s)      Cost C            ΔC           ||Δp||_2         ||g||_∞    
        0         7.804e-05       4.287e+02                                       5.101e+03   
        1         2.049e-04       9.622e+01      -3.325e+02       8.856e-01       9.936e+02   
        2         2.842e-04       5.346e+01      -4.277e+01       6.382e-01       3.246e+02   
        3         3.518e-04       5.072e+01      -2.738e+00       4.633e-02       4.134e+00   
        4         4.358e-04       5.072e+01      -6.618e-04       2.843e-03       4.314e-02   
        5         5.045e-04       5.072e+01      -3.914e-07       1.021e-04       2.567e-03   
    [ftol] Convergence achieved: 0 <= F_previous - F < ftol * F with ftol = 1e-08.




.. GENERATED FROM PYTHON SOURCE LINES 130-132

Display the fitted parameters
------------------------------

.. GENERATED FROM PYTHON SOURCE LINES 132-181

.. code-block:: Python


    print("Success:", result.success)
    print("Message:", result.message)
    print("Number of iterations:", result.n_iterations)
    print("Final cost:", result.cost)

    print("\nTrue parameters:")
    print(true_params)

    print("\nEstimated parameters:")
    print(optimized_parameters)

    x_plot = np.linspace(0, 3, 300)
    y_plot = model(optimized_parameters, x_plot)
    y_true_plot = model(true_params, x_plot)

    plt.figure(figsize=(10, 6))

    plt.scatter(
        x_data,
        y_data,
        label="Data Points",
        color="red",
        s=35,
    )

    plt.plot(
        x_plot,
        y_true_plot,
        label="True Curve",
        color="blue",
        linewidth=2,
    )

    plt.plot(
        x_plot,
        y_plot,
        label="Optimized Curve",
        color="orange",
        linestyle="--",
        linewidth=2,
    )

    plt.title("Curve Fitting")
    plt.xlabel("x")
    plt.ylabel("y")
    plt.legend()
    plt.grid()

    plt.show()


.. image-sg:: /_gallery/images/sphx_glr_curve_fitting_001.png
   :alt: Curve Fitting
   :srcset: /_gallery/images/sphx_glr_curve_fitting_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    Success: True
    Message: [ftol] Convergence achieved: 0 <= F_previous - F < ftol * F with ftol = 1e-08.
    Number of iterations: 5
    Final cost: 50.716550445680085

    True parameters:
    [2.5 0.5]

    Estimated parameters:
    [2.45861374 0.51137177]





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

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


.. _sphx_glr_download_.._.._docs_source__gallery_curve_fitting.py:

.. only:: html

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

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

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

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

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

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

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


.. only:: html

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

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