+def limited_quadratic(x, params):
+ """
+ Model the bump as:
+ flat region (off-surface)
+ quadratic region (in-contact)
+ flat region (high-voltage-rail)
+ Parameters:
+ x_contact (x value for the surface-contact kink)
+ y_contact (y value for the surface-contact kink)
+ slope (dy/dx at the surface-contact kink)
+ quad (d**2 y / dx**2, allow decreasing sensitivity with increased x)
+ """
+ high_voltage_rail = 2**16 - 1 # bits
+ x_contact,y_contact,slope,quad = params
+ y = slope*(x-x_contact) + quad*(x-x_contact)**2+ y_contact
+ y = numpy.clip(y, y_contact, high_voltage_rail)
+ return y
+
+def limited_quadratic_param_guess(x, y) :
+ """
+ Guess rough parameters for a limited_quadratic model. Assumes the
+ bump approaches (raising the deflection as it does so) first.
+ Retracting after the approach is optional. Approximates the contact
+ position and an on-surface (high) position by finding first crossings
+ of thresholds 0.3 and 0.7 of the y value's total range. Not the
+ most efficient algorithm, but it seems fairly robust.
+ """
+ y_contact = float(y.min())
+ y_max = float(y.max())
+ i = 0
+ y_low = y_contact + 0.3 * (y_max-y_contact)
+ y_high = y_contact + 0.7 * (y_max-y_contact)
+ while y[i] < y_low :
+ i += 1
+ i_low = i
+ while y[i] < y_high :
+ i += 1
+ i_high = i
+ x_contact = float(x[i_low])
+ x_high = float(x[i_high])
+ slope = (y_high - y_contact) / (x_high - x_contact)
+ quad = 0
+ return (x_contact, y_contact, slope, quad)
+
+def limited_quadratic_sensitivity(params):
+ """
+ Return the estimated sensitivity to small deflections according to
+ limited_quadratic fit parameters.
+ """
+ slope = params[2]
+ return slope
+
+@splittableKwargsFunction()
+def bump_fit(zpiezo_output_bits, deflection_input_bits,
+ paramGuesser=limited_quadratic_param_guess,
+ model=limited_quadratic,
+ sensitivity_from_fit_params=limited_quadratic_sensitivity,
+ plotVerbose=True) :
+ x = zpiezo_output_bits
+ y = deflection_input_bits
+ def residual(p, y, x) :
+ return model(x, p) - y
+ paramGuess = paramGuesser(x, y)
+ p,cov,info,mesg,ier = \
+ scipy.optimize.leastsq(residual, paramGuess, args=(y, x),
+ full_output=True, maxfev=int(10e3))
+ if config.TEXT_VERBOSE :
+ print "Fitted params:",p
+ print "Covariance mx:",cov
+ print "Info:", info
+ print "mesg:", mesg
+ if ier == 1 :
+ print "Solution converged"
+ else :
+ print "Solution did not converge"
+ if plotVerbose or config.PYLAB_VERBOSE :
+ yguess = model(x, paramGuess)
+ #yguess = None # Don't print the guess, since I'm convinced it's ok ;).
+ yfit = model(x, p)
+ bump_plot(data={"Z piezo output":x, "Deflection input":y},
+ yguess=yguess, yfit=yfit, plotVerbose=plotVerbose)
+ return sensitivity_from_fit_params(p)
+