source: tags/MetisMQIDemo/src/test/java/weka/core/neighboursearch/AbstractNearestNeighbourSearchTest.java

Last change on this file was 29, checked in by gnappo, 15 years ago

Taggata versione per la demo e aggiunto branch.

File size: 11.0 KB
Line 
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/*
18 * Copyright (C) 2007 University of Waikato
19 */
20
21package weka.core.neighboursearch;
22
23import weka.core.CheckGOE;
24import weka.core.CheckOptionHandler;
25import weka.core.FastVector;
26import weka.core.Instances;
27import weka.core.SerializationHelper;
28import weka.test.Regression;
29
30import java.io.BufferedReader;
31import java.io.InputStreamReader;
32import java.util.Random;
33
34import junit.framework.TestCase;
35
36/**
37 * Abstract Test class for neighboursearch algorithms.
38 *
39 * @author FracPete (fracpete at waikato dot ac dot nz)
40 * @version $Revision: 1.1 $
41 */
42public abstract class AbstractNearestNeighbourSearchTest
43  extends TestCase {
44 
45  /** The NearestNeighbourSearch to be tested */
46  protected NearestNeighbourSearch m_NearestNeighbourSearch;
47 
48  /** the OptionHandler tester */
49  protected CheckOptionHandler m_OptionTester;
50 
51  /** for testing GOE stuff */
52  protected CheckGOE m_GOETester;
53
54  /** the dataset used for testing */
55  protected Instances m_Instances;
56
57  /** the number of neighbors to test */
58  protected int m_NumNeighbors;
59
60  /** for selecting random instances */
61  protected Random m_Random;
62 
63  /**
64   * Constructs the <code>AbstractNearestNeighbourSearchTest</code>.
65   * Called by subclasses.
66   *
67   * @param name the name of the test class
68   */
69  public AbstractNearestNeighbourSearchTest(String name) { 
70    super(name); 
71  }
72
73  /**
74   * Returns the Instances to be used in testing.
75   *
76   * @return            the test instances
77   * @throws Exception  if loading fails
78   */
79  protected Instances getInstances() throws Exception {
80    Instances   result;
81   
82    result = new Instances(
83                new BufferedReader(
84                    new InputStreamReader(
85                        ClassLoader.getSystemResourceAsStream(
86                            "weka/core/neighboursearch/anneal.arff"))));
87    result.setClassIndex(result.numAttributes() - 1);
88   
89    return result;
90  }
91 
92  /**
93   * Configures the CheckOptionHandler uses for testing the option handling.
94   * Sets the NearestNeighbourSearch returned from the
95   * getNearestNeighbourSearch() method
96   *
97   * @return    the fully configured CheckOptionHandler
98   * @see       #getNearestNeighbourSearch()
99   */
100  protected CheckOptionHandler getOptionTester() {
101    CheckOptionHandler          result;
102   
103    result = new CheckOptionHandler();
104    result.setOptionHandler(getNearestNeighbourSearch());
105    result.setUserOptions(new String[0]);
106    result.setSilent(true);
107   
108    return result;
109  }
110 
111  /**
112   * Configures the CheckGOE used for testing GOE stuff.
113   * Sets the NearestNeighbourSearch returned from the
114   * getNearestNeighbourSearch() method.
115   *
116   * @return    the fully configured CheckGOE
117   * @see       #getNearestNeighbourSearch()
118   */
119  protected CheckGOE getGOETester() {
120    CheckGOE            result;
121   
122    result = new CheckGOE();
123    result.setObject(getNearestNeighbourSearch());
124    result.setIgnoredProperties(result.getIgnoredProperties() + ",instances");
125    result.setSilent(true);
126   
127    return result;
128  }
129
130  /**
131   * Used to create an instance of a specific NearestNeighbourSearch.
132   *
133   * @return a suitably configured <code>NearestNeighbourSearch</code> value
134   */
135  public abstract NearestNeighbourSearch getNearestNeighbourSearch();
136 
137  /**
138   * Called by JUnit before each test method. This implementation creates
139   * the default NearestNeighbourSearch to test and loads a test set of Instances.
140   *
141   * @exception Exception if an error occurs reading the example instances.
142   */
143  protected void setUp() throws Exception {
144    m_NearestNeighbourSearch = getNearestNeighbourSearch();
145    m_OptionTester           = getOptionTester();
146    m_GOETester              = getGOETester();
147    m_Instances              = getInstances();
148    m_NumNeighbors           = 3;
149    m_Random                 = new Random(1);
150  }
151
152  /** Called by JUnit after each test method */
153  protected void tearDown() {
154    m_NearestNeighbourSearch = null;
155    m_OptionTester           = null;
156    m_GOETester              = null;
157    m_Instances              = null;
158    m_NumNeighbors           = 0;
159    m_Random                 = null;
160  }
161
162  /**
163   * tests whether the scheme declares a serialVersionUID.
164   */
165  public void testSerialVersionUID() {
166    boolean     result;
167
168    result = !SerializationHelper.needsUID(m_NearestNeighbourSearch.getClass());
169
170    if (!result)
171      fail("Doesn't declare serialVersionUID!");
172  }
173 
174  /**
175   * tests the listing of the options
176   */
177  public void testListOptions() {
178    if (!m_OptionTester.checkListOptions())
179      fail("Options cannot be listed via listOptions.");
180  }
181 
182  /**
183   * tests the setting of the options
184   */
185  public void testSetOptions() {
186    if (!m_OptionTester.checkSetOptions())
187      fail("setOptions method failed.");
188  }
189 
190  /**
191   * tests whether the default settings are processed correctly
192   */
193  public void testDefaultOptions() {
194    if (!m_OptionTester.checkDefaultOptions())
195      fail("Default options were not processed correctly.");
196  }
197 
198  /**
199   * tests whether there are any remaining options
200   */
201  public void testRemainingOptions() {
202    if (!m_OptionTester.checkRemainingOptions())
203      fail("There were 'left-over' options.");
204  }
205 
206  /**
207   * tests the whether the user-supplied options stay the same after setting.
208   * getting, and re-setting again.
209   *
210   * @see       #getOptionTester()
211   */
212  public void testCanonicalUserOptions() {
213    if (!m_OptionTester.checkCanonicalUserOptions())
214      fail("setOptions method failed");
215  }
216 
217  /**
218   * tests the resetting of the options to the default ones
219   */
220  public void testResettingOptions() {
221    if (!m_OptionTester.checkSetOptions())
222      fail("Resetting of options failed");
223  }
224 
225  /**
226   * tests for a globalInfo method
227   */
228  public void testGlobalInfo() {
229    if (!m_GOETester.checkGlobalInfo())
230      fail("No globalInfo method");
231  }
232 
233  /**
234   * tests the tool tips
235   */
236  public void testToolTips() {
237    if (!m_GOETester.checkToolTips())
238      fail("Tool tips inconsistent");
239  }
240
241  /**
242   * tests whether the number of instances returned by the algorithms is the
243   * same as was requested
244   */
245  public void testNumberOfNeighbors() {
246    int         i;
247    int         instIndex;
248    Instances   neighbors;
249   
250    try {
251      m_NearestNeighbourSearch.setInstances(m_Instances);
252    }
253    catch (Exception e) {
254      fail("Failed setting the instances: " + e);
255    }
256   
257    for (i = 1; i <= m_NumNeighbors; i++) {
258      instIndex = m_Random.nextInt(m_Instances.numInstances());
259      try {
260        neighbors = m_NearestNeighbourSearch.kNearestNeighbours(
261                        m_Instances.instance(instIndex), i);
262        assertEquals(
263            "Returned different number of neighbors than requested", 
264            i, neighbors.numInstances());
265      }
266      catch (Exception e) {
267        fail(
268            "Failed for " + i + " neighbors on instance " + (instIndex+1) 
269            + ": " + e);
270      }
271    }
272  }
273 
274  /**
275   * tests whether the tokenizer correctly initializes in the
276   * buildTokenizer method
277   */
278  public void testBuildInitialization() {
279    String[][][]        results;
280    Instances           inst;
281    int                 i;
282    int                 n;
283    int                 m;
284   
285    results = new String[2][m_Instances.numInstances()][m_NumNeighbors];
286   
287    // two runs of determining neighbors
288    for (i = 0; i < 2; i++) {
289      try {
290        m_NearestNeighbourSearch.setInstances(m_Instances);
291       
292        for (n = 0; n < m_Instances.numInstances(); n++) {
293          for (m = 1; m <= m_NumNeighbors; m++) {
294            inst = m_NearestNeighbourSearch.kNearestNeighbours(
295                        m_Instances.instance(n), m);
296            results[i][n][m - 1] = inst.toString();
297          }
298        }
299      }
300      catch (Exception e) {
301        fail("Build " + (i + 1) + " failed: " + e);
302      }
303    }
304   
305    // compare the results
306    for (n = 0; n < m_Instances.numInstances(); n++) {
307      for (m = 1; m <= m_NumNeighbors; m++) {
308        if (!results[0][n][m - 1].equals(results[1][n][m - 1]))
309          fail("Results differ: instance #" + (n+1) + " with " + m + " neighbors");
310      }
311    }
312  }
313
314  /**
315   * Runs the NearestNeighbourSearch with the given data and returns the
316   * generated results.
317   *
318   * @param data        the data to use
319   * @return            a <code>FastVector</code> containing the results.
320   * @throws Exception  if search fails
321   */
322  protected FastVector useNearestNeighbourSearch(Instances data) throws Exception {
323    FastVector          result;
324    int                 i;
325    int                 n;
326    int                 m;
327    Instances           inst;
328    StringBuffer        item;
329   
330    m_NearestNeighbourSearch.setInstances(m_Instances);
331   
332    result = new FastVector();
333    for (i = 0; i < m_Instances.numInstances(); i++) {
334      item = new StringBuffer((i+1) + ". " + m_Instances.instance(i).toString() + ": ");
335      for (n = 1; n <= m_NumNeighbors; n++) {
336        inst = m_NearestNeighbourSearch.kNearestNeighbours(
337                        m_Instances.instance(i), n);
338        item.append(" neighbors=" + n + ": ");
339        for (m = 0; m < inst.numInstances(); m++) {
340          if (m > 0)
341            item.append("; ");
342          item.append("neighbor_" + (m+1) + "=" + inst.instance(m));
343        }
344      }
345      result.addElement(item.toString());
346    }
347   
348    return result;
349     
350  }
351
352  /**
353   * Returns a string containing all the results.
354   *
355   * @param tokens      a <code>FastVector</code> containing the results
356   * @return            a <code>String</code> representing the vector of results.
357   */
358  protected String resultsToString(FastVector results) {
359    StringBuffer sb = new StringBuffer();
360   
361    sb.append(results.size()).append(" results for " + m_Instances.relationName() + ":\n");
362    for (int i = 0; i < results.size(); i++)
363      sb.append(results.elementAt(i)).append('\n');
364   
365    return sb.toString();
366  }
367
368  /**
369   * Runs a regression test -- this checks that the output of the tested
370   * object matches that in a reference version. When this test is
371   * run without any pre-existing reference output, the reference version
372   * is created.
373   */
374  public void testRegression() {
375    Regression  reg;
376    FastVector  regressionResult;
377   
378    reg = new Regression(this.getClass());
379   
380    try {
381      regressionResult = useNearestNeighbourSearch(m_Instances);
382      reg.println(resultsToString(regressionResult));
383    }
384    catch (Exception e) {
385      fail("Regression test failed: " + e);
386    }
387   
388    try {
389      String diff = reg.diff();
390      if (diff == null) {
391        System.err.println("Warning: No reference available, creating."); 
392      } else if (!diff.equals("")) {
393        fail("Regression test failed. Difference:\n" + diff);
394      }
395    } 
396    catch (java.io.IOException ex) {
397      fail("Problem during regression testing.\n" + ex);
398    }
399  }
400}
Note: See TracBrowser for help on using the repository browser.