fourier¶
- mdhelper.fit.fourier.fourier(x: ndarray, omega: float, a0: float, *args: float) ndarray [source]¶
General Fourier series model.
\[y=a_0+\sum_{k=1}^na_i\cos{(k\omega x)}+b_i\sin{(k\omega x)}\]- Parameters:
- xnumpy.ndarray
\(x\)-values.
- omegafloat
Fundamental frequency \(\omega\) of the signal.
- a0float
Constant (intercept) term \(a_0\) for the \(k=0\) cosine term.
- *argsfloat
Fitting parameters for the Fourier series term(s), ordered as \(a_1,\,b_1,\,a_2,\,b_2,\ldots,\,a_n,\,b_n\), where \(n\) is the number of terms in the model. As such, the number of variable positional arguments must be even.
- Returns:
- fitnumpy.ndarray
Fitted \(y\)-values.
Examples
Generate \(x\)- and \(y\)-values (with error), and then use
scipy.optimize.curve_fit()
to fit coefficients for a one-term Fourier series model.>>> from scipy import optimize >>> rng = np.random.default_rng() >>> x = np.linspace(0, 5, 20) >>> err = (2 * rng.random(x.shape) - 1) / 10 >>> y = 1 + 2 * np.cos(x / 2) + 3 * np.sin(x / 2) + err >>> pk, _ = optimize.curve_fit( lambda x, omega, a0, a1, b1: fourier(x, omega, a0, a1, b1), x, y ) >>> pk array([0.51185734, 1.15090712, 1.87471839, 2.87117784])
Evaluate the fitted \(y\)-values using the coefficients.
>>> fourier(x, *pk) array([3.0256255 , 3.39422104, 3.72217562, 4.00354785, 4.23324026, 4.40709163, 4.52195238, 4.57574164, 4.56748494, 4.49733187, 4.36655334, 4.1775186 , 3.9336523 , 3.63937245, 3.30001035, 2.92171405, 2.51133696, 2.07631367, 1.62452525, 1.16415655])