Add os.path.expanduser() wrappers to user-supplied paths.
[hooke.git] / hooke / plugin / cut.py
index 975c2d3266e364140593b8760c17ba271bc24bdf..6aef07695bd38ea16ee8444c95d387a29c2f5e1c 100644 (file)
-# -*- coding: utf-8 -*-
-class cutCommands:
-
-    def _plug_init(self):
-        self.cut_basecurrent=None
-        self.cut_basepoints=None
-
-
-
-
-    def do_cut(self,args):
-        '''
-CUT
-        (cut.py)
-        Cut the selected signal between two points.
-        With the first parameter you have to select the signal (for FS for example
-        you can select with "0" the approacing curve and 1 for the retracting
-       curve. This depend also on how many set of data you have on the graph).
-        With the second parameter you select the output name file for the selection.
-       The data is arranged in two simple column without a header, the first column
-       is the "x" data and the second the "y".
-        -----------------
-        Syntax: distance "whatset" "namefile"
-        '''
-        if len(args)==0:
-               print "This command need the number of the graph that you want save and a name for the output file."
-               return
-       
-       a=args.split()
-       
-       
-       whatset=int(a[0])
-       outfile=a[1]
-       plot=self._get_displayed_plot()
-
-        print 'Select two points'
-        points=self._measure_N_points(N=2, whatset=whatset)
-       minbound=min(points[0].index, points[1].index)
-       maxbound=max(points[0].index, points[1].index)
-        boundpoints=[minbound, maxbound]
-       yarr=plot.vectors[whatset][1][boundpoints[0]:boundpoints[1]]
-       xarr=plot.vectors[whatset][0][boundpoints[0]:boundpoints[1]]
-
-       f=open(outfile,'w+')
-       for i in range(len(yarr)):
-               f.write(str(xarr[i])+";"+str(yarr[i])+"\n")
-        f.close()
+# Copyright (C) 2009-2010 Fabrizio Benedetti
+#                         Massimo Sandal <devicerandom@gmail.com>
+#                         W. Trevor King <wking@drexel.edu>
+#
+# 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 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
+# <http://www.gnu.org/licenses/>.
+
+"""The `cut` module provides :class:`CutPlugin` and
+:class:`CutCommand`.
+"""
+
+import os.path
+
+import numpy
+
+from ..command import Command, Argument, Failure
+from . import Plugin
+
+
+class CutPlugin (Plugin):
+    def __init__(self):
+        super(CutPlugin, self).__init__(name='cut')
+        self._commands = [CutCommand(self)]
+
+
+# Define common or complicated arguments
 
+def current_curve_callback(hooke, command, argument, value):
+    playlist = hooke.playlists.current()
+    if playlist == None:
+        raise Failure('No playlists loaded')
+    curve = playlist.current()
+    if curve == None:
+        raise Failure('No curves in playlist %s' % playlist.name)
+    return curve
 
+CurveArgument = Argument(
+    name='curve', type='curve', callback=current_curve_callback,
+    help="""
+:class:`hooke.curve.Curve` to cut from.  Defaults to the current curve.
+""".strip())
 
+
+# Define commands
+
+class CutCommand (Command):
+    """Cut the selected signal between two points and write it to a file.
+
+    The data is saved in TAB-delimited ASCII text.  A "#" prefixed
+    header will optionally appear at the beginning of the file naming
+    the columns.
+    """
+    def __init__(self, plugin):
+        super(CutCommand, self).__init__(
+            name='cut',
+            arguments=[
+                CurveArgument,
+                Argument(name='block', aliases=['set'], type='int', default=0,
+                    help="""
+Data block to save.  For an approach/retract force curve, `0` selects
+the approaching curve and `1` selects the retracting curve.
+""".strip()),
+                Argument(name='bounds', type='point', optional=False, count=2,
+                         help="""
+Indicies of points bounding the selected data.
+""".strip()),
+                Argument(name='output', type='file', default='cut.dat',
+                         help="""
+File name for the output data.
+""".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):
+        if params['curve'] == None:
+            params['curve'] = hooke.playlists.current().current()
+
+       i_min = min([p.index for p in params['points']])
+       i_max = max([p.index for p in params['points']])
+
+       data = params['curve'][params['bound']]
+        cut_data = data[i_min:i_max+1,:] # slice rows from row-major data
+        # +1 to include data[i_max] row
+
+        f = open(os.path.expanduser(params['output']), 'w')
+        if params['header'] == True:
+            f.write('# %s \n' % ('\t'.join(cut_data.info['columns'])))
+        numpy.savetxt(f, cut_data, delimiter='\t')
+        f.close()