Update SurfaceContactCommand to use flexible column/info names.
[hooke.git] / hooke / plugin / curve.py
index b93ccbc81e2c8a954c3590c69b1ca91af8b7bee7..3208afad5ece570529465db55df27c2bae74c6e5 100644 (file)
@@ -5,15 +5,15 @@
 #
 # This file is part of Hooke.
 #
-# Hooke is free software: you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation, either
-# version 3 of the License, or (at your option) any later version.
+# Hooke is free software: you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
 #
-# Hooke is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU Lesser General Public License for more details.
+# Hooke is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General
+# Public License for more details.
 #
 # You should have received a copy of the GNU Lesser General Public
 # License along with Hooke.  If not, see
@@ -24,21 +24,24 @@ associated :class:`hooke.command.Command`\s for handling
 :mod:`hooke.curve` classes.
 """
 
+import numpy
+
 from ..command import Command, Argument, Failure
 from ..curve import Data
 from ..plugin import Builtin
 from ..plugin.playlist import current_playlist_callback
 from ..util.calculus import derivative
 from ..util.fft import unitary_avg_power_spectrum
+from ..util.si import ppSI, split_data_label
 
 
 class CurvePlugin (Builtin):
     def __init__(self):
         super(CurvePlugin, self).__init__(name='curve')
         self._commands = [
-            InfoCommand(self), ExportCommand(self),
-            DifferenceCommand(self), DerivativeCommand(self),
-            PowerSpectrumCommand(self)]
+            GetCommand(self), InfoCommand(self), DeltaCommand(self),
+            ExportCommand(self), DifferenceCommand(self),
+            DerivativeCommand(self), PowerSpectrumCommand(self)]
 
 
 # Define common or complicated arguments
@@ -62,6 +65,17 @@ of the current playlist.
 
 # Define commands
 
+class GetCommand (Command):
+    """Return a :class:`hooke.curve.Curve`.
+    """
+    def __init__(self, plugin):
+        super(GetCommand, self).__init__(
+            name='get curve', arguments=[CurveArgument],
+            help=self.__doc__, plugin=plugin)
+
+    def _run(self, hooke, inqueue, outqueue, params):
+        outqueue.put(params['curve'])
+
 class InfoCommand (Command):
     """Get selected information about a :class:`hooke.curve.Curve`.
     """
@@ -121,9 +135,56 @@ class InfoCommand (Command):
     def _get_block_sizes(self, curve):
         return [block.shape for block in curve.data]
 
+
+class DeltaCommand (Command):
+    """Get distance information between two points.
+
+    With two points A and B, the returned distances are A-B.
+    """
+    def __init__(self, plugin):
+        super(DeltaCommand, self).__init__(
+            name='delta',
+            arguments=[
+                CurveArgument,
+                Argument(name='block', type='int', default=0,
+                    help="""
+Data block that points are selected from.  For an approach/retract
+force curve, `0` selects the approaching curve and `1` selects the
+retracting curve.
+""".strip()),
+                Argument(name='point', type='point', optional=False, count=2,
+                         help="""
+Indicies of points bounding the selected data.
+""".strip()),
+                Argument(name='SI', type='bool', default=False,
+                         help="""
+Return distances in SI notation.
+""".strip())
+                ],
+            help=self.__doc__, plugin=plugin)
+
+    def _run(self, hooke, inqueue, outqueue, params):
+        data = params['curve'].data[params['block']]
+        As = data[params['point'][0],:]
+        Bs = data[params['point'][1],:]
+        ds = [A-B for A,B in zip(As, Bs)]
+        if params['SI'] == False:
+            out = [(name, d) for name,d in zip(data.info['columns'], ds)]
+        else:
+            out = []
+            for name,d in zip(data.info['columns'], ds):
+                n,units = split_data_label(name)
+                out.append(
+                  (n, ppSI(value=d, unit=units, decimals=2)))
+        outqueue.put(out)
+
+
 class ExportCommand (Command):
     """Export a :class:`hooke.curve.Curve` data block as TAB-delimeted
     ASCII text.
+
+    A "#" prefixed header will optionally appear at the beginning of
+    the file naming the columns.
     """
     def __init__(self, plugin):
         super(ExportCommand, self).__init__(
@@ -133,27 +194,30 @@ class ExportCommand (Command):
                 Argument(name='block', aliases=['set'], type='int', default=0,
                          help="""
 Data block to save.  For an approach/retract force curve, `0` selects
-the approacing curve and `1` selects the retracting curve.
+the approaching curve and `1` selects the retracting curve.
 """.strip()),
                 Argument(name='output', type='file', default='curve.dat',
                          help="""
 File name for the output data.  Defaults to 'curve.dat'
+""".strip()),
+                Argument(name='header', type='bool', default=True,
+                         help="""
+True if you want the column-naming header line.
 """.strip()),
                 ],
             help=self.__doc__, plugin=plugin)
 
     def _run(self, hooke, inqueue, outqueue, params):
         data = params['curve'].data[params['block']]
+
         f = open(params['output'], 'w')
-        data.tofile(f, sep='\t')
+        if params['header'] == True:
+            f.write('# %s \n' % ('\t'.join(data.info['columns'])))
+        numpy.savetxt(f, data, delimiter='\t')
         f.close()
 
 class DifferenceCommand (Command):
-    """Calculate the derivative (actually, the discrete differentiation)
-    of a curve data block.
-
-    See :func:`hooke.util.calculus.derivative` for implementation
-    details.
+    """Calculate the difference between two blocks of data.
     """
     def __init__(self, plugin):
         super(DifferenceCommand, self).__init__(
@@ -164,18 +228,18 @@ class DifferenceCommand (Command):
                          default=1,
                          help="""
 Block A in A-B.  For an approach/retract force curve, `0` selects the
-approacing curve and `1` selects the retracting curve.
+approaching curve and `1` selects the retracting curve.
 """.strip()),
                 Argument(name='block two', aliases=['set two'], type='int',
                          default=0,
                          help='Block B in A-B.'),
                 Argument(name='x column', type='int', default=0,
                          help="""
-Column of data block to differentiate with respect to.
+Column of data to return as x values.
 """.strip()),
-                Argument(name='f column', type='int', default=1,
+                Argument(name='y column', type='int', default=1,
                          help="""
-Column of data block to differentiate.
+Column of data block to difference.
 """.strip()),
                 ],
             help=self.__doc__, plugin=plugin)
@@ -186,11 +250,15 @@ Column of data block to differentiate.
         assert a[:,params['x column']] == b[:,params['x column']]
         out = Data((a.shape[0],2), dtype=a.dtype)
         out[:,0] = a[:,params['x column']]
-        out[:,1] = a[:,params['f column']] - b[:,params['f column']]
+        out[:,1] = a[:,params['y column']] - b[:,params['y column']]
         outqueue.put(out)
 
 class DerivativeCommand (Command):
-    """Calculate the difference between two blocks of data.
+    """Calculate the derivative (actually, the discrete differentiation)
+    of a curve data block.
+
+    See :func:`hooke.util.calculus.derivative` for implementation
+    details.
     """
     def __init__(self, plugin):
         super(DerivativeCommand, self).__init__(
@@ -200,7 +268,7 @@ class DerivativeCommand (Command):
                 Argument(name='block', aliases=['set'], type='int', default=0,
                          help="""
 Data block to differentiate.  For an approach/retract force curve, `0`
-selects the approacing curve and `1` selects the retracting curve.
+selects the approaching curve and `1` selects the retracting curve.
 """.strip()),
                 Argument(name='x column', type='int', default=0,
                          help="""
@@ -235,11 +303,11 @@ class PowerSpectrumCommand (Command):
                 Argument(name='block', aliases=['set'], type='int', default=0,
                          help="""
 Data block to act on.  For an approach/retract force curve, `0`
-selects the approacing curve and `1` selects the retracting curve.
+selects the approaching curve and `1` selects the retracting curve.
 """.strip()),
-                Argument(name='column', type='int', default=1,
+                Argument(name='column', type='int', default=1,
                          help="""
-Column of data block to differentiate with respect to.
+Column of data block containing time-series data.
 """.strip()),
                 Argument(name='freq', type='float', default=1.0,
                          help="""
@@ -260,6 +328,6 @@ Otherwise, the chunks are end-to-end, and not overlapping.
     def _run(self, hooke, inqueue, outqueue, params):
         data = params['curve'].data[params['block']]
         outqueue.put(unitary_avg_power_spectrum(
-                data[:,params['column']], freq=params['freq'],
+                data[:,params['column']], freq=params['freq'],
                 chunk_size=params['chunk size'],
                 overlap=params['overlap']))