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