Commits

Anonymous committed 9b05475

adding wfdb, cvrg wrappers

  • Participants
  • Parent commits e17f08e
  • Branches staging20130912

Comments (0)

Files changed (8)

tools/wfdb/ann2rr.xml

+<?xml version="1.0"?>
+
+<tool name="ann2rr" id="ann2rr_id">
+  <description>
+    convert annotation files to interval lists
+  </description>
+  <requirements>
+    <requirement type="package">wfdb</requirement>
+  <requirements>
+
+  <command interpreter='python'>
+     wfdb_wrapper.py
+   --program ann2rr
+   --record $record
+   --annotator $annotator
+   --inAnnType ${annotator.ext}
+   --outputfile $outputfile
+   #if $options == "advanced":
+     --begintime $options.begintime
+     --stoptime $options.stoptime
+     --allIntervals $options.allIntervals
+     --consecutiveIntervals $options.consecutiveIntervals
+     --iformat $options.iformat
+     --itypeEnd $options.itypeEnd
+     --itypeBegun $options.itypeBegun
+     --timesFormatEnd $options.timesFormatEnd
+     --timesFormatBegin $options.timesFormatBegin
+     --annotationsEnd $options.annotationsEnd
+     --annotationsBegin $options.annotationsBegin
+   #end if
+
+  </command>
+
+  <inputs>
+    <param name="record" type="data" format="hea" label="Record ID"/>
+    <param name="annotator" type="data" format="atr,qrs,wqrs,nguess" label="Annotator"/>
+    <conditional name="options">
+      <param name="selectOptions" type="select" label="Modify Options?">
+        <option value="default" selected="true">Default options</option>
+        <option value="advanced">Modify options</option>
+      </param>
+
+      <when value="default" />
+      <when value="advanced">
+        <param name="begintime" type="text" label="Start Time" value="0" help="Begin at the specified time in record (default: start of the record)."/>
+        <param name="stoptime" type="text" label="Stop Time" value="e" help="Process until the specified time in record (default: the end of the record)."/>
+	<param name="allIntervals" type="boolean" checked="False" truevalue="true" falsevalue="false" label="Print all intervals (-A)" help="Print all intervals between annotations. By default, ann2rr prints only RR intervals (those between QRS (beat) annotations). This option overrides the -c and -p options." />
+	<param name="consecutiveIntervals" type="boolean" checked="False" truevalue="true" falsevalue="false" label="Print intervals between consecutive valid annotations only (-c)" />
+        <param name="iformat" type="text" value="" label="Print intervals in the specified format" help="By default, intervals are printed in units of sample intervals. Other formats include s (seconds), m (minutes), h (hours), and t (time interval in hh:mm:ss format). Formats s, m, and h may be followed by an integer between 0 and 15 inclusive, specifying the number of decimal places (default: 3). For example, use the option -is8 to obtain intervals in seconds with 8 decimal places." />
+        <param name="itypeEnd" type="text" value="" label="Print intervals ended by annotations of the specified types only" help="The type arguments should be annotation mnemonics (e.g., N), as normally printed by rdann(1) in the third column. More than one -p option may be used in a single command, and each -p option may have more than one type argument following it. If type begins with ‘‘-’’, however, it must immediately follow -p (standard annotation mnemonics do not begin with ‘‘-’’, but modification labels in an annotation file may define such mnemonics)." />
+        <param name="itypeBegin" type="text" value="" label="Print intervals begun by annotations of the specified types only" />
+        <param name="timesFormatEnd" type="text" value="" label="Print final times in format" help="This option accepts all of the formats defined for -i (to print the date and time in [hh:mm:ss dd/mm/yyyy] if the starting time and date have been recorded in the header file for record). If this option is chosen, the times appear at the end of each line of output." />
+        <param name="timesFormatBegin" type="text" value="" label="Print initial times in format" help="Any of the formats usable for the -v option may be used with -V. If this option is chosen, the times appear at the beginning of each line of output." />
+        <param name="annotationsEnd" type="boolean" checked="False" truevalue="true" falsevalue="false" label="Print final annotations" help="" />
+        <param name="annotationsBegin" type="boolean" checked="False" truevalue="true" falsevalue="false" label="Print initial annotations" help="" />
+      </when>
+    </conditional>
+  </inputs>
+
+  <outputs>
+    <data format="txt" name="outputfile" label="Output of ann2rr on ${on_string}" />
+  </outputs>
+
+  <help>
+::
+
+  These programs are typically used to obtain RR interval series from ECG annotation files, or to create an annotation file from such a series, but they have a wider range of uses.
+
+::
+
+  usage: ann2rr -r RECORD -a ANNOTATOR [OPTIONS ...]
+  where RECORD and ANNOTATOR specify the input, and OPTIONS may include::
+
+     -A      print all intervals between annotations (default: print only RR intervals; overrides -c, -p)
+     -c      print intervals between consecutive valid annotations only
+     -f TIME start at specified TIME
+     -i FMT  print intervals using format FMT (see below for values of FMT)
+     -p TYPE [TYPE ...]  print intervals ending with annotations of specified
+                         TYPEs only (use mnemonics such as N or V for TYPE)
+     -P TYPE [TYPE ...]  print intervals beginning with specified types only
+     -t TIME stop at specified TIME
+     -v FMT  print times of ends of intervals using format FMT (see below)
+     -V FMT  print times of beginnings of intervals using format FMT (see below)
+     -w      print annotations that end intervals
+     -W      print annotations that begin intervals
+
+::
+
+  By default, the output contains the RR intervals only, unless one or more
+  of -v, -V, -w, or -W are used.  Intervals and times are printed in units of
+  sample intervals, unless a format is specified using -i, -v, or -V.
+  Formats can be 'h' (hours), 'm' (minutes), 's' (seconds), 't' (hh:mm:ss);
+  when used with -v or -V, format 'T' yields dates and times if available,
+  or the format can be omitted to obtain times in sample intervals.  Formats
+  'h', 'm', and 's' may be followed by a number between 0 and 15, specifying
+  the number of decimal places (default: 3).  For example, to obtain intervals
+  in seconds with 8 decimal places, use '-i s8'.
+  </help>
+
+</tool>

tools/wfdb/nguess.xml

+<?xml version="1.0"?>
+
+<tool name="nguess" id="nguess_id">
+  <description>
+    guess the times of missing normal beats in an annotation file
+  </description>
+  <requirements>
+    <requirement type="package">wfdb</requirement>
+  <requirements>
+
+  <command interpreter="python">
+     wfdb_wrapper.py
+   --program nguess
+   --record $record
+   --annotator $annotator
+   --inAnnType ${annotator.ext}
+   --outputfile $outputfile
+   --outAnnType $outAnn
+   #if $options == "advanced":
+     --begintime $options.begintime
+     --stoptime $options.stoptime
+     --insertQann $options.insertQann
+   #end if
+
+  </command>
+
+  <inputs>
+    <param name="record" type="data" format="hea" label="Record ID"/>
+    <param name="annotator" type="data" format="atr,qrs,wqrs" label="Annotator"/>
+    <param name="outAnn" type="select" label="Output annotator type (default: nguess)">
+      <option value="nguess" selected="true">nguess</option>
+      <option value="qrs">qrs</option>
+      <option value="wqrs">wqrs</option>
+      <option value="atr">atr</option>
+    </param>
+    <conditional name="options">
+      <param name="selectOptions" type="select" label="Modify Options?">
+        <option value="default" selected="true">Default options</option>
+        <option value="advanced">Modify options</option>
+      </param>
+      <when value="default" />
+      <when value="advanced">
+        <param name="begintime" type="text" label="Start Time" value="0" help="Begin at the specified time in record (default: start of the record)."/>
+        <param name="stoptime" type="text" label="Stop Time" value="e" help="Process until the specified time in record (default: the end of the record)."/>
+        <param name="insertQann" type="text" value="" label="Insert number of annotations" help="Insert Q annotations in the output at the inferred locations of sinus beats only when the input RR interval exceeds M times the predicted RR interval (default: M = 1.75). M must be greater than 1; its useful range is roughly 1.5 to 2." />
+      </when>
+    </conditional>
+  </inputs>
+
+  <outputs>
+    <data format="nguess" name="outputfile" label="Output of nguess on ${on_string}" >
+      <change_format>
+	<when input="outAnn" value="qrs" format="qrs" />
+	<when input="outAnn" value="wqrs" format="wqrs" />
+	<when input="outAnn" value="atr" format="atr" />
+      </change_format>
+    </data>
+  </outputs>
+
+  <help>
+
+::
+
+  This program copies its input (a WFDB annotation file containing beat annotations), 
+  removing annotations of events other than sinus beats, and interpolating additional
+  Q (unknown beat) annotations at times when sinus beats are expected. Intervals between
+  sinus beats are predicted using a predictor array as described by Paul Schluter
+  ("The design and evaluation of a bedside cardiac arrhythmia monitor"; Ph.D. thesis, 
+  MIT Dept. of Electrical Engineering, 1981). When the predictions are inconsistent with 
+  the known sinus beats, as may occur in extreme noise or in highly irregular rhythms 
+  such as atrial fibrillation, no interpolations are made.
+
+::
+
+  usage: nguess -r RECORD -a ANNOTATOR [OPTIONS ...]
+  where RECORD and ANNOTATOR specify the input, and OPTIONS may include::
+
+  -f TIME    start at specified TIME
+  -m M       insert a Q if RR > M * prediction (M > 1; default: M = 1.75)
+  -o OANN    write output as annotator OANN (default: nguess)
+  -t TIME    stop at specified TIME
+
+::
+
+The output contains copies of all N annotations, with additional Q
+annotations inserted at the inferred locations of missing N (sinus) beats.
+  </help>
+
+</tool>

tools/wfdb/rdsamp.xml

+<?xml version="1.0"?>
+
+<tool name="rdsamp" id="rdsamp_id">
+  <description>
+    read WFDB signal files
+  </description>
+  <requirements>
+    <requirement type="package">wfdb</requirement>
+  <requirements>
+  <command interpreter='python'>
+     wfdb_wrapper.py
+   --program rdsamp
+   --record $record
+   --data $datafile
+   --outputfile $outputfile
+   #if $options == "advanced":
+     --begintime $options.begintime
+     --stoptime $options.stoptime
+     --resolution $options.resolution
+     --intervals $options.intervals
+     --precision $options.selectTimePrecision
+     --timeFormat $options.selectTimeFormat
+     --signalList $options.signalList
+     --signalStart $options.signalStart
+     --printHeader $options.printHeader
+     --outputFormat $options.outputFormat
+   #end if
+
+  </command>
+
+  <inputs>
+    <param name="record" type="data" format="hea" label="Record ID"/>
+    <param name="datafile" type="data" format="dat" label="Data File (*.dat)"/>
+    <conditional name="options">
+      <param name="selectOptions" type="select" label="Modify Options?">
+        <option value="default" selected="true">Default options</option>
+        <option value="advanced">Modify options</option>
+      </param>
+
+      <when value="default" />
+      <when value="advanced">
+        <param name="begintime" type="text" label="Start Time" value="0" help="Begin at the specified time in record (default: start of the record)."/>
+        <param name="stoptime" type="text" label="Stop Time" value="e" help="Process until the specified time in record (default: the end of the record)."/>
+	<param name="resolution" type="boolean" checked="False" truevalue="true" falsevalue="false" label="High-Resolution" help="Read the signal files in high-resolution mode (default: standard mode). These modes are identical for ordinary records. For multifrequency records, the standard decimation of oversampled signals to the frame rate is suppressed in high-resolution mode (rather, all other signals are resampled at the highest sampling frequency)." />
+	<param name="intervals" type="text" label="Interval to print" help="Limit the amount of output to the specified time interval (in standard time format; default: no limit). If both -l and -t are used, rdsamp stops at the earlier of the two limits." />
+	<param name="selectTimePrecision" type="select" label="Time Precision" >
+	  <option value="default">times in sample intervals and values in A/D units</option>
+	  <option value="milliseconds">times in seconds and milliseconds, and values in physical units</option>
+	  <option value="highestPrecision">Highest precision (up to 8 decimal places for seconds)</option>
+	</param>
+	<param name="selectTimeFormat" type="select" label="Time Format" >
+	  <option value="day">Time of day and date</option>
+	  <option value="elapsed">Elapsed time from the beginning of the record as hh:mm:ss</option>
+	  <option value="hours">Elapsed time in hours</option>
+	  <option value="minutes">Elapsed time in minutes</option>
+	  <option value="seconds">Elapsed time in seconds</option>
+	  <option value="interval">Elapsed time in sample intervals</option>
+	</param>
+        <param name="signalList" type="text" value="" label="Signal list" help="Print only the signals named in the signal-list (one or more input signal numbers or names, separated by spaces; default: print all signals). This option may be used to re-order or duplicate signals." />
+        <param name="signalStart" type="text" value="" label="Start at signal" help="Search for the first valid sample of the specified signal (a signal name or number) at or following the time specified with -f (or the beginning of the record if the -f option is not present), and begin printing at that time." />
+        <param name="printHeader" type="boolean" checked="False" truevalue="true" falsevalue="false" label="Print header line" help="Print column headings (signal names on the first line, units on the second). The names of some signals are too wide to fit in the columns; such names are shortened by omitting the initial characters (since names of related signals often differ only at the end, this helps to make the columns identifiable). Names of units are shortened when necessary by omitting the final characters, since the initial characters are usually most important for distinguishing different units." />
+        <param name="outputFormat" type="select" label="Output format" help="" >
+	  <option value="tabular">Tabular</option>
+	  <option value="csv">CSV</option>
+	  <option value="xml">WFDB-XML</option>
+	</param>	
+      </when>
+    </conditional>
+  </inputs>
+
+  <outputs>
+    <data format="txt" name="outputfile" label="Output of rdsamp" />
+  </outputs>
+
+  <help>
+::
+
+   rdsamp reads signal files for the specified record and writes the samples 
+   as decimal numbers on the standard output. If no options are provided, 
+   rdsamp starts at the beginning of the record and prints all samples. By 
+   default, each line of output contains the sample number and samples from 
+   each signal, beginning with channel 0, separated by tabs.
+
+
+::
+
+   usage: rdsamp -r RECORD [OPTIONS ...]
+   where RECORD is the name of the input record, and OPTIONS may include::
+
+   -c          use CSV (comma-separated value) output format
+   -f TIME     begin at specified time
+   -h          print this usage summary
+   -H          read multifrequency signals in high resolution mode
+   -l INTERVAL truncate output after the specified time interval (hh:mm:ss)
+   -p          print times and samples in physical units (default: raw units)
+   -P          same as -p, but with greater precision
+               -p and -P may be followed by a character to choose a time
+	       format;  choices are::
+
+	       -pd (or -Pd)  print time of day and date if known
+	       -pe (or -Pe)  print elapsed time as hours:minutes:seconds
+	       -ph (or -Ph)  print elapsed time in hours
+	       -pm (or -Pm)  print elapsed time in minutes
+	       -ps (or -Ps)  print elapsed time in seconds
+	       -pS (or -PS)  print elapsed time in sample intervals
+   -s SIGNAL [SIGNAL ...]  print only the specified signal(s)
+   -S SIGNAL   search for a valid sample of the specified SIGNAL at or after
+               the time specified with -f, and begin printing then
+   -t TIME     stop at specified time
+   -v          print column headings
+   -X          output in WFDB-XML format
+
+
+  </help>
+
+</tool>

tools/wfdb/sqrs.xml

+<?xml version="1.0"?>
+
+<tool name="sqrs" id="sqrs_id1">
+  <description>
+    single-channel QRS detector based on length transform
+  </description>
+  <requirements>
+    <requirement type="package">wfdb</requirement>
+  <requirements>
+
+  <command interpreter="python">
+     wfdb_wrapper.py   
+   --program sqrs
+   --record $record
+   --data $datafile
+   --outputfile $outputfile
+   #if $options.selectOptions == "advanced":
+     --begintime $options.begintime
+     --stoptime $options.stoptime
+     --resolution $options.resolution
+     --threshold $options.threshold
+     --signal $options.signal
+   #end if
+
+  </command>
+
+  <inputs>
+    <param name="record" type="data" format="hea" label="Record ID"/>
+    <param name="datafile" type="data" format="dat" label="Data File (*.dat)"/>
+    <conditional name="options">
+      <param name="selectOptions" type="select" label="Modify Options?">
+        <option value="default" selected="true">Default options</option>
+        <option value="advanced">Modify options</option>
+      </param>
+
+      <when value="default" />
+      <when value="advanced">
+        <param name="begintime" type="text" label="Start Time" value="0" help="Begin at the specified time in record (default: start of the record)."/>
+        <param name="stoptime" type="text" label="Stop Time" value="e" help="Process until the specified time in record (default: the end of the record)."/>
+	<param name="resolution" type="boolean" checked="False" truevalue="true" falsevalue="false" label="High-Resolution" help="Read the signal files in high-resolution mode (default: standard mode). These modes are identical for ordinary records. For multifrequency records, the standard decimation of oversampled signals to the frame rate is suppressed in high-resolution mode (rather, all other signals are resampled at the highest sampling frequency)." />
+        <param name="threshold" type="integer" value="500" label="Specify the detection threshold" help="use higher values to reduce false detections, or lower values to reduce the number of missed beats (default: 500)" />
+        <param name="signal" type="integer" value="0" label="Signal for QRS detection" help="Specify the signal (number or name) to be used for QRS detection (default: 0)." />
+	
+      </when>
+    </conditional>
+  </inputs>
+
+  <outputs>
+    <data format="qrs" name="outputfile" label="${tool.name} on ${on_string}: Reference annotation file" />
+  </outputs>
+
+  <help>
+
+::
+
+   sqrs attempts to locate QRS complexes in an ECG signal in the specified record.
+   The detector algorithm is based on example 10 in the WFDB Programmer’s Guide, 
+   which in turn is based on a Pascal program written by W.A.H. Engelse and 
+   C. Zeelenberg, ‘‘A single scan algorithm for QRS-detection and feature
+   extraction’’, Computers in Cardiology 6:37-42 (1979). sqrs does not include the
+   feature extraction capability of the Pascal program. The output of sqrs is an
+   annotation file (with annotator name qrs) in which all detected beats are
+   labelled normal; the annotation file may also contain ‘artifact’ annotations at
+   locations that sqrs believes are noise-corrupted.
+
+::
+
+  usage: sqrs -r RECORD [OPTIONS ...]
+  where RECORD is the name of the record to be analyzed, and OPTIONS may include any of::
+
+   -f TIME     begin at specified time
+   -H          read multifrequency signals in high resolution mode
+   -m THRESH   set detector threshold to THRESH (default: 500)
+   -s SIGNAL   analyze specified signal (default: 0)
+   -t TIME     stop at specified time
+
+::
+
+  If too many beats are missed, decrease THRESH;  if there are too many extra
+  detections, increase THRESH.
+
+  </help>
+
+</tool>

tools/wfdb/sqrs.xml.bk

+<?xml version="1.0"?>
+
+<tool name="sqrs" id="sqrs_id1">
+  <description>
+    single-channel QRS detector based on length transform
+  </description>
+
+  <command interpreter="python">
+     wfdb_wrapper.py   
+   --program sqrs
+   --record $record
+   #if $data_location.selectLocation == "history":
+     --data $datafile
+   #end if
+   #if $data_location.selectLocation == "library":
+     --data "colocated"
+   #end if
+   --output $outputfile
+   #if $options.selectOptions == "advanced":
+     --begintime $options.begintime
+     --stoptime $options.stoptime
+     --resolution $options.resolution
+     --threshold $options.threshold
+     --signal $options.signal
+   #end if
+
+  </command>
+
+  <inputs>
+    <param name="record" type="data" format="hea" label="Record ID"/>
+    <conditional name="data_location">
+      <param name="selectLocation" type="select" label="Location of data file">
+        <option value="history" selected="true">History</option>
+        <option value="library">Co-located with Record file</option>
+      </param>
+      <when value="history">
+	<param name="datafile" type="data" format="dat" label="Data File (*.dat)"/>
+      </when>
+      <when value="library"/>
+    </conditional>
+    <conditional name="options">
+      <param name="selectOptions" type="select" label="Modify Options?">
+        <option value="default" selected="true">Default options</option>
+        <option value="advanced">Modify options</option>
+      </param>
+
+      <when value="default" />
+      <when value="advanced">
+        <param name="begintime" type="text" label="Start Time" value="0" help="Begin at the specified time in record (default: start of the record)."/>
+        <param name="stoptime" type="text" label="Stop Time" value="e" help="Process until the specified time in record (default: the end of the record)."/>
+	<param name="resolution" type="boolean" checked="False" truevalue="true" falsevalue="false" label="High-Resolution" help="Read the signal files in high-resolution mode (default: standard mode). These modes are identical for ordinary records. For multifrequency records, the standard decimation of oversampled signals to the frame rate is suppressed in high-resolution mode (rather, all other signals are resampled at the highest sampling frequency)." />
+        <param name="threshold" type="integer" value="500" label="Specify the detection threshold" help="use higher values to reduce false detections, or lower values to reduce the number of missed beats (default: 500)" />
+        <param name="signal" type="integer" value="0" label="Signal for QRS detection" help="Specify the signal (number or name) to be used for QRS detection (default: 0)." />
+	
+      </when>
+    </conditional>
+  </inputs>
+
+  <outputs>
+    <data format="qrs" name="outputfile" label="${tool.name} on ${on_string}: Reference annotation file" />
+  </outputs>
+
+  <help>
+
+::
+
+   sqrs attempts to locate QRS complexes in an ECG signal in the specified record.
+   The detector algorithm is based on example 10 in the WFDB Programmer’s Guide, 
+   which in turn is based on a Pascal program written by W.A.H. Engelse and 
+   C. Zeelenberg, ‘‘A single scan algorithm for QRS-detection and feature
+   extraction’’, Computers in Cardiology 6:37-42 (1979). sqrs does not include the
+   feature extraction capability of the Pascal program. The output of sqrs is an
+   annotation file (with annotator name qrs) in which all detected beats are
+   labelled normal; the annotation file may also contain ‘artifact’ annotations at
+   locations that sqrs believes are noise-corrupted.
+
+::
+
+  usage: sqrs -r RECORD [OPTIONS ...]
+  where RECORD is the name of the record to be analyzed, and OPTIONS may include any of::
+
+   -f TIME     begin at specified time
+   -h          print this usage summary
+   -H          read multifrequency signals in high resolution mode
+   -m THRESH   set detector threshold to THRESH (default: 500)
+   -s SIGNAL   analyze specified signal (default: 0)
+   -t TIME     stop at specified time
+
+::
+
+  If too many beats are missed, decrease THRESH;  if there are too many extra
+  detections, increase THRESH.
+
+  </help>
+
+</tool>

tools/wfdb/wfdb_wrapper.py

+#!/usr/bin/python
+
+"""
+Runs wfdb commands on physionet db files
+wfdb_wrapper.py --program sqrs --record /scratch/go/galaxy/cvrg/100.hea
+
+usage: wfdb_wrapper.py [options]
+   -p, --program wfdb_command_name
+   -r, --record /filepath/to/record.hea
+   -d, --datafile /filepath/to/record.dat
+   -a, --annotator /filepath/to/record.[qrs,wqrs,atr]
+       --inAnntype [qrs,wqrs,atr]
+   -b, --begintime begin_time
+   -e, --stoptime stop_time
+       --resolution [true|false]
+       --jpoints [true|false]
+       --frequency frequency
+       --resample [true|false]
+       --insertQann M
+       --outAnnType [annotator type]
+       --allIntervals $selectOptions.allIntervals
+       --consecutiveIntervals $selectOptions.consecutiveIntervals
+       --iformat $options.iformat
+       --itypeEnd $options.itypeEnd
+       --itypeBegin $options.itypeBegin
+       --timesFormatEnd $options.timesFormatEnd
+       --timesFormatBegin $options.timesFormatBegin
+       --annotationsEnd $options.annotationsEnd
+       --annotationsBegin $options.annotationsBegin
+     --intervals $options.intervals
+     --precision $options.selectTimePrecision
+     --timeFormat $options.selectTimeFormat
+     --signalList $options.signalList
+     --signalStart $options.signalStart
+     --printHeader $options.printHeader
+     --outputFormat $options.outputFormat
+   -t, --threshold threshold
+   -s, --signal signal
+   -o, --outputfile outputfilename
+
+list of commands:
+sqrs
+wqrs
+nguess
+
+"""
+
+import optparse, os, shutil, sys, tempfile, re, subprocess, time
+
+def stop_err( msg ):
+    sys.stderr.write( "%s\n" % msg )
+    sys.exit()
+
+def get_recordname( record_file ):
+    recordFH = open(record_file, 'r')
+    firstLine = recordFH.readline()
+    recordFH.close()
+    metadata = firstLine.rsplit(" ")
+    record_name = metadata[0]
+    #print record_name
+    return record_name
+
+
+def __main__():
+    # timestamp
+    print "Start time:"
+    print time.strftime('%d/%m/%Y %H:%M:%S\n', time.localtime(time.time()))    
+
+    #Parse Command Line
+    parser = optparse.OptionParser()
+    parser.add_option( '-p', '--program', dest='program', help='wfdb program to use' )
+    parser.add_option( '-r', '--record', dest='recordfile', help='/filepath/to/record.hea' )
+    parser.add_option( '-d', '--datafile', dest='datafile', help='/filepath/to/record.dat' )
+    parser.add_option( '--annotator', dest='annotatorfile', help='/filepath/to/record.[qrs|wqrs|atr|nguess]' )
+    parser.add_option( '-q', '--qrsfile', dest='qrsfile', help='/filepath/to/record.qrs' )
+    parser.add_option( '-a', '--atrfile', dest='atrfile', help='/filepath/to/record.atr' )
+    parser.add_option( '--inAnnType', dest='inAnnType', help='input annotator type [wqrs, qrs, etc]' )
+    parser.add_option( '--outAnnType', dest='outAnnType', help='output annotator type [wqrs, qrs, etc]' )
+    parser.add_option( '-b', '--begintime', dest='begintime', help='First time period to make calculations')
+    parser.add_option( '-e', '--stoptime', dest='stoptime', help='Last time period to make calculations')
+    parser.add_option( '--resolution', dest='resolution', help='resolution definition level')
+    parser.add_option( '--jpoints', dest='jpoints', help='find and annotate J-points (QRS ends) as well as QRS onsets')
+    parser.add_option( '--frequency', dest='frequency', help='specify power line (mains) frequency ')
+    parser.add_option( '--resample', dest='resample', help='resample input')
+    parser.add_option( '--insertQann', dest='insertQann', help='insert a Q if RR > M ')
+    parser.add_option( '-s', '--signal', dest='signal', help='Analyze specified signal')
+    parser.add_option( '-t', '--threshold', dest='threshold', help='Threshold')
+    parser.add_option( '-o', '--outputfile', dest='outputfile', help='Output file')
+    parser.add_option( '--allIntervals', dest='allIntervals', help='intervals [true|fals]')
+    parser.add_option( '--consecutiveIntervals', dest='consecutiveIntervals', help='print consecutive intervals [true|false]')
+    parser.add_option( '--iformat', dest='iformat', help='input format')
+    parser.add_option( '--itypeEnd', dest='itypeEnd', help='input type end')
+    parser.add_option( '--itypeBegin', dest='itypeBegin', help='input type begin')
+    parser.add_option( '--timesFormatEnd', dest='timesFormatEnd', help='format time at end')
+    parser.add_option( '--timesFormatBegin', dest='timesFormatBegin', help='format time at beginning')
+    parser.add_option( '--annotationsEnd', dest='annotationsEnd', help='annotations at end')
+    parser.add_option( '--annotationsBegin', dest='annotationsBegin', help='annotations at beginning')
+    parser.add_option( '--intervals', dest='intervals', help='rdsam param' )
+    parser.add_option( '--precision', dest='selectTimePrecision', help='rdsam param' )
+    parser.add_option( '--timeFormat', dest='selectTimeFormat', help='rdsam param' )
+    parser.add_option( '--signalList', dest='signalList', help='rdsam param' )
+    parser.add_option( '--signalStart', dest='signalStart', help='rdsam param' )
+    parser.add_option( '--printHeader', dest='printHeader', help='rdsam param' )
+    parser.add_option( '--outputFormat', dest='outputFormat', help='rdsam param' )
+    (options, args) = parser.parse_args()
+
+    # set environment variables
+    os.environ["LD_LIBRARY_PATH"] = os.environ["LD_LIBRARY_PATH"] + ":/mnt/galaxyTools/tools/wfdb/wfdb-10.5.18/lib64"
+
+    # get record name
+    # open the record file and read the first line.
+    if options.recordfile:
+        record_name = get_recordname(options.recordfile)
+    else:
+        print "no record file provided"
+        sys.exit()
+
+    # create a temporary working directory
+    try:
+        tmp_wfdb_dir = tempfile.mkdtemp(dir="/tmp")
+
+        #cp any files to this temporary directory
+        if options.recordfile:
+            #tmp_record_filename = os.path.basename(options.recordfile)
+            tmp_record_filename = "%s.hea" % (record_name)
+            dest = "%s/%s" % (tmp_wfdb_dir, tmp_record_filename)
+            shutil.copyfile(options.recordfile, dest)
+            
+        if options.qrsfile:
+            #tmp_qrs_filename = os.path.basename(options.qrsfile)
+            tmp_qrs_filename = "%s.qrs" % (record_name)
+            dest = "%s/%s" % (tmp_wfdb_dir, tmp_qrs_filename)
+            shutil.copyfile(options.qrs, dest)
+
+        if options.atrfile:
+            #tmp_atr_filename = os.path.basename(options.atrfile)
+            tmp_atr_filename = "%s.atr" % (record_name)
+            dest = "%s/%s" % (tmp_wfdb_dir, tmp_atr_filename)
+            shutil.copyfile(options.atr, dest)
+
+        if options.datafile:
+            #tmp_data_filename = os.path.basename(options.datafile)
+            tmp_data_filename = "%s.dat" % (record_name)
+            dest = "%s/%s" % (tmp_wfdb_dir, tmp_data_filename)
+            shutil.copyfile(options.datafile, dest)
+
+        if options.annotatorfile:
+            #tmp_ann_filename = os.path.basename(options.annotatorfile)
+            tmp_ann_filename = "%s.%s" % (record_name, options.inAnnType)
+            dest = "%s/%s" % (tmp_wfdb_dir, tmp_ann_filename)
+            shutil.copyfile(options.annotatorfile, dest)
+
+
+
+        # set the temporary output filename for each program
+        if options.program == 'sqrs':
+            record_name = re.sub('.hea', '', tmp_record_filename )
+            qrs_tmp_outfile = "%s/%s.qrs" % (tmp_wfdb_dir, record_name)
+            #print qrs_tmp_outfile
+        if options.program == 'wqrs':
+            record_name = re.sub('.hea', '', tmp_record_filename )
+            wqrs_tmp_outfile = "%s/%s.wqrs" % (tmp_wfdb_dir, record_name)
+            #print qrs_tmp_outfile
+        if options.program == 'nguess':
+            record_name = re.sub('.hea', '', tmp_record_filename )
+            if options.outAnnType:
+                outType = options.outAnnType
+            else:
+                outType = "nguess"
+            nguess_tmp_outfile = "%s/%s.%s" % (tmp_wfdb_dir, record_name, outType)
+            #print nguess_tmp_outfile
+
+
+        # build command line
+        wfdb_dir = "/mnt/galaxyTools/tools/wfdb/wfdb-10.5.18/bin"
+        cmd = "%s/%s" % (wfdb_dir, options.program)
+        
+        if options.recordfile:
+            if tmp_record_filename:
+                record_name = re.sub('.hea', '', tmp_record_filename )
+                tmp_record = "%s/%s" % (tmp_wfdb_dir, record_name)
+                cmd += " -r %s" % (tmp_record)
+#        if options.datafile:
+#            if tmp_data_filename:
+#                if options.program != "sqrs" and options.program != "wqrs" and options.program != "nguess":
+#                    cmd += " -something"
+#        if options.qrsfile:
+#            if tmp_qrs_filename:
+#                if options.program != "sqrs" and options.program != "wqrs" and options.program != "nguess":
+#                    cmd += " -something"
+#        if options.atrfile:
+#            if tmp_atr_filename:
+#                if options.program != "sqrs" and options.program != "wqrs" and options.program != "nguess":
+#                    cmd += " -something"
+        if options.annotatorfile:
+            cmd += " -a %s" % (options.inAnnType)
+        if options.outAnnType:
+            cmd += " -o %s" % (options.outAnnType)
+        if options.begintime:
+            cmd += " -f %s" % (options.begintime)
+        if options.stoptime:
+            cmd += " -t %s" % (options.stoptime)
+        if options.resolution == "true":
+            cmd += " -H"
+        if options.jpoints == "true":
+            cmd += " -j"
+        if options.resample == "true":
+            cmd += " -R"
+        if options.frequency:
+            cmd += " -p %s" % (options.frequency)
+        if options.signal:
+            cmd += " -s %s" % (options.signal)
+        if options.threshold:
+            cmd += " -m %s" % (options.threshold)
+        if options.insertQann:
+            cmd += " -m %s" % (options.insertQann)
+        if options.allIntervals:
+            cmd += " -A"
+        if options.consecutiveIntervals:
+            cmd += " -c"
+        if options.iformat:
+            cmd += " -d %s" % (options.iformat)
+        if options.itypeEnd:
+            cmd += " -p %s" % (options.itypeEnd)
+        if options.itypeBegin:
+            cmd += " -P %s" % (options.itypeBegin)
+        if options.timesFormatEnd:
+            cmd += " -v %s" % (options.timesFormatEnd)
+        if options.timesFormatBegin:
+            cmd += " -V %s" % (options.timesFormatBegin)
+        if options.annotationsEnd:
+            cmd += " -w"
+        if options.annotationsBegin:
+            cmd += " -W"
+        if options.intervals:
+            cmd += " -l %s" % (options.intervals)
+        if options.selectTimePrecision:
+            precision_param = ""
+            if options.selectTimePrecision == "milliseconds":
+                precision_param += "-p"
+            elif options.selectTimePrecision == "highestPrecision":
+                precision_param += "-P"
+            if options.selectTimePrecision != "default":
+                if options.selectTimeFormat:
+                    if options.selectTimeFormat == "day":
+                        precision_param += "d"
+                    elif options.selectTimeFormat== "elapsed":
+                        precision_param += "e"
+                    elif options.selectTimeFormat== "hours":
+                        precision_param += "h"
+                    elif options.selectTimeFormat== "minutes":
+                        precision_param += "m"
+                    elif options.selectTimeFormat== "seconds":
+                        precision_param += "s"
+                    elif options.selectTimeFormat== "interval":
+                        precision_param += "S"
+            cmd += " %s" % (precision_param)
+        if options.signalList:
+            cmd += " -s %s" % (options.signalList)
+        if options.signalStart:
+            cmd += " -S %s" % (options.signalStart)
+        if options.printHeader:
+            cmd += " -v"
+        if options.outputFormat:
+            if options.outputFormat == 'csv':
+                cmd += " -c"
+            elif options.outputFormat == 'xml':
+                cmd += " -X"
+
+
+        if options.program == 'ann2rr' or options.program == 'rdsamp':
+            cmd += " > %s" % (options.outputfile)
+
+        print cmd
+        ## execute job in tempdir, move and rename output to appropriate dir, delete tempdir
+        ## execute command in tempdir
+        tmp_out = tempfile.NamedTemporaryFile().name
+        tmp_stdout = open( tmp_out, 'w' )
+        tmp_err = tempfile.NamedTemporaryFile().name
+        tmp_stderr = open( tmp_err, 'w' )
+        proc = subprocess.Popen( args=cmd, shell=True, cwd=".", stdout=tmp_stdout, stderr=tmp_stderr )
+
+        returncode = proc.wait()
+        tmp_stderr.close()
+        # get stderr, allowing for case where it's very large
+        tmp_stderr = open( tmp_err, 'rb' )
+        stderr = ''
+        buffsize = 1048576
+        try:
+            while True:
+                stderr += tmp_stderr.read( buffsize )
+                if not stderr or len( stderr ) % buffsize != 0:
+                    break
+        except OverflowError:
+            pass
+        tmp_stdout.close()
+        tmp_stderr.close()
+        if returncode != 0:
+            raise Exception, stderr
+
+        # if job is sqrs, copy the new qrs to the output file
+        if options.program == 'sqrs':
+            shutil.copyfile(qrs_tmp_outfile, options.outputfile)
+        # if job is wqrs, copy the new wqrs to the output file
+        if options.program == 'wqrs':
+            shutil.copyfile(wqrs_tmp_outfile, options.outputfile)
+        # if job is nguess, copy the new nguess to the output file
+        if options.program == 'nguess':
+            shutil.copyfile(nguess_tmp_outfile, options.outputfile)
+
+
+    ## delete tempdir
+    finally:
+        try:
+            shutil.rmtree(tmp_wfdb_dir) # delete directory
+#            try:
+#                with open(stderr): pass
+#                os.unlink(stderr)
+#            except IOError:
+#                print 'Cleanup done: stderr'
+#            try:
+#                with open(stdout): pass
+#                os.unlink(stdout)
+#            except IOError:
+#                print 'Cleanup done: stdout'
+            #print tmp_wfdb_dir
+        except OSError, e:
+            if e.errno != 2: # code 2 - no such file or directory
+                raise
+
+    print "End time:"
+    print time.strftime('%d/%m/%Y %H:%M:%S\n', time.localtime(time.time()))
+
+if __name__=="__main__": __main__()

tools/wfdb/wfdb_wrapper.py.bk

+#!/usr/bin/python
+
+"""
+Runs wfdb commands on physionet db files
+wfdb_wrapper.py --program sqrs --record /scratch/go/galaxy/cvrg/100.hea
+
+usage: wfdb_wrapper.py [options]
+   -p, --program wfdb_command_name
+   -r, --record /filepath/to/record.hea
+   -d, --datafile /filepath/to/record.dat
+   -b, --begintime begin_time
+   -e, --stoptime stop_time
+       --resolution resolution
+   -t, --threshold threshold
+   -s, --signal signal
+   -o, --outputfile outputfilename
+
+"""
+
+import optparse, os, shutil, sys, tempfile, re, subprocess
+
+def stop_err( msg ):
+    sys.stderr.write( "%s\n" % msg )
+    sys.exit()
+
+def __main__():
+    #Parse Command Line
+    parser = optparse.OptionParser()
+    parser.add_option( '-p', '--program', dest='program', help='wfdb program to use' )
+    parser.add_option( '-r', '--record', dest='recordfile', help='/filepath/to/record.hea' )
+    parser.add_option( '-d', '--datafile', dest='datafile', help='/filepath/to/record.dat' )
+    parser.add_option( '-q', '--qrsfile', dest='qrsfile', help='/filepath/to/record.qrs' )
+    parser.add_option( '-a', '--atrfile', dest='atrfile', help='/filepath/to/record.atr' )
+    parser.add_option( '-b', '--begintime', dest='begintime', help='First time period to make calculations')
+    parser.add_option( '-e', '--stoptime', dest='stoptime', help='Last time period to make calculations')
+    parser.add_option( '--resolution', dest='resolution', help='resolution definition level')
+    parser.add_option( '-s', '--signal', dest='signal', help='Analyze specified signal')
+    parser.add_option( '-t', '--threshold', dest='threshold', help='Threshold')
+    parser.add_option( '-o', '--outputfile', dest='outputfile', help='Output file')
+
+    (options, args) = parser.parse_args()
+
+    # set environment variables
+    os.environ["LD_LIBRARY_PATH"] = os.environ["LD_LIBRARY_PATH"] + ":/mnt/galaxyTools/tools/wfdb/wfdb-10.5.18/lib64"
+
+    # create a temporary working directory
+    try:
+        tmp_wfdb_dir = tempfile.mkdtemp(dir="/tmp")
+
+        #cp any files to this temporary directory
+        if options.recordfile:
+            tmp_record_filename = os.path.basename(options.recordfile)
+            dest = "%s/%s" % (tmp_wfdb_dir, tmp_record_filename)
+            shutil.copyfile(options.recordfile, dest)
+            
+        if options.qrsfile:
+            tmp_qrs_filename = os.path.basename(options.qrsfile)
+            dest = "%s/%s" % (tmp_wfdb_dir, tmp_qrs_filename)
+            shutil.copyfile(options.qrs, dest)
+
+        if options.atrfile:
+            tmp_atr_filename = os.path.basename(options.atrfile)
+            dest = "%s/%s" % (tmp_wfdb_dir, tmp_atr_filename)
+            shutil.copyfile(options.atr, dest)
+
+        if options.datafile:
+            if options.datafile == "colocated":
+                record_name = re.sub('.hea', '', tmp_record_filename )
+                options.datafile = os.path.dirname(options.recordfile) + "/" + record_name + ".dat"
+            tmp_data_filename = os.path.basename(options.datafile)
+            dest = "%s/%s" % (tmp_wfdb_dir, tmp_data_filename)
+            shutil.copyfile(options.datafile, dest)
+
+
+        # set the temporary output filename for each program
+        if options.program == 'sqrs':
+            record_name = re.sub('.hea', '', tmp_record_filename )
+            qrs_tmp_outfile = "%s/%s.qrs" % (tmp_wfdb_dir, record_name)
+            #print qrs_tmp_outfile
+
+        # build command line
+        wfdb_dir = "/mnt/galaxyTools/tools/wfdb/wfdb-10.5.18/bin"
+        cmd = "%s/%s" % (wfdb_dir, options.program)
+        
+        if options.recordfile:
+            if tmp_record_filename:
+                record_name = re.sub('.hea', '', tmp_record_filename )
+                tmp_record = "%s/%s" % (tmp_wfdb_dir, record_name)
+                cmd += " -r %s" % (tmp_record)
+        if options.datafile:
+            if tmp_data_filename:
+                if options.program != "sqrs":
+                    cmd += " -something"
+        if options.qrsfile:
+            if tmp_qrs_filename:
+                if options.program != "sqrs":
+                    cmd += " -something"
+        if options.atrfile:
+            if tmp_atr_filename:
+                if options.program != "sqrs":
+                    cmd += " -something"
+        if options.begintime:
+            cmd += " -f %s" % (options.begintime)
+        if options.stoptime:
+            cmd += " -t %s" % (options.stoptime)
+        if options.resolution:
+            cmd += " -H"
+        if options.signal:
+            cmd += " -s %s" % (options.signal)
+        if options.threshold:
+            cmd += " -m %s" % (options.threshold)
+    
+        print cmd
+        ## execute job in tempdir, move and rename output to appropriate dir, delete tempdir
+        ## execute command in tempdir
+        tmp_out = tempfile.NamedTemporaryFile().name
+        tmp_stdout = open( tmp_out, 'w' )
+        tmp_err = tempfile.NamedTemporaryFile().name
+        tmp_stderr = open( tmp_err, 'w' )
+        proc = subprocess.Popen( args=cmd, shell=True, cwd=".", stdout=tmp_stdout, stderr=tmp_stderr )
+
+        returncode = proc.wait()
+        tmp_stderr.close()
+        # get stderr, allowing for case where it's very large
+        tmp_stderr = open( tmp_err, 'rb' )
+        stderr = ''
+        buffsize = 1048576
+        try:
+            while True:
+                stderr += tmp_stderr.read( buffsize )
+                if not stderr or len( stderr ) % buffsize != 0:
+                    break
+        except OverflowError:
+            pass
+        tmp_stdout.close()
+        tmp_stderr.close()
+        if returncode != 0:
+            raise Exception, stderr
+
+        # if job is sqrs, copy the new qrs to the output file
+        if options.program == 'sqrs':
+            shutil.copyfile(qrs_tmp_outfile, options.outputfile)
+
+
+    ## delete tempdir
+    finally:
+        try:
+            shutil.rmtree(tmp_wfdb_dir) # delete directory
+        except OSError, e:
+            if e.errno != 2: # code 2 - no such file or directory
+                raise
+
+if __name__=="__main__": __main__()
+

tools/wfdb/wqrs.xml

+<?xml version="1.0"?>
+
+<tool name="wqrs" id="wqrs_id1">
+  <description>
+    single-channel QRS detector based on length transform
+  </description>
+  <requirements>
+    <requirement type="package">wfdb</requirement>
+  <requirements>
+
+  <command interpreter="python">
+     wfdb_wrapper.py   
+   --program wqrs
+   --record $record
+   --data $datafile
+   --outputfile $outputfile
+   #if $options == "advanced":
+     --begintime $options.begintime
+     --stoptime $options.stoptime
+     --resolution $options.resolution
+     --jpoints $options.jpoints
+     --threshold $options.threshold
+     --frequency $options.frequency
+     --signal $options.signal
+     --resample $options.resample
+   #end if
+
+  </command>
+
+  <inputs>
+    <param name="record" type="data" format="hea" label="Record ID"/>
+    <param name="datafile" type="data" format="dat" label="Data File (*.dat)"/>
+    <conditional name="options">
+      <param name="selectOptions" type="select" label="Modify Options?">
+        <option value="default" selected="true">Default options</option>
+        <option value="advanced">Modify options</option>
+      </param>
+
+      <when value="default" />
+      <when value="advanced">
+        <param name="begintime" type="text" label="Start Time" value="0" help="Begin at the specified time in record (default: start of the record)."/>
+        <param name="stoptime" type="text" label="Stop Time" value="e" help="Process until the specified time in record (default: the end of the record)."/>
+	<param name="resolution" type="boolean" checked="False" truevalue="true" falsevalue="false" label="High-Resolution" help="Read the signal files in high-resolution mode (default: standard mode). These modes are identical for ordinary records. For multifrequency records, the standard decimation of oversampled signals to the frame rate is suppressed in high-resolution mode" />
+	<param name="jpoints" type="boolean" checked="False" truevalue="true" falsevalue="false" label="Find and annotate J-points (QRS ends) as well as QRS onsets" />
+        <param name="threshold" type="integer" value="100" label="Specify the detection threshold" help="use higher values to reduce false detections, or lower values to reduce the number of missed beats (default: 100)" />
+        <param name="frequency" type="integer" value="60" label="Specify the power line (mains) frequency" help="Specify the power line (mains) frequency used at the time of the recording, in Hz (default: 60). wqrs will apply a notch filter of the specified frequency to the input signal before length-transforming it." />
+	<param name="resample" type="boolean" checked="False" truevalue="true" falsevalue="false" label="Resample" help="Resample the input at 120 Hz if the power line frequency is 60 Hz, or at 150 Hz otherwise (default: do not resample)." />
+        <param name="signal" type="integer" value="0" label="Signal for QRS detection" help="Specify the signal (number or name) to be used for QRS detection (default: 0)." />
+	
+      </when>
+    </conditional>
+  </inputs>
+
+  <outputs>
+    <data format="wqrs" name="outputfile" label="${tool.name} on ${on_string}: Reference annotation file" />
+  </outputs>
+
+  <help>
+
+::
+
+  wqrs attempts to locate QRS complexes in an ECG signal in the specified record. The detector algorithm is based on the length transform.
+
+::
+
+  usage: wqrs -r RECORD [OPTIONS ...]
+  where RECORD is the name of the record to be analyzed, and OPTIONS may include any of::
+
+  -f TIME     begin at specified time (default: beginning of the record)
+  -H          read multifrequency signals in high resolution mode
+  -j          find and annotate J-points (QRS ends) as well as QRS onsets
+  -m THRESH   set detector threshold to THRESH (default: 100)
+  -p FREQ     specify power line (mains) frequency (default: 60)
+  -R          resample input at 120 or 150 Hz, depending on power line
+              frequency (default: do not resample)
+  -s SIGNAL   analyze specified signal (default: 0)
+  -t TIME     stop at specified time (default: end of the record)
+
+::
+
+  If too many beats are missed, decrease THRESH;  if there are too many extra detections, increase THRESH.
+
+
+  </help>
+
+</tool>