Convert calibcant to the new, nestable h5config.
[calibcant.git] / calibcant / bump_analyze.py
1 # calibcant - tools for thermally calibrating AFM cantilevers
2 #
3 # Copyright (C) 2008-2011 W. Trevor King <wking@drexel.edu>
4 #
5 # This file is part of calibcant.
6 #
7 # calibcant is free software: you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation, either
10 # version 3 of the License, or (at your option) any later version.
11 #
12 # calibcant is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with calibcant.  If not, see
19 # <http://www.gnu.org/licenses/>.
20
21 """Surface bump analysis (measures photodiode sensitivity).
22
23 Separate the more general `bump_analyze()` from the other `bump_*()`
24 functions in calibcant.
25
26 The relevant physical quantities are:
27
28 * `Vzp_out`  Output z-piezo voltage (what we generate)
29 * `Vzp`      Applied z-piezo voltage (after external amplification)
30 * `Zp`       The z-piezo position
31 * `Zcant`    The cantilever vertical deflection
32 * `Vphoto`   The photodiode vertical deflection voltage (what we measure)
33
34 Which are related by the parameters:
35
36 * `zp_gain`           Vzp_out / Vzp
37 * `zp_sensitivity`    Zp / Vzp
38 * `photo_sensitivity` Vphoto / Zcant
39
40 `photo_sensitivity` is measured by bumping the cantilever against the
41 surface, where `Zp = Zcant` (see `calibrate.bump_acquire()`).  The
42 measured slope `Vphoto/Vout` is converted to `photo_sensitivity` with
43 `bump_analyze()`.
44
45 >>> import os
46 >>> from pprint import pprint
47 >>> import tempfile
48 >>> import numpy
49 >>> from h5config.storage.hdf5 import pprint_HDF5
50 >>> from pypiezo.config import ChannelConfig, AxisConfig
51 >>> from .config import BumpConfig
52
53 >>> fd,filename = tempfile.mkstemp(suffix='.h5', prefix='calibcant-')
54 >>> os.close(fd)
55
56 >>> bump_config = BumpConfig()
57 >>> z_channel_config = ChannelConfig()
58 >>> z_channel_config['name'] = 'z'
59 >>> z_channel_config['maxdata'] = 200
60 >>> z_channel_config['conversion-coefficients'] = (0,1)
61 >>> z_channel_config['conversion-origin'] = 0
62 >>> z_axis_config = AxisConfig()
63 >>> z_axis_config['channel'] = z_channel_config
64 >>> deflection_channel_config = ChannelConfig()
65 >>> deflection_channel_config['name'] = 'deflection'
66 >>> deflection_channel_config['maxdata'] = 200
67 >>> deflection_channel_config['conversion-coefficients'] = (0,1)
68 >>> deflection_channel_config['conversion-origin'] = 0
69
70 >>> raw_bump = {
71 ...     'z': numpy.arange(100, dtype=numpy.uint16),
72 ...     'deflection': numpy.arange(100, dtype=numpy.uint16),
73 ...     }
74 >>> raw_bump['deflection'][:50] = 50
75 >>> processed_bump = bump_analyze(
76 ...     raw_bump, bump_config, z_axis_config, deflection_channel_config)
77 >>> bump_plot(data=raw_bump)  # TODO: convert to V and m
78 >>> bump_save(filename=filename, group='/bump/', raw_bump=raw_bump,
79 ...     bump_config=bump_config, z_axis_config=z_axis_config,
80 ...     deflection_channel_config=deflection_channel_config,
81 ...     processed_bump=processed_bump)
82
83 >>> pprint_HDF5(filename)  # doctest: +ELLIPSIS, +REPORT_UDIFF
84 /
85   /bump
86     /bump/config
87       /bump/config/bump
88         <HDF5 dataset "far-steps": shape (), type "<i4">
89           200
90         <HDF5 dataset "model": shape (), type "|S9">
91           quadratic
92         <HDF5 dataset "push-depth": shape (), type "<f8">
93           2e-07
94         <HDF5 dataset "push-speed": shape (), type "<f8">
95           1e-06
96         <HDF5 dataset "samples": shape (), type "<i4">
97           1024
98         <HDF5 dataset "setpoint": shape (), type "<f8">
99           2.0
100       /bump/config/deflection
101         /bump/config/deflection/channel
102           <HDF5 dataset "channel": shape (), type "<i4">
103             0
104           <HDF5 dataset "conversion-coefficients": shape (2,), type "<i4">
105             [0 1]
106           <HDF5 dataset "conversion-origin": shape (), type "<i4">
107             0
108           <HDF5 dataset "device": shape (), type "|S12">
109             /dev/comedi0
110           <HDF5 dataset "inverse-conversion-coefficients": shape (), type "|S1">
111 <BLANKLINE>
112           <HDF5 dataset "inverse-conversion-origin": shape (), type "<f8">
113             1.0
114           <HDF5 dataset "maxdata": shape (), type "<i4">
115             200
116           <HDF5 dataset "name": shape (), type "|S10">
117             deflection
118           <HDF5 dataset "range": shape (), type "<i4">
119             1
120           <HDF5 dataset "subdevice": shape (), type "<i4">
121             -1
122       /bump/config/z
123         /bump/config/z/axis
124           /bump/config/z/axis/channel
125             <HDF5 dataset "channel": shape (), type "<i4">
126               0
127             <HDF5 dataset "conversion-coefficients": shape (2,), type "<i4">
128               [0 1]
129             <HDF5 dataset "conversion-origin": shape (), type "<i4">
130               0
131             <HDF5 dataset "device": shape (), type "|S12">
132               /dev/comedi0
133             <HDF5 dataset "inverse-conversion-coefficients": shape (), type "|S1">
134 <BLANKLINE>
135             <HDF5 dataset "inverse-conversion-origin": shape (), type "<f8">
136               1.0
137             <HDF5 dataset "maxdata": shape (), type "<i4">
138               200
139             <HDF5 dataset "name": shape (), type "|S1">
140               z
141             <HDF5 dataset "range": shape (), type "<i4">
142               1
143             <HDF5 dataset "subdevice": shape (), type "<i4">
144               -1
145           <HDF5 dataset "gain": shape (), type "<f8">
146             1.0
147           <HDF5 dataset "maximum": shape (), type "|S4">
148             None
149           <HDF5 dataset "minimum": shape (), type "|S4">
150             None
151           <HDF5 dataset "monitor": shape (), type "|S1">
152 <BLANKLINE>
153           <HDF5 dataset "sensitivity": shape (), type "<f8">
154             1.0
155     <HDF5 dataset "processed": shape (), type "<f8">
156       1.00...
157     /bump/raw
158       <HDF5 dataset "deflection": shape (100,), type "<u2">
159         [50 50 ... 50 51 52 ... 97 98 99]
160       <HDF5 dataset "z": shape (100,), type "<u2">
161         [ 0  1  2  3  ... 97 98 99]
162
163 >>> (raw_bump,bump_config,z_axis_config,deflection_channel_config,
164 ...     processed_bump) = bump_load(filename=filename, group='/bump/')
165
166 >>> pprint(raw_bump)  # doctest: +ELLIPSIS
167 {'deflection': array([50, 50, ... 51, 52, 53, ..., 97, 98, 99], dtype=uint16),
168  'z': array([ 0,  1,  2,  ..., 97, 98, 99], dtype=uint16)}
169 >>> processed_bump  # doctest: +ELLIPSIS
170 1.00...
171
172 >>> os.remove(filename)
173 """
174
175 import h5py as _h5py
176 import numpy as _numpy
177 from scipy.optimize import leastsq as _leastsq
178
179 try:
180     import matplotlib as _matplotlib
181     import matplotlib.pyplot as _matplotlib_pyplot
182     import time as _time  # for timestamping lines on plots
183 except (ImportError, RuntimeError), e:
184     _matplotlib = None
185     _matplotlib_import_error = e
186
187 from h5config.storage.hdf5 import HDF5_Storage as _HDF5_Storage
188 from h5config.storage.hdf5 import h5_create_group as _h5_create_group
189 from pypiezo.base import convert_bits_to_volts as _convert_bits_to_volts
190 from pypiezo.base import convert_bits_to_meters as _convert_bits_to_meters
191 from pypiezo.config import ChannelConfig as _ChannelConfig
192 from pypiezo.config import AxisConfig as _AxisConfig
193
194 from . import LOG as _LOG
195 from . import package_config as _package_config
196 from .config import Linear as _Linear
197 from .config import Quadratic as _Quadratic
198 from .config import BumpConfig as _BumpConfig
199
200
201 def bump_analyze(data, bump_config, z_axis_config,
202                  deflection_channel_config, plot=False):
203     """Return the slope of the bump.
204
205     Inputs:
206       data              dictionary of data in DAC/ADC bits
207       bump_config       `.config._BumpConfig` instance
208       z_axis_config     z `pypiezo.config.AxisConfig` instance
209       deflection_channel_config
210                         deflection `pypiezo.config.ChannelConfig` instance
211       plot              boolean overriding matplotlib config setting.
212     Returns:
213       photo_sensitivity (Vphoto/Zcant) in Volts/m
214
215     Checks for strong correlation (r-value) and low randomness chance
216     (p-value).
217     """
218     z = _convert_bits_to_meters(z_axis_config, data['z'])
219     deflection = _convert_bits_to_volts(
220         deflection_channel_config, data['deflection'])
221     high_voltage_rail = _convert_bits_to_volts(
222         deflection_channel_config, deflection_channel_config['maxdata'])
223     if bump_config['model'] == _Linear:
224         kwargs = {
225             'param_guesser': limited_linear_param_guess,
226             'model': limited_linear,
227             'sensitivity_from_fit_params': limited_linear_sensitivity,
228             }
229     else:  # _Quadratic
230         kwargs = {
231             'param_guesser': limited_quadratic_param_guess,
232             'model': limited_quadratic,
233             'sensitivity_from_fit_params': limited_quadratic_sensitivity,
234             }
235     photo_sensitivity = bump_fit(
236         z, deflection, high_voltage_rail=high_voltage_rail, plot=plot,
237         **kwargs)
238     return photo_sensitivity
239
240 def limited_linear(x, params, high_voltage_rail):
241     """
242     Model the bump as:
243       flat region (off-surface)
244       linear region (in-contact)
245       flat region (high-voltage-rail)
246     Parameters:
247       x_contact (x value for the surface-contact kink)
248       y_contact (y value for the surface-contact kink)
249       slope (dy/dx at the surface-contact kink)
250     """
251     x_contact,y_contact,slope = params
252     off_surface_mask = x <= x_contact
253     on_surface_mask = x > x_contact
254     y = (off_surface_mask * y_contact +
255          on_surface_mask * (y_contact + slope*(x-x_contact)))
256     y = _numpy.clip(y, y_contact, high_voltage_rail)
257     return y
258
259 def limited_linear_param_guess(x, y):
260     """
261     Guess rough parameters for a limited_linear model.  Assumes the
262     bump approaches (raising the deflection as it does so) first.
263     Retracting after the approach is optional.  Approximates the contact
264     position and an on-surface (high) position by finding first crossings
265     of thresholds 0.3 and 0.7 of the y value's total range.  Not the
266     most efficient algorithm, but it seems fairly robust.
267     """
268     y_contact = float(y.min())
269     y_max = float(y.max())
270     i = 0
271     y_low  = y_contact + 0.3 * (y_max-y_contact)
272     y_high = y_contact + 0.7 * (y_max-y_contact)
273     while y[i] < y_low:
274         i += 1
275     i_low = i
276     while y[i] < y_high:
277         i += 1
278     i_high = i
279     x_contact = float(x[i_low])
280     x_high = float(x[i_high])
281     slope = (y_high - y_contact) / (x_high - x_contact)
282     return (x_contact, y_contact, slope)
283
284 def limited_linear_sensitivity(params):
285     """
286     Return the estimated sensitivity to small deflections according to
287     limited_linear fit parameters.
288     """
289     slope = params[2]
290     return slope
291
292 def limited_quadratic(x, params, high_voltage_rail):
293     """
294     Model the bump as:
295       flat region (off-surface)
296       quadratic region (in-contact)
297       flat region (high-voltage-rail)
298     Parameters:
299       x_contact (x value for the surface-contact kink)
300       y_contact (y value for the surface-contact kink)
301       slope (dy/dx at the surface-contact kink)
302       quad (d**2 y / dx**2, allow decreasing sensitivity with increased x)
303     """
304     x_contact,y_contact,slope,quad = params
305     off_surface_mask = x <= x_contact
306     on_surface_mask = x > x_contact
307     y = (off_surface_mask * y_contact +
308          on_surface_mask * (
309             y_contact + slope*(x-x_contact) + quad*(x-x_contact)**2))
310     y = _numpy.clip(y, y_contact, high_voltage_rail)
311     return y
312
313 def limited_quadratic_param_guess(x, y):
314     """
315     Guess rough parameters for a limited_quadratic model.  Assumes the
316     bump approaches (raising the deflection as it does so) first.
317     Retracting after the approach is optional.  Approximates the contact
318     position and an on-surface (high) position by finding first crossings
319     of thresholds 0.3 and 0.7 of the y value's total range.  Not the
320     most efficient algorithm, but it seems fairly robust.
321     """
322     x_contact,y_contact,linear_slope = limited_linear_param_guess(x,y)
323     contact_depth = x.max() - x_contact
324     slope = linear_slope / 2
325     quad = slope / contact_depth
326     # The above slope and quad were chosen so
327     #   x = contact_depth
328     #   x*slope + x**2 * slope == x * linear_slope
329     return (x_contact, y_contact, slope, quad)
330
331 def limited_quadratic_sensitivity(params):
332     """
333     Return the estimated sensitivity to small deflections according to
334     limited_quadratic fit parameters.
335     """
336     slope = params[2]
337     return slope
338
339 def bump_fit(z, deflection, high_voltage_rail,
340              param_guesser=limited_quadratic_param_guess,
341              model=limited_quadratic,
342              sensitivity_from_fit_params=limited_quadratic_sensitivity,
343              plot=False):
344     """Fit a aurface bump and return the photodiode sensitivitiy.
345
346     Parameters:
347       z              piezo position in meters
348       deflection     photodiode deflection in volts
349       param_guesser  function that guesses initial model parameters
350       model          parametric model of deflection vs. z
351       sensitivity_from_fit_params  given fit params, return the sensitivity
352       plot              boolean overriding matplotlib config setting.
353     Returns:
354       photodiode_sensitivity  photodiode volts per piezo meter
355     """
356     _LOG.debug('fit bump data with model %s' % model)
357     def residual(p, deflection, z):
358         return model(z, p, high_voltage_rail=high_voltage_rail) - deflection
359     param_guess = param_guesser(z, deflection)
360     p,cov,info,mesg,ier = _leastsq(
361         residual, param_guess, args=(deflection, z), full_output=True,
362         maxfev=int(10e3))
363     _LOG.debug('fitted params: %s' % p)
364     _LOG.debug('covariance matrix: %s' % cov)
365     #_LOG.debug('info: %s' % info)
366     _LOG.debug('message: %s' % mesg)
367     if ier == 1:
368         _LOG.debug('solution converged')
369     else:
370         _LOG.debug('solution did not converge')
371     if plot or _package_config['matplotlib'] or True:
372         yguess = model(z, param_guess, high_voltage_rail=high_voltage_rail)
373         yfit = model(z, p, high_voltage_rail=high_voltage_rail)
374         bump_plot({'z': z, 'deflection': deflection}, yguess=yguess, yfit=yfit)
375     return sensitivity_from_fit_params(p)
376
377 def bump_save(filename, group='/', raw_bump=None, bump_config=None,
378               z_axis_config=None, deflection_channel_config=None,
379               processed_bump=None):
380     with _h5py.File(filename, 'a') as f:
381         cwg = _h5_create_group(f, group)
382         if raw_bump is not None:
383             for k in ['z', 'deflection']:
384                 try:
385                     del cwg['raw/{}'.format(k)]
386                 except KeyError:
387                     pass
388             cwg['raw/z'] = raw_bump['z']
389             cwg['raw/deflection'] = raw_bump['deflection']
390         storage = _HDF5_Storage()
391         for config,key in [(bump_config, 'config/bump'),
392                            (z_axis_config, 'config/z/axis'),
393                            (deflection_channel_config,
394                             'config/deflection/channel')]:
395             if config is None:
396                 continue
397             config_cwg = _h5_create_group(cwg, key)
398             storage.save(config=config, group=config_cwg)
399         if processed_bump is not None:
400             try:
401                 del cwg['processed']
402             except KeyError:
403                 pass
404             cwg['processed'] = processed_bump
405
406 def bump_load(filename, group='/'):
407     assert group.endswith('/')
408     raw_bump = processed_bump = None
409     configs = []
410     with _h5py.File(filename, 'a') as f:
411         try:
412             raw_bump = {
413                 'z': f[group+'raw/z'][...],
414                 'deflection': f[group+'raw/deflection'][...],
415                 }
416         except KeyError:
417             pass
418         for Config,key in [(_BumpConfig, 'config/bump'),
419                            (_AxisConfig, 'config/z/axis'),
420                            (_ChannelConfig, 'config/deflection/channel')]:
421             config = Config(storage=_HDF5_Storage(
422                     filename=filename, group=group+key))
423             configs.append(config)
424         try:
425             processed_bump = f[group+'processed'][...]
426         except KeyError:
427             pass
428     ret = [raw_bump]
429     ret.extend(configs)
430     ret.append(processed_bump)
431     for config in configs:
432         config.load()
433     return tuple(ret)
434
435 def bump_plot(data, yguess=None, yfit=None):
436     "Plot the bump (Vphoto vs Vzp)"
437     if not _matplotlib:
438         raise _matplotlib_import_error
439     figure = _matplotlib_pyplot.figure()
440     if yfit is None:
441         axes = figure.add_subplot(1, 1, 1)
442     else:
443         axes = figure.add_subplot(2, 1, 1)
444         residual_axes = figure.add_subplot(2, 1, 2)
445     timestamp = _time.strftime('%H%M%S')
446
447     axes.hold(True)
448     axes.plot(data['z'], data['deflection'], '.', label='bump')
449     if yguess != None:
450         axes.plot(data['z'], yguess, 'g-', label='guess')
451     if yfit != None:
452         axes.plot(data['z'], yfit, 'r-', label='fit')
453
454     axes.set_title('bump surface %s' % timestamp)
455     #axes.legend(loc='upper left')
456     axes.set_xlabel('Z piezo (meters)')
457     axes.set_ylabel('Photodiode (Volts)')
458     if yfit is not None:
459         # second subplot for residual
460         residual_axes.plot(data['z'], data['deflection'] - yfit,
461                            'r-', label='residual')
462         #residual_axes.legend(loc='upper right')
463         residual_axes.set_xlabel('Z piezo (meters)')
464         residual_axes.set_ylabel('Photodiode (Volts)')
465     figure.show()