StringToNominalFilter.java
Upload User: rhdiban
Upload Date: 2013-08-09
Package Size: 15085k
Code Size: 8k
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.  *    StringToNominalFilter.java
  18.  *    Copyright (C) 1999 Intelligenesis Corp.
  19.  *
  20.  */
  21. package weka.filters;
  22. import java.util.Enumeration;
  23. import java.util.Vector;
  24. import weka.core.Attribute;
  25. import weka.core.FastVector;
  26. import weka.core.Instance;
  27. import weka.core.Instances;
  28. import weka.core.Option;
  29. import weka.core.OptionHandler;
  30. import weka.core.Utils;
  31. import weka.core.UnsupportedAttributeTypeException;
  32. /** 
  33.  * Converts a string attribute (i.e. unspecified number of values) to nominal
  34.  * (i.e. set number of values). You should ensure that all string values that
  35.  * will appear are represented in the dataset.<p>
  36.  *
  37.  * Valid filter-specific options are: <p>
  38.  *
  39.  * -C col <br>
  40.  * Index of the attribute to be changed. (default last)<p>
  41.  *
  42.  * @author Len Trigg (len@intelligenesis.net) 
  43.  * @version $Revision: 1.6 $
  44.  */
  45. public class StringToNominalFilter extends Filter 
  46.   implements OptionHandler {
  47.   /** The attribute index setting (allows -1 = last). */
  48.   private int m_AttIndexSet = -1; 
  49.   /** The attribute index. */
  50.   private int m_AttIndex; 
  51.   /**
  52.    * Sets the format of the input instances.
  53.    *
  54.    * @param instanceInfo an Instances object containing the input 
  55.    * instance structure (any instances contained in the object are 
  56.    * ignored - only the structure is required).
  57.    * @return true if the outputFormat may be collected immediately.
  58.    * @exception UnsupportedAttributeTypeException if the selected attribute
  59.    * a string attribute.
  60.    * @exception Exception if the input format can't be set 
  61.    * successfully.
  62.    */
  63.   public boolean setInputFormat(Instances instanceInfo) 
  64.        throws Exception {
  65.     super.setInputFormat(instanceInfo);
  66.     m_AttIndex = m_AttIndexSet;
  67.     if (m_AttIndex < 0) {
  68.       m_AttIndex = instanceInfo.numAttributes() - 1;
  69.     }
  70.     if (!instanceInfo.attribute(m_AttIndex).isString()) {
  71.       throw new UnsupportedAttributeTypeException("Chosen attribute is not of type string.");
  72.     }
  73.     return false;
  74.   }
  75.   /**
  76.    * Input an instance for filtering. The instance is processed
  77.    * and made available for output immediately.
  78.    *
  79.    * @param instance the input instance.
  80.    * @return true if the filtered instance may now be
  81.    * collected with output().
  82.    * @exception IllegalStateException if no input structure has been defined.
  83.    */
  84.   public boolean input(Instance instance) {
  85.     if (getInputFormat() == null) {
  86.       throw new IllegalStateException("No input instance format defined");
  87.     }
  88.     if (m_NewBatch) {
  89.       resetQueue();
  90.       m_NewBatch = false;
  91.     }
  92.     if (isOutputFormatDefined()) {
  93.       Instance newInstance = (Instance)instance.copy();
  94.       push(newInstance);
  95.       return true;
  96.     }
  97.     bufferInput(instance);
  98.     return false;
  99.   }
  100.   /**
  101.    * Signifies that this batch of input to the filter is finished. If the 
  102.    * filter requires all instances prior to filtering, output() may now 
  103.    * be called to retrieve the filtered instances.
  104.    *
  105.    * @return true if there are instances pending output.
  106.    * @exception IllegalStateException if no input structure has been defined.
  107.    */
  108.   public boolean batchFinished() {
  109.     if (getInputFormat() == null) {
  110.       throw new IllegalStateException("No input instance format defined");
  111.     }
  112.     if (!isOutputFormatDefined()) {
  113.       setOutputFormat();
  114.       // Convert pending input instances
  115.       for(int i = 0; i < getInputFormat().numInstances(); i++) {
  116. push((Instance) getInputFormat().instance(i).copy());
  117.       }
  118.     } 
  119.     flushInput();
  120.     m_NewBatch = true;
  121.     return (numPendingOutput() != 0);
  122.   }
  123.   /**
  124.    * Returns an enumeration describing the available options.
  125.    *
  126.    * @return an enumeration of all the available options.
  127.    */
  128.   public Enumeration listOptions() {
  129.     Vector newVector = new Vector(1);
  130.     newVector.addElement(new Option(
  131.               "tSets the attribute index (default last).",
  132.               "C", 1, "-C <col>"));
  133.     return newVector.elements();
  134.   }
  135.   /**
  136.    * Parses the options for this object. Valid options are: <p>
  137.    *
  138.    * -C col <br>
  139.    * The column containing the values to be merged. (default last)<p>
  140.    *
  141.    * @param options the list of options as an array of strings
  142.    * @exception Exception if an option is not supported
  143.    */
  144.   public void setOptions(String[] options) throws Exception {
  145.     
  146.     String attributeIndex = Utils.getOption('C', options);
  147.     if (attributeIndex.length() != 0) {
  148.       if (attributeIndex.toLowerCase().equals("last")) {
  149. setAttributeIndex(-1);
  150.       } else if (attributeIndex.toLowerCase().equals("first")) {
  151. setAttributeIndex(0);
  152.       } else {
  153. setAttributeIndex(Integer.parseInt(attributeIndex) - 1);
  154.       }
  155.     } else {
  156.       setAttributeIndex(-1);
  157.     }
  158.        
  159.     if (getInputFormat() != null) {
  160.       setInputFormat(getInputFormat());
  161.     }
  162.   }
  163.   /**
  164.    * Gets the current settings of the filter.
  165.    *
  166.    * @return an array of strings suitable for passing to setOptions
  167.    */
  168.   public String [] getOptions() {
  169.     String [] options = new String [6];
  170.     int current = 0;
  171.     options[current++] = "-C";
  172.     options[current++] = "" + (getAttributeIndex() + 1);
  173.     while (current < options.length) {
  174.       options[current++] = "";
  175.     }
  176.     return options;
  177.   }
  178.   /**
  179.    * Get the index of the attribute used.
  180.    *
  181.    * @return the index of the attribute
  182.    */
  183.   public int getAttributeIndex() {
  184.     return m_AttIndexSet;
  185.   }
  186.   /**
  187.    * Sets index of the attribute used.
  188.    *
  189.    * @param index the index of the attribute
  190.    */
  191.   public void setAttributeIndex(int attIndex) {
  192.     
  193.     m_AttIndexSet = attIndex;
  194.   }
  195.   /**
  196.    * Set the output format. Takes the current average class values
  197.    * and m_InputFormat and calls setOutputFormat(Instances) 
  198.    * appropriately.
  199.    */
  200.   private void setOutputFormat() {
  201.     
  202.     Instances newData;
  203.     FastVector newAtts, newVals;
  204.       
  205.     // Compute new attributes
  206.       
  207.     newAtts = new FastVector(getInputFormat().numAttributes());
  208.     for (int j = 0; j < getInputFormat().numAttributes(); j++) {
  209.       Attribute att = getInputFormat().attribute(j);
  210.       if (j != m_AttIndex) {
  211. newAtts.addElement(att.copy()); 
  212.       } else {
  213.   
  214. // Compute list of attribute values
  215. newVals = new FastVector(att.numValues());
  216. for (int i = 0; i < att.numValues(); i++) {
  217.           newVals.addElement(att.value(i)); 
  218. }
  219. newAtts.addElement(new Attribute(att.name(), newVals));
  220.       }
  221.     }
  222.       
  223.     // Construct new header
  224.     newData = new Instances(getInputFormat().relationName(), newAtts, 0);
  225.     newData.setClassIndex(getInputFormat().classIndex());
  226.     setOutputFormat(newData);
  227.   }
  228.   
  229.   /**
  230.    * Main method for testing this class.
  231.    *
  232.    * @param argv should contain arguments to the filter: 
  233.    * use -h for help
  234.    */
  235.   public static void main(String [] argv) {
  236.     try {
  237.       if (Utils.getFlag('b', argv)) {
  238.   Filter.batchFilterFile(new StringToNominalFilter(), argv);
  239.       } else {
  240. Filter.filterFile(new StringToNominalFilter(), argv);
  241.       }
  242.     } catch (Exception ex) {
  243.       System.out.println(ex.getMessage());
  244.     }
  245.   }
  246. }