import numpy as np from scipy.optimize import leastsq def hfitoff(data, xdeg): """ Harmonic fit with offset """ start, end = min(xdeg), max(xdeg) guess_amplitude = 2 ** 0.5 * np.std(data) guess_phase = 0 guess_offset = np.mean(data) xrad = xdeg / 180 * np.pi optimize_func = lambda x: x[0] * np.sin(xrad + x[1]) + x[2] - data fit_amplitude, fit_phase, fit_offset = leastsq(optimize_func, [guess_amplitude, guess_phase, guess_offset])[0] fit_xdeg = np.linspace(start, end, 100) fit_data = fit_amplitude * np.sin(fit_xdeg / 180 * np.pi + fit_phase) + fit_offset ph_crest = 90 - fit_phase / np.pi * 180 xdeg_max = xdeg[np.argmax(data)] if start <= ph_crest <= end: return (fit_amplitude, fit_phase, fit_offset, True, ph_crest, fit_xdeg, fit_data) else: return (fit_amplitude, fit_phase, fit_offset, False, xdeg_max, fit_xdeg, fit_data)