1 # Copyright (C) 2008-2010 Massimo Sandal <devicerandom@gmail.com>
2 # W. Trevor King <wking@drexel.edu>
4 # This file is part of Hooke.
6 # Hooke is free software: you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation, either
9 # version 3 of the License, or (at your option) any later version.
11 # Hooke is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU Lesser General Public License for more details.
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with Hooke. If not, see
18 # <http://www.gnu.org/licenses/>.
20 """Driver for JPK ForceRobot's velocity clamp data format.
30 from .. import curve as curve
31 from .. import experiment as experiment
32 from . import Driver as Driver
35 class Closing (object):
36 """Add .__enter__() .__exit__() for `with` statements.
40 def __init__(self, obj):
46 def __exit__(self, *exc_info):
48 close_it = self.obj.close
49 except AttributeError:
55 class JPKDriver (Driver):
56 """Handle JPK ForceRobot's data format.
59 super(JPKDriver, self).__init__(name='jpk')
61 def is_me(self, path):
62 if zipfile.is_zipfile(path): # JPK file versions since at least 0.5
63 with Closing(zipfile.ZipFile(path, 'r')) as f:
64 if 'header.properties' not in f.namelist():
66 with Closing(f.open('header.properties')) as h:
67 if 'jpk-data-file' in h.read():
70 with Closing(open(path, 'r')) as f:
73 headlines.append(f.readline())
74 if headlines[0].startswith('# xPosition') \
75 and headlines[1].startswith('# yPosition'):
80 if zipfile.is_zipfile(path): # JPK file versions since at least 0.5
81 return self._read_zip(path)
83 return self._read_old(path)
85 def _read_zip(self, path):
86 with Closing(zipfile.ZipFile(path, 'r')) as f:
88 info = self._zip_info(f)
89 approach = self._zip_segment(f, info, 0)
90 retract = self._zip_segment(f, info, 1)
91 assert approach.info['name'] == 'approach', approach.info['name']
92 assert retract.info['name'] == 'retract', retract.info['name']
93 return ([approach, retract],
94 self._zip_translate_params(info, retract.info['raw info']))
96 def _zip_info(self, zipfile):
97 with Closing(zipfile.open('header.properties')) as f:
98 info = self._parse_params(f.readlines())
101 def _zip_segment(self, zipfile, info, index):
102 prop_file = zipfile.open(os.path.join(
103 'segments', str(index), 'segment-header.properties'))
104 prop = self._parse_params(prop_file.readlines())
106 expected_shape = (int(prop['force-segment-header']['num-points']),)
108 for chan in prop['channels']['list']:
109 chan_info = prop['channel'][chan]
110 channels.append(self._zip_channel(zipfile, index, chan, chan_info))
111 if channels[-1].shape != expected_shape:
112 raise NotImplementedError(
113 'Channel %d:%s in %s has strange shape %s != %s'
114 % (index, chan, zipfile.path,
115 channels[-1].shape, expected_shape))
117 shape=(len(channels[0]), len(channels)),
118 dtype=channels[0].dtype,
119 info=self._zip_translate_segment_params(prop))
120 for i,chan in enumerate(channels):
122 return self._zip_scale_segment(d)
124 def _zip_channel(self, zipfile, segment_index, channel_name, chan_info):
125 f = zipfile.open(os.path.join(
126 'segments', str(segment_index),
127 chan_info['data']['file']['name']), 'r')
128 assert chan_info['data']['file']['format'] == 'raw', \
129 'Non-raw data format:\n%s' % pprint.pformat(chan_info)
130 assert chan_info['data']['type'] == 'float-data', \
131 'Non-float data format:\n%s' % pprint.pformat(chan_info)
132 data = numpy.frombuffer(
134 dtype=numpy.dtype(numpy.float32).newbyteorder('>'),
135 # Is JPK data always big endian? I can't find a config
136 # setting. The ForceRobot brochure
137 # http://www.jpk.com/forcerobot300-1.download.6d694150f14773dc76bc0c3a8a6dd0e8.pdf
138 # lists a PowerPC chip on page 4, under Control
139 # electronics, and PPCs are usually big endian.
140 # http://en.wikipedia.org/wiki/PowerPC#Endian_modes
145 def _zip_translate_params(self, params, chan_info):
148 #'time':self._time_from_TODO(raw_info[]),
150 force_unit = chan_info['channel']['vDeflection']['conversion-set']['conversion']['force']['scaling']['unit']['unit']
151 assert force_unit == 'N', force_unit
152 force_base = chan_info['channel']['vDeflection']['conversion-set']['conversion']['force']['base-calibration-slot']
153 assert force_base == 'distance', force_base
154 dist_unit = chan_info['channel']['vDeflection']['conversion-set']['conversion']['distance']['scaling']['unit']['unit']
155 assert dist_unit == 'm', dist_unit
157 chan_info['channel']['vDeflection']['conversion-set']['conversion']['force']['scaling']['multiplier'])
158 info['spring constant (N/m)'] = force_mult
161 def _zip_translate_segment_params(self, params):
164 'columns':list(params['channels']['list']),
165 'name':params['force-segment-header']['name']['name'],
167 if info['name'] == 'extend-spm':
168 info['name'] = 'approach'
169 elif info['name'] == 'retract-spm':
170 info['name'] = 'retract'
172 raise NotImplementedError(
173 'Unrecognized segment type %s' % info['name'])
176 def _zip_scale_segment(self, segment):
182 segment.info['raw data'] = data
185 channels = segment.info['raw info']['channels']['list']
186 z_col = channels.index('height')
187 d_col = channels.index('vDeflection')
189 segment = self._zip_scale_channel(segment, z_col, 'calibrated')
190 segment = self._zip_scale_channel(segment, d_col, 'distance')
192 assert segment.info['columns'][z_col] == 'height (m)', \
193 segment.info['columns'][z_col]
194 assert segment.info['columns'][d_col] == 'vDeflection (m)', \
195 segment.info['columns'][d_col]
197 # scaled column indices same as raw column indices,
198 # because columns is a copy of channels.list
199 segment.info['columns'][z_col] = 'z piezo (m)'
200 segment.info['columns'][d_col] = 'deflection (m)'
203 def _zip_scale_channel(self, segment, channel, conversion):
204 channel_name = segment.info['raw info']['channels']['list'][channel]
205 conversion_set = segment.info['raw info']['channel'][channel_name]['conversion-set']
206 conversion_info = conversion_set['conversion'][conversion]
207 if conversion_info['base-calibration-slot'] \
208 != conversion_set['conversions']['base']:
209 # Our conversion is stacked on a previous conversion. Do
210 # the previous conversion first.
211 segment = self._zip_scale_channel(
212 segment, channel, conversion_info['base-calibration-slot'])
213 if conversion_info['type'] == 'file':
214 if os.path.exists(conversion_info['file']):
215 raise NotImplementedError('No calibration files were available for testing')
217 log = logging.getLogger('hooke')
219 'Skipping %s -> %s calibration for %s channel. Calibration file %s not found'
220 % (conversion_info['base-calibration-slot'],
221 conversion, channel_name, conversion_info['file']))
223 assert conversion_info['type'] == 'simple', conversion_info['type']
224 assert conversion_info['scaling']['type'] == 'linear', \
225 conversion_info['scaling']['type']
226 assert conversion_info['scaling']['style'] == 'offsetmultiplier', \
227 conversion_info['scaling']['style']
228 multiplier = float(conversion_info['scaling']['multiplier'])
229 offset = float(conversion_info['scaling']['offset'])
230 unit = conversion_info['scaling']['unit']['unit']
231 segment[:,channel] = segment[:,channel] * multiplier + offset
232 segment.info['columns'][channel] = '%s (%s)' % (channel_name, unit)
235 def _parse_params(self, lines):
239 if line.startswith('#'):
242 # e.g.: force-segment-header.type=xy-position-segment-header
243 fields = line.split('=', 1)
244 assert len(fields) == 2, line
245 setting = fields[0].split('.')
246 sub_info = info # drill down, e.g. info['force-s..']['type']
247 for s in setting[:-1]:
248 if s not in sub_info:
250 sub_info = sub_info[s]
251 if setting[-1] == 'list': # split a space-delimited list
252 sub_info[setting[-1]] = fields[1].split(' ')
254 sub_info[setting[-1]] = fields[1]
257 def _read_old(self, path):
258 raise NotImplementedError('No old-style JPK files were available for testing, please send us yours: %s' % path)