1 # Copyright (C) 2009-2011 W. Trevor King <wking@drexel.edu>
3 # This file is part of pyafm.
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.
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.
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/>.
18 """Tools for controlling atomic force microscopes.
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.
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
33 from . import LOG as _LOG
34 from .stepper import Stepper as _Stepper
35 from .temperature import Temperature as _Temperature
39 """Atomic force microscope positioning.
41 Uses a short range `piezo` and a long range `stepper` to position
42 an AFM tip relative to the surface.
46 piezo | pypiezo.afm.AFMpiezo instance
47 Fine positioning and deflection measurements.
48 stepper | stepper.Stepper instance
50 temperature | temperature.Controller instance or None
51 Optional temperature monitoring and control.
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
61 >>> fd,filename = tempfile.mkstemp(suffix='.h5', prefix='pyafm-')
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'
84 >>> afm = AFM(config=config, devices=devices)
85 >>> afm.setup_config()
87 >>> afm.get_temperature() # doctest: +SKIP
90 >>> print(afm.config.dump()) # doctest: +REPORT_UDIFF
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
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
142 name: test temperature
148 fallback-temperature: 295.15
151 >>> pyafm.storage.save_afm(afm=afm, filename=filename)
152 >>> pprint_HDF5(filename=filename) # doctest: +REPORT_UDIFF
154 <HDF5 dataset "fallback-temperature": shape (), type "<f8">
156 <HDF5 dataset "far": shape (), type "<f8">
158 <HDF5 dataset "main-axis": shape (), type "|S1">
160 <HDF5 dataset "name": shape (), type "|S1">
165 /piezo/axes/0/channel
166 <HDF5 dataset "analog-reference": shape (), type "|S6">
168 <HDF5 dataset "channel": shape (), type "<i4">
170 <HDF5 dataset "conversion-coefficients": shape (2,), type "<f8">
171 [ -1.00000000e+01 3.05180438e-04]
172 <HDF5 dataset "conversion-origin": shape (), type "<f8">
174 <HDF5 dataset "device": shape (), type "|S12">
176 <HDF5 dataset "inverse-conversion-coefficients": shape (2,), type "<f8">
178 <HDF5 dataset "inverse-conversion-origin": shape (), type "<f8">
180 <HDF5 dataset "maxdata": shape (), type "<i8">
182 <HDF5 dataset "name": shape (), type "|S1">
184 <HDF5 dataset "range": shape (), type "<i4">
186 <HDF5 dataset "subdevice": shape (), type "<i4">
188 <HDF5 dataset "gain": shape (), type "<f8">
190 <HDF5 dataset "maximum": shape (), type "<f8">
192 <HDF5 dataset "minimum": shape (), type "<f8">
194 <HDF5 dataset "monitor": shape (), type "|S1">
196 <HDF5 dataset "sensitivity": shape (), type "<f8">
200 <HDF5 dataset "analog-reference": shape (), type "|S6">
202 <HDF5 dataset "channel": shape (), type "<i4">
204 <HDF5 dataset "conversion-coefficients": shape (2,), type "<f8">
205 [ -1.00000000e+01 3.05180438e-04]
206 <HDF5 dataset "conversion-origin": shape (), type "<f8">
208 <HDF5 dataset "device": shape (), type "|S12">
210 <HDF5 dataset "inverse-conversion-coefficients": shape (2,), type "<f8">
212 <HDF5 dataset "inverse-conversion-origin": shape (), type "<f8">
214 <HDF5 dataset "maxdata": shape (), type "<i8">
216 <HDF5 dataset "name": shape (), type "|S10">
218 <HDF5 dataset "range": shape (), type "<i4">
220 <HDF5 dataset "subdevice": shape (), type "<i4">
222 <HDF5 dataset "name": shape (), type "|S10">
225 <HDF5 dataset "backlash": shape (), type "<i4">
227 <HDF5 dataset "delay": shape (), type "<f8">
229 <HDF5 dataset "full-step": shape (), type "|b1">
231 <HDF5 dataset "logic": shape (), type "|b1">
233 <HDF5 dataset "name": shape (), type "|S12">
236 <HDF5 dataset "channels": shape (4,), type "<i4">
238 <HDF5 dataset "device": shape (), type "|S12">
240 <HDF5 dataset "direction": shape (), type "|S6">
242 <HDF5 dataset "name": shape (), type "|S12">
244 <HDF5 dataset "subdevice": shape (), type "<i4">
246 <HDF5 dataset "subdevice-type": shape (), type "|S3">
248 <HDF5 dataset "step-size": shape (), type "<f8">
251 <HDF5 dataset "baudrate": shape (), type "<i4">
253 <HDF5 dataset "controller": shape (), type "<i4">
255 <HDF5 dataset "device": shape (), type "|S10">
257 <HDF5 dataset "max-current": shape (), type "<f8">
259 <HDF5 dataset "name": shape (), type "|S16">
261 <HDF5 dataset "units": shape (), type "|S7">
263 >>> afm2 = pyafm.storage.load_afm(filename=filename, devices=devices)
265 >>> afm2.get_temperature() # doctest: +SKIP
268 It's hard to test anything else without pugging into an actual AFM.
270 >>> for device in devices:
273 Cleanup our temporary config file.
275 >>> os.remove(filename)
277 def __init__(self, config, piezo=None, stepper=None, temperature=None,
281 self.stepper = stepper
282 self.temperature = temperature
283 self.load_from_config(devices=devices)
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'])
294 def setup_config(self):
296 self.piezo.setup_config()
297 self.config['piezo'] = self.piezo.config
299 self.config['piezo'] = None
301 self.stepper.setup_config()
302 self.config['stepper'] = self.stepper.config
304 self.config['stepper'] = None
306 self.temperature.setup_config()
307 self.config['temperature'] = self.temperature.config
309 self.config['temperature'] = None
311 def get_temperature(self):
312 """Measure the sample temperature.
314 Return the sample temperature in Kelvin or `None` if such a
315 measurement is not possible.
317 if hasattr(self.temperature, 'get_temperature'):
318 return self.temperature.get_temperature()
319 return self.config['default-temperature']
321 def move_just_onto_surface(self, depth=-50e-9, setpoint=2,
322 min_slope_ratio=10, far=200, steps=20,
324 """Position the AFM tip close to the surface.
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
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
338 _LOG.info('moving to %g onto the surface' % depth)
340 stepper_tolerance = 2*self.stepper.step_size
342 axis = self.piezo.axis_by_name(self.config['main-axis'])
343 def_config = self.piezo.config.select_config('inputs', 'deflection')
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)
349 _LOG.debug('zero the %s piezo output' % self.config['main-axis'])
351 axis_name=self.config['main-axis'], position=zero, steps=steps,
354 _LOG.debug("see if we're starting near the surface")
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)
361 pos = self._stepper_approach_again(
362 target_deflection=target_def, min_slope_ratio=min_slope_ratio,
364 except _SurfaceError, e:
366 pos = self._stepper_approach_again(
367 target_deflection=target_def, min_slope_ratio=min_slope_ratio,
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))
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)
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)
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)
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)
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))
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)
409 self.config['main-axis'], target, steps=steps, sleep=sleep)
412 'positioned %g m into the surface at stepper %d, piezo %d (%g m)'
413 % (depth, self.stepper.position, target, target_m))
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)
424 _LOG.error(('requested setpoint ({} bits) is less than the '
425 'minimum deflection value of 0 bits'
426 ).format(deflection))
427 raise ValueError(deflection)
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))
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)):
437 'additional surface location attempt (stepping backwards)')
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)
444 except _SurfaceError, e:
446 self.stepper.single_step(-1) # step out
447 _LOG.debug('giving up on finding the surface')
451 def stepper_approach(self, target_deflection):
452 _LOG.info('approach with stepper until deflection > {}'.format(
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()
463 def move_toward_surface(self, distance):
464 """Step in approximately `distance` meters.
466 steps = int(distance/self.stepper.step_size)
467 _LOG.info('step in {} steps (~{} m)' % (steps, distance))
468 self.stepper.step_relative(steps)
470 def move_away_from_surface(self, distance=None):
471 """Step back approximately `distance` meters.
474 distance = self.config['far']
475 self.move_toward_surface(-distance)