AbstractTimeSeries.java
Upload User: rhdiban
Upload Date: 2013-08-09
Package Size: 15085k
Code Size: 13k
Category:

Windows Develop

Development Platform:

Java

  1. /*
  2.  *    This program is free software; you can redistribute it and/or modify
  3.  *    it under the terms of the GNU General Public License as published by
  4.  *    the Free Software Foundation; either version 2 of the License, or
  5.  *    (at your option) any later version.
  6.  *
  7.  *    This program is distributed in the hope that it will be useful,
  8.  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
  9.  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  10.  *    GNU General Public License for more details.
  11.  *
  12.  *    You should have received a copy of the GNU General Public License
  13.  *    along with this program; if not, write to the Free Software
  14.  *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
  15.  */
  16. /*
  17.  *    AbstractTimeSeries.java
  18.  *    Copyright (C) 1999 Len Trigg
  19.  *
  20.  */
  21. package weka.filters.unsupervised.attribute;
  22. import weka.filters.*;
  23. import java.io.*;
  24. import java.util.*;
  25. import weka.core.*;
  26. /** 
  27.  * An abstract instance filter that assumes instances form time-series data and
  28.  * performs some merging of attribute values in the current instance with 
  29.  * attribute attribute values of some previous (or future) instance. For
  30.  * instances where the desired value is unknown either the instance may
  31.  * be dropped, or missing values used.<p>
  32.  *
  33.  * Valid filter-specific options are:<p>
  34.  *
  35.  * -R index1,index2-index4,...<br>
  36.  * Specify list of columns to calculate new values for.
  37.  * First and last are valid indexes.
  38.  * (default none)<p>
  39.  *
  40.  * -V <br>
  41.  * Invert matching sense (i.e. calculate for all non-specified columns)<p>
  42.  *
  43.  * -I num <br>
  44.  * The number of instances forward to merge values between.
  45.  * A negative number indicates taking values from a past instance.
  46.  * (default -1) <p>
  47.  *
  48.  * -M <br>
  49.  * For instances at the beginning or end of the dataset where the translated
  50.  * values are not known, use missing values (default is to remove those
  51.  * instances). <p>
  52.  *
  53.  * @author Len Trigg (trigg@cs.waikato.ac.nz)
  54.  * @version $Revision: 1.1 $
  55.  */
  56. public abstract class AbstractTimeSeries extends Filter
  57.   implements UnsupervisedFilter, OptionHandler {
  58.   /** Stores which columns to copy */
  59.   protected Range m_SelectedCols = new Range();
  60.   /**
  61.    * True if missing values should be used rather than removing instances
  62.    * where the translated value is not known (due to border effects).
  63.    */
  64.   protected boolean m_FillWithMissing;
  65.   /**
  66.    * The number of instances forward to translate values between.
  67.    * A negative number indicates taking values from a past instance.
  68.    */
  69.   protected int m_InstanceRange = -1;
  70.   /** Stores the historical instances to copy values between */
  71.   protected Queue m_History;
  72.   
  73.   /**
  74.    * Returns an enumeration describing the available options.
  75.    *
  76.    * @return an enumeration of all the available options.
  77.    */
  78.   public Enumeration listOptions() {
  79.     Vector newVector = new Vector(4);
  80.     newVector.addElement(new Option(
  81.               "tSpecify list of columns to translate in time. First andn"
  82.       + "tlast are valid indexes. (default none)",
  83.               "R", 1, "-R <index1,index2-index4,...>"));
  84.     newVector.addElement(new Option(
  85.       "tInvert matching sense (i.e. calculate for all non-specified columns)",
  86.               "V", 0, "-V"));
  87.     newVector.addElement(new Option(
  88.               "tThe number of instances forward to translate valuesn"
  89.       + "tbetween. A negative number indicates taking values fromn"
  90.       + "ta past instance. (default -1)",
  91.               "I", 1, "-I <num>"));
  92.     newVector.addElement(new Option(
  93.       "tFor instances at the beginning or end of the dataset wheren"
  94.       + "tthe translated values are not known, use missing valuesn"
  95.       + "t(default is to remove those instances).",
  96.               "M", 0, "-M"));
  97.     return newVector.elements();
  98.   }
  99.   /**
  100.    * Parses a given list of options controlling the behaviour of this object.
  101.    * Valid options are:<p>
  102.    *
  103.    * -R index1,index2-index4,...<br>
  104.    * Specify list of columns to copy. First and last are valid indexes.
  105.    * (default none)<p>
  106.    *
  107.    * -V<br>
  108.    * Invert matching sense (i.e. calculate for all non-specified columns)<p>
  109.    *
  110.    * -I num <br>
  111.    * The number of instances forward to translate values between.
  112.    * A negative number indicates taking values from a past instance.
  113.    * (default -1) <p>
  114.    *
  115.    * -M <br>
  116.    * For instances at the beginning or end of the dataset where the translated
  117.    * values are not known, use missing values (default is to remove those
  118.    * instances). <p>
  119.    *
  120.    * @param options the list of options as an array of strings
  121.    * @exception Exception if an option is not supported
  122.    */
  123.   public void setOptions(String[] options) throws Exception {
  124.     String copyList = Utils.getOption('R', options);
  125.     if (copyList.length() != 0) {
  126.       setAttributeIndices(copyList);
  127.     } else {
  128.       setAttributeIndices("");
  129.     }
  130.     
  131.     setInvertSelection(Utils.getFlag('V', options));
  132.     setFillWithMissing(Utils.getFlag('M', options));
  133.     
  134.     String instanceRange = Utils.getOption('I', options);
  135.     if (instanceRange.length() != 0) {
  136.       setInstanceRange(Integer.parseInt(instanceRange));
  137.     } else {
  138.       setInstanceRange(-1);
  139.     }
  140.     if (getInputFormat() != null) {
  141.       setInputFormat(getInputFormat());
  142.     }
  143.   }
  144.   /**
  145.    * Gets the current settings of the filter.
  146.    *
  147.    * @return an array of strings suitable for passing to setOptions
  148.    */
  149.   public String [] getOptions() {
  150.     String [] options = new String [6];
  151.     int current = 0;
  152.     if (!getAttributeIndices().equals("")) {
  153.       options[current++] = "-R"; options[current++] = getAttributeIndices();
  154.     }
  155.     if (getInvertSelection()) {
  156.       options[current++] = "-V";
  157.     }
  158.     options[current++] = "-I"; options[current++] = "" + getInstanceRange();
  159.     if (getFillWithMissing()) {
  160.       options[current++] = "-M";
  161.     }
  162.     while (current < options.length) {
  163.       options[current++] = "";
  164.     }
  165.     return options;
  166.   }
  167.   /**
  168.    * Sets the format of the input instances.
  169.    *
  170.    * @param instanceInfo an Instances object containing the input instance
  171.    * structure (any instances contained in the object are ignored - only the
  172.    * structure is required).
  173.    * @return true if the outputFormat may be collected immediately
  174.    * @exception Exception if the format couldn't be set successfully
  175.    */
  176.   public boolean setInputFormat(Instances instanceInfo) throws Exception {
  177.     super.setInputFormat(instanceInfo);
  178.     resetHistory();
  179.     m_SelectedCols.setUpper(instanceInfo.numAttributes() - 1);
  180.     return false;
  181.   }
  182.   
  183.   /**
  184.    * Input an instance for filtering. Ordinarily the instance is processed
  185.    * and made available for output immediately. Some filters require all
  186.    * instances be read before producing output.
  187.    *
  188.    * @param instance the input instance
  189.    * @return true if the filtered instance may now be
  190.    * collected with output().
  191.    * @exception Exception if the input instance was not of the correct 
  192.    * format or if there was a problem with the filtering.
  193.    */
  194.   public boolean input(Instance instance) throws Exception {
  195.     if (getInputFormat() == null) {
  196.       throw new NullPointerException("No input instance format defined");
  197.     }
  198.     if (m_NewBatch) {
  199.       resetQueue();
  200.       m_NewBatch = false;
  201.       resetHistory();
  202.     }
  203.     Instance newInstance = historyInput(instance);
  204.     if (newInstance != null) {
  205.       push(newInstance);
  206.       return true;
  207.     } else {
  208.       return false;
  209.     }
  210.   }
  211.   /**
  212.    * Signifies that this batch of input to the filter is finished. If the 
  213.    * filter requires all instances prior to filtering, output() may now 
  214.    * be called to retrieve the filtered instances.
  215.    *
  216.    * @return true if there are instances pending output
  217.    * @exception IllegalStateException if no input structure has been defined
  218.    */
  219.   public boolean batchFinished() {
  220.     if (getInputFormat() == null) {
  221.       throw new IllegalStateException("No input instance format defined");
  222.     }
  223.     if (getFillWithMissing() && (m_InstanceRange > 0)) {
  224.       while (!m_History.empty()) {
  225. push(mergeInstances(null, (Instance) m_History.pop()));
  226.       }
  227.     } 
  228.     m_NewBatch = true;
  229.     return (numPendingOutput() != 0);
  230.   }
  231.   
  232.   /**
  233.    * Gets whether missing values should be used rather than removing instances
  234.    * where the translated value is not known (due to border effects).
  235.    *
  236.    * @return true if so
  237.    */
  238.   public boolean getFillWithMissing() {
  239.     
  240.     return m_FillWithMissing;
  241.   }
  242.   
  243.   /**
  244.    * Sets whether missing values should be used rather than removing instances
  245.    * where the translated value is not known (due to border effects).
  246.    *
  247.    * @param newFillWithMissing true if so
  248.    */
  249.   public void setFillWithMissing(boolean newFillWithMissing) {
  250.     
  251.     m_FillWithMissing = newFillWithMissing;
  252.   }
  253.   /**
  254.    * Gets the number of instances forward to translate values between.
  255.    * A negative number indicates taking values from a past instance.
  256.    *
  257.    * @return Value of InstanceRange.
  258.    */
  259.   public int getInstanceRange() {
  260.     
  261.     return m_InstanceRange;
  262.   }
  263.   
  264.   /**
  265.    * Sets the number of instances forward to translate values between.
  266.    * A negative number indicates taking values from a past instance.
  267.    *
  268.    * @param newInstanceRange Value to assign to InstanceRange.
  269.    */
  270.   public void setInstanceRange(int newInstanceRange) {
  271.     
  272.     m_InstanceRange = newInstanceRange;
  273.   }
  274.   
  275.   /**
  276.    * Get whether the supplied columns are to be removed or kept
  277.    *
  278.    * @return true if the supplied columns will be kept
  279.    */
  280.   public boolean getInvertSelection() {
  281.     return m_SelectedCols.getInvert();
  282.   }
  283.   /**
  284.    * Set whether selected columns should be removed or kept. If true the 
  285.    * selected columns are kept and unselected columns are copied. If false
  286.    * selected columns are copied and unselected columns are kept.
  287.    *
  288.    * @param invert the new invert setting
  289.    */
  290.   public void setInvertSelection(boolean invert) {
  291.     m_SelectedCols.setInvert(invert);
  292.   }
  293.   /**
  294.    * Returns the tip text for this property
  295.    *
  296.    * @return tip text for this property suitable for
  297.    * displaying in the explorer/experimenter gui
  298.    */
  299.   public String attributeIndicesTipText() {
  300.     return "Specify range of attributes to act on."
  301.       + " This is a comma separated list of attribute indices, with"
  302.       + " "first" and "last" valid values. Specify an inclusive"
  303.       + " range with "-". E.g: "first-3,5,6-10,last".";
  304.   }
  305.   /**
  306.    * Get the current range selection
  307.    *
  308.    * @return a string containing a comma separated list of ranges
  309.    */
  310.   public String getAttributeIndices() {
  311.     return m_SelectedCols.getRanges();
  312.   }
  313.   /**
  314.    * Set which attributes are to be copied (or kept if invert is true)
  315.    *
  316.    * @param rangeList a string representing the list of attributes.  Since
  317.    * the string will typically come from a user, attributes are indexed from
  318.    * 1. <br>
  319.    * eg: first-3,5,6-last
  320.    */
  321.   public void setAttributeIndices(String rangeList) {
  322.     m_SelectedCols.setRanges(rangeList);
  323.   }
  324.   /**
  325.    * Set which attributes are to be copied (or kept if invert is true)
  326.    *
  327.    * @param attributes an array containing indexes of attributes to select.
  328.    * Since the array will typically come from a program, attributes are indexed
  329.    * from 0.
  330.    */
  331.   public void setAttributeIndicesArray(int [] attributes) {
  332.     setAttributeIndices(Range.indicesToRangeList(attributes));
  333.   }
  334.   /** Clears any instances from the history queue. */
  335.   protected void resetHistory() {
  336.     if (m_History == null) {
  337.       m_History = new Queue();
  338.     } else {
  339.       m_History.removeAllElements();
  340.     }
  341.   }
  342.   /**
  343.    * Adds an instance to the history buffer. If enough instances are in
  344.    * the buffer, a new instance may be output, with selected attribute
  345.    * values copied from one to another.
  346.    *
  347.    * @param instance the input instance
  348.    * @return a new instance with translated values, or null if no
  349.    * output instance is produced
  350.    */
  351.   protected Instance historyInput(Instance instance) {
  352.     m_History.push(instance);
  353.     if (m_History.size() <= Math.abs(m_InstanceRange)) {
  354.       if (getFillWithMissing() && (m_InstanceRange < 0)) {
  355. return mergeInstances(null, instance);
  356.       } else {
  357. return null;
  358.       }
  359.     }
  360.     if (m_InstanceRange < 0) {
  361.       return mergeInstances((Instance) m_History.pop(), instance);
  362.     } else {
  363.       return mergeInstances(instance, (Instance) m_History.pop());
  364.     }
  365.   }
  366.   /**
  367.    * Creates a new instance the same as one instance (the "destination")
  368.    * but with some attribute values copied from another instance
  369.    * (the "source")
  370.    *
  371.    * @param source the source instance
  372.    * @param dest the destination instance
  373.    * @return the new merged instance
  374.    */
  375.   protected abstract Instance mergeInstances(Instance source, Instance dest);
  376.   
  377. }