""" Given the set of points generated by
f(x) = 0.5 * cos(2 * x) + 2 * sin(0.5 * x) with some noise,
use Levenberg-Marquardt algorithm to find the model of the form
f(x) = a * cos(b * x) + b * sin(a * x) to fit all the points.
"""

import numpy as np
import scipy.optimize as scipy_opt

def sincos_func(x_data, a, b):
    """ Computes the function a * sin(b * x) + b * cos(a * x)
    Args:
        x_data : A Numpy array of input data
        a : Real-valued argument of the function
        b : Real-valued argument of the function

    Returns:
        A Numpy array of values of the function a * sin(b * x) + b * cos(a * x)
        evaluated at each x in xData
    """
    return a * np.cos(b * x_data) + b * np.sin(a * x_data)

def main():
    """ Main function to set up data points and calls Scipy curve fitting
    routine (whose underlying algorithm is Levenberg-Marquardt)
    """
    x_data = np.array([
        1.0, 1.5, -1.0, 2.0, 1.8, 2.5, -0.5, -0.8, -1.1, 2.2, 2.6, 2.8, -2.0,
        -2.2, -1.7, -1.4, 0.05, 0.0, 1.570796, -1.570796, 0.6, -0.6,
        1.67, 2.4, 0.1
    ])
    y_data = np.array([
        0.76, 0.860000, -1.18, 1.356, 1.118, 2.039, -0.224, -0.7934, -1.339,
        1.63, 2.1613, 2.35, -2.009, -1.936, -1.985, -1.759, 0.55, 0.5, 0.914,
        -1.9142, 0.77, -0.4, 1.0, 1.9, 0.59
    ])
    guess_abs = [[0.25, 1.5], [1.7, 3], [10, 5], [0.0, 3.0]]

    for guess_ab in guess_abs:
        ab, covariance = scipy_opt.curve_fit(
            sincos_func, x_data, y_data, guess_ab)
        print 'Intial guess: %s' % str(guess_ab)
        print 'LM results: %s' % str(ab)

if __name__ == "__main__":
    main()

Add scipy sin cos example
Add scipy sin cos example
