1 # Copyright (C) 2010 W. Trevor King <wking@drexel.edu>
3 # This file is part of Hooke.
5 # Hooke is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
10 # Hooke is distributed in the hope that it will be useful, but WITHOUT
11 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
12 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
13 # Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with Hooke. If not, see
17 # <http://www.gnu.org/licenses/>.
19 """Driver for W. Trevor King's velocity clamp data format.
21 See my related projects:
23 * http://www.physics.drexel.edu/~wking/code/git/git.php?p=unfold_protein.git
24 * http://www.physics.drexel.edu/~wking/code/git/git.php?p=calibrate_cantilever.git
25 * http://www.physics.drexel.edu/~wking/code/git/git.php?p=data_logger.git
26 * http://www.physics.drexel.edu/~wking/code/git/git.php?p=piezo.git
27 * http://www.physics.drexel.edu/~wking/code/git/git.php?p=pycomedi.git
29 And the deprecated projects (which Hooke replaces):
31 * http://www.physics.drexel.edu/~wking/code/git/git.php?p=scale_unfold.git
32 * http://www.physics.drexel.edu/~wking/code/git/git.php?p=sawmodel.git
44 from .. import curve as curve
45 from ..config import Setting
46 from . import Driver as Driver
49 import calibcant.config
50 calibcant_dir = calibcant.config.LOG_DIR
60 class WTKDriver (Driver):
61 """Handle W. Trevor King's data_logger data format.
64 super(WTKDriver, self).__init__(name='wtk')
66 def default_settings(self):
68 Setting(section=self.setting_section, help=self.__doc__),
69 Setting(section=self.setting_section,
70 option='cantilever calibration directory',
71 value=calibcant_dir, type='path',
72 help='Set the directory where cantilever calibration data is stored'),
75 def is_me(self, path):
76 if os.path.isdir(path):
78 if not path.endswith('_unfold'):
80 for p in self._paths(path):
81 if not os.path.isfile(p):
85 def read(self, path, info=None):
86 approach_path,retract_path,param_path = self._paths(path)
88 unlabeled_approach_data = numpy.loadtxt(
89 approach_path, dtype=numpy.uint16)
90 unlabeled_retract_data = numpy.loadtxt(
91 retract_path, dtype=numpy.uint16)
92 params = self._read_params(param_path)
93 params = self._translate_params(params)
95 # move data into Data blocks.
96 approach = self._scale_block(
97 unlabeled_approach_data, params, 'approach')
98 retract = self._scale_block(
99 unlabeled_retract_data, params, 'retract')
101 return ([approach, retract], info)
103 def _paths(self, path):
104 return (path+'_approach', path, path+'_param')
106 def _read_params(self, param_path):
108 for line in file(param_path):
109 ldata = [x.strip() for x in line.split(':', 1)]
110 if ldata[0] == 'Data fields':
111 params['columns'] = ldata[1].split()
112 elif len(ldata) == 2:
113 argwords = ldata[1].split()
114 if ldata[0] == 'Time' or len(argwords) != 1:
115 params[ldata[0]] = ldata[1]
116 else: # single word probably a number
117 params[ldata[0]] = float(ldata[1])
119 pass # ignore comment lines
122 def _translate_params(self, params):
123 ret = {'raw info':params,}
125 t = params['Time'] # 20100504135849
126 ret['time'] = self._time_from_localtime_string(t)
128 assert params['columns'] == ['Z_piezo_out', 'Deflection_in', 'Z_piezo_in'], \
129 'Unexpected columns: %s' % ret['columns']
130 ret['columns'] = ['z piezo (m)', 'deflection (m)', ]
132 calibcant_file = self._find_previous_cantilever_calibration_file(
134 calibcant_info = self._read_cantilever_calibration_file(calibcant_file)
135 ret['raw spring constant'] = calibcant_info
136 ret['spring constant (N/m)'] = calibcant_info['Cantilever k (N/m)']
137 ret['deflection sensitivity (m/V)'] = \
138 1.0/numpy.sqrt(calibcant_info['photoSensitivity**2 (V/nm)**2']) * 1e-9
140 # (32768 bits = 2**15 bits = 10 Volts)
141 ret['deflection sensitivity (V/bit)'] = 1.0/3276.8
142 ret['deflection range (V)'] = 20.0
143 ret['deflection offset (V)'] = 10.0 # assumes raw data is unsigned
145 ret['z piezo sensitivity (V/bit)'] = 1.0/3276.8 # output volts / bit
146 ret['z piezo range (V)'] = 20.0 # output volts
147 ret['z piezo offset (V)'] = 10.0 # output volts, assumes unsigned
148 ret['z piezo gain'] = \
149 params['Z piezo gain (Vp/Vo)'] # piezo volts / output volt
150 ret['z piezo sensitivity (m/V)'] = \
151 params['Z piezo sensitivity (nm/Vp)'] * 1e-9 # m / piezo volts
155 def _scale_block(self, data, info, name):
156 """Convert the block from its native format to a `numpy.float`
160 shape=(data.shape[0], 2),
162 info=copy.deepcopy(info)
164 ret.info['name'] = name
165 ret.info['raw data'] = data # store the raw data
166 ret.info['columns'] = ['z piezo (m)', 'deflection (m)']
169 # approach data does not have a Z_piezo_in column as of unfold v0.0.
170 z_rcol = info['raw info']['columns'].index('Z_piezo_out')
171 d_rcol = info['raw info']['columns'].index('Deflection_in')
173 # scaled column indices
174 z_scol = ret.info['columns'].index('z piezo (m)')
175 d_scol = ret.info['columns'].index('deflection (m)')
177 # Leading '-' because increasing voltage extends the piezo,
178 # moving the tip towards the surface (positive indentation),
179 # but it makes more sense to me to have it increase away from
180 # the surface (positive separation).
182 (data[:,z_rcol].astype(ret.dtype)
183 * info['z piezo sensitivity (V/bit)']
184 - info['z piezo offset (V)'])
185 * info['z piezo gain']
186 * info['z piezo sensitivity (m/V)']
189 # Leading '-' because deflection voltage increases as the tip
190 # moves away from the surface, but it makes more sense to me
191 # to have it increase as it moves toward the surface (positive
192 # tension on the protein chain).
195 * info['deflection sensitivity (V/bit)']
196 - info['deflection offset (V)'])
197 * info['deflection sensitivity (m/V)']
202 def _list_re_search(self, list, regexp):
203 "Return list entries matching re"
204 reg = re.compile(regexp)
211 def _list_cantilever_calibration_files(self, timestamp=None, basedir=None):
212 if timestamp == None:
213 timestamp = time.time()
215 basedir = self.config['cantilever calibration directory']
216 YYYYMMDD = time.strftime("%Y%m%d", time.localtime(timestamp))
217 dir = os.path.join(data_logger.normalize_logdir(basedir), YYYYMMDD)
218 if not os.path.exists(dir):
220 all_calibfiles = os.listdir(dir) # everything in the directory
221 #regexp = "%s.*_analysis_text " % (YYYYMMDD)
222 regexp = ".*_analysis_text"
223 calibfiles = self._list_re_search(all_calibfiles, regexp)
224 paths = [os.path.join(dir, cf) for cf in calibfiles]
227 def _calibfile_timestamp(self, path):
228 filename = os.path.basename(path)
229 YYYYMMDDHHMMSS = filename[0:14]
230 return self._time_from_localtime_string(YYYYMMDDHHMMSS)
232 def _find_previous_cantilever_calibration_file(
233 self, timestamp=None, basedir=None, previous_days=1):
235 If timestamp == None, uses current time.
236 Warning : brittle! depends on the default data_logger.py save filesystem.
237 Renaming files or moving directories will break me.
239 #if FORCED_CANTILEVER_CALIBRATION_FILE != None:
240 # return FORCED_CANTILEVER_CALIBRATION_FILE
242 for i in range(previous_days+1):
243 calibfiles.extend(self._list_cantilever_calibration_files(
244 timestamp-24*3600*i,basedir=basedir))
245 assert len(calibfiles) > 0 , \
246 "No calibration files in that day range in directory '%s'" % basedir
248 for i in range(len(calibfiles)):
249 if self._calibfile_timestamp(calibfiles[i]) > timestamp:
254 def _read_cantilever_calibration_file(self, filename):
255 ret = {'file': filename}
256 line_re = re.compile('(.*) *: (.*) [+]/- (.*) \((.*)\)\n')
257 for line in file(filename):
258 match = line_re.match(line)
261 'Invalid cantilever calibration line in %s: %s'
263 key,value,std_dev,rel_err = [
264 x.strip() for x in match.group(*range(1,5))]
265 if key == 'Variable (units)':
266 continue # ignore the header line
268 std_dev = float(std_dev)
269 # Handle older calibcant output.
271 key = 'Cantilever k (N/m)'
272 elif key == 'a**2 (V/nm)**2':
273 key = 'photoSensitivity**2 (V/nm)**2'
275 ret[key + ' (std. dev.)'] = std_dev
278 def _time_from_localtime_string(self, timestring, format="%Y%m%d%H%M%S"):
280 >>> print time.tzname
283 >>> d._time_from_localtime_string("19700101", format="%Y%m%d")/3600.0
285 >>> d._time_from_localtime_string("20081231", format="%Y%m%d")
287 >>> d._time_from_localtime_string("20090101", format="%Y%m%d")
290 timestruct = time.strptime(timestring, format)
291 timestamp = calendar.timegm(timestruct)
292 # Date strings are in localtime, so what we really want is
293 # .timelocale, but that doesn't exist. Workaround to convert
295 timestamp += time.timezone # assume no Daylight Savings Time (DST)
296 if bool(time.localtime(timestamp).tm_isdst) == True:
297 timestamp -= time.timezone - time.altzone # correct if DST
298 assert time.strftime(format, time.localtime(timestamp)) == timestring, "error in time_from_localtime_string, %s != %s" % (time.strftime(format, time.localtime(timestamp)), timestring)