Testing a sinewave fit code provide by Chat AI with different conditions.
Original Posted Date: Nov 22, 2023
Presentation
Code
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 31 06:38:35 2023
@author: aleja
"""
#Testing out code form Bing Chat as starting point
#some modification added for clarity,and testing
# Generate some sample data
import numpy as np
import matplotlib.pyplot as plt
N = 20 # number of data points
amp = 2.0 # amplitude of the sinewave
freq = 0.2 # frequency of the sinewave
phase = np.pi / 4 # phase of the sinewave
offset = 1.0 # offset of the sinewave
noise = 0.01 # noise level reduce from chat was 0.5 to see lest noise at first
#number of cycle freq * max x
# Create the x and y values
x = np.linspace(0,10, N) #changing this to test how strong this leastsq fit is
y = amp * np.sin(2 * np.pi * freq * x + phase) + offset
y += noise * np.random.randn(N) # add some noise
# Plot the data
plt.scatter(x, y)
plt.xlabel("x-voltage")
plt.ylabel("y-optical detector")
plt.title("Sample data-fictional")
plt.show()
#Next Fit testing out chat code
# Fit a sinewave using least squares optimization
from scipy.optimize import leastsq
# Define the sinewave function
def sin_func(p, x):
A, f, p, c = p # unpack the parameters
return A * np.sin(2 * np.pi * f * x + p) + c
# Define the error function to minimize
def error_func(p, x, y):
return y - sin_func(p, x)
# Make some initial guesses for the parameters
p0 = [amp, freq, phase, offset]
# Optimize the parameters using least squares
p_opt, p_cov = leastsq(error_func, p0, args=(x,y))
X = np.linspace(0, 10, N*10) #new x for better visual of sinewave
# Predict the y values using the optimized parameters
y_pred = sin_func(p_opt,X)
# Plot the inputdata(blue dots) and predicted curves(red line)
plt.plot(x,y,"b.",label="data")
plt.plot(X,y_pred,"r-",label="prediction")
plt.xlabel("x-voltage")
plt.ylabel("y-optical detector")
plt.title("Sinewave fitting using least squares-not real product data")
plt.legend()
plt.show()
#added print for simulation info
print("Simulated Paramters:")
print(f"Number of Points: {N}")
print(f"Number of cycles {freq*np.max(x):.1f}")
print(f"Amplitude: {amp:.3f}")
print(f"Frequency: {freq:.3f}")
print(f"Phase: {phase:.3f}")
print(f"Offset: {offset:.3f}")
print(f"Noise: {noise:.3f}")
print("\n")
# Print the optimized parameters
print("Fit Parameters:")
print(f"Amplitude: {p_opt[0]:.3f}")
print(f"Frequency: {p_opt[1]:.3f}")
print(f"Phase: {p_opt[2]:.3f}")
print(f"Offset: {p_opt[3]:.3f}")
#added comments below not part of Chat info
#summary: Chat created code was workable, added print to compare sim and fit
#opinion: does a good job at fitting sinewave ...see presentation
#opinion: best when provide with more points over cycle (most know this)
#see blog presentation at www.testengineerresource.com
#Environment used: python 3.11.3 and worked in Spyder IDE 5.4.3 (conda), mathplotlib 3.7.1
#Environment info: I have plot show in own window (not in Spyder)
#Plots are not clear to allow for testing of overlap sinewave fit.
#getting version info
#import matplotlib
#print ('matplotlib: {}'.format (matplotlib.__version__))
Notes
- Presentation: Testing a Chat AI provide Sinewave fit code
- Programming Language used: Python 3.11.3 in Spyder5.4.3,Matplotlib 3.7.2
- Presentation app: Microsoft’s PowerPoint
- Helpful resource: Stackoverflow, Search Engines , Bing chat AI, and Python communities.
- Bing and “Bing Chat” are Microsoft’s product.
- Python, Tkinter, Matplotlib, Scipy are products of respective companies
- Presentation shown to spark ideas of use.
- This presentation is not connected to or endorsed by any company.
- Use at your own risk.
- Tags: Python, Python3.11, Tkinter , Matplotlib , Scipy, LeastSq, List, Sinewave fit , scipy (optimize)











