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
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation, either
11 # version 3 of the License, or (at your option) any later version.
13 # Hooke is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU Lesser General 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
37 class CurvePlugin (Builtin):
39 super(CurvePlugin, self).__init__(name='curve')
41 InfoCommand(self), ExportCommand(self),
42 DifferenceCommand(self), DerivativeCommand(self),
43 PowerSpectrumCommand(self)]
46 # Define common or complicated arguments
48 def current_curve_callback(hooke, command, argument, value):
51 playlist = current_playlist_callback(hooke, command, argument, value)
52 curve = playlist.current()
54 raise Failure('No curves in %s' % playlist)
57 CurveArgument = Argument(
58 name='curve', type='curve', callback=current_curve_callback,
60 :class:`hooke.curve.Curve` to act on. Defaults to the current curve
61 of the current playlist.
67 class InfoCommand (Command):
68 """Get selected information about a :class:`hooke.curve.Curve`.
70 def __init__(self, plugin):
73 Argument(name='all', type='bool', default=False, count=1,
74 help='Get all curve information.'),
76 self.fields = ['name', 'path', 'experiment', 'driver', 'filetype', 'note',
77 'blocks', 'block sizes']
78 for field in self.fields:
80 name=field, type='bool', default=False, count=1,
81 help='Get curve %s' % field))
82 super(InfoCommand, self).__init__(
83 name='curve info', arguments=args,
84 help=self.__doc__, plugin=plugin)
86 def _run(self, hooke, inqueue, outqueue, params):
88 for key in self.fields:
89 fields[key] = params[key]
90 if reduce(lambda x,y: x and y, fields.values()) == False:
91 params['all'] = True # No specific fields set, default to 'all'
92 if params['all'] == True:
93 for key in self.fields:
96 for key in self.fields:
97 if fields[key] == True:
98 get = getattr(self, '_get_%s' % key.replace(' ', '_'))
99 lines.append('%s: %s' % (key, get(params['curve'])))
100 outqueue.put('\n'.join(lines))
102 def _get_name(self, curve):
105 def _get_path(self, curve):
108 def _get_experiment(self, curve):
109 return curve.info.get('experiment', None)
111 def _get_driver(self, curve):
114 def _get_filetype(self, curve):
115 return curve.info.get('filetype', None)
117 def _get_note(self, curve):
118 return curve.info.get('note', None)
120 def _get_blocks(self, curve):
121 return len(curve.data)
123 def _get_block_sizes(self, curve):
124 return [block.shape for block in curve.data]
126 class ExportCommand (Command):
127 """Export a :class:`hooke.curve.Curve` data block as TAB-delimeted
130 A "#" prefixed header will optionally appear at the beginning of
131 the file naming the columns.
133 def __init__(self, plugin):
134 super(ExportCommand, self).__init__(
138 Argument(name='block', aliases=['set'], type='int', default=0,
140 Data block to save. For an approach/retract force curve, `0` selects
141 the approaching curve and `1` selects the retracting curve.
143 Argument(name='output', type='file', default='curve.dat',
145 File name for the output data. Defaults to 'curve.dat'
147 Argument(name='header', type='bool', default=True,
149 True if you want the column-naming header line.
152 help=self.__doc__, plugin=plugin)
154 def _run(self, hooke, inqueue, outqueue, params):
155 data = params['curve'].data[int(params['block'])] # HACK, int() should be handled by ui
157 f = open(params['output'], 'w')
158 if params['header'] == True:
159 f.write('# %s \n' % ('\t'.join(data.info['columns'])))
160 numpy.savetxt(f, data, delimiter='\t')
163 class DifferenceCommand (Command):
164 """Calculate the derivative (actually, the discrete differentiation)
165 of a curve data block.
167 See :func:`hooke.util.calculus.derivative` for implementation
170 def __init__(self, plugin):
171 super(DifferenceCommand, self).__init__(
172 name='block difference',
175 Argument(name='block one', aliases=['set one'], type='int',
178 Block A in A-B. For an approach/retract force curve, `0` selects the
179 approaching curve and `1` selects the retracting curve.
181 Argument(name='block two', aliases=['set two'], type='int',
183 help='Block B in A-B.'),
184 Argument(name='x column', type='int', default=0,
186 Column of data block to differentiate with respect to.
188 Argument(name='f column', type='int', default=1,
190 Column of data block to differentiate.
193 help=self.__doc__, plugin=plugin)
195 def _run(self, hooke, inqueue, outqueue, params):
196 a = params['curve'].data[params['block one']]
197 b = params['curve'].data[params['block two']]
198 assert a[:,params['x column']] == b[:,params['x column']]
199 out = Data((a.shape[0],2), dtype=a.dtype)
200 out[:,0] = a[:,params['x column']]
201 out[:,1] = a[:,params['f column']] - b[:,params['f column']]
204 class DerivativeCommand (Command):
205 """Calculate the difference between two blocks of data.
207 def __init__(self, plugin):
208 super(DerivativeCommand, self).__init__(
209 name='block derivative',
212 Argument(name='block', aliases=['set'], type='int', default=0,
214 Data block to differentiate. For an approach/retract force curve, `0`
215 selects the approaching curve and `1` selects the retracting curve.
217 Argument(name='x column', type='int', default=0,
219 Column of data block to differentiate with respect to.
221 Argument(name='f column', type='int', default=1,
223 Column of data block to differentiate.
225 Argument(name='weights', type='dict', default={-1:-0.5, 1:0.5},
227 Weighting scheme dictionary for finite differencing. Defaults to
228 central differencing.
231 help=self.__doc__, plugin=plugin)
233 def _run(self, hooke, inqueue, outqueue, params):
234 data = params['curve'].data[params['block']]
235 outqueue.put(derivative(
236 block, x_col=params['x column'], f_col=params['f column'],
237 weights=params['weights']))
239 class PowerSpectrumCommand (Command):
240 """Calculate the power spectrum of a data block.
242 def __init__(self, plugin):
243 super(PowerSpectrumCommand, self).__init__(
244 name='block power spectrum',
247 Argument(name='block', aliases=['set'], type='int', default=0,
249 Data block to act on. For an approach/retract force curve, `0`
250 selects the approaching curve and `1` selects the retracting curve.
252 Argument(name='f column', type='int', default=1,
254 Column of data block to differentiate with respect to.
256 Argument(name='freq', type='float', default=1.0,
260 Argument(name='chunk size', type='int', default=2048,
262 Number of samples per chunk. Use a power of two.
264 Argument(name='overlap', type='bool', default=False,
266 If `True`, each chunk overlaps the previous chunk by half its length.
267 Otherwise, the chunks are end-to-end, and not overlapping.
270 help=self.__doc__, plugin=plugin)
272 def _run(self, hooke, inqueue, outqueue, params):
273 data = params['curve'].data[params['block']]
274 outqueue.put(unitary_avg_power_spectrum(
275 data[:,params['f column']], freq=params['freq'],
276 chunk_size=params['chunk size'],
277 overlap=params['overlap']))