1 # Copyright (C) 2008-2010 Alberto Gomez-Casado
3 # Massimo Sandal <devicerandom@gmail.com>
4 # W. Trevor King <wking@drexel.edu>
6 # This file is part of Hooke.
8 # Hooke is free software: you can redistribute it and/or modify it
9 # under the terms of the GNU Lesser General Public License as
10 # published by the Free Software Foundation, either version 3 of the
11 # License, or (at your option) any later version.
13 # Hooke is distributed in the hope that it will be useful, but WITHOUT
14 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
15 # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
16 # Public License for more details.
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with Hooke. If not, see
20 # <http://www.gnu.org/licenses/>.
22 """The ``curve`` module provides :class:`CurvePlugin` and several
23 associated :class:`hooke.command.Command`\s for handling
24 :mod:`hooke.curve` classes.
29 from ..command import Command, Argument, Failure
30 from ..curve import Data
31 from ..plugin import Builtin
32 from ..plugin.playlist import current_playlist_callback
33 from ..util.calculus import derivative
34 from ..util.fft import unitary_avg_power_spectrum
35 from ..util.si import ppSI, join_data_label, split_data_label
39 class CurvePlugin (Builtin):
41 super(CurvePlugin, self).__init__(name='curve')
43 GetCommand(self), InfoCommand(self), DeltaCommand(self),
44 ExportCommand(self), DifferenceCommand(self),
45 DerivativeCommand(self), PowerSpectrumCommand(self)]
48 # Define common or complicated arguments
50 def current_curve_callback(hooke, command, argument, value):
53 playlist = current_playlist_callback(hooke, command, argument, value)
54 curve = playlist.current()
56 raise Failure('No curves in %s' % playlist)
59 CurveArgument = Argument(
60 name='curve', type='curve', callback=current_curve_callback,
62 :class:`hooke.curve.Curve` to act on. Defaults to the current curve
63 of the current playlist.
69 class GetCommand (Command):
70 """Return a :class:`hooke.curve.Curve`.
72 def __init__(self, plugin):
73 super(GetCommand, self).__init__(
74 name='get curve', arguments=[CurveArgument],
75 help=self.__doc__, plugin=plugin)
77 def _run(self, hooke, inqueue, outqueue, params):
78 outqueue.put(params['curve'])
80 class InfoCommand (Command):
81 """Get selected information about a :class:`hooke.curve.Curve`.
83 def __init__(self, plugin):
86 Argument(name='all', type='bool', default=False, count=1,
87 help='Get all curve information.'),
89 self.fields = ['name', 'path', 'experiment', 'driver', 'filetype', 'note',
90 'blocks', 'block sizes']
91 for field in self.fields:
93 name=field, type='bool', default=False, count=1,
94 help='Get curve %s' % field))
95 super(InfoCommand, self).__init__(
96 name='curve info', arguments=args,
97 help=self.__doc__, plugin=plugin)
99 def _run(self, hooke, inqueue, outqueue, params):
101 for key in self.fields:
102 fields[key] = params[key]
103 if reduce(lambda x,y: x and y, fields.values()) == False:
104 params['all'] = True # No specific fields set, default to 'all'
105 if params['all'] == True:
106 for key in self.fields:
109 for key in self.fields:
110 if fields[key] == True:
111 get = getattr(self, '_get_%s' % key.replace(' ', '_'))
112 lines.append('%s: %s' % (key, get(params['curve'])))
113 outqueue.put('\n'.join(lines))
115 def _get_name(self, curve):
118 def _get_path(self, curve):
121 def _get_experiment(self, curve):
122 return curve.info.get('experiment', None)
124 def _get_driver(self, curve):
127 def _get_filetype(self, curve):
128 return curve.info.get('filetype', None)
130 def _get_note(self, curve):
131 return curve.info.get('note', None)
133 def _get_blocks(self, curve):
134 return len(curve.data)
136 def _get_block_sizes(self, curve):
137 return [block.shape for block in curve.data]
140 class DeltaCommand (Command):
141 """Get distance information between two points.
143 With two points A and B, the returned distances are A-B.
145 def __init__(self, plugin):
146 super(DeltaCommand, self).__init__(
150 Argument(name='block', type='int', default=0,
152 Data block that points are selected from. For an approach/retract
153 force curve, `0` selects the approaching curve and `1` selects the
156 Argument(name='point', type='point', optional=False, count=2,
158 Indicies of points bounding the selected data.
160 Argument(name='SI', type='bool', default=False,
162 Return distances in SI notation.
165 help=self.__doc__, plugin=plugin)
167 def _run(self, hooke, inqueue, outqueue, params):
168 data = params['curve'].data[params['block']]
169 As = data[params['point'][0],:]
170 Bs = data[params['point'][1],:]
171 ds = [A-B for A,B in zip(As, Bs)]
172 if params['SI'] == False:
173 out = [(name, d) for name,d in zip(data.info['columns'], ds)]
176 for name,d in zip(data.info['columns'], ds):
177 n,units = split_data_label(name)
179 (n, ppSI(value=d, unit=units, decimals=2)))
183 class ExportCommand (Command):
184 """Export a :class:`hooke.curve.Curve` data block as TAB-delimeted
187 A "#" prefixed header will optionally appear at the beginning of
188 the file naming the columns.
190 def __init__(self, plugin):
191 super(ExportCommand, self).__init__(
195 Argument(name='block', aliases=['set'], type='int', default=0,
197 Data block to save. For an approach/retract force curve, `0` selects
198 the approaching curve and `1` selects the retracting curve.
200 Argument(name='output', type='file', default='curve.dat',
202 File name for the output data. Defaults to 'curve.dat'
204 Argument(name='header', type='bool', default=True,
206 True if you want the column-naming header line.
209 help=self.__doc__, plugin=plugin)
211 def _run(self, hooke, inqueue, outqueue, params):
212 data = params['curve'].data[params['block']]
214 f = open(params['output'], 'w')
215 if params['header'] == True:
216 f.write('# %s \n' % ('\t'.join(data.info['columns'])))
217 numpy.savetxt(f, data, delimiter='\t')
220 class DifferenceCommand (Command):
221 """Calculate the difference between two blocks of data.
223 def __init__(self, plugin):
224 super(DifferenceCommand, self).__init__(
225 name='block difference',
228 Argument(name='block one', aliases=['set one'], type='int',
231 Block A in A-B. For an approach/retract force curve, `0` selects the
232 approaching curve and `1` selects the retracting curve.
234 Argument(name='block two', aliases=['set two'], type='int',
236 help='Block B in A-B.'),
237 Argument(name='x column', type='int', default=0,
239 Column of data to return as x values.
241 Argument(name='y column', type='int', default=1,
243 Column of data block to difference.
246 help=self.__doc__, plugin=plugin)
248 def _run(self, hooke, inqueue, outqueue, params):
249 a = params['curve'].data[params['block one']]
250 b = params['curve'].data[params['block two']]
251 assert a[:,params['x column']] == b[:,params['x column']]
252 out = Data((a.shape[0],2), dtype=a.dtype)
253 out[:,0] = a[:,params['x column']]
254 out[:,1] = a[:,params['y column']] - b[:,params['y column']]
257 class DerivativeCommand (Command):
258 """Calculate the derivative (actually, the discrete differentiation)
259 of a curve data block.
261 See :func:`hooke.util.calculus.derivative` for implementation
264 def __init__(self, plugin):
265 super(DerivativeCommand, self).__init__(
266 name='block derivative',
269 Argument(name='block', aliases=['set'], type='int', default=0,
271 Data block to differentiate. For an approach/retract force curve, `0`
272 selects the approaching curve and `1` selects the retracting curve.
274 Argument(name='x column', type='int', default=0,
276 Column of data block to differentiate with respect to.
278 Argument(name='f column', type='int', default=1,
280 Column of data block to differentiate.
282 Argument(name='weights', type='dict', default={-1:-0.5, 1:0.5},
284 Weighting scheme dictionary for finite differencing. Defaults to
285 central differencing.
288 help=self.__doc__, plugin=plugin)
290 def _run(self, hooke, inqueue, outqueue, params):
291 data = params['curve'].data[params['block']]
292 outqueue.put(derivative(
293 block, x_col=params['x column'], f_col=params['f column'],
294 weights=params['weights']))
296 class PowerSpectrumCommand (Command):
297 """Calculate the power spectrum of a data block.
299 def __init__(self, plugin):
300 super(PowerSpectrumCommand, self).__init__(
301 name='block power spectrum',
304 Argument(name='block', aliases=['set'], type='int', default=0,
306 Data block to act on. For an approach/retract force curve, `0`
307 selects the approaching curve and `1` selects the retracting curve.
309 Argument(name='column', type='string', optional=False,
311 Name of the data block column containing to-be-transformed data.
313 Argument(name='bounds', type='point', optional=True, count=2,
315 Indicies of points bounding the selected data.
317 Argument(name='freq', type='float', default=1.0,
321 Argument(name='freq units', type='string', default='Hz',
323 Units for the sampling frequency.
325 Argument(name='chunk size', type='int', default=2048,
327 Number of samples per chunk. Use a power of two.
329 Argument(name='overlap', type='bool', default=False,
331 If `True`, each chunk overlaps the previous chunk by half its length.
332 Otherwise, the chunks are end-to-end, and not overlapping.
334 Argument(name='output block name', type='string',
335 default='power spectrum',
337 Name of the new data block (without `of <source block name> <source column name>`) for storing the power spectrum.
340 help=self.__doc__, plugin=plugin)
342 def _run(self, hooke, inqueue, outqueue, params):
343 data = params['curve'].data[params['block']]
344 col = data.info['columns'].index(params['column'])
347 d = d[params['bounds'][0]:params['bounds'][1]]
348 freq_axis,power = unitary_avg_power_spectrum(
349 d, freq=params['freq'],
350 chunk_size=params['chunk size'],
351 overlap=params['overlap'])
352 name,data_units = split_data_label(params['column'])
353 b = Data((len(freq_axis),2), dtype=data.dtype)
354 b.info['name'] = '%s of %s %s' % (
355 params['output block name'], data.info['name'], params['column'])
356 b.info['columns'] = [
357 join_data_label('frequency axis', params['freq units']),
358 join_data_label('power density',
359 '%s^2/%s' % (data_units, params['freq units'])),
363 params['curve'].data.append(b)