Fix typo target_def -> target_deflection.
[pyafm.git] / pyafm.py
1 """Tools for controlling atomic force microscopes.
2
3 Provides control of AFM postition using both short-range (piezo) and
4 long range (stepper) vertical positioning.  There are separate modules
5 for controlling the piezo (`pypiezo`) and stepper (`stepper`), this
6 module only contains methods that require the capabilities of both.
7 """
8
9 import logging as _logging
10
11 from pypiezo.base import convert_volts_to_bits as _convert_volts_to_bits
12 from pypiezo.base import convert_meters_to_bits as _convert_meters_to_bits
13 from pypiezo.base import convert_bits_to_meters as _convert_bits_to_meters
14 from pypiezo.surface import SurfaceError as _SurfaceError
15 from pypiezo.surface import FlatFit as _FlatFit
16
17
18 __version__ = '0.1'
19
20
21 LOG = _logging.getLogger('pyafm')
22 "pyafm logger"
23
24 LOG.setLevel(_logging.DEBUG)
25 h = _logging.StreamHandler()
26 h.setLevel(_logging.WARN)
27 f = _logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
28 h.setFormatter(f)
29 LOG.addHandler(h)
30 del h, f
31
32
33 class AFM (object):
34     """Atomic force microscope positioning.
35
36     Uses a short range `piezo` and a long range `stepper` to position
37     an AFM tip relative to the surface.
38
39     Parameters
40     ----------
41     piezo | pypiezo.afm.AFMpiezo instance
42         Fine positioning and deflection measurements.
43     stepper | stepper.Stepper instance
44         Coarse positioning.
45     temperature | temperature.Controller instance or None
46         Optional temperature monitoring and control.
47     """
48     def __init__(self, piezo, stepper, temperature=None, axis_name='z'):
49         self.piezo = piezo
50         self.stepper = stepper
51         self.temperature = temperature
52         self.axis_name = axis_name
53
54     def get_temperature(self):
55         """Measure the sample temperature.
56
57         Return the sample temperature in Kelvin or `None` if such a
58         measurement is not possible.
59         """
60         if hasattr(self.temperature, 'get'):
61             return self.temperature.get_temperature()
62
63     def move_just_onto_surface(self, depth=-50e-9, setpoint=2, far=200):
64         """Position the AFM tip close to the surface.
65
66         Uses `.piezo.get_surface_position()` to pinpoint the position
67         of the surface.  Adjusts the stepper position as required via
68         `.stepper.step_relative()` to get within
69         `2*.stepper.step_size` meters of the surface.  Then adjusts
70         the piezo to place the cantilever `depth` meters onto the
71         surface.  Negative `depth`\s place the tip off the surface
72
73         If `.piezo.get_surface_position()` fails to find the surface,
74         backs off `far` half steps (for safety) and steps in (without
75         moving the zpiezo) until deflection voltage is greater than
76         `setpoint`.
77         """
78         LOG.info('moving to %g onto the surface' % depth)
79
80         stepper_tolerance = 2*self.stepper.step_size
81
82         axis = self.piezo.axis_by_name(self.axis_name)
83
84         zero = _convert_volts_to_bits(axis.axis_channel_config, 0)
85         target_def = _convert_volts_to_bits(axis.axis_channel_config, setpoint)
86
87         LOG.debug('zero the %s piezo output' % self.axis_name)
88         self.piezo.jump(axis_name=self.axis_name, position=zero)
89
90         LOG.debug("see if we're starting near the surface")
91         try:
92             pos = self.piezo.get_surface_position(
93                 axis_name=self.axis_name, max_deflection=target_def)
94         except _FlatFit, e:
95             LOG.info(e)
96             pos = self._stepper_approach_again(
97                 target_deflection=target_def, far=far)
98         except _SurfaceError, e:
99             LOG.info(e)
100             pos = self._stepper_approach_again(
101                 target_deflection=target_def, far=far)
102
103         pos_m = _convert_bits_to_meters(
104             axis.axis_channel_config, axis.axis_config, pos)
105         LOG.debug('located surface at stepper %d, piezo %d (%g m)'
106                   % (self.stepper.position, pos, pos_m))
107
108         LOG.debug('fine tune the stepper position')
109         while pos_m < -stepper_tolerance:  # step back if we need to
110             LOG.debug('step back')
111             self.stepper.step_relative(-1, backlash_safe=True)
112             try:
113                 pos = self.piezo.get_surface_position(
114                     axis_name=self.axis_name, max_deflection=target_def)
115             except _FlatFit, e:
116                 LOG.debug(e)
117                 continue
118             pos_m = _convert_bits_to_meters(
119                 axis.axis_channel_config, axis.axis_config, pos)
120             LOG.debug('located surface at stepper %d, piezo %d (%g m)'
121                       % (self.stepper.position, pos, pos_m))
122         while pos_m > stepper_tolerance:  # step forward if we need to
123             LOG.debug('step forward')
124             self.stepper.step_relative(1)
125             try:
126                 pos = self.piezo.get_surface_position(
127                     axis_name=self.axis_name, max_deflection=target_def)
128             except _FlatFit, e:
129                 LOG.debug(e)
130                 continue
131             pos_m = _convert_bits_to_meters(
132                 axis.axis_channel_config, axis.axis_config, pos)
133             LOG.debug('located surface at stepper %d, piezo %d (%g m)'
134                       % (self.stepper.position, pos, pos_m))
135
136         LOG.debug('adjust the %s piezo to place us just onto the surface'
137                   % self.axis_name)
138         target_m = pos_m + depth
139         target = _convert_meters_to_bits(
140             axis.axis_channel_config, axis.axis_config, target_m)
141         self.piezo.jump(self.axis_name, target)
142
143         LOG.debug(
144             'positioned %g m into the surface at stepper %d, piezo %d (%g m)'
145             % (depth, self.stepper.position, target, target_m))
146
147
148     def _stepper_approach_again(self, target_deflection, far):
149         LOG.info('back off %d half steps and approach until deflection > %g'
150                  % (far, target_deflection))
151
152         # back away
153         self.stepper.step_relative(-far, backlash_safe=True)
154
155         cd = self.piezo.read_deflection()  # cd = current deflection in bits
156         LOG.debug('single stepping approach')
157         while cd < target_deflection:
158             LOG.debug('deflection %g < setpoint %g.  step closer'
159                       % (cd, target_deflection))
160             self.stepper.single_step(1)  # step in
161             cd = self.piezo.read_deflection()
162
163         for i in range(2*max(1, self.stepper.backlash)):
164             LOG.debug('additional surface location attempt')
165             try:
166                 pos = self.piezo.get_surface_position(
167                     axis_name=self.axis_name, max_deflection=target_deflection)
168                 return pos
169             except _SurfaceError, e:
170                 LOG.info(e)
171             self.stepper.single_step(-1)  # step out
172         LOG.debug('giving up on finding the surface')
173         LOG.warn(e)
174         raise e