[weka] 02/05: Imported Upstream version 3.6.11
Tony Mancill
tmancill at moszumanska.debian.org
Sat May 3 22:55:41 UTC 2014
This is an automated email from the git hooks/post-receive script.
tmancill pushed a commit to branch master
in repository weka.
commit f22ed8552549483729abb30301c2d8d65b0e08ef
Author: tony mancill <tmancill at debian.org>
Date: Fri May 2 23:03:50 2014 -0700
Imported Upstream version 3.6.11
---
README | 6 +-
build.xml | 5 +-
changelogs/CHANGELOG-3-6-11 | 343 +++
changelogs/CHANGELOG-3-7-10 | 217 --
pom.xml | 2 +-
.../java/weka/attributeSelection/BestFirst.java | 3 +-
.../weka/attributeSelection/WrapperSubsetEval.java | 10 +-
src/main/java/weka/classifiers/Classifier.java | 229 +-
src/main/java/weka/classifiers/Evaluation.java | 3195 ++++++++++----------
.../search/global/GlobalScoreSearchAlgorithm.java | 2 +-
.../java/weka/classifiers/functions/LibSVM.java | 1570 +++++-----
.../functions/MultilayerPerceptron.java | 15 +-
.../functions/supportVector/PolyKernel.java | 15 +-
src/main/java/weka/classifiers/lazy/IBk.java | 9 +-
.../classifiers/mi/supportVector/MIPolyKernel.java | 13 +-
src/main/java/weka/classifiers/trees/ADTree.java | 8 +-
src/main/java/weka/classifiers/trees/LADTree.java | 6 +-
src/main/java/weka/classifiers/trees/REPTree.java | 12 +-
.../java/weka/classifiers/trees/RandomTree.java | 10 +-
.../java/weka/classifiers/trees/SimpleCart.java | 5 +-
.../java/weka/classifiers/trees/ft/FTtree.java | 6 +-
.../weka/classifiers/trees/j48/ClassifierTree.java | 14 +-
.../trees/j48/NBTreeClassifierTree.java | 11 +-
.../java/weka/classifiers/trees/lmt/LMTNode.java | 7 +-
.../java/weka/classifiers/trees/m5/RuleNode.java | 2 +-
src/main/java/weka/clusterers/EM.java | 25 +-
src/main/java/weka/clusterers/SimpleKMeans.java | 838 ++---
src/main/java/weka/clusterers/XMeans.java | 14 +-
.../DataObjects/EuclideanDataObject.java | 557 ++--
.../DataObjects/ManhattanDataObject.java | 561 ++--
src/main/java/weka/core/AttributeLocator.java | 287 +-
src/main/java/weka/core/Copyright.props | 4 +-
src/main/java/weka/core/DistanceFunction.java | 119 +-
src/main/java/weka/core/Instances.java | 129 +-
src/main/java/weka/core/Memory.java | 129 +-
src/main/java/weka/core/NormalizableDistance.java | 657 ++--
src/main/java/weka/core/Utils.java | 387 ++-
src/main/java/weka/core/converters/CSVLoader.java | 106 +-
src/main/java/weka/core/version.txt | 2 +-
.../java/weka/datagenerators/DataGenerator.java | 423 +--
src/main/java/weka/experiment/DatabaseUtils.java | 1234 ++++----
.../weka/experiment/DatabaseUtils.props.postgresql | 10 +-
.../weka/experiment/RegressionSplitEvaluator.java | 481 +--
.../filters/unsupervised/attribute/AddCluster.java | 1 +
.../unsupervised/attribute/RandomProjection.java | 6 +-
src/main/java/weka/gui/GUIChooser.java | 1099 ++++---
src/main/java/weka/gui/GenericObjectEditor.java | 1636 +++++-----
src/main/java/weka/gui/Main.java | 2232 +++++++-------
src/main/java/weka/gui/PropertySheetPanel.java | 902 +++---
src/main/java/weka/gui/arffviewer/ArffViewer.java | 285 +-
src/main/java/weka/gui/beans/Filter.java | 6 +-
.../java/weka/gui/beans/SerializedModelSaver.java | 430 +--
.../java/weka/gui/experiment/Experimenter.java | 145 +-
.../java/weka/gui/explorer/ClassifierPanel.java | 1310 ++++----
src/main/java/weka/gui/explorer/Explorer.java | 306 +-
.../weka/gui/explorer/messages/messages.properties | 5 +-
.../gui/graphvisualizer/HierarchicalBCEngine.java | 4 +-
src/main/java/weka/gui/sql/SqlViewer.java | 476 +--
.../attributeSelection/WrapperSubsetEvalTest.ref | 4 +-
.../functions/GaussianProcessesTest.ref | 20 +-
.../functions/IsotonicRegressionTest.ref | 20 +-
.../weka/classifiers/functions/LeastMedSqTest.ref | 20 +-
.../classifiers/functions/LinearRegressionTest.ref | 20 +-
.../classifiers/functions/PLSClassifierTest.ref | 20 +-
.../classifiers/functions/PaceRegressionTest.ref | 60 +-
.../weka/classifiers/functions/RBFNetworkTest.ref | 40 +-
.../weka/classifiers/functions/SMOregTest.ref | 20 +-
.../functions/SimpleLinearRegressionTest.ref | 20 +-
.../classifiers/meta/AdditiveRegressionTest.ref | 20 +-
.../wekarefs/weka/classifiers/meta/BaggingTest.ref | 20 +-
.../weka/classifiers/meta/RandomSubSpaceTest.ref | 20 +-
.../meta/RegressionByDiscretizationTest.ref | 20 +-
.../weka/classifiers/rules/M5RulesTest.ref | 20 +-
.../wekarefs/weka/classifiers/trees/M5PTest.ref | 20 +-
wekadocs/README | 6 +-
wekadocs/manual/manual.tex | 6 +-
76 files changed, 11236 insertions(+), 9661 deletions(-)
diff --git a/README b/README
index 7153a48..74956df 100644
--- a/README
+++ b/README
@@ -4,12 +4,12 @@
README
======
- WEKA 3.6.10
- 31 July 2013
+ WEKA 3.6.11
+ 24 April 2014
Java Programs for Machine Learning
- Copyright (C) 1998-2013 University of Waikato
+ Copyright (C) 1998-2014 University of Waikato
web: http://www.cs.waikato.ac.nz/~ml/weka
diff --git a/build.xml b/build.xml
index 7aee4a9..6b07357 100644
--- a/build.xml
+++ b/build.xml
@@ -9,7 +9,7 @@
Build file can reside and be executed from either inside weka or the
directory containing weka.
- $Revision: 9466 $
+ $Revision: 10685 $
===========================================================================
-->
@@ -488,9 +488,8 @@
</target>
<target name="superclean" depends="clean"
- description="Clean plus removes source trees! and doc directories">
+ description="Clean plus removes source trees!">
<!-- WARNING, this deletes the source and doc directories -->
<delete dir="${src}"/>
- <delete dir="${doc}"/>
</target>
</project>
diff --git a/changelogs/CHANGELOG-3-6-11 b/changelogs/CHANGELOG-3-6-11
new file mode 100644
index 0000000..b2abc9d
--- /dev/null
+++ b/changelogs/CHANGELOG-3-6-11
@@ -0,0 +1,343 @@
+------------------------------------------------------------------------
+r9937 | mhall | 2013-07-31 10:28:24 +1200 (Wed, 31 Jul 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/last-release.props
+ M /branches/stable-3-6/weka/src/main/java/weka/core/version.txt
+
+Version is now 3.6.11-snapshot; updated date in last-release.props
+------------------------------------------------------------------------
+r9967 | mhall | 2013-08-02 09:15:46 +1200 (Fri, 02 Aug 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/beans/Filter.java
+
+The variable holding the reference to the Thread used to perform filtering was not transient - fixed.
+------------------------------------------------------------------------
+r9986 | mhall | 2013-08-08 20:13:39 +1200 (Thu, 08 Aug 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/clusterers/XMeans.java
+
+The -O option now actually works - this was not implemented before :-) Furthermore, the Reader/Writer for IO of cluster center files are now closed properly after use and marked as transient (thus fixing not serializable exceptions).
+------------------------------------------------------------------------
+r9988 | mhall | 2013-08-09 22:13:38 +1200 (Fri, 09 Aug 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/clusterers/EM.java
+
+Now uses the model from the previous iteration if there is a slight decrease in log likelihood when iterating.
+------------------------------------------------------------------------
+r9993 | mhall | 2013-08-16 15:42:03 +1200 (Fri, 16 Aug 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/functions/supportVector/PolyKernel.java
+
+Bernhard's fix for a memory leak that got applied to the trunk but not here - fixed.
+------------------------------------------------------------------------
+r10021 | mhall | 2013-09-18 08:55:02 +1200 (Wed, 18 Sep 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/explorer/messages/messages.properties
+
+Fixed a typo
+------------------------------------------------------------------------
+r10029 | mhall | 2013-09-23 20:00:49 +1200 (Mon, 23 Sep 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/attribute/RandomProjection.java
+
+Fixed a bug where the class attribute was not being copied when creating the output structure.
+------------------------------------------------------------------------
+r10036 | mhall | 2013-09-25 23:09:05 +1200 (Wed, 25 Sep 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/mi/supportVector/MIPolyKernel.java
+
+Backported the clean() method from Weka 3.7.
+------------------------------------------------------------------------
+r10069 | mhall | 2013-10-14 09:46:50 +1300 (Mon, 14 Oct 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/lazy/IBk.java
+
+Updated the tip text for the cross-validate option.
+------------------------------------------------------------------------
+r10073 | mhall | 2013-10-14 14:16:48 +1300 (Mon, 14 Oct 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/functions/MultilayerPerceptron.java
+
+Bug fix from Eibe: MultilayerPerceptron no longer modifies the values of the test instances that are passed into distributionForInstance()...
+------------------------------------------------------------------------
+r10084 | mhall | 2013-10-18 19:54:08 +1300 (Fri, 18 Oct 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/core/converters/CSVLoader.java
+
+Was treating white space only entries as nominal values rather than missing - fixed.
+------------------------------------------------------------------------
+r10089 | mhall | 2013-10-18 22:45:36 +1300 (Fri, 18 Oct 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/core/converters/CSVLoader.java
+
+Javadoc fix.
+------------------------------------------------------------------------
+r10114 | mhall | 2013-10-25 18:38:35 +1300 (Fri, 25 Oct 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/bayes/net/search/global/GlobalScoreSearchAlgorithm.java
+
+Fixed a bug in the k-fold CV routine.
+------------------------------------------------------------------------
+r10127 | mhall | 2013-11-05 20:22:14 +1300 (Tue, 05 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/datagenerators/DataGenerator.java
+
+Changed the default output to be System.out instead of a StringWriter. This allows large datasets to be produced incrementally via redirection (rather than having to use -o) in the console and SimpleCLI.
+------------------------------------------------------------------------
+r10131 | mhall | 2013-11-08 14:22:38 +1300 (Fri, 08 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/clusterers/SimpleKMeans.java
+
+Fixed a bug where cluster nominal attribute value counts were not getting set properly when empty clusters were pruned. Only affected the case when empty clusters occurred and the user had opted to output standard deviations/frequency counts.
+------------------------------------------------------------------------
+r10206 | mhall | 2013-11-19 14:21:59 +1300 (Tue, 19 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/experiment/DatabaseUtils.java
+
+Changed the default for autoCommit (if not explicitly defined in the DatabaseUtils.props file) from false to true.
+------------------------------------------------------------------------
+r10256 | mhall | 2013-11-28 11:58:38 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/j48/ClassifierTree.java
+
+Now back-quotes characters in node labels for the graph output.
+------------------------------------------------------------------------
+r10258 | mhall | 2013-11-28 12:20:08 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/ADTree.java
+
+Now back-quotes characters in node labels for the graph output.
+------------------------------------------------------------------------
+r10259 | mhall | 2013-11-28 13:05:33 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/ft/FTtree.java
+
+Now back-quotes characters in node labels for the graph output.
+------------------------------------------------------------------------
+r10260 | mhall | 2013-11-28 13:07:10 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/LADTree.java
+
+Now back-quotes characters in node labels for the graph output.
+------------------------------------------------------------------------
+r10263 | mhall | 2013-11-28 13:12:41 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/lmt/LMTNode.java
+
+Now back-quotes characters in node labels for the graph output.
+------------------------------------------------------------------------
+r10265 | mhall | 2013-11-28 13:15:38 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/m5/RuleNode.java
+
+Now back-quotes characters in node labels for the graph output.
+------------------------------------------------------------------------
+r10267 | mhall | 2013-11-28 13:20:24 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/j48/NBTreeClassifierTree.java
+
+Now back-quotes characters in node labels for the graph output.
+------------------------------------------------------------------------
+r10269 | mhall | 2013-11-28 14:01:36 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/RandomTree.java
+
+Now back-quotes characters in node labels for the graph output.
+------------------------------------------------------------------------
+r10275 | mhall | 2013-11-28 14:17:35 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/REPTree.java
+
+Now back-quotes characters in node labels for the graph output.
+------------------------------------------------------------------------
+r10277 | mhall | 2013-11-28 14:20:02 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/ft/FTtree.java
+
+Changed Utils.quote() to Utils.backQuoteChars() in graph routine.
+------------------------------------------------------------------------
+r10278 | mhall | 2013-11-28 14:20:55 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/ADTree.java
+
+Changed Utils.quote() to Utils.backQuoteChars() in graph routine.
+------------------------------------------------------------------------
+r10279 | mhall | 2013-11-28 14:21:44 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/LADTree.java
+
+Changed Utils.quote() to Utils.backQuoteChars() in graph routine.
+------------------------------------------------------------------------
+r10281 | mhall | 2013-11-28 14:23:42 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/lmt/LMTNode.java
+
+Changed Utils.quote() to Utils.backQuoteChars() in graph routine.
+------------------------------------------------------------------------
+r10284 | mhall | 2013-11-28 14:26:33 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/m5/RuleNode.java
+
+Changed Utils.quote() to Utils.backQuoteChars() in graph routine.
+------------------------------------------------------------------------
+r10286 | mhall | 2013-11-28 14:28:14 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/j48/NBTreeClassifierTree.java
+
+Changed Utils.quote() to Utils.backQuoteChars() in graph routine.
+------------------------------------------------------------------------
+r10287 | mhall | 2013-11-28 14:28:51 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/RandomTree.java
+
+Changed Utils.quote() to Utils.backQuoteChars() in graph routine.
+------------------------------------------------------------------------
+r10290 | mhall | 2013-11-28 14:36:32 +1300 (Thu, 28 Nov 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/ADTree.java
+
+Changed Utils.quote() to Utils.backQuoteChars() in graph routine.
+------------------------------------------------------------------------
+r10372 | mhall | 2013-12-06 13:59:18 +1300 (Fri, 06 Dec 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/core/converters/CSVLoader.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/explorer/ClassifierPanel.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/explorer/messages/messages.properties
+
+Now pops up an error dialog (rather than throwing an IllegalArgumentException) if the user does not enter a valid range string for additional attribute output when printing predictions. The process also continues after the user presses OK in the dialog.
+------------------------------------------------------------------------
+r10397 | mhall | 2013-12-17 13:28:56 +1300 (Tue, 17 Dec 2013) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/attributeSelection/BestFirst.java
+
+Fixed the incomplete tool-tip text for the search termination property.
+------------------------------------------------------------------------
+r10412 | mhall | 2014-01-22 10:16:14 +1300 (Wed, 22 Jan 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/experiment/DatabaseUtils.props.postgresql
+
+A few type mapping additions (and a link to a useful document on PostgreSQL type mappings to Java classes) courtesy of Emmanuel Turner.
+------------------------------------------------------------------------
+r10424 | mhall | 2014-01-29 12:09:16 +1300 (Wed, 29 Jan 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/attributeSelection/WrapperSubsetEval.java
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/attributeSelection/WrapperSubsetEvalTest.ref
+
+Now prints accuracy (rather than error rate) when the class is nominal)
+------------------------------------------------------------------------
+r10425 | mhall | 2014-01-29 13:45:09 +1300 (Wed, 29 Jan 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/attribute/AddCluster.java
+
+Now enables capabilities for all class types.
+------------------------------------------------------------------------
+r10438 | mhall | 2014-02-13 11:40:54 +1300 (Thu, 13 Feb 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/core/Memory.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/GUIChooser.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/Main.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/arffviewer/ArffViewer.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/experiment/Experimenter.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/explorer/Explorer.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/sql/SqlViewer.java
+
+Shifted Thread.sleep() call out of each GUI's main() method and into Memory.isOutOfMemory(). isOutOfMemory() now attempts to adaptively adjust the sleep delay based on the amount of heap space still available
+------------------------------------------------------------------------
+r10475 | mhall | 2014-03-03 15:20:07 +1300 (Mon, 03 Mar 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/experiment/RegressionSplitEvaluator.java
+
+Now includes number unclassified and percent unclassified in the list of metrics computed.
+------------------------------------------------------------------------
+r10485 | mhall | 2014-03-04 21:02:08 +1300 (Tue, 04 Mar 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/Classifier.java
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/functions/GaussianProcessesTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/functions/IsotonicRegressionTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/functions/LeastMedSqTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/functions/LinearRegressionTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/functions/PLSClassifierTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/functions/PaceRegressionTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/functions/RBFNetworkTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/functions/SMOregTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/functions/SimpleLinearRegressionTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/meta/AdditiveRegressionTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/meta/BaggingTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/meta/RandomSubSpaceTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/meta/RegressionByDiscretizationTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/rules/M5RulesTest.ref
+ M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/classifiers/trees/M5PTest.ref
+
+Class attributes that are date attributes need to be treated the same way as classes that are numeric attributes... Behaviour of default methods for classifyInstance() and distributionForInstance() were previously broken for class attributes that were date attributes (they simply returned a missing value.)
+------------------------------------------------------------------------
+r10491 | mhall | 2014-03-06 20:09:36 +1300 (Thu, 06 Mar 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/SimpleCart.java
+
+From Eibe: Fixed problem where unprune() step caused root node to not be labeled a leaf when it really is a leaf. This only caused problems when unpruned tree consists of a single node that is a leaf node.
+------------------------------------------------------------------------
+r10497 | mhall | 2014-03-10 14:33:50 +1300 (Mon, 10 Mar 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/core/Instances.java
+
+Improved Javadoc for enumerateAttributes(): class is skipped when set.
+------------------------------------------------------------------------
+r10503 | mhall | 2014-03-11 21:41:40 +1300 (Tue, 11 Mar 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/graphvisualizer/HierarchicalBCEngine.java
+
+A for loop was using an index variable of type byte, which would overflow for graphs with more than 127 levels - fixed.
+------------------------------------------------------------------------
+r10534 | mhall | 2014-03-22 16:15:11 +1300 (Sat, 22 Mar 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/beans/SerializedModelSaver.java
+
+No longer causes upstream steps to grind to a halt if there is a problem saving the model. This also allows a proper error message to be displayed by the step (previously it wasn't happening).
+------------------------------------------------------------------------
+r10537 | mhall | 2014-03-22 16:37:44 +1300 (Sat, 22 Mar 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/clusterers/SimpleKMeans.java
+ M /branches/stable-3-6/weka/src/main/java/weka/core/DistanceFunction.java
+ M /branches/stable-3-6/weka/src/main/java/weka/core/NormalizableDistance.java
+
+Added a clean() method. Implementers should release any non-essential resources (such as copies of the training data) when this is called. Serialized SimpleKMeans models should be smaller now that it calls this new clean() method after buildClusterer() finishes.
+------------------------------------------------------------------------
+r10570 | mhall | 2014-03-31 18:59:23 +1300 (Mon, 31 Mar 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/core/Utils.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/GenericObjectEditor.java
+ M /branches/stable-3-6/weka/src/main/java/weka/gui/PropertySheetPanel.java
+
+Added tool tips displaying global info and capabilities information for schemes at the leaves of the JTree displayed by the GenericObjectEditor
+------------------------------------------------------------------------
+r10578 | mhall | 2014-04-01 14:49:44 +1300 (Tue, 01 Apr 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/EuclideanDataObject.java
+ M /branches/stable-3-6/weka/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/ManhattanDataObject.java
+
+From Eibe: Handling of sparse instances is now implemented correctly
+------------------------------------------------------------------------
+r10619 | mhall | 2014-04-09 12:53:55 +1200 (Wed, 09 Apr 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/Evaluation.java
+
+Some changes by Eibe ported to 3.6: cleaned up handling of no-cv a bit. Confusion matrix on training data is now output even if no-cv is specified. Incremental testing is now done when no-cv is specified.
+------------------------------------------------------------------------
+r10644 | mhall | 2014-04-16 15:40:08 +1200 (Wed, 16 Apr 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/core/Copyright.props
+
+Updated copyright date
+------------------------------------------------------------------------
+r10654 | mhall | 2014-04-22 10:39:10 +1200 (Tue, 22 Apr 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/core/AttributeLocator.java
+
+From Eibe:AttributeLocator now uses BitSet and ArrayList rather than Vector. In particular, BitSet is used instead of Vector<Byte>, resulting in *HUGE* space savings when using filters to process/produce large-dimensional datasets! Also removed occurrences of DenseInstance in error messages originating in AbstractInstance. Finally, improved efficiency of insertAttributeAt() and deleteAttributeAt() in Instances and added new method replaceAttributeAtt(), replacing almost all calls of inse [...]
+------------------------------------------------------------------------
+r10660 | mhall | 2014-04-23 11:37:31 +1200 (Wed, 23 Apr 2014) | 1 line
+Changed paths:
+ M /branches/stable-3-6/weka/src/main/java/weka/classifiers/functions/LibSVM.java
+
+Added missing values as a capability (since the replace missing values filter is applied internally by default). Now pre-processes nominal attributes with the unsupervised nominal to binary filter.
+------------------------------------------------------------------------
diff --git a/changelogs/CHANGELOG-3-7-10 b/changelogs/CHANGELOG-3-7-10
deleted file mode 100644
index 1b55227..0000000
--- a/changelogs/CHANGELOG-3-7-10
+++ /dev/null
@@ -1,217 +0,0 @@
-------------------------------------------------------------------------
-r9507 | mhall | 2013-01-25 11:45:50 +1300 (Fri, 25 Jan 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/core/version.txt
-
-stable-3-6 branch is now 3.6.10
-------------------------------------------------------------------------
-r9513 | mhall | 2013-01-25 14:18:34 +1300 (Fri, 25 Jan 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/core/Version.java
- M /branches/stable-3-6/weka/src/main/java/weka/core/version.txt
-
-Now handles version numbers with '-snapshot' in them
-------------------------------------------------------------------------
-r9518 | mhall | 2013-01-30 12:11:12 +1300 (Wed, 30 Jan 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/core/Attribute.java
-
-String attributes now have a dummy first value that is unlikely to ever occur as a real value.
-------------------------------------------------------------------------
-r9524 | mhall | 2013-02-08 03:58:06 +1300 (Fri, 08 Feb 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/RandomTree.java
-
-Added a serial version UID for inner Tree class.
-------------------------------------------------------------------------
-r9525 | mhall | 2013-02-08 04:00:16 +1300 (Fri, 08 Feb 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/classifiers/trees/RandomTree.java
-
-Quick javadoc fix.
-------------------------------------------------------------------------
-r9529 | mhall | 2013-02-08 08:27:10 +1300 (Fri, 08 Feb 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/attribute/InterquartileRange.java
- M /branches/stable-3-6/weka/src/test/java/weka/filters/unsupervised/attribute/InterquartileRangeTest.java
- M /branches/stable-3-6/weka/src/test/resources/wekarefs/weka/filters/unsupervised/attribute/InterquartileRangeTest.ref
-
-Capabilities corrected to reflect the fact that this filter does not handle missing values
-------------------------------------------------------------------------
-r9565 | mhall | 2013-02-19 20:08:15 +1300 (Tue, 19 Feb 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/attribute/StringToWordVector.java
-
-Now checks for a non-nominal class and turns on doNotOperateOnPerClassBasis in that case.
-------------------------------------------------------------------------
-r9566 | mhall | 2013-02-19 20:30:09 +1300 (Tue, 19 Feb 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/classifiers/functions/GaussianProcesses.java
-
-GaussianProcesses model now requires less memory after training because kernel cache is cleared after training.
-------------------------------------------------------------------------
-r9570 | mhall | 2013-02-19 22:27:27 +1300 (Tue, 19 Feb 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/attribute/KernelFilter.java
-
-Fixed bug in KernelFilter: now works with nominal class attributes as well.
-------------------------------------------------------------------------
-r9653 | mhall | 2013-03-21 16:24:36 +1300 (Thu, 21 Mar 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/core/converters/ArffLoader.java
-
-Now makes sure that the source reader is closed if an exception occurs during reading.
-------------------------------------------------------------------------
-r9657 | mhall | 2013-04-04 08:31:22 +1300 (Thu, 04 Apr 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/filters/supervised/instance/SMOTE.java
-
-Fixed a sorting problem that occurs under Java 7
-------------------------------------------------------------------------
-r9666 | mhall | 2013-04-05 16:20:09 +1300 (Fri, 05 Apr 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/attribute/PropositionalToMultiInstance.java
-
-Added option not to weight the bags by the number of instances they contain.
-------------------------------------------------------------------------
-r9692 | mhall | 2013-04-14 20:01:20 +1200 (Sun, 14 Apr 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/attributeSelection/GainRatioAttributeEval.java
-
-Now supports instance weights.
-------------------------------------------------------------------------
-r9697 | mhall | 2013-04-16 20:49:07 +1200 (Tue, 16 Apr 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/gui/beans/LogPanel.java
-
-Now formats timer digits so that each element always has two digits.
-------------------------------------------------------------------------
-r9700 | mhall | 2013-04-16 22:50:27 +1200 (Tue, 16 Apr 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/gui/beans/LogPanel.java
-
-Made the formatter a member variable rather than local to the timer.
-------------------------------------------------------------------------
-r9718 | mhall | 2013-05-19 15:48:03 +1200 (Sun, 19 May 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/filters/MultiFilter.java
- M /branches/stable-3-6/weka/src/main/java/weka/filters/SimpleStreamFilter.java
-
-MultiFilter was generating a npe in the case where a filter in the chain was streamable but did not produce an output instance at a given point - an example is RemoveWithValues where the input instance is consumed because it does not match. Fixed.
-------------------------------------------------------------------------
-r9728 | mhall | 2013-05-29 04:26:13 +1200 (Wed, 29 May 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/gui/explorer/ClustererPanel.java
-
-Some clusterers were greyed out when classes to clusters evaluation was selected, even if all attributes apart from the class pass the Capabilities check - fixed.
-------------------------------------------------------------------------
-r9731 | mhall | 2013-05-30 01:32:49 +1200 (Thu, 30 May 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/gui/explorer/ClassifierPanel.java
-
-PMML was appearing as a file type in the save classifier dialog - fixed.
-------------------------------------------------------------------------
-r9733 | mhall | 2013-05-30 06:44:39 +1200 (Thu, 30 May 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/classifiers/meta/GridSearch.java
-
-Capabilities now allow unary class. This allows LibSVM and other one class classifiers to be used with GridSearch.
-------------------------------------------------------------------------
-r9737 | mhall | 2013-06-01 08:47:11 +1200 (Sat, 01 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/core/Utils.java
-
-eq(), smOrEq() and grOrEq() now return true when both arguments are negative or positive infinity.
-------------------------------------------------------------------------
-r9751 | mhall | 2013-06-10 20:26:33 +1200 (Mon, 10 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/gui/beans/TrainingSetMaker.java
-
-Now accepts testSet connections.
-------------------------------------------------------------------------
-r9752 | mhall | 2013-06-10 20:28:22 +1200 (Mon, 10 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/gui/beans/TestSetMaker.java
-
-Now accepts trainingSet connections.
-------------------------------------------------------------------------
-r9755 | mhall | 2013-06-11 20:18:07 +1200 (Tue, 11 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/gui/explorer/ClassifierPanel.java
-
-File type filter is now defaults to "Model object files" again.
-------------------------------------------------------------------------
-r9758 | mhall | 2013-06-11 21:37:01 +1200 (Tue, 11 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/clusterers/SimpleKMeans.java
-
-Fixed an option description.
-------------------------------------------------------------------------
-r9764 | mhall | 2013-06-18 09:20:53 +1200 (Tue, 18 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/core/Instances.java
-
-sort() was slow due to stupidity on my part :-) Fixed.
-------------------------------------------------------------------------
-r9770 | mhall | 2013-06-18 20:56:29 +1200 (Tue, 18 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/classifiers/functions/LinearRegression.java
- M /branches/stable-3-6/weka/src/main/java/weka/core/matrix/LinearRegression.java
-
-Changes courtesy of Sean Daugherty that save memory and improve the speed of LinearRegression
-------------------------------------------------------------------------
-r9800 | fracpete | 2013-06-26 10:14:21 +1200 (Wed, 26 Jun 2013) | 2 lines
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/gui/explorer/PreprocessPanel.java
- M /branches/waikato/weka/src/main/java/weka/gui/explorer/PreprocessPanel.java
- M /trunk/weka/src/main/java/weka/gui/explorer/PreprocessPanel.java
-
-applyFilter(Filter) method now creates a copy of the supplied filter to avoid anything leaking back, e.g., into the GOE
-otherwise problems can arise, e.g., with an AddClassification filter that holds on to its loaded model
-------------------------------------------------------------------------
-r9804 | fracpete | 2013-06-26 14:39:04 +1200 (Wed, 26 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/instance/SubsetByExpression.java
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/instance/subsetbyexpression/Parser.cup
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/instance/subsetbyexpression/Parser.java
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/instance/subsetbyexpression/Scanner.java
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/instance/subsetbyexpression/sym.java
- M /trunk/weka/src/main/java/weka/filters/unsupervised/instance/SubsetByExpression.java
- M /trunk/weka/src/main/java/weka/filters/unsupervised/instance/subsetbyexpression/Parser.cup
- M /trunk/weka/src/main/java/weka/filters/unsupervised/instance/subsetbyexpression/Parser.java
- M /trunk/weka/src/main/java/weka/filters/unsupervised/instance/subsetbyexpression/Scanner.java
- M /trunk/weka/src/main/java/weka/filters/unsupervised/instance/subsetbyexpression/sym.java
-
-SubsetByExpression filter now handles STRING attributes as well
-------------------------------------------------------------------------
-r9814 | mhall | 2013-06-27 12:33:26 +1200 (Thu, 27 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/attribute/RemoveType.java
-
-Class should always be kept if set, even if selection is inverted.
-------------------------------------------------------------------------
-r9819 | mhall | 2013-06-27 14:58:01 +1200 (Thu, 27 Jun 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/filters/unsupervised/attribute/NominalToBinary.java
-
-Now implements StreamableFilter.
-------------------------------------------------------------------------
-r9835 | mhall | 2013-07-01 10:42:41 +1200 (Mon, 01 Jul 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/classifiers/rules/ConjunctiveRule.java
-
-Migrated Eibe's bug fix: Fixed bug significantly affecting results when nominal attributes are present. Rule growing stopped much too early.
-------------------------------------------------------------------------
-r9892 | mhall | 2013-07-25 14:30:27 +1200 (Thu, 25 Jul 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/gui/arffviewer/ArffViewerMainPanel.java
-
-Fixed a bug that occurred under Windows only when using the ArffViewer from the command line or GUIChooser - Save as would fail to save the current set of instances and claim that the chosen file name already exists.
-------------------------------------------------------------------------
-r9897 | mhall | 2013-07-25 20:11:43 +1200 (Thu, 25 Jul 2013) | 1 line
-Changed paths:
- M /branches/stable-3-6/weka/src/main/java/weka/classifiers/functions/supportVector/Kernel.java
- M /branches/stable-3-6/weka/src/main/java/weka/classifiers/functions/supportVector/PrecomputedKernelMatrixKernel.java
-
-PrecomputedKernelMatrixKernel now implements Copyable (so that shallow copies can be made) and Kernel.makeCopy and Kernel.makeCopies now check for Copyable before using deep copying via serialization
-------------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index f025568..2780090 100644
--- a/pom.xml
+++ b/pom.xml
@@ -5,7 +5,7 @@
<groupId>nz.ac.waikato.cms.weka</groupId>
<artifactId>weka-stable</artifactId>
- <version>3.6.10-SNAPSHOT</version><!-- weka-version -->
+ <version>3.6.11-SNAPSHOT</version><!-- weka-version -->
<packaging>jar</packaging>
<name>weka-stable</name>
diff --git a/src/main/java/weka/attributeSelection/BestFirst.java b/src/main/java/weka/attributeSelection/BestFirst.java
index 686c165..192f3fa 100644
--- a/src/main/java/weka/attributeSelection/BestFirst.java
+++ b/src/main/java/weka/attributeSelection/BestFirst.java
@@ -483,7 +483,8 @@ public class BestFirst
* displaying in the explorer/experimenter gui
*/
public String searchTerminationTipText() {
- return "Set the amount of backtracking. Specify the number of ";
+ return "Specify the number of consecutive non-improving nodes to allow " +
+ "before terminating the search.";
}
/**
diff --git a/src/main/java/weka/attributeSelection/WrapperSubsetEval.java b/src/main/java/weka/attributeSelection/WrapperSubsetEval.java
index 10407d1..e24eaab 100644
--- a/src/main/java/weka/attributeSelection/WrapperSubsetEval.java
+++ b/src/main/java/weka/attributeSelection/WrapperSubsetEval.java
@@ -108,7 +108,7 @@ import java.util.Vector;
<!-- options-end -->
*
* @author Mark Hall (mhall at cs.waikato.ac.nz)
- * @version $Revision: 7433 $
+ * @version $Revision: 10424 $
*/
public class WrapperSubsetEval
extends ASEvaluation
@@ -575,7 +575,7 @@ public class WrapperSubsetEval
errorRate /= (double)i;
m_Evaluation = null;
- return -errorRate;
+ return m_trainInstances.classAttribute().isNumeric() ? -errorRate : 1.0 - errorRate;
}
@@ -607,9 +607,9 @@ public class WrapperSubsetEval
text.append("\n");
if (m_trainInstances.attribute(m_classIndex).isNumeric()) {
- text.append("\tAccuracy estimation: RMSE\n");
+ text.append("\tSubset evaluation: RMSE\n");
} else {
- text.append("\tAccuracy estimation: classification error\n");
+ text.append("\tSubset evaluation: classification accuracy\n");
}
text.append("\tNumber of folds for accuracy estimation: "
@@ -675,7 +675,7 @@ public class WrapperSubsetEval
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 7433 $");
+ return RevisionUtils.extract("$Revision: 10424 $");
}
/**
diff --git a/src/main/java/weka/classifiers/Classifier.java b/src/main/java/weka/classifiers/Classifier.java
index 72104d9..fb81522 100644
--- a/src/main/java/weka/classifiers/Classifier.java
+++ b/src/main/java/weka/classifiers/Classifier.java
@@ -22,6 +22,10 @@
package weka.classifiers;
+import java.io.Serializable;
+import java.util.Enumeration;
+import java.util.Vector;
+
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.CapabilitiesHandler;
@@ -34,54 +38,47 @@ import weka.core.RevisionUtils;
import weka.core.SerializedObject;
import weka.core.Utils;
-import java.io.Serializable;
-import java.util.Enumeration;
-import java.util.Vector;
-
-/**
- * Abstract classifier. All schemes for numeric or nominal prediction in
- * Weka extend this class. Note that a classifier MUST either implement
+/**
+ * Abstract classifier. All schemes for numeric or nominal prediction in Weka
+ * extend this class. Note that a classifier MUST either implement
* distributionForInstance() or classifyInstance().
- *
+ *
* @author Eibe Frank (eibe at cs.waikato.ac.nz)
* @author Len Trigg (trigg at cs.waikato.ac.nz)
- * @version $Revision: 5536 $
+ * @version $Revision: 10485 $
*/
-public abstract class Classifier
- implements Cloneable, Serializable, OptionHandler, CapabilitiesHandler,
- RevisionHandler {
-
+public abstract class Classifier implements Cloneable, Serializable,
+ OptionHandler, CapabilitiesHandler, RevisionHandler {
+
/** for serialization */
private static final long serialVersionUID = 6502780192411755341L;
-
+
/** Whether the classifier is run in debug mode. */
protected boolean m_Debug = false;
/**
- * Generates a classifier. Must initialize all fields of the classifier
- * that are not being set via options (ie. multiple calls of buildClassifier
- * must always lead to the same result). Must not change the dataset
- * in any way.
- *
- * @param data set of instances serving as training data
- * @exception Exception if the classifier has not been
- * generated successfully
+ * Generates a classifier. Must initialize all fields of the classifier that
+ * are not being set via options (ie. multiple calls of buildClassifier must
+ * always lead to the same result). Must not change the dataset in any way.
+ *
+ * @param data set of instances serving as training data
+ * @exception Exception if the classifier has not been generated successfully
*/
public abstract void buildClassifier(Instances data) throws Exception;
/**
- * Classifies the given test instance. The instance has to belong to a
- * dataset when it's being classified. Note that a classifier MUST
- * implement either this or distributionForInstance().
- *
+ * Classifies the given test instance. The instance has to belong to a dataset
+ * when it's being classified. Note that a classifier MUST implement either
+ * this or distributionForInstance().
+ *
* @param instance the instance to be classified
- * @return the predicted most likely class for the instance or
- * Instance.missingValue() if no prediction is made
+ * @return the predicted most likely class for the instance or
+ * Instance.missingValue() if no prediction is made
* @exception Exception if an error occurred during the prediction
*/
public double classifyInstance(Instance instance) throws Exception {
- double [] dist = distributionForInstance(instance);
+ double[] dist = distributionForInstance(instance);
if (dist == null) {
throw new Exception("Null distribution predicted");
}
@@ -89,19 +86,20 @@ public abstract class Classifier
case Attribute.NOMINAL:
double max = 0;
int maxIndex = 0;
-
+
for (int i = 0; i < dist.length; i++) {
- if (dist[i] > max) {
- maxIndex = i;
- max = dist[i];
- }
+ if (dist[i] > max) {
+ maxIndex = i;
+ max = dist[i];
+ }
}
if (max > 0) {
- return maxIndex;
+ return maxIndex;
} else {
- return Instance.missingValue();
+ return Instance.missingValue();
}
case Attribute.NUMERIC:
+ case Attribute.DATE:
return dist[0];
default:
return Instance.missingValue();
@@ -109,19 +107,16 @@ public abstract class Classifier
}
/**
- * Predicts the class memberships for a given instance. If
- * an instance is unclassified, the returned array elements
- * must be all zero. If the class is numeric, the array
- * must consist of only one element, which contains the
- * predicted value. Note that a classifier MUST implement
- * either this or classifyInstance().
- *
+ * Predicts the class memberships for a given instance. If an instance is
+ * unclassified, the returned array elements must be all zero. If the class is
+ * numeric, the array must consist of only one element, which contains the
+ * predicted value. Note that a classifier MUST implement either this or
+ * classifyInstance().
+ *
* @param instance the instance to be classified
- * @return an array containing the estimated membership
- * probabilities of the test instance in each class
- * or the numeric prediction
- * @exception Exception if distribution could not be
- * computed successfully
+ * @return an array containing the estimated membership probabilities of the
+ * test instance in each class or the numeric prediction
+ * @exception Exception if distribution could not be computed successfully
*/
public double[] distributionForInstance(Instance instance) throws Exception {
@@ -130,69 +125,70 @@ public abstract class Classifier
case Attribute.NOMINAL:
double classification = classifyInstance(instance);
if (Instance.isMissingValue(classification)) {
- return dist;
+ return dist;
} else {
- dist[(int)classification] = 1.0;
+ dist[(int) classification] = 1.0;
}
return dist;
case Attribute.NUMERIC:
+ case Attribute.DATE:
dist[0] = classifyInstance(instance);
return dist;
default:
return dist;
}
- }
-
+ }
+
/**
- * Creates a new instance of a classifier given it's class name and
- * (optional) arguments to pass to it's setOptions method. If the
- * classifier implements OptionHandler and the options parameter is
- * non-null, the classifier will have it's options set.
- *
+ * Creates a new instance of a classifier given it's class name and (optional)
+ * arguments to pass to it's setOptions method. If the classifier implements
+ * OptionHandler and the options parameter is non-null, the classifier will
+ * have it's options set.
+ *
* @param classifierName the fully qualified class name of the classifier
* @param options an array of options suitable for passing to setOptions. May
- * be null.
+ * be null.
* @return the newly created classifier, ready for use.
* @exception Exception if the classifier name is invalid, or the options
- * supplied are not acceptable to the classifier
+ * supplied are not acceptable to the classifier
*/
- public static Classifier forName(String classifierName,
- String [] options) throws Exception {
+ public static Classifier forName(String classifierName, String[] options)
+ throws Exception {
- return (Classifier)Utils.forName(Classifier.class,
- classifierName,
- options);
+ return (Classifier) Utils
+ .forName(Classifier.class, classifierName, options);
}
/**
* Creates a deep copy of the given classifier using serialization.
- *
+ *
* @param model the classifier to copy
* @return a deep copy of the classifier
* @exception Exception if an error occurs
*/
public static Classifier makeCopy(Classifier model) throws Exception {
- return (Classifier)new SerializedObject(model).getObject();
+ return (Classifier) new SerializedObject(model).getObject();
}
/**
- * Creates a given number of deep copies of the given classifier using serialization.
+ * Creates a given number of deep copies of the given classifier using
+ * serialization.
*
* @param model the classifier to copy
* @param num the number of classifier copies to create.
* @return an array of classifiers.
* @exception Exception if an error occurs
*/
- public static Classifier [] makeCopies(Classifier model,
- int num) throws Exception {
+ public static Classifier[] makeCopies(Classifier model, int num)
+ throws Exception {
if (model == null) {
throw new Exception("No model classifier set");
}
- Classifier [] classifiers = new Classifier [num];
+ Classifier[] classifiers = new Classifier[num];
SerializedObject so = new SerializedObject(model);
- for(int i = 0; i < classifiers.length; i++) {
+ for (int i = 0; i < classifiers.length; i++) {
classifiers[i] = (Classifier) so.getObject();
}
return classifiers;
@@ -200,30 +196,33 @@ public abstract class Classifier
/**
* Returns an enumeration describing the available options.
- *
+ *
* @return an enumeration of all the available options.
*/
+ @Override
public Enumeration listOptions() {
Vector newVector = new Vector(1);
newVector.addElement(new Option(
- "\tIf set, classifier is run in debug mode and\n"
- + "\tmay output additional info to the console",
- "D", 0, "-D"));
+ "\tIf set, classifier is run in debug mode and\n"
+ + "\tmay output additional info to the console", "D", 0, "-D"));
return newVector.elements();
}
/**
- * Parses a given list of options. Valid options are:<p>
- *
- * -D <br>
- * If set, classifier is run in debug mode and
- * may output additional info to the console.<p>
- *
+ * Parses a given list of options. Valid options are:
+ * <p>
+ *
+ * -D <br>
+ * If set, classifier is run in debug mode and may output additional info to
+ * the console.
+ * <p>
+ *
* @param options the list of options as an array of strings
* @exception Exception if an option is not supported
*/
+ @Override
public void setOptions(String[] options) throws Exception {
setDebug(Utils.getFlag('D', options));
@@ -231,12 +230,13 @@ public abstract class Classifier
/**
* Gets the current settings of the Classifier.
- *
+ *
* @return an array of strings suitable for passing to setOptions
*/
- public String [] getOptions() {
+ @Override
+ public String[] getOptions() {
- String [] options;
+ String[] options;
if (getDebug()) {
options = new String[1];
options[0] = "-D";
@@ -248,7 +248,7 @@ public abstract class Classifier
/**
* Set debugging mode.
- *
+ *
* @param debug true if debug output should be printed
*/
public void setDebug(boolean debug) {
@@ -258,66 +258,69 @@ public abstract class Classifier
/**
* Get whether debugging is turned on.
- *
+ *
* @return true if debugging output is on
*/
public boolean getDebug() {
return m_Debug;
}
-
+
/**
* Returns the tip text for this property
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String debugTipText() {
- return "If set to true, classifier may output additional info to " +
- "the console.";
+ return "If set to true, classifier may output additional info to "
+ + "the console.";
}
- /**
+ /**
* Returns the Capabilities of this classifier. Maximally permissive
- * capabilities are allowed by default. Derived classifiers should
- * override this method and first disable all capabilities and then
- * enable just those capabilities that make sense for the scheme.
- *
- * @return the capabilities of this object
- * @see Capabilities
+ * capabilities are allowed by default. Derived classifiers should override
+ * this method and first disable all capabilities and then enable just those
+ * capabilities that make sense for the scheme.
+ *
+ * @return the capabilities of this object
+ * @see Capabilities
*/
+ @Override
public Capabilities getCapabilities() {
Capabilities result = new Capabilities(this);
result.enableAll();
-
+
return result;
}
-
+
/**
* Returns the revision string.
*
- * @return the revision
+ * @return the revision
*/
+ @Override
public String getRevision() {
- return RevisionUtils.extract("$Revision: 5536 $");
+ return RevisionUtils.extract("$Revision: 10485 $");
}
-
+
/**
* runs the classifier instance with the given options.
*
- * @param classifier the classifier to run
- * @param options the commandline options
+ * @param classifier the classifier to run
+ * @param options the commandline options
*/
protected static void runClassifier(Classifier classifier, String[] options) {
try {
System.out.println(Evaluation.evaluateModel(classifier, options));
- }
- catch (Exception e) {
- if ( ((e.getMessage() != null) && (e.getMessage().indexOf("General options") == -1))
- || (e.getMessage() == null) )
- e.printStackTrace();
- else
- System.err.println(e.getMessage());
+ } catch (Exception e) {
+ if (((e.getMessage() != null) && (e.getMessage().indexOf(
+ "General options") == -1))
+ || (e.getMessage() == null)) {
+ e.printStackTrace();
+ } else {
+ System.err.println(e.getMessage());
+ }
}
}
}
-
diff --git a/src/main/java/weka/classifiers/Evaluation.java b/src/main/java/weka/classifiers/Evaluation.java
index 1680766..938d2ef 100644
--- a/src/main/java/weka/classifiers/Evaluation.java
+++ b/src/main/java/weka/classifiers/Evaluation.java
@@ -22,6 +22,27 @@
package weka.classifiers;
+import java.beans.BeanInfo;
+import java.beans.Introspector;
+import java.beans.MethodDescriptor;
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.InputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.lang.reflect.Method;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.Random;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
import weka.classifiers.evaluation.NominalPrediction;
import weka.classifiers.evaluation.ThresholdCurve;
import weka.classifiers.pmml.consumer.PMMLClassifier;
@@ -48,144 +69,145 @@ import weka.core.xml.XMLSerialization;
import weka.estimators.Estimator;
import weka.estimators.KernelEstimator;
-import java.beans.BeanInfo;
-import java.beans.Introspector;
-import java.beans.MethodDescriptor;
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.FileReader;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.io.Reader;
-import java.lang.reflect.Method;
-import java.util.Date;
-import java.util.Enumeration;
-import java.util.Random;
-import java.util.zip.GZIPInputStream;
-import java.util.zip.GZIPOutputStream;
-
/**
- * Class for evaluating machine learning models. <p/>
- *
- * ------------------------------------------------------------------- <p/>
- *
- * General options when evaluating a learning scheme from the command-line: <p/>
- *
+ * Class for evaluating machine learning models.
+ * <p/>
+ *
+ * -------------------------------------------------------------------
+ * <p/>
+ *
+ * General options when evaluating a learning scheme from the command-line:
+ * <p/>
+ *
* -t filename <br/>
- * Name of the file with the training data. (required) <p/>
- *
+ * Name of the file with the training data. (required)
+ * <p/>
+ *
* -T filename <br/>
- * Name of the file with the test data. If missing a cross-validation
- * is performed. <p/>
- *
+ * Name of the file with the test data. If missing a cross-validation is
+ * performed.
+ * <p/>
+ *
* -c index <br/>
- * Index of the class attribute (1, 2, ...; default: last). <p/>
- *
+ * Index of the class attribute (1, 2, ...; default: last).
+ * <p/>
+ *
* -x number <br/>
- * The number of folds for the cross-validation (default: 10). <p/>
- *
+ * The number of folds for the cross-validation (default: 10).
+ * <p/>
+ *
* -no-cv <br/>
- * No cross validation. If no test file is provided, no evaluation
- * is done. <p/>
+ * No cross validation. If no test file is provided, no evaluation is done.
+ * <p/>
*
* -split-percentage percentage <br/>
- * Sets the percentage for the train/test set split, e.g., 66. <p/>
+ * Sets the percentage for the train/test set split, e.g., 66.
+ * <p/>
*
* -preserve-order <br/>
- * Preserves the order in the percentage split instead of randomizing
- * the data first with the seed value ('-s'). <p/>
- *
+ * Preserves the order in the percentage split instead of randomizing the data
+ * first with the seed value ('-s').
+ * <p/>
+ *
* -s seed <br/>
- * Random number seed for the cross-validation and percentage split
- * (default: 1). <p/>
- *
+ * Random number seed for the cross-validation and percentage split (default:
+ * 1).
+ * <p/>
+ *
* -m filename <br/>
- * The name of a file containing a cost matrix. <p/>
- *
+ * The name of a file containing a cost matrix.
+ * <p/>
+ *
* -l filename <br/>
- * Loads classifier from the given file. In case the filename ends with ".xml",
- * a PMML file is loaded or, if that fails, options are loaded from XML. <p/>
- *
+ * Loads classifier from the given file. In case the filename ends with ".xml",
+ * a PMML file is loaded or, if that fails, options are loaded from XML.
+ * <p/>
+ *
* -d filename <br/>
- * Saves classifier built from the training data into the given file. In case
- * the filename ends with ".xml" the options are saved XML, not the model. <p/>
- *
+ * Saves classifier built from the training data into the given file. In case
+ * the filename ends with ".xml" the options are saved XML, not the model.
+ * <p/>
+ *
* -v <br/>
- * Outputs no statistics for the training data. <p/>
- *
+ * Outputs no statistics for the training data.
+ * <p/>
+ *
* -o <br/>
- * Outputs statistics only, not the classifier. <p/>
+ * Outputs statistics only, not the classifier.
+ * <p/>
*
* -i <br/>
- * Outputs information-retrieval statistics per class. <p/>
- *
+ * Outputs information-retrieval statistics per class.
+ * <p/>
+ *
* -k <br/>
- * Outputs information-theoretic statistics. <p/>
- *
+ * Outputs information-theoretic statistics.
+ * <p/>
+ *
* -p range <br/>
* Outputs predictions for test instances (or the train instances if no test
- * instances provided and -no-cv is used), along with the attributes in the specified range
- * (and nothing else). Use '-p 0' if no attributes are desired. <p/>
+ * instances provided and -no-cv is used), along with the attributes in the
+ * specified range (and nothing else). Use '-p 0' if no attributes are desired.
+ * <p/>
*
* -distribution <br/>
- * Outputs the distribution instead of only the prediction
- * in conjunction with the '-p' option (only nominal classes). <p/>
- *
+ * Outputs the distribution instead of only the prediction in conjunction with
+ * the '-p' option (only nominal classes).
+ * <p/>
+ *
* -r <br/>
- * Outputs cumulative margin distribution (and nothing else). <p/>
- *
- * -g <br/>
- * Only for classifiers that implement "Graphable." Outputs
- * the graph representation of the classifier (and nothing
- * else). <p/>
+ * Outputs cumulative margin distribution (and nothing else).
+ * <p/>
+ *
+ * -g <br/>
+ * Only for classifiers that implement "Graphable." Outputs the graph
+ * representation of the classifier (and nothing else).
+ * <p/>
*
* -xml filename | xml-string <br/>
- * Retrieves the options from the XML-data instead of the command line. <p/>
+ * Retrieves the options from the XML-data instead of the command line.
+ * <p/>
*
* -threshold-file file <br/>
- * The file to save the threshold data to.
- * The format is determined by the extensions, e.g., '.arff' for ARFF
- * format or '.csv' for CSV. <p/>
- *
+ * The file to save the threshold data to. The format is determined by the
+ * extensions, e.g., '.arff' for ARFF format or '.csv' for CSV.
+ * <p/>
+ *
* -threshold-label label <br/>
- * The class label to determine the threshold data for
- * (default is the first label) <p/>
- *
- * ------------------------------------------------------------------- <p/>
- *
+ * The class label to determine the threshold data for (default is the first
+ * label)
+ * <p/>
+ *
+ * -------------------------------------------------------------------
+ * <p/>
+ *
* Example usage as the main of a classifier (called FunkyClassifier):
* <code> <pre>
* public static void main(String [] args) {
* runClassifier(new FunkyClassifier(), args);
* }
- * </pre> </code>
+ * </pre> </code>
* <p/>
- *
- * ------------------------------------------------------------------ <p/>
- *
- * Example usage from within an application:
- * <code> <pre>
+ *
+ * ------------------------------------------------------------------
+ * <p/>
+ *
+ * Example usage from within an application: <code> <pre>
* Instances trainInstances = ... instances got from somewhere
* Instances testInstances = ... instances got from somewhere
* Classifier scheme = ... scheme got from somewhere
- *
+ *
* Evaluation evaluation = new Evaluation(trainInstances);
* evaluation.evaluateModel(scheme, testInstances);
* System.out.println(evaluation.toSummaryString());
- * </pre> </code>
- *
- *
- * @author Eibe Frank (eibe at cs.waikato.ac.nz)
- * @author Len Trigg (trigg at cs.waikato.ac.nz)
- * @version $Revision: 9196 $
+ * </pre> </code>
+ *
+ *
+ * @author Eibe Frank (eibe at cs.waikato.ac.nz)
+ * @author Len Trigg (trigg at cs.waikato.ac.nz)
+ * @version $Revision: 10619 $
*/
-public class Evaluation
- implements Summarizable, RevisionHandler {
+public class Evaluation implements Summarizable, RevisionHandler {
/** The number of classes. */
protected int m_NumClasses;
@@ -209,16 +231,16 @@ public class Evaluation
protected double m_WithClass;
/** Array for storing the confusion matrix. */
- protected double [][] m_ConfusionMatrix;
+ protected double[][] m_ConfusionMatrix;
/** The names of the classes. */
- protected String [] m_ClassNames;
+ protected String[] m_ClassNames;
/** Is the class nominal or numeric? */
protected boolean m_ClassIsNominal;
/** The prior probabilities of the classes */
- protected double [] m_ClassPriors;
+ protected double[] m_ClassPriors;
/** The sum of counts for priors */
protected double m_ClassPriorsSum;
@@ -266,16 +288,16 @@ public class Evaluation
protected static int k_MarginResolution = 500;
/** Cumulative margin distribution */
- protected double m_MarginCounts [];
+ protected double m_MarginCounts[];
/** Number of non-missing class training instances seen */
protected int m_NumTrainClassVals;
/** Array containing all numeric training class values seen */
- protected double [] m_TrainClassVals;
+ protected double[] m_TrainClassVals;
/** Array containing all numeric training class weights */
- protected double [] m_TrainClassWeights;
+ protected double[] m_TrainClassWeights;
/** Numeric class error estimator for prior */
protected Estimator m_PriorErrorEstimator;
@@ -284,8 +306,8 @@ public class Evaluation
protected Estimator m_ErrorEstimator;
/**
- * The minimum probablility accepted from an estimator to avoid
- * taking log(0) in Sf calculations.
+ * The minimum probablility accepted from an estimator to avoid taking log(0)
+ * in Sf calculations.
*/
protected static final double MIN_SF_PROB = Double.MIN_VALUE;
@@ -298,21 +320,23 @@ public class Evaluation
/** The list of predictions that have been generated (for computing AUC) */
private FastVector m_Predictions;
- /** enables/disables the use of priors, e.g., if no training set is
- * present in case of de-serialized schemes */
+ /**
+ * enables/disables the use of priors, e.g., if no training set is present in
+ * case of de-serialized schemes
+ */
protected boolean m_NoPriors = false;
/**
- * Initializes all the counters for the evaluation.
- * Use <code>useNoPriors()</code> if the dataset is the test set and you
- * can't initialize with the priors from the training set via
+ * Initializes all the counters for the evaluation. Use
+ * <code>useNoPriors()</code> if the dataset is the test set and you can't
+ * initialize with the priors from the training set via
* <code>setPriors(Instances)</code>.
- *
- * @param data set of training instances, to get some header
- * information and prior class distribution information
- * @throws Exception if the class is not defined
- * @see #useNoPriors()
- * @see #setPriors(Instances)
+ *
+ * @param data set of training instances, to get some header information and
+ * prior class distribution information
+ * @throws Exception if the class is not defined
+ * @see #useNoPriors()
+ * @see #setPriors(Instances)
*/
public Evaluation(Instances data) throws Exception {
@@ -320,54 +344,52 @@ public class Evaluation
}
/**
- * Initializes all the counters for the evaluation and also takes a
- * cost matrix as parameter.
- * Use <code>useNoPriors()</code> if the dataset is the test set and you
- * can't initialize with the priors from the training set via
+ * Initializes all the counters for the evaluation and also takes a cost
+ * matrix as parameter. Use <code>useNoPriors()</code> if the dataset is the
+ * test set and you can't initialize with the priors from the training set via
* <code>setPriors(Instances)</code>.
- *
- * @param data set of training instances, to get some header
- * information and prior class distribution information
- * @param costMatrix the cost matrix---if null, default costs will be used
- * @throws Exception if cost matrix is not compatible with
- * data, the class is not defined or the class is numeric
- * @see #useNoPriors()
- * @see #setPriors(Instances)
- */
- public Evaluation(Instances data, CostMatrix costMatrix)
- throws Exception {
+ *
+ * @param data set of training instances, to get some header information and
+ * prior class distribution information
+ * @param costMatrix the cost matrix---if null, default costs will be used
+ * @throws Exception if cost matrix is not compatible with data, the class is
+ * not defined or the class is numeric
+ * @see #useNoPriors()
+ * @see #setPriors(Instances)
+ */
+ public Evaluation(Instances data, CostMatrix costMatrix) throws Exception {
m_NumClasses = data.numClasses();
m_NumFolds = 1;
m_ClassIsNominal = data.classAttribute().isNominal();
if (m_ClassIsNominal) {
- m_ConfusionMatrix = new double [m_NumClasses][m_NumClasses];
- m_ClassNames = new String [m_NumClasses];
- for(int i = 0; i < m_NumClasses; i++) {
- m_ClassNames[i] = data.classAttribute().value(i);
+ m_ConfusionMatrix = new double[m_NumClasses][m_NumClasses];
+ m_ClassNames = new String[m_NumClasses];
+ for (int i = 0; i < m_NumClasses; i++) {
+ m_ClassNames[i] = data.classAttribute().value(i);
}
}
m_CostMatrix = costMatrix;
if (m_CostMatrix != null) {
if (!m_ClassIsNominal) {
- throw new Exception("Class has to be nominal if cost matrix " +
- "given!");
+ throw new Exception("Class has to be nominal if cost matrix "
+ + "given!");
}
if (m_CostMatrix.size() != m_NumClasses) {
- throw new Exception("Cost matrix not compatible with data!");
+ throw new Exception("Cost matrix not compatible with data!");
}
}
- m_ClassPriors = new double [m_NumClasses];
+ m_ClassPriors = new double[m_NumClasses];
setPriors(data);
- m_MarginCounts = new double [k_MarginResolution + 1];
+ m_MarginCounts = new double[k_MarginResolution + 1];
}
/**
* Returns the area under ROC for those predictions that have been collected
- * in the evaluateClassifier(Classifier, Instances) method. Returns
+ * in the evaluateClassifier(Classifier, Instances) method. Returns
* Instance.missingValue() if the area is not available.
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the area under the ROC curve or not a number
*/
@@ -385,13 +407,13 @@ public class Evaluation
/**
* Calculates the weighted (by class size) AUC.
- *
+ *
* @return the weighted AUC.
*/
public double weightedAreaUnderROC() {
double[] classCounts = new double[m_NumClasses];
double classCountSum = 0;
-
+
for (int i = 0; i < m_NumClasses; i++) {
for (int j = 0; j < m_NumClasses; j++) {
classCounts[i] += m_ConfusionMatrix[i][j];
@@ -400,7 +422,7 @@ public class Evaluation
}
double aucTotal = 0;
- for(int i = 0; i < m_NumClasses; i++) {
+ for (int i = 0; i < m_NumClasses; i++) {
double temp = areaUnderROC(i);
if (!Instance.isMissingValue(temp)) {
aucTotal += (temp * classCounts[i]);
@@ -412,7 +434,7 @@ public class Evaluation
/**
* Returns a copy of the confusion matrix.
- *
+ *
* @return a copy of the confusion matrix as a two-dimensional array
*/
public double[][] confusionMatrix() {
@@ -422,34 +444,31 @@ public class Evaluation
for (int i = 0; i < m_ConfusionMatrix.length; i++) {
newMatrix[i] = new double[m_ConfusionMatrix[i].length];
System.arraycopy(m_ConfusionMatrix[i], 0, newMatrix[i], 0,
- m_ConfusionMatrix[i].length);
+ m_ConfusionMatrix[i].length);
}
return newMatrix;
}
/**
- * Performs a (stratified if class is nominal) cross-validation
- * for a classifier on a set of instances. Now performs
- * a deep copy of the classifier before each call to
- * buildClassifier() (just in case the classifier is not
- * initialized properly).
- *
+ * Performs a (stratified if class is nominal) cross-validation for a
+ * classifier on a set of instances. Now performs a deep copy of the
+ * classifier before each call to buildClassifier() (just in case the
+ * classifier is not initialized properly).
+ *
* @param classifier the classifier with any options set.
- * @param data the data on which the cross-validation is to be
- * performed
+ * @param data the data on which the cross-validation is to be performed
* @param numFolds the number of folds for the cross-validation
- * @param random random number generator for randomization
+ * @param random random number generator for randomization
* @param forPredictionsString varargs parameter that, if supplied, is
- * expected to hold a StringBuffer to print predictions to,
- * a Range of attributes to output and a Boolean (true if the distribution
- * is to be printed)
- * @throws Exception if a classifier could not be generated
- * successfully or the class is not defined
- */
- public void crossValidateModel(Classifier classifier,
- Instances data, int numFolds, Random random,
- Object... forPredictionsPrinting)
- throws Exception {
+ * expected to hold a StringBuffer to print predictions to, a Range
+ * of attributes to output and a Boolean (true if the distribution is
+ * to be printed)
+ * @throws Exception if a classifier could not be generated successfully or
+ * the class is not defined
+ */
+ public void crossValidateModel(Classifier classifier, Instances data,
+ int numFolds, Random random, Object... forPredictionsPrinting)
+ throws Exception {
// Make a copy of the data we can reorder
data = new Instances(data);
@@ -458,14 +477,16 @@ public class Evaluation
data.stratify(numFolds);
}
- // We assume that the first element is a StringBuffer, the second a Range (attributes
- // to output) and the third a Boolean (whether or not to output a distribution instead
+ // We assume that the first element is a StringBuffer, the second a Range
+ // (attributes
+ // to output) and the third a Boolean (whether or not to output a
+ // distribution instead
// of just a classification)
if (forPredictionsPrinting.length > 0) {
// print the header first
- StringBuffer buff = (StringBuffer)forPredictionsPrinting[0];
- Range attsToOutput = (Range)forPredictionsPrinting[1];
- boolean printDist = ((Boolean)forPredictionsPrinting[2]).booleanValue();
+ StringBuffer buff = (StringBuffer) forPredictionsPrinting[0];
+ Range attsToOutput = (Range) forPredictionsPrinting[1];
+ boolean printDist = ((Boolean) forPredictionsPrinting[2]).booleanValue();
printClassificationsHeader(data, attsToOutput, printDist, buff);
}
@@ -482,147 +503,166 @@ public class Evaluation
}
/**
- * Performs a (stratified if class is nominal) cross-validation
- * for a classifier on a set of instances.
- *
+ * Performs a (stratified if class is nominal) cross-validation for a
+ * classifier on a set of instances.
+ *
* @param classifierString a string naming the class of the classifier
- * @param data the data on which the cross-validation is to be
- * performed
+ * @param data the data on which the cross-validation is to be performed
* @param numFolds the number of folds for the cross-validation
* @param options the options to the classifier. Any options
- * @param random the random number generator for randomizing the data
- * accepted by the classifier will be removed from this array.
- * @throws Exception if a classifier could not be generated
- * successfully or the class is not defined
- */
- public void crossValidateModel(String classifierString,
- Instances data, int numFolds,
- String[] options, Random random)
- throws Exception {
+ * @param random the random number generator for randomizing the data accepted
+ * by the classifier will be removed from this array.
+ * @throws Exception if a classifier could not be generated successfully or
+ * the class is not defined
+ */
+ public void crossValidateModel(String classifierString, Instances data,
+ int numFolds, String[] options, Random random) throws Exception {
- crossValidateModel(Classifier.forName(classifierString, options),
- data, numFolds, random);
+ crossValidateModel(Classifier.forName(classifierString, options), data,
+ numFolds, random);
}
/**
- * Evaluates a classifier with the options given in an array of
- * strings. <p/>
- *
- * Valid options are: <p/>
- *
+ * Evaluates a classifier with the options given in an array of strings.
+ * <p/>
+ *
+ * Valid options are:
+ * <p/>
+ *
* -t filename <br/>
- * Name of the file with the training data. (required) <p/>
- *
+ * Name of the file with the training data. (required)
+ * <p/>
+ *
* -T filename <br/>
- * Name of the file with the test data. If missing a cross-validation
- * is performed. <p/>
- *
+ * Name of the file with the test data. If missing a cross-validation is
+ * performed.
+ * <p/>
+ *
* -c index <br/>
- * Index of the class attribute (1, 2, ...; default: last). <p/>
- *
+ * Index of the class attribute (1, 2, ...; default: last).
+ * <p/>
+ *
* -x number <br/>
- * The number of folds for the cross-validation (default: 10). <p/>
- *
+ * The number of folds for the cross-validation (default: 10).
+ * <p/>
+ *
* -no-cv <br/>
- * No cross validation. If no test file is provided, no evaluation
- * is done. <p/>
+ * No cross validation. If no test file is provided, no evaluation is done.
+ * <p/>
*
* -split-percentage percentage <br/>
- * Sets the percentage for the train/test set split, e.g., 66. <p/>
+ * Sets the percentage for the train/test set split, e.g., 66.
+ * <p/>
*
* -preserve-order <br/>
- * Preserves the order in the percentage split instead of randomizing
- * the data first with the seed value ('-s'). <p/>
- *
+ * Preserves the order in the percentage split instead of randomizing the data
+ * first with the seed value ('-s').
+ * <p/>
+ *
* -s seed <br/>
- * Random number seed for the cross-validation and percentage split
- * (default: 1). <p/>
- *
+ * Random number seed for the cross-validation and percentage split (default:
+ * 1).
+ * <p/>
+ *
* -m filename <br/>
- * The name of a file containing a cost matrix. <p/>
- *
+ * The name of a file containing a cost matrix.
+ * <p/>
+ *
* -l filename <br/>
* Loads classifier from the given file. In case the filename ends with
- * ".xml",a PMML file is loaded or, if that fails, options are loaded from XML. <p/>
- *
+ * ".xml",a PMML file is loaded or, if that fails, options are loaded from
+ * XML.
+ * <p/>
+ *
* -d filename <br/>
- * Saves classifier built from the training data into the given file. In case
- * the filename ends with ".xml" the options are saved XML, not the model. <p/>
- *
+ * Saves classifier built from the training data into the given file. In case
+ * the filename ends with ".xml" the options are saved XML, not the model.
+ * <p/>
+ *
* -v <br/>
- * Outputs no statistics for the training data. <p/>
- *
+ * Outputs no statistics for the training data.
+ * <p/>
+ *
* -o <br/>
- * Outputs statistics only, not the classifier. <p/>
+ * Outputs statistics only, not the classifier.
+ * <p/>
*
* -i <br/>
- * Outputs detailed information-retrieval statistics per class. <p/>
- *
+ * Outputs detailed information-retrieval statistics per class.
+ * <p/>
+ *
* -k <br/>
- * Outputs information-theoretic statistics. <p/>
- *
+ * Outputs information-theoretic statistics.
+ * <p/>
+ *
* -p range <br/>
* Outputs predictions for test instances (or the train instances if no test
- * instances provided and -no-cv is used), along with the attributes in the specified range (and
- * nothing else). Use '-p 0' if no attributes are desired. <p/>
- *
+ * instances provided and -no-cv is used), along with the attributes in the
+ * specified range (and nothing else). Use '-p 0' if no attributes are
+ * desired.
+ * <p/>
+ *
* -distribution <br/>
- * Outputs the distribution instead of only the prediction
- * in conjunction with the '-p' option (only nominal classes). <p/>
- *
+ * Outputs the distribution instead of only the prediction in conjunction with
+ * the '-p' option (only nominal classes).
+ * <p/>
+ *
* -r <br/>
- * Outputs cumulative margin distribution (and nothing else). <p/>
- *
- * -g <br/>
- * Only for classifiers that implement "Graphable." Outputs
- * the graph representation of the classifier (and nothing
- * else). <p/>
- *
+ * Outputs cumulative margin distribution (and nothing else).
+ * <p/>
+ *
+ * -g <br/>
+ * Only for classifiers that implement "Graphable." Outputs the graph
+ * representation of the classifier (and nothing else).
+ * <p/>
+ *
* -xml filename | xml-string <br/>
- * Retrieves the options from the XML-data instead of the command line. <p/>
+ * Retrieves the options from the XML-data instead of the command line.
+ * <p/>
*
* -threshold-file file <br/>
- * The file to save the threshold data to.
- * The format is determined by the extensions, e.g., '.arff' for ARFF
- * format or '.csv' for CSV. <p/>
- *
+ * The file to save the threshold data to. The format is determined by the
+ * extensions, e.g., '.arff' for ARFF format or '.csv' for CSV.
+ * <p/>
+ *
* -threshold-label label <br/>
- * The class label to determine the threshold data for
- * (default is the first label) <p/>
- *
+ * The class label to determine the threshold data for (default is the first
+ * label)
+ * <p/>
+ *
* @param classifierString class of machine learning classifier as a string
* @param options the array of string containing the options
* @throws Exception if model could not be evaluated successfully
- * @return a string describing the results
+ * @return a string describing the results
*/
- public static String evaluateModel(String classifierString,
- String [] options) throws Exception {
+ public static String evaluateModel(String classifierString, String[] options)
+ throws Exception {
- Classifier classifier;
+ Classifier classifier;
// Create classifier
try {
- classifier =
- (Classifier)Class.forName(classifierString).newInstance();
+ classifier = (Classifier) Class.forName(classifierString).newInstance();
} catch (Exception e) {
- throw new Exception("Can't find class with name "
- + classifierString + '.');
+ throw new Exception("Can't find class with name " + classifierString
+ + '.');
}
return evaluateModel(classifier, options);
}
/**
- * A test method for this class. Just extracts the first command line
- * argument as a classifier class name and calls evaluateModel.
- * @param args an array of command line arguments, the first of which
- * must be the class name of a classifier.
+ * A test method for this class. Just extracts the first command line argument
+ * as a classifier class name and calls evaluateModel.
+ *
+ * @param args an array of command line arguments, the first of which must be
+ * the class name of a classifier.
*/
- public static void main(String [] args) {
+ public static void main(String[] args) {
try {
if (args.length == 0) {
- throw new Exception("The first argument must be the class name"
- + " of a classifier");
+ throw new Exception("The first argument must be the class name"
+ + " of a classifier");
}
String classifier = args[0];
args[0] = "";
@@ -634,100 +674,118 @@ public class Evaluation
}
/**
- * Evaluates a classifier with the options given in an array of
- * strings. <p/>
- *
- * Valid options are: <p/>
- *
+ * Evaluates a classifier with the options given in an array of strings.
+ * <p/>
+ *
+ * Valid options are:
+ * <p/>
+ *
* -t name of training file <br/>
- * Name of the file with the training data. (required) <p/>
- *
+ * Name of the file with the training data. (required)
+ * <p/>
+ *
* -T name of test file <br/>
- * Name of the file with the test data. If missing a cross-validation
- * is performed. <p/>
- *
+ * Name of the file with the test data. If missing a cross-validation is
+ * performed.
+ * <p/>
+ *
* -c class index <br/>
- * Index of the class attribute (1, 2, ...; default: last). <p/>
- *
+ * Index of the class attribute (1, 2, ...; default: last).
+ * <p/>
+ *
* -x number of folds <br/>
- * The number of folds for the cross-validation (default: 10). <p/>
- *
+ * The number of folds for the cross-validation (default: 10).
+ * <p/>
+ *
* -no-cv <br/>
- * No cross validation. If no test file is provided, no evaluation
- * is done. <p/>
+ * No cross validation. If no test file is provided, no evaluation is done.
+ * <p/>
*
* -split-percentage percentage <br/>
- * Sets the percentage for the train/test set split, e.g., 66. <p/>
+ * Sets the percentage for the train/test set split, e.g., 66.
+ * <p/>
*
* -preserve-order <br/>
- * Preserves the order in the percentage split instead of randomizing
- * the data first with the seed value ('-s'). <p/>
- *
+ * Preserves the order in the percentage split instead of randomizing the data
+ * first with the seed value ('-s').
+ * <p/>
+ *
* -s seed <br/>
- * Random number seed for the cross-validation and percentage split
- * (default: 1). <p/>
- *
+ * Random number seed for the cross-validation and percentage split (default:
+ * 1).
+ * <p/>
+ *
* -m file with cost matrix <br/>
- * The name of a file containing a cost matrix. <p/>
- *
+ * The name of a file containing a cost matrix.
+ * <p/>
+ *
* -l filename <br/>
* Loads classifier from the given file. In case the filename ends with
- * ".xml",a PMML file is loaded or, if that fails, options are loaded from XML. <p/>
- *
+ * ".xml",a PMML file is loaded or, if that fails, options are loaded from
+ * XML.
+ * <p/>
+ *
* -d filename <br/>
- * Saves classifier built from the training data into the given file. In case
- * the filename ends with ".xml" the options are saved XML, not the model. <p/>
- *
+ * Saves classifier built from the training data into the given file. In case
+ * the filename ends with ".xml" the options are saved XML, not the model.
+ * <p/>
+ *
* -v <br/>
- * Outputs no statistics for the training data. <p/>
- *
+ * Outputs no statistics for the training data.
+ * <p/>
+ *
* -o <br/>
- * Outputs statistics only, not the classifier. <p/>
+ * Outputs statistics only, not the classifier.
+ * <p/>
*
* -i <br/>
- * Outputs detailed information-retrieval statistics per class. <p/>
- *
+ * Outputs detailed information-retrieval statistics per class.
+ * <p/>
+ *
* -k <br/>
- * Outputs information-theoretic statistics. <p/>
- *
+ * Outputs information-theoretic statistics.
+ * <p/>
+ *
* -p range <br/>
* Outputs predictions for test instances (or the train instances if no test
- * instances provided and -no-cv is used), along with the attributes in the specified range
- * (and nothing else). Use '-p 0' if no attributes are desired. <p/>
- *
+ * instances provided and -no-cv is used), along with the attributes in the
+ * specified range (and nothing else). Use '-p 0' if no attributes are
+ * desired.
+ * <p/>
+ *
* -distribution <br/>
- * Outputs the distribution instead of only the prediction
- * in conjunction with the '-p' option (only nominal classes). <p/>
- *
+ * Outputs the distribution instead of only the prediction in conjunction with
+ * the '-p' option (only nominal classes).
+ * <p/>
+ *
* -r <br/>
- * Outputs cumulative margin distribution (and nothing else). <p/>
- *
- * -g <br/>
- * Only for classifiers that implement "Graphable." Outputs
- * the graph representation of the classifier (and nothing
- * else). <p/>
- *
+ * Outputs cumulative margin distribution (and nothing else).
+ * <p/>
+ *
+ * -g <br/>
+ * Only for classifiers that implement "Graphable." Outputs the graph
+ * representation of the classifier (and nothing else).
+ * <p/>
+ *
* -xml filename | xml-string <br/>
- * Retrieves the options from the XML-data instead of the command line. <p/>
- *
+ * Retrieves the options from the XML-data instead of the command line.
+ * <p/>
+ *
* @param classifier machine learning classifier
* @param options the array of string containing the options
* @throws Exception if model could not be evaluated successfully
- * @return a string describing the results
+ * @return a string describing the results
*/
- public static String evaluateModel(Classifier classifier,
- String [] options) throws Exception {
+ public static String evaluateModel(Classifier classifier, String[] options)
+ throws Exception {
Instances train = null, tempTrain, test = null, template = null;
int seed = 1, folds = 10, classIndex = -1;
boolean noCrossValidation = false;
- String trainFileName, testFileName, sourceClass,
- classIndexString, seedString, foldsString, objectInputFileName,
- objectOutputFileName, attributeRangeString;
- boolean noOutput = false,
- printClassifications = false, trainStatistics = true,
- printMargins = false, printComplexityStatistics = false,
- printGraph = false, classStatistics = false, printSource = false;
+ String trainFileName, testFileName, sourceClass, classIndexString, seedString, foldsString, objectInputFileName, objectOutputFileName, attributeRangeString;
+ boolean noOutput = false, printClassifications = false, trainStatistics =
+ true, printMargins = false, printComplexityStatistics = false, printGraph =
+ false, classStatistics = false, printSource = false;
StringBuffer text = new StringBuffer();
DataSource trainSource = null, testSource = null;
ObjectInputStream objectInputStream = null;
@@ -735,13 +793,13 @@ public class Evaluation
CostMatrix costMatrix = null;
StringBuffer schemeOptionsText = null;
Range attributesToOutput = null;
- long trainTimeStart = 0, trainTimeElapsed = 0,
- testTimeStart = 0, testTimeElapsed = 0;
+ long trainTimeStart = 0, trainTimeElapsed = 0, testTimeStart = 0, testTimeElapsed =
+ 0;
String xml = "";
String[] optionsTmp = null;
Classifier classifierBackup;
boolean printDistribution = false;
- int actualClassIndex = -1; // 0-based class index
+ int actualClassIndex = -1; // 0-based class index
String splitPercentageString = "";
double splitPercentage = -1;
boolean preserveOrder = false;
@@ -753,197 +811,207 @@ public class Evaluation
// help requested?
if (Utils.getFlag("h", options) || Utils.getFlag("help", options)) {
-
+
// global info requested as well?
- boolean globalInfo = Utils.getFlag("synopsis", options) ||
- Utils.getFlag("info", options);
-
- throw new Exception("\nHelp requested."
- + makeOptionString(classifier, globalInfo));
+ boolean globalInfo =
+ Utils.getFlag("synopsis", options) || Utils.getFlag("info", options);
+
+ throw new Exception("\nHelp requested."
+ + makeOptionString(classifier, globalInfo));
}
-
+
try {
// do we get the input from XML instead of normal parameters?
xml = Utils.getOption("xml", options);
- if (!xml.equals(""))
- options = new XMLOptions(xml).toArray();
+ if (!xml.equals("")) {
+ options = new XMLOptions(xml).toArray();
+ }
// is the input model only the XML-Options, i.e. w/o built model?
optionsTmp = new String[options.length];
- for (int i = 0; i < options.length; i++)
- optionsTmp[i] = options[i];
+ for (int i = 0; i < options.length; i++) {
+ optionsTmp[i] = options[i];
+ }
String tmpO = Utils.getOption('l', optionsTmp);
- //if (Utils.getOption('l', optionsTmp).toLowerCase().endsWith(".xml")) {
+ // if (Utils.getOption('l', optionsTmp).toLowerCase().endsWith(".xml")) {
if (tmpO.endsWith(".xml")) {
- // try to load file as PMML first
- boolean success = false;
- try {
- PMMLModel pmmlModel = PMMLFactory.getPMMLModel(tmpO);
- if (pmmlModel instanceof PMMLClassifier) {
- classifier = ((PMMLClassifier)pmmlModel);
- success = true;
- }
- } catch (IllegalArgumentException ex) {
- success = false;
- }
- if (!success) {
- // load options from serialized data ('-l' is automatically erased!)
- XMLClassifier xmlserial = new XMLClassifier();
- Classifier cl = (Classifier) xmlserial.read(Utils.getOption('l', options));
-
- // merge options
- optionsTmp = new String[options.length + cl.getOptions().length];
- System.arraycopy(cl.getOptions(), 0, optionsTmp, 0, cl.getOptions().length);
- System.arraycopy(options, 0, optionsTmp, cl.getOptions().length, options.length);
- options = optionsTmp;
- }
+ // try to load file as PMML first
+ boolean success = false;
+ try {
+ PMMLModel pmmlModel = PMMLFactory.getPMMLModel(tmpO);
+ if (pmmlModel instanceof PMMLClassifier) {
+ classifier = ((PMMLClassifier) pmmlModel);
+ success = true;
+ }
+ } catch (IllegalArgumentException ex) {
+ success = false;
+ }
+ if (!success) {
+ // load options from serialized data ('-l' is automatically erased!)
+ XMLClassifier xmlserial = new XMLClassifier();
+ Classifier cl =
+ (Classifier) xmlserial.read(Utils.getOption('l', options));
+
+ // merge options
+ optionsTmp = new String[options.length + cl.getOptions().length];
+ System.arraycopy(cl.getOptions(), 0, optionsTmp, 0,
+ cl.getOptions().length);
+ System.arraycopy(options, 0, optionsTmp, cl.getOptions().length,
+ options.length);
+ options = optionsTmp;
+ }
}
noCrossValidation = Utils.getFlag("no-cv", options);
// Get basic options (options the same for all schemes)
classIndexString = Utils.getOption('c', options);
if (classIndexString.length() != 0) {
- if (classIndexString.equals("first"))
- classIndex = 1;
- else if (classIndexString.equals("last"))
- classIndex = -1;
- else
- classIndex = Integer.parseInt(classIndexString);
- }
- trainFileName = Utils.getOption('t', options);
+ if (classIndexString.equals("first")) {
+ classIndex = 1;
+ } else if (classIndexString.equals("last")) {
+ classIndex = -1;
+ } else {
+ classIndex = Integer.parseInt(classIndexString);
+ }
+ }
+ trainFileName = Utils.getOption('t', options);
objectInputFileName = Utils.getOption('l', options);
objectOutputFileName = Utils.getOption('d', options);
testFileName = Utils.getOption('T', options);
foldsString = Utils.getOption('x', options);
if (foldsString.length() != 0) {
- folds = Integer.parseInt(foldsString);
+ folds = Integer.parseInt(foldsString);
}
seedString = Utils.getOption('s', options);
if (seedString.length() != 0) {
- seed = Integer.parseInt(seedString);
+ seed = Integer.parseInt(seedString);
}
if (trainFileName.length() == 0) {
- if (objectInputFileName.length() == 0) {
- throw new Exception("No training file and no object "+
- "input file given.");
- }
- if (testFileName.length() == 0) {
- throw new Exception("No training file and no test "+
- "file given.");
- }
- } else if ((objectInputFileName.length() != 0) &&
- ((!(classifier instanceof UpdateableClassifier)) ||
- (testFileName.length() == 0))) {
- throw new Exception("Classifier not incremental, or no " +
- "test file provided: can't "+
- "use both train and model file.");
+ if (objectInputFileName.length() == 0) {
+ throw new Exception("No training file and no object "
+ + "input file given.");
+ }
+ if (testFileName.length() == 0) {
+ throw new Exception("No training file and no test " + "file given.");
+ }
+ } else if ((objectInputFileName.length() != 0)
+ && ((!(classifier instanceof UpdateableClassifier)) || (testFileName
+ .length() == 0))) {
+ throw new Exception("Classifier not incremental, or no "
+ + "test file provided: can't " + "use both train and model file.");
}
try {
- if (trainFileName.length() != 0) {
- trainSetPresent = true;
- trainSource = new DataSource(trainFileName);
- }
- if (testFileName.length() != 0) {
- testSetPresent = true;
- testSource = new DataSource(testFileName);
- }
- if (objectInputFileName.length() != 0) {
- if (objectInputFileName.endsWith(".xml")) {
- // if this is the case then it means that a PMML classifier was
- // successfully loaded earlier in the code
- objectInputStream = null;
- xmlInputStream = null;
- } else {
- InputStream is = new FileInputStream(objectInputFileName);
- if (objectInputFileName.endsWith(".gz")) {
- is = new GZIPInputStream(is);
- }
- // load from KOML?
- if (!(objectInputFileName.endsWith(".koml") && KOML.isPresent()) ) {
- objectInputStream = new ObjectInputStream(is);
- xmlInputStream = null;
- }
- else {
- objectInputStream = null;
- xmlInputStream = new BufferedInputStream(is);
- }
- }
- }
+ if (trainFileName.length() != 0) {
+ trainSetPresent = true;
+ trainSource = new DataSource(trainFileName);
+ }
+ if (testFileName.length() != 0) {
+ testSetPresent = true;
+ testSource = new DataSource(testFileName);
+ }
+ if (objectInputFileName.length() != 0) {
+ if (objectInputFileName.endsWith(".xml")) {
+ // if this is the case then it means that a PMML classifier was
+ // successfully loaded earlier in the code
+ objectInputStream = null;
+ xmlInputStream = null;
+ } else {
+ InputStream is = new FileInputStream(objectInputFileName);
+ if (objectInputFileName.endsWith(".gz")) {
+ is = new GZIPInputStream(is);
+ }
+ // load from KOML?
+ if (!(objectInputFileName.endsWith(".koml") && KOML.isPresent())) {
+ objectInputStream = new ObjectInputStream(is);
+ xmlInputStream = null;
+ } else {
+ objectInputStream = null;
+ xmlInputStream = new BufferedInputStream(is);
+ }
+ }
+ }
} catch (Exception e) {
- throw new Exception("Can't open file " + e.getMessage() + '.');
+ throw new Exception("Can't open file " + e.getMessage() + '.');
}
if (testSetPresent) {
- template = test = testSource.getStructure();
- if (classIndex != -1) {
- test.setClassIndex(classIndex - 1);
- } else {
- if ( (test.classIndex() == -1) || (classIndexString.length() != 0) )
- test.setClassIndex(test.numAttributes() - 1);
- }
- actualClassIndex = test.classIndex();
- }
- else {
- // percentage split
- splitPercentageString = Utils.getOption("split-percentage", options);
- if (splitPercentageString.length() != 0) {
- if (foldsString.length() != 0)
- throw new Exception(
- "Percentage split cannot be used in conjunction with "
- + "cross-validation ('-x').");
- splitPercentage = Double.parseDouble(splitPercentageString);
- if ((splitPercentage <= 0) || (splitPercentage >= 100))
- throw new Exception("Percentage split value needs be >0 and <100.");
- }
- else {
- splitPercentage = -1;
- }
- preserveOrder = Utils.getFlag("preserve-order", options);
- if (preserveOrder) {
- if (splitPercentage == -1)
- throw new Exception("Percentage split ('-percentage-split') is missing.");
- }
- // create new train/test sources
- if (splitPercentage > 0) {
- testSetPresent = true;
- Instances tmpInst = trainSource.getDataSet(actualClassIndex);
- if (!preserveOrder)
- tmpInst.randomize(new Random(seed));
- int trainSize =
+ template = test = testSource.getStructure();
+ if (classIndex != -1) {
+ test.setClassIndex(classIndex - 1);
+ } else {
+ if ((test.classIndex() == -1) || (classIndexString.length() != 0)) {
+ test.setClassIndex(test.numAttributes() - 1);
+ }
+ }
+ actualClassIndex = test.classIndex();
+ } else {
+ // percentage split
+ splitPercentageString = Utils.getOption("split-percentage", options);
+ if (splitPercentageString.length() != 0) {
+ if (foldsString.length() != 0) {
+ throw new Exception(
+ "Percentage split cannot be used in conjunction with "
+ + "cross-validation ('-x').");
+ }
+ splitPercentage = Double.parseDouble(splitPercentageString);
+ if ((splitPercentage <= 0) || (splitPercentage >= 100)) {
+ throw new Exception("Percentage split value needs be >0 and <100.");
+ }
+ } else {
+ splitPercentage = -1;
+ }
+ preserveOrder = Utils.getFlag("preserve-order", options);
+ if (preserveOrder) {
+ if (splitPercentage == -1) {
+ throw new Exception(
+ "Percentage split ('-percentage-split') is missing.");
+ }
+ }
+ // create new train/test sources
+ if (splitPercentage > 0) {
+ testSetPresent = true;
+ Instances tmpInst = trainSource.getDataSet(actualClassIndex);
+ if (!preserveOrder) {
+ tmpInst.randomize(new Random(seed));
+ }
+ int trainSize =
(int) Math.round(tmpInst.numInstances() * splitPercentage / 100);
- int testSize = tmpInst.numInstances() - trainSize;
- Instances trainInst = new Instances(tmpInst, 0, trainSize);
- Instances testInst = new Instances(tmpInst, trainSize, testSize);
- trainSource = new DataSource(trainInst);
- testSource = new DataSource(testInst);
- template = test = testSource.getStructure();
- if (classIndex != -1) {
- test.setClassIndex(classIndex - 1);
- } else {
- if ( (test.classIndex() == -1) || (classIndexString.length() != 0) )
- test.setClassIndex(test.numAttributes() - 1);
- }
- actualClassIndex = test.classIndex();
- }
+ int testSize = tmpInst.numInstances() - trainSize;
+ Instances trainInst = new Instances(tmpInst, 0, trainSize);
+ Instances testInst = new Instances(tmpInst, trainSize, testSize);
+ trainSource = new DataSource(trainInst);
+ testSource = new DataSource(testInst);
+ template = test = testSource.getStructure();
+ if (classIndex != -1) {
+ test.setClassIndex(classIndex - 1);
+ } else {
+ if ((test.classIndex() == -1) || (classIndexString.length() != 0)) {
+ test.setClassIndex(test.numAttributes() - 1);
+ }
+ }
+ actualClassIndex = test.classIndex();
+ }
}
if (trainSetPresent) {
- template = train = trainSource.getStructure();
- if (classIndex != -1) {
- train.setClassIndex(classIndex - 1);
- } else {
- if ( (train.classIndex() == -1) || (classIndexString.length() != 0) )
- train.setClassIndex(train.numAttributes() - 1);
- }
- actualClassIndex = train.classIndex();
- if ((testSetPresent) && !test.equalHeaders(train)) {
- throw new IllegalArgumentException("Train and test file not compatible!");
- }
+ template = train = trainSource.getStructure();
+ if (classIndex != -1) {
+ train.setClassIndex(classIndex - 1);
+ } else {
+ if ((train.classIndex() == -1) || (classIndexString.length() != 0)) {
+ train.setClassIndex(train.numAttributes() - 1);
+ }
+ }
+ actualClassIndex = train.classIndex();
+ if ((testSetPresent) && !test.equalHeaders(train)) {
+ throw new IllegalArgumentException(
+ "Train and test file not compatible!");
+ }
}
if (template == null) {
- throw new Exception("No actual dataset provided to use as template");
+ throw new Exception("No actual dataset provided to use as template");
}
- costMatrix = handleCostOption(
- Utils.getOption('m', options), template.numClasses());
+ costMatrix =
+ handleCostOption(Utils.getOption('m', options), template.numClasses());
classStatistics = Utils.getFlag('i', options);
noOutput = Utils.getFlag('o', options);
@@ -959,68 +1027,75 @@ public class Evaluation
// Check -p option
try {
- attributeRangeString = Utils.getOption('p', options);
- }
- catch (Exception e) {
- throw new Exception(e.getMessage() + "\nNOTE: the -p option has changed. " +
- "It now expects a parameter specifying a range of attributes " +
- "to list with the predictions. Use '-p 0' for none.");
+ attributeRangeString = Utils.getOption('p', options);
+ } catch (Exception e) {
+ throw new Exception(e.getMessage()
+ + "\nNOTE: the -p option has changed. "
+ + "It now expects a parameter specifying a range of attributes "
+ + "to list with the predictions. Use '-p 0' for none.");
}
if (attributeRangeString.length() != 0) {
- printClassifications = true;
- noOutput = true;
- if (!attributeRangeString.equals("0"))
- attributesToOutput = new Range(attributeRangeString);
+ printClassifications = true;
+ noOutput = true;
+ if (!attributeRangeString.equals("0")) {
+ attributesToOutput = new Range(attributeRangeString);
+ }
}
- if (!printClassifications && printDistribution)
- throw new Exception("Cannot print distribution without '-p' option!");
+ if (!printClassifications && printDistribution) {
+ throw new Exception("Cannot print distribution without '-p' option!");
+ }
// if no training file given, we don't have any priors
- if ( (!trainSetPresent) && (printComplexityStatistics) )
- throw new Exception("Cannot print complexity statistics ('-k') without training file ('-t')!");
+ if ((!trainSetPresent) && (printComplexityStatistics)) {
+ throw new Exception(
+ "Cannot print complexity statistics ('-k') without training file ('-t')!");
+ }
- // If a model file is given, we can't process
+ // If a model file is given, we can't process
// scheme-specific options
if (objectInputFileName.length() != 0) {
- Utils.checkForRemainingOptions(options);
+ Utils.checkForRemainingOptions(options);
} else {
- // Set options for classifier
- if (classifier instanceof OptionHandler) {
- for (int i = 0; i < options.length; i++) {
- if (options[i].length() != 0) {
- if (schemeOptionsText == null) {
- schemeOptionsText = new StringBuffer();
- }
- if (options[i].indexOf(' ') != -1) {
- schemeOptionsText.append('"' + options[i] + "\" ");
- } else {
- schemeOptionsText.append(options[i] + " ");
- }
- }
- }
- ((OptionHandler)classifier).setOptions(options);
- }
+ // Set options for classifier
+ if (classifier instanceof OptionHandler) {
+ for (String option : options) {
+ if (option.length() != 0) {
+ if (schemeOptionsText == null) {
+ schemeOptionsText = new StringBuffer();
+ }
+ if (option.indexOf(' ') != -1) {
+ schemeOptionsText.append('"' + option + "\" ");
+ } else {
+ schemeOptionsText.append(option + " ");
+ }
+ }
+ }
+ ((OptionHandler) classifier).setOptions(options);
+ }
}
Utils.checkForRemainingOptions(options);
} catch (Exception e) {
throw new Exception("\nWeka exception: " + e.getMessage()
- + makeOptionString(classifier, false));
+ + makeOptionString(classifier, false));
}
// Setup up evaluation objects
- Evaluation trainingEvaluation = new Evaluation(new Instances(template, 0), costMatrix);
- Evaluation testingEvaluation = new Evaluation(new Instances(template, 0), costMatrix);
+ Evaluation trainingEvaluation =
+ new Evaluation(new Instances(template, 0), costMatrix);
+ Evaluation testingEvaluation =
+ new Evaluation(new Instances(template, 0), costMatrix);
// disable use of priors if no training file given
- if (!trainSetPresent)
+ if (!trainSetPresent) {
testingEvaluation.useNoPriors();
+ }
if (objectInputFileName.length() != 0) {
// Load classifier from file
if (objectInputStream != null) {
- classifier = (Classifier) objectInputStream.readObject();
+ classifier = (Classifier) objectInputStream.readObject();
// try and read a header (if present)
Instances savedStructure = null;
try {
@@ -1034,12 +1109,12 @@ public class Evaluation
throw new Exception("training and test set are not compatible");
}
}
- objectInputStream.close();
- }
- else if (xmlInputStream != null) {
- // whether KOML is available has already been checked (objectInputStream would null otherwise)!
- classifier = (Classifier) KOML.read(xmlInputStream);
- xmlInputStream.close();
+ objectInputStream.close();
+ } else if (xmlInputStream != null) {
+ // whether KOML is available has already been checked (objectInputStream
+ // would null otherwise)!
+ classifier = (Classifier) KOML.read(xmlInputStream);
+ xmlInputStream.close();
}
}
@@ -1047,23 +1122,22 @@ public class Evaluation
classifierBackup = Classifier.makeCopy(classifier);
// Build the classifier if no object file provided
- if ((classifier instanceof UpdateableClassifier) &&
- (testSetPresent || noCrossValidation) &&
- (costMatrix == null) &&
- (trainSetPresent)) {
+ if ((classifier instanceof UpdateableClassifier)
+ && (testSetPresent || noCrossValidation) && (costMatrix == null)
+ && (trainSetPresent)) {
// Build classifier incrementally
trainingEvaluation.setPriors(train);
testingEvaluation.setPriors(train);
trainTimeStart = System.currentTimeMillis();
if (objectInputFileName.length() == 0) {
- classifier.buildClassifier(train);
+ classifier.buildClassifier(train);
}
Instance trainInst;
while (trainSource.hasMoreElements(train)) {
- trainInst = trainSource.nextElement(train);
- trainingEvaluation.updatePriors(trainInst);
- testingEvaluation.updatePriors(trainInst);
- ((UpdateableClassifier)classifier).updateClassifier(trainInst);
+ trainInst = trainSource.nextElement(train);
+ trainingEvaluation.updatePriors(trainInst);
+ testingEvaluation.updatePriors(trainInst);
+ ((UpdateableClassifier) classifier).updateClassifier(trainInst);
}
trainTimeElapsed = System.currentTimeMillis() - trainTimeStart;
} else if (objectInputFileName.length() == 0) {
@@ -1074,58 +1148,58 @@ public class Evaluation
trainTimeStart = System.currentTimeMillis();
classifier.buildClassifier(tempTrain);
trainTimeElapsed = System.currentTimeMillis() - trainTimeStart;
- }
+ }
// Save the classifier if an object output file is provided
if (objectOutputFileName.length() != 0) {
OutputStream os = new FileOutputStream(objectOutputFileName);
// binary
- if (!(objectOutputFileName.endsWith(".xml") || (objectOutputFileName.endsWith(".koml") && KOML.isPresent()))) {
- if (objectOutputFileName.endsWith(".gz")) {
- os = new GZIPOutputStream(os);
- }
- ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
- objectOutputStream.writeObject(classifier);
+ if (!(objectOutputFileName.endsWith(".xml") || (objectOutputFileName
+ .endsWith(".koml") && KOML.isPresent()))) {
+ if (objectOutputFileName.endsWith(".gz")) {
+ os = new GZIPOutputStream(os);
+ }
+ ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
+ objectOutputStream.writeObject(classifier);
if (template != null) {
objectOutputStream.writeObject(template);
}
- objectOutputStream.flush();
- objectOutputStream.close();
+ objectOutputStream.flush();
+ objectOutputStream.close();
}
// KOML/XML
else {
- BufferedOutputStream xmlOutputStream = new BufferedOutputStream(os);
- if (objectOutputFileName.endsWith(".xml")) {
- XMLSerialization xmlSerial = new XMLClassifier();
- xmlSerial.write(xmlOutputStream, classifier);
- }
- else
- // whether KOML is present has already been checked
- // if not present -> ".koml" is interpreted as binary - see above
- if (objectOutputFileName.endsWith(".koml")) {
- KOML.write(xmlOutputStream, classifier);
- }
- xmlOutputStream.close();
+ BufferedOutputStream xmlOutputStream = new BufferedOutputStream(os);
+ if (objectOutputFileName.endsWith(".xml")) {
+ XMLSerialization xmlSerial = new XMLClassifier();
+ xmlSerial.write(xmlOutputStream, classifier);
+ } else
+ // whether KOML is present has already been checked
+ // if not present -> ".koml" is interpreted as binary - see above
+ if (objectOutputFileName.endsWith(".koml")) {
+ KOML.write(xmlOutputStream, classifier);
+ }
+ xmlOutputStream.close();
}
}
// If classifier is drawable output string describing graph
- if ((classifier instanceof Drawable) && (printGraph)){
- return ((Drawable)classifier).graph();
+ if ((classifier instanceof Drawable) && (printGraph)) {
+ return ((Drawable) classifier).graph();
}
// Output the classifier as equivalent source
- if ((classifier instanceof Sourcable) && (printSource)){
+ if ((classifier instanceof Sourcable) && (printSource)) {
return wekaStaticWrapper((Sourcable) classifier, sourceClass);
}
// Output model
if (!(noOutput || printMargins)) {
if (classifier instanceof OptionHandler) {
- if (schemeOptionsText != null) {
- text.append("\nOptions: "+schemeOptionsText);
- text.append("\n");
- }
+ if (schemeOptionsText != null) {
+ text.append("\nOptions: " + schemeOptionsText);
+ text.append("\n");
+ }
}
text.append("\n" + classifier.toString() + "\n");
}
@@ -1141,77 +1215,82 @@ public class Evaluation
predsBuff = new StringBuffer();
// no test set -> use train set
if (source == null && noCrossValidation) {
- source = trainSource;
+ source = trainSource;
predsBuff.append("\n=== Predictions on training data ===\n\n");
} else {
predsBuff.append("\n=== Predictions on test data ===\n\n");
}
if (source != null) {
- /* return printClassifications(classifierClassifications, new Instances(template, 0),
- source, actualClassIndex + 1, attributesToOutput,
- printDistribution); */
- printClassifications(classifier, new Instances(template, 0),
- source, actualClassIndex + 1, attributesToOutput,
- printDistribution, predsBuff);
- // return predsText.toString();
+ /*
+ * return printClassifications(classifierClassifications, new
+ * Instances(template, 0), source, actualClassIndex + 1,
+ * attributesToOutput, printDistribution);
+ */
+ printClassifications(classifier, new Instances(template, 0), source,
+ actualClassIndex + 1, attributesToOutput, printDistribution,
+ predsBuff);
+ // return predsText.toString();
}
}
// Compute error estimate from training data
if ((trainStatistics) && (trainSetPresent)) {
- if ((classifier instanceof UpdateableClassifier) &&
- (testSetPresent) &&
- (costMatrix == null)) {
-
- // Classifier was trained incrementally, so we have to
- // reset the source.
- trainSource.reset();
-
- // Incremental testing
- train = trainSource.getStructure(actualClassIndex);
- testTimeStart = System.currentTimeMillis();
- Instance trainInst;
- while (trainSource.hasMoreElements(train)) {
- trainInst = trainSource.nextElement(train);
- trainingEvaluation.evaluateModelOnce((Classifier)classifier, trainInst);
- }
- testTimeElapsed = System.currentTimeMillis() - testTimeStart;
+ if ((classifier instanceof UpdateableClassifier)
+ && (testSetPresent || noCrossValidation) && (costMatrix == null)) {
+
+ // Classifier was trained incrementally, so we have to
+ // reset the source.
+ trainSource.reset();
+
+ // Incremental testing
+ train = trainSource.getStructure(actualClassIndex);
+ testTimeStart = System.currentTimeMillis();
+ Instance trainInst;
+ while (trainSource.hasMoreElements(train)) {
+ trainInst = trainSource.nextElement(train);
+ trainingEvaluation.evaluateModelOnce(classifier, trainInst);
+ }
+ testTimeElapsed = System.currentTimeMillis() - testTimeStart;
} else {
- testTimeStart = System.currentTimeMillis();
- trainingEvaluation.evaluateModel(
- classifier, trainSource.getDataSet(actualClassIndex));
- testTimeElapsed = System.currentTimeMillis() - testTimeStart;
+ testTimeStart = System.currentTimeMillis();
+ trainingEvaluation.evaluateModel(classifier,
+ trainSource.getDataSet(actualClassIndex));
+ testTimeElapsed = System.currentTimeMillis() - testTimeStart;
}
// Print the results of the training evaluation
if (printMargins) {
- return trainingEvaluation.toCumulativeMarginDistributionString();
+ return trainingEvaluation.toCumulativeMarginDistributionString();
} else {
if (!printClassifications) {
text.append("\nTime taken to build model: "
- + Utils.doubleToString(trainTimeElapsed / 1000.0,2)
- + " seconds");
+ + Utils.doubleToString(trainTimeElapsed / 1000.0, 2) + " seconds");
- if (splitPercentage > 0)
+ if (splitPercentage > 0) {
text.append("\nTime taken to test model on training split: ");
- else
+ } else {
text.append("\nTime taken to test model on training data: ");
- text.append(Utils.doubleToString(testTimeElapsed / 1000.0,2) + " seconds");
+ }
+ text.append(Utils.doubleToString(testTimeElapsed / 1000.0, 2)
+ + " seconds");
- if (splitPercentage > 0)
- text.append(trainingEvaluation.toSummaryString("\n\n=== Error on training"
- + " split ===\n", printComplexityStatistics));
- else
- text.append(trainingEvaluation.toSummaryString("\n\n=== Error on training"
- + " data ===\n", printComplexityStatistics));
+ if (splitPercentage > 0) {
+ text.append(trainingEvaluation.toSummaryString(
+ "\n\n=== Error on training" + " split ===\n",
+ printComplexityStatistics));
+ } else {
+ text.append(trainingEvaluation.toSummaryString(
+ "\n\n=== Error on training" + " data ===\n",
+ printComplexityStatistics));
+ }
if (template.classAttribute().isNominal()) {
if (classStatistics) {
text.append("\n\n" + trainingEvaluation.toClassDetailsString());
}
- if (!noCrossValidation)
- text.append("\n\n" + trainingEvaluation.toMatrixString());
+
+ text.append("\n\n" + trainingEvaluation.toMatrixString());
}
}
}
@@ -1224,74 +1303,68 @@ public class Evaluation
test = testSource.getStructure(test.classIndex());
Instance testInst;
while (testSource.hasMoreElements(test)) {
- testInst = testSource.nextElement(test);
- testingEvaluation.evaluateModelOnceAndRecordPrediction(
- (Classifier)classifier, testInst);
+ testInst = testSource.nextElement(test);
+ testingEvaluation.evaluateModelOnceAndRecordPrediction(classifier,
+ testInst);
}
if (splitPercentage > 0) {
if (!printClassifications) {
- text.append("\n\n" + testingEvaluation.
- toSummaryString("=== Error on test split ===\n",
- printComplexityStatistics));
+ text.append("\n\n"
+ + testingEvaluation.toSummaryString(
+ "=== Error on test split ===\n", printComplexityStatistics));
}
} else {
if (!printClassifications) {
- text.append("\n\n" + testingEvaluation.
- toSummaryString("=== Error on test data ===\n",
- printComplexityStatistics));
+ text.append("\n\n"
+ + testingEvaluation.toSummaryString("=== Error on test data ===\n",
+ printComplexityStatistics));
}
}
} else if (trainSource != null) {
if (!noCrossValidation) {
- // Testing is via cross-validation on training data
- Random random = new Random(seed);
- // use untrained (!) classifier for cross-validation
- classifier = Classifier.makeCopy(classifierBackup);
+ // Testing is via cross-validation on training data
+ Random random = new Random(seed);
+ // use untrained (!) classifier for cross-validation
+ classifier = Classifier.makeCopy(classifierBackup);
if (!printClassifications) {
- testingEvaluation.crossValidateModel(classifier,
- trainSource.getDataSet(actualClassIndex),
- folds, random);
+ testingEvaluation.crossValidateModel(classifier,
+ trainSource.getDataSet(actualClassIndex), folds, random);
if (template.classAttribute().isNumeric()) {
- text.append("\n\n\n" + testingEvaluation.
- toSummaryString("=== Cross-validation ===\n",
- printComplexityStatistics));
+ text.append("\n\n\n"
+ + testingEvaluation.toSummaryString("=== Cross-validation ===\n",
+ printComplexityStatistics));
} else {
- text.append("\n\n\n" + testingEvaluation.
- toSummaryString("=== Stratified " +
- "cross-validation ===\n",
- printComplexityStatistics));
+ text.append("\n\n\n"
+ + testingEvaluation.toSummaryString("=== Stratified "
+ + "cross-validation ===\n", printComplexityStatistics));
}
} else {
predsBuff = new StringBuffer();
predsBuff.append("\n=== Predictions under cross-validation ===\n\n");
testingEvaluation.crossValidateModel(classifier,
- trainSource.getDataSet(actualClassIndex),
- folds, random, predsBuff, attributesToOutput,
- new Boolean(printDistribution));
-/* if (template.classAttribute().isNumeric()) {
- text.append("\n\n\n" + testingEvaluation.
- toSummaryString("=== Cross-validation ===\n",
- printComplexityStatistics));
- } else {
- text.append("\n\n\n" + testingEvaluation.
- toSummaryString("=== Stratified " +
- "cross-validation ===\n",
- printComplexityStatistics));
- } */
+ trainSource.getDataSet(actualClassIndex), folds, random, predsBuff,
+ attributesToOutput, new Boolean(printDistribution));
+ /*
+ * if (template.classAttribute().isNumeric()) { text.append("\n\n\n" +
+ * testingEvaluation. toSummaryString("=== Cross-validation ===\n",
+ * printComplexityStatistics)); } else { text.append("\n\n\n" +
+ * testingEvaluation. toSummaryString("=== Stratified " +
+ * "cross-validation ===\n", printComplexityStatistics)); }
+ */
}
}
}
- if (template.classAttribute().isNominal()) {
- if (classStatistics && !noCrossValidation && !printClassifications) {
- text.append("\n\n" + testingEvaluation.toClassDetailsString());
+ if (template.classAttribute().isNominal() && !printClassifications
+ && (!noCrossValidation || (testSource != null))) {
+
+ if (classStatistics) {
+ text.append("\n\n" + testingEvaluation.toClassDetailsString());
}
- if (!noCrossValidation && !printClassifications)
- text.append("\n\n" + testingEvaluation.toMatrixString());
-
+ text.append("\n\n" + testingEvaluation.toMatrixString());
}
-
+
// predictions from cross-validation?
if (predsBuff != null) {
text.append("\n" + predsBuff);
@@ -1299,95 +1372,95 @@ public class Evaluation
if ((thresholdFile.length() != 0) && template.classAttribute().isNominal()) {
int labelIndex = 0;
- if (thresholdLabel.length() != 0)
- labelIndex = template.classAttribute().indexOfValue(thresholdLabel);
- if (labelIndex == -1)
- throw new IllegalArgumentException(
- "Class label '" + thresholdLabel + "' is unknown!");
+ if (thresholdLabel.length() != 0) {
+ labelIndex = template.classAttribute().indexOfValue(thresholdLabel);
+ }
+ if (labelIndex == -1) {
+ throw new IllegalArgumentException("Class label '" + thresholdLabel
+ + "' is unknown!");
+ }
ThresholdCurve tc = new ThresholdCurve();
- Instances result = tc.getCurve(testingEvaluation.predictions(), labelIndex);
+ Instances result =
+ tc.getCurve(testingEvaluation.predictions(), labelIndex);
DataSink.write(thresholdFile, result);
}
-
+
return text.toString();
}
/**
* Attempts to load a cost matrix.
- *
+ *
* @param costFileName the filename of the cost matrix
* @param numClasses the number of classes that should be in the cost matrix
- * (only used if the cost file is in old format).
+ * (only used if the cost file is in old format).
* @return a <code>CostMatrix</code> value, or null if costFileName is empty
* @throws Exception if an error occurs.
*/
- protected static CostMatrix handleCostOption(String costFileName,
- int numClasses)
- throws Exception {
+ protected static CostMatrix handleCostOption(String costFileName,
+ int numClasses) throws Exception {
if ((costFileName != null) && (costFileName.length() != 0)) {
- System.out.println(
- "NOTE: The behaviour of the -m option has changed between WEKA 3.0"
- +" and WEKA 3.1. -m now carries out cost-sensitive *evaluation*"
- +" only. For cost-sensitive *prediction*, use one of the"
- +" cost-sensitive metaschemes such as"
- +" weka.classifiers.meta.CostSensitiveClassifier or"
- +" weka.classifiers.meta.MetaCost");
+ System.out
+ .println("NOTE: The behaviour of the -m option has changed between WEKA 3.0"
+ + " and WEKA 3.1. -m now carries out cost-sensitive *evaluation*"
+ + " only. For cost-sensitive *prediction*, use one of the"
+ + " cost-sensitive metaschemes such as"
+ + " weka.classifiers.meta.CostSensitiveClassifier or"
+ + " weka.classifiers.meta.MetaCost");
Reader costReader = null;
try {
- costReader = new BufferedReader(new FileReader(costFileName));
+ costReader = new BufferedReader(new FileReader(costFileName));
} catch (Exception e) {
- throw new Exception("Can't open file " + e.getMessage() + '.');
+ throw new Exception("Can't open file " + e.getMessage() + '.');
}
try {
- // First try as a proper cost matrix format
- return new CostMatrix(costReader);
+ // First try as a proper cost matrix format
+ return new CostMatrix(costReader);
} catch (Exception ex) {
- try {
- // Now try as the poxy old format :-)
- //System.err.println("Attempting to read old format cost file");
- try {
- costReader.close(); // Close the old one
- costReader = new BufferedReader(new FileReader(costFileName));
- } catch (Exception e) {
- throw new Exception("Can't open file " + e.getMessage() + '.');
- }
- CostMatrix costMatrix = new CostMatrix(numClasses);
- //System.err.println("Created default cost matrix");
- costMatrix.readOldFormat(costReader);
- return costMatrix;
- //System.err.println("Read old format");
- } catch (Exception e2) {
- // re-throw the original exception
- //System.err.println("Re-throwing original exception");
- throw ex;
- }
+ try {
+ // Now try as the poxy old format :-)
+ // System.err.println("Attempting to read old format cost file");
+ try {
+ costReader.close(); // Close the old one
+ costReader = new BufferedReader(new FileReader(costFileName));
+ } catch (Exception e) {
+ throw new Exception("Can't open file " + e.getMessage() + '.');
+ }
+ CostMatrix costMatrix = new CostMatrix(numClasses);
+ // System.err.println("Created default cost matrix");
+ costMatrix.readOldFormat(costReader);
+ return costMatrix;
+ // System.err.println("Read old format");
+ } catch (Exception e2) {
+ // re-throw the original exception
+ // System.err.println("Re-throwing original exception");
+ throw ex;
+ }
}
} else {
return null;
}
}
-
+
/**
- * Evaluates the classifier on a given set of instances. Note that
- * the data must have exactly the same format (e.g. order of
- * attributes) as the data used to train the classifier! Otherwise
- * the results will generally be meaningless.
- *
+ * Evaluates the classifier on a given set of instances. Note that the data
+ * must have exactly the same format (e.g. order of attributes) as the data
+ * used to train the classifier! Otherwise the results will generally be
+ * meaningless.
+ *
* @param classifier machine learning classifier
* @param data set of test instances for evaluation
* @param forPredictionsString varargs parameter that, if supplied, is
- * expected to hold a StringBuffer to print predictions to,
- * a Range of attributes to output and a Boolean (true if the distribution
- * is to be printed)
+ * expected to hold a StringBuffer to print predictions to, a Range
+ * of attributes to output and a Boolean (true if the distribution is
+ * to be printed)
* @return the predictions
- * @throws Exception if model could not be evaluated
- * successfully
+ * @throws Exception if model could not be evaluated successfully
*/
- public double[] evaluateModel(Classifier classifier,
- Instances data,
- Object... forPredictionsPrinting) throws Exception {
+ public double[] evaluateModel(Classifier classifier, Instances data,
+ Object... forPredictionsPrinting) throws Exception {
// for predictions printing
StringBuffer buff = null;
Range attsToOutput = null;
@@ -1396,19 +1469,19 @@ public class Evaluation
double predictions[] = new double[data.numInstances()];
if (forPredictionsPrinting.length > 0) {
- buff = (StringBuffer)forPredictionsPrinting[0];
- attsToOutput = (Range)forPredictionsPrinting[1];
- printDist = ((Boolean)forPredictionsPrinting[2]).booleanValue();
+ buff = (StringBuffer) forPredictionsPrinting[0];
+ attsToOutput = (Range) forPredictionsPrinting[1];
+ printDist = ((Boolean) forPredictionsPrinting[2]).booleanValue();
}
// Need to be able to collect predictions if appropriate (for AUC)
for (int i = 0; i < data.numInstances(); i++) {
- predictions[i] = evaluateModelOnceAndRecordPrediction((Classifier)classifier,
- data.instance(i));
+ predictions[i] =
+ evaluateModelOnceAndRecordPrediction(classifier, data.instance(i));
if (buff != null) {
- buff.append(predictionText(classifier, data.instance(i), i,
- attsToOutput, printDist));
+ buff.append(predictionText(classifier, data.instance(i), i,
+ attsToOutput, printDist));
}
}
@@ -1416,34 +1489,34 @@ public class Evaluation
}
/**
- * Evaluates the classifier on a single instance and records the
- * prediction (if the class is nominal).
- *
+ * Evaluates the classifier on a single instance and records the prediction
+ * (if the class is nominal).
+ *
* @param classifier machine learning classifier
* @param instance the test instance to be classified
* @return the prediction made by the clasifier
- * @throws Exception if model could not be evaluated
- * successfully or the data contains string attributes
+ * @throws Exception if model could not be evaluated successfully or the data
+ * contains string attributes
*/
public double evaluateModelOnceAndRecordPrediction(Classifier classifier,
- Instance instance) throws Exception {
+ Instance instance) throws Exception {
- Instance classMissing = (Instance)instance.copy();
+ Instance classMissing = (Instance) instance.copy();
double pred = 0;
classMissing.setDataset(instance.dataset());
classMissing.setClassMissing();
if (m_ClassIsNominal) {
if (m_Predictions == null) {
- m_Predictions = new FastVector();
+ m_Predictions = new FastVector();
}
- double [] dist = classifier.distributionForInstance(classMissing);
+ double[] dist = classifier.distributionForInstance(classMissing);
pred = Utils.maxIndex(dist);
- if (dist[(int)pred] <= 0) {
- pred = Instance.missingValue();
+ if (dist[(int) pred] <= 0) {
+ pred = Instance.missingValue();
}
updateStatsForClassifier(dist, instance);
- m_Predictions.addElement(new NominalPrediction(instance.classValue(), dist,
- instance.weight()));
+ m_Predictions.addElement(new NominalPrediction(instance.classValue(),
+ dist, instance.weight()));
} else {
pred = classifier.classifyInstance(classMissing);
updateStatsForPredictor(pred, instance);
@@ -1453,25 +1526,25 @@ public class Evaluation
/**
* Evaluates the classifier on a single instance.
- *
+ *
* @param classifier machine learning classifier
* @param instance the test instance to be classified
* @return the prediction made by the clasifier
- * @throws Exception if model could not be evaluated
- * successfully or the data contains string attributes
+ * @throws Exception if model could not be evaluated successfully or the data
+ * contains string attributes
*/
- public double evaluateModelOnce(Classifier classifier,
- Instance instance) throws Exception {
+ public double evaluateModelOnce(Classifier classifier, Instance instance)
+ throws Exception {
- Instance classMissing = (Instance)instance.copy();
+ Instance classMissing = (Instance) instance.copy();
double pred = 0;
classMissing.setDataset(instance.dataset());
classMissing.setClassMissing();
if (m_ClassIsNominal) {
- double [] dist = classifier.distributionForInstance(classMissing);
+ double[] dist = classifier.distributionForInstance(classMissing);
pred = Utils.maxIndex(dist);
- if (dist[(int)pred] <= 0) {
- pred = Instance.missingValue();
+ if (dist[(int) pred] <= 0) {
+ pred = Instance.missingValue();
}
updateStatsForClassifier(dist, instance);
} else {
@@ -1483,20 +1556,19 @@ public class Evaluation
/**
* Evaluates the supplied distribution on a single instance.
- *
+ *
* @param dist the supplied distribution
* @param instance the test instance to be classified
* @return the prediction
- * @throws Exception if model could not be evaluated
- * successfully
+ * @throws Exception if model could not be evaluated successfully
*/
- public double evaluateModelOnce(double [] dist,
- Instance instance) throws Exception {
+ public double evaluateModelOnce(double[] dist, Instance instance)
+ throws Exception {
double pred;
if (m_ClassIsNominal) {
pred = Utils.maxIndex(dist);
- if (dist[(int)pred] <= 0) {
- pred = Instance.missingValue();
+ if (dist[(int) pred] <= 0) {
+ pred = Instance.missingValue();
}
updateStatsForClassifier(dist, instance);
} else {
@@ -1508,27 +1580,26 @@ public class Evaluation
/**
* Evaluates the supplied distribution on a single instance.
- *
+ *
* @param dist the supplied distribution
* @param instance the test instance to be classified
* @return the prediction
- * @throws Exception if model could not be evaluated
- * successfully
+ * @throws Exception if model could not be evaluated successfully
*/
- public double evaluateModelOnceAndRecordPrediction(double [] dist,
- Instance instance) throws Exception {
+ public double evaluateModelOnceAndRecordPrediction(double[] dist,
+ Instance instance) throws Exception {
double pred;
if (m_ClassIsNominal) {
if (m_Predictions == null) {
- m_Predictions = new FastVector();
+ m_Predictions = new FastVector();
}
pred = Utils.maxIndex(dist);
- if (dist[(int)pred] <= 0) {
- pred = Instance.missingValue();
+ if (dist[(int) pred] <= 0) {
+ pred = Instance.missingValue();
}
updateStatsForClassifier(dist, instance);
- m_Predictions.addElement(new NominalPrediction(instance.classValue(), dist,
- instance.weight()));
+ m_Predictions.addElement(new NominalPrediction(instance.classValue(),
+ dist, instance.weight()));
} else {
pred = dist[0];
updateStatsForPredictor(pred, instance);
@@ -1538,18 +1609,16 @@ public class Evaluation
/**
* Evaluates the supplied prediction on a single instance.
- *
+ *
* @param prediction the supplied prediction
* @param instance the test instance to be classified
- * @throws Exception if model could not be evaluated
- * successfully
+ * @throws Exception if model could not be evaluated successfully
*/
- public void evaluateModelOnce(double prediction,
- Instance instance) throws Exception {
+ public void evaluateModelOnce(double prediction, Instance instance)
+ throws Exception {
if (m_ClassIsNominal) {
- updateStatsForClassifier(makeDistribution(prediction),
- instance);
+ updateStatsForClassifier(makeDistribution(prediction), instance);
} else {
updateStatsForPredictor(prediction, instance);
}
@@ -1557,10 +1626,10 @@ public class Evaluation
/**
* Returns the predictions that have been collected.
- *
- * @return a reference to the FastVector containing the predictions
- * that have been collected. This should be null if no predictions
- * have been collected (e.g. if the class is numeric).
+ *
+ * @return a reference to the FastVector containing the predictions that have
+ * been collected. This should be null if no predictions have been
+ * collected (e.g. if the class is numeric).
*/
public FastVector predictions() {
@@ -1568,24 +1637,25 @@ public class Evaluation
}
/**
- * Wraps a static classifier in enough source to test using the weka
- * class libraries.
- *
+ * Wraps a static classifier in enough source to test using the weka class
+ * libraries.
+ *
* @param classifier a Sourcable Classifier
* @param className the name to give to the source code class
- * @return the source for a static classifier that can be tested with
- * weka libraries.
+ * @return the source for a static classifier that can be tested with weka
+ * libraries.
* @throws Exception if code-generation fails
*/
- public static String wekaStaticWrapper(Sourcable classifier, String className)
+ public static String wekaStaticWrapper(Sourcable classifier, String className)
throws Exception {
StringBuffer result = new StringBuffer();
String staticClassifier = classifier.toSource(className);
-
+
result.append("// Generated with Weka " + Version.VERSION + "\n");
result.append("//\n");
- result.append("// This code is public domain and comes with no warranty.\n");
+ result
+ .append("// This code is public domain and comes with no warranty.\n");
result.append("//\n");
result.append("// Timestamp: " + new Date() + "\n");
result.append("\n");
@@ -1601,7 +1671,7 @@ public class Evaluation
result.append("\n");
result.append("public class WekaWrapper\n");
result.append(" extends Classifier {\n");
-
+
// globalInfo
result.append("\n");
result.append(" /**\n");
@@ -1612,7 +1682,7 @@ public class Evaluation
result.append(" public String globalInfo() {\n");
result.append(" return toString();\n");
result.append(" }\n");
-
+
// getCapabilities
result.append("\n");
result.append(" /**\n");
@@ -1621,10 +1691,11 @@ public class Evaluation
result.append(" * @return the capabilities\n");
result.append(" */\n");
result.append(" public Capabilities getCapabilities() {\n");
- result.append(((Classifier) classifier).getCapabilities().toSource("result", 4));
+ result.append(((Classifier) classifier).getCapabilities().toSource(
+ "result", 4));
result.append(" return result;\n");
result.append(" }\n");
-
+
// buildClassifier
result.append("\n");
result.append(" /**\n");
@@ -1632,11 +1703,12 @@ public class Evaluation
result.append(" *\n");
result.append(" * @param i the training data\n");
result.append(" */\n");
- result.append(" public void buildClassifier(Instances i) throws Exception {\n");
+ result
+ .append(" public void buildClassifier(Instances i) throws Exception {\n");
result.append(" // can classifier handle the data?\n");
result.append(" getCapabilities().testWithFail(i);\n");
result.append(" }\n");
-
+
// classifyInstance
result.append("\n");
result.append(" /**\n");
@@ -1645,7 +1717,8 @@ public class Evaluation
result.append(" * @param i the instance to classify\n");
result.append(" * @return the classification result\n");
result.append(" */\n");
- result.append(" public double classifyInstance(Instance i) throws Exception {\n");
+ result
+ .append(" public double classifyInstance(Instance i) throws Exception {\n");
result.append(" Object[] s = new Object[i.numAttributes()];\n");
result.append(" \n");
result.append(" for (int j = 0; j < s.length; j++) {\n");
@@ -1677,16 +1750,18 @@ public class Evaluation
// toString
result.append("\n");
result.append(" /**\n");
- result.append(" * Returns only the classnames and what classifier it is based on.\n");
+ result
+ .append(" * Returns only the classnames and what classifier it is based on.\n");
result.append(" *\n");
result.append(" * @return a short description\n");
result.append(" */\n");
result.append(" public String toString() {\n");
- result.append(" return \"Auto-generated classifier wrapper, based on "
- + classifier.getClass().getName() + " (generated with Weka " + Version.VERSION + ").\\n"
- + "\" + this.getClass().getName() + \"/" + className + "\";\n");
+ result.append(" return \"Auto-generated classifier wrapper, based on "
+ + classifier.getClass().getName() + " (generated with Weka "
+ + Version.VERSION + ").\\n" + "\" + this.getClass().getName() + \"/"
+ + className + "\";\n");
result.append(" }\n");
-
+
// main
result.append("\n");
result.append(" /**\n");
@@ -1698,19 +1773,18 @@ public class Evaluation
result.append(" runClassifier(new WekaWrapper(), args);\n");
result.append(" }\n");
result.append("}\n");
-
+
// actual classifier code
result.append("\n");
result.append(staticClassifier);
-
+
return result.toString();
}
/**
- * Gets the number of test instances that had a known class value
- * (actually the sum of the weights of test instances with known
- * class value).
- *
+ * Gets the number of test instances that had a known class value (actually
+ * the sum of the weights of test instances with known class value).
+ *
* @return the number of test instances with known class
*/
public final double numInstances() {
@@ -1719,11 +1793,11 @@ public class Evaluation
}
/**
- * Gets the number of instances incorrectly classified (that is, for
- * which an incorrect prediction was made). (Actually the sum of the weights
- * of these instances)
- *
- * @return the number of incorrectly classified instances
+ * Gets the number of instances incorrectly classified (that is, for which an
+ * incorrect prediction was made). (Actually the sum of the weights of these
+ * instances)
+ *
+ * @return the number of incorrectly classified instances
*/
public final double incorrect() {
@@ -1731,11 +1805,10 @@ public class Evaluation
}
/**
- * Gets the percentage of instances incorrectly classified (that is, for
- * which an incorrect prediction was made).
- *
- * @return the percent of incorrectly classified instances
- * (between 0 and 100)
+ * Gets the percentage of instances incorrectly classified (that is, for which
+ * an incorrect prediction was made).
+ *
+ * @return the percent of incorrectly classified instances (between 0 and 100)
*/
public final double pctIncorrect() {
@@ -1743,9 +1816,9 @@ public class Evaluation
}
/**
- * Gets the total cost, that is, the cost of each prediction times the
- * weight of the instance, summed over all instances.
- *
+ * Gets the total cost, that is, the cost of each prediction times the weight
+ * of the instance, summed over all instances.
+ *
* @return the total cost
*/
public final double totalCost() {
@@ -1754,10 +1827,10 @@ public class Evaluation
}
/**
- * Gets the average cost, that is, total cost of misclassifications
- * (incorrect plus unclassified) over the total number of instances.
- *
- * @return the average cost.
+ * Gets the average cost, that is, total cost of misclassifications (incorrect
+ * plus unclassified) over the total number of instances.
+ *
+ * @return the average cost.
*/
public final double avgCost() {
@@ -1765,10 +1838,10 @@ public class Evaluation
}
/**
- * Gets the number of instances correctly classified (that is, for
- * which a correct prediction was made). (Actually the sum of the weights
- * of these instances)
- *
+ * Gets the number of instances correctly classified (that is, for which a
+ * correct prediction was made). (Actually the sum of the weights of these
+ * instances)
+ *
* @return the number of correctly classified instances
*/
public final double correct() {
@@ -1777,9 +1850,9 @@ public class Evaluation
}
/**
- * Gets the percentage of instances correctly classified (that is, for
- * which a correct prediction was made).
- *
+ * Gets the percentage of instances correctly classified (that is, for which a
+ * correct prediction was made).
+ *
* @return the percent of correctly classified instances (between 0 and 100)
*/
public final double pctCorrect() {
@@ -1788,10 +1861,10 @@ public class Evaluation
}
/**
- * Gets the number of instances not classified (that is, for
- * which no prediction was made by the classifier). (Actually the sum
- * of the weights of these instances)
- *
+ * Gets the number of instances not classified (that is, for which no
+ * prediction was made by the classifier). (Actually the sum of the weights of
+ * these instances)
+ *
* @return the number of unclassified instances
*/
public final double unclassified() {
@@ -1800,9 +1873,9 @@ public class Evaluation
}
/**
- * Gets the percentage of instances not classified (that is, for
- * which no prediction was made by the classifier).
- *
+ * Gets the percentage of instances not classified (that is, for which no
+ * prediction was made by the classifier).
+ *
* @return the percent of unclassified instances (between 0 and 100)
*/
public final double pctUnclassified() {
@@ -1811,12 +1884,12 @@ public class Evaluation
}
/**
- * Returns the estimated error rate or the root mean squared error
- * (if the class is numeric). If a cost matrix was given this
- * error rate gives the average cost.
- *
- * @return the estimated error rate (between 0 and 1, or between 0 and
- * maximum cost)
+ * Returns the estimated error rate or the root mean squared error (if the
+ * class is numeric). If a cost matrix was given this error rate gives the
+ * average cost.
+ *
+ * @return the estimated error rate (between 0 and 1, or between 0 and maximum
+ * cost)
*/
public final double errorRate() {
@@ -1832,20 +1905,19 @@ public class Evaluation
/**
* Returns value of kappa statistic if class is nominal.
- *
+ *
* @return the value of the kappa statistic
*/
public final double kappa() {
-
double[] sumRows = new double[m_ConfusionMatrix.length];
double[] sumColumns = new double[m_ConfusionMatrix.length];
double sumOfWeights = 0;
for (int i = 0; i < m_ConfusionMatrix.length; i++) {
for (int j = 0; j < m_ConfusionMatrix.length; j++) {
- sumRows[i] += m_ConfusionMatrix[i][j];
- sumColumns[j] += m_ConfusionMatrix[i][j];
- sumOfWeights += m_ConfusionMatrix[i][j];
+ sumRows[i] += m_ConfusionMatrix[i][j];
+ sumColumns[j] += m_ConfusionMatrix[i][j];
+ sumOfWeights += m_ConfusionMatrix[i][j];
}
}
double correct = 0, chanceAgreement = 0;
@@ -1865,28 +1937,26 @@ public class Evaluation
/**
* Returns the correlation coefficient if the class is numeric.
- *
+ *
* @return the correlation coefficient
* @throws Exception if class is not numeric
*/
public final double correlationCoefficient() throws Exception {
if (m_ClassIsNominal) {
- throw
- new Exception("Can't compute correlation coefficient: " +
- "class is nominal!");
+ throw new Exception("Can't compute correlation coefficient: "
+ + "class is nominal!");
}
double correlation = 0;
- double varActual =
- m_SumSqrClass - m_SumClass * m_SumClass /
- (m_WithClass - m_Unclassified);
- double varPredicted =
- m_SumSqrPredicted - m_SumPredicted * m_SumPredicted /
- (m_WithClass - m_Unclassified);
- double varProd =
- m_SumClassPredicted - m_SumClass * m_SumPredicted /
- (m_WithClass - m_Unclassified);
+ double varActual =
+ m_SumSqrClass - m_SumClass * m_SumClass / (m_WithClass - m_Unclassified);
+ double varPredicted =
+ m_SumSqrPredicted - m_SumPredicted * m_SumPredicted
+ / (m_WithClass - m_Unclassified);
+ double varProd =
+ m_SumClassPredicted - m_SumClass * m_SumPredicted
+ / (m_WithClass - m_Unclassified);
if (varActual * varPredicted <= 0) {
correlation = 0.0;
@@ -1898,11 +1968,11 @@ public class Evaluation
}
/**
- * Returns the mean absolute error. Refers to the error of the
- * predicted values for numeric classes, and the error of the
- * predicted probability distribution for nominal classes.
- *
- * @return the mean absolute error
+ * Returns the mean absolute error. Refers to the error of the predicted
+ * values for numeric classes, and the error of the predicted probability
+ * distribution for nominal classes.
+ *
+ * @return the mean absolute error
*/
public final double meanAbsoluteError() {
@@ -1911,35 +1981,37 @@ public class Evaluation
/**
* Returns the mean absolute error of the prior.
- *
- * @return the mean absolute error
+ *
+ * @return the mean absolute error
*/
public final double meanPriorAbsoluteError() {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return m_SumPriorAbsErr / m_WithClass;
}
/**
* Returns the relative absolute error.
- *
- * @return the relative absolute error
+ *
+ * @return the relative absolute error
* @throws Exception if it can't be computed
*/
public final double relativeAbsoluteError() throws Exception {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return 100 * meanAbsoluteError() / meanPriorAbsoluteError();
}
/**
* Returns the root mean squared error.
- *
- * @return the root mean squared error
+ *
+ * @return the root mean squared error
*/
public final double rootMeanSquaredError() {
@@ -1948,113 +2020,111 @@ public class Evaluation
/**
* Returns the root mean prior squared error.
- *
- * @return the root mean prior squared error
+ *
+ * @return the root mean prior squared error
*/
public final double rootMeanPriorSquaredError() {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return Math.sqrt(m_SumPriorSqrErr / m_WithClass);
}
/**
* Returns the root relative squared error if the class is numeric.
- *
- * @return the root relative squared error
+ *
+ * @return the root relative squared error
*/
public final double rootRelativeSquaredError() {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
- return 100.0 * rootMeanSquaredError() /
- rootMeanPriorSquaredError();
+ return 100.0 * rootMeanSquaredError() / rootMeanPriorSquaredError();
}
/**
* Calculate the entropy of the prior distribution
- *
+ *
* @return the entropy of the prior distribution
* @throws Exception if the class is not nominal
*/
public final double priorEntropy() throws Exception {
if (!m_ClassIsNominal) {
- throw
- new Exception("Can't compute entropy of class prior: " +
- "class numeric!");
+ throw new Exception("Can't compute entropy of class prior: "
+ + "class numeric!");
}
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
double entropy = 0;
- for(int i = 0; i < m_NumClasses; i++) {
- entropy -= m_ClassPriors[i] / m_ClassPriorsSum
- * Utils.log2(m_ClassPriors[i] / m_ClassPriorsSum);
+ for (int i = 0; i < m_NumClasses; i++) {
+ entropy -=
+ m_ClassPriors[i] / m_ClassPriorsSum
+ * Utils.log2(m_ClassPriors[i] / m_ClassPriorsSum);
}
return entropy;
}
/**
* Return the total Kononenko & Bratko Information score in bits
- *
+ *
* @return the K&B information score
* @throws Exception if the class is not nominal
*/
public final double KBInformation() throws Exception {
if (!m_ClassIsNominal) {
- throw
- new Exception("Can't compute K&B Info score: " +
- "class numeric!");
+ throw new Exception("Can't compute K&B Info score: " + "class numeric!");
}
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return m_SumKBInfo;
}
/**
- * Return the Kononenko & Bratko Information score in bits per
- * instance.
- *
+ * Return the Kononenko & Bratko Information score in bits per instance.
+ *
* @return the K&B information score
* @throws Exception if the class is not nominal
*/
public final double KBMeanInformation() throws Exception {
if (!m_ClassIsNominal) {
- throw
- new Exception("Can't compute K&B Info score: "
- + "class numeric!");
+ throw new Exception("Can't compute K&B Info score: " + "class numeric!");
}
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return m_SumKBInfo / (m_WithClass - m_Unclassified);
}
/**
* Return the Kononenko & Bratko Relative Information score
- *
+ *
* @return the K&B relative information score
* @throws Exception if the class is not nominal
*/
public final double KBRelativeInformation() throws Exception {
if (!m_ClassIsNominal) {
- throw
- new Exception("Can't compute K&B Info score: " +
- "class numeric!");
+ throw new Exception("Can't compute K&B Info score: " + "class numeric!");
}
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return 100.0 * KBInformation() / priorEntropy();
}
@@ -2066,8 +2136,9 @@ public class Evaluation
*/
public final double SFPriorEntropy() {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return m_SumPriorEntropy;
}
@@ -2079,8 +2150,9 @@ public class Evaluation
*/
public final double SFMeanPriorEntropy() {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return m_SumPriorEntropy / m_WithClass;
}
@@ -2092,8 +2164,9 @@ public class Evaluation
*/
public final double SFSchemeEntropy() {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return m_SumSchemeEntropy;
}
@@ -2105,45 +2178,48 @@ public class Evaluation
*/
public final double SFMeanSchemeEntropy() {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return m_SumSchemeEntropy / (m_WithClass - m_Unclassified);
}
/**
- * Returns the total SF, which is the null model entropy minus
- * the scheme entropy.
+ * Returns the total SF, which is the null model entropy minus the scheme
+ * entropy.
*
* @return the total SF
*/
public final double SFEntropyGain() {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
return m_SumPriorEntropy - m_SumSchemeEntropy;
}
/**
- * Returns the SF per instance, which is the null model entropy
- * minus the scheme entropy, per instance.
+ * Returns the SF per instance, which is the null model entropy minus the
+ * scheme entropy, per instance.
*
* @return the SF per instance
*/
public final double SFMeanEntropyGain() {
- if (m_NoPriors)
+ if (m_NoPriors) {
return Double.NaN;
+ }
- return (m_SumPriorEntropy - m_SumSchemeEntropy) /
- (m_WithClass - m_Unclassified);
+ return (m_SumPriorEntropy - m_SumSchemeEntropy)
+ / (m_WithClass - m_Unclassified);
}
/**
- * Output the cumulative margin distribution as a string suitable
- * for input for gnuplot or similar package.
- *
+ * Output the cumulative margin distribution as a string suitable for input
+ * for gnuplot or similar package.
+ *
* @return the cumulative margin distribution
* @throws Exception if the class attribute is nominal
*/
@@ -2155,27 +2231,29 @@ public class Evaluation
String result = "";
double cumulativeCount = 0;
double margin;
- for(int i = 0; i <= k_MarginResolution; i++) {
+ for (int i = 0; i <= k_MarginResolution; i++) {
if (m_MarginCounts[i] != 0) {
- cumulativeCount += m_MarginCounts[i];
- margin = (double)i * 2.0 / k_MarginResolution - 1.0;
- result = result + Utils.doubleToString(margin, 7, 3) + ' '
- + Utils.doubleToString(cumulativeCount * 100
- / m_WithClass, 7, 3) + '\n';
+ cumulativeCount += m_MarginCounts[i];
+ margin = i * 2.0 / k_MarginResolution - 1.0;
+ result =
+ result + Utils.doubleToString(margin, 7, 3) + ' '
+ + Utils.doubleToString(cumulativeCount * 100 / m_WithClass, 7, 3)
+ + '\n';
} else if (i == 0) {
- result = Utils.doubleToString(-1.0, 7, 3) + ' '
- + Utils.doubleToString(0, 7, 3) + '\n';
+ result =
+ Utils.doubleToString(-1.0, 7, 3) + ' '
+ + Utils.doubleToString(0, 7, 3) + '\n';
}
}
return result;
}
-
/**
* Calls toSummaryString() with no title and no complexity stats
- *
+ *
* @return a summary description of the classifier evaluation
*/
+ @Override
public String toSummaryString() {
return toSummaryString("", false);
@@ -2183,9 +2261,9 @@ public class Evaluation
/**
* Calls toSummaryString() with a default title.
- *
+ *
* @param printComplexityStatistics if true, complexity statistics are
- * returned as well
+ * returned as well
* @return the summary string
*/
public String toSummaryString(boolean printComplexityStatistics) {
@@ -2194,121 +2272,111 @@ public class Evaluation
}
/**
- * Outputs the performance statistics in summary form. Lists
- * number (and percentage) of instances classified correctly,
- * incorrectly and unclassified. Outputs the total number of
- * instances classified, and the number of instances (if any)
- * that had no class value provided.
- *
+ * Outputs the performance statistics in summary form. Lists number (and
+ * percentage) of instances classified correctly, incorrectly and
+ * unclassified. Outputs the total number of instances classified, and the
+ * number of instances (if any) that had no class value provided.
+ *
* @param title the title for the statistics
* @param printComplexityStatistics if true, complexity statistics are
- * returned as well
+ * returned as well
* @return the summary as a String
*/
- public String toSummaryString(String title,
- boolean printComplexityStatistics) {
+ public String toSummaryString(String title, boolean printComplexityStatistics) {
StringBuffer text = new StringBuffer();
if (printComplexityStatistics && m_NoPriors) {
printComplexityStatistics = false;
- System.err.println("Priors disabled, cannot print complexity statistics!");
+ System.err
+ .println("Priors disabled, cannot print complexity statistics!");
}
text.append(title + "\n");
try {
if (m_WithClass > 0) {
- if (m_ClassIsNominal) {
-
- text.append("Correctly Classified Instances ");
- text.append(Utils.doubleToString(correct(), 12, 4) + " " +
- Utils.doubleToString(pctCorrect(),
- 12, 4) + " %\n");
- text.append("Incorrectly Classified Instances ");
- text.append(Utils.doubleToString(incorrect(), 12, 4) + " " +
- Utils.doubleToString(pctIncorrect(),
- 12, 4) + " %\n");
- text.append("Kappa statistic ");
- text.append(Utils.doubleToString(kappa(), 12, 4) + "\n");
-
- if (m_CostMatrix != null) {
- text.append("Total Cost ");
- text.append(Utils.doubleToString(totalCost(), 12, 4) + "\n");
- text.append("Average Cost ");
- text.append(Utils.doubleToString(avgCost(), 12, 4) + "\n");
- }
- if (printComplexityStatistics) {
- text.append("K&B Relative Info Score ");
- text.append(Utils.doubleToString(KBRelativeInformation(), 12, 4)
- + " %\n");
- text.append("K&B Information Score ");
- text.append(Utils.doubleToString(KBInformation(), 12, 4)
- + " bits");
- text.append(Utils.doubleToString(KBMeanInformation(), 12, 4)
- + " bits/instance\n");
- }
- } else {
- text.append("Correlation coefficient ");
- text.append(Utils.doubleToString(correlationCoefficient(), 12 , 4) +
- "\n");
- }
- if (printComplexityStatistics) {
- text.append("Class complexity | order 0 ");
- text.append(Utils.doubleToString(SFPriorEntropy(), 12, 4)
- + " bits");
- text.append(Utils.doubleToString(SFMeanPriorEntropy(), 12, 4)
- + " bits/instance\n");
- text.append("Class complexity | scheme ");
- text.append(Utils.doubleToString(SFSchemeEntropy(), 12, 4)
- + " bits");
- text.append(Utils.doubleToString(SFMeanSchemeEntropy(), 12, 4)
- + " bits/instance\n");
- text.append("Complexity improvement (Sf) ");
- text.append(Utils.doubleToString(SFEntropyGain(), 12, 4) + " bits");
- text.append(Utils.doubleToString(SFMeanEntropyGain(), 12, 4)
- + " bits/instance\n");
- }
-
- text.append("Mean absolute error ");
- text.append(Utils.doubleToString(meanAbsoluteError(), 12, 4)
- + "\n");
- text.append("Root mean squared error ");
- text.append(Utils.
- doubleToString(rootMeanSquaredError(), 12, 4)
- + "\n");
- if (!m_NoPriors) {
- text.append("Relative absolute error ");
- text.append(Utils.doubleToString(relativeAbsoluteError(),
- 12, 4) + " %\n");
- text.append("Root relative squared error ");
- text.append(Utils.doubleToString(rootRelativeSquaredError(),
- 12, 4) + " %\n");
- }
+ if (m_ClassIsNominal) {
+
+ text.append("Correctly Classified Instances ");
+ text.append(Utils.doubleToString(correct(), 12, 4) + " "
+ + Utils.doubleToString(pctCorrect(), 12, 4) + " %\n");
+ text.append("Incorrectly Classified Instances ");
+ text.append(Utils.doubleToString(incorrect(), 12, 4) + " "
+ + Utils.doubleToString(pctIncorrect(), 12, 4) + " %\n");
+ text.append("Kappa statistic ");
+ text.append(Utils.doubleToString(kappa(), 12, 4) + "\n");
+
+ if (m_CostMatrix != null) {
+ text.append("Total Cost ");
+ text.append(Utils.doubleToString(totalCost(), 12, 4) + "\n");
+ text.append("Average Cost ");
+ text.append(Utils.doubleToString(avgCost(), 12, 4) + "\n");
+ }
+ if (printComplexityStatistics) {
+ text.append("K&B Relative Info Score ");
+ text.append(Utils.doubleToString(KBRelativeInformation(), 12, 4)
+ + " %\n");
+ text.append("K&B Information Score ");
+ text.append(Utils.doubleToString(KBInformation(), 12, 4) + " bits");
+ text.append(Utils.doubleToString(KBMeanInformation(), 12, 4)
+ + " bits/instance\n");
+ }
+ } else {
+ text.append("Correlation coefficient ");
+ text.append(Utils.doubleToString(correlationCoefficient(), 12, 4)
+ + "\n");
+ }
+ if (printComplexityStatistics) {
+ text.append("Class complexity | order 0 ");
+ text.append(Utils.doubleToString(SFPriorEntropy(), 12, 4) + " bits");
+ text.append(Utils.doubleToString(SFMeanPriorEntropy(), 12, 4)
+ + " bits/instance\n");
+ text.append("Class complexity | scheme ");
+ text.append(Utils.doubleToString(SFSchemeEntropy(), 12, 4) + " bits");
+ text.append(Utils.doubleToString(SFMeanSchemeEntropy(), 12, 4)
+ + " bits/instance\n");
+ text.append("Complexity improvement (Sf) ");
+ text.append(Utils.doubleToString(SFEntropyGain(), 12, 4) + " bits");
+ text.append(Utils.doubleToString(SFMeanEntropyGain(), 12, 4)
+ + " bits/instance\n");
+ }
+
+ text.append("Mean absolute error ");
+ text.append(Utils.doubleToString(meanAbsoluteError(), 12, 4) + "\n");
+ text.append("Root mean squared error ");
+ text.append(Utils.doubleToString(rootMeanSquaredError(), 12, 4) + "\n");
+ if (!m_NoPriors) {
+ text.append("Relative absolute error ");
+ text.append(Utils.doubleToString(relativeAbsoluteError(), 12, 4)
+ + " %\n");
+ text.append("Root relative squared error ");
+ text.append(Utils.doubleToString(rootRelativeSquaredError(), 12, 4)
+ + " %\n");
+ }
}
if (Utils.gr(unclassified(), 0)) {
- text.append("UnClassified Instances ");
- text.append(Utils.doubleToString(unclassified(), 12,4) + " " +
- Utils.doubleToString(pctUnclassified(),
- 12, 4) + " %\n");
+ text.append("UnClassified Instances ");
+ text.append(Utils.doubleToString(unclassified(), 12, 4) + " "
+ + Utils.doubleToString(pctUnclassified(), 12, 4) + " %\n");
}
text.append("Total Number of Instances ");
text.append(Utils.doubleToString(m_WithClass, 12, 4) + "\n");
if (m_MissingClass > 0) {
- text.append("Ignored Class Unknown Instances ");
- text.append(Utils.doubleToString(m_MissingClass, 12, 4) + "\n");
+ text.append("Ignored Class Unknown Instances ");
+ text.append(Utils.doubleToString(m_MissingClass, 12, 4) + "\n");
}
} catch (Exception ex) {
- // Should never occur since the class is known to be nominal
+ // Should never occur since the class is known to be nominal
// here
System.err.println("Arggh - Must be a bug in Evaluation class");
}
- return text.toString();
+ return text.toString();
}
/**
* Calls toMatrixString() with a default title.
- *
+ *
* @return the confusion matrix as a string
* @throws Exception if the class is numeric
*/
@@ -2318,10 +2386,9 @@ public class Evaluation
}
/**
- * Outputs the performance statistics as a classification confusion
- * matrix. For each class value, shows the distribution of
- * predicted class values.
- *
+ * Outputs the performance statistics as a classification confusion matrix.
+ * For each class value, shows the distribution of predicted class values.
+ *
* @param title the title for the confusion matrix
* @return the confusion matrix as a String
* @throws Exception if the class is numeric
@@ -2329,9 +2396,9 @@ public class Evaluation
public String toMatrixString(String title) throws Exception {
StringBuffer text = new StringBuffer();
- char [] IDChars = {'a','b','c','d','e','f','g','h','i','j',
- 'k','l','m','n','o','p','q','r','s','t',
- 'u','v','w','x','y','z'};
+ char[] IDChars =
+ { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
+ 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
int IDWidth;
boolean fractional = false;
@@ -2340,57 +2407,55 @@ public class Evaluation
}
// Find the maximum value in the matrix
- // and check for fractional display requirement
+ // and check for fractional display requirement
double maxval = 0;
- for(int i = 0; i < m_NumClasses; i++) {
- for(int j = 0; j < m_NumClasses; j++) {
- double current = m_ConfusionMatrix[i][j];
- if (current < 0) {
- current *= -10;
- }
- if (current > maxval) {
- maxval = current;
- }
- double fract = current - Math.rint(current);
- if (!fractional
- && ((Math.log(fract) / Math.log(10)) >= -2)) {
- fractional = true;
- }
- }
- }
-
- IDWidth = 1 + Math.max((int)(Math.log(maxval) / Math.log(10)
- + (fractional ? 3 : 0)),
- (int)(Math.log(m_NumClasses) /
- Math.log(IDChars.length)));
+ for (int i = 0; i < m_NumClasses; i++) {
+ for (int j = 0; j < m_NumClasses; j++) {
+ double current = m_ConfusionMatrix[i][j];
+ if (current < 0) {
+ current *= -10;
+ }
+ if (current > maxval) {
+ maxval = current;
+ }
+ double fract = current - Math.rint(current);
+ if (!fractional && ((Math.log(fract) / Math.log(10)) >= -2)) {
+ fractional = true;
+ }
+ }
+ }
+
+ IDWidth =
+ 1 + Math.max(
+ (int) (Math.log(maxval) / Math.log(10) + (fractional ? 3 : 0)),
+ (int) (Math.log(m_NumClasses) / Math.log(IDChars.length)));
text.append(title).append("\n");
- for(int i = 0; i < m_NumClasses; i++) {
+ for (int i = 0; i < m_NumClasses; i++) {
if (fractional) {
- text.append(" ").append(num2ShortID(i,IDChars,IDWidth - 3))
- .append(" ");
+ text.append(" ").append(num2ShortID(i, IDChars, IDWidth - 3))
+ .append(" ");
} else {
- text.append(" ").append(num2ShortID(i,IDChars,IDWidth));
+ text.append(" ").append(num2ShortID(i, IDChars, IDWidth));
}
}
text.append(" <-- classified as\n");
- for(int i = 0; i< m_NumClasses; i++) {
- for(int j = 0; j < m_NumClasses; j++) {
- text.append(" ").append(
- Utils.doubleToString(m_ConfusionMatrix[i][j],
- IDWidth,
- (fractional ? 2 : 0)));
+ for (int i = 0; i < m_NumClasses; i++) {
+ for (int j = 0; j < m_NumClasses; j++) {
+ text.append(" ").append(
+ Utils.doubleToString(m_ConfusionMatrix[i][j], IDWidth,
+ (fractional ? 2 : 0)));
}
- text.append(" | ").append(num2ShortID(i,IDChars,IDWidth))
- .append(" = ").append(m_ClassNames[i]).append("\n");
+ text.append(" | ").append(num2ShortID(i, IDChars, IDWidth)).append(" = ")
+ .append(m_ClassNames[i]).append("\n");
}
return text.toString();
}
/**
* Generates a breakdown of the accuracy for each class (with default title),
- * incorporating various information-retrieval statistics, such as
- * true/false positive rate, precision/recall/F-Measure. Should be
- * useful for ROC curves, recall/precision curves.
+ * incorporating various information-retrieval statistics, such as true/false
+ * positive rate, precision/recall/F-Measure. Should be useful for ROC curves,
+ * recall/precision curves.
*
* @return the statistics presented as a string
* @throws Exception if class is not nominal
@@ -2401,12 +2466,12 @@ public class Evaluation
}
/**
- * Generates a breakdown of the accuracy for each class,
- * incorporating various information-retrieval statistics, such as
- * true/false positive rate, precision/recall/F-Measure. Should be
- * useful for ROC curves, recall/precision curves.
+ * Generates a breakdown of the accuracy for each class, incorporating various
+ * information-retrieval statistics, such as true/false positive rate,
+ * precision/recall/F-Measure. Should be useful for ROC curves,
+ * recall/precision curves.
*
- * @param title the title to prepend the stats string with
+ * @param title the title to prepend the stats string with
* @return the statistics presented as a string
* @throws Exception if class is not nominal
*/
@@ -2416,51 +2481,50 @@ public class Evaluation
throw new Exception("Evaluation: No confusion matrix possible!");
}
- StringBuffer text = new StringBuffer(title
- + "\n TP Rate FP Rate"
- + " Precision Recall"
- + " F-Measure ROC Area Class\n");
- for(int i = 0; i < m_NumClasses; i++) {
- text.append(" " + Utils.doubleToString(truePositiveRate(i), 7, 3))
- .append(" ");
- text.append(Utils.doubleToString(falsePositiveRate(i), 7, 3))
- .append(" ");
- text.append(Utils.doubleToString(precision(i), 7, 3))
- .append(" ");
- text.append(Utils.doubleToString(recall(i), 7, 3))
- .append(" ");
- text.append(Utils.doubleToString(fMeasure(i), 7, 3))
- .append(" ");
+ StringBuffer text =
+ new StringBuffer(title + "\n TP Rate FP Rate"
+ + " Precision Recall" + " F-Measure ROC Area Class\n");
+ for (int i = 0; i < m_NumClasses; i++) {
+ text.append(
+ " " + Utils.doubleToString(truePositiveRate(i), 7, 3))
+ .append(" ");
+ text.append(Utils.doubleToString(falsePositiveRate(i), 7, 3)).append(
+ " ");
+ text.append(Utils.doubleToString(precision(i), 7, 3)).append(" ");
+ text.append(Utils.doubleToString(recall(i), 7, 3)).append(" ");
+ text.append(Utils.doubleToString(fMeasure(i), 7, 3)).append(" ");
double rocVal = areaUnderROC(i);
if (Instance.isMissingValue(rocVal)) {
- text.append(" ? ")
- .append(" ");
+ text.append(" ? ").append(" ");
} else {
- text.append(Utils.doubleToString(rocVal, 7, 3))
- .append(" ");
+ text.append(Utils.doubleToString(rocVal, 7, 3)).append(" ");
}
text.append(m_ClassNames[i]).append('\n');
}
- text.append("Weighted Avg. " + Utils.doubleToString(weightedTruePositiveRate(), 7, 3));
- text.append(" " + Utils.doubleToString(weightedFalsePositiveRate(), 7 ,3));
- text.append(" " + Utils.doubleToString(weightedPrecision(), 7 ,3));
- text.append(" " + Utils.doubleToString(weightedRecall(), 7 ,3));
- text.append(" " + Utils.doubleToString(weightedFMeasure(), 7 ,3));
- text.append(" " + Utils.doubleToString(weightedAreaUnderROC(), 7 ,3));
+ text.append("Weighted Avg. "
+ + Utils.doubleToString(weightedTruePositiveRate(), 7, 3));
+ text
+ .append(" " + Utils.doubleToString(weightedFalsePositiveRate(), 7, 3));
+ text.append(" " + Utils.doubleToString(weightedPrecision(), 7, 3));
+ text.append(" " + Utils.doubleToString(weightedRecall(), 7, 3));
+ text.append(" " + Utils.doubleToString(weightedFMeasure(), 7, 3));
+ text.append(" " + Utils.doubleToString(weightedAreaUnderROC(), 7, 3));
text.append("\n");
-
+
return text.toString();
}
/**
- * Calculate the number of true positives with respect to a particular class.
- * This is defined as<p/>
+ * Calculate the number of true positives with respect to a particular class.
+ * This is defined as
+ * <p/>
+ *
* <pre>
* correctly classified positives
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the true positive rate
*/
@@ -2469,21 +2533,23 @@ public class Evaluation
double correct = 0;
for (int j = 0; j < m_NumClasses; j++) {
if (j == classIndex) {
- correct += m_ConfusionMatrix[classIndex][j];
+ correct += m_ConfusionMatrix[classIndex][j];
}
}
return correct;
}
/**
- * Calculate the true positive rate with respect to a particular class.
- * This is defined as<p/>
+ * Calculate the true positive rate with respect to a particular class. This
+ * is defined as
+ * <p/>
+ *
* <pre>
* correctly classified positives
* ------------------------------
* total positives
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the true positive rate
*/
@@ -2492,7 +2558,7 @@ public class Evaluation
double correct = 0, total = 0;
for (int j = 0; j < m_NumClasses; j++) {
if (j == classIndex) {
- correct += m_ConfusionMatrix[classIndex][j];
+ correct += m_ConfusionMatrix[classIndex][j];
}
total += m_ConfusionMatrix[classIndex][j];
}
@@ -2504,13 +2570,13 @@ public class Evaluation
/**
* Calculates the weighted (by class size) true positive rate.
- *
+ *
* @return the weighted true positive rate.
*/
public double weightedTruePositiveRate() {
double[] classCounts = new double[m_NumClasses];
double classCountSum = 0;
-
+
for (int i = 0; i < m_NumClasses; i++) {
for (int j = 0; j < m_NumClasses; j++) {
classCounts[i] += m_ConfusionMatrix[i][j];
@@ -2519,7 +2585,7 @@ public class Evaluation
}
double truePosTotal = 0;
- for(int i = 0; i < m_NumClasses; i++) {
+ for (int i = 0; i < m_NumClasses; i++) {
double temp = truePositiveRate(i);
truePosTotal += (temp * classCounts[i]);
}
@@ -2528,12 +2594,14 @@ public class Evaluation
}
/**
- * Calculate the number of true negatives with respect to a particular class.
- * This is defined as<p/>
+ * Calculate the number of true negatives with respect to a particular class.
+ * This is defined as
+ * <p/>
+ *
* <pre>
* correctly classified negatives
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the true positive rate
*/
@@ -2542,25 +2610,27 @@ public class Evaluation
double correct = 0;
for (int i = 0; i < m_NumClasses; i++) {
if (i != classIndex) {
- for (int j = 0; j < m_NumClasses; j++) {
- if (j != classIndex) {
- correct += m_ConfusionMatrix[i][j];
- }
- }
+ for (int j = 0; j < m_NumClasses; j++) {
+ if (j != classIndex) {
+ correct += m_ConfusionMatrix[i][j];
+ }
+ }
}
}
return correct;
}
/**
- * Calculate the true negative rate with respect to a particular class.
- * This is defined as<p/>
+ * Calculate the true negative rate with respect to a particular class. This
+ * is defined as
+ * <p/>
+ *
* <pre>
* correctly classified negatives
* ------------------------------
* total negatives
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the true positive rate
*/
@@ -2569,12 +2639,12 @@ public class Evaluation
double correct = 0, total = 0;
for (int i = 0; i < m_NumClasses; i++) {
if (i != classIndex) {
- for (int j = 0; j < m_NumClasses; j++) {
- if (j != classIndex) {
- correct += m_ConfusionMatrix[i][j];
- }
- total += m_ConfusionMatrix[i][j];
- }
+ for (int j = 0; j < m_NumClasses; j++) {
+ if (j != classIndex) {
+ correct += m_ConfusionMatrix[i][j];
+ }
+ total += m_ConfusionMatrix[i][j];
+ }
}
}
if (total == 0) {
@@ -2585,13 +2655,13 @@ public class Evaluation
/**
* Calculates the weighted (by class size) true negative rate.
- *
+ *
* @return the weighted true negative rate.
*/
public double weightedTrueNegativeRate() {
double[] classCounts = new double[m_NumClasses];
double classCountSum = 0;
-
+
for (int i = 0; i < m_NumClasses; i++) {
for (int j = 0; j < m_NumClasses; j++) {
classCounts[i] += m_ConfusionMatrix[i][j];
@@ -2600,7 +2670,7 @@ public class Evaluation
}
double trueNegTotal = 0;
- for(int i = 0; i < m_NumClasses; i++) {
+ for (int i = 0; i < m_NumClasses; i++) {
double temp = trueNegativeRate(i);
trueNegTotal += (temp * classCounts[i]);
}
@@ -2609,12 +2679,14 @@ public class Evaluation
}
/**
- * Calculate number of false positives with respect to a particular class.
- * This is defined as<p/>
+ * Calculate number of false positives with respect to a particular class.
+ * This is defined as
+ * <p/>
+ *
* <pre>
* incorrectly classified negatives
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the false positive rate
*/
@@ -2623,25 +2695,27 @@ public class Evaluation
double incorrect = 0;
for (int i = 0; i < m_NumClasses; i++) {
if (i != classIndex) {
- for (int j = 0; j < m_NumClasses; j++) {
- if (j == classIndex) {
- incorrect += m_ConfusionMatrix[i][j];
- }
- }
+ for (int j = 0; j < m_NumClasses; j++) {
+ if (j == classIndex) {
+ incorrect += m_ConfusionMatrix[i][j];
+ }
+ }
}
}
return incorrect;
}
/**
- * Calculate the false positive rate with respect to a particular class.
- * This is defined as<p/>
+ * Calculate the false positive rate with respect to a particular class. This
+ * is defined as
+ * <p/>
+ *
* <pre>
* incorrectly classified negatives
* --------------------------------
* total negatives
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the false positive rate
*/
@@ -2650,12 +2724,12 @@ public class Evaluation
double incorrect = 0, total = 0;
for (int i = 0; i < m_NumClasses; i++) {
if (i != classIndex) {
- for (int j = 0; j < m_NumClasses; j++) {
- if (j == classIndex) {
- incorrect += m_ConfusionMatrix[i][j];
- }
- total += m_ConfusionMatrix[i][j];
- }
+ for (int j = 0; j < m_NumClasses; j++) {
+ if (j == classIndex) {
+ incorrect += m_ConfusionMatrix[i][j];
+ }
+ total += m_ConfusionMatrix[i][j];
+ }
}
}
if (total == 0) {
@@ -2666,13 +2740,13 @@ public class Evaluation
/**
* Calculates the weighted (by class size) false positive rate.
- *
+ *
* @return the weighted false positive rate.
*/
public double weightedFalsePositiveRate() {
double[] classCounts = new double[m_NumClasses];
double classCountSum = 0;
-
+
for (int i = 0; i < m_NumClasses; i++) {
for (int j = 0; j < m_NumClasses; j++) {
classCounts[i] += m_ConfusionMatrix[i][j];
@@ -2681,7 +2755,7 @@ public class Evaluation
}
double falsePosTotal = 0;
- for(int i = 0; i < m_NumClasses; i++) {
+ for (int i = 0; i < m_NumClasses; i++) {
double temp = falsePositiveRate(i);
falsePosTotal += (temp * classCounts[i]);
}
@@ -2689,15 +2763,15 @@ public class Evaluation
return falsePosTotal / classCountSum;
}
-
-
/**
- * Calculate number of false negatives with respect to a particular class.
- * This is defined as<p/>
+ * Calculate number of false negatives with respect to a particular class.
+ * This is defined as
+ * <p/>
+ *
* <pre>
* incorrectly classified positives
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the false positive rate
*/
@@ -2706,25 +2780,27 @@ public class Evaluation
double incorrect = 0;
for (int i = 0; i < m_NumClasses; i++) {
if (i == classIndex) {
- for (int j = 0; j < m_NumClasses; j++) {
- if (j != classIndex) {
- incorrect += m_ConfusionMatrix[i][j];
- }
- }
+ for (int j = 0; j < m_NumClasses; j++) {
+ if (j != classIndex) {
+ incorrect += m_ConfusionMatrix[i][j];
+ }
+ }
}
}
return incorrect;
}
/**
- * Calculate the false negative rate with respect to a particular class.
- * This is defined as<p/>
+ * Calculate the false negative rate with respect to a particular class. This
+ * is defined as
+ * <p/>
+ *
* <pre>
* incorrectly classified positives
* --------------------------------
* total positives
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the false positive rate
*/
@@ -2733,12 +2809,12 @@ public class Evaluation
double incorrect = 0, total = 0;
for (int i = 0; i < m_NumClasses; i++) {
if (i == classIndex) {
- for (int j = 0; j < m_NumClasses; j++) {
- if (j != classIndex) {
- incorrect += m_ConfusionMatrix[i][j];
- }
- total += m_ConfusionMatrix[i][j];
- }
+ for (int j = 0; j < m_NumClasses; j++) {
+ if (j != classIndex) {
+ incorrect += m_ConfusionMatrix[i][j];
+ }
+ total += m_ConfusionMatrix[i][j];
+ }
}
}
if (total == 0) {
@@ -2749,13 +2825,13 @@ public class Evaluation
/**
* Calculates the weighted (by class size) false negative rate.
- *
+ *
* @return the weighted false negative rate.
*/
public double weightedFalseNegativeRate() {
double[] classCounts = new double[m_NumClasses];
double classCountSum = 0;
-
+
for (int i = 0; i < m_NumClasses; i++) {
for (int j = 0; j < m_NumClasses; j++) {
classCounts[i] += m_ConfusionMatrix[i][j];
@@ -2764,7 +2840,7 @@ public class Evaluation
}
double falseNegTotal = 0;
- for(int i = 0; i < m_NumClasses; i++) {
+ for (int i = 0; i < m_NumClasses; i++) {
double temp = falseNegativeRate(i);
falseNegTotal += (temp * classCounts[i]);
}
@@ -2773,15 +2849,17 @@ public class Evaluation
}
/**
- * Calculate the recall with respect to a particular class.
- * This is defined as<p/>
+ * Calculate the recall with respect to a particular class. This is defined as
+ * <p/>
+ *
* <pre>
* correctly classified positives
* ------------------------------
* total positives
- * </pre><p/>
+ * </pre>
+ * <p/>
* (Which is also the same as the truePositiveRate.)
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the recall
*/
@@ -2792,7 +2870,7 @@ public class Evaluation
/**
* Calculates the weighted (by class size) recall.
- *
+ *
* @return the weighted recall.
*/
public double weightedRecall() {
@@ -2800,14 +2878,16 @@ public class Evaluation
}
/**
- * Calculate the precision with respect to a particular class.
- * This is defined as<p/>
+ * Calculate the precision with respect to a particular class. This is defined
+ * as
+ * <p/>
+ *
* <pre>
* correctly classified positives
* ------------------------------
* total predicted as positive
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the precision
*/
@@ -2816,7 +2896,7 @@ public class Evaluation
double correct = 0, total = 0;
for (int i = 0; i < m_NumClasses; i++) {
if (i == classIndex) {
- correct += m_ConfusionMatrix[i][classIndex];
+ correct += m_ConfusionMatrix[i][classIndex];
}
total += m_ConfusionMatrix[i][classIndex];
}
@@ -2828,13 +2908,13 @@ public class Evaluation
/**
* Calculates the weighted (by class size) false precision.
- *
+ *
* @return the weighted precision.
*/
public double weightedPrecision() {
double[] classCounts = new double[m_NumClasses];
double classCountSum = 0;
-
+
for (int i = 0; i < m_NumClasses; i++) {
for (int j = 0; j < m_NumClasses; j++) {
classCounts[i] += m_ConfusionMatrix[i][j];
@@ -2843,7 +2923,7 @@ public class Evaluation
}
double precisionTotal = 0;
- for(int i = 0; i < m_NumClasses; i++) {
+ for (int i = 0; i < m_NumClasses; i++) {
double temp = precision(i);
precisionTotal += (temp * classCounts[i]);
}
@@ -2852,14 +2932,16 @@ public class Evaluation
}
/**
- * Calculate the F-Measure with respect to a particular class.
- * This is defined as<p/>
+ * Calculate the F-Measure with respect to a particular class. This is defined
+ * as
+ * <p/>
+ *
* <pre>
* 2 * recall * precision
* ----------------------
* recall + precision
* </pre>
- *
+ *
* @param classIndex the index of the class to consider as "positive"
* @return the F-Measure
*/
@@ -2875,13 +2957,13 @@ public class Evaluation
/**
* Calculates the weighted (by class size) F-Measure.
- *
+ *
* @return the weighted F-Measure.
*/
public double weightedFMeasure() {
double[] classCounts = new double[m_NumClasses];
double classCountSum = 0;
-
+
for (int i = 0; i < m_NumClasses; i++) {
for (int j = 0; j < m_NumClasses; j++) {
classCounts[i] += m_ConfusionMatrix[i][j];
@@ -2890,7 +2972,7 @@ public class Evaluation
}
double fMeasureTotal = 0;
- for(int i = 0; i < m_NumClasses; i++) {
+ for (int i = 0; i < m_NumClasses; i++) {
double temp = fMeasure(i);
fMeasureTotal += (temp * classCounts[i]);
}
@@ -2900,11 +2982,10 @@ public class Evaluation
/**
* Sets the class prior probabilities
- *
- * @param train the training instances used to determine
- * the prior probabilities
- * @throws Exception if the class attribute of the instances is not
- * set
+ *
+ * @param train the training instances used to determine the prior
+ * probabilities
+ * @throws Exception if the class attribute of the instances is not set
*/
public void setPriors(Instances train) throws Exception {
m_NoPriors = false;
@@ -2918,24 +2999,23 @@ public class Evaluation
m_ErrorEstimator = null;
for (int i = 0; i < train.numInstances(); i++) {
- Instance currentInst = train.instance(i);
- if (!currentInst.classIsMissing()) {
- addNumericTrainClass(currentInst.classValue(),
- currentInst.weight());
- }
+ Instance currentInst = train.instance(i);
+ if (!currentInst.classIsMissing()) {
+ addNumericTrainClass(currentInst.classValue(), currentInst.weight());
+ }
}
} else {
for (int i = 0; i < m_NumClasses; i++) {
- m_ClassPriors[i] = 1;
+ m_ClassPriors[i] = 1;
}
m_ClassPriorsSum = m_NumClasses;
for (int i = 0; i < train.numInstances(); i++) {
- if (!train.instance(i).classIsMissing()) {
- m_ClassPriors[(int)train.instance(i).classValue()] +=
- train.instance(i).weight();
- m_ClassPriorsSum += train.instance(i).weight();
- }
+ if (!train.instance(i).classIsMissing()) {
+ m_ClassPriors[(int) train.instance(i).classValue()] +=
+ train.instance(i).weight();
+ m_ClassPriorsSum += train.instance(i).weight();
+ }
}
}
}
@@ -2945,80 +3025,107 @@ public class Evaluation
*
* @return the weighted class counts
*/
- public double [] getClassPriors() {
+ public double[] getClassPriors() {
return m_ClassPriors;
}
/**
- * Updates the class prior probabilities (when incrementally
- * training)
- *
+ * Updates the class prior probabilities (when incrementally training)
+ *
* @param instance the new training instance seen
- * @throws Exception if the class of the instance is not
- * set
+ * @throws Exception if the class of the instance is not set
*/
public void updatePriors(Instance instance) throws Exception {
if (!instance.classIsMissing()) {
if (!m_ClassIsNominal) {
- if (!instance.classIsMissing()) {
- addNumericTrainClass(instance.classValue(),
- instance.weight());
- }
+ if (!instance.classIsMissing()) {
+ addNumericTrainClass(instance.classValue(), instance.weight());
+ }
} else {
- m_ClassPriors[(int)instance.classValue()] +=
- instance.weight();
- m_ClassPriorsSum += instance.weight();
+ m_ClassPriors[(int) instance.classValue()] += instance.weight();
+ m_ClassPriorsSum += instance.weight();
}
- }
+ }
}
/**
- * disables the use of priors, e.g., in case of de-serialized schemes
- * that have no access to the original training set, but are evaluated
- * on a set set.
+ * disables the use of priors, e.g., in case of de-serialized schemes that
+ * have no access to the original training set, but are evaluated on a set
+ * set.
*/
public void useNoPriors() {
m_NoPriors = true;
}
/**
- * Tests whether the current evaluation object is equal to another
- * evaluation object
- *
+ * Tests whether the current evaluation object is equal to another evaluation
+ * object
+ *
* @param obj the object to compare against
* @return true if the two objects are equal
*/
+ @Override
public boolean equals(Object obj) {
if ((obj == null) || !(obj.getClass().equals(this.getClass()))) {
return false;
}
Evaluation cmp = (Evaluation) obj;
- if (m_ClassIsNominal != cmp.m_ClassIsNominal) return false;
- if (m_NumClasses != cmp.m_NumClasses) return false;
-
- if (m_Incorrect != cmp.m_Incorrect) return false;
- if (m_Correct != cmp.m_Correct) return false;
- if (m_Unclassified != cmp.m_Unclassified) return false;
- if (m_MissingClass != cmp.m_MissingClass) return false;
- if (m_WithClass != cmp.m_WithClass) return false;
-
- if (m_SumErr != cmp.m_SumErr) return false;
- if (m_SumAbsErr != cmp.m_SumAbsErr) return false;
- if (m_SumSqrErr != cmp.m_SumSqrErr) return false;
- if (m_SumClass != cmp.m_SumClass) return false;
- if (m_SumSqrClass != cmp.m_SumSqrClass) return false;
- if (m_SumPredicted != cmp.m_SumPredicted) return false;
- if (m_SumSqrPredicted != cmp.m_SumSqrPredicted) return false;
- if (m_SumClassPredicted != cmp.m_SumClassPredicted) return false;
+ if (m_ClassIsNominal != cmp.m_ClassIsNominal) {
+ return false;
+ }
+ if (m_NumClasses != cmp.m_NumClasses) {
+ return false;
+ }
+
+ if (m_Incorrect != cmp.m_Incorrect) {
+ return false;
+ }
+ if (m_Correct != cmp.m_Correct) {
+ return false;
+ }
+ if (m_Unclassified != cmp.m_Unclassified) {
+ return false;
+ }
+ if (m_MissingClass != cmp.m_MissingClass) {
+ return false;
+ }
+ if (m_WithClass != cmp.m_WithClass) {
+ return false;
+ }
+
+ if (m_SumErr != cmp.m_SumErr) {
+ return false;
+ }
+ if (m_SumAbsErr != cmp.m_SumAbsErr) {
+ return false;
+ }
+ if (m_SumSqrErr != cmp.m_SumSqrErr) {
+ return false;
+ }
+ if (m_SumClass != cmp.m_SumClass) {
+ return false;
+ }
+ if (m_SumSqrClass != cmp.m_SumSqrClass) {
+ return false;
+ }
+ if (m_SumPredicted != cmp.m_SumPredicted) {
+ return false;
+ }
+ if (m_SumSqrPredicted != cmp.m_SumSqrPredicted) {
+ return false;
+ }
+ if (m_SumClassPredicted != cmp.m_SumClassPredicted) {
+ return false;
+ }
if (m_ClassIsNominal) {
for (int i = 0; i < m_NumClasses; i++) {
- for (int j = 0; j < m_NumClasses; j++) {
- if (m_ConfusionMatrix[i][j] != cmp.m_ConfusionMatrix[i][j]) {
- return false;
- }
- }
+ for (int j = 0; j < m_NumClasses; j++) {
+ if (m_ConfusionMatrix[i][j] != cmp.m_ConfusionMatrix[i][j]) {
+ return false;
+ }
+ }
}
}
@@ -3028,60 +3135,58 @@ public class Evaluation
/**
* Prints the predictions for the given dataset into a String variable.
*
- * @param classifier the classifier to use
- * @param train the training data
- * @param testSource the test set
- * @param classIndex the class index (1-based), if -1 ot does not
- * override the class index is stored in the data
- * file (by using the last attribute)
- * @param attributesToOutput the indices of the attributes to output
- * @return the generated predictions for the attribute range
- * @throws Exception if test file cannot be opened
- */
- public static void printClassifications(Classifier classifier,
- Instances train,
- DataSource testSource,
- int classIndex,
- Range attributesToOutput,
- StringBuffer predsText) throws Exception {
-
- printClassifications(classifier, train,
- testSource, classIndex,
- attributesToOutput, false, predsText);
+ * @param classifier the classifier to use
+ * @param train the training data
+ * @param testSource the test set
+ * @param classIndex the class index (1-based), if -1 ot does not override the
+ * class index is stored in the data file (by using the last
+ * attribute)
+ * @param attributesToOutput the indices of the attributes to output
+ * @return the generated predictions for the attribute range
+ * @throws Exception if test file cannot be opened
+ */
+ public static void printClassifications(Classifier classifier,
+ Instances train, DataSource testSource, int classIndex,
+ Range attributesToOutput, StringBuffer predsText) throws Exception {
+
+ printClassifications(classifier, train, testSource, classIndex,
+ attributesToOutput, false, predsText);
}
/**
* Prints the header for the predictions output into a supplied StringBuffer
- *
+ *
* @param test structure of the test set to print predictions for
* @param attributesToOutput indices of the attributes to output
* @param printDistribution prints the complete distribution for nominal
- * attributes, not just the predicted value
+ * attributes, not just the predicted value
* @param text the StringBuffer to print to
*/
- protected static void printClassificationsHeader(Instances test,
- Range attributesToOutput,
- boolean printDistribution,
- StringBuffer text) {
+ protected static void printClassificationsHeader(Instances test,
+ Range attributesToOutput, boolean printDistribution, StringBuffer text) {
// print header
- if (test.classAttribute().isNominal())
- if (printDistribution)
+ if (test.classAttribute().isNominal()) {
+ if (printDistribution) {
text.append(" inst# actual predicted error distribution");
- else
+ } else {
text.append(" inst# actual predicted error prediction");
- else
+ }
+ } else {
text.append(" inst# actual predicted error");
+ }
if (attributesToOutput != null) {
attributesToOutput.setUpper(test.numAttributes() - 1);
text.append(" (");
boolean first = true;
for (int i = 0; i < test.numAttributes(); i++) {
- if (i == test.classIndex())
+ if (i == test.classIndex()) {
continue;
+ }
if (attributesToOutput.isInRange(i)) {
- if (!first)
+ if (!first) {
text.append(",");
+ }
text.append(test.attribute(i).name());
first = false;
}
@@ -3094,180 +3199,202 @@ public class Evaluation
/**
* Prints the predictions for the given dataset into a supplied StringBuffer
*
- * @param classifier the classifier to use
- * @param train the training data
- * @param testSource the test set
- * @param classIndex the class index (1-based), if -1 ot does not
- * override the class index is stored in the data
- * file (by using the last attribute)
- * @param attributesToOutput the indices of the attributes to output
- * @param printDistribution prints the complete distribution for nominal
- * classes, not just the predicted value
- * @param text StringBuffer to hold the printed predictions
- * @throws Exception if test file cannot be opened
- */
- public static void printClassifications(Classifier classifier,
- Instances train,
- DataSource testSource,
- int classIndex,
- Range attributesToOutput,
- boolean printDistribution,
- StringBuffer text) throws Exception {
+ * @param classifier the classifier to use
+ * @param train the training data
+ * @param testSource the test set
+ * @param classIndex the class index (1-based), if -1 ot does not override the
+ * class index is stored in the data file (by using the last
+ * attribute)
+ * @param attributesToOutput the indices of the attributes to output
+ * @param printDistribution prints the complete distribution for nominal
+ * classes, not just the predicted value
+ * @param text StringBuffer to hold the printed predictions
+ * @throws Exception if test file cannot be opened
+ */
+ public static void printClassifications(Classifier classifier,
+ Instances train, DataSource testSource, int classIndex,
+ Range attributesToOutput, boolean printDistribution, StringBuffer text)
+ throws Exception {
if (testSource != null) {
Instances test = testSource.getStructure();
if (classIndex != -1) {
- test.setClassIndex(classIndex - 1);
+ test.setClassIndex(classIndex - 1);
} else {
- if (test.classIndex() == -1)
- test.setClassIndex(test.numAttributes() - 1);
+ if (test.classIndex() == -1) {
+ test.setClassIndex(test.numAttributes() - 1);
+ }
}
// print the header
- printClassificationsHeader(test, attributesToOutput, printDistribution, text);
+ printClassificationsHeader(test, attributesToOutput, printDistribution,
+ text);
// print predictions
int i = 0;
testSource.reset();
test = testSource.getStructure(test.classIndex());
while (testSource.hasMoreElements(test)) {
- Instance inst = testSource.nextElement(test);
- text.append(predictionText(classifier, inst, i,
- attributesToOutput, printDistribution));
- i++;
+ Instance inst = testSource.nextElement(test);
+ text.append(predictionText(classifier, inst, i, attributesToOutput,
+ printDistribution));
+ i++;
}
}
- // return text.toString();
+ // return text.toString();
}
/**
* store the prediction made by the classifier as a string
*
- * @param classifier the classifier to use
- * @param inst the instance to generate text from
- * @param instNum the index in the dataset
- * @param attributesToOutput the indices of the attributes to output
- * @param printDistribution prints the complete distribution for nominal
- * classes, not just the predicted value
- * @return the prediction as a String
- * @throws Exception if something goes wrong
- * @see #printClassifications(Classifier, Instances, String, int, Range, boolean)
- */
- protected static String predictionText(Classifier classifier,
- Instance inst,
- int instNum,
- Range attributesToOutput,
- boolean printDistribution)
-
- throws Exception {
+ * @param classifier the classifier to use
+ * @param inst the instance to generate text from
+ * @param instNum the index in the dataset
+ * @param attributesToOutput the indices of the attributes to output
+ * @param printDistribution prints the complete distribution for nominal
+ * classes, not just the predicted value
+ * @return the prediction as a String
+ * @throws Exception if something goes wrong
+ * @see #printClassifications(Classifier, Instances, String, int, Range,
+ * boolean)
+ */
+ protected static String predictionText(Classifier classifier, Instance inst,
+ int instNum, Range attributesToOutput, boolean printDistribution)
+
+ throws Exception {
StringBuffer result = new StringBuffer();
int width = 10;
int prec = 3;
- Instance withMissing = (Instance)inst.copy();
+ Instance withMissing = (Instance) inst.copy();
withMissing.setDataset(inst.dataset());
withMissing.setMissing(withMissing.classIndex());
double predValue = classifier.classifyInstance(withMissing);
// index
- result.append(Utils.padLeft("" + (instNum+1), 6));
+ result.append(Utils.padLeft("" + (instNum + 1), 6));
if (inst.dataset().classAttribute().isNumeric()) {
// actual
- if (inst.classIsMissing())
- result.append(" " + Utils.padLeft("?", width));
- else
- result.append(" " + Utils.doubleToString(inst.classValue(), width, prec));
+ if (inst.classIsMissing()) {
+ result.append(" " + Utils.padLeft("?", width));
+ } else {
+ result.append(" "
+ + Utils.doubleToString(inst.classValue(), width, prec));
+ }
// predicted
- if (Instance.isMissingValue(predValue))
- result.append(" " + Utils.padLeft("?", width));
- else
- result.append(" " + Utils.doubleToString(predValue, width, prec));
+ if (Instance.isMissingValue(predValue)) {
+ result.append(" " + Utils.padLeft("?", width));
+ } else {
+ result.append(" " + Utils.doubleToString(predValue, width, prec));
+ }
// error
- if (Instance.isMissingValue(predValue) || inst.classIsMissing())
- result.append(" " + Utils.padLeft("?", width));
- else
- result.append(" " + Utils.doubleToString(predValue - inst.classValue(), width, prec));
+ if (Instance.isMissingValue(predValue) || inst.classIsMissing()) {
+ result.append(" " + Utils.padLeft("?", width));
+ } else {
+ result.append(" "
+ + Utils.doubleToString(predValue - inst.classValue(), width, prec));
+ }
} else {
// actual
- result.append(" " + Utils.padLeft(((int) inst.classValue()+1) + ":" + inst.toString(inst.classIndex()), width));
+ result.append(" "
+ + Utils.padLeft(
+ ((int) inst.classValue() + 1) + ":"
+ + inst.toString(inst.classIndex()), width));
// predicted
- if (Instance.isMissingValue(predValue))
- result.append(" " + Utils.padLeft("?", width));
- else
- result.append(" " + Utils.padLeft(((int) predValue+1) + ":" + inst.dataset().classAttribute().value((int)predValue), width));
+ if (Instance.isMissingValue(predValue)) {
+ result.append(" " + Utils.padLeft("?", width));
+ } else {
+ result.append(" "
+ + Utils.padLeft(((int) predValue + 1) + ":"
+ + inst.dataset().classAttribute().value((int) predValue), width));
+ }
// error?
- if (!Instance.isMissingValue(predValue) && !inst.classIsMissing() && ((int) predValue+1 != (int) inst.classValue()+1))
- result.append(" " + " + ");
- else
- result.append(" " + " ");
+ if (!Instance.isMissingValue(predValue) && !inst.classIsMissing()
+ && ((int) predValue + 1 != (int) inst.classValue() + 1)) {
+ result.append(" " + " + ");
+ } else {
+ result.append(" " + " ");
+ }
// prediction/distribution
if (printDistribution) {
- if (Instance.isMissingValue(predValue)) {
- result.append(" " + "?");
- }
- else {
- result.append(" ");
- double[] dist = classifier.distributionForInstance(withMissing);
- for (int n = 0; n < dist.length; n++) {
- if (n > 0)
- result.append(",");
- if (n == (int) predValue)
- result.append("*");
+ if (Instance.isMissingValue(predValue)) {
+ result.append(" " + "?");
+ } else {
+ result.append(" ");
+ double[] dist = classifier.distributionForInstance(withMissing);
+ for (int n = 0; n < dist.length; n++) {
+ if (n > 0) {
+ result.append(",");
+ }
+ if (n == (int) predValue) {
+ result.append("*");
+ }
result.append(Utils.doubleToString(dist[n], prec));
- }
- }
- }
- else {
- if (Instance.isMissingValue(predValue))
- result.append(" " + "?");
- else
- result.append(" " + Utils.doubleToString(classifier.distributionForInstance(withMissing) [(int)predValue], prec));
+ }
+ }
+ } else {
+ if (Instance.isMissingValue(predValue)) {
+ result.append(" " + "?");
+ } else {
+ result.append(" "
+ + Utils.doubleToString(
+ classifier.distributionForInstance(withMissing)[(int) predValue],
+ prec));
+ }
}
}
// attributes
- result.append(" " + attributeValuesString(withMissing, attributesToOutput) + "\n");
+ result.append(" " + attributeValuesString(withMissing, attributesToOutput)
+ + "\n");
return result.toString();
}
/**
- * Builds a string listing the attribute values in a specified range of indices,
- * separated by commas and enclosed in brackets.
- *
+ * Builds a string listing the attribute values in a specified range of
+ * indices, separated by commas and enclosed in brackets.
+ *
* @param instance the instance to print the values from
* @param attRange the range of the attributes to list
* @return a string listing values of the attributes in the range
*/
- protected static String attributeValuesString(Instance instance, Range attRange) {
+ protected static String attributeValuesString(Instance instance,
+ Range attRange) {
StringBuffer text = new StringBuffer();
if (attRange != null) {
boolean firstOutput = true;
attRange.setUpper(instance.numAttributes() - 1);
- for (int i=0; i<instance.numAttributes(); i++)
- if (attRange.isInRange(i) && i != instance.classIndex()) {
- if (firstOutput) text.append("(");
- else text.append(",");
- text.append(instance.toString(i));
- firstOutput = false;
- }
- if (!firstOutput) text.append(")");
+ for (int i = 0; i < instance.numAttributes(); i++) {
+ if (attRange.isInRange(i) && i != instance.classIndex()) {
+ if (firstOutput) {
+ text.append("(");
+ } else {
+ text.append(",");
+ }
+ text.append(instance.toString(i));
+ firstOutput = false;
+ }
+ }
+ if (!firstOutput) {
+ text.append(")");
+ }
}
return text.toString();
}
/**
* Make up the help string giving all the command line options
- *
+ *
* @param classifier the classifier to include options for
- * @param globalInfo include the global information string
- * for the classifier (if available).
+ * @param globalInfo include the global information string for the classifier
+ * (if available).
* @return a string detailing the valid command line options
*/
- protected static String makeOptionString(Classifier classifier,
- boolean globalInfo) {
+ protected static String makeOptionString(Classifier classifier,
+ boolean globalInfo) {
StringBuffer optionsText = new StringBuffer("");
@@ -3277,34 +3404,42 @@ public class Evaluation
optionsText.append("\tOutput help information.\n");
optionsText.append("-synopsis or -info\n");
optionsText.append("\tOutput synopsis for classifier (use in conjunction "
- + " with -h)\n");
+ + " with -h)\n");
optionsText.append("-t <name of training file>\n");
optionsText.append("\tSets training file.\n");
optionsText.append("-T <name of test file>\n");
- optionsText.append("\tSets test file. If missing, a cross-validation will be performed\n");
+ optionsText
+ .append("\tSets test file. If missing, a cross-validation will be performed\n");
optionsText.append("\ton the training data.\n");
optionsText.append("-c <class index>\n");
optionsText.append("\tSets index of class attribute (default: last).\n");
optionsText.append("-x <number of folds>\n");
- optionsText.append("\tSets number of folds for cross-validation (default: 10).\n");
+ optionsText
+ .append("\tSets number of folds for cross-validation (default: 10).\n");
optionsText.append("-no-cv\n");
optionsText.append("\tDo not perform any cross validation.\n");
optionsText.append("-split-percentage <percentage>\n");
- optionsText.append("\tSets the percentage for the train/test set split, e.g., 66.\n");
+ optionsText
+ .append("\tSets the percentage for the train/test set split, e.g., 66.\n");
optionsText.append("-preserve-order\n");
optionsText.append("\tPreserves the order in the percentage split.\n");
optionsText.append("-s <random number seed>\n");
- optionsText.append("\tSets random number seed for cross-validation or percentage split\n");
+ optionsText
+ .append("\tSets random number seed for cross-validation or percentage split\n");
optionsText.append("\t(default: 1).\n");
optionsText.append("-m <name of file with cost matrix>\n");
optionsText.append("\tSets file with cost matrix.\n");
optionsText.append("-l <name of input file>\n");
- optionsText.append("\tSets model input file. In case the filename ends with '.xml',\n");
- optionsText.append("\ta PMML file is loaded or, if that fails, options are loaded\n");
+ optionsText
+ .append("\tSets model input file. In case the filename ends with '.xml',\n");
+ optionsText
+ .append("\ta PMML file is loaded or, if that fails, options are loaded\n");
optionsText.append("\tfrom the XML file.\n");
optionsText.append("-d <name of output file>\n");
- optionsText.append("\tSets model output file. In case the filename ends with '.xml',\n");
- optionsText.append("\tonly the options are saved to the XML file, not the model.\n");
+ optionsText
+ .append("\tSets model output file. In case the filename ends with '.xml',\n");
+ optionsText
+ .append("\tonly the options are saved to the XML file, not the model.\n");
optionsText.append("-v\n");
optionsText.append("\tOutputs no statistics for training data.\n");
optionsText.append("-o\n");
@@ -3315,49 +3450,53 @@ public class Evaluation
optionsText.append("-k\n");
optionsText.append("\tOutputs information-theoretic statistics.\n");
optionsText.append("-p <attribute range>\n");
- optionsText.append("\tOnly outputs predictions for test instances (or the train\n"
- + "\tinstances if no test instances provided and -no-cv is used),\n"
- + "\talong with attributes (0 for none).\n");
+ optionsText
+ .append("\tOnly outputs predictions for test instances (or the train\n"
+ + "\tinstances if no test instances provided and -no-cv is used),\n"
+ + "\talong with attributes (0 for none).\n");
optionsText.append("-distribution\n");
- optionsText.append("\tOutputs the distribution instead of only the prediction\n");
- optionsText.append("\tin conjunction with the '-p' option (only nominal classes).\n");
+ optionsText
+ .append("\tOutputs the distribution instead of only the prediction\n");
+ optionsText
+ .append("\tin conjunction with the '-p' option (only nominal classes).\n");
optionsText.append("-r\n");
optionsText.append("\tOnly outputs cumulative margin distribution.\n");
if (classifier instanceof Sourcable) {
optionsText.append("-z <class name>\n");
optionsText.append("\tOnly outputs the source representation"
- + " of the classifier,\n\tgiving it the supplied"
- + " name.\n");
+ + " of the classifier,\n\tgiving it the supplied" + " name.\n");
}
if (classifier instanceof Drawable) {
optionsText.append("-g\n");
optionsText.append("\tOnly outputs the graph representation"
- + " of the classifier.\n");
+ + " of the classifier.\n");
}
optionsText.append("-xml filename | xml-string\n");
- optionsText.append("\tRetrieves the options from the XML-data instead of the "
- + "command line.\n");
+ optionsText
+ .append("\tRetrieves the options from the XML-data instead of the "
+ + "command line.\n");
optionsText.append("-threshold-file <file>\n");
- optionsText.append("\tThe file to save the threshold data to.\n"
- + "\tThe format is determined by the extensions, e.g., '.arff' for ARFF \n"
- + "\tformat or '.csv' for CSV.\n");
+ optionsText
+ .append("\tThe file to save the threshold data to.\n"
+ + "\tThe format is determined by the extensions, e.g., '.arff' for ARFF \n"
+ + "\tformat or '.csv' for CSV.\n");
optionsText.append("-threshold-label <label>\n");
- optionsText.append("\tThe class label to determine the threshold data for\n"
- + "\t(default is the first label)\n");
+ optionsText
+ .append("\tThe class label to determine the threshold data for\n"
+ + "\t(default is the first label)\n");
// Get scheme-specific options
if (classifier instanceof OptionHandler) {
optionsText.append("\nOptions specific to "
- + classifier.getClass().getName()
- + ":\n\n");
- Enumeration enu = ((OptionHandler)classifier).listOptions();
+ + classifier.getClass().getName() + ":\n\n");
+ Enumeration enu = ((OptionHandler) classifier).listOptions();
while (enu.hasMoreElements()) {
- Option option = (Option) enu.nextElement();
- optionsText.append(option.synopsis() + '\n');
- optionsText.append(option.description() + "\n");
+ Option option = (Option) enu.nextElement();
+ optionsText.append(option.synopsis() + '\n');
+ optionsText.append(option.description() + "\n");
}
}
-
+
// Get global information (if available)
if (globalInfo) {
try {
@@ -3369,7 +3508,7 @@ public class Evaluation
}
return optionsText.toString();
}
-
+
/**
* Return the global info (if it exists) for the supplied classifier
*
@@ -3382,43 +3521,43 @@ public class Evaluation
MethodDescriptor[] methods;
methods = bi.getMethodDescriptors();
Object[] args = {};
- String result = "\nSynopsis for " + classifier.getClass().getName()
- + ":\n\n";
-
- for (int i = 0; i < methods.length; i++) {
- String name = methods[i].getDisplayName();
- Method meth = methods[i].getMethod();
+ String result =
+ "\nSynopsis for " + classifier.getClass().getName() + ":\n\n";
+
+ for (MethodDescriptor method : methods) {
+ String name = method.getDisplayName();
+ Method meth = method.getMethod();
if (name.equals("globalInfo")) {
- String globalInfo = (String)(meth.invoke(classifier, args));
+ String globalInfo = (String) (meth.invoke(classifier, args));
result += globalInfo;
break;
}
}
-
+
return result;
}
/**
* Method for generating indices for the confusion matrix.
- *
- * @param num integer to format
- * @param IDChars the characters to use
- * @param IDWidth the width of the entry
- * @return the formatted integer as a string
+ *
+ * @param num integer to format
+ * @param IDChars the characters to use
+ * @param IDWidth the width of the entry
+ * @return the formatted integer as a string
*/
protected String num2ShortID(int num, char[] IDChars, int IDWidth) {
- char ID [] = new char [IDWidth];
+ char ID[] = new char[IDWidth];
int i;
- for(i = IDWidth - 1; i >=0; i--) {
+ for (i = IDWidth - 1; i >= 0; i--) {
ID[i] = IDChars[num % IDChars.length];
num = num / IDChars.length - 1;
if (num < 0) {
- break;
+ break;
}
}
- for(i--; i >= 0; i--) {
+ for (i--; i >= 0; i--) {
ID[i] = ' ';
}
@@ -3426,110 +3565,104 @@ public class Evaluation
}
/**
- * Convert a single prediction into a probability distribution
- * with all zero probabilities except the predicted value which
- * has probability 1.0;
- *
+ * Convert a single prediction into a probability distribution with all zero
+ * probabilities except the predicted value which has probability 1.0;
+ *
* @param predictedClass the index of the predicted class
* @return the probability distribution
*/
- protected double [] makeDistribution(double predictedClass) {
+ protected double[] makeDistribution(double predictedClass) {
- double [] result = new double [m_NumClasses];
+ double[] result = new double[m_NumClasses];
if (Instance.isMissingValue(predictedClass)) {
return result;
}
if (m_ClassIsNominal) {
- result[(int)predictedClass] = 1.0;
+ result[(int) predictedClass] = 1.0;
} else {
result[0] = predictedClass;
}
return result;
- }
+ }
/**
- * Updates all the statistics about a classifiers performance for
- * the current test instance.
- *
- * @param predictedDistribution the probabilities assigned to
- * each class
+ * Updates all the statistics about a classifiers performance for the current
+ * test instance.
+ *
+ * @param predictedDistribution the probabilities assigned to each class
* @param instance the instance to be classified
- * @throws Exception if the class of the instance is not
- * set
+ * @throws Exception if the class of the instance is not set
*/
- protected void updateStatsForClassifier(double [] predictedDistribution,
- Instance instance)
- throws Exception {
+ protected void updateStatsForClassifier(double[] predictedDistribution,
+ Instance instance) throws Exception {
- int actualClass = (int)instance.classValue();
+ int actualClass = (int) instance.classValue();
if (!instance.classIsMissing()) {
updateMargins(predictedDistribution, actualClass, instance.weight());
- // Determine the predicted class (doesn't detect multiple
+ // Determine the predicted class (doesn't detect multiple
// classifications)
int predictedClass = -1;
double bestProb = 0.0;
- for(int i = 0; i < m_NumClasses; i++) {
- if (predictedDistribution[i] > bestProb) {
- predictedClass = i;
- bestProb = predictedDistribution[i];
- }
+ for (int i = 0; i < m_NumClasses; i++) {
+ if (predictedDistribution[i] > bestProb) {
+ predictedClass = i;
+ bestProb = predictedDistribution[i];
+ }
}
m_WithClass += instance.weight();
// Determine misclassification cost
if (m_CostMatrix != null) {
- if (predictedClass < 0) {
- // For missing predictions, we assume the worst possible cost.
- // This is pretty harsh.
- // Perhaps we could take the negative of the cost of a correct
- // prediction (-m_CostMatrix.getElement(actualClass,actualClass)),
- // although often this will be zero
- m_TotalCost += instance.weight()
- * m_CostMatrix.getMaxCost(actualClass, instance);
- } else {
- m_TotalCost += instance.weight()
- * m_CostMatrix.getElement(actualClass, predictedClass,
- instance);
- }
+ if (predictedClass < 0) {
+ // For missing predictions, we assume the worst possible cost.
+ // This is pretty harsh.
+ // Perhaps we could take the negative of the cost of a correct
+ // prediction (-m_CostMatrix.getElement(actualClass,actualClass)),
+ // although often this will be zero
+ m_TotalCost +=
+ instance.weight() * m_CostMatrix.getMaxCost(actualClass, instance);
+ } else {
+ m_TotalCost +=
+ instance.weight()
+ * m_CostMatrix.getElement(actualClass, predictedClass, instance);
+ }
}
// Update counts when no class was predicted
if (predictedClass < 0) {
- m_Unclassified += instance.weight();
- return;
+ m_Unclassified += instance.weight();
+ return;
}
- double predictedProb = Math.max(MIN_SF_PROB,
- predictedDistribution[actualClass]);
- double priorProb = Math.max(MIN_SF_PROB,
- m_ClassPriors[actualClass]
- / m_ClassPriorsSum);
+ double predictedProb =
+ Math.max(MIN_SF_PROB, predictedDistribution[actualClass]);
+ double priorProb =
+ Math.max(MIN_SF_PROB, m_ClassPriors[actualClass] / m_ClassPriorsSum);
if (predictedProb >= priorProb) {
- m_SumKBInfo += (Utils.log2(predictedProb) -
- Utils.log2(priorProb))
- * instance.weight();
+ m_SumKBInfo +=
+ (Utils.log2(predictedProb) - Utils.log2(priorProb))
+ * instance.weight();
} else {
- m_SumKBInfo -= (Utils.log2(1.0-predictedProb) -
- Utils.log2(1.0-priorProb))
- * instance.weight();
+ m_SumKBInfo -=
+ (Utils.log2(1.0 - predictedProb) - Utils.log2(1.0 - priorProb))
+ * instance.weight();
}
m_SumSchemeEntropy -= Utils.log2(predictedProb) * instance.weight();
m_SumPriorEntropy -= Utils.log2(priorProb) * instance.weight();
- updateNumericScores(predictedDistribution,
- makeDistribution(instance.classValue()),
- instance.weight());
+ updateNumericScores(predictedDistribution,
+ makeDistribution(instance.classValue()), instance.weight());
// Update other stats
m_ConfusionMatrix[actualClass][predictedClass] += instance.weight();
if (predictedClass != actualClass) {
- m_Incorrect += instance.weight();
+ m_Incorrect += instance.weight();
} else {
- m_Correct += instance.weight();
+ m_Correct += instance.weight();
}
} else {
m_MissingClass += instance.weight();
@@ -3537,99 +3670,97 @@ public class Evaluation
}
/**
- * Updates all the statistics about a predictors performance for
- * the current test instance.
- *
+ * Updates all the statistics about a predictors performance for the current
+ * test instance.
+ *
* @param predictedValue the numeric value the classifier predicts
* @param instance the instance to be classified
- * @throws Exception if the class of the instance is not
- * set
+ * @throws Exception if the class of the instance is not set
*/
protected void updateStatsForPredictor(double predictedValue,
- Instance instance)
- throws Exception {
+ Instance instance) throws Exception {
- if (!instance.classIsMissing()){
+ if (!instance.classIsMissing()) {
// Update stats
m_WithClass += instance.weight();
if (Instance.isMissingValue(predictedValue)) {
- m_Unclassified += instance.weight();
- return;
+ m_Unclassified += instance.weight();
+ return;
}
m_SumClass += instance.weight() * instance.classValue();
- m_SumSqrClass += instance.weight() * instance.classValue()
- * instance.classValue();
- m_SumClassPredicted += instance.weight()
- * instance.classValue() * predictedValue;
+ m_SumSqrClass +=
+ instance.weight() * instance.classValue() * instance.classValue();
+ m_SumClassPredicted +=
+ instance.weight() * instance.classValue() * predictedValue;
m_SumPredicted += instance.weight() * predictedValue;
m_SumSqrPredicted += instance.weight() * predictedValue * predictedValue;
if (m_ErrorEstimator == null) {
- setNumericPriorsFromBuffer();
+ setNumericPriorsFromBuffer();
}
- double predictedProb = Math.max(m_ErrorEstimator.getProbability(
- predictedValue
- - instance.classValue()),
- MIN_SF_PROB);
- double priorProb = Math.max(m_PriorErrorEstimator.getProbability(
- instance.classValue()),
- MIN_SF_PROB);
+ double predictedProb =
+ Math.max(
+ m_ErrorEstimator.getProbability(predictedValue
+ - instance.classValue()), MIN_SF_PROB);
+ double priorProb =
+ Math.max(m_PriorErrorEstimator.getProbability(instance.classValue()),
+ MIN_SF_PROB);
m_SumSchemeEntropy -= Utils.log2(predictedProb) * instance.weight();
m_SumPriorEntropy -= Utils.log2(priorProb) * instance.weight();
- m_ErrorEstimator.addValue(predictedValue - instance.classValue(),
- instance.weight());
+ m_ErrorEstimator.addValue(predictedValue - instance.classValue(),
+ instance.weight());
updateNumericScores(makeDistribution(predictedValue),
- makeDistribution(instance.classValue()),
- instance.weight());
+ makeDistribution(instance.classValue()), instance.weight());
- } else
+ } else {
m_MissingClass += instance.weight();
+ }
}
/**
* Update the cumulative record of classification margins
- *
- * @param predictedDistribution the probability distribution predicted for
- * the current instance
+ *
+ * @param predictedDistribution the probability distribution predicted for the
+ * current instance
* @param actualClass the index of the actual instance class
* @param weight the weight assigned to the instance
*/
- protected void updateMargins(double [] predictedDistribution,
- int actualClass, double weight) {
+ protected void updateMargins(double[] predictedDistribution, int actualClass,
+ double weight) {
double probActual = predictedDistribution[actualClass];
double probNext = 0;
- for(int i = 0; i < m_NumClasses; i++)
- if ((i != actualClass) &&
- (predictedDistribution[i] > probNext))
- probNext = predictedDistribution[i];
+ for (int i = 0; i < m_NumClasses; i++) {
+ if ((i != actualClass) && (predictedDistribution[i] > probNext)) {
+ probNext = predictedDistribution[i];
+ }
+ }
double margin = probActual - probNext;
- int bin = (int)((margin + 1.0) / 2.0 * k_MarginResolution);
+ int bin = (int) ((margin + 1.0) / 2.0 * k_MarginResolution);
m_MarginCounts[bin] += weight;
}
/**
- * Update the numeric accuracy measures. For numeric classes, the
- * accuracy is between the actual and predicted class values. For
- * nominal classes, the accuracy is between the actual and
- * predicted class probabilities.
- *
+ * Update the numeric accuracy measures. For numeric classes, the accuracy is
+ * between the actual and predicted class values. For nominal classes, the
+ * accuracy is between the actual and predicted class probabilities.
+ *
* @param predicted the predicted values
* @param actual the actual value
* @param weight the weight associated with this prediction
*/
- protected void updateNumericScores(double [] predicted,
- double [] actual, double weight) {
+ protected void updateNumericScores(double[] predicted, double[] actual,
+ double weight) {
double diff;
double sumErr = 0, sumAbsErr = 0, sumSqrErr = 0;
double sumPriorAbsErr = 0, sumPriorSqrErr = 0;
- for(int i = 0; i < m_NumClasses; i++) {
+ for (int i = 0; i < m_NumClasses; i++) {
diff = predicted[i] - actual[i];
sumErr += diff;
sumAbsErr += Math.abs(diff);
@@ -3646,27 +3777,26 @@ public class Evaluation
}
/**
- * Adds a numeric (non-missing) training class value and weight to
- * the buffer of stored values.
- *
+ * Adds a numeric (non-missing) training class value and weight to the buffer
+ * of stored values.
+ *
* @param classValue the class value
* @param weight the instance weight
*/
protected void addNumericTrainClass(double classValue, double weight) {
if (m_TrainClassVals == null) {
- m_TrainClassVals = new double [100];
- m_TrainClassWeights = new double [100];
+ m_TrainClassVals = new double[100];
+ m_TrainClassWeights = new double[100];
}
if (m_NumTrainClassVals == m_TrainClassVals.length) {
- double [] temp = new double [m_TrainClassVals.length * 2];
- System.arraycopy(m_TrainClassVals, 0,
- temp, 0, m_TrainClassVals.length);
+ double[] temp = new double[m_TrainClassVals.length * 2];
+ System.arraycopy(m_TrainClassVals, 0, temp, 0, m_TrainClassVals.length);
m_TrainClassVals = temp;
- temp = new double [m_TrainClassWeights.length * 2];
- System.arraycopy(m_TrainClassWeights, 0,
- temp, 0, m_TrainClassWeights.length);
+ temp = new double[m_TrainClassWeights.length * 2];
+ System.arraycopy(m_TrainClassWeights, 0, temp, 0,
+ m_TrainClassWeights.length);
m_TrainClassWeights = temp;
}
m_TrainClassVals[m_NumTrainClassVals] = classValue;
@@ -3675,29 +3805,29 @@ public class Evaluation
}
/**
- * Sets up the priors for numeric class attributes from the
- * training class values that have been seen so far.
+ * Sets up the priors for numeric class attributes from the training class
+ * values that have been seen so far.
*/
protected void setNumericPriorsFromBuffer() {
double numPrecision = 0.01; // Default value
if (m_NumTrainClassVals > 1) {
- double [] temp = new double [m_NumTrainClassVals];
+ double[] temp = new double[m_NumTrainClassVals];
System.arraycopy(m_TrainClassVals, 0, temp, 0, m_NumTrainClassVals);
- int [] index = Utils.sort(temp);
+ int[] index = Utils.sort(temp);
double lastVal = temp[index[0]];
double deltaSum = 0;
int distinct = 0;
for (int i = 1; i < temp.length; i++) {
- double current = temp[index[i]];
- if (current != lastVal) {
- deltaSum += current - lastVal;
- lastVal = current;
- distinct++;
- }
+ double current = temp[index[i]];
+ if (current != lastVal) {
+ deltaSum += current - lastVal;
+ lastVal = current;
+ distinct++;
+ }
}
if (distinct > 0) {
- numPrecision = deltaSum / distinct;
+ numPrecision = deltaSum / distinct;
}
}
m_PriorErrorEstimator = new KernelEstimator(numPrecision);
@@ -3707,16 +3837,17 @@ public class Evaluation
m_ClassPriors[0] += m_TrainClassVals[i] * m_TrainClassWeights[i];
m_ClassPriorsSum += m_TrainClassWeights[i];
m_PriorErrorEstimator.addValue(m_TrainClassVals[i],
- m_TrainClassWeights[i]);
+ m_TrainClassWeights[i]);
}
}
-
+
/**
* Returns the revision string.
*
- * @return the revision
+ * @return the revision
*/
+ @Override
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9196 $");
+ return RevisionUtils.extract("$Revision: 10619 $");
}
}
diff --git a/src/main/java/weka/classifiers/bayes/net/search/global/GlobalScoreSearchAlgorithm.java b/src/main/java/weka/classifiers/bayes/net/search/global/GlobalScoreSearchAlgorithm.java
index 3b5c03e..91f7f23 100644
--- a/src/main/java/weka/classifiers/bayes/net/search/global/GlobalScoreSearchAlgorithm.java
+++ b/src/main/java/weka/classifiers/bayes/net/search/global/GlobalScoreSearchAlgorithm.java
@@ -293,8 +293,8 @@ public class GlobalScoreSearchAlgorithm
Instance instance = instances.instance(iInstance);
instance.setWeight(-instance.weight());
fAccuracy += accuracyIncrease(instance);
+ fWeight += instance.weight();
instance.setWeight(-instance.weight());
- fWeight += instance.weight();
}
// restore influence of fold iFold from the probability distribution
diff --git a/src/main/java/weka/classifiers/functions/LibSVM.java b/src/main/java/weka/classifiers/functions/LibSVM.java
index 81f6515..41f8cad 100644
--- a/src/main/java/weka/classifiers/functions/LibSVM.java
+++ b/src/main/java/weka/classifiers/functions/LibSVM.java
@@ -23,9 +23,17 @@
package weka.classifiers.functions;
-import weka.classifiers.Classifier;
+import java.lang.reflect.Array;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.Enumeration;
+import java.util.Random;
+import java.util.StringTokenizer;
+import java.util.Vector;
+
import weka.classifiers.RandomizableClassifier;
import weka.core.Capabilities;
+import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
@@ -33,22 +41,14 @@ import weka.core.RevisionUtils;
import weka.core.SelectedTag;
import weka.core.Tag;
import weka.core.TechnicalInformation;
+import weka.core.TechnicalInformation.Type;
import weka.core.TechnicalInformationHandler;
import weka.core.Utils;
-import weka.core.Capabilities.Capability;
-import weka.core.TechnicalInformation.Type;
import weka.filters.Filter;
+import weka.filters.unsupervised.attribute.NominalToBinary;
import weka.filters.unsupervised.attribute.Normalize;
import weka.filters.unsupervised.attribute.ReplaceMissingValues;
-import java.lang.reflect.Array;
-import java.lang.reflect.Field;
-import java.lang.reflect.Method;
-import java.util.Enumeration;
-import java.util.Random;
-import java.util.StringTokenizer;
-import java.util.Vector;
-
/*
* Modifications by FracPete:
* - complete overhaul to make it useable in Weka
@@ -57,20 +57,28 @@ import java.util.Vector;
* - uses more efficient code to transfer the data into the libsvm sparse format
*/
-/**
- <!-- globalinfo-start -->
- * A wrapper class for the libsvm tools (the libsvm classes, typically the jar file, need to be in the classpath to use this classifier).<br/>
+/**
+ <!-- globalinfo-start -->
+ * A wrapper class for the libsvm tools (the libsvm
+ * classes, typically the jar file, need to be in the classpath to use this
+ * classifier).<br/>
* LibSVM runs faster than SMO since it uses LibSVM to build the SVM classifier.<br/>
- * LibSVM allows users to experiment with One-class SVM, Regressing SVM, and nu-SVM supported by LibSVM tool. LibSVM reports many useful statistics about LibSVM classifier (e.g., confusion matrix,precision, recall, ROC score, etc.).<br/>
+ * LibSVM allows users to experiment with One-class SVM, Regressing SVM, and
+ * nu-SVM supported by LibSVM tool. LibSVM reports many useful statistics about
+ * LibSVM classifier (e.g., confusion matrix,precision, recall, ROC score,
+ * etc.).<br/>
* <br/>
- * Yasser EL-Manzalawy (2005). WLSVM. URL http://www.cs.iastate.edu/~yasser/wlsvm/.<br/>
+ * Yasser EL-Manzalawy (2005). WLSVM. URL
+ * http://www.cs.iastate.edu/~yasser/wlsvm/.<br/>
* <br/>
- * Chih-Chung Chang, Chih-Jen Lin (2001). LIBSVM - A Library for Support Vector Machines. URL http://www.csie.ntu.edu.tw/~cjlin/libsvm/.
+ * Chih-Chung Chang, Chih-Jen Lin (2001). LIBSVM - A Library for Support Vector
+ * Machines. URL http://www.csie.ntu.edu.tw/~cjlin/libsvm/.
* <p/>
<!-- globalinfo-end -->
- *
- <!-- technical-bibtex-start -->
+ *
+ <!-- technical-bibtex-start -->
* BibTeX:
+ *
* <pre>
* @misc{EL-Manzalawy2005,
* author = {Yasser EL-Manzalawy},
@@ -90,123 +98,160 @@ import java.util.Vector;
* </pre>
* <p/>
<!-- technical-bibtex-end -->
- *
- <!-- options-start -->
- * Valid options are: <p/>
*
- * <pre> -S <int>
+ <!-- options-start -->
+ * Valid options are:
+ * <p/>
+ *
+ * <pre>
+ * -S <int>
* Set type of SVM (default: 0)
* 0 = C-SVC
* 1 = nu-SVC
* 2 = one-class SVM
* 3 = epsilon-SVR
- * 4 = nu-SVR</pre>
+ * 4 = nu-SVR
+ * </pre>
*
- * <pre> -K <int>
+ * <pre>
+ * -K <int>
* Set type of kernel function (default: 2)
* 0 = linear: u'*v
* 1 = polynomial: (gamma*u'*v + coef0)^degree
* 2 = radial basis function: exp(-gamma*|u-v|^2)
- * 3 = sigmoid: tanh(gamma*u'*v + coef0)</pre>
+ * 3 = sigmoid: tanh(gamma*u'*v + coef0)
+ * </pre>
*
- * <pre> -D <int>
- * Set degree in kernel function (default: 3)</pre>
+ * <pre>
+ * -D <int>
+ * Set degree in kernel function (default: 3)
+ * </pre>
*
- * <pre> -G <double>
- * Set gamma in kernel function (default: 1/k)</pre>
+ * <pre>
+ * -G <double>
+ * Set gamma in kernel function (default: 1/k)
+ * </pre>
*
- * <pre> -R <double>
- * Set coef0 in kernel function (default: 0)</pre>
+ * <pre>
+ * -R <double>
+ * Set coef0 in kernel function (default: 0)
+ * </pre>
*
- * <pre> -C <double>
+ * <pre>
+ * -C <double>
* Set the parameter C of C-SVC, epsilon-SVR, and nu-SVR
- * (default: 1)</pre>
+ * (default: 1)
+ * </pre>
*
- * <pre> -N <double>
+ * <pre>
+ * -N <double>
* Set the parameter nu of nu-SVC, one-class SVM, and nu-SVR
- * (default: 0.5)</pre>
+ * (default: 0.5)
+ * </pre>
*
- * <pre> -Z
- * Turns on normalization of input data (default: off)</pre>
+ * <pre>
+ * -Z
+ * Turns on normalization of input data (default: off)
+ * </pre>
*
- * <pre> -J
+ * <pre>
+ * -J
* Turn off nominal to binary conversion.
- * WARNING: use only if your data is all numeric!</pre>
+ * WARNING: use only if your data is all numeric!
+ * </pre>
*
- * <pre> -V
+ * <pre>
+ * -V
* Turn off missing value replacement.
- * WARNING: use only if your data has no missing values.</pre>
+ * WARNING: use only if your data has no missing values.
+ * </pre>
*
- * <pre> -P <double>
- * Set the epsilon in loss function of epsilon-SVR (default: 0.1)</pre>
+ * <pre>
+ * -P <double>
+ * Set the epsilon in loss function of epsilon-SVR (default: 0.1)
+ * </pre>
*
- * <pre> -M <double>
- * Set cache memory size in MB (default: 40)</pre>
+ * <pre>
+ * -M <double>
+ * Set cache memory size in MB (default: 40)
+ * </pre>
*
- * <pre> -E <double>
- * Set tolerance of termination criterion (default: 0.001)</pre>
+ * <pre>
+ * -E <double>
+ * Set tolerance of termination criterion (default: 0.001)
+ * </pre>
*
- * <pre> -H
- * Turns the shrinking heuristics off (default: on)</pre>
+ * <pre>
+ * -H
+ * Turns the shrinking heuristics off (default: on)
+ * </pre>
*
- * <pre> -W <double>
+ * <pre>
+ * -W <double>
* Set the parameters C of class i to weight[i]*C, for C-SVC
* E.g., for a 3-class problem, you could use "1 1 1" for equally
* weighted classes.
- * (default: 1 for all classes)</pre>
+ * (default: 1 for all classes)
+ * </pre>
*
- * <pre> -B
- * Generate probability estimates for classification</pre>
+ * <pre>
+ * -B
+ * Generate probability estimates for classification
+ * </pre>
*
- * <pre> -seed <num>
+ * <pre>
+ * -seed <num>
* Random seed
- * (default = 1)</pre>
+ * (default = 1)
+ * </pre>
*
<!-- options-end -->
- *
- * @author Yasser EL-Manzalawy
- * @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 8940 $
- * @see weka.core.converters.LibSVMLoader
- * @see weka.core.converters.LibSVMSaver
+ *
+ * @author Yasser EL-Manzalawy
+ * @author FracPete (fracpete at waikato dot ac dot nz)
+ * @version $Revision: 10660 $
+ * @see weka.core.converters.LibSVMLoader
+ * @see weka.core.converters.LibSVMSaver
*/
-public class LibSVM
- extends RandomizableClassifier
- implements TechnicalInformationHandler {
-
+public class LibSVM extends RandomizableClassifier implements
+ TechnicalInformationHandler {
+
/** the svm classname */
protected final static String CLASS_SVM = "libsvm.svm";
-
+
/** the svm_model classname */
protected final static String CLASS_SVMMODEL = "libsvm.svm_model";
-
+
/** the svm_problem classname */
protected final static String CLASS_SVMPROBLEM = "libsvm.svm_problem";
-
+
/** the svm_parameter classname */
protected final static String CLASS_SVMPARAMETER = "libsvm.svm_parameter";
-
+
/** the svm_node classname */
protected final static String CLASS_SVMNODE = "libsvm.svm_node";
-
+
/** serial UID */
protected static final long serialVersionUID = 14172;
-
+
/** LibSVM Model */
protected Object m_Model;
-
+
/** for normalizing the data */
protected Filter m_Filter = null;
-
+
+ /** for converting mult-valued nominal attributes to binary */
+ protected Filter m_NominalToBinary;
+
/** The filter used to get rid of missing values. */
protected ReplaceMissingValues m_ReplaceMissingValues;
-
+
/** normalize input data */
protected boolean m_Normalize = false;
-
+
/** If true, the replace missing values filter is not applied */
private boolean m_noReplaceMissingValues;
-
+
/** SVM type C-SVC (classification) */
public static final int SVMTYPE_C_SVC = 0;
/** SVM type nu-SVC (classification) */
@@ -223,12 +268,11 @@ public class LibSVM
new Tag(SVMTYPE_NU_SVC, "nu-SVC (classification)"),
new Tag(SVMTYPE_ONE_CLASS_SVM, "one-class SVM (classification)"),
new Tag(SVMTYPE_EPSILON_SVR, "epsilon-SVR (regression)"),
- new Tag(SVMTYPE_NU_SVR, "nu-SVR (regression)")
- };
-
+ new Tag(SVMTYPE_NU_SVR, "nu-SVR (regression)") };
+
/** the SVM type */
protected int m_SVMType = SVMTYPE_C_SVC;
-
+
/** kernel type linear: u'*v */
public static final int KERNELTYPE_LINEAR = 0;
/** kernel type polynomial: (gamma*u'*v + coef0)^degree */
@@ -242,1048 +286,1071 @@ public class LibSVM
new Tag(KERNELTYPE_LINEAR, "linear: u'*v"),
new Tag(KERNELTYPE_POLYNOMIAL, "polynomial: (gamma*u'*v + coef0)^degree"),
new Tag(KERNELTYPE_RBF, "radial basis function: exp(-gamma*|u-v|^2)"),
- new Tag(KERNELTYPE_SIGMOID, "sigmoid: tanh(gamma*u'*v + coef0)")
- };
-
+ new Tag(KERNELTYPE_SIGMOID, "sigmoid: tanh(gamma*u'*v + coef0)") };
+
/** the kernel type */
protected int m_KernelType = KERNELTYPE_RBF;
-
- /** for poly - in older versions of libsvm declared as a double.
- * At least since 2.82 it is an int. */
+
+ /**
+ * for poly - in older versions of libsvm declared as a double. At least since
+ * 2.82 it is an int.
+ */
protected int m_Degree = 3;
-
+
/** for poly/rbf/sigmoid */
protected double m_Gamma = 0;
-
+
/** for poly/rbf/sigmoid (the actual gamma) */
protected double m_GammaActual = 0;
-
+
/** for poly/sigmoid */
protected double m_Coef0 = 0;
-
+
/** in MB */
protected double m_CacheSize = 40;
-
+
/** stopping criteria */
protected double m_eps = 1e-3;
-
+
/** cost, for C_SVC, EPSILON_SVR and NU_SVR */
protected double m_Cost = 1;
-
+
/** for C_SVC */
protected int[] m_WeightLabel = new int[0];
-
+
/** for C_SVC */
protected double[] m_Weight = new double[0];
-
+
/** for NU_SVC, ONE_CLASS, and NU_SVR */
protected double m_nu = 0.5;
-
+
/** loss, for EPSILON_SVR */
protected double m_Loss = 0.1;
-
+
/** use the shrinking heuristics */
- protected boolean m_Shrinking = true;
-
- /** whether to generate probability estimates instead of +1/-1 in case of
- * classification problems */
+ protected boolean m_Shrinking = true;
+
+ /**
+ * whether to generate probability estimates instead of +1/-1 in case of
+ * classification problems
+ */
protected boolean m_ProbabilityEstimates = false;
-
+
/** whether the libsvm classes are in the Classpath */
protected static boolean m_Present = false;
static {
try {
Class.forName(CLASS_SVM);
m_Present = true;
- }
- catch (Exception e) {
+ } catch (Exception e) {
m_Present = false;
}
}
-
+
/**
* Returns a string describing classifier
*
- * @return a description suitable for displaying in the
- * explorer/experimenter gui
+ * @return a description suitable for displaying in the explorer/experimenter
+ * gui
*/
public String globalInfo() {
- return
- "A wrapper class for the libsvm tools (the libsvm classes, typically "
- + "the jar file, need to be in the classpath to use this classifier).\n"
- + "LibSVM runs faster than SMO since it uses LibSVM to build the SVM "
- + "classifier.\n"
- + "LibSVM allows users to experiment with One-class SVM, Regressing SVM, "
- + "and nu-SVM supported by LibSVM tool. LibSVM reports many useful "
- + "statistics about LibSVM classifier (e.g., confusion matrix,"
- + "precision, recall, ROC score, etc.).\n"
- + "\n"
- + getTechnicalInformation().toString();
+ return "A wrapper class for the libsvm tools (the libsvm classes, typically "
+ + "the jar file, need to be in the classpath to use this classifier).\n"
+ + "LibSVM runs faster than SMO since it uses LibSVM to build the SVM "
+ + "classifier.\n"
+ + "LibSVM allows users to experiment with One-class SVM, Regressing SVM, "
+ + "and nu-SVM supported by LibSVM tool. LibSVM reports many useful "
+ + "statistics about LibSVM classifier (e.g., confusion matrix,"
+ + "precision, recall, ROC score, etc.).\n"
+ + "\n"
+ + getTechnicalInformation().toString();
}
/**
- * Returns an instance of a TechnicalInformation object, containing
- * detailed information about the technical background of this class,
- * e.g., paper reference or book this class is based on.
+ * Returns an instance of a TechnicalInformation object, containing detailed
+ * information about the technical background of this class, e.g., paper
+ * reference or book this class is based on.
*
* @return the technical information about this class
*/
+ @Override
public TechnicalInformation getTechnicalInformation() {
- TechnicalInformation result;
- TechnicalInformation additional;
-
+ TechnicalInformation result;
+ TechnicalInformation additional;
+
result = new TechnicalInformation(Type.MISC);
result.setValue(TechnicalInformation.Field.AUTHOR, "Yasser EL-Manzalawy");
result.setValue(TechnicalInformation.Field.YEAR, "2005");
result.setValue(TechnicalInformation.Field.TITLE, "WLSVM");
- result.setValue(TechnicalInformation.Field.NOTE, "LibSVM was originally developed as 'WLSVM'");
- result.setValue(TechnicalInformation.Field.URL, "http://www.cs.iastate.edu/~yasser/wlsvm/");
- result.setValue(TechnicalInformation.Field.NOTE, "You don't need to include the WLSVM package in the CLASSPATH");
-
+ result.setValue(TechnicalInformation.Field.NOTE,
+ "LibSVM was originally developed as 'WLSVM'");
+ result.setValue(TechnicalInformation.Field.URL,
+ "http://www.cs.iastate.edu/~yasser/wlsvm/");
+ result.setValue(TechnicalInformation.Field.NOTE,
+ "You don't need to include the WLSVM package in the CLASSPATH");
+
additional = result.add(Type.MISC);
- additional.setValue(TechnicalInformation.Field.AUTHOR, "Chih-Chung Chang and Chih-Jen Lin");
- additional.setValue(TechnicalInformation.Field.TITLE, "LIBSVM - A Library for Support Vector Machines");
+ additional.setValue(TechnicalInformation.Field.AUTHOR,
+ "Chih-Chung Chang and Chih-Jen Lin");
+ additional.setValue(TechnicalInformation.Field.TITLE,
+ "LIBSVM - A Library for Support Vector Machines");
additional.setValue(TechnicalInformation.Field.YEAR, "2001");
- additional.setValue(TechnicalInformation.Field.URL, "http://www.csie.ntu.edu.tw/~cjlin/libsvm/");
- additional.setValue(TechnicalInformation.Field.NOTE, "The Weka classifier works with version 2.82 of LIBSVM");
-
+ additional.setValue(TechnicalInformation.Field.URL,
+ "http://www.csie.ntu.edu.tw/~cjlin/libsvm/");
+ additional.setValue(TechnicalInformation.Field.NOTE,
+ "The Weka classifier works with version 2.82 of LIBSVM");
+
return result;
}
-
+
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
+ @Override
public Enumeration listOptions() {
- Vector result;
-
+ Vector result;
+
result = new Vector();
-
- result.addElement(
- new Option(
- "\tSet type of SVM (default: 0)\n"
- + "\t\t 0 = C-SVC\n"
- + "\t\t 1 = nu-SVC\n"
- + "\t\t 2 = one-class SVM\n"
- + "\t\t 3 = epsilon-SVR\n"
- + "\t\t 4 = nu-SVR",
- "S", 1, "-S <int>"));
-
- result.addElement(
- new Option(
- "\tSet type of kernel function (default: 2)\n"
- + "\t\t 0 = linear: u'*v\n"
- + "\t\t 1 = polynomial: (gamma*u'*v + coef0)^degree\n"
- + "\t\t 2 = radial basis function: exp(-gamma*|u-v|^2)\n"
- + "\t\t 3 = sigmoid: tanh(gamma*u'*v + coef0)",
- "K", 1, "-K <int>"));
-
- result.addElement(
- new Option(
- "\tSet degree in kernel function (default: 3)",
- "D", 1, "-D <int>"));
-
- result.addElement(
- new Option(
- "\tSet gamma in kernel function (default: 1/k)",
- "G", 1, "-G <double>"));
-
- result.addElement(
- new Option(
- "\tSet coef0 in kernel function (default: 0)",
- "R", 1, "-R <double>"));
-
- result.addElement(
- new Option(
- "\tSet the parameter C of C-SVC, epsilon-SVR, and nu-SVR\n"
- + "\t (default: 1)",
- "C", 1, "-C <double>"));
-
- result.addElement(
- new Option(
- "\tSet the parameter nu of nu-SVC, one-class SVM, and nu-SVR\n"
- + "\t (default: 0.5)",
- "N", 1, "-N <double>"));
-
- result.addElement(
- new Option(
- "\tTurns on normalization of input data (default: off)",
- "Z", 0, "-Z"));
-
- result.addElement(
- new Option("\tTurn off nominal to binary conversion."
- + "\n\tWARNING: use only if your data is all numeric!",
- "J", 0, "-J"));
-
- result.addElement(
- new Option("\tTurn off missing value replacement."
- + "\n\tWARNING: use only if your data has no missing "
- + "values.", "V", 0, "-V"));
-
- result.addElement(
- new Option(
- "\tSet the epsilon in loss function of epsilon-SVR (default: 0.1)",
- "P", 1, "-P <double>"));
-
- result.addElement(
- new Option(
- "\tSet cache memory size in MB (default: 40)",
- "M", 1, "-M <double>"));
-
- result.addElement(
- new Option(
- "\tSet tolerance of termination criterion (default: 0.001)",
- "E", 1, "-E <double>"));
-
- result.addElement(
- new Option(
- "\tTurns the shrinking heuristics off (default: on)",
- "H", 0, "-H"));
-
- result.addElement(
- new Option(
- "\tSet the parameters C of class i to weight[i]*C, for C-SVC\n"
- + "\tE.g., for a 3-class problem, you could use \"1 1 1\" for equally\n"
- + "\tweighted classes.\n"
- + "\t(default: 1 for all classes)",
- "W", 1, "-W <double>"));
-
- result.addElement(
- new Option(
- "\tGenerate probability estimates for classification",
- "B", 0, "-B"));
-
- result.addElement(
- new Option("\tRandom seed\n\t(default = 1)", "seed", 1, "-seed <num>"));
-
+
+ result.addElement(new Option("\tSet type of SVM (default: 0)\n"
+ + "\t\t 0 = C-SVC\n" + "\t\t 1 = nu-SVC\n" + "\t\t 2 = one-class SVM\n"
+ + "\t\t 3 = epsilon-SVR\n" + "\t\t 4 = nu-SVR", "S", 1, "-S <int>"));
+
+ result.addElement(new Option("\tSet type of kernel function (default: 2)\n"
+ + "\t\t 0 = linear: u'*v\n"
+ + "\t\t 1 = polynomial: (gamma*u'*v + coef0)^degree\n"
+ + "\t\t 2 = radial basis function: exp(-gamma*|u-v|^2)\n"
+ + "\t\t 3 = sigmoid: tanh(gamma*u'*v + coef0)", "K", 1, "-K <int>"));
+
+ result.addElement(new Option(
+ "\tSet degree in kernel function (default: 3)", "D", 1, "-D <int>"));
+
+ result.addElement(new Option(
+ "\tSet gamma in kernel function (default: 1/k)", "G", 1, "-G <double>"));
+
+ result.addElement(new Option("\tSet coef0 in kernel function (default: 0)",
+ "R", 1, "-R <double>"));
+
+ result.addElement(new Option(
+ "\tSet the parameter C of C-SVC, epsilon-SVR, and nu-SVR\n"
+ + "\t (default: 1)", "C", 1, "-C <double>"));
+
+ result.addElement(new Option(
+ "\tSet the parameter nu of nu-SVC, one-class SVM, and nu-SVR\n"
+ + "\t (default: 0.5)", "N", 1, "-N <double>"));
+
+ result.addElement(new Option(
+ "\tTurns on normalization of input data (default: off)", "Z", 0, "-Z"));
+
+ result.addElement(new Option("\tTurn off nominal to binary conversion."
+ + "\n\tWARNING: use only if your data is all numeric!", "J", 0, "-J"));
+
+ result.addElement(new Option("\tTurn off missing value replacement."
+ + "\n\tWARNING: use only if your data has no missing " + "values.", "V",
+ 0, "-V"));
+
+ result.addElement(new Option(
+ "\tSet the epsilon in loss function of epsilon-SVR (default: 0.1)", "P",
+ 1, "-P <double>"));
+
+ result.addElement(new Option("\tSet cache memory size in MB (default: 40)",
+ "M", 1, "-M <double>"));
+
+ result.addElement(new Option(
+ "\tSet tolerance of termination criterion (default: 0.001)", "E", 1,
+ "-E <double>"));
+
+ result.addElement(new Option(
+ "\tTurns the shrinking heuristics off (default: on)", "H", 0, "-H"));
+
+ result
+ .addElement(new Option(
+ "\tSet the parameters C of class i to weight[i]*C, for C-SVC\n"
+ + "\tE.g., for a 3-class problem, you could use \"1 1 1\" for equally\n"
+ + "\tweighted classes.\n" + "\t(default: 1 for all classes)", "W", 1,
+ "-W <double>"));
+
+ result.addElement(new Option(
+ "\tGenerate probability estimates for classification", "B", 0, "-B"));
+
+ result.addElement(new Option("\tRandom seed\n\t(default = 1)", "seed", 1,
+ "-seed <num>"));
+
return result.elements();
}
-
+
/**
- * Sets the classifier options <p/>
+ * Sets the classifier options
+ * <p/>
*
- <!-- options-start -->
- * Valid options are: <p/>
+ <!-- options-start -->
+ * Valid options are:
+ * <p/>
*
- * <pre> -S <int>
+ * <pre>
+ * -S <int>
* Set type of SVM (default: 0)
* 0 = C-SVC
* 1 = nu-SVC
* 2 = one-class SVM
* 3 = epsilon-SVR
- * 4 = nu-SVR</pre>
+ * 4 = nu-SVR
+ * </pre>
*
- * <pre> -K <int>
+ * <pre>
+ * -K <int>
* Set type of kernel function (default: 2)
* 0 = linear: u'*v
* 1 = polynomial: (gamma*u'*v + coef0)^degree
* 2 = radial basis function: exp(-gamma*|u-v|^2)
- * 3 = sigmoid: tanh(gamma*u'*v + coef0)</pre>
- *
- * <pre> -D <int>
- * Set degree in kernel function (default: 3)</pre>
- *
- * <pre> -G <double>
- * Set gamma in kernel function (default: 1/k)</pre>
- *
- * <pre> -R <double>
- * Set coef0 in kernel function (default: 0)</pre>
- *
- * <pre> -C <double>
+ * 3 = sigmoid: tanh(gamma*u'*v + coef0)
+ * </pre>
+ *
+ * <pre>
+ * -D <int>
+ * Set degree in kernel function (default: 3)
+ * </pre>
+ *
+ * <pre>
+ * -G <double>
+ * Set gamma in kernel function (default: 1/k)
+ * </pre>
+ *
+ * <pre>
+ * -R <double>
+ * Set coef0 in kernel function (default: 0)
+ * </pre>
+ *
+ * <pre>
+ * -C <double>
* Set the parameter C of C-SVC, epsilon-SVR, and nu-SVR
- * (default: 1)</pre>
+ * (default: 1)
+ * </pre>
*
- * <pre> -N <double>
+ * <pre>
+ * -N <double>
* Set the parameter nu of nu-SVC, one-class SVM, and nu-SVR
- * (default: 0.5)</pre>
+ * (default: 0.5)
+ * </pre>
*
- * <pre> -Z
- * Turns on normalization of input data (default: off)</pre>
+ * <pre>
+ * -Z
+ * Turns on normalization of input data (default: off)
+ * </pre>
*
- * <pre> -J
+ * <pre>
+ * -J
* Turn off nominal to binary conversion.
- * WARNING: use only if your data is all numeric!</pre>
+ * WARNING: use only if your data is all numeric!
+ * </pre>
*
- * <pre> -V
+ * <pre>
+ * -V
* Turn off missing value replacement.
- * WARNING: use only if your data has no missing values.</pre>
- *
- * <pre> -P <double>
- * Set the epsilon in loss function of epsilon-SVR (default: 0.1)</pre>
- *
- * <pre> -M <double>
- * Set cache memory size in MB (default: 40)</pre>
- *
- * <pre> -E <double>
- * Set tolerance of termination criterion (default: 0.001)</pre>
- *
- * <pre> -H
- * Turns the shrinking heuristics off (default: on)</pre>
- *
- * <pre> -W <double>
+ * WARNING: use only if your data has no missing values.
+ * </pre>
+ *
+ * <pre>
+ * -P <double>
+ * Set the epsilon in loss function of epsilon-SVR (default: 0.1)
+ * </pre>
+ *
+ * <pre>
+ * -M <double>
+ * Set cache memory size in MB (default: 40)
+ * </pre>
+ *
+ * <pre>
+ * -E <double>
+ * Set tolerance of termination criterion (default: 0.001)
+ * </pre>
+ *
+ * <pre>
+ * -H
+ * Turns the shrinking heuristics off (default: on)
+ * </pre>
+ *
+ * <pre>
+ * -W <double>
* Set the parameters C of class i to weight[i]*C, for C-SVC
* E.g., for a 3-class problem, you could use "1 1 1" for equally
* weighted classes.
- * (default: 1 for all classes)</pre>
+ * (default: 1 for all classes)
+ * </pre>
*
- * <pre> -B
- * Generate probability estimates for classification</pre>
+ * <pre>
+ * -B
+ * Generate probability estimates for classification
+ * </pre>
*
- * <pre> -seed <num>
+ * <pre>
+ * -seed <num>
* Random seed
- * (default = 1)</pre>
+ * (default = 1)
+ * </pre>
*
<!-- options-end -->
- *
- * @param options the options to parse
- * @throws Exception if parsing fails
+ *
+ * @param options the options to parse
+ * @throws Exception if parsing fails
*/
+ @Override
public void setOptions(String[] options) throws Exception {
- String tmpStr;
-
+ String tmpStr;
+
tmpStr = Utils.getOption('S', options);
- if (tmpStr.length() != 0)
- setSVMType(
- new SelectedTag(Integer.parseInt(tmpStr), TAGS_SVMTYPE));
- else
- setSVMType(
- new SelectedTag(SVMTYPE_C_SVC, TAGS_SVMTYPE));
-
+ if (tmpStr.length() != 0) {
+ setSVMType(new SelectedTag(Integer.parseInt(tmpStr), TAGS_SVMTYPE));
+ } else {
+ setSVMType(new SelectedTag(SVMTYPE_C_SVC, TAGS_SVMTYPE));
+ }
+
tmpStr = Utils.getOption('K', options);
- if (tmpStr.length() != 0)
- setKernelType(
- new SelectedTag(Integer.parseInt(tmpStr), TAGS_KERNELTYPE));
- else
- setKernelType(
- new SelectedTag(KERNELTYPE_RBF, TAGS_KERNELTYPE));
-
+ if (tmpStr.length() != 0) {
+ setKernelType(new SelectedTag(Integer.parseInt(tmpStr), TAGS_KERNELTYPE));
+ } else {
+ setKernelType(new SelectedTag(KERNELTYPE_RBF, TAGS_KERNELTYPE));
+ }
+
tmpStr = Utils.getOption('D', options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setDegree(Integer.parseInt(tmpStr));
- else
+ } else {
setDegree(3);
-
+ }
+
tmpStr = Utils.getOption('G', options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setGamma(Double.parseDouble(tmpStr));
- else
+ } else {
setGamma(0);
-
+ }
+
tmpStr = Utils.getOption('R', options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setCoef0(Double.parseDouble(tmpStr));
- else
+ } else {
setCoef0(0);
-
+ }
+
tmpStr = Utils.getOption('N', options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setNu(Double.parseDouble(tmpStr));
- else
+ } else {
setNu(0.5);
-
+ }
+
tmpStr = Utils.getOption('M', options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setCacheSize(Double.parseDouble(tmpStr));
- else
+ } else {
setCacheSize(40);
-
+ }
+
tmpStr = Utils.getOption('C', options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setCost(Double.parseDouble(tmpStr));
- else
+ } else {
setCost(1);
-
+ }
+
tmpStr = Utils.getOption('E', options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setEps(Double.parseDouble(tmpStr));
- else
+ } else {
setEps(1e-3);
-
+ }
+
setNormalize(Utils.getFlag('Z', options));
-
+
setDoNotReplaceMissingValues(Utils.getFlag("V", options));
-
+
tmpStr = Utils.getOption('P', options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setLoss(Double.parseDouble(tmpStr));
- else
+ } else {
setLoss(0.1);
-
+ }
+
setShrinking(!Utils.getFlag('H', options));
-
+
setWeights(Utils.getOption('W', options));
-
+
setProbabilityEstimates(Utils.getFlag('B', options));
-
+
String seedString = Utils.getOption("seed", options);
if (seedString.length() > 0) {
setSeed(Integer.parseInt(seedString.trim()));
}
}
-
+
/**
* Returns the current options
*
- * @return the current setup
+ * @return the current setup
*/
+ @Override
public String[] getOptions() {
-
- Vector result;
-
- result = new Vector();
-
+
+ Vector result;
+
+ result = new Vector();
+
result.add("-S");
result.add("" + m_SVMType);
-
+
result.add("-K");
result.add("" + m_KernelType);
-
+
result.add("-D");
result.add("" + getDegree());
-
+
result.add("-G");
result.add("" + getGamma());
-
+
result.add("-R");
result.add("" + getCoef0());
-
+
result.add("-N");
result.add("" + getNu());
-
+
result.add("-M");
result.add("" + getCacheSize());
-
+
result.add("-C");
result.add("" + getCost());
-
+
result.add("-E");
result.add("" + getEps());
-
+
result.add("-P");
result.add("" + getLoss());
-
- if (!getShrinking())
+
+ if (!getShrinking()) {
result.add("-H");
-
- if (getNormalize())
+ }
+
+ if (getNormalize()) {
result.add("-Z");
-
- if (getDoNotReplaceMissingValues())
+ }
+
+ if (getDoNotReplaceMissingValues()) {
result.add("-V");
-
+ }
+
if (getWeights().length() != 0) {
result.add("-W");
result.add("" + getWeights());
}
-
- if (getProbabilityEstimates())
+
+ if (getProbabilityEstimates()) {
result.add("-B");
-
- result.add("-seed"); result.add("" + getSeed());
-
+ }
+
+ result.add("-seed");
+ result.add("" + getSeed());
+
return (String[]) result.toArray(new String[result.size()]);
}
-
+
/**
- * returns whether the libsvm classes are present or not, i.e. whether the
+ * returns whether the libsvm classes are present or not, i.e. whether the
* classes are in the classpath or not
- *
+ *
* @return whether the libsvm classes are available
*/
public static boolean isPresent() {
return m_Present;
}
-
+
/**
* Sets type of SVM (default SVMTYPE_C_SVC)
*
- * @param value the type of the SVM
+ * @param value the type of the SVM
*/
public void setSVMType(SelectedTag value) {
- if (value.getTags() == TAGS_SVMTYPE)
+ if (value.getTags() == TAGS_SVMTYPE) {
m_SVMType = value.getSelectedTag().getID();
+ }
}
-
+
/**
* Gets type of SVM
*
- * @return the type of the SVM
+ * @return the type of the SVM
*/
public SelectedTag getSVMType() {
return new SelectedTag(m_SVMType, TAGS_SVMTYPE);
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String SVMTypeTipText() {
return "The type of SVM to use.";
}
-
+
/**
* Sets type of kernel function (default KERNELTYPE_RBF)
*
- * @param value the kernel type
+ * @param value the kernel type
*/
public void setKernelType(SelectedTag value) {
- if (value.getTags() == TAGS_KERNELTYPE)
+ if (value.getTags() == TAGS_KERNELTYPE) {
m_KernelType = value.getSelectedTag().getID();
+ }
}
-
+
/**
* Gets type of kernel function
*
- * @return the kernel type
+ * @return the kernel type
*/
public SelectedTag getKernelType() {
return new SelectedTag(m_KernelType, TAGS_KERNELTYPE);
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String kernelTypeTipText() {
return "The type of kernel to use";
}
-
+
/**
* Sets the degree of the kernel
*
- * @param value the degree of the kernel
+ * @param value the degree of the kernel
*/
public void setDegree(int value) {
m_Degree = value;
}
-
+
/**
* Gets the degree of the kernel
*
- * @return the degree of the kernel
+ * @return the degree of the kernel
*/
public int getDegree() {
return m_Degree;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String degreeTipText() {
return "The degree of the kernel.";
}
-
+
/**
* Sets gamma (default = 1/no of attributes)
*
- * @param value the gamma value
+ * @param value the gamma value
*/
public void setGamma(double value) {
m_Gamma = value;
}
-
+
/**
* Gets gamma
*
- * @return the current gamma
+ * @return the current gamma
*/
public double getGamma() {
return m_Gamma;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String gammaTipText() {
return "The gamma to use, if 0 then 1/max_index is used.";
}
-
+
/**
* Sets coef (default 0)
*
- * @param value the coef
+ * @param value the coef
*/
public void setCoef0(double value) {
m_Coef0 = value;
}
-
+
/**
* Gets coef
*
- * @return the coef
+ * @return the coef
*/
public double getCoef0() {
return m_Coef0;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String coef0TipText() {
return "The coefficient to use.";
}
-
+
/**
* Sets nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
*
- * @param value the new nu value
+ * @param value the new nu value
*/
public void setNu(double value) {
m_nu = value;
}
-
+
/**
* Gets nu of nu-SVC, one-class SVM, and nu-SVR (default 0.5)
*
- * @return the current nu value
+ * @return the current nu value
*/
public double getNu() {
return m_nu;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String nuTipText() {
return "The value of nu for nu-SVC, one-class SVM and nu-SVR.";
}
-
+
/**
* Sets cache memory size in MB (default 40)
*
- * @param value the memory size in MB
+ * @param value the memory size in MB
*/
public void setCacheSize(double value) {
m_CacheSize = value;
}
-
+
/**
* Gets cache memory size in MB
*
- * @return the memory size in MB
+ * @return the memory size in MB
*/
public double getCacheSize() {
return m_CacheSize;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String cacheSizeTipText() {
return "The cache size in MB.";
}
-
+
/**
* Sets the parameter C of C-SVC, epsilon-SVR, and nu-SVR (default 1)
*
- * @param value the cost value
+ * @param value the cost value
*/
public void setCost(double value) {
m_Cost = value;
}
-
+
/**
* Sets the parameter C of C-SVC, epsilon-SVR, and nu-SVR
*
- * @return the cost value
+ * @return the cost value
*/
public double getCost() {
return m_Cost;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String costTipText() {
return "The cost parameter C for C-SVC, epsilon-SVR and nu-SVR.";
}
-
+
/**
* Sets tolerance of termination criterion (default 0.001)
*
- * @param value the tolerance
+ * @param value the tolerance
*/
public void setEps(double value) {
m_eps = value;
}
-
+
/**
* Gets tolerance of termination criterion
*
- * @return the current tolerance
+ * @return the current tolerance
*/
public double getEps() {
return m_eps;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String epsTipText() {
return "The tolerance of the termination criterion.";
}
-
+
/**
* Sets the epsilon in loss function of epsilon-SVR (default 0.1)
*
- * @param value the loss epsilon
+ * @param value the loss epsilon
*/
public void setLoss(double value) {
m_Loss = value;
}
-
+
/**
* Gets the epsilon in loss function of epsilon-SVR
*
- * @return the loss epsilon
+ * @return the loss epsilon
*/
public double getLoss() {
return m_Loss;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String lossTipText() {
return "The epsilon for the loss function in epsilon-SVR.";
}
-
+
/**
* whether to use the shrinking heuristics
*
- * @param value true uses shrinking
+ * @param value true uses shrinking
*/
public void setShrinking(boolean value) {
m_Shrinking = value;
}
-
+
/**
* whether to use the shrinking heuristics
*
- * @return true, if shrinking is used
+ * @return true, if shrinking is used
*/
public boolean getShrinking() {
return m_Shrinking;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String shrinkingTipText() {
return "Whether to use the shrinking heuristic.";
}
-
+
/**
* whether to normalize input data
*
- * @param value whether to normalize the data
+ * @param value whether to normalize the data
*/
public void setNormalize(boolean value) {
m_Normalize = value;
}
-
+
/**
* whether to normalize input data
*
- * @return true, if the data is normalized
+ * @return true, if the data is normalized
*/
public boolean getNormalize() {
return m_Normalize;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String normalizeTipText() {
return "Whether to normalize the data.";
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String doNotReplaceMissingValuesTipText() {
return "Whether to turn off automatic replacement of missing "
+ "values. WARNING: set to true only if the data does not "
+ "contain missing values.";
}
-
+
/**
- * Whether to turn off automatic replacement of missing values.
- * Set to true only if the data does not contain missing values.
+ * Whether to turn off automatic replacement of missing values. Set to true
+ * only if the data does not contain missing values.
*
- * @param b true if automatic missing values replacement is
- * to be disabled.
+ * @param b true if automatic missing values replacement is to be disabled.
*/
public void setDoNotReplaceMissingValues(boolean b) {
m_noReplaceMissingValues = b;
}
-
+
/**
- * Gets whether automatic replacement of missing values is
- * disabled.
+ * Gets whether automatic replacement of missing values is disabled.
*
- * @return true if automatic replacement of missing values
- * is disabled.
+ * @return true if automatic replacement of missing values is disabled.
*/
public boolean getDoNotReplaceMissingValues() {
return m_noReplaceMissingValues;
}
-
+
/**
* Sets the parameters C of class i to weight[i]*C, for C-SVC (default 1).
* Blank separated list of doubles.
*
- * @param weightsStr the weights (doubles, separated by blanks)
+ * @param weightsStr the weights (doubles, separated by blanks)
*/
public void setWeights(String weightsStr) {
- StringTokenizer tok;
- int i;
-
- tok = new StringTokenizer(weightsStr, " ");
- m_Weight = new double[tok.countTokens()];
+ StringTokenizer tok;
+ int i;
+
+ tok = new StringTokenizer(weightsStr, " ");
+ m_Weight = new double[tok.countTokens()];
m_WeightLabel = new int[tok.countTokens()];
-
- if (m_Weight.length == 0)
- System.out.println(
- "Zero Weights processed. Default weights will be used");
-
+
+ if (m_Weight.length == 0) {
+ System.out
+ .println("Zero Weights processed. Default weights will be used");
+ }
+
for (i = 0; i < m_Weight.length; i++) {
- m_Weight[i] = Double.parseDouble(tok.nextToken());
+ m_Weight[i] = Double.parseDouble(tok.nextToken());
m_WeightLabel[i] = i;
}
}
-
+
/**
* Gets the parameters C of class i to weight[i]*C, for C-SVC (default 1).
* Blank separated doubles.
*
- * @return the weights (doubles separated by blanks)
+ * @return the weights (doubles separated by blanks)
*/
public String getWeights() {
- String result;
- int i;
-
+ String result;
+ int i;
+
result = "";
for (i = 0; i < m_Weight.length; i++) {
- if (i > 0)
+ if (i > 0) {
result += " ";
+ }
result += Double.toString(m_Weight[i]);
}
-
+
return result;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String weightsTipText() {
return "The weights to use for the classes (blank-separated list, eg, \"1 1 1\" for a 3-class problem), if empty 1 is used by default.";
}
-
+
/**
- * Returns whether probability estimates are generated instead of -1/+1 for
+ * Returns whether probability estimates are generated instead of -1/+1 for
* classification problems.
*
- * @param value whether to predict probabilities
+ * @param value whether to predict probabilities
*/
public void setProbabilityEstimates(boolean value) {
m_ProbabilityEstimates = value;
}
-
+
/**
- * Sets whether to generate probability estimates instead of -1/+1 for
+ * Sets whether to generate probability estimates instead of -1/+1 for
* classification problems.
*
- * @return true, if probability estimates should be returned
+ * @return true, if probability estimates should be returned
*/
public boolean getProbabilityEstimates() {
return m_ProbabilityEstimates;
}
-
+
/**
* Returns the tip text for this property
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String probabilityEstimatesTipText() {
return "Whether to generate probability estimates instead of -1/+1 for classification problems.";
}
-
+
/**
* sets the specified field
*
- * @param o the object to set the field for
- * @param name the name of the field
- * @param value the new value of the field
+ * @param o the object to set the field for
+ * @param name the name of the field
+ * @param value the new value of the field
*/
protected void setField(Object o, String name, Object value) {
- Field f;
-
+ Field f;
+
try {
f = o.getClass().getField(name);
f.set(o, value);
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
-
+
/**
* sets the specified field in an array
*
- * @param o the object to set the field for
- * @param name the name of the field
- * @param index the index in the array
- * @param value the new value of the field
+ * @param o the object to set the field for
+ * @param name the name of the field
+ * @param index the index in the array
+ * @param value the new value of the field
*/
protected void setField(Object o, String name, int index, Object value) {
- Field f;
-
+ Field f;
+
try {
f = o.getClass().getField(name);
Array.set(f.get(o), index, value);
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
-
+
/**
* returns the current value of the specified field
*
- * @param o the object the field is member of
- * @param name the name of the field
- * @return the value
+ * @param o the object the field is member of
+ * @param name the name of the field
+ * @return the value
*/
protected Object getField(Object o, String name) {
- Field f;
- Object result;
-
+ Field f;
+ Object result;
+
try {
- f = o.getClass().getField(name);
+ f = o.getClass().getField(name);
result = f.get(o);
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
result = null;
}
-
+
return result;
}
-
+
/**
* sets a new array for the field
*
- * @param o the object to set the array for
- * @param name the name of the field
- * @param type the type of the array
- * @param length the length of the one-dimensional array
+ * @param o the object to set the array for
+ * @param name the name of the field
+ * @param type the type of the array
+ * @param length the length of the one-dimensional array
*/
protected void newArray(Object o, String name, Class type, int length) {
- newArray(o, name, type, new int[]{length});
+ newArray(o, name, type, new int[] { length });
}
-
+
/**
* sets a new array for the field
*
- * @param o the object to set the array for
- * @param name the name of the field
- * @param type the type of the array
- * @param dimensions the dimensions of the array
+ * @param o the object to set the array for
+ * @param name the name of the field
+ * @param type the type of the array
+ * @param dimensions the dimensions of the array
*/
protected void newArray(Object o, String name, Class type, int[] dimensions) {
- Field f;
-
+ Field f;
+
try {
f = o.getClass().getField(name);
f.set(o, Array.newInstance(type, dimensions));
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
-
+
/**
* executes the specified method and returns the result, if any
*
- * @param o the object the method should be called from
- * @param name the name of the method
- * @param paramClasses the classes of the parameters
- * @param paramValues the values of the parameters
- * @return the return value of the method, if any (in that case null)
+ * @param o the object the method should be called from
+ * @param name the name of the method
+ * @param paramClasses the classes of the parameters
+ * @param paramValues the values of the parameters
+ * @return the return value of the method, if any (in that case null)
*/
- protected Object invokeMethod(Object o, String name, Class[] paramClasses, Object[] paramValues) {
- Method m;
- Object result;
-
+ protected Object invokeMethod(Object o, String name, Class[] paramClasses,
+ Object[] paramValues) {
+ Method m;
+ Object result;
+
result = null;
-
+
try {
- m = o.getClass().getMethod(name, paramClasses);
+ m = o.getClass().getMethod(name, paramClasses);
result = m.invoke(o, paramValues);
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
result = null;
}
-
+
return result;
}
-
+
/**
* transfers the local variables into a svm_parameter object
*
* @return the configured svm_parameter object
*/
protected Object getParameters() {
- Object result;
- int i;
-
+ Object result;
+ int i;
+
try {
result = Class.forName(CLASS_SVMPARAMETER).newInstance();
-
+
setField(result, "svm_type", new Integer(m_SVMType));
setField(result, "kernel_type", new Integer(m_KernelType));
setField(result, "degree", new Integer(m_Degree));
@@ -1296,23 +1363,23 @@ public class LibSVM
setField(result, "p", new Double(m_Loss));
setField(result, "shrinking", new Integer(m_Shrinking ? 1 : 0));
setField(result, "nr_weight", new Integer(m_Weight.length));
- setField(result, "probability", new Integer(m_ProbabilityEstimates ? 1 : 0));
-
+ setField(result, "probability", new Integer(m_ProbabilityEstimates ? 1
+ : 0));
+
newArray(result, "weight", Double.TYPE, m_Weight.length);
newArray(result, "weight_label", Integer.TYPE, m_Weight.length);
for (i = 0; i < m_Weight.length; i++) {
setField(result, "weight", i, new Double(m_Weight[i]));
setField(result, "weight_label", i, new Integer(m_WeightLabel[i]));
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
result = null;
}
-
+
return result;
}
-
+
/**
* returns the svm_problem
*
@@ -1321,189 +1388,189 @@ public class LibSVM
* @return the svm_problem object
*/
protected Object getProblem(Vector vx, Vector vy) {
- Object result;
-
+ Object result;
+
try {
result = Class.forName(CLASS_SVMPROBLEM).newInstance();
-
+
setField(result, "l", new Integer(vy.size()));
-
- newArray(result, "x", Class.forName(CLASS_SVMNODE), new int[]{vy.size(), 0});
- for (int i = 0; i < vy.size(); i++)
+
+ newArray(result, "x", Class.forName(CLASS_SVMNODE), new int[] {
+ vy.size(), 0 });
+ for (int i = 0; i < vy.size(); i++) {
setField(result, "x", i, vx.elementAt(i));
-
+ }
+
newArray(result, "y", Double.TYPE, vy.size());
- for (int i = 0; i < vy.size(); i++)
+ for (int i = 0; i < vy.size(); i++) {
setField(result, "y", i, vy.elementAt(i));
- }
- catch (Exception e) {
+ }
+ } catch (Exception e) {
e.printStackTrace();
result = null;
}
-
+
return result;
}
-
+
/**
* returns an instance into a sparse libsvm array
*
- * @param instance the instance to work on
- * @return the libsvm array
- * @throws Exception if setup of array fails
+ * @param instance the instance to work on
+ * @return the libsvm array
+ * @throws Exception if setup of array fails
*/
protected Object instanceToArray(Instance instance) throws Exception {
- int index;
- int count;
- int i;
- Object result;
-
+ int index;
+ int count;
+ int i;
+ Object result;
+
// determine number of non-zero attributes
- /*for (i = 0; i < instance.numAttributes(); i++) {
- if (i == instance.classIndex())
- continue;
- if (instance.value(i) != 0)
- count++;
- } */
+ /*
+ * for (i = 0; i < instance.numAttributes(); i++) { if (i ==
+ * instance.classIndex()) continue; if (instance.value(i) != 0) count++; }
+ */
count = 0;
for (i = 0; i < instance.numValues(); i++) {
- if (instance.index(i) == instance.classIndex())
+ if (instance.index(i) == instance.classIndex()) {
continue;
- if (instance.valueSparse(i) != 0)
+ }
+ if (instance.valueSparse(i) != 0) {
count++;
+ }
}
// fill array
- /* result = Array.newInstance(Class.forName(CLASS_SVMNODE), count);
- index = 0;
- for (i = 0; i < instance.numAttributes(); i++) {
- if (i == instance.classIndex())
- continue;
- if (instance.value(i) == 0)
- continue;
+ /*
+ * result = Array.newInstance(Class.forName(CLASS_SVMNODE), count); index =
+ * 0; for (i = 0; i < instance.numAttributes(); i++) { if (i ==
+ * instance.classIndex()) continue; if (instance.value(i) == 0) continue;
+ *
+ * Array.set(result, index, Class.forName(CLASS_SVMNODE).newInstance());
+ * setField(Array.get(result, index), "index", new Integer(i + 1));
+ * setField(Array.get(result, index), "value", new
+ * Double(instance.value(i))); index++; }
+ */
- Array.set(result, index, Class.forName(CLASS_SVMNODE).newInstance());
- setField(Array.get(result, index), "index", new Integer(i + 1));
- setField(Array.get(result, index), "value", new Double(instance.value(i)));
- index++;
- } */
-
result = Array.newInstance(Class.forName(CLASS_SVMNODE), count);
- index = 0;
+ index = 0;
for (i = 0; i < instance.numValues(); i++) {
-
+
int idx = instance.index(i);
- if (idx == instance.classIndex())
+ if (idx == instance.classIndex()) {
continue;
- if (instance.valueSparse(i) == 0)
+ }
+ if (instance.valueSparse(i) == 0) {
continue;
+ }
Array.set(result, index, Class.forName(CLASS_SVMNODE).newInstance());
setField(Array.get(result, index), "index", new Integer(idx + 1));
- setField(Array.get(result, index), "value", new Double(instance.valueSparse(i)));
+ setField(Array.get(result, index), "value",
+ new Double(instance.valueSparse(i)));
index++;
}
-
+
return result;
}
-
+
/**
- * Computes the distribution for a given instance.
- * In case of 1-class classification, 1 is returned at index 0 if libsvm
- * returns 1 and NaN (= missing) if libsvm returns -1.
- *
- * @param instance the instance for which distribution is computed
- * @return the distribution
- * @throws Exception if the distribution can't be computed successfully
+ * Computes the distribution for a given instance. In case of 1-class
+ * classification, 1 is returned at index 0 if libsvm returns 1 and NaN (=
+ * missing) if libsvm returns -1.
+ *
+ * @param instance the instance for which distribution is computed
+ * @return the distribution
+ * @throws Exception if the distribution can't be computed successfully
*/
- public double[] distributionForInstance (Instance instance) throws Exception {
+ @Override
+ public double[] distributionForInstance(Instance instance) throws Exception {
int[] labels = new int[instance.numClasses()];
double[] prob_estimates = null;
if (m_ProbabilityEstimates) {
invokeMethod(
- Class.forName(CLASS_SVM).newInstance(),
- "svm_get_labels",
- new Class[]{
- Class.forName(CLASS_SVMMODEL),
- Array.newInstance(Integer.TYPE, instance.numClasses()).getClass()},
- new Object[]{
- m_Model,
- labels});
+ Class.forName(CLASS_SVM).newInstance(),
+ "svm_get_labels",
+ new Class[] { Class.forName(CLASS_SVMMODEL),
+ Array.newInstance(Integer.TYPE, instance.numClasses()).getClass() },
+ new Object[] { m_Model, labels });
prob_estimates = new double[instance.numClasses()];
}
-
+
if (!getDoNotReplaceMissingValues()) {
m_ReplaceMissingValues.input(instance);
m_ReplaceMissingValues.batchFinished();
instance = m_ReplaceMissingValues.output();
}
-
+
if (m_Filter != null) {
m_Filter.input(instance);
m_Filter.batchFinished();
instance = m_Filter.output();
}
+ m_NominalToBinary.input(instance);
+ m_NominalToBinary.batchFinished();
+ instance = m_NominalToBinary.output();
+
Object x = instanceToArray(instance);
double v;
double[] result = new double[instance.numClasses()];
- if ( m_ProbabilityEstimates
- && ((m_SVMType == SVMTYPE_C_SVC) || (m_SVMType == SVMTYPE_NU_SVC)) ) {
- v = ((Double) invokeMethod(
+ if (m_ProbabilityEstimates
+ && ((m_SVMType == SVMTYPE_C_SVC) || (m_SVMType == SVMTYPE_NU_SVC))) {
+ v =
+ ((Double) invokeMethod(
Class.forName(CLASS_SVM).newInstance(),
"svm_predict_probability",
- new Class[]{
- Class.forName(CLASS_SVMMODEL),
- Array.newInstance(Class.forName(CLASS_SVMNODE), Array.getLength(x)).getClass(),
- Array.newInstance(Double.TYPE, prob_estimates.length).getClass()},
- new Object[]{
- m_Model,
- x,
- prob_estimates})).doubleValue();
+ new Class[] {
+ Class.forName(CLASS_SVMMODEL),
+ Array.newInstance(Class.forName(CLASS_SVMNODE), Array.getLength(x))
+ .getClass(),
+ Array.newInstance(Double.TYPE, prob_estimates.length).getClass() },
+ new Object[] { m_Model, x, prob_estimates })).doubleValue();
// Return order of probabilities to canonical weka attribute order
for (int k = 0; k < prob_estimates.length; k++) {
result[labels[k]] = prob_estimates[k];
}
- }
- else {
- v = ((Double) invokeMethod(
- Class.forName(CLASS_SVM).newInstance(),
- "svm_predict",
- new Class[]{
- Class.forName(CLASS_SVMMODEL),
- Array.newInstance(Class.forName(CLASS_SVMNODE), Array.getLength(x)).getClass()},
- new Object[]{
- m_Model,
- x})).doubleValue();
-
+ } else {
+ v =
+ ((Double) invokeMethod(Class.forName(CLASS_SVM).newInstance(),
+ "svm_predict", new Class[] {
+ Class.forName(CLASS_SVMMODEL),
+ Array.newInstance(Class.forName(CLASS_SVMNODE), Array.getLength(x))
+ .getClass() }, new Object[] { m_Model, x })).doubleValue();
+
if (instance.classAttribute().isNominal()) {
- if (m_SVMType == SVMTYPE_ONE_CLASS_SVM) {
- if (v > 0)
- result[0] = 1;
- else
- // outlier (interface for Classifier specifies that unclassified instances
+ if (m_SVMType == SVMTYPE_ONE_CLASS_SVM) {
+ if (v > 0) {
+ result[0] = 1;
+ } else {
+ // outlier (interface for Classifier specifies that unclassified
+ // instances
// should return a distribution of all zeros)
- result[0] = 0;
- }
- else {
- result[(int) v] = 1;
- }
- }
- else {
- result[0] = v;
+ result[0] = 0;
+ }
+ } else {
+ result[(int) v] = 1;
+ }
+ } else {
+ result[0] = v;
}
}
- return result;
+ return result;
}
/**
* Returns default capabilities of the classifier.
- *
- * @return the capabilities of this classifier
+ *
+ * @return the capabilities of this classifier
*/
+ @Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
@@ -1512,6 +1579,7 @@ public class LibSVM
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
+ result.enable(Capability.MISSING_VALUES);
// class
result.enableDependency(Capability.UNARY_CLASS);
@@ -1520,135 +1588,144 @@ public class LibSVM
result.enableDependency(Capability.DATE_CLASS);
switch (m_SVMType) {
- case SVMTYPE_C_SVC:
- case SVMTYPE_NU_SVC:
- result.enable(Capability.NOMINAL_CLASS);
- break;
-
- case SVMTYPE_ONE_CLASS_SVM:
- result.enable(Capability.UNARY_CLASS);
- break;
-
- case SVMTYPE_EPSILON_SVR:
- case SVMTYPE_NU_SVR:
- result.enable(Capability.NUMERIC_CLASS);
- result.enable(Capability.DATE_CLASS);
- break;
-
- default:
- throw new IllegalArgumentException("SVMType " + m_SVMType + " is not supported!");
+ case SVMTYPE_C_SVC:
+ case SVMTYPE_NU_SVC:
+ result.enable(Capability.NOMINAL_CLASS);
+ break;
+
+ case SVMTYPE_ONE_CLASS_SVM:
+ result.enable(Capability.UNARY_CLASS);
+ break;
+
+ case SVMTYPE_EPSILON_SVR:
+ case SVMTYPE_NU_SVR:
+ result.enable(Capability.NUMERIC_CLASS);
+ result.enable(Capability.DATE_CLASS);
+ break;
+
+ default:
+ throw new IllegalArgumentException("SVMType " + m_SVMType
+ + " is not supported!");
}
result.enable(Capability.MISSING_CLASS_VALUES);
-
+
return result;
}
-
+
/**
* builds the classifier
*
- * @param insts the training instances
- * @throws Exception if libsvm classes not in classpath or libsvm
- * encountered a problem
+ * @param insts the training instances
+ * @throws Exception if libsvm classes not in classpath or libsvm encountered
+ * a problem
*/
+ @Override
public void buildClassifier(Instances insts) throws Exception {
m_Filter = null;
-
- if (!isPresent())
+
+ if (!isPresent()) {
throw new Exception("libsvm classes not in CLASSPATH!");
+ }
// remove instances with missing class
insts = new Instances(insts);
insts.deleteWithMissingClass();
-
+
if (!getDoNotReplaceMissingValues()) {
m_ReplaceMissingValues = new ReplaceMissingValues();
m_ReplaceMissingValues.setInputFormat(insts);
insts = Filter.useFilter(insts, m_ReplaceMissingValues);
}
-
+
// can classifier handle the data?
// we check this here so that if the user turns off
// replace missing values filtering, it will fail
// if the data actually does have missing values
getCapabilities().testWithFail(insts);
-
+
if (getNormalize()) {
m_Filter = new Normalize();
m_Filter.setInputFormat(insts);
insts = Filter.useFilter(insts, m_Filter);
}
-
+
+ // nominal to binary
+ m_NominalToBinary = new NominalToBinary();
+ m_NominalToBinary.setInputFormat(insts);
+ insts = Filter.useFilter(insts, m_NominalToBinary);
+
Vector vy = new Vector();
Vector vx = new Vector();
int max_index = 0;
-
+
for (int d = 0; d < insts.numInstances(); d++) {
Instance inst = insts.instance(d);
Object x = instanceToArray(inst);
int m = Array.getLength(x);
-
- if (m > 0)
- max_index = Math.max(max_index, ((Integer) getField(Array.get(x, m - 1), "index")).intValue());
+
+ if (m > 0) {
+ max_index =
+ Math.max(max_index,
+ ((Integer) getField(Array.get(x, m - 1), "index")).intValue());
+ }
vx.addElement(x);
vy.addElement(new Double(inst.classValue()));
}
-
+
// calculate actual gamma
- if (getGamma() == 0)
+ if (getGamma() == 0) {
m_GammaActual = 1.0 / max_index;
- else
+ } else {
m_GammaActual = m_Gamma;
+ }
// check parameter
- String error_msg = (String) invokeMethod(
- Class.forName(CLASS_SVM).newInstance(),
- "svm_check_parameter",
- new Class[]{
- Class.forName(CLASS_SVMPROBLEM),
- Class.forName(CLASS_SVMPARAMETER)},
- new Object[]{
- getProblem(vx, vy),
- getParameters()});
-
- if (error_msg != null)
+ String error_msg =
+ (String) invokeMethod(Class.forName(CLASS_SVM).newInstance(),
+ "svm_check_parameter", new Class[] { Class.forName(CLASS_SVMPROBLEM),
+ Class.forName(CLASS_SVMPARAMETER) }, new Object[] {
+ getProblem(vx, vy), getParameters() });
+
+ if (error_msg != null) {
throw new Exception("Error: " + error_msg);
-
+ }
+
// make probability estimates deterministic from run to run
Class svmClass = Class.forName(CLASS_SVM);
Field randF = svmClass.getField("rand");
- Random rand = (Random)randF.get(null); // static field
+ Random rand = (Random) randF.get(null); // static field
rand.setSeed(m_Seed);
-
+
// train model
- m_Model = invokeMethod(
- Class.forName(CLASS_SVM).newInstance(),
- "svm_train",
- new Class[]{
- Class.forName(CLASS_SVMPROBLEM),
- Class.forName(CLASS_SVMPARAMETER)},
- new Object[]{
- getProblem(vx, vy),
- getParameters()});
- }
-
+ m_Model =
+ invokeMethod(
+ Class.forName(CLASS_SVM).newInstance(),
+ "svm_train",
+ new Class[] { Class.forName(CLASS_SVMPROBLEM),
+ Class.forName(CLASS_SVMPARAMETER) }, new Object[] {
+ getProblem(vx, vy), getParameters() });
+ }
+
/**
* returns a string representation
*
- * @return a string representation
+ * @return a string representation
*/
+ @Override
public String toString() {
return "LibSVM wrapper, original code by Yasser EL-Manzalawy (= WLSVM)";
}
-
+
/**
* Returns the revision string.
*
- * @return the revision
+ * @return the revision
*/
+ @Override
public String getRevision() {
- return RevisionUtils.extract("$Revision: 8940 $");
+ return RevisionUtils.extract("$Revision: 10660 $");
}
-
+
/**
* Main method for testing this class.
*
@@ -1658,4 +1735,3 @@ public class LibSVM
runClassifier(new LibSVM(), args);
}
}
-
diff --git a/src/main/java/weka/classifiers/functions/MultilayerPerceptron.java b/src/main/java/weka/classifiers/functions/MultilayerPerceptron.java
index 55378d0..8e38356 100644
--- a/src/main/java/weka/classifiers/functions/MultilayerPerceptron.java
+++ b/src/main/java/weka/classifiers/functions/MultilayerPerceptron.java
@@ -143,7 +143,7 @@ import javax.swing.JTextField;
<!-- options-end -->
*
* @author Malcolm Ware (mfw4 at cs.waikato.ac.nz)
- * @version $Revision: 9445 $
+ * @version $Revision: 10073 $
*/
public class MultilayerPerceptron
extends Classifier
@@ -434,7 +434,7 @@ public class MultilayerPerceptron
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9445 $");
+ return RevisionUtils.extract("$Revision: 10073 $");
}
}
@@ -685,14 +685,14 @@ public class MultilayerPerceptron
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9445 $");
+ return RevisionUtils.extract("$Revision: 10073 $");
}
}
/**
* This provides the basic controls for working with the neuralnetwork
* @author Malcolm Ware (mfw4 at cs.waikato.ac.nz)
- * @version $Revision: 9445 $
+ * @version $Revision: 10073 $
*/
class ControlPanel
extends JPanel
@@ -888,7 +888,7 @@ public class MultilayerPerceptron
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9445 $");
+ return RevisionUtils.extract("$Revision: 10073 $");
}
}
@@ -2106,6 +2106,9 @@ public class MultilayerPerceptron
m_currentInstance = i;
}
+ // Make a copy of the instance so that it isn't modified
+ m_currentInstance = (Instance)m_currentInstance.copy();
+
if (m_normalizeAttributes) {
for (int noa = 0; noa < m_instances.numAttributes(); noa++) {
if (noa != m_instances.classIndex()) {
@@ -2693,6 +2696,6 @@ public class MultilayerPerceptron
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9445 $");
+ return RevisionUtils.extract("$Revision: 10073 $");
}
}
diff --git a/src/main/java/weka/classifiers/functions/supportVector/PolyKernel.java b/src/main/java/weka/classifiers/functions/supportVector/PolyKernel.java
index f83f57c..ee50601 100644
--- a/src/main/java/weka/classifiers/functions/supportVector/PolyKernel.java
+++ b/src/main/java/weka/classifiers/functions/supportVector/PolyKernel.java
@@ -68,7 +68,7 @@ import java.util.Vector;
* @author Eibe Frank (eibe at cs.waikato.ac.nz)
* @author Shane Legg (shane at intelligenesis.net) (sparse vector code)
* @author Stuart Inglis (stuart at reeltwo.com) (sparse vector code)
- * @version $Revision: 5808 $
+ * @version $Revision: 9993 $
*/
public class PolyKernel
extends CachedKernel {
@@ -90,6 +90,17 @@ public class PolyKernel
}
/**
+ * Frees the cache used by the kernel.
+ */
+ public void clean() {
+ if (getExponent() == 1.0) {
+ m_data = null;
+ }
+ super.clean();
+ }
+
+
+ /**
* Creates a new <code>PolyKernel</code> instance.
*
* @param data the training dataset used.
@@ -349,7 +360,7 @@ public class PolyKernel
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 5808 $");
+ return RevisionUtils.extract("$Revision: 9993 $");
}
}
diff --git a/src/main/java/weka/classifiers/lazy/IBk.java b/src/main/java/weka/classifiers/lazy/IBk.java
index 2fb1134..c6f35ad 100644
--- a/src/main/java/weka/classifiers/lazy/IBk.java
+++ b/src/main/java/weka/classifiers/lazy/IBk.java
@@ -110,7 +110,7 @@ import java.util.Vector;
* @author Stuart Inglis (singlis at cs.waikato.ac.nz)
* @author Len Trigg (trigg at cs.waikato.ac.nz)
* @author Eibe Frank (eibe at cs.waikato.ac.nz)
- * @version $Revision: 6573 $
+ * @version $Revision: 10069 $
*/
public class IBk
extends Classifier
@@ -385,8 +385,9 @@ public class IBk
*/
public String crossValidateTipText() {
- return "Whether hold-one-out cross-validation will be used " +
- "to select the best k value.";
+ return "Whether hold-one-out cross-validation will be used to " +
+ "select the best k value between 1 and the value specified as " +
+ "the KNN parameter.";
}
/**
@@ -1055,7 +1056,7 @@ public class IBk
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 6573 $");
+ return RevisionUtils.extract("$Revision: 10069 $");
}
/**
diff --git a/src/main/java/weka/classifiers/mi/supportVector/MIPolyKernel.java b/src/main/java/weka/classifiers/mi/supportVector/MIPolyKernel.java
index 8d88d8b..10583e2 100644
--- a/src/main/java/weka/classifiers/mi/supportVector/MIPolyKernel.java
+++ b/src/main/java/weka/classifiers/mi/supportVector/MIPolyKernel.java
@@ -66,7 +66,7 @@ import weka.core.Capabilities.Capability;
* @author Shane Legg (shane at intelligenesis.net) (sparse vector code)
* @author Stuart Inglis (stuart at reeltwo.com) (sparse vector code)
* @author Lin Dong (ld21 at cs.waikato.ac.nz) (MIkernel)
- * @version $Revision: 9144 $
+ * @version $Revision: 10036 $
*/
public class MIPolyKernel
extends PolyKernel
@@ -177,12 +177,21 @@ public class MIPolyKernel
}
/**
+ * Frees the cache used by the kernel.
+ */
+ public void clean() {
+ m_storage = null;
+ m_keys = null;
+ m_kernelMatrix = null;
+ }
+
+ /**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9144 $");
+ return RevisionUtils.extract("$Revision: 10036 $");
}
}
diff --git a/src/main/java/weka/classifiers/trees/ADTree.java b/src/main/java/weka/classifiers/trees/ADTree.java
index 7dc13bf..2b9b98c 100644
--- a/src/main/java/weka/classifiers/trees/ADTree.java
+++ b/src/main/java/weka/classifiers/trees/ADTree.java
@@ -97,7 +97,7 @@ import java.util.Vector;
*
* @author Richard Kirkby (rkirkby at cs.waikato.ac.nz)
* @author Bernhard Pfahringer (bernhard at cs.waikato.ac.nz)
- * @version $Revision: 5535 $
+ * @version $Revision: 10290 $
*/
public class ADTree
extends Classifier
@@ -924,13 +924,13 @@ public class ADTree
text.append("S" + splitOrder + "P" + predOrder + "->" + "S" + split.orderAdded +
" [style=dotted]\n");
text.append("S" + split.orderAdded + " [label=\"" + split.orderAdded + ": " +
- split.attributeString(m_trainInstances) + "\"]\n");
+ Utils.backQuoteChars(split.attributeString(m_trainInstances)) + "\"]\n");
for (int i=0; i<split.getNumOfBranches(); i++) {
PredictionNode child = split.getChildForBranch(i);
if (child != null) {
text.append("S" + split.orderAdded + "->" + "S" + split.orderAdded + "P" + i +
- " [label=\"" + split.comparisonString(i, m_trainInstances) + "\"]\n");
+ " [label=\"" + Utils.backQuoteChars(split.comparisonString(i, m_trainInstances)) + "\"]\n");
graphTraverse(child, text, split.orderAdded, i,
split.instancesDownBranch(i, instances));
}
@@ -1484,7 +1484,7 @@ public class ADTree
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 5535 $");
+ return RevisionUtils.extract("$Revision: 10290 $");
}
/**
diff --git a/src/main/java/weka/classifiers/trees/LADTree.java b/src/main/java/weka/classifiers/trees/LADTree.java
index b878920..eb9b391 100644
--- a/src/main/java/weka/classifiers/trees/LADTree.java
+++ b/src/main/java/weka/classifiers/trees/LADTree.java
@@ -71,7 +71,7 @@ import weka.core.TechnicalInformation.Type;
<!-- options-end -->
*
* @author Richard Kirkby
- * @version $Revision: 8127 $
+ * @version $Revision: 10279 $
*/
public class LADTree
@@ -1121,7 +1121,7 @@ public class LADTree
PredictionNode child = split.getChildForBranch(i);
if (child != null) {
text.append("S" + split.orderAdded + "->" + "S" + split.orderAdded + "P" + i +
- " [label=\"" + split.comparisonString(i) + "\"]\n");
+ " [label=\"" + Utils.backQuoteChars(split.comparisonString(i)) + "\"]\n");
graphTraverse(child, text, split.orderAdded, i);
}
}
@@ -1466,7 +1466,7 @@ public class LADTree
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 8127 $");
+ return RevisionUtils.extract("$Revision: 10279 $");
}
/**
diff --git a/src/main/java/weka/classifiers/trees/REPTree.java b/src/main/java/weka/classifiers/trees/REPTree.java
index eacfb80..cab455a 100644
--- a/src/main/java/weka/classifiers/trees/REPTree.java
+++ b/src/main/java/weka/classifiers/trees/REPTree.java
@@ -77,7 +77,7 @@ import java.util.Vector;
<!-- options-end -->
*
* @author Eibe Frank (eibe at cs.waikato.ac.nz)
- * @version $Revision: 9389 $
+ * @version $Revision: 10275 $
*/
public class REPTree
extends Classifier
@@ -350,12 +350,12 @@ public class REPTree
num++;
if (m_Attribute == -1) {
text.append("N" + Integer.toHexString(Tree.this.hashCode()) +
- " [label=\"" + num + leafString(parent) +"\"" +
+ " [label=\"" + num + Utils.backQuoteChars(leafString(parent)) +"\"" +
"shape=box]\n");
} else {
text.append("N" + Integer.toHexString(Tree.this.hashCode()) +
" [label=\"" + num + ": " +
- m_Info.attribute(m_Attribute).name() +
+ Utils.backQuoteChars(m_Info.attribute(m_Attribute).name()) +
"\"]\n");
for (int i = 0; i < m_Successors.length; i++) {
text.append("N" + Integer.toHexString(Tree.this.hashCode())
@@ -372,7 +372,7 @@ public class REPTree
Utils.doubleToString(m_SplitPoint, 2));
}
} else {
- text.append(" = " + m_Info.attribute(m_Attribute).value(i));
+ text.append(" = " + Utils.backQuoteChars(m_Info.attribute(m_Attribute).value(i)));
}
text.append("\"]\n");
num = m_Successors[i].toGraph(text, num, this);
@@ -1341,7 +1341,7 @@ public class REPTree
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9389 $");
+ return RevisionUtils.extract("$Revision: 10275 $");
}
}
@@ -1972,7 +1972,7 @@ public class REPTree
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9389 $");
+ return RevisionUtils.extract("$Revision: 10275 $");
}
/**
diff --git a/src/main/java/weka/classifiers/trees/RandomTree.java b/src/main/java/weka/classifiers/trees/RandomTree.java
index 5c1fbbf..1532624 100644
--- a/src/main/java/weka/classifiers/trees/RandomTree.java
+++ b/src/main/java/weka/classifiers/trees/RandomTree.java
@@ -99,7 +99,7 @@ import weka.core.WeightedInstancesHandler;
*
* @author Eibe Frank (eibe at cs.waikato.ac.nz)
* @author Richard Kirkby (rkirkby at cs.waikato.ac.nz)
- * @version $Revision: 9525 $
+ * @version $Revision: 10287 $
*/
public class RandomTree extends Classifier implements OptionHandler,
WeightedInstancesHandler, Randomizable, Drawable {
@@ -872,7 +872,7 @@ public class RandomTree extends Classifier implements OptionHandler,
public int toGraph(StringBuffer text, int num) throws Exception {
int maxIndex = Utils.maxIndex(m_ClassDistribution);
- String classValue = m_Info.classAttribute().value(maxIndex);
+ String classValue = Utils.backQuoteChars(m_Info.classAttribute().value(maxIndex));
num++;
if (m_Attribute == -1) {
@@ -884,7 +884,7 @@ public class RandomTree extends Classifier implements OptionHandler,
for (int i = 0; i < m_Successors.length; i++) {
text.append("N" + Integer.toHexString(hashCode()) + "->" + "N"
+ Integer.toHexString(m_Successors[i].hashCode()) + " [label=\""
- + m_Info.attribute(m_Attribute).name());
+ + Utils.backQuoteChars(m_Info.attribute(m_Attribute).name()));
if (m_Info.attribute(m_Attribute).isNumeric()) {
if (i == 0) {
text.append(" < " + Utils.doubleToString(m_SplitPoint, 2));
@@ -892,7 +892,7 @@ public class RandomTree extends Classifier implements OptionHandler,
text.append(" >= " + Utils.doubleToString(m_SplitPoint, 2));
}
} else {
- text.append(" = " + m_Info.attribute(m_Attribute).value(i));
+ text.append(" = " + Utils.backQuoteChars(m_Info.attribute(m_Attribute).value(i)));
}
text.append("\"]\n");
num = m_Successors[i].toGraph(text, num);
@@ -1445,7 +1445,7 @@ public class RandomTree extends Classifier implements OptionHandler,
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9525 $");
+ return RevisionUtils.extract("$Revision: 10287 $");
}
/**
diff --git a/src/main/java/weka/classifiers/trees/SimpleCart.java b/src/main/java/weka/classifiers/trees/SimpleCart.java
index 9d836e7..dc5c893 100644
--- a/src/main/java/weka/classifiers/trees/SimpleCart.java
+++ b/src/main/java/weka/classifiers/trees/SimpleCart.java
@@ -107,7 +107,7 @@ import java.util.Vector;
<!-- options-end -->
*
* @author Haijian Shi (hs69 at cs.waikato.ac.nz)
- * @version $Revision: 5535 $
+ * @version $Revision: 10491 $
*/
public class SimpleCart
extends RandomizableClassifier
@@ -380,6 +380,7 @@ public class SimpleCart
m_totalTrainInstances = totalInstances;
m_isLeaf = true;
+ m_Successors = null;
m_ClassProbs = new double[classProbs.length];
m_Distribution = new double[classProbs.length];
@@ -2009,7 +2010,7 @@ public class SimpleCart
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 5535 $");
+ return RevisionUtils.extract("$Revision: 10491 $");
}
/**
diff --git a/src/main/java/weka/classifiers/trees/ft/FTtree.java b/src/main/java/weka/classifiers/trees/ft/FTtree.java
index f39bbc5..b639acf 100644
--- a/src/main/java/weka/classifiers/trees/ft/FTtree.java
+++ b/src/main/java/weka/classifiers/trees/ft/FTtree.java
@@ -643,7 +643,7 @@ public abstract class FTtree
}else {
text.append("N" + m_id
+ " [label=\"" +
- m_localModel.leftSide(m_train) + "\" ");
+ Utils.backQuoteChars(m_localModel.leftSide(m_train)) + "\" ");
text.append("]\n");
graphTree(text);
}
@@ -662,7 +662,7 @@ public abstract class FTtree
text.append("N" + m_id
+ "->" +
"N" + m_sons[i].m_id +
- " [label=\"" + m_localModel.rightSide(i,m_train).trim() +
+ " [label=\"" + Utils.backQuoteChars(m_localModel.rightSide(i,m_train).trim()) +
"\"]\n");
if (m_sons[i].m_isLeaf && m_sons[i].m_hasConstr) {
text.append("N" +m_sons[i].m_id + " [label=\"FT_"+m_sons[i].m_leafModelNum+":"+
@@ -674,7 +674,7 @@ public abstract class FTtree
text.append("]\n");
}else{
text.append("N" + m_sons[i].m_id +
- " [label=\""+m_sons[i].m_localModel.leftSide(m_train) +
+ " [label=\""+ Utils.backQuoteChars(m_sons[i].m_localModel.leftSide(m_train)) +
"\" ");
text.append("]\n");
m_sons[i].graphTree(text);
diff --git a/src/main/java/weka/classifiers/trees/j48/ClassifierTree.java b/src/main/java/weka/classifiers/trees/j48/ClassifierTree.java
index 4f2998f..f877a1b 100644
--- a/src/main/java/weka/classifiers/trees/j48/ClassifierTree.java
+++ b/src/main/java/weka/classifiers/trees/j48/ClassifierTree.java
@@ -38,7 +38,7 @@ import java.io.Serializable;
* classification.
*
* @author Eibe Frank (eibe at cs.waikato.ac.nz)
- * @version $Revision: 5531 $
+ * @version $Revision: 10256 $
*/
public class ClassifierTree
implements Drawable, Serializable, CapabilitiesHandler, RevisionHandler {
@@ -318,7 +318,7 @@ public class ClassifierTree
if (m_isLeaf) {
text.append("N" + m_id
+ " [label=\"" +
- m_localModel.dumpLabel(0,m_train) + "\" " +
+ Utils.quote(m_localModel.dumpLabel(0,m_train)) + "\" " +
"shape=box style=filled ");
if (m_train != null && m_train.numInstances() > 0) {
text.append("data =\n" + m_train + "\n");
@@ -329,7 +329,7 @@ public class ClassifierTree
}else {
text.append("N" + m_id
+ " [label=\"" +
- m_localModel.leftSide(m_train) + "\" ");
+ Utils.quote(m_localModel.leftSide(m_train)) + "\" ");
if (m_train != null && m_train.numInstances() > 0) {
text.append("data =\n" + m_train + "\n");
text.append(",\n");
@@ -555,11 +555,11 @@ public class ClassifierTree
text.append("N" + m_id
+ "->" +
"N" + m_sons[i].m_id +
- " [label=\"" + m_localModel.rightSide(i,m_train).trim() +
+ " [label=\"" + Utils.quote(m_localModel.rightSide(i,m_train).trim()) +
"\"]\n");
if (m_sons[i].m_isLeaf) {
text.append("N" + m_sons[i].m_id +
- " [label=\""+m_localModel.dumpLabel(i,m_train)+"\" "+
+ " [label=\""+ Utils.quote(m_localModel.dumpLabel(i,m_train))+"\" "+
"shape=box style=filled ");
if (m_train != null && m_train.numInstances() > 0) {
text.append("data =\n" + m_sons[i].m_train + "\n");
@@ -568,7 +568,7 @@ public class ClassifierTree
text.append("]\n");
} else {
text.append("N" + m_sons[i].m_id +
- " [label=\""+m_sons[i].m_localModel.leftSide(m_train) +
+ " [label=\""+ Utils.quote(m_sons[i].m_localModel.leftSide(m_train))+
"\" ");
if (m_train != null && m_train.numInstances() > 0) {
text.append("data =\n" + m_sons[i].m_train + "\n");
@@ -708,6 +708,6 @@ public class ClassifierTree
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 5531 $");
+ return RevisionUtils.extract("$Revision: 10256 $");
}
}
diff --git a/src/main/java/weka/classifiers/trees/j48/NBTreeClassifierTree.java b/src/main/java/weka/classifiers/trees/j48/NBTreeClassifierTree.java
index 68fc4da..6bc795a 100644
--- a/src/main/java/weka/classifiers/trees/j48/NBTreeClassifierTree.java
+++ b/src/main/java/weka/classifiers/trees/j48/NBTreeClassifierTree.java
@@ -28,13 +28,14 @@ import weka.core.Capabilities;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.Capabilities.Capability;
+import weka.core.Utils;
/**
* Class for handling a naive bayes tree structure used for
* classification.
*
* @author Mark Hall (mhall at cs.waikato.ac.nz)
- * @version $Revision: 5535 $
+ * @version $Revision: 10286 $
*/
public class NBTreeClassifierTree
extends ClassifierTree {
@@ -221,7 +222,7 @@ public class NBTreeClassifierTree
}else {
text.append("N" + m_id
+ " [label=\"" +
- m_localModel.leftSide(m_train) + "\" ");
+ Utils.backQuoteChars(m_localModel.leftSide(m_train)) + "\" ");
if (m_train != null && m_train.numInstances() > 0) {
text.append("data =\n" + m_train + "\n");
text.append(",\n");
@@ -244,7 +245,7 @@ public class NBTreeClassifierTree
text.append("N" + m_id
+ "->" +
"N" + m_sons[i].m_id +
- " [label=\"" + m_localModel.rightSide(i,m_train).trim() +
+ " [label=\"" + Utils.backQuoteChars(m_localModel.rightSide(i,m_train).trim()) +
"\"]\n");
if (m_sons[i].m_isLeaf) {
text.append("N" + m_sons[i].m_id +
@@ -257,7 +258,7 @@ public class NBTreeClassifierTree
text.append("]\n");
} else {
text.append("N" + m_sons[i].m_id +
- " [label=\""+m_sons[i].m_localModel.leftSide(m_train) +
+ " [label=\""+ Utils.backQuoteChars(m_sons[i].m_localModel.leftSide(m_train)) +
"\" ");
if (m_train != null && m_train.numInstances() > 0) {
text.append("data =\n" + m_sons[i].m_train + "\n");
@@ -275,6 +276,6 @@ public class NBTreeClassifierTree
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 5535 $");
+ return RevisionUtils.extract("$Revision: 10286 $");
}
}
diff --git a/src/main/java/weka/classifiers/trees/lmt/LMTNode.java b/src/main/java/weka/classifiers/trees/lmt/LMTNode.java
index 399e85b..f884b9d 100644
--- a/src/main/java/weka/classifiers/trees/lmt/LMTNode.java
+++ b/src/main/java/weka/classifiers/trees/lmt/LMTNode.java
@@ -30,6 +30,7 @@ import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
+import weka.core.Utils;
import weka.filters.Filter;
import weka.filters.supervised.attribute.NominalToBinary;
@@ -903,7 +904,7 @@ public class LMTNode
}else {
text.append("N" + m_id
+ " [label=\"" +
- m_localModel.leftSide(m_train) + "\" ");
+ Utils.backQuoteChars(m_localModel.leftSide(m_train)) + "\" ");
text.append("]\n");
graphTree(text);
}
@@ -922,7 +923,7 @@ public class LMTNode
text.append("N" + m_id
+ "->" +
"N" + m_sons[i].m_id +
- " [label=\"" + m_localModel.rightSide(i,m_train).trim() +
+ " [label=\"" + Utils.backQuoteChars(m_localModel.rightSide(i,m_train).trim()) +
"\"]\n");
if (m_sons[i].m_isLeaf) {
text.append("N" +m_sons[i].m_id + " [label=\"LM_"+m_sons[i].m_leafModelNum+":"+
@@ -930,7 +931,7 @@ public class LMTNode
text.append("]\n");
} else {
text.append("N" + m_sons[i].m_id +
- " [label=\""+m_sons[i].m_localModel.leftSide(m_train) +
+ " [label=\""+ Utils.backQuoteChars(m_sons[i].m_localModel.leftSide(m_train)) +
"\" ");
text.append("]\n");
m_sons[i].graphTree(text);
diff --git a/src/main/java/weka/classifiers/trees/m5/RuleNode.java b/src/main/java/weka/classifiers/trees/m5/RuleNode.java
index fa549c9..9e19296 100644
--- a/src/main/java/weka/classifiers/trees/m5/RuleNode.java
+++ b/src/main/java/weka/classifiers/trees/m5/RuleNode.java
@@ -1055,7 +1055,7 @@ public class RuleNode
text.append("N" + m_id
+ (m_isLeaf
? " [label=\"LM " + m_leafModelNum
- : " [label=\"" + m_instances.attribute(m_splitAtt).name())
+ : " [label=\"" + Utils.backQuoteChars(m_instances.attribute(m_splitAtt).name()))
+ (m_isLeaf
? " (" + ((m_globalDeviation > 0.0)
? m_numInstances + "/"
diff --git a/src/main/java/weka/clusterers/EM.java b/src/main/java/weka/clusterers/EM.java
index 627b0b9..75ce5b0 100644
--- a/src/main/java/weka/clusterers/EM.java
+++ b/src/main/java/weka/clusterers/EM.java
@@ -86,7 +86,7 @@ import java.util.Vector;
*
* @author Mark Hall (mhall at cs.waikato.ac.nz)
* @author Eibe Frank (eibe at cs.waikato.ac.nz)
- * @version $Revision: 6299 $
+ * @version $Revision: 9988 $
*/
public class EM
extends RandomizableDensityBasedClusterer
@@ -95,6 +95,10 @@ public class EM
/** for serialization */
static final long serialVersionUID = 8348181483812829475L;
+ private Estimator m_modelPrev[][];
+ private double[][][] m_modelNormalPrev;
+ private double[] m_priorsPrev;
+
/** hold the discrete estimators for each cluster */
private Estimator m_model[][];
@@ -512,6 +516,11 @@ public class EM
m_model = new DiscreteEstimator[m_num_clusters][m_num_attribs];
m_modelNormal = new double[m_num_clusters][m_num_attribs][3];
m_priors = new double[m_num_clusters];
+
+ m_modelPrev = new DiscreteEstimator[m_num_clusters][m_num_attribs];
+ m_modelNormalPrev = new double[m_num_clusters][m_num_attribs][3];
+ m_priorsPrev = new double[m_num_clusters];
+
Instances centers = bestK.getClusterCentroids();
Instances stdD = bestK.getClusterStandardDevs();
int [][][] nominalCounts = bestK.getClusterNominalCounts();
@@ -576,6 +585,7 @@ public class EM
throws Exception {
for (int i = 0; i < m_num_clusters; i++) {
+ m_priorsPrev[i] = m_priors[i];
m_priors[i] = 0.0;
}
@@ -615,11 +625,15 @@ public class EM
for (int i = 0; i < m_num_clusters; i++) {
for (int j = 0; j < m_num_attribs; j++) {
if (m_theInstances.attribute(j).isNominal()) {
+ m_modelPrev[i][j] = m_model[i][j];
m_model[i][j] = new DiscreteEstimator(m_theInstances.
attribute(j).numValues()
, true);
}
else {
+ m_modelNormalPrev[i][j][0] = m_modelNormal[i][j][0];
+ m_modelNormalPrev[i][j][1] = m_modelNormal[i][j][1];
+ m_modelNormalPrev[i][j][2] = m_modelNormal[i][j][2];
m_modelNormal[i][j][0] = m_modelNormal[i][j][1] =
m_modelNormal[i][j][2] = 0.0;
}
@@ -1399,6 +1413,13 @@ public class EM
if (i > 0) {
if ((llk - llkold) < 1e-6) {
+ if (llk - llkold < 0) {
+ // decrease in log likelihood - revert to the model from the
+ // previous iteration
+ m_modelNormal = m_modelNormalPrev;
+ m_model = m_modelPrev;
+ m_priors = m_priorsPrev;
+ }
break;
}
}
@@ -1436,7 +1457,7 @@ public class EM
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 6299 $");
+ return RevisionUtils.extract("$Revision: 9988 $");
}
// ============
diff --git a/src/main/java/weka/clusterers/SimpleKMeans.java b/src/main/java/weka/clusterers/SimpleKMeans.java
index 949946d..eb9e963 100644
--- a/src/main/java/weka/clusterers/SimpleKMeans.java
+++ b/src/main/java/weka/clusterers/SimpleKMeans.java
@@ -21,9 +21,15 @@
*/
package weka.clusterers;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.Random;
+import java.util.Vector;
+
import weka.classifiers.rules.DecisionTableHashKey;
import weka.core.Attribute;
import weka.core.Capabilities;
+import weka.core.Capabilities.Capability;
import weka.core.DistanceFunction;
import weka.core.EuclideanDistance;
import weka.core.Instance;
@@ -33,65 +39,69 @@ import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.Utils;
import weka.core.WeightedInstancesHandler;
-import weka.core.Capabilities.Capability;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.ReplaceMissingValues;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Random;
-import java.util.Vector;
-
/**
- <!-- globalinfo-start -->
- * Cluster data using the k means algorithm
+ * <!-- globalinfo-start --> Cluster data using the k means algorithm
* <p/>
- <!-- globalinfo-end -->
- *
- <!-- options-start -->
- * Valid options are: <p/>
+ * <!-- globalinfo-end -->
*
- * <pre> -N <num>
+ * <!-- options-start --> Valid options are:
+ * <p/>
+ *
+ * <pre>
+ * -N <num>
* number of clusters.
- * (default 2).</pre>
+ * (default 2).
+ * </pre>
*
- * <pre> -V
+ * <pre>
+ * -V
* Display std. deviations for centroids.
* </pre>
*
- * <pre> -M
+ * <pre>
+ * -M
* Replace missing values with mean/mode.
* </pre>
*
- * <pre> -S <num>
+ * <pre>
+ * -S <num>
* Random number seed.
- * (default 10)</pre>
+ * (default 10)
+ * </pre>
*
- * <pre> -A <classname and options>
+ * <pre>
+ * -A <classname and options>
* Distance function to be used for instance comparison
- * (default weka.core.EuclidianDistance)</pre>
+ * (default weka.core.EuclidianDistance)
+ * </pre>
*
- * <pre> -I <num>
- * Maximum number of iterations. </pre>
+ * <pre>
+ * -I <num>
+ * Maximum number of iterations.
+ * </pre>
*
- * <pre> -O
- * Preserve order of instances. </pre>
+ * <pre>
+ * -O
+ * Preserve order of instances.
+ * </pre>
*
*
- <!-- options-end -->
- *
+ * <!-- options-end -->
+ *
* @author Mark Hall (mhall at cs.waikato.ac.nz)
* @author Eibe Frank (eibe at cs.waikato.ac.nz)
- * @version $Revision: 9758 $
+ * @version $Revision: 10537 $
* @see RandomizableClusterer
*/
-public class SimpleKMeans
- extends RandomizableClusterer
- implements NumberOfClustersRequestable, WeightedInstancesHandler {
+public class SimpleKMeans extends RandomizableClusterer implements
+ NumberOfClustersRequestable, WeightedInstancesHandler {
/** for serialization */
static final long serialVersionUID = -3235809600124455376L;
-
+
/**
* replace missing values in training instances
*/
@@ -112,19 +122,18 @@ public class SimpleKMeans
*/
private Instances m_ClusterStdDevs;
-
/**
- * For each cluster, holds the frequency counts for the values of each
- * nominal attribute
+ * For each cluster, holds the frequency counts for the values of each nominal
+ * attribute
*/
- private int [][][] m_ClusterNominalCounts;
+ private int[][][] m_ClusterNominalCounts;
private int[][] m_ClusterMissingCounts;
-
+
/**
- * Stats on the full data set for comparison purposes
- * In case the attribute is numeric the value is the mean if is
- * being used the Euclidian distance or the median if Manhattan distance
- * and if the attribute is nominal then it's mode is saved
+ * Stats on the full data set for comparison purposes In case the attribute is
+ * numeric the value is the mean if is being used the Euclidian distance or
+ * the median if Manhattan distance and if the attribute is nominal then it's
+ * mode is saved
*/
private double[] m_FullMeansOrMediansOrModes;
private double[] m_FullStdDevs;
@@ -144,7 +153,7 @@ public class SimpleKMeans
/**
* The number of instances in each cluster
*/
- private int [] m_ClusterSizes;
+ private int[] m_ClusterSizes;
/**
* Maximum number of iterations to be executed
@@ -159,35 +168,36 @@ public class SimpleKMeans
/**
* Holds the squared errors for all clusters
*/
- private double [] m_squaredErrors;
+ private double[] m_squaredErrors;
/** the distance function used. */
protected DistanceFunction m_DistanceFunction = new EuclideanDistance();
/**
- * Preserve order of instances
+ * Preserve order of instances
*/
private boolean m_PreserveOrder = false;
-
+
/**
* Assignments obtained
*/
protected int[] m_Assignments = null;
-
+
/**
* the default constructor
*/
public SimpleKMeans() {
super();
-
+
m_SeedDefault = 10;
setSeed(m_SeedDefault);
}
-
+
/**
* Returns a string describing this clusterer
- * @return a description of the evaluator suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return a description of the evaluator suitable for displaying in the
+ * explorer/experimenter gui
*/
public String globalInfo() {
return "Cluster data using the k means algorithm. Can use either "
@@ -198,9 +208,10 @@ public class SimpleKMeans
/**
* Returns default capabilities of the clusterer.
- *
- * @return the capabilities of this clusterer
+ *
+ * @return the capabilities of this clusterer
*/
+ @Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
result.disableAll();
@@ -215,13 +226,13 @@ public class SimpleKMeans
}
/**
- * Generates a clusterer. Has to initialize all fields of the clusterer
- * that are not being set via options.
- *
- * @param data set of instances serving as training data
- * @throws Exception if the clusterer has not been
- * generated successfully
+ * Generates a clusterer. Has to initialize all fields of the clusterer that
+ * are not being set via options.
+ *
+ * @param data set of instances serving as training data
+ * @throws Exception if the clusterer has not been generated successfully
*/
+ @Override
public void buildClusterer(Instances data) throws Exception {
// can clusterer handle the data?
@@ -231,7 +242,7 @@ public class SimpleKMeans
m_ReplaceMissingFilter = new ReplaceMissingValues();
Instances instances = new Instances(data);
-
+
instances.setClassIndex(-1);
if (!m_dontReplaceMissing) {
m_ReplaceMissingFilter.setInputFormat(instances);
@@ -243,7 +254,7 @@ public class SimpleKMeans
m_FullStdDevs = new double[instances.numAttributes()];
}
m_FullNominalCounts = new int[instances.numAttributes()][0];
-
+
m_FullMeansOrMediansOrModes = moveCentroid(0, instances, false);
for (int i = 0; i < instances.numAttributes(); i++) {
m_FullMissingCounts[i] = instances.attributeStats(i).missingCount;
@@ -256,206 +267,224 @@ public class SimpleKMeans
}
} else {
m_FullNominalCounts[i] = instances.attributeStats(i).nominalCounts;
- if (m_FullMissingCounts[i]
- > m_FullNominalCounts[i][Utils.maxIndex(m_FullNominalCounts[i])]) {
- m_FullMeansOrMediansOrModes[i] = -1; // mark missing as most common value
+ if (m_FullMissingCounts[i] > m_FullNominalCounts[i][Utils
+ .maxIndex(m_FullNominalCounts[i])]) {
+ m_FullMeansOrMediansOrModes[i] = -1; // mark missing as most common
+ // value
}
}
}
m_ClusterCentroids = new Instances(instances, m_NumClusters);
- int[] clusterAssignments = new int [instances.numInstances()];
+ int[] clusterAssignments = new int[instances.numInstances()];
- if(m_PreserveOrder)
+ if (m_PreserveOrder) {
m_Assignments = clusterAssignments;
-
+ }
+
m_DistanceFunction.setInstances(instances);
-
+
Random RandomO = new Random(getSeed());
int instIndex;
HashMap initC = new HashMap();
DecisionTableHashKey hk = null;
Instances initInstances = null;
- if(m_PreserveOrder)
+ if (m_PreserveOrder) {
initInstances = new Instances(instances);
- else
+ } else {
initInstances = instances;
-
+ }
+
for (int j = initInstances.numInstances() - 1; j >= 0; j--) {
- instIndex = RandomO.nextInt(j+1);
+ instIndex = RandomO.nextInt(j + 1);
hk = new DecisionTableHashKey(initInstances.instance(instIndex),
- initInstances.numAttributes(), true);
+ initInstances.numAttributes(), true);
if (!initC.containsKey(hk)) {
m_ClusterCentroids.add(initInstances.instance(instIndex));
- initC.put(hk, null);
+ initC.put(hk, null);
}
initInstances.swap(j, instIndex);
-
+
if (m_ClusterCentroids.numInstances() == m_NumClusters) {
- break;
+ break;
}
}
m_NumClusters = m_ClusterCentroids.numInstances();
-
- //removing reference
+
+ // removing reference
initInstances = null;
-
+
int i;
boolean converged = false;
int emptyClusterCount;
- Instances [] tempI = new Instances[m_NumClusters];
- m_squaredErrors = new double [m_NumClusters];
- m_ClusterNominalCounts = new int [m_NumClusters][instances.numAttributes()][0];
+ Instances[] tempI = new Instances[m_NumClusters];
+ m_squaredErrors = new double[m_NumClusters];
+ m_ClusterNominalCounts = new int[m_NumClusters][instances.numAttributes()][0];
m_ClusterMissingCounts = new int[m_NumClusters][instances.numAttributes()];
while (!converged) {
emptyClusterCount = 0;
m_Iterations++;
converged = true;
for (i = 0; i < instances.numInstances(); i++) {
- Instance toCluster = instances.instance(i);
- int newC = clusterProcessedInstance(toCluster, true);
- if (newC != clusterAssignments[i]) {
- converged = false;
- }
- clusterAssignments[i] = newC;
+ Instance toCluster = instances.instance(i);
+ int newC = clusterProcessedInstance(toCluster, true);
+ if (newC != clusterAssignments[i]) {
+ converged = false;
+ }
+ clusterAssignments[i] = newC;
}
-
+
// update centroids
m_ClusterCentroids = new Instances(instances, m_NumClusters);
for (i = 0; i < m_NumClusters; i++) {
- tempI[i] = new Instances(instances, 0);
+ tempI[i] = new Instances(instances, 0);
}
for (i = 0; i < instances.numInstances(); i++) {
- tempI[clusterAssignments[i]].add(instances.instance(i));
+ tempI[clusterAssignments[i]].add(instances.instance(i));
}
for (i = 0; i < m_NumClusters; i++) {
- if (tempI[i].numInstances() == 0) {
- // empty cluster
- emptyClusterCount++;
- } else {
- moveCentroid( i, tempI[i], true );
- }
+ if (tempI[i].numInstances() == 0) {
+ // empty cluster
+ emptyClusterCount++;
+ } else {
+ moveCentroid(i, tempI[i], true);
+ }
}
-
- if (m_Iterations == m_MaxIterations)
+
+ if (m_Iterations == m_MaxIterations) {
converged = true;
+ }
if (emptyClusterCount > 0) {
- m_NumClusters -= emptyClusterCount;
+ m_NumClusters -= emptyClusterCount;
if (converged) {
Instances[] t = new Instances[m_NumClusters];
int index = 0;
for (int k = 0; k < tempI.length; k++) {
if (tempI[k].numInstances() > 0) {
- t[index++] = tempI[k];
+ t[index] = tempI[k];
+
+ for (i = 0; i < tempI[k].numAttributes(); i++) {
+ m_ClusterNominalCounts[index][i] = m_ClusterNominalCounts[k][i];
+ }
+ index++;
}
}
tempI = t;
} else {
tempI = new Instances[m_NumClusters];
}
- }
-
+ }
+
if (!converged) {
- m_squaredErrors = new double [m_NumClusters];
- m_ClusterNominalCounts = new int [m_NumClusters][instances.numAttributes()][0];
+ m_squaredErrors = new double[m_NumClusters];
+ m_ClusterNominalCounts = new int[m_NumClusters][instances
+ .numAttributes()][0];
}
}
-
+
if (m_displayStdDevs) {
m_ClusterStdDevs = new Instances(instances, m_NumClusters);
}
- m_ClusterSizes = new int [m_NumClusters];
+ m_ClusterSizes = new int[m_NumClusters];
for (i = 0; i < m_NumClusters; i++) {
if (m_displayStdDevs) {
- double [] vals2 = new double[instances.numAttributes()];
+ double[] vals2 = new double[instances.numAttributes()];
for (int j = 0; j < instances.numAttributes(); j++) {
if (instances.attribute(j).isNumeric()) {
vals2[j] = Math.sqrt(tempI[i].variance(j));
} else {
vals2[j] = Instance.missingValue();
- }
- }
+ }
+ }
m_ClusterStdDevs.add(new Instance(1.0, vals2));
}
m_ClusterSizes[i] = tempI[i].numInstances();
}
+
+ // Save memory!!
+ m_DistanceFunction.clean();
}
/**
- * Move the centroid to it's new coordinates. Generate the centroid coordinates based
- * on it's members (objects assigned to the cluster of the centroid) and the distance
- * function being used.
- * @param centroidIndex index of the centroid which the coordinates will be computed
- * @param members the objects that are assigned to the cluster of this centroid
- * @param updateClusterInfo if the method is supposed to update the m_Cluster arrays
+ * Move the centroid to it's new coordinates. Generate the centroid
+ * coordinates based on it's members (objects assigned to the cluster of the
+ * centroid) and the distance function being used.
+ *
+ * @param centroidIndex index of the centroid which the coordinates will be
+ * computed
+ * @param members the objects that are assigned to the cluster of this
+ * centroid
+ * @param updateClusterInfo if the method is supposed to update the m_Cluster
+ * arrays
* @return the centroid coordinates
*/
- protected double[] moveCentroid(int centroidIndex, Instances members, boolean updateClusterInfo){
- double [] vals = new double[members.numAttributes()];
-
- //used only for Manhattan Distance
+ protected double[] moveCentroid(int centroidIndex, Instances members,
+ boolean updateClusterInfo) {
+ double[] vals = new double[members.numAttributes()];
+
+ // used only for Manhattan Distance
Instances sortedMembers = null;
int middle = 0;
boolean dataIsEven = false;
-
- if(m_DistanceFunction instanceof ManhattanDistance){
- middle = (members.numInstances()-1)/2;
- dataIsEven = ((members.numInstances()%2)==0);
- if(m_PreserveOrder){
+
+ if (m_DistanceFunction instanceof ManhattanDistance) {
+ middle = (members.numInstances() - 1) / 2;
+ dataIsEven = ((members.numInstances() % 2) == 0);
+ if (m_PreserveOrder) {
sortedMembers = members;
- }else{
+ } else {
sortedMembers = new Instances(members);
}
}
-
- for (int j = 0; j < members.numAttributes(); j++) {
-
- //in case of Euclidian distance the centroid is the mean point
- //in case of Manhattan distance the centroid is the median point
- //in both cases, if the attribute is nominal, the centroid is the mode
- if(m_DistanceFunction instanceof EuclideanDistance ||
- members.attribute(j).isNominal())
- {
- vals[j] = members.meanOrMode(j);
- }else if(m_DistanceFunction instanceof ManhattanDistance){
- //singleton special case
- if(members.numInstances() == 1){
+
+ for (int j = 0; j < members.numAttributes(); j++) {
+
+ // in case of Euclidian distance the centroid is the mean point
+ // in case of Manhattan distance the centroid is the median point
+ // in both cases, if the attribute is nominal, the centroid is the mode
+ if (m_DistanceFunction instanceof EuclideanDistance
+ || members.attribute(j).isNominal()) {
+ vals[j] = members.meanOrMode(j);
+ } else if (m_DistanceFunction instanceof ManhattanDistance) {
+ // singleton special case
+ if (members.numInstances() == 1) {
vals[j] = members.instance(0).value(j);
- }else{
+ } else {
vals[j] = sortedMembers.kthSmallestValue(j, middle + 1);
if (dataIsEven) {
vals[j] = (vals[j] + sortedMembers.kthSmallestValue(j, middle + 2)) / 2;
}
}
- }
-
- if(updateClusterInfo){
+ }
+
+ if (updateClusterInfo) {
m_ClusterMissingCounts[centroidIndex][j] = members.attributeStats(j).missingCount;
m_ClusterNominalCounts[centroidIndex][j] = members.attributeStats(j).nominalCounts;
if (members.attribute(j).isNominal()) {
- if (m_ClusterMissingCounts[centroidIndex][j] >
- m_ClusterNominalCounts[centroidIndex][j][Utils.maxIndex(m_ClusterNominalCounts[centroidIndex][j])])
- {
- vals[j] = Instance.missingValue(); // mark mode as missing
- }
+ if (m_ClusterMissingCounts[centroidIndex][j] > m_ClusterNominalCounts[centroidIndex][j][Utils
+ .maxIndex(m_ClusterNominalCounts[centroidIndex][j])]) {
+ vals[j] = Instance.missingValue(); // mark mode as missing
+ }
} else {
- if (m_ClusterMissingCounts[centroidIndex][j] == members.numInstances()) {
+ if (m_ClusterMissingCounts[centroidIndex][j] == members
+ .numInstances()) {
vals[j] = Instance.missingValue(); // mark mean as missing
}
}
}
}
- if(updateClusterInfo)
+ if (updateClusterInfo) {
m_ClusterCentroids.add(new Instance(1.0, vals));
+ }
return vals;
}
-
+
/**
* clusters an instance that has been through the filters
- *
+ *
* @param instance the instance to assign a cluster to
* @param updateErrors if true, update the within clusters sum of errors
* @return a cluster number
@@ -464,15 +493,16 @@ public class SimpleKMeans
double minDist = Integer.MAX_VALUE;
int bestCluster = 0;
for (int i = 0; i < m_NumClusters; i++) {
- double dist = m_DistanceFunction.distance(instance, m_ClusterCentroids.instance(i));
+ double dist = m_DistanceFunction.distance(instance,
+ m_ClusterCentroids.instance(i));
if (dist < minDist) {
- minDist = dist;
- bestCluster = i;
+ minDist = dist;
+ bestCluster = i;
}
}
if (updateErrors) {
- if(m_DistanceFunction instanceof EuclideanDistance){
- //Euclidean distance to Squared Euclidean distance
+ if (m_DistanceFunction instanceof EuclideanDistance) {
+ // Euclidean distance to Squared Euclidean distance
minDist *= minDist;
}
m_squaredErrors[bestCluster] += minDist;
@@ -482,13 +512,13 @@ public class SimpleKMeans
/**
* Classifies a given instance.
- *
+ *
* @param instance the instance to be assigned to a cluster
- * @return the number of the assigned cluster as an interger
- * if the class is enumerated, otherwise the predicted value
- * @throws Exception if instance could not be classified
- * successfully
+ * @return the number of the assigned cluster as an interger if the class is
+ * enumerated, otherwise the predicted value
+ * @throws Exception if instance could not be classified successfully
*/
+ @Override
public int clusterInstance(Instance instance) throws Exception {
Instance inst = null;
if (!m_dontReplaceMissing) {
@@ -504,58 +534,54 @@ public class SimpleKMeans
/**
* Returns the number of clusters.
- *
+ *
* @return the number of clusters generated for a training dataset.
- * @throws Exception if number of clusters could not be returned
- * successfully
+ * @throws Exception if number of clusters could not be returned successfully
*/
+ @Override
public int numberOfClusters() throws Exception {
return m_NumClusters;
}
/**
* Returns an enumeration describing the available options.
- *
+ *
* @return an enumeration of all the available options.
*/
- public Enumeration listOptions () {
+ @Override
+ public Enumeration listOptions() {
Vector result = new Vector();
+ result.addElement(new Option("\tnumber of clusters.\n" + "\t(default 2).",
+ "N", 1, "-N <num>"));
+ result.addElement(new Option("\tDisplay std. deviations for centroids.\n",
+ "V", 0, "-V"));
result.addElement(new Option(
- "\tnumber of clusters.\n"
- + "\t(default 2).",
- "N", 1, "-N <num>"));
- result.addElement(new Option(
- "\tDisplay std. deviations for centroids.\n",
- "V", 0, "-V"));
- result.addElement(new Option(
- "\tDon't replace missing values with mean/mode.\n",
- "M", 0, "-M"));
-
- result.add(new Option(
- "\tDistance function to use.\n"
- + "\t(default: weka.core.EuclideanDistance)",
- "A", 1,"-A <classname and options>"));
-
- result.add(new Option(
- "\tMaximum number of iterations.\n",
- "I",1,"-I <num>"));
+ "\tDon't replace missing values with mean/mode.\n", "M", 0, "-M"));
+
+ result.add(new Option("\tDistance function to use.\n"
+ + "\t(default: weka.core.EuclideanDistance)", "A", 1,
+ "-A <classname and options>"));
+
+ result.add(new Option("\tMaximum number of iterations.\n", "I", 1,
+ "-I <num>"));
+
+ result.addElement(new Option("\tPreserve order of instances.\n", "O", 0,
+ "-O"));
- result.addElement(new Option(
- "\tPreserve order of instances.\n",
- "O", 0, "-O"));
-
Enumeration en = super.listOptions();
- while (en.hasMoreElements())
+ while (en.hasMoreElements()) {
result.addElement(en.nextElement());
+ }
- return result.elements();
+ return result.elements();
}
/**
* Returns the tip text for this property
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String numClustersTipText() {
return "set number of clusters";
@@ -563,10 +589,11 @@ public class SimpleKMeans
/**
* set the number of clusters to generate
- *
+ *
* @param n the number of clusters to generate
* @throws Exception if number of clusters is negative
*/
+ @Override
public void setNumClusters(int n) throws Exception {
if (n <= 0) {
throw new Exception("Number of clusters must be > 0");
@@ -576,7 +603,7 @@ public class SimpleKMeans
/**
* gets the number of clusters to generate
- *
+ *
* @return the number of clusters to generate
*/
public int getNumClusters() {
@@ -585,8 +612,9 @@ public class SimpleKMeans
/**
* Returns the tip text for this property
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String maxIterationsTipText() {
return "set maximum number of iterations";
@@ -594,7 +622,7 @@ public class SimpleKMeans
/**
* set the maximum number of iterations to be executed
- *
+ *
* @param n the maximum number of iterations
* @throws Exception if maximum number of iteration is smaller than 1
*/
@@ -607,18 +635,18 @@ public class SimpleKMeans
/**
* gets the number of maximum iterations to be executed
- *
+ *
* @return the number of clusters to generate
*/
public int getMaxIterations() {
return m_MaxIterations;
}
-
/**
* Returns the tip text for this property
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String displayStdDevsTipText() {
return "Display std deviations of numeric attributes "
@@ -626,22 +654,20 @@ public class SimpleKMeans
}
/**
- * Sets whether standard deviations and nominal count
- * Should be displayed in the clustering output
- *
- * @param stdD true if std. devs and counts should be
- * displayed
+ * Sets whether standard deviations and nominal count Should be displayed in
+ * the clustering output
+ *
+ * @param stdD true if std. devs and counts should be displayed
*/
public void setDisplayStdDevs(boolean stdD) {
m_displayStdDevs = stdD;
}
/**
- * Gets whether standard deviations and nominal count
- * Should be displayed in the clustering output
- *
- * @return true if std. devs and counts should be
- * displayed
+ * Gets whether standard deviations and nominal count Should be displayed in
+ * the clustering output
+ *
+ * @return true if std. devs and counts should be displayed
*/
public boolean getDisplayStdDevs() {
return m_displayStdDevs;
@@ -649,8 +675,9 @@ public class SimpleKMeans
/**
* Returns the tip text for this property
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String dontReplaceMissingValuesTipText() {
return "Replace missing values globally with mean/mode.";
@@ -658,9 +685,8 @@ public class SimpleKMeans
/**
* Sets whether missing values are to be replaced
- *
- * @param r true if missing values are to be
- * replaced
+ *
+ * @param r true if missing values are to be replaced
*/
public void setDontReplaceMissingValues(boolean r) {
m_dontReplaceMissing = r;
@@ -668,9 +694,8 @@ public class SimpleKMeans
/**
* Gets whether missing values are to be replaced
- *
- * @return true if missing values are to be
- * replaced
+ *
+ * @return true if missing values are to be replaced
*/
public boolean getDontReplaceMissingValues() {
return m_dontReplaceMissing;
@@ -679,12 +704,12 @@ public class SimpleKMeans
/**
* Returns the tip text for this property.
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String distanceFunctionTipText() {
- return "The distance function to use for instances comparison " +
- "(default: weka.core.EuclideanDistance). ";
+ return "The distance function to use for instances comparison "
+ + "(default: weka.core.EuclideanDistance). ";
}
/**
@@ -703,18 +728,19 @@ public class SimpleKMeans
* @throws Exception if instances cannot be processed
*/
public void setDistanceFunction(DistanceFunction df) throws Exception {
- if(!(df instanceof EuclideanDistance) &&
- !(df instanceof ManhattanDistance))
- {
- throw new Exception("SimpleKMeans currently only supports the Euclidean and Manhattan distances.");
- }
+ if (!(df instanceof EuclideanDistance)
+ && !(df instanceof ManhattanDistance)) {
+ throw new Exception(
+ "SimpleKMeans currently only supports the Euclidean and Manhattan distances.");
+ }
m_DistanceFunction = df;
- }
+ }
/**
* Returns the tip text for this property
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String preserveInstancesOrderTipText() {
return "Preserve order of instances.";
@@ -722,9 +748,8 @@ public class SimpleKMeans
/**
* Sets whether order of instances must be preserved
- *
- * @param r true if missing values are to be
- * replaced
+ *
+ * @param r true if missing values are to be replaced
*/
public void setPreserveInstancesOrder(boolean r) {
m_PreserveOrder = r;
@@ -732,55 +757,65 @@ public class SimpleKMeans
/**
* Gets whether order of instances must be preserved
- *
- * @return true if missing values are to be
- * replaced
+ *
+ * @return true if missing values are to be replaced
*/
public boolean getPreserveInstancesOrder() {
return m_PreserveOrder;
}
-
-
+
/**
- * Parses a given list of options. <p/>
+ * Parses a given list of options.
+ * <p/>
*
- <!-- options-start -->
- * Valid options are: <p/>
+ * <!-- options-start --> Valid options are:
+ * <p/>
*
- * <pre> -N <num>
+ * <pre>
+ * -N <num>
* number of clusters.
- * (default 2).</pre>
+ * (default 2).
+ * </pre>
*
- * <pre> -V
+ * <pre>
+ * -V
* Display std. deviations for centroids.
* </pre>
*
- * <pre> -M
+ * <pre>
+ * -M
* Replace missing values with mean/mode.
* </pre>
*
- * <pre> -S <num>
+ * <pre>
+ * -S <num>
* Random number seed.
- * (default 10)</pre>
+ * (default 10)
+ * </pre>
*
- * <pre> -A <classname and options>
+ * <pre>
+ * -A <classname and options>
* Distance function to be used for instance comparison
- * (default weka.core.EuclidianDistance)</pre>
+ * (default weka.core.EuclidianDistance)
+ * </pre>
*
- * <pre> -I <num>
- * Maximum number of iterations. </pre>
- *
- * <pre> -O
+ * <pre>
+ * -I <num>
+ * Maximum number of iterations.
+ * </pre>
+ *
+ * <pre>
+ * -O
* Preserve order of instances.
* </pre>
*
- <!-- options-end -->
- *
+ * <!-- options-end -->
+ *
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
- public void setOptions (String[] options)
- throws Exception {
+ @Override
+ public void setOptions(String[] options) throws Exception {
m_displayStdDevs = Utils.getFlag("V", options);
m_dontReplaceMissing = Utils.getFlag("M", options);
@@ -790,29 +825,27 @@ public class SimpleKMeans
if (optionString.length() != 0) {
setNumClusters(Integer.parseInt(optionString));
}
-
+
optionString = Utils.getOption("I", options);
if (optionString.length() != 0) {
setMaxIterations(Integer.parseInt(optionString));
}
-
+
String distFunctionClass = Utils.getOption('A', options);
- if(distFunctionClass.length() != 0) {
+ if (distFunctionClass.length() != 0) {
String distFunctionClassSpec[] = Utils.splitOptions(distFunctionClass);
- if(distFunctionClassSpec.length == 0) {
- throw new Exception("Invalid DistanceFunction specification string.");
+ if (distFunctionClassSpec.length == 0) {
+ throw new Exception("Invalid DistanceFunction specification string.");
}
String className = distFunctionClassSpec[0];
distFunctionClassSpec[0] = "";
- setDistanceFunction( (DistanceFunction)
- Utils.forName( DistanceFunction.class,
- className, distFunctionClassSpec) );
- }
- else {
+ setDistanceFunction((DistanceFunction) Utils.forName(
+ DistanceFunction.class, className, distFunctionClassSpec));
+ } else {
setDistanceFunction(new EuclideanDistance());
}
-
+
m_PreserveOrder = Utils.getFlag("O", options);
super.setOptions(options);
@@ -820,13 +853,14 @@ public class SimpleKMeans
/**
* Gets the current settings of SimpleKMeans
- *
+ *
* @return an array of strings suitable for passing to setOptions()
*/
- public String[] getOptions () {
- int i;
- Vector result;
- String[] options;
+ @Override
+ public String[] getOptions() {
+ int i;
+ Vector result;
+ String[] options;
result = new Vector();
@@ -842,28 +876,30 @@ public class SimpleKMeans
result.add("" + getNumClusters());
result.add("-A");
- result.add((m_DistanceFunction.getClass().getName() + " " +
- Utils.joinOptions(m_DistanceFunction.getOptions())).trim());
-
+ result.add((m_DistanceFunction.getClass().getName() + " " + Utils
+ .joinOptions(m_DistanceFunction.getOptions())).trim());
+
result.add("-I");
- result.add(""+ getMaxIterations());
+ result.add("" + getMaxIterations());
- if(m_PreserveOrder){
+ if (m_PreserveOrder) {
result.add("-O");
}
-
+
options = super.getOptions();
- for (i = 0; i < options.length; i++)
+ for (i = 0; i < options.length; i++) {
result.add(options[i]);
+ }
- return (String[]) result.toArray(new String[result.size()]);
+ return (String[]) result.toArray(new String[result.size()]);
}
/**
* return a string describing this clusterer
- *
+ *
* @return a description of the clusterer as a string
*/
+ @Override
public String toString() {
if (m_ClusterCentroids == null) {
return "No clusterer built yet!";
@@ -873,24 +909,24 @@ public class SimpleKMeans
int maxAttWidth = 0;
boolean containsNumeric = false;
for (int i = 0; i < m_NumClusters; i++) {
- for (int j = 0 ;j < m_ClusterCentroids.numAttributes(); j++) {
+ for (int j = 0; j < m_ClusterCentroids.numAttributes(); j++) {
if (m_ClusterCentroids.attribute(j).name().length() > maxAttWidth) {
maxAttWidth = m_ClusterCentroids.attribute(j).name().length();
}
- if (m_ClusterCentroids.attribute(j).isNumeric()) {
+ if (m_ClusterCentroids.attribute(j).isNumeric()) {
containsNumeric = true;
- double width = Math.log(Math.abs(m_ClusterCentroids.instance(i).value(j))) /
- Math.log(10.0);
- // System.err.println(m_ClusterCentroids.instance(i).value(j)+" "+width);
+ double width = Math.log(Math.abs(m_ClusterCentroids.instance(i)
+ .value(j))) / Math.log(10.0);
+ // System.err.println(m_ClusterCentroids.instance(i).value(j)+" "+width);
if (width < 0) {
width = 1;
}
// decimal + # decimal places + 1
- width += 6.0;
- if ((int)width > maxWidth) {
- maxWidth = (int)width;
- }
- }
+ width += 6.0;
+ if ((int) width > maxWidth) {
+ maxWidth = (int) width;
+ }
+ }
}
}
@@ -898,7 +934,7 @@ public class SimpleKMeans
if (m_ClusterCentroids.attribute(i).isNominal()) {
Attribute a = m_ClusterCentroids.attribute(i);
for (int j = 0; j < m_ClusterCentroids.numInstances(); j++) {
- String val = a.value((int)m_ClusterCentroids.instance(j).value(i));
+ String val = a.value((int) m_ClusterCentroids.instance(j).value(i));
if (val.length() > maxWidth) {
maxWidth = val.length();
}
@@ -917,11 +953,13 @@ public class SimpleKMeans
for (int i = 0; i < m_ClusterCentroids.numAttributes(); i++) {
if (m_ClusterCentroids.attribute(i).isNominal()) {
int maxV = Utils.maxIndex(m_FullNominalCounts[i]);
- /* int percent = (int)((double)m_FullNominalCounts[i][maxV] /
- Utils.sum(m_ClusterSizes) * 100.0); */
+ /*
+ * int percent = (int)((double)m_FullNominalCounts[i][maxV] /
+ * Utils.sum(m_ClusterSizes) * 100.0);
+ */
int percent = 6; // max percent width (100%)
String nomV = "" + m_FullNominalCounts[i][maxV];
- // + " (" + percent + "%)";
+ // + " (" + percent + "%)";
if (nomV.length() + percent > maxWidth) {
maxWidth = nomV.length() + 1;
}
@@ -930,17 +968,17 @@ public class SimpleKMeans
}
// check for size of cluster sizes
- for (int i = 0; i < m_ClusterSizes.length; i++) {
- String size = "(" + m_ClusterSizes[i] + ")";
+ for (int m_ClusterSize : m_ClusterSizes) {
+ String size = "(" + m_ClusterSize + ")";
if (size.length() > maxWidth) {
maxWidth = size.length();
}
}
-
+
if (m_displayStdDevs && maxAttWidth < "missing".length()) {
maxAttWidth = "missing".length();
}
-
+
String plusMinus = "+/-";
maxAttWidth += 2;
if (m_displayStdDevs && containsNumeric) {
@@ -958,37 +996,37 @@ public class SimpleKMeans
maxWidth = "missing".length() + 1;
}
-
-
StringBuffer temp = new StringBuffer();
- // String naString = "N/A";
+ // String naString = "N/A";
-
- /* for (int i = 0; i < maxWidth+2; i++) {
- naString += " ";
- } */
+ /*
+ * for (int i = 0; i < maxWidth+2; i++) { naString += " "; }
+ */
temp.append("\nkMeans\n======\n");
- temp.append("\nNumber of iterations: " + m_Iterations+"\n");
-
- if(m_DistanceFunction instanceof EuclideanDistance){
- temp.append("Within cluster sum of squared errors: " + Utils.sum(m_squaredErrors));
- }else{
- temp.append("Sum of within cluster distances: " + Utils.sum(m_squaredErrors));
+ temp.append("\nNumber of iterations: " + m_Iterations + "\n");
+
+ if (m_DistanceFunction instanceof EuclideanDistance) {
+ temp.append("Within cluster sum of squared errors: "
+ + Utils.sum(m_squaredErrors));
+ } else {
+ temp.append("Sum of within cluster distances: "
+ + Utils.sum(m_squaredErrors));
}
-
-
+
if (!m_dontReplaceMissing) {
temp.append("\nMissing values globally replaced with mean/mode");
}
temp.append("\n\nCluster centroids:\n");
- temp.append(pad("Cluster#", " ", (maxAttWidth + (maxWidth * 2 + 2)) - "Cluster#".length(), true));
+ temp.append(pad("Cluster#", " ", (maxAttWidth + (maxWidth * 2 + 2))
+ - "Cluster#".length(), true));
temp.append("\n");
- temp.append(pad("Attribute", " ", maxAttWidth - "Attribute".length(), false));
+ temp
+ .append(pad("Attribute", " ", maxAttWidth - "Attribute".length(), false));
-
- temp.append(pad("Full Data", " ", maxWidth + 1 - "Full Data".length(), true));
+ temp
+ .append(pad("Full Data", " ", maxWidth + 1 - "Full Data".length(), true));
// cluster numbers
for (int i = 0; i < m_NumClusters; i++) {
@@ -999,16 +1037,18 @@ public class SimpleKMeans
// cluster sizes
String cSize = "(" + Utils.sum(m_ClusterSizes) + ")";
- temp.append(pad(cSize, " ", maxAttWidth + maxWidth + 1 - cSize.length(), true));
+ temp.append(pad(cSize, " ", maxAttWidth + maxWidth + 1 - cSize.length(),
+ true));
for (int i = 0; i < m_NumClusters; i++) {
cSize = "(" + m_ClusterSizes[i] + ")";
- temp.append(pad(cSize, " ",maxWidth + 1 - cSize.length(), true));
+ temp.append(pad(cSize, " ", maxWidth + 1 - cSize.length(), true));
}
temp.append("\n");
- temp.append(pad("", "=", maxAttWidth +
- (maxWidth * (m_ClusterCentroids.numInstances()+1)
- + m_ClusterCentroids.numInstances() + 1), true));
+ temp.append(pad("", "=",
+ maxAttWidth
+ + (maxWidth * (m_ClusterCentroids.numInstances() + 1)
+ + m_ClusterCentroids.numInstances() + 1), true));
temp.append("\n");
for (int i = 0; i < m_ClusterCentroids.numAttributes(); i++) {
@@ -1023,19 +1063,22 @@ public class SimpleKMeans
// full data
if (m_ClusterCentroids.attribute(i).isNominal()) {
if (m_FullMeansOrMediansOrModes[i] == -1) { // missing
- valMeanMode = pad("missing", " ", maxWidth + 1 - "missing".length(), true);
+ valMeanMode = pad("missing", " ", maxWidth + 1 - "missing".length(),
+ true);
} else {
- valMeanMode =
- pad((strVal = m_ClusterCentroids.attribute(i).value((int)m_FullMeansOrMediansOrModes[i])),
- " ", maxWidth + 1 - strVal.length(), true);
+ valMeanMode = pad(
+ (strVal = m_ClusterCentroids.attribute(i).value(
+ (int) m_FullMeansOrMediansOrModes[i])), " ", maxWidth + 1
+ - strVal.length(), true);
}
} else {
if (Double.isNaN(m_FullMeansOrMediansOrModes[i])) {
- valMeanMode = pad("missing", " ", maxWidth + 1 - "missing".length(), true);
+ valMeanMode = pad("missing", " ", maxWidth + 1 - "missing".length(),
+ true);
} else {
- valMeanMode = pad((strVal = Utils.doubleToString(m_FullMeansOrMediansOrModes[i],
- maxWidth,4).trim()),
- " ", maxWidth + 1 - strVal.length(), true);
+ valMeanMode = pad(
+ (strVal = Utils.doubleToString(m_FullMeansOrMediansOrModes[i],
+ maxWidth, 4).trim()), " ", maxWidth + 1 - strVal.length(), true);
}
}
temp.append(valMeanMode);
@@ -1043,19 +1086,23 @@ public class SimpleKMeans
for (int j = 0; j < m_NumClusters; j++) {
if (m_ClusterCentroids.attribute(i).isNominal()) {
if (m_ClusterCentroids.instance(j).isMissing(i)) {
- valMeanMode = pad("missing", " ", maxWidth + 1 - "missing".length(), true);
+ valMeanMode = pad("missing", " ",
+ maxWidth + 1 - "missing".length(), true);
} else {
- valMeanMode =
- pad((strVal = m_ClusterCentroids.attribute(i).value((int)m_ClusterCentroids.instance(j).value(i))),
- " ", maxWidth + 1 - strVal.length(), true);
+ valMeanMode = pad(
+ (strVal = m_ClusterCentroids.attribute(i).value(
+ (int) m_ClusterCentroids.instance(j).value(i))), " ", maxWidth
+ + 1 - strVal.length(), true);
}
} else {
if (m_ClusterCentroids.instance(j).isMissing(i)) {
- valMeanMode = pad("missing", " ", maxWidth + 1 - "missing".length(), true);
+ valMeanMode = pad("missing", " ",
+ maxWidth + 1 - "missing".length(), true);
} else {
- valMeanMode = pad((strVal = Utils.doubleToString(m_ClusterCentroids.instance(j).value(i),
- maxWidth,4).trim()),
- " ", maxWidth + 1 - strVal.length(), true);
+ valMeanMode = pad(
+ (strVal = Utils.doubleToString(
+ m_ClusterCentroids.instance(j).value(i), maxWidth, 4).trim()),
+ " ", maxWidth + 1 - strVal.length(), true);
}
}
temp.append(valMeanMode);
@@ -1074,25 +1121,25 @@ public class SimpleKMeans
String val = " " + a.value(j);
temp.append(pad(val, " ", maxAttWidth + 1 - val.length(), false));
int count = m_FullNominalCounts[i][j];
- int percent = (int)((double)m_FullNominalCounts[i][j] /
- Utils.sum(m_ClusterSizes) * 100.0);
+ int percent = (int) ((double) m_FullNominalCounts[i][j]
+ / Utils.sum(m_ClusterSizes) * 100.0);
String percentS = "" + percent + "%)";
percentS = pad(percentS, " ", 5 - percentS.length(), true);
stdDevVal = "" + count + " (" + percentS;
- stdDevVal =
- pad(stdDevVal, " ", maxWidth + 1 - stdDevVal.length(), true);
+ stdDevVal = pad(stdDevVal, " ", maxWidth + 1 - stdDevVal.length(),
+ true);
temp.append(stdDevVal);
// Clusters
for (int k = 0; k < m_NumClusters; k++) {
count = m_ClusterNominalCounts[k][i][j];
- percent = (int)((double)m_ClusterNominalCounts[k][i][j] /
- m_ClusterSizes[k] * 100.0);
+ percent = (int) ((double) m_ClusterNominalCounts[k][i][j]
+ / m_ClusterSizes[k] * 100.0);
percentS = "" + percent + "%)";
percentS = pad(percentS, " ", 5 - percentS.length(), true);
stdDevVal = "" + count + " (" + percentS;
- stdDevVal =
- pad(stdDevVal, " ", maxWidth + 1 - stdDevVal.length(), true);
+ stdDevVal = pad(stdDevVal, " ",
+ maxWidth + 1 - stdDevVal.length(), true);
temp.append(stdDevVal);
}
temp.append("\n");
@@ -1100,27 +1147,28 @@ public class SimpleKMeans
// missing (if any)
if (m_FullMissingCounts[i] > 0) {
// Full data
- temp.append(pad(" missing", " ", maxAttWidth + 1 - " missing".length(), false));
+ temp.append(pad(" missing", " ",
+ maxAttWidth + 1 - " missing".length(), false));
int count = m_FullMissingCounts[i];
- int percent = (int)((double)m_FullMissingCounts[i] /
- Utils.sum(m_ClusterSizes) * 100.0);
+ int percent = (int) ((double) m_FullMissingCounts[i]
+ / Utils.sum(m_ClusterSizes) * 100.0);
String percentS = "" + percent + "%)";
percentS = pad(percentS, " ", 5 - percentS.length(), true);
stdDevVal = "" + count + " (" + percentS;
- stdDevVal =
- pad(stdDevVal, " ", maxWidth + 1 - stdDevVal.length(), true);
+ stdDevVal = pad(stdDevVal, " ", maxWidth + 1 - stdDevVal.length(),
+ true);
temp.append(stdDevVal);
-
+
// Clusters
for (int k = 0; k < m_NumClusters; k++) {
count = m_ClusterMissingCounts[k][i];
- percent = (int)((double)m_ClusterMissingCounts[k][i] /
- m_ClusterSizes[k] * 100.0);
+ percent = (int) ((double) m_ClusterMissingCounts[k][i]
+ / m_ClusterSizes[k] * 100.0);
percentS = "" + percent + "%)";
percentS = pad(percentS, " ", 5 - percentS.length(), true);
stdDevVal = "" + count + " (" + percentS;
- stdDevVal =
- pad(stdDevVal, " ", maxWidth + 1 - stdDevVal.length(), true);
+ stdDevVal = pad(stdDevVal, " ",
+ maxWidth + 1 - stdDevVal.length(), true);
temp.append(stdDevVal);
}
@@ -1133,10 +1181,10 @@ public class SimpleKMeans
if (Double.isNaN(m_FullMeansOrMediansOrModes[i])) {
stdDevVal = pad("--", " ", maxAttWidth + maxWidth + 1 - 2, true);
} else {
- stdDevVal = pad((strVal = plusMinus
- + Utils.doubleToString(m_FullStdDevs[i],
- maxWidth,4).trim()),
- " ", maxWidth + maxAttWidth + 1 - strVal.length(), true);
+ stdDevVal = pad(
+ (strVal = plusMinus
+ + Utils.doubleToString(m_FullStdDevs[i], maxWidth, 4).trim()),
+ " ", maxWidth + maxAttWidth + 1 - strVal.length(), true);
}
temp.append(stdDevVal);
@@ -1145,11 +1193,11 @@ public class SimpleKMeans
if (m_ClusterCentroids.instance(j).isMissing(i)) {
stdDevVal = pad("--", " ", maxWidth + 1 - 2, true);
} else {
- stdDevVal =
- pad((strVal = plusMinus
- + Utils.doubleToString(m_ClusterStdDevs.instance(j).value(i),
- maxWidth,4).trim()),
- " ", maxWidth + 1 - strVal.length(), true);
+ stdDevVal = pad(
+ (strVal = plusMinus
+ + Utils.doubleToString(m_ClusterStdDevs.instance(j).value(i),
+ maxWidth, 4).trim()), " ", maxWidth + 1 - strVal.length(),
+ true);
}
temp.append(stdDevVal);
}
@@ -1162,18 +1210,17 @@ public class SimpleKMeans
return temp.toString();
}
- private String pad(String source, String padChar,
- int length, boolean leftPad) {
+ private String pad(String source, String padChar, int length, boolean leftPad) {
StringBuffer temp = new StringBuffer();
if (leftPad) {
- for (int i = 0; i< length; i++) {
+ for (int i = 0; i < length; i++) {
temp.append(padChar);
}
temp.append(source);
} else {
temp.append(source);
- for (int i = 0; i< length; i++) {
+ for (int i = 0; i < length; i++) {
temp.append(padChar);
}
}
@@ -1183,7 +1230,7 @@ public class SimpleKMeans
/**
* Gets the the cluster centroids
*
- * @return the cluster centroids
+ * @return the cluster centroids
*/
public Instances getClusterCentroids() {
return m_ClusterCentroids;
@@ -1192,27 +1239,26 @@ public class SimpleKMeans
/**
* Gets the standard deviations of the numeric attributes in each cluster
*
- * @return the standard deviations of the numeric attributes
- * in each cluster
+ * @return the standard deviations of the numeric attributes in each cluster
*/
public Instances getClusterStandardDevs() {
return m_ClusterStdDevs;
}
/**
- * Returns for each cluster the frequency counts for the values of each
+ * Returns for each cluster the frequency counts for the values of each
* nominal attribute
*
- * @return the counts
+ * @return the counts
*/
- public int [][][] getClusterNominalCounts() {
+ public int[][][] getClusterNominalCounts() {
return m_ClusterNominalCounts;
}
/**
* Gets the squared error for all clusters
*
- * @return the squared error
+ * @return the squared error
*/
public double getSquaredError() {
return Utils.sum(m_squaredErrors);
@@ -1221,44 +1267,48 @@ public class SimpleKMeans
/**
* Gets the number of instances in each cluster
*
- * @return The number of instances in each cluster
+ * @return The number of instances in each cluster
*/
- public int [] getClusterSizes() {
+ public int[] getClusterSizes() {
return m_ClusterSizes;
}
-
+
/**
* Gets the assignments for each instance
+ *
* @return Array of indexes of the centroid assigned to each instance
- * @throws Exception if order of instances wasn't preserved or no assignments were made
+ * @throws Exception if order of instances wasn't preserved or no assignments
+ * were made
*/
- public int [] getAssignments() throws Exception{
- if(!m_PreserveOrder){
- throw new Exception("The assignments are only available when order of instances is preserved (-O)");
+ public int[] getAssignments() throws Exception {
+ if (!m_PreserveOrder) {
+ throw new Exception(
+ "The assignments are only available when order of instances is preserved (-O)");
}
- if(m_Assignments == null){
+ if (m_Assignments == null) {
throw new Exception("No assignments made.");
}
return m_Assignments;
}
-
+
/**
* Returns the revision string.
*
- * @return the revision
+ * @return the revision
*/
+ @Override
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9758 $");
+ return RevisionUtils.extract("$Revision: 10537 $");
}
/**
* Main method for testing this class.
- *
- * @param argv should contain the following arguments: <p>
- * -t training file [-N number of clusters]
+ *
+ * @param argv should contain the following arguments:
+ * <p>
+ * -t training file [-N number of clusters]
*/
- public static void main (String[] argv) {
+ public static void main(String[] argv) {
runClusterer(new SimpleKMeans(), argv);
}
}
-
diff --git a/src/main/java/weka/clusterers/XMeans.java b/src/main/java/weka/clusterers/XMeans.java
index fc37d2d..c30387e 100644
--- a/src/main/java/weka/clusterers/XMeans.java
+++ b/src/main/java/weka/clusterers/XMeans.java
@@ -149,7 +149,7 @@ import java.util.Vector;
* @author Gabi Schmidberger (gabi at cs.waikato.ac.nz)
* @author Mark Hall (mhall at cs.waikato.ac.nz)
* @author Malcolm Ware (mfw4 at cs.waikato.ac.nz)
- * @version $Revision: 7135 $
+ * @version $Revision: 9986 $
* @see RandomizableClusterer
*/
public class XMeans
@@ -229,13 +229,13 @@ public class XMeans
protected File m_DebugVectorsFile = new File(System.getProperty("user.dir"));
/** input file for the cluster centers. */
- protected Reader m_CenterInput = null;
+ protected transient Reader m_CenterInput = null;
/** file name of the output file for the cluster centers. */
protected File m_OutputCenterFile = new File(System.getProperty("user.dir"));
/** output file for the cluster centers. */
- protected PrintWriter m_CenterOutput = null;
+ protected transient PrintWriter m_CenterOutput = null;
/**
* temporary variable holding cluster assignments while iterating.
@@ -641,6 +641,12 @@ public class XMeans
}
m_NumClusters = newNumClusters;
}
+
+ if (m_ClusterCenters.numInstances() > 0 && m_CenterOutput != null) {
+ m_CenterOutput.println(m_ClusterCenters.toString());
+ m_CenterOutput.close();
+ m_CenterOutput = null;
+ }
}
/**
@@ -2406,7 +2412,7 @@ public class XMeans
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 7135 $");
+ return RevisionUtils.extract("$Revision: 9986 $");
}
/**
diff --git a/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/EuclideanDataObject.java b/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/EuclideanDataObject.java
index 95979d5..7308635 100644
--- a/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/EuclideanDataObject.java
+++ b/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/EuclideanDataObject.java
@@ -22,8 +22,6 @@
package weka.clusterers.forOPTICSAndDBScan.DataObjects;
-import java.io.Serializable;
-
import weka.clusterers.forOPTICSAndDBScan.Databases.Database;
import weka.core.Attribute;
import weka.core.Instance;
@@ -31,6 +29,8 @@ import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
+import java.io.Serializable;
+
/**
* <p>
* EuclideanDataObject.java <br/>
@@ -39,276 +39,313 @@ import weka.core.Utils;
* Time: 5:50:22 PM <br/>
* $ Revision 1.4 $ <br/>
* </p>
- *
+ *
* @author Matthias Schubert (schubert at dbs.ifi.lmu.de)
* @author Zhanna Melnikova-Albrecht (melnikov at cip.ifi.lmu.de)
* @author Rainer Holzmann (holzmann at cip.ifi.lmu.de)
* @version $Revision: 8108 $
*/
-public class EuclideanDataObject implements DataObject, Serializable,
- RevisionHandler {
-
- /** for serialization */
- private static final long serialVersionUID = -4408119914898291075L;
-
- /**
- * Holds the original instance
- */
- private final Instance instance;
-
- /**
- * Holds the (unique) key that is associated with this DataObject
- */
- private String key;
-
- /**
- * Holds the ID of the cluster, to which this DataObject is assigned
- */
- private int clusterID;
-
- /**
- * Holds the status for this DataObject (true, if it has been processed, else
- * false)
- */
- private boolean processed;
-
- /**
- * Holds the coreDistance for this DataObject
- */
- private double c_dist;
-
- /**
- * Holds the reachabilityDistance for this DataObject
- */
- private double r_dist;
-
- /**
- * Holds the database, that is the keeper of this DataObject
- */
- private final Database database;
-
- // *****************************************************************************************************************
- // constructors
- // *****************************************************************************************************************
-
- /**
- * Constructs a new DataObject. The original instance is kept as
- * instance-variable
- *
- * @param originalInstance the original instance
- */
- public EuclideanDataObject(Instance originalInstance, String key,
- Database database) {
- this.database = database;
- this.key = key;
- instance = originalInstance;
- clusterID = DataObject.UNCLASSIFIED;
- processed = false;
- c_dist = DataObject.UNDEFINED;
- r_dist = DataObject.UNDEFINED;
- }
-
- // *****************************************************************************************************************
- // methods
- // *****************************************************************************************************************
-
- /**
- * Compares two DataObjects in respect to their attribute-values
- *
- * @param dataObject The DataObject, that is compared with this.dataObject;
- * now assumed to be of the same type and with the same structure
- * @return Returns true, if the DataObjects correspond in each value, else
- * returns false
- */
- public boolean equals(DataObject dataObject) {
- if (this == dataObject)
+public class EuclideanDataObject
+ implements DataObject, Serializable, RevisionHandler {
+
+ /** for serialization */
+ private static final long serialVersionUID = -4408119914898291075L;
+
+ /**
+ * Holds the original instance
+ */
+ private Instance instance;
+
+ /**
+ * Holds the (unique) key that is associated with this DataObject
+ */
+ private String key;
+
+ /**
+ * Holds the ID of the cluster, to which this DataObject is assigned
+ */
+ private int clusterID;
+
+ /**
+ * Holds the status for this DataObject (true, if it has been processed, else false)
+ */
+ private boolean processed;
+
+ /**
+ * Holds the coreDistance for this DataObject
+ */
+ private double c_dist;
+
+ /**
+ * Holds the reachabilityDistance for this DataObject
+ */
+ private double r_dist;
+
+ /**
+ * Holds the database, that is the keeper of this DataObject
+ */
+ private Database database;
+
+ // *****************************************************************************************************************
+ // constructors
+ // *****************************************************************************************************************
+
+ /**
+ * Constructs a new DataObject. The original instance is kept as instance-variable
+ * @param originalInstance the original instance
+ */
+ public EuclideanDataObject(Instance originalInstance, String key, Database database) {
+ this.database = database;
+ this.key = key;
+ instance = originalInstance;
+ clusterID = DataObject.UNCLASSIFIED;
+ processed = false;
+ c_dist = DataObject.UNDEFINED;
+ r_dist = DataObject.UNDEFINED;
+ }
+
+ // *****************************************************************************************************************
+ // methods
+ // *****************************************************************************************************************
+
+ /**
+ * Compares two DataObjects in respect to their attribute-values
+ * @param dataObject The DataObject, that is compared with this.dataObject;
+ * now assumed to be of the same type and with the same structure
+ * @return Returns true, if the DataObjects correspond in each value, else returns false
+ */
+ public boolean equals(DataObject dataObject) {
+ if (this == dataObject) return true;
+
+ Instance firstInstance = getInstance();
+ Instance secondInstance = dataObject.getInstance();
+ int firstNumValues = firstInstance.numValues();
+ int secondNumValues = secondInstance.numValues();
+ int numAttributes = firstInstance.numAttributes();
+
+ int firstI, secondI;
+ for (int p1 = 0, p2 = 0; p1 < firstNumValues || p2 < secondNumValues;) {
+ if (p1 >= firstNumValues) {
+ firstI = numAttributes;
+ } else {
+ firstI = firstInstance.index(p1);
+ }
+
+ if (p2 >= secondNumValues) {
+ secondI = numAttributes;
+ } else {
+ secondI = secondInstance.index(p2);
+ }
+
+ if (firstI == secondI) {
+ if (firstInstance.valueSparse(p1) != secondInstance.valueSparse(p2)) {
+ return false;
+ }
+ p1++;
+ p2++;
+ } else if (firstI > secondI) {
+ if (0 != secondInstance.valueSparse(p2)) {
+ return false;
+ }
+ p2++;
+ } else {
+ if (0 != firstInstance.valueSparse(p1)) {
+ return false;
+ }
+ p1++;
+ }
+ }
return true;
+ }
+
+ /**
+ * Calculates the euclidian-distance between dataObject and this.dataObject
+ * @param dataObject The DataObject, that is used for distance-calculation with this.dataObject;
+ * now assumed to be of the same type and with the same structure
+ * @return double-value The euclidian-distance between dataObject and this.dataObject
+ */
+ public double distance(DataObject dataObject) {
+ double dist = 0.0;
+
+ Instance firstInstance = getInstance();
+ Instance secondInstance = dataObject.getInstance();
+ int firstNumValues = firstInstance.numValues();
+ int secondNumValues = secondInstance.numValues();
+ int numAttributes = firstInstance.numAttributes();
+
+ int firstI, secondI;
+ for (int p1 = 0, p2 = 0; p1 < firstNumValues || p2 < secondNumValues;) {
+ if (p1 >= firstNumValues) {
+ firstI = numAttributes;
+ } else {
+ firstI = firstInstance.index(p1);
+ }
- for (int i = 0; i < getInstance().numValues(); i++) {
- double i_value_Instance_1 = getInstance().valueSparse(i);
- double i_value_Instance_2 = dataObject.getInstance().valueSparse(i);
+ if (p2 >= secondNumValues) {
+ secondI = numAttributes;
+ } else {
+ secondI = secondInstance.index(p2);
+ }
- if (i_value_Instance_1 != i_value_Instance_2)
- return false;
+ double cDistance = 0;
+ if (firstI == secondI) {
+ cDistance = computeDistance(firstI, firstInstance.valueSparse(p1),
+ secondInstance.valueSparse(p2));
+ p1++;
+ p2++;
+ } else if (firstI > secondI) {
+ cDistance = computeDistance(secondI, 0, secondInstance.valueSparse(p2));
+ p2++;
+ } else {
+ cDistance = computeDistance(firstI, firstInstance.valueSparse(p1), 0);
+ p1++;
+ }
+ dist += cDistance * cDistance;
+ }
+ return Math.sqrt(dist);
}
- return true;
- }
-
- /**
- * Calculates the euclidian-distance between dataObject and this.dataObject
- *
- * @param dataObject The DataObject, that is used for distance-calculation
- * with this.dataObject; now assumed to be of the same type and with
- * the same structure
- * @return double-value The euclidian-distance between dataObject and
- * this.dataObject
- */
- public double distance(DataObject dataObject) {
- double dist = 0.0;
-
- for (int i = 0; i < getInstance().numValues(); i++) {
- double cDistance = computeDistance(getInstance().index(i), getInstance()
- .valueSparse(i), dataObject.getInstance().valueSparse(i));
- dist += cDistance * cDistance;
+
+ /**
+ * Performs euclidian-distance-calculation between two given values
+ * @param index of the attribute within the DataObject's instance
+ * @param v value_1
+ * @param v1 value_2
+ * @return double norm-distance between value_1 and value_2
+ */
+ private double computeDistance(int index, double v, double v1) {
+ switch (getInstance().attribute(index).type()) {
+ case Attribute.NOMINAL:
+ return (Instance.isMissingValue(v) || Instance.isMissingValue(v1)
+ || ((int) v != (int) v1)) ? 1 : 0;
+
+ case Attribute.NUMERIC:
+ if (Instance.isMissingValue(v) || Instance.isMissingValue(v1)) {
+ if (Instance.isMissingValue(v) && Instance.isMissingValue(v1))
+ return 1;
+ else {
+ return (Instance.isMissingValue(v)) ? norm(v1, index)
+ : norm(v, index);
+ }
+ } else
+ return norm(v, index) - norm(v1, index);
+
+ default:
+ return 0;
+ }
}
- return Math.sqrt(dist);
- }
-
- /**
- * Performs euclidian-distance-calculation between two given values
- *
- * @param index of the attribute within the DataObject's instance
- * @param v value_1
- * @param v1 value_2
- * @return double norm-distance between value_1 and value_2
- */
- private double computeDistance(int index, double v, double v1) {
- switch (getInstance().attribute(index).type()) {
- case Attribute.NOMINAL:
- return (Instance.isMissingValue(v) || Instance.isMissingValue(v1) || ((int) v != (int) v1)) ? 1
- : 0;
-
- case Attribute.NUMERIC:
- if (Instance.isMissingValue(v) || Instance.isMissingValue(v1)) {
- if (Instance.isMissingValue(v) && Instance.isMissingValue(v1))
- return 1;
- else {
- return (Instance.isMissingValue(v)) ? norm(v1, index)
- : norm(v, index);
+
+ /**
+ * Normalizes a given value of a numeric attribute.
+ *
+ * @param x the value to be normalized
+ * @param i the attribute's index
+ */
+ private double norm(double x, int i) {
+ if (Double.isNaN(database.getAttributeMinValues()[i])
+ || Utils.eq(database.getAttributeMaxValues()[i], database.getAttributeMinValues()[i])) {
+ return 0;
+ } else {
+ return (x - database.getAttributeMinValues()[i]) /
+ (database.getAttributeMaxValues()[i] - database.getAttributeMinValues()[i]);
}
- } else
- return norm(v, index) - norm(v1, index);
+ }
+
+ /**
+ * Returns the original instance
+ * @return originalInstance
+ */
+ public Instance getInstance() {
+ return instance;
+ }
+
+ /**
+ * Returns the key for this DataObject
+ * @return key
+ */
+ public String getKey() {
+ return key;
+ }
+
+ /**
+ * Sets the key for this DataObject
+ * @param key The key is represented as string
+ */
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ /**
+ * Sets the clusterID (cluster), to which this DataObject belongs to
+ * @param clusterID Number of the Cluster
+ */
+ public void setClusterLabel(int clusterID) {
+ this.clusterID = clusterID;
+ }
+
+ /**
+ * Returns the clusterID, to which this DataObject belongs to
+ * @return clusterID
+ */
+ public int getClusterLabel() {
+ return clusterID;
+ }
+
+ /**
+ * Marks this dataObject as processed
+ * @param processed True, if the DataObject has been already processed, false else
+ */
+ public void setProcessed(boolean processed) {
+ this.processed = processed;
+ }
+
+ /**
+ * Gives information about the status of a dataObject
+ * @return True, if this dataObject has been processed, else false
+ */
+ public boolean isProcessed() {
+ return processed;
+ }
+
+ /**
+ * Sets a new coreDistance for this dataObject
+ * @param c_dist coreDistance
+ */
+ public void setCoreDistance(double c_dist) {
+ this.c_dist = c_dist;
+ }
+
+ /**
+ * Returns the coreDistance for this dataObject
+ * @return coreDistance
+ */
+ public double getCoreDistance() {
+ return c_dist;
+ }
+
+ /**
+ * Sets a new reachability-distance for this dataObject
+ */
+ public void setReachabilityDistance(double r_dist) {
+ this.r_dist = r_dist;
+ }
+
+ /**
+ * Returns the reachabilityDistance for this dataObject
+ */
+ public double getReachabilityDistance() {
+ return r_dist;
+ }
- default:
- return 0;
+ public String toString() {
+ return instance.toString();
}
- }
-
- /**
- * Normalizes a given value of a numeric attribute.
- *
- * @param x the value to be normalized
- * @param i the attribute's index
- */
- private double norm(double x, int i) {
- if (Double.isNaN(database.getAttributeMinValues()[i])
- || Utils.eq(database.getAttributeMaxValues()[i],
- database.getAttributeMinValues()[i])) {
- return 0;
- } else {
- return (x - database.getAttributeMinValues()[i])
- / (database.getAttributeMaxValues()[i] - database
- .getAttributeMinValues()[i]);
+
+ /**
+ * Returns the revision string.
+ *
+ * @return the revision
+ */
+ public String getRevision() {
+ return RevisionUtils.extract("$Revision: 8108 $");
}
- }
-
- /**
- * Returns the original instance
- *
- * @return originalInstance
- */
- public Instance getInstance() {
- return instance;
- }
-
- /**
- * Returns the key for this DataObject
- *
- * @return key
- */
- public String getKey() {
- return key;
- }
-
- /**
- * Sets the key for this DataObject
- *
- * @param key The key is represented as string
- */
- public void setKey(String key) {
- this.key = key;
- }
-
- /**
- * Sets the clusterID (cluster), to which this DataObject belongs to
- *
- * @param clusterID Number of the Cluster
- */
- public void setClusterLabel(int clusterID) {
- this.clusterID = clusterID;
- }
-
- /**
- * Returns the clusterID, to which this DataObject belongs to
- *
- * @return clusterID
- */
- public int getClusterLabel() {
- return clusterID;
- }
-
- /**
- * Marks this dataObject as processed
- *
- * @param processed True, if the DataObject has been already processed, false
- * else
- */
- public void setProcessed(boolean processed) {
- this.processed = processed;
- }
-
- /**
- * Gives information about the status of a dataObject
- *
- * @return True, if this dataObject has been processed, else false
- */
- public boolean isProcessed() {
- return processed;
- }
-
- /**
- * Sets a new coreDistance for this dataObject
- *
- * @param c_dist coreDistance
- */
- public void setCoreDistance(double c_dist) {
- this.c_dist = c_dist;
- }
-
- /**
- * Returns the coreDistance for this dataObject
- *
- * @return coreDistance
- */
- public double getCoreDistance() {
- return c_dist;
- }
-
- /**
- * Sets a new reachability-distance for this dataObject
- */
- public void setReachabilityDistance(double r_dist) {
- this.r_dist = r_dist;
- }
-
- /**
- * Returns the reachabilityDistance for this dataObject
- */
- public double getReachabilityDistance() {
- return r_dist;
- }
-
- @Override
- public String toString() {
- return instance.toString();
- }
-
- /**
- * Returns the revision string.
- *
- * @return the revision
- */
- public String getRevision() {
- return RevisionUtils.extract("$Revision: 8108 $");
- }
}
diff --git a/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/ManhattanDataObject.java b/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/ManhattanDataObject.java
index 954d9d9..6d90967 100644
--- a/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/ManhattanDataObject.java
+++ b/src/main/java/weka/clusterers/forOPTICSAndDBScan/DataObjects/ManhattanDataObject.java
@@ -22,8 +22,6 @@
package weka.clusterers.forOPTICSAndDBScan.DataObjects;
-import java.io.Serializable;
-
import weka.clusterers.forOPTICSAndDBScan.Databases.Database;
import weka.core.Attribute;
import weka.core.Instance;
@@ -31,6 +29,8 @@ import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
+import java.io.Serializable;
+
/**
* <p>
* ManhattanDataObject.java <br/>
@@ -39,276 +39,315 @@ import weka.core.Utils;
* Time: 5:50:22 PM <br/>
* $ Revision 1.4 $ <br/>
* </p>
- *
+ *
* @author Matthias Schubert (schubert at dbs.ifi.lmu.de)
* @author Zhanna Melnikova-Albrecht (melnikov at cip.ifi.lmu.de)
* @author Rainer Holzmann (holzmann at cip.ifi.lmu.de)
- * @version $Revision: 9420 $
+ * @version $Revision: 10571 $
*/
-public class ManhattanDataObject implements DataObject, Serializable,
- RevisionHandler {
-
- /** for serialization */
- private static final long serialVersionUID = -3417720553766544582L;
-
- /**
- * Holds the original instance
- */
- private final Instance instance;
-
- /**
- * Holds the (unique) key that is associated with this DataObject
- */
- private String key;
-
- /**
- * Holds the ID of the cluster, to which this DataObject is assigned
- */
- private int clusterID;
-
- /**
- * Holds the status for this DataObject (true, if it has been processed, else
- * false)
- */
- private boolean processed;
-
- /**
- * Holds the coreDistance for this DataObject
- */
- private double c_dist;
-
- /**
- * Holds the reachabilityDistance for this DataObject
- */
- private double r_dist;
-
- /**
- * Holds the database, that is the keeper of this DataObject
- */
- private final Database database;
-
- // *****************************************************************************************************************
- // constructors
- // *****************************************************************************************************************
-
- /**
- * Constructs a new DataObject. The original instance is kept as
- * instance-variable
- *
- * @param originalInstance the original instance
- */
- public ManhattanDataObject(Instance originalInstance, String key,
- Database database) {
- this.database = database;
- this.key = key;
- instance = originalInstance;
- clusterID = DataObject.UNCLASSIFIED;
- processed = false;
- c_dist = DataObject.UNDEFINED;
- r_dist = DataObject.UNDEFINED;
- }
-
- // *****************************************************************************************************************
- // methods
- // *****************************************************************************************************************
-
- /**
- * Compares two DataObjects in respect to their attribute-values
- *
- * @param dataObject The DataObject, that is compared with this.dataObject;
- * now assumed to be of the same type and with the same structure
- * @return Returns true, if the DataObjects correspond in each value, else
- * returns false
- */
- public boolean equals(DataObject dataObject) {
- if (this == dataObject)
+public class ManhattanDataObject
+ implements DataObject, Serializable, RevisionHandler {
+
+ /** for serialization */
+ private static final long serialVersionUID = -3417720553766544582L;
+
+ /**
+ * Holds the original instance
+ */
+ private Instance instance;
+
+ /**
+ * Holds the (unique) key that is associated with this DataObject
+ */
+ private String key;
+
+ /**
+ * Holds the ID of the cluster, to which this DataObject is assigned
+ */
+ private int clusterID;
+
+ /**
+ * Holds the status for this DataObject (true, if it has been processed, else false)
+ */
+ private boolean processed;
+
+ /**
+ * Holds the coreDistance for this DataObject
+ */
+ private double c_dist;
+
+ /**
+ * Holds the reachabilityDistance for this DataObject
+ */
+ private double r_dist;
+
+ /**
+ * Holds the database, that is the keeper of this DataObject
+ */
+ private Database database;
+
+ // *****************************************************************************************************************
+ // constructors
+ // *****************************************************************************************************************
+
+ /**
+ * Constructs a new DataObject. The original instance is kept as instance-variable
+ * @param originalInstance the original instance
+ */
+ public ManhattanDataObject(Instance originalInstance, String key, Database database) {
+ this.database = database;
+ this.key = key;
+ instance = originalInstance;
+ clusterID = DataObject.UNCLASSIFIED;
+ processed = false;
+ c_dist = DataObject.UNDEFINED;
+ r_dist = DataObject.UNDEFINED;
+ }
+
+ // *****************************************************************************************************************
+ // methods
+ // *****************************************************************************************************************
+
+
+ /**
+ * Compares two DataObjects in respect to their attribute-values
+ * @param dataObject The DataObject, that is compared with this.dataObject;
+ * now assumed to be of the same type and with the same structure
+ * @return Returns true, if the DataObjects correspond in each value, else returns false
+ */
+ public boolean equals(DataObject dataObject) {
+ if (this == dataObject) return true;
+
+ Instance firstInstance = getInstance();
+ Instance secondInstance = dataObject.getInstance();
+ int firstNumValues = firstInstance.numValues();
+ int secondNumValues = secondInstance.numValues();
+ int numAttributes = firstInstance.numAttributes();
+
+ int firstI, secondI;
+ for (int p1 = 0, p2 = 0; p1 < firstNumValues || p2 < secondNumValues;) {
+ if (p1 >= firstNumValues) {
+ firstI = numAttributes;
+ } else {
+ firstI = firstInstance.index(p1);
+ }
+
+ if (p2 >= secondNumValues) {
+ secondI = numAttributes;
+ } else {
+ secondI = secondInstance.index(p2);
+ }
+
+ if (firstI == secondI) {
+ if (firstInstance.valueSparse(p1) != secondInstance.valueSparse(p2)) {
+ return false;
+ }
+ p1++;
+ p2++;
+ } else if (firstI > secondI) {
+ if (0 != secondInstance.valueSparse(p2)) {
+ return false;
+ }
+ p2++;
+ } else {
+ if (0 != firstInstance.valueSparse(p1)) {
+ return false;
+ }
+ p1++;
+ }
+ }
return true;
+ }
+
+ /**
+ * Calculates the manhattan-distance between dataObject and this.dataObject
+ * @param dataObject The DataObject, that is used for distance-calculation with this.dataObject
+ * now assumed to be of the same type and with the same structure
+ * @return double-value The manhattan-distance between dataObject and this.dataObject
+ * NaN, if the computation could not be performed
+ */
+ public double distance(DataObject dataObject) {
+ double dist = 0.0;
+
+ Instance firstInstance = getInstance();
+ Instance secondInstance = dataObject.getInstance();
+ int firstNumValues = firstInstance.numValues();
+ int secondNumValues = secondInstance.numValues();
+ int numAttributes = firstInstance.numAttributes();
+
+ int firstI, secondI;
+ for (int p1 = 0, p2 = 0; p1 < firstNumValues || p2 < secondNumValues;) {
+ if (p1 >= firstNumValues) {
+ firstI = numAttributes;
+ } else {
+ firstI = firstInstance.index(p1);
+ }
- for (int i = 0; i < getInstance().numValues(); i++) {
- double i_value_Instance_1 = getInstance().valueSparse(i);
- double i_value_Instance_2 = dataObject.getInstance().valueSparse(i);
+ if (p2 >= secondNumValues) {
+ secondI = numAttributes;
+ } else {
+ secondI = secondInstance.index(p2);
+ }
- if (i_value_Instance_1 != i_value_Instance_2)
- return false;
+ double cDistance = 0;
+ if (firstI == secondI) {
+ cDistance = computeDistance(firstI, firstInstance.valueSparse(p1),
+ secondInstance.valueSparse(p2));
+ p1++;
+ p2++;
+ } else if (firstI > secondI) {
+ cDistance = computeDistance(secondI, 0, secondInstance.valueSparse(p2));
+ p2++;
+ } else {
+ cDistance = computeDistance(firstI, firstInstance.valueSparse(p1), 0);
+ p1++;
+ }
+ dist += Math.abs(cDistance);
+ }
+ return dist;
}
- return true;
- }
-
- /**
- * Calculates the manhattan-distance between dataObject and this.dataObject
- *
- * @param dataObject The DataObject, that is used for distance-calculation
- * with this.dataObject now assumed to be of the same type and with
- * the same structure
- * @return double-value The manhattan-distance between dataObject and
- * this.dataObject NaN, if the computation could not be performed
- */
- public double distance(DataObject dataObject) {
- double dist = 0.0;
-
- for (int i = 0; i < getInstance().numValues(); i++) {
- double cDistance = computeDistance(getInstance().index(i), getInstance()
- .valueSparse(i), dataObject.getInstance().valueSparse(i));
- dist += Math.abs(cDistance);
+
+ /**
+ * Performs manhattan-distance-calculation between two given values
+ * @param index of the attribute within the DataObject's instance
+ * @param v value_1
+ * @param v1 value_2
+ * @return double norm-distance between value_1 and value_2
+ */
+ private double computeDistance(int index, double v, double v1) {
+ switch (getInstance().attribute(index).type()) {
+ case Attribute.NOMINAL:
+ return (Instance.isMissingValue(v) || Instance.isMissingValue(v1)
+ || ((int) v != (int) v1)) ? 1 : 0;
+
+ case Attribute.NUMERIC:
+ if (Instance.isMissingValue(v) || Instance.isMissingValue(v1)) {
+ if (Instance.isMissingValue(v) && Instance.isMissingValue(v1))
+ return 1;
+ else {
+ return (Instance.isMissingValue(v)) ? norm(v1, index)
+ : norm(v, index);
+ }
+ } else
+ return norm(v, index) - norm(v1, index);
+
+ default:
+ return 0;
+ }
}
- return dist;
- }
-
- /**
- * Performs manhattan-distance-calculation between two given values
- *
- * @param index of the attribute within the DataObject's instance
- * @param v value_1
- * @param v1 value_2
- * @return double norm-distance between value_1 and value_2
- */
- private double computeDistance(int index, double v, double v1) {
- switch (getInstance().attribute(index).type()) {
- case Attribute.NOMINAL:
- return (Instance.isMissingValue(v) || Instance.isMissingValue(v1) || ((int) v != (int) v1)) ? 1
- : 0;
-
- case Attribute.NUMERIC:
- if (Instance.isMissingValue(v) || Instance.isMissingValue(v1)) {
- if (Instance.isMissingValue(v) && Instance.isMissingValue(v1))
- return 1;
- else {
- return (Instance.isMissingValue(v)) ? norm(v1, index)
- : norm(v, index);
+
+ /**
+ * Normalizes a given value of a numeric attribute.
+ *
+ * @param x the value to be normalized
+ * @param i the attribute's index
+ */
+ private double norm(double x, int i) {
+ if (Double.isNaN(database.getAttributeMinValues()[i])
+ || Utils.eq(database.getAttributeMaxValues()[i], database.getAttributeMinValues()[i])) {
+ return 0;
+ } else {
+ return (x - database.getAttributeMinValues()[i]) /
+ (database.getAttributeMaxValues()[i] - database.getAttributeMinValues()[i]);
}
- } else
- return norm(v, index) - norm(v1, index);
+ }
+
+ /**
+ * Returns the original instance
+ * @return originalInstance
+ */
+ public Instance getInstance() {
+ return instance;
+ }
+
+ /**
+ * Returns the key for this DataObject
+ * @return key
+ */
+ public String getKey() {
+ return key;
+ }
+
+ /**
+ * Sets the key for this DataObject
+ * @param key The key is represented as string
+ */
+ public void setKey(String key) {
+ this.key = key;
+ }
+
+ /**
+ * Sets the clusterID (cluster), to which this DataObject belongs to
+ * @param clusterID Number of the Cluster
+ */
+ public void setClusterLabel(int clusterID) {
+ this.clusterID = clusterID;
+ }
+
+ /**
+ * Returns the clusterID, to which this DataObject belongs to
+ * @return clusterID
+ */
+ public int getClusterLabel() {
+ return clusterID;
+ }
+
+ /**
+ * Marks this dataObject as processed
+ * @param processed True, if the DataObject has been already processed, false else
+ */
+ public void setProcessed(boolean processed) {
+ this.processed = processed;
+ }
+
+ /**
+ * Gives information about the status of a dataObject
+ * @return True, if this dataObject has been processed, else false
+ */
+ public boolean isProcessed() {
+ return processed;
+ }
+
+ /**
+ * Sets a new coreDistance for this dataObject
+ * @param c_dist coreDistance
+ */
+ public void setCoreDistance(double c_dist) {
+ this.c_dist = c_dist;
+ }
+
+ /**
+ * Returns the coreDistance for this dataObject
+ * @return coreDistance
+ */
+ public double getCoreDistance() {
+ return c_dist;
+ }
+
+ /**
+ * Sets a new reachability-distance for this dataObject
+ */
+ public void setReachabilityDistance(double r_dist) {
+ this.r_dist = r_dist;
+ }
+
+ /**
+ * Returns the reachabilityDistance for this dataObject
+ */
+ public double getReachabilityDistance() {
+ return r_dist;
+ }
- default:
- return 0;
+ public String toString() {
+ return instance.toString();
}
- }
-
- /**
- * Normalizes a given value of a numeric attribute.
- *
- * @param x the value to be normalized
- * @param i the attribute's index
- */
- private double norm(double x, int i) {
- if (Double.isNaN(database.getAttributeMinValues()[i])
- || Utils.eq(database.getAttributeMaxValues()[i],
- database.getAttributeMinValues()[i])) {
- return 0;
- } else {
- return (x - database.getAttributeMinValues()[i])
- / (database.getAttributeMaxValues()[i] - database
- .getAttributeMinValues()[i]);
+
+ /**
+ * Returns the revision string.
+ *
+ * @return the revision
+ */
+ public String getRevision() {
+ return RevisionUtils.extract("$Revision: 10571 $");
}
- }
-
- /**
- * Returns the original instance
- *
- * @return originalInstance
- */
- public Instance getInstance() {
- return instance;
- }
-
- /**
- * Returns the key for this DataObject
- *
- * @return key
- */
- public String getKey() {
- return key;
- }
-
- /**
- * Sets the key for this DataObject
- *
- * @param key The key is represented as string
- */
- public void setKey(String key) {
- this.key = key;
- }
-
- /**
- * Sets the clusterID (cluster), to which this DataObject belongs to
- *
- * @param clusterID Number of the Cluster
- */
- public void setClusterLabel(int clusterID) {
- this.clusterID = clusterID;
- }
-
- /**
- * Returns the clusterID, to which this DataObject belongs to
- *
- * @return clusterID
- */
- public int getClusterLabel() {
- return clusterID;
- }
-
- /**
- * Marks this dataObject as processed
- *
- * @param processed True, if the DataObject has been already processed, false
- * else
- */
- public void setProcessed(boolean processed) {
- this.processed = processed;
- }
-
- /**
- * Gives information about the status of a dataObject
- *
- * @return True, if this dataObject has been processed, else false
- */
- public boolean isProcessed() {
- return processed;
- }
-
- /**
- * Sets a new coreDistance for this dataObject
- *
- * @param c_dist coreDistance
- */
- public void setCoreDistance(double c_dist) {
- this.c_dist = c_dist;
- }
-
- /**
- * Returns the coreDistance for this dataObject
- *
- * @return coreDistance
- */
- public double getCoreDistance() {
- return c_dist;
- }
-
- /**
- * Sets a new reachability-distance for this dataObject
- */
- public void setReachabilityDistance(double r_dist) {
- this.r_dist = r_dist;
- }
-
- /**
- * Returns the reachabilityDistance for this dataObject
- */
- public double getReachabilityDistance() {
- return r_dist;
- }
-
- @Override
- public String toString() {
- return instance.toString();
- }
-
- /**
- * Returns the revision string.
- *
- * @return the revision
- */
- public String getRevision() {
- return RevisionUtils.extract("$Revision: 9420 $");
- }
}
diff --git a/src/main/java/weka/core/AttributeLocator.java b/src/main/java/weka/core/AttributeLocator.java
index 23c8111..bef1c1f 100644
--- a/src/main/java/weka/core/AttributeLocator.java
+++ b/src/main/java/weka/core/AttributeLocator.java
@@ -16,40 +16,43 @@
/*
* StringLocator.java
- * Copyright (C) 2005 University of Waikato, Hamilton, New Zealand
+ * Copyright (C) 2005-2014 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.io.Serializable;
-import java.util.Vector;
+import java.util.ArrayList;
+import java.util.BitSet;
/**
- * This class locates and records the indices of a certain type of attributes,
+ * This class locates and records the indices of a certain type of attributes,
* recursively in case of Relational attributes.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision: 1.4 $
* @see Attribute#RELATIONAL
*/
-public class AttributeLocator
- implements Serializable, Comparable<AttributeLocator>, RevisionHandler {
-
+public class AttributeLocator implements Serializable,
+ Comparable<AttributeLocator>, RevisionHandler {
+
/** for serialization */
private static final long serialVersionUID = -2932848827681070345L;
/** the attribute indices that may be inspected */
protected int[] m_AllowedIndices = null;
-
+
/** contains the attribute locations, either true or false Boolean objects */
- protected Vector m_Attributes = null;
-
- /** contains the locator locations, either null or a AttributeLocator reference */
- protected Vector m_Locators = null;
+ protected BitSet m_Attributes = null;
+
+ /**
+ * contains the locator locations, either null or a AttributeLocator reference
+ */
+ protected ArrayList<AttributeLocator> m_Locators = null;
/** the type of the attribute */
protected int m_Type = -1;
-
+
/** the referenced data */
protected Instances m_Data = null;
@@ -58,278 +61,276 @@ public class AttributeLocator
/** the indices of locator objects */
protected int[] m_LocatorIndices = null;
-
+
/**
- * Initializes the AttributeLocator with the given data for the specified
- * type of attribute. Checks all attributes.
+ * Initializes the AttributeLocator with the given data for the specified type
+ * of attribute. Checks all attributes.
*
- * @param data the data to work on
- * @param type the type of attribute to locate
+ * @param data the data to work on
+ * @param type the type of attribute to locate
*/
public AttributeLocator(Instances data, int type) {
this(data, type, 0, data.numAttributes() - 1);
}
-
+
/**
- * Initializes the AttributeLocator with the given data for the specified
- * type of attribute. Checks only the given range.
+ * Initializes the AttributeLocator with the given data for the specified type
+ * of attribute. Checks only the given range.
*
- * @param data the data to work on
- * @param type the type of attribute to locate
- * @param fromIndex the first index to inspect (including)
- * @param toIndex the last index to check (including)
+ * @param data the data to work on
+ * @param type the type of attribute to locate
+ * @param fromIndex the first index to inspect (including)
+ * @param toIndex the last index to check (including)
*/
public AttributeLocator(Instances data, int type, int fromIndex, int toIndex) {
super();
int[] indices = new int[toIndex - fromIndex + 1];
- for (int i = 0; i < indices.length; i++)
+ for (int i = 0; i < indices.length; i++) {
indices[i] = fromIndex + i;
-
+ }
+
initialize(data, type, indices);
}
-
+
/**
- * initializes the AttributeLocator with the given data for the specified
- * type of attribute. Checks only the given attribute indices.
+ * initializes the AttributeLocator with the given data for the specified type
+ * of attribute. Checks only the given attribute indices.
*
- * @param data the data to work on
- * @param type the type of attribute to locate
- * @param indices the attribute indices to check
+ * @param data the data to work on
+ * @param type the type of attribute to locate
+ * @param indices the attribute indices to check
*/
public AttributeLocator(Instances data, int type, int[] indices) {
super();
initialize(data, type, indices);
}
-
+
/**
* initializes the AttributeLocator
*
- * @param data the data to base the search for attributes on
- * @param type the type of attribute to look for
- * @param indices the indices that are allowed to check
+ * @param data the data to base the search for attributes on
+ * @param type the type of attribute to look for
+ * @param indices the indices that are allowed to check
*/
protected void initialize(Instances data, int type, int[] indices) {
m_Data = new Instances(data, 0);
m_Type = type;
-
+
m_AllowedIndices = new int[indices.length];
System.arraycopy(indices, 0, m_AllowedIndices, 0, indices.length);
-
+
locate();
- m_Indices = find(true);
+ m_Indices = find(true);
m_LocatorIndices = find(false);
}
-
+
/**
* returns the type of attribute that is located
*
- * @return the type of attribute
+ * @return the type of attribute
*/
public int getType() {
return m_Type;
}
-
+
/**
* returns the indices that are allowed to check for the attribute type
*
- * @return the indices that are checked for the attribute type
+ * @return the indices that are checked for the attribute type
*/
public int[] getAllowedIndices() {
return m_AllowedIndices;
}
-
+
/**
* sets up the structure
*/
protected void locate() {
- int i;
-
- m_Attributes = new Vector();
- m_Locators = new Vector();
-
+ int i;
+
+ m_Attributes = new BitSet(m_AllowedIndices.length);
+ m_Locators = new ArrayList<AttributeLocator>();
+
for (i = 0; i < m_AllowedIndices.length; i++) {
- if (m_Data.attribute(m_AllowedIndices[i]).type() == Attribute.RELATIONAL)
- m_Locators.add(new AttributeLocator(m_Data.attribute(m_AllowedIndices[i]).relation(), getType()));
- else
- m_Locators.add(null);
-
- if (m_Data.attribute(m_AllowedIndices[i]).type() == getType())
- m_Attributes.add(new Boolean(true));
- else
- m_Attributes.add(new Boolean(false));
+ if (m_Data.attribute(m_AllowedIndices[i]).type() == Attribute.RELATIONAL) {
+ m_Locators.add(new AttributeLocator(m_Data.attribute(
+ m_AllowedIndices[i]).relation(), getType()));
+ } else {
+ m_Locators.add(null);
+ }
+
+ m_Attributes.set(i,
+ m_Data.attribute(m_AllowedIndices[i]).type() == getType());
}
}
-
+
/**
* returns the underlying data
*
- * @return the underlying Instances object
+ * @return the underlying Instances object
*/
public Instances getData() {
return m_Data;
}
-
+
/**
* returns the indices of the searched-for attributes (if TRUE) or the indices
* of AttributeLocator objects (if FALSE)
*
- * @param findAtts if true the indices of attributes are located,
- * otherwise the ones of AttributeLocator objects
- * @return the indices of the attributes or the AttributeLocator objects
+ * @param findAtts if true the indices of attributes are located, otherwise
+ * the ones of AttributeLocator objects
+ * @return the indices of the attributes or the AttributeLocator objects
*/
protected int[] find(boolean findAtts) {
- int i;
- int[] result;
- Vector indices;
+ int i;
+ int[] result;
+ ArrayList<Integer> indices;
// determine locations
- indices = new Vector();
+ indices = new ArrayList<Integer>();
if (findAtts) {
for (i = 0; i < m_Attributes.size(); i++) {
- if (((Boolean) m_Attributes.get(i)).booleanValue())
- indices.add(new Integer(i));
+ if (m_Attributes.get(i)) {
+ indices.add(new Integer(i));
+ }
}
- }
- else {
+ } else {
for (i = 0; i < m_Locators.size(); i++) {
- if (m_Locators.get(i) != null)
- indices.add(new Integer(i));
+ if (m_Locators.get(i) != null) {
+ indices.add(new Integer(i));
+ }
}
}
-
+
// fill array
result = new int[indices.size()];
- for (i = 0; i < indices.size(); i++)
- result[i] = ((Integer) indices.get(i)).intValue();
-
+ for (i = 0; i < indices.size(); i++) {
+ result[i] = indices.get(i).intValue();
+ }
+
return result;
}
/**
* returns actual index in the Instances object.
*
- * @param index the index in the m_AllowedIndices array
- * @return the actual index in the instances object
+ * @param index the index in the m_AllowedIndices array
+ * @return the actual index in the instances object
*/
public int getActualIndex(int index) {
return m_AllowedIndices[index];
}
-
+
/**
- * Returns the indices of the attributes. These indices are referring
- * to the m_AllowedIndices array, not the actual indices in the Instances
- * object.
+ * Returns the indices of the attributes. These indices are referring to the
+ * m_AllowedIndices array, not the actual indices in the Instances object.
*
- * @return the indices of the attributes
- * @see #getActualIndex(int)
+ * @return the indices of the attributes
+ * @see #getActualIndex(int)
*/
public int[] getAttributeIndices() {
return m_Indices;
}
-
+
/**
- * Returns the indices of the AttributeLocator objects. These indices are
- * referring to the m_AllowedIndices array, not the actual indices in the
+ * Returns the indices of the AttributeLocator objects. These indices are
+ * referring to the m_AllowedIndices array, not the actual indices in the
* Instances object.
*
- * @return the indices of the AttributeLocator objects
- * @see #getActualIndex(int)
+ * @return the indices of the AttributeLocator objects
+ * @see #getActualIndex(int)
*/
public int[] getLocatorIndices() {
return m_LocatorIndices;
}
-
+
/**
- * Returns the AttributeLocator at the given index. This index refers to
- * the index of the m_AllowedIndices array, not the actual Instances object.
+ * Returns the AttributeLocator at the given index. This index refers to the
+ * index of the m_AllowedIndices array, not the actual Instances object.
*
- * @param index the index of the locator to retrieve
- * @return the AttributeLocator at the given index
+ * @param index the index of the locator to retrieve
+ * @return the AttributeLocator at the given index
*/
public AttributeLocator getLocator(int index) {
- return (AttributeLocator) m_Locators.get(index);
+ return m_Locators.get(index);
}
-
+
/**
- * Compares this object with the specified object for order. Returns a
- * negative integer, zero, or a positive integer as this object is less
- * than, equal to, or greater than the specified object. Only type and
- * indices are checked.
+ * Compares this object with the specified object for order. Returns a
+ * negative integer, zero, or a positive integer as this object is less than,
+ * equal to, or greater than the specified object. Only type and indices are
+ * checked.
*
- * @param o the object to compare with
- * @return -1 if less than, 0 if equal, +1 if greater than the
- * given object
+ * @param o the object to compare with
+ * @return -1 if less than, 0 if equal, +1 if greater than the given object
*/
+ @Override
public int compareTo(AttributeLocator o) {
- int result;
- int i;
-
+ int result;
+ int i;
+
result = 0;
-
+
// 1. check type
if (this.getType() < o.getType()) {
result = -1;
- }
- else if (this.getType() > o.getType()) {
+ } else if (this.getType() > o.getType()) {
result = 1;
- }
- else {
+ } else {
// 2. check indices
if (this.getAllowedIndices().length < o.getAllowedIndices().length) {
- result = -1;
- }
- else if (this.getAllowedIndices().length > o.getAllowedIndices().length) {
- result = 1;
- }
- else {
- for (i = 0; i < this.getAllowedIndices().length; i++) {
- if (this.getAllowedIndices()[i] < o.getAllowedIndices()[i]) {
- result = -1;
- break;
- }
- else if (this.getAllowedIndices()[i] > o.getAllowedIndices()[i]) {
- result = 1;
- break;
- }
- else {
- result = 0;
- }
- }
+ result = -1;
+ } else if (this.getAllowedIndices().length > o.getAllowedIndices().length) {
+ result = 1;
+ } else {
+ for (i = 0; i < this.getAllowedIndices().length; i++) {
+ if (this.getAllowedIndices()[i] < o.getAllowedIndices()[i]) {
+ result = -1;
+ break;
+ } else if (this.getAllowedIndices()[i] > o.getAllowedIndices()[i]) {
+ result = 1;
+ break;
+ } else {
+ result = 0;
+ }
+ }
}
}
-
+
return result;
}
-
+
/**
- * Indicates whether some other object is "equal to" this one. Only type
- * and indices are checked.
+ * Indicates whether some other object is "equal to" this one. Only type and
+ * indices are checked.
*
- * @param o the AttributeLocator to check for equality
- * @return true if the AttributeLocators have the same type and
- * indices
+ * @param o the AttributeLocator to check for equality
+ * @return true if the AttributeLocators have the same type and indices
*/
+ @Override
public boolean equals(Object o) {
return (compareTo((AttributeLocator) o) == 0);
}
-
+
/**
* returns a string representation of this object
*
- * @return a string representation
+ * @return a string representation
*/
+ @Override
public String toString() {
return m_Attributes.toString();
}
-
+
/**
* Returns the revision string.
*
- * @return the revision
+ * @return the revision
*/
+ @Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 1.4 $");
}
diff --git a/src/main/java/weka/core/Copyright.props b/src/main/java/weka/core/Copyright.props
index 95f82e8..408b89e 100644
--- a/src/main/java/weka/core/Copyright.props
+++ b/src/main/java/weka/core/Copyright.props
@@ -1,10 +1,10 @@
# central copyright information
#
# Author: FracPete (fracpete at waikato dot ac dot nz)
-# Version: $Revision: 9441 $
+# Version: $Revision: 10644 $
FromYear=1999
-ToYear=2013
+ToYear=2014
Owner=The University of Waikato
Address=Hamilton, New Zealand
URL=http://www.cs.waikato.ac.nz/~ml/weka/
diff --git a/src/main/java/weka/core/DistanceFunction.java b/src/main/java/weka/core/DistanceFunction.java
index da6ffa4..c943071 100644
--- a/src/main/java/weka/core/DistanceFunction.java
+++ b/src/main/java/weka/core/DistanceFunction.java
@@ -27,133 +27,136 @@ import weka.core.neighboursearch.PerformanceStats;
/**
* Interface for any class that can compute and return distances between two
* instances.
- *
- * @author Ashraf M. Kibriya (amk14 at cs.waikato.ac.nz)
- * @version $Revision: 1.7 $
+ *
+ * @author Ashraf M. Kibriya (amk14 at cs.waikato.ac.nz)
+ * @version $Revision: 1.7 $
*/
public interface DistanceFunction extends OptionHandler {
/**
* Sets the instances.
*
- * @param insts the instances to use
+ * @param insts the instances to use
*/
public void setInstances(Instances insts);
/**
* returns the instances currently set.
*
- * @return the current instances
+ * @return the current instances
*/
public Instances getInstances();
/**
- * Sets the range of attributes to use in the calculation of the distance.
- * The indices start from 1, 'first' and 'last' are valid as well.
- * E.g.: first-3,5,6-last
+ * Sets the range of attributes to use in the calculation of the distance. The
+ * indices start from 1, 'first' and 'last' are valid as well. E.g.:
+ * first-3,5,6-last
*
- * @param value the new attribute index range
+ * @param value the new attribute index range
*/
public void setAttributeIndices(String value);
-
+
/**
* Gets the range of attributes used in the calculation of the distance.
*
- * @return the attribute index range
+ * @return the attribute index range
*/
public String getAttributeIndices();
-
+
/**
* Sets whether the matching sense of attribute indices is inverted or not.
*
- * @param value if true the matching sense is inverted
+ * @param value if true the matching sense is inverted
*/
public void setInvertSelection(boolean value);
-
+
/**
* Gets whether the matching sense of attribute indices is inverted or not.
*
- * @return true if the matching sense is inverted
+ * @return true if the matching sense is inverted
*/
public boolean getInvertSelection();
/**
* Calculates the distance between two instances.
*
- * @param first the first instance
- * @param second the second instance
- * @return the distance between the two given instances
+ * @param first the first instance
+ * @param second the second instance
+ * @return the distance between the two given instances
*/
public double distance(Instance first, Instance second);
/**
* Calculates the distance between two instances.
*
- * @param first the first instance
- * @param second the second instance
- * @param stats the performance stats object
- * @return the distance between the two given instances
- * @throws Exception if calculation fails
+ * @param first the first instance
+ * @param second the second instance
+ * @param stats the performance stats object
+ * @return the distance between the two given instances
+ * @throws Exception if calculation fails
*/
- public double distance(Instance first, Instance second, PerformanceStats stats)
- throws Exception;
+ public double distance(Instance first, Instance second, PerformanceStats stats)
+ throws Exception;
/**
- * Calculates the distance between two instances. Offers speed up (if the
- * distance function class in use supports it) in nearest neighbour search by
- * taking into account the cutOff or maximum distance. Depending on the
- * distance function class, post processing of the distances by
+ * Calculates the distance between two instances. Offers speed up (if the
+ * distance function class in use supports it) in nearest neighbour search by
+ * taking into account the cutOff or maximum distance. Depending on the
+ * distance function class, post processing of the distances by
* postProcessDistances(double []) may be required if this function is used.
- *
- * @param first the first instance
- * @param second the second instance
- * @param cutOffValue If the distance being calculated becomes larger than
- * cutOffValue then the rest of the calculation is
- * discarded.
- * @return the distance between the two given instances or
- * Double.POSITIVE_INFINITY if the distance being
- * calculated becomes larger than cutOffValue.
+ *
+ * @param first the first instance
+ * @param second the second instance
+ * @param cutOffValue If the distance being calculated becomes larger than
+ * cutOffValue then the rest of the calculation is discarded.
+ * @return the distance between the two given instances or
+ * Double.POSITIVE_INFINITY if the distance being calculated becomes
+ * larger than cutOffValue.
*/
public double distance(Instance first, Instance second, double cutOffValue);
/**
- * Calculates the distance between two instances. Offers speed up (if the
- * distance function class in use supports it) in nearest neighbour search by
- * taking into account the cutOff or maximum distance. Depending on the
- * distance function class, post processing of the distances by
+ * Calculates the distance between two instances. Offers speed up (if the
+ * distance function class in use supports it) in nearest neighbour search by
+ * taking into account the cutOff or maximum distance. Depending on the
+ * distance function class, post processing of the distances by
* postProcessDistances(double []) may be required if this function is used.
- *
- * @param first the first instance
- * @param second the second instance
- * @param cutOffValue If the distance being calculated becomes larger than
- * cutOffValue then the rest of the calculation is
- * discarded.
- * @param stats the performance stats object
- * @return the distance between the two given instances or
- * Double.POSITIVE_INFINITY if the distance being
- * calculated becomes larger than cutOffValue.
+ *
+ * @param first the first instance
+ * @param second the second instance
+ * @param cutOffValue If the distance being calculated becomes larger than
+ * cutOffValue then the rest of the calculation is discarded.
+ * @param stats the performance stats object
+ * @return the distance between the two given instances or
+ * Double.POSITIVE_INFINITY if the distance being calculated becomes
+ * larger than cutOffValue.
*/
- public double distance(Instance first, Instance second,
- double cutOffValue, PerformanceStats stats);
+ public double distance(Instance first, Instance second, double cutOffValue,
+ PerformanceStats stats);
/**
* Does post processing of the distances (if necessary) returned by
* distance(distance(Instance first, Instance second, double cutOffValue). It
* may be necessary, depending on the distance function, to do post processing
* to set the distances on the correct scale. Some distance function classes
- * may not return correct distances using the cutOffValue distance function to
- * minimize the inaccuracies resulting from floating point comparison and
+ * may not return correct distances using the cutOffValue distance function to
+ * minimize the inaccuracies resulting from floating point comparison and
* manipulation.
*
- * @param distances the distances to post-process
+ * @param distances the distances to post-process
*/
public void postProcessDistances(double distances[]);
/**
* Update the distance function (if necessary) for the newly added instance.
*
- * @param ins the instance to add
+ * @param ins the instance to add
*/
public void update(Instance ins);
+ /**
+ * Free any references to training instances
+ */
+ public void clean();
+
}
diff --git a/src/main/java/weka/core/Instances.java b/src/main/java/weka/core/Instances.java
index 217bbfd..571edf7 100644
--- a/src/main/java/weka/core/Instances.java
+++ b/src/main/java/weka/core/Instances.java
@@ -67,7 +67,7 @@ import weka.core.converters.ConverterUtils.DataSource;
* @author Eibe Frank (eibe at cs.waikato.ac.nz)
* @author Len Trigg (trigg at cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9764 $
+ * @version $Revision: 10497 $
*/
public class Instances implements Serializable, RevisionHandler {
@@ -116,13 +116,6 @@ public class Instances implements Serializable, RevisionHandler {
protected int m_Lines = 0;
/**
- * used in randomizeAttribute and undoRandomizeAttribute to store/restore the
- * index of attribute that was last shuffled, and it's original values
- */
- private final int attIdx4Randomization = -1;
- private double[] attIdxOrigValues;
-
- /**
* Reads an ARFF file from a reader, and assigns a weight of one to each
* instance. Lets the index of the class attribute be undefined (negative).
*
@@ -156,8 +149,7 @@ public class Instances implements Serializable, RevisionHandler {
// @ requires capacity >= 0;
// @ ensures classIndex() == -1;
@Deprecated
- public Instances(/* @non_null@ */Reader reader, int capacity)
- throws IOException {
+ public Instances(/* @non_null@ */Reader reader, int capacity) throws IOException {
ArffReader arff = new ArffReader(reader, 0);
Instances header = arff.getStructure();
@@ -199,8 +191,9 @@ public class Instances implements Serializable, RevisionHandler {
* @param capacity the number of rows to reserve
*/
protected void initialize(Instances dataset, int capacity) {
- if (capacity < 0)
+ if (capacity < 0) {
capacity = 0;
+ }
// Strings only have to be "shallow" copied because
// they can't be modified.
@@ -227,7 +220,7 @@ public class Instances implements Serializable, RevisionHandler {
if ((first < 0) || ((first + toCopy) > source.numInstances())) {
throw new IllegalArgumentException("Parameters first and/or toCopy out "
- + "of range");
+ + "of range");
}
source.copyInstances(first, this, toCopy);
}
@@ -251,13 +244,14 @@ public class Instances implements Serializable, RevisionHandler {
for (int i = 0; i < attInfo.size(); i++) {
if (names.contains(((Attribute) attInfo.elementAt(i)).name())) {
nonUniqueNames.append("'" + ((Attribute) attInfo.elementAt(i)).name()
- + "' ");
+ + "' ");
}
names.add(((Attribute) attInfo.elementAt(i)).name());
}
- if (names.size() != attInfo.size())
+ if (names.size() != attInfo.size()) {
throw new IllegalArgumentException("Attribute names are not unique!"
- + " Causes: " + nonUniqueNames.toString());
+ + " Causes: " + nonUniqueNames.toString());
+ }
names.clear();
m_RelationName = name;
@@ -285,7 +279,7 @@ public class Instances implements Serializable, RevisionHandler {
newAtts.addElement(new Attribute(att.name(), (FastVector) null, i));
} else if (att.type() == Attribute.RELATIONAL) {
newAtts.addElement(new Attribute(att.name(), new Instances(att
- .relation(), 0), i));
+ .relation(), 0), i));
}
}
if (newAtts.size() == 0) {
@@ -294,7 +288,7 @@ public class Instances implements Serializable, RevisionHandler {
FastVector atts = (FastVector) m_Attributes.copy();
for (int i = 0; i < newAtts.size(); i++) {
atts.setElementAt(newAtts.elementAt(i),
- ((Attribute) newAtts.elementAt(i)).index());
+ ((Attribute) newAtts.elementAt(i)).index());
}
Instances result = new Instances(this, 0);
result.m_Attributes = atts;
@@ -397,7 +391,7 @@ public class Instances implements Serializable, RevisionHandler {
if (!(Utils.eq(instance.value(i), (int) instance.value(i)))) {
return false;
} else if (Utils.sm(instance.value(i), 0)
- || Utils.gr(instance.value(i), attribute(i).numValues())) {
+ || Utils.gr(instance.value(i), attribute(i).numValues())) {
return false;
}
}
@@ -569,7 +563,8 @@ public class Instances implements Serializable, RevisionHandler {
}
/**
- * Returns an enumeration of all the attributes.
+ * Returns an enumeration of all the attributes. The class attribute (if set)
+ * is skipped by this enumeration.
*
* @return enumeration of all the attributes.
*/
@@ -635,7 +630,7 @@ public class Instances implements Serializable, RevisionHandler {
Random r = new Random(seed);
r.setSeed(instance(r.nextInt(numInstances())).toStringNoWeight().hashCode()
- + seed);
+ + seed);
return r;
}
@@ -657,7 +652,7 @@ public class Instances implements Serializable, RevisionHandler {
}
if (attribute(att.name()) != null) {
throw new IllegalArgumentException("Attribute name '" + att.name()
- + "' already in use at position #" + attribute(att.name()).index());
+ + "' already in use at position #" + attribute(att.name()).index());
}
att = (Attribute) att.copy();
freshAttributeInfo();
@@ -713,12 +708,12 @@ public class Instances implements Serializable, RevisionHandler {
if (!attribute(attIndex).isNumeric()) {
throw new IllegalArgumentException(
- "Instances: attribute must be numeric to compute kth-smallest value.");
+ "Instances: attribute must be numeric to compute kth-smallest value.");
}
if ((k < 1) || (k > numInstances())) {
throw new IllegalArgumentException(
- "Instances: value for k for computing kth-smallest value too large.");
+ "Instances: value for k for computing kth-smallest value too large.");
}
double[] vals = new double[numInstances()];
@@ -891,8 +886,9 @@ public class Instances implements Serializable, RevisionHandler {
*/
public void randomize(Random random) {
- for (int j = numInstances() - 1; j > 0; j--)
+ for (int j = numInstances() - 1; j > 0; j--) {
swap(j, random.nextInt(j + 1));
+ }
}
/**
@@ -945,11 +941,12 @@ public class Instances implements Serializable, RevisionHandler {
public void renameAttribute(int att, String name) {
// name already present?
for (int i = 0; i < numAttributes(); i++) {
- if (i == att)
+ if (i == att) {
continue;
+ }
if (attribute(i).name().equals(name)) {
throw new IllegalArgumentException("Attribute name '" + name
- + "' already present at position #" + i);
+ + "' already present at position #" + i);
}
}
@@ -1011,8 +1008,9 @@ public class Instances implements Serializable, RevisionHandler {
public void renameAttributeValue(Attribute att, String val, String name) {
int v = att.indexOfValue(val);
- if (v == -1)
+ if (v == -1) {
throw new IllegalArgumentException(val + " not found");
+ }
renameAttributeValue(att.index(), v, name);
}
@@ -1100,7 +1098,7 @@ public class Instances implements Serializable, RevisionHandler {
* length or contains negative weights.
*/
public Instances resampleWithWeights(Random random, double[] weights,
- boolean[] sampled) {
+ boolean[] sampled) {
if (weights.length != numInstances()) {
throw new IllegalArgumentException("weights.length != numInstances.");
@@ -1263,7 +1261,7 @@ public class Instances implements Serializable, RevisionHandler {
if (numFolds <= 1) {
throw new IllegalArgumentException(
- "Number of folds must be greater than 1");
+ "Number of folds must be greater than 1");
}
if (m_ClassIndex < 0) {
throw new UnassignedClassException("Class index is negative (not set)!");
@@ -1277,7 +1275,7 @@ public class Instances implements Serializable, RevisionHandler {
for (int j = index; j < numInstances(); j++) {
Instance instance2 = instance(j);
if ((instance1.classValue() == instance2.classValue())
- || (instance1.classIsMissing() && instance2.classIsMissing())) {
+ || (instance1.classIsMissing() && instance2.classIsMissing())) {
swap(index, j);
index++;
}
@@ -1325,14 +1323,15 @@ public class Instances implements Serializable, RevisionHandler {
}
if (numFolds > numInstances()) {
throw new IllegalArgumentException(
- "Can't have more folds than instances!");
+ "Can't have more folds than instances!");
}
numInstForFold = numInstances() / numFolds;
if (numFold < numInstances() % numFolds) {
numInstForFold++;
offset = numFold;
- } else
+ } else {
offset = numInstances() % numFolds;
+ }
test = new Instances(this, numInstForFold);
first = numFold * (numInstances() / numFolds) + offset;
copyInstances(first, test, numInstForFold);
@@ -1351,7 +1350,7 @@ public class Instances implements Serializable, RevisionHandler {
StringBuffer text = new StringBuffer();
text.append(ARFF_RELATION).append(" ").append(Utils.quote(m_RelationName))
- .append("\n\n");
+ .append("\n\n");
for (int i = 0; i < numAttributes(); i++) {
text.append(attribute(i)).append("\n");
}
@@ -1403,19 +1402,20 @@ public class Instances implements Serializable, RevisionHandler {
}
if (numFolds > numInstances()) {
throw new IllegalArgumentException(
- "Can't have more folds than instances!");
+ "Can't have more folds than instances!");
}
numInstForFold = numInstances() / numFolds;
if (numFold < numInstances() % numFolds) {
numInstForFold++;
offset = numFold;
- } else
+ } else {
offset = numInstances() % numFolds;
+ }
train = new Instances(this, numInstances() - numInstForFold);
first = numFold * (numInstances() / numFolds) + offset;
copyInstances(0, train, first);
copyInstances(first + numInstForFold, train, numInstances() - first
- - numInstForFold);
+ - numInstForFold);
return train;
}
@@ -1455,13 +1455,13 @@ public class Instances implements Serializable, RevisionHandler {
if (!attribute(attIndex).isNumeric()) {
throw new IllegalArgumentException(
- "Can't compute variance because attribute is " + "not numeric!");
+ "Can't compute variance because attribute is " + "not numeric!");
}
for (int i = 0; i < numInstances(); i++) {
if (!instance(i).isMissing(attIndex)) {
sum += instance(i).weight() * instance(i).value(attIndex);
sumSquared += instance(i).weight() * instance(i).value(attIndex)
- * instance(i).value(attIndex);
+ * instance(i).value(attIndex);
sumOfWeights += instance(i).weight();
}
}
@@ -1469,7 +1469,7 @@ public class Instances implements Serializable, RevisionHandler {
return 0;
}
double result = (sumSquared - (sum * sum / sumOfWeights))
- / (sumOfWeights - 1);
+ / (sumOfWeights - 1);
// We don't like negative variance
if (result < 0) {
@@ -1733,7 +1733,7 @@ public class Instances implements Serializable, RevisionHandler {
if (first.numInstances() != second.numInstances()) {
throw new IllegalArgumentException(
- "Instance sets must be of the same size");
+ "Instance sets must be of the same size");
}
// Create the vector of merged attributes
@@ -1747,7 +1747,7 @@ public class Instances implements Serializable, RevisionHandler {
// Create the set of Instances
Instances merged = new Instances(first.relationName() + '_'
- + second.relationName(), newAttributes, first.numInstances());
+ + second.relationName(), newAttributes, first.numInstances());
// Merge each instance
for (int i = 0; i < first.numInstances(); i++) {
merged.add(first.instance(i).mergeInstance(second.instance(i)));
@@ -1823,9 +1823,9 @@ public class Instances implements Serializable, RevisionHandler {
System.out.println("\nClass name: " + instances.classAttribute().name());
System.out.println("\nClass index: " + instances.classIndex());
System.out.println("\nClass is nominal: "
- + instances.classAttribute().isNominal());
+ + instances.classAttribute().isNominal());
System.out.println("\nClass is numeric: "
- + instances.classAttribute().isNumeric());
+ + instances.classAttribute().isNumeric());
System.out.println("\nClasses:\n");
for (i = 0; i < instances.numClasses(); i++) {
System.out.println(instances.classAttribute().value(i));
@@ -1861,18 +1861,18 @@ public class Instances implements Serializable, RevisionHandler {
System.out.println("\nSet with inserted attribute:\n");
System.out.println(secondInstances);
System.out.println("\nClass name: "
- + secondInstances.classAttribute().name());
+ + secondInstances.classAttribute().name());
// Delete the attribute
secondInstances.deleteAttributeAt(0);
System.out.println("\nSet with attribute deleted:\n");
System.out.println(secondInstances);
System.out.println("\nClass name: "
- + secondInstances.classAttribute().name());
+ + secondInstances.classAttribute().name());
// Test if headers are equal
System.out.println("\nHeaders equal: "
- + instances.equalHeaders(secondInstances) + "\n");
+ + instances.equalHeaders(secondInstances) + "\n");
// Print data in internal format.
System.out.println("\nData (internal values):\n");
@@ -1898,7 +1898,7 @@ public class Instances implements Serializable, RevisionHandler {
Instances copy = new Instances(empty, 0);
copy.renameAttribute(copy.classAttribute(), "new_name");
copy.renameAttributeValue(copy.classAttribute(), copy.classAttribute()
- .value(0), "new_val_name");
+ .value(0), "new_val_name");
System.out.println("\nDataset with names changed:\n" + copy);
System.out.println("\nOriginal dataset:\n" + empty);
}
@@ -1910,7 +1910,7 @@ public class Instances implements Serializable, RevisionHandler {
System.out.println(num + " instances from " + (start + 1) + ". instance");
secondInstances = new Instances(instances, start, num);
System.out.println("\nClass name: "
- + secondInstances.classAttribute().name());
+ + secondInstances.classAttribute().name());
// Print all instances and their weights (and the sum of weights).
System.out.println("\nInstances and their weights:\n");
@@ -2011,7 +2011,7 @@ public class Instances implements Serializable, RevisionHandler {
}
// read file and print statistics
else if ((args.length == 1) && (!args[0].equals("-h"))
- && (!args[0].equals("help"))) {
+ && (!args[0].equals("help"))) {
DataSource source = new DataSource(args[0]);
i = source.getDataSet();
System.out.println(i.toSummaryString());
@@ -2021,35 +2021,39 @@ public class Instances implements Serializable, RevisionHandler {
DataSource source1 = new DataSource(args[1]);
DataSource source2 = new DataSource(args[2]);
i = Instances
- .mergeInstances(source1.getDataSet(), source2.getDataSet());
+ .mergeInstances(source1.getDataSet(), source2.getDataSet());
System.out.println(i);
}
// read two files, append them and print result to stdout
else if ((args.length == 3) && (args[0].toLowerCase().equals("append"))) {
DataSource source1 = new DataSource(args[1]);
DataSource source2 = new DataSource(args[2]);
- if (!source1.getStructure().equalHeaders(source2.getStructure()))
+ if (!source1.getStructure().equalHeaders(source2.getStructure())) {
throw new Exception("The two datasets have different headers!");
+ }
Instances structure = source1.getStructure();
System.out.println(source1.getStructure());
- while (source1.hasMoreElements(structure))
+ while (source1.hasMoreElements(structure)) {
System.out.println(source1.nextElement(structure));
+ }
structure = source2.getStructure();
- while (source2.hasMoreElements(structure))
+ while (source2.hasMoreElements(structure)) {
System.out.println(source2.nextElement(structure));
+ }
}
// read two files and compare their headers
else if ((args.length == 3) && (args[0].toLowerCase().equals("headers"))) {
DataSource source1 = new DataSource(args[1]);
DataSource source2 = new DataSource(args[2]);
- if (source1.getStructure().equalHeaders(source2.getStructure()))
+ if (source1.getStructure().equalHeaders(source2.getStructure())) {
System.out.println("Headers match");
- else
+ } else {
System.out.println("Headers don't match");
+ }
}
// read file and seed value, randomize data and print result to stdout
else if ((args.length == 3)
- && (args[0].toLowerCase().equals("randomize"))) {
+ && (args[0].toLowerCase().equals("randomize"))) {
DataSource source = new DataSource(args[2]);
i = source.getDataSet();
i.randomize(new Random(Integer.parseInt(args[1])));
@@ -2058,11 +2062,11 @@ public class Instances implements Serializable, RevisionHandler {
// wrong parameters
else {
System.err.println("\nUsage:\n" + "\tweka.core.Instances help\n"
- + "\tweka.core.Instances <filename>\n"
- + "\tweka.core.Instances merge <filename1> <filename2>\n"
- + "\tweka.core.Instances append <filename1> <filename2>\n"
- + "\tweka.core.Instances headers <filename1> <filename2>\n"
- + "\tweka.core.Instances randomize <seed> <filename>\n");
+ + "\tweka.core.Instances <filename>\n"
+ + "\tweka.core.Instances merge <filename1> <filename2>\n"
+ + "\tweka.core.Instances append <filename1> <filename2>\n"
+ + "\tweka.core.Instances headers <filename1> <filename2>\n"
+ + "\tweka.core.Instances randomize <seed> <filename>\n");
}
} catch (Exception ex) {
ex.printStackTrace();
@@ -2075,7 +2079,8 @@ public class Instances implements Serializable, RevisionHandler {
*
* @return the revision
*/
+ @Override
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9764 $");
+ return RevisionUtils.extract("$Revision: 10497 $");
}
}
diff --git a/src/main/java/weka/core/Memory.java b/src/main/java/weka/core/Memory.java
index a84a613..30bdc37 100644
--- a/src/main/java/weka/core/Memory.java
+++ b/src/main/java/weka/core/Memory.java
@@ -37,15 +37,24 @@ import javax.swing.JOptionPane;
*/
public class Memory implements RevisionHandler {
+ public static final long OUT_OF_MEMORY_THRESHOLD = 52428800L;
+
+ public static final long LOW_MEMORY_MINIMUM = 104857600L;
+
+ public static final long MAX_SLEEP_TIME = 10L;
+
/** whether memory management is enabled */
protected static boolean m_Enabled = true;
/** whether a GUI is present */
protected boolean m_UseGUI = false;
+ /** the delay before testing for out of memory */
+ protected long m_SleepTime = MAX_SLEEP_TIME;
+
/** the managed bean to use */
protected static MemoryMXBean m_MemoryMXBean = ManagementFactory
- .getMemoryMXBean();
+ .getMemoryMXBean();
/** the last MemoryUsage object obtained */
protected MemoryUsage m_MemoryUsage = null;
@@ -137,11 +146,30 @@ public class Memory implements RevisionHandler {
* false)
*/
public boolean isOutOfMemory() {
+ try {
+ Thread.sleep(m_SleepTime);
+ } catch (InterruptedException ex) {
+ ex.printStackTrace();
+ }
+
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
if (isEnabled()) {
- return ((m_MemoryUsage.getMax() - m_MemoryUsage.getUsed()) < 52428800);
- } else
+
+ long avail = m_MemoryUsage.getMax() - m_MemoryUsage.getUsed();
+ if (avail > OUT_OF_MEMORY_THRESHOLD) {
+ long num = (avail - OUT_OF_MEMORY_THRESHOLD) / 5242880 + 1;
+
+ m_SleepTime = (long) (2.0 * (Math.log(num) + 2.5));
+ if (m_SleepTime > MAX_SLEEP_TIME) {
+ m_SleepTime = MAX_SLEEP_TIME;
+ }
+ // System.out.println("Delay = " + m_SleepTime);
+ }
+
+ return avail < OUT_OF_MEMORY_THRESHOLD;
+ } else {
return false;
+ }
}
/**
@@ -157,8 +185,8 @@ public class Memory implements RevisionHandler {
long lowThreshold = (long) (0.2 * m_MemoryUsage.getMax());
// min threshold of 100Mb
- if (lowThreshold < 104857600) {
- lowThreshold = 104857600;
+ if (lowThreshold < LOW_MEMORY_MINIMUM) {
+ lowThreshold = LOW_MEMORY_MINIMUM;
}
long avail = m_MemoryUsage.getMax() - m_MemoryUsage.getUsed();
@@ -187,36 +215,38 @@ public class Memory implements RevisionHandler {
* @see #m_Enabled
*/
public void showOutOfMemory() {
- if (!isEnabled() || (m_MemoryUsage == null))
+ if (!isEnabled() || (m_MemoryUsage == null)) {
return;
+ }
System.gc();
String msg = "Not enough memory (less than 50MB left on heap). Please load a smaller "
- + "dataset or use a larger heap size.\n"
- + "- initial heap size: "
- + Utils.doubleToString(toMegaByte(m_MemoryUsage.getInit()), 1)
- + "MB\n"
- + "- current memory (heap) used: "
- + Utils.doubleToString(toMegaByte(m_MemoryUsage.getUsed()), 1)
- + "MB\n"
- + "- max. memory (heap) available: "
- + Utils.doubleToString(toMegaByte(m_MemoryUsage.getMax()), 1)
- + "MB\n"
- + "\n"
- + "Note:\n"
- + "The Java heap size can be specified with the -Xmx option.\n"
- + "E.g., to use 128MB as heap size, the command line looks like this:\n"
- + " java -Xmx128m -classpath ...\n"
- + "This does NOT work in the SimpleCLI, the above java command refers\n"
- + "to the one with which Weka is started. See the Weka FAQ on the web\n"
- + "for further info.";
+ + "dataset or use a larger heap size.\n"
+ + "- initial heap size: "
+ + Utils.doubleToString(toMegaByte(m_MemoryUsage.getInit()), 1)
+ + "MB\n"
+ + "- current memory (heap) used: "
+ + Utils.doubleToString(toMegaByte(m_MemoryUsage.getUsed()), 1)
+ + "MB\n"
+ + "- max. memory (heap) available: "
+ + Utils.doubleToString(toMegaByte(m_MemoryUsage.getMax()), 1)
+ + "MB\n"
+ + "\n"
+ + "Note:\n"
+ + "The Java heap size can be specified with the -Xmx option.\n"
+ + "E.g., to use 128MB as heap size, the command line looks like this:\n"
+ + " java -Xmx128m -classpath ...\n"
+ + "This does NOT work in the SimpleCLI, the above java command refers\n"
+ + "to the one with which Weka is started. See the Weka FAQ on the web\n"
+ + "for further info.";
System.err.println(msg);
- if (getUseGUI())
+ if (getUseGUI()) {
JOptionPane.showMessageDialog(null, msg, "OutOfMemory",
- JOptionPane.WARNING_MESSAGE);
+ JOptionPane.WARNING_MESSAGE);
+ }
}
/**
@@ -225,30 +255,31 @@ public class Memory implements RevisionHandler {
* @return true if user opts to continue, disabled or GUI is not present.
*/
public boolean showMemoryIsLow() {
- if (!isEnabled() || (m_MemoryUsage == null))
+ if (!isEnabled() || (m_MemoryUsage == null)) {
return true;
+ }
String msg = "Warning: memory is running low - available heap space is less than "
- + "20% of maximum or 100MB (whichever is greater)\n\n"
- + "- initial heap size: "
- + Utils.doubleToString(toMegaByte(m_MemoryUsage.getInit()), 1)
- + "MB\n"
- + "- current memory (heap) used: "
- + Utils.doubleToString(toMegaByte(m_MemoryUsage.getUsed()), 1)
- + "MB\n"
- + "- max. memory (heap) available: "
- + Utils.doubleToString(toMegaByte(m_MemoryUsage.getMax()), 1)
- + "MB\n\n"
- + "Consider deleting some results before continuing.\nCheck the Weka FAQ "
- + "on the web for suggestions on how to save memory.\n"
- + "Note that Weka will shut down when less than 50MB remain."
- + "\nDo you wish to continue regardless?\n\n";
+ + "20% of maximum or 100MB (whichever is greater)\n\n"
+ + "- initial heap size: "
+ + Utils.doubleToString(toMegaByte(m_MemoryUsage.getInit()), 1)
+ + "MB\n"
+ + "- current memory (heap) used: "
+ + Utils.doubleToString(toMegaByte(m_MemoryUsage.getUsed()), 1)
+ + "MB\n"
+ + "- max. memory (heap) available: "
+ + Utils.doubleToString(toMegaByte(m_MemoryUsage.getMax()), 1)
+ + "MB\n\n"
+ + "Consider deleting some results before continuing.\nCheck the Weka FAQ "
+ + "on the web for suggestions on how to save memory.\n"
+ + "Note that Weka will shut down when less than 50MB remain."
+ + "\nDo you wish to continue regardless?\n\n";
System.err.println(msg);
if (getUseGUI()) {
int result = JOptionPane.showConfirmDialog(null, msg, "Low Memory",
- JOptionPane.YES_NO_OPTION);
+ JOptionPane.YES_NO_OPTION);
return (result == JOptionPane.YES_OPTION);
}
@@ -271,10 +302,11 @@ public class Memory implements RevisionHandler {
t = thGroup[i];
if (t != null) {
if (t != Thread.currentThread()) {
- if (t.getName().startsWith("Thread"))
+ if (t.getName().startsWith("Thread")) {
t.stop();
- else if (t.getName().startsWith("AWT-EventQueue"))
+ } else if (t.getName().startsWith("AWT-EventQueue")) {
t.stop();
+ }
}
}
}
@@ -289,6 +321,7 @@ public class Memory implements RevisionHandler {
*
* @return the revision
*/
+ @Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 9487 $");
}
@@ -301,10 +334,10 @@ public class Memory implements RevisionHandler {
public static void main(String[] args) {
Memory mem = new Memory();
System.out.println("Initial memory: "
- + Utils.doubleToString(Memory.toMegaByte(mem.getInitial()), 1) + "MB"
- + " (" + mem.getInitial() + ")");
+ + Utils.doubleToString(Memory.toMegaByte(mem.getInitial()), 1) + "MB"
+ + " (" + mem.getInitial() + ")");
System.out.println("Max memory: "
- + Utils.doubleToString(Memory.toMegaByte(mem.getMax()), 1) + "MB"
- + " (" + mem.getMax() + ")");
+ + Utils.doubleToString(Memory.toMegaByte(mem.getMax()), 1) + "MB" + " ("
+ + mem.getMax() + ")");
}
}
diff --git a/src/main/java/weka/core/NormalizableDistance.java b/src/main/java/weka/core/NormalizableDistance.java
index 0408058..07f1a37 100644
--- a/src/main/java/weka/core/NormalizableDistance.java
+++ b/src/main/java/weka/core/NormalizableDistance.java
@@ -22,40 +22,42 @@
package weka.core;
-import weka.core.neighboursearch.PerformanceStats;
-
import java.io.Serializable;
import java.util.Enumeration;
import java.util.Vector;
+import weka.core.neighboursearch.PerformanceStats;
+
/**
* Represents the abstract ancestor for normalizable distance functions, like
* Euclidean or Manhattan distance.
- *
+ *
* @author Fracpete (fracpete at waikato dot ac dot nz)
- * @author Gabi Schmidberger (gabi at cs.waikato.ac.nz) -- original code from weka.core.EuclideanDistance
- * @author Ashraf M. Kibriya (amk14 at cs.waikato.ac.nz) -- original code from weka.core.EuclideanDistance
+ * @author Gabi Schmidberger (gabi at cs.waikato.ac.nz) -- original code from
+ * weka.core.EuclideanDistance
+ * @author Ashraf M. Kibriya (amk14 at cs.waikato.ac.nz) -- original code from
+ * weka.core.EuclideanDistance
* @version $Revision: 1.2 $
*/
-public abstract class NormalizableDistance
- implements DistanceFunction, OptionHandler, Serializable, RevisionHandler {
-
+public abstract class NormalizableDistance implements DistanceFunction,
+ OptionHandler, Serializable, RevisionHandler {
+
/** Index in ranges for MIN. */
public static final int R_MIN = 0;
/** Index in ranges for MAX. */
-
+
public static final int R_MAX = 1;
-
+
/** Index in ranges for WIDTH. */
public static final int R_WIDTH = 2;
/** the instances used internally. */
protected Instances m_Data = null;
- /** True if normalization is turned off (default false).*/
+ /** True if normalization is turned off (default false). */
protected boolean m_DontNormalize = false;
-
+
/** The range of the attributes. */
protected double[][] m_Ranges;
@@ -64,7 +66,7 @@ public abstract class NormalizableDistance
/** The boolean flags, whether an attribute will be used or not. */
protected boolean[] m_ActiveIndices;
-
+
/** Whether all the necessary preparations have been done. */
protected boolean m_Validated;
@@ -76,119 +78,120 @@ public abstract class NormalizableDistance
}
/**
- * Initializes the distance function and automatically initializes the
- * ranges.
+ * Initializes the distance function and automatically initializes the ranges.
*
- * @param data the instances the distance function should work on
+ * @param data the instances the distance function should work on
*/
public NormalizableDistance(Instances data) {
setInstances(data);
}
-
+
/**
* Returns a string describing this object.
*
- * @return a description of the evaluator suitable for
- * displaying in the explorer/experimenter gui
+ * @return a description of the evaluator suitable for displaying in the
+ * explorer/experimenter gui
*/
public abstract String globalInfo();
/**
* Returns an enumeration describing the available options.
- *
- * @return an enumeration of all the available options.
+ *
+ * @return an enumeration of all the available options.
*/
+ @Override
public Enumeration listOptions() {
Vector result = new Vector();
-
- result.add(new Option(
- "\tTurns off the normalization of attribute \n"
- + "\tvalues in distance calculation.",
- "D", 0, "-D"));
-
- result.addElement(new Option(
- "\tSpecifies list of columns to used in the calculation of the \n"
- + "\tdistance. 'first' and 'last' are valid indices.\n"
- + "\t(default: first-last)",
- "R", 1, "-R <col1,col2-col4,...>"));
+
+ result.add(new Option("\tTurns off the normalization of attribute \n"
+ + "\tvalues in distance calculation.", "D", 0, "-D"));
result.addElement(new Option(
- "\tInvert matching sense of column indices.",
- "V", 0, "-V"));
-
+ "\tSpecifies list of columns to used in the calculation of the \n"
+ + "\tdistance. 'first' and 'last' are valid indices.\n"
+ + "\t(default: first-last)", "R", 1, "-R <col1,col2-col4,...>"));
+
+ result.addElement(new Option("\tInvert matching sense of column indices.",
+ "V", 0, "-V"));
+
return result.elements();
}
/**
* Gets the current settings. Returns empty array.
- *
- * @return an array of strings suitable for passing to setOptions()
+ *
+ * @return an array of strings suitable for passing to setOptions()
*/
+ @Override
public String[] getOptions() {
- Vector<String> result;
-
+ Vector<String> result;
+
result = new Vector<String>();
- if (getDontNormalize())
+ if (getDontNormalize()) {
result.add("-D");
-
+ }
+
result.add("-R");
result.add(getAttributeIndices());
-
- if (getInvertSelection())
+
+ if (getInvertSelection()) {
result.add("-V");
+ }
return result.toArray(new String[result.size()]);
}
/**
* Parses a given list of options.
- *
- * @param options the list of options as an array of strings
- * @throws Exception if an option is not supported
+ *
+ * @param options the list of options as an array of strings
+ * @throws Exception if an option is not supported
*/
+ @Override
public void setOptions(String[] options) throws Exception {
- String tmpStr;
-
+ String tmpStr;
+
setDontNormalize(Utils.getFlag('D', options));
-
+
tmpStr = Utils.getOption('R', options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
- else
+ } else {
setAttributeIndices("first-last");
+ }
setInvertSelection(Utils.getFlag('V', options));
}
-
- /**
+
+ /**
* Returns the tip text for this property.
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String dontNormalizeTipText() {
- return "Whether if the normalization of attributes should be turned off " +
- "for distance calculation (Default: false i.e. attribute values " +
- "are normalized). ";
+ return "Whether if the normalization of attributes should be turned off "
+ + "for distance calculation (Default: false i.e. attribute values "
+ + "are normalized). ";
}
-
- /**
+
+ /**
* Sets whether if the attribute values are to be normalized in distance
* calculation.
*
- * @param dontNormalize if true the values are not normalized
+ * @param dontNormalize if true the values are not normalized
*/
public void setDontNormalize(boolean dontNormalize) {
m_DontNormalize = dontNormalize;
invalidate();
}
-
+
/**
* Gets whether if the attribute values are to be normazlied in distance
* calculation. (default false i.e. attribute values are normalized.)
*
- * @return false if values get normalized
+ * @return false if values get normalized
*/
public boolean getDontNormalize() {
return m_DontNormalize;
@@ -196,78 +199,80 @@ public abstract class NormalizableDistance
/**
* Returns the tip text for this property.
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String attributeIndicesTipText() {
- return
- "Specify range of attributes to act on. "
+ return "Specify range of attributes to act on. "
+ "This is a comma separated list of attribute indices, with "
+ "\"first\" and \"last\" valid values. Specify an inclusive "
+ "range with \"-\". E.g: \"first-3,5,6-10,last\".";
}
/**
- * Sets the range of attributes to use in the calculation of the distance.
- * The indices start from 1, 'first' and 'last' are valid as well.
- * E.g.: first-3,5,6-last
+ * Sets the range of attributes to use in the calculation of the distance. The
+ * indices start from 1, 'first' and 'last' are valid as well. E.g.:
+ * first-3,5,6-last
*
- * @param value the new attribute index range
+ * @param value the new attribute index range
*/
+ @Override
public void setAttributeIndices(String value) {
m_AttributeIndices.setRanges(value);
invalidate();
}
-
+
/**
* Gets the range of attributes used in the calculation of the distance.
*
- * @return the attribute index range
+ * @return the attribute index range
*/
+ @Override
public String getAttributeIndices() {
return m_AttributeIndices.getRanges();
- }
+ }
/**
* Returns the tip text for this property.
- *
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String invertSelectionTipText() {
- return
- "Set attribute selection mode. If false, only selected "
+ return "Set attribute selection mode. If false, only selected "
+ "attributes in the range will be used in the distance calculation; if "
+ "true, only non-selected attributes will be used for the calculation.";
}
-
+
/**
* Sets whether the matching sense of attribute indices is inverted or not.
*
- * @param value if true the matching sense is inverted
+ * @param value if true the matching sense is inverted
*/
+ @Override
public void setInvertSelection(boolean value) {
m_AttributeIndices.setInvert(value);
invalidate();
}
-
+
/**
* Gets whether the matching sense of attribute indices is inverted or not.
*
- * @return true if the matching sense is inverted
+ * @return true if the matching sense is inverted
*/
+ @Override
public boolean getInvertSelection() {
return m_AttributeIndices.getInvert();
}
-
+
/**
* invalidates all initializations.
*/
protected void invalidate() {
m_Validated = false;
}
-
+
/**
* performs the initializations if necessary.
*/
@@ -277,7 +282,7 @@ public abstract class NormalizableDistance
m_Validated = true;
}
}
-
+
/**
* initializes the ranges and the attributes being used.
*/
@@ -292,15 +297,17 @@ public abstract class NormalizableDistance
protected void initializeAttributeIndices() {
m_AttributeIndices.setUpper(m_Data.numAttributes() - 1);
m_ActiveIndices = new boolean[m_Data.numAttributes()];
- for (int i = 0; i < m_ActiveIndices.length; i++)
+ for (int i = 0; i < m_ActiveIndices.length; i++) {
m_ActiveIndices[i] = m_AttributeIndices.isInRange(i);
+ }
}
/**
* Sets the instances.
*
- * @param insts the instances to use
+ * @param insts the instances to use
*/
+ @Override
public void setInstances(Instances insts) {
m_Data = insts;
invalidate();
@@ -309,8 +316,9 @@ public abstract class NormalizableDistance
/**
* returns the instances currently set.
*
- * @return the current instances
+ * @return the current instances
*/
+ @Override
public Instances getInstances() {
return m_Data;
}
@@ -318,29 +326,32 @@ public abstract class NormalizableDistance
/**
* Does nothing, derived classes may override it though.
*
- * @param distances the distances to post-process
+ * @param distances the distances to post-process
*/
+ @Override
public void postProcessDistances(double[] distances) {
}
/**
* Update the distance function (if necessary) for the newly added instance.
*
- * @param ins the instance to add
+ * @param ins the instance to add
*/
+ @Override
public void update(Instance ins) {
validate();
-
+
m_Ranges = updateRanges(ins, m_Ranges);
}
/**
* Calculates the distance between two instances.
*
- * @param first the first instance
- * @param second the second instance
- * @return the distance between the two given instances
+ * @param first the first instance
+ * @param second the second instance
+ * @return the distance between the two given instances
*/
+ @Override
public double distance(Instance first, Instance second) {
return distance(first, second, null);
}
@@ -348,252 +359,244 @@ public abstract class NormalizableDistance
/**
* Calculates the distance between two instances.
*
- * @param first the first instance
- * @param second the second instance
- * @param stats the performance stats object
- * @return the distance between the two given instances
+ * @param first the first instance
+ * @param second the second instance
+ * @param stats the performance stats object
+ * @return the distance between the two given instances
*/
+ @Override
public double distance(Instance first, Instance second, PerformanceStats stats) {
return distance(first, second, Double.POSITIVE_INFINITY, stats);
}
/**
- * Calculates the distance between two instances. Offers speed up (if the
- * distance function class in use supports it) in nearest neighbour search by
- * taking into account the cutOff or maximum distance. Depending on the
- * distance function class, post processing of the distances by
+ * Calculates the distance between two instances. Offers speed up (if the
+ * distance function class in use supports it) in nearest neighbour search by
+ * taking into account the cutOff or maximum distance. Depending on the
+ * distance function class, post processing of the distances by
* postProcessDistances(double []) may be required if this function is used.
- *
- * @param first the first instance
- * @param second the second instance
- * @param cutOffValue If the distance being calculated becomes larger than
- * cutOffValue then the rest of the calculation is
- * discarded.
- * @return the distance between the two given instances or
- * Double.POSITIVE_INFINITY if the distance being
- * calculated becomes larger than cutOffValue.
- */
+ *
+ * @param first the first instance
+ * @param second the second instance
+ * @param cutOffValue If the distance being calculated becomes larger than
+ * cutOffValue then the rest of the calculation is discarded.
+ * @return the distance between the two given instances or
+ * Double.POSITIVE_INFINITY if the distance being calculated becomes
+ * larger than cutOffValue.
+ */
+ @Override
public double distance(Instance first, Instance second, double cutOffValue) {
return distance(first, second, cutOffValue, null);
}
/**
- * Calculates the distance between two instances. Offers speed up (if the
- * distance function class in use supports it) in nearest neighbour search by
- * taking into account the cutOff or maximum distance. Depending on the
- * distance function class, post processing of the distances by
+ * Calculates the distance between two instances. Offers speed up (if the
+ * distance function class in use supports it) in nearest neighbour search by
+ * taking into account the cutOff or maximum distance. Depending on the
+ * distance function class, post processing of the distances by
* postProcessDistances(double []) may be required if this function is used.
- *
- * @param first the first instance
- * @param second the second instance
- * @param cutOffValue If the distance being calculated becomes larger than
- * cutOffValue then the rest of the calculation is
- * discarded.
- * @param stats the performance stats object
- * @return the distance between the two given instances or
- * Double.POSITIVE_INFINITY if the distance being
- * calculated becomes larger than cutOffValue.
- */
- public double distance(Instance first, Instance second, double cutOffValue, PerformanceStats stats) {
+ *
+ * @param first the first instance
+ * @param second the second instance
+ * @param cutOffValue If the distance being calculated becomes larger than
+ * cutOffValue then the rest of the calculation is discarded.
+ * @param stats the performance stats object
+ * @return the distance between the two given instances or
+ * Double.POSITIVE_INFINITY if the distance being calculated becomes
+ * larger than cutOffValue.
+ */
+ @Override
+ public double distance(Instance first, Instance second, double cutOffValue,
+ PerformanceStats stats) {
double distance = 0;
int firstI, secondI;
int firstNumValues = first.numValues();
int secondNumValues = second.numValues();
int numAttributes = m_Data.numAttributes();
int classIndex = m_Data.classIndex();
-
+
validate();
-
- for (int p1 = 0, p2 = 0; p1 < firstNumValues || p2 < secondNumValues; ) {
- if (p1 >= firstNumValues)
- firstI = numAttributes;
- else
- firstI = first.index(p1);
-
- if (p2 >= secondNumValues)
- secondI = numAttributes;
- else
- secondI = second.index(p2);
+
+ for (int p1 = 0, p2 = 0; p1 < firstNumValues || p2 < secondNumValues;) {
+ if (p1 >= firstNumValues) {
+ firstI = numAttributes;
+ } else {
+ firstI = first.index(p1);
+ }
+
+ if (p2 >= secondNumValues) {
+ secondI = numAttributes;
+ } else {
+ secondI = second.index(p2);
+ }
if (firstI == classIndex) {
- p1++;
- continue;
+ p1++;
+ continue;
}
if ((firstI < numAttributes) && !m_ActiveIndices[firstI]) {
- p1++;
- continue;
+ p1++;
+ continue;
}
-
+
if (secondI == classIndex) {
- p2++;
- continue;
+ p2++;
+ continue;
}
if ((secondI < numAttributes) && !m_ActiveIndices[secondI]) {
- p2++;
- continue;
+ p2++;
+ continue;
}
-
+
double diff;
-
+
if (firstI == secondI) {
- diff = difference(firstI,
- first.valueSparse(p1),
- second.valueSparse(p2));
- p1++;
- p2++;
+ diff = difference(firstI, first.valueSparse(p1), second.valueSparse(p2));
+ p1++;
+ p2++;
+ } else if (firstI > secondI) {
+ diff = difference(secondI, 0, second.valueSparse(p2));
+ p2++;
+ } else {
+ diff = difference(firstI, first.valueSparse(p1), 0);
+ p1++;
}
- else if (firstI > secondI) {
- diff = difference(secondI,
- 0, second.valueSparse(p2));
- p2++;
+ if (stats != null) {
+ stats.incrCoordCount();
}
- else {
- diff = difference(firstI,
- first.valueSparse(p1), 0);
- p1++;
- }
- if (stats != null)
- stats.incrCoordCount();
-
+
distance = updateDistance(distance, diff);
- if (distance > cutOffValue)
+ if (distance > cutOffValue) {
return Double.POSITIVE_INFINITY;
+ }
}
return distance;
}
-
+
/**
* Updates the current distance calculated so far with the new difference
- * between two attributes. The difference between the attributes was
+ * between two attributes. The difference between the attributes was
* calculated with the difference(int,double,double) method.
*
- * @param currDist the current distance calculated so far
- * @param diff the difference between two new attributes
- * @return the update distance
- * @see #difference(int, double, double)
+ * @param currDist the current distance calculated so far
+ * @param diff the difference between two new attributes
+ * @return the update distance
+ * @see #difference(int, double, double)
*/
protected abstract double updateDistance(double currDist, double diff);
-
+
/**
* Normalizes a given value of a numeric attribute.
- *
- * @param x the value to be normalized
- * @param i the attribute's index
- * @return the normalized value
+ *
+ * @param x the value to be normalized
+ * @param i the attribute's index
+ * @return the normalized value
*/
protected double norm(double x, int i) {
- if (Double.isNaN(m_Ranges[i][R_MIN]) || (m_Ranges[i][R_MAX] == m_Ranges[i][R_MIN]))
+ if (Double.isNaN(m_Ranges[i][R_MIN])
+ || (m_Ranges[i][R_MAX] == m_Ranges[i][R_MIN])) {
return 0;
- else
+ } else {
return (x - m_Ranges[i][R_MIN]) / (m_Ranges[i][R_WIDTH]);
+ }
}
/**
- * Computes the difference between two given attribute
- * values.
+ * Computes the difference between two given attribute values.
*
- * @param index the attribute index
- * @param val1 the first value
- * @param val2 the second value
- * @return the difference
+ * @param index the attribute index
+ * @param val1 the first value
+ * @param val2 the second value
+ * @return the difference
*/
protected double difference(int index, double val1, double val2) {
switch (m_Data.attribute(index).type()) {
- case Attribute.NOMINAL:
- if (Instance.isMissingValue(val1) ||
- Instance.isMissingValue(val2) ||
- ((int) val1 != (int) val2)) {
- return 1;
- }
- else {
- return 0;
- }
-
- case Attribute.NUMERIC:
- if (Instance.isMissingValue(val1) ||
- Instance.isMissingValue(val2)) {
- if (Instance.isMissingValue(val1) &&
- Instance.isMissingValue(val2)) {
- if (!m_DontNormalize) //We are doing normalization
- return 1;
- else
- return (m_Ranges[index][R_MAX] - m_Ranges[index][R_MIN]);
+ case Attribute.NOMINAL:
+ if (Instance.isMissingValue(val1) || Instance.isMissingValue(val2)
+ || ((int) val1 != (int) val2)) {
+ return 1;
+ } else {
+ return 0;
+ }
+
+ case Attribute.NUMERIC:
+ if (Instance.isMissingValue(val1) || Instance.isMissingValue(val2)) {
+ if (Instance.isMissingValue(val1) && Instance.isMissingValue(val2)) {
+ if (!m_DontNormalize) {
+ return 1;
+ } else {
+ return (m_Ranges[index][R_MAX] - m_Ranges[index][R_MIN]);
}
- else {
- double diff;
- if (Instance.isMissingValue(val2)) {
- diff = (!m_DontNormalize) ? norm(val1, index) : val1;
- }
- else {
- diff = (!m_DontNormalize) ? norm(val2, index) : val2;
- }
- if (!m_DontNormalize && diff < 0.5) {
- diff = 1.0 - diff;
- }
- else if (m_DontNormalize) {
- if ((m_Ranges[index][R_MAX]-diff) > (diff-m_Ranges[index][R_MIN]))
- return m_Ranges[index][R_MAX]-diff;
- else
- return diff-m_Ranges[index][R_MIN];
+ } else {
+ double diff;
+ if (Instance.isMissingValue(val2)) {
+ diff = (!m_DontNormalize) ? norm(val1, index) : val1;
+ } else {
+ diff = (!m_DontNormalize) ? norm(val2, index) : val2;
+ }
+ if (!m_DontNormalize && diff < 0.5) {
+ diff = 1.0 - diff;
+ } else if (m_DontNormalize) {
+ if ((m_Ranges[index][R_MAX] - diff) > (diff - m_Ranges[index][R_MIN])) {
+ return m_Ranges[index][R_MAX] - diff;
+ } else {
+ return diff - m_Ranges[index][R_MIN];
}
- return diff;
}
+ return diff;
}
- else {
- return (!m_DontNormalize) ?
- (norm(val1, index) - norm(val2, index)) :
- (val1 - val2);
- }
-
- default:
- return 0;
+ } else {
+ return (!m_DontNormalize) ? (norm(val1, index) - norm(val2, index))
+ : (val1 - val2);
+ }
+
+ default:
+ return 0;
}
}
-
+
/**
- * Initializes the ranges using all instances of the dataset.
- * Sets m_Ranges.
+ * Initializes the ranges using all instances of the dataset. Sets m_Ranges.
*
- * @return the ranges
+ * @return the ranges
*/
public double[][] initializeRanges() {
if (m_Data == null) {
m_Ranges = null;
return m_Ranges;
}
-
+
int numAtt = m_Data.numAttributes();
- double[][] ranges = new double [numAtt][3];
-
+ double[][] ranges = new double[numAtt][3];
+
if (m_Data.numInstances() <= 0) {
initializeRangesEmpty(numAtt, ranges);
m_Ranges = ranges;
return m_Ranges;
- }
- else {
+ } else {
// initialize ranges using the first instance
updateRangesFirst(m_Data.instance(0), numAtt, ranges);
}
-
+
// update ranges, starting from the second
- for (int i = 1; i < m_Data.numInstances(); i++)
+ for (int i = 1; i < m_Data.numInstances(); i++) {
updateRanges(m_Data.instance(i), numAtt, ranges);
+ }
m_Ranges = ranges;
-
+
return m_Ranges;
}
-
+
/**
- * Used to initialize the ranges. For this the values of the first
- * instance is used to save time.
- * Sets low and high to the values of the first instance and
- * width to zero.
+ * Used to initialize the ranges. For this the values of the first instance is
+ * used to save time. Sets low and high to the values of the first instance
+ * and width to zero.
*
- * @param instance the new instance
- * @param numAtt number of attributes in the model
- * @param ranges low, high and width values for all attributes
+ * @param instance the new instance
+ * @param numAtt number of attributes in the model
+ * @param ranges low, high and width values for all attributes
*/
public void updateRangesFirst(Instance instance, int numAtt, double[][] ranges) {
for (int j = 0; j < numAtt; j++) {
@@ -601,22 +604,21 @@ public abstract class NormalizableDistance
ranges[j][R_MIN] = instance.value(j);
ranges[j][R_MAX] = instance.value(j);
ranges[j][R_WIDTH] = 0.0;
- }
- else { // if value was missing
+ } else { // if value was missing
ranges[j][R_MIN] = Double.POSITIVE_INFINITY;
ranges[j][R_MAX] = -Double.POSITIVE_INFINITY;
ranges[j][R_WIDTH] = Double.POSITIVE_INFINITY;
}
}
}
-
+
/**
* Updates the minimum and maximum and width values for all the attributes
* based on a new instance.
*
- * @param instance the new instance
- * @param numAtt number of attributes in the model
- * @param ranges low, high and width values for all attributes
+ * @param instance the new instance
+ * @param numAtt number of attributes in the model
+ * @param ranges low, high and width values for all attributes
*/
public void updateRanges(Instance instance, int numAtt, double[][] ranges) {
// updateRangesFirst must have been called on ranges
@@ -626,12 +628,11 @@ public abstract class NormalizableDistance
if (value < ranges[j][R_MIN]) {
ranges[j][R_MIN] = value;
ranges[j][R_WIDTH] = ranges[j][R_MAX] - ranges[j][R_MIN];
- if (value > ranges[j][R_MAX]) { //if this is the first value that is
- ranges[j][R_MAX] = value; //not missing. The,0
+ if (value > ranges[j][R_MAX]) { // if this is the first value that is
+ ranges[j][R_MAX] = value; // not missing. The,0
ranges[j][R_WIDTH] = ranges[j][R_MAX] - ranges[j][R_MIN];
}
- }
- else {
+ } else {
if (value > ranges[j][R_MAX]) {
ranges[j][R_MAX] = value;
ranges[j][R_WIDTH] = ranges[j][R_MAX] - ranges[j][R_MIN];
@@ -640,12 +641,12 @@ public abstract class NormalizableDistance
}
}
}
-
+
/**
* Used to initialize the ranges.
*
- * @param numAtt number of attributes in the model
- * @param ranges low, high and width values for all attributes
+ * @param numAtt number of attributes in the model
+ * @param ranges low, high and width values for all attributes
*/
public void initializeRangesEmpty(int numAtt, double[][] ranges) {
for (int j = 0; j < numAtt; j++) {
@@ -654,13 +655,13 @@ public abstract class NormalizableDistance
ranges[j][R_WIDTH] = Double.POSITIVE_INFINITY;
}
}
-
+
/**
* Updates the ranges given a new instance.
*
- * @param instance the new instance
- * @param ranges low, high and width values for all attributes
- * @return the updated ranges
+ * @param instance the new instance
+ * @param ranges low, high and width values for all attributes
+ * @return the updated ranges
*/
public double[][] updateRanges(Instance instance, double[][] ranges) {
// updateRangesFirst must have been called on ranges
@@ -678,30 +679,30 @@ public abstract class NormalizableDistance
}
}
}
-
+
return ranges;
}
-
+
/**
* Initializes the ranges of a subset of the instances of this dataset.
* Therefore m_Ranges is not set.
*
- * @param instList list of indexes of the subset
- * @return the ranges
- * @throws Exception if something goes wrong
+ * @param instList list of indexes of the subset
+ * @return the ranges
+ * @throws Exception if something goes wrong
*/
public double[][] initializeRanges(int[] instList) throws Exception {
- if (m_Data == null)
+ if (m_Data == null) {
throw new Exception("No instances supplied.");
-
+ }
+
int numAtt = m_Data.numAttributes();
- double[][] ranges = new double [numAtt][3];
-
+ double[][] ranges = new double[numAtt][3];
+
if (m_Data.numInstances() <= 0) {
initializeRangesEmpty(numAtt, ranges);
return ranges;
- }
- else {
+ } else {
// initialize ranges using the first instance
updateRangesFirst(m_Data.instance(instList[0]), numAtt, ranges);
// update ranges, starting from the second
@@ -714,102 +715,114 @@ public abstract class NormalizableDistance
/**
* Initializes the ranges of a subset of the instances of this dataset.
- * Therefore m_Ranges is not set.
- * The caller of this method should ensure that the supplied start and end
- * indices are valid (start <= end, end<instList.length etc) and
- * correct.
- *
- * @param instList list of indexes of the instances
- * @param startIdx start index of the subset of instances in the indices array
- * @param endIdx end index of the subset of instances in the indices array
- * @return the ranges
- * @throws Exception if something goes wrong
- */
- public double[][] initializeRanges(int[] instList, int startIdx, int endIdx) throws Exception {
- if (m_Data == null)
+ * Therefore m_Ranges is not set. The caller of this method should ensure that
+ * the supplied start and end indices are valid (start <= end,
+ * end<instList.length etc) and correct.
+ *
+ * @param instList list of indexes of the instances
+ * @param startIdx start index of the subset of instances in the indices array
+ * @param endIdx end index of the subset of instances in the indices array
+ * @return the ranges
+ * @throws Exception if something goes wrong
+ */
+ public double[][] initializeRanges(int[] instList, int startIdx, int endIdx)
+ throws Exception {
+ if (m_Data == null) {
throw new Exception("No instances supplied.");
-
+ }
+
int numAtt = m_Data.numAttributes();
- double[][] ranges = new double [numAtt][3];
-
+ double[][] ranges = new double[numAtt][3];
+
if (m_Data.numInstances() <= 0) {
initializeRangesEmpty(numAtt, ranges);
return ranges;
- }
- else {
+ } else {
// initialize ranges using the first instance
updateRangesFirst(m_Data.instance(instList[startIdx]), numAtt, ranges);
// update ranges, starting from the second
- for (int i = startIdx+1; i <= endIdx; i++) {
+ for (int i = startIdx + 1; i <= endIdx; i++) {
updateRanges(m_Data.instance(instList[i]), numAtt, ranges);
}
}
-
+
return ranges;
}
-
+
/**
* Update the ranges if a new instance comes.
*
- * @param instance the new instance
+ * @param instance the new instance
*/
public void updateRanges(Instance instance) {
validate();
-
+
m_Ranges = updateRanges(instance, m_Ranges);
}
-
+
/**
* Test if an instance is within the given ranges.
*
- * @param instance the instance
- * @param ranges the ranges the instance is tested to be in
- * @return true if instance is within the ranges
+ * @param instance the instance
+ * @param ranges the ranges the instance is tested to be in
+ * @return true if instance is within the ranges
*/
public boolean inRanges(Instance instance, double[][] ranges) {
boolean isIn = true;
-
+
// updateRangesFirst must have been called on ranges
for (int j = 0; isIn && (j < ranges.length); j++) {
if (!instance.isMissing(j)) {
double value = instance.value(j);
isIn = value <= ranges[j][R_MAX];
- if (isIn) isIn = value >= ranges[j][R_MIN];
+ if (isIn) {
+ isIn = value >= ranges[j][R_MIN];
+ }
}
}
-
+
return isIn;
}
-
+
+ /**
+ * Free any references to training instances
+ */
+ @Override
+ public void clean() {
+ m_Data = new Instances(m_Data, 0);
+ }
+
/**
* Check if ranges are set.
*
- * @return true if ranges are set
+ * @return true if ranges are set
*/
public boolean rangesSet() {
return (m_Ranges != null);
}
-
+
/**
* Method to get the ranges.
*
- * @return the ranges
- * @throws Exception if no randes are set yet
+ * @return the ranges
+ * @throws Exception if no randes are set yet
*/
public double[][] getRanges() throws Exception {
validate();
-
- if (m_Ranges == null)
+
+ if (m_Ranges == null) {
throw new Exception("Ranges not yet set.");
-
+ }
+
return m_Ranges;
}
-
+
/**
* Returns an empty string.
*
- * @return an empty string
+ * @return an empty string
*/
+ @Override
public String toString() {
return "";
}
diff --git a/src/main/java/weka/core/Utils.java b/src/main/java/weka/core/Utils.java
index 188ccb1..566617c 100644
--- a/src/main/java/weka/core/Utils.java
+++ b/src/main/java/weka/core/Utils.java
@@ -22,12 +22,19 @@
package weka.core;
+import java.beans.BeanInfo;
+import java.beans.Introspector;
+import java.beans.MethodDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Array;
+import java.lang.reflect.Method;
+import java.text.BreakIterator;
import java.util.Properties;
import java.util.Random;
+import weka.gui.PropertySheetPanel;
+
/**
* Class implementing some simple utility methods.
*
@@ -35,7 +42,7 @@ import java.util.Random;
* @author Yong Wang
* @author Len Trigg
* @author Julien Prados
- * @version $Revision: 9737 $
+ * @version $Revision: 10570 $
*/
public final class Utils implements RevisionHandler {
@@ -70,14 +77,14 @@ public final class Utils implements RevisionHandler {
// jdk1.1/docs/guide/misc/resources.html
// defaultProps.load(ClassLoader.getSystemResourceAsStream(resourceName));
defaultProps.load((new Utils()).getClass().getClassLoader()
- .getResourceAsStream(resourceName));
+ .getResourceAsStream(resourceName));
} catch (Exception ex) {
/*
* throw new Exception("Problem reading default properties: " +
* ex.getMessage());
*/
System.err.println("Warning, unable to load properties file from "
- + "system resource (Utils.java)");
+ + "system resource (Utils.java)");
}
// Hardcoded slash is OK here
@@ -90,7 +97,7 @@ public final class Utils implements RevisionHandler {
// Allow a properties file in the home directory to override
Properties userProps = new Properties(defaultProps);
File propFile = new File(System.getProperties().getProperty("user.home")
- + File.separatorChar + resourceName);
+ + File.separatorChar + resourceName);
if (propFile.exists()) {
try {
userProps.load(new FileInputStream(propFile));
@@ -178,7 +185,7 @@ public final class Utils implements RevisionHandler {
* @return the input string with occurrences of substring replaced.
*/
public static String replaceSubstring(String inString, String subString,
- String replaceString) {
+ String replaceString) {
StringBuffer result = new StringBuffer();
int oldLoc = 0, loc = 0;
@@ -229,7 +236,7 @@ public final class Utils implements RevisionHandler {
* @return the output string
*/
private static/* @pure@ */String fixStringLength(String inString, int length,
- boolean right) {
+ boolean right) {
if (inString.length() < length) {
while (inString.length() < length) {
@@ -250,7 +257,7 @@ public final class Utils implements RevisionHandler {
* @return the double as a formatted string
*/
public static/* @pure@ */String doubleToString(double value,
- int afterDecimalPoint) {
+ int afterDecimalPoint) {
StringBuffer stringBuffer;
double temp;
@@ -260,7 +267,7 @@ public final class Utils implements RevisionHandler {
temp = value * Math.pow(10.0, afterDecimalPoint);
if (Math.abs(temp) < Long.MAX_VALUE) {
precisionValue = (temp > 0) ? (long) (temp + 0.5) : -(long) (Math
- .abs(temp) + 0.5);
+ .abs(temp) + 0.5);
if (precisionValue == 0) {
stringBuffer = new StringBuffer(String.valueOf(0));
} else {
@@ -286,7 +293,7 @@ public final class Utils implements RevisionHandler {
}
int currentPos = stringBuffer.length() - 1;
while ((currentPos > dotPosition)
- && (stringBuffer.charAt(currentPos) == '0')) {
+ && (stringBuffer.charAt(currentPos) == '0')) {
stringBuffer.setCharAt(currentPos--, ' ');
}
if (stringBuffer.charAt(currentPos) == '.') {
@@ -308,7 +315,7 @@ public final class Utils implements RevisionHandler {
* @return the double as a formatted string
*/
public static/* @pure@ */String doubleToString(double value, int width,
- int afterDecimalPoint) {
+ int afterDecimalPoint) {
String tempString = doubleToString(value, afterDecimalPoint);
char[] result;
@@ -369,10 +376,11 @@ public final class Utils implements RevisionHandler {
* @return the class of the innermost elements
*/
public static Class getArrayClass(Class c) {
- if (c.getComponentType().isArray())
+ if (c.getComponentType().isArray()) {
return getArrayClass(c.getComponentType());
- else
+ } else {
return c.getComponentType();
+ }
}
/**
@@ -384,10 +392,11 @@ public final class Utils implements RevisionHandler {
* @return the dimensions of the array
*/
public static int getArrayDimensions(Class array) {
- if (array.getComponentType().isArray())
+ if (array.getComponentType().isArray()) {
return 1 + getArrayDimensions(array.getComponentType());
- else
+ } else {
return 1;
+ }
}
/**
@@ -422,17 +431,20 @@ public final class Utils implements RevisionHandler {
result = "null";
} else if (dimensions == 1) {
for (i = 0; i < Array.getLength(array); i++) {
- if (i > 0)
+ if (i > 0) {
result += ",";
- if (Array.get(array, i) == null)
+ }
+ if (Array.get(array, i) == null) {
result += "null";
- else
+ } else {
result += Array.get(array, i).toString();
+ }
}
} else {
for (i = 0; i < Array.getLength(array); i++) {
- if (i > 0)
+ if (i > 0) {
result += ",";
+ }
result += "[" + arrayToString(Array.get(array, i)) + "]";
}
}
@@ -458,7 +470,7 @@ public final class Utils implements RevisionHandler {
* @exception Exception if there are any non-empty options
*/
public static void checkForRemainingOptions(String[] options)
- throws Exception {
+ throws Exception {
int illegalOptionsFound = 0;
StringBuffer text = new StringBuffer();
@@ -466,10 +478,10 @@ public final class Utils implements RevisionHandler {
if (options == null) {
return;
}
- for (int i = 0; i < options.length; i++) {
- if (options[i].length() > 0) {
+ for (String option : options) {
+ if (option.length() > 0) {
illegalOptionsFound++;
- text.append(options[i] + ' ');
+ text.append(option + ' ');
}
}
if (illegalOptionsFound > 0) {
@@ -506,8 +518,9 @@ public final class Utils implements RevisionHandler {
int pos = getOptionPos(flag, options);
- if (pos > -1)
+ if (pos > -1) {
options[pos] = "";
+ }
return (pos > -1);
}
@@ -523,7 +536,7 @@ public final class Utils implements RevisionHandler {
* @exception Exception if the option indicated by the flag can't be found
*/
public static/* @non_null@ */String getOption(char flag, String[] options)
- throws Exception {
+ throws Exception {
return getOption("" + flag, options);
}
@@ -539,7 +552,7 @@ public final class Utils implements RevisionHandler {
* @exception Exception if the option indicated by the flag can't be found
*/
public static/* @non_null@ */String getOption(String flag, String[] options)
- throws Exception {
+ throws Exception {
String newString;
int i = getOptionPos(flag, options);
@@ -583,8 +596,9 @@ public final class Utils implements RevisionHandler {
* @return the position if found, or -1 otherwise
*/
public static int getOptionPos(String flag, String[] options) {
- if (options == null)
+ if (options == null) {
return -1;
+ }
for (int i = 0; i < options.length; i++) {
if ((options[i].length() > 0) && (options[i].charAt(0) == '-')) {
@@ -593,11 +607,13 @@ public final class Utils implements RevisionHandler {
Double.valueOf(options[i]);
} catch (NumberFormatException e) {
// found?
- if (options[i].equals("-" + flag))
+ if (options[i].equals("-" + flag)) {
return i;
+ }
// did we reach "--"?
- if (options[i].charAt(1) == '-')
+ if (options[i].charAt(1) == '-') {
return -1;
+ }
}
}
}
@@ -629,9 +645,9 @@ public final class Utils implements RevisionHandler {
// backquote the following characters
if ((string.indexOf('\n') != -1) || (string.indexOf('\r') != -1)
- || (string.indexOf('\'') != -1) || (string.indexOf('"') != -1)
- || (string.indexOf('\\') != -1) || (string.indexOf('\t') != -1)
- || (string.indexOf('%') != -1) || (string.indexOf('\u001E') != -1)) {
+ || (string.indexOf('\'') != -1) || (string.indexOf('"') != -1)
+ || (string.indexOf('\\') != -1) || (string.indexOf('\t') != -1)
+ || (string.indexOf('%') != -1) || (string.indexOf('\u001E') != -1)) {
string = backQuoteChars(string);
quote = true;
}
@@ -639,9 +655,9 @@ public final class Utils implements RevisionHandler {
// Enclose the string in 's if the string contains a recently added
// backquote or contains one of the following characters.
if ((quote == true) || (string.indexOf('{') != -1)
- || (string.indexOf('}') != -1) || (string.indexOf(',') != -1)
- || (string.equals("?")) || (string.indexOf(' ') != -1)
- || (string.equals(""))) {
+ || (string.indexOf('}') != -1) || (string.indexOf(',') != -1)
+ || (string.equals("?")) || (string.indexOf(' ') != -1)
+ || (string.equals(""))) {
string = ("'".concat(string)).concat("'");
}
@@ -661,9 +677,9 @@ public final class Utils implements RevisionHandler {
string = string.substring(1, string.length() - 1);
if ((string.indexOf("\\n") != -1) || (string.indexOf("\\r") != -1)
- || (string.indexOf("\\'") != -1) || (string.indexOf("\\\"") != -1)
- || (string.indexOf("\\\\") != -1) || (string.indexOf("\\t") != -1)
- || (string.indexOf("\\%") != -1) || (string.indexOf("\\u001E") != -1)) {
+ || (string.indexOf("\\'") != -1) || (string.indexOf("\\\"") != -1)
+ || (string.indexOf("\\\\") != -1) || (string.indexOf("\\t") != -1)
+ || (string.indexOf("\\%") != -1) || (string.indexOf("\\u001E") != -1)) {
string = unbackQuoteChars(string);
}
}
@@ -687,7 +703,7 @@ public final class Utils implements RevisionHandler {
// replace each of the following characters with the backquoted version
char charsFind[] = { '\\', '\'', '\t', '\n', '\r', '"', '%', '\u001E' };
String charsReplace[] = { "\\\\", "\\'", "\\t", "\\n", "\\r", "\\\"",
- "\\%", "\\u001E" };
+ "\\%", "\\u001E" };
for (int i = 0; i < charsFind.length; i++) {
if (string.indexOf(charsFind[i]) != -1) {
newStringBuffer = new StringBuffer();
@@ -837,7 +853,7 @@ public final class Utils implements RevisionHandler {
// replace each of the following characters with the backquoted version
String charsFind[] = { "\\\\", "\\'", "\\t", "\\n", "\\r", "\\\"", "\\%",
- "\\u001E" };
+ "\\u001E" };
char charsReplace[] = { '\\', '\'', '\t', '\n', '\r', '"', '%', '\u001E' };
int pos[] = new int[charsFind.length];
int curPos;
@@ -880,7 +896,7 @@ public final class Utils implements RevisionHandler {
* parse error
*/
public static String[] splitOptions(String quotedOptionString)
- throws Exception {
+ throws Exception {
FastVector optionsVec = new FastVector();
String str = new String(quotedOptionString);
@@ -890,13 +906,15 @@ public final class Utils implements RevisionHandler {
// trimLeft
i = 0;
- while ((i < str.length()) && (Character.isWhitespace(str.charAt(i))))
+ while ((i < str.length()) && (Character.isWhitespace(str.charAt(i)))) {
i++;
+ }
str = str.substring(i);
// stop when str is empty
- if (str.length() == 0)
+ if (str.length() == 0) {
break;
+ }
// if str start with a double quote
if (str.charAt(0) == '"') {
@@ -904,17 +922,20 @@ public final class Utils implements RevisionHandler {
// find the first not anti-slached double quote
i = 1;
while (i < str.length()) {
- if (str.charAt(i) == str.charAt(0))
+ if (str.charAt(i) == str.charAt(0)) {
break;
+ }
if (str.charAt(i) == '\\') {
i += 1;
- if (i >= str.length())
+ if (i >= str.length()) {
throw new Exception("String should not finish with \\");
+ }
}
i += 1;
}
- if (i >= str.length())
+ if (i >= str.length()) {
throw new Exception("Quote parse error.");
+ }
// add the founded string to the option vector (without quotes)
String optStr = str.substring(1, i);
@@ -924,8 +945,9 @@ public final class Utils implements RevisionHandler {
} else {
// find first whiteSpace
i = 0;
- while ((i < str.length()) && (!Character.isWhitespace(str.charAt(i))))
+ while ((i < str.length()) && (!Character.isWhitespace(str.charAt(i)))) {
i++;
+ }
// add the founded string to the option vector
String optStr = str.substring(0, i);
@@ -952,21 +974,21 @@ public final class Utils implements RevisionHandler {
public static String joinOptions(String[] optionArray) {
String optionString = "";
- for (int i = 0; i < optionArray.length; i++) {
- if (optionArray[i].equals("")) {
+ for (String element : optionArray) {
+ if (element.equals("")) {
continue;
}
boolean escape = false;
- for (int n = 0; n < optionArray[i].length(); n++) {
- if (Character.isWhitespace(optionArray[i].charAt(n))) {
+ for (int n = 0; n < element.length(); n++) {
+ if (Character.isWhitespace(element.charAt(n))) {
escape = true;
break;
}
}
if (escape) {
- optionString += '"' + backQuoteChars(optionArray[i]) + '"';
+ optionString += '"' + backQuoteChars(element) + '"';
} else {
- optionString += optionArray[i];
+ optionString += element;
}
optionString += " ";
}
@@ -1000,7 +1022,7 @@ public final class Utils implements RevisionHandler {
* are not acceptable to the object
*/
public static Object forName(Class classType, String className,
- String[] options) throws Exception {
+ String[] options) throws Exception {
Class c = null;
try {
@@ -1010,7 +1032,7 @@ public final class Utils implements RevisionHandler {
}
if (!classType.isAssignableFrom(c)) {
throw new Exception(classType.getName() + " is not assignable from "
- + className);
+ + className);
}
Object o = c.newInstance();
if ((o instanceof OptionHandler) && (options != null)) {
@@ -1031,9 +1053,9 @@ public final class Utils implements RevisionHandler {
int total = 0;
double x = 0;
- for (int j = 0; j < counts.length; j++) {
- x -= xlogx(counts[j]);
- total += counts[j];
+ for (int count : counts) {
+ x -= xlogx(count);
+ total += count;
}
return x + xlogx(total);
}
@@ -1176,8 +1198,8 @@ public final class Utils implements RevisionHandler {
if (vector.length == 0) {
return 0;
}
- for (int i = 0; i < vector.length; i++) {
- sum += vector[i];
+ for (double element : vector) {
+ sum += element;
}
return sum / vector.length;
}
@@ -1235,8 +1257,8 @@ public final class Utils implements RevisionHandler {
public static void normalize(double[] doubles) {
double sum = 0;
- for (int i = 0; i < doubles.length; i++) {
- sum += doubles[i];
+ for (double d : doubles) {
+ sum += d;
}
normalize(doubles, sum);
}
@@ -1298,7 +1320,7 @@ public final class Utils implements RevisionHandler {
if (gr(prob, 1) || (sm(prob, 0))) {
throw new IllegalArgumentException("probToLogOdds: probability must "
- + "be in [0,1] " + prob);
+ + "be in [0,1] " + prob);
}
double p = SMALL + (1.0 - 2 * SMALL) * prob;
return Math.log(p / (1 - p));
@@ -1314,7 +1336,7 @@ public final class Utils implements RevisionHandler {
public static/* @pure@ */int round(double value) {
int roundedValue = value > 0 ? (int) (value + 0.5) : -(int) (Math
- .abs(value) + 0.5);
+ .abs(value) + 0.5);
return roundedValue;
}
@@ -1373,7 +1395,7 @@ public final class Utils implements RevisionHandler {
* @return the double rounded to the given precision
*/
public static/* @pure@ */double roundDouble(double value,
- int afterDecimalPoint) {
+ int afterDecimalPoint) {
double mask = Math.pow(10.0, afterDecimalPoint);
@@ -1458,7 +1480,7 @@ public final class Utils implements RevisionHandler {
* @return an array of integers with the positions in the sorted array.
*/
public static/* @pure@ */int[] sortWithNoMissingValues(
- /* @non_null@ */double[] array) {
+ /* @non_null@ */double[] array) {
int[] index = initialIndex(array.length);
if (array.length > 1) {
@@ -1496,15 +1518,18 @@ public final class Utils implements RevisionHandler {
while (i < index.length) {
numEqual = 1;
for (int j = i + 1; ((j < index.length) && Utils.eq(array[index[i]],
- array[index[j]])); j++)
+ array[index[j]])); j++) {
numEqual++;
+ }
if (numEqual > 1) {
helpIndex = new int[numEqual];
- for (int j = 0; j < numEqual; j++)
+ for (int j = 0; j < numEqual; j++) {
helpIndex[j] = i + j;
+ }
quickSort(index, helpIndex, 0, numEqual - 1);
- for (int j = 0; j < numEqual; j++)
+ for (int j = 0; j < numEqual; j++) {
newIndex[i + j] = index[helpIndex[j]];
+ }
i += numEqual;
} else {
newIndex[i] = index[i];
@@ -1530,12 +1555,12 @@ public final class Utils implements RevisionHandler {
if (vector.length <= 1) {
return 0;
}
- for (int i = 0; i < vector.length; i++) {
- sum += vector[i];
- sumSquared += (vector[i] * vector[i]);
+ for (double element : vector) {
+ sum += element;
+ sumSquared += (element * element);
}
double result = (sumSquared - (sum * sum / vector.length))
- / (vector.length - 1);
+ / (vector.length - 1);
// We don't like negative variance
if (result < 0) {
@@ -1555,8 +1580,8 @@ public final class Utils implements RevisionHandler {
double sum = 0;
- for (int i = 0; i < doubles.length; i++) {
- sum += doubles[i];
+ for (double d : doubles) {
+ sum += d;
}
return sum;
}
@@ -1571,8 +1596,8 @@ public final class Utils implements RevisionHandler {
int sum = 0;
- for (int i = 0; i < ints.length; i++) {
- sum += ints[i];
+ for (int j : ints) {
+ sum += j;
}
return sum;
}
@@ -1608,7 +1633,7 @@ public final class Utils implements RevisionHandler {
* pivot.
*/
private static int sortLeftRightAndCenter(double[] array, int[] index, int l,
- int r) {
+ int r) {
int c = (l + r) / 2;
conditionalSwap(array, index, l, c);
@@ -1631,7 +1656,7 @@ public final class Utils implements RevisionHandler {
* Conditional swap for quick sort.
*/
private static void conditionalSwap(double[] array, int[] index, int left,
- int right) {
+ int right) {
if (array[index[left]] > array[index[right]]) {
int help = index[left];
@@ -1652,14 +1677,16 @@ public final class Utils implements RevisionHandler {
* @return the index of the middle element
*/
private static int partition(double[] array, int[] index, int l, int r,
- double pivot) {
+ double pivot) {
r--;
while (true) {
- while ((array[index[++l]] < pivot))
+ while ((array[index[++l]] < pivot)) {
;
- while ((array[index[--r]] > pivot))
+ }
+ while ((array[index[--r]] > pivot)) {
;
+ }
if (l >= r) {
return l;
}
@@ -1720,7 +1747,7 @@ public final class Utils implements RevisionHandler {
// @ requires array != index;
// assignable index;
private static void quickSort(/* @non_null@ */double[] array, /* @non_null@ */
- int[] index, int left, int right) {
+ int[] index, int left, int right) {
int diff = right - left;
@@ -1771,7 +1798,7 @@ public final class Utils implements RevisionHandler {
// @ requires array != index;
// assignable index;
private static void quickSort(/* @non_null@ */int[] array, /* @non_null@ */
- int[] index, int left, int right) {
+ int[] index, int left, int right) {
if (left < right) {
int middle = partition(array, index, left, right);
@@ -1794,7 +1821,7 @@ public final class Utils implements RevisionHandler {
*/
// @ requires 0 <= first && first <= right && right < array.length;
private static int select(/* @non_null@ */double[] array, /* @non_null@ */
- int[] index, int left, int right, int k) {
+ int[] index, int left, int right, int k) {
int diff = right - left;
switch (diff) {
@@ -1878,7 +1905,7 @@ public final class Utils implements RevisionHandler {
File userDir = new File(System.getProperty("user.dir"));
String userPath = userDir.getAbsolutePath() + File.separator;
String targetPath = (new File(absolute.getParent())).getPath()
- + File.separator;
+ + File.separator;
String fileName = absolute.getName();
StringBuffer relativePath = new StringBuffer();
// relativePath.append("."+File.separator);
@@ -1925,7 +1952,7 @@ public final class Utils implements RevisionHandler {
if (tcount == -1) {
// then target file is probably on another drive (under windows)
throw new Exception("Can't construct a path to file relative to user "
- + "dir.");
+ + "dir.");
}
if (targetTemp.indexOf(File.separator) == -1) {
targetTemp = "";
@@ -1953,7 +1980,7 @@ public final class Utils implements RevisionHandler {
*/
// @ requires 0 <= first && first <= right && right < array.length;
private static int select(/* @non_null@ */int[] array, /* @non_null@ */
- int[] index, int left, int right, int k) {
+ int[] index, int left, int right, int k) {
if (left == right) {
return left;
@@ -1968,12 +1995,150 @@ public final class Utils implements RevisionHandler {
}
/**
+ * Utility method for grabbing the global info help (if it exists) from an
+ * arbitrary object. Can also append capabilities information if the object is
+ * a CapabilitiesHandler.
+ *
+ * @param object the object to grab global info from
+ * @param addCapabilities true if capabilities information is to be added to
+ * the result
+ * @return the global help info or null if global info does not exist
+ */
+ public static String getGlobalInfo(Object object, boolean addCapabilities) {
+ // set tool tip text from global info if supplied
+ String gi = null;
+ StringBuilder result = new StringBuilder();
+ try {
+ BeanInfo bi = Introspector.getBeanInfo(object.getClass());
+ MethodDescriptor[] methods = bi.getMethodDescriptors();
+ for (MethodDescriptor method : methods) {
+ String name = method.getDisplayName();
+ Method meth = method.getMethod();
+ if (name.equals("globalInfo")) {
+ if (meth.getReturnType().equals(String.class)) {
+ Object args[] = {};
+ String globalInfo = (String) (meth.invoke(object, args));
+ gi = globalInfo;
+ break;
+ }
+ }
+ }
+ } catch (Exception ex) {
+
+ }
+
+ // Max. number of characters per line (may overflow)
+ int lineWidth = 180;
+
+ result.append("<html>");
+
+ if (gi != null && gi.length() > 0) {
+
+ StringBuilder firstLine = new StringBuilder();
+ firstLine.append("<font color=blue>");
+ boolean addFirstBreaks = true;
+ int indexOfDot = gi.indexOf(".");
+ if (indexOfDot > 0) {
+ firstLine.append(gi.substring(0, gi.indexOf(".")));
+ if (gi.length() - indexOfDot < 3) {
+ addFirstBreaks = false;
+ }
+ gi = gi.substring(indexOfDot + 1, gi.length());
+ } else {
+ firstLine.append(gi);
+ gi = "";
+ }
+ firstLine.append("</font>");
+ if ((addFirstBreaks) && !(gi.startsWith("\n\n"))) {
+ if (!gi.startsWith("\n")) {
+ firstLine.append("<br>");
+ }
+ firstLine.append("<br>");
+ }
+ result.append(Utils.lineWrap(firstLine.toString(), lineWidth));
+
+ result.append(Utils.lineWrap(gi, lineWidth).replace("\n", "<br>"));
+ result.append("<br>");
+ }
+
+ if (addCapabilities) {
+ if (object instanceof CapabilitiesHandler) {
+ if (!result.toString().endsWith("<br><br>")) {
+ result.append("<br>");
+ }
+ String caps = PropertySheetPanel.addCapabilities(
+ "<font color=red>CAPABILITIES</font>",
+ ((CapabilitiesHandler) object).getCapabilities());
+ caps = Utils.lineWrap(caps, lineWidth).replace("\n", "<br>");
+ result.append(caps);
+ }
+
+ if (object instanceof MultiInstanceCapabilitiesHandler) {
+ result.append("<br>");
+ String caps = PropertySheetPanel.addCapabilities(
+ "<font color=red>MI CAPABILITIES</font>",
+ ((MultiInstanceCapabilitiesHandler) object)
+ .getMultiInstanceCapabilities());
+ caps = Utils.lineWrap(caps, lineWidth).replace("\n", "<br>");
+ result.append(caps);
+ }
+ }
+
+ result.append("</html>");
+
+ if (result.toString().equals("<html></html>")) {
+ return null;
+ }
+ return result.toString();
+ }
+
+ /**
+ * Implements simple line breaking. Reformats the given string by introducing
+ * line breaks so that, ideally, no line exceeds the given number of
+ * characters. Line breaks are assumed to be indicated by newline characters.
+ * Existing line breaks are left in the input text.
+ *
+ * @param input the string to line wrap
+ * @param maxLineWidth the maximum permitted number of characters in a line
+ * @return the processed string
+ */
+ public static String lineWrap(String input, int maxLineWidth) {
+
+ StringBuffer sb = new StringBuffer();
+ BreakIterator biterator = BreakIterator.getLineInstance();
+ biterator.setText(input);
+ int linestart = 0;
+ int previous = 0;
+ while (true) {
+ int next = biterator.next();
+ String toAdd = input.substring(linestart, previous);
+ if (next == BreakIterator.DONE) {
+ sb.append(toAdd);
+ break;
+ }
+ if (next - linestart > maxLineWidth) {
+ sb.append(toAdd + '\n');
+ linestart = previous;
+ } else {
+ int newLineIndex = toAdd.lastIndexOf('\n');
+ if (newLineIndex != -1) {
+ sb.append(toAdd.substring(0, newLineIndex + 1));
+ linestart += newLineIndex + 1;
+ }
+ }
+ previous = next;
+ }
+ return sb.toString();
+ }
+
+ /**
* Returns the revision string.
*
* @return the revision
*/
+ @Override
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9737 $");
+ return RevisionUtils.extract("$Revision: 10570 $");
}
/**
@@ -1993,42 +2158,42 @@ public final class Utils implements RevisionHandler {
System.out.println("First option split up:");
if (ops.length > 0) {
String[] firstOptionSplitUp = Utils.splitOptions(ops[0]);
- for (int i = 0; i < firstOptionSplitUp.length; i++) {
- System.out.println(firstOptionSplitUp[i]);
+ for (String element : firstOptionSplitUp) {
+ System.out.println(element);
}
}
System.out.println("Partitioned options: ");
String[] partitionedOptions = Utils.partitionOptions(ops);
- for (int i = 0; i < partitionedOptions.length; i++) {
- System.out.println(partitionedOptions[i]);
+ for (String partitionedOption : partitionedOptions) {
+ System.out.println(partitionedOption);
}
System.out.println("Get position of flag -f: "
- + Utils.getOptionPos('f', ops));
+ + Utils.getOptionPos('f', ops));
System.out.println("Get flag -f: " + Utils.getFlag('f', ops));
System.out.println("Get position of option -o: "
- + Utils.getOptionPos('o', ops));
+ + Utils.getOptionPos('o', ops));
System.out.println("Get option -o: " + Utils.getOption('o', ops));
System.out.println("Checking for remaining options... ");
Utils.checkForRemainingOptions(ops);
// Statistics
System.out.println("Original array with NaN (doubles): ");
- for (int i = 0; i < doublesWithNaN.length; i++) {
- System.out.print(doublesWithNaN[i] + " ");
+ for (double element : doublesWithNaN) {
+ System.out.print(element + " ");
}
System.out.println();
System.out.println("Original array (doubles): ");
- for (int i = 0; i < doubles.length; i++) {
- System.out.print(doubles[i] + " ");
+ for (double d : doubles) {
+ System.out.print(d + " ");
}
System.out.println();
System.out.println("Original array (ints): ");
- for (int i = 0; i < ints.length; i++) {
- System.out.print(ints[i] + " ");
+ for (int j : ints) {
+ System.out.print(j + " ");
}
System.out.println();
System.out.println("Correlation: "
- + Utils.correlation(doubles, doubles, doubles.length));
+ + Utils.correlation(doubles, doubles, doubles.length));
System.out.println("Mean: " + Utils.mean(doubles));
System.out.println("Variance: " + Utils.variance(doubles));
System.out.println("Sum (doubles): " + Utils.sum(doubles));
@@ -2038,9 +2203,9 @@ public final class Utils implements RevisionHandler {
System.out.println("Min index (doubles): " + Utils.minIndex(doubles));
System.out.println("Min index (ints): " + Utils.minIndex(ints));
System.out.println("Median (doubles): "
- + Utils.kthSmallestValue(doubles, doubles.length / 2));
+ + Utils.kthSmallestValue(doubles, doubles.length / 2));
System.out.println("Median (ints): "
- + Utils.kthSmallestValue(ints, ints.length / 2));
+ + Utils.kthSmallestValue(ints, ints.length / 2));
// Sorting and normalizing
System.out.println("Sorted array with NaN (doubles): ");
@@ -2075,14 +2240,14 @@ public final class Utils implements RevisionHandler {
System.out.println();
System.out.println("Normalized array (doubles): ");
Utils.normalize(doubles);
- for (int i = 0; i < doubles.length; i++) {
- System.out.print(doubles[i] + " ");
+ for (double d : doubles) {
+ System.out.print(d + " ");
}
System.out.println();
System.out.println("Normalized again (doubles): ");
Utils.normalize(doubles, Utils.sum(doubles));
- for (int i = 0; i < doubles.length; i++) {
- System.out.print(doubles[i] + " ");
+ for (double d : doubles) {
+ System.out.print(d + " ");
}
System.out.println();
@@ -2103,16 +2268,16 @@ public final class Utils implements RevisionHandler {
System.out.println("5 * log(5): " + Utils.xlogx(5));
System.out.println("5.5 rounded: " + Utils.round(5.5));
System.out.println("5.55555 rounded to 2 decimal places: "
- + Utils.roundDouble(5.55555, 2));
+ + Utils.roundDouble(5.55555, 2));
// Arrays
System.out.println("Array-Dimensions of 'new int[][]': "
- + Utils.getArrayDimensions(new int[][] {}));
+ + Utils.getArrayDimensions(new int[][] {}));
System.out.println("Array-Dimensions of 'new int[][]{{1,2,3},{4,5,6}}': "
- + Utils.getArrayDimensions(new int[][] { { 1, 2, 3 }, { 4, 5, 6 } }));
+ + Utils.getArrayDimensions(new int[][] { { 1, 2, 3 }, { 4, 5, 6 } }));
String[][][] s = new String[3][4][];
System.out.println("Array-Dimensions of 'new String[3][4][]': "
- + Utils.getArrayDimensions(s));
+ + Utils.getArrayDimensions(s));
} catch (Exception e) {
e.printStackTrace();
}
diff --git a/src/main/java/weka/core/converters/CSVLoader.java b/src/main/java/weka/core/converters/CSVLoader.java
index 7f75d29..587a27b 100644
--- a/src/main/java/weka/core/converters/CSVLoader.java
+++ b/src/main/java/weka/core/converters/CSVLoader.java
@@ -46,15 +46,13 @@ import weka.core.RevisionUtils;
import weka.core.Utils;
/**
- <!-- globalinfo-start -->
- * Reads a source that is in comma separated or tab
+ * <!-- globalinfo-start --> Reads a source that is in comma separated or tab
* separated format. Assumes that the first row in the file determines the
* number of and names of the attributes.
* <p/>
- <!-- globalinfo-end -->
+ * <!-- globalinfo-end -->
*
- <!-- options-start -->
- * Valid options are:
+ * <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
@@ -99,14 +97,14 @@ import weka.core.Utils;
* Specify as a comma separated list (e.g. ",' (default: '"')
* </pre>
*
- <!-- options-end -->
+ * <!-- options-end -->
*
* @author Mark Hall (mhall at cs.waikato.ac.nz)
- * @version $Revision: 9280 $
+ * @version $Revision: 10372 $
* @see Loader
*/
public class CSVLoader extends AbstractFileLoader implements BatchConverter,
- OptionHandler {
+ OptionHandler {
/** for serialization. */
static final long serialVersionUID = 5607529739745491340L;
@@ -167,6 +165,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*
* @return the file extension
*/
+ @Override
public String getFileExtension() {
return FILE_EXTENSION;
}
@@ -176,6 +175,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*
* @return a short file description
*/
+ @Override
public String getFileDescription() {
return "CSV data files";
}
@@ -185,6 +185,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*
* @return the file extensions
*/
+ @Override
public String[] getFileExtensions() {
return new String[] { getFileExtension() };
}
@@ -197,8 +198,8 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*/
public String globalInfo() {
return "Reads a source that is in comma separated or tab separated format. "
- + "Assumes that the first row in the file determines the number of "
- + "and names of the attributes.";
+ + "Assumes that the first row in the file determines the number of "
+ + "and names of the attributes.";
}
/**
@@ -206,39 +207,41 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*
* @return an enumeration of all the available options.
*/
+ @Override
public Enumeration listOptions() {
Vector result = new Vector();
result.addElement(new Option(
- "\tThe range of attributes to force type to be NOMINAL.\n"
- + "\t'first' and 'last' are accepted as well.\n"
- + "\tExamples: \"first-last\", \"1,4,5-27,50-last\"\n"
- + "\t(default: -none-)", "N", 1, "-N <range>"));
+ "\tThe range of attributes to force type to be NOMINAL.\n"
+ + "\t'first' and 'last' are accepted as well.\n"
+ + "\tExamples: \"first-last\", \"1,4,5-27,50-last\"\n"
+ + "\t(default: -none-)", "N", 1, "-N <range>"));
result.addElement(new Option(
- "\tThe range of attribute to force type to be STRING.\n"
- + "\t'first' and 'last' are accepted as well.\n"
- + "\tExamples: \"first-last\", \"1,4,5-27,50-last\"\n"
- + "\t(default: -none-)", "S", 1, "-S <range>"));
+ "\tThe range of attribute to force type to be STRING.\n"
+ + "\t'first' and 'last' are accepted as well.\n"
+ + "\tExamples: \"first-last\", \"1,4,5-27,50-last\"\n"
+ + "\t(default: -none-)", "S", 1, "-S <range>"));
result.add(new Option(
- "\tThe range of attribute to force type to be DATE.\n"
- + "\t'first' and 'last' are accepted as well.\n"
- + "\tExamples: \"first-last\", \"1,4,5-27,50-last\"\n"
- + "\t(default: -none-)", "D", 1, "-D <range>"));
+ "\tThe range of attribute to force type to be DATE.\n"
+ + "\t'first' and 'last' are accepted as well.\n"
+ + "\tExamples: \"first-last\", \"1,4,5-27,50-last\"\n"
+ + "\t(default: -none-)", "D", 1, "-D <range>"));
result.add(new Option(
- "\tThe date formatting string to use to parse date values.\n"
- + "\t(default: \"yyyy-MM-dd'T'HH:mm:ss\")", "format", 1,
- "-format <date format>"));
+ "\tThe date formatting string to use to parse date values.\n"
+ + "\t(default: \"yyyy-MM-dd'T'HH:mm:ss\")", "format", 1,
+ "-format <date format>"));
result.addElement(new Option("\tThe string representing a missing value.\n"
- + "\t(default: ?)", "M", 1, "-M <str>"));
+ + "\t(default: ?)", "M", 1, "-M <str>"));
- result.addElement(new Option(
+ result
+ .addElement(new Option(
"\tThe enclosure character(s) to use for strings.\n"
- + "\tSpecify as a comma separated list (e.g. \",'"
- + " (default: \",')", "E", 1, "-E <enclosures>"));
+ + "\tSpecify as a comma separated list (e.g. \",'"
+ + " (default: \",')", "E", 1, "-E <enclosures>"));
return result.elements();
}
@@ -247,8 +250,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
* Parses a given list of options.
* <p/>
*
- <!-- options-start -->
- * Valid options are:
+ * <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
@@ -293,11 +295,12 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
* Specify as a comma separated list (e.g. ",' (default: '"')
* </pre>
*
- <!-- options-end -->
+ * <!-- options-end -->
*
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
+ @Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
@@ -338,6 +341,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*
* @return an array of strings suitable for passing to setOptions
*/
+ @Override
public String[] getOptions() {
Vector<String> result;
@@ -395,7 +399,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*/
public String nominalAttributesTipText() {
return "The range of attributes to force to be of type NOMINAL, example "
- + "ranges: 'first-last', '1,4,7-14,50-last'.";
+ + "ranges: 'first-last', '1,4,7-14,50-last'.";
}
/**
@@ -424,7 +428,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*/
public String stringAttributesTipText() {
return "The range of attributes to force to be of type STRING, example "
- + "ranges: 'first-last', '1,4,7-14,50-last'.";
+ + "ranges: 'first-last', '1,4,7-14,50-last'.";
}
/**
@@ -453,7 +457,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*/
public String dateAttributesTipText() {
return "The range of attributes to force to type STRING, example "
- + "ranges: 'first-last', '1,4,7-14, 50-last'.";
+ + "ranges: 'first-last', '1,4,7-14, 50-last'.";
}
/**
@@ -683,11 +687,11 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
String relationName;
if (m_sourceFile != null)
relationName = (m_sourceFile.getName())
- .replaceAll("\\.[cC][sS][vV]$", "");
+ .replaceAll("\\.[cC][sS][vV]$", "");
else
relationName = "stream";
Instances dataSet = new Instances(relationName, atts,
- m_cumulativeInstances.size());
+ m_cumulativeInstances.size());
for (int i = 0; i < m_cumulativeInstances.size(); i++) {
current = ((FastVector) m_cumulativeInstances.elementAt(i));
@@ -707,7 +711,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
vals[j] = index;
} else {
throw new IllegalStateException(
- "Wrong attribute type at position " + (i + 1) + "!!!");
+ "Wrong attribute type at position " + (i + 1) + "!!!");
}
}
} else if (dataSet.attribute(j).isNominal()) {
@@ -781,7 +785,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
boolean wasSep;
while (tokenizer.ttype != StreamTokenizer.TT_EOL
- && tokenizer.ttype != StreamTokenizer.TT_EOF) {
+ && tokenizer.ttype != StreamTokenizer.TT_EOF) {
// Get next token
if (!first) {
@@ -789,12 +793,13 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
}
if (tokenizer.ttype == ',' || tokenizer.ttype == '\t'
- || tokenizer.ttype == StreamTokenizer.TT_EOL) {
+ || tokenizer.ttype == StreamTokenizer.TT_EOL) {
current.addElement(m_MissingValue);
wasSep = true;
} else {
wasSep = false;
- if (tokenizer.sval.equals(m_MissingValue)) {
+ if (tokenizer.sval.equals(m_MissingValue)
+ || tokenizer.sval.trim().length() == 0) {
current.addElement(new String(m_MissingValue));
} else {
// try to parse as a number
@@ -817,8 +822,8 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
// check number of values read
if (current.size() != m_structure.numAttributes()) {
ConverterUtils.errms(tokenizer,
- "wrong number of values. Read " + current.size() + ", expected "
- + m_structure.numAttributes());
+ "wrong number of values. Read " + current.size() + ", expected "
+ + m_structure.numAttributes());
}
// check for structure update
@@ -868,7 +873,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
for (int i = 0; i < current.size(); i++) {
Object ob = current.elementAt(i);
if ((ob instanceof String) || (m_NominalAttributes.isInRange(i))
- || (m_StringAttributes.isInRange(i)) || m_dateAttributes.isInRange(i)) {
+ || (m_StringAttributes.isInRange(i)) || m_dateAttributes.isInRange(i)) {
if (ob.toString().compareTo(m_MissingValue) == 0) {
// do nothing
} else {
@@ -899,14 +904,14 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
if (tempHash.size() == 0) {
for (int j = 0; j < m_cumulativeInstances.size(); j++) {
FastVector tempUpdate = ((FastVector) m_cumulativeInstances
- .elementAt(j));
+ .elementAt(j));
Object tempO = tempUpdate.elementAt(i);
if (tempO instanceof String) {
// must have been a missing value
} else {
if (!tempHash.containsKey(tempO)) {
tempHash.put(new Double(((Double) tempO).doubleValue()),
- new Integer(tempHash.size()));
+ new Integer(tempHash.size()));
}
}
}
@@ -922,7 +927,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
if (!tempHash.containsKey(ob)) {
int newIndex = tempHash.size();
tempHash.put(new Double(((Double) ob).doubleValue()), new Integer(
- newIndex));
+ newIndex));
}
}
} else {
@@ -968,7 +973,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
String relationName;
if (m_sourceFile != null)
relationName = (m_sourceFile.getName())
- .replaceAll("\\.[cC][sS][vV]$", "");
+ .replaceAll("\\.[cC][sS][vV]$", "");
else
relationName = "stream";
m_structure = new Instances(relationName, attribNames, 0);
@@ -991,7 +996,7 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
for (String e : parts) {
if (e.length() > 1 || e.length() == 0) {
throw new IllegalArgumentException(
- "Enclosures can only be single characters");
+ "Enclosures can only be single characters");
}
tokenizer.quoteChar(e.charAt(0));
}
@@ -1022,8 +1027,9 @@ public class CSVLoader extends AbstractFileLoader implements BatchConverter,
*
* @return the revision
*/
+ @Override
public String getRevision() {
- return RevisionUtils.extract("$Revision: 9280 $");
+ return RevisionUtils.extract("$Revision: 10372 $");
}
/**
diff --git a/src/main/java/weka/core/version.txt b/src/main/java/weka/core/version.txt
index 3e64a1d..c788d3a 100644
--- a/src/main/java/weka/core/version.txt
+++ b/src/main/java/weka/core/version.txt
@@ -1 +1 @@
-3-6-10
\ No newline at end of file
+3-6-11
\ No newline at end of file
diff --git a/src/main/java/weka/datagenerators/DataGenerator.java b/src/main/java/weka/datagenerators/DataGenerator.java
index cdc113d..98e1bcd 100644
--- a/src/main/java/weka/datagenerators/DataGenerator.java
+++ b/src/main/java/weka/datagenerators/DataGenerator.java
@@ -22,33 +22,32 @@
package weka.datagenerators;
-import weka.core.Instance;
-import weka.core.Instances;
-import weka.core.Option;
-import weka.core.OptionHandler;
-import weka.core.Randomizable;
-import weka.core.RevisionHandler;
-import weka.core.Utils;
-
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
-import java.io.StringWriter;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Random;
import java.util.Vector;
-/**
- * Abstract superclass for data generators that generate data for
- * classifiers and clusterers.
- *
+import weka.core.Instance;
+import weka.core.Instances;
+import weka.core.Option;
+import weka.core.OptionHandler;
+import weka.core.Randomizable;
+import weka.core.RevisionHandler;
+import weka.core.Utils;
+
+/**
+ * Abstract superclass for data generators that generate data for classifiers
+ * and clusterers.
+ *
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision: 1.8 $
*/
-public abstract class DataGenerator
- implements OptionHandler, Randomizable, Serializable, RevisionHandler {
+public abstract class DataGenerator implements OptionHandler, Randomizable,
+ Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -3698585946221802578L;
@@ -62,30 +61,34 @@ public abstract class DataGenerator
/** Relation name the dataset should have */
protected String m_RelationName = "";
- /** Number of instances that should be produced into the dataset
- * this number is by default m_NumExamples,
- * but can be reset by the generator
+ /**
+ * Number of instances that should be produced into the dataset this number is
+ * by default m_NumExamples, but can be reset by the generator
*/
protected int m_NumExamplesAct;
- /** default output (is printed to stdout after generation) */
- protected transient StringWriter m_DefaultOutput = new StringWriter();
+ /** default output (stdout) */
+ protected transient PrintWriter m_DefaultOutput = new PrintWriter(
+ new java.io.OutputStreamWriter(System.out));
/** PrintWriter for outputting the generated data */
- protected transient PrintWriter m_Output = new PrintWriter(m_DefaultOutput);
+ protected transient PrintWriter m_Output = m_DefaultOutput;
- /** random number generator seed*/
+ /** random number generator seed */
protected int m_Seed;
- /** random number generator*/
+ /** random number generator */
protected Random m_Random = null;
/** flag, that indicates whether the relationname is currently assembled */
protected boolean m_CreatingRelationName = false;
- /** a black list for options not to be listed (for derived generators)
- * in the makeOptionString method
- * @see #makeOptionString(DataGenerator) */
+ /**
+ * a black list for options not to be listed (for derived generators) in the
+ * makeOptionString method
+ *
+ * @see #makeOptionString(DataGenerator)
+ */
protected static HashSet m_OptionBlacklist;
static {
m_OptionBlacklist = new HashSet();
@@ -93,26 +96,27 @@ public abstract class DataGenerator
/**
* initializes with default settings. <br/>
- * Note: default values are set via a default<name> method. These
+ * Note: default values are set via a default<name> method. These
* default methods are also used in the listOptions method and in the
- * setOptions method. Why? Derived generators can override the return value
- * of these default methods, to avoid exceptions.
+ * setOptions method. Why? Derived generators can override the return value of
+ * these default methods, to avoid exceptions.
*/
public DataGenerator() {
clearBlacklist();
-
+
setNumExamplesAct(defaultNumExamplesAct());
setSeed(defaultSeed());
}
/**
- * creates a vector out of the enumeration from the listOptions of the
- * super class. Only a "convenience" method.
- * @param enm the Enumeration to dump into a vector
- * @return the elements of the enumeration in a vector
+ * creates a vector out of the enumeration from the listOptions of the super
+ * class. Only a "convenience" method.
+ *
+ * @param enm the Enumeration to dump into a vector
+ * @return the elements of the enumeration in a vector
*/
protected Vector enumToVector(Enumeration enm) {
- Vector result;
+ Vector result;
result = new Vector();
@@ -124,49 +128,46 @@ public abstract class DataGenerator
/**
* Returns an enumeration describing the available options.
- *
+ *
* @return an enumeration of all the available options
*/
+ @Override
public Enumeration listOptions() {
- Vector result;
+ Vector result;
result = new Vector();
- result.addElement(new Option(
- "\tPrints this help.",
- "h", 1, "-h"));
+ result.addElement(new Option("\tPrints this help.", "h", 1, "-h"));
result.addElement(new Option(
- "\tThe name of the output file, otherwise the generated data is\n"
- + "\tprinted to stdout.",
- "o", 1, "-o <file>"));
+ "\tThe name of the output file, otherwise the generated data is\n"
+ + "\tprinted to stdout.", "o", 1, "-o <file>"));
- result.addElement(new Option(
- "\tThe name of the relation.",
- "r", 1, "-r <name>"));
+ result.addElement(new Option("\tThe name of the relation.", "r", 1,
+ "-r <name>"));
- result.addElement(new Option(
- "\tWhether to print debug informations.",
- "d", 0, "-d"));
+ result.addElement(new Option("\tWhether to print debug informations.", "d",
+ 0, "-d"));
- result.addElement(new Option(
- "\tThe seed for random function (default "
- + defaultSeed() + ")",
- "S", 1, "-S"));
+ result.addElement(new Option("\tThe seed for random function (default "
+ + defaultSeed() + ")", "S", 1, "-S"));
return result.elements();
}
/**
- * Parses a list of options for this object. <p/>
- *
- * For list of valid options see class description. <p/>
- *
+ * Parses a list of options for this object.
+ * <p/>
+ *
+ * For list of valid options see class description.
+ * <p/>
+ *
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
+ @Override
public void setOptions(String[] options) throws Exception {
- String tmpStr;
+ String tmpStr;
// remove unwanted options
options = removeBlacklist(options);
@@ -184,7 +185,7 @@ public abstract class DataGenerator
throw new Exception("No Output defined!");
setDebug(Utils.getFlag('d', options));
-
+
tmpStr = Utils.getOption('S', options);
if (tmpStr.length() != 0)
setSeed(Integer.parseInt(tmpStr));
@@ -193,15 +194,16 @@ public abstract class DataGenerator
}
/**
- * Gets the current settings of the datagenerator RDG1. Removing of
- * blacklisted options has to be done in the derived class, that defines
- * the blacklist-entry.
- *
+ * Gets the current settings of the datagenerator RDG1. Removing of
+ * blacklisted options has to be done in the derived class, that defines the
+ * blacklist-entry.
+ *
* @return an array of strings suitable for passing to setOptions
- * @see #removeBlacklist(String[])
+ * @see #removeBlacklist(String[])
*/
+ @Override
public String[] getOptions() {
- Vector result;
+ Vector result;
result = new Vector();
@@ -213,7 +215,7 @@ public abstract class DataGenerator
if (getDebug())
result.add("-d");
-
+
result.add("-S");
result.add("" + getSeed());
@@ -221,12 +223,11 @@ public abstract class DataGenerator
}
/**
- * Initializes the format for the dataset produced.
- * Must be called before the generateExample or generateExamples
- * methods are used. Also sets a default relation name in case
- * the current relation name is empty.
- *
- * @return the format for the dataset
+ * Initializes the format for the dataset produced. Must be called before the
+ * generateExample or generateExamples methods are used. Also sets a default
+ * relation name in case the current relation name is empty.
+ *
+ * @return the format for the dataset
* @throws Exception if the generating of the format failed
* @see #defaultRelationName()
*/
@@ -238,75 +239,76 @@ public abstract class DataGenerator
}
/**
- * Generates one example of the dataset.
- *
+ * Generates one example of the dataset.
+ *
* @return the generated example
* @throws Exception if the format of the dataset is not yet defined
- * @throws Exception if the generator only works with generateExamples
- * which means in non single mode
+ * @throws Exception if the generator only works with generateExamples which
+ * means in non single mode
*/
public abstract Instance generateExample() throws Exception;
/**
- * Generates all examples of the dataset.
- *
+ * Generates all examples of the dataset.
+ *
* @return the generated dataset
* @throws Exception if the format of the dataset is not yet defined
- * @throws Exception if the generator only works with generateExample,
- * which means in single mode
+ * @throws Exception if the generator only works with generateExample, which
+ * means in single mode
*/
public abstract Instances generateExamples() throws Exception;
/**
- * Generates a comment string that documentates the data generator.
- * By default this string is added at the beginning of the produced output
- * as ARFF file type, next after the options.
+ * Generates a comment string that documentates the data generator. By default
+ * this string is added at the beginning of the produced output as ARFF file
+ * type, next after the options.
*
* @return string contains info about the generated rules
* @throws Exception if the generating of the documentation fails
*/
- public abstract String generateStart () throws Exception;
+ public abstract String generateStart() throws Exception;
/**
- * Generates a comment string that documentates the data generator.
- * By default this string is added at the end of the produced output
- * as ARFF file type.
+ * Generates a comment string that documentates the data generator. By default
+ * this string is added at the end of the produced output as ARFF file type.
*
* @return string contains info about the generated rules
* @throws Exception if the generating of the documentation fails
*/
- public abstract String generateFinished () throws Exception;
+ public abstract String generateFinished() throws Exception;
/**
- * Return if single mode is set for the given data generator
- * mode depends on option setting and or generator type.
+ * Return if single mode is set for the given data generator mode depends on
+ * option setting and or generator type.
*
* @return single mode flag
* @throws Exception if mode is not set yet
*/
- public abstract boolean getSingleModeFlag () throws Exception;
+ public abstract boolean getSingleModeFlag() throws Exception;
/**
* Sets the debug flag.
+ *
* @param debug the new debug flag
*/
- public void setDebug(boolean debug) {
+ public void setDebug(boolean debug) {
m_Debug = debug;
}
/**
* Gets the debug flag.
- * @return the debug flag
+ *
+ * @return the debug flag
*/
- public boolean getDebug() {
- return m_Debug;
+ public boolean getDebug() {
+ return m_Debug;
}
-
+
/**
* Returns the tip text for this property
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String debugTipText() {
return "Whether the generator is run in debug mode or not.";
@@ -314,6 +316,7 @@ public abstract class DataGenerator
/**
* Sets the relation name the dataset should have.
+ *
* @param relationName the new relation name
*/
public void setRelationName(String relationName) {
@@ -326,10 +329,10 @@ public abstract class DataGenerator
* @return a relation name based on the options
*/
protected String defaultRelationName() {
- StringBuffer result;
- String[] options;
- String option;
- int i;
+ StringBuffer result;
+ String[] options;
+ String option;
+ int i;
m_CreatingRelationName = true;
@@ -349,15 +352,16 @@ public abstract class DataGenerator
}
/**
- * returns the relation name to use, i.e., in case the currently set
- * relation name is empty, a generic one is returned. Must be used in
+ * returns the relation name to use, i.e., in case the currently set relation
+ * name is empty, a generic one is returned. Must be used in
* defineDataFormat()
+ *
* @return the relation name
* @see #defaultRelationName()
* @see #defineDataFormat()
*/
protected String getRelationNameToUse() {
- String result;
+ String result;
result = getRelationName();
if (result.length() == 0)
@@ -368,17 +372,18 @@ public abstract class DataGenerator
/**
* Gets the relation name the dataset should have.
+ *
* @return the relation name the dataset should have
*/
- public String getRelationName() {
+ public String getRelationName() {
return m_RelationName;
}
-
+
/**
* Returns the tip text for this property
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String relationNameTipText() {
return "The relation name of the generated data (if empty, a generic one will be supplied).";
@@ -395,25 +400,27 @@ public abstract class DataGenerator
/**
* Sets the number of examples the dataset should have.
+ *
* @param numExamplesAct the new number of examples
*/
- protected void setNumExamplesAct(int numExamplesAct) {
+ protected void setNumExamplesAct(int numExamplesAct) {
m_NumExamplesAct = numExamplesAct;
}
/**
* Gets the number of examples the dataset should have.
+ *
* @return the number of examples the dataset should have
*/
- public int getNumExamplesAct() {
- return m_NumExamplesAct;
+ public int getNumExamplesAct() {
+ return m_NumExamplesAct;
}
-
+
/**
* Returns the tip text for this property
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
protected String numExamplesActTipText() {
return "The actual number of examples to generate.";
@@ -421,51 +428,55 @@ public abstract class DataGenerator
/**
* Sets the print writer.
+ *
* @param newOutput the new print writer
*/
public void setOutput(PrintWriter newOutput) {
- m_Output = newOutput;
+ m_Output = newOutput;
m_DefaultOutput = null;
}
/**
* Gets the print writer.
+ *
* @return print writer object
*/
- public PrintWriter getOutput() {
- return m_Output;
+ public PrintWriter getOutput() {
+ return m_Output;
}
/**
- * Gets the string writer, which is used for outputting to stdout.
- * A workaround for the problem of closing stdout when closing the
- * associated Printwriter.
- * @return print string writer object
+ * Gets the writer, which is used for outputting to stdout. A workaround for
+ * the problem of closing stdout when closing the associated Printwriter.
+ *
+ * @return writer object
*/
- public StringWriter defaultOutput() {
- return m_DefaultOutput;
+ public PrintWriter defaultOutput() {
+ return m_DefaultOutput;
}
-
+
/**
* Returns the tip text for this property
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String outputTipText() {
return "The output writer to use for printing the generated data.";
}
/**
- * Sets the format of the dataset that is to be generated.
- * @param newFormat the new dataset format of the dataset
+ * Sets the format of the dataset that is to be generated.
+ *
+ * @param newFormat the new dataset format of the dataset
*/
public void setDatasetFormat(Instances newFormat) {
m_DatasetFormat = new Instances(newFormat, 0);
}
/**
- * Gets the format of the dataset that is to be generated.
+ * Gets the format of the dataset that is to be generated.
+ *
* @return the dataset format of the dataset
*/
public Instances getDatasetFormat() {
@@ -474,12 +485,12 @@ public abstract class DataGenerator
else
return null;
}
-
+
/**
* Returns the tip text for this property
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String formatTipText() {
return "The data format to use.";
@@ -493,31 +504,33 @@ public abstract class DataGenerator
protected int defaultSeed() {
return 1;
}
-
+
/**
* Gets the random number seed.
- *
+ *
* @return the random number seed.
*/
- public int getSeed() {
- return m_Seed;
+ @Override
+ public int getSeed() {
+ return m_Seed;
}
-
+
/**
* Sets the random number seed.
- *
+ *
* @param newSeed the new random number seed.
*/
- public void setSeed(int newSeed) {
- m_Seed = newSeed;
+ @Override
+ public void setSeed(int newSeed) {
+ m_Seed = newSeed;
m_Random = new Random(newSeed);
}
-
+
/**
* Returns the tip text for this property
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String seedTipText() {
return "The seed value for the random number generator.";
@@ -525,30 +538,30 @@ public abstract class DataGenerator
/**
* Gets the random generator.
- *
+ *
* @return the random generator
*/
public Random getRandom() {
if (m_Random == null)
- m_Random = new Random (getSeed());
+ m_Random = new Random(getSeed());
return m_Random;
}
-
+
/**
* Sets the random generator.
- *
+ *
* @param newRandom is the random generator.
*/
public void setRandom(Random newRandom) {
m_Random = newRandom;
}
-
+
/**
* Returns the tip text for this property
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String randomTipText() {
return "The random number generator to use.";
@@ -556,13 +569,13 @@ public abstract class DataGenerator
/**
* Returns a string representing the dataset in the instance queue.
+ *
* @return the string representing the output data format
*/
protected String toStringFormat() {
if (m_DatasetFormat == null)
return "";
- return
- m_DatasetFormat.toString();
+ return m_DatasetFormat.toString();
}
/**
@@ -571,11 +584,12 @@ public abstract class DataGenerator
protected static void clearBlacklist() {
m_OptionBlacklist.clear();
}
-
+
/**
* adds the given option, e.g., for "-V" use "V", to the blacklist of options
* that are not to be output via the makeOptionString method
- * @param option the option to exclude from listing
+ *
+ * @param option the option to exclude from listing
* @see #makeOptionString(DataGenerator)
*/
protected static void addToBlacklist(String option) {
@@ -583,9 +597,10 @@ public abstract class DataGenerator
}
/**
- * checks, whether the given option is in the blacklist of options not to
- * be output by makeOptionString
- * @param option the option to check
+ * checks, whether the given option is in the blacklist of options not to be
+ * output by makeOptionString
+ *
+ * @param option the option to check
* @return true if the option is on the blacklist
* @see #makeOptionString(DataGenerator)
*/
@@ -600,12 +615,12 @@ public abstract class DataGenerator
* @return the processed options array
*/
protected String[] removeBlacklist(String[] options) {
- Enumeration enm;
- Hashtable pool;
- Option option;
+ Enumeration enm;
+ Hashtable pool;
+ Option option;
// retrieve options that are on blacklist
- enm = listOptions();
+ enm = listOptions();
pool = new Hashtable();
while (enm.hasMoreElements()) {
option = (Option) enm.nextElement();
@@ -622,8 +637,7 @@ public abstract class DataGenerator
Utils.getFlag(option.name(), options);
else
Utils.getOption(option.name(), options);
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
@@ -638,10 +652,10 @@ public abstract class DataGenerator
* @return the assembled option string
*/
protected static String makeOptionString(DataGenerator generator) {
- StringBuffer result;
- Enumeration enm;
- Option option;
-
+ StringBuffer result;
+ Enumeration enm;
+ Option option;
+
result = new StringBuffer();
result.append("\nData Generator options:\n\n");
@@ -659,18 +673,18 @@ public abstract class DataGenerator
/**
* Calls the data generator.
- *
- * @param generator one of the data generators
+ *
+ * @param generator one of the data generators
* @param options options of the data generator
* @throws Exception if there was an error in the option list
*/
- public static void makeData(DataGenerator generator, String[] options)
+ public static void makeData(DataGenerator generator, String[] options)
throws Exception {
- boolean printhelp;
- Vector unknown;
- int i;
-
+ boolean printhelp;
+ Vector unknown;
+ int i;
+
// help?
printhelp = (Utils.getFlag('h', options));
@@ -679,11 +693,11 @@ public abstract class DataGenerator
try {
options = generator.removeBlacklist(options);
generator.setOptions(options);
-
+
// check for left-over options, but don't raise exception
unknown = new Vector();
for (i = 0; i < options.length; i++) {
- if (options[i].length() != 0)
+ if (options[i].length() != 0)
unknown.add(options[i]);
}
if (unknown.size() > 0) {
@@ -692,19 +706,18 @@ public abstract class DataGenerator
System.out.print(" " + unknown.get(i));
System.out.println();
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
printhelp = true;
}
}
-
+
if (printhelp) {
System.out.println(makeOptionString(generator));
return;
}
-
- // define dataset format
+
+ // define dataset format
// computes actual number of examples to be produced
generator.setDatasetFormat(generator.defineDataFormat());
@@ -715,13 +728,13 @@ public abstract class DataGenerator
output.println("%");
output.println("% Commandline");
output.println("%");
- output.println("% " + generator.getClass().getName() + " "
- + Utils.joinOptions(generator.getOptions()));
+ output.println("% " + generator.getClass().getName() + " "
+ + Utils.joinOptions(generator.getOptions()));
output.println("%");
// comment at beginning of ARFF File
String commentAtStart = generator.generateStart();
-
+
if (commentAtStart.length() > 0) {
output.println("%");
output.println("% Prologue");
@@ -737,20 +750,19 @@ public abstract class DataGenerator
if (singleMode) {
// output of dataset header
output.println(generator.toStringFormat());
- for (i = 0; i < generator.getNumExamplesAct(); i++) {
+ for (i = 0; i < generator.getNumExamplesAct(); i++) {
// over all examples to be produced
Instance inst = generator.generateExample();
output.println(inst);
}
- }
- else { // generator produces all instances at once
+ } else { // generator produces all instances at once
Instances dataset = generator.generateExamples();
- // output of dataset
- output.println(dataset);
+ // output of dataset
+ output.println(dataset);
}
// comment at end of ARFF File
String commentAtEnd = generator.generateFinished();
-
+
if (commentAtEnd.length() > 0) {
output.println("%");
output.println("% Epilogue");
@@ -758,31 +770,30 @@ public abstract class DataGenerator
output.println(commentAtEnd.trim());
output.println("%");
}
-
+
output.flush();
- output.close();
- // print result to stdout?
- if (generator.defaultOutput() != null)
- System.out.println(generator.defaultOutput().toString());
+ if (generator.getOutput() != generator.defaultOutput()) {
+ output.close();
+ }
}
-
+
/**
* runs the datagenerator instance with the given options.
*
- * @param datagenerator the datagenerator to run
- * @param options the commandline options
+ * @param datagenerator the datagenerator to run
+ * @param options the commandline options
*/
- protected static void runDataGenerator(DataGenerator datagenerator, String[] options) {
+ protected static void runDataGenerator(DataGenerator datagenerator,
+ String[] options) {
try {
DataGenerator.makeData(datagenerator, options);
- }
- catch (Exception e) {
- if ( (e.getMessage() != null)
- && (e.getMessage().indexOf("Data Generator options") == -1) )
- e.printStackTrace();
+ } catch (Exception e) {
+ if ((e.getMessage() != null)
+ && (e.getMessage().indexOf("Data Generator options") == -1))
+ e.printStackTrace();
else
- System.err.println(e.getMessage());
+ System.err.println(e.getMessage());
}
}
}
diff --git a/src/main/java/weka/experiment/DatabaseUtils.java b/src/main/java/weka/experiment/DatabaseUtils.java
index 182f121..10ebe73 100644
--- a/src/main/java/weka/experiment/DatabaseUtils.java
+++ b/src/main/java/weka/experiment/DatabaseUtils.java
@@ -22,10 +22,6 @@
package weka.experiment;
-import weka.core.RevisionHandler;
-import weka.core.RevisionUtils;
-import weka.core.Utils;
-
import java.io.Serializable;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
@@ -42,28 +38,32 @@ import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
+import weka.core.RevisionHandler;
+import weka.core.RevisionUtils;
+import weka.core.Utils;
+
/**
* DatabaseUtils provides utility functions for accessing the experiment
- * database. The jdbc
- * driver and database to be used default to "jdbc.idbDriver" and
- * "jdbc:idb=experiments.prp". These may be changed by creating
- * a java properties file called DatabaseUtils.props in user.home or
- * the current directory. eg:<p>
- *
+ * database. The jdbc driver and database to be used default to "jdbc.idbDriver"
+ * and "jdbc:idb=experiments.prp". These may be changed by creating a java
+ * properties file called DatabaseUtils.props in user.home or the current
+ * directory. eg:
+ * <p>
+ *
* <code><pre>
* jdbcDriver=jdbc.idbDriver
* jdbcURL=jdbc:idb=experiments.prp
- * </pre></code><p>
- *
+ * </pre></code>
+ * <p>
+ *
* @author Len Trigg (trigg at cs.waikato.ac.nz)
- * @version $Revision: 5240 $
+ * @version $Revision: 10206 $
*/
-public class DatabaseUtils
- implements Serializable, RevisionHandler {
+public class DatabaseUtils implements Serializable, RevisionHandler {
/** for serialization. */
static final long serialVersionUID = -8252351994547116729L;
-
+
/** The name of the table containing the index to experiments. */
public static final String EXP_INDEX_TABLE = "Experiment_index";
@@ -72,7 +72,7 @@ public class DatabaseUtils
/** The name of the column containing the experiment setup (parameters). */
public static final String EXP_SETUP_COL = "Experiment_setup";
-
+
/** The name of the column containing the results table name. */
public static final String EXP_RESULT_COL = "Result_table";
@@ -109,31 +109,31 @@ public class DatabaseUtils
/** Type mapping for FLOAT used for reading experiment results. */
public static final int FLOAT = 7;
/** Type mapping for DATE used for reading experiment results. */
- public static final int DATE = 8;
+ public static final int DATE = 8;
/** Type mapping for TEXT used for reading, e.g., text blobs. */
- public static final int TEXT = 9;
+ public static final int TEXT = 9;
/** Type mapping for TIME used for reading TIME columns. */
- public static final int TIME = 10;
-
+ public static final int TIME = 10;
+
/** Database URL. */
protected String m_DatabaseURL;
-
+
/** The prepared statement used for database queries. */
protected transient PreparedStatement m_PreparedStatement;
-
+
/** The database connection. */
protected transient Connection m_Connection;
/** True if debugging output should be printed. */
protected boolean m_Debug = false;
-
+
/** Database username. */
protected String m_userName = "";
/** Database Password. */
protected String m_password = "";
- /* mappings used for creating Tables. Can be overridden in DatabaseUtils.props*/
+ /* mappings used for creating Tables. Can be overridden in DatabaseUtils.props */
/** string type for the create table statement. */
protected String m_stringType = "LONGVARCHAR";
/** integer type for the create table statement. */
@@ -158,15 +158,16 @@ public class DatabaseUtils
/** the character to mask SQL keywords (by appending this character). */
protected String m_KeywordsMaskChar = "_";
-
+
/**
* Reads properties and sets up the database drivers.
- *
- * @throws Exception if an error occurs
+ *
+ * @throws Exception if an error occurs
*/
public DatabaseUtils() throws Exception {
- if (DRIVERS_ERRORS == null)
+ if (DRIVERS_ERRORS == null) {
DRIVERS_ERRORS = new Vector();
+ }
try {
PROPERTIES = Utils.readProperties(PROPERTY_FILE);
@@ -187,126 +188,125 @@ public class DatabaseUtils
Class.forName(driver);
DRIVERS.addElement(driver);
result = true;
- }
- catch (Exception e) {
+ } catch (Exception e) {
result = false;
}
- if (m_Debug || (!result && !DRIVERS_ERRORS.contains(driver)))
- System.err.println(
- "Trying to add database driver (JDBC): " + driver
- + " - " + (result ? "Success!" : "Error, not in CLASSPATH?"));
- if (!result)
+ if (m_Debug || (!result && !DRIVERS_ERRORS.contains(driver))) {
+ System.err.println("Trying to add database driver (JDBC): " + driver
+ + " - " + (result ? "Success!" : "Error, not in CLASSPATH?"));
+ }
+ if (!result) {
DRIVERS_ERRORS.add(driver);
+ }
}
} catch (Exception ex) {
System.err.println("Problem reading properties. Fix before continuing.");
System.err.println(ex);
}
- m_DatabaseURL = PROPERTIES.getProperty("jdbcURL", "jdbc:idb=experiments.prp");
- m_stringType = PROPERTIES.getProperty("CREATE_STRING", "LONGVARCHAR");
- m_intType = PROPERTIES.getProperty("CREATE_INT", "INT");
- m_doubleType = PROPERTIES.getProperty("CREATE_DOUBLE", "DOUBLE");
- m_checkForUpperCaseNames = PROPERTIES.getProperty(
- "checkUpperCaseNames", "false").equals("true");
- m_checkForLowerCaseNames = PROPERTIES.getProperty(
- "checkLowerCaseNames", "false").equals("true");
- m_setAutoCommit = PROPERTIES.getProperty(
- "setAutoCommit", "false").equals("true");
- m_createIndex = PROPERTIES.getProperty(
- "createIndex", "false").equals("true");
- setKeywords(PROPERTIES.getProperty(
- "Keywords", "AND,ASC,BY,DESC,FROM,GROUP,INSERT,ORDER,SELECT,UPDATE,WHERE"));
+ m_DatabaseURL = PROPERTIES.getProperty("jdbcURL",
+ "jdbc:idb=experiments.prp");
+ m_stringType = PROPERTIES.getProperty("CREATE_STRING", "LONGVARCHAR");
+ m_intType = PROPERTIES.getProperty("CREATE_INT", "INT");
+ m_doubleType = PROPERTIES.getProperty("CREATE_DOUBLE", "DOUBLE");
+ m_checkForUpperCaseNames = PROPERTIES.getProperty("checkUpperCaseNames",
+ "false").equals("true");
+ m_checkForLowerCaseNames = PROPERTIES.getProperty("checkLowerCaseNames",
+ "false").equals("true");
+ m_setAutoCommit = PROPERTIES.getProperty("setAutoCommit", "true").equals(
+ "true");
+ m_createIndex = PROPERTIES.getProperty("createIndex", "false").equals(
+ "true");
+ setKeywords(PROPERTIES.getProperty("Keywords",
+ "AND,ASC,BY,DESC,FROM,GROUP,INSERT,ORDER,SELECT,UPDATE,WHERE"));
setKeywordsMaskChar(PROPERTIES.getProperty("KeywordsMaskChar", "_"));
}
-
- /**
- * returns key column headings in their original case. Used for
- * those databases that create uppercase column names.
+
+ /**
+ * returns key column headings in their original case. Used for those
+ * databases that create uppercase column names.
*
- * @param columnName the column to retrieve the original case for
- * @return the original case
+ * @param columnName the column to retrieve the original case for
+ * @return the original case
*/
- protected String attributeCaseFix(String columnName){
+ protected String attributeCaseFix(String columnName) {
if (m_checkForUpperCaseNames) {
String ucname = columnName.toUpperCase();
if (ucname.equals(EXP_TYPE_COL.toUpperCase())) {
- return EXP_TYPE_COL;
+ return EXP_TYPE_COL;
} else if (ucname.equals(EXP_SETUP_COL.toUpperCase())) {
- return EXP_SETUP_COL;
+ return EXP_SETUP_COL;
} else if (ucname.equals(EXP_RESULT_COL.toUpperCase())) {
- return EXP_RESULT_COL;
+ return EXP_RESULT_COL;
} else {
- return columnName;
+ return columnName;
}
- }
- else if (m_checkForLowerCaseNames) {
+ } else if (m_checkForLowerCaseNames) {
String ucname = columnName.toLowerCase();
if (ucname.equals(EXP_TYPE_COL.toLowerCase())) {
- return EXP_TYPE_COL;
+ return EXP_TYPE_COL;
} else if (ucname.equals(EXP_SETUP_COL.toLowerCase())) {
- return EXP_SETUP_COL;
+ return EXP_SETUP_COL;
} else if (ucname.equals(EXP_RESULT_COL.toLowerCase())) {
- return EXP_RESULT_COL;
+ return EXP_RESULT_COL;
} else {
- return columnName;
+ return columnName;
}
- }
- else {
+ } else {
return columnName;
}
}
-
+
/**
* translates the column data type string to an integer value that indicates
* which data type / get()-Method to use in order to retrieve values from the
- * database (see DatabaseUtils.Properties, InstanceQuery()). Blanks in the type
- * are replaced with underscores "_", since Java property names can't contain blanks.
+ * database (see DatabaseUtils.Properties, InstanceQuery()). Blanks in the
+ * type are replaced with underscores "_", since Java property names can't
+ * contain blanks.
*
- * @param type the column type as retrieved with
- * java.sql.MetaData.getColumnTypeName(int)
- * @return an integer value that indicates
- * which data type / get()-Method to use in order to
- * retrieve values from the
+ * @param type the column type as retrieved with
+ * java.sql.MetaData.getColumnTypeName(int)
+ * @return an integer value that indicates which data type / get()-Method to
+ * use in order to retrieve values from the
*/
public int translateDBColumnType(String type) {
try {
// Oracle, e.g., has datatypes like "DOUBLE PRECISION"
// BUT property names can't have blanks in the name (unless escaped with
- // a backslash), hence also check for names where the blanks are
+ // a backslash), hence also check for names where the blanks are
// replaced with underscores "_":
String value = PROPERTIES.getProperty(type);
String typeUnderscore = type.replaceAll(" ", "_");
- if (value == null)
- value = PROPERTIES.getProperty(typeUnderscore);
+ if (value == null) {
+ value = PROPERTIES.getProperty(typeUnderscore);
+ }
return Integer.parseInt(value);
} catch (NumberFormatException e) {
- throw new IllegalArgumentException(
- "Unknown data type: " + type + ". "
- + "Add entry in " + PROPERTY_FILE + ".\n"
- + "If the type contains blanks, either escape them with a backslash "
- + "or use underscores instead of blanks.");
+ throw new IllegalArgumentException("Unknown data type: " + type + ". "
+ + "Add entry in " + PROPERTY_FILE + ".\n"
+ + "If the type contains blanks, either escape them with a backslash "
+ + "or use underscores instead of blanks.");
}
}
/**
- * Converts an array of objects to a string by inserting a space
- * between each element. Null elements are printed as ?
- *
- * @param array the array of objects
- * @return a value of type 'String'
+ * Converts an array of objects to a string by inserting a space between each
+ * element. Null elements are printed as ?
+ *
+ * @param array the array of objects
+ * @return a value of type 'String'
*/
public static String arrayToString(Object[] array) {
String result = "";
if (array == null) {
result = "<null>";
} else {
- for (int i = 0; i < array.length; i++) {
- if (array[i] == null) {
- result += " ?";
- } else {
- result += " " + array[i];
- }
+ for (Object element : array) {
+ if (element == null) {
+ result += " ?";
+ } else {
+ result += " " + element;
+ }
}
}
return result;
@@ -314,64 +314,64 @@ public class DatabaseUtils
/**
* Returns the name associated with a SQL type.
- *
- * @param type the SQL type
- * @return the name of the type
+ *
+ * @param type the SQL type
+ * @return the name of the type
*/
public static String typeName(int type) {
switch (type) {
- case Types.BIGINT :
- return "BIGINT ";
- case Types.BINARY:
- return "BINARY";
- case Types.BIT:
- return "BIT";
- case Types.CHAR:
- return "CHAR";
- case Types.DATE:
- return "DATE";
- case Types.DECIMAL:
- return "DECIMAL";
- case Types.DOUBLE:
- return "DOUBLE";
- case Types.FLOAT:
- return "FLOAT";
- case Types.INTEGER:
- return "INTEGER";
- case Types.LONGVARBINARY:
- return "LONGVARBINARY";
- case Types.LONGVARCHAR:
- return "LONGVARCHAR";
- case Types.NULL:
- return "NULL";
- case Types.NUMERIC:
- return "NUMERIC";
- case Types.OTHER:
- return "OTHER";
- case Types.REAL:
- return "REAL";
- case Types.SMALLINT:
- return "SMALLINT";
- case Types.TIME:
- return "TIME";
- case Types.TIMESTAMP:
- return "TIMESTAMP";
- case Types.TINYINT:
- return "TINYINT";
- case Types.VARBINARY:
- return "VARBINARY";
- case Types.VARCHAR:
- return "VARCHAR";
- default:
- return "Unknown";
+ case Types.BIGINT:
+ return "BIGINT ";
+ case Types.BINARY:
+ return "BINARY";
+ case Types.BIT:
+ return "BIT";
+ case Types.CHAR:
+ return "CHAR";
+ case Types.DATE:
+ return "DATE";
+ case Types.DECIMAL:
+ return "DECIMAL";
+ case Types.DOUBLE:
+ return "DOUBLE";
+ case Types.FLOAT:
+ return "FLOAT";
+ case Types.INTEGER:
+ return "INTEGER";
+ case Types.LONGVARBINARY:
+ return "LONGVARBINARY";
+ case Types.LONGVARCHAR:
+ return "LONGVARCHAR";
+ case Types.NULL:
+ return "NULL";
+ case Types.NUMERIC:
+ return "NUMERIC";
+ case Types.OTHER:
+ return "OTHER";
+ case Types.REAL:
+ return "REAL";
+ case Types.SMALLINT:
+ return "SMALLINT";
+ case Types.TIME:
+ return "TIME";
+ case Types.TIMESTAMP:
+ return "TIMESTAMP";
+ case Types.TINYINT:
+ return "TINYINT";
+ case Types.VARBINARY:
+ return "VARBINARY";
+ case Types.VARCHAR:
+ return "VARCHAR";
+ default:
+ return "Unknown";
}
}
/**
* Returns the tip text for this property.
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String databaseURLTipText() {
return "Set the URL to the database.";
@@ -379,17 +379,17 @@ public class DatabaseUtils
/**
* Get the value of DatabaseURL.
- *
- * @return Value of DatabaseURL.
+ *
+ * @return Value of DatabaseURL.
*/
public String getDatabaseURL() {
return m_DatabaseURL;
}
-
+
/**
* Set the value of DatabaseURL.
- *
- * @param newDatabaseURL Value to assign to DatabaseURL.
+ *
+ * @param newDatabaseURL Value to assign to DatabaseURL.
*/
public void setDatabaseURL(String newDatabaseURL) {
m_DatabaseURL = newDatabaseURL;
@@ -398,26 +398,28 @@ public class DatabaseUtils
/**
* Returns the tip text for this property.
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String debugTipText() {
return "Whether debug information is printed.";
}
-
+
/**
- * Sets whether there should be printed some debugging output to stderr or not.
+ * Sets whether there should be printed some debugging output to stderr or
+ * not.
*
- * @param d true if output should be printed
+ * @param d true if output should be printed
*/
public void setDebug(boolean d) {
m_Debug = d;
}
/**
- * Gets whether there should be printed some debugging output to stderr or not.
+ * Gets whether there should be printed some debugging output to stderr or
+ * not.
*
- * @return true if output should be printed
+ * @return true if output should be printed
*/
public boolean getDebug() {
return m_Debug;
@@ -426,63 +428,63 @@ public class DatabaseUtils
/**
* Returns the tip text for this property.
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String usernameTipText() {
return "The user to use for connecting to the database.";
}
- /**
+ /**
* Set the database username.
- *
- * @param username Username for Database.
+ *
+ * @param username Username for Database.
*/
- public void setUsername(String username){
- m_userName = username;
+ public void setUsername(String username) {
+ m_userName = username;
}
-
- /**
+
+ /**
* Get the database username.
- *
- * @return Database username
+ *
+ * @return Database username
*/
- public String getUsername(){
+ public String getUsername() {
return m_userName;
}
/**
* Returns the tip text for this property.
*
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String passwordTipText() {
return "The password to use for connecting to the database.";
}
- /**
+ /**
* Set the database password.
- *
- * @param password Password for Database.
+ *
+ * @param password Password for Database.
*/
- public void setPassword(String password){
+ public void setPassword(String password) {
m_password = password;
}
-
- /**
+
+ /**
* Get the database password.
- *
- * @return Password for Database.
+ *
+ * @return Password for Database.
*/
- public String getPassword(){
+ public String getPassword() {
return m_password;
}
/**
* Opens a connection to the database.
- *
- * @throws Exception if an error occurs
+ *
+ * @throws Exception if an error occurs
*/
public void connectToDatabase() throws Exception {
if (m_Debug) {
@@ -490,37 +492,37 @@ public class DatabaseUtils
}
if (m_Connection == null) {
if (m_userName.equals("")) {
- try {
- m_Connection = DriverManager.getConnection(m_DatabaseURL);
- } catch (java.sql.SQLException e) {
-
- // Try loading the drivers
- for (int i = 0; i < DRIVERS.size(); i++) {
- try {
- Class.forName((String)DRIVERS.elementAt(i));
- } catch (Exception ex) {
- // Drop through
- }
- }
- m_Connection = DriverManager.getConnection(m_DatabaseURL);
- }
+ try {
+ m_Connection = DriverManager.getConnection(m_DatabaseURL);
+ } catch (java.sql.SQLException e) {
+
+ // Try loading the drivers
+ for (int i = 0; i < DRIVERS.size(); i++) {
+ try {
+ Class.forName((String) DRIVERS.elementAt(i));
+ } catch (Exception ex) {
+ // Drop through
+ }
+ }
+ m_Connection = DriverManager.getConnection(m_DatabaseURL);
+ }
} else {
- try {
- m_Connection = DriverManager.getConnection(m_DatabaseURL, m_userName,
- m_password);
- } catch (java.sql.SQLException e) {
-
- // Try loading the drivers
- for (int i = 0; i < DRIVERS.size(); i++) {
- try {
- Class.forName((String)DRIVERS.elementAt(i));
- } catch (Exception ex) {
- // Drop through
- }
- }
- m_Connection = DriverManager.getConnection(m_DatabaseURL, m_userName,
- m_password);
- }
+ try {
+ m_Connection = DriverManager.getConnection(m_DatabaseURL, m_userName,
+ m_password);
+ } catch (java.sql.SQLException e) {
+
+ // Try loading the drivers
+ for (int i = 0; i < DRIVERS.size(); i++) {
+ try {
+ Class.forName((String) DRIVERS.elementAt(i));
+ } catch (Exception ex) {
+ // Drop through
+ }
+ }
+ m_Connection = DriverManager.getConnection(m_DatabaseURL, m_userName,
+ m_password);
+ }
}
}
m_Connection.setAutoCommit(m_setAutoCommit);
@@ -528,8 +530,8 @@ public class DatabaseUtils
/**
* Closes the connection to the database.
- *
- * @throws Exception if an error occurs
+ *
+ * @throws Exception if an error occurs
*/
public void disconnectFromDatabase() throws Exception {
if (m_Debug) {
@@ -540,176 +542,181 @@ public class DatabaseUtils
m_Connection = null;
}
}
-
+
/**
* Returns true if a database connection is active.
- *
- * @return a value of type 'boolean'
+ *
+ * @return a value of type 'boolean'
*/
public boolean isConnected() {
return (m_Connection != null);
}
/**
- * Returns whether the cursors only support forward movement or are
- * scroll sensitive (with ResultSet.CONCUR_READ_ONLY concurrency).
- * Returns always false if not connected
+ * Returns whether the cursors only support forward movement or are scroll
+ * sensitive (with ResultSet.CONCUR_READ_ONLY concurrency). Returns always
+ * false if not connected
*
- * @return true if connected and the cursor is scroll-sensitive
- * @see ResultSet#TYPE_SCROLL_SENSITIVE
- * @see ResultSet#TYPE_FORWARD_ONLY
- * @see ResultSet#CONCUR_READ_ONLY
+ * @return true if connected and the cursor is scroll-sensitive
+ * @see ResultSet#TYPE_SCROLL_SENSITIVE
+ * @see ResultSet#TYPE_FORWARD_ONLY
+ * @see ResultSet#CONCUR_READ_ONLY
*/
public boolean isCursorScrollSensitive() {
- boolean result;
-
+ boolean result;
+
result = false;
-
+
try {
- if (isConnected())
- result = m_Connection.getMetaData().supportsResultSetConcurrency(
- ResultSet.TYPE_SCROLL_SENSITIVE,
- ResultSet.CONCUR_READ_ONLY);
- }
- catch (Exception e) {
+ if (isConnected()) {
+ result = m_Connection.getMetaData().supportsResultSetConcurrency(
+ ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
+ }
+ } catch (Exception e) {
// ignored
}
-
+
return result;
}
-
+
/**
- * Checks whether cursors are scrollable in general, false otherwise
- * (also if not connected).
+ * Checks whether cursors are scrollable in general, false otherwise (also if
+ * not connected).
*
- * @return true if scrollable and connected
- * @see #getSupportedCursorScrollType()
+ * @return true if scrollable and connected
+ * @see #getSupportedCursorScrollType()
*/
public boolean isCursorScrollable() {
return (getSupportedCursorScrollType() != -1);
}
-
+
/**
- * Returns the type of scrolling that the cursor supports, -1 if not
- * supported or not connected. Checks first for TYPE_SCROLL_SENSITIVE
- * and then for TYPE_SCROLL_INSENSITIVE. In both cases CONCUR_READ_ONLY
- * as concurrency is used.
+ * Returns the type of scrolling that the cursor supports, -1 if not supported
+ * or not connected. Checks first for TYPE_SCROLL_SENSITIVE and then for
+ * TYPE_SCROLL_INSENSITIVE. In both cases CONCUR_READ_ONLY as concurrency is
+ * used.
*
- * @return the scroll type, or -1 if not connected or no scrolling supported
- * @see ResultSet#TYPE_SCROLL_SENSITIVE
- * @see ResultSet#TYPE_SCROLL_INSENSITIVE
+ * @return the scroll type, or -1 if not connected or no scrolling supported
+ * @see ResultSet#TYPE_SCROLL_SENSITIVE
+ * @see ResultSet#TYPE_SCROLL_INSENSITIVE
*/
public int getSupportedCursorScrollType() {
- int result;
-
+ int result;
+
result = -1;
-
+
try {
if (isConnected()) {
- if (m_Connection.getMetaData().supportsResultSetConcurrency(
- ResultSet.TYPE_SCROLL_SENSITIVE,
- ResultSet.CONCUR_READ_ONLY))
- result = ResultSet.TYPE_SCROLL_SENSITIVE;
-
- if (result == -1) {
- if (m_Connection.getMetaData().supportsResultSetConcurrency(
- ResultSet.TYPE_SCROLL_INSENSITIVE,
- ResultSet.CONCUR_READ_ONLY))
- result = ResultSet.TYPE_SCROLL_INSENSITIVE;
- }
+ if (m_Connection.getMetaData().supportsResultSetConcurrency(
+ ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
+ result = ResultSet.TYPE_SCROLL_SENSITIVE;
+ }
+
+ if (result == -1) {
+ if (m_Connection.getMetaData().supportsResultSetConcurrency(
+ ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY)) {
+ result = ResultSet.TYPE_SCROLL_INSENSITIVE;
+ }
+ }
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
// ignored
}
-
+
return result;
}
/**
- * Executes a SQL query. Caller must clean up manually with
+ * Executes a SQL query. Caller must clean up manually with
* <code>close()</code>.
- *
- * @param query the SQL query
- * @return true if the query generated results
+ *
+ * @param query the SQL query
+ * @return true if the query generated results
* @throws SQLException if an error occurs
* @see #close()
*/
public boolean execute(String query) throws SQLException {
- if (!isConnected())
+ if (!isConnected()) {
throw new IllegalStateException("Not connected, please connect first!");
-
- if (!isCursorScrollable())
- m_PreparedStatement = m_Connection.prepareStatement(
- query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- else
- m_PreparedStatement = m_Connection.prepareStatement(
- query, getSupportedCursorScrollType(), ResultSet.CONCUR_READ_ONLY);
-
- return(m_PreparedStatement.execute());
+ }
+
+ if (!isCursorScrollable()) {
+ m_PreparedStatement = m_Connection.prepareStatement(query,
+ ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
+ } else {
+ m_PreparedStatement = m_Connection.prepareStatement(query,
+ getSupportedCursorScrollType(), ResultSet.CONCUR_READ_ONLY);
+ }
+
+ return (m_PreparedStatement.execute());
}
/**
- * Gets the results generated by a previous query. Caller must clean up
+ * Gets the results generated by a previous query. Caller must clean up
* manually with <code>close(ResultSet)</code>. Returns null if object has
* been deserialized.
- *
- * @return the result set.
+ *
+ * @return the result set.
* @throws SQLException if an error occurs
* @see #close(ResultSet)
*/
public ResultSet getResultSet() throws SQLException {
- if (m_PreparedStatement != null)
+ if (m_PreparedStatement != null) {
return m_PreparedStatement.getResultSet();
- else
+ } else {
return null;
+ }
}
/**
* Executes a SQL DDL query or an INSERT, DELETE or UPDATE.
- *
- * @param query the SQL DDL query
- * @return the number of affected rows
+ *
+ * @param query the SQL DDL query
+ * @return the number of affected rows
* @throws SQLException if an error occurs
*/
public int update(String query) throws SQLException {
- if (!isConnected())
+ if (!isConnected()) {
throw new IllegalStateException("Not connected, please connect first!");
-
+ }
+
Statement statement;
- if (!isCursorScrollable())
- statement = m_Connection.createStatement(
- ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- else
- statement = m_Connection.createStatement(
- getSupportedCursorScrollType(), ResultSet.CONCUR_READ_ONLY);
+ if (!isCursorScrollable()) {
+ statement = m_Connection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY);
+ } else {
+ statement = m_Connection.createStatement(getSupportedCursorScrollType(),
+ ResultSet.CONCUR_READ_ONLY);
+ }
int result = statement.executeUpdate(query);
statement.close();
-
+
return result;
}
/**
* Executes a SQL SELECT query that returns a ResultSet. Note: the ResultSet
* object must be closed by the caller.
- *
- * @param query the SQL query
- * @return the generated ResultSet
+ *
+ * @param query the SQL query
+ * @return the generated ResultSet
* @throws SQLException if an error occurs
*/
public ResultSet select(String query) throws SQLException {
- if (!isConnected())
+ if (!isConnected()) {
throw new IllegalStateException("Not connected, please connect first!");
-
+ }
+
Statement statement;
- if (!isCursorScrollable())
- statement = m_Connection.createStatement(
- ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- else
- statement = m_Connection.createStatement(
- getSupportedCursorScrollType(), ResultSet.CONCUR_READ_ONLY);
+ if (!isCursorScrollable()) {
+ statement = m_Connection.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY);
+ } else {
+ statement = m_Connection.createStatement(getSupportedCursorScrollType(),
+ ResultSet.CONCUR_READ_ONLY);
+ }
ResultSet result = statement.executeQuery(query);
-
+
return result;
}
@@ -718,7 +725,7 @@ public class DatabaseUtils
* avoid memory leaks in JDBC drivers - in contrast to the JDBC specs, a lot
* of JDBC drives don't clean up correctly.
*
- * @param rs the ResultSet to clean up
+ * @param rs the ResultSet to clean up
*/
public void close(ResultSet rs) {
try {
@@ -727,49 +734,48 @@ public class DatabaseUtils
statement.close();
statement = null;
rs = null;
- }
- catch (Exception e) {
+ } catch (Exception e) {
// ignored
}
}
-
+
/**
* closes the m_PreparedStatement to avoid memory leaks.
*/
public void close() {
if (m_PreparedStatement != null) {
try {
- m_PreparedStatement.close();
- m_PreparedStatement = null;
- }
- catch (Exception e) {
- // ignored
+ m_PreparedStatement.close();
+ m_PreparedStatement = null;
+ } catch (Exception e) {
+ // ignored
}
}
}
-
+
/**
* Checks that a given table exists.
- *
- * @param tableName the name of the table to look for.
- * @return true if the table exists.
- * @throws Exception if an error occurs.
+ *
+ * @param tableName the name of the table to look for.
+ * @return true if the table exists.
+ * @throws Exception if an error occurs.
*/
public boolean tableExists(String tableName) throws Exception {
- if (!isConnected())
+ if (!isConnected()) {
throw new IllegalStateException("Not connected, please connect first!");
-
+ }
+
if (m_Debug) {
System.err.println("Checking if table " + tableName + " exists...");
}
DatabaseMetaData dbmd = m_Connection.getMetaData();
ResultSet rs;
if (m_checkForUpperCaseNames) {
- rs = dbmd.getTables (null, null, tableName.toUpperCase(), null);
+ rs = dbmd.getTables(null, null, tableName.toUpperCase(), null);
} else if (m_checkForLowerCaseNames) {
- rs = dbmd.getTables (null, null, tableName.toLowerCase(), null);
+ rs = dbmd.getTables(null, null, tableName.toLowerCase(), null);
} else {
- rs = dbmd.getTables (null, null, tableName, null);
+ rs = dbmd.getTables(null, null, tableName, null);
}
boolean tableExists = rs.next();
if (rs.next()) {
@@ -778,64 +784,58 @@ public class DatabaseUtils
rs.close();
if (m_Debug) {
if (tableExists) {
- System.err.println("... " + tableName + " exists");
+ System.err.println("... " + tableName + " exists");
} else {
- System.err.println("... " + tableName + " does not exist");
+ System.err.println("... " + tableName + " does not exist");
}
}
return tableExists;
}
/**
- * processes the string in such a way that it can be stored in the
- * database, i.e., it changes backslashes into slashes and doubles single
- * quotes.
+ * processes the string in such a way that it can be stored in the database,
+ * i.e., it changes backslashes into slashes and doubles single quotes.
*
- * @param s the string to work on
- * @return the processed string
+ * @param s the string to work on
+ * @return the processed string
*/
public static String processKeyString(String s) {
return s.replaceAll("\\\\", "/").replaceAll("'", "''");
}
-
+
/**
- * Executes a database query to see whether a result for the supplied key
- * is already in the database.
- *
- * @param tableName the name of the table to search for the key in
- * @param rp the ResultProducer who will generate the result if
- * required
- * @param key the key for the result
- * @return true if the result with that key is in the database
- * already
- * @throws Exception if an error occurs
+ * Executes a database query to see whether a result for the supplied key is
+ * already in the database.
+ *
+ * @param tableName the name of the table to search for the key in
+ * @param rp the ResultProducer who will generate the result if required
+ * @param key the key for the result
+ * @return true if the result with that key is in the database already
+ * @throws Exception if an error occurs
*/
- protected boolean isKeyInTable(String tableName,
- ResultProducer rp,
- Object[] key)
- throws Exception {
+ protected boolean isKeyInTable(String tableName, ResultProducer rp,
+ Object[] key) throws Exception {
- String query = "SELECT Key_Run"
- + " FROM " + tableName;
- String [] keyNames = rp.getKeyNames();
+ String query = "SELECT Key_Run" + " FROM " + tableName;
+ String[] keyNames = rp.getKeyNames();
if (keyNames.length != key.length) {
throw new Exception("Key names and key values of different lengths");
}
boolean first = true;
for (int i = 0; i < key.length; i++) {
if (key[i] != null) {
- if (first) {
- query += " WHERE ";
- first = false;
- } else {
- query += " AND ";
- }
- query += "Key_" + keyNames[i] + '=';
- if (key[i] instanceof String) {
- query += "'" + processKeyString(key[i].toString()) + "'";
- } else {
- query += key[i].toString();
- }
+ if (first) {
+ query += " WHERE ";
+ first = false;
+ } else {
+ query += " AND ";
+ }
+ query += "Key_" + keyNames[i] + '=';
+ if (key[i] instanceof String) {
+ query += "'" + processKeyString(key[i].toString()) + "'";
+ } else {
+ query += key[i].toString();
+ }
}
}
boolean retval = false;
@@ -843,8 +843,8 @@ public class DatabaseUtils
if (rs.next()) {
retval = true;
if (rs.next()) {
- throw new Exception("More than one result entry "
- + "for result key: " + query);
+ throw new Exception("More than one result entry " + "for result key: "
+ + query);
}
}
close(rs);
@@ -852,50 +852,46 @@ public class DatabaseUtils
}
/**
- * Executes a database query to extract a result for the supplied key
- * from the database.
- *
- * @param tableName the name of the table where the result is stored
- * @param rp the ResultProducer who will generate the result if
- * required
- * @param key the key for the result
- * @return true if the result with that key is in the database
- * already
- * @throws Exception if an error occurs
+ * Executes a database query to extract a result for the supplied key from the
+ * database.
+ *
+ * @param tableName the name of the table where the result is stored
+ * @param rp the ResultProducer who will generate the result if required
+ * @param key the key for the result
+ * @return true if the result with that key is in the database already
+ * @throws Exception if an error occurs
*/
- public Object[] getResultFromTable(String tableName,
- ResultProducer rp,
- Object [] key)
- throws Exception {
+ public Object[] getResultFromTable(String tableName, ResultProducer rp,
+ Object[] key) throws Exception {
String query = "SELECT ";
- String [] resultNames = rp.getResultNames();
+ String[] resultNames = rp.getResultNames();
for (int i = 0; i < resultNames.length; i++) {
if (i != 0) {
- query += ", ";
+ query += ", ";
}
query += resultNames[i];
}
query += " FROM " + tableName;
- String [] keyNames = rp.getKeyNames();
+ String[] keyNames = rp.getKeyNames();
if (keyNames.length != key.length) {
throw new Exception("Key names and key values of different lengths");
}
boolean first = true;
for (int i = 0; i < key.length; i++) {
if (key[i] != null) {
- if (first) {
- query += " WHERE ";
- first = false;
- } else {
- query += " AND ";
- }
- query += "Key_" + keyNames[i] + '=';
- if (key[i] instanceof String) {
- query += "'" + processKeyString(key[i].toString()) + "'";
- } else {
- query += key[i].toString();
- }
+ if (first) {
+ query += " WHERE ";
+ first = false;
+ } else {
+ query += " AND ";
+ }
+ query += "Key_" + keyNames[i] + '=';
+ if (key[i] instanceof String) {
+ query += "'" + processKeyString(key[i].toString()) + "'";
+ } else {
+ query += key[i].toString();
+ }
}
}
ResultSet rs = select(query);
@@ -905,108 +901,103 @@ public class DatabaseUtils
throw new Exception("No result for query: " + query);
}
// Extract the columns for the result
- Object [] result = new Object [numAttributes];
- for(int i = 1; i <= numAttributes; i++) {
+ Object[] result = new Object[numAttributes];
+ for (int i = 1; i <= numAttributes; i++) {
switch (translateDBColumnType(md.getColumnTypeName(i))) {
- case STRING :
- result[i - 1] = rs.getString(i);
- if (rs.wasNull()) {
- result[i - 1] = null;
- }
- break;
- case FLOAT:
- case DOUBLE:
- result[i - 1] = new Double(rs.getDouble(i));
- if (rs.wasNull()) {
- result[i - 1] = null;
- }
- break;
- default:
- throw new Exception("Unhandled SQL result type (field " + (i + 1)
- + "): "
- + DatabaseUtils.typeName(md.getColumnType(i)));
+ case STRING:
+ result[i - 1] = rs.getString(i);
+ if (rs.wasNull()) {
+ result[i - 1] = null;
+ }
+ break;
+ case FLOAT:
+ case DOUBLE:
+ result[i - 1] = new Double(rs.getDouble(i));
+ if (rs.wasNull()) {
+ result[i - 1] = null;
+ }
+ break;
+ default:
+ throw new Exception("Unhandled SQL result type (field " + (i + 1)
+ + "): " + DatabaseUtils.typeName(md.getColumnType(i)));
}
}
if (rs.next()) {
- throw new Exception("More than one result entry "
- + "for result key: " + query);
+ throw new Exception("More than one result entry " + "for result key: "
+ + query);
}
close(rs);
return result;
}
/**
- * Executes a database query to insert a result for the supplied key
- * into the database.
- *
- * @param tableName the name of the table where the result is stored
- * @param rp the ResultProducer who will generate the result if
- * required
- * @param key the key for the result
- * @param result the result to store
- * @throws Exception if an error occurs
+ * Executes a database query to insert a result for the supplied key into the
+ * database.
+ *
+ * @param tableName the name of the table where the result is stored
+ * @param rp the ResultProducer who will generate the result if required
+ * @param key the key for the result
+ * @param result the result to store
+ * @throws Exception if an error occurs
*/
- public void putResultInTable(String tableName,
- ResultProducer rp,
- Object [] key,
- Object [] result)
- throws Exception {
-
- String query = "INSERT INTO " + tableName
- + " VALUES ( ";
+ public void putResultInTable(String tableName, ResultProducer rp,
+ Object[] key, Object[] result) throws Exception {
+
+ String query = "INSERT INTO " + tableName + " VALUES ( ";
// Add the results to the table
for (int i = 0; i < key.length; i++) {
if (i != 0) {
- query += ',';
+ query += ',';
}
if (key[i] != null) {
- if (key[i] instanceof String) {
- query += "'" + processKeyString(key[i].toString()) + "'";
- } else if (key[i] instanceof Double) {
- query += safeDoubleToString((Double)key[i]);
- } else {
- query += key[i].toString();
- }
+ if (key[i] instanceof String) {
+ query += "'" + processKeyString(key[i].toString()) + "'";
+ } else if (key[i] instanceof Double) {
+ query += safeDoubleToString((Double) key[i]);
+ } else {
+ query += key[i].toString();
+ }
} else {
- query += "NULL";
+ query += "NULL";
}
}
- for (int i = 0; i < result.length; i++) {
- query += ',';
- if (result[i] != null) {
- if (result[i] instanceof String) {
- query += "'" + result[i].toString() + "'";
- } else if (result[i] instanceof Double) {
- query += safeDoubleToString((Double)result[i]);
- } else {
- query += result[i].toString();
- //!!
- //System.err.println("res: "+ result[i].toString());
- }
+ for (Object element : result) {
+ query += ',';
+ if (element != null) {
+ if (element instanceof String) {
+ query += "'" + element.toString() + "'";
+ } else if (element instanceof Double) {
+ query += safeDoubleToString((Double) element);
+ } else {
+ query += element.toString();
+ // !!
+ // System.err.println("res: "+ result[i].toString());
+ }
} else {
- query += "NULL";
+ query += "NULL";
}
}
query += ')';
-
+
if (m_Debug) {
System.err.println("Submitting result: " + query);
}
update(query);
close();
}
-
+
/**
- * Inserts a + if the double is in scientific notation.
- * MySQL doesn't understand the number otherwise.
+ * Inserts a + if the double is in scientific notation. MySQL doesn't
+ * understand the number otherwise.
*
- * @param number the number to convert
- * @return the number as string
+ * @param number the number to convert
+ * @return the number as string
*/
private String safeDoubleToString(Double number) {
// NaN is treated as NULL
- if (number.isNaN())
+ if (number.isNaN()) {
return "NULL";
+ }
String orig = number.toString();
@@ -1022,18 +1013,18 @@ public class DatabaseUtils
/**
* Returns true if the experiment index exists.
- *
- * @return true if the index exists
- * @throws Exception if an error occurs
+ *
+ * @return true if the index exists
+ * @throws Exception if an error occurs
*/
public boolean experimentIndexExists() throws Exception {
return tableExists(EXP_INDEX_TABLE);
}
-
+
/**
* Attempts to create the experiment index table.
- *
- * @throws Exception if an error occurs.
+ *
+ * @throws Exception if an error occurs.
*/
public void createExperimentIndex() throws Exception {
if (m_Debug) {
@@ -1044,38 +1035,34 @@ public class DatabaseUtils
// Workaround for MySQL (doesn't support LONGVARBINARY)
// Also for InstantDB which attempts to interpret numbers when storing
// in LONGVARBINARY
- /* if (m_Connection.getMetaData().getDriverName().
- equals("Mark Matthews' MySQL Driver")
- || (m_Connection.getMetaData().getDriverName().
- indexOf("InstantDB JDBC Driver") != -1)) {
- query = "CREATE TABLE " + EXP_INDEX_TABLE
- + " ( " + EXP_TYPE_COL + " TEXT,"
- + " " + EXP_SETUP_COL + " TEXT,"
- + " " + EXP_RESULT_COL + " INT )";
- } else { */
-
- query = "CREATE TABLE " + EXP_INDEX_TABLE
- + " ( " + EXP_TYPE_COL + " "+ m_stringType+","
- + " " + EXP_SETUP_COL + " "+ m_stringType+","
- + " " + EXP_RESULT_COL + " "+ m_intType+" )";
- // }
+ /*
+ * if (m_Connection.getMetaData().getDriverName().
+ * equals("Mark Matthews' MySQL Driver") ||
+ * (m_Connection.getMetaData().getDriverName().
+ * indexOf("InstantDB JDBC Driver") != -1)) { query = "CREATE TABLE " +
+ * EXP_INDEX_TABLE + " ( " + EXP_TYPE_COL + " TEXT," + " " + EXP_SETUP_COL
+ * + " TEXT," + " " + EXP_RESULT_COL + " INT )"; } else {
+ */
+
+ query = "CREATE TABLE " + EXP_INDEX_TABLE + " ( " + EXP_TYPE_COL + " "
+ + m_stringType + "," + " " + EXP_SETUP_COL + " " + m_stringType + ","
+ + " " + EXP_RESULT_COL + " " + m_intType + " )";
+ // }
// Other possible fields:
- // creator user name (from System properties)
- // creation date
+ // creator user name (from System properties)
+ // creation date
update(query);
close();
}
/**
- * Attempts to insert a results entry for the table into the
- * experiment index.
- *
- * @param rp the ResultProducer generating the results
- * @return the name of the created results table
- * @throws Exception if an error occurs.
+ * Attempts to insert a results entry for the table into the experiment index.
+ *
+ * @param rp the ResultProducer generating the results
+ * @return the name of the created results table
+ * @throws Exception if an error occurs.
*/
- public String createExperimentIndexEntry(ResultProducer rp)
- throws Exception {
+ public String createExperimentIndexEntry(ResultProducer rp) throws Exception {
if (m_Debug) {
System.err.println("Creating experiment index entry...");
@@ -1083,15 +1070,16 @@ public class DatabaseUtils
// Execute compound transaction
int numRows = 0;
-
+
// Workaround for MySQL (doesn't support transactions)
- /* if (m_Connection.getMetaData().getDriverName().
- equals("Mark Matthews' MySQL Driver")) {
- m_Statement.execute("LOCK TABLES " + EXP_INDEX_TABLE + " WRITE");
- System.err.println("LOCKING TABLE");
- } else {*/
-
- //}
+ /*
+ * if (m_Connection.getMetaData().getDriverName().
+ * equals("Mark Matthews' MySQL Driver")) {
+ * m_Statement.execute("LOCK TABLES " + EXP_INDEX_TABLE + " WRITE");
+ * System.err.println("LOCKING TABLE"); } else {
+ */
+
+ // }
// Get the number of rows
String query = "SELECT COUNT(*) FROM " + EXP_INDEX_TABLE;
@@ -1107,29 +1095,28 @@ public class DatabaseUtils
// Add an entry in the index table
String expType = rp.getClass().getName();
String expParams = rp.getCompatibilityState();
- query = "INSERT INTO " + EXP_INDEX_TABLE
- +" VALUES ('"
- + expType + "', '" + expParams
- + "', " + numRows + " )";
+ query = "INSERT INTO " + EXP_INDEX_TABLE + " VALUES ('" + expType + "', '"
+ + expParams + "', " + numRows + " )";
if (update(query) > 0) {
if (m_Debug) {
- System.err.println("...create returned resultset");
+ System.err.println("...create returned resultset");
}
}
close();
-
+
// Finished compound transaction
// Workaround for MySQL (doesn't support transactions)
- /* if (m_Connection.getMetaData().getDriverName().
- equals("Mark Matthews' MySQL Driver")) {
- m_Statement.execute("UNLOCK TABLES");
- System.err.println("UNLOCKING TABLE");
- } else { */
+ /*
+ * if (m_Connection.getMetaData().getDriverName().
+ * equals("Mark Matthews' MySQL Driver")) {
+ * m_Statement.execute("UNLOCK TABLES");
+ * System.err.println("UNLOCKING TABLE"); } else {
+ */
if (!m_setAutoCommit) {
m_Connection.commit();
m_Connection.setAutoCommit(true);
}
- //}
+ // }
String tableName = getResultsTableName(rp);
if (tableName == null) {
@@ -1142,7 +1129,7 @@ public class DatabaseUtils
try {
query = "DROP TABLE " + tableName;
if (m_Debug) {
- System.err.println(query);
+ System.err.println(query);
}
update(query);
} catch (SQLException ex) {
@@ -1152,14 +1139,13 @@ public class DatabaseUtils
}
/**
- * Gets the name of the experiment table that stores results from a
- * particular ResultProducer.
- *
- * @param rp the ResultProducer
- * @return the name of the table where the results for this
- * ResultProducer are stored, or null if there is no
- * table for this ResultProducer.
- * @throws Exception if an error occurs
+ * Gets the name of the experiment table that stores results from a particular
+ * ResultProducer.
+ *
+ * @param rp the ResultProducer
+ * @return the name of the table where the results for this ResultProducer are
+ * stored, or null if there is no table for this ResultProducer.
+ * @throws Exception if an error occurs
*/
public String getResultsTableName(ResultProducer rp) throws Exception {
// Get the experiment table name, or create a new table if necessary.
@@ -1168,36 +1154,33 @@ public class DatabaseUtils
}
String expType = rp.getClass().getName();
String expParams = rp.getCompatibilityState();
- String query = "SELECT " + EXP_RESULT_COL
- + " FROM " + EXP_INDEX_TABLE
- + " WHERE " + EXP_TYPE_COL + "='" + expType
- + "' AND " + EXP_SETUP_COL + "='" + expParams + "'";
+ String query = "SELECT " + EXP_RESULT_COL + " FROM " + EXP_INDEX_TABLE
+ + " WHERE " + EXP_TYPE_COL + "='" + expType + "' AND " + EXP_SETUP_COL
+ + "='" + expParams + "'";
String tableName = null;
ResultSet rs = select(query);
if (rs.next()) {
tableName = rs.getString(1);
if (rs.next()) {
- throw new Exception("More than one index entry "
- + "for experiment config: " + query);
+ throw new Exception("More than one index entry "
+ + "for experiment config: " + query);
}
}
close(rs);
if (m_Debug) {
- System.err.println("...results table = " + ((tableName == null)
- ? "<null>"
- : EXP_RESULT_PREFIX
- + tableName));
+ System.err.println("...results table = "
+ + ((tableName == null) ? "<null>" : EXP_RESULT_PREFIX + tableName));
}
return (tableName == null) ? tableName : EXP_RESULT_PREFIX + tableName;
}
/**
* Creates a results table for the supplied result producer.
- *
- * @param rp the ResultProducer generating the results
- * @param tableName the name of the resultsTable
- * @return the name of the created results table
- * @throws Exception if an error occurs.
+ *
+ * @param rp the ResultProducer generating the results
+ * @param tableName the name of the resultsTable
+ * @return the name of the created results table
+ * @throws Exception if an error occurs.
*/
public String createResultsTable(ResultProducer rp, String tableName)
throws Exception {
@@ -1207,31 +1190,31 @@ public class DatabaseUtils
}
String query = "CREATE TABLE " + tableName + " ( ";
// Loop over the key fields
- String [] names = rp.getKeyNames();
- Object [] types = rp.getKeyTypes();
+ String[] names = rp.getKeyNames();
+ Object[] types = rp.getKeyTypes();
if (names.length != types.length) {
throw new Exception("key names types differ in length");
}
for (int i = 0; i < names.length; i++) {
query += "Key_" + names[i] + " ";
if (types[i] instanceof Double) {
- query += m_doubleType;
+ query += m_doubleType;
} else if (types[i] instanceof String) {
- // Workaround for MySQL (doesn't support LONGVARCHAR)
- // Also for InstantDB which attempts to interpret numbers when storing
- // in LONGVARBINARY
- /*if (m_Connection.getMetaData().getDriverName().
- equals("Mark Matthews' MySQL Driver")
- || (m_Connection.getMetaData().getDriverName().
- indexOf("InstantDB JDBC Driver")) != -1) {
- query += "TEXT ";
- } else { */
- //query += "LONGVARCHAR ";
- query += m_stringType+" ";
- //}
+ // Workaround for MySQL (doesn't support LONGVARCHAR)
+ // Also for InstantDB which attempts to interpret numbers when storing
+ // in LONGVARBINARY
+ /*
+ * if (m_Connection.getMetaData().getDriverName().
+ * equals("Mark Matthews' MySQL Driver") ||
+ * (m_Connection.getMetaData().getDriverName().
+ * indexOf("InstantDB JDBC Driver")) != -1) { query += "TEXT "; } else {
+ */
+ // query += "LONGVARCHAR ";
+ query += m_stringType + " ";
+ // }
} else {
- throw new Exception("Unknown/unsupported field type in key");
+ throw new Exception("Unknown/unsupported field type in key");
}
query += ", ";
}
@@ -1244,151 +1227,154 @@ public class DatabaseUtils
for (int i = 0; i < names.length; i++) {
query += names[i] + " ";
if (types[i] instanceof Double) {
- query += m_doubleType;
+ query += m_doubleType;
} else if (types[i] instanceof String) {
-
- // Workaround for MySQL (doesn't support LONGVARCHAR)
- // Also for InstantDB which attempts to interpret numbers when storing
- // in LONGVARBINARY
- /*if (m_Connection.getMetaData().getDriverName().
- equals("Mark Matthews' MySQL Driver")
- || (m_Connection.getMetaData().getDriverName().
- equals("InstantDB JDBC Driver"))) {
- query += "TEXT ";
- } else {*/
- //query += "LONGVARCHAR ";
- query += m_stringType+" ";
- //}
+
+ // Workaround for MySQL (doesn't support LONGVARCHAR)
+ // Also for InstantDB which attempts to interpret numbers when storing
+ // in LONGVARBINARY
+ /*
+ * if (m_Connection.getMetaData().getDriverName().
+ * equals("Mark Matthews' MySQL Driver") ||
+ * (m_Connection.getMetaData().getDriverName().
+ * equals("InstantDB JDBC Driver"))) { query += "TEXT "; } else {
+ */
+ // query += "LONGVARCHAR ";
+ query += m_stringType + " ";
+ // }
} else {
- throw new Exception("Unknown/unsupported field type in key");
+ throw new Exception("Unknown/unsupported field type in key");
}
if (i < names.length - 1) {
- query += ", ";
+ query += ", ";
}
}
query += " )";
-
+
update(query);
- if (m_Debug)
+ if (m_Debug) {
System.err.println("table created");
+ }
close();
-
if (m_createIndex) {
- query = "CREATE UNIQUE INDEX Key_IDX ON "+ tableName +" (";
+ query = "CREATE UNIQUE INDEX Key_IDX ON " + tableName + " (";
+
+ String[] keyNames = rp.getKeyNames();
- String [] keyNames = rp.getKeyNames();
-
boolean first = true;
- for (int i = 0; i < keyNames.length; i++) {
- if (keyNames[i] != null) {
- if (first) {
- first = false;
- query += "Key_" + keyNames[i];
- } else {
- query += ",Key_" + keyNames[i];
- }
- }
+ for (String keyName : keyNames) {
+ if (keyName != null) {
+ if (first) {
+ first = false;
+ query += "Key_" + keyName;
+ } else {
+ query += ",Key_" + keyName;
+ }
+ }
}
query += ")";
-
+
update(query);
}
return tableName;
}
-
+
/**
* Sets the keywords (comma-separated list) to use.
*
- * @param value the list of keywords
+ * @param value the list of keywords
*/
public void setKeywords(String value) {
- String[] keywords;
- int i;
-
+ String[] keywords;
+ int i;
+
m_Keywords.clear();
-
+
keywords = value.replaceAll(" ", "").split(",");
- for (i = 0; i < keywords.length; i++)
+ for (i = 0; i < keywords.length; i++) {
m_Keywords.add(keywords[i].toUpperCase());
+ }
}
-
+
/**
* Returns the currently stored keywords (as comma-separated list).
*
- * @return the list of keywords
+ * @return the list of keywords
*/
public String getKeywords() {
- String result;
- Vector<String> list;
- int i;
-
+ String result;
+ Vector<String> list;
+ int i;
+
list = new Vector<String>(m_Keywords);
Collections.sort(list);
-
+
result = "";
for (i = 0; i < list.size(); i++) {
- if (i > 0)
- result += ",";
+ if (i > 0) {
+ result += ",";
+ }
result += list.get(i);
}
-
+
return result;
}
-
+
/**
- * Sets the mask character to append to table or attribute names that
- * are a reserved keyword.
+ * Sets the mask character to append to table or attribute names that are a
+ * reserved keyword.
*
- * @param value the new character
+ * @param value the new character
*/
public void setKeywordsMaskChar(String value) {
m_KeywordsMaskChar = value;
}
-
+
/**
* Returns the currently set mask character.
*
- * @return the character
+ * @return the character
*/
public String getKeywordsMaskChar() {
return m_KeywordsMaskChar;
}
-
+
/**
* Checks whether the given string is a reserved keyword.
*
- * @param s the string to check
- * @return true if the string is a keyword
- * @see #m_Keywords
+ * @param s the string to check
+ * @return true if the string is a keyword
+ * @see #m_Keywords
*/
public boolean isKeyword(String s) {
return m_Keywords.contains(s.toUpperCase());
}
-
+
/**
- * If the given string is a keyword, then the mask character will be
- * appended and returned. Otherwise, the same string will be returned
- * unchanged.
+ * If the given string is a keyword, then the mask character will be appended
+ * and returned. Otherwise, the same string will be returned unchanged.
*
- * @param s the string to check
- * @return the potentially masked string
- * @see #m_KeywordsMaskChar
- * @see #isKeyword(String)
+ * @param s the string to check
+ * @return the potentially masked string
+ * @see #m_KeywordsMaskChar
+ * @see #isKeyword(String)
*/
public String maskKeyword(String s) {
- if (isKeyword(s))
+ if (isKeyword(s)) {
return s + m_KeywordsMaskChar;
- else
+ } else {
return s;
+ }
}
-
+
/**
* Returns the revision string.
*
- * @return the revision
+ * @return the revision
*/
+ @Override
public String getRevision() {
- return RevisionUtils.extract("$Revision: 5240 $");
+ return RevisionUtils.extract("$Revision: 10206 $");
}
}
diff --git a/src/main/java/weka/experiment/DatabaseUtils.props.postgresql b/src/main/java/weka/experiment/DatabaseUtils.props.postgresql
index 8fa8bc2..6f58585 100644
--- a/src/main/java/weka/experiment/DatabaseUtils.props.postgresql
+++ b/src/main/java/weka/experiment/DatabaseUtils.props.postgresql
@@ -6,7 +6,7 @@
# url: http://www.postgresql.org/
# jdbc: http://jdbc.postgresql.org/
# author: Fracpete (fracpete at waikato dot ac dot nz)
-# version: $Revision: 7849 $
+# version: $Revision: 10412 $
# JDBC driver (comma-separated list)
jdbcDriver=org.postgresql.Driver
@@ -27,6 +27,8 @@ jdbcURL=jdbc:postgresql://server_name:5432/database_name
# text, getString() = 9; --> string
# time, getTime() = 10; --> date
+# PostgreSQL data types to Java classes information can be found at:
+# http://www.postgresql.org/message-id/AANLkTinsk4rwT7v-751bwQkgTN1rkA=8uE-jk69nape-@mail.gmail.com
varchar=0
text=0
float4=7
@@ -36,6 +38,12 @@ oid=5
timestamp=8
date=8
+int2=5
+int8=2
+numeric=2
+bpchar=9
+
+
# other options
CREATE_DOUBLE=float8
CREATE_STRING=text
diff --git a/src/main/java/weka/experiment/RegressionSplitEvaluator.java b/src/main/java/weka/experiment/RegressionSplitEvaluator.java
index 2a0d341..a8ec04e 100644
--- a/src/main/java/weka/experiment/RegressionSplitEvaluator.java
+++ b/src/main/java/weka/experiment/RegressionSplitEvaluator.java
@@ -20,9 +20,17 @@
*
*/
-
package weka.experiment;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamClass;
+import java.io.Serializable;
+import java.lang.management.ManagementFactory;
+import java.lang.management.ThreadMXBean;
+import java.util.Enumeration;
+import java.util.Vector;
+
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.rules.ZeroR;
@@ -37,45 +45,39 @@ import weka.core.RevisionUtils;
import weka.core.Summarizable;
import weka.core.Utils;
-import java.io.ByteArrayOutputStream;
-import java.io.ObjectOutputStream;
-import java.io.ObjectStreamClass;
-import java.io.Serializable;
-import java.lang.management.ManagementFactory;
-import java.lang.management.ThreadMXBean;
-import java.util.Enumeration;
-import java.util.Vector;
-
/**
- <!-- globalinfo-start -->
- * A SplitEvaluator that produces results for a classification scheme on a numeric class attribute.
+ * <!-- globalinfo-start --> A SplitEvaluator that produces results for a
+ * classification scheme on a numeric class attribute.
+ * <p/>
+ * <!-- globalinfo-end -->
+ *
+ * <!-- options-start --> Valid options are:
* <p/>
- <!-- globalinfo-end -->
- *
- <!-- options-start -->
- * Valid options are: <p/>
*
- * <pre> -W <class name>
+ * <pre>
+ * -W <class name>
* The full class name of the classifier.
- * eg: weka.classifiers.bayes.NaiveBayes</pre>
+ * eg: weka.classifiers.bayes.NaiveBayes
+ * </pre>
*
- * <pre>
+ * <pre>
* Options specific to classifier weka.classifiers.rules.ZeroR:
* </pre>
*
- * <pre> -D
+ * <pre>
+ * -D
* If set, classifier is run in debug mode and
- * may output additional info to the console</pre>
+ * may output additional info to the console
+ * </pre>
*
- <!-- options-end -->
+ * <!-- options-end -->
*
* @author Len Trigg (trigg at cs.waikato.ac.nz)
- * @version $Revision: 7510 $
+ * @version $Revision: 10475 $
*/
-public class RegressionSplitEvaluator
- implements SplitEvaluator, OptionHandler, AdditionalMeasureProducer,
- RevisionHandler {
-
+public class RegressionSplitEvaluator implements SplitEvaluator, OptionHandler,
+ AdditionalMeasureProducer, RevisionHandler {
+
/** for serialization */
static final long serialVersionUID = -328181640503349202L;
@@ -84,14 +86,16 @@ public class RegressionSplitEvaluator
/** The classifier used for evaluation */
protected Classifier m_Classifier;
-
+
/** The names of any additional measures to look for in SplitEvaluators */
- protected String [] m_AdditionalMeasures = null;
+ protected String[] m_AdditionalMeasures = null;
- /** Array of booleans corresponding to the measures in m_AdditionalMeasures
- indicating which of the AdditionalMeasures the current classifier
- can produce */
- protected boolean [] m_doesProduce = null;
+ /**
+ * Array of booleans corresponding to the measures in m_AdditionalMeasures
+ * indicating which of the AdditionalMeasures the current classifier can
+ * produce
+ */
+ protected boolean[] m_doesProduce = null;
/** Holds the statistics for the most recent application of the classifier */
protected String m_result = null;
@@ -106,7 +110,7 @@ public class RegressionSplitEvaluator
private static final int KEY_SIZE = 3;
/** The length of a result */
- private static final int RESULT_SIZE = 21;
+ private static final int RESULT_SIZE = 23;
/**
* No args constructor.
@@ -118,100 +122,104 @@ public class RegressionSplitEvaluator
/**
* Returns a string describing this split evaluator
- * @return a description of the split evaluator suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return a description of the split evaluator suitable for displaying in the
+ * explorer/experimenter gui
*/
public String globalInfo() {
return "A SplitEvaluator that produces results for a classification "
- +"scheme on a numeric class attribute.";
+ + "scheme on a numeric class attribute.";
}
/**
* Returns an enumeration describing the available options..
- *
+ *
* @return an enumeration of all the available options.
*/
+ @Override
public Enumeration listOptions() {
Vector newVector = new Vector(1);
- newVector.addElement(new Option(
- "\tThe full class name of the classifier.\n"
- +"\teg: weka.classifiers.bayes.NaiveBayes",
- "W", 1,
- "-W <class name>"));
-
- if ((m_Template != null) &&
- (m_Template instanceof OptionHandler)) {
- newVector.addElement(new Option(
- "",
- "", 0, "\nOptions specific to classifier "
- + m_Template.getClass().getName() + ":"));
- Enumeration enu = ((OptionHandler)m_Template).listOptions();
+ newVector
+ .addElement(new Option("\tThe full class name of the classifier.\n"
+ + "\teg: weka.classifiers.bayes.NaiveBayes", "W", 1, "-W <class name>"));
+
+ if ((m_Template != null) && (m_Template instanceof OptionHandler)) {
+ newVector.addElement(new Option("", "", 0,
+ "\nOptions specific to classifier " + m_Template.getClass().getName()
+ + ":"));
+ Enumeration enu = ((OptionHandler) m_Template).listOptions();
while (enu.hasMoreElements()) {
- newVector.addElement(enu.nextElement());
+ newVector.addElement(enu.nextElement());
}
}
return newVector.elements();
}
/**
- * Parses a given list of options. <p/>
- *
- <!-- options-start -->
- * Valid options are: <p/>
+ * Parses a given list of options.
+ * <p/>
*
- * <pre> -W <class name>
+ * <!-- options-start --> Valid options are:
+ * <p/>
+ *
+ * <pre>
+ * -W <class name>
* The full class name of the classifier.
- * eg: weka.classifiers.bayes.NaiveBayes</pre>
+ * eg: weka.classifiers.bayes.NaiveBayes
+ * </pre>
*
- * <pre>
+ * <pre>
* Options specific to classifier weka.classifiers.rules.ZeroR:
* </pre>
*
- * <pre> -D
+ * <pre>
+ * -D
* If set, classifier is run in debug mode and
- * may output additional info to the console</pre>
+ * may output additional info to the console
+ * </pre>
+ *
+ * <!-- options-end -->
*
- <!-- options-end -->
- *
* All option after -- will be passed to the classifier.
- *
+ *
* @param options the list of options as an array of strings
* @throws Exception if an option is not supported
*/
+ @Override
public void setOptions(String[] options) throws Exception {
-
+
String cName = Utils.getOption('W', options);
if (cName.length() == 0) {
throw new Exception("A classifier must be specified with"
- + " the -W option.");
+ + " the -W option.");
}
// Do it first without options, so if an exception is thrown during
// the option setting, listOptions will contain options for the actual
// Classifier.
setClassifier(Classifier.forName(cName, null));
if (getClassifier() instanceof OptionHandler) {
- ((OptionHandler) getClassifier())
- .setOptions(Utils.partitionOptions(options));
+ ((OptionHandler) getClassifier()).setOptions(Utils
+ .partitionOptions(options));
updateOptions();
}
}
/**
* Gets the current settings of the Classifier.
- *
+ *
* @return an array of strings suitable for passing to setOptions
*/
- public String [] getOptions() {
+ @Override
+ public String[] getOptions() {
- String [] classifierOptions = new String [0];
- if ((m_Template != null) &&
- (m_Template instanceof OptionHandler)) {
- classifierOptions = ((OptionHandler)m_Template).getOptions();
+ String[] classifierOptions = new String[0];
+ if ((m_Template != null) && (m_Template instanceof OptionHandler)) {
+ classifierOptions = ((OptionHandler) m_Template).getOptions();
}
-
- String [] options = new String [classifierOptions.length + 3];
+
+ String[] options = new String[classifierOptions.length + 3];
int current = 0;
if (getClassifier() != null) {
@@ -220,8 +228,8 @@ public class RegressionSplitEvaluator
}
options[current++] = "--";
- System.arraycopy(classifierOptions, 0, options, current,
- classifierOptions.length);
+ System.arraycopy(classifierOptions, 0, options, current,
+ classifierOptions.length);
current += classifierOptions.length;
while (current < options.length) {
options[current++] = "";
@@ -230,90 +238,95 @@ public class RegressionSplitEvaluator
}
/**
- * Set a list of method names for additional measures to look for
- * in Classifiers. This could contain many measures (of which only a
- * subset may be produceable by the current Classifier) if an experiment
- * is the type that iterates over a set of properties.
+ * Set a list of method names for additional measures to look for in
+ * Classifiers. This could contain many measures (of which only a subset may
+ * be produceable by the current Classifier) if an experiment is the type that
+ * iterates over a set of properties.
+ *
* @param additionalMeasures an array of method names.
*/
- public void setAdditionalMeasures(String [] additionalMeasures) {
+ @Override
+ public void setAdditionalMeasures(String[] additionalMeasures) {
m_AdditionalMeasures = additionalMeasures;
// determine which (if any) of the additional measures this classifier
// can produce
if (m_AdditionalMeasures != null && m_AdditionalMeasures.length > 0) {
- m_doesProduce = new boolean [m_AdditionalMeasures.length];
+ m_doesProduce = new boolean[m_AdditionalMeasures.length];
if (m_Template instanceof AdditionalMeasureProducer) {
- Enumeration en = ((AdditionalMeasureProducer)m_Template).
- enumerateMeasures();
- while (en.hasMoreElements()) {
- String mname = (String)en.nextElement();
- for (int j=0;j<m_AdditionalMeasures.length;j++) {
- if (mname.compareToIgnoreCase(m_AdditionalMeasures[j]) == 0) {
- m_doesProduce[j] = true;
- }
- }
- }
+ Enumeration en = ((AdditionalMeasureProducer) m_Template)
+ .enumerateMeasures();
+ while (en.hasMoreElements()) {
+ String mname = (String) en.nextElement();
+ for (int j = 0; j < m_AdditionalMeasures.length; j++) {
+ if (mname.compareToIgnoreCase(m_AdditionalMeasures[j]) == 0) {
+ m_doesProduce[j] = true;
+ }
+ }
+ }
}
} else {
m_doesProduce = null;
}
}
-
- /**
- * Returns an enumeration of any additional measure names that might be
- * in the classifier
+ /**
+ * Returns an enumeration of any additional measure names that might be in the
+ * classifier
+ *
* @return an enumeration of the measure names
*/
+ @Override
public Enumeration enumerateMeasures() {
Vector newVector = new Vector();
if (m_Template instanceof AdditionalMeasureProducer) {
- Enumeration en = ((AdditionalMeasureProducer)m_Template).
- enumerateMeasures();
+ Enumeration en = ((AdditionalMeasureProducer) m_Template)
+ .enumerateMeasures();
while (en.hasMoreElements()) {
- String mname = (String)en.nextElement();
- newVector.addElement(mname);
+ String mname = (String) en.nextElement();
+ newVector.addElement(mname);
}
}
return newVector.elements();
}
-
+
/**
* Returns the value of the named measure
+ *
* @param additionalMeasureName the name of the measure to query for its value
* @return the value of the named measure
* @throws IllegalArgumentException if the named measure is not supported
*/
+ @Override
public double getMeasure(String additionalMeasureName) {
if (m_Template instanceof AdditionalMeasureProducer) {
if (m_Classifier == null) {
- throw new IllegalArgumentException("ClassifierSplitEvaluator: " +
- "Can't return result for measure, " +
- "classifier has not been built yet.");
+ throw new IllegalArgumentException("ClassifierSplitEvaluator: "
+ + "Can't return result for measure, "
+ + "classifier has not been built yet.");
}
- return ((AdditionalMeasureProducer)m_Classifier).
- getMeasure(additionalMeasureName);
+ return ((AdditionalMeasureProducer) m_Classifier)
+ .getMeasure(additionalMeasureName);
} else {
throw new IllegalArgumentException("ClassifierSplitEvaluator: "
- +"Can't return value for : "+additionalMeasureName
- +". "+m_Template.getClass().getName()+" "
- +"is not an AdditionalMeasureProducer");
+ + "Can't return value for : " + additionalMeasureName + ". "
+ + m_Template.getClass().getName() + " "
+ + "is not an AdditionalMeasureProducer");
}
}
/**
* Gets the data types of each of the key columns produced for a single run.
- * The number of key fields must be constant
- * for a given SplitEvaluator.
- *
- * @return an array containing objects of the type of each key column. The
- * objects should be Strings, or Doubles.
+ * The number of key fields must be constant for a given SplitEvaluator.
+ *
+ * @return an array containing objects of the type of each key column. The
+ * objects should be Strings, or Doubles.
*/
- public Object [] getKeyTypes() {
+ @Override
+ public Object[] getKeyTypes() {
- Object [] keyTypes = new Object[KEY_SIZE];
+ Object[] keyTypes = new Object[KEY_SIZE];
keyTypes[0] = "";
keyTypes[1] = "";
keyTypes[2] = "";
@@ -321,15 +334,15 @@ public class RegressionSplitEvaluator
}
/**
- * Gets the names of each of the key columns produced for a single run.
- * The number of key fields must be constant
- * for a given SplitEvaluator.
- *
+ * Gets the names of each of the key columns produced for a single run. The
+ * number of key fields must be constant for a given SplitEvaluator.
+ *
* @return an array containing the name of each key column
*/
- public String [] getKeyNames() {
+ @Override
+ public String[] getKeyNames() {
- String [] keyNames = new String[KEY_SIZE];
+ String[] keyNames = new String[KEY_SIZE];
keyNames[0] = "Scheme";
keyNames[1] = "Scheme_options";
keyNames[2] = "Scheme_version_ID";
@@ -337,16 +350,17 @@ public class RegressionSplitEvaluator
}
/**
- * Gets the key describing the current SplitEvaluator. For example
- * This may contain the name of the classifier used for classifier
- * predictive evaluation. The number of key fields must be constant
- * for a given SplitEvaluator.
- *
+ * Gets the key describing the current SplitEvaluator. For example This may
+ * contain the name of the classifier used for classifier predictive
+ * evaluation. The number of key fields must be constant for a given
+ * SplitEvaluator.
+ *
* @return an array of objects containing the key.
*/
- public Object [] getKey(){
+ @Override
+ public Object[] getKey() {
- Object [] key = new Object[KEY_SIZE];
+ Object[] key = new Object[KEY_SIZE];
key[0] = m_Template.getClass().getName();
key[1] = m_ClassifierOptions;
key[2] = m_ClassifierVersion;
@@ -354,18 +368,17 @@ public class RegressionSplitEvaluator
}
/**
- * Gets the data types of each of the result columns produced for a
- * single run. The number of result fields must be constant
- * for a given SplitEvaluator.
- *
- * @return an array containing objects of the type of each result column.
- * The objects should be Strings, or Doubles.
+ * Gets the data types of each of the result columns produced for a single
+ * run. The number of result fields must be constant for a given
+ * SplitEvaluator.
+ *
+ * @return an array containing objects of the type of each result column. The
+ * objects should be Strings, or Doubles.
*/
- public Object [] getResultTypes() {
- int addm = (m_AdditionalMeasures != null)
- ? m_AdditionalMeasures.length
- : 0;
- Object [] resultTypes = new Object[RESULT_SIZE+addm];
+ @Override
+ public Object[] getResultTypes() {
+ int addm = (m_AdditionalMeasures != null) ? m_AdditionalMeasures.length : 0;
+ Object[] resultTypes = new Object[RESULT_SIZE + addm];
Double doub = new Double(0);
int current = 0;
resultTypes[current++] = doub;
@@ -376,6 +389,8 @@ public class RegressionSplitEvaluator
resultTypes[current++] = doub;
resultTypes[current++] = doub;
resultTypes[current++] = doub;
+ resultTypes[current++] = doub;
+ resultTypes[current++] = doub;
resultTypes[current++] = doub;
resultTypes[current++] = doub;
@@ -389,7 +404,7 @@ public class RegressionSplitEvaluator
resultTypes[current++] = doub;
resultTypes[current++] = doub;
resultTypes[current++] = doub;
-
+
// sizes
resultTypes[current++] = doub;
resultTypes[current++] = doub;
@@ -398,27 +413,25 @@ public class RegressionSplitEvaluator
resultTypes[current++] = "";
// add any additional measures
- for (int i=0;i<addm;i++) {
+ for (int i = 0; i < addm; i++) {
resultTypes[current++] = doub;
}
- if (current != RESULT_SIZE+addm) {
+ if (current != RESULT_SIZE + addm) {
throw new Error("ResultTypes didn't fit RESULT_SIZE");
}
return resultTypes;
}
/**
- * Gets the names of each of the result columns produced for a single run.
- * The number of result fields must be constant
- * for a given SplitEvaluator.
- *
+ * Gets the names of each of the result columns produced for a single run. The
+ * number of result fields must be constant for a given SplitEvaluator.
+ *
* @return an array containing the name of each result column
*/
- public String [] getResultNames() {
- int addm = (m_AdditionalMeasures != null)
- ? m_AdditionalMeasures.length
- : 0;
- String [] resultNames = new String[RESULT_SIZE+addm];
+ @Override
+ public String[] getResultNames() {
+ int addm = (m_AdditionalMeasures != null) ? m_AdditionalMeasures.length : 0;
+ String[] resultNames = new String[RESULT_SIZE + addm];
int current = 0;
resultNames[current++] = "Number_of_training_instances";
resultNames[current++] = "Number_of_testing_instances";
@@ -429,6 +442,8 @@ public class RegressionSplitEvaluator
resultNames[current++] = "Relative_absolute_error";
resultNames[current++] = "Root_relative_squared_error";
resultNames[current++] = "Correlation_coefficient";
+ resultNames[current++] = "Number_unclassified";
+ resultNames[current++] = "Percent_unclassified";
// SF stats
resultNames[current++] = "SF_prior_entropy";
@@ -448,32 +463,32 @@ public class RegressionSplitEvaluator
resultNames[current++] = "Serialized_Model_Size";
resultNames[current++] = "Serialized_Train_Set_Size";
resultNames[current++] = "Serialized_Test_Set_Size";
-
+
// Classifier defined extras
resultNames[current++] = "Summary";
// add any additional measures
- for (int i=0;i<addm;i++) {
+ for (int i = 0; i < addm; i++) {
resultNames[current++] = m_AdditionalMeasures[i];
}
- if (current != RESULT_SIZE+addm) {
+ if (current != RESULT_SIZE + addm) {
throw new Error("ResultNames didn't fit RESULT_SIZE");
}
return resultNames;
}
/**
- * Gets the results for the supplied train and test datasets. Now performs
- * a deep copy of the classifier before it is built and evaluated (just in case
+ * Gets the results for the supplied train and test datasets. Now performs a
+ * deep copy of the classifier before it is built and evaluated (just in case
* the classifier is not initialized properly in buildClassifier()).
- *
+ *
* @param train the training Instances.
* @param test the testing Instances.
- * @return the results stored in an array. The objects stored in
- * the array may be Strings, Doubles, or null (for the missing value).
+ * @return the results stored in an array. The objects stored in the array may
+ * be Strings, Doubles, or null (for the missing value).
* @throws Exception if a problem occurs while getting the results
*/
- public Object [] getResult(Instances train, Instances test)
- throws Exception {
+ @Override
+ public Object[] getResult(Instances train, Instances test) throws Exception {
if (train.classAttribute().type() != Attribute.NUMERIC) {
throw new Exception("Class attribute is not numeric!");
@@ -483,33 +498,37 @@ public class RegressionSplitEvaluator
}
ThreadMXBean thMonitor = ManagementFactory.getThreadMXBean();
boolean canMeasureCPUTime = thMonitor.isThreadCpuTimeSupported();
- if(canMeasureCPUTime && !thMonitor.isThreadCpuTimeEnabled())
+ if (canMeasureCPUTime && !thMonitor.isThreadCpuTimeEnabled()) {
thMonitor.setThreadCpuTimeEnabled(true);
-
+ }
+
int addm = (m_AdditionalMeasures != null) ? m_AdditionalMeasures.length : 0;
- Object [] result = new Object[RESULT_SIZE+addm];
+ Object[] result = new Object[RESULT_SIZE + addm];
long thID = Thread.currentThread().getId();
- long CPUStartTime=-1, trainCPUTimeElapsed=-1, testCPUTimeElapsed=-1,
- trainTimeStart, trainTimeElapsed, testTimeStart, testTimeElapsed;
+ long CPUStartTime = -1, trainCPUTimeElapsed = -1, testCPUTimeElapsed = -1, trainTimeStart, trainTimeElapsed, testTimeStart, testTimeElapsed;
Evaluation eval = new Evaluation(train);
m_Classifier = Classifier.makeCopy(m_Template);
trainTimeStart = System.currentTimeMillis();
- if(canMeasureCPUTime)
+ if (canMeasureCPUTime) {
CPUStartTime = thMonitor.getThreadUserTime(thID);
+ }
m_Classifier.buildClassifier(train);
- if(canMeasureCPUTime)
+ if (canMeasureCPUTime) {
trainCPUTimeElapsed = thMonitor.getThreadUserTime(thID) - CPUStartTime;
+ }
trainTimeElapsed = System.currentTimeMillis() - trainTimeStart;
testTimeStart = System.currentTimeMillis();
- if(canMeasureCPUTime)
+ if (canMeasureCPUTime) {
CPUStartTime = thMonitor.getThreadUserTime(thID);
+ }
eval.evaluateModel(m_Classifier, test);
- if(canMeasureCPUTime)
+ if (canMeasureCPUTime) {
testCPUTimeElapsed = thMonitor.getThreadUserTime(thID) - CPUStartTime;
+ }
testTimeElapsed = System.currentTimeMillis() - testTimeStart;
thMonitor = null;
-
+
m_result = eval.toSummaryString();
// The results stored are all per instance -- can be multiplied by the
// number of instances to get absolute numbers
@@ -522,6 +541,8 @@ public class RegressionSplitEvaluator
result[current++] = new Double(eval.relativeAbsoluteError());
result[current++] = new Double(eval.rootRelativeSquaredError());
result[current++] = new Double(eval.correlationCoefficient());
+ result[current++] = new Double(eval.unclassified());
+ result[current++] = new Double(eval.pctUnclassified());
result[current++] = new Double(eval.SFPriorEntropy());
result[current++] = new Double(eval.SFSchemeEntropy());
@@ -529,19 +550,18 @@ public class RegressionSplitEvaluator
result[current++] = new Double(eval.SFMeanPriorEntropy());
result[current++] = new Double(eval.SFMeanSchemeEntropy());
result[current++] = new Double(eval.SFMeanEntropyGain());
-
+
// Timing stats
result[current++] = new Double(trainTimeElapsed / 1000.0);
result[current++] = new Double(testTimeElapsed / 1000.0);
- if(canMeasureCPUTime) {
- result[current++] = new Double((trainCPUTimeElapsed/1000000.0) / 1000.0);
- result[current++] = new Double((testCPUTimeElapsed /1000000.0) / 1000.0);
- }
- else {
+ if (canMeasureCPUTime) {
+ result[current++] = new Double((trainCPUTimeElapsed / 1000000.0) / 1000.0);
+ result[current++] = new Double((testCPUTimeElapsed / 1000000.0) / 1000.0);
+ } else {
result[current++] = new Double(Instance.missingValue());
result[current++] = new Double(Instance.missingValue());
}
-
+
// sizes
ByteArrayOutputStream bastream = new ByteArrayOutputStream();
ObjectOutputStream oostream = new ObjectOutputStream(bastream);
@@ -555,18 +575,18 @@ public class RegressionSplitEvaluator
oostream = new ObjectOutputStream(bastream);
oostream.writeObject(test);
result[current++] = new Double(bastream.size());
-
+
if (m_Classifier instanceof Summarizable) {
- result[current++] = ((Summarizable)m_Classifier).toSummaryString();
+ result[current++] = ((Summarizable) m_Classifier).toSummaryString();
} else {
result[current++] = null;
}
-
- for (int i=0;i<addm;i++) {
+
+ for (int i = 0; i < addm; i++) {
if (m_doesProduce[i]) {
try {
- double dv = ((AdditionalMeasureProducer)m_Classifier).
- getMeasure(m_AdditionalMeasures[i]);
+ double dv = ((AdditionalMeasureProducer) m_Classifier)
+ .getMeasure(m_AdditionalMeasures[i]);
if (!Instance.isMissingValue(dv)) {
Double value = new Double(dv);
result[current++] = value;
@@ -580,8 +600,8 @@ public class RegressionSplitEvaluator
result[current++] = null;
}
}
-
- if (current != RESULT_SIZE+addm) {
+
+ if (current != RESULT_SIZE + addm) {
throw new Error("Results didn't fit RESULT_SIZE");
}
return result;
@@ -589,8 +609,9 @@ public class RegressionSplitEvaluator
/**
* Returns the tip text for this property
- * @return tip text for this property suitable for
- * displaying in the explorer/experimenter gui
+ *
+ * @return tip text for this property suitable for displaying in the
+ * explorer/experimenter gui
*/
public String classifierTipText() {
return "The classifier to use.";
@@ -598,21 +619,21 @@ public class RegressionSplitEvaluator
/**
* Get the value of Classifier.
- *
+ *
* @return Value of Classifier.
*/
public Classifier getClassifier() {
-
+
return m_Template;
}
-
+
/**
* Sets the classifier.
- *
+ *
* @param newClassifier the new classifier to use.
*/
public void setClassifier(Classifier newClassifier) {
-
+
m_Template = newClassifier;
updateOptions();
@@ -623,16 +644,15 @@ public class RegressionSplitEvaluator
* Updates the options that the current classifier is using.
*/
protected void updateOptions() {
-
+
if (m_Template instanceof OptionHandler) {
- m_ClassifierOptions = Utils.joinOptions(((OptionHandler)m_Template)
- .getOptions());
+ m_ClassifierOptions = Utils.joinOptions(((OptionHandler) m_Template)
+ .getOptions());
} else {
m_ClassifierOptions = "";
}
if (m_Template instanceof Serializable) {
- ObjectStreamClass obs = ObjectStreamClass.lookup(m_Template
- .getClass());
+ ObjectStreamClass obs = ObjectStreamClass.lookup(m_Template.getClass());
m_ClassifierVersion = "" + obs.getSerialVersionUID();
} else {
m_ClassifierVersion = "";
@@ -642,25 +662,26 @@ public class RegressionSplitEvaluator
/**
* Set the Classifier to use, given it's class name. A new classifier will be
* instantiated.
- *
+ *
* @param newClassifierName the Classifier class name.
* @throws Exception if the class name is invalid.
*/
public void setClassifierName(String newClassifierName) throws Exception {
try {
- setClassifier((Classifier)Class.forName(newClassifierName)
- .newInstance());
+ setClassifier((Classifier) Class.forName(newClassifierName).newInstance());
} catch (Exception ex) {
throw new Exception("Can't find Classifier with class name: "
- + newClassifierName);
+ + newClassifierName);
}
}
/**
* Gets the raw output from the classifier
+ *
* @return the raw output from the classifier
*/
+ @Override
public String getRawResultOutput() {
StringBuffer result = new StringBuffer();
@@ -668,29 +689,29 @@ public class RegressionSplitEvaluator
return "<null> classifier";
}
result.append(toString());
- result.append("Classifier model: \n"+m_Classifier.toString()+'\n');
+ result.append("Classifier model: \n" + m_Classifier.toString() + '\n');
// append the performance statistics
if (m_result != null) {
result.append(m_result);
-
+
if (m_doesProduce != null) {
- for (int i=0;i<m_doesProduce.length;i++) {
- if (m_doesProduce[i]) {
- try {
- double dv = ((AdditionalMeasureProducer)m_Classifier).
- getMeasure(m_AdditionalMeasures[i]);
- if (!Instance.isMissingValue(dv)) {
- Double value = new Double(dv);
- result.append(m_AdditionalMeasures[i]+" : "+value+'\n');
- } else {
- result.append(m_AdditionalMeasures[i]+" : "+'?'+'\n');
- }
- } catch (Exception ex) {
- System.err.println(ex);
- }
- }
- }
+ for (int i = 0; i < m_doesProduce.length; i++) {
+ if (m_doesProduce[i]) {
+ try {
+ double dv = ((AdditionalMeasureProducer) m_Classifier)
+ .getMeasure(m_AdditionalMeasures[i]);
+ if (!Instance.isMissingValue(dv)) {
+ Double value = new Double(dv);
+ result.append(m_AdditionalMeasures[i] + " : " + value + '\n');
+ } else {
+ result.append(m_AdditionalMeasures[i] + " : " + '?' + '\n');
+ }
+ } catch (Exception ex) {
+ System.err.println(ex);
+ }
+ }
+ }
}
}
return result.toString();
@@ -698,25 +719,27 @@ public class RegressionSplitEvaluator
/**
* Returns a text description of the split evaluator.
- *
+ *
* @return a text description of the split evaluator.
*/
+ @Override
public String toString() {
String result = "RegressionSplitEvaluator: ";
if (m_Template == null) {
return result + "<null> classifier";
}
- return result + m_Template.getClass().getName() + " "
- + m_ClassifierOptions + "(version " + m_ClassifierVersion + ")";
+ return result + m_Template.getClass().getName() + " " + m_ClassifierOptions
+ + "(version " + m_ClassifierVersion + ")";
}
-
+
/**
* Returns the revision string.
*
- * @return the revision
+ * @return the revision
*/
+ @Override
public String getRevision() {
- return RevisionUtils.extract("$Revision: 7510 $");
+ return RevisionUtils.extract("$Revision: 10475 $");
}
} // RegressionSplitEvaluator
diff --git a/src/main/java/weka/filters/unsupervised/attribute/AddCluster.java b/src/main/java/weka/filters/unsupervised/attribute/AddCluster.java
index 6a28a2f..269287d 100644
--- a/src/main/java/weka/filters/unsupervised/attribute/AddCluster.java
+++ b/src/main/java/weka/filters/unsupervised/attribute/AddCluster.java
@@ -106,6 +106,7 @@ public class AddCluster
*/
public Capabilities getCapabilities() {
Capabilities result = m_Clusterer.getCapabilities();
+ result.enableAllClasses();
result.setMinimumNumberInstances(0);
diff --git a/src/main/java/weka/filters/unsupervised/attribute/RandomProjection.java b/src/main/java/weka/filters/unsupervised/attribute/RandomProjection.java
index 9fc2fa6..a3a254b 100644
--- a/src/main/java/weka/filters/unsupervised/attribute/RandomProjection.java
+++ b/src/main/java/weka/filters/unsupervised/attribute/RandomProjection.java
@@ -103,7 +103,7 @@ import java.util.Vector;
<!-- options-end -->
*
* @author Ashraf M. Kibriya (amk14 at cs.waikato.ac.nz)
- * @version $Revision: 6750 $ [1.0 - 22 July 2003 - Initial version (Ashraf M. Kibriya)]
+ * @version $Revision: 10029 $ [1.0 - 22 July 2003 - Initial version (Ashraf M. Kibriya)]
*/
public class RandomProjection
extends Filter
@@ -765,7 +765,7 @@ public class RandomProjection
}
if(currentFormat.classIndex()!=-1) { //if classindex is set
//attributes.removeElementAt(attributes.size()-1);
- attributes.addElement(currentFormat.attribute(currentFormat.classIndex()));
+ attributes.addElement(currentFormat.attribute(currentFormat.classIndex()).copy());
newClassIndex = attributes.size()-1;
}
@@ -891,7 +891,7 @@ public class RandomProjection
* @return the revision
*/
public String getRevision() {
- return RevisionUtils.extract("$Revision: 6750 $");
+ return RevisionUtils.extract("$Revision: 10029 $");
}
/**
diff --git a/src/main/java/weka/gui/GUIChooser.java b/src/main/java/weka/gui/GUIChooser.java
index 4c24acb..0f32814 100644
--- a/src/main/java/weka/gui/GUIChooser.java
+++ b/src/main/java/weka/gui/GUIChooser.java
@@ -47,7 +47,6 @@ import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
-import java.util.Locale;
import java.util.Vector;
import javax.swing.BorderFactory;
@@ -91,34 +90,34 @@ import weka.gui.visualize.PlotData2D;
import weka.gui.visualize.ThresholdVisualizePanel;
import weka.gui.visualize.VisualizePanel;
-/**
- * The main class for the Weka GUIChooser. Lets the user choose
- * which GUI they want to run.
- *
+/**
+ * The main class for the Weka GUIChooser. Lets the user choose which GUI they
+ * want to run.
+ *
* @author Len Trigg (trigg at cs.waikato.ac.nz)
* @author Mark Hall (mhall at cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9490 $
+ * @version $Revision: 10793 $
*/
-public class GUIChooser
- extends JFrame {
-
+public class GUIChooser extends JFrame {
+
static {
try {
Object MacApp = Class.forName("com.apple.eawt.Application").newInstance();
-
- Object macArffHandler = Class.forName("weka.gui.MacArffOpenFilesHandler").newInstance();
-
+
+ Object macArffHandler =
+ Class.forName("weka.gui.MacArffOpenFilesHandler").newInstance();
+
Class fileHandlerClass = Class.forName("com.apple.eawt.OpenFilesHandler");
Class[] paramClass = new Class[1];
paramClass[0] = fileHandlerClass;
Object[] args = new Object[1];
args[0] = macArffHandler;
-
+
Method m = MacApp.getClass().getMethod("setOpenFileHandler", paramClass);
System.out.println("Trying to install a file handler for Mac...");
m.invoke(MacApp, macArffHandler);
-
+
} catch (Exception ex) {
// quietly ignore...
}
@@ -129,34 +128,37 @@ public class GUIChooser
/** the GUIChooser itself */
protected GUIChooser m_Self;
-
+
// Menu stuff
private JMenuBar m_jMenuBar;
private JMenu m_jMenuProgram;
private JMenu m_jMenuVisualization;
private JMenu m_jMenuTools;
private JMenu m_jMenuHelp;
-
+
// Applications
/** the panel for the application buttons */
protected JPanel m_PanelApplications = new JPanel();
-
+
/** Click to open the Explorer */
- protected JButton m_ExplorerBut = new JButton(Messages.getInstance().getString("GUIChooser_Explorer_Text"));
+ protected JButton m_ExplorerBut = new JButton(Messages.getInstance()
+ .getString("GUIChooser_Explorer_Text"));
/** The frame containing the explorer interface */
protected JFrame m_ExplorerFrame;
/** Click to open the Explorer */
- protected JButton m_ExperimenterBut = new JButton(Messages.getInstance().getString("GUIChooser_Experimenter_Text"));
+ protected JButton m_ExperimenterBut = new JButton(Messages.getInstance()
+ .getString("GUIChooser_Experimenter_Text"));
/** The frame containing the experiment interface */
protected JFrame m_ExperimenterFrame;
/** Click to open the KnowledgeFlow */
- protected JButton m_KnowledgeFlowBut = new JButton(Messages.getInstance().getString("GUIChooser_KnowledgeFlow_Text"));
-
+ protected JButton m_KnowledgeFlowBut = new JButton(Messages.getInstance()
+ .getString("GUIChooser_KnowledgeFlow_Text"));
+
/** Pending file to load on startup of the KnowledgeFlow */
protected String m_pendingKnowledgeFlowLoad = null;
@@ -164,8 +166,9 @@ public class GUIChooser
protected JFrame m_KnowledgeFlowFrame;
/** Click to open the simplecli */
- protected JButton m_SimpleBut = new JButton(Messages.getInstance().getString("GUIChooser_Simple_CLI_Text"));
-
+ protected JButton m_SimpleBut = new JButton(Messages.getInstance().getString(
+ "GUIChooser_Simple_CLI_Text"));
+
/** The SimpleCLI */
protected SimpleCLI m_SimpleCLI;
@@ -174,10 +177,10 @@ public class GUIChooser
/** The frame containing the SqlViewer */
protected JFrame m_SqlViewerFrame;
-
+
/** The frame containing the Bayes net GUI */
protected JFrame m_BayesNetGUIFrame;
-
+
/** The frame containing the ensemble library interface */
protected JFrame m_EnsembleLibraryFrame;
@@ -197,12 +200,12 @@ public class GUIChooser
/** The frame containing the boundary visualizer */
protected JFrame m_BoundaryVisualizerFrame;
-
+
// Help
/** The frame containing the system info */
protected JFrame m_SystemInfoFrame;
-
+
// Other
/** The frame containing the memory usage */
@@ -212,29 +215,34 @@ public class GUIChooser
protected static LogWindow m_LogWindow = new LogWindow();
/** The weka image */
- Image m_weka = Toolkit.getDefaultToolkit().
- getImage(GUIChooser.class.getClassLoader().getResource("weka/gui/images/weka_background.gif"));
+ Image m_weka = Toolkit.getDefaultToolkit().getImage(
+ GUIChooser.class.getClassLoader().getResource(
+ "weka/gui/images/weka_background.gif"));
/** filechooser for the TreeVisualizer */
- protected JFileChooser m_FileChooserTreeVisualizer = new JFileChooser(new File(System.getProperty("user.dir")));
+ protected JFileChooser m_FileChooserTreeVisualizer = new JFileChooser(
+ new File(System.getProperty("user.dir")));
/** filechooser for the GraphVisualizer */
- protected JFileChooser m_FileChooserGraphVisualizer = new JFileChooser(new File(System.getProperty("user.dir")));
+ protected JFileChooser m_FileChooserGraphVisualizer = new JFileChooser(
+ new File(System.getProperty("user.dir")));
/** filechooser for Plots */
- protected JFileChooser m_FileChooserPlot = new JFileChooser(new File(System.getProperty("user.dir")));
+ protected JFileChooser m_FileChooserPlot = new JFileChooser(new File(
+ System.getProperty("user.dir")));
/** filechooser for ROC curves */
- protected JFileChooser m_FileChooserROC = new JFileChooser(new File(System.getProperty("user.dir")));
-
+ protected JFileChooser m_FileChooserROC = new JFileChooser(new File(
+ System.getProperty("user.dir")));
+
/** the icon for the frames */
protected Image m_Icon;
-
+
/** contains the child frames (title <-> object). */
protected HashSet<Container> m_ChildFrames = new HashSet<Container>();
-
+
/**
- * Create a singleton instance of the GUIChooser
+ * Create a singleton instance of the GUIChooser
*/
public static synchronized void createSingleton() {
if (m_chooser == null) {
@@ -244,111 +252,132 @@ public class GUIChooser
/**
* Get the singleton instance of the GUIChooser
- *
+ *
* @return the singleton instance of the GUIChooser
*/
public static GUIChooser getSingleton() {
return m_chooser;
}
-
+
/**
* Creates the experiment environment gui with no initial experiment
*/
public GUIChooser() {
super(Messages.getInstance().getString("GUIChooser_Title_Text"));
-
+
m_Self = this;
// filechoosers
- m_FileChooserGraphVisualizer.addChoosableFileFilter(
- new ExtensionFileFilter(".bif", Messages.getInstance().getString("GUIChooser_BIF_Files_Text")));
- m_FileChooserGraphVisualizer.addChoosableFileFilter(
- new ExtensionFileFilter(".xml", Messages.getInstance().getString("GUIChooser_XML_Files_Text")));
-
- m_FileChooserPlot.addChoosableFileFilter(
- new ExtensionFileFilter(
- Instances.FILE_EXTENSION,
- Messages.getInstance().getString("GUIChooser_ARFF_Files_Text_Front") + Instances.FILE_EXTENSION + Messages.getInstance().getString("GUIChooser_ARFF_Files_Text_End")));
+ m_FileChooserGraphVisualizer
+ .addChoosableFileFilter(new ExtensionFileFilter(".bif", Messages
+ .getInstance().getString("GUIChooser_BIF_Files_Text")));
+ m_FileChooserGraphVisualizer
+ .addChoosableFileFilter(new ExtensionFileFilter(".xml", Messages
+ .getInstance().getString("GUIChooser_XML_Files_Text")));
+
+ m_FileChooserPlot.addChoosableFileFilter(new ExtensionFileFilter(
+ Instances.FILE_EXTENSION, Messages.getInstance().getString(
+ "GUIChooser_ARFF_Files_Text_Front")
+ + Instances.FILE_EXTENSION
+ + Messages.getInstance().getString("GUIChooser_ARFF_Files_Text_End")));
m_FileChooserPlot.setMultiSelectionEnabled(true);
-
- m_FileChooserROC.addChoosableFileFilter(
- new ExtensionFileFilter(
- Instances.FILE_EXTENSION,
- Messages.getInstance().getString("GUIChooser_ARFF_Files_Text_Front") + Instances.FILE_EXTENSION + Messages.getInstance().getString("GUIChooser_ARFF_Files_Text_End")));
+
+ m_FileChooserROC.addChoosableFileFilter(new ExtensionFileFilter(
+ Instances.FILE_EXTENSION, Messages.getInstance().getString(
+ "GUIChooser_ARFF_Files_Text_Front")
+ + Instances.FILE_EXTENSION
+ + Messages.getInstance().getString("GUIChooser_ARFF_Files_Text_End")));
// general layout
- m_Icon = Toolkit.getDefaultToolkit().getImage(
- GUIChooser.class.getClassLoader().getResource("weka/gui/weka_icon_new_48.png"));
+ m_Icon =
+ Toolkit.getDefaultToolkit().getImage(
+ GUIChooser.class.getClassLoader().getResource(
+ "weka/gui/weka_icon_new_48.png"));
setIconImage(m_Icon);
this.getContentPane().setLayout(new BorderLayout());
-
+
this.getContentPane().add(m_PanelApplications, BorderLayout.EAST);
// applications
- m_PanelApplications.setBorder(BorderFactory.createTitledBorder(Messages.getInstance().getString("GUIChooser_Applications_Text")));
+ m_PanelApplications.setBorder(BorderFactory.createTitledBorder(Messages
+ .getInstance().getString("GUIChooser_Applications_Text")));
m_PanelApplications.setLayout(new GridLayout(4, 1));
m_PanelApplications.add(m_ExplorerBut);
m_PanelApplications.add(m_ExperimenterBut);
m_PanelApplications.add(m_KnowledgeFlowBut);
m_PanelApplications.add(m_SimpleBut);
-
+
// Weka image plus copyright info
JPanel wekaPan = new JPanel();
wekaPan.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
wekaPan.setLayout(new BorderLayout());
- wekaPan.setToolTipText(Messages.getInstance().getString("GUIChooser_Weka_Native_Bird_Text"));
+ wekaPan.setToolTipText(Messages.getInstance().getString(
+ "GUIChooser_Weka_Native_Bird_Text"));
ImageIcon wii = new ImageIcon(m_weka);
JLabel wekaLab = new JLabel(wii);
wekaPan.add(wekaLab, BorderLayout.CENTER);
- String infoString = Messages.getInstance().getString("GUIChooser_Information_Text_Front") + " " + Version.VERSION + "<br>"
- + "(c) " + Copyright.getFromYear() + " - " + Copyright.getToYear() + "<br>" + Copyright.getOwner() + "<br>"
- + Copyright.getAddress() + Messages.getInstance().getString("GUIChooser_Information_Text_End");
+ String infoString =
+ Messages.getInstance().getString("GUIChooser_Information_Text_Front")
+ + " " + Version.VERSION + "<br>" + "(c) " + Copyright.getFromYear()
+ + " - " + Copyright.getToYear() + "<br>" + Copyright.getOwner()
+ + "<br>" + Copyright.getAddress()
+ + Messages.getInstance().getString("GUIChooser_Information_Text_End");
JLabel infoLab = new JLabel(infoString);
infoLab.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
wekaPan.add(infoLab, BorderLayout.SOUTH);
-
+
this.getContentPane().add(wekaPan, BorderLayout.CENTER);
// Menu bar
m_jMenuBar = new JMenuBar();
-
+
// Program
m_jMenuProgram = new JMenu();
m_jMenuBar.add(m_jMenuProgram);
- m_jMenuProgram.setText(Messages.getInstance().getString("GUIChooser_Program_Text"));
+ m_jMenuProgram.setText(Messages.getInstance().getString(
+ "GUIChooser_Program_Text"));
m_jMenuProgram.setMnemonic('P');
-
+
// Program/LogWindow
JMenuItem jMenuItemProgramLogWindow = new JMenuItem();
m_jMenuProgram.add(jMenuItemProgramLogWindow);
- jMenuItemProgramLogWindow.setText(Messages.getInstance().getString("GUIChooser_LogWindow_Text"));
- //jMenuItemProgramLogWindow.setMnemonic('L');
- jMenuItemProgramLogWindow.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, KeyEvent.CTRL_MASK));
+ jMenuItemProgramLogWindow.setText(Messages.getInstance().getString(
+ "GUIChooser_LogWindow_Text"));
+ // jMenuItemProgramLogWindow.setMnemonic('L');
+ jMenuItemProgramLogWindow.setAccelerator(KeyStroke.getKeyStroke(
+ KeyEvent.VK_L, KeyEvent.CTRL_MASK));
m_LogWindow.setIconImage(m_Icon);
jMenuItemProgramLogWindow.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
m_LogWindow.setVisible(true);
}
});
-
+
final JMenuItem jMenuItemProgramMemUsage = new JMenuItem();
m_jMenuProgram.add(jMenuItemProgramMemUsage);
- jMenuItemProgramMemUsage.setText(Messages.getInstance().getString("GUIChooser_Memory_Usage_Text"));
- //jMenuItemProgramMemUsage.setMnemonic('M');
- jMenuItemProgramMemUsage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_M, KeyEvent.CTRL_MASK));
-
+ jMenuItemProgramMemUsage.setText(Messages.getInstance().getString(
+ "GUIChooser_Memory_Usage_Text"));
+ // jMenuItemProgramMemUsage.setMnemonic('M');
+ jMenuItemProgramMemUsage.setAccelerator(KeyStroke.getKeyStroke(
+ KeyEvent.VK_M, KeyEvent.CTRL_MASK));
+
jMenuItemProgramMemUsage.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
if (m_MemoryUsageFrame == null) {
- final MemoryUsagePanel panel = new MemoryUsagePanel();
+ final MemoryUsagePanel panel = new MemoryUsagePanel();
jMenuItemProgramMemUsage.setEnabled(false);
- m_MemoryUsageFrame = new JFrame(Messages.getInstance().getString("GUIChooser_Memory_Usage_List_Text"));
+ m_MemoryUsageFrame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_Memory_Usage_List_Text"));
m_MemoryUsageFrame.setIconImage(m_Icon);
m_MemoryUsageFrame.getContentPane().setLayout(new BorderLayout());
m_MemoryUsageFrame.getContentPane().add(panel, BorderLayout.CENTER);
m_MemoryUsageFrame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent w) {
panel.stopMonitoring();
m_MemoryUsageFrame.dispose();
@@ -360,51 +389,59 @@ public class GUIChooser
m_MemoryUsageFrame.pack();
m_MemoryUsageFrame.setSize(400, 50);
Point l = panel.getFrameLocation();
- if ((l.x != -1) && (l.y != -1))
+ if ((l.x != -1) && (l.y != -1)) {
m_MemoryUsageFrame.setLocation(l);
+ }
m_MemoryUsageFrame.setVisible(true);
Dimension size = m_MemoryUsageFrame.getPreferredSize();
- m_MemoryUsageFrame.setSize(new Dimension((int) size.getWidth(), (int) size.getHeight()));
+ m_MemoryUsageFrame.setSize(new Dimension((int) size.getWidth(),
+ (int) size.getHeight()));
}
}
});
-
+
m_jMenuProgram.add(new JSeparator());
-
+
// Program/Exit
JMenuItem jMenuItemProgramExit = new JMenuItem();
m_jMenuProgram.add(jMenuItemProgramExit);
- jMenuItemProgramExit.setText(Messages.getInstance().getString("GUIChooser_Exit_Text"));
-// jMenuItemProgramExit.setMnemonic('E');
- jMenuItemProgramExit.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E, KeyEvent.CTRL_MASK));
+ jMenuItemProgramExit.setText(Messages.getInstance().getString(
+ "GUIChooser_Exit_Text"));
+ // jMenuItemProgramExit.setMnemonic('E');
+ jMenuItemProgramExit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,
+ KeyEvent.CTRL_MASK));
jMenuItemProgramExit.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
dispose();
checkExit();
}
});
-
+
// Visualization
m_jMenuVisualization = new JMenu();
m_jMenuBar.add(m_jMenuVisualization);
- m_jMenuVisualization.setText(Messages.getString("GUIChooser_Visualization_Text")); // "Visualization"
+ m_jMenuVisualization.setText(Messages
+ .getString("GUIChooser_Visualization_Text")); // "Visualization"
m_jMenuVisualization.setMnemonic('V');
-
+
// Visualization/Plot
JMenuItem jMenuItemVisualizationPlot = new JMenuItem();
m_jMenuVisualization.add(jMenuItemVisualizationPlot);
- jMenuItemVisualizationPlot.setText(Messages.getInstance().getString("GUIChooser_Plot_Text"));
- //jMenuItemVisualizationPlot.setMnemonic('P');
- jMenuItemVisualizationPlot.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_MASK));
-
+ jMenuItemVisualizationPlot.setText(Messages.getInstance().getString(
+ "GUIChooser_Plot_Text"));
+ // jMenuItemVisualizationPlot.setMnemonic('P');
+ jMenuItemVisualizationPlot.setAccelerator(KeyStroke.getKeyStroke(
+ KeyEvent.VK_P, KeyEvent.CTRL_MASK));
+
jMenuItemVisualizationPlot.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
// choose file
int retVal = m_FileChooserPlot.showOpenDialog(m_Self);
- if (retVal != JFileChooser.APPROVE_OPTION)
+ if (retVal != JFileChooser.APPROVE_OPTION) {
return;
+ }
// build plot
VisualizePanel panel = new VisualizePanel();
@@ -412,41 +449,56 @@ public class GUIChooser
File[] files = m_FileChooserPlot.getSelectedFiles();
for (int j = 0; j < files.length; j++) {
String filename = files[j].getAbsolutePath();
- if (j > 0)
+ if (j > 0) {
filenames += ", ";
+ }
filenames += filename;
- System.err.println(Messages.getInstance().getString("GUIChooser_LoadingInstancesFrom_Error_Text") + filename);
-
+ System.err.println(Messages.getInstance().getString(
+ "GUIChooser_LoadingInstancesFrom_Error_Text")
+ + filename);
+
try {
Reader r = new java.io.BufferedReader(new FileReader(filename));
Instances i = new Instances(r);
- i.setClassIndex(i.numAttributes()-1);
+ i.setClassIndex(i.numAttributes() - 1);
PlotData2D pd1 = new PlotData2D(i);
if (j == 0) {
- pd1.setPlotName(Messages.getInstance().getString("GUIChooser_MasterPlot_Text"));
+ pd1.setPlotName(Messages.getInstance().getString(
+ "GUIChooser_MasterPlot_Text"));
panel.setMasterPlot(pd1);
} else {
- pd1.setPlotName(Messages.getInstance().getString("GUIChooser_Plot_Text") + (j+1));
+ pd1.setPlotName(Messages.getInstance().getString(
+ "GUIChooser_Plot_Text")
+ + (j + 1));
pd1.m_useCustomColour = true;
- pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue;
+ pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue;
panel.addPlot(pd1);
}
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("GUIChooser_Plot_LoadingFile_Error_Text_Front") + files[j] + Messages.getInstance().getString("GUIChooser_Plot_LoadingFile_Error_Text_End") + ex.getMessage());
+ m_Self,
+ Messages.getInstance().getString(
+ "GUIChooser_Plot_LoadingFile_Error_Text_Front")
+ + files[j]
+ + Messages.getInstance().getString(
+ "GUIChooser_Plot_LoadingFile_Error_Text_End")
+ + ex.getMessage());
return;
}
}
// create frame
- final JFrame frame = new JFrame(Messages.getInstance().getString("GUIChooser_Plot_PlotName_Text") + filenames);
+ final JFrame frame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_Plot_PlotName_Text")
+ + filenames);
frame.setIconImage(m_Icon);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent e) {
m_Plots.remove(frame);
frame.dispose();
@@ -459,57 +511,73 @@ public class GUIChooser
m_Plots.add(frame);
}
});
-
+
// Visualization/ROC
JMenuItem jMenuItemVisualizationROC = new JMenuItem();
m_jMenuVisualization.add(jMenuItemVisualizationROC);
- jMenuItemVisualizationROC.setText(Messages.getInstance().getString("GUIChooser_ROC_Text"));
+ jMenuItemVisualizationROC.setText(Messages.getInstance().getString(
+ "GUIChooser_ROC_Text"));
// jMenuItemVisualizationROC.setMnemonic('R');
- jMenuItemVisualizationROC.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, KeyEvent.CTRL_MASK));
-
+ jMenuItemVisualizationROC.setAccelerator(KeyStroke.getKeyStroke(
+ KeyEvent.VK_R, KeyEvent.CTRL_MASK));
+
jMenuItemVisualizationROC.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
// choose file
int retVal = m_FileChooserROC.showOpenDialog(m_Self);
- if (retVal != JFileChooser.APPROVE_OPTION)
+ if (retVal != JFileChooser.APPROVE_OPTION) {
return;
+ }
// create plot
- String filename = m_FileChooserROC.getSelectedFile().getAbsolutePath();
+ String filename = m_FileChooserROC.getSelectedFile().getAbsolutePath();
Instances result = null;
try {
result = new Instances(new BufferedReader(new FileReader(filename)));
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("GUIChooser_ROC_LoadingFile_Error_Text_Front") + filename + Messages.getInstance().getString("GUIChooser_ROC_LoadingFile_Error_Text_End") + ex.getMessage());
+ m_Self,
+ Messages.getInstance().getString(
+ "GUIChooser_ROC_LoadingFile_Error_Text_Front")
+ + filename
+ + Messages.getInstance().getString(
+ "GUIChooser_ROC_LoadingFile_Error_Text_End") + ex.getMessage());
return;
}
result.setClassIndex(result.numAttributes() - 1);
ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
- vmc.setROCString(Messages.getInstance().getString("GUIChooser_ROC_AreaUnderROC_Text_Front") +
- Utils.doubleToString(ThresholdCurve.getROCArea(result), 4) + Messages.getInstance().getString("GUIChooser_ROC_AreaUnderROC_Text_End"));
+ vmc.setROCString(Messages.getInstance().getString(
+ "GUIChooser_ROC_AreaUnderROC_Text_Front")
+ + Utils.doubleToString(ThresholdCurve.getROCArea(result), 4)
+ + Messages.getInstance().getString(
+ "GUIChooser_ROC_AreaUnderROC_Text_End"));
vmc.setName(result.relationName());
PlotData2D tempd = new PlotData2D(result);
tempd.setPlotName(result.relationName());
tempd.addInstanceNumberAttribute();
try {
vmc.addPlot(tempd);
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("GUIChooser_ROC_AddingPlot_Error_Text") + ex.getMessage());
+ m_Self,
+ Messages.getInstance().getString(
+ "GUIChooser_ROC_AddingPlot_Error_Text")
+ + ex.getMessage());
return;
}
- final JFrame frame = new JFrame(Messages.getInstance().getString("GUIChooser_ROC_File_Text") + filename);
+ final JFrame frame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_ROC_File_Text")
+ + filename);
frame.setIconImage(m_Icon);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(vmc, BorderLayout.CENTER);
frame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent e) {
m_ROCs.remove(frame);
frame.dispose();
@@ -522,43 +590,57 @@ public class GUIChooser
m_ROCs.add(frame);
}
});
-
+
// Visualization/TreeVisualizer
JMenuItem jMenuItemVisualizationTree = new JMenuItem();
m_jMenuVisualization.add(jMenuItemVisualizationTree);
- jMenuItemVisualizationTree.setText(Messages.getInstance().getString("GUIChooser_TreeVisualizer_Text"));
+ jMenuItemVisualizationTree.setText(Messages.getInstance().getString(
+ "GUIChooser_TreeVisualizer_Text"));
// jMenuItemVisualizationTree.setMnemonic('T');
- jMenuItemVisualizationTree.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, KeyEvent.CTRL_MASK));
-
+ jMenuItemVisualizationTree.setAccelerator(KeyStroke.getKeyStroke(
+ KeyEvent.VK_T, KeyEvent.CTRL_MASK));
+
jMenuItemVisualizationTree.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
// choose file
int retVal = m_FileChooserTreeVisualizer.showOpenDialog(m_Self);
- if (retVal != JFileChooser.APPROVE_OPTION)
+ if (retVal != JFileChooser.APPROVE_OPTION) {
return;
+ }
// build tree
- String filename = m_FileChooserTreeVisualizer.getSelectedFile().getAbsolutePath();
+ String filename =
+ m_FileChooserTreeVisualizer.getSelectedFile().getAbsolutePath();
TreeBuild builder = new TreeBuild();
Node top = null;
NodePlace arrange = new PlaceNode2();
try {
top = builder.create(new FileReader(filename));
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("GUIChooser_TreeVisualizer_LoadingFile_Error_Text_Front") + filename + Messages.getInstance().getString("GUIChooser_TreeVisualizer_LoadingFile_Error_Text_End") + ex.getMessage());
+ m_Self,
+ Messages.getInstance().getString(
+ "GUIChooser_TreeVisualizer_LoadingFile_Error_Text_Front")
+ + filename
+ + Messages.getInstance().getString(
+ "GUIChooser_TreeVisualizer_LoadingFile_Error_Text_End")
+ + ex.getMessage());
return;
}
// create frame
- final JFrame frame = new JFrame(Messages.getInstance().getString("GUIChooser_TreeVisualizer_File_Text") + filename);
+ final JFrame frame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_TreeVisualizer_File_Text")
+ + filename);
frame.setIconImage(m_Icon);
frame.getContentPane().setLayout(new BorderLayout());
- frame.getContentPane().add(new TreeVisualizer(null, top, arrange), BorderLayout.CENTER);
+ frame.getContentPane().add(new TreeVisualizer(null, top, arrange),
+ BorderLayout.CENTER);
frame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent e) {
m_TreeVisualizers.remove(frame);
frame.dispose();
@@ -571,47 +653,59 @@ public class GUIChooser
m_TreeVisualizers.add(frame);
}
});
-
+
// Visualization/GraphVisualizer
JMenuItem jMenuItemVisualizationGraph = new JMenuItem();
m_jMenuVisualization.add(jMenuItemVisualizationGraph);
- jMenuItemVisualizationGraph.setText(Messages.getInstance().getString("GUIChooser_GraphVisualizer_Text"));
- // jMenuItemVisualizationGraph.setMnemonic('G');
- jMenuItemVisualizationGraph.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, KeyEvent.CTRL_MASK));
-
+ jMenuItemVisualizationGraph.setText(Messages.getInstance().getString(
+ "GUIChooser_GraphVisualizer_Text"));
+ // jMenuItemVisualizationGraph.setMnemonic('G');
+ jMenuItemVisualizationGraph.setAccelerator(KeyStroke.getKeyStroke(
+ KeyEvent.VK_G, KeyEvent.CTRL_MASK));
+
jMenuItemVisualizationGraph.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
// choose file
int retVal = m_FileChooserGraphVisualizer.showOpenDialog(m_Self);
- if (retVal != JFileChooser.APPROVE_OPTION)
+ if (retVal != JFileChooser.APPROVE_OPTION) {
return;
+ }
// build graph
- String filename = m_FileChooserGraphVisualizer.getSelectedFile().getAbsolutePath();
+ String filename =
+ m_FileChooserGraphVisualizer.getSelectedFile().getAbsolutePath();
GraphVisualizer panel = new GraphVisualizer();
- try{
- if ( filename.toLowerCase().endsWith(".xml")
- || filename.toLowerCase().endsWith(".bif") ) {
+ try {
+ if (filename.toLowerCase().endsWith(".xml")
+ || filename.toLowerCase().endsWith(".bif")) {
panel.readBIF(new FileInputStream(filename));
- }
- else {
+ } else {
panel.readDOT(new FileReader(filename));
}
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("GUIChooser_GraphVisualizer_LoadingFile_Error_Text_Front") + filename + Messages.getInstance().getString("GUIChooser_GraphVisualizer_LoadingFile_Error_Text_End") + ex.getMessage());
+ m_Self,
+ Messages.getInstance().getString(
+ "GUIChooser_GraphVisualizer_LoadingFile_Error_Text_Front")
+ + filename
+ + Messages.getInstance().getString(
+ "GUIChooser_GraphVisualizer_LoadingFile_Error_Text_End")
+ + ex.getMessage());
return;
}
// create frame
- final JFrame frame = new JFrame(Messages.getInstance().getString("GUIChooser_GraphVisualizer_File_Text") + filename);
+ final JFrame frame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_GraphVisualizer_File_Text")
+ + filename);
frame.setIconImage(m_Icon);
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(panel, BorderLayout.CENTER);
frame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent e) {
m_GraphVisualizers.remove(frame);
frame.dispose();
@@ -624,27 +718,34 @@ public class GUIChooser
m_GraphVisualizers.add(frame);
}
});
-
+
// Visualization/BoundaryVisualizer
final JMenuItem jMenuItemVisualizationBoundary = new JMenuItem();
m_jMenuVisualization.add(jMenuItemVisualizationBoundary);
- jMenuItemVisualizationBoundary.setText(Messages.getInstance().getString("GUIChooser_BoundaryVisualizer_Text"));
+ jMenuItemVisualizationBoundary.setText(Messages.getInstance().getString(
+ "GUIChooser_BoundaryVisualizer_Text"));
// jMenuItemVisualizationBoundary.setMnemonic('B');
- jMenuItemVisualizationBoundary.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_B, KeyEvent.CTRL_MASK));
-
+ jMenuItemVisualizationBoundary.setAccelerator(KeyStroke.getKeyStroke(
+ KeyEvent.VK_B, KeyEvent.CTRL_MASK));
+
jMenuItemVisualizationBoundary.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
if (m_BoundaryVisualizerFrame == null) {
jMenuItemVisualizationBoundary.setEnabled(false);
- m_BoundaryVisualizerFrame = new JFrame(Messages.getInstance().getString("GUIChooser_BoundaryVisualizer_JFrame_Text"));
+ m_BoundaryVisualizerFrame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_BoundaryVisualizer_JFrame_Text"));
m_BoundaryVisualizerFrame.setIconImage(m_Icon);
- m_BoundaryVisualizerFrame.getContentPane().setLayout(new BorderLayout());
-
+ m_BoundaryVisualizerFrame.getContentPane().setLayout(
+ new BorderLayout());
+
final BoundaryVisualizer bv = new BoundaryVisualizer();
- m_BoundaryVisualizerFrame.getContentPane().add(bv, BorderLayout.CENTER);
+ m_BoundaryVisualizerFrame.getContentPane().add(bv,
+ BorderLayout.CENTER);
m_BoundaryVisualizerFrame.setSize(bv.getMinimumSize());
m_BoundaryVisualizerFrame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent w) {
bv.stopPlotting();
m_BoundaryVisualizerFrame.dispose();
@@ -654,7 +755,7 @@ public class GUIChooser
}
});
m_BoundaryVisualizerFrame.pack();
- //m_BoundaryVisualizerFrame.setSize(800, 600);
+ // m_BoundaryVisualizerFrame.setSize(800, 600);
m_BoundaryVisualizerFrame.setResizable(false);
m_BoundaryVisualizerFrame.setVisible(true);
// dont' do a System.exit after last window got closed!
@@ -662,27 +763,30 @@ public class GUIChooser
}
}
});
-
+
// Extensions
- JMenu jMenuExtensions = new JMenu(Messages.getInstance().getString("GUIChooser_Extensions_Text"));
+ JMenu jMenuExtensions =
+ new JMenu(Messages.getInstance().getString("GUIChooser_Extensions_Text"));
jMenuExtensions.setMnemonic(java.awt.event.KeyEvent.VK_E);
m_jMenuBar.add(jMenuExtensions);
jMenuExtensions.setVisible(false);
-
- String extensions = GenericObjectEditor.EDITOR_PROPERTIES.getProperty(
+
+ String extensions =
+ GenericObjectEditor.EDITOR_PROPERTIES.getProperty(
MainMenuExtension.class.getName(), "");
if (extensions.length() > 0) {
jMenuExtensions.setVisible(true);
- String[] classnames = GenericObjectEditor.EDITOR_PROPERTIES.getProperty(
+ String[] classnames =
+ GenericObjectEditor.EDITOR_PROPERTIES.getProperty(
MainMenuExtension.class.getName(), "").split(",");
- Hashtable<String,JMenu> submenus = new Hashtable<String,JMenu>();
+ Hashtable<String, JMenu> submenus = new Hashtable<String, JMenu>();
// add all extensions
- for (int i = 0; i < classnames.length; i++) {
- String classname = classnames[i];
+ for (String classname : classnames) {
try {
- MainMenuExtension ext = (MainMenuExtension) Class.forName(classname).newInstance();
+ MainMenuExtension ext =
+ (MainMenuExtension) Class.forName(classname).newInstance();
// menuitem in a submenu?
JMenu submenu = null;
@@ -698,19 +802,20 @@ public class GUIChooser
// create menu item
JMenuItem menuitem = new JMenuItem();
menuitem.setText(ext.getMenuTitle());
- // does the extension need a frame or does it have its own ActionListener?
+ // does the extension need a frame or does it have its own
+ // ActionListener?
ActionListener listener = ext.getActionListener(m_Self);
if (listener != null) {
menuitem.addActionListener(listener);
- }
- else {
+ } else {
final JMenuItem finalMenuitem = menuitem;
final MainMenuExtension finalExt = ext;
menuitem.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
- Component frame = createFrame(
- m_Self, finalMenuitem.getText(),
- null, null, null, -1, -1, null, false, false);
+ Component frame =
+ createFrame(m_Self, finalMenuitem.getText(), null, null,
+ null, -1, -1, null, false, false);
finalExt.fillFrame(frame);
frame.setVisible(true);
}
@@ -718,35 +823,39 @@ public class GUIChooser
}
// sorted insert of menu item
- if (submenu != null)
+ if (submenu != null) {
insertMenuItem(submenu, menuitem);
- else
+ } else {
insertMenuItem(jMenuExtensions, menuitem);
- }
- catch (Exception e) {
+ }
+ } catch (Exception e) {
e.printStackTrace();
}
}
}
-
+
// Tools
m_jMenuTools = new JMenu();
m_jMenuBar.add(m_jMenuTools);
- m_jMenuTools.setText(Messages.getInstance().getString("GUIChooser_Tools_Text"));
+ m_jMenuTools.setText(Messages.getInstance().getString(
+ "GUIChooser_Tools_Text"));
m_jMenuTools.setMnemonic('T');
-
+
// Tools/ArffViewer
JMenuItem jMenuItemToolsArffViewer = new JMenuItem();
m_jMenuTools.add(jMenuItemToolsArffViewer);
- jMenuItemToolsArffViewer.setText(Messages.getInstance().getString("GUIChooser_ArffViewer_Text"));
+ jMenuItemToolsArffViewer.setText(Messages.getInstance().getString(
+ "GUIChooser_ArffViewer_Text"));
// jMenuItemToolsArffViewer.setMnemonic('A');
- jMenuItemToolsArffViewer.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK));
-
+ jMenuItemToolsArffViewer.setAccelerator(KeyStroke.getKeyStroke(
+ KeyEvent.VK_A, KeyEvent.CTRL_MASK));
+
jMenuItemToolsArffViewer.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
final ArffViewer av = new ArffViewer();
av.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent w) {
m_ArffViewers.remove(av);
checkExit();
@@ -756,25 +865,30 @@ public class GUIChooser
m_ArffViewers.add(av);
}
});
-
+
// Tools/SqlViewer
final JMenuItem jMenuItemToolsSql = new JMenuItem();
m_jMenuTools.add(jMenuItemToolsSql);
- jMenuItemToolsSql.setText(Messages.getInstance().getString("GUIChooser_SqlViewer_Text"));
+ jMenuItemToolsSql.setText(Messages.getInstance().getString(
+ "GUIChooser_SqlViewer_Text"));
// jMenuItemToolsSql.setMnemonic('S');
- jMenuItemToolsSql.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK));
-
+ jMenuItemToolsSql.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,
+ KeyEvent.CTRL_MASK));
+
jMenuItemToolsSql.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
if (m_SqlViewerFrame == null) {
jMenuItemToolsSql.setEnabled(false);
final SqlViewer sql = new SqlViewer(null);
- m_SqlViewerFrame = new JFrame(Messages.getInstance().getString("GUIChooser_SqlViewer_JFrame_Text"));
+ m_SqlViewerFrame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_SqlViewer_JFrame_Text"));
m_SqlViewerFrame.setIconImage(m_Icon);
m_SqlViewerFrame.getContentPane().setLayout(new BorderLayout());
m_SqlViewerFrame.getContentPane().add(sql, BorderLayout.CENTER);
m_SqlViewerFrame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent w) {
sql.saveSize();
m_SqlViewerFrame.dispose();
@@ -788,24 +902,30 @@ public class GUIChooser
}
}
});
-
+
// Tools/Bayes net editor
final JMenuItem jMenuItemBayesNet = new JMenuItem();
m_jMenuTools.add(jMenuItemBayesNet);
- jMenuItemBayesNet.setText(Messages.getInstance().getString("GUIChooser_BayesNetEditor_Text"));
- jMenuItemBayesNet.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_MASK));
+ jMenuItemBayesNet.setText(Messages.getInstance().getString(
+ "GUIChooser_BayesNetEditor_Text"));
+ jMenuItemBayesNet.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
+ KeyEvent.CTRL_MASK));
jMenuItemBayesNet.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
if (m_BayesNetGUIFrame == null) {
jMenuItemBayesNet.setEnabled(false);
final GUI bayesNetGUI = new GUI();
JMenuBar bayesBar = bayesNetGUI.getMenuBar();
- m_BayesNetGUIFrame = new JFrame(Messages.getInstance().getString("GUIChooser_BayesNetworkEditor_JFrame_Text"));
+ m_BayesNetGUIFrame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_BayesNetworkEditor_JFrame_Text"));
m_BayesNetGUIFrame.setIconImage(m_Icon);
m_BayesNetGUIFrame.setJMenuBar(bayesBar);
- m_BayesNetGUIFrame.getContentPane().add(bayesNetGUI, BorderLayout.CENTER);
+ m_BayesNetGUIFrame.getContentPane().add(bayesNetGUI,
+ BorderLayout.CENTER);
m_BayesNetGUIFrame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent w) {
m_BayesNetGUIFrame.dispose();
m_BayesNetGUIFrame = null;
@@ -818,69 +938,83 @@ public class GUIChooser
}
}
});
-
+
// Help
m_jMenuHelp = new JMenu();
m_jMenuBar.add(m_jMenuHelp);
- m_jMenuHelp.setText(Messages.getInstance().getString("GUIChooser_Help_Text"));
+ m_jMenuHelp.setText(Messages.getInstance()
+ .getString("GUIChooser_Help_Text"));
m_jMenuHelp.setMnemonic('H');
-
+
// Help/Homepage
JMenuItem jMenuItemHelpHomepage = new JMenuItem();
m_jMenuHelp.add(jMenuItemHelpHomepage);
- jMenuItemHelpHomepage.setText(Messages.getInstance().getString("GUIChooser_WekaHomepage_Text"));
+ jMenuItemHelpHomepage.setText(Messages.getInstance().getString(
+ "GUIChooser_WekaHomepage_Text"));
// jMenuItemHelpHomepage.setMnemonic('H');
- jMenuItemHelpHomepage.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, KeyEvent.CTRL_MASK));
+ jMenuItemHelpHomepage.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H,
+ KeyEvent.CTRL_MASK));
jMenuItemHelpHomepage.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
- BrowserHelper.openURL(Messages.getInstance().getString("GUIChooser_WekaHomepage_URL_Text"));
+ BrowserHelper.openURL(Messages.getInstance().getString(
+ "GUIChooser_WekaHomepage_URL_Text"));
}
});
-
+
m_jMenuHelp.add(new JSeparator());
-
+
// Help/WekaWiki
JMenuItem jMenuItemHelpWekaWiki = new JMenuItem();
m_jMenuHelp.add(jMenuItemHelpWekaWiki);
- jMenuItemHelpWekaWiki.setText(Messages.getInstance().getString("GUIChooser_WekaHOWTO_Text"));
+ jMenuItemHelpWekaWiki.setText(Messages.getInstance().getString(
+ "GUIChooser_WekaHOWTO_Text"));
// jMenuItemHelpWekaWiki.setMnemonic('W');
- jMenuItemHelpWekaWiki.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, KeyEvent.CTRL_MASK));
-
+ jMenuItemHelpWekaWiki.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W,
+ KeyEvent.CTRL_MASK));
+
jMenuItemHelpWekaWiki.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
- BrowserHelper.openURL(Messages.getInstance().getString("GUIChooser_WekaWiki_URL_Text"));
+ BrowserHelper.openURL(Messages.getInstance().getString(
+ "GUIChooser_WekaWiki_URL_Text"));
}
});
-
+
// Help/Sourceforge
JMenuItem jMenuItemHelpSourceforge = new JMenuItem();
m_jMenuHelp.add(jMenuItemHelpSourceforge);
- jMenuItemHelpSourceforge.setText(Messages.getInstance().getString("GUIChooser_WekaOnSourceforge_Text"));
-// jMenuItemHelpSourceforge.setMnemonic('F');
- jMenuItemHelpSourceforge.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F, KeyEvent.CTRL_MASK));
-
+ jMenuItemHelpSourceforge.setText(Messages.getInstance().getString(
+ "GUIChooser_WekaOnSourceforge_Text"));
+ // jMenuItemHelpSourceforge.setMnemonic('F');
+ jMenuItemHelpSourceforge.setAccelerator(KeyStroke.getKeyStroke(
+ KeyEvent.VK_F, KeyEvent.CTRL_MASK));
+
jMenuItemHelpSourceforge.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
- BrowserHelper.openURL(Messages.getInstance().getString("GUIChooser_WekaOnSourceforge_URL_Text"));
+ BrowserHelper.openURL(Messages.getInstance().getString(
+ "GUIChooser_WekaOnSourceforge_URL_Text"));
}
});
-
+
// Help/SystemInfo
final JMenuItem jMenuItemHelpSysInfo = new JMenuItem();
m_jMenuHelp.add(jMenuItemHelpSysInfo);
- jMenuItemHelpSysInfo.setText(Messages.getInstance().getString("GUIChooser_SystemInfo_Text"));
-// jMenuItemHelpSysInfo.setMnemonic('S');
- jMenuItemHelpSysInfo.
- setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, KeyEvent.CTRL_MASK));
-
+ jMenuItemHelpSysInfo.setText(Messages.getInstance().getString(
+ "GUIChooser_SystemInfo_Text"));
+ // jMenuItemHelpSysInfo.setMnemonic('S');
+ jMenuItemHelpSysInfo.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I,
+ KeyEvent.CTRL_MASK));
+
jMenuItemHelpSysInfo.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
if (m_SystemInfoFrame == null) {
jMenuItemHelpSysInfo.setEnabled(false);
- m_SystemInfoFrame = new JFrame(Messages.getInstance().getString("GUIChooser_SystemInfo_JFrame_Text"));
+ m_SystemInfoFrame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_SystemInfo_JFrame_Text"));
m_SystemInfoFrame.setIconImage(m_Icon);
m_SystemInfoFrame.getContentPane().setLayout(new BorderLayout());
@@ -890,8 +1024,9 @@ public class GUIChooser
// sort names
Vector names = new Vector();
Enumeration enm = info.keys();
- while (enm.hasMoreElements())
+ while (enm.hasMoreElements()) {
names.add(enm.nextElement());
+ }
Collections.sort(names);
// generate table
@@ -900,12 +1035,19 @@ public class GUIChooser
data[i][0] = names.get(i).toString();
data[i][1] = info.get(data[i][0]).toString();
}
-
- String[] titles = new String[]{Messages.getInstance().getString("GUIChooser_SystemInfo_TitleKey_Text"), Messages.getInstance().getString("GUIChooser_SystemInfo_TitleValue_Text")};
+
+ String[] titles =
+ new String[] {
+ Messages.getInstance().getString(
+ "GUIChooser_SystemInfo_TitleKey_Text"),
+ Messages.getInstance().getString(
+ "GUIChooser_SystemInfo_TitleValue_Text") };
JTable table = new JTable(data, titles);
- m_SystemInfoFrame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
+ m_SystemInfoFrame.getContentPane().add(new JScrollPane(table),
+ BorderLayout.CENTER);
m_SystemInfoFrame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent w) {
m_SystemInfoFrame.dispose();
m_SystemInfoFrame = null;
@@ -919,81 +1061,90 @@ public class GUIChooser
}
}
});
-
-
+
// applications
m_ExplorerBut.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
showExplorer(null);
}
});
m_ExperimenterBut.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
- if (m_ExperimenterFrame == null) {
- System.out.println("CALLED ExperimentEnvironment");
-
- m_ExperimenterBut.setEnabled(false);
- m_ExperimenterFrame = new JFrame(Messages.getInstance().getString("GUIChooser_WekaExperimentEnvironment_JFrame_Text"));
- m_ExperimenterFrame.setIconImage(m_Icon);
- m_ExperimenterFrame.getContentPane().setLayout(new BorderLayout());
- m_ExperimenterFrame.getContentPane()
- .add(new Experimenter(false), BorderLayout.CENTER);
- m_ExperimenterFrame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent w) {
- m_ExperimenterFrame.dispose();
- m_ExperimenterFrame = null;
- m_ExperimenterBut.setEnabled(true);
- checkExit();
- }
- });
- m_ExperimenterFrame.pack();
- m_ExperimenterFrame.setSize(800, 600);
- m_ExperimenterFrame.setVisible(true);
- }
+ if (m_ExperimenterFrame == null) {
+ System.out.println("CALLED ExperimentEnvironment");
+
+ m_ExperimenterBut.setEnabled(false);
+ m_ExperimenterFrame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_WekaExperimentEnvironment_JFrame_Text"));
+ m_ExperimenterFrame.setIconImage(m_Icon);
+ m_ExperimenterFrame.getContentPane().setLayout(new BorderLayout());
+ m_ExperimenterFrame.getContentPane().add(new Experimenter(false),
+ BorderLayout.CENTER);
+ m_ExperimenterFrame.addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowClosing(WindowEvent w) {
+ m_ExperimenterFrame.dispose();
+ m_ExperimenterFrame = null;
+ m_ExperimenterBut.setEnabled(true);
+ checkExit();
+ }
+ });
+ m_ExperimenterFrame.pack();
+ m_ExperimenterFrame.setSize(800, 600);
+ m_ExperimenterFrame.setVisible(true);
+ }
}
});
KnowledgeFlowApp.addStartupListener(new weka.gui.beans.StartUpListener() {
- public void startUpComplete() {
- if (m_KnowledgeFlowFrame == null) {
- final KnowledgeFlowApp kna = KnowledgeFlowApp.getSingleton();
- m_KnowledgeFlowBut.setEnabled(false);
- if (m_pendingKnowledgeFlowLoad != null &&
- m_pendingKnowledgeFlowLoad.length() > 0) {
- KnowledgeFlowApp.getSingleton().
- loadInitialLayout(m_pendingKnowledgeFlowLoad);
- m_pendingKnowledgeFlowLoad = null;
- }
- m_KnowledgeFlowFrame = new JFrame(Messages.getInstance().getString("GUIChooser_WekaKnowledgeFlowEnvironment_JFrame_Text"));
- m_KnowledgeFlowFrame.setIconImage(m_Icon);
- m_KnowledgeFlowFrame.getContentPane().setLayout(new BorderLayout());
- m_KnowledgeFlowFrame.getContentPane()
- .add(kna, BorderLayout.CENTER);
- m_KnowledgeFlowFrame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent w) {
- kna.clearLayout();
- m_KnowledgeFlowFrame.dispose();
- m_KnowledgeFlowFrame = null;
- m_KnowledgeFlowBut.setEnabled(true);
- checkExit();
- }
- });
- m_KnowledgeFlowFrame.pack();
- m_KnowledgeFlowFrame.setSize(1000, 750);
- m_KnowledgeFlowFrame.setVisible(true);
+ @Override
+ public void startUpComplete() {
+ if (m_KnowledgeFlowFrame == null) {
+ final KnowledgeFlowApp kna = KnowledgeFlowApp.getSingleton();
+ m_KnowledgeFlowBut.setEnabled(false);
+ if (m_pendingKnowledgeFlowLoad != null
+ && m_pendingKnowledgeFlowLoad.length() > 0) {
+ KnowledgeFlowApp.getSingleton().loadInitialLayout(
+ m_pendingKnowledgeFlowLoad);
+ m_pendingKnowledgeFlowLoad = null;
}
+ m_KnowledgeFlowFrame =
+ new JFrame(Messages.getInstance().getString(
+ "GUIChooser_WekaKnowledgeFlowEnvironment_JFrame_Text"));
+ m_KnowledgeFlowFrame.setIconImage(m_Icon);
+ m_KnowledgeFlowFrame.getContentPane().setLayout(new BorderLayout());
+ m_KnowledgeFlowFrame.getContentPane().add(kna, BorderLayout.CENTER);
+ m_KnowledgeFlowFrame.addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowClosing(WindowEvent w) {
+ kna.clearLayout();
+ m_KnowledgeFlowFrame.dispose();
+ m_KnowledgeFlowFrame = null;
+ m_KnowledgeFlowBut.setEnabled(true);
+ checkExit();
+ }
+ });
+ m_KnowledgeFlowFrame.pack();
+ m_KnowledgeFlowFrame.setSize(1000, 750);
+ m_KnowledgeFlowFrame.setVisible(true);
}
- });
+ }
+ });
m_KnowledgeFlowBut.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
showKnowledgeFlow(null);
}
});
m_SimpleBut.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
if (m_SimpleCLI == null) {
m_SimpleBut.setEnabled(false);
@@ -1001,9 +1152,11 @@ public class GUIChooser
m_SimpleCLI = new SimpleCLI();
m_SimpleCLI.setIconImage(m_Icon);
} catch (Exception ex) {
- throw new Error(Messages.getInstance().getString("GUIChooser_UnableToStartSimpleCLI_Error_Text"));
+ throw new Error(Messages.getInstance().getString(
+ "GUIChooser_UnableToStartSimpleCLI_Error_Text"));
}
m_SimpleCLI.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent w) {
m_SimpleCLI.dispose();
m_SimpleCLI = null;
@@ -1016,43 +1169,37 @@ public class GUIChooser
}
});
- /*m_EnsembleLibraryBut.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- if (m_EnsembleLibraryFrame == null) {
- m_EnsembleLibraryBut.setEnabled(false);
- m_EnsembleLibraryFrame = new JFrame("EnsembleLibrary");
- m_EnsembleLibraryFrame.setIconImage(m_Icon);
- m_EnsembleLibraryFrame.getContentPane().setLayout(new BorderLayout());
- EnsembleLibrary value = new EnsembleLibrary();
- EnsembleLibraryEditor libraryEditor = new EnsembleLibraryEditor();
- libraryEditor.setValue(value);
- m_EnsembleLibraryFrame.getContentPane().add(libraryEditor.getCustomEditor(), BorderLayout.CENTER);
- m_EnsembleLibraryFrame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent w) {
- m_EnsembleLibraryFrame.dispose();
- m_EnsembleLibraryFrame = null;
- m_EnsembleLibraryBut.setEnabled(true);
- checkExit();
- }
- });
- m_EnsembleLibraryFrame.pack();
- m_EnsembleLibraryFrame.setSize(800, 600);
- m_EnsembleLibraryFrame.setVisible(true);
- }
- }
- }); */
-
+ /*
+ * m_EnsembleLibraryBut.addActionListener(new ActionListener() { public void
+ * actionPerformed(ActionEvent e) { if (m_EnsembleLibraryFrame == null) {
+ * m_EnsembleLibraryBut.setEnabled(false); m_EnsembleLibraryFrame = new
+ * JFrame("EnsembleLibrary"); m_EnsembleLibraryFrame.setIconImage(m_Icon);
+ * m_EnsembleLibraryFrame.getContentPane().setLayout(new BorderLayout());
+ * EnsembleLibrary value = new EnsembleLibrary(); EnsembleLibraryEditor
+ * libraryEditor = new EnsembleLibraryEditor();
+ * libraryEditor.setValue(value);
+ * m_EnsembleLibraryFrame.getContentPane().add
+ * (libraryEditor.getCustomEditor(), BorderLayout.CENTER);
+ * m_EnsembleLibraryFrame.addWindowListener(new WindowAdapter() { public
+ * void windowClosing(WindowEvent w) { m_EnsembleLibraryFrame.dispose();
+ * m_EnsembleLibraryFrame = null; m_EnsembleLibraryBut.setEnabled(true);
+ * checkExit(); } }); m_EnsembleLibraryFrame.pack();
+ * m_EnsembleLibraryFrame.setSize(800, 600);
+ * m_EnsembleLibraryFrame.setVisible(true); } } });
+ */
+
setJMenuBar(m_jMenuBar);
addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent w) {
- dispose();
- checkExit();
+ dispose();
+ checkExit();
}
});
pack();
}
-
+
public void showKnowledgeFlow(String fileToLoad) {
if (m_KnowledgeFlowFrame == null) {
KnowledgeFlow.startApp();
@@ -1063,7 +1210,7 @@ public class GUIChooser
}
}
}
-
+
public void showExplorer(String fileToLoad) {
Explorer expl = null;
if (m_ExplorerFrame == null) {
@@ -1075,26 +1222,27 @@ public class GUIChooser
m_ExplorerFrame.getContentPane().add(expl, BorderLayout.CENTER);
m_ExplorerFrame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent w) {
- m_ExplorerFrame.dispose();
- m_ExplorerFrame = null;
- m_ExplorerBut.setEnabled(true);
- checkExit();
- }
- });
+ @Override
+ public void windowClosing(WindowEvent w) {
+ m_ExplorerFrame.dispose();
+ m_ExplorerFrame = null;
+ m_ExplorerBut.setEnabled(true);
+ checkExit();
+ }
+ });
m_ExplorerFrame.pack();
m_ExplorerFrame.setSize(800, 600);
m_ExplorerFrame.setVisible(true);
} else {
Object o = m_ExplorerFrame.getContentPane().getComponent(0);
if (o instanceof Explorer) {
- expl = (Explorer)o;
+ expl = (Explorer) o;
}
}
if (fileToLoad != null) {
try {
- weka.core.converters.AbstractFileLoader loader =
+ weka.core.converters.AbstractFileLoader loader =
weka.core.converters.ConverterUtils.getLoaderForFile(fileToLoad);
loader.setFile(new File(fileToLoad));
expl.getPreprocessPanel().setInstancesFromFile(loader);
@@ -1103,40 +1251,41 @@ public class GUIChooser
}
}
}
-
+
/**
* insert the menu item in a sorted fashion.
*
- * @param menu the menu to add the item to
- * @param menuitem the menu item to add
+ * @param menu the menu to add the item to
+ * @param menuitem the menu item to add
*/
protected void insertMenuItem(JMenu menu, JMenuItem menuitem) {
insertMenuItem(menu, menuitem, 0);
}
-
+
/**
* insert the menu item in a sorted fashion.
*
- * @param menu the menu to add the item to
- * @param menuitem the menu item to add
- * @param startIndex the index in the menu to start with (0-based)
+ * @param menu the menu to add the item to
+ * @param menuitem the menu item to add
+ * @param startIndex the index in the menu to start with (0-based)
*/
protected void insertMenuItem(JMenu menu, JMenuItem menuitem, int startIndex) {
- boolean inserted;
- int i;
- JMenuItem current;
- String currentStr;
- String newStr;
-
+ boolean inserted;
+ int i;
+ JMenuItem current;
+ String currentStr;
+ String newStr;
+
inserted = false;
- newStr = menuitem.getText().toLowerCase();
-
+ newStr = menuitem.getText().toLowerCase();
+
// try to find a spot inbetween
for (i = startIndex; i < menu.getMenuComponentCount(); i++) {
- if (!(menu.getMenuComponent(i) instanceof JMenuItem))
+ if (!(menu.getMenuComponent(i) instanceof JMenuItem)) {
continue;
-
- current = (JMenuItem) menu.getMenuComponent(i);
+ }
+
+ current = (JMenuItem) menu.getMenuComponent(i);
currentStr = current.getText().toLowerCase();
if (currentStr.compareTo(newStr) > 0) {
inserted = true;
@@ -1144,61 +1293,62 @@ public class GUIChooser
break;
}
}
-
+
// add it at the end if not yet inserted
- if (!inserted)
+ if (!inserted) {
menu.add(menuitem);
+ }
}
-
+
/**
* creates a frame and returns it.
*
- * @param parent the parent of the generated frame
- * @param title the title of the frame
- * @param c the component to place, can be null
- * @param layout the layout to use, e.g., BorderLayout
- * @param layoutConstraints the layout constraints, e.g., BorderLayout.CENTER
- * @param width the width of the frame, ignored if -1
- * @param height the height of the frame, ignored if -1
- * @param menu an optional menu
- * @param listener if true a default listener is added
- * @param visible if true then the frame is made visible immediately
- * @return the generated frame
+ * @param parent the parent of the generated frame
+ * @param title the title of the frame
+ * @param c the component to place, can be null
+ * @param layout the layout to use, e.g., BorderLayout
+ * @param layoutConstraints the layout constraints, e.g., BorderLayout.CENTER
+ * @param width the width of the frame, ignored if -1
+ * @param height the height of the frame, ignored if -1
+ * @param menu an optional menu
+ * @param listener if true a default listener is added
+ * @param visible if true then the frame is made visible immediately
+ * @return the generated frame
*/
- protected Container createFrame(
- GUIChooser parent, String title, Component c, LayoutManager layout,
- Object layoutConstraints, int width, int height, JMenuBar menu,
- boolean listener, boolean visible) {
+ protected Container createFrame(GUIChooser parent, String title, Component c,
+ LayoutManager layout, Object layoutConstraints, int width, int height,
+ JMenuBar menu, boolean listener, boolean visible) {
Container result = null;
-
final ChildFrameSDI frame = new ChildFrameSDI(parent, title);
// layout
frame.setLayout(layout);
- if (c != null)
+ if (c != null) {
frame.getContentPane().add(c, layoutConstraints);
+ }
// menu
frame.setJMenuBar(menu);
// size
frame.pack();
- if ((width > -1) && (height > -1))
+ if ((width > -1) && (height > -1)) {
frame.setSize(width, height);
+ }
frame.validate();
// location
int screenHeight = getGraphicsConfiguration().getBounds().height;
- int screenWidth = getGraphicsConfiguration().getBounds().width;
- frame.setLocation(
- (screenWidth - frame.getBounds().width) / 2,
- (screenHeight - frame.getBounds().height) / 2);
+ int screenWidth = getGraphicsConfiguration().getBounds().width;
+ frame.setLocation((screenWidth - frame.getBounds().width) / 2,
+ (screenHeight - frame.getBounds().height) / 2);
// listener?
if (listener) {
frame.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent e) {
frame.dispose();
}
@@ -1206,142 +1356,148 @@ public class GUIChooser
}
// display frame
- if (visible)
+ if (visible) {
frame.setVisible(true);
+ }
result = frame;
-
return result;
}
-
+
/**
* Specialized JFrame class.
*
- * @author fracpete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9490 $
+ * @author fracpete (fracpete at waikato dot ac dot nz)
+ * @version $Revision: 10793 $
*/
- public static class ChildFrameSDI
- extends JFrame {
-
+ public static class ChildFrameSDI extends JFrame {
+
/** for serialization. */
private static final long serialVersionUID = 8588293938686425618L;
-
+
/** the parent frame. */
protected GUIChooser m_Parent;
-
+
/**
* constructs a new internal frame that knows about its parent.
*
- * @param parent the parent frame
- * @param title the title of the frame
+ * @param parent the parent frame
+ * @param title the title of the frame
*/
public ChildFrameSDI(GUIChooser parent, String title) {
super(title);
-
+
m_Parent = parent;
addWindowListener(new WindowAdapter() {
+ @Override
public void windowActivated(WindowEvent e) {
// update title of parent
- if (getParentFrame() != null)
+ if (getParentFrame() != null) {
getParentFrame().createTitle(getTitle());
+ }
}
});
-
+
// add to parent
if (getParentFrame() != null) {
getParentFrame().addChildFrame(this);
setIconImage(getParentFrame().getIconImage());
}
}
-
+
/**
* returns the parent frame, can be null.
*
- * @return the parent frame
+ * @return the parent frame
*/
public GUIChooser getParentFrame() {
return m_Parent;
}
-
+
/**
* de-registers the child frame with the parent first.
*/
+ @Override
public void dispose() {
if (getParentFrame() != null) {
getParentFrame().removeChildFrame(this);
getParentFrame().createTitle("");
}
-
+
super.dispose();
}
}
-
+
/**
* creates and displays the title.
*
- * @param title the additional part of the title
+ * @param title the additional part of the title
*/
protected void createTitle(String title) {
- String newTitle;
-
- newTitle = Messages.getInstance().getString("GUIChooser_CreateTitle_Text_Front") + new Version();
- if (title.length() != 0)
- newTitle += Messages.getInstance().getString("GUIChooser_CreateTitle_Text_End") + title;
-
+ String newTitle;
+
+ newTitle =
+ Messages.getInstance().getString("GUIChooser_CreateTitle_Text_Front")
+ + new Version();
+ if (title.length() != 0) {
+ newTitle +=
+ Messages.getInstance().getString("GUIChooser_CreateTitle_Text_End")
+ + title;
+ }
+
setTitle(newTitle);
}
-
+
/**
* adds the given child frame to the list of frames.
*
- * @param c the child frame to add
+ * @param c the child frame to add
*/
public void addChildFrame(Container c) {
m_ChildFrames.add(c);
}
-
+
/**
* tries to remove the child frame, it returns true if it could do such.
*
- * @param c the child frame to remove
- * @return true if the child frame could be removed
+ * @param c the child frame to remove
+ * @return true if the child frame could be removed
*/
public boolean removeChildFrame(Container c) {
boolean result = m_ChildFrames.remove(c);
return result;
}
-
+
/**
* Kills the JVM if all windows have been closed.
*/
private void checkExit() {
if (!isVisible()
- // applications
- && (m_ExplorerFrame == null)
- && (m_ExperimenterFrame == null)
- && (m_KnowledgeFlowFrame == null)
- && (m_SimpleCLI == null)
- // tools
- && (m_ArffViewers.size() == 0)
- && (m_SqlViewerFrame == null)
- && (m_EnsembleLibraryFrame == null)
- // visualization
- && (m_Plots.size() == 0)
- && (m_ROCs.size() == 0)
- && (m_TreeVisualizers.size() == 0)
- && (m_GraphVisualizers.size() == 0)
- && (m_BoundaryVisualizerFrame == null)
- // help
- && (m_SystemInfoFrame == null) ) {
+ // applications
+ && (m_ExplorerFrame == null)
+ && (m_ExperimenterFrame == null)
+ && (m_KnowledgeFlowFrame == null)
+ && (m_SimpleCLI == null)
+ // tools
+ && (m_ArffViewers.size() == 0)
+ && (m_SqlViewerFrame == null)
+ && (m_EnsembleLibraryFrame == null)
+ // visualization
+ && (m_Plots.size() == 0) && (m_ROCs.size() == 0)
+ && (m_TreeVisualizers.size() == 0) && (m_GraphVisualizers.size() == 0)
+ && (m_BoundaryVisualizerFrame == null)
+ // help
+ && (m_SystemInfoFrame == null)) {
System.exit(0);
}
}
- /** variable for the GUIChooser class which would be set to null by the memory
- monitoring thread to free up some memory if we running out of memory
+ /**
+ * variable for the GUIChooser class which would be set to null by the memory
+ * monitoring thread to free up some memory if we running out of memory
*/
private static GUIChooser m_chooser;
@@ -1350,84 +1506,87 @@ public class GUIChooser
/**
* Tests out the GUIChooser environment.
- *
+ *
* @param args ignored.
*/
- public static void main(String [] args) {
+ public static void main(String[] args) {
- weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages.getInstance().getString("GUIChooser_Main_LoggingStarted_Text"));
+ weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages
+ .getInstance().getString("GUIChooser_Main_LoggingStarted_Text"));
LookAndFeel.setLookAndFeel();
-
+
try {
// uncomment to disable the memory management:
- //m_Memory.setEnabled(false);
+ // m_Memory.setEnabled(false);
- //m_chooser = new GUIChooser();
+ // m_chooser = new GUIChooser();
GUIChooser.createSingleton();
m_chooser.setVisible(true);
-
+
if (args != null && args.length > 0) {
m_chooser.showExplorer(args[0]);
}
Thread memMonitor = new Thread() {
+ @Override
public void run() {
- while(true) {
- try {
- //System.out.println("before sleeping");
- this.sleep(4000);
-
- System.gc();
-
- if (m_Memory.isOutOfMemory()) {
- // clean up
- m_chooser.dispose();
- if(m_chooser.m_ExperimenterFrame!=null) {
- m_chooser.m_ExperimenterFrame.dispose();
- m_chooser.m_ExperimenterFrame =null;
- }
- if(m_chooser.m_ExplorerFrame!=null) {
- m_chooser.m_ExplorerFrame.dispose();
- m_chooser.m_ExplorerFrame = null;
- }
- if(m_chooser.m_KnowledgeFlowFrame!=null) {
- m_chooser.m_KnowledgeFlowFrame.dispose();
- m_chooser.m_KnowledgeFlowFrame = null;
- }
- if(m_chooser.m_SimpleCLI!=null) {
- m_chooser.m_SimpleCLI.dispose();
- m_chooser.m_SimpleCLI = null;
- }
- if (m_chooser.m_ArffViewers.size() > 0) {
- for (int i = 0; i < m_chooser.m_ArffViewers.size(); i++) {
- ArffViewer av = (ArffViewer)
- m_chooser.m_ArffViewers.get(i);
- av.dispose();
- }
- m_chooser.m_ArffViewers.clear();
+ while (true) {
+ // try {
+ // //System.out.println("before sleeping");
+ // this.sleep(4000);
+
+ // System.gc();
+
+ if (m_Memory.isOutOfMemory()) {
+ // clean up
+ m_chooser.dispose();
+ if (m_chooser.m_ExperimenterFrame != null) {
+ m_chooser.m_ExperimenterFrame.dispose();
+ m_chooser.m_ExperimenterFrame = null;
+ }
+ if (m_chooser.m_ExplorerFrame != null) {
+ m_chooser.m_ExplorerFrame.dispose();
+ m_chooser.m_ExplorerFrame = null;
+ }
+ if (m_chooser.m_KnowledgeFlowFrame != null) {
+ m_chooser.m_KnowledgeFlowFrame.dispose();
+ m_chooser.m_KnowledgeFlowFrame = null;
+ }
+ if (m_chooser.m_SimpleCLI != null) {
+ m_chooser.m_SimpleCLI.dispose();
+ m_chooser.m_SimpleCLI = null;
+ }
+ if (m_chooser.m_ArffViewers.size() > 0) {
+ for (int i = 0; i < m_chooser.m_ArffViewers.size(); i++) {
+ ArffViewer av = (ArffViewer) m_chooser.m_ArffViewers.get(i);
+ av.dispose();
}
- m_chooser = null;
- System.gc();
-
- // display error
- m_chooser.m_LogWindow.setVisible(true);
- m_chooser.m_LogWindow.toFront();
- System.err.println(Messages.getInstance().getString("GUIChooser_Main_Error_Text_Front"));
- m_Memory.showOutOfMemory();
- System.err.println(Messages.getInstance().getString("GUIChooser_Main_Error_Text_End"));
- System.exit(-1);
+ m_chooser.m_ArffViewers.clear();
}
- }
- catch(InterruptedException ex) {
- ex.printStackTrace();
+ m_chooser = null;
+ System.gc();
+
+ // display error
+ m_chooser.m_LogWindow.setVisible(true);
+ m_chooser.m_LogWindow.toFront();
+ System.err.println(Messages.getInstance().getString(
+ "GUIChooser_Main_Error_Text_Front"));
+ m_Memory.showOutOfMemory();
+ System.err.println(Messages.getInstance().getString(
+ "GUIChooser_Main_Error_Text_End"));
+ System.exit(-1);
}
+ // }
+ // catch(InterruptedException ex) {
+ // ex.printStackTrace();
+ // }
}
}
};
memMonitor.setPriority(Thread.NORM_PRIORITY);
- memMonitor.start();
+ memMonitor.start();
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
diff --git a/src/main/java/weka/gui/GenericObjectEditor.java b/src/main/java/weka/gui/GenericObjectEditor.java
index 632c013..6dbfdc5 100644
--- a/src/main/java/weka/gui/GenericObjectEditor.java
+++ b/src/main/java/weka/gui/GenericObjectEditor.java
@@ -22,15 +22,6 @@
package weka.gui;
-import weka.core.Capabilities;
-import weka.core.CapabilitiesHandler;
-import weka.core.ClassDiscovery;
-import weka.core.OptionHandler;
-import weka.core.SerializedObject;
-import weka.core.Utils;
-import weka.core.Capabilities.Capability;
-import weka.gui.CheckBoxList.CheckBoxListModel;
-
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
@@ -41,6 +32,7 @@ import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
+import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.PropertyChangeEvent;
@@ -78,6 +70,15 @@ import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
+import weka.core.Capabilities;
+import weka.core.Capabilities.Capability;
+import weka.core.CapabilitiesHandler;
+import weka.core.ClassDiscovery;
+import weka.core.OptionHandler;
+import weka.core.SerializedObject;
+import weka.core.Utils;
+import weka.gui.CheckBoxList.CheckBoxListModel;
+
/**
* A PropertyEditor for objects. It can be used either in a static or a dynamic
* way. <br>
@@ -92,10 +93,11 @@ import javax.swing.tree.TreeSelectionModel;
* properties file is read only once when the class is first loaded -- this may
* need to be changed if we ever end up running in a Java OS ;-). <br>
* <br>
- * If it is used in a <b>dynamic</b> way (the <code>UseDynamic</code> property
- * of the GenericPropertiesCreator props file is set to <code>true</code>)
- * then the classes to list are discovered by the
- * <code>GenericPropertiesCreator</code> class (it checks the complete classpath).
+ * If it is used in a <b>dynamic</b> way (the <code>UseDynamic</code> property
+ * of the GenericPropertiesCreator props file is set to <code>true</code>) then
+ * the classes to list are discovered by the
+ * <code>GenericPropertiesCreator</code> class (it checks the complete
+ * classpath).
*
* @see GenericPropertiesCreator
* @see GenericPropertiesCreator#useDynamic()
@@ -106,35 +108,37 @@ import javax.swing.tree.TreeSelectionModel;
* @author Xin Xu (xx5 at cs.waikato.ac.nz)
* @author Richard Kirkby (rkirkby at cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 7059 $
+ * @version $Revision: 10570 $
*/
public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier {
-
+
/** The object being configured. */
protected Object m_Object;
-
- /** Holds a copy of the current object that can be reverted to
- if the user decides to cancel. */
+
+ /**
+ * Holds a copy of the current object that can be reverted to if the user
+ * decides to cancel.
+ */
protected Object m_Backup;
-
+
/** Handles property change notification. */
protected PropertyChangeSupport m_Support = new PropertyChangeSupport(this);
-
+
/** The Class of objects being edited. */
protected Class m_ClassType;
-
+
/** The model containing the list of names to select from. */
protected Hashtable m_ObjectNames;
/** The GUI component for editing values, created when needed. */
protected GOEPanel m_EditorComponent;
-
+
/** True if the GUI component is needed. */
protected boolean m_Enabled = true;
-
+
/** The name of the properties file. */
protected static String PROPERTY_FILE = "weka/gui/GenericObjectEditor.props";
-
+
/** Contains the editor properties. */
protected static Properties EDITOR_PROPERTIES;
@@ -146,19 +150,20 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/** The property panel created for the objects. */
protected PropertyPanel m_ObjectPropertyPanel;
-
+
/** whether the class can be changed. */
protected boolean m_canChangeClassInDialog;
-
+
/** whether the Weka Editors were already registered. */
protected static boolean m_EditorsRegistered;
/** for filtering the tree based on the Capabilities of the leaves. */
protected Capabilities m_CapabilitiesFilter = null;
-
- /**
+
+ /**
* Loads the configuration property file (USE_DYNAMIC is FALSE) or determines
* the classes dynamically (USE_DYNAMIC is TRUE)
+ *
* @see #USE_DYNAMIC
* @see GenericPropertiesCreator
*/
@@ -169,182 +174,245 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
// dynamic approach?
if (creator.useDynamic()) {
- try {
- creator.execute(false);
- EDITOR_PROPERTIES = creator.getOutputProperties();
- }
- catch (Exception e) {
- JOptionPane.showMessageDialog(
- null,
- Messages.getInstance().getString("GenericObjectEditor_JOptionPaneShowMessageDialog_Text_First")
- + e.toString(),
- Messages.getInstance().getString("GenericObjectEditor_JOptionPaneShowMessageDialog_Text_Second"),
- JOptionPane.ERROR_MESSAGE);
- }
- }
- else {
- // Allow a properties file in the current directory to override
- try {
- EDITOR_PROPERTIES = Utils.readProperties(PROPERTY_FILE);
- java.util.Enumeration keys =
- (java.util.Enumeration)EDITOR_PROPERTIES.propertyNames();
- if (!keys.hasMoreElements()) {
- throw new Exception(Messages.getInstance().getString("GenericObjectEditor_Exception_Text"));
- }
- }
- catch (Exception ex) {
- JOptionPane.showMessageDialog(
- null,
- Messages.getInstance().getString("GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_First")
- + PROPERTY_FILE + Messages.getInstance().getString("GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Second")
- + System.getProperties().getProperty("user.home")
- + Messages.getInstance().getString("GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Third"),
- Messages.getInstance().getString("GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Fourth"),
- JOptionPane.ERROR_MESSAGE);
- }
+ try {
+ creator.execute(false);
+ EDITOR_PROPERTIES = creator.getOutputProperties();
+ } catch (Exception e) {
+ JOptionPane.showMessageDialog(
+ null,
+ Messages.getInstance().getString(
+ "GenericObjectEditor_JOptionPaneShowMessageDialog_Text_First")
+ + e.toString(),
+ Messages.getInstance().getString(
+ "GenericObjectEditor_JOptionPaneShowMessageDialog_Text_Second"),
+ JOptionPane.ERROR_MESSAGE);
+ }
+ } else {
+ // Allow a properties file in the current directory to override
+ try {
+ EDITOR_PROPERTIES = Utils.readProperties(PROPERTY_FILE);
+ java.util.Enumeration keys = EDITOR_PROPERTIES.propertyNames();
+ if (!keys.hasMoreElements()) {
+ throw new Exception(Messages.getInstance().getString(
+ "GenericObjectEditor_Exception_Text"));
+ }
+ } catch (Exception ex) {
+ JOptionPane
+ .showMessageDialog(
+ null,
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_First")
+ + PROPERTY_FILE
+ + Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Second")
+ + System.getProperties().getProperty("user.home")
+ + Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Third"),
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Fourth"),
+ JOptionPane.ERROR_MESSAGE);
+ }
}
- }
- catch (Exception e) {
- JOptionPane.showMessageDialog(
- null,
- Messages.getInstance().getString("GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Fifth")
- + e.toString(),
- Messages.getInstance().getString("GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Sixth"),
- JOptionPane.ERROR_MESSAGE);
+ } catch (Exception e) {
+ JOptionPane
+ .showMessageDialog(
+ null,
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Fifth")
+ + e.toString(),
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_Exception_JOptionPaneShowMessageDialog_Text_Sixth"),
+ JOptionPane.ERROR_MESSAGE);
}
}
/**
* A specialized TreeNode for supporting filtering via Capabilities.
*/
- public class GOETreeNode
- extends DefaultMutableTreeNode {
-
+ public class GOETreeNode extends DefaultMutableTreeNode {
+
/** for serialization. */
static final long serialVersionUID = -1707872446682150133L;
-
+
/** color for "no support". */
public final static String NO_SUPPORT = "silver";
-
+
/** color for "maybe support". */
public final static String MAYBE_SUPPORT = "blue";
-
+
/** the Capabilities object to use for filtering. */
protected Capabilities m_Capabilities = null;
-
+
+ /** tool tip */
+ protected String m_toolTipText;
+
/**
- * Creates a tree node that has no parent and no children, but which
- * allows children.
+ * Creates a tree node that has no parent and no children, but which allows
+ * children.
*/
public GOETreeNode() {
super();
}
-
+
/**
- * Creates a tree node with no parent, no children, but which allows
+ * Creates a tree node with no parent, no children, but which allows
* children, and initializes it with the specified user object.
*
- * @param userObject an Object provided by the user that constitutes
- * the node's data
+ * @param userObject an Object provided by the user that constitutes the
+ * node's data
*/
public GOETreeNode(Object userObject) {
super(userObject);
}
-
+
/**
- * Creates a tree node with no parent, no children, initialized with the
+ * Creates a tree node with no parent, no children, initialized with the
* specified user object, and that allows children only if specified.
-
- * @param userObject an Object provided by the user that constitutes
- * the node's data
- * @param allowsChildren if true, the node is allowed to have child nodes
- * -- otherwise, it is always a leaf node
+ *
+ * @param userObject an Object provided by the user that constitutes the
+ * node's data
+ * @param allowsChildren if true, the node is allowed to have child nodes --
+ * otherwise, it is always a leaf node
*/
public GOETreeNode(Object userObject, boolean allowsChildren) {
super(userObject, allowsChildren);
}
-
+
+ /**
+ * Set the tool tip for this node
+ *
+ * @param tip the tool tip for this node
+ */
+ public void setToolTipText(String tip) {
+ m_toolTipText = tip;
+ }
+
+ /**
+ * Get the tool tip for this node
+ *
+ * @return the tool tip for this node
+ */
+ public String getToolTipText() {
+ return m_toolTipText;
+ }
+
/**
* generates if necessary a Capabilities object for the given leaf.
*/
protected void initCapabilities() {
- String classname;
- Class cls;
- Object obj;
-
- if (m_Capabilities != null)
- return;
- if (!isLeaf())
- return;
-
+ String classname;
+ Class cls;
+ Object obj;
+
+ if (m_Capabilities != null) {
+ return;
+ }
+ if (!isLeaf()) {
+ return;
+ }
+
classname = getClassnameFromPath(new TreePath(getPath()));
try {
- cls = Class.forName(classname);
- if (!ClassDiscovery.hasInterface(CapabilitiesHandler.class, cls))
- return;
-
- obj = cls.newInstance();
- m_Capabilities = ((CapabilitiesHandler) obj).getCapabilities();
- }
- catch (Exception e) {
- // ignore it
+ cls = Class.forName(classname);
+ if (!ClassDiscovery.hasInterface(CapabilitiesHandler.class, cls)) {
+ return;
+ }
+
+ obj = cls.newInstance();
+ m_Capabilities = ((CapabilitiesHandler) obj).getCapabilities();
+ } catch (Exception e) {
+ // ignore it
}
}
-
+
/**
* returns a string representation of this treenode.
*
- * @return the text to display
+ * @return the text to display
*/
+ @Override
public String toString() {
- String result;
-
+ String result;
+
result = super.toString();
-
+
if (m_CapabilitiesFilter != null) {
- initCapabilities();
- if (m_Capabilities != null) {
- if (m_Capabilities.supportsMaybe(m_CapabilitiesFilter) && !m_Capabilities.supports(m_CapabilitiesFilter))
- result = Messages.getInstance().getString("GenericObjectEditor_GOETreeNode_ToString_Result_Text_First") + MAYBE_SUPPORT + Messages.getInstance().getString("GenericObjectEditor_GOETreeNode_ToString_Result_Text_Second") + result + Messages.getInstance().getString("GenericObjectEditor_GOETreeNode_ToString_Result_Text_Third");
- else if (!m_Capabilities.supports(m_CapabilitiesFilter))
- result = Messages.getInstance().getString("GenericObjectEditor_GOETreeNode_ToString_Result_Text_Fourth") + NO_SUPPORT + Messages.getInstance().getString("GenericObjectEditor_GOETreeNode_ToString_Result_Text_Fifth") + result + Messages.getInstance().getString("GenericObjectEditor_GOETreeNode_ToString_Result_Text_Sixth");
- }
+ initCapabilities();
+ if (m_Capabilities != null) {
+ if (m_Capabilities.supportsMaybe(m_CapabilitiesFilter)
+ && !m_Capabilities.supports(m_CapabilitiesFilter)) {
+ result = Messages.getInstance().getString(
+ "GenericObjectEditor_GOETreeNode_ToString_Result_Text_First")
+ + MAYBE_SUPPORT
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_GOETreeNode_ToString_Result_Text_Second")
+ + result
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_GOETreeNode_ToString_Result_Text_Third");
+ } else if (!m_Capabilities.supports(m_CapabilitiesFilter)) {
+ result = Messages.getInstance().getString(
+ "GenericObjectEditor_GOETreeNode_ToString_Result_Text_Fourth")
+ + NO_SUPPORT
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_GOETreeNode_ToString_Result_Text_Fifth")
+ + result
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_GOETreeNode_ToString_Result_Text_Sixth");
+ }
+ }
}
-
+
return result;
}
}
-
+
/**
* A dialog for selecting Capabilities to look for in the GOE tree.
*/
- public class CapabilitiesFilterDialog
- extends JDialog {
-
+ public class CapabilitiesFilterDialog extends JDialog {
+
/** for serialization. */
static final long serialVersionUID = -7845503345689646266L;
-
+
/** the dialog itself. */
protected JDialog m_Self;
-
+
/** the popup to display again. */
protected JPopupMenu m_Popup = null;
-
+
/** the capabilities used for initializing the dialog. */
protected Capabilities m_Capabilities = new Capabilities(null);
/** the label, listing the name of the superclass. */
protected JLabel m_InfoLabel = new JLabel();
-
+
/** the list with all the capabilities. */
protected CheckBoxList m_List = new CheckBoxList();
-
+
/** the OK button. */
- protected JButton m_OkButton = new JButton(Messages.getInstance().getString("GenericObjectEditor_CapabilitiesFilterDialog_OkButton_JButton_Text"));
-
+ protected JButton m_OkButton = new JButton(Messages.getInstance()
+ .getString(
+ "GenericObjectEditor_CapabilitiesFilterDialog_OkButton_JButton_Text"));
+
/** the Cancel button. */
- protected JButton m_CancelButton = new JButton(Messages.getInstance().getString("GenericObjectEditor_CapabilitiesFilterDialog_CancelButton_JButton_Text"));
-
+ protected JButton m_CancelButton = new JButton(
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_CapabilitiesFilterDialog_CancelButton_JButton_Text"));
+
/**
* creates a dialog to choose Capabilities from.
*/
@@ -352,62 +420,72 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
super();
m_Self = this;
-
+
initGUI();
}
-
+
/**
* sets up the GUI.
*/
protected void initGUI() {
- JPanel panel;
- CheckBoxListModel model;
+ JPanel panel;
+ CheckBoxListModel model;
- setTitle(Messages.getInstance().getString("GenericObjectEditor_InitGUI_SetTitle_Text"));
+ setTitle(Messages.getInstance().getString(
+ "GenericObjectEditor_InitGUI_SetTitle_Text"));
setLayout(new BorderLayout());
-
+
panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
getContentPane().add(panel, BorderLayout.NORTH);
- m_InfoLabel.setText(
- Messages.getInstance().getString("GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_First")
- + m_ClassType.getName().replaceAll(".*\\.", "")
- + Messages.getInstance().getString("GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Second")
- + GOETreeNode.NO_SUPPORT
- + Messages.getInstance().getString("GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Third")
- + GOETreeNode.NO_SUPPORT
- + Messages.getInstance().getString("GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Fourth")
- + GOETreeNode.MAYBE_SUPPORT
- + Messages.getInstance().getString("GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Fifth")
- + GOETreeNode.MAYBE_SUPPORT
- + Messages.getInstance().getString("GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Sixth"));
+ m_InfoLabel.setText(Messages.getInstance().getString(
+ "GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_First")
+ + m_ClassType.getName().replaceAll(".*\\.", "")
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Second")
+ + GOETreeNode.NO_SUPPORT
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Third")
+ + GOETreeNode.NO_SUPPORT
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Fourth")
+ + GOETreeNode.MAYBE_SUPPORT
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Fifth")
+ + GOETreeNode.MAYBE_SUPPORT
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_InitGUI_InfoLabel_SetTitle_Text_Sixth"));
panel.add(m_InfoLabel, BorderLayout.CENTER);
-
+
// list
getContentPane().add(new JScrollPane(m_List), BorderLayout.CENTER);
model = (CheckBoxListModel) m_List.getModel();
- for (Capability cap: Capability.values())
- model.addElement(cap);
-
+ for (Capability cap : Capability.values()) {
+ model.addElement(cap);
+ }
+
// buttons
panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
getContentPane().add(panel, BorderLayout.SOUTH);
-
+
m_OkButton.setMnemonic('O');
m_OkButton.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
updateCapabilities();
- if (m_CapabilitiesFilter == null)
+ if (m_CapabilitiesFilter == null) {
m_CapabilitiesFilter = new Capabilities(null);
+ }
m_CapabilitiesFilter.assign(m_Capabilities);
m_Self.setVisible(false);
showPopup();
}
});
panel.add(m_OkButton);
-
+
m_CancelButton.setMnemonic('C');
m_CancelButton.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
m_Self.setVisible(false);
showPopup();
@@ -424,48 +502,51 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
* @see #m_List
*/
protected void updateList() {
- CheckBoxListModel model;
-
+ CheckBoxListModel model;
+
model = (CheckBoxListModel) m_List.getModel();
- for (Capability cap: Capability.values())
- model.setChecked(model.indexOf(cap), m_Capabilities.handles(cap));
+ for (Capability cap : Capability.values()) {
+ model.setChecked(model.indexOf(cap), m_Capabilities.handles(cap));
+ }
}
-
+
/**
- * transfers the selected Capabilities from the JList to the
- * Capabilities object.
+ * transfers the selected Capabilities from the JList to the Capabilities
+ * object.
*
* @see #m_Capabilities
* @see #m_List
*/
protected void updateCapabilities() {
- CheckBoxListModel model;
-
+ CheckBoxListModel model;
+
model = (CheckBoxListModel) m_List.getModel();
- for (Capability cap: Capability.values()) {
- if (model.getChecked(model.indexOf(cap)))
+ for (Capability cap : Capability.values()) {
+ if (model.getChecked(model.indexOf(cap))) {
m_Capabilities.enable(cap);
- else
- m_Capabilities.disable(cap);
+ } else {
+ m_Capabilities.disable(cap);
+ }
}
}
-
+
/**
* sets the initial capabilities.
*
* @param value the capabilities to use
*/
public void setCapabilities(Capabilities value) {
- if (value != null)
- m_Capabilities.assign(value);
- else
- m_Capabilities = new Capabilities(null);
-
+ if (value != null) {
+ m_Capabilities.assign(value);
+ } else {
+ m_Capabilities = new Capabilities(null);
+ }
+
updateList();
}
-
+
/**
* returns the currently selected capabilities.
*
@@ -474,7 +555,7 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
public Capabilities getCapabilities() {
return m_Capabilities;
}
-
+
/**
* sets the JPopupMenu to display again after closing the dialog.
*
@@ -483,7 +564,7 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
public void setPopup(JPopupMenu value) {
m_Popup = value;
}
-
+
/**
* returns the currently set JPopupMenu.
*
@@ -492,92 +573,100 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
public JPopupMenu getPopup() {
return m_Popup;
}
-
+
/**
* if a JPopupMenu is set, it is displayed again. Displaying this dialog
* closes any JPopupMenu automatically.
*/
public void showPopup() {
- if (getPopup() != null)
- getPopup().setVisible(true);
+ if (getPopup() != null) {
+ getPopup().setVisible(true);
+ }
}
}
-
+
/**
- * Creates a popup menu containing a tree that is aware
- * of the screen dimensions.
+ * Creates a popup menu containing a tree that is aware of the screen
+ * dimensions.
*/
- public class JTreePopupMenu
- extends JPopupMenu {
-
+ public class JTreePopupMenu extends JPopupMenu {
+
/** for serialization. */
static final long serialVersionUID = -3404546329655057387L;
/** the popup itself. */
- private JPopupMenu m_Self;
-
+ private final JPopupMenu m_Self;
+
/** The tree. */
- private JTree m_tree;
+ private final JTree m_tree;
/** The scroller. */
- private JScrollPane m_scroller;
+ private final JScrollPane m_scroller;
/** The filter button in case of CapabilitiesHandlers. */
- private JButton m_FilterButton = new JButton(Messages.getInstance().getString("GenericObjectEditor_JTreePopupMenu_FilterButton_JButton_Text"));
+ private final JButton m_FilterButton = new JButton(
+ Messages.getInstance().getString(
+ "GenericObjectEditor_JTreePopupMenu_FilterButton_JButton_Text"));
/** The remove filter button in case of CapabilitiesHandlers. */
- private JButton m_RemoveFilterButton = new JButton(Messages.getInstance().getString("GenericObjectEditor_JTreePopupMenu_RemoveFilterButton_JButton_Text"));
-
+ private final JButton m_RemoveFilterButton = new JButton(Messages
+ .getInstance().getString(
+ "GenericObjectEditor_JTreePopupMenu_RemoveFilterButton_JButton_Text"));
+
/** The button for closing the popup again. */
- private JButton m_CloseButton = new JButton(Messages.getInstance().getString("GenericObjectEditor_JTreePopupMenu_CloseButton_JButton_Text"));
-
+ private final JButton m_CloseButton = new JButton(Messages.getInstance()
+ .getString("GenericObjectEditor_JTreePopupMenu_CloseButton_JButton_Text"));
+
/**
* Constructs a new popup menu.
- *
+ *
* @param tree the tree to put in the menu
*/
public JTreePopupMenu(JTree tree) {
m_Self = this;
-
+
setLayout(new BorderLayout());
JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
add(panel, BorderLayout.SOUTH);
if (ClassDiscovery.hasInterface(CapabilitiesHandler.class, m_ClassType)) {
- // filter
- m_FilterButton.setMnemonic('F');
- m_FilterButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() == m_FilterButton) {
- CapabilitiesFilterDialog dialog = new CapabilitiesFilterDialog();
- dialog.setCapabilities(m_CapabilitiesFilter);
- dialog.setPopup(m_Self);
- dialog.setVisible(true);
- m_Support.firePropertyChange("", null, null);
- repaint();
- }
- }
- });
- panel.add(m_FilterButton);
-
- // remove
- m_RemoveFilterButton.setMnemonic('R');
- m_RemoveFilterButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() == m_RemoveFilterButton) {
- m_CapabilitiesFilter = null;
- m_Support.firePropertyChange("", null, null);
- repaint();
- }
- }
- });
- panel.add(m_RemoveFilterButton);
+ // filter
+ m_FilterButton.setMnemonic('F');
+ m_FilterButton.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (e.getSource() == m_FilterButton) {
+ CapabilitiesFilterDialog dialog = new CapabilitiesFilterDialog();
+ dialog.setCapabilities(m_CapabilitiesFilter);
+ dialog.setPopup(m_Self);
+ dialog.setVisible(true);
+ m_Support.firePropertyChange("", null, null);
+ repaint();
+ }
+ }
+ });
+ panel.add(m_FilterButton);
+
+ // remove
+ m_RemoveFilterButton.setMnemonic('R');
+ m_RemoveFilterButton.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (e.getSource() == m_RemoveFilterButton) {
+ m_CapabilitiesFilter = null;
+ m_Support.firePropertyChange("", null, null);
+ repaint();
+ }
+ }
+ });
+ panel.add(m_RemoveFilterButton);
}
// close
m_CloseButton.setMnemonic('C');
m_CloseButton.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == m_CloseButton) {
m_Self.setVisible(false);
@@ -585,18 +674,18 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
}
});
panel.add(m_CloseButton);
-
+
m_tree = tree;
-
+
JPanel treeView = new JPanel();
treeView.setLayout(new BorderLayout());
treeView.add(m_tree, BorderLayout.NORTH);
-
+
// make backgrounds look the same
treeView.setBackground(m_tree.getBackground());
m_scroller = new JScrollPane(treeView);
-
+
m_scroller.setPreferredSize(new Dimension(300, 400));
m_scroller.getVerticalScrollBar().setUnitIncrement(20);
@@ -605,11 +694,12 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Displays the menu, making sure it will fit on the screen.
- *
+ *
* @param invoker the component thast invoked the menu
* @param x the x location of the popup
* @param y the y location of the popup
*/
+ @Override
public void show(Component invoker, int x, int y) {
super.show(invoker, x, y);
@@ -624,9 +714,13 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
Dimension scrollerSize = m_scroller.getPreferredSize();
int height = (int) scrollerSize.getHeight();
int width = (int) scrollerSize.getWidth();
- if (width > maxWidth) width = maxWidth;
- if (height > maxHeight) height = maxHeight;
-
+ if (width > maxWidth) {
+ width = maxWidth;
+ }
+ if (height > maxHeight) {
+ height = maxHeight;
+ }
+
// commit any size changes
m_scroller.setPreferredSize(new Dimension(width, height));
revalidate();
@@ -637,130 +731,141 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Handles the GUI side of editing values.
*/
- public class GOEPanel
- extends JPanel {
-
+ public class GOEPanel extends JPanel {
+
/** for serialization. */
static final long serialVersionUID = 3656028520876011335L;
-
+
/** The component that performs classifier customization. */
protected PropertySheetPanel m_ChildPropertySheet;
-
+
/** The name of the current class. */
protected JLabel m_ClassNameLabel;
/** Open object from disk. */
protected JButton m_OpenBut;
-
+
/** Save object to disk. */
protected JButton m_SaveBut;
-
+
/** ok button. */
protected JButton m_okBut;
-
+
/** cancel button. */
protected JButton m_cancelBut;
-
+
/** The filechooser for opening and saving object files. */
protected JFileChooser m_FileChooser;
-
+
/** Creates the GUI editor component. */
public GOEPanel() {
-
+
m_Backup = copyObject(m_Object);
-
- m_ClassNameLabel = new JLabel(Messages.getInstance().getString("GenericObjectEditor_GOEPanel_ClassNameLabel_JLabel_Text"));
- m_ClassNameLabel.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
+
+ m_ClassNameLabel = new JLabel(Messages.getInstance().getString(
+ "GenericObjectEditor_GOEPanel_ClassNameLabel_JLabel_Text"));
+ m_ClassNameLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
m_ChildPropertySheet = new PropertySheetPanel();
- m_ChildPropertySheet.addPropertyChangeListener
- (new PropertyChangeListener() {
- public void propertyChange(PropertyChangeEvent evt) {
- m_Support.firePropertyChange("", null, null);
- }
- });
-
- m_OpenBut = new JButton(Messages.getInstance().getString("GenericObjectEditor_OpenBut_JButton_Text"));
- m_OpenBut.setToolTipText(Messages.getInstance().getString("GenericObjectEditor_OpenBut_SetToolTipText_Text"));
+ m_ChildPropertySheet
+ .addPropertyChangeListener(new PropertyChangeListener() {
+ @Override
+ public void propertyChange(PropertyChangeEvent evt) {
+ m_Support.firePropertyChange("", null, null);
+ }
+ });
+
+ m_OpenBut = new JButton(Messages.getInstance().getString(
+ "GenericObjectEditor_OpenBut_JButton_Text"));
+ m_OpenBut.setToolTipText(Messages.getInstance().getString(
+ "GenericObjectEditor_OpenBut_SetToolTipText_Text"));
m_OpenBut.setEnabled(true);
m_OpenBut.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- Object object = openObject();
- if (object != null) {
- // setValue takes care of: Making sure obj is of right type,
- // and firing property change.
- setValue(object);
- // Need a second setValue to get property values filled in OK.
- // Not sure why.
- setValue(object);
- }
- }
- });
-
- m_SaveBut = new JButton(Messages.getInstance().getString("GenericObjectEditor_SaveBut_JButton_Text"));
- m_SaveBut.setToolTipText(Messages.getInstance().getString("GenericObjectEditor_SaveBut_SetToolTipText_Text"));
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ Object object = openObject();
+ if (object != null) {
+ // setValue takes care of: Making sure obj is of right type,
+ // and firing property change.
+ setValue(object);
+ // Need a second setValue to get property values filled in OK.
+ // Not sure why.
+ setValue(object);
+ }
+ }
+ });
+
+ m_SaveBut = new JButton(Messages.getInstance().getString(
+ "GenericObjectEditor_SaveBut_JButton_Text"));
+ m_SaveBut.setToolTipText(Messages.getInstance().getString(
+ "GenericObjectEditor_SaveBut_SetToolTipText_Text"));
m_SaveBut.setEnabled(true);
m_SaveBut.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- saveObject(m_Object);
- }
- });
-
- m_okBut = new JButton(Messages.getInstance().getString("GenericObjectEditor_OkBut_JButton_Text"));
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ saveObject(m_Object);
+ }
+ });
+
+ m_okBut = new JButton(Messages.getInstance().getString(
+ "GenericObjectEditor_OkBut_JButton_Text"));
m_okBut.setEnabled(true);
m_okBut.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
-
- m_Backup = copyObject(m_Object);
- if ((getTopLevelAncestor() != null)
- && (getTopLevelAncestor() instanceof Window)) {
- Window w = (Window) getTopLevelAncestor();
- w.dispose();
- }
- }
- });
-
- m_cancelBut = new JButton(Messages.getInstance().getString("GenericObjectEditor_CancelBut_JButton_Text"));
+ @Override
+ public void actionPerformed(ActionEvent e) {
+
+ m_Backup = copyObject(m_Object);
+ if ((getTopLevelAncestor() != null)
+ && (getTopLevelAncestor() instanceof Window)) {
+ Window w = (Window) getTopLevelAncestor();
+ w.dispose();
+ }
+ }
+ });
+
+ m_cancelBut = new JButton(Messages.getInstance().getString(
+ "GenericObjectEditor_CancelBut_JButton_Text"));
m_cancelBut.setEnabled(true);
m_cancelBut.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- if (m_Backup != null) {
-
- m_Object = copyObject(m_Backup);
-
- // To fire property change
- m_Support.firePropertyChange("", null, null);
- m_ObjectNames = getClassesFromProperties();
- updateObjectNames();
- updateChildPropertySheet();
- }
- if ((getTopLevelAncestor() != null)
- && (getTopLevelAncestor() instanceof Window)) {
- Window w = (Window) getTopLevelAncestor();
- w.dispose();
- }
- }
- });
-
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ if (m_Backup != null) {
+
+ m_Object = copyObject(m_Backup);
+
+ // To fire property change
+ m_Support.firePropertyChange("", null, null);
+ m_ObjectNames = getClassesFromProperties();
+ updateObjectNames();
+ updateChildPropertySheet();
+ }
+ if ((getTopLevelAncestor() != null)
+ && (getTopLevelAncestor() instanceof Window)) {
+ Window w = (Window) getTopLevelAncestor();
+ w.dispose();
+ }
+ }
+ });
+
setLayout(new BorderLayout());
if (m_canChangeClassInDialog) {
- JButton chooseButton = createChooseClassButton();
- JPanel top = new JPanel();
- top.setLayout(new BorderLayout());
- top.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
- top.add(chooseButton, BorderLayout.WEST);
- top.add(m_ClassNameLabel, BorderLayout.CENTER);
- add(top, BorderLayout.NORTH);
+ JButton chooseButton = createChooseClassButton();
+ JPanel top = new JPanel();
+ top.setLayout(new BorderLayout());
+ top.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
+ top.add(chooseButton, BorderLayout.WEST);
+ top.add(m_ClassNameLabel, BorderLayout.CENTER);
+ add(top, BorderLayout.NORTH);
} else {
- add(m_ClassNameLabel, BorderLayout.NORTH);
+ add(m_ClassNameLabel, BorderLayout.NORTH);
}
add(m_ChildPropertySheet, BorderLayout.CENTER);
// Since we resize to the size of the property sheet, a scrollpane isn't
// typically needed
// add(new JScrollPane(m_ChildPropertySheet), BorderLayout.CENTER);
-
+
JPanel okcButs = new JPanel();
okcButs.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
okcButs.setLayout(new GridLayout(1, 4, 5, 5));
@@ -771,84 +876,112 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
add(okcButs, BorderLayout.SOUTH);
if (m_ClassType != null) {
- m_ObjectNames = getClassesFromProperties();
- if (m_Object != null) {
- updateObjectNames();
- updateChildPropertySheet();
- }
+ m_ObjectNames = getClassesFromProperties();
+ if (m_Object != null) {
+ updateObjectNames();
+ updateChildPropertySheet();
+ }
}
}
-
+
/**
* Enables/disables the cancel button.
- *
- * @param flag true to enable cancel button, false
- * to disable it
+ *
+ * @param flag true to enable cancel button, false to disable it
*/
protected void setCancelButton(boolean flag) {
- if(m_cancelBut != null)
- m_cancelBut.setEnabled(flag);
+ if (m_cancelBut != null) {
+ m_cancelBut.setEnabled(flag);
+ }
}
-
+
/**
* Opens an object from a file selected by the user.
*
* @return the loaded object, or null if the operation was cancelled
*/
protected Object openObject() {
-
+
if (m_FileChooser == null) {
- createFileChooser();
+ createFileChooser();
}
int returnVal = m_FileChooser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
- File selected = m_FileChooser.getSelectedFile();
- try {
- ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected)));
- Object obj = oi.readObject();
- oi.close();
- if (!m_ClassType.isAssignableFrom(obj.getClass())) {
- throw new Exception(Messages.getInstance().getString("GenericObjectEditor_OpenObject_Exception_Text") + m_ClassType.getName());
- }
- return obj;
- } catch (Exception ex) {
- JOptionPane.showMessageDialog(this,
- Messages.getInstance().getString("GenericObjectEditor_OpenObject_Exception_JOptionPaneShowMessageDialog_Text")
- + selected.getName()
- + Messages.getInstance().getString("GenericObjectEditor_OpenObject_Exception_JOptionPaneShowMessageDialog_Text") + ex.getMessage(),
- Messages.getInstance().getString("GenericObjectEditor_OpenObject_Exception_JOptionPaneShowMessageDialog_Text"),
- JOptionPane.ERROR_MESSAGE);
- }
+ File selected = m_FileChooser.getSelectedFile();
+ try {
+ ObjectInputStream oi = new ObjectInputStream(new BufferedInputStream(
+ new FileInputStream(selected)));
+ Object obj = oi.readObject();
+ oi.close();
+ if (!m_ClassType.isAssignableFrom(obj.getClass())) {
+ throw new Exception(Messages.getInstance().getString(
+ "GenericObjectEditor_OpenObject_Exception_Text")
+ + m_ClassType.getName());
+ }
+ return obj;
+ } catch (Exception ex) {
+ JOptionPane
+ .showMessageDialog(
+ this,
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_OpenObject_Exception_JOptionPaneShowMessageDialog_Text")
+ + selected.getName()
+ + Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_OpenObject_Exception_JOptionPaneShowMessageDialog_Text")
+ + ex.getMessage(),
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_OpenObject_Exception_JOptionPaneShowMessageDialog_Text"),
+ JOptionPane.ERROR_MESSAGE);
+ }
}
return null;
}
-
+
/**
* Saves an object to a file selected by the user.
*
* @param object the object to save
*/
protected void saveObject(Object object) {
-
+
if (m_FileChooser == null) {
- createFileChooser();
+ createFileChooser();
}
int returnVal = m_FileChooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
- File sFile = m_FileChooser.getSelectedFile();
- try {
- ObjectOutputStream oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile)));
- oo.writeObject(object);
- oo.close();
- } catch (Exception ex) {
- JOptionPane.showMessageDialog(this,
- Messages.getInstance().getString("GenericObjectEditor_SaveObject_Exception_JOptionPaneShowMessageDialog_Text")
- + sFile.getName()
- + Messages.getInstance().getString("GenericObjectEditor_SaveObject_Exception_JOptionPaneShowMessageDialog_Text") + ex.getMessage(),
- Messages.getInstance().getString("GenericObjectEditor_SaveObject_Exception_JOptionPaneShowMessageDialog_Text"),
- JOptionPane.ERROR_MESSAGE);
- }
+ File sFile = m_FileChooser.getSelectedFile();
+ try {
+ ObjectOutputStream oo = new ObjectOutputStream(
+ new BufferedOutputStream(new FileOutputStream(sFile)));
+ oo.writeObject(object);
+ oo.close();
+ } catch (Exception ex) {
+ JOptionPane
+ .showMessageDialog(
+ this,
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_SaveObject_Exception_JOptionPaneShowMessageDialog_Text")
+ + sFile.getName()
+ + Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_SaveObject_Exception_JOptionPaneShowMessageDialog_Text")
+ + ex.getMessage(),
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_SaveObject_Exception_JOptionPaneShowMessageDialog_Text"),
+ JOptionPane.ERROR_MESSAGE);
+ }
}
}
@@ -856,11 +989,11 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
* Creates the file chooser the user will use to save/load files with.
*/
protected void createFileChooser() {
-
+
m_FileChooser = new JFileChooser(new File(System.getProperty("user.dir")));
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
}
-
+
/**
* Makes a copy of an object using serialization.
*
@@ -872,16 +1005,17 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
Object result = null;
try {
result = GenericObjectEditor.this.makeCopy(source);
- setCancelButton(true);
-
+ setCancelButton(true);
+
} catch (Exception ex) {
- setCancelButton(false);
- System.err.println(Messages.getInstance().getString("GenericObjectEditor_CopyObject_Error_Text"));
- System.err.println(ex);
+ setCancelButton(false);
+ System.err.println(Messages.getInstance().getString(
+ "GenericObjectEditor_CopyObject_Error_Text"));
+ System.err.println(ex);
}
return result;
}
-
+
/**
* Allows customization of the action label on the dialog.
*
@@ -892,7 +1026,7 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
m_okBut.setText(newLabel);
}
- /**
+ /**
* This is used to hook an action listener to the ok button.
*
* @param a The action listener.
@@ -901,7 +1035,7 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
m_okBut.addActionListener(a);
}
-
+
/**
* This is used to hook an action listener to the cancel button.
*
@@ -911,7 +1045,7 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
m_cancelBut.addActionListener(a);
}
-
+
/**
* This is used to remove an action listener from the ok button.
*
@@ -921,7 +1055,7 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
m_okBut.removeActionListener(a);
}
-
+
/**
* This is used to remove an action listener from the cancel button.
*
@@ -931,16 +1065,17 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
m_cancelBut.removeActionListener(a);
}
-
+
/**
* Updates the child property sheet, and creates if needed.
*/
public void updateChildPropertySheet() {
-
+
// Update the object name displayed
- String className = Messages.getInstance().getString("GenericObjectEditor_UpdateChildPropertySheet_ClassName_Text");
+ String className = Messages.getInstance().getString(
+ "GenericObjectEditor_UpdateChildPropertySheet_ClassName_Text");
if (m_Object != null) {
- className = m_Object.getClass().getName();
+ className = m_Object.getClass().getName();
}
m_ClassNameLabel.setText(className);
@@ -949,10 +1084,10 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
// Adjust size of containing window if possible
if ((getTopLevelAncestor() != null)
- && (getTopLevelAncestor() instanceof Window)) {
- ((Window) getTopLevelAncestor()).pack();
+ && (getTopLevelAncestor() instanceof Window)) {
+ ((Window) getTopLevelAncestor()).pack();
}
- }
+ }
}
/**
@@ -964,60 +1099,67 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
}
/**
- * Constructor that allows specifying whether it is possible
- * to change the class within the editor dialog.
- *
+ * Constructor that allows specifying whether it is possible to change the
+ * class within the editor dialog.
+ *
* @param canChangeClassInDialog whether the user can change the class
*/
public GenericObjectEditor(boolean canChangeClassInDialog) {
m_canChangeClassInDialog = canChangeClassInDialog;
}
-
+
/**
* registers all the editors in Weka.
*/
public static void registerEditors() {
- Properties props;
- Enumeration enm;
- String name;
- String value;
- Class baseCls;
- Class cls;
-
- if (m_EditorsRegistered)
+ Properties props;
+ Enumeration enm;
+ String name;
+ String value;
+ Class baseCls;
+ Class cls;
+
+ if (m_EditorsRegistered) {
return;
-
- System.err.println(Messages.getInstance().getString("GenericObjectEditor_RegisterEditors_Error_Text"));
+ }
+
+ System.err.println(Messages.getInstance().getString(
+ "GenericObjectEditor_RegisterEditors_Error_Text"));
m_EditorsRegistered = true;
// load properties
try {
props = Utils.readProperties(GUIEDITORS_PROPERTY_FILE);
- }
- catch (Exception e) {
+ } catch (Exception e) {
props = new Properties();
e.printStackTrace();
}
-
+
enm = props.propertyNames();
while (enm.hasMoreElements()) {
- name = enm.nextElement().toString();
+ name = enm.nextElement().toString();
value = props.getProperty(name, "");
try {
- // array class?
- if (name.endsWith("[]")) {
- baseCls = Class.forName(name.substring(0, name.indexOf("[]")));
- cls = Array.newInstance(baseCls, 1).getClass();
- }
- else {
- cls = Class.forName(name);
- }
- // register
- PropertyEditorManager.registerEditor(cls, Class.forName(value));
- }
- catch (Exception e) {
- System.err.println(Messages.getInstance().getString("GenericObjectEditor_RegisterEditors_Exception_Error_Text_First") + name + Messages.getInstance().getString("GenericObjectEditor_RegisterEditors_Exception_Error_Text_Second") + value + Messages.getInstance().getString("GenericObjectEditor_RegisterEditors_Exception_Error_Text_Third") + e);
+ // array class?
+ if (name.endsWith("[]")) {
+ baseCls = Class.forName(name.substring(0, name.indexOf("[]")));
+ cls = Array.newInstance(baseCls, 1).getClass();
+ } else {
+ cls = Class.forName(name);
+ }
+ // register
+ PropertyEditorManager.registerEditor(cls, Class.forName(value));
+ } catch (Exception e) {
+ System.err.println(Messages.getInstance().getString(
+ "GenericObjectEditor_RegisterEditors_Exception_Error_Text_First")
+ + name
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_RegisterEditors_Exception_Error_Text_Second")
+ + value
+ + Messages.getInstance().getString(
+ "GenericObjectEditor_RegisterEditors_Exception_Error_Text_Third")
+ + e);
}
}
}
@@ -1025,134 +1167,136 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Sets whether the user can change the class in the dialog.
*
- * @param value if true then the user can change the class
+ * @param value if true then the user can change the class
*/
public void setCanChangeClassInDialog(boolean value) {
m_canChangeClassInDialog = value;
}
-
+
/**
* Returns whether the user can change the class in the dialog.
*
- * @return true if the user can change the class
+ * @return true if the user can change the class
*/
public boolean getCanChangeClassInDialog() {
return m_canChangeClassInDialog;
}
-
+
/**
- * Returns the backup object (may be null if there is no
- * backup.
- *
+ * Returns the backup object (may be null if there is no backup.
+ *
* @return the backup object
*/
public Object getBackup() {
return m_Backup;
}
-
+
/**
- * returns the name of the root element of the given class name,
+ * returns the name of the root element of the given class name,
* <code>null</code> if it doesn't contain the separator.
*
* @param clsname the full classname
- * @param separator the separator
+ * @param separator the separator
* @return string the root element
*/
protected static String getRootFromClass(String clsname, String separator) {
- if (clsname.indexOf(separator) > -1)
+ if (clsname.indexOf(separator) > -1) {
return clsname.substring(0, clsname.indexOf(separator));
- else
+ } else {
return null;
+ }
}
-
+
/**
- * parses the given string of classes separated by ", " and returns the
- * a hashtable with as many entries as there are different root elements in
- * the class names (the key is the root element). E.g. if there's only
- * "weka." as the prefix for all classes the a hashtable of size 1 is returned.
- * if NULL is the input, then NULL is also returned.
+ * parses the given string of classes separated by ", " and returns the a
+ * hashtable with as many entries as there are different root elements in the
+ * class names (the key is the root element). E.g. if there's only "weka." as
+ * the prefix for all classes the a hashtable of size 1 is returned. if NULL
+ * is the input, then NULL is also returned.
*
* @param classes the classnames to work on
- * @return for each distinct root element in the classnames, one entry in
- * the hashtable (with the root element as key)
+ * @return for each distinct root element in the classnames, one entry in the
+ * hashtable (with the root element as key)
*/
public static Hashtable sortClassesByRoot(String classes) {
- Hashtable roots;
- Hashtable result;
- Enumeration enm;
- int i;
- StringTokenizer tok;
- String clsname;
- Vector list;
- HierarchyPropertyParser hpp;
- String separator;
- String root;
- String tmpStr;
-
- if (classes == null)
+ Hashtable roots;
+ Hashtable result;
+ Enumeration enm;
+ int i;
+ StringTokenizer tok;
+ String clsname;
+ Vector list;
+ HierarchyPropertyParser hpp;
+ String separator;
+ String root;
+ String tmpStr;
+
+ if (classes == null) {
return null;
-
- roots = new Hashtable();
- hpp = new HierarchyPropertyParser();
+ }
+
+ roots = new Hashtable();
+ hpp = new HierarchyPropertyParser();
separator = hpp.getSeperator();
-
+
// go over all classnames and store them in the hashtable, with the
// root element as the key
- tok = new StringTokenizer(classes, ", ");
+ tok = new StringTokenizer(classes, ", ");
while (tok.hasMoreElements()) {
clsname = tok.nextToken();
- root = getRootFromClass(clsname, separator);
- if (root == null)
+ root = getRootFromClass(clsname, separator);
+ if (root == null) {
continue;
-
+ }
+
// already stored?
if (!roots.containsKey(root)) {
list = new Vector();
roots.put(root, list);
- }
- else {
+ } else {
list = (Vector) roots.get(root);
}
-
+
list.add(clsname);
}
-
+
// build result
result = new Hashtable();
- enm = roots.keys();
+ enm = roots.keys();
while (enm.hasMoreElements()) {
root = (String) enm.nextElement();
list = (Vector) roots.get(root);
tmpStr = "";
for (i = 0; i < list.size(); i++) {
- if (i > 0)
+ if (i > 0) {
tmpStr += ",";
+ }
tmpStr += (String) list.get(i);
}
result.put(root, tmpStr);
}
-
+
return result;
}
- /**
- * Called when the class of object being edited changes.
+ /**
+ * Called when the class of object being edited changes.
*
* @return the hashtable containing the HierarchyPropertyParsers for the root
* elements
*/
- protected Hashtable getClassesFromProperties() {
+ protected Hashtable getClassesFromProperties() {
Hashtable hpps = new Hashtable();
String className = m_ClassType.getName();
- Hashtable typeOptions = sortClassesByRoot(EDITOR_PROPERTIES.getProperty(className));
+ Hashtable typeOptions = sortClassesByRoot(EDITOR_PROPERTIES
+ .getProperty(className));
if (typeOptions == null) {
/*
- System.err.println("Warning: No configuration property found in\n"
- + PROPERTY_FILE + "\n"
- + "for " + className);
- */
- } else {
+ * System.err.println("Warning: No configuration property found in\n" +
+ * PROPERTY_FILE + "\n" + "for " + className);
+ */
+ } else {
try {
Enumeration enm = typeOptions.keys();
while (enm.hasMoreElements()) {
@@ -1160,138 +1304,150 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
String typeOption = (String) typeOptions.get(root);
HierarchyPropertyParser hpp = new HierarchyPropertyParser();
hpp.build(typeOption, ", ");
- hpps.put(root, hpp);
+ hpps.put(root, hpp);
}
} catch (Exception ex) {
- System.err.println(Messages.getInstance().getString("GenericObjectEditor_GetClassesFromProperties_Exception_Error_Text") + typeOptions);
- }
+ System.err.println(Messages.getInstance().getString(
+ "GenericObjectEditor_GetClassesFromProperties_Exception_Error_Text")
+ + typeOptions);
+ }
}
return hpps;
}
-
+
/**
- * Updates the list of selectable object names, adding any new names to the list.
+ * Updates the list of selectable object names, adding any new names to the
+ * list.
*/
protected void updateObjectNames() {
-
+
if (m_ObjectNames == null) {
m_ObjectNames = getClassesFromProperties();
}
-
+
if (m_Object != null) {
String className = m_Object.getClass().getName();
- String root = getRootFromClass(className, new HierarchyPropertyParser().getSeperator());
- HierarchyPropertyParser hpp = (HierarchyPropertyParser) m_ObjectNames.get(root);
+ String root = getRootFromClass(className,
+ new HierarchyPropertyParser().getSeperator());
+ HierarchyPropertyParser hpp = (HierarchyPropertyParser) m_ObjectNames
+ .get(root);
if (hpp != null) {
- if(!hpp.contains(className)){
+ if (!hpp.contains(className)) {
hpp.add(className);
}
}
}
}
-
+
/**
- * Sets whether the editor is "enabled", meaning that the current
- * values will be painted.
- *
+ * Sets whether the editor is "enabled", meaning that the current values will
+ * be painted.
+ *
* @param newVal a value of type 'boolean'
*/
public void setEnabled(boolean newVal) {
-
+
if (newVal != m_Enabled) {
m_Enabled = newVal;
}
}
-
+
/**
* Sets the class of values that can be edited.
- *
+ *
* @param type a value of type 'Class'
*/
public void setClassType(Class type) {
-
+
m_ClassType = type;
m_ObjectNames = getClassesFromProperties();
}
-
+
/**
- * Sets the current object to be the default, taken as the first item in
- * the chooser.
+ * Sets the current object to be the default, taken as the first item in the
+ * chooser.
*/
public void setDefaultValue() {
-
+
if (m_ClassType == null) {
- System.err.println(Messages.getInstance().getString("GenericObjectEditor_SetDefaultValue_Error_Text"));
+ System.err.println(Messages.getInstance().getString(
+ "GenericObjectEditor_SetDefaultValue_Error_Text"));
return;
- }
-
+ }
+
Hashtable hpps = getClassesFromProperties();
HierarchyPropertyParser hpp = null;
Enumeration enm = hpps.elements();
-
- try{
+
+ try {
while (enm.hasMoreElements()) {
- hpp = (HierarchyPropertyParser) enm.nextElement();
- if(hpp.depth() > 0) {
+ hpp = (HierarchyPropertyParser) enm.nextElement();
+ if (hpp.depth() > 0) {
hpp.goToRoot();
- while(!hpp.isLeafReached())
+ while (!hpp.isLeafReached()) {
hpp.goToChild(0);
-
+ }
+
String defaultValue = hpp.fullValue();
setValue(Class.forName(defaultValue).newInstance());
}
}
- }catch(Exception ex){
- System.err.println(Messages.getInstance().getString("GenericObjectEditor_SetDefaultValue_Exception_Error_Text") +
- hpp.fullValue());
+ } catch (Exception ex) {
+ System.err.println(Messages.getInstance().getString(
+ "GenericObjectEditor_SetDefaultValue_Exception_Error_Text")
+ + hpp.fullValue());
ex.printStackTrace();
}
}
-
+
/**
- * Sets the current Object. If the Object is in the
- * Object chooser, this becomes the selected item (and added
- * to the chooser if necessary).
- *
+ * Sets the current Object. If the Object is in the Object chooser, this
+ * becomes the selected item (and added to the chooser if necessary).
+ *
* @param o an object that must be a Object.
*/
+ @Override
public void setValue(Object o) {
-
+
if (m_ClassType == null) {
- System.err.println(Messages.getInstance().getString("GenericObjectEditor_SetValue_Error_Text_First"));
+ System.err.println(Messages.getInstance().getString(
+ "GenericObjectEditor_SetValue_Error_Text_First"));
return;
}
if (!m_ClassType.isAssignableFrom(o.getClass())) {
- System.err.println(Messages.getInstance().getString("GenericObjectEditor_SetValue_Error_Text_Second"));
+ System.err.println(Messages.getInstance().getString(
+ "GenericObjectEditor_SetValue_Error_Text_Second"));
return;
}
-
+
setObject(o);
- if (m_EditorComponent != null) m_EditorComponent.repaint();
+ if (m_EditorComponent != null) {
+ m_EditorComponent.repaint();
+ }
updateObjectNames();
}
-
+
/**
* Sets the current Object.
- *
+ *
* @param c a value of type 'Object'
*/
protected void setObject(Object c) {
-
+
// This should really call equals() for comparison.
- boolean trueChange ;
+ boolean trueChange;
if (getValue() != null) {
trueChange = (!c.equals(getValue()));
- }
- else
+ } else {
trueChange = true;
-
+ }
+
m_Backup = m_Object;
-
+
m_Object = c;
-
+
if (m_EditorComponent != null) {
m_EditorComponent.updateChildPropertySheet();
}
@@ -1299,14 +1455,15 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
m_Support.firePropertyChange("", null, null);
}
}
-
+
/**
* Gets the current Object.
- *
+ *
* @return the current Object
*/
+ @Override
public Object getValue() {
-
+
Object result = null;
try {
result = makeCopy(m_Object);
@@ -1315,26 +1472,27 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
}
return result;
}
-
+
/**
- * Supposedly returns an initialization string to create a Object
- * identical to the current one, including it's state, but this doesn't
- * appear possible given that the initialization string isn't supposed to
- * contain multiple statements.
- *
+ * Supposedly returns an initialization string to create a Object identical to
+ * the current one, including it's state, but this doesn't appear possible
+ * given that the initialization string isn't supposed to contain multiple
+ * statements.
+ *
* @return the java source code initialisation string
*/
+ @Override
public String getJavaInitializationString() {
return "new " + m_Object.getClass().getName() + "()";
}
/**
- * Returns true to indicate that we can paint a representation of the
- * Object.
- *
+ * Returns true to indicate that we can paint a representation of the Object.
+ *
* @return true
*/
+ @Override
public boolean isPaintable() {
return true;
@@ -1342,29 +1500,29 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Paints a representation of the current Object.
- *
+ *
* @param gfx the graphics context to use
* @param box the area we are allowed to paint into
*/
+ @Override
public void paintValue(java.awt.Graphics gfx, java.awt.Rectangle box) {
if (m_Enabled) {
String rep;
if (m_Object != null) {
- rep = m_Object.getClass().getName();
+ rep = m_Object.getClass().getName();
} else {
- rep = Messages.getInstance().getString("GenericObjectEditor_PaintValue_Rep_Text");
+ rep = Messages.getInstance().getString(
+ "GenericObjectEditor_PaintValue_Rep_Text");
}
int dotPos = rep.lastIndexOf('.');
if (dotPos != -1) {
- rep = rep.substring(dotPos + 1);
+ rep = rep.substring(dotPos + 1);
}
/*
- if (m_Object instanceof OptionHandler) {
- rep += " " + Utils.joinOptions(((OptionHandler)m_Object)
- .getOptions());
- }
- */
+ * if (m_Object instanceof OptionHandler) { rep += " " +
+ * Utils.joinOptions(((OptionHandler)m_Object) .getOptions()); }
+ */
java.awt.Font originalFont = gfx.getFont();
gfx.setFont(originalFont.deriveFont(java.awt.Font.BOLD));
@@ -1375,29 +1533,32 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
gfx.setFont(originalFont);
if (m_Object instanceof OptionHandler) {
- gfx.drawString(" " + Utils.joinOptions(((OptionHandler)m_Object).getOptions()),
- repwidth + 2, fm.getAscent() + vpad);
+ gfx.drawString(
+ " " + Utils.joinOptions(((OptionHandler) m_Object).getOptions()),
+ repwidth + 2, fm.getAscent() + vpad);
}
}
}
/**
* Returns null as we don't support getting/setting values as text.
- *
+ *
* @return null
*/
+ @Override
public String getAsText() {
return null;
}
/**
- * Returns null as we don't support getting/setting values as text.
- *
+ * Returns null as we don't support getting/setting values as text.
+ *
* @param text the text value
- * @throws IllegalArgumentException as we don't support
- * getting/setting values as text.
+ * @throws IllegalArgumentException as we don't support getting/setting values
+ * as text.
*/
+ @Override
public void setAsText(String text) {
throw new IllegalArgumentException(text);
@@ -1405,9 +1566,10 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Returns null as we don't support getting values as tags.
- *
+ *
* @return null
*/
+ @Override
public String[] getTags() {
return null;
@@ -1415,19 +1577,21 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Returns true because we do support a custom editor.
- *
+ *
* @return true
*/
+ @Override
public boolean supportsCustomEditor() {
return true;
}
-
+
/**
* Returns the array editing component.
- *
+ *
* @return a value of type 'java.awt.Component'
*/
+ @Override
public java.awt.Component getCustomEditor() {
if (m_EditorComponent == null) {
@@ -1438,9 +1602,10 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Adds a PropertyChangeListener who will be notified of value changes.
- *
+ *
* @param l a value of type 'PropertyChangeListener'
*/
+ @Override
public void addPropertyChangeListener(PropertyChangeListener l) {
m_Support.addPropertyChangeListener(l);
@@ -1448,9 +1613,10 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Removes a PropertyChangeListener.
- *
+ *
* @param l a value of type 'PropertyChangeListener'
*/
+ @Override
public void removePropertyChangeListener(PropertyChangeListener l) {
m_Support.removePropertyChangeListener(l);
@@ -1458,14 +1624,16 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Gets the custom panel used for editing the object.
- *
+ *
* @return the panel
*/
+ @Override
public JPanel getCustomPanel() {
- final JButton chooseButton = createChooseClassButton();
+ final JButton chooseButton = createChooseClassButton();
m_ObjectPropertyPanel = new PropertyPanel(this, true);
-
+
JPanel customPanel = new JPanel() {
+ @Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
chooseButton.setEnabled(enabled);
@@ -1478,31 +1646,33 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
}
/**
- * Creates a button that when clicked will enable the user to change
- * the class of the object being edited.
+ * Creates a button that when clicked will enable the user to change the class
+ * of the object being edited.
*
* @return the choose button
*/
protected JButton createChooseClassButton() {
- JButton setButton = new JButton(Messages.getInstance().getString("GenericObjectEditor_CreateChooseClassButton_SetButton_JButton_Text"));
+ JButton setButton = new JButton(Messages.getInstance().getString(
+ "GenericObjectEditor_CreateChooseClassButton_SetButton_JButton_Text"));
// anonymous action listener shows a JTree popup and allows the user
// to choose the class they want
setButton.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
-
- JPopupMenu popup = getChooseClassPopupMenu();
-
- // show the popup where the source component is
- if (e.getSource() instanceof Component) {
- Component comp = (Component) e.getSource();
- popup.show(comp, comp.getX(), comp.getY());
- popup.pack();
- popup.repaint();
- }
- }
- });
+ @Override
+ public void actionPerformed(ActionEvent e) {
+
+ JPopupMenu popup = getChooseClassPopupMenu();
+
+ // show the popup where the source component is
+ if (e.getSource() instanceof Component) {
+ Component comp = (Component) e.getSource();
+ popup.show(comp, comp.getX(), comp.getY());
+ popup.pack();
+ popup.repaint();
+ }
+ }
+ });
return setButton;
}
@@ -1510,30 +1680,32 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* creates a classname from the given path.
*
- * @param path the path to generate the classname from
- * @return the generated classname
+ * @param path the path to generate the classname from
+ * @return the generated classname
*/
protected String getClassnameFromPath(TreePath path) {
StringBuffer classname = new StringBuffer();
-
+
// recreate class name from path
int start = 0;
- if (m_ObjectNames.size() > 1)
+ if (m_ObjectNames.size() > 1) {
start = 1;
+ }
for (int i = start; i < path.getPathCount(); i++) {
- if (i>start) classname.append(".");
- classname.append(
- (String) ((GOETreeNode) path.getPathComponent(i)).getUserObject());
+ if (i > start) {
+ classname.append(".");
+ }
+ classname.append((String) ((GOETreeNode) path.getPathComponent(i))
+ .getUserObject());
}
-
+
return classname.toString();
}
-
+
/**
- * Returns a popup menu that allows the user to change
- * the class of object.
- *
+ * Returns a popup menu that allows the user to change the class of object.
+ *
* @return a JPopupMenu that when shown will let the user choose the class
*/
public JPopupMenu getChooseClassPopupMenu() {
@@ -1546,51 +1718,54 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
if (m_treeNodeOfCurrentObject != null) {
tree.setSelectionPath(new TreePath(m_treeNodeOfCurrentObject.getPath()));
}
- tree.getSelectionModel().setSelectionMode
- (TreeSelectionModel.SINGLE_TREE_SELECTION);
+ tree.getSelectionModel().setSelectionMode(
+ TreeSelectionModel.SINGLE_TREE_SELECTION);
// create the popup
final JPopupMenu popup = new JTreePopupMenu(tree);
// respond when the user chooses a class
tree.addTreeSelectionListener(new TreeSelectionListener() {
- public void valueChanged(TreeSelectionEvent e) {
- GOETreeNode node = (GOETreeNode) tree.getLastSelectedPathComponent();
-
- if (node == null)
- return;
-
- if (node.isLeaf()) {
- /*if (node.m_Capabilities != null && m_CapabilitiesFilter != null) {
- if (!node.m_Capabilities.supportsMaybe(m_CapabilitiesFilter) &&
- !node.m_Capabilities.supports(m_CapabilitiesFilter)) {
- return;
- }
- } */
- classSelected(getClassnameFromPath(tree.getSelectionPath()));
- popup.setVisible(false);
- }
- }
- });
-
+ @Override
+ public void valueChanged(TreeSelectionEvent e) {
+ GOETreeNode node = (GOETreeNode) tree.getLastSelectedPathComponent();
+
+ if (node == null) {
+ return;
+ }
+
+ if (node.isLeaf()) {
+ /*
+ * if (node.m_Capabilities != null && m_CapabilitiesFilter != null) {
+ * if (!node.m_Capabilities.supportsMaybe(m_CapabilitiesFilter) &&
+ * !node.m_Capabilities.supports(m_CapabilitiesFilter)) { return; } }
+ */
+ classSelected(getClassnameFromPath(tree.getSelectionPath()));
+ popup.setVisible(false);
+ }
+ }
+ });
+
return popup;
}
/**
* Creates a JTree from an object heirarchy.
- *
+ *
* @param hpps the hierarchy of objects to mirror in the tree
* @return a JTree representation of the hierarchy
*/
protected JTree createTree(Hashtable hpps) {
- GOETreeNode superRoot;
- Enumeration enm;
+ GOETreeNode superRoot;
+ Enumeration enm;
HierarchyPropertyParser hpp;
-
- if (hpps.size() > 1)
- superRoot = new GOETreeNode(Messages.getInstance().getString("GenericObjectEditor_CreateTree_GOETreeNode_Text"));
- else
+
+ if (hpps.size() > 1) {
+ superRoot = new GOETreeNode(Messages.getInstance().getString(
+ "GenericObjectEditor_CreateTree_GOETreeNode_Text"));
+ } else {
superRoot = null;
+ }
enm = hpps.elements();
while (enm.hasMoreElements()) {
@@ -1598,40 +1773,76 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
hpp.goToRoot();
GOETreeNode root = new GOETreeNode(hpp.getValue());
addChildrenToTree(root, hpp);
-
- if (superRoot == null)
+
+ if (superRoot == null) {
superRoot = root;
- else
+ } else {
superRoot.add(root);
+ }
}
-
- JTree tree = new JTree(superRoot);
-
+
+ JTree tree = new JTree(superRoot) {
+
+ /** For serialization */
+ private static final long serialVersionUID = 6991903188102450549L;
+
+ @Override
+ public String getToolTipText(MouseEvent e) {
+ if ((getRowForLocation(e.getX(), e.getY())) == -1) {
+ return null;
+ }
+ TreePath currPath = getPathForLocation(e.getX(), e.getY());
+ if (currPath.getLastPathComponent() instanceof DefaultMutableTreeNode) {
+ DefaultMutableTreeNode node = (DefaultMutableTreeNode) currPath
+ .getLastPathComponent();
+
+ if (node.isLeaf()) {
+
+ return ((GOETreeNode) node).getToolTipText();
+ }
+ }
+ return null;
+ }
+ };
+ tree.setToolTipText("");
+
return tree;
}
/**
- * Recursively builds a JTree from an object heirarchy.
- * Also updates m_treeNodeOfCurrentObject if the current object
- * is discovered during creation.
- *
+ * Recursively builds a JTree from an object heirarchy. Also updates
+ * m_treeNodeOfCurrentObject if the current object is discovered during
+ * creation.
+ *
* @param tree the root of the tree to add children to
* @param hpp the hierarchy of objects to mirror in the tree
*/
- protected void addChildrenToTree(GOETreeNode tree,
- HierarchyPropertyParser hpp) {
+ protected void addChildrenToTree(GOETreeNode tree, HierarchyPropertyParser hpp) {
try {
- for (int i=0; i<hpp.numChildren(); i++) {
- hpp.goToChild(i);
- GOETreeNode child = new GOETreeNode(hpp.getValue());
- if ((m_Object != null) &&
- m_Object.getClass().getName().equals(hpp.fullValue())) {
- m_treeNodeOfCurrentObject = child;
- }
- tree.add(child);
- addChildrenToTree(child, hpp);
- hpp.goToParent();
+ for (int i = 0; i < hpp.numChildren(); i++) {
+ hpp.goToChild(i);
+ GOETreeNode child = new GOETreeNode(hpp.getValue());
+ if ((m_Object != null)
+ && m_Object.getClass().getName().equals(hpp.fullValue())) {
+ m_treeNodeOfCurrentObject = child;
+ }
+ tree.add(child);
+
+ if (hpp.isLeafReached()) {
+ String algName = hpp.fullValue();
+ try {
+ Object alg = Class.forName(algName).newInstance();
+ String toolTip = Utils.getGlobalInfo(alg, true);
+ if (toolTip != null) {
+ child.setToolTipText(toolTip);
+ }
+ } catch (Exception ex) {
+ }
+ }
+
+ addChildrenToTree(child, hpp);
+ hpp.goToParent();
}
} catch (Exception e) {
e.printStackTrace();
@@ -1640,59 +1851,72 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
/**
* Called when the user selects an class type to change to.
- *
+ *
* @param className the name of the class that was selected
*/
protected void classSelected(String className) {
- try {
+ try {
if ((m_Object != null) && m_Object.getClass().getName().equals(className)) {
- return;
+ return;
}
-
+
setValue(Class.forName(className).newInstance());
- //m_ObjectPropertyPanel.showPropertyDialog();
+ // m_ObjectPropertyPanel.showPropertyDialog();
if (m_EditorComponent != null) {
- m_EditorComponent.updateChildPropertySheet();
+ m_EditorComponent.updateChildPropertySheet();
}
} catch (Exception ex) {
- JOptionPane.showMessageDialog(null,
- Messages.getInstance().getString("GenericObjectEditor_ClassSelected_Exception_JOptionPaneShowMessageDialog_Text_First")
- + className + Messages.getInstance().getString("GenericObjectEditor_ClassSelected_Exception_JOptionPaneShowMessageDialog_Text_Second"),
- Messages.getInstance().getString("GenericObjectEditor_ClassSelected_Exception_JOptionPaneShowMessageDialog_Text_Third"),
- JOptionPane.ERROR_MESSAGE);
+ JOptionPane
+ .showMessageDialog(
+ null,
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_ClassSelected_Exception_JOptionPaneShowMessageDialog_Text_First")
+ + className
+ + Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_ClassSelected_Exception_JOptionPaneShowMessageDialog_Text_Second"),
+ Messages
+ .getInstance()
+ .getString(
+ "GenericObjectEditor_ClassSelected_Exception_JOptionPaneShowMessageDialog_Text_Third"),
+ JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
try {
- if(m_Backup != null)
- setValue(m_Backup);
- else
- setDefaultValue();
- } catch(Exception e) {
- System.err.println(ex.getMessage());
- ex.printStackTrace();
+ if (m_Backup != null) {
+ setValue(m_Backup);
+ } else {
+ setDefaultValue();
+ }
+ } catch (Exception e) {
+ System.err.println(ex.getMessage());
+ ex.printStackTrace();
}
}
}
-
+
/**
* Sets the capabilities to use for filtering.
*
- * @param value the object to get the filter capabilities from
+ * @param value the object to get the filter capabilities from
*/
public void setCapabilitiesFilter(Capabilities value) {
m_CapabilitiesFilter = new Capabilities(null);
m_CapabilitiesFilter.assign(value);
}
-
+
/**
* Returns the current Capabilities filter, can be null.
*
- * @return the current Capabiliities used for filtering
+ * @return the current Capabiliities used for filtering
*/
public Capabilities getCapabilitiesFilter() {
return m_CapabilitiesFilter;
}
-
+
/**
* Removes the current Capabilities filter.
*/
@@ -1712,69 +1936,71 @@ public class GenericObjectEditor implements PropertyEditor, CustomPanelSupplier
Object result = so.getObject();
return result;
}
-
+
/**
- * Returns the available classnames for a certain property in the
- * props file.
+ * Returns the available classnames for a certain property in the props file.
*
- * @param property the property to get the classnames for
- * @return the classnames
+ * @param property the property to get the classnames for
+ * @return the classnames
*/
public static Vector<String> getClassnames(String property) {
- Vector<String> result;
- String value;
- String[] items;
- int i;
-
+ Vector<String> result;
+ String value;
+ String[] items;
+ int i;
+
result = new Vector<String>();
-
- value = EDITOR_PROPERTIES.getProperty(property, "").replaceAll(" ", "").trim();
+
+ value = EDITOR_PROPERTIES.getProperty(property, "").replaceAll(" ", "")
+ .trim();
if (value.length() > 0) {
items = value.split(",");
- for (i = 0; i < items.length; i++)
- result.add(items[i]);
+ for (i = 0; i < items.length; i++) {
+ result.add(items[i]);
+ }
}
-
+
return result;
}
/**
* Tests out the Object editor from the command line.
- *
+ *
* @param args may contain the class name of a Object to edit
*/
- public static void main(String [] args) {
+ public static void main(String[] args) {
try {
GenericObjectEditor.registerEditors();
GenericObjectEditor ce = new GenericObjectEditor(true);
ce.setClassType(weka.classifiers.Classifier.class);
Object initial = new weka.classifiers.rules.ZeroR();
- if (args.length > 0){
- ce.setClassType(Class.forName(args[0]));
- if(args.length > 1){
- initial = (Object)Class.forName(args[1]).newInstance();
- ce.setValue(initial);
- }
- else
- ce.setDefaultValue();
+ if (args.length > 0) {
+ ce.setClassType(Class.forName(args[0]));
+ if (args.length > 1) {
+ initial = Class.forName(args[1]).newInstance();
+ ce.setValue(initial);
+ } else {
+ ce.setDefaultValue();
+ }
+ } else {
+ ce.setValue(initial);
}
- else
- ce.setValue(initial);
-
+
PropertyDialog pd = new PropertyDialog((Frame) null, ce, 100, 100);
pd.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- PropertyEditor pe = ((PropertyDialog)e.getSource()).getEditor();
- Object c = (Object)pe.getValue();
- String options = "";
- if (c instanceof OptionHandler) {
- options = Utils.joinOptions(((OptionHandler)c).getOptions());
- }
- System.out.println(c.getClass().getName() + " " + options);
- System.exit(0);
- }
- });
+ @Override
+ public void windowClosing(WindowEvent e) {
+ PropertyEditor pe = ((PropertyDialog) e.getSource()).getEditor();
+ Object c = pe.getValue();
+ String options = "";
+ if (c instanceof OptionHandler) {
+ options = Utils.joinOptions(((OptionHandler) c).getOptions());
+ }
+ System.out.println(c.getClass().getName() + " " + options);
+ System.exit(0);
+ }
+ });
pd.setVisible(true);
} catch (Exception ex) {
ex.printStackTrace();
diff --git a/src/main/java/weka/gui/Main.java b/src/main/java/weka/gui/Main.java
index 4647659..14ea0a3 100644
--- a/src/main/java/weka/gui/Main.java
+++ b/src/main/java/weka/gui/Main.java
@@ -22,35 +22,6 @@
package weka.gui;
-import weka.classifiers.bayes.net.GUI;
-import weka.classifiers.evaluation.ThresholdCurve;
-import weka.core.Copyright;
-import weka.core.Instances;
-import weka.core.Memory;
-import weka.core.Option;
-import weka.core.OptionHandler;
-import weka.core.SelectedTag;
-import weka.core.SystemInfo;
-import weka.core.Tag;
-import weka.core.Utils;
-import weka.core.Version;
-import weka.gui.arffviewer.ArffViewerMainPanel;
-import weka.gui.beans.KnowledgeFlowApp;
-import weka.gui.beans.StartUpListener;
-import weka.gui.boundaryvisualizer.BoundaryVisualizer;
-import weka.gui.experiment.Experimenter;
-import weka.gui.explorer.Explorer;
-import weka.gui.graphvisualizer.GraphVisualizer;
-import weka.gui.sql.SqlViewer;
-import weka.gui.treevisualizer.Node;
-import weka.gui.treevisualizer.NodePlace;
-import weka.gui.treevisualizer.PlaceNode2;
-import weka.gui.treevisualizer.TreeBuild;
-import weka.gui.treevisualizer.TreeVisualizer;
-import weka.gui.visualize.PlotData2D;
-import weka.gui.visualize.ThresholdVisualizePanel;
-import weka.gui.visualize.VisualizePanel;
-
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
@@ -98,204 +69,237 @@ import javax.swing.WindowConstants;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
+import weka.classifiers.bayes.net.GUI;
+import weka.classifiers.evaluation.ThresholdCurve;
+import weka.core.Copyright;
+import weka.core.Instances;
+import weka.core.Memory;
+import weka.core.Option;
+import weka.core.OptionHandler;
+import weka.core.SelectedTag;
+import weka.core.SystemInfo;
+import weka.core.Tag;
+import weka.core.Utils;
+import weka.core.Version;
+import weka.gui.arffviewer.ArffViewerMainPanel;
+import weka.gui.beans.KnowledgeFlowApp;
+import weka.gui.beans.StartUpListener;
+import weka.gui.boundaryvisualizer.BoundaryVisualizer;
+import weka.gui.experiment.Experimenter;
+import weka.gui.explorer.Explorer;
+import weka.gui.graphvisualizer.GraphVisualizer;
+import weka.gui.sql.SqlViewer;
+import weka.gui.treevisualizer.Node;
+import weka.gui.treevisualizer.NodePlace;
+import weka.gui.treevisualizer.PlaceNode2;
+import weka.gui.treevisualizer.TreeBuild;
+import weka.gui.treevisualizer.TreeVisualizer;
+import weka.gui.visualize.PlotData2D;
+import weka.gui.visualize.ThresholdVisualizePanel;
+import weka.gui.visualize.VisualizePanel;
+
/**
* Menu-based GUI for Weka, replacement for the GUIChooser.
- *
- <!-- options-start -->
- * Valid options are: <p/>
*
- * <pre> -gui <MDI|SDI>
+ * <!-- options-start --> Valid options are:
+ * <p/>
+ *
+ * <pre>
+ * -gui <MDI|SDI>
* Determines the layout of the GUI:
* MDI = MDI Layout
* SDI = SDI Layout
- * (default: MDI)</pre>
+ * (default: MDI)
+ * </pre>
*
- <!-- options-end -->
- *
- * @author fracpete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9490 $
+ * <!-- options-end -->
+ *
+ * @author fracpete (fracpete at waikato dot ac dot nz)
+ * @version $Revision: 10438 $
*/
-public class Main
- extends JFrame
- implements OptionHandler {
-
+public class Main extends JFrame implements OptionHandler {
+
/** for serialization. */
private static final long serialVersionUID = 1453813254824253849L;
-
+
/**
* DesktopPane with background image.
*
- * @author fracpete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9490 $
+ * @author fracpete (fracpete at waikato dot ac dot nz)
+ * @version $Revision: 10438 $
*/
- public static class BackgroundDesktopPane
- extends JDesktopPane {
-
+ public static class BackgroundDesktopPane extends JDesktopPane {
+
/** for serialization. */
private static final long serialVersionUID = 2046713123452402745L;
-
+
/** the actual background image. */
protected Image m_Background;
-
+
/**
* intializes the desktop pane.
*
- * @param image the image to use as background
+ * @param image the image to use as background
*/
public BackgroundDesktopPane(String image) {
super();
-
+
try {
- m_Background = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource(image));
- }
- catch (Exception e) {
- e.printStackTrace();
+ m_Background = Toolkit.getDefaultToolkit().getImage(
+ ClassLoader.getSystemResource(image));
+ } catch (Exception e) {
+ e.printStackTrace();
}
}
-
+
/**
* draws the background image.
*
- * @param g the graphics context
+ * @param g the graphics context
*/
+ @Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
-
+
if (m_Background != null) {
- g.setColor(Color.WHITE);
- g.clearRect(0, 0, getWidth(), getHeight());
-
- int width = m_Background.getWidth(null);
- int height = m_Background.getHeight(null);
- int x = (getWidth() - width) / 2;
- int y = (getHeight() - height) / 2;
- g.drawImage(m_Background, x, y, width, height, this);
+ g.setColor(Color.WHITE);
+ g.clearRect(0, 0, getWidth(), getHeight());
+
+ int width = m_Background.getWidth(null);
+ int height = m_Background.getHeight(null);
+ int x = (getWidth() - width) / 2;
+ int y = (getHeight() - height) / 2;
+ g.drawImage(m_Background, x, y, width, height, this);
}
}
}
-
+
/**
* Specialized JFrame class.
*
- * @author fracpete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9490 $
+ * @author fracpete (fracpete at waikato dot ac dot nz)
+ * @version $Revision: 10438 $
*/
- public static class ChildFrameSDI
- extends JFrame {
-
+ public static class ChildFrameSDI extends JFrame {
+
/** for serialization. */
private static final long serialVersionUID = 8588293938686425618L;
-
+
/** the parent frame. */
protected Main m_Parent;
-
+
/**
* constructs a new internal frame that knows about its parent.
*
- * @param parent the parent frame
- * @param title the title of the frame
+ * @param parent the parent frame
+ * @param title the title of the frame
*/
public ChildFrameSDI(Main parent, String title) {
super(title);
-
+
m_Parent = parent;
addWindowListener(new WindowAdapter() {
- public void windowActivated(WindowEvent e) {
- // update title of parent
- if (getParentFrame() != null)
- getParentFrame().createTitle(getTitle());
- }
+ @Override
+ public void windowActivated(WindowEvent e) {
+ // update title of parent
+ if (getParentFrame() != null) {
+ getParentFrame().createTitle(getTitle());
+ }
+ }
});
-
+
// add to parent
if (getParentFrame() != null) {
- getParentFrame().addChildFrame(this);
- setIconImage(getParentFrame().getIconImage());
+ getParentFrame().addChildFrame(this);
+ setIconImage(getParentFrame().getIconImage());
}
}
-
+
/**
* returns the parent frame, can be null.
*
- * @return the parent frame
+ * @return the parent frame
*/
public Main getParentFrame() {
return m_Parent;
}
-
+
/**
* de-registers the child frame with the parent first.
*/
+ @Override
public void dispose() {
if (getParentFrame() != null) {
- getParentFrame().removeChildFrame(this);
- getParentFrame().createTitle("");
+ getParentFrame().removeChildFrame(this);
+ getParentFrame().createTitle("");
}
-
+
super.dispose();
}
}
-
+
/**
* Specialized JInternalFrame class.
*
- * @author fracpete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9490 $
+ * @author fracpete (fracpete at waikato dot ac dot nz)
+ * @version $Revision: 10438 $
*/
- public static class ChildFrameMDI
- extends JInternalFrame {
-
+ public static class ChildFrameMDI extends JInternalFrame {
+
/** for serialization. */
private static final long serialVersionUID = 3772573515346899959L;
-
+
/** the parent frame. */
protected Main m_Parent;
-
+
/**
* constructs a new internal frame that knows about its parent.
*
- * @param parent the parent frame
- * @param title the title of the frame
+ * @param parent the parent frame
+ * @param title the title of the frame
*/
public ChildFrameMDI(Main parent, String title) {
super(title, true, true, true, true);
-
+
m_Parent = parent;
addInternalFrameListener(new InternalFrameAdapter() {
- public void internalFrameActivated(InternalFrameEvent e) {
- // update title of parent
- if (getParentFrame() != null)
- getParentFrame().createTitle(getTitle());
- }
+ @Override
+ public void internalFrameActivated(InternalFrameEvent e) {
+ // update title of parent
+ if (getParentFrame() != null) {
+ getParentFrame().createTitle(getTitle());
+ }
+ }
});
-
+
// add to parent
if (getParentFrame() != null) {
- getParentFrame().addChildFrame(this);
- getParentFrame().jDesktopPane.add(this);
+ getParentFrame().addChildFrame(this);
+ getParentFrame().jDesktopPane.add(this);
}
}
-
+
/**
* returns the parent frame, can be null.
*
- * @return the parent frame
+ * @return the parent frame
*/
public Main getParentFrame() {
return m_Parent;
}
-
+
/**
* de-registers the child frame with the parent first.
*/
+ @Override
public void dispose() {
if (getParentFrame() != null) {
- getParentFrame().removeChildFrame(this);
- getParentFrame().createTitle("");
+ getParentFrame().removeChildFrame(this);
+ getParentFrame().createTitle("");
}
-
+
super.dispose();
}
}
@@ -306,30 +310,35 @@ public class Main
public final static int GUI_SDI = 1;
/** GUI tags. */
public static final Tag[] TAGS_GUI = {
- new Tag(GUI_MDI, "MDI", Messages.getInstance().getString("Main_Tag_GUI_Text_First")),
- new Tag(GUI_SDI, "SDI", Messages.getInstance().getString("Main_Tag_GUI_Text_Second"))
- };
-
+ new Tag(GUI_MDI, "MDI", Messages.getInstance().getString(
+ "Main_Tag_GUI_Text_First")),
+ new Tag(GUI_SDI, "SDI", Messages.getInstance().getString(
+ "Main_Tag_GUI_Text_Second")) };
+
/** the frame itself. */
protected Main m_Self;
-
+
/** the type of GUI to display. */
protected int m_GUIType = GUI_MDI;
-
- /** variable for the Main class which would be set to null by the memory
- * monitoring thread to free up some memory if we running out of memory. */
+
+ /**
+ * variable for the Main class which would be set to null by the memory
+ * monitoring thread to free up some memory if we running out of memory.
+ */
protected static Main m_MainCommandline;
-
+
/** singleton instance of the GUI. */
protected static Main m_MainSingleton;
- /** list of things to be notified when the startup process of
- * the KnowledgeFlow is complete. */
+ /**
+ * list of things to be notified when the startup process of the KnowledgeFlow
+ * is complete.
+ */
protected static Vector m_StartupListeners = new Vector();
/** for monitoring the Memory consumption. */
protected static Memory m_Memory = new Memory(true);
-
+
/** contains the child frames (title <-> object). */
protected HashSet<Container> m_ChildFrames = new HashSet<Container>();
@@ -337,17 +346,21 @@ public class Main
protected static LogWindow m_LogWindow = new LogWindow();
/** filechooser for the TreeVisualizer. */
- protected JFileChooser m_FileChooserTreeVisualizer = new JFileChooser(new File(System.getProperty("user.dir")));
+ protected JFileChooser m_FileChooserTreeVisualizer = new JFileChooser(
+ new File(System.getProperty("user.dir")));
/** filechooser for the GraphVisualizer. */
- protected JFileChooser m_FileChooserGraphVisualizer = new JFileChooser(new File(System.getProperty("user.dir")));
+ protected JFileChooser m_FileChooserGraphVisualizer = new JFileChooser(
+ new File(System.getProperty("user.dir")));
/** filechooser for Plots. */
- protected JFileChooser m_FileChooserPlot = new JFileChooser(new File(System.getProperty("user.dir")));
+ protected JFileChooser m_FileChooserPlot = new JFileChooser(new File(
+ System.getProperty("user.dir")));
/** filechooser for ROC curves. */
- protected JFileChooser m_FileChooserROC = new JFileChooser(new File(System.getProperty("user.dir")));
-
+ protected JFileChooser m_FileChooserROC = new JFileChooser(new File(
+ System.getProperty("user.dir")));
+
// GUI components
private JMenu jMenuHelp;
private JMenu jMenuVisualization;
@@ -358,14 +371,12 @@ public class Main
private JMenuItem jMenuItemHelpAbout;
private JMenuItem jMenuItemHelpHomepage;
private JMenuItem jMenuItemHelpWekaWiki;
- private JMenuItem jMenuItemHelpWekaDoc;
private JMenuItem jMenuItemHelpSourceforge;
private JMenuItem jMenuItemVisualizationBoundaryVisualizer;
private JMenuItem jMenuItemVisualizationGraphVisualizer;
private JMenuItem jMenuItemVisualizationTreeVisualizer;
private JMenuItem jMenuItemVisualizationROC;
private JMenuItem jMenuItemVisualizationPlot;
- private JMenuItem jMenuItemToolsEnsembleLibrary;
private JMenuItem jMenuItemToolsSqlViewer;
private JMenuItem jMenuItemToolsArffViewer;
private JMenuItem jMenuItemApplicationsSimpleCLI;
@@ -375,207 +386,216 @@ public class Main
private JMenuItem jMenuItemProgramExit;
private JMenuItem jMenuItemProgramLogWindow;
private JMenuItem jMenuItemProgramMemoryUsage;
- private JMenuItem jMenuItemProgramPreferences; // TODO: see below
private JMenu jMenuProgram;
private JMenu jMenuExtensions;
private JMenu jMenuWindows;
private JMenuBar jMenuBar;
-
+
/**
* default constructor.
*/
public Main() {
super();
}
-
+
/**
* creates a frame (depending on m_GUIType) and returns it.
*
- * @param parent the parent of the generated frame
- * @param title the title of the frame
- * @param c the component to place, can be null
- * @param layout the layout to use, e.g., BorderLayout
- * @param layoutConstraints the layout constraints, e.g., BorderLayout.CENTER
- * @param width the width of the frame, ignored if -1
- * @param height the height of the frame, ignored if -1
- * @param menu an optional menu
- * @param listener if true a default listener is added
- * @param visible if true then the frame is made visible immediately
- * @return the generated frame
- * @see #m_GUIType
+ * @param parent the parent of the generated frame
+ * @param title the title of the frame
+ * @param c the component to place, can be null
+ * @param layout the layout to use, e.g., BorderLayout
+ * @param layoutConstraints the layout constraints, e.g., BorderLayout.CENTER
+ * @param width the width of the frame, ignored if -1
+ * @param height the height of the frame, ignored if -1
+ * @param menu an optional menu
+ * @param listener if true a default listener is added
+ * @param visible if true then the frame is made visible immediately
+ * @return the generated frame
+ * @see #m_GUIType
*/
- protected Container createFrame(
- Main parent, String title, Component c, LayoutManager layout,
- Object layoutConstraints, int width, int height, JMenuBar menu,
- boolean listener, boolean visible) {
+ protected Container createFrame(Main parent, String title, Component c,
+ LayoutManager layout, Object layoutConstraints, int width, int height,
+ JMenuBar menu, boolean listener, boolean visible) {
Container result = null;
-
+
if (m_GUIType == GUI_MDI) {
final ChildFrameMDI frame = new ChildFrameMDI(parent, title);
-
+
// layout
frame.setLayout(layout);
- if (c != null)
- frame.getContentPane().add(c, layoutConstraints);
-
+ if (c != null) {
+ frame.getContentPane().add(c, layoutConstraints);
+ }
+
// menu
frame.setJMenuBar(menu);
-
+
// size
frame.pack();
- if ((width > -1) && (height > -1))
- frame.setSize(width, height);
+ if ((width > -1) && (height > -1)) {
+ frame.setSize(width, height);
+ }
frame.validate();
// listener?
if (listener) {
- frame.addInternalFrameListener(new InternalFrameAdapter() {
- public void internalFrameClosing(InternalFrameEvent e) {
- frame.dispose();
- }
- });
+ frame.addInternalFrameListener(new InternalFrameAdapter() {
+ @Override
+ public void internalFrameClosing(InternalFrameEvent e) {
+ frame.dispose();
+ }
+ });
}
-
+
// display frame
if (visible) {
- frame.setVisible(true);
- try {
- frame.setSelected(true);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
+ frame.setVisible(true);
+ try {
+ frame.setSelected(true);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
}
-
+
result = frame;
- }
- else if (m_GUIType == GUI_SDI) {
+ } else if (m_GUIType == GUI_SDI) {
final ChildFrameSDI frame = new ChildFrameSDI(parent, title);
-
+
// layout
frame.setLayout(layout);
- if (c != null)
- frame.getContentPane().add(c, layoutConstraints);
-
+ if (c != null) {
+ frame.getContentPane().add(c, layoutConstraints);
+ }
+
// menu
frame.setJMenuBar(menu);
-
+
// size
frame.pack();
- if ((width > -1) && (height > -1))
- frame.setSize(width, height);
+ if ((width > -1) && (height > -1)) {
+ frame.setSize(width, height);
+ }
frame.validate();
// location
int screenHeight = getGraphicsConfiguration().getBounds().height;
- int screenWidth = getGraphicsConfiguration().getBounds().width;
- frame.setLocation(
- (screenWidth - frame.getBounds().width) / 2,
- (screenHeight - frame.getBounds().height) / 2);
-
+ int screenWidth = getGraphicsConfiguration().getBounds().width;
+ frame.setLocation((screenWidth - frame.getBounds().width) / 2,
+ (screenHeight - frame.getBounds().height) / 2);
+
// listener?
if (listener) {
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- frame.dispose();
- }
- });
+ frame.addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowClosing(WindowEvent e) {
+ frame.dispose();
+ }
+ });
}
-
+
// display frame
- if (visible)
- frame.setVisible(true);
+ if (visible) {
+ frame.setVisible(true);
+ }
result = frame;
}
-
+
return result;
}
-
+
/**
* insert the menu item in a sorted fashion.
*
- * @param menu the menu to add the item to
- * @param menuitem the menu item to add
+ * @param menu the menu to add the item to
+ * @param menuitem the menu item to add
*/
protected void insertMenuItem(JMenu menu, JMenuItem menuitem) {
insertMenuItem(menu, menuitem, 0);
}
-
+
/**
* insert the menu item in a sorted fashion.
*
- * @param menu the menu to add the item to
- * @param menuitem the menu item to add
- * @param startIndex the index in the menu to start with (0-based)
+ * @param menu the menu to add the item to
+ * @param menuitem the menu item to add
+ * @param startIndex the index in the menu to start with (0-based)
*/
protected void insertMenuItem(JMenu menu, JMenuItem menuitem, int startIndex) {
- boolean inserted;
- int i;
- JMenuItem current;
- String currentStr;
- String newStr;
-
+ boolean inserted;
+ int i;
+ JMenuItem current;
+ String currentStr;
+ String newStr;
+
inserted = false;
- newStr = menuitem.getText().toLowerCase();
-
+ newStr = menuitem.getText().toLowerCase();
+
// try to find a spot inbetween
for (i = startIndex; i < menu.getMenuComponentCount(); i++) {
- if (!(menu.getMenuComponent(i) instanceof JMenuItem))
- continue;
-
- current = (JMenuItem) menu.getMenuComponent(i);
+ if (!(menu.getMenuComponent(i) instanceof JMenuItem)) {
+ continue;
+ }
+
+ current = (JMenuItem) menu.getMenuComponent(i);
currentStr = current.getText().toLowerCase();
if (currentStr.compareTo(newStr) > 0) {
- inserted = true;
- menu.insert(menuitem, i);
- break;
+ inserted = true;
+ menu.insert(menuitem, i);
+ break;
}
}
-
+
// add it at the end if not yet inserted
- if (!inserted)
+ if (!inserted) {
menu.add(menuitem);
+ }
}
-
+
/**
* initializes the GUI.
*/
protected void initGUI() {
m_Self = this;
-
+
try {
// main window
createTitle("");
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- this.setIconImage(new ImageIcon(getClass().getClassLoader().getResource("weka/gui/weka_icon_new_48.png")).getImage());
+ this.setIconImage(new ImageIcon(getClass().getClassLoader().getResource(
+ "weka/gui/weka_icon_new_48.png")).getImage());
// bits and pieces
- m_FileChooserGraphVisualizer.addChoosableFileFilter(
- new ExtensionFileFilter(".bif", Messages.getInstance().getString("Main_InitGUI_ExtensionFileFilter_Text_First")));
- m_FileChooserGraphVisualizer.addChoosableFileFilter(
- new ExtensionFileFilter(".xml", Messages.getInstance().getString("Main_InitGUI_ExtensionFileFilter_Text_Second")));
-
- m_FileChooserPlot.addChoosableFileFilter(
- new ExtensionFileFilter(
- Instances.FILE_EXTENSION,
- Messages.getInstance().getString("Main_InitGUI_ExtensionFileFilter_Text_Third") + Instances.FILE_EXTENSION + ")"));
+ m_FileChooserGraphVisualizer
+ .addChoosableFileFilter(new ExtensionFileFilter(".bif", Messages
+ .getInstance().getString(
+ "Main_InitGUI_ExtensionFileFilter_Text_First")));
+ m_FileChooserGraphVisualizer
+ .addChoosableFileFilter(new ExtensionFileFilter(".xml", Messages
+ .getInstance().getString(
+ "Main_InitGUI_ExtensionFileFilter_Text_Second")));
+
+ m_FileChooserPlot.addChoosableFileFilter(new ExtensionFileFilter(
+ Instances.FILE_EXTENSION, Messages.getInstance().getString(
+ "Main_InitGUI_ExtensionFileFilter_Text_Third")
+ + Instances.FILE_EXTENSION + ")"));
m_FileChooserPlot.setMultiSelectionEnabled(true);
- m_FileChooserROC.addChoosableFileFilter(
- new ExtensionFileFilter(
- Instances.FILE_EXTENSION,
- Messages.getInstance().getString("Main_InitGUI_ExtensionFileFilter_Text_Third") + Instances.FILE_EXTENSION + ")"));
+ m_FileChooserROC.addChoosableFileFilter(new ExtensionFileFilter(
+ Instances.FILE_EXTENSION, Messages.getInstance().getString(
+ "Main_InitGUI_ExtensionFileFilter_Text_Third")
+ + Instances.FILE_EXTENSION + ")"));
// Desktop
if (m_GUIType == GUI_MDI) {
- jDesktopPane = new BackgroundDesktopPane("weka/gui/images/weka_background.gif");
- jDesktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
- setContentPane(jDesktopPane);
- }
- else {
- jDesktopPane = null;
+ jDesktopPane = new BackgroundDesktopPane(
+ "weka/gui/images/weka_background.gif");
+ jDesktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
+ setContentPane(jDesktopPane);
+ } else {
+ jDesktopPane = null;
}
// Menu
@@ -585,80 +605,86 @@ public class Main
// Program
jMenuProgram = new JMenu();
jMenuBar.add(jMenuProgram);
- jMenuProgram.setText(Messages.getInstance().getString("Main_InitGUI_JMenuProgram_SetText_Text"));
+ jMenuProgram.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuProgram_SetText_Text"));
jMenuProgram.setMnemonic('P');
// Program/Preferences
// TODO: read all properties from all props file and display them
/*
- jMenuItemProgramPreferences = new JMenuItem();
- jMenuProgram.add(jMenuItemProgramPreferences);
- jMenuItemProgramPreferences.setText("Preferences");
- jMenuItemProgramPreferences.setMnemonic('P');
- jMenuItemProgramPreferences.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- System.out.println("jMenuItemProgramPreferences.actionPerformed, event="+evt);
- //TODO add your code for jMenuItemProgramPreferences.actionPerformed
- }
- });
+ * jMenuItemProgramPreferences = new JMenuItem();
+ * jMenuProgram.add(jMenuItemProgramPreferences);
+ * jMenuItemProgramPreferences.setText("Preferences");
+ * jMenuItemProgramPreferences.setMnemonic('P');
+ * jMenuItemProgramPreferences.addActionListener(new ActionListener() {
+ * public void actionPerformed(ActionEvent evt) {
+ * System.out.println("jMenuItemProgramPreferences.actionPerformed, event="
+ * +evt); //TODO add your code for
+ * jMenuItemProgramPreferences.actionPerformed } });
*/
// Program/LogWindow
jMenuItemProgramLogWindow = new JMenuItem();
jMenuProgram.add(jMenuItemProgramLogWindow);
- jMenuItemProgramLogWindow.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemProgramLogWindow_SetText_Text"));
+ jMenuItemProgramLogWindow.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemProgramLogWindow_SetText_Text"));
jMenuItemProgramLogWindow.setMnemonic('L');
jMenuItemProgramLogWindow.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- m_LogWindow.setVisible(true);
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ m_LogWindow.setVisible(true);
+ }
});
-
+
jMenuItemProgramMemoryUsage = new JMenuItem();
jMenuProgram.add(jMenuItemProgramMemoryUsage);
- jMenuItemProgramMemoryUsage.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemProgramMemoryUsage_SetText_Text"));
+ jMenuItemProgramMemoryUsage.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemProgramMemoryUsage_SetText_Text"));
jMenuItemProgramMemoryUsage.setMnemonic('M');
jMenuItemProgramMemoryUsage.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemProgramMemoryUsage.getText();
- if (!containsWindow(title)) {
- final MemoryUsagePanel panel = new MemoryUsagePanel();
- Container c = createFrame(
- m_Self, title, panel, new BorderLayout(),
- BorderLayout.CENTER, 400, 50, null, true, true);
-
- // optimize size
- Dimension size = c.getPreferredSize();
- c.setSize(new Dimension((int) size.getWidth(), (int) size.getHeight()));
-
- // stop threads
- if (m_GUIType == GUI_MDI) {
- final ChildFrameMDI frame = (ChildFrameMDI) c;
- Point l = panel.getFrameLocation();
- if ((l.x != -1) && (l.y != -1))
- frame.setLocation(l);
- frame.addInternalFrameListener(new InternalFrameAdapter() {
- public void internalFrameClosing(InternalFrameEvent e) {
- panel.stopMonitoring();
- }
- });
- }
- else {
- final ChildFrameSDI frame = (ChildFrameSDI) c;
- Point l = panel.getFrameLocation();
- if ((l.x != -1) && (l.y != -1))
- frame.setLocation(l);
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- panel.stopMonitoring();
- }
- });
- }
- }
- else {
- showWindow(getWindow(title));
- }
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemProgramMemoryUsage.getText();
+ if (!containsWindow(title)) {
+ final MemoryUsagePanel panel = new MemoryUsagePanel();
+ Container c = createFrame(m_Self, title, panel, new BorderLayout(),
+ BorderLayout.CENTER, 400, 50, null, true, true);
+
+ // optimize size
+ Dimension size = c.getPreferredSize();
+ c.setSize(new Dimension((int) size.getWidth(), (int) size
+ .getHeight()));
+
+ // stop threads
+ if (m_GUIType == GUI_MDI) {
+ final ChildFrameMDI frame = (ChildFrameMDI) c;
+ Point l = panel.getFrameLocation();
+ if ((l.x != -1) && (l.y != -1)) {
+ frame.setLocation(l);
+ }
+ frame.addInternalFrameListener(new InternalFrameAdapter() {
+ @Override
+ public void internalFrameClosing(InternalFrameEvent e) {
+ panel.stopMonitoring();
+ }
+ });
+ } else {
+ final ChildFrameSDI frame = (ChildFrameSDI) c;
+ Point l = panel.getFrameLocation();
+ if ((l.x != -1) && (l.y != -1)) {
+ frame.setLocation(l);
+ }
+ frame.addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowClosing(WindowEvent e) {
+ panel.stopMonitoring();
+ }
+ });
+ }
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
});
jMenuProgram.add(new JSeparator());
@@ -666,293 +692,325 @@ public class Main
// Program/Exit
jMenuItemProgramExit = new JMenuItem();
jMenuProgram.add(jMenuItemProgramExit);
- jMenuItemProgramExit.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemProgramExit_SetText_Text"));
+ jMenuItemProgramExit.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemProgramExit_SetText_Text"));
jMenuItemProgramExit.setMnemonic('E');
- jMenuItemProgramExit.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- // close all children
- Iterator iter = getWindowList();
- Vector<Container> list = new Vector<Container>();
- while (iter.hasNext())
- list.add((Container) iter.next());
- for (int i = 0; i < list.size(); i++) {
- Container c = list.get(i);
- if (c instanceof ChildFrameMDI)
- ((ChildFrameMDI) c).dispose();
- else if (c instanceof ChildFrameSDI)
- ((ChildFrameSDI) c).dispose();
- }
- // close logwindow
- m_LogWindow.dispose();
- // close main window
- m_Self.dispose();
- // make sure we stop
- System.exit(0);
- }
+ jMenuItemProgramExit.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ // close all children
+ Iterator iter = getWindowList();
+ Vector<Container> list = new Vector<Container>();
+ while (iter.hasNext()) {
+ list.add((Container) iter.next());
+ }
+ for (int i = 0; i < list.size(); i++) {
+ Container c = list.get(i);
+ if (c instanceof ChildFrameMDI) {
+ ((ChildFrameMDI) c).dispose();
+ } else if (c instanceof ChildFrameSDI) {
+ ((ChildFrameSDI) c).dispose();
+ }
+ }
+ // close logwindow
+ m_LogWindow.dispose();
+ // close main window
+ m_Self.dispose();
+ // make sure we stop
+ System.exit(0);
+ }
});
// Applications
jMenuApplications = new JMenu();
jMenuBar.add(jMenuApplications);
- jMenuApplications.setText(Messages.getInstance().getString("Main_InitGUI_JMenuApplications_SetText_Text"));
+ jMenuApplications.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuApplications_SetText_Text"));
jMenuApplications.setMnemonic('A');
// Applications/Explorer
jMenuItemApplicationsExplorer = new JMenuItem();
jMenuApplications.add(jMenuItemApplicationsExplorer);
- jMenuItemApplicationsExplorer.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemApplicationsExplorer_SetText_Text"));
+ jMenuItemApplicationsExplorer.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemApplicationsExplorer_SetText_Text"));
jMenuItemApplicationsExplorer.setMnemonic('E');
jMenuItemApplicationsExplorer.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemApplicationsExplorer.getText();
- if (!containsWindow(title)) {
- createFrame(
- m_Self, title, new Explorer(), new BorderLayout(),
- BorderLayout.CENTER, 800, 600, null, true, true);
- }
- else {
- showWindow(getWindow(title));
- }
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemApplicationsExplorer.getText();
+ if (!containsWindow(title)) {
+ createFrame(m_Self, title, new Explorer(), new BorderLayout(),
+ BorderLayout.CENTER, 800, 600, null, true, true);
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
});
// Applications/Experimenter
jMenuItemApplicationsExperimenter = new JMenuItem();
jMenuApplications.add(jMenuItemApplicationsExperimenter);
- jMenuItemApplicationsExperimenter.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemApplicationsExperimenter_SetText_Text"));
+ jMenuItemApplicationsExperimenter.setText(Messages.getInstance()
+ .getString(
+ "Main_InitGUI_JMenuItemApplicationsExperimenter_SetText_Text"));
jMenuItemApplicationsExperimenter.setMnemonic('X');
jMenuItemApplicationsExperimenter.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemApplicationsExperimenter.getText();
- if (!containsWindow(title)) {
- createFrame(
- m_Self, title, new Experimenter(false), new BorderLayout(),
- BorderLayout.CENTER, 800, 600, null, true, true);
- }
- else {
- showWindow(getWindow(title));
- }
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemApplicationsExperimenter.getText();
+ if (!containsWindow(title)) {
+ createFrame(m_Self, title, new Experimenter(false),
+ new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true,
+ true);
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
});
// Applications/KnowledgeFlow
jMenuItemApplicationsKnowledgeFlow = new JMenuItem();
jMenuApplications.add(jMenuItemApplicationsKnowledgeFlow);
- jMenuItemApplicationsKnowledgeFlow.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemApplicationsKnowledgeFlow_SetText_Text"));
+ jMenuItemApplicationsKnowledgeFlow.setText(Messages.getInstance()
+ .getString(
+ "Main_InitGUI_JMenuItemApplicationsKnowledgeFlow_SetText_Text"));
jMenuItemApplicationsKnowledgeFlow.setMnemonic('K');
- jMenuItemApplicationsKnowledgeFlow.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemApplicationsKnowledgeFlow.getText();
- if (!containsWindow(title)) {
- KnowledgeFlowApp.createSingleton(new String[0]);
- createFrame(
- m_Self, title, KnowledgeFlowApp.getSingleton(), new BorderLayout(),
- BorderLayout.CENTER, 900, 600, null, true, true);
- }
- else {
- showWindow(getWindow(title));
- }
- }
- });
+ jMenuItemApplicationsKnowledgeFlow
+ .addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemApplicationsKnowledgeFlow.getText();
+ if (!containsWindow(title)) {
+ KnowledgeFlowApp.createSingleton(new String[0]);
+ createFrame(m_Self, title, KnowledgeFlowApp.getSingleton(),
+ new BorderLayout(), BorderLayout.CENTER, 900, 600, null, true,
+ true);
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
+ });
// Applications/SimpleCLI
jMenuItemApplicationsSimpleCLI = new JMenuItem();
jMenuApplications.add(jMenuItemApplicationsSimpleCLI);
- jMenuItemApplicationsSimpleCLI.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemApplicationsSimpleCLI_SetText_Text"));
+ jMenuItemApplicationsSimpleCLI.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemApplicationsSimpleCLI_SetText_Text"));
jMenuItemApplicationsSimpleCLI.setMnemonic('S');
jMenuItemApplicationsSimpleCLI.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemApplicationsSimpleCLI.getText();
- if (!containsWindow(title)) {
- try {
- createFrame(
- m_Self, title, new SimpleCLIPanel(), new BorderLayout(),
- BorderLayout.CENTER, 600, 500, null, true, true);
- }
- catch (Exception e) {
- e.printStackTrace();
- JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text") + e.getMessage());
- return;
- }
- }
- else {
- showWindow(getWindow(title));
- }
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemApplicationsSimpleCLI.getText();
+ if (!containsWindow(title)) {
+ try {
+ createFrame(m_Self, title, new SimpleCLIPanel(),
+ new BorderLayout(), BorderLayout.CENTER, 600, 500, null, true,
+ true);
+ } catch (Exception e) {
+ e.printStackTrace();
+ JOptionPane.showMessageDialog(
+ m_Self,
+ Messages.getInstance().getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text")
+ + e.getMessage());
+ return;
+ }
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
});
// Tools
jMenuTools = new JMenu();
jMenuBar.add(jMenuTools);
- jMenuTools.setText(Messages.getInstance().getString("Main_InitGUI_JMenuTools_JMenu_SetText_Text")); // ""
+ jMenuTools.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuTools_JMenu_SetText_Text")); // ""
jMenuTools.setMnemonic('T');
// Tools/ArffViewer
jMenuItemToolsArffViewer = new JMenuItem();
jMenuTools.add(jMenuItemToolsArffViewer);
- jMenuItemToolsArffViewer.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemToolsArffViewer_SetText_Text"));
+ jMenuItemToolsArffViewer.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemToolsArffViewer_SetText_Text"));
jMenuItemToolsArffViewer.setMnemonic('A');
jMenuItemToolsArffViewer.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemToolsArffViewer.getText();
- if (!containsWindow(title)) {
- ArffViewerMainPanel panel = new ArffViewerMainPanel(null);
- panel.setConfirmExit(false);
- Container frame = createFrame(
- m_Self, title, panel, new BorderLayout(),
- BorderLayout.CENTER, 800, 600, panel.getMenu(), true, true);
- panel.setParent(frame);
- }
- else {
- showWindow(getWindow(title));
- }
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemToolsArffViewer.getText();
+ if (!containsWindow(title)) {
+ ArffViewerMainPanel panel = new ArffViewerMainPanel(null);
+ panel.setConfirmExit(false);
+ Container frame = createFrame(m_Self, title, panel,
+ new BorderLayout(), BorderLayout.CENTER, 800, 600,
+ panel.getMenu(), true, true);
+ panel.setParent(frame);
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
});
// Tools/SqlViewer
jMenuItemToolsSqlViewer = new JMenuItem();
jMenuTools.add(jMenuItemToolsSqlViewer);
- jMenuItemToolsSqlViewer.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemToolsSqlViewer_SetText_Text")); //"SqlViewer"
+ jMenuItemToolsSqlViewer.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemToolsSqlViewer_SetText_Text")); // "SqlViewer"
jMenuItemToolsSqlViewer.setMnemonic('S');
jMenuItemToolsSqlViewer.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemToolsSqlViewer.getText();
- if (!containsWindow(title)) {
- final SqlViewer sql = new SqlViewer(null);
- final Container frame = createFrame(
- m_Self, title, sql, new BorderLayout(),
- BorderLayout.CENTER, -1, -1, null, false, true);
-
- // custom listener
- if (frame instanceof ChildFrameMDI) {
- ((ChildFrameMDI) frame).addInternalFrameListener(new InternalFrameAdapter() {
- public void internalFrameClosing(InternalFrameEvent e) {
- sql.saveSize();
- ((ChildFrameMDI) frame).dispose();
- }
- });
- }
- else if (frame instanceof ChildFrameSDI) {
- ((ChildFrameSDI) frame).addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- sql.saveSize();
- ((ChildFrameSDI) frame).dispose();
- }
- });
- }
- }
- else {
- showWindow(getWindow(title));
- }
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemToolsSqlViewer.getText();
+ if (!containsWindow(title)) {
+ final SqlViewer sql = new SqlViewer(null);
+ final Container frame = createFrame(m_Self, title, sql,
+ new BorderLayout(), BorderLayout.CENTER, -1, -1, null, false,
+ true);
+
+ // custom listener
+ if (frame instanceof ChildFrameMDI) {
+ ((ChildFrameMDI) frame)
+ .addInternalFrameListener(new InternalFrameAdapter() {
+ @Override
+ public void internalFrameClosing(InternalFrameEvent e) {
+ sql.saveSize();
+ ((ChildFrameMDI) frame).dispose();
+ }
+ });
+ } else if (frame instanceof ChildFrameSDI) {
+ ((ChildFrameSDI) frame).addWindowListener(new WindowAdapter() {
+ @Override
+ public void windowClosing(WindowEvent e) {
+ sql.saveSize();
+ ((ChildFrameSDI) frame).dispose();
+ }
+ });
+ }
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
});
-
+
// Tools/Bayes net editor
// Tools/Bayes net editor
final JMenuItem jMenuItemBayesNet = new JMenuItem();
jMenuTools.add(jMenuItemBayesNet);
- jMenuItemBayesNet.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemBayesNet_SetText_Text"));
+ jMenuItemBayesNet.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemBayesNet_SetText_Text"));
jMenuItemBayesNet.setMnemonic('N');
jMenuItemBayesNet.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent e) {
String title = jMenuItemBayesNet.getText();
-
+
if (!containsWindow(title)) {
final GUI bayesNetGUI = new GUI();
- final Container frame = createFrame(
- m_Self, title, bayesNetGUI, new BorderLayout(),
- BorderLayout.CENTER, 800, 600, bayesNetGUI.getMenuBar(), false, true);
- }
- else {
+ final Container frame = createFrame(m_Self, title, bayesNetGUI,
+ new BorderLayout(), BorderLayout.CENTER, 800, 600,
+ bayesNetGUI.getMenuBar(), false, true);
+ } else {
showWindow(getWindow(title));
- }
- }
+ }
+ }
});
// Tools/EnsembleLibrary
- /* currently disabled due to bugs... FracPete
- jMenuItemToolsEnsembleLibrary = new JMenuItem();
- jMenuTools.add(jMenuItemToolsEnsembleLibrary);
- jMenuItemToolsEnsembleLibrary.setText("EnsembleLibrary");
- jMenuItemToolsEnsembleLibrary.setMnemonic('E');
- jMenuItemToolsEnsembleLibrary.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemToolsEnsembleLibrary.getText();
- if (!containsWindow(title)) {
- EnsembleLibrary value = new EnsembleLibrary();
- EnsembleLibraryEditor libraryEditor = new EnsembleLibraryEditor();
- libraryEditor.setValue(value);
- createFrame(
- m_Self, title, libraryEditor.getCustomEditor(), new BorderLayout(),
- BorderLayout.CENTER, 800, 600, null, true, true);
- }
- else {
- showWindow(getWindow(title));
- }
- }
- });
- */
+ /*
+ * currently disabled due to bugs... FracPete
+ * jMenuItemToolsEnsembleLibrary = new JMenuItem();
+ * jMenuTools.add(jMenuItemToolsEnsembleLibrary);
+ * jMenuItemToolsEnsembleLibrary.setText("EnsembleLibrary");
+ * jMenuItemToolsEnsembleLibrary.setMnemonic('E');
+ * jMenuItemToolsEnsembleLibrary.addActionListener(new ActionListener() {
+ * public void actionPerformed(ActionEvent evt) { String title =
+ * jMenuItemToolsEnsembleLibrary.getText(); if (!containsWindow(title)) {
+ * EnsembleLibrary value = new EnsembleLibrary(); EnsembleLibraryEditor
+ * libraryEditor = new EnsembleLibraryEditor();
+ * libraryEditor.setValue(value); createFrame( m_Self, title,
+ * libraryEditor.getCustomEditor(), new BorderLayout(),
+ * BorderLayout.CENTER, 800, 600, null, true, true); } else {
+ * showWindow(getWindow(title)); } } });
+ */
// Visualization
jMenuVisualization = new JMenu();
jMenuBar.add(jMenuVisualization);
- jMenuVisualization.setText(Messages.getInstance().getString("Main_InitGUI_JMenuVisualization_SetText_Text"));
+ jMenuVisualization.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuVisualization_SetText_Text"));
jMenuVisualization.setMnemonic('V');
// Visualization/Plot
jMenuItemVisualizationPlot = new JMenuItem();
jMenuVisualization.add(jMenuItemVisualizationPlot);
- jMenuItemVisualizationPlot.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemVisualizationPlot_SetText_Text"));
+ jMenuItemVisualizationPlot.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemVisualizationPlot_SetText_Text"));
jMenuItemVisualizationPlot.setMnemonic('P');
jMenuItemVisualizationPlot.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- // choose file
- int retVal = m_FileChooserPlot.showOpenDialog(m_Self);
- if (retVal != JFileChooser.APPROVE_OPTION)
- return;
-
- // build plot
- VisualizePanel panel = new VisualizePanel();
- String filenames = "";
- File[] files = m_FileChooserPlot.getSelectedFiles();
- for (int j = 0; j < files.length; j++) {
- String filename = files[j].getAbsolutePath();
- if (j > 0)
- filenames += ", ";
- filenames += filename;
- System.err.println(Messages.getInstance().getString("Main_InitGUI_Error_Text") + filename);
- try {
- Reader r = new java.io.BufferedReader(new FileReader(filename));
- Instances i = new Instances(r);
- i.setClassIndex(i.numAttributes()-1);
- PlotData2D pd1 = new PlotData2D(i);
-
- if (j == 0) {
- pd1.setPlotName(Messages.getInstance().getString("Main_InitGUI_Pd1_SetPlotName_Text_First"));
- panel.setMasterPlot(pd1);
- } else {
- pd1.setPlotName(Messages.getInstance().getString("Main_InitGUI_Pd1_SetPlotName_Text_Second") + (j+1));
- pd1.m_useCustomColour = true;
- pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue;
- panel.addPlot(pd1);
- }
- }
- catch (Exception e) {
- e.printStackTrace();
- JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_First") + files[j] + Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Second") + e.getMessage());
- return;
- }
- }
-
- // create frame
- createFrame(
- m_Self, jMenuItemVisualizationPlot.getText() + " - " + filenames,
- panel, new BorderLayout(),
- BorderLayout.CENTER, 800, 600, null, true, true);
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ // choose file
+ int retVal = m_FileChooserPlot.showOpenDialog(m_Self);
+ if (retVal != JFileChooser.APPROVE_OPTION) {
+ return;
+ }
+
+ // build plot
+ VisualizePanel panel = new VisualizePanel();
+ String filenames = "";
+ File[] files = m_FileChooserPlot.getSelectedFiles();
+ for (int j = 0; j < files.length; j++) {
+ String filename = files[j].getAbsolutePath();
+ if (j > 0) {
+ filenames += ", ";
+ }
+ filenames += filename;
+ System.err.println(Messages.getInstance().getString(
+ "Main_InitGUI_Error_Text")
+ + filename);
+ try {
+ Reader r = new java.io.BufferedReader(new FileReader(filename));
+ Instances i = new Instances(r);
+ i.setClassIndex(i.numAttributes() - 1);
+ PlotData2D pd1 = new PlotData2D(i);
+
+ if (j == 0) {
+ pd1.setPlotName(Messages.getInstance().getString(
+ "Main_InitGUI_Pd1_SetPlotName_Text_First"));
+ panel.setMasterPlot(pd1);
+ } else {
+ pd1.setPlotName(Messages.getInstance().getString(
+ "Main_InitGUI_Pd1_SetPlotName_Text_Second")
+ + (j + 1));
+ pd1.m_useCustomColour = true;
+ pd1.m_customColour = (j % 2 == 0) ? Color.red : Color.blue;
+ panel.addPlot(pd1);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ JOptionPane
+ .showMessageDialog(
+ m_Self,
+ Messages
+ .getInstance()
+ .getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_First")
+ + files[j]
+ + Messages
+ .getInstance()
+ .getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Second")
+ + e.getMessage());
+ return;
+ }
+ }
+
+ // create frame
+ createFrame(m_Self, jMenuItemVisualizationPlot.getText() + " - "
+ + filenames, panel, new BorderLayout(), BorderLayout.CENTER, 800,
+ 600, null, true, true);
+ }
});
// Visualization/ROC
@@ -960,269 +1018,339 @@ public class Main
// http://weka.sourceforge.net/wiki/index.php/Visualizing_ROC_curve
jMenuItemVisualizationROC = new JMenuItem();
jMenuVisualization.add(jMenuItemVisualizationROC);
- jMenuItemVisualizationROC.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemVisualizationROC_SetText_Text"));
+ jMenuItemVisualizationROC.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemVisualizationROC_SetText_Text"));
jMenuItemVisualizationROC.setMnemonic('R');
jMenuItemVisualizationROC.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- // choose file
- int retVal = m_FileChooserROC.showOpenDialog(m_Self);
- if (retVal != JFileChooser.APPROVE_OPTION)
- return;
-
- // create plot
- String filename = m_FileChooserROC.getSelectedFile().getAbsolutePath();
- Instances result = null;
- try {
- result = new Instances(new BufferedReader(new FileReader(filename)));
- }
- catch (Exception e) {
- e.printStackTrace();
- JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Third") + filename + Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Fourth") + e.getMessage());
- return;
- }
- result.setClassIndex(result.numAttributes() - 1);
- ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
- vmc.setROCString(Messages.getInstance().getString("Main_InitGUI_Vmc_SetROCString_Text") +
- Utils.doubleToString(ThresholdCurve.getROCArea(result), 4) + ")");
- vmc.setName(result.relationName());
- PlotData2D tempd = new PlotData2D(result);
- tempd.setPlotName(result.relationName());
- tempd.addInstanceNumberAttribute();
- try {
- vmc.addPlot(tempd);
- }
- catch (Exception e) {
- e.printStackTrace();
- JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Fifth") + e.getMessage());
- return;
- }
-
- createFrame(
- m_Self, jMenuItemVisualizationROC.getText() + " - " + filename,
- vmc, new BorderLayout(),
- BorderLayout.CENTER, 800, 600, null, true, true);
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ // choose file
+ int retVal = m_FileChooserROC.showOpenDialog(m_Self);
+ if (retVal != JFileChooser.APPROVE_OPTION) {
+ return;
+ }
+
+ // create plot
+ String filename = m_FileChooserROC.getSelectedFile()
+ .getAbsolutePath();
+ Instances result = null;
+ try {
+ result = new Instances(new BufferedReader(new FileReader(filename)));
+ } catch (Exception e) {
+ e.printStackTrace();
+ JOptionPane
+ .showMessageDialog(
+ m_Self,
+ Messages
+ .getInstance()
+ .getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Third")
+ + filename
+ + Messages
+ .getInstance()
+ .getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Fourth")
+ + e.getMessage());
+ return;
+ }
+ result.setClassIndex(result.numAttributes() - 1);
+ ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
+ vmc.setROCString(Messages.getInstance().getString(
+ "Main_InitGUI_Vmc_SetROCString_Text")
+ + Utils.doubleToString(ThresholdCurve.getROCArea(result), 4) + ")");
+ vmc.setName(result.relationName());
+ PlotData2D tempd = new PlotData2D(result);
+ tempd.setPlotName(result.relationName());
+ tempd.addInstanceNumberAttribute();
+ try {
+ vmc.addPlot(tempd);
+ } catch (Exception e) {
+ e.printStackTrace();
+ JOptionPane
+ .showMessageDialog(
+ m_Self,
+ Messages
+ .getInstance()
+ .getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Fifth")
+ + e.getMessage());
+ return;
+ }
+
+ createFrame(m_Self, jMenuItemVisualizationROC.getText() + " - "
+ + filename, vmc, new BorderLayout(), BorderLayout.CENTER, 800, 600,
+ null, true, true);
+ }
});
// Visualization/TreeVisualizer
jMenuItemVisualizationTreeVisualizer = new JMenuItem();
jMenuVisualization.add(jMenuItemVisualizationTreeVisualizer);
- jMenuItemVisualizationTreeVisualizer.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemVisualizationTreeVisualizer_SetText_Text"));
+ jMenuItemVisualizationTreeVisualizer.setText(Messages.getInstance()
+ .getString(
+ "Main_InitGUI_JMenuItemVisualizationTreeVisualizer_SetText_Text"));
jMenuItemVisualizationTreeVisualizer.setMnemonic('T');
- jMenuItemVisualizationTreeVisualizer.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- // choose file
- int retVal = m_FileChooserTreeVisualizer.showOpenDialog(m_Self);
- if (retVal != JFileChooser.APPROVE_OPTION)
- return;
-
- // build tree
- String filename = m_FileChooserTreeVisualizer.getSelectedFile().getAbsolutePath();
- TreeBuild builder = new TreeBuild();
- Node top = null;
- NodePlace arrange = new PlaceNode2();
- try {
- top = builder.create(new FileReader(filename));
- }
- catch (Exception e) {
- e.printStackTrace();
- JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Sixth") + filename + Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Seventh") + e.getMessage());
- return;
- }
-
- // create frame
- createFrame(
- m_Self, jMenuItemVisualizationTreeVisualizer.getText() + " - " + filename,
- new TreeVisualizer(null, top, arrange), new BorderLayout(),
- BorderLayout.CENTER, 800, 600, null, true, true);
- }
- });
+ jMenuItemVisualizationTreeVisualizer
+ .addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ // choose file
+ int retVal = m_FileChooserTreeVisualizer.showOpenDialog(m_Self);
+ if (retVal != JFileChooser.APPROVE_OPTION) {
+ return;
+ }
+
+ // build tree
+ String filename = m_FileChooserTreeVisualizer.getSelectedFile()
+ .getAbsolutePath();
+ TreeBuild builder = new TreeBuild();
+ Node top = null;
+ NodePlace arrange = new PlaceNode2();
+ try {
+ top = builder.create(new FileReader(filename));
+ } catch (Exception e) {
+ e.printStackTrace();
+ JOptionPane
+ .showMessageDialog(
+ m_Self,
+ Messages
+ .getInstance()
+ .getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Sixth")
+ + filename
+ + Messages
+ .getInstance()
+ .getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Seventh")
+ + e.getMessage());
+ return;
+ }
+
+ // create frame
+ createFrame(m_Self, jMenuItemVisualizationTreeVisualizer.getText()
+ + " - " + filename, new TreeVisualizer(null, top, arrange),
+ new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true,
+ true);
+ }
+ });
// Visualization/GraphVisualizer
jMenuItemVisualizationGraphVisualizer = new JMenuItem();
jMenuVisualization.add(jMenuItemVisualizationGraphVisualizer);
- jMenuItemVisualizationGraphVisualizer.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemVisualizationGraphVisualizer_SetText_Text"));
+ jMenuItemVisualizationGraphVisualizer.setText(Messages.getInstance()
+ .getString(
+ "Main_InitGUI_JMenuItemVisualizationGraphVisualizer_SetText_Text"));
jMenuItemVisualizationGraphVisualizer.setMnemonic('G');
- jMenuItemVisualizationGraphVisualizer.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- // choose file
- int retVal = m_FileChooserGraphVisualizer.showOpenDialog(m_Self);
- if (retVal != JFileChooser.APPROVE_OPTION)
- return;
-
- // build graph
- String filename = m_FileChooserGraphVisualizer.getSelectedFile().getAbsolutePath();
- GraphVisualizer panel = new GraphVisualizer();
- try{
- if ( filename.toLowerCase().endsWith(".xml")
- || filename.toLowerCase().endsWith(".bif") ) {
- panel.readBIF(new FileInputStream(filename));
- }
- else {
- panel.readDOT(new FileReader(filename));
- }
- }
- catch (Exception e) {
- e.printStackTrace();
- JOptionPane.showMessageDialog(
- m_Self, Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Eighth") + filename + Messages.getInstance().getString("Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_nineth") + e.getMessage());
- return;
- }
-
- // create frame
- createFrame(
- m_Self, jMenuItemVisualizationGraphVisualizer.getText() + " - " + filename,
- panel, new BorderLayout(),
- BorderLayout.CENTER, 800, 600, null, true, true);
- }
- });
+ jMenuItemVisualizationGraphVisualizer
+ .addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ // choose file
+ int retVal = m_FileChooserGraphVisualizer.showOpenDialog(m_Self);
+ if (retVal != JFileChooser.APPROVE_OPTION) {
+ return;
+ }
+
+ // build graph
+ String filename = m_FileChooserGraphVisualizer.getSelectedFile()
+ .getAbsolutePath();
+ GraphVisualizer panel = new GraphVisualizer();
+ try {
+ if (filename.toLowerCase().endsWith(".xml")
+ || filename.toLowerCase().endsWith(".bif")) {
+ panel.readBIF(new FileInputStream(filename));
+ } else {
+ panel.readDOT(new FileReader(filename));
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ JOptionPane
+ .showMessageDialog(
+ m_Self,
+ Messages
+ .getInstance()
+ .getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_Eighth")
+ + filename
+ + Messages
+ .getInstance()
+ .getString(
+ "Main_InitGUI_Exception_JOptionPaneShowMessageDialog_Text_nineth")
+ + e.getMessage());
+ return;
+ }
+
+ // create frame
+ createFrame(m_Self, jMenuItemVisualizationGraphVisualizer.getText()
+ + " - " + filename, panel, new BorderLayout(),
+ BorderLayout.CENTER, 800, 600, null, true, true);
+ }
+ });
// Visualization/BoundaryVisualizer
jMenuItemVisualizationBoundaryVisualizer = new JMenuItem();
jMenuVisualization.add(jMenuItemVisualizationBoundaryVisualizer);
- jMenuItemVisualizationBoundaryVisualizer.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemVisualizationBoundaryVisualizer_SetText_Text"));
+ jMenuItemVisualizationBoundaryVisualizer
+ .setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemVisualizationBoundaryVisualizer_SetText_Text"));
jMenuItemVisualizationBoundaryVisualizer.setMnemonic('B');
- jMenuItemVisualizationBoundaryVisualizer.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemVisualizationBoundaryVisualizer.getText();
- if (!containsWindow(title)) {
- createFrame(
- m_Self, title, new BoundaryVisualizer(), new BorderLayout(),
- BorderLayout.CENTER, 800, 600, null, true, true);
- // dont' do a System.exit after last window got closed!
- BoundaryVisualizer.setExitIfNoWindowsOpen(false);
- }
- else {
- showWindow(getWindow(title));
- }
- }
- });
+ jMenuItemVisualizationBoundaryVisualizer
+ .addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemVisualizationBoundaryVisualizer.getText();
+ if (!containsWindow(title)) {
+ createFrame(m_Self, title, new BoundaryVisualizer(),
+ new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true,
+ true);
+ // dont' do a System.exit after last window got closed!
+ BoundaryVisualizer.setExitIfNoWindowsOpen(false);
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
+ });
// Extensions
- jMenuExtensions = new JMenu(Messages.getInstance().getString("Main_InitGUI_JMenuExtensions_JMenu_Text"));
+ jMenuExtensions = new JMenu(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuExtensions_JMenu_Text"));
jMenuExtensions.setMnemonic(java.awt.event.KeyEvent.VK_E);
jMenuBar.add(jMenuExtensions);
jMenuExtensions.setVisible(false);
String extensions = GenericObjectEditor.EDITOR_PROPERTIES.getProperty(
- MainMenuExtension.class.getName(), "");
+ MainMenuExtension.class.getName(), "");
if (extensions.length() > 0) {
- jMenuExtensions.setVisible(true);
- String[] classnames = GenericObjectEditor.EDITOR_PROPERTIES.getProperty(
- MainMenuExtension.class.getName(), "").split(",");
- Hashtable<String,JMenu> submenus = new Hashtable<String,JMenu>();
-
- // add all extensions
- for (int i = 0; i < classnames.length; i++) {
- String classname = classnames[i];
- try {
- MainMenuExtension ext = (MainMenuExtension) Class.forName(classname).newInstance();
-
- // menuitem in a submenu?
- JMenu submenu = null;
- if (ext.getSubmenuTitle() != null) {
- submenu = submenus.get(ext.getSubmenuTitle());
- if (submenu == null) {
- submenu = new JMenu(ext.getSubmenuTitle());
- submenus.put(ext.getSubmenuTitle(), submenu);
- insertMenuItem(jMenuExtensions, submenu);
- }
- }
-
- // create menu item
- JMenuItem menuitem = new JMenuItem();
- menuitem.setText(ext.getMenuTitle());
- // does the extension need a frame or does it have its own ActionListener?
- ActionListener listener = ext.getActionListener(m_Self);
- if (listener != null) {
- menuitem.addActionListener(listener);
- }
- else {
- final JMenuItem finalMenuitem = menuitem;
- final MainMenuExtension finalExt = ext;
- menuitem.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- Component frame = createFrame(
- m_Self, finalMenuitem.getText(),
- null, null, null, -1, -1, null, false, false);
- finalExt.fillFrame(frame);
- frame.setVisible(true);
- }
- });
- }
-
- // sorted insert of menu item
- if (submenu != null)
- insertMenuItem(submenu, menuitem);
- else
- insertMenuItem(jMenuExtensions, menuitem);
- }
- catch (Exception e) {
- e.printStackTrace();
- }
- }
+ jMenuExtensions.setVisible(true);
+ String[] classnames = GenericObjectEditor.EDITOR_PROPERTIES
+ .getProperty(MainMenuExtension.class.getName(), "").split(",");
+ Hashtable<String, JMenu> submenus = new Hashtable<String, JMenu>();
+
+ // add all extensions
+ for (String classname : classnames) {
+ try {
+ MainMenuExtension ext = (MainMenuExtension) Class
+ .forName(classname).newInstance();
+
+ // menuitem in a submenu?
+ JMenu submenu = null;
+ if (ext.getSubmenuTitle() != null) {
+ submenu = submenus.get(ext.getSubmenuTitle());
+ if (submenu == null) {
+ submenu = new JMenu(ext.getSubmenuTitle());
+ submenus.put(ext.getSubmenuTitle(), submenu);
+ insertMenuItem(jMenuExtensions, submenu);
+ }
+ }
+
+ // create menu item
+ JMenuItem menuitem = new JMenuItem();
+ menuitem.setText(ext.getMenuTitle());
+ // does the extension need a frame or does it have its own
+ // ActionListener?
+ ActionListener listener = ext.getActionListener(m_Self);
+ if (listener != null) {
+ menuitem.addActionListener(listener);
+ } else {
+ final JMenuItem finalMenuitem = menuitem;
+ final MainMenuExtension finalExt = ext;
+ menuitem.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent e) {
+ Component frame = createFrame(m_Self,
+ finalMenuitem.getText(), null, null, null, -1, -1, null,
+ false, false);
+ finalExt.fillFrame(frame);
+ frame.setVisible(true);
+ }
+ });
+ }
+
+ // sorted insert of menu item
+ if (submenu != null) {
+ insertMenuItem(submenu, menuitem);
+ } else {
+ insertMenuItem(jMenuExtensions, menuitem);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
}
// Windows
- jMenuWindows = new JMenu(Messages.getInstance().getString("Main_InitGUI_JMenuWindows_JMenu_Text"));
+ jMenuWindows = new JMenu(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuWindows_JMenu_Text"));
jMenuWindows.setMnemonic(java.awt.event.KeyEvent.VK_W);
jMenuBar.add(jMenuWindows);
- jMenuWindows.setVisible(false); // initially, there are no windows open
+ jMenuWindows.setVisible(false); // initially, there are no windows open
// Help
jMenuHelp = new JMenu();
jMenuBar.add(jMenuHelp);
- jMenuHelp.setText(Messages.getInstance().getString("Main_InitGUI_JMenuHelp_SetText_Text"));
+ jMenuHelp.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuHelp_SetText_Text"));
jMenuHelp.setMnemonic('H');
// Help/Homepage
jMenuItemHelpHomepage = new JMenuItem();
jMenuHelp.add(jMenuItemHelpHomepage);
- jMenuItemHelpHomepage.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemHelpHomepage_SetText_Text"));
+ jMenuItemHelpHomepage.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemHelpHomepage_SetText_Text"));
jMenuItemHelpHomepage.setMnemonic('H');
jMenuItemHelpHomepage.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- BrowserHelper.openURL(m_Self, Messages.getInstance().getString("Main_InitGUI_BrowserHelper_OpenURL_Text_First"));
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ BrowserHelper.openURL(
+ m_Self,
+ Messages.getInstance().getString(
+ "Main_InitGUI_BrowserHelper_OpenURL_Text_First"));
+ }
});
jMenuHelp.add(new JSeparator());
-/* // Help/WekaDoc
- jMenuItemHelpWekaDoc = new JMenuItem();
- jMenuHelp.add(jMenuItemHelpWekaDoc);
- jMenuItemHelpWekaDoc.setText("Online documentation");
- jMenuItemHelpWekaDoc.setMnemonic('D');
- jMenuItemHelpWekaDoc.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- BrowserHelper.openURL(m_Self, "http://weka.sourceforge.net/wekadoc/");
- }
- }); */
+ /*
+ * // Help/WekaDoc jMenuItemHelpWekaDoc = new JMenuItem();
+ * jMenuHelp.add(jMenuItemHelpWekaDoc);
+ * jMenuItemHelpWekaDoc.setText("Online documentation");
+ * jMenuItemHelpWekaDoc.setMnemonic('D');
+ * jMenuItemHelpWekaDoc.addActionListener(new ActionListener() { public
+ * void actionPerformed(ActionEvent evt) { BrowserHelper.openURL(m_Self,
+ * "http://weka.sourceforge.net/wekadoc/"); } });
+ */
// Help/WekaWiki
jMenuItemHelpWekaWiki = new JMenuItem();
jMenuHelp.add(jMenuItemHelpWekaWiki);
- jMenuItemHelpWekaWiki.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemHelpWekaWiki_SetText_Text"));
+ jMenuItemHelpWekaWiki.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemHelpWekaWiki_SetText_Text"));
jMenuItemHelpWekaWiki.setMnemonic('W');
jMenuItemHelpWekaWiki.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- BrowserHelper.openURL(m_Self, Messages.getInstance().getString("Main_InitGUI_BrowserHelper_OpenURL_Text_Second"));
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ BrowserHelper.openURL(
+ m_Self,
+ Messages.getInstance().getString(
+ "Main_InitGUI_BrowserHelper_OpenURL_Text_Second"));
+ }
});
// Help/Sourceforge
jMenuItemHelpSourceforge = new JMenuItem();
jMenuHelp.add(jMenuItemHelpSourceforge);
- jMenuItemHelpSourceforge.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemHelpSourceforge_SetText_Text"));
+ jMenuItemHelpSourceforge.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemHelpSourceforge_SetText_Text"));
jMenuItemHelpSourceforge.setMnemonic('F');
jMenuItemHelpSourceforge.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- BrowserHelper.openURL(m_Self, Messages.getInstance().getString("Main_InitGUI_BrowserHelperOpenURL_Text_Third"));
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ BrowserHelper.openURL(
+ m_Self,
+ Messages.getInstance().getString(
+ "Main_InitGUI_BrowserHelperOpenURL_Text_Third"));
+ }
});
jMenuHelp.add(new JSeparator());
@@ -1230,39 +1358,44 @@ public class Main
// Help/SystemInfo
jMenuItemHelpSystemInfo = new JMenuItem();
jMenuHelp.add(jMenuItemHelpSystemInfo);
- jMenuItemHelpSystemInfo.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemHelpSystemInfo_SetText_Text"));
+ jMenuItemHelpSystemInfo.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemHelpSystemInfo_SetText_Text"));
jMenuItemHelpHomepage.setMnemonic('S');
jMenuItemHelpSystemInfo.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemHelpSystemInfo.getText();
- if (!containsWindow(title)) {
- // get info
- Hashtable info = new SystemInfo().getSystemInfo();
-
- // sort names
- Vector names = new Vector();
- Enumeration enm = info.keys();
- while (enm.hasMoreElements())
- names.add(enm.nextElement());
- Collections.sort(names);
-
- // generate table
- String[][] data = new String[info.size()][2];
- for (int i = 0; i < names.size(); i++) {
- data[i][0] = names.get(i).toString();
- data[i][1] = info.get(data[i][0]).toString();
- }
- String[] titles = new String[]{Messages.getInstance().getString("Main_InitGUI_Title_Text_First"), Messages.getInstance().getString("Main_InitGUI_Title_Text_Second")};
- JTable table = new JTable(data, titles);
-
- createFrame(
- m_Self, title, new JScrollPane(table), new BorderLayout(),
- BorderLayout.CENTER, 800, 600, null, true, true);
- }
- else {
- showWindow(getWindow(title));
- }
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemHelpSystemInfo.getText();
+ if (!containsWindow(title)) {
+ // get info
+ Hashtable info = new SystemInfo().getSystemInfo();
+
+ // sort names
+ Vector names = new Vector();
+ Enumeration enm = info.keys();
+ while (enm.hasMoreElements()) {
+ names.add(enm.nextElement());
+ }
+ Collections.sort(names);
+
+ // generate table
+ String[][] data = new String[info.size()][2];
+ for (int i = 0; i < names.size(); i++) {
+ data[i][0] = names.get(i).toString();
+ data[i][1] = info.get(data[i][0]).toString();
+ }
+ String[] titles = new String[] {
+ Messages.getInstance().getString("Main_InitGUI_Title_Text_First"),
+ Messages.getInstance()
+ .getString("Main_InitGUI_Title_Text_Second") };
+ JTable table = new JTable(data, titles);
+
+ createFrame(m_Self, title, new JScrollPane(table),
+ new BorderLayout(), BorderLayout.CENTER, 800, 600, null, true,
+ true);
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
});
jMenuHelp.add(new JSeparator());
@@ -1270,181 +1403,191 @@ public class Main
// Help/About
jMenuItemHelpAbout = new JMenuItem();
jMenuHelp.add(jMenuItemHelpAbout);
- jMenuItemHelpAbout.setText(Messages.getInstance().getString("Main_InitGUI_JMenuItemHelpAbout_SetText_Text"));
+ jMenuItemHelpAbout.setText(Messages.getInstance().getString(
+ "Main_InitGUI_JMenuItemHelpAbout_SetText_Text"));
jMenuItemHelpAbout.setMnemonic('A');
jMenuItemHelpAbout.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent evt) {
- String title = jMenuItemHelpAbout.getText();
- if (!containsWindow(title)) {
- JPanel wekaPan = new JPanel();
- wekaPan.setToolTipText(Messages.getInstance().getString("Main_InitGUI_WekaPan_JPanel_SetToolTipText_Text"));
- ImageIcon wii = new ImageIcon(Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("weka/gui/weka3.gif")));
- JLabel wekaLab = new JLabel(wii);
- wekaPan.add(wekaLab);
- Container frame = createFrame(
- m_Self, title, wekaPan, new BorderLayout(),
- BorderLayout.CENTER, -1, -1, null, true, true);
-
- JPanel titlePan = new JPanel();
- titlePan.setLayout(new GridLayout(8,1));
- titlePan.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
- titlePan.add(new JLabel(Messages.getInstance().getString("Main_InitGUI_TitlePan_Add_JLabel_Text_First"), SwingConstants.CENTER));
- titlePan.add(new JLabel(Messages.getInstance().getString("Main_InitGUI_TitlePan_Add_JLabel_Text_Second"), SwingConstants.CENTER));
- titlePan.add(new JLabel(Messages.getInstance().getString("Main_InitGUI_TitlePan_Add_JLabel_Text_Third")));
- titlePan.add(new JLabel(Messages.getInstance().getString("Main_InitGUI_TitlePan_Add_JLabel_Text_Fourth") + Version.VERSION, SwingConstants.CENTER));
- titlePan.add(new JLabel(Messages.getInstance().getString("Main_InitGUI_TitlePan_Add_JLabel_Text_Fifth")));
- titlePan.add(new JLabel(Messages.getInstance().getString("Main_InitGUI_TitlePan_Add_JLabel_Text_Sixth") + Copyright.getFromYear() + " - " + Copyright.getToYear(), SwingConstants.CENTER));
- titlePan.add(new JLabel(Copyright.getOwner(), SwingConstants.CENTER));
- titlePan.add(new JLabel(Copyright.getAddress(), SwingConstants.CENTER));
-
- if (frame instanceof ChildFrameMDI) {
- ((ChildFrameMDI) frame).getContentPane().add(titlePan, BorderLayout.NORTH);
- ((ChildFrameMDI) frame).pack();
- }
- else if (frame instanceof ChildFrameSDI) {
- ((ChildFrameSDI) frame).getContentPane().add(titlePan, BorderLayout.NORTH);
- ((ChildFrameSDI) frame).pack();
- }
- }
- else {
- showWindow(getWindow(title));
- }
- }
+ @Override
+ public void actionPerformed(ActionEvent evt) {
+ String title = jMenuItemHelpAbout.getText();
+ if (!containsWindow(title)) {
+ JPanel wekaPan = new JPanel();
+ wekaPan.setToolTipText(Messages.getInstance().getString(
+ "Main_InitGUI_WekaPan_JPanel_SetToolTipText_Text"));
+ ImageIcon wii = new ImageIcon(Toolkit.getDefaultToolkit().getImage(
+ ClassLoader.getSystemResource("weka/gui/weka3.gif")));
+ JLabel wekaLab = new JLabel(wii);
+ wekaPan.add(wekaLab);
+ Container frame = createFrame(m_Self, title, wekaPan,
+ new BorderLayout(), BorderLayout.CENTER, -1, -1, null, true, true);
+
+ JPanel titlePan = new JPanel();
+ titlePan.setLayout(new GridLayout(8, 1));
+ titlePan.setBorder(BorderFactory.createEmptyBorder(10, 5, 10, 5));
+ titlePan.add(new JLabel(Messages.getInstance().getString(
+ "Main_InitGUI_TitlePan_Add_JLabel_Text_First"),
+ SwingConstants.CENTER));
+ titlePan.add(new JLabel(Messages.getInstance().getString(
+ "Main_InitGUI_TitlePan_Add_JLabel_Text_Second"),
+ SwingConstants.CENTER));
+ titlePan.add(new JLabel(Messages.getInstance().getString(
+ "Main_InitGUI_TitlePan_Add_JLabel_Text_Third")));
+ titlePan.add(new JLabel(Messages.getInstance().getString(
+ "Main_InitGUI_TitlePan_Add_JLabel_Text_Fourth")
+ + Version.VERSION, SwingConstants.CENTER));
+ titlePan.add(new JLabel(Messages.getInstance().getString(
+ "Main_InitGUI_TitlePan_Add_JLabel_Text_Fifth")));
+ titlePan.add(new JLabel(Messages.getInstance().getString(
+ "Main_InitGUI_TitlePan_Add_JLabel_Text_Sixth")
+ + Copyright.getFromYear() + " - " + Copyright.getToYear(),
+ SwingConstants.CENTER));
+ titlePan.add(new JLabel(Copyright.getOwner(), SwingConstants.CENTER));
+ titlePan.add(new JLabel(Copyright.getAddress(),
+ SwingConstants.CENTER));
+
+ if (frame instanceof ChildFrameMDI) {
+ ((ChildFrameMDI) frame).getContentPane().add(titlePan,
+ BorderLayout.NORTH);
+ ((ChildFrameMDI) frame).pack();
+ } else if (frame instanceof ChildFrameSDI) {
+ ((ChildFrameSDI) frame).getContentPane().add(titlePan,
+ BorderLayout.NORTH);
+ ((ChildFrameSDI) frame).pack();
+ }
+ } else {
+ showWindow(getWindow(title));
+ }
+ }
});
// size + position
int screenHeight = getGraphicsConfiguration().getBounds().height;
- int screenWidth = getGraphicsConfiguration().getBounds().width;
+ int screenWidth = getGraphicsConfiguration().getBounds().width;
if (m_GUIType == GUI_MDI) {
- int newHeight = (int) (((double) screenHeight) * 0.75);
- int newWidth = (int) (((double) screenWidth) * 0.75);
- setSize(
- 1000 > newWidth ? newWidth : 1000,
- 800 > newHeight ? newHeight : 800);
- setLocation(
- (screenWidth - getBounds().width) / 2,
- (screenHeight - getBounds().height) / 2);
+ int newHeight = (int) (screenHeight * 0.75);
+ int newWidth = (int) (screenWidth * 0.75);
+ setSize(1000 > newWidth ? newWidth : 1000, 800 > newHeight ? newHeight
+ : 800);
+ setLocation((screenWidth - getBounds().width) / 2,
+ (screenHeight - getBounds().height) / 2);
+ } else if (m_GUIType == GUI_SDI) {
+ pack();
+ setSize(screenWidth, getHeight());
+ setLocation(0, 0);
}
- else if (m_GUIType == GUI_SDI) {
- pack();
- setSize(screenWidth, getHeight());
- setLocation(0, 0);
- }
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
-
+
/**
* creates and displays the title.
*
- * @param title the additional part of the title
+ * @param title the additional part of the title
*/
protected void createTitle(String title) {
- String newTitle;
-
- newTitle = Messages.getInstance().getString("Main_CreateTitle_NewTitle_Text") + new Version();
- if (title.length() != 0)
+ String newTitle;
+
+ newTitle = Messages.getInstance().getString(
+ "Main_CreateTitle_NewTitle_Text")
+ + new Version();
+ if (title.length() != 0) {
newTitle += " - " + title;
-
+ }
+
setTitle(newTitle);
}
-
+
/**
* adds the given child frame to the list of frames.
*
- * @param c the child frame to add
+ * @param c the child frame to add
*/
public void addChildFrame(Container c) {
m_ChildFrames.add(c);
windowListChanged();
}
-
+
/**
* tries to remove the child frame, it returns true if it could do such.
*
- * @param c the child frame to remove
- * @return true if the child frame could be removed
+ * @param c the child frame to remove
+ * @return true if the child frame could be removed
*/
public boolean removeChildFrame(Container c) {
boolean result = m_ChildFrames.remove(c);
windowListChanged();
return result;
}
-
+
/**
* brings child frame to the top.
*
- * @param c the frame to activate
- * @return true if frame was activated
+ * @param c the frame to activate
+ * @return true if frame was activated
*/
public boolean showWindow(Container c) {
- boolean result;
- ChildFrameMDI mdiFrame;
- ChildFrameSDI sdiFrame;
-
+ boolean result;
+ ChildFrameMDI mdiFrame;
+ ChildFrameSDI sdiFrame;
+
if (c != null) {
try {
- if (c instanceof ChildFrameMDI) {
- mdiFrame = (ChildFrameMDI) c;
- mdiFrame.setIcon(false);
- mdiFrame.toFront();
- createTitle(mdiFrame.getTitle());
- }
- else if (c instanceof ChildFrameSDI) {
- sdiFrame = (ChildFrameSDI) c;
- sdiFrame.setExtendedState(JFrame.NORMAL);
- sdiFrame.toFront();
- createTitle(sdiFrame.getTitle());
- }
- }
- catch (Exception e) {
- e.printStackTrace();
+ if (c instanceof ChildFrameMDI) {
+ mdiFrame = (ChildFrameMDI) c;
+ mdiFrame.setIcon(false);
+ mdiFrame.toFront();
+ createTitle(mdiFrame.getTitle());
+ } else if (c instanceof ChildFrameSDI) {
+ sdiFrame = (ChildFrameSDI) c;
+ sdiFrame.setExtendedState(JFrame.NORMAL);
+ sdiFrame.toFront();
+ createTitle(sdiFrame.getTitle());
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
}
result = true;
- }
- else {
+ } else {
result = false;
}
-
+
return result;
}
-
+
/**
- * brings the first frame to the top that is of the specified
- * window class.
- *
- * @param windowClass the class to display the first child for
- * @return true, if a child was found and brought to front
+ * brings the first frame to the top that is of the specified window class.
+ *
+ * @param windowClass the class to display the first child for
+ * @return true, if a child was found and brought to front
*/
public boolean showWindow(Class windowClass) {
return showWindow(getWindow(windowClass));
}
-
+
/**
* returns all currently open frames.
*
- * @return an iterator over all currently open frame
+ * @return an iterator over all currently open frame
*/
public Iterator getWindowList() {
return m_ChildFrames.iterator();
}
/**
- * returns the first instance of the given window class, null if none can be
+ * returns the first instance of the given window class, null if none can be
* found.
*
- * @param windowClass the class to retrieve the first instance for
- * @return null, if no instance can be found
+ * @param windowClass the class to retrieve the first instance for
+ * @return null, if no instance can be found
*/
public Container getWindow(Class windowClass) {
- Container result;
- Iterator iter;
- Container current;
-
+ Container result;
+ Iterator iter;
+ Container current;
+
result = null;
- iter = getWindowList();
+ iter = getWindowList();
while (iter.hasNext()) {
current = (Container) iter.next();
if (current.getClass() == windowClass) {
@@ -1452,161 +1595,167 @@ public class Main
break;
}
}
-
+
return result;
}
/**
- * returns the first window with the given title, null if none can be
- * found.
+ * returns the first window with the given title, null if none can be found.
*
- * @param title the title to look for
- * @return null, if no instance can be found
+ * @param title the title to look for
+ * @return null, if no instance can be found
*/
public Container getWindow(String title) {
- Container result;
- Iterator iter;
- Container current;
- boolean found;
-
+ Container result;
+ Iterator iter;
+ Container current;
+ boolean found;
+
result = null;
- iter = getWindowList();
+ iter = getWindowList();
while (iter.hasNext()) {
current = (Container) iter.next();
- found = false;
-
- if (current instanceof ChildFrameMDI)
- found = ((ChildFrameMDI) current).getTitle().equals(title);
- else if (current instanceof ChildFrameSDI)
- found = ((ChildFrameSDI) current).getTitle().equals(title);
-
+ found = false;
+
+ if (current instanceof ChildFrameMDI) {
+ found = ((ChildFrameMDI) current).getTitle().equals(title);
+ } else if (current instanceof ChildFrameSDI) {
+ found = ((ChildFrameSDI) current).getTitle().equals(title);
+ }
+
if (found) {
result = current;
break;
}
}
-
+
return result;
}
-
+
/**
- * checks, whether an instance of the given window class is already in
- * the Window list.
+ * checks, whether an instance of the given window class is already in the
+ * Window list.
*
- * @param windowClass the class to check for an instance in the current
- * window list
- * @return true if the class is already listed in the Window list
+ * @param windowClass the class to check for an instance in the current window
+ * list
+ * @return true if the class is already listed in the Window list
*/
public boolean containsWindow(Class windowClass) {
return (getWindow(windowClass) != null);
}
-
+
/**
- * checks, whether a window with the given title is already in
- * the Window list.
+ * checks, whether a window with the given title is already in the Window
+ * list.
*
- * @param title the title to check for in the current window list
- * @return true if a window with the given title is already
- * listed in the Window list
+ * @param title the title to check for in the current window list
+ * @return true if a window with the given title is already listed in the
+ * Window list
*/
public boolean containsWindow(String title) {
return (getWindow(title) != null);
}
-
+
/**
* minimizes all windows.
*/
public void minimizeWindows() {
- Iterator iter;
- Container frame;
-
+ Iterator iter;
+ Container frame;
+
iter = getWindowList();
while (iter.hasNext()) {
frame = (Container) iter.next();
try {
- if (frame instanceof ChildFrameMDI)
- ((ChildFrameMDI) frame).setIcon(true);
- else if (frame instanceof ChildFrameSDI)
- ((ChildFrameSDI) frame).setExtendedState(JFrame.ICONIFIED);
- }
- catch (Exception e) {
- e.printStackTrace();
+ if (frame instanceof ChildFrameMDI) {
+ ((ChildFrameMDI) frame).setIcon(true);
+ } else if (frame instanceof ChildFrameSDI) {
+ ((ChildFrameSDI) frame).setExtendedState(JFrame.ICONIFIED);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
}
}
}
-
+
/**
* restores all windows.
*/
public void restoreWindows() {
- Iterator iter;
- Container frame;
-
+ Iterator iter;
+ Container frame;
+
iter = getWindowList();
while (iter.hasNext()) {
frame = (Container) iter.next();
try {
- if (frame instanceof ChildFrameMDI)
- ((ChildFrameMDI) frame).setIcon(false);
- else if (frame instanceof ChildFrameSDI)
- ((ChildFrameSDI) frame).setExtendedState(JFrame.NORMAL);
- }
- catch (Exception e) {
- e.printStackTrace();
+ if (frame instanceof ChildFrameMDI) {
+ ((ChildFrameMDI) frame).setIcon(false);
+ } else if (frame instanceof ChildFrameSDI) {
+ ((ChildFrameSDI) frame).setExtendedState(JFrame.NORMAL);
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
}
}
}
-
+
/**
* is called when window list changed somehow (add or remove).
*/
public void windowListChanged() {
createWindowMenu();
}
-
+
/**
* creates the menu of currently open windows.
*/
protected synchronized void createWindowMenu() {
- Iterator iter;
- JMenuItem menuItem;
- int startIndex;
-
+ Iterator iter;
+ JMenuItem menuItem;
+ int startIndex;
+
// remove all existing entries
jMenuWindows.removeAll();
-
+
// minimize + restore + separator
- menuItem = new JMenuItem(Messages.getInstance().getString("Main_CreateWindowMenu_MenuItem_JMenuItem_Text_First"));
+ menuItem = new JMenuItem(Messages.getInstance().getString(
+ "Main_CreateWindowMenu_MenuItem_JMenuItem_Text_First"));
menuItem.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent evt) {
minimizeWindows();
}
});
jMenuWindows.add(menuItem);
-
- menuItem = new JMenuItem(Messages.getInstance().getString("Main_CreateWindowMenu_MenuItem_JMenuItem_Text_Second"));
+
+ menuItem = new JMenuItem(Messages.getInstance().getString(
+ "Main_CreateWindowMenu_MenuItem_JMenuItem_Text_Second"));
menuItem.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent evt) {
restoreWindows();
}
});
jMenuWindows.add(menuItem);
-
+
jMenuWindows.addSeparator();
-
+
// windows
startIndex = jMenuWindows.getMenuComponentCount() - 1;
iter = getWindowList();
jMenuWindows.setVisible(iter.hasNext());
while (iter.hasNext()) {
Container frame = (Container) iter.next();
- if (frame instanceof ChildFrameMDI)
- menuItem = new JMenuItem(((ChildFrameMDI) frame).getTitle());
- else if (frame instanceof ChildFrameSDI)
- menuItem = new JMenuItem(((ChildFrameSDI) frame).getTitle());
+ if (frame instanceof ChildFrameMDI) {
+ menuItem = new JMenuItem(((ChildFrameMDI) frame).getTitle());
+ } else if (frame instanceof ChildFrameSDI) {
+ menuItem = new JMenuItem(((ChildFrameSDI) frame).getTitle());
+ }
insertMenuItem(jMenuWindows, menuItem, startIndex);
menuItem.setActionCommand(Integer.toString(frame.hashCode()));
menuItem.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent evt) {
Container frame = null;
Iterator iter = getWindowList();
@@ -1623,45 +1772,47 @@ public class Main
});
}
}
-
+
/**
* Shows or hides this component depending on the value of parameter b.
*
- * @param b if true, shows this component; otherwise, hides this
- * component
+ * @param b if true, shows this component; otherwise, hides this component
*/
+ @Override
public void setVisible(boolean b) {
super.setVisible(b);
-
- if (b)
+
+ if (b) {
paint(this.getGraphics());
+ }
}
-
+
/**
* Create the singleton instance of the Main GUI.
*
- * @param args commandline options
+ * @param args commandline options
*/
public static void createSingleton(String[] args) {
- if (m_MainSingleton == null)
+ if (m_MainSingleton == null) {
m_MainSingleton = new Main();
-
+ }
+
// set options
try {
m_MainSingleton.setOptions(args);
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
// notify listeners (if any)
- for (int i = 0; i < m_StartupListeners.size(); i++)
+ for (int i = 0; i < m_StartupListeners.size(); i++) {
((StartUpListener) m_StartupListeners.elementAt(i)).startUpComplete();
+ }
}
/**
* Return the singleton instance of the Main GUI.
- *
+ *
* @return the singleton instance
*/
public static Main getSingleton() {
@@ -1671,7 +1822,7 @@ public class Main
/**
* Add a listener to be notified when startup is complete.
*
- * @param s a listener to add
+ * @param s a listener to add
*/
public static void addStartupListener(StartUpListener s) {
m_StartupListeners.add(s);
@@ -1679,80 +1830,87 @@ public class Main
/**
* Gets an enumeration describing the available options.
- *
- * @return an enumeration of all the available options.
+ *
+ * @return an enumeration of all the available options.
*/
- public Enumeration listOptions(){
- Vector result;
- String desc;
- SelectedTag tag;
- int i;
+ @Override
+ public Enumeration listOptions() {
+ Vector result;
+ String desc;
+ SelectedTag tag;
+ int i;
result = new Vector();
- desc = "";
+ desc = "";
for (i = 0; i < TAGS_GUI.length; i++) {
tag = new SelectedTag(TAGS_GUI[i].getID(), TAGS_GUI);
- desc += "\t" + tag.getSelectedTag().getIDStr()
- + " = " + tag.getSelectedTag().getReadable()
- + "\n";
+ desc += "\t" + tag.getSelectedTag().getIDStr() + " = "
+ + tag.getSelectedTag().getReadable() + "\n";
}
- result.addElement(new Option(
- Messages.getInstance().getString("Main_ListOptions_Option_Text_First")
- + desc
- + Messages.getInstance().getString("Main_ListOptions_Option_Text_Second") + new SelectedTag(GUI_MDI, TAGS_GUI) + ")",
- "gui", 1, "-gui " + Tag.toOptionList(TAGS_GUI)));
+ result.addElement(new Option(Messages.getInstance().getString(
+ "Main_ListOptions_Option_Text_First")
+ + desc
+ + Messages.getInstance().getString("Main_ListOptions_Option_Text_Second")
+ + new SelectedTag(GUI_MDI, TAGS_GUI) + ")", "gui", 1, "-gui "
+ + Tag.toOptionList(TAGS_GUI)));
return result.elements();
}
-
+
/**
* returns the options of the current setup.
- *
- * @return the current options
+ *
+ * @return the current options
*/
- public String[] getOptions(){
- Vector<String> result;
+ @Override
+ public String[] getOptions() {
+ Vector<String> result;
result = new Vector();
result.add("-gui");
result.add("" + getGUIType());
- return result.toArray(new String[result.size()]);
+ return result.toArray(new String[result.size()]);
}
/**
- * Parses the options for this object. <p/>
- *
- <!-- options-start -->
- * Valid options are: <p/>
+ * Parses the options for this object.
+ * <p/>
+ *
+ * <!-- options-start --> Valid options are:
+ * <p/>
*
- * <pre> -gui <MDI|SDI>
+ * <pre>
+ * -gui <MDI|SDI>
* Determines the layout of the GUI:
* MDI = MDI Layout
* SDI = SDI Layout
- * (default: MDI)</pre>
+ * (default: MDI)
+ * </pre>
*
- <!-- options-end -->
- *
- * @param options the options to use
- * @throws Exception if setting of options fails
+ * <!-- options-end -->
+ *
+ * @param options the options to use
+ * @throws Exception if setting of options fails
*/
+ @Override
public void setOptions(String[] options) throws Exception {
- String tmpStr;
+ String tmpStr;
tmpStr = Utils.getOption("gui", options);
- if (tmpStr.length() != 0)
+ if (tmpStr.length() != 0) {
setGUIType(new SelectedTag(tmpStr, TAGS_GUI));
- else
+ } else {
setGUIType(new SelectedTag(GUI_MDI, TAGS_GUI));
+ }
}
/**
- * Sets the type of GUI to use.
- *
- * @param value .the GUI type
+ * Sets the type of GUI to use.
+ *
+ * @param value .the GUI type
*/
public void setGUIType(SelectedTag value) {
if (value.getTags() == TAGS_GUI) {
@@ -1762,102 +1920,112 @@ public class Main
}
/**
- * Gets the currently set type of GUI to display.
+ * Gets the currently set type of GUI to display.
*
- * @return the current GUI Type.
+ * @return the current GUI Type.
*/
public SelectedTag getGUIType() {
return new SelectedTag(m_GUIType, TAGS_GUI);
}
-
+
/**
* starts the application.
*
- * @param args the commandline arguments - ignored
+ * @param args the commandline arguments - ignored
*/
public static void main(String[] args) {
- weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages.getInstance().getString("Main_Main_Logger_Text"));
-
+ weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages
+ .getInstance().getString("Main_Main_Logger_Text"));
+
LookAndFeel.setLookAndFeel();
-
+
try {
// uncomment the following line to disable the memory management:
- //m_Memory.setEnabled(false);
+ // m_Memory.setEnabled(false);
// help?
if (Utils.getFlag('h', args)) {
- System.out.println();
- System.out.println(Messages.getInstance().getString("Main_Main_Text_First"));
- System.out.println();
- System.out.println(Messages.getInstance().getString("Main_Main_Text_Second"));
- System.out.println();
- System.out.println("-h");
- System.out.println(Messages.getInstance().getString("Main_Main_Text_Third"));
- System.out.println();
-
- Enumeration enu = new Main().listOptions();
- while (enu.hasMoreElements()) {
- Option option = (Option) enu.nextElement();
- System.out.println(option.synopsis());
- System.out.println(option.description());
- }
-
- System.out.println();
- System.exit(0);
+ System.out.println();
+ System.out.println(Messages.getInstance().getString(
+ "Main_Main_Text_First"));
+ System.out.println();
+ System.out.println(Messages.getInstance().getString(
+ "Main_Main_Text_Second"));
+ System.out.println();
+ System.out.println("-h");
+ System.out.println(Messages.getInstance().getString(
+ "Main_Main_Text_Third"));
+ System.out.println();
+
+ Enumeration enu = new Main().listOptions();
+ while (enu.hasMoreElements()) {
+ Option option = (Option) enu.nextElement();
+ System.out.println(option.synopsis());
+ System.out.println(option.description());
+ }
+
+ System.out.println();
+ System.exit(0);
}
-
+
// setup splash screen
Main.addStartupListener(new weka.gui.beans.StartUpListener() {
+ @Override
public void startUpComplete() {
m_MainCommandline = Main.getSingleton();
m_MainCommandline.setVisible(true);
}
});
Main.addStartupListener(new StartUpListener() {
+ @Override
public void startUpComplete() {
SplashWindow.disposeSplash();
}
});
- SplashWindow.splash(ClassLoader.getSystemResource("weka/gui/images/weka_splash.gif"));
+ SplashWindow.splash(ClassLoader
+ .getSystemResource("weka/gui/images/weka_splash.gif"));
// start GUI
- final String[] options = (String[]) args.clone();
+ final String[] options = args.clone();
Thread nt = new Thread() {
- public void run() {
- weka.gui.SplashWindow.invokeMethod(
- Main.class.getName(), "createSingleton", options);
- }
+ @Override
+ public void run() {
+ weka.gui.SplashWindow.invokeMethod(Main.class.getName(),
+ "createSingleton", options);
+ }
};
nt.start();
-
+
Thread memMonitor = new Thread() {
- public void run() {
- while(true) {
- try {
- Thread.sleep(4000);
- System.gc();
-
- if (m_Memory.isOutOfMemory()) {
- // clean up
- m_MainCommandline = null;
- System.gc();
-
- // display error
- System.err.println(Messages.getInstance().getString("Main_Main_Thread_Run_Error_Text_First"));
- m_Memory.showOutOfMemory();
- System.err.println(Messages.getInstance().getString("Main_Main_Thread_Run_Error_Text_Second"));
- System.exit(-1);
- }
-
- } catch(InterruptedException ex) { ex.printStackTrace(); }
- }
- }
+ @Override
+ public void run() {
+ while (true) {
+ // try {
+ // Thread.sleep(4000);
+ // System.gc();
+
+ if (m_Memory.isOutOfMemory()) {
+ // clean up
+ m_MainCommandline = null;
+ System.gc();
+
+ // display error
+ System.err.println(Messages.getInstance().getString(
+ "Main_Main_Thread_Run_Error_Text_First"));
+ m_Memory.showOutOfMemory();
+ System.err.println(Messages.getInstance().getString(
+ "Main_Main_Thread_Run_Error_Text_Second"));
+ System.exit(-1);
+ }
+
+ // } catch(InterruptedException ex) { ex.printStackTrace(); }
+ }
+ }
};
-
+
memMonitor.setPriority(Thread.MAX_PRIORITY);
memMonitor.start();
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
diff --git a/src/main/java/weka/gui/PropertySheetPanel.java b/src/main/java/weka/gui/PropertySheetPanel.java
index a9f5179..ccee9e4 100644
--- a/src/main/java/weka/gui/PropertySheetPanel.java
+++ b/src/main/java/weka/gui/PropertySheetPanel.java
@@ -20,13 +20,8 @@
*
*/
-
package weka.gui;
-import weka.core.Capabilities;
-import weka.core.CapabilitiesHandler;
-import weka.core.MultiInstanceCapabilitiesHandler;
-
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dialog;
@@ -68,16 +63,19 @@ import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
+import weka.core.Capabilities;
+import weka.core.CapabilitiesHandler;
+import weka.core.MultiInstanceCapabilitiesHandler;
-/**
- * Displays a property sheet where (supported) properties of the target
- * object may be edited.
- *
+/**
+ * Displays a property sheet where (supported) properties of the target object
+ * may be edited.
+ *
* @author Len Trigg (trigg at cs.waikato.ac.nz)
- * @version $Revision: 7059 $
+ * @version $Revision: 10570 $
*/
-public class PropertySheetPanel extends JPanel
- implements PropertyChangeListener {
+public class PropertySheetPanel extends JPanel implements
+ PropertyChangeListener {
/** for serialization. */
private static final long serialVersionUID = -8939835593429918345L;
@@ -85,35 +83,34 @@ public class PropertySheetPanel extends JPanel
/**
* A specialized dialog for displaying the capabilities.
*/
- protected class CapabilitiesHelpDialog
- extends JDialog
- implements PropertyChangeListener {
-
+ protected class CapabilitiesHelpDialog extends JDialog implements
+ PropertyChangeListener {
+
/** for serialization. */
private static final long serialVersionUID = -1404770987103289858L;
-
+
/** the dialog itself. */
private CapabilitiesHelpDialog m_Self;
-
+
/**
* default constructor.
*
- * @param owner the owning frame
+ * @param owner the owning frame
*/
public CapabilitiesHelpDialog(Frame owner) {
super(owner);
-
+
initialize();
}
-
+
/**
* default constructor.
*
- * @param owner the owning dialog
+ * @param owner the owning dialog
*/
public CapabilitiesHelpDialog(Dialog owner) {
super(owner);
-
+
initialize();
}
@@ -121,10 +118,11 @@ public class PropertySheetPanel extends JPanel
* Initializes the dialog.
*/
protected void initialize() {
- setTitle(Messages.getInstance().getString("PropertySheetPanel_CapabilitiesHelpDialog_Initialize_SetTitle_Text"));
+ setTitle(Messages.getInstance().getString(
+ "PropertySheetPanel_CapabilitiesHelpDialog_Initialize_SetTitle_Text"));
m_Self = this;
-
+
m_CapabilitiesText = new JTextArea();
m_CapabilitiesText.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
m_CapabilitiesText.setLineWrap(true);
@@ -132,117 +130,145 @@ public class PropertySheetPanel extends JPanel
m_CapabilitiesText.setEditable(false);
updateText();
addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- m_Self.dispose();
- if (m_CapabilitiesDialog == m_Self) {
- m_CapabilitiesBut.setEnabled(true);
- }
- }
+ @Override
+ public void windowClosing(WindowEvent e) {
+ m_Self.dispose();
+ if (m_CapabilitiesDialog == m_Self) {
+ m_CapabilitiesBut.setEnabled(true);
+ }
+ }
});
getContentPane().setLayout(new BorderLayout());
- getContentPane().add(new JScrollPane(m_CapabilitiesText), BorderLayout.CENTER);
+ getContentPane().add(new JScrollPane(m_CapabilitiesText),
+ BorderLayout.CENTER);
pack();
}
/**
- * returns a comma-separated list of all the capabilities.
- *
- * @param c the capabilities to get a string representation from
- * @return the string describing the capabilities
- */
- protected String listCapabilities(Capabilities c) {
- String result;
- Iterator iter;
-
- result = "";
- iter = c.capabilities();
- while (iter.hasNext()) {
- if (result.length() != 0)
- result += ", ";
- result += iter.next().toString();
- }
-
- return result;
- }
-
- /**
- * generates a string from the capapbilities, suitable to add to the help
- * text.
- *
- * @param title the title for the capabilities
- * @param c the capabilities
- * @return a string describing the capabilities
- */
- protected String addCapabilities(String title, Capabilities c) {
- String result;
- String caps;
-
- result = title + "\n";
-
- // class
- caps = listCapabilities(c.getClassCapabilities());
- if (caps.length() != 0) {
- result += Messages.getInstance().getString("PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_First");
- result += caps;
- result += Messages.getInstance().getString("PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Second");
- }
-
- // attribute
- caps = listCapabilities(c.getAttributeCapabilities());
- if (caps.length() != 0) {
- result += Messages.getInstance().getString("PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Third");
- result += caps;
- result += Messages.getInstance().getString("PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Fourth");
- }
-
- // other capabilities
- caps = listCapabilities(c.getOtherCapabilities());
- if (caps.length() != 0) {
- result += Messages.getInstance().getString("PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Fifth");
- result += caps;
- result += Messages.getInstance().getString("PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Sixth");
- }
-
- // additional stuff
- result += Messages.getInstance().getString("PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Seventh");
- result += Messages.getInstance().getString("PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Eighth") + c.getMinimumNumberInstances() + "\n";
- result += "\n";
-
- return result;
- }
-
- /**
* updates the content of the capabilities help dialog.
*/
protected void updateText() {
StringBuffer helpText = new StringBuffer();
-
- if (m_Target instanceof CapabilitiesHandler)
- helpText.append(
- addCapabilities(
- "CAPABILITIES",
- ((CapabilitiesHandler) m_Target).getCapabilities()));
-
- if (m_Target instanceof MultiInstanceCapabilitiesHandler)
- helpText.append(
- addCapabilities(
- "MI CAPABILITIES",
- ((MultiInstanceCapabilitiesHandler) m_Target).getMultiInstanceCapabilities()));
-
+
+ if (m_Target instanceof CapabilitiesHandler) {
+ helpText.append(addCapabilities("CAPABILITIES",
+ ((CapabilitiesHandler) m_Target).getCapabilities()));
+ }
+
+ if (m_Target instanceof MultiInstanceCapabilitiesHandler) {
+ helpText.append(addCapabilities("MI CAPABILITIES",
+ ((MultiInstanceCapabilitiesHandler) m_Target)
+ .getMultiInstanceCapabilities()));
+ }
+
m_CapabilitiesText.setText(helpText.toString());
m_CapabilitiesText.setCaretPosition(0);
}
-
+
/**
* This method gets called when a bound property is changed.
- *
- * @param evt the change event
+ *
+ * @param evt the change event
*/
+ @Override
public void propertyChange(PropertyChangeEvent evt) {
updateText();
}
}
-
+
+ /**
+ * returns a comma-separated list of all the capabilities.
+ *
+ * @param c the capabilities to get a string representation from
+ * @return the string describing the capabilities
+ */
+ public static String listCapabilities(Capabilities c) {
+ String result;
+ Iterator iter;
+
+ result = "";
+ iter = c.capabilities();
+ while (iter.hasNext()) {
+ if (result.length() != 0) {
+ result += ", ";
+ }
+ result += iter.next().toString();
+ }
+
+ return result;
+ }
+
+ /**
+ * generates a string from the capapbilities, suitable to add to the help
+ * text.
+ *
+ * @param title the title for the capabilities
+ * @param c the capabilities
+ * @return a string describing the capabilities
+ */
+ public static String addCapabilities(String title, Capabilities c) {
+ String result;
+ String caps;
+
+ result = title + "\n";
+
+ // class
+ caps = listCapabilities(c.getClassCapabilities());
+ if (caps.length() != 0) {
+ result += Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_First");
+ result += caps;
+ result += Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Second");
+ }
+
+ // attribute
+ caps = listCapabilities(c.getAttributeCapabilities());
+ if (caps.length() != 0) {
+ result += Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Third");
+ result += caps;
+ result += Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Fourth");
+ }
+
+ // other capabilities
+ caps = listCapabilities(c.getOtherCapabilities());
+ if (caps.length() != 0) {
+ result += Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Fifth");
+ result += caps;
+ result += Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Sixth");
+ }
+
+ // additional stuff
+ result += Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Seventh");
+ result += Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_CapabilitiesHelpDialog_AddCapabilities_SetTitle_Text_Eighth")
+ + c.getMinimumNumberInstances() + "\n";
+ result += "\n";
+
+ return result;
+ }
+
/** The target object being edited. */
private Object m_Target;
@@ -281,15 +307,17 @@ public class PropertySheetPanel extends JPanel
/** Button to pop up the capabilities in a separate dialog. */
private JButton m_CapabilitiesBut;
-
+
/** the TextArea of the Capabilities help dialog. */
private JTextArea m_CapabilitiesText;
/** A count of the number of properties we have an editor for. */
private int m_NumEditable = 0;
- /** The panel holding global info and help, if provided by
- the object being editied. */
+ /**
+ * The panel holding global info and help, if provided by the object being
+ * editied.
+ */
private JPanel m_aboutPanel;
/**
@@ -297,30 +325,31 @@ public class PropertySheetPanel extends JPanel
*/
public PropertySheetPanel() {
- // setBorder(BorderFactory.createLineBorder(Color.red));
+ // setBorder(BorderFactory.createLineBorder(Color.red));
setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
}
/**
- * Return the panel containing global info and help for
- * the object being edited. May return null if the edited
- * object provides no global info or tip text.
- *
+ * Return the panel containing global info and help for the object being
+ * edited. May return null if the edited object provides no global info or tip
+ * text.
+ *
* @return the about panel.
*/
public JPanel getAboutPanel() {
return m_aboutPanel;
}
- /** A support object for handling property change listeners. */
- private PropertyChangeSupport support = new PropertyChangeSupport(this);
+ /** A support object for handling property change listeners. */
+ private final PropertyChangeSupport support = new PropertyChangeSupport(this);
/**
* Updates the property sheet panel with a changed property and also passed
* the event along.
- *
+ *
* @param evt a value of type 'PropertyChangeEvent'
*/
+ @Override
public void propertyChange(PropertyChangeEvent evt) {
wasModified(evt); // Let our panel update before guys downstream
support.firePropertyChange("", null, null);
@@ -328,25 +357,27 @@ public class PropertySheetPanel extends JPanel
/**
* Adds a PropertyChangeListener.
- *
+ *
* @param l a value of type 'PropertyChangeListener'
*/
+ @Override
public void addPropertyChangeListener(PropertyChangeListener l) {
support.addPropertyChangeListener(l);
}
/**
* Removes a PropertyChangeListener.
- *
+ *
* @param l a value of type 'PropertyChangeListener'
*/
+ @Override
public void removePropertyChangeListener(PropertyChangeListener l) {
support.removePropertyChangeListener(l);
}
-
+
/**
* Sets a new target object for customisation.
- *
+ *
* @param targ a value of type 'Object'
*/
public synchronized void setTarget(Object targ) {
@@ -363,7 +394,7 @@ public class PropertySheetPanel extends JPanel
JScrollPane scrollPane = new JScrollPane(scrollablePanel);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
add(scrollPane, BorderLayout.CENTER);
-
+
GridBagLayout gbLayout = new GridBagLayout();
scrollablePanel.setLayout(gbLayout);
@@ -375,7 +406,8 @@ public class PropertySheetPanel extends JPanel
m_Properties = bi.getPropertyDescriptors();
m_Methods = bi.getMethodDescriptors();
} catch (IntrospectionException ex) {
- System.err.println(Messages.getInstance().getString("PropertySheetPanel_SetTarget_IntrospectionException_Error_Text"));
+ System.err.println(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_IntrospectionException_Error_Text"));
return;
}
@@ -383,64 +415,85 @@ public class PropertySheetPanel extends JPanel
m_HelpText = null;
// Look for a globalInfo method that returns a string
// describing the target
- for (int i = 0;i < m_Methods.length; i++) {
- String name = m_Methods[i].getDisplayName();
- Method meth = m_Methods[i].getMethod();
+ for (MethodDescriptor m_Method : m_Methods) {
+ String name = m_Method.getDisplayName();
+ Method meth = m_Method.getMethod();
if (name.equals("globalInfo")) {
- if (meth.getReturnType().equals(String.class)) {
- try {
- Object args[] = { };
- String globalInfo = (String)(meth.invoke(m_Target, args));
+ if (meth.getReturnType().equals(String.class)) {
+ try {
+ Object args[] = {};
+ String globalInfo = (String) (meth.invoke(m_Target, args));
String summary = globalInfo;
int ci = globalInfo.indexOf('.');
if (ci != -1) {
summary = globalInfo.substring(0, ci + 1);
}
- final String className = targ.getClass().getName();
- m_HelpText = new StringBuffer(Messages.getInstance().getString("PropertySheetPanel_SetTarget_HelpText_Text_First"));
- m_HelpText.append(className).append(Messages.getInstance().getString("PropertySheetPanel_SetTarget_HelpText_Text_Second"));
- m_HelpText.append(Messages.getInstance().getString("PropertySheetPanel_SetTarget_HelpText_Text_Third")).append(globalInfo).append(Messages.getInstance().getString("PropertySheetPanel_SetTarget_HelpText_Text_Fourth"));
- m_HelpBut = new JButton(Messages.getInstance().getString("PropertySheetPanel_SetTarget_HelpBut_JButton_Text"));
- m_HelpBut.setToolTipText(Messages.getInstance().getString("PropertySheetPanel_SetTarget_HelpBut_SetToolTipText_Text")
- + className);
-
- m_HelpBut.addActionListener(new ActionListener() {
+ final String className = targ.getClass().getName();
+ m_HelpText = new StringBuffer(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_HelpText_Text_First"));
+ m_HelpText.append(className).append(
+ Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_HelpText_Text_Second"));
+ m_HelpText
+ .append(
+ Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_HelpText_Text_Third"))
+ .append(globalInfo)
+ .append(
+ Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_HelpText_Text_Fourth"));
+ m_HelpBut = new JButton(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_HelpBut_JButton_Text"));
+ m_HelpBut.setToolTipText(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_HelpBut_SetToolTipText_Text")
+ + className);
+
+ m_HelpBut.addActionListener(new ActionListener() {
+ @Override
public void actionPerformed(ActionEvent a) {
openHelpFrame();
m_HelpBut.setEnabled(false);
}
});
- if (m_Target instanceof CapabilitiesHandler) {
- m_CapabilitiesBut = new JButton(Messages.getInstance().getString("PropertySheetPanel_SetTarget_CapabilitiesBut_JButton_Text"));
- m_CapabilitiesBut.setToolTipText(Messages.getInstance().getString("PropertySheetPanel_SetTarget_CapabilitiesBut_SetToolTipText_Text")
- + className);
-
- m_CapabilitiesBut.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent a) {
- openCapabilitiesHelpDialog();
- m_CapabilitiesBut.setEnabled(false);
- }
- });
- }
- else {
- m_CapabilitiesBut = null;
- }
-
- jt.setColumns(30);
- jt.setFont(new Font("SansSerif", Font.PLAIN,12));
- jt.setEditable(false);
- jt.setLineWrap(true);
- jt.setWrapStyleWord(true);
- jt.setText(summary);
+ if (m_Target instanceof CapabilitiesHandler) {
+ m_CapabilitiesBut = new JButton(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_CapabilitiesBut_JButton_Text"));
+ m_CapabilitiesBut
+ .setToolTipText(Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_SetTarget_CapabilitiesBut_SetToolTipText_Text")
+ + className);
+
+ m_CapabilitiesBut.addActionListener(new ActionListener() {
+ @Override
+ public void actionPerformed(ActionEvent a) {
+ openCapabilitiesHelpDialog();
+ m_CapabilitiesBut.setEnabled(false);
+ }
+ });
+ } else {
+ m_CapabilitiesBut = null;
+ }
+
+ jt.setColumns(30);
+ jt.setFont(new Font("SansSerif", Font.PLAIN, 12));
+ jt.setEditable(false);
+ jt.setLineWrap(true);
+ jt.setWrapStyleWord(true);
+ jt.setText(summary);
jt.setBackground(getBackground());
- JPanel jp = new JPanel();
- jp.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(Messages.getInstance().getString("PropertySheetPanel_SetTarget_Jp_JPanel_BorderFactoryCreateTitledBorder_Text")),
- BorderFactory.createEmptyBorder(5, 5, 5, 5)
- ));
- jp.setLayout(new BorderLayout());
- jp.add(jt, BorderLayout.CENTER);
+ JPanel jp = new JPanel();
+ jp.setBorder(BorderFactory.createCompoundBorder(
+ BorderFactory
+ .createTitledBorder(Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_SetTarget_Jp_JPanel_BorderFactoryCreateTitledBorder_Text")),
+ BorderFactory.createEmptyBorder(5, 5, 5, 5)));
+ jp.setLayout(new BorderLayout());
+ jp.add(jt, BorderLayout.CENTER);
JPanel p2 = new JPanel();
p2.setLayout(new BorderLayout());
p2.add(m_HelpBut, BorderLayout.NORTH);
@@ -451,21 +504,21 @@ public class PropertySheetPanel extends JPanel
p2.add(p3, BorderLayout.CENTER);
}
jp.add(p2, BorderLayout.EAST);
- GridBagConstraints gbConstraints = new GridBagConstraints();
- // gbConstraints.anchor = GridBagConstraints.EAST;
- gbConstraints.fill = GridBagConstraints.BOTH;
- // gbConstraints.gridy = 0; gbConstraints.gridx = 0;
- gbConstraints.gridwidth = 2;
- gbConstraints.insets = new Insets(0,5,0,5);
- gbLayout.setConstraints(jp, gbConstraints);
- m_aboutPanel = jp;
- scrollablePanel.add(m_aboutPanel);
- componentOffset = 1;
- break;
- } catch (Exception ex) {
-
- }
- }
+ GridBagConstraints gbConstraints = new GridBagConstraints();
+ // gbConstraints.anchor = GridBagConstraints.EAST;
+ gbConstraints.fill = GridBagConstraints.BOTH;
+ // gbConstraints.gridy = 0; gbConstraints.gridx = 0;
+ gbConstraints.gridwidth = 2;
+ gbConstraints.insets = new Insets(0, 5, 0, 5);
+ gbLayout.setConstraints(jp, gbConstraints);
+ m_aboutPanel = jp;
+ scrollablePanel.add(m_aboutPanel);
+ componentOffset = 1;
+ break;
+ } catch (Exception ex) {
+
+ }
+ }
}
}
@@ -479,7 +532,7 @@ public class PropertySheetPanel extends JPanel
// Don't display hidden or expert properties.
if (m_Properties[i].isHidden() || m_Properties[i].isExpert()) {
- continue;
+ continue;
}
String name = m_Properties[i].getDisplayName();
@@ -489,124 +542,131 @@ public class PropertySheetPanel extends JPanel
// Only display read/write properties.
if (getter == null || setter == null) {
- continue;
+ continue;
}
-
+
JComponent view = null;
try {
- Object args[] = { };
- Object value = getter.invoke(m_Target, args);
- m_Values[i] = value;
-
- PropertyEditor editor = null;
- Class pec = m_Properties[i].getPropertyEditorClass();
- if (pec != null) {
- try {
- editor = (PropertyEditor)pec.newInstance();
- } catch (Exception ex) {
- // Drop through.
- }
- }
- if (editor == null) {
- editor = PropertyEditorManager.findEditor(type);
- }
- m_Editors[i] = editor;
-
- // If we can't edit this component, skip it.
- if (editor == null) {
- // If it's a user-defined property we give a warning.
- String getterClass = m_Properties[i].getReadMethod()
- .getDeclaringClass().getName();
- /*
- if (getterClass.indexOf("java.") != 0) {
- System.err.println("Warning: Can't find public property editor"
- + " for property \"" + name + "\" (class \""
- + type.getName() + "\"). Skipping.");
- }
- */
- continue;
- }
- if (editor instanceof GenericObjectEditor) {
- ((GenericObjectEditor) editor).setClassType(type);
- }
-
- // Don't try to set null values:
- if (value == null) {
- // If it's a user-defined property we give a warning.
- String getterClass = m_Properties[i].getReadMethod()
- .getDeclaringClass().getName();
- /*
- if (getterClass.indexOf("java.") != 0) {
- System.err.println("Warning: Property \"" + name
- + "\" has null initial value. Skipping.");
- }
- */
- continue;
- }
-
- editor.setValue(value);
-
- // now look for a TipText method for this property
+ Object args[] = {};
+ Object value = getter.invoke(m_Target, args);
+ m_Values[i] = value;
+
+ PropertyEditor editor = null;
+ Class pec = m_Properties[i].getPropertyEditorClass();
+ if (pec != null) {
+ try {
+ editor = (PropertyEditor) pec.newInstance();
+ } catch (Exception ex) {
+ // Drop through.
+ }
+ }
+ if (editor == null) {
+ editor = PropertyEditorManager.findEditor(type);
+ }
+ m_Editors[i] = editor;
+
+ // If we can't edit this component, skip it.
+ if (editor == null) {
+ // If it's a user-defined property we give a warning.
+ String getterClass = m_Properties[i].getReadMethod()
+ .getDeclaringClass().getName();
+ /*
+ * if (getterClass.indexOf("java.") != 0) {
+ * System.err.println("Warning: Can't find public property editor" +
+ * " for property \"" + name + "\" (class \"" + type.getName() +
+ * "\"). Skipping."); }
+ */
+ continue;
+ }
+ if (editor instanceof GenericObjectEditor) {
+ ((GenericObjectEditor) editor).setClassType(type);
+ }
+
+ // Don't try to set null values:
+ if (value == null) {
+ // If it's a user-defined property we give a warning.
+ String getterClass = m_Properties[i].getReadMethod()
+ .getDeclaringClass().getName();
+ /*
+ * if (getterClass.indexOf("java.") != 0) {
+ * System.err.println("Warning: Property \"" + name +
+ * "\" has null initial value. Skipping."); }
+ */
+ continue;
+ }
+
+ editor.setValue(value);
+
+ // now look for a TipText method for this property
String tipName = name + "TipText";
- for (int j = 0; j < m_Methods.length; j++) {
- String mname = m_Methods[j].getDisplayName();
- Method meth = m_Methods[j].getMethod();
- if (mname.equals(tipName)) {
- if (meth.getReturnType().equals(String.class)) {
- try {
- String tempTip = (String)(meth.invoke(m_Target, args));
- int ci = tempTip.indexOf('.');
- if (ci < 0) {
- m_TipTexts[i] = tempTip;
- } else {
- m_TipTexts[i] = tempTip.substring(0, ci);
- }
+ for (MethodDescriptor m_Method : m_Methods) {
+ String mname = m_Method.getDisplayName();
+ Method meth = m_Method.getMethod();
+ if (mname.equals(tipName)) {
+ if (meth.getReturnType().equals(String.class)) {
+ try {
+ String tempTip = (String) (meth.invoke(m_Target, args));
+ int ci = tempTip.indexOf('.');
+ if (ci < 0) {
+ m_TipTexts[i] = tempTip;
+ } else {
+ m_TipTexts[i] = tempTip.substring(0, ci);
+ }
if (m_HelpText != null) {
if (firstTip) {
- m_HelpText.append(Messages.getInstance().getString("PropertySheetPanel_SetTarget_HelpText_Text_Fifth"));
+ m_HelpText.append(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_HelpText_Text_Fifth"));
firstTip = false;
}
m_HelpText.append(name).append(" -- ");
m_HelpText.append(tempTip).append("\n\n");
- //jt.setText(m_HelpText.toString());
+ // jt.setText(m_HelpText.toString());
}
- } catch (Exception ex) {
-
- }
- break;
- }
- }
- }
-
-
- // Now figure out how to display it...
- if (editor.isPaintable() && editor.supportsCustomEditor()) {
- view = new PropertyPanel(editor);
- } else if (editor.getTags() != null) {
- view = new PropertyValueSelector(editor);
- } else if (editor.getAsText() != null) {
- //String init = editor.getAsText();
- view = new PropertyText(editor);
- } else {
- System.err.println(Messages.getInstance().getString("PropertySheetPanel_SetTarget_Error_Text_First") + name
- + Messages.getInstance().getString("PropertySheetPanel_SetTarget_Error_Text_Second"));
- continue;
- }
-
- editor.addPropertyChangeListener(this);
+ } catch (Exception ex) {
+
+ }
+ break;
+ }
+ }
+ }
+
+ // Now figure out how to display it...
+ if (editor.isPaintable() && editor.supportsCustomEditor()) {
+ view = new PropertyPanel(editor);
+ } else if (editor.getTags() != null) {
+ view = new PropertyValueSelector(editor);
+ } else if (editor.getAsText() != null) {
+ // String init = editor.getAsText();
+ view = new PropertyText(editor);
+ } else {
+ System.err.println(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_Error_Text_First")
+ + name
+ + Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_Error_Text_Second"));
+ continue;
+ }
+
+ editor.addPropertyChangeListener(this);
} catch (InvocationTargetException ex) {
- System.err.println(Messages.getInstance().getString("PropertySheetPanel_SetTarget_Error_Text_Third") + name
- + Messages.getInstance().getString("PropertySheetPanel_SetTarget_Error_Text_Fourth")
- + ex.getTargetException());
- ex.getTargetException().printStackTrace();
- continue;
+ System.err.println(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_Error_Text_Third")
+ + name
+ + Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_Error_Text_Fourth")
+ + ex.getTargetException());
+ ex.getTargetException().printStackTrace();
+ continue;
} catch (Exception ex) {
- System.err.println(Messages.getInstance().getString("PropertySheetPanel_SetTarget_Error_Text_Fifth") + name
- + Messages.getInstance().getString("PropertySheetPanel_SetTarget_Error_Text_Sixth") + ex);
- ex.printStackTrace();
- continue;
+ System.err.println(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_Error_Text_Fifth")
+ + name
+ + Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_Error_Text_Sixth") + ex);
+ ex.printStackTrace();
+ continue;
}
m_Labels[i] = new JLabel(name, SwingConstants.RIGHT);
@@ -615,12 +675,13 @@ public class PropertySheetPanel extends JPanel
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.anchor = GridBagConstraints.EAST;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
- gbConstraints.gridy = i+componentOffset; gbConstraints.gridx = 0;
+ gbConstraints.gridy = i + componentOffset;
+ gbConstraints.gridx = 0;
gbLayout.setConstraints(m_Labels[i], gbConstraints);
scrollablePanel.add(m_Labels[i]);
JPanel newPanel = new JPanel();
if (m_TipTexts[i] != null) {
- m_Views[i].setToolTipText(m_TipTexts[i]);
+ m_Views[i].setToolTipText(m_TipTexts[i]);
}
newPanel.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10));
newPanel.setLayout(new BorderLayout());
@@ -628,29 +689,32 @@ public class PropertySheetPanel extends JPanel
gbConstraints = new GridBagConstraints();
gbConstraints.anchor = GridBagConstraints.WEST;
gbConstraints.fill = GridBagConstraints.BOTH;
- gbConstraints.gridy = i+componentOffset; gbConstraints.gridx = 1;
+ gbConstraints.gridy = i + componentOffset;
+ gbConstraints.gridx = 1;
gbConstraints.weightx = 100;
gbLayout.setConstraints(newPanel, gbConstraints);
scrollablePanel.add(newPanel);
- m_NumEditable ++;
+ m_NumEditable++;
}
if (m_NumEditable == 0) {
- JLabel empty = new JLabel(Messages.getInstance().getString("PropertySheetPanel_SetTarget_Empty_JLabel_Text"),
- SwingConstants.CENTER);
+ JLabel empty = new JLabel(Messages.getInstance().getString(
+ "PropertySheetPanel_SetTarget_Empty_JLabel_Text"),
+ SwingConstants.CENTER);
Dimension d = empty.getPreferredSize();
empty.setPreferredSize(new Dimension(d.width * 2, d.height * 2));
empty.setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 10));
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.anchor = GridBagConstraints.CENTER;
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
- gbConstraints.gridy = componentOffset; gbConstraints.gridx = 0;
+ gbConstraints.gridy = componentOffset;
+ gbConstraints.gridx = 0;
gbLayout.setConstraints(empty, gbConstraints);
scrollablePanel.add(empty);
}
validate();
- setVisible(true);
+ setVisible(true);
}
/**
@@ -662,17 +726,23 @@ public class PropertySheetPanel extends JPanel
ta.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
- //ta.setBackground(getBackground());
+ // ta.setBackground(getBackground());
ta.setEditable(false);
ta.setText(m_HelpText.toString());
ta.setCaretPosition(0);
JDialog jdtmp;
- if (PropertyDialog.getParentDialog(this) != null)
- jdtmp = new JDialog(PropertyDialog.getParentDialog(this), Messages.getInstance().getString("PropertySheetPanel_OpenHelpFrame_Jdtmp_JDialog_Text_First"));
- else
- jdtmp = new JDialog(PropertyDialog.getParentFrame(this), Messages.getInstance().getString("PropertySheetPanel_OpenHelpFrame_Jdtmp_JDialog_Text_Second"));
+ if (PropertyDialog.getParentDialog(this) != null) {
+ jdtmp = new JDialog(PropertyDialog.getParentDialog(this), Messages
+ .getInstance().getString(
+ "PropertySheetPanel_OpenHelpFrame_Jdtmp_JDialog_Text_First"));
+ } else {
+ jdtmp = new JDialog(PropertyDialog.getParentFrame(this), Messages
+ .getInstance().getString(
+ "PropertySheetPanel_OpenHelpFrame_Jdtmp_JDialog_Text_Second"));
+ }
final JDialog jd = jdtmp;
jd.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent e) {
jd.dispose();
if (m_HelpDialog == jd) {
@@ -684,109 +754,143 @@ public class PropertySheetPanel extends JPanel
jd.getContentPane().add(new JScrollPane(ta), BorderLayout.CENTER);
jd.pack();
jd.setSize(400, 350);
- jd.setLocation(m_aboutPanel.getTopLevelAncestor().getLocationOnScreen().x
- + m_aboutPanel.getTopLevelAncestor().getSize().width,
- m_aboutPanel.getTopLevelAncestor().getLocationOnScreen().y);
+ jd.setLocation(m_aboutPanel.getTopLevelAncestor().getLocationOnScreen().x
+ + m_aboutPanel.getTopLevelAncestor().getSize().width, m_aboutPanel
+ .getTopLevelAncestor().getLocationOnScreen().y);
jd.setVisible(true);
m_HelpDialog = jd;
}
-
+
/**
* opens the help dialog for the capabilities.
*/
protected void openCapabilitiesHelpDialog() {
- if (PropertyDialog.getParentDialog(this) != null)
- m_CapabilitiesDialog = new CapabilitiesHelpDialog(PropertyDialog.getParentDialog(this));
- else
- m_CapabilitiesDialog = new CapabilitiesHelpDialog(PropertyDialog.getParentFrame(this));
+ if (PropertyDialog.getParentDialog(this) != null) {
+ m_CapabilitiesDialog = new CapabilitiesHelpDialog(
+ PropertyDialog.getParentDialog(this));
+ } else {
+ m_CapabilitiesDialog = new CapabilitiesHelpDialog(
+ PropertyDialog.getParentFrame(this));
+ }
m_CapabilitiesDialog.setSize(400, 350);
- m_CapabilitiesDialog.setLocation(m_aboutPanel.getTopLevelAncestor().getLocationOnScreen().x
- + m_aboutPanel.getTopLevelAncestor().getSize().width,
- m_aboutPanel.getTopLevelAncestor().getLocationOnScreen().y);
+ m_CapabilitiesDialog.setLocation(m_aboutPanel.getTopLevelAncestor()
+ .getLocationOnScreen().x
+ + m_aboutPanel.getTopLevelAncestor().getSize().width, m_aboutPanel
+ .getTopLevelAncestor().getLocationOnScreen().y);
m_CapabilitiesDialog.setVisible(true);
addPropertyChangeListener(m_CapabilitiesDialog);
}
/**
* Gets the number of editable properties for the current target.
- *
+ *
* @return the number of editable properties.
*/
public int editableProperties() {
return m_NumEditable;
}
-
+
/**
- * Updates the propertysheet when a value has been changed (from outside
- * the propertysheet?).
- *
+ * Updates the propertysheet when a value has been changed (from outside the
+ * propertysheet?).
+ *
* @param evt a value of type 'PropertyChangeEvent'
*/
synchronized void wasModified(PropertyChangeEvent evt) {
- // System.err.println("wasModified");
+ // System.err.println("wasModified");
if (evt.getSource() instanceof PropertyEditor) {
PropertyEditor editor = (PropertyEditor) evt.getSource();
- for (int i = 0 ; i < m_Editors.length; i++) {
- if (m_Editors[i] == editor) {
- PropertyDescriptor property = m_Properties[i];
- Object value = editor.getValue();
- m_Values[i] = value;
- Method setter = property.getWriteMethod();
- try {
- Object args[] = { value };
- args[0] = value;
- setter.invoke(m_Target, args);
- } catch (InvocationTargetException ex) {
- if (ex.getTargetException()
- instanceof PropertyVetoException) {
- String message = Messages.getInstance().getString("PropertySheetPanel_WasModified_Message_Text")
- + ex.getTargetException().getMessage();
- System.err.println(message);
-
+ for (int i = 0; i < m_Editors.length; i++) {
+ if (m_Editors[i] == editor) {
+ PropertyDescriptor property = m_Properties[i];
+ Object value = editor.getValue();
+ m_Values[i] = value;
+ Method setter = property.getWriteMethod();
+ try {
+ Object args[] = { value };
+ args[0] = value;
+ setter.invoke(m_Target, args);
+ } catch (InvocationTargetException ex) {
+ if (ex.getTargetException() instanceof PropertyVetoException) {
+ String message = Messages.getInstance().getString(
+ "PropertySheetPanel_WasModified_Message_Text")
+ + ex.getTargetException().getMessage();
+ System.err.println(message);
+
Component jf;
- if(evt.getSource() instanceof JPanel)
- jf = ((JPanel)evt.getSource()).getParent();
- else
- jf = new JFrame();
- JOptionPane.showMessageDialog(jf, message,
- Messages.getInstance().getString("PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Text_First"),
- JOptionPane.WARNING_MESSAGE);
- if(jf instanceof JFrame)
- ((JFrame)jf).dispose();
+ if (evt.getSource() instanceof JPanel) {
+ jf = ((JPanel) evt.getSource()).getParent();
+ } else {
+ jf = new JFrame();
+ }
+ JOptionPane
+ .showMessageDialog(
+ jf,
+ message,
+ Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Text_First"),
+ JOptionPane.WARNING_MESSAGE);
+ if (jf instanceof JFrame) {
+ ((JFrame) jf).dispose();
+ }
} else {
- System.err.println(ex.getTargetException().getClass().getName()+
- Messages.getInstance().getString("PropertySheetPanel_WasModified_Error_Text_First") + property.getName() +Messages.getInstance().getString("PropertySheetPanel_WasModified_Error_Text_Second") +
- ex.getTargetException().getMessage());
+ System.err.println(ex.getTargetException().getClass().getName()
+ + Messages.getInstance().getString(
+ "PropertySheetPanel_WasModified_Error_Text_First")
+ + property.getName()
+ + Messages.getInstance().getString(
+ "PropertySheetPanel_WasModified_Error_Text_Second")
+ + ex.getTargetException().getMessage());
Component jf;
- if(evt.getSource() instanceof JPanel)
- jf = ((JPanel)evt.getSource()).getParent();
- else
- jf = new JFrame();
- JOptionPane.showMessageDialog(jf,
- ex.getTargetException().getClass().getName()+
- Messages.getInstance().getString("PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Second") + property.getName()+
- Messages.getInstance().getString("PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Third")+
- ex.getTargetException().getMessage(),
- Messages.getInstance().getString("PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Fourth"),
- JOptionPane.WARNING_MESSAGE);
- if(jf instanceof JFrame)
- ((JFrame)jf).dispose();
+ if (evt.getSource() instanceof JPanel) {
+ jf = ((JPanel) evt.getSource()).getParent();
+ } else {
+ jf = new JFrame();
+ }
+ JOptionPane
+ .showMessageDialog(
+ jf,
+ ex.getTargetException().getClass().getName()
+ + Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Second")
+ + property.getName()
+ + Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Third")
+ + ex.getTargetException().getMessage(),
+ Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Fourth"),
+ JOptionPane.WARNING_MESSAGE);
+ if (jf instanceof JFrame) {
+ ((JFrame) jf).dispose();
+ }
}
- } catch (Exception ex) {
- System.err.println(Messages.getInstance().getString("PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Fifth")
- + property.getName());
- }
- if (m_Views[i] != null && m_Views[i] instanceof PropertyPanel) {
- //System.err.println("Trying to repaint the property canvas");
- m_Views[i].repaint();
- revalidate();
- }
- break;
- }
+ } catch (Exception ex) {
+ System.err
+ .println(Messages
+ .getInstance()
+ .getString(
+ "PropertySheetPanel_WasModified_JOptionPaneShowMessageDialog_Fifth")
+ + property.getName());
+ }
+ if (m_Views[i] != null && m_Views[i] instanceof PropertyPanel) {
+ // System.err.println("Trying to repaint the property canvas");
+ m_Views[i].repaint();
+ revalidate();
+ }
+ break;
+ }
}
}
@@ -795,43 +899,41 @@ public class PropertySheetPanel extends JPanel
for (int i = 0; i < m_Properties.length; i++) {
Object o;
try {
- Method getter = m_Properties[i].getReadMethod();
- Method setter = m_Properties[i].getWriteMethod();
-
- if (getter == null || setter == null) {
- // ignore set/get only properties
- continue;
- }
-
- Object args[] = { };
- o = getter.invoke(m_Target, args);
+ Method getter = m_Properties[i].getReadMethod();
+ Method setter = m_Properties[i].getWriteMethod();
+
+ if (getter == null || setter == null) {
+ // ignore set/get only properties
+ continue;
+ }
+
+ Object args[] = {};
+ o = getter.invoke(m_Target, args);
} catch (Exception ex) {
- o = null;
+ o = null;
}
if (o == m_Values[i] || (o != null && o.equals(m_Values[i]))) {
- // The property is equal to its old value.
- continue;
+ // The property is equal to its old value.
+ continue;
}
m_Values[i] = o;
// Make sure we have an editor for this property...
if (m_Editors[i] == null) {
- continue;
+ continue;
}
- // The property has changed! Update the editor.
+ // The property has changed! Update the editor.
m_Editors[i].removePropertyChangeListener(this);
m_Editors[i].setValue(o);
m_Editors[i].addPropertyChangeListener(this);
if (m_Views[i] != null) {
- //System.err.println("Trying to repaint " + (i + 1));
- m_Views[i].repaint();
+ // System.err.println("Trying to repaint " + (i + 1));
+ m_Views[i].repaint();
}
}
// Make sure the target bean gets repainted.
if (Beans.isInstanceOf(m_Target, Component.class)) {
- ((Component)(Beans.getInstanceOf(m_Target, Component.class))).repaint();
+ ((Component) (Beans.getInstanceOf(m_Target, Component.class))).repaint();
}
}
}
-
-
diff --git a/src/main/java/weka/gui/arffviewer/ArffViewer.java b/src/main/java/weka/gui/arffviewer/ArffViewer.java
index 2c918c6..693a2b9 100644
--- a/src/main/java/weka/gui/arffviewer/ArffViewer.java
+++ b/src/main/java/weka/gui/arffviewer/ArffViewer.java
@@ -22,10 +22,6 @@
package weka.gui.arffviewer;
-import weka.core.Memory;
-import weka.gui.ComponentHelper;
-import weka.gui.LookAndFeel;
-
import java.awt.BorderLayout;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
@@ -33,27 +29,29 @@ import java.awt.event.WindowListener;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
+import weka.core.Memory;
+import weka.gui.ComponentHelper;
+import weka.gui.LookAndFeel;
+
/**
* A little tool for viewing ARFF files.
- *
- *
+ *
+ *
* @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 7059 $
+ * @version $Revision: 10438 $
*/
-public class ArffViewer
- extends JFrame
- implements WindowListener {
-
+public class ArffViewer extends JFrame implements WindowListener {
+
/** for serialization */
static final long serialVersionUID = -7455845566922685175L;
/** the main panel */
private ArffViewerMainPanel m_MainPanel;
-
+
/** for monitoring the Memory consumption */
private static Memory m_Memory = new Memory(true);
-
+
/** the viewer if started from command line */
private static ArffViewer m_Viewer;
@@ -62,7 +60,7 @@ public class ArffViewer
/** the command line arguments */
private static String[] m_Args;
-
+
/**
* initializes the object
*/
@@ -70,7 +68,7 @@ public class ArffViewer
super(Messages.getInstance().getString("ArffViewer_ArffViewer_Text"));
createFrame();
}
-
+
/**
* creates all the components in the frame
*/
@@ -85,72 +83,75 @@ public class ArffViewer
removeWindowListener(this);
// add listener anew
addWindowListener(this);
-
+
getContentPane().setLayout(new BorderLayout());
-
+
m_MainPanel = new ArffViewerMainPanel(this);
m_MainPanel.setConfirmExit(false);
getContentPane().add(m_MainPanel, BorderLayout.CENTER);
-
+
setJMenuBar(m_MainPanel.getMenu());
}
-
+
/**
* returns the left coordinate if the frame would be centered
*
- * @return the left coordinate
+ * @return the left coordinate
*/
protected int getCenteredLeft() {
- int width;
- int x;
-
- width = getBounds().width;
- x = (getGraphicsConfiguration().getBounds().width - width) / 2;
-
- if (x < 0)
+ int width;
+ int x;
+
+ width = getBounds().width;
+ x = (getGraphicsConfiguration().getBounds().width - width) / 2;
+
+ if (x < 0) {
x = 0;
-
+ }
+
return x;
}
-
+
/**
* returns the top coordinate if the frame would be centered
*
- * @return the top coordinate
+ * @return the top coordinate
*/
protected int getCenteredTop() {
- int height;
- int y;
-
+ int height;
+ int y;
+
height = getBounds().height;
- y = (getGraphicsConfiguration().getBounds().height - height) / 2;
-
- if (y < 0)
+ y = (getGraphicsConfiguration().getBounds().height - height) / 2;
+
+ if (y < 0) {
y = 0;
-
+ }
+
return y;
}
-
+
/**
* positions the window at the center of the screen
*/
- public void setCenteredLocation() {
+ public void setCenteredLocation() {
setLocation(getCenteredLeft(), getCenteredTop());
}
-
+
/**
* whether to present a MessageBox on Exit or not
- * @param confirm whether a MessageBox pops up or not to confirm
- * exit
+ *
+ * @param confirm whether a MessageBox pops up or not to confirm exit
*/
public void setConfirmExit(boolean confirm) {
m_MainPanel.setConfirmExit(confirm);
}
-
+
/**
- * returns the setting of whether to display a confirm messagebox or not
- * on exit
- * @return whether a messagebox is displayed or not
+ * returns the setting of whether to display a confirm messagebox or not on
+ * exit
+ *
+ * @return whether a messagebox is displayed or not
*/
public boolean getConfirmExit() {
return m_MainPanel.getConfirmExit();
@@ -159,7 +160,7 @@ public class ArffViewer
/**
* whether to do a System.exit(0) on close
*
- * @param value enables/disables the System.exit(0)
+ * @param value enables/disables the System.exit(0)
*/
public void setExitOnClose(boolean value) {
m_MainPanel.setExitOnClose(value);
@@ -168,21 +169,21 @@ public class ArffViewer
/**
* returns TRUE if a System.exit(0) is done on a close
*
- * @return true if System.exit(0) is done
+ * @return true if System.exit(0) is done
*/
public boolean getExitOnClose() {
return m_MainPanel.getExitOnClose();
}
-
+
/**
* returns the main panel
*
- * @return the main panel
+ * @return the main panel
*/
public ArffViewerMainPanel getMainPanel() {
return m_MainPanel;
}
-
+
/**
* validates and repaints the frame
*/
@@ -194,164 +195,184 @@ public class ArffViewer
/**
* invoked when a window is activated
*
- * @param e the window event
+ * @param e the window event
*/
+ @Override
public void windowActivated(WindowEvent e) {
}
-
+
/**
* invoked when a window is closed
*
- * @param e the window event
+ * @param e the window event
*/
+ @Override
public void windowClosed(WindowEvent e) {
}
-
+
/**
* invoked when a window is in the process of closing
*
- * @param e the window event
+ * @param e the window event
*/
+ @Override
public void windowClosing(WindowEvent e) {
- int button;
-
- while (getMainPanel().getTabbedPane().getTabCount() > 0)
+ int button;
+
+ while (getMainPanel().getTabbedPane().getTabCount() > 0) {
getMainPanel().closeFile(false);
-
+ }
+
if (getConfirmExit()) {
- button = ComponentHelper.showMessageBox(
+ button = ComponentHelper
+ .showMessageBox(
this,
- Messages.getInstance().getString("ArffViewer_WindowClosing_ComponentHelperShowMessageBox_Text_First") + getTitle(),
- Messages.getInstance().getString("ArffViewer_WindowClosing_ComponentHelperShowMessageBox_Text_Second"),
- JOptionPane.YES_NO_OPTION,
- JOptionPane.QUESTION_MESSAGE);
- if (button == JOptionPane.YES_OPTION)
+ Messages
+ .getInstance()
+ .getString(
+ "ArffViewer_WindowClosing_ComponentHelperShowMessageBox_Text_First")
+ + getTitle(),
+ Messages
+ .getInstance()
+ .getString(
+ "ArffViewer_WindowClosing_ComponentHelperShowMessageBox_Text_Second"),
+ JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
+ if (button == JOptionPane.YES_OPTION) {
dispose();
- }
- else {
+ }
+ } else {
dispose();
}
- if (getExitOnClose())
+ if (getExitOnClose()) {
System.exit(0);
+ }
}
-
+
/**
* invoked when a window is deactivated
*
- * @param e the window event
+ * @param e the window event
*/
+ @Override
public void windowDeactivated(WindowEvent e) {
}
-
+
/**
* invoked when a window is deiconified
*
- * @param e the window event
+ * @param e the window event
*/
+ @Override
public void windowDeiconified(WindowEvent e) {
}
-
+
/**
* invoked when a window is iconified
*
- * @param e the window event
+ * @param e the window event
*/
+ @Override
public void windowIconified(WindowEvent e) {
}
-
+
/**
* invoked when a window is has been opened
*
- * @param e the window event
+ * @param e the window event
*/
+ @Override
public void windowOpened(WindowEvent e) {
}
-
+
/**
* returns only the classname
*
- * @return the classname
+ * @return the classname
*/
+ @Override
public String toString() {
return this.getClass().getName();
}
-
+
/**
- * shows the frame and it tries to load all the arff files that were
- * provided as arguments.
+ * shows the frame and it tries to load all the arff files that were provided
+ * as arguments.
*
- * @param args the commandline parameters
- * @throws Exception if something goes wrong
+ * @param args the commandline parameters
+ * @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
- weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages.getInstance().getString("ArffViewer_Main_Logger_Text"));
+ weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages
+ .getInstance().getString("ArffViewer_Main_Logger_Text"));
LookAndFeel.setLookAndFeel();
-
+
try {
// uncomment to disable the memory management:
- //m_Memory.setEnabled(false);
+ // m_Memory.setEnabled(false);
- m_Viewer = new ArffViewer();
+ m_Viewer = new ArffViewer();
m_Viewer.setExitOnClose(true);
m_Viewer.setVisible(true);
m_FilesLoaded = false;
- m_Args = args;
+ m_Args = args;
Thread memMonitor = new Thread() {
+ @Override
public void run() {
- while(true) {
- try {
- if ( (m_Args.length > 0) && (!m_FilesLoaded) ) {
- for (int i = 0; i < m_Args.length; i++) {
- System.out.println("Loading " + (i+1) + "/"
- + m_Args.length + ": '" + m_Args[i] + "'...");
- m_Viewer.getMainPanel().loadFile(m_Args[i]);
- }
- m_Viewer.getMainPanel().getTabbedPane().setSelectedIndex(0);
- System.out.println("Finished!");
- m_FilesLoaded = true;
+ while (true) {
+ // try {
+ if ((m_Args.length > 0) && (!m_FilesLoaded)) {
+ for (int i = 0; i < m_Args.length; i++) {
+ System.out.println("Loading " + (i + 1) + "/" + m_Args.length
+ + ": '" + m_Args[i] + "'...");
+ m_Viewer.getMainPanel().loadFile(m_Args[i]);
}
+ m_Viewer.getMainPanel().getTabbedPane().setSelectedIndex(0);
+ System.out.println("Finished!");
+ m_FilesLoaded = true;
+ }
- //System.out.println("before sleeping");
- Thread.sleep(4000);
-
+ // System.out.println("before sleeping");
+ // Thread.sleep(4000);
+ //
+ // System.gc();
+
+ if (m_Memory.isOutOfMemory()) {
+ // clean up
+ m_Viewer.dispose();
+ m_Viewer = null;
System.gc();
-
- if (m_Memory.isOutOfMemory()) {
- // clean up
- m_Viewer.dispose();
- m_Viewer = null;
- System.gc();
-
- // stop threads
- m_Memory.stopThreads();
-
- // display error
- System.err.println(Messages.getInstance().getString("ArffViewer_Main_Error_DisplayedMessage_Text"));
- m_Memory.showOutOfMemory();
- System.err.println(Messages.getInstance().getString("ArffViewer_Main_Error_Restarting_Text"));
-
- // restart GUI
- System.gc();
- m_Viewer = new ArffViewer();
- m_Viewer.setExitOnClose(true);
- m_Viewer.setVisible(true);
- // Note: no re-loading of datasets, otherwise we could end up
- // in an endless loop!
- }
- }
- catch(InterruptedException ex) {
- ex.printStackTrace();
+
+ // stop threads
+ m_Memory.stopThreads();
+
+ // display error
+ System.err.println(Messages.getInstance().getString(
+ "ArffViewer_Main_Error_DisplayedMessage_Text"));
+ m_Memory.showOutOfMemory();
+ System.err.println(Messages.getInstance().getString(
+ "ArffViewer_Main_Error_Restarting_Text"));
+
+ // restart GUI
+ System.gc();
+ m_Viewer = new ArffViewer();
+ m_Viewer.setExitOnClose(true);
+ m_Viewer.setVisible(true);
+ // Note: no re-loading of datasets, otherwise we could end up
+ // in an endless loop!
}
+ // }
+ // catch(InterruptedException ex) {
+ // ex.printStackTrace();
+ // }
}
}
};
memMonitor.setPriority(Thread.NORM_PRIORITY);
- memMonitor.start();
- }
- catch (Exception ex) {
+ memMonitor.start();
+ } catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
diff --git a/src/main/java/weka/gui/beans/Filter.java b/src/main/java/weka/gui/beans/Filter.java
index 4265cb9..fad71fe 100644
--- a/src/main/java/weka/gui/beans/Filter.java
+++ b/src/main/java/weka/gui/beans/Filter.java
@@ -45,7 +45,7 @@ import javax.swing.JPanel;
* A wrapper bean for Weka filters
*
* @author <a href="mailto:mhall at cs.waikato.ac.nz">Mark Hall</a>
- * @version $Revision: 7059 $
+ * @version $Revision: 9967 $
*/
public class Filter
extends JPanel
@@ -69,7 +69,7 @@ public class Filter
private static int FILTERING_TEST = 2;
private int m_state = IDLE;
- protected Thread m_filterThread = null;
+ protected transient Thread m_filterThread = null;
private transient Instances m_trainingSet;
private transient Instances m_testingSet;
@@ -547,6 +547,7 @@ public class Filter
}
}
block(false);
+ m_filterThread = null;
}
}
};
@@ -629,6 +630,7 @@ public class Filter
}
}
block(false);
+ m_filterThread = null;
}
}
};
diff --git a/src/main/java/weka/gui/beans/SerializedModelSaver.java b/src/main/java/weka/gui/beans/SerializedModelSaver.java
index 9d058b2..5b5c9b0 100644
--- a/src/main/java/weka/gui/beans/SerializedModelSaver.java
+++ b/src/main/java/weka/gui/beans/SerializedModelSaver.java
@@ -22,39 +22,37 @@
package weka.gui.beans;
-import java.io.ObjectInputStream;
-import java.io.Serializable;
+import java.awt.BorderLayout;
+import java.beans.EventSetDescriptor;
+import java.io.BufferedOutputStream;
import java.io.File;
-import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
-import java.io.BufferedOutputStream;
import java.io.IOException;
-import java.awt.BorderLayout;
-import java.beans.EventSetDescriptor;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
import java.util.ArrayList;
import java.util.Vector;
+
import javax.swing.JPanel;
-import weka.classifiers.Classifier;
-import weka.core.Instances;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
-import weka.core.xml.KOML;
-import weka.core.xml.XStream;
+import weka.core.Instances;
import weka.core.Tag;
import weka.core.Utils;
+import weka.core.xml.KOML;
+import weka.core.xml.XStream;
/**
* A bean that saves serialized models
- *
+ *
* @author Mark Hall (mhall{[at]}pentaho{[dot]}org
- * @version $Revision: 7878 $
+ * @version $Revision: 10534 $
*/
-public class SerializedModelSaver
- extends JPanel
- implements BeanCommon, Visible, BatchClassifierListener,
- IncrementalClassifierListener, BatchClustererListener,
- EnvironmentHandler, Serializable {
+public class SerializedModelSaver extends JPanel implements BeanCommon,
+ Visible, BatchClassifierListener, IncrementalClassifierListener,
+ BatchClustererListener, EnvironmentHandler, Serializable {
/** for serialization */
private static final long serialVersionUID = 3956528599473814287L;
@@ -62,15 +60,13 @@ public class SerializedModelSaver
/**
* Default visual for data sources
*/
- protected BeanVisual m_visual =
- new BeanVisual("AbstractDataSink",
- BeanVisual.ICON_PATH+"SerializedModelSaver.gif",
- BeanVisual.ICON_PATH+"SerializedModelSaver_animated.gif");
+ protected BeanVisual m_visual = new BeanVisual("AbstractDataSink",
+ BeanVisual.ICON_PATH + "SerializedModelSaver.gif", BeanVisual.ICON_PATH
+ + "SerializedModelSaver_animated.gif");
/**
- * Non null if this object is a target for any events.
- * Provides for the simplest case when only one incomming connection
- * is allowed.
+ * Non null if this object is a target for any events. Provides for the
+ * simplest case when only one incomming connection is allowed.
*/
protected Object m_listenee = null;
@@ -101,31 +97,43 @@ public class SerializedModelSaver
/** the extension for serialized models (binary Java serialization) */
public final static String FILE_EXTENSION = "model";
- /** relative path for the directory (relative to the user.dir (startup directory))? */
+ /**
+ * relative path for the directory (relative to the user.dir (startup
+ * directory))?
+ */
private boolean m_useRelativePath = false;
/**
- * Available file formats. Reflection is used to check if classes
- * are available for deep object serialization to XML
+ * Available file formats. Reflection is used to check if classes are
+ * available for deep object serialization to XML
*/
public static ArrayList<Tag> s_fileFormatsAvailable;
static {
s_fileFormatsAvailable = new ArrayList<Tag>();
- s_fileFormatsAvailable.add(new Tag(BINARY, Messages.getInstance().getString("SerializedModelSaver_FileFormatsAvailable_Text_First")
- + FILE_EXTENSION + Messages.getInstance().getString("SerializedModelSaver_FileFormatsAvailable_Text_Second"), "", false));
+ s_fileFormatsAvailable.add(new Tag(BINARY, Messages.getInstance()
+ .getString("SerializedModelSaver_FileFormatsAvailable_Text_First")
+ + FILE_EXTENSION
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_FileFormatsAvailable_Text_Second"), "", false));
if (KOML.isPresent()) {
- s_fileFormatsAvailable.add(new Tag(KOMLV,
- Messages.getInstance().getString("SerializedModelSaver_FileFormatsAvailable_Text_Third")
- + KOML.FILE_EXTENSION + FILE_EXTENSION + Messages.getInstance().getString("SerializedModelSaver_FileFormatsAvailable_Text_Fourth"), "", false));
+ s_fileFormatsAvailable.add(new Tag(KOMLV, Messages.getInstance()
+ .getString("SerializedModelSaver_FileFormatsAvailable_Text_Third")
+ + KOML.FILE_EXTENSION
+ + FILE_EXTENSION
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_FileFormatsAvailable_Text_Fourth"), "", false));
}
if (XStream.isPresent()) {
- s_fileFormatsAvailable.add(new Tag(XSTREAM,
- Messages.getInstance().getString("SerializedModelSaver_FileFormatsAvailable_Text_Fifth")
- + XStream.FILE_EXTENSION + FILE_EXTENSION + Messages.getInstance().getString("SerializedModelSaver_FileFormatsAvailable_Text_Sixth"), "", false));
+ s_fileFormatsAvailable.add(new Tag(XSTREAM, Messages.getInstance()
+ .getString("SerializedModelSaver_FileFormatsAvailable_Text_Fifth")
+ + XStream.FILE_EXTENSION
+ + FILE_EXTENSION
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_FileFormatsAvailable_Text_Sixth"), "", false));
}
}
-
+
/**
* The environment variables.
*/
@@ -139,7 +147,7 @@ public class SerializedModelSaver
setLayout(new BorderLayout());
add(m_visual, BorderLayout.CENTER);
m_fileFormat = s_fileFormatsAvailable.get(0);
-
+
m_env = Environment.getSystemWide();
}
@@ -148,6 +156,7 @@ public class SerializedModelSaver
*
* @param name the name to use
*/
+ @Override
public void setCustomName(String name) {
m_visual.setText(name);
}
@@ -157,96 +166,103 @@ public class SerializedModelSaver
*
* @return the custom name (or the default name)
*/
+ @Override
public String getCustomName() {
return m_visual.getText();
}
/**
* Use the default images for this bean.
- *
+ *
*/
+ @Override
public void useDefaultVisual() {
- m_visual.loadIcons(BeanVisual.ICON_PATH+"SerializedModelSaver.gif",
- BeanVisual.ICON_PATH+"SerializedModelSaver_animated.gif");
+ m_visual.loadIcons(BeanVisual.ICON_PATH + "SerializedModelSaver.gif",
+ BeanVisual.ICON_PATH + "SerializedModelSaver_animated.gif");
m_visual.setText("SerializedModelSaver");
}
/**
* Set the visual for this data source.
- *
+ *
* @param newVisual a <code>BeanVisual</code> value
*/
+ @Override
public void setVisual(BeanVisual newVisual) {
m_visual = newVisual;
}
/**
* Get the visual being used by this data source.
- *
+ *
*/
+ @Override
public BeanVisual getVisual() {
return m_visual;
}
/**
- * Returns true if, at this time,
- * the object will accept a connection according to the supplied
- * EventSetDescriptor.
- *
+ * Returns true if, at this time, the object will accept a connection
+ * according to the supplied EventSetDescriptor.
+ *
* @param esd the EventSetDescriptor
* @return true if the object will accept a connection
*/
+ @Override
public boolean connectionAllowed(EventSetDescriptor esd) {
return connectionAllowed(esd.getName());
}
/**
- * Returns true if, at this time,
- * the object will accept a connection according to the supplied
- * event name.
- *
+ * Returns true if, at this time, the object will accept a connection
+ * according to the supplied event name.
+ *
* @param eventName the event
* @return true if the object will accept a connection
*/
+ @Override
public boolean connectionAllowed(String eventName) {
return (m_listenee == null);
}
/**
- * Notify this object that it has been registered as a listener with
- * a source with respect to the supplied event name.
- *
+ * Notify this object that it has been registered as a listener with a source
+ * with respect to the supplied event name.
+ *
* @param eventName the event
- * @param source the source with which this object has been registered as
- * a listener
+ * @param source the source with which this object has been registered as a
+ * listener
*/
+ @Override
public synchronized void connectionNotification(String eventName,
- Object source) {
+ Object source) {
if (connectionAllowed(eventName)) {
m_listenee = source;
}
}
/**
- * Notify this object that it has been deregistered as a listener with
- * a source with respect to the supplied event name.
- *
+ * Notify this object that it has been deregistered as a listener with a
+ * source with respect to the supplied event name.
+ *
* @param eventName the event
- * @param source the source with which this object has been registered as
- * a listener
+ * @param source the source with which this object has been registered as a
+ * listener
*/
+ @Override
public synchronized void disconnectionNotification(String eventName,
- Object source) {
+ Object source) {
if (m_listenee == source) {
m_listenee = null;
}
}
-
+
/**
* Set a log for this bean.
- *
+ *
* @param logger a <code>weka.gui.Logger</code> value
*/
+ @Override
public void setLog(weka.gui.Logger logger) {
m_logger = logger;
}
@@ -254,135 +270,143 @@ public class SerializedModelSaver
/**
* Stop any processing that the bean might be doing.
*/
+ @Override
public void stop() {
// tell the listenee (upstream bean) to stop
if (m_listenee instanceof BeanCommon) {
- ((BeanCommon)m_listenee).stop();
+ ((BeanCommon) m_listenee).stop();
}
}
-
+
/**
- * Returns true if. at this time, the bean is busy with some
- * (i.e. perhaps a worker thread is performing some calculation).
+ * Returns true if. at this time, the bean is busy with some (i.e. perhaps a
+ * worker thread is performing some calculation).
*
* @return true if the bean is busy.
*/
+ @Override
public boolean isBusy() {
return false;
}
/**
- * makes sure that the filename is valid, i.e., replaces slashes,
- * backslashes and colons with underscores ("_").
+ * makes sure that the filename is valid, i.e., replaces slashes, backslashes
+ * and colons with underscores ("_").
*
- * @param filename the filename to cleanse
- * @return the cleansed filename
+ * @param filename the filename to cleanse
+ * @return the cleansed filename
*/
protected String sanitizeFilename(String filename) {
- return filename.replaceAll("\\\\", "_").replaceAll(":", "_").replaceAll("/", "_");
+ return filename.replaceAll("\\\\", "_").replaceAll(":", "_")
+ .replaceAll("/", "_");
}
/**
* Accept and save a batch trained clusterer.
- *
+ *
* @param ce a <code>BatchClassifierEvent</code> value
*/
+ @Override
public void acceptClusterer(BatchClustererEvent ce) {
- if (ce.getTestSet() == null ||
- ce.getTestOrTrain() == BatchClustererEvent.TEST ||
- ce.getTestSet().isStructureOnly()) {
+ if (ce.getTestSet() == null
+ || ce.getTestOrTrain() == BatchClustererEvent.TEST
+ || ce.getTestSet().isStructureOnly()) {
return;
}
Instances trainHeader = ce.getTestSet().getDataSet().stringFreeStructure();
- String titleString = ce.getClusterer().getClass().getName();
- titleString = titleString.
- substring(titleString.lastIndexOf('.') + 1,
- titleString.length());
+ String titleString = ce.getClusterer().getClass().getName();
+ titleString = titleString.substring(titleString.lastIndexOf('.') + 1,
+ titleString.length());
String prefix = "";
try {
prefix = m_env.substitute(m_filenamePrefix);
} catch (Exception ex) {
- stop(); // stop all processing
- String message = Messages.getInstance().getString("SerializedModelSaver_AcceptClusterer_Message_Text_First")
- + statusMessagePrefix()
- + Messages.getInstance().getString("SerializedModelSaver_AcceptClusterer_Message_Text_Second")
+ String message = Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClusterer_Message_Text_First")
+ + statusMessagePrefix()
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClusterer_Message_Text_Second")
+ ex.getMessage();
if (m_logger != null) {
m_logger.logMessage(message);
m_logger.statusMessage(statusMessagePrefix()
- + Messages.getInstance().getString("SerializedModelSaver_AcceptClusterer_StatusMessage_Text_First"));
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClusterer_StatusMessage_Text_First"));
} else {
System.err.println(message);
}
return;
}
- String fileName = ""
- + prefix
- + titleString
- + "_"
- + ce.getSetNumber()
- + "_" + ce.getMaxSetNumber();
+ String fileName = "" + prefix + titleString + "_" + ce.getSetNumber() + "_"
+ + ce.getMaxSetNumber();
fileName = sanitizeFilename(fileName);
-
+
String dirName = m_directory.getPath();
try {
dirName = m_env.substitute(dirName);
} catch (Exception ex) {
- stop(); // stop all processing
- String message = Messages.getInstance().getString("SerializedModelSaver_AcceptClusterer_Message_Text_Third")
- + statusMessagePrefix() + Messages.getInstance().getString("SerializedModelSaver_AcceptClusterer_Message_Text_Fourth")
- + ex.getMessage();
+ String message = Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClusterer_Message_Text_Third")
+ + statusMessagePrefix()
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClusterer_Message_Text_Fourth")
+ + ex.getMessage();
if (m_logger != null) {
m_logger.logMessage(message);
m_logger.statusMessage(statusMessagePrefix()
- + Messages.getInstance().getString("SerializedModelSaver_AcceptClusterer_StatusMessage_Text_Second"));
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClusterer_StatusMessage_Text_Second"));
} else {
System.err.println(message);
}
return;
}
File tempFile = new File(dirName);
- fileName = tempFile.getAbsolutePath()
- + File.separator
- + fileName;
+ fileName = tempFile.getAbsolutePath() + File.separator + fileName;
saveModel(fileName, trainHeader, ce.getClusterer());
}
/**
* Accept and save an incrementally trained classifier.
- *
+ *
* @param ce the BatchClassifierEvent containing the classifier
*/
+ @Override
public void acceptClassifier(final IncrementalClassifierEvent ce) {
if (ce.getStatus() == IncrementalClassifierEvent.BATCH_FINISHED) {
// Only save model when the end of the stream is reached
Instances header = ce.getStructure();
- String titleString = ce.getClassifier().getClass().getName();
- titleString = titleString.
- substring(titleString.lastIndexOf('.') + 1,
- titleString.length());
+ String titleString = ce.getClassifier().getClass().getName();
+ titleString = titleString.substring(titleString.lastIndexOf('.') + 1,
+ titleString.length());
String prefix = "";
try {
prefix = m_env.substitute(m_filenamePrefix);
} catch (Exception ex) {
- stop(); // stop processing
- String message = Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_Message_Text_First")
- + statusMessagePrefix() + Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_Message_Text_Second")
+ String message = Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_Message_Text_First")
+ + statusMessagePrefix()
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_Message_Text_Second")
+ ex.getMessage();
if (m_logger != null) {
m_logger.logMessage(message);
- m_logger.statusMessage(statusMessagePrefix()
- + Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_StatusMessage_Text_First"));
+ m_logger
+ .statusMessage(statusMessagePrefix()
+ + Messages
+ .getInstance()
+ .getString(
+ "SerializedModelSaver_AcceptClassifier_StatusMessage_Text_First"));
} else {
System.err.println(message);
}
return;
}
-
+
String fileName = "" + prefix + titleString;
fileName = sanitizeFilename(fileName);
@@ -390,14 +414,20 @@ public class SerializedModelSaver
try {
dirName = m_env.substitute(dirName);
} catch (Exception ex) {
- stop(); // stop processing
- String message = Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_Message_Text_Third")
- + statusMessagePrefix() + Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_Message_Text_Fourth")
+ String message = Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_Message_Text_Third")
+ + statusMessagePrefix()
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_Message_Text_Fourth")
+ ex.getMessage();
if (m_logger != null) {
m_logger.logMessage(message);
- m_logger.statusMessage(statusMessagePrefix()
- + Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_StatusMessage_Text_Second"));
+ m_logger
+ .statusMessage(statusMessagePrefix()
+ + Messages
+ .getInstance()
+ .getString(
+ "SerializedModelSaver_AcceptClassifier_StatusMessage_Text_Second"));
} else {
System.err.println(message);
}
@@ -405,68 +435,67 @@ public class SerializedModelSaver
}
File tempFile = new File(dirName);
- fileName = tempFile.getAbsolutePath()
- + File.separator
- + fileName;
-
+ fileName = tempFile.getAbsolutePath() + File.separator + fileName;
+
saveModel(fileName, header, ce.getClassifier());
}
}
-
+
/**
* Accept and save a batch trained classifier.
- *
+ *
* @param ce the BatchClassifierEvent containing the classifier
*/
+ @Override
public void acceptClassifier(final BatchClassifierEvent ce) {
- if (ce.getTrainSet() == null ||
- ce.getTrainSet().isStructureOnly()) {
+ if (ce.getTrainSet() == null || ce.getTrainSet().isStructureOnly()) {
return;
}
Instances trainHeader = new Instances(ce.getTrainSet().getDataSet(), 0);
- String titleString = ce.getClassifier().getClass().getName();
- titleString = titleString.
- substring(titleString.lastIndexOf('.') + 1,
- titleString.length());
+ String titleString = ce.getClassifier().getClass().getName();
+ titleString = titleString.substring(titleString.lastIndexOf('.') + 1,
+ titleString.length());
String prefix = "";
try {
prefix = m_env.substitute(m_filenamePrefix);
} catch (Exception ex) {
- stop(); // stop processing
- String message = Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_Message_Text_Fifth")
- + statusMessagePrefix() + Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_Message_Text_Sixth")
+ String message = Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_Message_Text_Fifth")
+ + statusMessagePrefix()
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_Message_Text_Sixth")
+ ex.getMessage();
if (m_logger != null) {
m_logger.logMessage(message);
m_logger.statusMessage(statusMessagePrefix()
- + Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_StatusMessage_Text_Third"));
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_StatusMessage_Text_Third"));
} else {
System.err.println(message);
}
return;
}
- String fileName = ""
- + prefix
- + titleString
- + "_"
- + ce.getSetNumber()
- + "_" + ce.getMaxSetNumber();
+ String fileName = "" + prefix + titleString + "_" + ce.getSetNumber() + "_"
+ + ce.getMaxSetNumber();
fileName = sanitizeFilename(fileName);
-
+
String dirName = m_directory.getPath();
try {
dirName = m_env.substitute(dirName);
} catch (Exception ex) {
- stop(); // stop processing
- String message = Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_Message_Text_Seventh")
- + statusMessagePrefix() + Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_Message_Text_Eighth")
- + ex.getMessage();
+ String message = Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_Message_Text_Seventh")
+ + statusMessagePrefix()
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_Message_Text_Eighth")
+ + ex.getMessage();
if (m_logger != null) {
m_logger.logMessage(message);
m_logger.statusMessage(statusMessagePrefix()
- + Messages.getInstance().getString("SerializedModelSaver_AcceptClassifier_StatusMessage_Text_Fourth"));
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_AcceptClassifier_StatusMessage_Text_Fourth"));
} else {
System.err.println(message);
}
@@ -474,9 +503,7 @@ public class SerializedModelSaver
}
File tempFile = new File(dirName);
- fileName = tempFile.getAbsolutePath()
- + File.separator
- + fileName;
+ fileName = tempFile.getAbsolutePath() + File.separator + fileName;
saveModel(fileName, trainHeader, ce.getClassifier());
}
@@ -484,8 +511,7 @@ public class SerializedModelSaver
/**
* Helper routine to actually save the models.
*/
-
-
+
private void saveModel(String fileName, Instances trainHeader, Object model) {
m_fileFormat = validateFileFormat(m_fileFormat);
if (m_fileFormat == null) {
@@ -506,30 +532,37 @@ public class SerializedModelSaver
fileName = fileName + "." + FILE_EXTENSION;
saveBinary(new File(fileName), model, trainHeader);
break;
- }
+ }
} catch (Exception ex) {
- stop(); // stop all processing
- System.err.println(Messages.getInstance().getString("SerializedModelSaver_SaveModel_Error_Text"));
+ System.err.println(Messages.getInstance().getString(
+ "SerializedModelSaver_SaveModel_Error_Text"));
if (m_logger != null) {
- m_logger.logMessage(Messages.getInstance().getString("SerializedModelSaver_SaveModel_LogMessage_Text_First")
- + statusMessagePrefix() + Messages.getInstance().getString("SerializedModelSaver_SaveModel_LogMessage_Text_Second"));
+ m_logger.logMessage(Messages.getInstance().getString(
+ "SerializedModelSaver_SaveModel_LogMessage_Text_First")
+ + statusMessagePrefix()
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_SaveModel_LogMessage_Text_Second")
+ + " : "
+ + ex.getMessage());
m_logger.statusMessage(statusMessagePrefix()
- + Messages.getInstance().getString("SerializedModelSaver_SaveModel_StatusMessage_Text"));
+ + Messages.getInstance().getString(
+ "SerializedModelSaver_SaveModel_StatusMessage_Text"));
}
}
}
/**
* Save a model in binary form.
- *
+ *
* @param saveTo the file name to save to
* @param model the model to save
- * @param header the header of the data that was used to train the model (optional)
+ * @param header the header of the data that was used to train the model
+ * (optional)
*/
- public static void saveBinary(File saveTo, Object model, Instances header) throws IOException {
- ObjectOutputStream os =
- new ObjectOutputStream(new BufferedOutputStream(
- new FileOutputStream(saveTo)));
+ public static void saveBinary(File saveTo, Object model, Instances header)
+ throws IOException {
+ ObjectOutputStream os = new ObjectOutputStream(new BufferedOutputStream(
+ new FileOutputStream(saveTo)));
os.writeObject(model);
// now the header
if (header != null) {
@@ -540,12 +573,14 @@ public class SerializedModelSaver
/**
* Save a model in KOML deep object serialized XML form.
- *
+ *
* @param saveTo the file name to save to
* @param model the model to save
- * @param header the header of the data that was used to train the model (optional)
+ * @param header the header of the data that was used to train the model
+ * (optional)
*/
- public static void saveKOML(File saveTo, Object model, Instances header) throws Exception {
+ public static void saveKOML(File saveTo, Object model, Instances header)
+ throws Exception {
Vector v = new Vector();
v.add(model);
if (header != null) {
@@ -557,12 +592,14 @@ public class SerializedModelSaver
/**
* Save a model in XStream deep object serialized XML form.
- *
+ *
* @param saveTo the file name to save to
* @param model the model to save
- * @param header the header of the data that was used to train the model (optional)
+ * @param header the header of the data that was used to train the model
+ * (optional)
*/
- public static void saveXStream(File saveTo, Object model, Instances header) throws Exception {
+ public static void saveXStream(File saveTo, Object model, Instances header)
+ throws Exception {
Vector v = new Vector();
v.add(model);
if (header != null) {
@@ -574,16 +611,16 @@ public class SerializedModelSaver
/**
* Get the directory that the model(s) will be saved into
- *
+ *
* @return the directory to save to
*/
public File getDirectory() {
return m_directory;
}
-
+
/**
* Set the directory that the model(s) will be saved into.
- *
+ *
* @param d the directory to save to
*/
public void setDirectory(File d) {
@@ -597,19 +634,19 @@ public class SerializedModelSaver
}
/**
- * Set whether to use relative paths for the directory.
- * I.e. relative to the startup (user.dir) directory
- *
+ * Set whether to use relative paths for the directory. I.e. relative to the
+ * startup (user.dir) directory
+ *
* @param rp true if relative paths are to be used
*/
public void setUseRelativePath(boolean rp) {
m_useRelativePath = rp;
}
-
+
/**
- * Get whether to use relative paths for the directory.
- * I.e. relative to the startup (user.dir) directory
- *
+ * Get whether to use relative paths for the directory. I.e. relative to the
+ * startup (user.dir) directory
+ *
* @return true if relative paths are to be used
*/
public boolean getUseRelativePath() {
@@ -618,7 +655,7 @@ public class SerializedModelSaver
/**
* Get the prefix to prepend to the model file names.
- *
+ *
* @return the prefix to prepend
*/
public String getPrefix() {
@@ -627,7 +664,7 @@ public class SerializedModelSaver
/**
* Set the prefix to prepend to the model file names.
- *
+ *
* @param p the prefix to prepend
*/
public void setPrefix(String p) {
@@ -636,16 +673,17 @@ public class SerializedModelSaver
/**
* Global info for this bean. Gets displayed in the GUI.
- *
+ *
* @return information about this bean.
*/
public String globalInfo() {
- return Messages.getInstance().getString("SerializedModelSaver_GlobalInfo_Text");
+ return Messages.getInstance().getString(
+ "SerializedModelSaver_GlobalInfo_Text");
}
/**
* Set the file format to use for saving.
- *
+ *
* @param ff the file format to use
*/
public void setFileFormat(Tag ff) {
@@ -654,7 +692,7 @@ public class SerializedModelSaver
/**
* Get the file format to use for saving.
- *
+ *
* @return the file format to use
*/
public Tag getFileFormat() {
@@ -662,9 +700,9 @@ public class SerializedModelSaver
}
/**
- * Validate the file format. After this bean is deserialized, classes for
- * XML serialization may not be in the classpath any more.
- *
+ * Validate the file format. After this bean is deserialized, classes for XML
+ * serialization may not be in the classpath any more.
+ *
* @param ff the current file format to validate
*/
public Tag validateFileFormat(Tag ff) {
@@ -683,28 +721,28 @@ public class SerializedModelSaver
return r;
}
-
+
private String statusMessagePrefix() {
return getCustomName() + "$" + hashCode() + "|";
}
-
+
/**
* Set environment variables to use.
*
- * @param env the environment variables to
- * use
+ * @param env the environment variables to use
*/
+ @Override
public void setEnvironment(Environment env) {
m_env = env;
}
-
+
// Custom de-serialization in order to set default
// environment variables on de-serialization
- private void readObject(ObjectInputStream aStream)
- throws IOException, ClassNotFoundException {
+ private void readObject(ObjectInputStream aStream) throws IOException,
+ ClassNotFoundException {
aStream.defaultReadObject();
-
+
// set a default environment to use
m_env = Environment.getSystemWide();
}
-}
\ No newline at end of file
+}
diff --git a/src/main/java/weka/gui/experiment/Experimenter.java b/src/main/java/weka/gui/experiment/Experimenter.java
index 66c8c7c..8a16f9f 100644
--- a/src/main/java/weka/gui/experiment/Experimenter.java
+++ b/src/main/java/weka/gui/experiment/Experimenter.java
@@ -22,10 +22,6 @@
package weka.gui.experiment;
-import weka.core.Memory;
-import weka.experiment.Experiment;
-import weka.gui.LookAndFeel;
-
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.Toolkit;
@@ -38,15 +34,18 @@ import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
-/**
- * The main class for the experiment environment. Lets the user create,
- * open, save, configure, run experiments, and analyse experimental results.
- *
+import weka.core.Memory;
+import weka.experiment.Experiment;
+import weka.gui.LookAndFeel;
+
+/**
+ * The main class for the experiment environment. Lets the user create, open,
+ * save, configure, run experiments, and analyse experimental results.
+ *
* @author Len Trigg (trigg at cs.waikato.ac.nz)
- * @version $Revision: 9495 $
+ * @version $Revision: 10438 $
*/
-public class Experimenter
- extends JPanel {
+public class Experimenter extends JPanel {
/** for serialization */
private static final long serialVersionUID = -5751617505738193788L;
@@ -63,8 +62,10 @@ public class Experimenter
/** The tabbed pane that controls which sub-pane we are working with */
protected JTabbedPane m_TabbedPane = new JTabbedPane();
- /** True if the class attribute is the first attribute for all
- datasets involved in this experiment. */
+ /**
+ * True if the class attribute is the first attribute for all datasets
+ * involved in this experiment.
+ */
protected boolean m_ClassFirst = false;
/**
@@ -72,37 +73,56 @@ public class Experimenter
*/
public Experimenter(boolean classFirst) {
- System.out.println("[DEBUGGER] ---- " + Messages.getInstance().getString("Experimenter_TabbedPane_Setup_Key_Text"));
-
+ System.out.println("[DEBUGGER] ---- "
+ + Messages.getInstance().getString(
+ "Experimenter_TabbedPane_Setup_Key_Text"));
+
m_SetupPanel = new SetupModePanel();
m_ResultsPanel = new ResultsPanel();
m_RunPanel = new RunPanel();
m_RunPanel.setResultsPanel(m_ResultsPanel);
-
+
m_ClassFirst = classFirst;
- m_TabbedPane.addTab(Messages.getInstance().getString("Experimenter_TabbedPane_Setup_Key_Text"), null, m_SetupPanel, Messages.getInstance().getString("Experimenter_TabbedPane_Setup_Value_Text"));
- m_TabbedPane.addTab(Messages.getInstance().getString("Experimenter_TabbedPane_Run_Key_Text"), null, m_RunPanel, Messages.getInstance().getString("Experimenter_TabbedPane_Run_Value_Text"));
- m_TabbedPane.addTab(Messages.getInstance().getString("Experimenter_TabbedPane_Analyse_Key_Text"), null, m_ResultsPanel, Messages.getInstance().getString("Experimenter_TabbedPane_Analyse_Value_Text"));
+ m_TabbedPane.addTab(
+ Messages.getInstance()
+ .getString("Experimenter_TabbedPane_Setup_Key_Text"),
+ null,
+ m_SetupPanel,
+ Messages.getInstance().getString(
+ "Experimenter_TabbedPane_Setup_Value_Text"));
+ m_TabbedPane.addTab(
+ Messages.getInstance().getString("Experimenter_TabbedPane_Run_Key_Text"),
+ null, m_RunPanel,
+ Messages.getInstance()
+ .getString("Experimenter_TabbedPane_Run_Value_Text"));
+ m_TabbedPane.addTab(
+ Messages.getInstance().getString(
+ "Experimenter_TabbedPane_Analyse_Key_Text"),
+ null,
+ m_ResultsPanel,
+ Messages.getInstance().getString(
+ "Experimenter_TabbedPane_Analyse_Value_Text"));
m_TabbedPane.setSelectedIndex(0);
m_TabbedPane.setEnabledAt(1, false);
m_SetupPanel.addPropertyChangeListener(new PropertyChangeListener() {
+ @Override
public void propertyChange(PropertyChangeEvent e) {
- //System.err.println("Updated experiment");
- Experiment exp = m_SetupPanel.getExperiment();
- exp.classFirst(m_ClassFirst);
- m_RunPanel.setExperiment(exp);
- //m_ResultsPanel.setExperiment(exp);
- m_TabbedPane.setEnabledAt(1, true);
+ // System.err.println("Updated experiment");
+ Experiment exp = m_SetupPanel.getExperiment();
+ exp.classFirst(m_ClassFirst);
+ m_RunPanel.setExperiment(exp);
+ // m_ResultsPanel.setExperiment(exp);
+ m_TabbedPane.setEnabledAt(1, true);
}
});
setLayout(new BorderLayout());
add(m_TabbedPane, BorderLayout.CENTER);
}
-
- /** variable for the Experimenter class which would be set to null by the memory
- monitoring thread to free up some memory if we running out of memory
+ /**
+ * variable for the Experimenter class which would be set to null by the
+ * memory monitoring thread to free up some memory if we running out of memory
*/
private static Experimenter m_experimenter;
@@ -111,61 +131,68 @@ public class Experimenter
/**
* Tests out the experiment environment.
- *
+ *
* @param args ignored.
*/
- public static void main(String [] args) {
- weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages.getInstance().getString("Experimenter_Main_LoggingStarted_Text"));
+ public static void main(String[] args) {
+ weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages
+ .getInstance().getString("Experimenter_Main_LoggingStarted_Text"));
LookAndFeel.setLookAndFeel();
-
+
try {
// uncomment to disable the memory management:
- //m_Memory.setEnabled(false);
+ // m_Memory.setEnabled(false);
boolean classFirst = false;
if (args.length > 0) {
- classFirst = args[0].equals("CLASS_FIRST");
+ classFirst = args[0].equals("CLASS_FIRST");
}
m_experimenter = new Experimenter(classFirst);
- final JFrame jf = new JFrame(Messages.getInstance().getString("Experimenter_Main_WekaExperimentEnvironment_JFrame_Text"));
+ final JFrame jf = new JFrame(Messages.getInstance().getString(
+ "Experimenter_Main_WekaExperimentEnvironment_JFrame_Text"));
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(m_experimenter, BorderLayout.CENTER);
jf.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- jf.dispose();
- System.exit(0);
- }
+ @Override
+ public void windowClosing(WindowEvent e) {
+ jf.dispose();
+ System.exit(0);
+ }
});
jf.pack();
jf.setSize(800, 600);
jf.setVisible(true);
-
- Image icon = Toolkit.getDefaultToolkit().
- getImage(m_experimenter.getClass().getClassLoader().getResource("weka/gui/weka_icon_new_48.png"));
+
+ Image icon = Toolkit.getDefaultToolkit().getImage(
+ m_experimenter.getClass().getClassLoader()
+ .getResource("weka/gui/weka_icon_new_48.png"));
jf.setIconImage(icon);
Thread memMonitor = new Thread() {
+ @Override
public void run() {
- while(true) {
- try {
- this.sleep(4000);
-
+ while (true) {
+ // try {
+ // this.sleep(4000);
+ //
+ // System.gc();
+
+ if (m_Memory.isOutOfMemory()) {
+ // clean up
+ jf.dispose();
+ m_experimenter = null;
System.gc();
- if (m_Memory.isOutOfMemory()) {
- // clean up
- jf.dispose();
- m_experimenter = null;
- System.gc();
-
- // display error
- System.err.println(Messages.getInstance().getString("Experimenter_Main_Error_Text_First"));
- m_Memory.showOutOfMemory();
- System.err.println(Messages.getInstance().getString("Experimenter_Main_Error_Text_Second"));
- System.exit(-1);
- }
+ // display error
+ System.err.println(Messages.getInstance().getString(
+ "Experimenter_Main_Error_Text_First"));
+ m_Memory.showOutOfMemory();
+ System.err.println(Messages.getInstance().getString(
+ "Experimenter_Main_Error_Text_Second"));
+ System.exit(-1);
+ }
- } catch(InterruptedException ex) { ex.printStackTrace(); }
+ // } catch(InterruptedException ex) { ex.printStackTrace(); }
}
}
};
diff --git a/src/main/java/weka/gui/explorer/ClassifierPanel.java b/src/main/java/weka/gui/explorer/ClassifierPanel.java
index 11536ca..9f08c52 100644
--- a/src/main/java/weka/gui/explorer/ClassifierPanel.java
+++ b/src/main/java/weka/gui/explorer/ClassifierPanel.java
@@ -142,10 +142,10 @@ import weka.gui.visualize.plugins.VisualizePlugin;
* @author Len Trigg (trigg at cs.waikato.ac.nz)
* @author Mark Hall (mhall at cs.waikato.ac.nz)
* @author Richard Kirkby (rkirkby at cs.waikato.ac.nz)
- * @version $Revision: 9755 $
+ * @version $Revision: 10372 $
*/
public class ClassifierPanel extends JPanel implements
- CapabilitiesFilterChangeListener, ExplorerPanel, LogHandler {
+ CapabilitiesFilterChangeListener, ExplorerPanel, LogHandler {
/** for serialization */
static final long serialVersionUID = 6959973704963624003L;
@@ -182,89 +182,88 @@ public class ClassifierPanel extends JPanel implements
/** Click to set test mode to cross-validation */
protected JRadioButton m_CVBut = new JRadioButton(Messages.getInstance()
- .getString("ClassifierPanel_CVBut_JRadioButton_Text"));
+ .getString("ClassifierPanel_CVBut_JRadioButton_Text"));
/** Click to set test mode to generate a % split */
protected JRadioButton m_PercentBut = new JRadioButton(Messages.getInstance()
- .getString("ClassifierPanel_PercentBut_JRadioButton_Text"));
+ .getString("ClassifierPanel_PercentBut_JRadioButton_Text"));
/** Click to set test mode to test on training data */
protected JRadioButton m_TrainBut = new JRadioButton(Messages.getInstance()
- .getString("ClassifierPanel_TrainBut_JRadioButton_Text"));
+ .getString("ClassifierPanel_TrainBut_JRadioButton_Text"));
/** Click to set test mode to a user-specified test set */
protected JRadioButton m_TestSplitBut = new JRadioButton(Messages
- .getInstance()
- .getString("ClassifierPanel_TestSplitBut_JRadioButton_Text"));
+ .getInstance().getString("ClassifierPanel_TestSplitBut_JRadioButton_Text"));
/**
* Check to save the predictions in the results list for visualizing later on
*/
protected JCheckBox m_StorePredictionsBut = new JCheckBox(Messages
- .getInstance().getString(
- "ClassifierPanel_StorePredictionsBut_JCheckBox_Text"));
+ .getInstance().getString(
+ "ClassifierPanel_StorePredictionsBut_JCheckBox_Text"));
/** Check to output the model built from the training data */
protected JCheckBox m_OutputModelBut = new JCheckBox(Messages.getInstance()
- .getString("ClassifierPanel_OutputModelBut_JCheckBox_Text"));
+ .getString("ClassifierPanel_OutputModelBut_JCheckBox_Text"));
/** Check to output true/false positives, precision/recall for each class */
protected JCheckBox m_OutputPerClassBut = new JCheckBox(Messages
- .getInstance().getString(
- "ClassifierPanel_OutputPerClassBut_JCheckBox_Text"));
+ .getInstance()
+ .getString("ClassifierPanel_OutputPerClassBut_JCheckBox_Text"));
/** Check to output a confusion matrix */
protected JCheckBox m_OutputConfusionBut = new JCheckBox(Messages
- .getInstance().getString(
- "ClassifierPanel_OutputConfusionBut_JCheckBox_Text"));
+ .getInstance().getString(
+ "ClassifierPanel_OutputConfusionBut_JCheckBox_Text"));
/** Check to output entropy statistics */
protected JCheckBox m_OutputEntropyBut = new JCheckBox(Messages.getInstance()
- .getString("ClassifierPanel_OutputEntropyBut_JCheckBox_Text"));
+ .getString("ClassifierPanel_OutputEntropyBut_JCheckBox_Text"));
/** Check to output text predictions */
protected JCheckBox m_OutputPredictionsTextBut = new JCheckBox(Messages
- .getInstance().getString(
- "ClassifierPanel_OutputPredictionsTextBut_JCheckBox_Text"));
+ .getInstance().getString(
+ "ClassifierPanel_OutputPredictionsTextBut_JCheckBox_Text"));
/** Lists indices for additional attributes to output */
protected JTextField m_OutputAdditionalAttributesText = new JTextField("", 10);
/** Label for the text field with additional attributes in the output */
protected JLabel m_OutputAdditionalAttributesLab = new JLabel(Messages
- .getInstance().getString(
- "ClassifierPanel_OutputAdditionalAttributesLab_JLabel_Text"));
+ .getInstance().getString(
+ "ClassifierPanel_OutputAdditionalAttributesLab_JLabel_Text"));
/** the range of attributes to output */
protected Range m_OutputAdditionalAttributesRange = null;
/** Check to evaluate w.r.t a cost matrix */
protected JCheckBox m_EvalWRTCostsBut = new JCheckBox(Messages.getInstance()
- .getString("ClassifierPanel_EvalWRTCostsBut_JCheckBox_Text"));
+ .getString("ClassifierPanel_EvalWRTCostsBut_JCheckBox_Text"));
/** for the cost matrix */
protected JButton m_SetCostsBut = new JButton(Messages.getInstance()
- .getString("ClassifierPanel_SetCostsBut_JButton_Text"));
+ .getString("ClassifierPanel_SetCostsBut_JButton_Text"));
/** Label by where the cv folds are entered */
protected JLabel m_CVLab = new JLabel(Messages.getInstance().getString(
- "ClassifierPanel_CVLab_JLabel_Text"), SwingConstants.RIGHT);
+ "ClassifierPanel_CVLab_JLabel_Text"), SwingConstants.RIGHT);
/** The field where the cv folds are entered */
protected JTextField m_CVText = new JTextField(Messages.getInstance()
- .getString("ClassifierPanel_CVText_JTextField_Text"), 3);
+ .getString("ClassifierPanel_CVText_JTextField_Text"), 3);
/** Label by where the % split is entered */
protected JLabel m_PercentLab = new JLabel(Messages.getInstance().getString(
- "ClassifierPanel_PercentLab_JLabel_Text"), SwingConstants.RIGHT);
+ "ClassifierPanel_PercentLab_JLabel_Text"), SwingConstants.RIGHT);
/** The field where the % split is entered */
protected JTextField m_PercentText = new JTextField(Messages.getInstance()
- .getString("ClassifierPanel_PercentText_JTextField_Text"), 3);
+ .getString("ClassifierPanel_PercentText_JTextField_Text"), 3);
/** The button used to open a separate test dataset */
protected JButton m_SetTestBut = new JButton(Messages.getInstance()
- .getString("ClassifierPanel_SetTestBut_JButton_Text"));
+ .getString("ClassifierPanel_SetTestBut_JButton_Text"));
/** The frame used to show the test set selection panel */
protected JFrame m_SetTestFrame;
@@ -285,43 +284,43 @@ public class ClassifierPanel extends JPanel implements
/** Button for further output/visualize options */
JButton m_MoreOptions = new JButton(Messages.getInstance().getString(
- "ClassifierPanel_MoreOptions_JButton_Text"));
+ "ClassifierPanel_MoreOptions_JButton_Text"));
/** User specified random seed for cross validation or % split */
protected JTextField m_RandomSeedText = new JTextField(Messages.getInstance()
- .getString("ClassifierPanel_RandomSeedText_JTextField_Text"), 3);
+ .getString("ClassifierPanel_RandomSeedText_JTextField_Text"), 3);
/** the label for the random seed textfield */
protected JLabel m_RandomLab = new JLabel(Messages.getInstance().getString(
- "ClassifierPanel_RandomLab_JLabel_Text"), SwingConstants.RIGHT);
+ "ClassifierPanel_RandomLab_JLabel_Text"), SwingConstants.RIGHT);
/** Whether randomization is turned off to preserve order */
protected JCheckBox m_PreserveOrderBut = new JCheckBox(Messages.getInstance()
- .getString("ClassifierPanel_PreserveOrderBut_JCheckBox_Text"));
+ .getString("ClassifierPanel_PreserveOrderBut_JCheckBox_Text"));
/**
* Whether to output the source code (only for classifiers importing
* Sourcable)
*/
protected JCheckBox m_OutputSourceCode = new JCheckBox(Messages.getInstance()
- .getString("ClassifierPanel_OutputSourceCode_JCheckBox_Text"));
+ .getString("ClassifierPanel_OutputSourceCode_JCheckBox_Text"));
/** The name of the generated class (only applicable to Sourcable schemes) */
- protected JTextField m_SourceCodeClass = new JTextField(Messages
- .getInstance().getString(
- "ClassifierPanel_SourceCodeClass_JTextField_Text"), 10);
+ protected JTextField m_SourceCodeClass = new JTextField(
+ Messages.getInstance().getString(
+ "ClassifierPanel_SourceCodeClass_JTextField_Text"), 10);
/** Click to start running the classifier */
protected JButton m_StartBut = new JButton(Messages.getInstance().getString(
- "ClassifierPanel_StartBut_JButton_Text"));
+ "ClassifierPanel_StartBut_JButton_Text"));
/** Click to stop a running classifier */
protected JButton m_StopBut = new JButton(Messages.getInstance().getString(
- "ClassifierPanel_StopBut_JButton_Text"));
+ "ClassifierPanel_StopBut_JButton_Text"));
/** Stop the class combo from taking up to much space */
private final Dimension COMBO_SIZE = new Dimension(150,
- m_StartBut.getPreferredSize().height);
+ m_StartBut.getPreferredSize().height);
/** The cost matrix editor for evaluation costs */
protected CostMatrixEditor m_CostMatrixEditor = new CostMatrixEditor();
@@ -340,16 +339,16 @@ public class ClassifierPanel extends JPanel implements
/** Filter to ensure only model files are selected */
protected FileFilter m_ModelFilter = new ExtensionFileFilter(
- MODEL_FILE_EXTENSION, Messages.getInstance().getString(
- "ClassifierPanel_ModelFilter_FileFilter_Text"));
+ MODEL_FILE_EXTENSION, Messages.getInstance().getString(
+ "ClassifierPanel_ModelFilter_FileFilter_Text"));
protected FileFilter m_PMMLModelFilter = new ExtensionFileFilter(
- PMML_FILE_EXTENSION, Messages.getInstance().getString(
- "ClassifierPanel_PMMLModelFilter_FileFilter_Text"));
+ PMML_FILE_EXTENSION, Messages.getInstance().getString(
+ "ClassifierPanel_PMMLModelFilter_FileFilter_Text"));
/** The file chooser for selecting model files */
protected JFileChooser m_FileChooser = new JFileChooser(new File(
- System.getProperty("user.dir")));
+ System.getProperty("user.dir")));
/* Register the property editors we need */
static {
@@ -373,9 +372,9 @@ public class ClassifierPanel extends JPanel implements
}
}
});
- m_History.setBorder(BorderFactory.createTitledBorder(Messages.getInstance()
- .getString(
- "ClassifierPanel_History_BorderFactoryCreateTitledBorder_Text")));
+ m_History.setBorder(BorderFactory
+ .createTitledBorder(Messages.getInstance().getString(
+ "ClassifierPanel_History_BorderFactoryCreateTitledBorder_Text")));
m_ClassifierEditor.setClassType(Classifier.class);
m_ClassifierEditor.setValue(ExplorerDefaults.getClassifier());
m_ClassifierEditor.addPropertyChangeListener(new PropertyChangeListener() {
@@ -387,12 +386,12 @@ public class ClassifierPanel extends JPanel implements
Classifier classifier = (Classifier) m_ClassifierEditor.getValue();
Capabilities currentSchemeCapabilities = null;
if (classifier != null && currentFilter != null
- && (classifier instanceof CapabilitiesHandler)) {
+ && (classifier instanceof CapabilitiesHandler)) {
currentSchemeCapabilities = ((CapabilitiesHandler) classifier)
- .getCapabilities();
+ .getCapabilities();
if (!currentSchemeCapabilities.supportsMaybe(currentFilter)
- && !currentSchemeCapabilities.supports(currentFilter)) {
+ && !currentSchemeCapabilities.supports(currentFilter)) {
m_StartBut.setEnabled(false);
}
}
@@ -401,47 +400,45 @@ public class ClassifierPanel extends JPanel implements
});
m_ClassCombo.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_ClassCombo_SetToolTipText_Text"));
+ "ClassifierPanel_ClassCombo_SetToolTipText_Text"));
m_TrainBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_TrainBut_SetToolTipText_Text"));
+ "ClassifierPanel_TrainBut_SetToolTipText_Text"));
m_CVBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_CVBut_SetToolTipText_Text"));
+ "ClassifierPanel_CVBut_SetToolTipText_Text"));
m_PercentBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_PercentBut_SetToolTipText_Text"));
+ "ClassifierPanel_PercentBut_SetToolTipText_Text"));
m_TestSplitBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_TestSplitBut_SetToolTipText_Text"));
+ "ClassifierPanel_TestSplitBut_SetToolTipText_Text"));
m_StartBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_StartBut_SetToolTipText_Text"));
+ "ClassifierPanel_StartBut_SetToolTipText_Text"));
m_StopBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_StopBut_SetToolTipText_Text"));
+ "ClassifierPanel_StopBut_SetToolTipText_Text"));
m_StorePredictionsBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_StorePredictionsBut_SetToolTipText_Text"));
+ "ClassifierPanel_StorePredictionsBut_SetToolTipText_Text"));
m_OutputModelBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_OutputModelBut_SetToolTipText_Text"));
+ "ClassifierPanel_OutputModelBut_SetToolTipText_Text"));
m_OutputPerClassBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_OutputPerClassBut_SetToolTipText_Text"));
+ "ClassifierPanel_OutputPerClassBut_SetToolTipText_Text"));
m_OutputConfusionBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_OutputConfusionBut_SetToolTipText_Text"));
+ "ClassifierPanel_OutputConfusionBut_SetToolTipText_Text"));
m_OutputEntropyBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_OutputEntropyBut_SetToolTipText_Text"));
+ "ClassifierPanel_OutputEntropyBut_SetToolTipText_Text"));
m_EvalWRTCostsBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_EvalWRTCostsBut_SetToolTipText_Text"));
+ "ClassifierPanel_EvalWRTCostsBut_SetToolTipText_Text"));
m_OutputPredictionsTextBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_OutputPredictionsTextBut_SetToolTipText_Text"));
- m_OutputAdditionalAttributesText
- .setToolTipText(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_OutputAdditionalAttributesText_SetToolTipText_Text"));
+ "ClassifierPanel_OutputPredictionsTextBut_SetToolTipText_Text"));
+ m_OutputAdditionalAttributesText.setToolTipText(Messages.getInstance()
+ .getString(
+ "ClassifierPanel_OutputAdditionalAttributesText_SetToolTipText_Text"));
m_RandomLab.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_RandomLab_SetToolTipText_Text"));
+ "ClassifierPanel_RandomLab_SetToolTipText_Text"));
m_RandomSeedText.setToolTipText(m_RandomLab.getToolTipText());
m_PreserveOrderBut.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_PreserveOrderBut_SetToolTipText_Text"));
+ "ClassifierPanel_PreserveOrderBut_SetToolTipText_Text"));
m_OutputSourceCode.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_OutputSourceCode_SetToolTipText_Text"));
+ "ClassifierPanel_OutputSourceCode_SetToolTipText_Text"));
m_SourceCodeClass.setToolTipText(Messages.getInstance().getString(
- "ClassifierPanel_SourceCodeClass_SetToolTipText_Text"));
+ "ClassifierPanel_SourceCodeClass_SetToolTipText_Text"));
m_FileChooser.addChoosableFileFilter(m_PMMLModelFilter);
m_FileChooser.setFileFilter(m_ModelFilter);
@@ -449,32 +446,32 @@ public class ClassifierPanel extends JPanel implements
m_FileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
m_StorePredictionsBut.setSelected(ExplorerDefaults
- .getClassifierStorePredictionsForVis());
+ .getClassifierStorePredictionsForVis());
m_OutputModelBut.setSelected(ExplorerDefaults.getClassifierOutputModel());
m_OutputPerClassBut.setSelected(ExplorerDefaults
- .getClassifierOutputPerClassStats());
+ .getClassifierOutputPerClassStats());
m_OutputConfusionBut.setSelected(ExplorerDefaults
- .getClassifierOutputConfusionMatrix());
+ .getClassifierOutputConfusionMatrix());
m_EvalWRTCostsBut.setSelected(ExplorerDefaults
- .getClassifierCostSensitiveEval());
+ .getClassifierCostSensitiveEval());
m_OutputEntropyBut.setSelected(ExplorerDefaults
- .getClassifierOutputEntropyEvalMeasures());
+ .getClassifierOutputEntropyEvalMeasures());
m_OutputPredictionsTextBut.setSelected(ExplorerDefaults
- .getClassifierOutputPredictions());
+ .getClassifierOutputPredictions());
m_OutputPredictionsTextBut.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
m_OutputAdditionalAttributesText.setEnabled(m_OutputPredictionsTextBut
- .isSelected());
+ .isSelected());
}
});
m_OutputAdditionalAttributesText.setText(ExplorerDefaults
- .getClassifierOutputAdditionalAttributes());
+ .getClassifierOutputAdditionalAttributes());
m_OutputAdditionalAttributesText.setEnabled(m_OutputPredictionsTextBut
- .isSelected());
+ .isSelected());
m_RandomSeedText.setText("" + ExplorerDefaults.getClassifierRandomSeed());
m_PreserveOrderBut.setSelected(ExplorerDefaults
- .getClassifierPreserveOrder());
+ .getClassifierPreserveOrder());
m_OutputSourceCode.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@@ -482,7 +479,7 @@ public class ClassifierPanel extends JPanel implements
}
});
m_OutputSourceCode.setSelected(ExplorerDefaults
- .getClassifierOutputSourceCode());
+ .getClassifierOutputSourceCode());
m_SourceCodeClass.setText(ExplorerDefaults.getClassifierSourceCodeClass());
m_SourceCodeClass.setEnabled(m_OutputSourceCode.isSelected());
m_ClassCombo.setEnabled(false);
@@ -530,23 +527,24 @@ public class ClassifierPanel extends JPanel implements
public void actionPerformed(ActionEvent e) {
m_SetCostsBut.setEnabled(false);
if (m_SetCostsFrame == null) {
- if (PropertyDialog.getParentDialog(ClassifierPanel.this) != null)
+ if (PropertyDialog.getParentDialog(ClassifierPanel.this) != null) {
m_SetCostsFrame = new PropertyDialog(PropertyDialog
- .getParentDialog(ClassifierPanel.this), m_CostMatrixEditor,
- 100, 100);
- else
+ .getParentDialog(ClassifierPanel.this), m_CostMatrixEditor, 100,
+ 100);
+ } else {
m_SetCostsFrame = new PropertyDialog(PropertyDialog
- .getParentFrame(ClassifierPanel.this), m_CostMatrixEditor, 100,
- 100);
+ .getParentFrame(ClassifierPanel.this), m_CostMatrixEditor, 100,
+ 100);
+ }
m_SetCostsFrame.setTitle(Messages.getInstance().getString(
- "ClassifierPanel_SetCostsFrame_SetTitle_Text"));
+ "ClassifierPanel_SetCostsFrame_SetTitle_Text"));
// pd.setSize(250,150);
m_SetCostsFrame.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent p) {
m_SetCostsBut.setEnabled(m_EvalWRTCostsBut.isSelected());
if ((m_SetCostsFrame != null)
- && (!m_EvalWRTCostsBut.isSelected())) {
+ && (!m_EvalWRTCostsBut.isSelected())) {
m_SetCostsFrame.setVisible(false);
}
}
@@ -558,8 +556,9 @@ public class ClassifierPanel extends JPanel implements
int classIndex = m_ClassCombo.getSelectedIndex();
int numClasses = m_Instances.attribute(classIndex).numValues();
if (numClasses != ((CostMatrix) m_CostMatrixEditor.getValue())
- .numColumns())
+ .numColumns()) {
m_CostMatrixEditor.setValue(new CostMatrix(numClasses));
+ }
m_SetCostsFrame.setVisible(true);
}
@@ -606,7 +605,7 @@ public class ClassifierPanel extends JPanel implements
@Override
public void mouseClicked(MouseEvent e) {
if (((e.getModifiers() & InputEvent.BUTTON1_MASK) != InputEvent.BUTTON1_MASK)
- || e.isAltDown()) {
+ || e.isAltDown()) {
int index = m_History.getList().locationToIndex(e.getPoint());
if (index != -1) {
String name = m_History.getNameAtIndex(index);
@@ -647,7 +646,7 @@ public class ClassifierPanel extends JPanel implements
JPanel sourcePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
m_OutputSourceCode.setEnabled(m_ClassifierEditor.getValue() instanceof Sourcable);
m_SourceCodeClass.setEnabled(m_OutputSourceCode.isEnabled()
- && m_OutputSourceCode.isSelected());
+ && m_OutputSourceCode.isSelected());
sourcePanel.add(m_OutputSourceCode);
sourcePanel.add(m_SourceCodeClass);
moreOptionsPanel.add(sourcePanel);
@@ -656,7 +655,7 @@ public class ClassifierPanel extends JPanel implements
all.setLayout(new BorderLayout());
JButton oK = new JButton(Messages.getInstance().getString(
- "ClassifierPanel_OK_JButton_Text"));
+ "ClassifierPanel_OK_JButton_Text"));
JPanel okP = new JPanel();
okP.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
okP.setLayout(new GridLayout(1, 1, 5, 5));
@@ -666,8 +665,8 @@ public class ClassifierPanel extends JPanel implements
all.add(okP, BorderLayout.SOUTH);
final JDialog jd = new JDialog(PropertyDialog
- .getParentFrame(ClassifierPanel.this), Messages.getInstance()
- .getString("ClassifierPanel_JD_JDialog_Text"));
+ .getParentFrame(ClassifierPanel.this), Messages.getInstance()
+ .getString("ClassifierPanel_JD_JDialog_Text"));
jd.getContentPane().setLayout(new BorderLayout());
jd.getContentPane().add(all, BorderLayout.CENTER);
jd.addWindowListener(new java.awt.event.WindowAdapter() {
@@ -693,9 +692,9 @@ public class ClassifierPanel extends JPanel implements
// Layout the GUI
JPanel p1 = new JPanel();
p1.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(Messages.getInstance().getString(
- "ClassifierPanel_P1_JPanel_BorderFactoryCreateTitledBorder_Text")),
- BorderFactory.createEmptyBorder(0, 5, 5, 5)));
+ BorderFactory.createTitledBorder(Messages.getInstance().getString(
+ "ClassifierPanel_P1_JPanel_BorderFactoryCreateTitledBorder_Text")),
+ BorderFactory.createEmptyBorder(0, 5, 5, 5)));
p1.setLayout(new BorderLayout());
p1.add(m_CEPanel, BorderLayout.NORTH);
@@ -703,9 +702,9 @@ public class ClassifierPanel extends JPanel implements
GridBagLayout gbL = new GridBagLayout();
p2.setLayout(gbL);
p2.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(Messages.getInstance().getString(
- "ClassifierPanel_P2_JPanel_BorderFactoryCreateTitledBorder_Text")),
- BorderFactory.createEmptyBorder(0, 5, 5, 5)));
+ BorderFactory.createTitledBorder(Messages.getInstance().getString(
+ "ClassifierPanel_P2_JPanel_BorderFactoryCreateTitledBorder_Text")),
+ BorderFactory.createEmptyBorder(0, 5, 5, 5)));
GridBagConstraints gbC = new GridBagConstraints();
gbC.anchor = GridBagConstraints.WEST;
gbC.gridy = 0;
@@ -808,8 +807,8 @@ public class ClassifierPanel extends JPanel implements
JPanel p3 = new JPanel();
p3.setBorder(BorderFactory.createTitledBorder(Messages.getInstance()
- .getString(
- "ClassifierPanel_P3_JPanel_BorderFactoryCreateTitledBorder_Text")));
+ .getString(
+ "ClassifierPanel_P3_JPanel_BorderFactoryCreateTitledBorder_Text")));
p3.setLayout(new BorderLayout());
final JScrollPane js = new JScrollPane(m_OutText);
p3.add(js, BorderLayout.CENTER);
@@ -909,36 +908,37 @@ public class ClassifierPanel extends JPanel implements
switch (m_Instances.attribute(i).type()) {
case Attribute.NOMINAL:
type = Messages.getInstance().getString(
- "ClassifierPanel_SetInstances_Type_AttributeNOMINAL_Text");
+ "ClassifierPanel_SetInstances_Type_AttributeNOMINAL_Text");
break;
case Attribute.NUMERIC:
type = Messages.getInstance().getString(
- "ClassifierPanel_SetInstances_Type_AttributeNUMERIC_Text");
+ "ClassifierPanel_SetInstances_Type_AttributeNUMERIC_Text");
break;
case Attribute.STRING:
type = Messages.getInstance().getString(
- "ClassifierPanel_SetInstances_Type_AttributeSTRING_Text");
+ "ClassifierPanel_SetInstances_Type_AttributeSTRING_Text");
break;
case Attribute.DATE:
type = Messages.getInstance().getString(
- "ClassifierPanel_SetInstances_Type_AttributeDATE_Text");
+ "ClassifierPanel_SetInstances_Type_AttributeDATE_Text");
break;
case Attribute.RELATIONAL:
type = Messages.getInstance().getString(
- "ClassifierPanel_SetInstances_Type_AttributeRELATIONAL_Text");
+ "ClassifierPanel_SetInstances_Type_AttributeRELATIONAL_Text");
break;
default:
type = Messages.getInstance().getString(
- "ClassifierPanel_SetInstances_Type_AttributeDEFAULT_Text");
+ "ClassifierPanel_SetInstances_Type_AttributeDEFAULT_Text");
}
attribNames[i] = type + m_Instances.attribute(i).name();
}
m_ClassCombo.setModel(new DefaultComboBoxModel(attribNames));
if (attribNames.length > 0) {
- if (inst.classIndex() == -1)
+ if (inst.classIndex() == -1) {
m_ClassCombo.setSelectedIndex(attribNames.length - 1);
- else
+ } else {
m_ClassCombo.setSelectedIndex(inst.classIndex());
+ }
m_ClassCombo.setEnabled(true);
m_StartBut.setEnabled(m_RunThread == null);
m_StopBut.setEnabled(m_RunThread != null);
@@ -958,11 +958,12 @@ public class ClassifierPanel extends JPanel implements
if (m_SetTestFrame == null) {
final SetInstancesPanel sp = new SetInstancesPanel(true,
- m_Explorer.getPreprocessPanel().m_FileChooser);
+ m_Explorer.getPreprocessPanel().m_FileChooser);
if (m_TestLoader != null) {
try {
- if (m_TestLoader.getStructure() != null)
+ if (m_TestLoader.getStructure() != null) {
sp.setInstances(m_TestLoader.getStructure());
+ }
} catch (Exception ex) {
ex.printStackTrace();
}
@@ -976,7 +977,7 @@ public class ClassifierPanel extends JPanel implements
// Add propertychangelistener to update m_TestLoader whenever
// it changes in the settestframe
m_SetTestFrame = new JFrame(Messages.getInstance().getString(
- "ClassifierPanel_SetTestSet_SetTestFrame_JFrame_Text"));
+ "ClassifierPanel_SetTestSet_SetTestFrame_JFrame_Text"));
sp.setParentFrame(m_SetTestFrame); // enable Close-Button
m_SetTestFrame.getContentPane().setLayout(new BorderLayout());
m_SetTestFrame.getContentPane().add(sp, BorderLayout.CENTER);
@@ -1002,11 +1003,11 @@ public class ClassifierPanel extends JPanel implements
* @param plotSize additional plotting information (size)
*/
public static void processClassifierPrediction(Instance toPredict,
- Classifier classifier, Evaluation eval, Instances plotInstances,
- FastVector plotShape, FastVector plotSize) {
+ Classifier classifier, Evaluation eval, Instances plotInstances,
+ FastVector plotShape, FastVector plotSize) {
try {
double pred = eval.evaluateModelOnceAndRecordPrediction(classifier,
- toPredict);
+ toPredict);
if (plotInstances != null) {
double[] values = new double[plotInstances.numAttributes()];
@@ -1030,7 +1031,7 @@ public class ClassifierPanel extends JPanel implements
plotInstances.add(new Instance(1.0, values));
if (toPredict.classAttribute().isNominal()) {
if (toPredict.isMissing(toPredict.classIndex())
- || Instance.isMissingValue(pred)) {
+ || Instance.isMissingValue(pred)) {
plotShape.addElement(new Integer(Plot2D.MISSING_SHAPE));
} else if (pred != toPredict.classValue()) {
// set to default error point shape
@@ -1044,7 +1045,7 @@ public class ClassifierPanel extends JPanel implements
// store the error (to be converted to a point size later)
Double errd = null;
if (!toPredict.isMissing(toPredict.classIndex())
- && !Instance.isMissingValue(pred)) {
+ && !Instance.isMissingValue(pred)) {
errd = new Double(pred - toPredict.classValue());
plotShape.addElement(new Integer(Plot2D.CONST_AUTOMATIC_SHAPE));
} else {
@@ -1121,18 +1122,18 @@ public class ClassifierPanel extends JPanel implements
attVals.addElement(classAt.value(i));
}
predictedClass = new Attribute(
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_SetUpVisualizableInstances_PredictedClass_Attribute_Text_First")
- + classAt.name(), attVals);
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_SetUpVisualizableInstances_PredictedClass_Attribute_Text_First")
+ + classAt.name(), attVals);
} else {
predictedClass = new Attribute(
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_SetUpVisualizableInstances_PredictedClass_Attribute_Text_Second")
- + classAt.name());
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_SetUpVisualizableInstances_PredictedClass_Attribute_Text_Second")
+ + classAt.name());
}
for (int i = 0; i < trainInstances.numAttributes(); i++) {
@@ -1142,7 +1143,7 @@ public class ClassifierPanel extends JPanel implements
hv.addElement(trainInstances.attribute(i).copy());
}
return new Instances(trainInstances.relationName() + "_predicted", hv,
- trainInstances.numInstances());
+ trainInstances.numInstances());
}
/**
@@ -1153,31 +1154,29 @@ public class ClassifierPanel extends JPanel implements
* @param title the title to print
*/
protected void printPredictionsHeader(StringBuffer outBuff, Instances inst,
- String title) {
- outBuff
- .append(Messages.getInstance().getString(
- "ClassifierPanel_PrintPredictionsHeader_OutBuffer_Text_First")
- + title
- + " "
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_PrintPredictionsHeader_OutBuffer_Text_First_Alpha"));
+ String title) {
+ outBuff.append(Messages.getInstance().getString(
+ "ClassifierPanel_PrintPredictionsHeader_OutBuffer_Text_First")
+ + title
+ + " "
+ + Messages.getInstance().getString(
+ "ClassifierPanel_PrintPredictionsHeader_OutBuffer_Text_First_Alpha"));
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_PrintPredictionsHeader_OutBuffer_Text_Second"));
+ "ClassifierPanel_PrintPredictionsHeader_OutBuffer_Text_Second"));
if (inst.classAttribute().isNominal()) {
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_PrintPredictionsHeader_OutBuffer_Text_Third"));
+ "ClassifierPanel_PrintPredictionsHeader_OutBuffer_Text_Third"));
}
if (m_OutputAdditionalAttributesRange != null) {
outBuff.append(" (");
boolean first = true;
for (int i = 0; i < inst.numAttributes() - 1; i++) {
if (m_OutputAdditionalAttributesRange.isInRange(i)) {
- if (!first)
+ if (!first) {
outBuff.append(",");
- else
+ } else {
first = false;
+ }
outBuff.append(inst.attribute(i).name());
}
}
@@ -1204,7 +1203,7 @@ public class ClassifierPanel extends JPanel implements
public void run() {
// Copy the current state of things
m_Log.statusMessage(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_First"));
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_First"));
CostMatrix costMatrix = null;
Instances inst = new Instances(m_Instances);
DataSource source = null;
@@ -1228,7 +1227,7 @@ public class ClassifierPanel extends JPanel implements
}
if (m_EvalWRTCostsBut.isSelected()) {
costMatrix = new CostMatrix(
- (CostMatrix) m_CostMatrixEditor.getValue());
+ (CostMatrix) m_CostMatrixEditor.getValue());
}
boolean outputModel = m_OutputModelBut.isSelected();
boolean outputConfusion = m_OutputConfusionBut.isSelected();
@@ -1237,14 +1236,30 @@ public class ClassifierPanel extends JPanel implements
boolean outputEntropy = m_OutputEntropyBut.isSelected();
boolean saveVis = m_StorePredictionsBut.isSelected();
boolean outputPredictionsText = m_OutputPredictionsTextBut
- .isSelected();
+ .isSelected();
if (m_OutputAdditionalAttributesText.getText().equals("")) {
m_OutputAdditionalAttributesRange = null;
} else {
- m_OutputAdditionalAttributesRange = new Range(
+ try {
+ m_OutputAdditionalAttributesRange = new Range(
m_OutputAdditionalAttributesText.getText());
- m_OutputAdditionalAttributesRange
+ m_OutputAdditionalAttributesRange
.setUpper(inst.numAttributes() - 1);
+ } catch (IllegalArgumentException e) {
+ JOptionPane.showMessageDialog(
+ ClassifierPanel.this,
+ Messages.getInstance().getString(
+ "ClassifierPanel_OutputAdditionalAttributes_First")
+ + "\n\n"
+ + m_OutputAdditionalAttributesText.getText()
+ + "\n\n"
+ + Messages.getInstance().getString(
+ "ClassifierPanel_OutputAdditionalAttributes_Second"),
+ Messages.getInstance().getString(
+ "ClassifierPanel_OutputAdditionalAttributes_Title"),
+ JOptionPane.ERROR_MESSAGE);
+ m_OutputAdditionalAttributesRange = null;
+ }
}
String grph = null;
@@ -1259,13 +1274,13 @@ public class ClassifierPanel extends JPanel implements
template = Classifier.makeCopy(classifier);
} catch (Exception ex) {
m_Log.logMessage(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Log_LogMessage_Text_First")
- + ex.getMessage());
+ "ClassifierPanel_StartClassifier_Log_LogMessage_Text_First")
+ + ex.getMessage());
}
Classifier fullClassifier = null;
StringBuffer outBuff = new StringBuffer();
String name = (new SimpleDateFormat("HH:mm:ss - "))
- .format(new Date());
+ .format(new Date());
String cname = classifier.getClass().getName();
if (cname.startsWith("weka.classifiers.")) {
name += cname.substring("weka.classifiers.".length());
@@ -1273,10 +1288,11 @@ public class ClassifierPanel extends JPanel implements
name += cname;
}
String cmd = m_ClassifierEditor.getValue().getClass().getName();
- if (m_ClassifierEditor.getValue() instanceof OptionHandler)
+ if (m_ClassifierEditor.getValue() instanceof OptionHandler) {
cmd += " "
- + Utils.joinOptions(((OptionHandler) m_ClassifierEditor
- .getValue()).getOptions());
+ + Utils.joinOptions(((OptionHandler) m_ClassifierEditor
+ .getValue()).getOptions());
+ }
Evaluation eval = null;
try {
if (m_CVBut.isSelected()) {
@@ -1284,14 +1300,14 @@ public class ClassifierPanel extends JPanel implements
numFolds = Integer.parseInt(m_CVText.getText());
if (numFolds <= 1) {
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Exception_Text_First"));
+ "ClassifierPanel_StartClassifier_Exception_Text_First"));
}
} else if (m_PercentBut.isSelected()) {
testMode = 2;
percent = Double.parseDouble(m_PercentText.getText());
if ((percent <= 0) || (percent >= 100)) {
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Exception_Text_Second"));
+ "ClassifierPanel_StartClassifier_Exception_Text_Second"));
}
} else if (m_TrainBut.isSelected()) {
testMode = 3;
@@ -1300,16 +1316,16 @@ public class ClassifierPanel extends JPanel implements
// Check the test instance compatibility
if (source == null) {
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Exception_Text_Third"));
+ "ClassifierPanel_StartClassifier_Exception_Text_Third"));
}
if (!inst.equalHeaders(userTestStructure)) {
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Exception_Text_Fourth"));
+ "ClassifierPanel_StartClassifier_Exception_Text_Fourth"));
}
userTestStructure.setClassIndex(classIndex);
} else {
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Exception_Text_Fifth"));
+ "ClassifierPanel_StartClassifier_Exception_Text_Fifth"));
}
inst.setClassIndex(classIndex);
@@ -1322,99 +1338,87 @@ public class ClassifierPanel extends JPanel implements
// Output some header information
m_Log.logMessage(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Second")
- + cname);
+ "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Second")
+ + cname);
m_Log.logMessage(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Third")
- + cmd);
+ "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Third")
+ + cmd);
if (m_Log instanceof TaskLogger) {
((TaskLogger) m_Log).taskStarted();
}
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_First"));
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_First"));
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Second")
- + cname);
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Second")
+ + cname);
if (classifier instanceof OptionHandler) {
String[] o = ((OptionHandler) classifier).getOptions();
outBuff.append(" " + Utils.joinOptions(o));
}
outBuff.append("\n");
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Fourth")
- + inst.relationName() + '\n');
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Fourth")
+ + inst.relationName() + '\n');
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Sixth")
- + inst.numInstances() + '\n');
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Sixth")
+ + inst.numInstances() + '\n');
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Eigth")
- + inst.numAttributes() + '\n');
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Eigth")
+ + inst.numAttributes() + '\n');
if (inst.numAttributes() < 100) {
for (int i = 0; i < inst.numAttributes(); i++) {
outBuff.append(" " + inst.attribute(i).name()
- + '\n');
+ + '\n');
}
} else {
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Twelveth"));
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Twelveth"));
}
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Thirteenth"));
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Thirteenth"));
switch (testMode) {
case 3: // Test on training
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Fourteenth"));
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Fourteenth"));
break;
case 1: // CV mode
- outBuff
- .append(""
- + numFolds
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Sixteenth"));
+ outBuff.append(""
+ + numFolds
+ + Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Sixteenth"));
break;
case 2: // Percent split
- outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Seventeenth")
- + percent
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Eighteenth"));
+ outBuff.append(Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Seventeenth")
+ + percent
+ + Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Eighteenth"));
break;
case 4: // Test on user split
- if (source.isIncremental())
- outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Nineteenth"));
- else
+ if (source.isIncremental()) {
+ outBuff.append(Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Nineteenth"));
+ } else {
outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_Twentyth")
- + source.getDataSet().numInstances()
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentyFirst"));
+ .append(Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_Twentyth")
+ + source.getDataSet().numInstances()
+ + Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentyFirst"));
+ }
break;
}
if (costMatrix != null) {
outBuff
- .append(
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentySecond"))
- .append(costMatrix.toString()).append("\n");
+ .append(
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentySecond"))
+ .append(costMatrix.toString()).append("\n");
}
outBuff.append("\n");
m_History.addResult(name, outBuff);
@@ -1423,10 +1427,10 @@ public class ClassifierPanel extends JPanel implements
// Build the model and output it.
if (outputModel || (testMode == 3) || (testMode == 4)) {
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Second"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Second"));
trainTimeStart = System.currentTimeMillis();
classifier.buildClassifier(inst);
@@ -1434,23 +1438,20 @@ public class ClassifierPanel extends JPanel implements
}
if (outputModel) {
- outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentySixth"));
+ outBuff.append(Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentySixth"));
outBuff.append(classifier.toString() + "\n");
outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentyEighth")
- + Utils.doubleToString(trainTimeElapsed / 1000.0, 2)
- + " "
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentyNineth"));
+ .append(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentyEighth")
+ + Utils.doubleToString(trainTimeElapsed / 1000.0, 2)
+ + " "
+ + Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_TwentyNineth"));
m_History.updateResult(name);
if (classifier instanceof Drawable) {
grph = null;
@@ -1475,15 +1476,15 @@ public class ClassifierPanel extends JPanel implements
for (int jj = 0; jj < inst.numInstances(); jj++) {
processClassifierPrediction(inst.instance(jj), classifier,
- eval, predInstances, plotShape, plotSize);
+ eval, predInstances, plotShape, plotSize);
if (outputPredictionsText) {
outBuff.append(predictionText(classifier, inst.instance(jj),
- jj + 1));
+ jj + 1));
}
if ((jj % 100) == 0) {
m_Log.statusMessage("Evaluating on training data. Processed "
- + jj + " instances...");
+ + jj + " instances...");
}
}
if (outputPredictionsText) {
@@ -1517,56 +1518,56 @@ public class ClassifierPanel extends JPanel implements
// Make some splits and do a CV
for (int fold = 0; fold < numFolds; fold++) {
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Eighth")
- + (fold + 1)
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Nineth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Eighth")
+ + (fold + 1)
+ + Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Nineth"));
Instances train = inst.trainCV(numFolds, fold, random);
eval.setPriors(train);
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Tenth")
- + (fold + 1)
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Twelveth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Tenth")
+ + (fold + 1)
+ + Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Twelveth"));
Classifier current = null;
try {
current = Classifier.makeCopy(template);
} catch (Exception ex) {
m_Log
- .logMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Fifth")
- + ex.getMessage());
+ .logMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Fifth")
+ + ex.getMessage());
}
current.buildClassifier(train);
Instances test = inst.testCV(numFolds, fold);
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Eleventh")
- + (fold + 1)
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Twelveth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Eleventh")
+ + (fold + 1)
+ + Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Twelveth"));
for (int jj = 0; jj < test.numInstances(); jj++) {
processClassifierPrediction(test.instance(jj), current, eval,
- predInstances, plotShape, plotSize);
+ predInstances, plotShape, plotSize);
if (outputPredictionsText) {
outBuff.append(predictionText(current, test.instance(jj),
- jj + 1));
+ jj + 1));
}
}
}
@@ -1575,128 +1576,122 @@ public class ClassifierPanel extends JPanel implements
}
if (inst.attribute(classIndex).isNominal()) {
outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_ThirtyThird"));
+ .append(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_ThirtyThird"));
} else {
outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_ThirtyFourth"));
+ .append(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_ThirtyFourth"));
}
break;
case 2: // Percent split
if (!m_PreserveOrderBut.isSelected()) {
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Thirteenth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Thirteenth"));
try {
rnd = Integer.parseInt(m_RandomSeedText.getText().trim());
} catch (Exception ex) {
m_Log
- .logMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Fourteenth"));
+ .logMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Fourteenth"));
rnd = 1;
}
inst.randomize(new Random(rnd));
}
int trainSize = (int) Math.round(inst.numInstances() * percent
- / 100);
+ / 100);
int testSize = inst.numInstances() - trainSize;
Instances train = new Instances(inst, 0, trainSize);
Instances test = new Instances(inst, trainSize, testSize);
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Fifteenth")
- + trainSize
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Sixteenth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Fifteenth")
+ + trainSize
+ + Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Sixteenth"));
Classifier current = null;
try {
current = Classifier.makeCopy(template);
} catch (Exception ex) {
- m_Log
- .logMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Sixth")
- + ex.getMessage());
+ m_Log.logMessage(Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Sixth")
+ + ex.getMessage());
}
current.buildClassifier(train);
eval = new Evaluation(train, costMatrix);
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Seventeenth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Seventeenth"));
if (outputPredictionsText) {
printPredictionsHeader(
- outBuff,
- inst,
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_PrintPredictionsHeader_Text_First"));
+ outBuff,
+ inst,
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_PrintPredictionsHeader_Text_First"));
}
for (int jj = 0; jj < test.numInstances(); jj++) {
processClassifierPrediction(test.instance(jj), current, eval,
- predInstances, plotShape, plotSize);
+ predInstances, plotShape, plotSize);
if (outputPredictionsText) {
outBuff.append(predictionText(current, test.instance(jj),
- jj + 1));
+ jj + 1));
}
if ((jj % 100) == 0) {
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Eighteenth")
- + jj
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Nineteenth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Eighteenth")
+ + jj
+ + Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Nineteenth"));
}
}
if (outputPredictionsText) {
outBuff.append("\n");
}
- outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_ThirtySixth"));
+ outBuff.append(Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_ThirtySixth"));
break;
case 4: // Test on user split
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Twentyth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_Twentyth"));
eval = new Evaluation(inst, costMatrix);
if (outputPredictionsText) {
printPredictionsHeader(
- outBuff,
- inst,
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_PrintPredictionsHeader_Text_Second"));
+ outBuff,
+ inst,
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_PrintPredictionsHeader_Text_Second"));
}
Instance instance;
@@ -1704,37 +1699,34 @@ public class ClassifierPanel extends JPanel implements
while (source.hasMoreElements(userTestStructure)) {
instance = source.nextElement(userTestStructure);
processClassifierPrediction(instance, classifier, eval,
- predInstances, plotShape, plotSize);
+ predInstances, plotShape, plotSize);
if (outputPredictionsText) {
outBuff.append(predictionText(classifier, instance, jj + 1));
}
if ((++jj % 100) == 0) {
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentyFirst")
- + jj
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentySecond"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentyFirst")
+ + jj
+ + Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentySecond"));
}
}
if (outputPredictionsText) {
outBuff.append("\n");
}
- outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_ThirtyEighth"));
+ outBuff.append(Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_ThirtyEighth"));
break;
default:
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Exception_Text"));
+ "ClassifierPanel_StartClassifier_Exception_Text"));
}
if (outputSummary) {
@@ -1753,46 +1745,43 @@ public class ClassifierPanel extends JPanel implements
}
if ((fullClassifier instanceof Sourcable)
- && m_OutputSourceCode.isSelected()) {
- outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_OutBuffer_Text_FourtySecond"));
+ && m_OutputSourceCode.isSelected()) {
+ outBuff.append(Messages.getInstance().getString(
+ "ClassifierPanel_StartClassifier_OutBuffer_Text_FourtySecond"));
outBuff.append(Evaluation.wekaStaticWrapper(
- ((Sourcable) fullClassifier), m_SourceCodeClass.getText()));
+ ((Sourcable) fullClassifier), m_SourceCodeClass.getText()));
}
m_History.updateResult(name);
m_Log.logMessage(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Seventh")
- + cname);
+ "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Seventh")
+ + cname);
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentyThird"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentyThird"));
} catch (Exception ex) {
ex.printStackTrace();
m_Log.logMessage(ex.getMessage());
JOptionPane
- .showMessageDialog(
- ClassifierPanel.this,
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_JOptionPaneShowMessageDialog_Text_First")
- + ex.getMessage(),
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_JOptionPaneShowMessageDialog_Text_Second"),
- JOptionPane.ERROR_MESSAGE);
+ .showMessageDialog(
+ ClassifierPanel.this,
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_JOptionPaneShowMessageDialog_Text_First")
+ + ex.getMessage(),
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_JOptionPaneShowMessageDialog_Text_Second"),
+ JOptionPane.ERROR_MESSAGE);
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentyFourth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentyFourth"));
} finally {
try {
if (!saveVis && outputModel) {
@@ -1806,9 +1795,9 @@ public class ClassifierPanel extends JPanel implements
}
m_History.addObject(name, vv);
} else if (saveVis && predInstances != null
- && predInstances.numInstances() > 0) {
+ && predInstances.numInstances() > 0) {
if (predInstances.attribute(predInstances.classIndex())
- .isNumeric()) {
+ .isNumeric()) {
postProcessPlotInfo(plotSize);
}
m_CurrentVis = new VisualizePanel();
@@ -1848,13 +1837,13 @@ public class ClassifierPanel extends JPanel implements
if (isInterrupted()) {
m_Log.logMessage(Messages.getInstance().getString(
- "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Eighth")
- + cname);
+ "ClassifierPanel_StartClassifier_Log_LogMessage_Text_Eighth")
+ + cname);
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentyFourth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_StartClassifier_Log_StatusMessage_Text_TwentyFourth"));
}
synchronized (this) {
@@ -1883,7 +1872,7 @@ public class ClassifierPanel extends JPanel implements
* @return the generated row
*/
protected String predictionText(Classifier classifier, Instance inst,
- int instNum) throws Exception {
+ int instNum) throws Exception {
// > inst# actual predicted error probability distribution
@@ -1893,12 +1882,13 @@ public class ClassifierPanel extends JPanel implements
if (inst.classAttribute().isNominal()) {
// actual
- if (inst.classIsMissing())
+ if (inst.classIsMissing()) {
text.append(Utils.padLeft("?", 10) + " ");
- else
+ } else {
text.append(Utils.padLeft("" + ((int) inst.classValue() + 1) + ":"
- + inst.stringValue(inst.classAttribute()), 10)
- + " ");
+ + inst.stringValue(inst.classAttribute()), 10)
+ + " ");
+ }
// predicted
double[] probdist = null;
@@ -1906,49 +1896,55 @@ public class ClassifierPanel extends JPanel implements
if (inst.classAttribute().isNominal()) {
probdist = classifier.distributionForInstance(inst);
pred = Utils.maxIndex(probdist);
- if (probdist[(int) pred] <= 0.0)
+ if (probdist[(int) pred] <= 0.0) {
pred = Instance.missingValue();
+ }
} else {
pred = classifier.classifyInstance(inst);
}
- text.append(Utils.padLeft(
- (Instance.isMissingValue(pred) ? "?" : (((int) pred + 1) + ":" + inst
- .classAttribute().value((int) pred))), 10)
- + " ");
+ text.append(Utils.padLeft((Instance.isMissingValue(pred) ? "?"
+ : (((int) pred + 1) + ":" + inst.classAttribute().value((int) pred))),
+ 10)
+ + " ");
// error
- if (pred == inst.classValue())
+ if (pred == inst.classValue()) {
text.append(Utils.padLeft(" ", 6) + " ");
- else
+ } else {
text.append(Utils.padLeft("+", 6) + " ");
+ }
// prob dist
if (inst.classAttribute().type() == Attribute.NOMINAL) {
for (int i = 0; i < probdist.length; i++) {
- if (i == (int) pred)
+ if (i == (int) pred) {
text.append(" *");
- else
+ } else {
text.append(" ");
+ }
text.append(Utils.doubleToString(probdist[i], 5, 3));
}
}
} else {
// actual
- if (inst.classIsMissing())
+ if (inst.classIsMissing()) {
text.append(Utils.padLeft("?", 10) + " ");
- else
+ } else {
text.append(Utils.doubleToString(inst.classValue(), 10, 3) + " ");
+ }
// predicted
double pred = classifier.classifyInstance(inst);
- if (Instance.isMissingValue(pred))
+ if (Instance.isMissingValue(pred)) {
text.append(Utils.padLeft("?", 10) + " ");
- else
+ } else {
text.append(Utils.doubleToString(pred, 10, 3) + " ");
+ }
// err
- if (!inst.classIsMissing() && !Instance.isMissingValue(pred))
+ if (!inst.classIsMissing() && !Instance.isMissingValue(pred)) {
text.append(Utils.doubleToString(pred - inst.classValue(), 10, 3));
+ }
}
// additional Attributes
@@ -1957,10 +1953,11 @@ public class ClassifierPanel extends JPanel implements
boolean first = true;
for (int i = 0; i < inst.numAttributes() - 1; i++) {
if (m_OutputAdditionalAttributesRange.isInRange(i)) {
- if (!first)
+ if (!first) {
text.append(",");
- else
+ } else {
first = false;
+ }
text.append(inst.toString(i));
}
}
@@ -1984,7 +1981,7 @@ public class ClassifierPanel extends JPanel implements
JPopupMenu resultListMenu = new JPopupMenu();
JMenuItem visMainBuffer = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VisMainBuffer_JMenuItem_Text"));
+ "ClassifierPanel_Visualize_VisMainBuffer_JMenuItem_Text"));
if (selectedName != null) {
visMainBuffer.addActionListener(new ActionListener() {
@Override
@@ -1998,7 +1995,7 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.add(visMainBuffer);
JMenuItem visSepBuffer = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VisSepBuffer_JMenuItem_Text"));
+ "ClassifierPanel_Visualize_VisSepBuffer_JMenuItem_Text"));
if (selectedName != null) {
visSepBuffer.addActionListener(new ActionListener() {
@Override
@@ -2012,7 +2009,7 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.add(visSepBuffer);
JMenuItem saveOutput = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_SaveOutput_JMenuItem_Text"));
+ "ClassifierPanel_Visualize_SaveOutput_JMenuItem_Text"));
if (selectedName != null) {
saveOutput.addActionListener(new ActionListener() {
@Override
@@ -2026,7 +2023,7 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.add(saveOutput);
JMenuItem deleteOutput = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_DeleteOutput_JMenuItem_Text"));
+ "ClassifierPanel_Visualize_DeleteOutput_JMenuItem_Text"));
if (selectedName != null) {
deleteOutput.addActionListener(new ActionListener() {
@Override
@@ -2042,7 +2039,7 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.addSeparator();
JMenuItem loadModel = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_LoadModel_JMenuItem_Text"));
+ "ClassifierPanel_Visualize_LoadModel_JMenuItem_Text"));
loadModel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@@ -2090,7 +2087,7 @@ public class ClassifierPanel extends JPanel implements
final Instances trainHeader = temp_trainHeader;
JMenuItem saveModel = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_SaveModel_JMenuItem_Text"));
+ "ClassifierPanel_Visualize_SaveModel_JMenuItem_Text"));
if (classifier != null) {
saveModel.addActionListener(new ActionListener() {
@Override
@@ -2104,7 +2101,7 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.add(saveModel);
JMenuItem reEvaluate = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_ReEvaluate_JMenuItem_Text"));
+ "ClassifierPanel_Visualize_ReEvaluate_JMenuItem_Text"));
if (classifier != null && m_TestLoader != null) {
reEvaluate.addActionListener(new ActionListener() {
@Override
@@ -2120,7 +2117,7 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.addSeparator();
JMenuItem visErrors = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VisErrors_JMenuItem_Text"));
+ "ClassifierPanel_Visualize_VisErrors_JMenuItem_Text"));
if (vp != null) {
if ((vp.getXIndex() == 0) && (vp.getYIndex() == 1)) {
try {
@@ -2142,23 +2139,24 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.add(visErrors);
JMenuItem visGrph = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VisGrph_JMenuItem_Text_First"));
+ "ClassifierPanel_Visualize_VisGrph_JMenuItem_Text_First"));
if (grph != null) {
if (((Drawable) temp_classifier).graphType() == Drawable.TREE) {
visGrph.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String title;
- if (vp != null)
+ if (vp != null) {
title = vp.getName();
- else
+ } else {
title = selectedName;
+ }
visualizeTree(grph, title);
}
});
} else if (((Drawable) temp_classifier).graphType() == Drawable.BayesNet) {
visGrph.setText(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VisGrph_JMenuItem_Text_Second"));
+ "ClassifierPanel_Visualize_VisGrph_JMenuItem_Text_Second"));
visGrph.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
@@ -2171,15 +2169,16 @@ public class ClassifierPanel extends JPanel implements
th.start();
}
});
- } else
+ } else {
visGrph.setEnabled(false);
+ }
} else {
visGrph.setEnabled(false);
}
resultListMenu.add(visGrph);
JMenuItem visMargin = new JMenuItem(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VisMargin_JMenuItem_Text"));
+ "ClassifierPanel_Visualize_VisMargin_JMenuItem_Text"));
if (preds != null) {
visMargin.addActionListener(new ActionListener() {
@Override
@@ -2206,7 +2205,7 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.add(visMargin);
JMenu visThreshold = new JMenu(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VisThreshold_JMenu_Text"));
+ "ClassifierPanel_Visualize_VisThreshold_JMenu_Text"));
if (preds != null && classAtt != null) {
for (int i = 0; i < classAtt.numValues(); i++) {
JMenuItem clv = new JMenuItem(classAtt.value(i));
@@ -2220,24 +2219,25 @@ public class ClassifierPanel extends JPanel implements
// VisualizePanel vmc = new VisualizePanel();
ThresholdVisualizePanel vmc = new ThresholdVisualizePanel();
vmc.setROCString(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VMC_SetROCString_Text_First")
- + Utils.doubleToString(ThresholdCurve.getROCArea(result), 4)
- + Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VMC_SetROCString_Text_Second"));
+ "ClassifierPanel_Visualize_VMC_SetROCString_Text_First")
+ + Utils.doubleToString(ThresholdCurve.getROCArea(result), 4)
+ + Messages.getInstance().getString(
+ "ClassifierPanel_Visualize_VMC_SetROCString_Text_Second"));
vmc.setLog(m_Log);
vmc.setName(result.relationName()
- + Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VMC_SetName_Text_First")
- + classAtt.value(classValue)
- + Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VMC_SetName_Text_Second"));
+ + Messages.getInstance().getString(
+ "ClassifierPanel_Visualize_VMC_SetName_Text_First")
+ + classAtt.value(classValue)
+ + Messages.getInstance().getString(
+ "ClassifierPanel_Visualize_VMC_SetName_Text_Second"));
PlotData2D tempd = new PlotData2D(result);
tempd.setPlotName(result.relationName());
tempd.addInstanceNumberAttribute();
// specify which points are connected
boolean[] cp = new boolean[result.numInstances()];
- for (int n = 1; n < cp.length; n++)
+ for (int n = 1; n < cp.length; n++) {
cp[n] = true;
+ }
tempd.setConnectPoints(cp);
// add plot
vmc.addPlot(tempd);
@@ -2255,7 +2255,7 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.add(visThreshold);
JMenu visCostBenefit = new JMenu(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VisCostBenefit_JMenu_Text"));
+ "ClassifierPanel_Visualize_VisCostBenefit_JMenu_Text"));
if ((preds != null) && (classAtt != null) && (classAtt.isNominal())) {
for (int i = 0; i < classAtt.numValues(); i++) {
JMenuItem clv = new JMenuItem(classAtt.value(i));
@@ -2288,8 +2288,9 @@ public class ClassifierPanel extends JPanel implements
tempd.m_alwaysDisplayPointsOfThisSize = 10;
// specify which points are connected
boolean[] cp = new boolean[result.numInstances()];
- for (int n = 1; n < cp.length; n++)
+ for (int n = 1; n < cp.length; n++) {
cp[n] = true;
+ }
tempd.setConnectPoints(cp);
String windowTitle = "";
@@ -2297,14 +2298,14 @@ public class ClassifierPanel extends JPanel implements
String cname = classifier.getClass().getName();
if (cname.startsWith("weka.classifiers.")) {
windowTitle = ""
- + cname.substring("weka.classifiers.".length()) + " ";
+ + cname.substring("weka.classifiers.".length()) + " ";
}
}
windowTitle += Messages.getInstance().getString(
- "ClassifierPanel_Visualize_WindowTitle_Text_First")
- + classAttToUse.value(0)
- + Messages.getInstance().getString(
- "ClassifierPanel_Visualize_WindowTitle_Text_Second");
+ "ClassifierPanel_Visualize_WindowTitle_Text_First")
+ + classAttToUse.value(0)
+ + Messages.getInstance().getString(
+ "ClassifierPanel_Visualize_WindowTitle_Text_Second");
// add plot
cbAnalysis.setCurveData(tempd, classAttToUse);
@@ -2322,7 +2323,7 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.add(visCostBenefit);
JMenu visCost = new JMenu(Messages.getInstance().getString(
- "ClassifierPanel_VisCost_JMenu_Text"));
+ "ClassifierPanel_VisCost_JMenu_Text"));
if (preds != null && classAtt != null) {
for (int i = 0; i < classAtt.numValues(); i++) {
JMenuItem clv = new JMenuItem(classAtt.value(i));
@@ -2336,11 +2337,11 @@ public class ClassifierPanel extends JPanel implements
VisualizePanel vmc = new VisualizePanel();
vmc.setLog(m_Log);
vmc.setName(result.relationName()
- + Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VMC_SetName_Text_Third")
- + classAtt.value(classValue)
- + Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VMC_SetName_Text_Fourth"));
+ + Messages.getInstance().getString(
+ "ClassifierPanel_Visualize_VMC_SetName_Text_Third")
+ + classAtt.value(classValue)
+ + Messages.getInstance().getString(
+ "ClassifierPanel_Visualize_VMC_SetName_Text_Fourth"));
PlotData2D tempd = new PlotData2D(result);
tempd.m_displayAllPoints = true;
tempd.setPlotName(result.relationName());
@@ -2365,18 +2366,19 @@ public class ClassifierPanel extends JPanel implements
resultListMenu.add(visCost);
JMenu visPlugins = new JMenu(Messages.getInstance().getString(
- "ClassifierPanel_Visualize_VisPlugins_JMenu_Text"));
+ "ClassifierPanel_Visualize_VisPlugins_JMenu_Text"));
Vector pluginsVector = GenericObjectEditor
- .getClassnames(VisualizePlugin.class.getName());
+ .getClassnames(VisualizePlugin.class.getName());
boolean availablePlugins = false;
for (int i = 0; i < pluginsVector.size(); i++) {
String className = (String) (pluginsVector.elementAt(i));
try {
VisualizePlugin plugin = (VisualizePlugin) Class.forName(className)
- .newInstance();
- if (plugin == null)
+ .newInstance();
+ if (plugin == null) {
continue;
+ }
availablePlugins = true;
JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem(preds, classAtt);
Version version = new Version();
@@ -2407,17 +2409,18 @@ public class ClassifierPanel extends JPanel implements
// errors
pluginsVector = GenericObjectEditor
- .getClassnames(ErrorVisualizePlugin.class.getName());
+ .getClassnames(ErrorVisualizePlugin.class.getName());
for (int i = 0; i < pluginsVector.size(); i++) {
String className = (String) (pluginsVector.elementAt(i));
try {
ErrorVisualizePlugin plugin = (ErrorVisualizePlugin) Class.forName(
- className).newInstance();
- if (plugin == null)
+ className).newInstance();
+ if (plugin == null) {
continue;
+ }
availablePlugins = true;
JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem(vp
- .getInstances());
+ .getInstances());
Version version = new Version();
if (pluginMenuItem != null) {
/*
@@ -2439,17 +2442,18 @@ public class ClassifierPanel extends JPanel implements
// trees
if (((Drawable) temp_classifier).graphType() == Drawable.TREE) {
pluginsVector = GenericObjectEditor
- .getClassnames(TreeVisualizePlugin.class.getName());
+ .getClassnames(TreeVisualizePlugin.class.getName());
for (int i = 0; i < pluginsVector.size(); i++) {
String className = (String) (pluginsVector.elementAt(i));
try {
TreeVisualizePlugin plugin = (TreeVisualizePlugin) Class.forName(
- className).newInstance();
- if (plugin == null)
+ className).newInstance();
+ if (plugin == null) {
continue;
+ }
availablePlugins = true;
JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem(grph,
- selectedName);
+ selectedName);
Version version = new Version();
if (pluginMenuItem != null) {
/*
@@ -2470,17 +2474,18 @@ public class ClassifierPanel extends JPanel implements
// graphs
else {
pluginsVector = GenericObjectEditor
- .getClassnames(GraphVisualizePlugin.class.getName());
+ .getClassnames(GraphVisualizePlugin.class.getName());
for (int i = 0; i < pluginsVector.size(); i++) {
String className = (String) (pluginsVector.elementAt(i));
try {
GraphVisualizePlugin plugin = (GraphVisualizePlugin) Class.forName(
- className).newInstance();
- if (plugin == null)
+ className).newInstance();
+ if (plugin == null) {
continue;
+ }
availablePlugins = true;
JMenuItem pluginMenuItem = plugin.getVisualizeMenuItem(grph,
- selectedName);
+ selectedName);
Version version = new Version();
if (pluginMenuItem != null) {
/*
@@ -2500,8 +2505,9 @@ public class ClassifierPanel extends JPanel implements
}
}
- if (availablePlugins)
+ if (availablePlugins) {
resultListMenu.add(visPlugins);
+ }
resultListMenu.show(m_History.getList(), x, y);
}
@@ -2515,7 +2521,7 @@ public class ClassifierPanel extends JPanel implements
*/
protected void visualizeTree(String dottyString, String treeName) {
final javax.swing.JFrame jf = new javax.swing.JFrame(Messages.getInstance()
- .getString("ClassifierPanel_VisualizeTree_JF_JFrame_Text") + treeName);
+ .getString("ClassifierPanel_VisualizeTree_JF_JFrame_Text") + treeName);
jf.setSize(500, 400);
jf.getContentPane().setLayout(new BorderLayout());
TreeVisualizer tv = new TreeVisualizer(null, dottyString, new PlaceNode2());
@@ -2540,8 +2546,8 @@ public class ClassifierPanel extends JPanel implements
*/
protected void visualizeBayesNet(String XMLBIF, String graphName) {
final javax.swing.JFrame jf = new javax.swing.JFrame(Messages.getInstance()
- .getString("ClassifierPanel_VisualizeBayesNet_JF_JFrame_Text")
- + graphName);
+ .getString("ClassifierPanel_VisualizeBayesNet_JF_JFrame_Text")
+ + graphName);
jf.setSize(500, 400);
jf.getContentPane().setLayout(new BorderLayout());
GraphVisualizer gv = new GraphVisualizer();
@@ -2549,7 +2555,7 @@ public class ClassifierPanel extends JPanel implements
gv.readBIF(XMLBIF);
} catch (BIFFormatException be) {
System.err.println(Messages.getInstance().getString(
- "ClassifierPanel_VisualizeBayesNet_Error_Text"));
+ "ClassifierPanel_VisualizeBayesNet_Error_Text"));
be.printStackTrace();
}
gv.layoutGraph();
@@ -2576,9 +2582,9 @@ public class ClassifierPanel extends JPanel implements
if (sp != null) {
String plotName = sp.getName();
final javax.swing.JFrame jf = new javax.swing.JFrame(Messages
- .getInstance().getString(
- "ClassifierPanel_VisualizeClassifierErrors_JF_JFrame_Text")
- + plotName);
+ .getInstance().getString(
+ "ClassifierPanel_VisualizeClassifierErrors_JF_JFrame_Text")
+ + plotName);
jf.setSize(600, 400);
jf.getContentPane().setLayout(new BorderLayout());
@@ -2600,10 +2606,10 @@ public class ClassifierPanel extends JPanel implements
* @param cb the CostBenefitAnalysis panel to pop up
*/
protected void visualizeCostBenefitAnalysis(CostBenefitAnalysis cb,
- String classifierAndRelationName) {
+ String classifierAndRelationName) {
if (cb != null) {
String windowTitle = Messages.getInstance().getString(
- "ClassifierPanel_VisualizeCostBenefitAnalysis_WindowTitle_Text");
+ "ClassifierPanel_VisualizeCostBenefitAnalysis_WindowTitle_Text");
if (classifierAndRelationName != null) {
windowTitle += "- " + classifierAndRelationName;
}
@@ -2633,7 +2639,7 @@ public class ClassifierPanel extends JPanel implements
if (sb != null) {
if (m_SaveOut.save(sb)) {
m_Log.logMessage(Messages.getInstance().getString(
- "ClassifierPanel_SaveBuffer_Log_LogMessage_Text"));
+ "ClassifierPanel_SaveBuffer_Log_LogMessage_Text"));
}
}
}
@@ -2659,7 +2665,7 @@ public class ClassifierPanel extends JPanel implements
* @param trainHeader the header of the training instances
*/
protected void saveClassifier(String name, Classifier classifier,
- Instances trainHeader) {
+ Instances trainHeader) {
File sFile = null;
boolean saveOK = true;
@@ -2671,10 +2677,10 @@ public class ClassifierPanel extends JPanel implements
sFile = m_FileChooser.getSelectedFile();
if (!sFile.getName().toLowerCase().endsWith(MODEL_FILE_EXTENSION)) {
sFile = new File(sFile.getParent(), sFile.getName()
- + MODEL_FILE_EXTENSION);
+ + MODEL_FILE_EXTENSION);
}
m_Log.statusMessage(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_Log_StatusMessage_Text"));
+ "ClassifierPanel_SaveClassifier_Log_StatusMessage_Text"));
try {
OutputStream os = new FileOutputStream(sFile);
@@ -2684,34 +2690,36 @@ public class ClassifierPanel extends JPanel implements
ObjectOutputStream objectOutputStream = new ObjectOutputStream(os);
objectOutputStream.writeObject(classifier);
trainHeader = trainHeader.stringFreeStructure();
- if (trainHeader != null)
+ if (trainHeader != null) {
objectOutputStream.writeObject(trainHeader);
+ }
objectOutputStream.flush();
objectOutputStream.close();
} catch (Exception e) {
JOptionPane
- .showMessageDialog(
- null,
- e,
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_SaveClassifier_JOptionPaneShowMessageDialog_Text_First"),
- JOptionPane.ERROR_MESSAGE);
+ .showMessageDialog(
+ null,
+ e,
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_SaveClassifier_JOptionPaneShowMessageDialog_Text_First"),
+ JOptionPane.ERROR_MESSAGE);
saveOK = false;
}
- if (saveOK)
+ if (saveOK) {
m_Log.logMessage(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_First")
- + name
- + Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_Second")
- + sFile.getName()
- + Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_Third"));
+ "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_First")
+ + name
+ + Messages.getInstance().getString(
+ "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_Second")
+ + sFile.getName()
+ + Messages.getInstance().getString(
+ "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_Third"));
+ }
m_Log.statusMessage(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_JOptionPaneShowMessageDialog_Text"));
+ "ClassifierPanel_SaveClassifier_JOptionPaneShowMessageDialog_Text"));
}
}
@@ -2729,7 +2737,7 @@ public class ClassifierPanel extends JPanel implements
Instances trainHeader = null;
m_Log.statusMessage(Messages.getInstance().getString(
- "ClassifierPanel_LoadClassifier_Log_StatusMessage_Text_First"));
+ "ClassifierPanel_LoadClassifier_Log_StatusMessage_Text_First"));
try {
InputStream is = new FileInputStream(selected);
@@ -2743,7 +2751,7 @@ public class ClassifierPanel extends JPanel implements
*/
} else {
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_LoadClassifier_Exception_Text"));
+ "ClassifierPanel_LoadClassifier_Exception_Text"));
}
} else {
if (selected.getName().endsWith(".gz")) {
@@ -2760,45 +2768,46 @@ public class ClassifierPanel extends JPanel implements
} catch (Exception e) {
JOptionPane
- .showMessageDialog(
- null,
- e,
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_LoadClassifier_JOptionPaneShowMessageDialog_Text"),
- JOptionPane.ERROR_MESSAGE);
+ .showMessageDialog(
+ null,
+ e,
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_LoadClassifier_JOptionPaneShowMessageDialog_Text"),
+ JOptionPane.ERROR_MESSAGE);
}
m_Log.statusMessage(Messages.getInstance().getString(
- "ClassifierPanel_LoadClassifier_Log_StatusMessage_Text_Second"));
+ "ClassifierPanel_LoadClassifier_Log_StatusMessage_Text_Second"));
if (classifier != null) {
m_Log.logMessage(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_Fourth")
- + selected.getName()
- + Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_Fifth"));
+ "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_Fourth")
+ + selected.getName()
+ + Messages.getInstance().getString(
+ "ClassifierPanel_SaveClassifier_Log_LogMessage_Text_Fifth"));
String name = (new SimpleDateFormat("HH:mm:ss - ")).format(new Date());
String cname = classifier.getClass().getName();
- if (cname.startsWith("weka.classifiers."))
+ if (cname.startsWith("weka.classifiers.")) {
cname = cname.substring("weka.classifiers.".length());
+ }
name += cname
- + Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_Name_Text_First")
- + selected.getName()
- + Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_Name_Text_Second");
+ + Messages.getInstance().getString(
+ "ClassifierPanel_SaveClassifier_Name_Text_First")
+ + selected.getName()
+ + Messages.getInstance().getString(
+ "ClassifierPanel_SaveClassifier_Name_Text_Second");
StringBuffer outBuff = new StringBuffer();
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_First"));
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_First"));
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Second")
- + selected.getName() + "\n");
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Second")
+ + selected.getName() + "\n");
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Fourth")
- + classifier.getClass().getName());
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Fourth")
+ + classifier.getClass().getName());
if (classifier instanceof OptionHandler) {
String[] o = ((OptionHandler) classifier).getOptions();
outBuff.append(" " + Utils.joinOptions(o));
@@ -2806,35 +2815,36 @@ public class ClassifierPanel extends JPanel implements
outBuff.append("\n");
if (trainHeader != null) {
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Fifth")
- + trainHeader.relationName() + '\n');
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Fifth")
+ + trainHeader.relationName() + '\n');
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Seventh")
- + trainHeader.numAttributes() + '\n');
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Seventh")
+ + trainHeader.numAttributes() + '\n');
if (trainHeader.numAttributes() < 100) {
for (int i = 0; i < trainHeader.numAttributes(); i++) {
outBuff.append(" " + trainHeader.attribute(i).name()
- + '\n');
+ + '\n');
}
} else {
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Nineth"));
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Nineth"));
}
} else {
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Tenth"));
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Tenth"));
}
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Eleventh"));
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Eleventh"));
outBuff.append(classifier.toString() + "\n");
m_History.addResult(name, outBuff);
m_History.setSingle(name);
FastVector vv = new FastVector();
vv.addElement(classifier);
- if (trainHeader != null)
+ if (trainHeader != null) {
vv.addElement(trainHeader);
+ }
// allow visualization of graphable classifiers
String grph = null;
if (classifier instanceof Drawable) {
@@ -2843,8 +2853,9 @@ public class ClassifierPanel extends JPanel implements
} catch (Exception ex) {
}
}
- if (grph != null)
+ if (grph != null) {
vv.addElement(grph);
+ }
m_History.addObject(name, vv);
}
@@ -2860,7 +2871,7 @@ public class ClassifierPanel extends JPanel implements
* @param trainHeader the header of the training set
*/
protected void reevaluateModel(final String name,
- final Classifier classifier, final Instances trainHeader) {
+ final Classifier classifier, final Instances trainHeader) {
if (m_RunThread == null) {
synchronized (this) {
@@ -2872,7 +2883,7 @@ public class ClassifierPanel extends JPanel implements
public void run() {
// Copy the current state of things
m_Log.statusMessage(Messages.getInstance().getString(
- "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_First"));
+ "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_First"));
StringBuffer outBuff = m_History.getNamedBuffer(name);
DataSource source = null;
@@ -2885,7 +2896,7 @@ public class ClassifierPanel extends JPanel implements
CostMatrix costMatrix = null;
if (m_EvalWRTCostsBut.isSelected()) {
costMatrix = new CostMatrix(
- (CostMatrix) m_CostMatrixEditor.getValue());
+ (CostMatrix) m_CostMatrixEditor.getValue());
}
boolean outputConfusion = m_OutputConfusionBut.isSelected();
boolean outputPerClass = m_OutputPerClassBut.isSelected();
@@ -2893,7 +2904,7 @@ public class ClassifierPanel extends JPanel implements
boolean outputEntropy = m_OutputEntropyBut.isSelected();
boolean saveVis = m_StorePredictionsBut.isSelected();
boolean outputPredictionsText = m_OutputPredictionsTextBut
- .isSelected();
+ .isSelected();
String grph = null;
Evaluation eval = null;
@@ -2908,61 +2919,49 @@ public class ClassifierPanel extends JPanel implements
// Check the test instance compatibility
if (source == null) {
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_ReEvaluateModel_Exception_Text_First"));
+ "ClassifierPanel_ReEvaluateModel_Exception_Text_First"));
}
if (trainHeader != null) {
- if (trainHeader.classIndex() > userTestStructure.numAttributes() - 1)
+ if (trainHeader.classIndex() > userTestStructure.numAttributes() - 1) {
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_ReEvaluateModel_Exception_Text_Second"));
+ "ClassifierPanel_ReEvaluateModel_Exception_Text_Second"));
+ }
userTestStructure.setClassIndex(trainHeader.classIndex());
if (!trainHeader.equalHeaders(userTestStructure)) {
throw new Exception(Messages.getInstance().getString(
- "ClassifierPanel_ReEvaluateModel_Exception_Text_Third"));
+ "ClassifierPanel_ReEvaluateModel_Exception_Text_Third"));
}
} else {
if (classifier instanceof PMMLClassifier) {
// set the class based on information in the mining schema
Instances miningSchemaStructure = ((PMMLClassifier) classifier)
- .getMiningSchema().getMiningSchemaAsInstances();
+ .getMiningSchema().getMiningSchemaAsInstances();
String className = miningSchemaStructure.classAttribute()
- .name();
+ .name();
Attribute classMatch = userTestStructure.attribute(className);
if (classMatch == null) {
- throw new Exception(
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Exception_Text_Fourth")
- + className
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Exception_Text_Fifth"));
+ throw new Exception(Messages.getInstance().getString(
+ "ClassifierPanel_ReEvaluateModel_Exception_Text_Fourth")
+ + className
+ + Messages.getInstance().getString(
+ "ClassifierPanel_ReEvaluateModel_Exception_Text_Fifth"));
}
userTestStructure.setClass(classMatch);
} else {
userTestStructure.setClassIndex(userTestStructure
- .numAttributes() - 1);
+ .numAttributes() - 1);
}
}
if (m_Log instanceof TaskLogger) {
((TaskLogger) m_Log).taskStarted();
}
- m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Second"));
- m_Log
- .logMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_First")
- + name
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_Second"));
+ m_Log.statusMessage(Messages.getInstance().getString(
+ "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Second"));
+ m_Log.logMessage(Messages.getInstance().getString(
+ "ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_First")
+ + name
+ + Messages.getInstance().getString(
+ "ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_Second"));
eval = new Evaluation(userTestStructure, costMatrix);
eval.useNoPriors();
@@ -2974,44 +2973,42 @@ public class ClassifierPanel extends JPanel implements
}
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Twelveth"));
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Twelveth"));
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Thirteenth"));
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Thirteenth"));
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Fourteenth")
- + userTestStructure.relationName() + '\n');
- if (incrementalLoader)
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Fourteenth")
+ + userTestStructure.relationName() + '\n');
+ if (incrementalLoader) {
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Sixteenth"));
- else
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Sixteenth"));
+ } else {
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Seventeenth")
- + source.getDataSet().numInstances() + "\n");
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Seventeenth")
+ + source.getDataSet().numInstances() + "\n");
+ }
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_Nineteenth")
- + userTestStructure.numAttributes() + "\n\n");
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_Nineteenth")
+ + userTestStructure.numAttributes() + "\n\n");
if (trainHeader == null
- && !(classifier instanceof weka.classifiers.pmml.consumer.PMMLClassifier)) {
+ && !(classifier instanceof weka.classifiers.pmml.consumer.PMMLClassifier)) {
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_TwentyFirst"));
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_TwentyFirst"));
}
if (outputPredictionsText) {
- outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_TwentySecond"));
outBuff.append(Messages.getInstance().getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_TwentyThird"));
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_TwentySecond"));
+ outBuff.append(Messages.getInstance().getString(
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_TwentyThird"));
if (userTestStructure.classAttribute().isNominal()) {
outBuff
- .append(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_SaveClassifier_OutBuffer_Text_TwentyFourth"));
+ .append(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_SaveClassifier_OutBuffer_Text_TwentyFourth"));
}
outBuff.append("\n");
}
@@ -3021,21 +3018,21 @@ public class ClassifierPanel extends JPanel implements
while (source.hasMoreElements(userTestStructure)) {
instance = source.nextElement(userTestStructure);
processClassifierPrediction(instance, classifier, eval,
- predInstances, plotShape, plotSize);
+ predInstances, plotShape, plotSize);
if (outputPredictionsText) {
outBuff.append(predictionText(classifier, instance, jj + 1));
}
if ((++jj % 100) == 0) {
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Third")
- + jj
- + Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Fourth"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Third")
+ + jj
+ + Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Fourth"));
}
}
@@ -3060,41 +3057,35 @@ public class ClassifierPanel extends JPanel implements
m_History.updateResult(name);
m_Log.logMessage(Messages.getInstance().getString(
- "ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_Third"));
- m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Fifth"));
+ "ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_Third"));
+ m_Log.statusMessage(Messages.getInstance().getString(
+ "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Fifth"));
} catch (Exception ex) {
ex.printStackTrace();
m_Log.logMessage(ex.getMessage());
- m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Sixth"));
+ m_Log.statusMessage(Messages.getInstance().getString(
+ "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Sixth"));
ex.printStackTrace();
m_Log.logMessage(ex.getMessage());
JOptionPane
- .showMessageDialog(
- ClassifierPanel.this,
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_JOptionPaneShowMessageDialog_Text_First")
- + ex.getMessage(),
- Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_JOptionPaneShowMessageDialog_Text_Second"),
- JOptionPane.ERROR_MESSAGE);
+ .showMessageDialog(
+ ClassifierPanel.this,
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_ReEvaluateModel_JOptionPaneShowMessageDialog_Text_First")
+ + ex.getMessage(),
+ Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_ReEvaluateModel_JOptionPaneShowMessageDialog_Text_Second"),
+ JOptionPane.ERROR_MESSAGE);
m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Seventh"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Seventh"));
} finally {
try {
if (classifier instanceof PMMLClassifier) {
@@ -3107,18 +3098,18 @@ public class ClassifierPanel extends JPanel implements
if (predInstances != null && predInstances.numInstances() > 0) {
if (predInstances.attribute(predInstances.classIndex())
- .isNumeric()) {
+ .isNumeric()) {
postProcessPlotInfo(plotSize);
}
m_CurrentVis = new VisualizePanel();
m_CurrentVis.setName(name + " ("
- + userTestStructure.relationName() + ")");
+ + userTestStructure.relationName() + ")");
m_CurrentVis.setLog(m_Log);
PlotData2D tempd = new PlotData2D(predInstances);
tempd.setShapeSize(plotSize);
tempd.setShapeType(plotShape);
tempd.setPlotName(name + " ("
- + userTestStructure.relationName() + ")");
+ + userTestStructure.relationName() + ")");
// tempd.addInstanceNumberAttribute();
m_CurrentVis.addPlot(tempd);
@@ -3135,8 +3126,9 @@ public class ClassifierPanel extends JPanel implements
if (saveVis) {
FastVector vv = new FastVector();
vv.addElement(classifier);
- if (trainHeader != null)
+ if (trainHeader != null) {
vv.addElement(trainHeader);
+ }
vv.addElement(m_CurrentVis);
if (grph != null) {
vv.addElement(grph);
@@ -3149,8 +3141,9 @@ public class ClassifierPanel extends JPanel implements
} else {
FastVector vv = new FastVector();
vv.addElement(classifier);
- if (trainHeader != null)
+ if (trainHeader != null) {
vv.addElement(trainHeader);
+ }
m_History.addObject(name, vv);
}
}
@@ -3158,16 +3151,13 @@ public class ClassifierPanel extends JPanel implements
ex.printStackTrace();
}
if (isInterrupted()) {
+ m_Log.logMessage(Messages.getInstance().getString(
+ "ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_Fourth"));
m_Log
- .logMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_Fourth"));
- m_Log
- .statusMessage(Messages
- .getInstance()
- .getString(
- "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Seventh"));
+ .statusMessage(Messages
+ .getInstance()
+ .getString(
+ "ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Seventh"));
}
synchronized (this) {
@@ -3202,10 +3192,11 @@ public class ClassifierPanel extends JPanel implements
return;
}
- if (!ExplorerDefaults.getInitGenericObjectEditorFilter())
+ if (!ExplorerDefaults.getInitGenericObjectEditorFilter()) {
tempInst = new Instances(m_Instances, 0);
- else
+ } else {
tempInst = new Instances(m_Instances);
+ }
tempInst.setClassIndex(m_ClassCombo.getSelectedIndex());
try {
@@ -3223,12 +3214,12 @@ public class ClassifierPanel extends JPanel implements
Classifier classifier = (Classifier) m_ClassifierEditor.getValue();
Capabilities currentSchemeCapabilities = null;
if (classifier != null && currentFilter != null
- && (classifier instanceof CapabilitiesHandler)) {
+ && (classifier instanceof CapabilitiesHandler)) {
currentSchemeCapabilities = ((CapabilitiesHandler) classifier)
- .getCapabilities();
+ .getCapabilities();
if (!currentSchemeCapabilities.supportsMaybe(currentFilter)
- && !currentSchemeCapabilities.supports(currentFilter)) {
+ && !currentSchemeCapabilities.supports(currentFilter)) {
m_StartBut.setEnabled(false);
}
}
@@ -3241,10 +3232,11 @@ public class ClassifierPanel extends JPanel implements
*/
@Override
public void capabilitiesFilterChanged(CapabilitiesFilterChangeEvent e) {
- if (e.getFilter() == null)
+ if (e.getFilter() == null) {
updateCapabilitiesFilter(null);
- else
+ } else {
updateCapabilitiesFilter((Capabilities) e.getFilter().clone());
+ }
}
/**
@@ -3286,7 +3278,7 @@ public class ClassifierPanel extends JPanel implements
@Override
public String getTabTitleToolTip() {
return Messages.getInstance().getString(
- "ClassifierPanel_GetTabTitleToolTip_Text");
+ "ClassifierPanel_GetTabTitleToolTip_Text");
}
/**
@@ -3298,7 +3290,7 @@ public class ClassifierPanel extends JPanel implements
try {
final javax.swing.JFrame jf = new javax.swing.JFrame(Messages
- .getInstance().getString("ClassifierPanel_Main_JFrame_Text"));
+ .getInstance().getString("ClassifierPanel_Main_JFrame_Text"));
jf.getContentPane().setLayout(new BorderLayout());
final ClassifierPanel sp = new ClassifierPanel();
jf.getContentPane().add(sp, BorderLayout.CENTER);
@@ -3317,10 +3309,10 @@ public class ClassifierPanel extends JPanel implements
jf.setVisible(true);
if (args.length == 1) {
System.err.println(Messages.getInstance().getString(
- "ClassifierPanel_Main_Error_Text")
- + args[0]);
+ "ClassifierPanel_Main_Error_Text")
+ + args[0]);
java.io.Reader r = new java.io.BufferedReader(new java.io.FileReader(
- args[0]));
+ args[0]));
Instances i = new Instances(r);
sp.setInstances(i);
}
diff --git a/src/main/java/weka/gui/explorer/Explorer.java b/src/main/java/weka/gui/explorer/Explorer.java
index 291858b..2c30d81 100644
--- a/src/main/java/weka/gui/explorer/Explorer.java
+++ b/src/main/java/weka/gui/explorer/Explorer.java
@@ -22,17 +22,6 @@
package weka.gui.explorer;
-import weka.core.Capabilities;
-import weka.core.Copyright;
-import weka.core.Instances;
-import weka.core.Memory;
-import weka.core.converters.AbstractFileLoader;
-import weka.core.converters.ConverterUtils;
-import weka.gui.LogPanel;
-import weka.gui.Logger;
-import weka.gui.LookAndFeel;
-import weka.gui.WekaTaskMonitor;
-
import java.awt.BorderLayout;
import java.awt.Image;
import java.awt.Toolkit;
@@ -53,15 +42,25 @@ import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeEvent;
-/**
- * The main class for the Weka explorer. Lets the user create,
- * open, save, configure, datasets, and perform ML analysis.
- *
+import weka.core.Capabilities;
+import weka.core.Copyright;
+import weka.core.Instances;
+import weka.core.Memory;
+import weka.core.converters.AbstractFileLoader;
+import weka.core.converters.ConverterUtils;
+import weka.gui.LogPanel;
+import weka.gui.Logger;
+import weka.gui.LookAndFeel;
+import weka.gui.WekaTaskMonitor;
+
+/**
+ * The main class for the Weka explorer. Lets the user create, open, save,
+ * configure, datasets, and perform ML analysis.
+ *
* @author Len Trigg (trigg at cs.waikato.ac.nz)
- * @version $Revision: 9495 $
+ * @version $Revision: 10438 $
*/
-public class Explorer
- extends JPanel {
+public class Explorer extends JPanel {
/** for serialization */
private static final long serialVersionUID = -7674003708867909578L;
@@ -70,49 +69,48 @@ public class Explorer
* Interface for classes that listen for filter changes.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9495 $
+ * @version $Revision: 10438 $
*/
- public static interface CapabilitiesFilterChangeListener
- extends EventListener {
-
+ public static interface CapabilitiesFilterChangeListener extends
+ EventListener {
+
/**
* method gets called in case of a change event
*
- * @param e the associated change event
+ * @param e the associated change event
*/
public void capabilitiesFilterChanged(CapabilitiesFilterChangeEvent e);
}
/**
- * This event can be fired in case the capabilities filter got changed
+ * This event can be fired in case the capabilities filter got changed
*
* @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9495 $
+ * @version $Revision: 10438 $
*/
- public static class CapabilitiesFilterChangeEvent
- extends ChangeEvent {
+ public static class CapabilitiesFilterChangeEvent extends ChangeEvent {
/** for serialization */
private static final long serialVersionUID = 1194260517270385559L;
-
+
/** the capabilities filter */
protected Capabilities m_Filter;
-
+
/**
* Constructs a GOECapabilitiesFilterChangeEvent object.
*
- * @param source the Object that is the source of the event
- * @param filter the responsible capabilities filter
+ * @param source the Object that is the source of the event
+ * @param filter the responsible capabilities filter
*/
public CapabilitiesFilterChangeEvent(Object source, Capabilities filter) {
super(source);
m_Filter = filter;
}
-
+
/**
* returns the associated Capabilities filter
*
- * @return the filter
+ * @return the filter
*/
public Capabilities getFilter() {
return m_Filter;
@@ -123,7 +121,7 @@ public class Explorer
* A common interface for panels to be displayed in the Explorer
*
* @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9495 $
+ * @version $Revision: 10438 $
*/
public static interface ExplorerPanel {
@@ -131,31 +129,31 @@ public class Explorer
* Sets the Explorer to use as parent frame (used for sending notifications
* about changes in the data)
*
- * @param parent the parent frame
+ * @param parent the parent frame
*/
public void setExplorer(Explorer parent);
-
+
/**
* returns the parent Explorer frame
*
- * @return the parent
+ * @return the parent
*/
public Explorer getExplorer();
-
+
/**
* Tells the panel to use a new set of instances.
- *
+ *
* @param inst a set of Instances
*/
public void setInstances(Instances inst);
-
+
/**
* Returns the title for the tab in the Explorer
*
* @return the title of this tab
*/
public String getTabTitle();
-
+
/**
* Returns the tooltip for the tab in the Explorer
*
@@ -168,13 +166,13 @@ public class Explorer
* A common interface for panels in the explorer that can handle logs
*
* @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9495 $
+ * @version $Revision: 10438 $
*/
public static interface LogHandler {
-
+
/**
* Sets the Logger to receive informational messages
- *
+ *
* @param newLog the Logger that will now get info messages
*/
public void setLog(Logger newLog);
@@ -182,65 +180,75 @@ public class Explorer
/** The panel for preprocessing instances */
protected PreprocessPanel m_PreprocessPanel = new PreprocessPanel();
-
+
/** Contains all the additional panels apart from the pre-processing panel */
protected Vector<ExplorerPanel> m_Panels = new Vector<ExplorerPanel>();
-
+
/** The tabbed pane that controls which sub-pane we are working with */
protected JTabbedPane m_TabbedPane = new JTabbedPane();
-
+
/** The panel for log and status messages */
protected LogPanel m_LogPanel = new LogPanel(new WekaTaskMonitor());
-
+
/** the listeners that listen to filter changes */
protected HashSet<CapabilitiesFilterChangeListener> m_CapabilitiesFilterChangeListeners = new HashSet<CapabilitiesFilterChangeListener>();
-
+
/**
* Creates the experiment environment gui with no initial experiment
*/
public Explorer() {
-
- String date = (new SimpleDateFormat("EEEE, d MMMM yyyy")).format(new Date());
- m_LogPanel.logMessage(Messages.getInstance().getString("Explorer_LogPanel_LogMessage_Text_First"));
- m_LogPanel.logMessage(Messages.getInstance().getString("Explorer_LogPanel_LogMessage_Text_Second") + Copyright.getFromYear() + Messages.getInstance().getString("Explorer_LogPanel_LogMessage_Text_Third")
- + Copyright.getToYear()
- + " " + Copyright.getOwner() + ", " + Copyright.getAddress());
- m_LogPanel.logMessage(Messages.getInstance().getString("Explorer_LogPanel_LogMessage_Text_Fourth") + Copyright.getURL());
- m_LogPanel.logMessage(Messages.getInstance().getString("Explorer_LogPanel_LogMessage_Text_Fifth") + date);
- m_LogPanel.statusMessage(Messages.getInstance().getString("Explorer_LogPanel_StatusMessage_Text_First"));
+
+ String date = (new SimpleDateFormat("EEEE, d MMMM yyyy"))
+ .format(new Date());
+ m_LogPanel.logMessage(Messages.getInstance().getString(
+ "Explorer_LogPanel_LogMessage_Text_First"));
+ m_LogPanel.logMessage(Messages.getInstance().getString(
+ "Explorer_LogPanel_LogMessage_Text_Second")
+ + Copyright.getFromYear()
+ + Messages.getInstance().getString(
+ "Explorer_LogPanel_LogMessage_Text_Third")
+ + Copyright.getToYear()
+ + " " + Copyright.getOwner() + ", " + Copyright.getAddress());
+ m_LogPanel.logMessage(Messages.getInstance().getString(
+ "Explorer_LogPanel_LogMessage_Text_Fourth")
+ + Copyright.getURL());
+ m_LogPanel.logMessage(Messages.getInstance().getString(
+ "Explorer_LogPanel_LogMessage_Text_Fifth")
+ + date);
+ m_LogPanel.statusMessage(Messages.getInstance().getString(
+ "Explorer_LogPanel_StatusMessage_Text_First"));
// intialize pre-processpanel
m_PreprocessPanel.setLog(m_LogPanel);
- m_TabbedPane.addTab(
- m_PreprocessPanel.getTabTitle(),
- null,
- m_PreprocessPanel,
- m_PreprocessPanel.getTabTitleToolTip());
-
+ m_TabbedPane.addTab(m_PreprocessPanel.getTabTitle(), null,
+ m_PreprocessPanel, m_PreprocessPanel.getTabTitleToolTip());
+
// initialize additional panels
String[] tabs = ExplorerDefaults.getTabs();
Hashtable<String, HashSet> tabOptions = new Hashtable<String, HashSet>();
- for (int i = 0; i < tabs.length; i++) {
+ for (String tab : tabs) {
try {
- // determine classname and additional options
- String[] optionsStr = tabs[i].split(":");
- String classname = optionsStr[0];
- HashSet options = new HashSet();
- tabOptions.put(classname, options);
- for (int n = 1; n < optionsStr.length; n++)
- options.add(optionsStr[n]);
-
- // setup panel
- ExplorerPanel panel = (ExplorerPanel) Class.forName(classname).newInstance();
- panel.setExplorer(this);
- m_Panels.add(panel);
- if (panel instanceof LogHandler)
- ((LogHandler) panel).setLog(m_LogPanel);
- m_TabbedPane.addTab(
- panel.getTabTitle(), null, (JPanel) panel, panel.getTabTitleToolTip());
- }
- catch (Exception e) {
- e.printStackTrace();
+ // determine classname and additional options
+ String[] optionsStr = tab.split(":");
+ String classname = optionsStr[0];
+ HashSet options = new HashSet();
+ tabOptions.put(classname, options);
+ for (int n = 1; n < optionsStr.length; n++) {
+ options.add(optionsStr[n]);
+ }
+
+ // setup panel
+ ExplorerPanel panel = (ExplorerPanel) Class.forName(classname)
+ .newInstance();
+ panel.setExplorer(this);
+ m_Panels.add(panel);
+ if (panel instanceof LogHandler) {
+ ((LogHandler) panel).setLog(m_LogPanel);
+ }
+ m_TabbedPane.addTab(panel.getTabTitle(), null, (JPanel) panel,
+ panel.getTabTitleToolTip());
+ } catch (Exception e) {
+ e.printStackTrace();
}
}
@@ -253,11 +261,12 @@ public class Explorer
// setup notification for dataset changes
m_PreprocessPanel.addPropertyChangeListener(new PropertyChangeListener() {
+ @Override
public void propertyChange(PropertyChangeEvent e) {
- for (int i = 0; i < m_Panels.size(); i++) {
- m_Panels.get(i).setInstances(m_PreprocessPanel.getInstances());
- m_TabbedPane.setEnabledAt(i + 1, true);
- }
+ for (int i = 0; i < m_Panels.size(); i++) {
+ m_Panels.get(i).setInstances(m_PreprocessPanel.getInstances());
+ m_TabbedPane.setEnabledAt(i + 1, true);
+ }
}
});
@@ -265,8 +274,10 @@ public class Explorer
m_PreprocessPanel.setExplorer(this);
addCapabilitiesFilterListener(m_PreprocessPanel);
for (int i = 0; i < m_Panels.size(); i++) {
- if (m_Panels.get(i) instanceof CapabilitiesFilterChangeListener)
- addCapabilitiesFilterListener((CapabilitiesFilterChangeListener) m_Panels.get(i));
+ if (m_Panels.get(i) instanceof CapabilitiesFilterChangeListener) {
+ addCapabilitiesFilterListener((CapabilitiesFilterChangeListener) m_Panels
+ .get(i));
+ }
}
// add components to layout
@@ -274,41 +285,41 @@ public class Explorer
add(m_TabbedPane, BorderLayout.CENTER);
add(m_LogPanel, BorderLayout.SOUTH);
}
-
+
/**
* returns all the panels, apart from the PreprocessPanel
*
- * @return the currently displayed panels w/o PreprocessPanel
+ * @return the currently displayed panels w/o PreprocessPanel
*/
public Vector<ExplorerPanel> getPanels() {
return m_Panels;
}
-
+
/**
- * returns the instance of the PreprocessPanel being used in this instance
- * of the Explorer
+ * returns the instance of the PreprocessPanel being used in this instance of
+ * the Explorer
*
- * @return the panel
+ * @return the panel
*/
public PreprocessPanel getPreprocessPanel() {
return m_PreprocessPanel;
}
-
+
/**
* returns the tabbed pane of the Explorer
*
- * @return the tabbed pane
+ * @return the tabbed pane
*/
public JTabbedPane getTabbedPane() {
return m_TabbedPane;
}
-
+
/**
* adds the listener to the list of objects that listen for changes of the
* CapabilitiesFilter
*
- * @param l the listener to add
- * @see #m_CapabilitiesFilterChangeListeners
+ * @param l the listener to add
+ * @see #m_CapabilitiesFilterChangeListeners
*/
public void addCapabilitiesFilterListener(CapabilitiesFilterChangeListener l) {
m_CapabilitiesFilterChangeListeners.add(l);
@@ -317,28 +328,32 @@ public class Explorer
/**
* Removes the specified listener from the set of listeners if it is present.
*
- * @param l the listener to remove
- * @return true if the listener was registered
+ * @param l the listener to remove
+ * @return true if the listener was registered
*/
- public boolean removeCapabilitiesFilterListener(CapabilitiesFilterChangeListener l) {
+ public boolean removeCapabilitiesFilterListener(
+ CapabilitiesFilterChangeListener l) {
return m_CapabilitiesFilterChangeListeners.remove(l);
}
-
+
/**
* notifies all the listeners of a change
*
- * @param filter the affected filter
+ * @param filter the affected filter
*/
public void notifyCapabilitiesFilterListener(Capabilities filter) {
- for (CapabilitiesFilterChangeListener l: m_CapabilitiesFilterChangeListeners) {
- if (l == this)
- continue;
- l.capabilitiesFilterChanged(new CapabilitiesFilterChangeEvent(this, filter));
+ for (CapabilitiesFilterChangeListener l : m_CapabilitiesFilterChangeListeners) {
+ if (l == this) {
+ continue;
+ }
+ l.capabilitiesFilterChanged(new CapabilitiesFilterChangeEvent(this,
+ filter));
}
}
-
- /** variable for the Explorer class which would be set to null by the memory
- monitoring thread to free up some memory if we running out of memory
+
+ /**
+ * variable for the Explorer class which would be set to null by the memory
+ * monitoring thread to free up some memory if we running out of memory
*/
private static Explorer m_explorer;
@@ -347,24 +362,27 @@ public class Explorer
/**
* Tests out the explorer environment.
- *
+ *
* @param args ignored.
*/
- public static void main(String [] args) {
+ public static void main(String[] args) {
+
+ weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages
+ .getInstance().getString("Explorer_Main_Logger_Text"));
- weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages.getInstance().getString("Explorer_Main_Logger_Text"));
-
LookAndFeel.setLookAndFeel();
-
+
try {
// uncomment to disable the memory management:
- //m_Memory.setEnabled(false);
+ // m_Memory.setEnabled(false);
m_explorer = new Explorer();
- final JFrame jf = new JFrame(Messages.getInstance().getString("Explorer_Main_JFrame_Text"));
+ final JFrame jf = new JFrame(Messages.getInstance().getString(
+ "Explorer_Main_JFrame_Text"));
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(m_explorer, BorderLayout.CENTER);
jf.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent e) {
jf.dispose();
System.exit(0);
@@ -373,40 +391,46 @@ public class Explorer
jf.pack();
jf.setSize(800, 600);
jf.setVisible(true);
- Image icon = Toolkit.getDefaultToolkit().
- getImage(m_explorer.getClass().getClassLoader().getResource("weka/gui/weka_icon_new_48.png"));
+ Image icon = Toolkit.getDefaultToolkit().getImage(
+ m_explorer.getClass().getClassLoader()
+ .getResource("weka/gui/weka_icon_new_48.png"));
jf.setIconImage(icon);
if (args.length == 1) {
- System.err.println(Messages.getInstance().getString("Explorer_Main_Run_Error_Text") + args[0]);
+ System.err.println(Messages.getInstance().getString(
+ "Explorer_Main_Run_Error_Text")
+ + args[0]);
AbstractFileLoader loader = ConverterUtils.getLoaderForFile(args[0]);
- loader.setFile(new File(args[0]));
+ loader.setFile(new File(args[0]));
m_explorer.m_PreprocessPanel.setInstancesFromFile(loader);
}
Thread memMonitor = new Thread() {
+ @Override
public void run() {
- while(true) {
- try {
- //System.out.println("Before sleeping.");
- this.sleep(4000);
+ while (true) {
+ // try {
+ // //System.out.println("Before sleeping.");
+ // this.sleep(4000);
- System.gc();
+ // System.gc();
- if (m_Memory.isOutOfMemory()) {
- // clean up
- jf.dispose();
- m_explorer = null;
- System.gc();
+ if (m_Memory.isOutOfMemory()) {
+ // clean up
+ jf.dispose();
+ m_explorer = null;
+ System.gc();
- // display error
- System.err.println(Messages.getInstance().getString("Explorer_Main_Run_Error_Text_First"));
- m_Memory.showOutOfMemory();
- System.err.println(Messages.getInstance().getString("Explorer_Main_Run_Error_Text_Second"));
- System.exit(-1);
- }
+ // display error
+ System.err.println(Messages.getInstance().getString(
+ "Explorer_Main_Run_Error_Text_First"));
+ m_Memory.showOutOfMemory();
+ System.err.println(Messages.getInstance().getString(
+ "Explorer_Main_Run_Error_Text_Second"));
+ System.exit(-1);
+ }
- } catch(InterruptedException ex) { ex.printStackTrace(); }
+ // } catch(InterruptedException ex) { ex.printStackTrace(); }
}
}
};
diff --git a/src/main/java/weka/gui/explorer/messages/messages.properties b/src/main/java/weka/gui/explorer/messages/messages.properties
index 4ef906f..74b80ef 100644
--- a/src/main/java/weka/gui/explorer/messages/messages.properties
+++ b/src/main/java/weka/gui/explorer/messages/messages.properties
@@ -379,7 +379,7 @@ ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Fourth= instances...
ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_Third=Finished re-evaluation
ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Fifth=OK
ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Sixth=See error log
-ClassifierPanel_ReEvaluateModel_JOptionPaneShowMessageDialog_Text_First=Problem evaluationg classifier:\n
+ClassifierPanel_ReEvaluateModel_JOptionPaneShowMessageDialog_Text_First=Problem evaluating classifier:\n
ClassifierPanel_ReEvaluateModel_JOptionPaneShowMessageDialog_Text_Second=Evaluate classifier
ClassifierPanel_ReEvaluateModel_Log_StatusMessage_Text_Seventh=Problem evaluating classifier
ClassifierPanel_ReEvaluateModel_Log_LogMessage_Text_Fourth=Interrupted reevaluate model
@@ -388,6 +388,9 @@ ClassifierPanel_GetTabTitle_Text=Classify
ClassifierPanel_GetTabTitleToolTip_Text=Classify instances
ClassifierPanel_Main_JFrame_Text=Weka Explorer: Classifier
ClassifierPanel_Main_Error_Text=Loading instances from
+ClassifierPanel_OutputAdditionalAttributes_First=Illegal additional attribute Specification:
+ClassifierPanel_OutputAdditionalAttributes_Second=A range string is required - e.g. '2,4,6-last.'
+ClassifierPanel_OutputAdditionalAttributes_Title=Illegal additional attribute specification
#ClustererPanel.java
ClustererPanel_PercentBut_JRadioButton_Text=Percentage split
diff --git a/src/main/java/weka/gui/graphvisualizer/HierarchicalBCEngine.java b/src/main/java/weka/gui/graphvisualizer/HierarchicalBCEngine.java
index 009ecab..90db7b4 100644
--- a/src/main/java/weka/gui/graphvisualizer/HierarchicalBCEngine.java
+++ b/src/main/java/weka/gui/graphvisualizer/HierarchicalBCEngine.java
@@ -57,7 +57,7 @@ import java.awt.GridBagConstraints;
* vertices present in each level.
*
* @author Ashraf M. Kibriya (amk14 at cs.waikato.ac.nz)
- * @version $Revision: 7059 $ - 24 Apr 2003 - Initial version (Ashraf M. Kibriya)
+ * @version $Revision: 10503 $ - 24 Apr 2003 - Initial version (Ashraf M. Kibriya)
*
*/
public class HierarchicalBCEngine implements GraphConstants, LayoutEngine {
@@ -497,7 +497,7 @@ public class HierarchicalBCEngine implements GraphConstants, LayoutEngine {
//****Assigning nodes to each level
int levelsCounter[] = new int[maxLevel+1];
nodeLevels = new int[maxLevel+1][];
- for(byte i=0; i<nodesLevel.length; i++) {
+ for(int i=0; i<nodesLevel.length; i++) {
if(nodeLevels[nodesLevel[i]]==null)
nodeLevels[nodesLevel[i]] = new int[ levelCounts[nodesLevel[i]] ];
//nodeLevels[nodesLevel[i]].addElement(new Integer(i));
diff --git a/src/main/java/weka/gui/sql/SqlViewer.java b/src/main/java/weka/gui/sql/SqlViewer.java
index a4075ec..67acf66 100644
--- a/src/main/java/weka/gui/sql/SqlViewer.java
+++ b/src/main/java/weka/gui/sql/SqlViewer.java
@@ -22,17 +22,6 @@
package weka.gui.sql;
-import weka.core.Memory;
-import weka.gui.LookAndFeel;
-import weka.gui.sql.event.ConnectionEvent;
-import weka.gui.sql.event.ConnectionListener;
-import weka.gui.sql.event.HistoryChangedEvent;
-import weka.gui.sql.event.HistoryChangedListener;
-import weka.gui.sql.event.QueryExecuteEvent;
-import weka.gui.sql.event.QueryExecuteListener;
-import weka.gui.sql.event.ResultChangedEvent;
-import weka.gui.sql.event.ResultChangedListener;
-
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.WindowAdapter;
@@ -49,18 +38,25 @@ import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JPanel;
+import weka.core.Memory;
+import weka.gui.LookAndFeel;
+import weka.gui.sql.event.ConnectionEvent;
+import weka.gui.sql.event.ConnectionListener;
+import weka.gui.sql.event.HistoryChangedEvent;
+import weka.gui.sql.event.HistoryChangedListener;
+import weka.gui.sql.event.QueryExecuteEvent;
+import weka.gui.sql.event.QueryExecuteListener;
+import weka.gui.sql.event.ResultChangedEvent;
+import weka.gui.sql.event.ResultChangedListener;
+
/**
* Represents a little tool for querying SQL databases.
- *
- * @author FracPete (fracpete at waikato dot ac dot nz)
- * @version $Revision: 9490 $
+ *
+ * @author FracPete (fracpete at waikato dot ac dot nz)
+ * @version $Revision: 10438 $
*/
-public class SqlViewer
- extends JPanel
- implements ConnectionListener,
- HistoryChangedListener,
- QueryExecuteListener,
- ResultChangedListener {
+public class SqlViewer extends JPanel implements ConnectionListener,
+ HistoryChangedListener, QueryExecuteListener, ResultChangedListener {
/** for serialization. */
private static final long serialVersionUID = -4395028775566514329L;
@@ -73,7 +69,7 @@ public class SqlViewer
/** the height property in the history file. */
public final static String HEIGHT = "height";
-
+
/** the parent of this panel. */
protected JFrame m_Parent;
@@ -103,22 +99,22 @@ public class SqlViewer
/** stores the history. */
protected Properties m_History;
-
+
/**
* initializes the SqlViewer.
*
- * @param parent the parent of this panel
+ * @param parent the parent of this panel
*/
public SqlViewer(JFrame parent) {
super();
-
- m_Parent = parent;
- m_URL = "";
- m_User = "";
+
+ m_Parent = parent;
+ m_URL = "";
+ m_User = "";
m_Password = "";
- m_Query = "";
- m_History = new Properties();
-
+ m_Query = "";
+ m_History = new Properties();
+
createPanel();
}
@@ -126,9 +122,9 @@ public class SqlViewer
* builds the interface.
*/
protected void createPanel() {
- JPanel panel;
- JPanel panel2;
-
+ JPanel panel;
+ JPanel panel2;
+
setLayout(new BorderLayout());
// connection
@@ -136,8 +132,9 @@ public class SqlViewer
panel = new JPanel(new BorderLayout());
add(panel, BorderLayout.NORTH);
panel.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(Messages.getInstance().getString("SqlViewer_CreatePanel_Panel_BorderFactoryCreateTitledBorder_Text")),
- BorderFactory.createEmptyBorder(0, 5, 5, 5)));
+ BorderFactory.createTitledBorder(Messages.getInstance().getString(
+ "SqlViewer_CreatePanel_Panel_BorderFactoryCreateTitledBorder_Text")),
+ BorderFactory.createEmptyBorder(0, 5, 5, 5)));
panel.add(m_ConnectionPanel, BorderLayout.CENTER);
// query
@@ -145,9 +142,14 @@ public class SqlViewer
panel = new JPanel(new BorderLayout());
add(panel, BorderLayout.CENTER);
panel2 = new JPanel(new BorderLayout());
- panel2.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(Messages.getInstance().getString("SqlViewer_CreatePanel_Panel2_BorderFactoryCreateTitledBorder_Text_First")),
- BorderFactory.createEmptyBorder(0, 5, 5, 5)));
+ panel2
+ .setBorder(BorderFactory.createCompoundBorder(
+ BorderFactory
+ .createTitledBorder(Messages
+ .getInstance()
+ .getString(
+ "SqlViewer_CreatePanel_Panel2_BorderFactoryCreateTitledBorder_Text_First")),
+ BorderFactory.createEmptyBorder(0, 5, 5, 5)));
panel2.add(m_QueryPanel, BorderLayout.NORTH);
panel.add(panel2, BorderLayout.NORTH);
@@ -155,9 +157,14 @@ public class SqlViewer
m_ResultPanel = new ResultPanel(m_Parent);
m_ResultPanel.setQueryPanel(m_QueryPanel);
panel2 = new JPanel(new BorderLayout());
- panel2.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(Messages.getInstance().getString("SqlViewer_CreatePanel_Panel2_BorderFactoryCreateTitledBorder_Text_Second")),
- BorderFactory.createEmptyBorder(0, 5, 5, 5)));
+ panel2
+ .setBorder(BorderFactory.createCompoundBorder(
+ BorderFactory
+ .createTitledBorder(Messages
+ .getInstance()
+ .getString(
+ "SqlViewer_CreatePanel_Panel2_BorderFactoryCreateTitledBorder_Text_Second")),
+ BorderFactory.createEmptyBorder(0, 5, 5, 5)));
panel2.add(m_ResultPanel, BorderLayout.CENTER);
panel.add(panel2, BorderLayout.CENTER);
@@ -165,9 +172,14 @@ public class SqlViewer
m_InfoPanel = new InfoPanel(m_Parent);
panel = new JPanel(new BorderLayout());
add(panel, BorderLayout.SOUTH);
- panel.setBorder(BorderFactory.createCompoundBorder(
- BorderFactory.createTitledBorder(Messages.getInstance().getString("SqlViewer_CreatePanel_Panel_BorderFactoryCreateTitledBorder_Text_Second")),
- BorderFactory.createEmptyBorder(0, 5, 5, 5)));
+ panel
+ .setBorder(BorderFactory.createCompoundBorder(
+ BorderFactory
+ .createTitledBorder(Messages
+ .getInstance()
+ .getString(
+ "SqlViewer_CreatePanel_Panel_BorderFactoryCreateTitledBorder_Text_Second")),
+ BorderFactory.createEmptyBorder(0, 5, 5, 5)));
panel.add(m_InfoPanel, BorderLayout.CENTER);
// listeners
@@ -181,102 +193,131 @@ public class SqlViewer
// history
loadHistory(true);
}
-
+
/**
- * This method gets called when the connection is either established
- * or disconnected.
+ * This method gets called when the connection is either established or
+ * disconnected.
*
- * @param evt the event
+ * @param evt the event
*/
+ @Override
public void connectionChange(ConnectionEvent evt) {
if (evt.getType() == ConnectionEvent.DISCONNECT) {
- m_InfoPanel.append( Messages.getInstance().getString("SqlViewer_ConnectionChange_InfoPanel_Text_First")
- + evt.getDbUtils().getDatabaseURL(),
- "information_small.gif" );
- }
- else {
- m_InfoPanel.append( Messages.getInstance().getString("SqlViewer_ConnectionChange_InfoPanel_Text_Second")
- + evt.getDbUtils().getDatabaseURL()
- + " = " + evt.isConnected(),
- "information_small.gif" );
+ m_InfoPanel.append(
+ Messages.getInstance().getString(
+ "SqlViewer_ConnectionChange_InfoPanel_Text_First")
+ + evt.getDbUtils().getDatabaseURL(), "information_small.gif");
+ } else {
+ m_InfoPanel.append(
+ Messages.getInstance().getString(
+ "SqlViewer_ConnectionChange_InfoPanel_Text_Second")
+ + evt.getDbUtils().getDatabaseURL() + " = " + evt.isConnected(),
+ "information_small.gif");
}
// did an exception happen?
- if (evt.getException() != null)
- m_InfoPanel.append(Messages.getInstance().getString("SqlViewer_ConnectionChange_InfoPanel_Text_Third") + evt.getException(), "error_small.gif");
+ if (evt.getException() != null) {
+ m_InfoPanel.append(
+ Messages.getInstance().getString(
+ "SqlViewer_ConnectionChange_InfoPanel_Text_Third")
+ + evt.getException(), "error_small.gif");
+ }
// set focus
- if (evt.isConnected())
+ if (evt.isConnected()) {
m_QueryPanel.setFocus();
- else
+ } else {
m_ConnectionPanel.setFocus();
+ }
}
-
+
/**
* This method gets called when a query has been executed.
*
- * @param evt the event
+ * @param evt the event
*/
+ @Override
public void queryExecuted(QueryExecuteEvent evt) {
- ResultSetHelper helper;
-
+ ResultSetHelper helper;
+
if (evt.failed()) {
- m_InfoPanel.append(Messages.getInstance().getString("SqlViewer_QueryExecuted_InfoPanel_Text_First") + evt.getQuery(), "error_small.gif");
- m_InfoPanel.append(Messages.getInstance().getString("SqlViewer_QueryExecuted_InfoPanel_Text_Second") + evt.getException(), "error_small.gif");
- }
- else {
- m_InfoPanel.append(Messages.getInstance().getString("SqlViewer_QueryExecuted_InfoPanel_Text_Third") + evt.getQuery(), "information_small.gif");
+ m_InfoPanel.append(
+ Messages.getInstance().getString(
+ "SqlViewer_QueryExecuted_InfoPanel_Text_First")
+ + evt.getQuery(), "error_small.gif");
+ m_InfoPanel.append(
+ Messages.getInstance().getString(
+ "SqlViewer_QueryExecuted_InfoPanel_Text_Second")
+ + evt.getException(), "error_small.gif");
+ } else {
+ m_InfoPanel.append(
+ Messages.getInstance().getString(
+ "SqlViewer_QueryExecuted_InfoPanel_Text_Third")
+ + evt.getQuery(), "information_small.gif");
try {
if (evt.hasResult()) {
helper = new ResultSetHelper(evt.getResultSet());
- if ((evt.getMaxRows() > 0) && (helper.getRowCount() >= evt.getMaxRows()))
- m_InfoPanel.append(helper.getRowCount() + Messages.getInstance().getString("SqlViewer_QueryExecuted_InfoPanel_Text_Fourth")
- + evt.getMaxRows() + Messages.getInstance().getString("SqlViewer_QueryExecuted_InfoPanel_Text_Fifth"),
- "information_small.gif");
- else if (helper.getRowCount() == -1)
- m_InfoPanel.append(Messages.getInstance().getString("SqlViewer_QueryExecuted_InfoPanel_Text_Sixth"),
+ if ((evt.getMaxRows() > 0)
+ && (helper.getRowCount() >= evt.getMaxRows())) {
+ m_InfoPanel.append(
+ helper.getRowCount()
+ + Messages.getInstance().getString(
+ "SqlViewer_QueryExecuted_InfoPanel_Text_Fourth")
+ + evt.getMaxRows()
+ + Messages.getInstance().getString(
+ "SqlViewer_QueryExecuted_InfoPanel_Text_Fifth"),
+ "information_small.gif");
+ } else if (helper.getRowCount() == -1) {
+ m_InfoPanel.append(
+ Messages.getInstance().getString(
+ "SqlViewer_QueryExecuted_InfoPanel_Text_Sixth"),
+ "information_small.gif");
+ } else {
+ m_InfoPanel.append(
+ helper.getRowCount()
+ + Messages.getInstance().getString(
+ "SqlViewer_QueryExecuted_InfoPanel_Text_Seventh"),
"information_small.gif");
- else
- m_InfoPanel.append(helper.getRowCount() + Messages.getInstance().getString("SqlViewer_QueryExecuted_InfoPanel_Text_Seventh"),
- "information_small.gif");
+ }
}
// save max rows
loadHistory(false);
- m_History.setProperty(
- QueryPanel.MAX_ROWS, Integer.toString(evt.getMaxRows()));
+ m_History.setProperty(QueryPanel.MAX_ROWS,
+ Integer.toString(evt.getMaxRows()));
saveHistory();
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
}
-
+
/**
* This method gets called when a query has been executed.
*
- * @param evt the event
+ * @param evt the event
*/
+ @Override
public void resultChanged(ResultChangedEvent evt) {
- m_URL = evt.getURL();
- m_User = evt.getUser();
+ m_URL = evt.getURL();
+ m_User = evt.getUser();
m_Password = evt.getPassword();
- m_Query = evt.getQuery();
+ m_Query = evt.getQuery();
}
-
+
/**
- * This method gets called when a history is modified.
- * It saves the history immediately to the users home directory.
+ * This method gets called when a history is modified. It saves the history
+ * immediately to the users home directory.
*
- * @param evt the event
+ * @param evt the event
*/
+ @Override
public void historyChanged(HistoryChangedEvent evt) {
// load history, in case some other process changed it!
loadHistory(false);
-
- m_History.setProperty(
- evt.getHistoryName(), modelToString(evt.getHistory()));
+
+ m_History
+ .setProperty(evt.getHistoryName(), modelToString(evt.getHistory()));
// save it
saveHistory();
@@ -285,77 +326,74 @@ public class SqlViewer
/**
* returns the filename of the history file.
*
- * @return the history file
+ * @return the history file
*/
protected String getHistoryFilename() {
- return System.getProperties().getProperty("user.home")
- + File.separatorChar
- + HISTORY_FILE;
+ return System.getProperties().getProperty("user.home") + File.separatorChar
+ + HISTORY_FILE;
}
/**
* transforms the given, comma-separated string into a DefaultListModel.
*
- * @param s the string to break up and transform into a list model
- * @return the generated DefaultListModel
+ * @param s the string to break up and transform into a list model
+ * @return the generated DefaultListModel
*/
protected DefaultListModel stringToModel(String s) {
- DefaultListModel result;
- String tmpStr;
- int i;
- boolean quote;
- String[] find;
- String[] replace;
- int index;
+ DefaultListModel result;
+ String tmpStr;
+ int i;
+ boolean quote;
+ String[] find;
+ String[] replace;
+ int index;
result = new DefaultListModel();
-
+
// get rid of doubled quotes, \\n, etc.
- find = new String[]{"\"\"", "\\n", "\\r", "\\t"};
- replace = new String[]{"\"", "\n", "\r", "\t"};
+ find = new String[] { "\"\"", "\\n", "\\r", "\\t" };
+ replace = new String[] { "\"", "\n", "\r", "\t" };
for (i = 0; i < find.length; i++) {
tmpStr = "";
while (s.length() > 0) {
index = s.indexOf(find[i]);
if (index > -1) {
tmpStr += s.substring(0, index) + replace[i];
- s = s.substring(index + 2);
- }
- else {
+ s = s.substring(index + 2);
+ } else {
tmpStr += s;
- s = "";
+ s = "";
}
}
s = tmpStr;
}
- quote = false;
+ quote = false;
tmpStr = "";
for (i = 0; i < s.length(); i++) {
if (s.charAt(i) == '"') {
quote = !quote;
tmpStr += "" + s.charAt(i);
- }
- else if (s.charAt(i) == ',') {
+ } else if (s.charAt(i) == ',') {
if (quote) {
tmpStr += "" + s.charAt(i);
- }
- else {
- if (tmpStr.startsWith("\""))
+ } else {
+ if (tmpStr.startsWith("\"")) {
tmpStr = tmpStr.substring(1, tmpStr.length() - 1);
+ }
result.addElement(tmpStr);
tmpStr = "";
}
- }
- else {
+ } else {
tmpStr += "" + s.charAt(i);
}
}
-
+
// add last element
if (!tmpStr.equals("")) {
- if (tmpStr.startsWith("\""))
+ if (tmpStr.startsWith("\"")) {
tmpStr = tmpStr.substring(1, tmpStr.length() - 1);
+ }
result.addElement(tmpStr);
}
@@ -365,39 +403,43 @@ public class SqlViewer
/**
* converts the given model into a comma-separated string.
*
- * @param m the model to convert
- * @return the string representation of the model
+ * @param m the model to convert
+ * @return the string representation of the model
*/
protected String modelToString(DefaultListModel m) {
- String result;
- String tmpStr;
- int i;
- int n;
- boolean quote;
+ String result;
+ String tmpStr;
+ int i;
+ int n;
+ boolean quote;
result = "";
for (i = 0; i < m.size(); i++) {
- if (i > 0)
+ if (i > 0) {
result += ",";
-
+ }
+
tmpStr = m.get(i).toString();
- quote = (tmpStr.indexOf(",") > -1) || (tmpStr.indexOf(" ") > -1);
-
- if (quote)
+ quote = (tmpStr.indexOf(",") > -1) || (tmpStr.indexOf(" ") > -1);
+
+ if (quote) {
result += "\"";
-
+ }
+
for (n = 0; n < tmpStr.length(); n++) {
// double quotes
- if (tmpStr.charAt(n) == '"')
+ if (tmpStr.charAt(n) == '"') {
result += "" + "\"\"";
- // normal character
- else
+ // normal character
+ } else {
result += "" + tmpStr.charAt(n);
+ }
}
-
- if (quote)
+
+ if (quote) {
result += "\"";
+ }
}
return result;
@@ -406,42 +448,39 @@ public class SqlViewer
/**
* loads the history properties of the SqlViewer in the user's home directory.
*
- * @param set whether to set the read properties in the panels or not
+ * @param set whether to set the read properties in the panels or not
* @see #HISTORY_FILE
*/
protected void loadHistory(boolean set) {
- BufferedInputStream str;
- File file;
- int width;
- int height;
+ BufferedInputStream str;
+ File file;
+ int width;
+ int height;
try {
file = new File(getHistoryFilename());
if (file.exists()) {
- str = new BufferedInputStream(
- new FileInputStream(getHistoryFilename()));
+ str = new BufferedInputStream(new FileInputStream(getHistoryFilename()));
m_History.load(str);
}
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
// set the histories
if (set) {
- m_ConnectionPanel.setHistory(
- stringToModel(
- m_History.getProperty(ConnectionPanel.HISTORY_NAME, "")));
- m_QueryPanel.setHistory(
- stringToModel(
- m_History.getProperty(QueryPanel.HISTORY_NAME, "")));
- m_QueryPanel.setMaxRows(
- Integer.parseInt(m_History.getProperty(QueryPanel.MAX_ROWS, "100")));
-
- width = Integer.parseInt(m_History.getProperty(WIDTH, "0"));
+ m_ConnectionPanel.setHistory(stringToModel(m_History.getProperty(
+ ConnectionPanel.HISTORY_NAME, "")));
+ m_QueryPanel.setHistory(stringToModel(m_History.getProperty(
+ QueryPanel.HISTORY_NAME, "")));
+ m_QueryPanel.setMaxRows(Integer.parseInt(m_History.getProperty(
+ QueryPanel.MAX_ROWS, "100")));
+
+ width = Integer.parseInt(m_History.getProperty(WIDTH, "0"));
height = Integer.parseInt(m_History.getProperty(HEIGHT, "0"));
- if ((width != 0) && (height != 0))
- setPreferredSize(new Dimension(width, height));
+ if ((width != 0) && (height != 0)) {
+ setPreferredSize(new Dimension(width, height));
+ }
}
}
@@ -451,14 +490,12 @@ public class SqlViewer
* @see #HISTORY_FILE
*/
protected void saveHistory() {
- BufferedOutputStream str;
-
+ BufferedOutputStream str;
+
try {
- str = new BufferedOutputStream(
- new FileOutputStream(getHistoryFilename()));
+ str = new BufferedOutputStream(new FileOutputStream(getHistoryFilename()));
m_History.store(str, "SQL-Viewer-History");
- }
- catch (Exception e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
@@ -474,10 +511,10 @@ public class SqlViewer
saveHistory();
}
-
+
/**
- * calls the clear method of all sub-panels to set back to default values
- * and free up memory.
+ * calls the clear method of all sub-panels to set back to default values and
+ * free up memory.
*/
public void clear() {
m_ConnectionPanel.clear();
@@ -490,8 +527,8 @@ public class SqlViewer
* returns the database URL from the currently active tab in the ResultPanel,
* otherwise an empty string.
*
- * @see ResultPanel
- * @return the currently selected tab's URL
+ * @see ResultPanel
+ * @return the currently selected tab's URL
*/
public String getURL() {
return m_URL;
@@ -501,8 +538,8 @@ public class SqlViewer
* returns the user from the currently active tab in the ResultPanel,
* otherwise an empty string.
*
- * @see ResultPanel
- * @return the currently selected tab's user
+ * @see ResultPanel
+ * @return the currently selected tab's user
*/
public String getUser() {
return m_User;
@@ -512,8 +549,8 @@ public class SqlViewer
* returns the password from the currently active tab in the ResultPanel,
* otherwise an empty string.
*
- * @see ResultPanel
- * @return the currently selected tab's password
+ * @see ResultPanel
+ * @return the currently selected tab's password
*/
public String getPassword() {
return m_Password;
@@ -523,8 +560,8 @@ public class SqlViewer
* returns the query from the currently active tab in the ResultPanel,
* otherwise an empty string.
*
- * @see ResultPanel
- * @return the currently selected tab's query
+ * @see ResultPanel
+ * @return the currently selected tab's query
*/
public String getQuery() {
return m_Query;
@@ -533,7 +570,7 @@ public class SqlViewer
/**
* adds the given listener to the list of listeners.
*
- * @param l the listener to add to the list
+ * @param l the listener to add to the list
*/
public void addConnectionListener(ConnectionListener l) {
m_ConnectionPanel.addConnectionListener(l);
@@ -542,7 +579,7 @@ public class SqlViewer
/**
* removes the given listener from the list of listeners.
*
- * @param l the listener to remove
+ * @param l the listener to remove
*/
public void removeConnectionListener(ConnectionListener l) {
m_ConnectionPanel.removeConnectionListener(l);
@@ -551,7 +588,7 @@ public class SqlViewer
/**
* adds the given listener to the list of listeners.
*
- * @param l the listener to add to the list
+ * @param l the listener to add to the list
*/
public void addQueryExecuteListener(QueryExecuteListener l) {
m_QueryPanel.addQueryExecuteListener(l);
@@ -560,7 +597,7 @@ public class SqlViewer
/**
* removes the given listener from the list of listeners.
*
- * @param l the listener to remove
+ * @param l the listener to remove
*/
public void removeQueryExecuteListener(QueryExecuteListener l) {
m_QueryPanel.removeQueryExecuteListener(l);
@@ -569,7 +606,7 @@ public class SqlViewer
/**
* adds the given listener to the list of listeners.
*
- * @param l the listener to add to the list
+ * @param l the listener to add to the list
*/
public void addResultChangedListener(ResultChangedListener l) {
m_ResultPanel.addResultChangedListener(l);
@@ -578,7 +615,7 @@ public class SqlViewer
/**
* removes the given listener from the list of listeners.
*
- * @param l the listener to remove
+ * @param l the listener to remove
*/
public void removeResultChangedListener(ResultChangedListener l) {
m_ResultPanel.removeResultChangedListener(l);
@@ -587,7 +624,7 @@ public class SqlViewer
/**
* adds the given listener to the list of listeners.
*
- * @param l the listener to add to the list
+ * @param l the listener to add to the list
*/
public void addHistoryChangedListener(HistoryChangedListener l) {
m_ConnectionPanel.addHistoryChangedListener(l);
@@ -597,7 +634,7 @@ public class SqlViewer
/**
* removes the given listener from the list of listeners.
*
- * @param l the listener to remove
+ * @param l the listener to remove
*/
public void removeHistoryChangedListener(HistoryChangedListener l) {
m_ConnectionPanel.removeHistoryChangedListener(l);
@@ -606,28 +643,31 @@ public class SqlViewer
/** for monitoring the Memory consumption. */
private static Memory m_Memory = new Memory(true);
-
+
/** the sql viewer. */
private static SqlViewer m_Viewer;
-
+
/**
* starts the SQL-Viewer interface.
*
- * @param args the commandline arguments - ignored
+ * @param args the commandline arguments - ignored
*/
public static void main(String[] args) {
- weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages.getInstance().getString("SqlViewer_Main_Log_Text"));
+ weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO, Messages
+ .getInstance().getString("SqlViewer_Main_Log_Text"));
LookAndFeel.setLookAndFeel();
-
+
try {
// uncomment to disable the memory management:
- //m_Memory.setEnabled(false);
+ // m_Memory.setEnabled(false);
- final JFrame jf = new JFrame(Messages.getInstance().getString("SqlViewer_Main_JFrame_Text"));
+ final JFrame jf = new JFrame(Messages.getInstance().getString(
+ "SqlViewer_Main_JFrame_Text"));
m_Viewer = new SqlViewer(jf);
jf.getContentPane().setLayout(new BorderLayout());
jf.getContentPane().add(m_Viewer, BorderLayout.CENTER);
jf.addWindowListener(new WindowAdapter() {
+ @Override
public void windowClosing(WindowEvent e) {
m_Viewer.saveSize();
jf.dispose();
@@ -639,38 +679,40 @@ public class SqlViewer
jf.setVisible(true);
Thread memMonitor = new Thread() {
+ @Override
public void run() {
while (true) {
- try {
- this.sleep(4000);
-
+ // try {
+ // this.sleep(4000);
+ //
+ // System.gc();
+
+ if (m_Memory.isOutOfMemory()) {
+ // clean up
+ jf.dispose();
+ m_Viewer = null;
System.gc();
- if (m_Memory.isOutOfMemory()) {
- // clean up
- jf.dispose();
- m_Viewer = null;
- System.gc();
-
- // display error
- System.err.println(Messages.getInstance().getString("SqlViewer_Main_Error_Text_First"));
- m_Memory.showOutOfMemory();
- System.err.println(Messages.getInstance().getString("SqlViewer_Main_Error_Text_Second"));
- System.exit(-1);
- }
-
- }
- catch (InterruptedException ex) {
- ex.printStackTrace();
+ // display error
+ System.err.println(Messages.getInstance().getString(
+ "SqlViewer_Main_Error_Text_First"));
+ m_Memory.showOutOfMemory();
+ System.err.println(Messages.getInstance().getString(
+ "SqlViewer_Main_Error_Text_Second"));
+ System.exit(-1);
}
+
+ // }
+ // catch (InterruptedException ex) {
+ // ex.printStackTrace();
+ // }
}
}
};
memMonitor.setPriority(Thread.MAX_PRIORITY);
memMonitor.start();
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
diff --git a/src/test/resources/wekarefs/weka/attributeSelection/WrapperSubsetEvalTest.ref b/src/test/resources/wekarefs/weka/attributeSelection/WrapperSubsetEvalTest.ref
index 3fb2603..9ddb80c 100644
--- a/src/test/resources/wekarefs/weka/attributeSelection/WrapperSubsetEvalTest.ref
+++ b/src/test/resources/wekarefs/weka/attributeSelection/WrapperSubsetEvalTest.ref
@@ -5,13 +5,13 @@
Search Method:
Greedy Stepwise (forwards).
Start set: no attributes
- Merit of best subset found: 0
+ Merit of best subset found: 1
Attribute Subset Evaluator (supervised, Class (nominal): 5 Class):
Wrapper Subset Evaluator
Learning scheme: weka.classifiers.trees.J48
Scheme options: -C 0.25 -M 2
- Accuracy estimation: classification error
+ Subset evaluation: classification accuracy
Number of folds for accuracy estimation: 5
Selected attributes: 1 : 1
diff --git a/src/test/resources/wekarefs/weka/classifiers/functions/GaussianProcessesTest.ref b/src/test/resources/wekarefs/weka/classifiers/functions/GaussianProcessesTest.ref
index 41ea488..1c9e34a 100644
--- a/src/test/resources/wekarefs/weka/classifiers/functions/GaussianProcessesTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/functions/GaussianProcessesTest.ref
@@ -11,14 +11,14 @@ NUM: 0.1216476559638977 0.6758340844092869 1.0
NUM: 1.174964651465416 1.0771035240739353 1.0
10 predictions
-NUM: 3.31347966E12 0.0 1.0
-NUM: 2.30363646E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 2.87171646E12 0.0 1.0
-NUM: 2.58763326E12 0.0 1.0
-NUM: 4.03932606E12 0.0 1.0
-NUM: 9.7826046E11 0.0 1.0
-NUM: 1.98810366E12 0.0 1.0
-NUM: 3.88155966E12 0.0 1.0
-NUM: 2.27210046E12 0.0 1.0
+NUM: 3.31347966E12 2.9833596557858984E12 1.0
+NUM: 2.30363646E12 2.378565625053778E12 1.0
+NUM: 2.84009406E12 2.7300543568634434E12 1.0
+NUM: 2.87171646E12 2.7493098958306846E12 1.0
+NUM: 2.58763326E12 2.568569758793188E12 1.0
+NUM: 4.03932606E12 3.174581057061477E12 1.0
+NUM: 9.7826046E11 1.725683612063846E12 1.0
+NUM: 1.98810366E12 2.1727604070114585E12 1.0
+NUM: 3.88155966E12 3.1557546800125503E12 1.0
+NUM: 2.27210046E12 2.35747180257288E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/functions/IsotonicRegressionTest.ref b/src/test/resources/wekarefs/weka/classifiers/functions/IsotonicRegressionTest.ref
index 3fa9434..f179904 100644
--- a/src/test/resources/wekarefs/weka/classifiers/functions/IsotonicRegressionTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/functions/IsotonicRegressionTest.ref
@@ -11,14 +11,14 @@ NUM: 1.0900637060403824 1.0771798491477966 1.0
NUM: 1.1143292635679245 1.0771798491477966 1.0
10 predictions
-NUM: 1.89340926E12 0.0 1.0
-NUM: 3.62909886E12 0.0 1.0
-NUM: 1.32532926E12 0.0 1.0
-NUM: 2.96632446E12 0.0 1.0
-NUM: 1.67248446E12 0.0 1.0
-NUM: 2.01963966E12 0.0 1.0
-NUM: 2.74548606E12 0.0 1.0
-NUM: 2.20894206E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 2.80855806E12 0.0 1.0
+NUM: 1.89340926E12 1.89340926E12 1.0
+NUM: 3.62909886E12 3.59747646E12 1.0
+NUM: 1.32532926E12 1.10449086E12 1.0
+NUM: 2.96632446E12 2.93478846E12 1.0
+NUM: 1.67248446E12 1.89340926E12 1.0
+NUM: 2.01963966E12 1.95648126E12 1.0
+NUM: 2.74548606E12 2.77702206E12 1.0
+NUM: 2.20894206E12 2.30363646E12 1.0
+NUM: 2.84009406E12 2.77702206E12 1.0
+NUM: 2.80855806E12 2.77702206E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/functions/LeastMedSqTest.ref b/src/test/resources/wekarefs/weka/classifiers/functions/LeastMedSqTest.ref
index 9f7beee..3997e47 100644
--- a/src/test/resources/wekarefs/weka/classifiers/functions/LeastMedSqTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/functions/LeastMedSqTest.ref
@@ -11,14 +11,14 @@ NUM: 0.09358982741832733 0.16483739111391021 1.0
NUM: 1.0427293479442596 1.185838778315307 1.0
10 predictions
-NUM: 2.80855806E12 0.0 1.0
-NUM: 2.58763326E12 0.0 1.0
-NUM: 1.54625406E12 0.0 1.0
-NUM: 2.61925566E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 1.04133246E12 0.0 1.0
-NUM: 3.43971006E12 0.0 1.0
-NUM: 2.80855806E12 0.0 1.0
-NUM: 1.83025086E12 0.0 1.0
-NUM: 1.29379326E12 0.0 1.0
+NUM: 2.80855806E12 2.8085580600004893E12 1.0
+NUM: 2.58763326E12 2.5876332583856445E12 1.0
+NUM: 1.54625406E12 1.5462540629474026E12 1.0
+NUM: 2.61925566E12 2.6192556586347554E12 1.0
+NUM: 2.84009406E12 2.8400940579933286E12 1.0
+NUM: 1.04133246E12 1.041332461423814E12 1.0
+NUM: 3.43971006E12 3.4397100567892363E12 1.0
+NUM: 2.80855806E12 2.808558058522171E12 1.0
+NUM: 1.83025086E12 1.8302508602628188E12 1.0
+NUM: 1.29379326E12 1.2937932622763335E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/functions/LinearRegressionTest.ref b/src/test/resources/wekarefs/weka/classifiers/functions/LinearRegressionTest.ref
index faba6d5..46547a7 100644
--- a/src/test/resources/wekarefs/weka/classifiers/functions/LinearRegressionTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/functions/LinearRegressionTest.ref
@@ -11,14 +11,14 @@ NUM: 0.09358982741832733 0.2182552828933523 1.0
NUM: 1.0427293479442596 1.1552771499517829 1.0
10 predictions
-NUM: 2.80855806E12 0.0 1.0
-NUM: 2.58763326E12 0.0 1.0
-NUM: 1.54625406E12 0.0 1.0
-NUM: 2.61925566E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 1.04133246E12 0.0 1.0
-NUM: 3.43971006E12 0.0 1.0
-NUM: 2.80855806E12 0.0 1.0
-NUM: 1.83025086E12 0.0 1.0
-NUM: 1.29379326E12 0.0 1.0
+NUM: 2.80855806E12 2.8085580597055015E12 1.0
+NUM: 2.58763326E12 2.5876332599510005E12 1.0
+NUM: 1.54625406E12 1.5462540611080254E12 1.0
+NUM: 2.61925566E12 2.619255659915878E12 1.0
+NUM: 2.84009406E12 2.8400940596704585E12 1.0
+NUM: 1.04133246E12 1.0413324616691511E12 1.0
+NUM: 3.43971006E12 3.439710059004154E12 1.0
+NUM: 2.80855806E12 2.8085580597055015E12 1.0
+NUM: 1.83025086E12 1.8302508607925725E12 1.0
+NUM: 1.29379326E12 1.2937932613885295E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/functions/PLSClassifierTest.ref b/src/test/resources/wekarefs/weka/classifiers/functions/PLSClassifierTest.ref
index 7b0770c..14e798c 100644
--- a/src/test/resources/wekarefs/weka/classifiers/functions/PLSClassifierTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/functions/PLSClassifierTest.ref
@@ -11,14 +11,14 @@ NUM: 1.129369854927063 2.96104849784504 1.0
NUM: 0.04425336420536041 2.2421452568416544 1.0
10 predictions
-NUM: 2.52456126E12 0.0 1.0
-NUM: 1.48318206E12 0.0 1.0
-NUM: 3.50286846E12 0.0 1.0
-NUM: 1.92494526E12 0.0 1.0
-NUM: 1.16756286E12 0.0 1.0
-NUM: 3.91309566E12 0.0 1.0
-NUM: 2.74548606E12 0.0 1.0
-NUM: 1.32532926E12 0.0 1.0
-NUM: 2.99794686E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
+NUM: 2.52456126E12 2.528585122827065E12 1.0
+NUM: 1.48318206E12 1.4868194168913804E12 1.0
+NUM: 3.50286846E12 3.501291819411203E12 1.0
+NUM: 1.92494526E12 1.9217826573221392E12 1.0
+NUM: 1.16756286E12 1.1701380480574395E12 1.0
+NUM: 3.91309566E12 3.910855297567234E12 1.0
+NUM: 2.74548606E12 2.744611885533327E12 1.0
+NUM: 1.32532926E12 1.3278535639800986E12 1.0
+NUM: 2.99794686E12 2.9979740540012656E12 1.0
+NUM: 2.84009406E12 2.8372775982657056E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/functions/PaceRegressionTest.ref b/src/test/resources/wekarefs/weka/classifiers/functions/PaceRegressionTest.ref
index 94a0fd6..bd3ee4e 100644
--- a/src/test/resources/wekarefs/weka/classifiers/functions/PaceRegressionTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/functions/PaceRegressionTest.ref
@@ -31,34 +31,34 @@ NUM: 1.111428126692772 1.0580873743492816 1.0
NUM: 0.11447009444236755 0.26710359999257005 1.0
30 predictions
-NUM: 1.95648126E12 0.0 1.0
-NUM: 2.27210046E12 0.0 1.0
-NUM: 1.60941246E12 0.0 1.0
-NUM: 3.88155966E12 0.0 1.0
-NUM: 2.05117566E12 0.0 1.0
-NUM: 9.4663806E11 0.0 1.0
-NUM: 3.59747646E12 0.0 1.0
-NUM: 2.99794686E12 0.0 1.0
-NUM: 3.81840126E12 0.0 1.0
-NUM: 1.19909886E12 0.0 1.0
-NUM: 3.97616766E12 0.0 1.0
-NUM: 3.75532926E12 0.0 1.0
-NUM: 2.08271166E12 0.0 1.0
-NUM: 3.88155966E12 0.0 1.0
-NUM: 2.30363646E12 0.0 1.0
-NUM: 3.09255486E12 0.0 1.0
-NUM: 3.37663806E12 0.0 1.0
-NUM: 3.47124606E12 0.0 1.0
-NUM: 3.91309566E12 0.0 1.0
-NUM: 3.56594046E12 0.0 1.0
-NUM: 1.29379326E12 0.0 1.0
-NUM: 1.45155966E12 0.0 1.0
-NUM: 1.10449086E12 0.0 1.0
-NUM: 3.02948286E12 0.0 1.0
-NUM: 3.66063486E12 0.0 1.0
-NUM: 3.72370686E12 0.0 1.0
-NUM: 1.89340926E12 0.0 1.0
-NUM: 1.73564286E12 0.0 1.0
-NUM: 2.80855806E12 0.0 1.0
-NUM: 1.23072126E12 0.0 1.0
+NUM: 1.95648126E12 1.9564812600000554E12 1.0
+NUM: 2.27210046E12 2.2721004600000903E12 1.0
+NUM: 1.60941246E12 1.609412459999926E12 1.0
+NUM: 3.88155966E12 3.8815596599999717E12 1.0
+NUM: 2.05117566E12 2.0511756600000042E12 1.0
+NUM: 9.4663806E11 9.46638060000085E11 1.0
+NUM: 3.59747646E12 3.597476459999947E12 1.0
+NUM: 2.99794686E12 2.9979468600000776E12 1.0
+NUM: 3.81840126E12 3.818401260000098E12 1.0
+NUM: 1.19909886E12 1.1990988600000142E12 1.0
+NUM: 3.97616766E12 3.97616765999995E12 1.0
+NUM: 3.75532926E12 3.755329259999973E12 1.0
+NUM: 2.08271166E12 2.0827116600000967E12 1.0
+NUM: 3.88155966E12 3.8815596599998794E12 1.0
+NUM: 2.30363646E12 2.3036364599999624E12 1.0
+NUM: 3.09255486E12 3.0925548600001084E12 1.0
+NUM: 3.37663806E12 3.3766380599998823E12 1.0
+NUM: 3.47124606E12 3.471246059999858E12 1.0
+NUM: 3.91309566E12 3.913095659999978E12 1.0
+NUM: 3.56594046E12 3.5659404599999966E12 1.0
+NUM: 1.29379326E12 1.293793259999924E12 1.0
+NUM: 1.45155966E12 1.4515596600000684E12 1.0
+NUM: 1.10449086E12 1.1044908600000552E12 1.0
+NUM: 3.02948286E12 3.0294828600000435E12 1.0
+NUM: 3.66063486E12 3.6606348599999844E12 1.0
+NUM: 3.72370686E12 3.723706860000097E12 1.0
+NUM: 1.89340926E12 1.8934092600000198E12 1.0
+NUM: 1.73564286E12 1.7356428600000842E12 1.0
+NUM: 2.80855806E12 2.8085580599999707E12 1.0
+NUM: 1.23072126E12 1.230721260000033E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/functions/RBFNetworkTest.ref b/src/test/resources/wekarefs/weka/classifiers/functions/RBFNetworkTest.ref
index d44c900..c55f1c8 100644
--- a/src/test/resources/wekarefs/weka/classifiers/functions/RBFNetworkTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/functions/RBFNetworkTest.ref
@@ -43,24 +43,24 @@ NOM: 0.0 0.0 1.0 0.9999999999271709 7.282904736370312E-11
NOM: 1.0 1.0 1.0 6.831981012411189E-7 0.9999993168018988
20 predictions
-NUM: 4.03932606E12 0.0 1.0
-NUM: 1.67248446E12 0.0 1.0
-NUM: 3.34501566E12 0.0 1.0
-NUM: 2.20894206E12 0.0 1.0
-NUM: 1.29379326E12 0.0 1.0
-NUM: 2.39833086E12 0.0 1.0
-NUM: 1.92494526E12 0.0 1.0
-NUM: 1.13602686E12 0.0 1.0
-NUM: 2.58763326E12 0.0 1.0
-NUM: 1.00979646E12 0.0 1.0
-NUM: 1.95648126E12 0.0 1.0
-NUM: 2.27210046E12 0.0 1.0
-NUM: 1.60941246E12 0.0 1.0
-NUM: 3.88155966E12 0.0 1.0
-NUM: 2.05117566E12 0.0 1.0
-NUM: 9.4663806E11 0.0 1.0
-NUM: 3.59747646E12 0.0 1.0
-NUM: 2.99794686E12 0.0 1.0
-NUM: 3.81840126E12 0.0 1.0
-NUM: 1.19909886E12 0.0 1.0
+NUM: 4.03932606E12 3.504791682394592E12 1.0
+NUM: 1.67248446E12 1.7587170843366736E12 1.0
+NUM: 3.34501566E12 3.491082552121102E12 1.0
+NUM: 2.20894206E12 1.841662646295225E12 1.0
+NUM: 1.29379326E12 1.758291029078164E12 1.0
+NUM: 2.39833086E12 2.0482895221613315E12 1.0
+NUM: 1.92494526E12 1.7686338897249868E12 1.0
+NUM: 1.13602686E12 1.758237868102078E12 1.0
+NUM: 2.58763326E12 2.5161265996131294E12 1.0
+NUM: 1.00979646E12 1.758224797170255E12 1.0
+NUM: 1.95648126E12 1.771427156559956E12 1.0
+NUM: 2.27210046E12 1.887181473434714E12 1.0
+NUM: 1.60941246E12 1.758522388114341E12 1.0
+NUM: 3.88155966E12 3.5044834777778364E12 1.0
+NUM: 2.05117566E12 1.767223964310025E12 1.0
+NUM: 9.4663806E11 1.7582218997336086E12 1.0
+NUM: 3.59747646E12 3.502137496453468E12 1.0
+NUM: 2.99794686E12 3.378702771268237E12 1.0
+NUM: 3.81840126E12 3.504249794765879E12 1.0
+NUM: 1.19909886E12 1.7582515642465112E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/functions/SMOregTest.ref b/src/test/resources/wekarefs/weka/classifiers/functions/SMOregTest.ref
index e1585f6..8f0e2d9 100644
--- a/src/test/resources/wekarefs/weka/classifiers/functions/SMOregTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/functions/SMOregTest.ref
@@ -11,14 +11,14 @@ NUM: 0.1216476559638977 0.14870767744827693 1.0
NUM: 1.174964651465416 1.1327354968149428 1.0
10 predictions
-NUM: 3.31347966E12 0.0 1.0
-NUM: 2.30363646E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 2.87171646E12 0.0 1.0
-NUM: 2.58763326E12 0.0 1.0
-NUM: 4.03932606E12 0.0 1.0
-NUM: 9.7826046E11 0.0 1.0
-NUM: 1.98810366E12 0.0 1.0
-NUM: 3.88155966E12 0.0 1.0
-NUM: 2.27210046E12 0.0 1.0
+NUM: 3.31347966E12 3.3114301329174307E12 1.0
+NUM: 2.30363646E12 2.305126273981909E12 1.0
+NUM: 2.84009406E12 2.839703674746011E12 1.0
+NUM: 2.87171646E12 2.871215243224169E12 1.0
+NUM: 2.58763326E12 2.5881277100122607E12 1.0
+NUM: 4.03932606E12 4.034732555822825E12 1.0
+NUM: 9.7826046E11 9.843955077199668E11 1.0
+NUM: 1.98810366E12 1.9906993666554924E12 1.0
+NUM: 3.88155966E12 3.877519102159674E12 1.0
+NUM: 2.27210046E12 2.273700802685777E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/functions/SimpleLinearRegressionTest.ref b/src/test/resources/wekarefs/weka/classifiers/functions/SimpleLinearRegressionTest.ref
index 971a0e9..5d0a92e 100644
--- a/src/test/resources/wekarefs/weka/classifiers/functions/SimpleLinearRegressionTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/functions/SimpleLinearRegressionTest.ref
@@ -11,14 +11,14 @@ NUM: 1.0900637060403824 1.0702937538918273 1.0
NUM: 1.1143292635679245 1.1048837501680633 1.0
10 predictions
-NUM: 1.89340926E12 0.0 1.0
-NUM: 3.62909886E12 0.0 1.0
-NUM: 1.32532926E12 0.0 1.0
-NUM: 2.96632446E12 0.0 1.0
-NUM: 1.67248446E12 0.0 1.0
-NUM: 2.01963966E12 0.0 1.0
-NUM: 2.74548606E12 0.0 1.0
-NUM: 2.20894206E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 2.80855806E12 0.0 1.0
+NUM: 1.89340926E12 1.893409259999948E12 1.0
+NUM: 3.62909886E12 3.6290988600000767E12 1.0
+NUM: 1.32532926E12 1.325329259999901E12 1.0
+NUM: 2.96632446E12 2.9663244600000557E12 1.0
+NUM: 1.67248446E12 1.6724844599998828E12 1.0
+NUM: 2.01963966E12 2.0196396600000522E12 1.0
+NUM: 2.74548606E12 2.745486059999946E12 1.0
+NUM: 2.20894206E12 2.2089420600000693E12 1.0
+NUM: 2.84009406E12 2.8400940600000596E12 1.0
+NUM: 2.80855806E12 2.8085580600000454E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/meta/AdditiveRegressionTest.ref b/src/test/resources/wekarefs/weka/classifiers/meta/AdditiveRegressionTest.ref
index cbf9f53..8e1127c 100644
--- a/src/test/resources/wekarefs/weka/classifiers/meta/AdditiveRegressionTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/meta/AdditiveRegressionTest.ref
@@ -11,14 +11,14 @@ NUM: 0.09358982741832733 0.1569500113720445 1.0
NUM: 1.0427293479442596 1.1908077480679315 1.0
10 predictions
-NUM: 2.80855806E12 0.0 1.0
-NUM: 2.58763326E12 0.0 1.0
-NUM: 1.54625406E12 0.0 1.0
-NUM: 2.61925566E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 1.04133246E12 0.0 1.0
-NUM: 3.43971006E12 0.0 1.0
-NUM: 2.80855806E12 0.0 1.0
-NUM: 1.83025086E12 0.0 1.0
-NUM: 1.29379326E12 0.0 1.0
+NUM: 2.80855806E12 2.1065957171045918E12 1.0
+NUM: 2.58763326E12 1.6823932606349207E12 1.0
+NUM: 1.54625406E12 1.8899102771045918E12 1.0
+NUM: 2.61925566E12 1.6823932606349207E12 1.0
+NUM: 2.84009406E12 1.6823932606349207E12 1.0
+NUM: 1.04133246E12 1.3380529206349207E12 1.0
+NUM: 3.43971006E12 3.551282668968254E12 1.0
+NUM: 2.80855806E12 1.6823932606349207E12 1.0
+NUM: 1.83025086E12 1.4657078206349207E12 1.0
+NUM: 1.29379326E12 1.8669016772534014E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/meta/BaggingTest.ref b/src/test/resources/wekarefs/weka/classifiers/meta/BaggingTest.ref
index d9a0c60..8c686be 100644
--- a/src/test/resources/wekarefs/weka/classifiers/meta/BaggingTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/meta/BaggingTest.ref
@@ -23,14 +23,14 @@ NOM: 0.0 0.0 1.0 0.6700000000000002 0.32999999999999996
NOM: 1.0 1.0 1.0 0.06999999999999999 0.93
10 predictions
-NUM: 2.80855806E12 NaN 1.0
-NUM: 2.58763326E12 NaN 1.0
-NUM: 1.54625406E12 NaN 1.0
-NUM: 2.61925566E12 NaN 1.0
-NUM: 2.84009406E12 NaN 1.0
-NUM: 1.04133246E12 NaN 1.0
-NUM: 3.43971006E12 NaN 1.0
-NUM: 2.80855806E12 NaN 1.0
-NUM: 1.83025086E12 NaN 1.0
-NUM: 1.29379326E12 NaN 1.0
+NUM: 2.80855806E12 2.6650858817142856E12 1.0
+NUM: 2.58763326E12 2.229992761714286E12 1.0
+NUM: 1.54625406E12 1.968647737714286E12 1.0
+NUM: 2.61925566E12 2.4544426817142856E12 1.0
+NUM: 2.84009406E12 2.6650858817142856E12 1.0
+NUM: 1.04133246E12 1.968647737714286E12 1.0
+NUM: 3.43971006E12 3.411237516E12 1.0
+NUM: 2.80855806E12 2.6650858817142856E12 1.0
+NUM: 1.83025086E12 2.029919737714286E12 1.0
+NUM: 1.29379326E12 1.968647737714286E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/meta/RandomSubSpaceTest.ref b/src/test/resources/wekarefs/weka/classifiers/meta/RandomSubSpaceTest.ref
index 9ffd351..2c6a199 100644
--- a/src/test/resources/wekarefs/weka/classifiers/meta/RandomSubSpaceTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/meta/RandomSubSpaceTest.ref
@@ -23,14 +23,14 @@ NOM: 0.0 0.0 1.0 0.76 0.24
NOM: 1.0 1.0 1.0 0.06 0.9400000000000001
10 predictions
-NUM: 2.80855806E12 NaN 1.0
-NUM: 2.58763326E12 NaN 1.0
-NUM: 1.54625406E12 NaN 1.0
-NUM: 2.61925566E12 NaN 1.0
-NUM: 2.84009406E12 NaN 1.0
-NUM: 1.04133246E12 NaN 1.0
-NUM: 3.43971006E12 NaN 1.0
-NUM: 2.80855806E12 NaN 1.0
-NUM: 1.83025086E12 NaN 1.0
-NUM: 1.29379326E12 NaN 1.0
+NUM: 2.80855806E12 2.52587166E12 1.0
+NUM: 2.58763326E12 2.48721054E12 1.0
+NUM: 1.54625406E12 2.20635726E12 1.0
+NUM: 2.61925566E12 2.48721054E12 1.0
+NUM: 2.84009406E12 2.6826027E12 1.0
+NUM: 1.04133246E12 2.3630883E12 1.0
+NUM: 3.43971006E12 3.0113259E12 1.0
+NUM: 2.80855806E12 2.6826027E12 1.0
+NUM: 1.83025086E12 2.48721054E12 1.0
+NUM: 1.29379326E12 2.20635726E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/meta/RegressionByDiscretizationTest.ref b/src/test/resources/wekarefs/weka/classifiers/meta/RegressionByDiscretizationTest.ref
index de4c339..c678fbe 100644
--- a/src/test/resources/wekarefs/weka/classifiers/meta/RegressionByDiscretizationTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/meta/RegressionByDiscretizationTest.ref
@@ -11,14 +11,14 @@ NUM: 0.09358982741832733 0.12408751621842384 1.0
NUM: 1.0427293479442596 1.1861572712659836 1.0
10 predictions
-NUM: 2.80855806E12 0.0 1.0
-NUM: 2.58763326E12 0.0 1.0
-NUM: 1.54625406E12 0.0 1.0
-NUM: 2.61925566E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 1.04133246E12 0.0 1.0
-NUM: 3.43971006E12 0.0 1.0
-NUM: 2.80855806E12 0.0 1.0
-NUM: 1.83025086E12 0.0 1.0
-NUM: 1.29379326E12 0.0 1.0
+NUM: 2.80855806E12 2.87167326E12 1.0
+NUM: 2.58763326E12 2.87167326E12 1.0
+NUM: 1.54625406E12 1.95652446E12 1.0
+NUM: 2.61925566E12 2.87167326E12 1.0
+NUM: 2.84009406E12 2.87167326E12 1.0
+NUM: 1.04133246E12 1.45161726E12 1.0
+NUM: 3.43971006E12 3.80788926E12 1.0
+NUM: 2.80855806E12 2.87167326E12 1.0
+NUM: 1.83025086E12 1.95652446E12 1.0
+NUM: 1.29379326E12 1.45161726E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/rules/M5RulesTest.ref b/src/test/resources/wekarefs/weka/classifiers/rules/M5RulesTest.ref
index d204f55..039b51f 100644
--- a/src/test/resources/wekarefs/weka/classifiers/rules/M5RulesTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/rules/M5RulesTest.ref
@@ -11,14 +11,14 @@ NUM: 0.09358982741832733 0.06831368814303418 1.0
NUM: 1.0427293479442596 1.1226325106140949 1.0
10 predictions
-NUM: 2.80855806E12 0.0 1.0
-NUM: 2.58763326E12 0.0 1.0
-NUM: 1.54625406E12 0.0 1.0
-NUM: 2.61925566E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 1.04133246E12 0.0 1.0
-NUM: 3.43971006E12 0.0 1.0
-NUM: 2.80855806E12 0.0 1.0
-NUM: 1.83025086E12 0.0 1.0
-NUM: 1.29379326E12 0.0 1.0
+NUM: 2.80855806E12 2.808558059705502E12 1.0
+NUM: 2.58763326E12 2.587633259951001E12 1.0
+NUM: 1.54625406E12 1.5462540611080247E12 1.0
+NUM: 2.61925566E12 2.6192556599158784E12 1.0
+NUM: 2.84009406E12 2.8400940596704595E12 1.0
+NUM: 1.04133246E12 1.0413324616691498E12 1.0
+NUM: 3.43971006E12 3.4397100590041553E12 1.0
+NUM: 2.80855806E12 2.808558059705502E12 1.0
+NUM: 1.83025086E12 1.830250860792572E12 1.0
+NUM: 1.29379326E12 1.2937932613885286E12 1.0
diff --git a/src/test/resources/wekarefs/weka/classifiers/trees/M5PTest.ref b/src/test/resources/wekarefs/weka/classifiers/trees/M5PTest.ref
index d204f55..039b51f 100644
--- a/src/test/resources/wekarefs/weka/classifiers/trees/M5PTest.ref
+++ b/src/test/resources/wekarefs/weka/classifiers/trees/M5PTest.ref
@@ -11,14 +11,14 @@ NUM: 0.09358982741832733 0.06831368814303418 1.0
NUM: 1.0427293479442596 1.1226325106140949 1.0
10 predictions
-NUM: 2.80855806E12 0.0 1.0
-NUM: 2.58763326E12 0.0 1.0
-NUM: 1.54625406E12 0.0 1.0
-NUM: 2.61925566E12 0.0 1.0
-NUM: 2.84009406E12 0.0 1.0
-NUM: 1.04133246E12 0.0 1.0
-NUM: 3.43971006E12 0.0 1.0
-NUM: 2.80855806E12 0.0 1.0
-NUM: 1.83025086E12 0.0 1.0
-NUM: 1.29379326E12 0.0 1.0
+NUM: 2.80855806E12 2.808558059705502E12 1.0
+NUM: 2.58763326E12 2.587633259951001E12 1.0
+NUM: 1.54625406E12 1.5462540611080247E12 1.0
+NUM: 2.61925566E12 2.6192556599158784E12 1.0
+NUM: 2.84009406E12 2.8400940596704595E12 1.0
+NUM: 1.04133246E12 1.0413324616691498E12 1.0
+NUM: 3.43971006E12 3.4397100590041553E12 1.0
+NUM: 2.80855806E12 2.808558059705502E12 1.0
+NUM: 1.83025086E12 1.830250860792572E12 1.0
+NUM: 1.29379326E12 1.2937932613885286E12 1.0
diff --git a/wekadocs/README b/wekadocs/README
index 7153a48..74956df 100644
--- a/wekadocs/README
+++ b/wekadocs/README
@@ -4,12 +4,12 @@
README
======
- WEKA 3.6.10
- 31 July 2013
+ WEKA 3.6.11
+ 24 April 2014
Java Programs for Machine Learning
- Copyright (C) 1998-2013 University of Waikato
+ Copyright (C) 1998-2014 University of Waikato
web: http://www.cs.waikato.ac.nz/~ml/weka
diff --git a/wekadocs/manual/manual.tex b/wekadocs/manual/manual.tex
index aace8e0..47ea4ef 100644
--- a/wekadocs/manual/manual.tex
+++ b/wekadocs/manual/manual.tex
@@ -14,7 +14,7 @@
% Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
%
-% Version: $Revision: 9935 $
+% Version: $Revision: 10665 $
\documentclass[a4paper]{book}
@@ -26,7 +26,7 @@
\input{hyphenation}
\input{extensions}
-\title{\epsfig{file=images/coat_of_arms.eps,width=10cm}\vspace{3cm}\\WEKA Manual\\for Version 3-6-10}
+\title{\epsfig{file=images/coat_of_arms.eps,width=10cm}\vspace{3cm}\\WEKA Manual\\for Version 3-6-11}
\author{Remco R. Bouckaert\\Eibe Frank\\Mark Hall\\Richard Kirkby\\Peter Reutemann\\Alex Seewald\\David Scuse}
\setcounter{secnumdepth}{3}
@@ -39,7 +39,7 @@
\thispagestyle{empty}
\center
\begin{table}[b]
-\copyright 2002-2013 \\
+\copyright 2002-2014 \\
\\
University of Waikato, Hamilton, New Zealand \\
Alex Seewald (original Commnd-line primer) \\
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-java/weka.git
More information about the pkg-java-commits
mailing list