Ralf
Ralf

Reputation: 19

Fourier Series calculated in symfit

I am using the example code provided on https://symfit.readthedocs.io/en/master/examples/ex_fourier_series.html to calculate the Fourier Series of a given function. However, after I successfully installed the package symfit and begain to run the example code, I got an error: ImportError: cannot import name 'parameters' in the first line of the code from symfit import parameters, variables, sin, cos, Fit. Obviously'parameters' is an object in the package symfit, but I don't know why it told me the object 'parameters' couldn't be found. The sample code is as follow:

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

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

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

# Make step function data
xdata = np.linspace(-np.pi, np.pi)
ydata = np.zeros_like(xdata)
ydata[xdata > 0] = 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()

Thankyou for reading my question!

Upvotes: 0

Views: 285

Answers (1)

Ralf
Ralf

Reputation: 19

Oh, I can run this code now. So, I change my IDE from Spyder(included in Annaconda) to Pycharm, and it works. I just uninstall Annaconda and use Pycharm instead. I don't know what happen to the Annaconda, maybe some error occoured inside it that the installation of symfit is imcompleted.

Upvotes: 0

Related Questions