e6d7fb5fe1471c774a8576bd5c8ddce81e3b117a
[pyafm.git] / pyafm / afm.py
1 # Copyright (C) 2009-2011 W. Trevor King <wking@drexel.edu>
2 #
3 # This file is part of pyafm.
4 #
5 # pyafm is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by the
7 # Free Software Foundation, either version 3 of the License, or (at your
8 # option) any later version.
9 #
10 # pyafm is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with pyafm.  If not, see <http://www.gnu.org/licenses/>.
17
18 """Tools for controlling atomic force microscopes.
19
20 Provides control of AFM postition using both short-range (piezo) and
21 long range (stepper) vertical positioning.  There are separate modules
22 for controlling the piezo (`pypiezo`) and stepper (`stepper`), this
23 module only contains methods that require the capabilities of both.
24 """
25
26 from pypiezo.afm import AFMPiezo as _AFMPiezo
27 from pypiezo.base import convert_bits_to_meters as _convert_bits_to_meters
28 from pypiezo.base import convert_meters_to_bits as _convert_meters_to_bits
29 from pypiezo.base import convert_volts_to_bits as _convert_volts_to_bits
30 from pypiezo.surface import FlatFit as _FlatFit
31 from pypiezo.surface import SurfaceError as _SurfaceError
32
33 from . import LOG as _LOG
34 from .stepper import Stepper as _Stepper
35 from .temperature import Temperature as _Temperature
36
37
38 class AFM (object):
39     """Atomic force microscope positioning.
40
41     Uses a short range `piezo` and a long range `stepper` to position
42     an AFM tip relative to the surface.
43
44     Parameters
45     ----------
46     piezo | pypiezo.afm.AFMpiezo instance
47         Fine positioning and deflection measurements.
48     stepper | stepper.Stepper instance
49         Coarse positioning.
50     temperature | temperature.Controller instance or None
51         Optional temperature monitoring and control.
52
53     >>> import os
54     >>> import tempfile
55     >>> from pycomedi import constant
56     >>> import pypiezo.config
57     >>> import pyafm.config
58     >>> import pyafm.storage
59     >>> from h5config.storage.hdf5 import pprint_HDF5
60
61     >>> fd,filename = tempfile.mkstemp(suffix='.h5', prefix='pyafm-')
62     >>> os.close(fd)
63
64     >>> devices = []
65
66     >>> config = pyafm.config.AFMConfig()
67     >>> config['piezo'] = pypiezo.config.PiezoConfig()
68     >>> config['piezo']['name'] = 'test piezo'
69     >>> config['piezo']['axes'] = [pypiezo.config.AxisConfig()]
70     >>> config['piezo']['axes'][0]['channel'] = (
71     ...     pypiezo.config.OutputChannelConfig())
72     >>> config['piezo']['axes'][0]['channel']['name'] = 'z'
73     >>> config['piezo']['inputs'] = [pypiezo.config.InputChannelConfig()]
74     >>> config['piezo']['inputs'][0]['name'] = 'deflection'
75     >>> config['stepper'] = pyafm.config.StepperConfig()
76     >>> config['stepper']['port'] = pyafm.config.DigitalPortConfig()
77     >>> config['stepper']['port']['channels'] = [1, 2, 3, 4]
78     >>> config['stepper']['port']['direction'] = constant.IO_DIRECTION.output
79     >>> config['stepper']['port']['name'] = 'stepper port'
80     >>> config['stepper']['name'] = 'test stepper'
81     >>> config['temperature'] = pyafm.config.TemperatureConfig()
82     >>> config['temperature']['name'] = 'test temperature'
83
84     >>> afm = AFM(config=config, devices=devices)
85     >>> afm.setup_config()
86
87     >>> afm.get_temperature()  # doctest: +SKIP
88     297.37
89
90     >>> print(afm.config.dump())  # doctest: +REPORT_UDIFF
91     name: 
92     main-axis: 
93     piezo:
94       name: test piezo
95       axes:
96         0:
97           gain: 1.0
98           sensitivity: 1.0
99           minimum: -10.0
100           maximum: 10.0
101           channel:
102             name: z
103             device: /dev/comedi0
104             subdevice: 1
105             channel: 0
106             maxdata: 65535
107             range: 0
108             analog-reference: ground
109             conversion-coefficients: -10.0,0.000305180437934
110             conversion-origin: 0.0
111             inverse-conversion-coefficients: 0.0,3276.75
112             inverse-conversion-origin: -10.0
113           monitor: 
114       inputs:
115         0:
116           name: deflection
117           device: /dev/comedi0
118           subdevice: 0
119           channel: 0
120           maxdata: 65535
121           range: 0
122           analog-reference: ground
123           conversion-coefficients: -10.0,0.000305180437934
124           conversion-origin: 0.0
125           inverse-conversion-coefficients: 0.0,3276.75
126           inverse-conversion-origin: -10.0
127     stepper:
128       name: test stepper
129       full-step: yes
130       logic: yes
131       delay: 0.01
132       step-size: 1.7e-07
133       backlash: 100
134       port:
135         name: stepper port
136         device: /dev/comedi0
137         subdevice: 2
138         subdevice-type: dio
139         channels: 1,2,3,4
140         direction: output
141     temperature:
142       name: test temperature
143       units: Celsius
144       controller: 1
145       device: /dev/ttyS0
146       baudrate: 9600
147       max-current: 0.0
148     fallback-temperature: 295.15
149     far: 3e-05
150
151     >>> pyafm.storage.save_afm(afm=afm, filename=filename)
152     >>> pprint_HDF5(filename=filename)  # doctest: +REPORT_UDIFF
153     /
154       <HDF5 dataset "fallback-temperature": shape (), type "<f8">
155         295.15
156       <HDF5 dataset "far": shape (), type "<f8">
157         3e-05
158       <HDF5 dataset "main-axis": shape (), type "|S1">
159     <BLANKLINE>
160       <HDF5 dataset "name": shape (), type "|S1">
161     <BLANKLINE>
162       /piezo
163         /piezo/axes
164           /piezo/axes/0
165             /piezo/axes/0/channel
166               <HDF5 dataset "analog-reference": shape (), type "|S6">
167                 ground
168               <HDF5 dataset "channel": shape (), type "<i4">
169                 0
170               <HDF5 dataset "conversion-coefficients": shape (2,), type "<f8">
171                 [ -1.00000000e+01   3.05180438e-04]
172               <HDF5 dataset "conversion-origin": shape (), type "<f8">
173                 0.0
174               <HDF5 dataset "device": shape (), type "|S12">
175                 /dev/comedi0
176               <HDF5 dataset "inverse-conversion-coefficients": shape (2,), type "<f8">
177                 [    0.    3276.75]
178               <HDF5 dataset "inverse-conversion-origin": shape (), type "<f8">
179                 -10.0
180               <HDF5 dataset "maxdata": shape (), type "<i8">
181                 65535
182               <HDF5 dataset "name": shape (), type "|S1">
183                 z
184               <HDF5 dataset "range": shape (), type "<i4">
185                 0
186               <HDF5 dataset "subdevice": shape (), type "<i4">
187                 1
188             <HDF5 dataset "gain": shape (), type "<f8">
189               1.0
190             <HDF5 dataset "maximum": shape (), type "<f8">
191               10.0
192             <HDF5 dataset "minimum": shape (), type "<f8">
193               -10.0
194             <HDF5 dataset "monitor": shape (), type "|S1">
195     <BLANKLINE>
196             <HDF5 dataset "sensitivity": shape (), type "<f8">
197               1.0
198         /piezo/inputs
199           /piezo/inputs/0
200             <HDF5 dataset "analog-reference": shape (), type "|S6">
201               ground
202             <HDF5 dataset "channel": shape (), type "<i4">
203               0
204             <HDF5 dataset "conversion-coefficients": shape (2,), type "<f8">
205               [ -1.00000000e+01   3.05180438e-04]
206             <HDF5 dataset "conversion-origin": shape (), type "<f8">
207               0.0
208             <HDF5 dataset "device": shape (), type "|S12">
209               /dev/comedi0
210             <HDF5 dataset "inverse-conversion-coefficients": shape (2,), type "<f8">
211               [    0.    3276.75]
212             <HDF5 dataset "inverse-conversion-origin": shape (), type "<f8">
213               -10.0
214             <HDF5 dataset "maxdata": shape (), type "<i8">
215               65535
216             <HDF5 dataset "name": shape (), type "|S10">
217               deflection
218             <HDF5 dataset "range": shape (), type "<i4">
219               0
220             <HDF5 dataset "subdevice": shape (), type "<i4">
221               0
222         <HDF5 dataset "name": shape (), type "|S10">
223           test piezo
224       /stepper
225         <HDF5 dataset "backlash": shape (), type "<i4">
226           100
227         <HDF5 dataset "delay": shape (), type "<f8">
228           0.01
229         <HDF5 dataset "full-step": shape (), type "|b1">
230           True
231         <HDF5 dataset "logic": shape (), type "|b1">
232           True
233         <HDF5 dataset "name": shape (), type "|S12">
234           test stepper
235         /stepper/port
236           <HDF5 dataset "channels": shape (4,), type "<i4">
237             [1 2 3 4]
238           <HDF5 dataset "device": shape (), type "|S12">
239             /dev/comedi0
240           <HDF5 dataset "direction": shape (), type "|S6">
241             output
242           <HDF5 dataset "name": shape (), type "|S12">
243             stepper port
244           <HDF5 dataset "subdevice": shape (), type "<i4">
245             2
246           <HDF5 dataset "subdevice-type": shape (), type "|S3">
247             dio
248         <HDF5 dataset "step-size": shape (), type "<f8">
249           1.7e-07
250       /temperature
251         <HDF5 dataset "baudrate": shape (), type "<i4">
252           9600
253         <HDF5 dataset "controller": shape (), type "<i4">
254           1
255         <HDF5 dataset "device": shape (), type "|S10">
256           /dev/ttyS0
257         <HDF5 dataset "max-current": shape (), type "<f8">
258           0.0
259         <HDF5 dataset "name": shape (), type "|S16">
260           test temperature
261         <HDF5 dataset "units": shape (), type "|S7">
262           Celsius
263     >>> afm2 = pyafm.storage.load_afm(filename=filename, devices=devices)
264
265     >>> afm2.get_temperature()  # doctest: +SKIP
266     297.37
267
268     It's hard to test anything else without pugging into an actual AFM.
269
270     >>> for device in devices:
271     ...     device.close()
272
273     Cleanup our temporary config file.
274
275     >>> os.remove(filename)
276     """
277     def __init__(self, config, piezo=None, stepper=None, temperature=None,
278                  devices=None):
279         self.config = config
280         self.piezo = piezo
281         self.stepper = stepper
282         self.temperature = temperature
283         self.load_from_config(devices=devices)
284
285     def load_from_config(self, devices):
286         c = self.config  # reduce verbosity
287         if self.piezo is None and c['piezo']:
288             self.piezo = _AFMPiezo(config=c['piezo'], devices=devices)
289         if self.stepper is None and c['stepper']:
290             self.stepper = _Stepper(config=c['stepper'], devices=devices)
291         if self.temperature is None and c['temperature']:
292             self.temperature = _Temperature(config=c['temperature'])
293
294     def setup_config(self):
295         if self.piezo:
296             self.piezo.setup_config()
297             self.config['piezo'] = self.piezo.config
298         else:
299             self.config['piezo'] = None
300         if self.stepper:
301             self.stepper.setup_config()
302             self.config['stepper'] = self.stepper.config
303         else:
304             self.config['stepper'] = None
305         if self.temperature:
306             self.temperature.setup_config()
307             self.config['temperature'] = self.temperature.config
308         else:
309             self.config['temperature'] = None
310
311     def get_temperature(self):
312         """Measure the sample temperature.
313
314         Return the sample temperature in Kelvin or `None` if such a
315         measurement is not possible.
316         """
317         if hasattr(self.temperature, 'get_temperature'):
318             return self.temperature.get_temperature()
319         return self.config['default-temperature']
320
321     def move_just_onto_surface(self, depth=-50e-9, setpoint=2,
322                                min_slope_ratio=10, far=200, steps=20,
323                                sleep=0.0001):
324         """Position the AFM tip close to the surface.
325
326         Uses `.piezo.get_surface_position()` to pinpoint the position
327         of the surface.  Adjusts the stepper position as required via
328         `.stepper.single_step()` to get within
329         `2*.stepper.step_size` meters of the surface.  Then adjusts
330         the piezo to place the cantilever `depth` meters onto the
331         surface.  Negative `depth`\s place the tip off the surface
332
333         If `.piezo.get_surface_position()` fails to find the surface,
334         backs off `far` half steps (for safety) and steps in (without
335         moving the zpiezo) until deflection voltage is greater than
336         `setpoint`.
337         """
338         _LOG.info('moving to %g onto the surface' % depth)
339
340         stepper_tolerance = 2*self.stepper.step_size
341
342         axis = self.piezo.axis_by_name(self.config['main-axis'])
343         def_config = self.piezo.config.select_config('inputs', 'deflection')
344
345         zero = _convert_volts_to_bits(axis.config['channel'], 0)
346         target_def = _convert_volts_to_bits(def_config, setpoint)
347         self._check_target_deflection(deflection=target_def)
348
349         _LOG.debug('zero the %s piezo output' % self.config['main-axis'])
350         self.piezo.jump(
351             axis_name=self.config['main-axis'], position=zero, steps=steps,
352             sleep=sleep)
353
354         _LOG.debug("see if we're starting near the surface")
355         try:
356             pos = self.piezo.get_surface_position(
357                 axis_name=self.config['main-axis'], max_deflection=target_def,
358                 min_slope_ratio=min_slope_ratio)
359         except _FlatFit, e:
360             _LOG.info(e)
361             pos = self._stepper_approach_again(
362                 target_deflection=target_def, min_slope_ratio=min_slope_ratio,
363                 far=far)
364         except _SurfaceError, e:
365             _LOG.info(e)
366             pos = self._stepper_approach_again(
367                 target_deflection=target_def, min_slope_ratio=min_slope_ratio,
368                 far=far)
369
370         pos_m = _convert_bits_to_meters(axis.config, pos)
371         _LOG.debug('located surface at stepper %d, piezo %d (%g m)'
372                   % (self.stepper.position, pos, pos_m))
373
374         _LOG.debug('fine tune the stepper position')
375         while pos_m < -stepper_tolerance:  # step back if we need to
376             _LOG.debug('step back')
377             self.stepper.single_step(-1)
378             try:
379                 pos = self.piezo.get_surface_position(
380                     axis_name=self.config['main-axis'],
381                     max_deflection=target_def,
382                     min_slope_ratio=min_slope_ratio)
383             except _FlatFit, e:
384                 _LOG.debug(e)
385                 continue
386             pos_m = _convert_bits_to_meters(axis.config, pos)
387             _LOG.debug('located surface at stepper %d, piezo %d (%g m)'
388                       % (self.stepper.position, pos, pos_m))
389         while pos_m > stepper_tolerance:  # step forward if we need to
390             _LOG.debug('step forward')
391             self.stepper.single_step(1)
392             try:
393                 pos = self.piezo.get_surface_position(
394                     axis_name=self.config['main-axis'],
395                     max_deflection=target_def,
396                     min_slope_ratio=min_slope_ratio)
397             except _FlatFit, e:
398                 _LOG.debug(e)
399                 continue
400             pos_m = _convert_bits_to_meters(axis.config, pos)
401             _LOG.debug('located surface at stepper %d, piezo %d (%g m)'
402                       % (self.stepper.position, pos, pos_m))
403
404         _LOG.debug('adjust the %s piezo to place us just onto the surface'
405                   % self.config['main-axis'])
406         target_m = pos_m + depth
407         target = _convert_meters_to_bits(axis.config, target_m)
408         self.piezo.jump(
409             self.config['main-axis'], target, steps=steps, sleep=sleep)
410
411         _LOG.debug(
412             'positioned %g m into the surface at stepper %d, piezo %d (%g m)'
413             % (depth, self.stepper.position, target, target_m))
414
415     def _check_target_deflection(self, deflection):
416         defc = self.piezo._deflection_channel()
417         max_def = defc.get_maxdata()
418         if deflection > max_def:
419             _LOG.error(('requested setpoint ({} bits) is larger than the '
420                         'maximum deflection value of {} bits'
421                         ).format(deflection, max_def))
422             raise ValueError(deflection)
423         elif deflection < 0:
424             _LOG.error(('requested setpoint ({} bits) is less than the '
425                         'minimum deflection value of 0 bits'
426                         ).format(deflection))
427             raise ValueError(deflection)
428
429     def _stepper_approach_again(self, target_deflection, min_slope_ratio, far):
430         _LOG.info('back off %d half steps and approach until deflection > %g'
431                  % (far, target_deflection))
432         # back away
433         self.stepper.step_relative(-far, backlash_safe=True)
434         self.stepper_approach(target_deflection=target_deflection)
435         for i in range(2*max(1, self.stepper.backlash)):
436             _LOG.debug(
437                 'additional surface location attempt (stepping backwards)')
438             try:
439                 pos = self.piezo.get_surface_position(
440                     axis_name=self.config['main-axis'],
441                     max_deflection=target_deflection,
442                     min_slope_ratio=min_slope_ratio)
443                 return pos
444             except _SurfaceError, e:
445                 _LOG.info(e)
446             self.stepper.single_step(-1)  # step out
447         _LOG.debug('giving up on finding the surface')
448         _LOG.warn(e)
449         raise e
450
451     def stepper_approach(self, target_deflection):
452         _LOG.info('approach with stepper until deflection > {}'.format(
453                 target_deflection))
454         self._check_target_deflection(deflection=target_deflection)
455         cd = self.piezo.read_deflection()  # cd = current deflection in bits
456         _LOG.debug('single stepping approach')
457         while cd < target_deflection:
458             _LOG.debug('deflection {} < setpoint {}.  step closer'.format(
459                     cd, target_deflection))
460             self.stepper.single_step(1)  # step in
461             cd = self.piezo.read_deflection()
462
463     def move_toward_surface(self, distance):
464         """Step in approximately `distance` meters.
465         """
466         steps = int(distance/self.stepper.step_size)
467         _LOG.info('step in {} steps (~{} m)' % (steps, distance))
468         self.stepper.step_relative(steps)
469
470     def move_away_from_surface(self, distance=None):
471         """Step back approximately `distance` meters.
472         """
473         if distance is None:
474             distance = self.config['far']
475         self.move_toward_surface(-distance)