convert to H5config and bump to v0.7.
[calibcant.git] / calibcant / bump.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 """Acquire, save, and load cantilever calibration bump data.
22
23 For measuring photodiode sensitivity.
24
25 The relevent physical quantities are:
26   Vzp_out  Output z-piezo voltage (what we generate)
27   Vzp      Applied z-piezo voltage (after external ZPGAIN)
28   Zp       The z-piezo position
29   Zcant    The cantilever vertical deflection
30   Vphoto   The photodiode vertical deflection voltage (what we measure)
31
32 Which are related by the parameters:
33   zp_gain           Vzp_out / Vzp
34   zp_sensitivity    Zp / Vzp
35   photo_sensitivity Vphoto / Zcant
36
37 Cantilever calibration assumes a pre-calibrated z-piezo
38 (zp_sensitivity) and amplifier (zp_gain).  In our lab, the z-piezo is
39 calibrated by imaging a calibration sample, which has features with
40 well defined sizes, and the gain is set with a knob on our modified
41 NanoScope.
42
43 Photo-sensitivity is measured by bumping the cantilever against the
44 surface, where `Zp = Zcant` (see the `bump_*()` family of functions).
45 The measured slope Vphoto/Vout is converted to photo-sensitivity via
46
47   Vphoto/Vzp_out * Vzp_out/Vzp  * Vzp/Zp   *    Zp/Zcant =    Vphoto/Zcant
48    (measured)      (1/zp_gain) (1/zp_sensitivity)  (1)    (photo_sensitivity)
49
50 We do all these measurements a few times to estimate statistical
51 errors.
52
53 The functions are layed out in the families:
54   bump_*()
55 For each family, * can be any of:
56   acquire       get real-world data
57   save         store real-world data to disk
58   load         get real-world data from disk
59   analyze      interperate the real-world data.
60   plot         show a nice graphic to convince people we're working :p
61
62 A family name without any _* extension (e.g. `bump()`), runs `*_acquire()`,
63 `*_save()`, `*_analyze()`.
64
65 If `package_config['matplotlib']` is `True`, `*_analyze()` will call
66 `*_plot()` internally.
67 """
68
69 import numpy as _numpy
70
71 from pypiezo.base import convert_meters_to_bits as _convert_meters_to_bits
72 from pypiezo.base import convert_bits_to_meters as _convert_bits_to_meters
73
74 from . import LOG as _LOG
75 from .bump_analyze import bump_analyze as _bump_analyze
76 from .bump_analyze import bump_save as _bump_save
77
78
79 def bump_acquire(afm, bump_config):
80     """Ramps `push_depth` closer and returns to the original position.
81
82     Inputs:
83       afm          a pyafm.AFM instance
84       bump_config  a .config._BumpConfig instance
85
86     Returns the acquired ramp data dictionary, with data in DAC/ADC bits.
87     """
88     afm.move_just_onto_surface(
89         depth=bump_config['initial-position'], far=bump_config['far-steps'])
90
91     _LOG.info('bump the surface to a depth of %g m'
92               % bump_config['push-depth'])
93
94     axis = afm.piezo.axis_by_name(afm.axis_name)
95
96     start_pos = afm.piezo.last_output[afm.axis_name]
97     start_pos_m = _convert_bits_to_meters(
98         axis.axis_channel_config, axis.axis_config, start_pos)
99     close_pos_m = start_pos_m + bump_config['push-depth']
100     close_pos = _convert_meters_to_bits(
101         axis.axis_channel_config, axis.axis_config, close_pos_m)
102
103     dtype = afm.piezo.channel_dtype(afm.axis_name, direction='output')
104     appr = _numpy.linspace(
105         start_pos, close_pos, bump_config['samples']).astype(dtype)
106     # switch numpy.append to numpy.concatenate with version 2.0+
107     out = _numpy.append(appr, appr[::-1])
108     out = out.reshape((len(out), 1))
109
110     # (samples) / (meters) * (meters/second) = (samples/second)
111     freq = (bump_config['samples'] / bump_config['push-depth']
112             * bump_config['push-speed'])
113
114     data = afm.piezo.ramp(out, freq, output_names=[afm.axis_name],
115                           input_names=['deflection'])
116
117     out = out.reshape((len(out),))
118     data = data.reshape((data.size,))
119     return {afm.axis_name: out, 'deflection': data}
120
121 def bump(afm, bump_config, filename, group='/'):
122     """Wrapper around bump_acquire(), bump_analyze(), bump_save().
123
124     >>> import os
125     >>> import tempfile
126     >>> from pycomedi.device import Device
127     >>> from pycomedi.subdevice import StreamingSubdevice
128     >>> from pycomedi.channel import AnalogChannel, DigitalChannel
129     >>> from pycomedi.constant import AREF, IO_DIRECTION, SUBDEVICE_TYPE, UNIT
130     >>> from pypiezo.afm import AFMPiezo
131     >>> from pypiezo.base import PiezoAxis, InputChannel
132     >>> from pypiezo.config import (HDF5_ChannelConfig, HDF5_AxisConfig,
133     ...     pprint_HDF5)
134     >>> from stepper import Stepper
135     >>> from pyafm import AFM
136     >>> from .config import HDF5_BumpConfig
137
138     >>> fd,filename = tempfile.mkstemp(suffix='.h5', prefix='calibcant-')
139     >>> os.close(fd)
140
141     >>> d = Device('/dev/comedi0')
142     >>> d.open()
143
144     Setup an `AFMPiezo` instance.
145
146     >>> s_in = d.find_subdevice_by_type(SUBDEVICE_TYPE.ai,
147     ...     factory=StreamingSubdevice)
148     >>> s_out = d.find_subdevice_by_type(SUBDEVICE_TYPE.ao,
149     ...     factory=StreamingSubdevice)
150
151     >>> axis_channel = s_out.channel(
152     ...     0, factory=AnalogChannel, aref=AREF.ground)
153     >>> input_channel = s_in.channel(0, factory=AnalogChannel, aref=AREF.diff)
154     >>> for chan in [axis_channel, input_channel]:
155     ...     chan.range = chan.find_range(unit=UNIT.volt, min=-10, max=10)
156
157     We set the minimum voltage for the `z` axis to -9 (a volt above
158     the minimum possible voltage) to help with testing
159     `.get_surface_position`.  Without this minimum voltage, small
160     calibration errors could lead to a railed -10 V input for the
161     first few surface approaching steps, which could lead to an
162     `EdgeKink` error instead of a `FlatFit` error.
163
164     >>> axis_config = HDF5_AxisConfig(filename, '/bump/config/z/axis')
165     >>> axis_config.update(
166     ...     {'gain':20, 'sensitivity':8e-9, 'minimum':-9})
167     >>> axis_channel_config = HDF5_ChannelConfig(
168     ...     filename, '/bump/config/z/channel')
169     >>> input_channel_config = HDF5_ChannelConfig(
170     ...     filename, '/bump/config/deflection/channel')
171
172     >>> a = PiezoAxis(axis_config=axis_config,
173     ...     axis_channel_config=axis_channel_config,
174     ...     axis_channel=axis_channel, name='z')
175     >>> a.setup_config()
176
177     >>> c = InputChannel(
178     ...     channel_config=input_channel_config, channel=input_channel,
179     ...     name='deflection')
180     >>> c.setup_config()
181
182     >>> piezo = AFMPiezo(axes=[a], input_channels=[c])
183
184     Setup a `stepper` instance.
185
186     >>> s_d = d.find_subdevice_by_type(SUBDEVICE_TYPE.dio)
187     >>> d_channels = [s_d.channel(i, factory=DigitalChannel)
188     ...             for i in (0, 1, 2, 3)]
189     >>> for chan in d_channels:
190     ...     chan.dio_config(IO_DIRECTION.output)
191
192     >>> def write(value):
193     ...     s_d.dio_bitfield(bits=value, write_mask=2**4-1)
194
195     >>> stepper = Stepper(write=write)
196
197     Setup an `AFM` instance.
198
199     >>> afm = AFM(piezo, stepper)
200
201     Test a bump:
202
203     >>> bump_config = HDF5_BumpConfig(
204     ...     filename=filename, group='/bump/config/bump')
205     >>> bump(afm, bump_config, filename, group='/bump')
206     TODO: replace skipped example data with real-world values
207     >>> pprint_HDF5(filename)  # doctest: +ELLIPSIS, +REPORT_UDIFF
208
209     Close the Comedi device.
210
211     >>> d.close()
212
213     Cleanup our temporary config file.
214
215     >>> os.remove(filename)
216     """
217     deflection_channel = afm.piezo.input_channel_by_name('deflection')
218     axis = afm.piezo.axis_by_name(afm.axis_name)
219
220     data = bump_acquire(afm, bump_config)
221     photo_sensitivity = _bump_analyze(
222         data, bump_config, z_channel_config=axis.axis_channel_config,
223         z_axis_config=axis.axis_config,
224         deflection_channel_config=deflection_channel.channel_config)
225     _bump_save(
226         filename, group, data, bump_config,
227         z_channel_config=axis.axis_channel_config,
228         z_axis_config=axis.axis_config,
229         deflection_channel_config=deflection_channel.channel_config,
230         processed_bump=photo_sensitivity)
231     return photo_sensitivity