abdullatif
abdullatif

Reputation: 90

curve fitting different in Python than Matlab

I have a code in Matlab that I want to convert to python. In the Matlab code, I'm using the curve fitting toolbox to fit some data to the Fourier series of order 3. Here is how I did it in Matlab:

ft= fittype('fourier3');                                
myfit = fit(x,y,ft)
figure(20)
plot(y)
hold
figure(20)
plot(myfit)

And here is the plot of the data

enter image description here

So, to convert it to Python, I searched for equivalent library to the curve fitting toolbox, and found a library named 'symfit' which serves the same purpose. I looked the documentation and found example that can help, so I used the example as in the description with my data as follows:

from symfit import parameters, variables, sin, cos, Fit
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

def fourier_series(x, f, n=0):
    """
    Returns a symbolic fourier series of order `n`.

    :param n: Order of the fourier series.
    :param x: Independent variable
    :param f: Frequency of the fourier series
    """
    # Make the parameter objects for all the terms
    a0, *cos_a = parameters(','.join(['a{}'.format(i) for i in range(0, n + 1)]))
    sin_b = parameters(','.join(['b{}'.format(i) for i in range(1, n + 1)]))
    # Construct the series
    series = a0 + sum(ai * cos(i * f * x) + bi * sin(i * f * x)
                     for i, (ai, bi) in enumerate(zip(cos_a, sin_b), start=1))
    return series

T = pd.read_excel('data.xls')
A = pd.DataFrame(T)

x, y = variables('x, y')
w, = parameters('w')
model_dict = {y: fourier_series(x, f=w, n=3)}
print(model_dict)

xdata = np.array(A.iloc[:, 0])
ydata = np.array(A.iloc[:, 1])

# Define a Fit object for this model and data
fit = Fit(model_dict, x=xdata, y=ydata)
fit_result = fit.execute()
print(fit_result)

# Plot the result
plt.plot(xdata, ydata)
plt.plot(xdata, fit.model(x=xdata, **fit_result.params).y, ls=':')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

But when running the code, here is the plot I get:

enter image description here

I don't know why the fitted data is a straight line. Can anyone help with that problem? I don't know whether I used the wrong algorithm or I'm plotting the data incorrectly.

Edit: Here is the data file for those who would like to try: https://docs.google.com/spreadsheets/d/18lL1iMZ3kdaqUUtRDLNRK4A3uCPzOrXt/edit?usp=sharing&ouid=112684448221465330517&rtpof=true&sd=true

Upvotes: 1

Views: 731

Answers (0)

Related Questions