Added update_copyright.py to automate copyright blurb maintenance
[calibcant.git] / calibcant / bump.py
1 #!/usr/bin/python
2 #
3 # calibcant - tools for thermally calibrating AFM cantilevers
4 #
5 # Copyright (C) 2007-2009 William Trevor King
6 #
7 # This program is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU General Public License as
9 # published by the Free Software Foundation; either version 3 of the
10 # License, or (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15 # See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 # 02111-1307, USA.
21 #
22 # The author may be contacted at <wking@drexel.edu> on the Internet, or
23 # write to Trevor King, Drexel University, Physics Dept., 3141 Chestnut St.,
24 # Philadelphia PA 19104, USA.
25
26 """
27 Aquire, save, and load cantilever calibration bump data.
28 For measuring photodiode sensitivity.
29
30 W. Trevor King Dec. 2007 - Oct. 2008
31
32 The relevent physical quantities are :
33  Vzp_out  Output z-piezo voltage (what we generate)
34  Vzp      Applied z-piezo voltage (after external ZPGAIN)
35  Zp       The z-piezo position
36  Zcant    The cantilever vertical deflection
37  Vphoto   The photodiode vertical deflection voltage (what we measure)
38
39 Which are related by the parameters :
40  zpGain           Vzp_out / Vzp
41  zpSensitivity    Zp / Vzp
42  photoSensitivity Vphoto / Zcant
43
44 Cantilever calibration assumes a pre-calibrated z-piezo (zpSensitivity) and
45 amplifier (zpGain).  In our lab, the z-piezo is calibrated by imaging a
46 calibration sample, which has features with well defined sizes, and the gain
47 is set with a knob on the Nanoscope.
48
49 photoSensitivity is measured by bumping the cantilever against the surface,
50 where Zp = Zcant (see the bump_*() family of functions)
51 The measured slope Vphoto/Vout is converted to photoSensitivity via
52 Vphoto/Vzp_out * Vzp_out/Vzp  * Vzp/Zp   *    Zp/Zcant =    Vphoto/Zcant
53  (measured)      (1/zpGain) (1/zpSensitivity)    (1)  (photoSensitivity)
54
55 We do all these measurements a few times to estimate statistical errors.
56
57 The functions are layed out in the families:
58  bump_*()
59 For each family, * can be any of :
60  aquire       get real-world data
61  save         store real-world data to disk
62  load         get real-world data from disk
63  analyze      interperate the real-world data.
64  plot         show a nice graphic to convince people we're working :p
65  load_analyze_tweaked
66               read a file with a list of paths to previously saved real world data
67               load each file using *_load(), analyze using *_analyze(), and
68               optionally plot using *_plot().
69               Intended for re-processing old data.
70 A family name without any _* extension (e.g. bump()),
71  runs *_aquire(), *_save(), *_analyze(), *_plot().
72 """
73
74 import numpy
75 import time 
76
77 import data_logger
78 import FFT_tools
79 import piezo.z_piezo_utils as z_piezo_utils
80
81 from .bump_analyze import bump_analyze
82
83
84 LOG_DATA = True  # quietly grab all real-world data and log to LOG_DIR
85 LOG_DIR = '$DEFAULT$/calibrate_cantilever'
86
87 TEXT_VERBOSE = True      # for debugging
88
89
90 # bump family
91
92 def bump_aquire(zpiezo, push_depth, npoints, freq) :
93     """
94     Ramps closer push_depth and returns to the original position.
95     Inputs:
96      zpiezo     an opened zpiezo.zpiezo instance
97      push_depth distance to approach, in nm
98      npoints    number points during the approach and during the retreat
99      freq       rate at which data is aquired
100      log_dir    directory to log data to (see data_logger.py).
101                 None to turn off logging (see also the global LOG_DATA).
102     Returns the aquired ramp data dictionary, with data in DAC/ADC bits.
103     """
104     # generate the bump output
105     start_pos = zpiezo.curPos()
106     pos_dist = zpiezo.pos_nm2out(push_depth) - zpiezo.pos_nm2out(0)
107     close_pos = start_pos + pos_dist
108     appr = linspace(start_pos, close_pos, npoints)
109     retr = linspace(close_pos, start_pos, npoints)
110     out = concatenate((appr, retr))
111     # run the bump, and measure deflection
112     if TEXT_VERBOSE :
113         print "Bump %g nm" % push_depth
114     data = zpiezo.ramp(out, freq)
115     # default saving, so we have a log in-case the operator is lazy ;)
116     if LOG_DATA == True :
117         log = data_logger.data_log(LOG_DIR, noclobber_logsubdir=False,
118                                    log_name="bump_surface")
119         log.write_dict_of_arrays(data)
120     return data
121
122 def bump_save(data, log_dir) :
123     "Save the dictionary data, using data_logger.data_log()"
124     if log_dir != None :
125         log = data_logger.data_log(log_dir, noclobber_logsubdir=False,
126                                    log_name="bump")
127         log.write_dict_of_arrays(data)
128
129 def bump_load(datafile) :
130     "Load the dictionary data, using data_logger.date_load()"
131     dl = data_logger.data_load()
132     data = dl.read_dict_of_arrays(path)
133     return data
134
135 def bump_plot(data, plotVerbose) :
136     "Plot the bump (Vphoto vs Vzp) if plotVerbose or PYLAB_VERBOSE == True"
137     if plotVerbose or PYLAB_VERBOSE :
138         _import_pylab()
139         _pylab.figure(BASE_FIGNUM)
140         _pylab.plot(data["Z piezo output"], data["Deflection input"],
141                     '.', label='bump')
142         _pylab.title("bump surface")
143         _pylab.legend(loc='upper left')
144         _flush_plot()
145
146 def bump(zpiezo, push_depth, npoints=1024, freq=100e3,
147          log_dir=None,
148          plotVerbose=False) :
149     """
150     Wrapper around bump_aquire(), bump_save(), bump_analyze(), bump_plot()
151     """
152     data = bump_aquire(zpiezo, push_depth, npoints, freq)
153     bump_save(data, log_dir)
154     photoSensitivity = bump_analyze(data, zpiezo.gain, zpiezo.sensitivity,
155                                     zpiezo.pos_out2V, zpiezo.def_in2V)
156     bump_plot(data, plotVerbose)
157     return photoSensitivity
158
159 def bump_load_analyze_tweaked(tweak_file, zpGain=_usual_zpGain,
160                               zpSensitivity=_usual_zpSensitivity,
161                               Vzp_out2V=_usual_Vzp_out2V,
162                               Vphoto_in2V=_usual_Vphoto_in2V,
163                               plotVerbose=False) :
164     "Load the output file of tweak_calib_bump.sh, return an array of slopes"
165     photoSensitivity = []
166     for line in file(tweak_file, 'r') :
167         parsed = line.split()
168         path = parsed[0].split('\n')[0]
169         # read the data
170         full_data = bump_load(path)
171         if len(parsed) == 1 :
172             data = full_data # use whole bump
173         else :
174             # use the listed sections
175             zp = []
176             df = []
177             for rng in parsed[1:] :
178                 p = rng.split(':')
179                 starti = int(p[0])
180                 stopi = int(p[1])
181                 zp.extend(full_data['Z piezo output'][starti:stopi])
182                 df.extend(full_data['Deflection input'][starti:stopi])
183             data = {'Z piezo output': array(zp),
184                     'Deflection input':array(df)}
185         pSi = bump_analyze(data, zpGain, zpSensitivity,
186                            Vzp_out2V, Vphoto_in2V, plotVerbose)
187         photoSensitivity.append(pSi)
188         bump_plot(data, plotVervose)
189     return array(photoSensitivity, dtype=numpy.float)
190