index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/DictionaryBuilder.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* DictionaryBuilder.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import weka.core.stemmers.NullStemmer;
import weka.core.stemmers.Stemmer;
import weka.core.stopwords.Null;
import weka.core.stopwords.StopwordsHandler;
import weka.core.tokenizers.Tokenizer;
import weka.core.tokenizers.WordTokenizer;
import weka.gui.ProgrammaticProperty;
/**
* Class for building and maintaining a dictionary of terms. Has methods for
* loading, saving and aggregating dictionaries. Supports loading/saving in
* binary and textual format. Textual format is expected to have one or two
* comma separated values per line of the format.
* <p>
*
* <pre>
* term [,doc_count]
* </pre>
*
* where
*
* <pre>
* doc_count
* </pre>
*
* is the number of documents that the term has occurred in.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class DictionaryBuilder implements Aggregateable<DictionaryBuilder>,
OptionHandler, Serializable {
/** For serialization */
private static final long serialVersionUID = 5579506627960356012L;
/** Input structure */
protected Instances m_inputFormat;
/** Output structure */
protected Instances m_outputFormat;
/** Holds the dictionaries (one per class) that are compiled while processing */
protected Map<String, int[]>[] m_dictsPerClass;
/**
* Holds the final dictionary that is consolidated across classes and pruned
* according to m_wordsToKeep. First element of array contains the index of
* the word. The second (optional) element contains the document count for the
* word (i.e. number of training docs the word occurs in).
*/
protected Map<String, int[]> m_consolidatedDict;
/** Holds the tokenized input vector */
protected transient Map<String, int[]> m_inputVector;
/**
* True if the final number of words to keep should not be applied on a per
* class basis
*/
protected boolean m_doNotOperateOnPerClassBasis;
/** Whether to output frequency counts instead of presence indicators */
protected boolean m_outputCounts;
/** True if all tokens should be downcased. */
protected boolean m_lowerCaseTokens;
/** the stemming algorithm. */
protected Stemmer m_stemmer = new NullStemmer();
/** Stopword handler to use. */
protected StopwordsHandler m_stopwordsHandler = new Null();
/**
* The default number of words (per class if there is a class attribute
* assigned) to attempt to keep.
*/
protected int m_wordsToKeep = 1000;
/**
* Prune dictionary (per class) of low freq terms after every x documents. 0 =
* no periodic pruning
*/
protected long m_periodicPruneRate;
/** Minimum frequency to retain dictionary entries */
protected int m_minFrequency = 1;
/** Count of input vectors seen */
protected int m_count = 0;
/** the tokenizer algorithm to use. */
protected Tokenizer m_tokenizer = new WordTokenizer();
/** Range of columns to convert to word vectors. */
protected Range m_selectedRange = new Range("first-last");
/** Holds the class index */
protected int m_classIndex = -1;
/** Number of classes */
protected int m_numClasses = 1;
/** A String prefix for the attribute names. */
protected String m_Prefix = "";
/** True if the TF transform is to be applied */
protected boolean m_TFTransform;
/** True if the IDF transform is to be applied */
protected boolean m_IDFTransform;
/** Whether to normalize to average length of training docs */
protected boolean m_normalize;
/** The sum of document lengths */
protected double m_docLengthSum;
/** The average document length */
protected double m_avgDocLength;
/** Whether to keep the dictionary(s) sorted alphabetically */
protected boolean m_sortDictionary;
/** True if the input data contains string attributes to convert */
protected boolean m_inputContainsStringAttributes;
/**
* Set the average document length to use when normalizing
*
* @param averageDocLength the average document length to use
*/
@ProgrammaticProperty
public void setAverageDocLength(double averageDocLength) {
m_avgDocLength = averageDocLength;
}
/**
* Get the average document length to use when normalizing
*
* @return the average document length
*/
public double getAverageDocLength() {
return m_avgDocLength;
}
/**
* Tip text for this property
*
* @return the tip text for this property
*/
public String sortDictionaryTipText() {
return "Sort the dictionary alphabetically";
}
/**
* Set whether to keep the dictionary sorted alphabetically as it is built.
* Setting this to true uses a TreeMap internally (which is slower than the
* default unsorted LinkedHashMap).
*
* @param sortDictionary true to keep the dictionary sorted alphabetically
*/
public void setSortDictionary(boolean sortDictionary) {
m_sortDictionary = sortDictionary;
}
/**
* Get whether to keep the dictionary sorted alphabetically as it is built.
* Setting this to true uses a TreeMap internally (which is slower than the
* default unsorted LinkedHashMap).
*
* @return true to keep the dictionary sorted alphabetically
*/
public boolean getSortDictionary() {
return m_sortDictionary;
}
/**
* Gets whether output instances contain 0 or 1 indicating word presence, or
* word counts.
*
* @return true if word counts should be output.
*/
public boolean getOutputWordCounts() {
return m_outputCounts;
}
/**
* Sets whether output instances contain 0 or 1 indicating word presence, or
* word counts.
*
* @param outputWordCounts true if word counts should be output.
*/
public void setOutputWordCounts(boolean outputWordCounts) {
m_outputCounts = outputWordCounts;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String outputWordCountsTipText() {
return "Output word counts rather than boolean 0 or 1"
+ "(indicating presence or absence of a word).";
}
/**
* Get the value of m_SelectedRange.
*
* @return Value of m_SelectedRange.
*/
public Range getSelectedRange() {
return m_selectedRange;
}
/**
* Set the value of m_SelectedRange.
*
* @param newSelectedRange Value to assign to m_SelectedRange.
*/
public void setSelectedRange(String newSelectedRange) {
m_selectedRange = new Range(newSelectedRange);
}
/**
* Returns the tip text for this property.
*
* @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."
+ " 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\".";
}
/**
* Gets the current range selection.
*
* @return a string containing a comma separated list of ranges
*/
public String getAttributeIndices() {
return m_selectedRange.getRanges();
}
/**
* Sets which attributes are to be worked on.
*
* @param rangeList a string representing the list of attributes. Since the
* string will typically come from a user, attributes are indexed
* from 1. <br>
* eg: first-3,5,6-last
* @throws IllegalArgumentException if an invalid range list is supplied
*/
public void setAttributeIndices(String rangeList) {
m_selectedRange.setRanges(rangeList);
}
/**
* Sets which attributes are to be processed.
*
* @param attributes an array containing indexes of attributes to process.
* Since the array will typically come from a program, attributes are
* indexed from 0.
* @throws IllegalArgumentException if an invalid set of ranges is supplied
*/
public void setAttributeIndicesArray(int[] attributes) {
setAttributeIndices(Range.indicesToRangeList(attributes));
}
/**
* Returns the tip text for this property.
*
* @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"
+ " attributes in the range will be worked on; if"
+ " true, only non-selected attributes will be processed.";
}
/**
* Gets whether the supplied columns are to be processed or skipped.
*
* @return true if the supplied columns will be kept
*/
public boolean getInvertSelection() {
return m_selectedRange.getInvert();
}
/**
* Sets whether selected columns should be processed or skipped.
*
* @param invert the new invert setting
*/
public void setInvertSelection(boolean invert) {
m_selectedRange.setInvert(invert);
}
/**
* Gets the number of words (per class if there is a class attribute assigned)
* to attempt to keep.
*
* @return the target number of words in the output vector (per class if
* assigned).
*/
public int getWordsToKeep() {
return m_wordsToKeep;
}
/**
* Sets the number of words (per class if there is a class attribute assigned)
* to attempt to keep.
*
* @param newWordsToKeep the target number of words in the output vector (per
* class if assigned).
*/
public void setWordsToKeep(int newWordsToKeep) {
m_wordsToKeep = newWordsToKeep;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String wordsToKeepTipText() {
return "The number of words (per class if there is a class attribute "
+ "assigned) to attempt to keep.";
}
/**
* Gets the rate (number of instances) at which the dictionary is periodically
* pruned.
*
* @return the rate at which the dictionary is periodically pruned
*/
public long getPeriodicPruning() {
return m_periodicPruneRate;
}
/**
* Sets the rate (number of instances) at which the dictionary is periodically
* pruned
*
*
* @param newPeriodicPruning the rate at which the dictionary is periodically
* pruned
*/
public void setPeriodicPruning(long newPeriodicPruning) {
m_periodicPruneRate = newPeriodicPruning;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String periodicPruningTipText() {
return "Specify the rate (x% of the input dataset) at which to periodically prune the dictionary. "
+ "wordsToKeep prunes after creating a full dictionary. You may not have enough "
+ "memory for this approach.";
}
/**
* Gets whether if the word frequencies should be transformed into log(1+fij)
* where fij is the frequency of word i in document(instance) j.
*
* @return true if word frequencies are to be transformed.
*/
public boolean getTFTransform() {
return m_TFTransform;
}
/**
* Sets whether if the word frequencies should be transformed into log(1+fij)
* where fij is the frequency of word i in document(instance) j.
*
* @param TFTransform true if word frequencies are to be transformed.
*/
public void setTFTransform(boolean TFTransform) {
this.m_TFTransform = TFTransform;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String TFTransformTipText() {
return "Sets whether if the word frequencies should be transformed into:\n "
+ " log(1+fij) \n"
+ " where fij is the frequency of word i in document (instance) j.";
}
/**
* Get the attribute name prefix.
*
* @return The current attribute name prefix.
*/
public String getAttributeNamePrefix() {
return m_Prefix;
}
/**
* Set the attribute name prefix.
*
* @param newPrefix String to use as the attribute name prefix.
*/
public void setAttributeNamePrefix(String newPrefix) {
m_Prefix = newPrefix;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String attributeNamePrefixTipText() {
return "Prefix for the created attribute names. " + "(default: \"\")";
}
/**
* Sets whether if the word frequencies in a document should be transformed
* into: <br>
* fij*log(num of Docs/num of Docs with word i) <br>
* where fij is the frequency of word i in document(instance) j.
*
* @return true if the word frequencies are to be transformed.
*/
public boolean getIDFTransform() {
return this.m_IDFTransform;
}
/**
* Sets whether if the word frequencies in a document should be transformed
* into: <br>
* fij*log(num of Docs/num of Docs with word i) <br>
* where fij is the frequency of word i in document(instance) j.
*
* @param IDFTransform true if the word frequecies are to be transformed
*/
public void setIDFTransform(boolean IDFTransform) {
this.m_IDFTransform = IDFTransform;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String IDFTransformTipText() {
return "Sets whether if the word frequencies in a document should be "
+ "transformed into: \n"
+ " fij*log(num of Docs/num of Docs with word i) \n"
+ " where fij is the frequency of word i in document (instance) j.";
}
/**
* Get whether word frequencies for a document should be normalized
*
* @return true if word frequencies should be normalized
*/
public boolean getNormalize() {
return m_normalize;
}
/**
* Set whether word frequencies for a document should be normalized
*
* @param n true if word frequencies should be normalized
*/
public void setNormalize(boolean n) {
m_normalize = n;
}
/**
* Tip text for this property
*
* @return the tip text for this property
*/
public String normalizeTipText() {
return "Whether word frequencies for a document (instance) should "
+ "be normalized or not";
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String normalizeDocLengthTipText() {
return "Sets whether if the word frequencies for a document (instance) "
+ "should be normalized or not.";
}
/**
* Gets whether if the tokens are to be downcased or not.
*
* @return true if the tokens are to be downcased.
*/
public boolean getLowerCaseTokens() {
return this.m_lowerCaseTokens;
}
/**
* Sets whether if the tokens are to be downcased or not. (Doesn't affect
* non-alphabetic characters in tokens).
*
* @param downCaseTokens should be true if only lower case tokens are to be
* formed.
*/
public void setLowerCaseTokens(boolean downCaseTokens) {
this.m_lowerCaseTokens = downCaseTokens;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String lowerCaseTokensTipText() {
return "If set then all the word tokens are converted to lower case "
+ "before being added to the dictionary.";
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String doNotOperateOnPerClassBasisTipText() {
return "If this is set, the maximum number of words and the "
+ "minimum term frequency is not enforced on a per-class "
+ "basis but based on the documents in all the classes "
+ "(even if a class attribute is set).";
}
/**
* Get the DoNotOperateOnPerClassBasis value.
*
* @return the DoNotOperateOnPerClassBasis value.
*/
public boolean getDoNotOperateOnPerClassBasis() {
return m_doNotOperateOnPerClassBasis;
}
/**
* Set the DoNotOperateOnPerClassBasis value.
*
* @param newDoNotOperateOnPerClassBasis The new DoNotOperateOnPerClassBasis
* value.
*/
public void setDoNotOperateOnPerClassBasis(
boolean newDoNotOperateOnPerClassBasis) {
this.m_doNotOperateOnPerClassBasis = newDoNotOperateOnPerClassBasis;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String minTermFreqTipText() {
return "Sets the minimum term frequency. This is enforced "
+ "on a per-class basis.";
}
/**
* Get the MinTermFreq value.
*
* @return the MinTermFreq value.
*/
public int getMinTermFreq() {
return m_minFrequency;
}
/**
* Set the MinTermFreq value.
*
* @param newMinTermFreq The new MinTermFreq value.
*/
public void setMinTermFreq(int newMinTermFreq) {
m_minFrequency = newMinTermFreq;
}
/**
* Returns the current stemming algorithm, null if none is used.
*
* @return the current stemming algorithm, null if none set
*/
public Stemmer getStemmer() {
return m_stemmer;
}
/**
* the stemming algorithm to use, null means no stemming at all (i.e., the
* NullStemmer is used).
*
* @param value the configured stemming algorithm, or null
* @see NullStemmer
*/
public void setStemmer(Stemmer value) {
if (value != null) {
m_stemmer = value;
} else {
m_stemmer = new NullStemmer();
}
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String stemmerTipText() {
return "The stemming algorithm to use on the words.";
}
/**
* Gets the stopwords handler.
*
* @return the stopwords handler
*/
public StopwordsHandler getStopwordsHandler() {
return m_stopwordsHandler;
}
/**
* Sets the stopwords handler to use.
*
* @param value the stopwords handler, if null, Null is used
*/
public void setStopwordsHandler(StopwordsHandler value) {
if (value != null) {
m_stopwordsHandler = value;
} else {
m_stopwordsHandler = new Null();
}
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String stopwordsHandlerTipText() {
return "The stopwords handler to use (Null means no stopwords are used).";
}
/**
* Returns the current tokenizer algorithm.
*
* @return the current tokenizer algorithm
*/
public Tokenizer getTokenizer() {
return m_tokenizer;
}
/**
* the tokenizer algorithm to use.
*
* @param value the configured tokenizing algorithm
*/
public void setTokenizer(Tokenizer value) {
m_tokenizer = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String tokenizerTipText() {
return "The tokenizing algorithm to use on the strings.";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result
.addElement(new Option(
"\tOutput word counts rather than boolean word presence.\n", "C", 0,
"-C"));
result.addElement(new Option(
"\tSpecify list of string attributes to convert to words (as weka Range).\n"
+ "\t(default: select all string attributes)", "R", 1,
"-R <index1,index2-index4,...>"));
result.addElement(new Option("\tInvert matching sense of column indexes.",
"V", 0, "-V"));
result.addElement(new Option(
"\tSpecify a prefix for the created attribute names.\n"
+ "\t(default: \"\")", "P", 1, "-P <attribute name prefix>"));
result.addElement(new Option(
"\tSpecify approximate number of word fields to create.\n"
+ "\tSurplus words will be discarded..\n" + "\t(default: 1000)", "W",
1, "-W <number of words to keep>"));
result
.addElement(new Option(
"\tSpecify the rate (e.g., every x instances) at which to periodically prune the dictionary.\n"
+ "\t-W prunes after creating a full dictionary. You may not have enough memory for this approach.\n"
+ "\t(default: no periodic pruning)", "prune-rate", 1,
"-prune-rate <every x instances>"));
result
.addElement(new Option(
"\tTransform the word frequencies into log(1+fij)\n"
+ "\twhere fij is the frequency of word i in jth document(instance).\n",
"T", 0, "-T"));
result.addElement(new Option("\tTransform each word frequency into:\n"
+ "\tfij*log(num of Documents/num of documents containing word i)\n"
+ "\t where fij if frequency of word i in jth document(instance)", "I",
0, "-I"));
result
.addElement(new Option(
"\tWhether to 0=not normalize/1=normalize all data/2=normalize test data only\n"
+ "\tto average length of training documents "
+ "(default 0=don\'t normalize).", "N", 1, "-N"));
result.addElement(new Option("\tConvert all tokens to lowercase before "
+ "adding to the dictionary.", "L", 0, "-L"));
result.addElement(new Option(
"\tThe stopwords handler to use (default Null).", "-stopwords-handler",
1, "-stopwords-handler"));
result.addElement(new Option(
"\tThe stemming algorithm (classname plus parameters) to use.",
"stemmer", 1, "-stemmer <spec>"));
result.addElement(new Option("\tThe minimum term frequency (default = 1).",
"M", 1, "-M <int>"));
result.addElement(new Option(
"\tIf this is set, the maximum number of words and the \n"
+ "\tminimum term frequency is not enforced on a per-class \n"
+ "\tbasis but based on the documents in all the classes \n"
+ "\t(even if a class attribute is set).", "O", 0, "-O"));
result.addElement(new Option(
"\tThe tokenizing algorihtm (classname plus parameters) to use.\n"
+ "\t(default: " + WordTokenizer.class.getName() + ")", "tokenizer", 1,
"-tokenizer <spec>"));
return result.elements();
}
/**
* Gets the current settings of the DictionaryBuilder
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-R");
result.add(getSelectedRange().getRanges());
if (getInvertSelection()) {
result.add("-V");
}
if (!"".equals(getAttributeNamePrefix())) {
result.add("-P");
result.add(getAttributeNamePrefix());
}
result.add("-W");
result.add(String.valueOf(getWordsToKeep()));
result.add("-prune-rate");
result.add(String.valueOf(getPeriodicPruning()));
if (getOutputWordCounts()) {
result.add("-C");
}
if (getTFTransform()) {
result.add("-T");
}
if (getIDFTransform()) {
result.add("-I");
}
if (getNormalize()) {
result.add("-N");
}
if (getLowerCaseTokens()) {
result.add("-L");
}
if (getStemmer() != null) {
result.add("-stemmer");
String spec = getStemmer().getClass().getName();
if (getStemmer() instanceof OptionHandler) {
spec +=
" " + Utils.joinOptions(((OptionHandler) getStemmer()).getOptions());
}
result.add(spec.trim());
}
if (getStopwordsHandler() != null) {
result.add("-stopwords-handler");
String spec = getStopwordsHandler().getClass().getName();
if (getStopwordsHandler() instanceof OptionHandler) {
spec +=
" "
+ Utils.joinOptions(((OptionHandler) getStopwordsHandler())
.getOptions());
}
result.add(spec.trim());
}
result.add("-M");
result.add(String.valueOf(getMinTermFreq()));
if (getDoNotOperateOnPerClassBasis()) {
result.add("-O");
}
result.add("-tokenizer");
String spec = getTokenizer().getClass().getName();
spec +=
" " + Utils.joinOptions(((OptionHandler) getTokenizer()).getOptions());
result.add(spec.trim());
return result.toArray(new String[result.size()]);
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -C
* Output word counts rather than boolean word presence.
* </pre>
*
* <pre>
* -R <index1,index2-index4,...>
* Specify list of string attributes to convert to words (as weka Range).
* (default: select all string attributes)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indexes.
* </pre>
*
* <pre>
* -P <attribute name prefix>
* Specify a prefix for the created attribute names.
* (default: "")
* </pre>
*
* <pre>
* -W <number of words to keep>
* Specify approximate number of word fields to create.
* Surplus words will be discarded..
* (default: 1000)
* </pre>
*
* <pre>
* -prune-rate <rate as a percentage of dataset>
* Specify the rate (e.g., every 10% of the input dataset) at which to periodically prune the dictionary.
* -W prunes after creating a full dictionary. You may not have enough memory for this approach.
* (default: no periodic pruning)
* </pre>
*
* <pre>
* -T
* Transform the word frequencies into log(1+fij)
* where fij is the frequency of word i in jth document(instance).
* </pre>
*
* <pre>
* -I
* Transform each word frequency into:
* fij*log(num of Documents/num of documents containing word i)
* where fij if frequency of word i in jth document(instance)
* </pre>
*
* <pre>
* -N
* Whether to 0=not normalize/1=normalize all data/2=normalize test data only
* to average length of training documents (default 0=don't normalize).
* </pre>
*
* <pre>
* -L
* Convert all tokens to lowercase before adding to the dictionary.
* </pre>
*
* <pre>
* -stopwords-handler
* The stopwords handler to use (default Null).
* </pre>
*
* <pre>
* -stemmer <spec>
* The stemming algorithm (classname plus parameters) to use.
* </pre>
*
* <pre>
* -M <int>
* The minimum term frequency (default = 1).
* </pre>
*
* <pre>
* -O
* If this is set, the maximum number of words and the
* minimum term frequency is not enforced on a per-class
* basis but based on the documents in all the classes
* (even if a class attribute is set).
* </pre>
*
* <pre>
* -tokenizer <spec>
* The tokenizing algorihtm (classname plus parameters) to use.
* (default: weka.core.tokenizers.WordTokenizer)
* </pre>
*
* <!-- 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 value = Utils.getOption('R', options);
if (value.length() != 0) {
setSelectedRange(value);
} else {
setSelectedRange("first-last");
}
setInvertSelection(Utils.getFlag('V', options));
value = Utils.getOption('P', options);
if (value.length() != 0) {
setAttributeNamePrefix(value);
} else {
setAttributeNamePrefix("");
}
value = Utils.getOption('W', options);
if (value.length() != 0) {
setWordsToKeep(Integer.valueOf(value).intValue());
} else {
setWordsToKeep(1000);
}
value = Utils.getOption("prune-rate", options);
if (value.length() > 0) {
setPeriodicPruning(Integer.parseInt(value));
} else {
setPeriodicPruning(-1);
}
value = Utils.getOption('M', options);
if (value.length() != 0) {
setMinTermFreq(Integer.valueOf(value).intValue());
} else {
setMinTermFreq(1);
}
setOutputWordCounts(Utils.getFlag('C', options));
setTFTransform(Utils.getFlag('T', options));
setIDFTransform(Utils.getFlag('I', options));
setDoNotOperateOnPerClassBasis(Utils.getFlag('O', options));
setNormalize(Utils.getFlag('N', options));
setLowerCaseTokens(Utils.getFlag('L', options));
String stemmerString = Utils.getOption("stemmer", options);
if (stemmerString.length() == 0) {
setStemmer(null);
} else {
String[] stemmerSpec = Utils.splitOptions(stemmerString);
if (stemmerSpec.length == 0) {
throw new Exception("Invalid stemmer specification string");
}
String stemmerName = stemmerSpec[0];
stemmerSpec[0] = "";
Stemmer stemmer =
(Stemmer) Utils.forName(weka.core.stemmers.Stemmer.class, stemmerName,
stemmerSpec);
setStemmer(stemmer);
}
String stopwordsHandlerString =
Utils.getOption("stopwords-handler", options);
if (stopwordsHandlerString.length() == 0) {
setStopwordsHandler(null);
} else {
String[] stopwordsHandlerSpec =
Utils.splitOptions(stopwordsHandlerString);
if (stopwordsHandlerSpec.length == 0) {
throw new Exception("Invalid StopwordsHandler specification string");
}
String stopwordsHandlerName = stopwordsHandlerSpec[0];
stopwordsHandlerSpec[0] = "";
StopwordsHandler stopwordsHandler =
(StopwordsHandler) Utils.forName(
weka.core.stopwords.StopwordsHandler.class, stopwordsHandlerName,
stopwordsHandlerSpec);
setStopwordsHandler(stopwordsHandler);
}
String tokenizerString = Utils.getOption("tokenizer", options);
if (tokenizerString.length() == 0) {
setTokenizer(new WordTokenizer());
} else {
String[] tokenizerSpec = Utils.splitOptions(tokenizerString);
if (tokenizerSpec.length == 0) {
throw new Exception("Invalid tokenizer specification string");
}
String tokenizerName = tokenizerSpec[0];
tokenizerSpec[0] = "";
Tokenizer tokenizer =
(Tokenizer) Utils.forName(weka.core.tokenizers.Tokenizer.class,
tokenizerName, tokenizerSpec);
setTokenizer(tokenizer);
}
Utils.checkForRemainingOptions(options);
}
@SuppressWarnings("unchecked")
public void setup(Instances inputFormat) throws Exception {
m_inputContainsStringAttributes = inputFormat.checkForStringAttributes();
m_inputFormat = inputFormat.stringFreeStructure();
if (!m_inputContainsStringAttributes) {
return;
}
m_numClasses =
!m_doNotOperateOnPerClassBasis && m_inputFormat.classIndex() >= 0 && m_inputFormat.classAttribute().isNominal() ?
m_inputFormat.numClasses() : 1;
m_dictsPerClass =
m_sortDictionary ? new TreeMap[m_numClasses]
: new LinkedHashMap[m_numClasses];
m_classIndex = m_inputFormat.classIndex();
for (int i = 0; i < m_numClasses; i++) {
m_dictsPerClass[i] =
m_sortDictionary ? new TreeMap<String, int[]>()
: new LinkedHashMap<String, int[]>();
}
determineSelectedRange(inputFormat);
}
/**
* Gets the currently set input format
*
* @return the current input format
*/
public Instances getInputFormat() {
return m_inputFormat;
}
/**
* Returns true if this DictionaryBuilder is ready to vectorize incoming
* instances
*
* @return true if we can vectorize incoming instances
*/
public boolean readyToVectorize() {
return m_inputFormat != null && m_consolidatedDict != null;
}
/**
* determines the selected range.
*/
private void determineSelectedRange(Instances inputFormat) {
// Calculate the default set of fields to convert
if (m_selectedRange == null) {
StringBuffer fields = new StringBuffer();
for (int j = 0; j < inputFormat.numAttributes(); j++) {
if (inputFormat.attribute(j).type() == Attribute.STRING) {
fields.append((j + 1) + ",");
}
}
m_selectedRange = new Range(fields.toString());
}
m_selectedRange.setUpper(inputFormat.numAttributes() - 1);
// Prevent the user from converting non-string fields
StringBuffer fields = new StringBuffer();
for (int j = 0; j < inputFormat.numAttributes(); j++) {
if (m_selectedRange.getInvert()) {
if (!m_selectedRange.isInRange(j) ||
inputFormat.attribute(j).type() != Attribute.STRING) {
fields.append((j + 1) + ",");
}
} else {
if (m_selectedRange.isInRange(j)
&& inputFormat.attribute(j).type() == Attribute.STRING) {
fields.append((j + 1) + ",");
}
}
}
m_selectedRange.setRanges(fields.toString());
m_selectedRange.setUpper(inputFormat.numAttributes() - 1);
}
/**
* Get the output format
*
* @return the output format
* @throws Exception if there is no input format set and/or the dictionary has
* not been constructed yet.
*/
public Instances getVectorizedFormat() throws Exception {
if (m_inputFormat == null) {
throw new Exception("No input format available. Call setup() and "
+ "make sure a dictionary has been built first.");
}
if (!m_inputContainsStringAttributes) {
return m_inputFormat;
}
if (m_consolidatedDict == null) {
throw new Exception("Dictionary hasn't been built or finalized yet!");
}
if (m_outputFormat != null) {
return m_outputFormat;
}
ArrayList<Attribute> newAtts = new ArrayList<Attribute>();
// int classIndex = m_inputFormat.classIndex();
int classIndex = -1;
for (int i = 0; i < m_inputFormat.numAttributes(); i++) {
/*
* if (i == m_inputFormat.classIndex()) { continue; }
*/
if (!m_selectedRange.isInRange(i)) {
if (m_inputFormat.classIndex() == i) {
classIndex = newAtts.size();
}
newAtts.add((Attribute) m_inputFormat.attribute(i).copy());
}
}
// now do the dictionary
for (Map.Entry<String, int[]> e : m_consolidatedDict.entrySet()) {
newAtts.add(new Attribute(m_Prefix + e.getKey()));
}
/* Instances newFormat =
new Instances(m_inputFormat.relationName() + "_dictionaryBuilder_"
+ m_consolidatedDict.size(), newAtts, 0); */
Instances newFormat =
new Instances(m_inputFormat.relationName(), newAtts, 0);
if (classIndex >= 0) {
newFormat.setClassIndex(classIndex);
}
return newFormat;
}
/**
* Convert a batch of instances
*
* @param batch the batch to convert.
* @param setAvgDocLength true to compute and set the average document length
* for this DictionaryBuilder from the batch - this uses the final
* pruned dictionary when computing doc lengths. When vectorizing
* non-training batches, and normalization has been turned on, this
* should be set to false.
*
* @return the converted batch
* @throws Exception if there is no input format set and/or the dictionary has
* not been constructed yet.
*/
public Instances vectorizeBatch(Instances batch, boolean setAvgDocLength)
throws Exception {
if (m_inputFormat == null) {
throw new Exception("No input format available. Call setup() and "
+ "make sure a dictionary has been built first.");
}
if (!m_inputContainsStringAttributes) {
// nothing to do
return batch;
}
if (m_consolidatedDict == null) {
throw new Exception("Dictionary hasn't been built or consolidated yet!");
}
Instances vectorized = new Instances(m_outputFormat, batch.numInstances());
boolean normTemp = m_normalize;
if (setAvgDocLength) {
// make sure normalization is turned off until the second pass once
// we've set the post dictionary pruning average document length
m_normalize = false;
}
if (batch.numInstances() > 0) {
int[] offsetHolder = new int[1];
vectorized.add(vectorizeInstance(batch.instance(0), offsetHolder, true));
for (int i = 1; i < batch.numInstances(); i++) {
vectorized
.add(vectorizeInstance(batch.instance(i), offsetHolder, true));
}
if (setAvgDocLength) {
m_avgDocLength = 0;
for (int i = 0; i < vectorized.numInstances(); i++) {
Instance inst = vectorized.instance(i);
double docLength = 0;
for (int j = 0; j < inst.numValues(); j++) {
if (inst.index(j) >= offsetHolder[0]) {
docLength += inst.valueSparse(j) * inst.valueSparse(j);
}
}
m_avgDocLength += Math.sqrt(docLength);
}
m_avgDocLength /= vectorized.numInstances();
if (normTemp) {
for (int i = 0; i < vectorized.numInstances(); i++) {
normalizeInstance(vectorized.instance(i), offsetHolder[0]);
}
}
}
}
m_normalize = normTemp;
vectorized.compactify();
return vectorized;
}
/**
* Convert an input instance. Any string attributes not being vectorized do
* not have their values retained in memory (i.e. only the string values for
* the instance being vectorized are held in memory).
*
* @param input the input instance
* @return a converted instance
* @throws Exception if there is no input format set and/or the dictionary has
* not been constructed yet.
*/
public Instance vectorizeInstance(Instance input) throws Exception {
return vectorizeInstance(input, new int[1], false);
}
/**
* Convert an input instance.
*
* @param input the input instance
* @param retainStringAttValuesInMemory true if the values of string
* attributes not being vectorized should be retained in memory
* @return a converted instance
* @throws Exception if there is no input format set and/or the dictionary has
* not been constructed yet
*/
public Instance vectorizeInstance(Instance input,
boolean retainStringAttValuesInMemory) throws Exception {
return vectorizeInstance(input, new int[1], retainStringAttValuesInMemory);
}
private Instance vectorizeInstance(Instance input, int[] offsetHolder,
boolean retainStringAttValuesInMemory) throws Exception {
if (!m_inputContainsStringAttributes) {
return input;
}
if (m_inputFormat == null) {
throw new Exception("No input format available. Call setup() and "
+ "make sure a dictionary has been built first.");
}
if (m_consolidatedDict == null) {
throw new Exception("Dictionary hasn't been built or consolidated yet!");
}
int indexOffset = 0;
int classIndex = m_outputFormat.classIndex();
Map<Integer, double[]> contained = new TreeMap<Integer, double[]>();
for (int i = 0; i < m_inputFormat.numAttributes(); i++) {
if (!m_selectedRange.isInRange(i)) {
if (!m_inputFormat.attribute(i).isString()
&& !m_inputFormat.attribute(i).isRelationValued()) {
// add nominal and numeric directly
if (input.value(i) != 0.0) {
contained.put(indexOffset, new double[] { input.value(i) });
}
} else {
if (input.isMissing(i)) {
contained.put(indexOffset, new double[] { Utils.missingValue() });
} else if (m_inputFormat.attribute(i).isString()) {
String strVal = input.stringValue(i);
if (retainStringAttValuesInMemory) {
double strIndex =
m_outputFormat.attribute(indexOffset).addStringValue(strVal);
contained.put(indexOffset, new double[] { strIndex });
} else {
m_outputFormat.attribute(indexOffset).setStringValue(strVal);
contained.put(indexOffset, new double[] { 0 });
}
} else {
// relational
if (m_outputFormat.attribute(indexOffset).numValues() == 0) {
Instances relationalHeader =
m_outputFormat.attribute(indexOffset).relation();
// hack to defeat sparse instances bug
m_outputFormat.attribute(indexOffset).addRelation(
relationalHeader);
}
int newIndex =
m_outputFormat.attribute(indexOffset).addRelation(
input.relationalValue(i));
contained.put(indexOffset, new double[] { newIndex });
}
}
indexOffset++;
}
}
offsetHolder[0] = indexOffset;
// dictionary entries
for (int i = 0; i < m_inputFormat.numAttributes(); i++) {
if (m_selectedRange.isInRange(i) && !input.isMissing(i)) {
m_tokenizer.tokenize(input.stringValue(i));
while (m_tokenizer.hasMoreElements()) {
String word = m_tokenizer.nextElement();
if (m_lowerCaseTokens) {
word = word.toLowerCase();
}
word = m_stemmer.stem(word);
int[] idxAndDocCount = m_consolidatedDict.get(word);
if (idxAndDocCount != null) {
if (m_outputCounts) {
double[] inputCount =
contained.get(idxAndDocCount[0] + indexOffset);
if (inputCount != null) {
inputCount[0]++;
} else {
contained.put(idxAndDocCount[0] + indexOffset,
new double[] { 1 });
}
} else {
contained
.put(idxAndDocCount[0] + indexOffset, new double[] { 1 });
}
}
}
}
}
// TF transform
if (m_TFTransform) {
for (Map.Entry<Integer, double[]> e : contained.entrySet()) {
int index = e.getKey();
if (index >= indexOffset) {
double[] val = e.getValue();
val[0] = Math.log(val[0] + 1);
}
}
}
// IDF transform
if (m_IDFTransform) {
for (Map.Entry<Integer, double[]> e : contained.entrySet()) {
int index = e.getKey();
if (index >= indexOffset) {
double[] val = e.getValue();
String word = m_outputFormat.attribute(index).name();
word = word.substring(m_Prefix.length());
int[] idxAndDocCount = m_consolidatedDict.get(word);
if (idxAndDocCount == null) {
throw new Exception("This should never occur");
}
if (idxAndDocCount.length != 2) {
throw new Exception("Can't compute IDF transform as document "
+ "counts are not available");
}
val[0] = val[0] * Math.log(m_count / (double) idxAndDocCount[1]);
}
}
}
double[] values = new double[contained.size()];
int[] indices = new int[contained.size()];
int i = 0;
for (Map.Entry<Integer, double[]> e : contained.entrySet()) {
values[i] = e.getValue()[0];
indices[i++] = e.getKey().intValue();
}
Instance inst =
new SparseInstance(input.weight(), values, indices,
m_outputFormat.numAttributes());
inst.setDataset(m_outputFormat);
if (m_normalize) {
normalizeInstance(inst, indexOffset);
}
return inst;
}
/**
* Normalizes given instance to average doc length (only the newly constructed
* attributes).
*
* @param inst the instance to normalize
* @param offset index of the start of the dictionary attributes
* @throws Exception if avg. doc length not set
*/
private void normalizeInstance(Instance inst, int offset) throws Exception {
if (m_avgDocLength <= 0) {
throw new Exception("Average document length is not set!");
}
double docLength = 0;
// compute length of document vector
for (int i = 0; i < inst.numValues(); i++) {
if (inst.index(i) >= offset
&& inst.index(i) != m_outputFormat.classIndex()) {
docLength += inst.valueSparse(i) * inst.valueSparse(i);
}
}
docLength = Math.sqrt(docLength);
// normalized document vector
for (int i = 0; i < inst.numValues(); i++) {
if (inst.index(i) >= offset
&& inst.index(i) != m_outputFormat.classIndex()) {
double val = inst.valueSparse(i) * m_avgDocLength / docLength;
inst.setValueSparse(i, val);
if (val == 0) {
System.err.println("setting value " + inst.index(i) + " to zero.");
i--;
}
}
}
}
/**
* Process an instance by tokenizing string attributes and updating the
* dictionary.
*
* @param inst the instance to process
*/
public void processInstance(Instance inst) {
if (!m_inputContainsStringAttributes) {
return;
}
if (m_inputVector == null) {
m_inputVector = new LinkedHashMap<String, int[]>();
} else {
m_inputVector.clear();
}
int dIndex = 0;
if (!m_doNotOperateOnPerClassBasis && m_classIndex >= 0 && m_inputFormat.classAttribute().isNominal()) {
if (!inst.classIsMissing()) {
dIndex = (int) inst.classValue();
} else {
return; // skip missing class instances
}
}
for (int j = 0; j < inst.numAttributes(); j++) {
if (m_selectedRange.isInRange(j) && !inst.isMissing(j)) {
m_tokenizer.tokenize(inst.stringValue(j));
while (m_tokenizer.hasMoreElements()) {
String word = m_tokenizer.nextElement();
if (m_lowerCaseTokens) {
word = word.toLowerCase();
}
word = m_stemmer.stem(word);
if (m_stopwordsHandler.isStopword(word)) {
continue;
}
int[] counts = m_inputVector.get(word);
if (counts == null) {
counts = new int[2];
counts[0] = 1; // word count
counts[1] = 1; // doc count
m_inputVector.put(word, counts);
} else {
counts[0]++;
}
}
}
}
// now update dictionary for the words that have
// occurred in this instance (document)
double docLength = 0;
for (Map.Entry<String, int[]> e : m_inputVector.entrySet()) {
int[] dictCounts = m_dictsPerClass[dIndex].get(e.getKey());
if (dictCounts == null) {
dictCounts = new int[2];
m_dictsPerClass[dIndex].put(e.getKey(), dictCounts);
}
dictCounts[0] += e.getValue()[0];
dictCounts[1] += e.getValue()[1];
docLength += e.getValue()[0] * e.getValue()[0];
}
if (m_normalize) {
// this is normalization based document length *before* final dictionary
// pruning. DictionaryBuilder operates incrementally, so it is not
// possible to normalize based on a final dictionary
m_docLengthSum += Math.sqrt(docLength);
}
m_count++;
pruneDictionary();
}
/**
* Prunes the dictionary of low frequency terms
*/
protected void pruneDictionary() {
if (m_periodicPruneRate > 0 && m_count % m_periodicPruneRate == 0) {
for (Map<String, int[]> m_dictsPerClas : m_dictsPerClass) {
Iterator<Map.Entry<String, int[]>> entries =
m_dictsPerClas.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, int[]> entry = entries.next();
if (entry.getValue()[0] < m_minFrequency) {
entries.remove();
}
}
}
}
}
/**
* Clear the dictionary(s)
*/
public void reset() {
m_dictsPerClass = null;
m_count = 0;
m_docLengthSum = 0;
m_avgDocLength = 0;
m_inputFormat = null;
m_outputFormat = null;
m_consolidatedDict = null;
}
/**
* Get the current dictionary(s) (one per class for nominal class, if set).
* These are the dictionaries that are built/updated when processInstance() is
* called. The finalized dictionary (used for vectorization) can be obtained
* by calling finalizeDictionary() - this returns a consolidated (over
* classes) and pruned final dictionary.
*
* @param minFrequencyPrune prune the dictionaries of low frequency terms
* before returning them
* @return the dictionaries
*/
public Map<String, int[]>[] getDictionaries(boolean minFrequencyPrune)
throws WekaException {
if (m_dictsPerClass == null) {
throw new WekaException("No dictionaries have been built yet!");
}
if (minFrequencyPrune) {
pruneDictionary();
}
return m_dictsPerClass;
}
@Override
public DictionaryBuilder aggregate(DictionaryBuilder toAgg) throws Exception {
Map<String, int[]>[] toAggDicts = toAgg.getDictionaries(false);
if (toAggDicts.length != m_dictsPerClass.length) {
throw new Exception("Number of dictionaries from the builder to "
+ "be aggregated does not match our number of dictionaries");
}
// we assume that the order of class values is consistent
for (int i = 0; i < toAggDicts.length; i++) {
Map<String, int[]> toAggDictForClass = toAggDicts[i];
for (Map.Entry<String, int[]> e : toAggDictForClass.entrySet()) {
int[] ourCounts = m_dictsPerClass[i].get(e.getKey());
if (ourCounts == null) {
ourCounts = new int[2];
m_dictsPerClass[i].put(e.getKey(), ourCounts);
}
ourCounts[0] += e.getValue()[0]; // word count
ourCounts[1] += e.getValue()[1]; // doc count
}
}
m_count += toAgg.m_count;
m_docLengthSum += toAgg.m_docLengthSum;
return this;
}
@Override
public void finalizeAggregation() throws Exception {
finalizeDictionary();
}
/**
* Performs final pruning and consolidation according to the number of words
* to keep property. Finalization is performed just once, subsequent calls to
* this method return the finalized dictionary computed on the first call
* (unless reset() has been called in between).
*
* @return the consolidated and pruned final dictionary, or null if the input
* format did not contain any string attributes within the selected
* range to process
* @throws Exception if a problem occurs
*/
public Map<String, int[]> finalizeDictionary() throws Exception {
if (!m_inputContainsStringAttributes) {
return null;
}
// perform final pruning and consolidation
// according to wordsToKeep
if (m_consolidatedDict != null) {
return m_consolidatedDict;
}
if (m_dictsPerClass == null) {
System.err.println(this.hashCode());
throw new WekaException("No dictionary built yet!");
}
int[] prune = new int[m_dictsPerClass.length];
for (int z = 0; z < prune.length; z++) {
int[] array = new int[m_dictsPerClass[z].size()];
int index = 0;
for (Map.Entry<String, int[]> e : m_dictsPerClass[z].entrySet()) {
array[index++] = e.getValue()[0];
}
if (array.length < m_wordsToKeep) {
prune[z] = m_minFrequency;
} else {
Arrays.sort(array);
prune[z] =
Math.max(m_minFrequency, array[array.length - m_wordsToKeep]);
}
}
// now consolidate across classes
Map<String, int[]> consolidated = new LinkedHashMap<String, int[]>();
int index = 0;
for (int z = 0; z < prune.length; z++) {
for (Map.Entry<String, int[]> e : m_dictsPerClass[z].entrySet()) {
if (e.getValue()[0] >= prune[z]) {
int[] counts = consolidated.get(e.getKey());
if (counts == null) {
counts = new int[2];
counts[0] = index++;
consolidated.put(e.getKey(), counts);
}
// counts[0] += e.getValue()[0];
counts[1] += e.getValue()[1];
}
}
}
m_consolidatedDict = consolidated;
m_dictsPerClass = null;
if (m_normalize) {
m_avgDocLength = m_docLengthSum / m_count;
}
m_outputFormat = getVectorizedFormat();
return m_consolidatedDict;
}
/**
* Load a dictionary from a file
*
* @param filename the file to load from
* @param plainText true if the dictionary is in text format
* @throws IOException if a problem occurs
*/
public void loadDictionary(String filename, boolean plainText)
throws IOException {
loadDictionary(new File(filename), plainText);
}
/**
* Load a dictionary from a file
*
* @param toLoad the file to load from
* @param plainText true if the dictionary is in text format
* @throws IOException if a problem occurs
*/
public void loadDictionary(File toLoad, boolean plainText) throws IOException {
if (plainText) {
loadDictionary(new FileReader(toLoad));
} else {
loadDictionary(new FileInputStream(toLoad));
}
}
/**
* Load a textual dictionary from a reader
*
* @param reader the reader to read from
* @throws IOException if a problem occurs
*/
public void loadDictionary(Reader reader) throws IOException {
BufferedReader br = new BufferedReader(reader);
m_consolidatedDict = new LinkedHashMap<String, int[]>();
try {
String line = br.readLine();
int index = 0;
if (line != null) {
if (line.startsWith("@@@") && line.endsWith("@@@")) {
String avgS = line.replace("@@@", "");
try {
m_avgDocLength = Double.parseDouble(avgS);
} catch (NumberFormatException ex) {
System.err.println("Unable to parse average document length '"
+ avgS + "'");
}
line = br.readLine();
if (line == null) {
throw new IOException("Empty dictionary file!");
}
}
boolean hasDocCounts = false;
if (line.lastIndexOf(",") > 0) {
String countS =
line.substring(line.lastIndexOf(",") + 1, line.length()).trim();
try {
int dCount = Integer.parseInt(countS);
hasDocCounts = true;
int[] holder = new int[2];
holder[1] = dCount;
holder[0] = index++;
m_consolidatedDict.put(line.substring(0, line.lastIndexOf(",")),
holder);
} catch (NumberFormatException ex) {
// ignore quietly
}
}
while ((line = br.readLine()) != null) {
int[] holder = new int[hasDocCounts ? 2 : 1];
holder[0] = index++;
if (hasDocCounts) {
String countS =
line.substring(line.lastIndexOf(",") + 1, line.length()).trim();
line = line.substring(0, line.lastIndexOf(","));
try {
int dCount = Integer.parseInt(countS);
holder[1] = dCount;
} catch (NumberFormatException e) {
throw new IOException(e);
}
}
m_consolidatedDict.put(line, holder);
}
} else {
throw new IOException("Empty dictionary file!");
}
} finally {
br.close();
}
try {
m_outputFormat = getVectorizedFormat();
} catch (Exception ex) {
throw new IOException(ex);
}
}
/**
* Load a binary dictionary from an input stream
*
* @param is the input stream to read from
* @throws IOException if a problem occurs
*/
@SuppressWarnings("unchecked")
public void loadDictionary(InputStream is) throws IOException {
ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(is));
try {
List<Object> holder = (List<Object>) ois.readObject();
m_avgDocLength = (Double) holder.get(0);
m_consolidatedDict = (Map<String, int[]>) holder.get(1);
} catch (ClassNotFoundException ex) {
throw new IOException(ex);
} finally {
ois.close();
}
}
/**
* Save the dictionary
*
* @param filename the file to save to
* @param plainText true if the dictionary should be saved in text format
* @throws IOException if a problem occurs
*/
public void saveDictionary(String filename, boolean plainText)
throws IOException {
saveDictionary(new File(filename), plainText);
}
/**
* Save a dictionary
*
* @param toSave the file to save to
* @param plainText true if the dictionary should be saved in text format
* @throws IOException if a problem occurs
*/
public void saveDictionary(File toSave, boolean plainText) throws IOException {
if (plainText) {
saveDictionary(new FileWriter(toSave));
} else {
saveDictionary(new FileOutputStream(toSave));
}
}
/**
* Save the dictionary in textual format
*
* @param writer the writer to write to
* @throws IOException if a problem occurs
*/
public void saveDictionary(Writer writer) throws IOException {
if (!m_inputContainsStringAttributes) {
throw new IOException("Input did not contain any string attributes!");
}
if (m_consolidatedDict == null) {
throw new IOException("No dictionary to save!");
}
BufferedWriter br = new BufferedWriter(writer);
try {
if (m_avgDocLength > 0) {
br.write("@@@" + m_avgDocLength + "@@@\n");
}
for (Map.Entry<String, int[]> e : m_consolidatedDict.entrySet()) {
int[] v = e.getValue();
br.write(e.getKey() + "," + (v.length > 1 ? v[1] : "") + "\n");
}
} finally {
br.flush();
br.close();
}
}
/**
* Save the dictionary in binary form
*
* @param os the output stream to write to
* @throws IOException if a problem occurs
*/
public void saveDictionary(OutputStream os) throws IOException {
if (!m_inputContainsStringAttributes) {
throw new IOException("Input did not contain any string attributes!");
}
if (m_consolidatedDict == null) {
throw new IOException("No dictionary to save!");
}
ObjectOutputStream oos =
new ObjectOutputStream(new BufferedOutputStream(os));
List<Object> holder = new ArrayList<Object>();
holder.add(m_avgDocLength);
holder.add(m_consolidatedDict);
try {
oos.writeObject(holder);
} finally {
oos.flush();
oos.close();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/DistanceFunction.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* DistanceFunction.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import weka.core.neighboursearch.PerformanceStats;
/**
* Interface for any class that can compute and return distances between two
* instances.
*
* @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface DistanceFunction extends OptionHandler {
/**
* Sets the instances.
*
* @param insts the instances to use
*/
public void setInstances(Instances insts);
/**
* returns the instances currently set.
*
* @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
*
* @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
*/
public String getAttributeIndices();
/**
* Sets whether the matching sense of attribute indices is inverted or not.
*
* @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
*/
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
*/
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
*/
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
* 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.
*/
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
* 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);
/**
* 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
* manipulation.
*
* @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
*/
public void update(Instance ins);
/**
* Free any references to training instances
*/
public void clean();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Drawable.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Drawable.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Interface to something that can be drawn as a graph.
*
* @author Ashraf M. Kibriya(amk14@cs.waikato.ac.nz), Eibe Frank(eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface Drawable {
int NOT_DRAWABLE = 0, TREE = 1, BayesNet = 2, Newick = 3;
/**
* Returns the type of graph representing
* the object.
*
* @return the type of graph representing the object
*/
int graphType();
/**
* Returns a string that describes a graph representing
* the object. The string should be in XMLBIF ver.
* 0.3 format if the graph is a BayesNet, otherwise
* it should be in dotty format.
*
* @return the graph described by a string
* @exception Exception if the graph can't be computed
*/
String graph() throws Exception;
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/EnumHelper.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* EnumHelper.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.lang.reflect.Method;
/**
* Helper/wrapper class for obtaining an arbitrary enum value from an arbitrary
* enum type. An enum value wrapped in this class can be serialized by Weka's
* XML serialization mechanism.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: $
*/
public class EnumHelper {
/**
* The fully qualified name of the enum class to wrap
*/
protected String m_enumClass;
/**
* The selected/wapped enum value (as obtained by calling toString() on the
* value)
*/
protected String m_selectedEnumValue;
/**
* Constructor
*
* @param e the enum value to wrap
*/
public EnumHelper(Enum e) {
m_selectedEnumValue = e.toString();
m_enumClass = e.getClass().getName();
}
/**
* No-op constructor (for beans conformity)
*/
public EnumHelper() {
}
/**
* Set the fully qualified enum class name
*
* @param enumClass the fully qualified name of the enum class
*/
public void setEnumClass(String enumClass) {
m_enumClass = enumClass;
}
/**
* Get the fully qualified enum class name
*
* @return the fully qualified name of the enum class
*/
public String getEnumClass() {
return m_enumClass;
}
/**
* Set the selected/wrapped enum value (as obtained by calling toString() on
* the enum value)
*
* @param selectedEnumValue the enum value to wrap
*/
public void setSelectedEnumValue(String selectedEnumValue) {
m_selectedEnumValue = selectedEnumValue;
}
/**
* Get the selected/wrapped enum value (as obtained by calling toString() on
* the enum value)
*
* @return the enum value to wrap
*/
public String getSelectedEnumValue() {
return m_selectedEnumValue;
}
/**
* Helper method to recover an enum value given the fully qualified name of
* the enum and the value in question as strings
*
* @param enmumClass a string containing the fully qualified name of the enum
* class
* @param enumValue a string containing the value of the enum to find
* @return the enum value as an Object
* @throws Exception if a problem occurs
*/
public static Object valueFromString(String enmumClass, String enumValue)
throws Exception {
Class<?> eClazz = WekaPackageClassLoaderManager.forName(enmumClass);
Method valuesM = eClazz.getMethod("values");
Enum[] values = (Enum[]) valuesM.invoke(null);
for (Enum e : values) {
if (e.toString().equals(enumValue)) {
return e;
}
}
return null;
}
/**
* Main method for testing this class
*
* @param args arguments
*/
public static void main(String[] args) {
try {
if (args.length != 2) {
System.err
.println("usage: weka.core.EnumHelper <enum class> <enum value>");
}
Object eVal = EnumHelper.valueFromString(args[0], args[1]);
System.out.println("The enum's value is: " + eVal.toString());
System.out.println("The enum's class is: " + eVal.getClass().toString());
if (eVal instanceof Enum) {
System.out.println("The value is an instance of Enum superclass");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Environment.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Environment.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
/**
* This class encapsulates a map of all environment and java system properties.
* There are methods for adding and removing variables to this Environment
* object as well as to the system wide global environment. There is also a
* method for replacing key names (enclosed by ${}) with their associated value
* in Strings.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class Environment implements RevisionHandler {
private static Environment m_systemWide = new Environment();
// Map to hold all the system environment variables + java properties
private final Map<String, String> m_envVars = new TreeMap<String, String>();
/**
* Constructs a new Environment object with all environment variables
* and java properties set.
*/
public Environment() {
// get the env variables first
Map<String, String> env = System.getenv();
Set<String> keys = env.keySet();
Iterator<String> i = keys.iterator();
while (i.hasNext()) {
String kv = i.next();
String value = env.get(kv);
m_envVars.put(kv, value);
}
// get the java properties
Properties jvmProps = System.getProperties();
Enumeration<?> pKeys = jvmProps.propertyNames();
while (pKeys.hasMoreElements()) {
String kv = (String) pKeys.nextElement();
String value = jvmProps.getProperty(kv);
m_envVars.put(kv, value);
}
m_envVars.put("weka.version", Version.VERSION);
}
/**
* Constructor that makes a new Environment object containing all
* the entries in the supplied one
*
* @param other the Environment object to copy to this one
*/
public Environment(Environment other) {
m_envVars.putAll(other.m_envVars);
}
/**
* Get the singleton system-wide (visible to every class in the running VM)
* set of environment variables.
*
* @return the system-wide set of environment variables.
*/
public static Environment getSystemWide() {
return m_systemWide;
}
/**
* Tests for the presence of environment variables.
*
* @param source the string to test
* @return true if the argument contains one or more environment variables
*/
public static boolean containsEnvVariables(String source) {
return (source.indexOf("${") >= 0);
}
/**
* Substitute a variable names for their values in the given string.
*
* @param source the source string to replace variables in
* @return a String with all variable names replaced with their values
* @throws Exception if an unknown variable name is encountered
*/
public String substitute(String source) throws Exception {
// Grab each variable out of the string
int index = source.indexOf("${");
while (index >= 0) {
index += 2;
int endIndex = source.indexOf('}');
if (endIndex >= 0 && endIndex > index + 1) {
String key = source.substring(index, endIndex);
// look this sucker up
String replace = m_envVars.get(key);
if (replace != null) {
String toReplace = "${" + key + "}";
source = source.replace(toReplace, replace);
} else {
throw new Exception("[Environment] Variable " + key
+ " doesn't seem to be set.");
}
} else {
break;
}
index = source.indexOf("${");
}
return source;
}
/**
* Add a variable to the internal map of this properties object.
*
* @param key the name of the variable
* @param value its value
*/
public void addVariable(String key, String value) {
m_envVars.put(key, value);
}
/**
* Add a a variable to the internal map of this properties object and to the
* global system-wide environment;
*
* @param key the name of the variable
* @param value its value
*/
public void addVariableSystemWide(String key, String value) {
addVariable(key, value); // local
// system wide
if (this != getSystemWide()) {
getSystemWide().addVariableSystemWide(key, value);
}
System.setProperty(key, value);
}
/**
* Remove a named variable from the map.
*
* @param key the name of the varaible to remove.
*/
public void removeVariable(String key) {
m_envVars.remove(key);
}
/**
* Get the names of the variables (keys) stored in the internal map.
*
* @return a Set of variable names (keys)
*/
public Set<String> getVariableNames() {
return m_envVars.keySet();
}
/**
* Get the value for a particular variable.
*
* @param key the name of the variable to get
* @return the associated value or null if this variable is not in the
* internal map
*/
public String getVariableValue(String key) {
return m_envVars.get(key);
}
/**
* Main method for testing this class.
*
* @param args a list of strings to replace variables in (e.g. "\${os.name}
* "\${java.version}")
*/
public static void main(String[] args) {
Environment t = new Environment();
// String test =
// "Here is a string with the variable ${java.version} and ${os.name} in it";
if (args.length == 0) {
System.err
.println("Usage: java weka.core.Environment <string> <string> ...");
} else {
try {
for (String arg : args) {
String newS = t.substitute(arg);
System.out.println("Original string:\n" + arg + "\n\nNew string:\n"
+ newS);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/EnvironmentHandler.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* EnvironmentHandler.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
/**
* Interface for something that can utilize environment
* variables. NOTE: since environment variables should
* be transient, the implementer needs to be careful
* of state after de-serialization. Default system-wide
* environment variables can be got via a call to
* <code>weka.core.Environment.getSystemWide()</code>
*
* @author mhall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public interface EnvironmentHandler {
/**
* Set environment variables to use.
*
* @param env the environment variables to
* use
*/
void setEnvironment(Environment env);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/EnvironmentProperties.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* EnvironmentProperties.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.util.Properties;
import java.util.Set;
/**
* Extends Properties to allow the value of a system property (if set) to
* override that which has been loaded/set. This allows the user to override
* from the command line any property that is loaded into a property file via
* weka.core.Utils.readProperties().
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class EnvironmentProperties extends Properties {
protected transient Environment m_env = Environment.getSystemWide();
public EnvironmentProperties() {
super();
}
public EnvironmentProperties(Properties props) {
super(props);
}
@Override
public String getProperty(String key) {
// allow system-wide properties to override
if (m_env == null) {
m_env = Environment.getSystemWide();
}
String result = m_env.getVariableValue(key);
if (result == null) {
result = super.getProperty(key);
}
return result;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/EuclideanDistance.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* EuclideanDistance.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.neighboursearch.PerformanceStats;
/**
<!-- globalinfo-start -->
* Implementing Euclidean distance (or similarity) function.<br/>
* <br/>
* One object defines not one distance but the data model in which the distances between objects of that data model can be computed.<br/>
* <br/>
* Attention: For efficiency reasons the use of consistency checks (like are the data models of the two instances exactly the same), is low.<br/>
* <br/>
* For more information, see:<br/>
* <br/>
* Wikipedia. Euclidean distance. URL http://en.wikipedia.org/wiki/Euclidean_distance.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @misc{missing_id,
* author = {Wikipedia},
* title = {Euclidean distance},
* URL = {http://en.wikipedia.org/wiki/Euclidean_distance}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -D
* Turns off the normalization of attribute
* values in distance calculation.</pre>
*
* <pre> -R <col1,col2-col4,...>
* Specifies list of columns to used in the calculation of the
* distance. 'first' and 'last' are valid indices.
* (default: first-last)</pre>
*
* <pre> -V
* Invert matching sense of column indices.</pre>
*
<!-- options-end -->
*
* @author Gabi Schmidberger (gabi@cs.waikato.ac.nz)
* @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class EuclideanDistance
extends NormalizableDistance
implements Cloneable, TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = 1068606253458807903L;
/**
* Constructs an Euclidean Distance object, Instances must be still set.
*/
public EuclideanDistance() {
super();
}
/**
* Constructs an Euclidean Distance object and automatically initializes the
* ranges.
*
* @param data the instances the distance function should work on
*/
public EuclideanDistance(Instances data) {
super(data);
}
/**
* Returns a string describing this object.
*
* @return a description of the evaluator suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return
"Implementing Euclidean distance (or similarity) function.\n\n"
+ "One object defines not one distance but the data model in which "
+ "the distances between objects of that data model can be computed.\n\n"
+ "Attention: For efficiency reasons the use of consistency checks "
+ "(like are the data models of the two instances exactly the same), "
+ "is low.\n\n"
+ "For more information, see:\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.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.MISC);
result.setValue(Field.AUTHOR, "Wikipedia");
result.setValue(Field.TITLE, "Euclidean distance");
result.setValue(Field.URL, "http://en.wikipedia.org/wiki/Euclidean_distance");
return result;
}
/**
* Calculates the distance between two 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) {
return Math.sqrt(distance(first, second, Double.POSITIVE_INFINITY));
}
/**
* Calculates the distance (or similarity) between two instances. Need to
* pass this returned distance later on to postprocess method to set it on
* correct scale. <br/>
* P.S.: Please don't mix the use of this function with
* distance(Instance first, Instance second), as that already does post
* processing. Please consider passing Double.POSITIVE_INFINITY as the cutOffValue to
* this function and then later on do the post processing on all the
* distances.
*
* @param first the first instance
* @param second the second instance
* @param stats the structure for storing performance statistics.
* @return the distance between the two given instances or
* Double.POSITIVE_INFINITY.
*/
public double distance(Instance first, Instance second, PerformanceStats stats) { //debug method pls remove after use
return Math.sqrt(distance(first, second, Double.POSITIVE_INFINITY, stats));
}
/**
* Updates the current distance calculated so far with the new difference
* 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)
*/
protected double updateDistance(double currDist, double diff) {
double result;
result = currDist;
result += diff * diff;
return result;
}
/**
* Does post processing of the distances (if necessary) returned by
* distance(distance(Instance first, Instance second, double cutOffValue). It
* is necessary to do so to get the correct distances if
* distance(distance(Instance first, Instance second, double cutOffValue) is
* used. This is because that function actually returns the squared distance
* to avoid inaccuracies arising from floating point comparison.
*
* @param distances the distances to post-process
*/
public void postProcessDistances(double distances[]) {
for(int i = 0; i < distances.length; i++) {
distances[i] = Math.sqrt(distances[i]);
}
}
/**
* Returns the squared difference of two values of an attribute.
*
* @param index the attribute index
* @param val1 the first value
* @param val2 the second value
* @return the squared difference
*/
public double sqDifference(int index, double val1, double val2) {
double val = difference(index, val1, val2);
return val*val;
}
/**
* Returns value in the middle of the two parameter values.
*
* @param ranges the ranges to this dimension
* @return the middle value
*/
public double getMiddle(double[] ranges) {
double middle = ranges[R_MIN] + ranges[R_WIDTH] * 0.5;
return middle;
}
/**
* Returns the index of the closest point to the current instance.
* Index is index in Instances object that is the second parameter.
*
* @param instance the instance to assign a cluster to
* @param allPoints all points
* @param pointList the list of points
* @return the index of the closest point
* @throws Exception if something goes wrong
*/
public int closestPoint(Instance instance, Instances allPoints,
int[] pointList) throws Exception {
double minDist = Integer.MAX_VALUE;
int bestPoint = 0;
for (int i = 0; i < pointList.length; i++) {
double dist = distance(instance, allPoints.instance(pointList[i]), Double.POSITIVE_INFINITY);
if (dist < minDist) {
minDist = dist;
bestPoint = i;
}
}
return pointList[bestPoint];
}
/**
* Returns true if the value of the given dimension is smaller or equal the
* value to be compared with.
*
* @param instance the instance where the value should be taken of
* @param dim the dimension of the value
* @param value the value to compare with
* @return true if value of instance is smaller or equal value
*/
public boolean valueIsSmallerEqual(Instance instance, int dim,
double value) { //This stays
return instance.value(dim) <= value;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/FastVector.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* FastVector.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
/**
* Simple extension of ArrayList. Exists for legacy reasons.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
@Deprecated
public class FastVector<E> extends ArrayList<E> implements Copyable,
RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -2173635135622930169L;
/**
* Constructs an empty vector with initial capacity zero.
*/
public FastVector() {
super();
}
/**
* Constructs a vector with the given capacity.
*
* @param capacity the vector's initial capacity
*/
public FastVector(int capacity) {
super(capacity);
}
/**
* Adds an element to this vector. Increases its capacity if its not large
* enough.
*
* @param element the element to add
*/
public final void addElement(E element) {
add(element);
}
/**
* Produces a shallow copy of this vector.
*
* @return the new vector
*/
@Override
public final FastVector<E> copy() {
return Utils.cast(clone());
}
/**
* Clones the vector and shallow copies all its elements. The elements have to
* implement the Copyable interface.
*
* @return the new vector
*/
public final FastVector<E> copyElements() {
FastVector<E> copy = copy();
for (int i = 0; i < size(); i++) {
copy.set(i, Utils.<E> cast(((Copyable) get(i)).copy()));
}
return copy;
}
/**
* Returns the element at the given position.
*
* @param index the element's index
* @return the element with the given index
*/
public final E elementAt(int index) {
return get(index);
}
/**
* Returns an enumeration of this vector.
*
* @return an enumeration of this vector
*/
public final Enumeration<E> elements() {
return new WekaEnumeration<E>(this);
}
/**
* Returns an enumeration of this vector, skipping the element with the given
* index.
*
* @param index the element to skip
* @return an enumeration of this vector
*/
public final Enumeration<E> elements(int index) {
return new WekaEnumeration<E>(this, index);
}
/**
* Returns the first element of the vector.
*
* @return the first element of the vector
*/
public final E firstElement() {
return get(0);
}
/**
* Inserts an element at the given position.
*
* @param element the element to be inserted
* @param index the element's index
*/
public final void insertElementAt(E element, int index) {
add(index, element);
}
/**
* Returns the last element of the vector.
*
* @return the last element of the vector
*/
public final E lastElement() {
return get(size() - 1);
}
/**
* Deletes an element from this vector.
*
* @param index the index of the element to be deleted
*/
public final void removeElementAt(int index) {
remove(index);
}
/**
* Removes all components from this vector and sets its size to zero.
*/
public final void removeAllElements() {
clear();
}
/**
* Appends all elements of the supplied vector to this vector.
*
* @param toAppend the FastVector containing elements to append.
*/
public final void appendElements(Collection<? extends E> toAppend) {
addAll(toAppend);
}
/**
* Sets the vector's capacity to the given value.
*
* @param capacity the new capacity
*/
public final void setCapacity(int capacity) {
ensureCapacity(capacity);
}
/**
* Sets the element at the given index.
*
* @param element the element to be put into the vector
* @param index the index at which the element is to be placed
*/
public final void setElementAt(E element, int index) {
set(index, element);
}
/**
* Swaps two elements in the vector.
*
* @param first index of the first element
* @param second index of the second element
*/
public final void swap(int first, int second) {
E in = get(first);
set(first, get(second));
set(second, in);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/FileHelper.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* FileHelper.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.File;
/**
* Wrapper class for File objects. File objects wrapped in this class
* can be serialized by Weka's XML serialization mechanism.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: $
*/
public class FileHelper {
/** The file path as a string */
protected String m_filePath;
/**
* Constructor
*
* @param file the file to wrap
*/
public FileHelper(File file) {
m_filePath = file.toString();
}
/**
* No-op constructor for beans conformity
*/
public FileHelper() {
}
/**
* Set the file path
*
* @param path the path to set
*/
public void setFilePath(String path) {
m_filePath = path;
}
/**
* Get the file path
*
* @return the path to set
*/
public String getFilePath() {
return m_filePath;
}
/**
* Get the file wrapped in this instance
*
* @return the File object
*/
public File getFile() {
if (m_filePath != null) {
return new File(m_filePath);
}
return new File(System.getProperty("user.home"));
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/FilteredDistance.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* FilteredDistance.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import weka.core.DistanceFunction;
import weka.core.neighboursearch.PerformanceStats;
import weka.filters.Filter;
import weka.filters.unsupervised.attribute.RandomProjection;
import weka.filters.unsupervised.attribute.Remove;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Collections;
import java.io.Serializable;
/**
<!-- globalinfo-start -->
Applies the given filter before calling the given distance function.
<p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
Valid options are: <p/>
<pre> -F
The filter to use. (default: weka.unsupervised.attribute.RandomProjection</pre>
<pre> -E
The distance function to use. (default: weka.core.EuclideanDistance</pre>
<pre>
Options specific to filter weka.filters.unsupervised.attribute.RandomProjection:
</pre>
<pre> -N <number>
The number of dimensions (attributes) the data should be reduced to
(default 10; exclusive of the class attribute, if it is set).</pre>
<pre> -D [SPARSE1|SPARSE2|GAUSSIAN]
The distribution to use for calculating the random matrix.
Sparse1 is:
sqrt(3)*{-1 with prob(1/6), 0 with prob(2/3), +1 with prob(1/6)}
Sparse2 is:
{-1 with prob(1/2), +1 with prob(1/2)}
</pre>
<pre> -P <percent>
The percentage of dimensions (attributes) the data should
be reduced to (exclusive of the class attribute, if it is set). The -N
option is ignored if this option is present and is greater
than zero.</pre>
<pre> -M
Replace missing values using the ReplaceMissingValues filter</pre>
<pre> -R <num>
The random seed for the random number generator used for
calculating the random matrix (default 42).</pre>
<pre>
Options specific to distance function weka.core.EuclideanDistance:
</pre>
<pre> -D
Turns off the normalization of attribute
values in distance calculation.</pre>
<pre> -R <col1,col2-col4,...>
Specifies list of columns to used in the calculation of the
distance. 'first' and 'last' are valid indices.
(default: first-last)</pre>
<pre> -V
Invert matching sense of column indices.</pre>
<pre> -R <col1,col2-col4,...>
Specifies list of columns to used in the calculation of the
distance. 'first' and 'last' are valid indices.
(default: first-last)</pre>
<pre> -V
Invert matching sense of column indices.</pre>
<!-- options-end -->
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 8034 $
*/
public class FilteredDistance implements DistanceFunction, OptionHandler, Serializable {
/** The distance function to use. */
DistanceFunction m_Distance = new EuclideanDistance();
/** The filter to use. */
Filter m_Filter = new RandomProjection();
/** Remove filter to remove attributes if required. */
Remove m_Remove = new Remove();
/**
* Default constructor: need to set up Remove filter.
*/
public FilteredDistance() {
m_Remove.setInvertSelection(true);
m_Remove.setAttributeIndices("first-last");
}
/**
* Returns a string describing this object.
*
* @return a description of the evaluator suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return
"Applies the given filter before calling the given distance function.";
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String filterTipText() {
return "The filter to be used.";
}
/**
* Sets the filter
*
* @param filter the filter with all options set.
*/
public void setFilter(Filter filter) {
m_Filter = filter;
}
/**
* Gets the filter used.
*
* @return the filter
*/
public Filter getFilter() {
return m_Filter;
}
/**
* Returns the tip text for this property
* @return tip text for this property suitable for
* displaying in the explorer/experimenter gui
*/
public String distanceTipText() {
return "The distance to be used.";
}
/**
* Sets the distance
*
* @param distance the distance with all options set.
*/
public void setDistance(DistanceFunction distance) {
m_Distance = distance;
}
/**
* Gets the distance used.
*
* @return the distance
*/
public DistanceFunction getDistance() {
return m_Distance;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.add(new Option("\tThe filter to use. (default: weka.unsupervised.attribute.RandomProjection",
"F", 1, "-F"));
result.addElement(new Option("\tThe distance function to use. (default: weka.core.EuclideanDistance",
"E", 0, "-E"));
if (m_Filter instanceof OptionHandler) {
result.addElement(new Option(
"",
"", 0, "\nOptions specific to filter "
+ m_Filter.getClass().getName() + ":"));
result.addAll(Collections.list(((OptionHandler)m_Filter).listOptions()));
}
if (m_Distance instanceof OptionHandler) {
result.addElement(new Option(
"",
"", 0, "\nOptions specific to distance function "
+ m_Distance.getClass().getName() + ":"));
result.addAll(Collections.list(((OptionHandler)m_Distance).listOptions()));
}
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.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()
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-R");
result.add(getAttributeIndices());
if (getInvertSelection()) {
result.add("-V");
}
result.add("-F");
result.add("" + getFilterSpec());
result.add("-D");
result.add("" + getDistanceSpec());
return result.toArray(new String[result.size()]);
}
/**
* Gets the filter specification string, which contains the class name of
* the filter and any options to the filter
*
* @return the filter string.
*/
protected String getFilterSpec() {
Filter c = getFilter();
if (c instanceof OptionHandler) {
return c.getClass().getName() + " "
+ Utils.joinOptions(((OptionHandler)c).getOptions());
}
return c.getClass().getName();
}
/**
* Gets the distance specification string, which contains the class name of
* the distance and any options to the distance
*
* @return the distance string.
*/
protected String getDistanceSpec() {
DistanceFunction c = getDistance();
if (c instanceof OptionHandler) {
return c.getClass().getName() + " "
+ Utils.joinOptions(((OptionHandler)c).getOptions());
}
return c.getClass().getName();
}
/**
* 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
*/
@Override
public void setOptions(String[] options) throws Exception {
String distance = Utils.getOption('D', options);
if (distance.length() != 0) {
String distanceSpec[] = Utils.splitOptions(distance);
if (distanceSpec.length == 0) {
throw new Exception("Invalid distance specification string.");
}
String className = distanceSpec[0];
distanceSpec[0] = "";
setDistance((DistanceFunction) Utils.forName(
DistanceFunction.class, className, distanceSpec));
} else {
setDistance(new EuclideanDistance());
}
String filter = Utils.getOption('F', options);
if (filter.length() != 0) {
String filterSpec[] = Utils.splitOptions(filter);
if (filterSpec.length == 0) {
throw new Exception("Invalid filter specification string.");
}
String className = filterSpec[0];
filterSpec[0] = "";
setFilter((Filter) Utils.forName(
Filter.class, className, filterSpec));
} else {
setFilter(new RandomProjection());
}
String tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} else {
setAttributeIndices("first-last");
}
setInvertSelection(Utils.getFlag('V', options));
}
/**
* Sets the instances.
*
* @param insts the instances to use
*/
public void setInstances(Instances insts) {
try {
m_Remove.setInputFormat(insts);
Instances reducedInstances = Filter.useFilter(insts, m_Remove);
m_Filter.setInputFormat(reducedInstances);
m_Distance.setInstances(Filter.useFilter(reducedInstances, m_Filter));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* returns the instances currently set.
*
* @return the current instances
*/
public Instances getInstances() {
return m_Distance.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
*
* @param value the new attribute index range
*/
public void setAttributeIndices(String value) {
m_Remove.setAttributeIndices(value);
}
/**
* Gets the range of attributes used in the calculation of the distance.
*
* @return the attribute index range
*/
public String getAttributeIndices() {
return m_Remove.getAttributeIndices();
}
/**
* Sets whether the matching sense of attribute indices is inverted or not.
*
* @param value if true the matching sense is inverted
*/
public void setInvertSelection(boolean value) {
m_Remove.setInvertSelection(!value);
}
/**
* Gets whether the matching sense of attribute indices is inverted or not.
*
* @return true if the matching sense is inverted
*/
public boolean getInvertSelection() {
return !m_Remove.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
*/
public double distance(Instance first, Instance second) {
return distance(first, second, Double.POSITIVE_INFINITY, null);
}
/**
* 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
*/
public double distance(Instance first, Instance second, PerformanceStats stats)
throws Exception {
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
* 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.
*/
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
* 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) {
try {
m_Remove.input(first);
m_Filter.input(m_Remove.output());
Instance firstFiltered = m_Filter.output();
m_Remove.input(second);
m_Filter.input(m_Remove.output());
Instance secondFiltered = m_Filter.output();
return m_Distance.distance(firstFiltered, secondFiltered, cutOffValue, stats);
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
/**
* 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
* manipulation.
*
* @param distances the distances to post-process
*/
public void postProcessDistances(double distances[]) {
m_Distance.postProcessDistances(distances);
}
/**
* Update the distance function (if necessary) for the newly added instance.
*
* @param ins the instance to add
*/
public void update(Instance ins) {
try {
m_Remove.input(ins);
m_Filter.input(m_Remove.output());
m_Distance.update(m_Filter.output());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Free any references to training instances
*/
public void clean() {
m_Distance.clean();
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/FindWithCapabilities.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* FindWithCapabilities.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import weka.core.Capabilities.Capability;
import weka.gui.GenericPropertiesCreator;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* Locates all classes with certain capabilities. One should keep in mind, that
* works only with the default capabilities of a scheme and doesn't take
* dependencies into account. E.g., a meta-classifier that could have a base
* classifier handling numeric classes, but by default uses one with a nominal
* class, will never show up in a search for schemes that handle numeric
* classes.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* All class and attribute options can be prefixed with 'not',
* e.g., '-not-numeric-class'. This makes sure that the returned
* schemes 'cannot' handle numeric classes.
* </pre>
*
* <pre>
* -num-instances <num>
* The minimum number of instances (default 1).
* </pre>
*
* <pre>
* -unary-class
* Must handle unray classes.
* </pre>
*
* <pre>
* -binary-class
* Must handle binary classes.
* </pre>
*
* <pre>
* -nominal-class
* Must handle nominal classes.
* </pre>
*
* <pre>
* -numeric-class
* Must handle numeric classes.
* </pre>
*
* <pre>
* -string-class
* Must handle string classes.
* </pre>
*
* <pre>
* -date-class
* Must handle date classes.
* </pre>
*
* <pre>
* -relational-class
* Must handle relational classes.
* </pre>
*
* <pre>
* -missing-class-values
* Must handle missing class values.
* </pre>
*
* <pre>
* -no-class
* Doesn't need a class.
* </pre>
*
* <pre>
* -unary-atts
* Must handle unary attributes.
* </pre>
*
* <pre>
* -binary-atts
* Must handle binary attributes.
* </pre>
*
* <pre>
* -nominal-atts
* Must handle nominal attributes.
* </pre>
*
* <pre>
* -numeric-atts
* Must handle numeric attributes.
* </pre>
*
* <pre>
* -string-atts
* Must handle string attributes.
* </pre>
*
* <pre>
* -date-atts
* Must handle date attributes.
* </pre>
*
* <pre>
* -relational-atts
* Must handle relational attributes.
* </pre>
*
* <pre>
* -missing-att-values
* Must handle missing attribute values.
* </pre>
*
* <pre>
* -only-multiinstance
* Must handle multi-instance data.
* </pre>
*
* <pre>
* -W <classname>
* The Capabilities handler to base the handling on.
* The other parameters can be used to override the ones
* determined from the handler. Additional parameters for
* handler can be passed on after the '--'.
* Either '-W' or '-t' can be used.
* </pre>
*
* <pre>
* -t <file>
* The dataset to base the capabilities on.
* The other parameters can be used to override the ones
* determined from the handler.
* Either '-t' or '-W' can be used.
* </pre>
*
* <pre>
* -c <num>
* The index of the class attribute, -1 for none.
* 'first' and 'last' are also valid.
* Only in conjunction with option '-t'.
* </pre>
*
* <pre>
* -superclass
* Superclass to look for in the packages.
* </pre>
*
* <pre>
* -packages
* Comma-separated list of packages to search in.
* </pre>
*
* <pre>
* -generic
* Retrieves the package list from the GenericPropertiesCreator
* for the given superclass. (overrides -packages <list>).
* </pre>
*
* <pre>
* -misses
* Also prints the classname that didn't match the criteria.
* </pre>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Capabilities
* @see Capabilities.Capability
* @see GenericPropertiesCreator
*/
public class FindWithCapabilities implements OptionHandler,
CapabilitiesHandler,
RevisionHandler, CommandlineRunnable {
/** the capabilities to look for. */
protected Capabilities m_Capabilities = new Capabilities(this);
/** the capabilities to look for to "not have". */
protected Capabilities m_NotCapabilities = new Capabilities(this);
/** the packages to search in. */
protected Vector<String> m_Packages = new Vector<String>();
/** a capabilities handler to retrieve the capabilities from. */
protected CapabilitiesHandler m_Handler = null;
/** a file the capabilities can be based on. */
protected String m_Filename = "";
/** the class index, in case the capabilities are based on a file. */
protected SingleIndex m_ClassIndex = new SingleIndex();
/**
* the superclass from the GenericPropertiesCreator to retrieve the packages
* from.
*/
protected String m_Superclass = "";
/** whether to use the GenericPropertiesCreator with the superclass. */
protected boolean m_GenericPropertiesCreator = false;
/** the classes that matched. */
protected Vector<String> m_Matches = new Vector<String>();
/** the class that didn't match. */
protected Vector<String> m_Misses = new Vector<String>();
/** Whether capabilities should not be checked */
protected boolean m_DoNotCheckCapabilities = false;
/**
* Set whether not to check capabilities.
*
* @param doNotCheckCapabilities true if capabilities are not to be checked.
*/
public void setDoNotCheckCapabilities(boolean doNotCheckCapabilities) {
m_DoNotCheckCapabilities = doNotCheckCapabilities;
}
/**
* Get whether capabilities checking is turned off.
*
* @return true if capabilities checking is turned off.
*/
public boolean getDoNotCheckCapabilities() {
return m_DoNotCheckCapabilities;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("", "", 0,
"All class and attribute options can be prefixed with 'not',\n"
+ "e.g., '-not-numeric-class'. This makes sure that the returned\n"
+ "schemes 'cannot' handle numeric classes."));
result.addElement(new Option(
"\tThe minimum number of instances (default 1).", "num-instances", 1,
"-num-instances <num>"));
result.addElement(new Option("\tMust handle unray classes.", "unary-class",
0, "-unary-class"));
result.addElement(new Option("\tMust handle binary classes.",
"binary-class", 0, "-binary-class"));
result.addElement(new Option("\tMust handle nominal classes.",
"nominal-class", 0, "-nominal-class"));
result.addElement(new Option("\tMust handle numeric classes.",
"numeric-class", 0, "-numeric-class"));
result.addElement(new Option("\tMust handle string classes.",
"string-class", 0, "-string-class"));
result.addElement(new Option("\tMust handle date classes.", "date-class",
0, "-date-class"));
result.addElement(new Option("\tMust handle relational classes.",
"relational-class", 0, "-relational-class"));
result.addElement(new Option("\tMust handle missing class values.",
"missing-class-values", 0, "-missing-class-values"));
result.addElement(new Option("\tDoesn't need a class.", "no-class", 0,
"-no-class"));
result.addElement(new Option("\tMust handle unary attributes.",
"unary-atts", 0, "-unary-atts"));
result.addElement(new Option("\tMust handle binary attributes.",
"binary-atts", 0, "-binary-atts"));
result.addElement(new Option("\tMust handle nominal attributes.",
"nominal-atts", 0, "-nominal-atts"));
result.addElement(new Option("\tMust handle numeric attributes.",
"numeric-atts", 0, "-numeric-atts"));
result.addElement(new Option("\tMust handle string attributes.",
"string-atts", 0, "-string-atts"));
result.addElement(new Option("\tMust handle date attributes.", "date-atts",
0, "-date-atts"));
result.addElement(new Option("\tMust handle relational attributes.",
"relational-atts", 0, "-relational-atts"));
result.addElement(new Option("\tMust handle missing attribute values.",
"missing-att-values", 0, "-missing-att-values"));
result.addElement(new Option("\tMust handle multi-instance data.",
"only-multiinstance", 0, "-only-multiinstance"));
result.addElement(new Option(
"\tThe Capabilities handler to base the handling on.\n"
+ "\tThe other parameters can be used to override the ones\n"
+ "\tdetermined from the handler. Additional parameters for\n"
+ "\thandler can be passed on after the '--'.\n"
+ "\tEither '-W' or '-t' can be used.", "W", 1, "-W <classname>"));
result.addElement(new Option("\tThe dataset to base the capabilities on.\n"
+ "\tThe other parameters can be used to override the ones\n"
+ "\tdetermined from the handler.\n"
+ "\tEither '-t' or '-W' can be used.", "t", 1, "-t <file>"));
result.addElement(new Option(
"\tThe index of the class attribute, -1 for none.\n"
+ "\t'first' and 'last' are also valid.\n"
+ "\tOnly in conjunction with option '-t'.", "c", 1, "-c <num>"));
result.addElement(new Option("\tSuperclass to look for in the packages.\n",
"superclass", 1, "-superclass"));
result.addElement(new Option(
"\tComma-separated list of packages to search in.", "packages", 1,
"-packages"));
result.addElement(new Option(
"\tRetrieves the package list from the GenericPropertiesCreator\n"
+ "\tfor the given superclass. (overrides -packages <list>).",
"generic", 1, "-generic"));
result.addElement(new Option(
"\tAlso prints the classname that didn't match the criteria.", "misses",
0, "-misses"));
return result.elements();
}
/**
* 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
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
Class<?> cls;
CapabilitiesHandler handler;
boolean initialized;
StringTokenizer tok;
GenericPropertiesCreator creator;
Properties props;
m_Capabilities = new Capabilities(this);
initialized = false;
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() != 0) {
cls = Class.forName(tmpStr);
if (InheritanceUtils.hasInterface(CapabilitiesHandler.class, cls)) {
initialized = true;
handler = (CapabilitiesHandler) cls.newInstance();
if (handler instanceof OptionHandler) {
((OptionHandler) handler).setOptions(Utils.partitionOptions(options));
}
setHandler(handler);
} else {
throw new IllegalArgumentException("Class '" + tmpStr
+ "' is not a CapabilitiesHandler!");
}
} else {
tmpStr = Utils.getOption('c', options);
if (tmpStr.length() != 0) {
setClassIndex(tmpStr);
} else {
setClassIndex("last");
}
tmpStr = Utils.getOption('t', options);
setFilename(tmpStr);
}
tmpStr = Utils.getOption("num-instances", options);
if (tmpStr.length() != 0) {
m_Capabilities.setMinimumNumberInstances(Integer.parseInt(tmpStr));
} else if (!initialized) {
m_Capabilities.setMinimumNumberInstances(1);
}
// allowed
if (Utils.getFlag("no-class", options)) {
enable(Capability.NO_CLASS);
}
// not allowed
if (Utils.getFlag("not-no-class", options)) {
enableNot(Capability.NO_CLASS);
}
if (!m_Capabilities.handles(Capability.NO_CLASS)) {
// allowed
if (Utils.getFlag("nominal-class", options)) {
enable(Capability.NOMINAL_CLASS);
disable(Capability.BINARY_CLASS);
}
if (Utils.getFlag("binary-class", options)) {
enable(Capability.BINARY_CLASS);
disable(Capability.UNARY_CLASS);
}
if (Utils.getFlag("unary-class", options)) {
enable(Capability.UNARY_CLASS);
}
if (Utils.getFlag("numeric-class", options)) {
enable(Capability.NUMERIC_CLASS);
}
if (Utils.getFlag("string-class", options)) {
enable(Capability.STRING_CLASS);
}
if (Utils.getFlag("date-class", options)) {
enable(Capability.DATE_CLASS);
}
if (Utils.getFlag("relational-class", options)) {
enable(Capability.RELATIONAL_CLASS);
}
if (Utils.getFlag("missing-class-values", options)) {
enable(Capability.MISSING_CLASS_VALUES);
}
}
// not allowed
if (Utils.getFlag("not-nominal-class", options)) {
enableNot(Capability.NOMINAL_CLASS);
disableNot(Capability.BINARY_CLASS);
}
if (Utils.getFlag("not-binary-class", options)) {
enableNot(Capability.BINARY_CLASS);
disableNot(Capability.UNARY_CLASS);
}
if (Utils.getFlag("not-unary-class", options)) {
enableNot(Capability.UNARY_CLASS);
}
if (Utils.getFlag("not-numeric-class", options)) {
enableNot(Capability.NUMERIC_CLASS);
}
if (Utils.getFlag("not-string-class", options)) {
enableNot(Capability.STRING_CLASS);
}
if (Utils.getFlag("not-date-class", options)) {
enableNot(Capability.DATE_CLASS);
}
if (Utils.getFlag("not-relational-class", options)) {
enableNot(Capability.RELATIONAL_CLASS);
}
if (Utils.getFlag("not-relational-class", options)) {
enableNot(Capability.RELATIONAL_CLASS);
}
if (Utils.getFlag("not-missing-class-values", options)) {
enableNot(Capability.MISSING_CLASS_VALUES);
}
// allowed
if (Utils.getFlag("nominal-atts", options)) {
enable(Capability.NOMINAL_ATTRIBUTES);
disable(Capability.BINARY_ATTRIBUTES);
}
if (Utils.getFlag("binary-atts", options)) {
enable(Capability.BINARY_ATTRIBUTES);
disable(Capability.UNARY_ATTRIBUTES);
}
if (Utils.getFlag("unary-atts", options)) {
enable(Capability.UNARY_ATTRIBUTES);
}
if (Utils.getFlag("numeric-atts", options)) {
enable(Capability.NUMERIC_ATTRIBUTES);
}
if (Utils.getFlag("string-atts", options)) {
enable(Capability.STRING_ATTRIBUTES);
}
if (Utils.getFlag("date-atts", options)) {
enable(Capability.DATE_ATTRIBUTES);
}
if (Utils.getFlag("relational-atts", options)) {
enable(Capability.RELATIONAL_ATTRIBUTES);
}
if (Utils.getFlag("missing-att-values", options)) {
enable(Capability.MISSING_VALUES);
}
// not allowed
if (Utils.getFlag("not-nominal-atts", options)) {
enableNot(Capability.NOMINAL_ATTRIBUTES);
disableNot(Capability.BINARY_ATTRIBUTES);
}
if (Utils.getFlag("not-binary-atts", options)) {
enableNot(Capability.BINARY_ATTRIBUTES);
disableNot(Capability.UNARY_ATTRIBUTES);
}
if (Utils.getFlag("not-unary-atts", options)) {
enableNot(Capability.UNARY_ATTRIBUTES);
}
if (Utils.getFlag("not-numeric-atts", options)) {
enableNot(Capability.NUMERIC_ATTRIBUTES);
}
if (Utils.getFlag("not-string-atts", options)) {
enableNot(Capability.STRING_ATTRIBUTES);
}
if (Utils.getFlag("not-date-atts", options)) {
enableNot(Capability.DATE_ATTRIBUTES);
}
if (Utils.getFlag("not-relational-atts", options)) {
enableNot(Capability.RELATIONAL_ATTRIBUTES);
}
if (Utils.getFlag("not-missing-att-values", options)) {
enableNot(Capability.MISSING_VALUES);
}
if (Utils.getFlag("only-multiinstance", options)) {
enable(Capability.ONLY_MULTIINSTANCE);
}
tmpStr = Utils.getOption("superclass", options);
if (tmpStr.length() != 0) {
m_Superclass = tmpStr;
} else {
throw new IllegalArgumentException("A superclass has to be specified!");
}
tmpStr = Utils.getOption("packages", options);
if (tmpStr.length() != 0) {
tok = new StringTokenizer(tmpStr, ",");
m_Packages = new Vector<String>();
while (tok.hasMoreTokens()) {
m_Packages.add(tok.nextToken());
}
}
if (Utils.getFlag("generic", options)) {
creator = new GenericPropertiesCreator();
creator.execute(false);
props = creator.getInputProperties();
tok = new StringTokenizer(props.getProperty(m_Superclass), ",");
m_Packages = new Vector<String>();
while (tok.hasMoreTokens()) {
m_Packages.add(tok.nextToken());
}
}
}
/**
* Gets the current settings of this object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
String[] options;
int i;
result = new Vector<String>();
result.add("-num-instances");
result.add("" + m_Capabilities.getMinimumNumberInstances());
if (isEnabled(Capability.NO_CLASS)) {
result.add("-no-class");
} else {
if (isEnabled(Capability.UNARY_CLASS)) {
result.add("-unary-class");
}
if (isEnabled(Capability.BINARY_CLASS)) {
result.add("-binary-class");
}
if (isEnabled(Capability.NOMINAL_CLASS)) {
result.add("-nominal-class");
}
if (isEnabled(Capability.NUMERIC_CLASS)) {
result.add("-numeric-class");
}
if (isEnabled(Capability.STRING_CLASS)) {
result.add("-string-class");
}
if (isEnabled(Capability.DATE_CLASS)) {
result.add("-date-class");
}
if (isEnabled(Capability.RELATIONAL_CLASS)) {
result.add("-relational-class");
}
if (isEnabled(Capability.MISSING_CLASS_VALUES)) {
result.add("-missing-class-values");
}
}
if (isEnabled(Capability.UNARY_ATTRIBUTES)) {
result.add("-unary-atts");
}
if (isEnabled(Capability.BINARY_ATTRIBUTES)) {
result.add("-binary-atts");
}
if (isEnabled(Capability.NOMINAL_ATTRIBUTES)) {
result.add("-nominal-atts");
}
if (isEnabled(Capability.NUMERIC_ATTRIBUTES)) {
result.add("-numeric-atts");
}
if (isEnabled(Capability.STRING_ATTRIBUTES)) {
result.add("-string-atts");
}
if (isEnabled(Capability.DATE_ATTRIBUTES)) {
result.add("-date-atts");
}
if (isEnabled(Capability.RELATIONAL_ATTRIBUTES)) {
result.add("-relational-atts");
}
if (isEnabled(Capability.MISSING_VALUES)) {
result.add("-missing-att-values");
}
// not allowed
if (isEnabledNot(Capability.NO_CLASS)) {
result.add("-not-no-class");
}
if (isEnabledNot(Capability.UNARY_CLASS)) {
result.add("-not-unary-class");
}
if (isEnabledNot(Capability.BINARY_CLASS)) {
result.add("-not-binary-class");
}
if (isEnabledNot(Capability.NOMINAL_CLASS)) {
result.add("-not-nominal-class");
}
if (isEnabledNot(Capability.NUMERIC_CLASS)) {
result.add("-not-numeric-class");
}
if (isEnabledNot(Capability.STRING_CLASS)) {
result.add("-not-string-class");
}
if (isEnabledNot(Capability.DATE_CLASS)) {
result.add("-not-date-class");
}
if (isEnabledNot(Capability.RELATIONAL_CLASS)) {
result.add("-not-relational-class");
}
if (isEnabledNot(Capability.MISSING_CLASS_VALUES)) {
result.add("-not-missing-class-values");
}
if (isEnabledNot(Capability.UNARY_ATTRIBUTES)) {
result.add("-not-unary-atts");
}
if (isEnabledNot(Capability.BINARY_ATTRIBUTES)) {
result.add("-not-binary-atts");
}
if (isEnabledNot(Capability.NOMINAL_ATTRIBUTES)) {
result.add("-not-nominal-atts");
}
if (isEnabledNot(Capability.NUMERIC_ATTRIBUTES)) {
result.add("-not-numeric-atts");
}
if (isEnabledNot(Capability.STRING_ATTRIBUTES)) {
result.add("-not-string-atts");
}
if (isEnabledNot(Capability.DATE_ATTRIBUTES)) {
result.add("-not-date-atts");
}
if (isEnabledNot(Capability.RELATIONAL_ATTRIBUTES)) {
result.add("-not-relational-atts");
}
if (isEnabledNot(Capability.MISSING_VALUES)) {
result.add("-not-missing-att-values");
}
if (isEnabled(Capability.ONLY_MULTIINSTANCE)) {
result.add("-only-multi-instance");
}
if (getHandler() != null) {
result.add("-W");
result.add(getHandler().getClass().getName());
if (getHandler() instanceof OptionHandler) {
result.add("--");
options = ((OptionHandler) getHandler()).getOptions();
for (i = 0; i < options.length; i++) {
result.add(options[i]);
}
}
} else if (getFilename().length() != 0) {
result.add("-t");
result.add(getFilename());
result.add("-c");
result.add(m_ClassIndex.getSingleIndex());
}
if (m_Superclass.length() != 0) {
result.add("-superclass");
result.add(m_Superclass);
} else {
result.add("-packages");
result.add(m_Packages.toString().replaceAll("\\[", "")
.replaceAll("\\]", ""));
}
return result.toArray(new String[result.size()]);
}
/**
* sets the Capabilities handler to generate the data for.
*
* @param value the handler
*/
public void setHandler(CapabilitiesHandler value) {
m_Handler = value;
setCapabilities(m_Handler.getCapabilities());
}
/**
* returns the current set CapabilitiesHandler to generate the dataset for,
* can be null.
*
* @return the handler
*/
public CapabilitiesHandler getHandler() {
return m_Handler;
}
/**
* Sets the dataset filename to base the capabilities on. It immediately loads
* the dataset and retrieves the capabilities from it.
*
* @param value the filename of the dataset
*/
public void setFilename(String value) {
Instances insts;
m_Filename = value;
if (m_Filename.length() != 0) {
try {
insts = new Instances(new BufferedReader(new FileReader(m_Filename)));
m_ClassIndex.setUpper(insts.numAttributes());
insts.setClassIndex(Integer.parseInt(getClassIndex()) - 1);
setCapabilities(Capabilities.forInstances(insts));
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* returns the current filename for the dataset to base the capabilities on.
*
* @return the filename of the dataset
*/
public String getFilename() {
return m_Filename;
}
/**
* sets the class index, -1 for none, first and last are also valid.
*
* @param value the class index
*/
public void setClassIndex(String value) {
if (value.equals("-1")) {
m_ClassIndex = null;
} else {
m_ClassIndex = new SingleIndex(value);
}
}
/**
* returns the current current class index, -1 if no class attribute.
*
* @return the class index
*/
public String getClassIndex() {
if (m_ClassIndex == null) {
return "-1";
} else {
return "" + m_ClassIndex.getIndex();
}
}
/**
* enables the given capability.
*
* @param c the capability to enable
*/
public void enable(Capability c) {
m_Capabilities.enable(c);
}
/**
* whether the given capability is enabled.
*
* @param c the capability to enable
* @return true if the capability is enabled
*/
public boolean isEnabled(Capability c) {
return m_Capabilities.handles(c);
}
/**
* disables the given capability.
*
* @param c the capability to disable
*/
public void disable(Capability c) {
m_Capabilities.disable(c);
}
/**
* enables the given "not to have" capability.
*
* @param c the capability to enable
*/
public void enableNot(Capability c) {
m_NotCapabilities.enable(c);
}
/**
* whether the given "not to have" capability is enabled.
*
* @param c the capability to enable
* @return true if the capability is enabled
*/
public boolean isEnabledNot(Capability c) {
return m_NotCapabilities.handles(c);
}
/**
* disables the given "not to have" capability.
*
* @param c the capability to disable
*/
public void disableNot(Capability c) {
m_NotCapabilities.disable(c);
}
/**
* returns true if the given capability can be handled.
*
* @param c the capability to check
* @return true if the capability can be handled
*/
public boolean handles(Capability c) {
return m_Capabilities.handles(c);
}
/**
* The capabilities to search for.
*
* @return the capabilities to search for
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
return m_Capabilities;
}
/**
* Uses the given Capabilities for the search.
*
* @param c the capabilities to use for the search
*/
public void setCapabilities(Capabilities c) {
m_Capabilities = (Capabilities) c.clone();
}
/**
* The "not to have" capabilities to search for.
*
* @return the capabilities to search for
* @see Capabilities
*/
public Capabilities getNotCapabilities() {
return m_NotCapabilities;
}
/**
* Uses the given "not to have" Capabilities for the search.
*
* @param c the capabilities to use for the search
*/
public void setNotCapabilities(Capabilities c) {
m_NotCapabilities = (Capabilities) c.clone();
}
/**
* returns the matches from the last find call.
*
* @return the matching classname from the last find run
*/
public Vector<String> getMatches() {
return m_Matches;
}
/**
* returns the misses from the last find call.
*
* @return the classnames that didn't match from the last find run
*/
public Vector<String> getMisses() {
return m_Misses;
}
/**
* returns a list with all the classnames that fit the criteria.
*
* @return contains all classnames that fit the criteria
*/
public Vector<String> find() {
Vector<String> list;
int i;
Class<?> cls;
Object obj;
CapabilitiesHandler handler;
boolean fits;
Capabilities caps;
m_Matches = new Vector<String>();
m_Misses = new Vector<String>();
list = ClassDiscovery.find(m_Superclass,
m_Packages.toArray(new String[m_Packages.size()]));
for (i = 0; i < list.size(); i++) {
try {
// cls = Class.forName(list.get(i));
cls = WekaPackageClassLoaderManager.forName(list.get(i));
// obj = cls.newInstance();
obj = WekaPackageClassLoaderManager.objectForName(list.get(i));
// exclude itself
if (cls == this.getClass()) {
continue;
}
// really a CapabilitiesHandler?
if (!(obj instanceof CapabilitiesHandler)) {
continue;
}
// check capabilities enumeration
handler = (CapabilitiesHandler) obj;
caps = handler.getCapabilities();
fits = true;
for (Capability cap : Capability.values()) {
if (m_Capabilities.handles(cap)) {
if (!(caps.handles(cap))) {
fits = false;
break;
}
}
}
if (!fits) {
m_Misses.add(list.get(i));
continue;
}
// check "not" list
for (Capability cap : Capability.values()) {
if (m_NotCapabilities.handles(cap)) {
if ((caps.handles(cap))) {
fits = false;
break;
}
}
}
if (!fits) {
m_Misses.add(list.get(i));
continue;
}
// other stuff
if (caps.getMinimumNumberInstances() > m_Capabilities
.getMinimumNumberInstances()) {
m_Misses.add(list.get(i));
continue;
}
// matches all criteria!
m_Matches.add(list.get(i));
} catch (Exception e) {
// ignore
}
}
return m_Matches;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Executes the location of classes with parameters from the commandline.
*
* @param args the commandline parameters
*/
public static void main(String[] args) {
try {
FindWithCapabilities find = new FindWithCapabilities();
find.run(find, args);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override public void preExecution() throws Exception {
}
@Override public void run(Object toRun, String[] args) throws Exception {
FindWithCapabilities find;
Vector<String> list;
String result;
int i;
boolean printMisses;
Iterator<Capability> iter;
boolean first;
// make sure that packages are loaded and the GenericPropertiesCreator
// executes to populate the lists correctly
weka.gui.GenericObjectEditor.determineClasses();
printMisses = false;
try {
find = new FindWithCapabilities();
try {
printMisses = Utils.getFlag("misses", args);
find.setOptions(args);
Utils.checkForRemainingOptions(args);
} catch (Exception ex) {
result = ex.getMessage() + "\n\n"
+ find.getClass().getName().replaceAll(".*\\.", "") + " Options:\n\n";
Enumeration<Option> enm = find.listOptions();
while (enm.hasMoreElements()) {
Option option = enm.nextElement();
result += option.synopsis() + "\n" + option.description() + "\n";
}
throw new Exception(result);
}
System.out.println("\nSearching for the following Capabilities:");
// allowed
System.out.print("- allowed: ");
iter = find.getCapabilities().capabilities();
first = true;
while (iter.hasNext()) {
if (!first) {
System.out.print(", ");
}
first = false;
System.out.print(iter.next());
}
System.out.println();
// not allowed
System.out.print("- not allowed: ");
iter = find.getNotCapabilities().capabilities();
first = true;
if (iter.hasNext()) {
while (iter.hasNext()) {
if (!first) {
System.out.print(", ");
}
first = false;
System.out.print(iter.next());
}
System.out.println();
} else {
System.out.println("-");
}
find.find();
// matches
list = find.getMatches();
if (list.size() == 1) {
System.out.println("\nFound " + list.size()
+ " class that matched the criteria:\n");
} else {
System.out.println("\nFound " + list.size()
+ " classes that matched the criteria:\n");
}
for (i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
// misses
if (printMisses) {
list = find.getMisses();
if (list.size() == 1) {
System.out.println("\nFound " + list.size()
+ " class that didn't match the criteria:\n");
} else {
System.out.println("\nFound " + list.size()
+ " classes that didn't match the criteria:\n");
}
for (i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
System.out.println();
} catch (Exception ex) {
System.err.println(ex.getMessage());
} finally {
System.exit(0);
}
}
@Override public void postExecution() throws Exception {
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/FontHelper.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* FontHelper.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.awt.Font;
/**
* Wrapper class for Font objects. Fonts wrapped in this class can
* be serialized by Weka's XML serialization mechanism.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: $
*/
public class FontHelper {
/** The name of the font */
protected String m_fontName;
/** The style of the font */
protected int m_fontStyle;
/** The font size */
protected int m_fontSize;
/**
* Constructor
*
* @param font the font to wrap
*/
public FontHelper(Font font) {
m_fontName = font.getFontName();
m_fontSize = font.getSize();
m_fontStyle = font.getStyle();
}
/**
* No-op constructor (for beans conformity)
*/
public FontHelper() {
}
/**
* Set the font name
*
* @param fontName the name of the font
*/
public void setFontName(String fontName) {
m_fontName = fontName;
}
/**
* Get the font name
*
* @return the font name
*/
public String getFontName() {
return m_fontName;
}
/**
* Set the font style (see constants in Font class)
*
* @param style the style of the font
*/
public void setFontStyle(int style) {
m_fontStyle = style;
}
/**
* Get the font style (see constants in Font class)
*
* @return the style of the font
*/
public int getFontStyle() {
return m_fontStyle;
}
/**
* Set the font size
*
* @param size the size
*/
public void setFontSize(int size) {
m_fontSize = size;
}
/**
* Get the font size
*
* @return the size
*/
public int getFontSize() {
return m_fontSize;
}
/**
* Get the Font wrapped by this instance
*
* @return the Font object
*/
public Font getFont() {
if (m_fontName != null) {
return new Font(m_fontName, m_fontStyle, m_fontSize);
}
return new Font("Monospaced", Font.PLAIN, 12);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/GlobalInfoJavadoc.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* GlobalInfoJavadoc.java
* Copyright (C) 2006-2012,2015 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.lang.reflect.Method;
/**
* Generates Javadoc comments from the class's globalInfo method. Can
* automatically update the comments if they're surrounded by
* the GLOBALINFO_STARTTAG and GLOBALINFO_ENDTAG (the indention is determined via
* the GLOBALINFO_STARTTAG). <br><br>
*
<!-- options-start -->
* Valid options are: <br>
*
* <pre> -W <classname>
* The class to load.</pre>
*
* <pre> -nostars
* Suppresses the '*' in the Javadoc.</pre>
*
* <pre> -dir <dir>
* The directory above the package hierarchy of the class.</pre>
*
* <pre> -silent
* Suppresses printing in the console.</pre>
*
<!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see #GLOBALINFO_METHOD
* @see #GLOBALINFO_STARTTAG
* @see #GLOBALINFO_ENDTAG
*/
public class GlobalInfoJavadoc
extends Javadoc {
/** the globalInfo method name */
public final static String GLOBALINFO_METHOD = "globalInfo";
/** the start comment tag for inserting the generated Javadoc */
public final static String GLOBALINFO_STARTTAG = "<!-- globalinfo-start -->";
/** the end comment tag for inserting the generated Javadoc */
public final static String GLOBALINFO_ENDTAG = "<!-- globalinfo-end -->";
/**
* default constructor
*/
public GlobalInfoJavadoc() {
super();
m_StartTag = new String[1];
m_EndTag = new String[1];
m_StartTag[0] = GLOBALINFO_STARTTAG;
m_EndTag[0] = GLOBALINFO_ENDTAG;
}
/**
* generates and returns the Javadoc for the specified start/end tag pair.
*
* @param index the index in the start/end tag array
* @return the generated Javadoc
* @throws Exception in case the generation fails
*/
protected String generateJavadoc(int index) throws Exception {
String result;
Method method;
result = "";
if (index == 0) {
if (!canInstantiateClass())
return result;
try {
method = getInstance().getClass().getMethod(GLOBALINFO_METHOD, (Class[]) null);
}
catch (Exception e) {
// no method "globalInfo"
return result;
}
// retrieve global info
result = toHTML((String) method.invoke(getInstance(), (Object[]) null));
result = result.trim() + "\n<br><br>\n";
// stars?
if (getUseStars())
result = indent(result, 1, "* ");
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Parses the given commandline parameters and generates the Javadoc.
*
* @param args the commandline parameters for the object
*/
public static void main(String[] args) {
runJavadoc(new GlobalInfoJavadoc(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/InheritanceUtils.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* InheritanceUtils.java
* Copyright (C) 2017 University of Waikato, Hamilton, NZ
*/
package weka.core;
/**
* Helper class for inheritance related operations.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class InheritanceUtils {
/**
* Checks whether the "otherclass" is a subclass of the given "superclass".
*
* @param superclass the superclass to check against
* @param otherclass this class is checked whether it is a subclass of the the
* superclass
* @return TRUE if "otherclass" is a true subclass
*/
public static boolean isSubclass(String superclass, String otherclass) {
try {
// return isSubclass(Class.forName(superclass), Class.forName(otherclass));
return isSubclass(WekaPackageClassLoaderManager.forName(superclass), WekaPackageClassLoaderManager
.forName(otherclass));
} catch (Exception e) {
return false;
}
}
/**
* Checks whether the "otherclass" is a subclass of the given "superclass".
*
* @param superclass the superclass to check against
* @param otherclass this class is checked whether it is a subclass of the the
* superclass
* @return TRUE if "otherclass" is a true subclass
*/
public static boolean isSubclass(Class<?> superclass, Class<?> otherclass) {
Class<?> currentclass;
boolean result;
result = false;
currentclass = otherclass;
do {
result = currentclass.equals(superclass);
// topmost class reached?
if (currentclass.equals(Object.class)) {
break;
}
if (!result) {
currentclass = currentclass.getSuperclass();
}
} while (!result);
return result;
}
/**
* Checks whether the given class implements the given interface.
*
* @param intf the interface to look for in the given class
* @param cls the class to check for the interface
* @return TRUE if the class contains the interface
*/
public static boolean hasInterface(String intf, String cls) {
try {
// return hasInterface(Class.forName(intf), Class.forName(cls));
return hasInterface(WekaPackageClassLoaderManager.forName(intf), WekaPackageClassLoaderManager
.forName(cls));
} catch (Exception e) {
return false;
}
}
/**
* Checks whether the given class implements the given interface.
*
* @param intf the interface to look for in the given class
* @param cls the class to check for the interface
* @return TRUE if the class contains the interface
*/
public static boolean hasInterface(Class<?> intf, Class<?> cls) {
Class<?>[] intfs;
int i;
boolean result;
Class<?> currentclass;
result = false;
currentclass = cls;
do {
// check all the interfaces, this class implements
intfs = currentclass.getInterfaces();
for (i = 0; i < intfs.length; i++) {
if (intfs[i].equals(intf)) {
result = true;
break;
}
}
// get parent class
if (!result) {
currentclass = currentclass.getSuperclass();
// topmost class reached or no superclass?
if ((currentclass == null) || (currentclass.equals(Object.class))) {
break;
}
}
} while (!result);
return result;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Instance.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Instance.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.Enumeration;
/**
* Interface representing an instance. All values (numeric, date, nominal,
* string or relational) are internally stored as floating-point numbers in the
* original concrete class implementations (now called DenseInstance.java and
* SparseInstance.java), and the methods in this interface reflect this. If an
* attribute is nominal (or a string or relational), the stored value is the
* index of the corresponding nominal (or string or relational) value in the
* attribute's definition. We have chosen this approach in favor of a more
* elegant object-oriented approach because it is much faster.
* <p>
*
* Typical usage (code from the main() method of this class):
* <p>
*
* <code>
* ... <br>
*
* // Create empty instance with three attribute values <br>
* Instance inst = new DenseInstance(3); <br><br>
*
* // Set instance's values for the attributes "length", "weight", and "position"<br>
* inst.setValue(length, 5.3); <br>
* inst.setValue(weight, 300); <br>
* inst.setValue(position, "first"); <br><br>
*
* // Set instance's dataset to be the dataset "race" <br>
* inst.setDataset(race); <br><br>
*
* // Print the instance <br>
* System.out.println("The instance: " + inst); <br>
*
* ... <br>
* </code>
* <p>
*
* All methods that change an instance's attribute values must be safe, ie. a
* change of an instance's attribute values must not affect any other instances.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface Instance extends Copyable {
/**
* Returns the attribute with the given index.
*
* @param index the attribute's index
* @return the attribute at the given position
* @throws UnassignedDatasetException if instance doesn't have access to a
* dataset
*/
public Attribute attribute(int index);
/**
* Returns the attribute with the given index in the sparse representation.
* Same as attribute(int) for a DenseInstance.
*
* @param indexOfIndex the index of the attribute's index
* @return the attribute at the given position
* @throws UnassignedDatasetException if instance doesn't have access to a
* dataset
*/
public Attribute attributeSparse(int indexOfIndex);
/**
* Returns class attribute.
*
* @return the class attribute
* @throws UnassignedDatasetException if the class is not set or the instance
* doesn't have access to a dataset
*/
public Attribute classAttribute();
/**
* Returns the class attribute's index.
*
* @return the class index as an integer
* @throws UnassignedDatasetException if instance doesn't have access to a
* dataset
*/
public int classIndex();
/**
* Tests if an instance's class is missing.
*
* @return true if the instance's class is missing
* @throws UnassignedClassException if the class is not set or the instance
* doesn't have access to a dataset
*/
public boolean classIsMissing();
/**
* Returns an instance's class value as a floating-point number.
*
* @return the corresponding value as a double (If the corresponding attribute
* is nominal (or a string) then it returns the value's index as a
* double).
* @throws UnassignedClassException if the class is not set or the instance
* doesn't have access to a dataset
*/
public double classValue();
/**
* Copies the instance but fills up its values based on the given array
* of doubles. The copy has access to the same dataset.
*
* @param values the array with new values
* @return the new instance
*/
public Instance copy(double[] values);
/**
* Returns the dataset this instance has access to. (ie. obtains information
* about attribute types from) Null if the instance doesn't have access to a
* dataset.
*
* @return the dataset the instance has accesss to
*/
public Instances dataset();
/**
* Deletes an attribute at the given position (0 to numAttributes() - 1). Only
* succeeds if the instance does not have access to any dataset because
* otherwise inconsistencies could be introduced.
*
* @param position the attribute's position
* @throws RuntimeException if the instance has access to a dataset
*/
public void deleteAttributeAt(int position);
/**
* Returns an enumeration of all the attributes.
*
* @return enumeration of all the attributes
* @throws UnassignedDatasetException if the instance doesn't have access to a
* dataset
*/
public Enumeration<Attribute> enumerateAttributes();
/**
* Tests if the headers of two instances are equivalent.
*
* @param inst another instance
* @return true if the header of the given instance is equivalent to this
* instance's header
* @throws UnassignedDatasetException if instance doesn't have access to any
* dataset
*/
public boolean equalHeaders(Instance inst);
/**
* Checks if the headers of two instances are equivalent. If not, then returns
* a message why they differ.
*
* @param inst another instance
* @return null if the header of the given instance is equivalent to this
* instance's header, otherwise a message with details on why they
* differ
*/
public String equalHeadersMsg(Instance inst);
/**
* Tests whether an instance has a missing value. Skips the class attribute if
* set.
*
* @return true if instance has a missing value.
* @throws UnassignedDatasetException if instance doesn't have access to any
* dataset
*/
public boolean hasMissingValue();
/**
* Returns the index of the attribute stored at the given position in the
* sparse representation. Identify function for an instance of type
* DenseInstance.
*
* @param position the position
* @return the index of the attribute stored at the given position
*/
public int index(int position);
/**
* Inserts an attribute at the given position (0 to numAttributes()). Only
* succeeds if the instance does not have access to any dataset because
* otherwise inconsistencies could be introduced.
*
* @param position the attribute's position
* @throws RuntimeException if the instance has accesss to a dataset
* @throws IllegalArgumentException if the position is out of range
*/
public void insertAttributeAt(int position);
/**
* Tests if a specific value is "missing".
*
* @param attIndex the attribute's index
* @return true if the value is "missing"
*/
public boolean isMissing(int attIndex);
/**
* Tests if a specific value is "missing" in the sparse representation. Samse
* as isMissing(int) for a DenseInstance.
*
* @param indexOfIndex the index of the attribute's index
* @return true if the value is "missing"
*/
public boolean isMissingSparse(int indexOfIndex);
/**
* Tests if a specific value is "missing". The given attribute has to belong
* to a dataset.
*
* @param att the attribute
* @return true if the value is "missing"
*/
public boolean isMissing(Attribute att);
/**
* Merges this instance with the given instance and returns the result.
* Dataset is set to null. The returned instance is of the same type as this
* instance.
*
* @param inst the instance to be merged with this one
* @return the merged instances
*/
public Instance mergeInstance(Instance inst);
/**
* Returns the number of attributes.
*
* @return the number of attributes as an integer
*/
public int numAttributes();
/**
* Returns the number of class labels.
*
* @return the number of class labels as an integer if the class attribute is
* nominal, 1 otherwise.
* @throws UnassignedDatasetException if instance doesn't have access to any
* dataset
*/
public int numClasses();
/**
* Returns the number of values present in a sparse representation.
*
* @return the number of values
*/
public int numValues();
/**
* Replaces all missing values in the instance with the values contained in
* the given array. A deep copy of the vector of attribute values is performed
* before the values are replaced.
*
* @param array containing the means and modes
* @throws IllegalArgumentException if numbers of attributes are unequal
*/
public void replaceMissingValues(double[] array);
/**
* Sets the class value of an instance to be "missing". A deep copy of the
* vector of attribute values is performed before the value is set to be
* missing.
*
* @throws UnassignedClassException if the class is not set
* @throws UnassignedDatasetException if the instance doesn't have access to a
* dataset
*/
public void setClassMissing();
/**
* Sets the class value of an instance to the given value (internal
* floating-point format). A deep copy of the vector of attribute values is
* performed before the value is set.
*
* @param value the new attribute value (If the corresponding attribute is
* nominal (or a string) then this is the new value's index as a
* double).
* @throws UnassignedClassException if the class is not set
* @throws UnassignedDatasetException if the instance doesn't have access to a
* dataset
*/
public void setClassValue(double value);
/**
* Sets the class value of an instance to the given value. A deep copy of the
* vector of attribute values is performed before the value is set.
*
* @param value the new class value (If the class is a string attribute and
* the value can't be found, the value is added to the attribute).
* @throws UnassignedClassException if the class is not set
* @throws UnassignedDatasetException if the dataset is not set
* @throws IllegalArgumentException if the attribute is not nominal or a
* string, or the value couldn't be found for a nominal attribute
*/
public void setClassValue(String value);
/**
* Sets the reference to the dataset. Does not check if the instance is
* compatible with the dataset. Note: the dataset does not know about this
* instance. If the structure of the dataset's header gets changed, this
* instance will not be adjusted automatically.
*
* @param instances the reference to the dataset
*/
public void setDataset(Instances instances);
/**
* Sets a specific value to be "missing". Performs a deep copy of the vector
* of attribute values before the value is set to be missing.
*
* @param attIndex the attribute's index
*/
public void setMissing(int attIndex);
/**
* Sets a specific value to be "missing". Performs a deep copy of the vector
* of attribute values before the value is set to be missing. The given
* attribute has to belong to a dataset.
*
* @param att the attribute
*/
public void setMissing(Attribute att);
/**
* Sets a specific value in the instance to the given value (internal
* floating-point format). Performs a deep copy of the vector of attribute
* values before the value is set.
*
* @param attIndex the attribute's index
* @param value the new attribute value (If the corresponding attribute is
* nominal (or a string) then this is the new value's index as a
* double).
*/
public void setValue(int attIndex, double value);
/**
* Sets a specific value in the instance to the given value (internal
* floating-point format), given an index into the sparse representation.
* Performs a deep copy of the vector of attribute values before the value is
* set. Same as setValue(int, double) for a DenseInstance.
*
* @param indexOfIndex the index of the attribute's index
* @param value the new attribute value (If the corresponding attribute is
* nominal (or a string) then this is the new value's index as a
* double).
*/
public void setValueSparse(int indexOfIndex, double value);
/**
* Sets a value of a nominal or string attribute to the given value. Performs
* a deep copy of the vector of attribute values before the value is set.
*
* @param attIndex the attribute's index
* @param value the new attribute value (If the attribute is a string
* attribute and the value can't be found, the value is added to the
* attribute).
* @throws UnassignedDatasetException if the dataset is not set
* @throws IllegalArgumentException if the selected attribute is not nominal
* or a string, or the supplied value couldn't be found for a
* nominal attribute
*/
public void setValue(int attIndex, String value);
/**
* Sets a specific value in the instance to the given value (internal
* floating-point format). Performs a deep copy of the vector of attribute
* values before the value is set, so if you are planning on calling setValue
* many times it may be faster to create a new instance using toDoubleArray.
* The given attribute has to belong to a dataset.
*
* @param att the attribute
* @param value the new attribute value (If the corresponding attribute is
* nominal (or a string) then this is the new value's index as a
* double).
*/
public void setValue(Attribute att, double value);
/**
* Sets a value of an nominal or string attribute to the given value. Performs
* a deep copy of the vector of attribute values before the value is set, so
* if you are planning on calling setValue many times it may be faster to
* create a new instance using toDoubleArray. The given attribute has to
* belong to a dataset.
*
* @param att the attribute
* @param value the new attribute value (If the attribute is a string
* attribute and the value can't be found, the value is added to the
* attribute).
* @throws IllegalArgumentException if the the attribute is not nominal or a
* string, or the value couldn't be found for a nominal attribute
*/
public void setValue(Attribute att, String value);
/**
* Sets the weight of an instance.
*
* @param weight the weight
*/
public void setWeight(double weight);
/**
* Returns the relational value of a relational attribute.
*
* @param attIndex the attribute's index
* @return the corresponding relation as an Instances object
* @throws IllegalArgumentException if the attribute is not a relation-valued
* attribute
* @throws UnassignedDatasetException if the instance doesn't belong to a
* dataset.
*/
public Instances relationalValue(int attIndex);
/**
* Returns the relational value of a relational attribute.
*
* @param att the attribute
* @return the corresponding relation as an Instances object
* @throws IllegalArgumentException if the attribute is not a relation-valued
* attribute
* @throws UnassignedDatasetException if the instance doesn't belong to a
* dataset.
*/
public Instances relationalValue(Attribute att);
/**
* Returns the value of a nominal, string, date, or relational attribute for
* the instance as a string.
*
* @param attIndex the attribute's index
* @return the value as a string
* @throws IllegalArgumentException if the attribute is not a nominal, string,
* date, or relation-valued attribute.
* @throws UnassignedDatasetException if the instance doesn't belong to a
* dataset.
*/
public String stringValue(int attIndex);
/**
* Returns the value of a nominal, string, date, or relational attribute for
* the instance as a string.
*
* @param att the attribute
* @return the value as a string
* @throws IllegalArgumentException if the attribute is not a nominal, string,
* date, or relation-valued attribute.
* @throws UnassignedDatasetException if the instance doesn't belong to a
* dataset.
*/
public String stringValue(Attribute att);
/**
* Returns the values of each attribute as an array of doubles.
*
* @return an array containing all the instance attribute values
*/
public double[] toDoubleArray();
/**
* Returns the description of one instance (without weight appended). If the
* instance doesn't have access to a dataset, it returns the internal
* floating-point values. Quotes string values that contain whitespace
* characters.
*
* This method is used by getRandomNumberGenerator() in Instances.java in
* order to maintain backwards compatibility with weka 3.4.
*
* @param afterDecimalPoint maximum number of digits after the decimal point
* for numeric values
*
* @return the instance's description as a string
*/
public String toStringNoWeight(int afterDecimalPoint);
/**
* Returns the description of one instance (without weight appended). If the
* instance doesn't have access to a dataset, it returns the internal
* floating-point values. Quotes string values that contain whitespace
* characters.
*
* This method is used by getRandomNumberGenerator() in Instances.java in
* order to maintain backwards compatibility with weka 3.4.
*
* @return the instance's description as a string
*/
public String toStringNoWeight();
/**
* Returns the description of one instance with any numeric values printed at
* the supplied maximum number of decimal places. If the instance doesn't have
* access to a dataset, it returns the internal floating-point values. Quotes
* string values that contain whitespace characters.
*
* @param afterDecimalPoint the maximum number of digits permitted after the
* decimal point for a numeric value
*
* @return the instance's description as a string
*/
public String toStringMaxDecimalDigits(int afterDecimalPoint);
/**
* Returns the description of one value of the instance as a string. If the
* instance doesn't have access to a dataset, it returns the internal
* floating-point value. Quotes string values that contain whitespace
* characters, or if they are a question mark.
*
* @param attIndex the attribute's index
* @param afterDecimalPoint the maximum number of digits permitted after the
* decimal point for numeric values
* @return the value's description as a string
*/
public String toString(int attIndex, int afterDecimalPoint);
/**
* Returns the description of one value of the instance as a string. If the
* instance doesn't have access to a dataset, it returns the internal
* floating-point value. Quotes string values that contain whitespace
* characters, or if they are a question mark.
*
* @param attIndex the attribute's index
* @return the value's description as a string
*/
public String toString(int attIndex);
/**
* Returns the description of one value of the instance as a string. If the
* instance doesn't have access to a dataset it returns the internal
* floating-point value. Quotes string values that contain whitespace
* characters, or if they are a question mark. The given attribute has to
* belong to a dataset.
*
* @param att the attribute
* @param afterDecimalPoint the maximum number of decimal places to print
* @return the value's description as a string
*/
public String toString(Attribute att, int afterDecimalPoint);
/**
* Returns the description of one value of the instance as a string. If the
* instance doesn't have access to a dataset it returns the internal
* floating-point value. Quotes string values that contain whitespace
* characters, or if they are a question mark. The given attribute has to
* belong to a dataset.
*
* @param att the attribute
* @return the value's description as a string
*/
public String toString(Attribute att);
/**
* Returns an instance's attribute value in internal format.
*
* @param attIndex the attribute's index
* @return the specified value as a double (If the corresponding attribute is
* nominal (or a string) then it returns the value's index as a
* double).
*/
public double value(int attIndex);
/**
* Returns an instance's attribute value in internal format, given an index in
* the sparse representation. Same as value(int) for a DenseInstance.
*
* @param indexOfIndex the index of the attribute's index
* @return the specified value as a double (If the corresponding attribute is
* nominal (or a string) then it returns the value's index as a
* double).
*/
public double valueSparse(int indexOfIndex);
/**
* Returns an instance's attribute value in internal format. The given
* attribute has to belong to a dataset.
*
* @param att the attribute
* @return the specified value as a double (If the corresponding attribute is
* nominal (or a string) then it returns the value's index as a
* double).
*/
public double value(Attribute att);
/**
* Returns the instance's weight.
*
* @return the instance's weight as a double
*/
public double weight();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/InstanceComparator.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* InstanceComparator.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
/**
* A comparator for the Instance class. it can be used with or without the
* class label. Missing values are sorted at the beginning.</br>
* Can be used as comparator in the sorting and binary search algorithms of
* <code>Arrays</code> and <code>Collections</code>.
* Relational values are compared instance by instance with a nested
* InstanceComparator.
*
* @see Instance
* @author FracPete (fracpete at cs dot waikato dot ac dot nz)
* @version $Revision$
* @see java.util.Arrays
* @see java.util.Collections
*/
public class InstanceComparator
implements Comparator<Instance>, Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -6589278678230949683L;
/** whether to include the class in the comparison */
protected boolean m_IncludeClass;
/** the range of attributes to use for comparison. */
protected Range m_Range;
/**
* Initializes the comparator and includes the class in the comparison
* and all attributes included.
*/
public InstanceComparator() {
this(true);
}
/**
* Initializes the comparator with all attributes included.
*
* @param includeClass whether to include the class in the comparison
*/
public InstanceComparator(boolean includeClass) {
this(includeClass, "first-last", false);
}
/**
* Initializes the comparator.
*
* @param includeClass whether to include the class in the comparison
* @param range the attribute range string
* @param inverted whether to invert the matching sense of the att range
*/
public InstanceComparator(boolean includeClass, String range, boolean invert) {
super();
m_Range = new Range();
setIncludeClass(includeClass);
setRange(range);
setInvert(invert);
}
/**
* Sets whether the class should be included in the comparison.
*
* @param includeClass true if to include the class in the comparison
*/
public void setIncludeClass(boolean includeClass) {
m_IncludeClass = includeClass;
}
/**
* Returns whether the class is included in the comparison.
*
* @return true if the class is included
*/
public boolean getIncludeClass() {
return m_IncludeClass;
}
/**
* Sets the attribute range to use for comparison.
*
* @param value the attribute range
*/
public void setRange(String value) {
m_Range.setRanges(value);
}
/**
* Returns the attribute range to use in the comparison.
*
* @return the attribute range
*/
public String getRange() {
return m_Range.getRanges();
}
/**
* Sets whether to invert the matching sense of the attribute range.
*
* @param invert true if to invert the matching sense
*/
public void setInvert(boolean value) {
m_Range.setInvert(value);
}
/**
* Returns whether the matching sense of the attribute range is inverted.
*
* @return true if the matching sense is inverted
*/
public boolean getInvert() {
return m_Range.getInvert();
}
/**
* compares the two instances, returns -1 if o1 is smaller than o2, 0
* if equal and +1 if greater. The method assumes that both instance objects
* have the same attributes, they don't have to belong to the same dataset.
*
* @param inst1 the first instance to compare
* @param inst2 the second instance to compare
* @return returns -1 if inst1 is smaller than inst2, 0 if equal and +1
* if greater
*/
public int compare(Instance inst1, Instance inst2) {
int result;
int classindex;
int i;
Instances data1;
Instances data2;
int n;
InstanceComparator comp;
m_Range.setUpper(inst1.numAttributes() - 1);
// get class index
if (inst1.classIndex() == -1)
classindex = inst1.numAttributes() - 1;
else
classindex = inst1.classIndex();
result = 0;
for (i = 0; i < inst1.numAttributes(); i++) {
// in selected range?
if (!m_Range.isInRange(i))
continue;
// exclude class?
if (!getIncludeClass() && (i == classindex))
continue;
// comparing attribute values
// 1. special handling if missing value (NaN) is involved:
if (inst1.isMissing(i) || inst2.isMissing(i)) {
if (inst1.isMissing(i) && inst2.isMissing(i)) {
continue;
}
else {
if (inst1.isMissing(i))
result = -1;
else
result = 1;
break;
}
}
// 2. regular values:
else {
switch (inst1.attribute(i).type()) {
case Attribute.STRING:
result = inst1.stringValue(i).compareTo(inst2.stringValue(i));
break;
case Attribute.RELATIONAL:
data1 = inst1.relationalValue(i);
data2 = inst2.relationalValue(i);
n = 0;
comp = new InstanceComparator();
while ((n < data1.numInstances()) && (n < data2.numInstances()) && (result == 0)) {
result = comp.compare(data1.instance(n), data2.instance(n));
n++;
}
break;
default:
if (Utils.eq(inst1.value(i), inst2.value(i))) {
continue;
}
else {
if (inst1.value(i) < inst2.value(i))
result = -1;
else
result = 1;
break;
}
}
}
if (result != 0)
break;
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* for testing only. takes an ARFF-filename as first argument to perform
* some tests.
*/
public static void main(String[] args) throws Exception {
Instances inst;
Comparator<Instance> comp;
if (args.length == 0)
return;
// read instances
inst = new Instances(new BufferedReader(new FileReader(args[0])));
inst.setClassIndex(inst.numAttributes() - 1);
// compare incl. class
comp = new InstanceComparator();
System.out.println("\nIncluding the class");
System.out.println("comparing 1. instance with 1.: " + comp.compare(inst.instance(0), inst.instance(0)));
System.out.println("comparing 1. instance with 2.: " + comp.compare(inst.instance(0), inst.instance(1)));
System.out.println("comparing 2. instance with 1.: " + comp.compare(inst.instance(1), inst.instance(0)));
// compare excl. class
comp = new InstanceComparator(false);
System.out.println("\nExcluding the class");
System.out.println("comparing 1. instance with 1.: " + comp.compare(inst.instance(0), inst.instance(0)));
System.out.println("comparing 1. instance with 2.: " + comp.compare(inst.instance(0), inst.instance(1)));
System.out.println("comparing 2. instance with 1.: " + comp.compare(inst.instance(1), inst.instance(0)));
// sort the data on all attributes
Instances tmp = new Instances(inst);
Collections.sort(tmp, new InstanceComparator(false));
System.out.println("\nSorted on all attributes");
System.out.println(tmp);
// sort the data on 2nd attribute
tmp = new Instances(inst);
Collections.sort(tmp, new InstanceComparator(false, "2", false));
System.out.println("\nSorted on 2nd attribute");
System.out.println(tmp);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Instances.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Instances.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Serializable;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import weka.core.converters.ArffLoader.ArffReader;
import weka.core.converters.ConverterUtils.DataSource;
/**
* Class for handling an ordered set of weighted instances.
* <p>
*
* Typical usage:
* <p>
*
* <pre>
* import weka.core.converters.ConverterUtils.DataSource;
* ...
*
* // Read all the instances in the file (ARFF, CSV, XRFF, ...)
* DataSource source = new DataSource(filename);
* Instances instances = source.getDataSet();
*
* // Make the last attribute be the class
* instances.setClassIndex(instances.numAttributes() - 1);
*
* // Print header and instances.
* System.out.println("\nDataset:\n");
* System.out.println(instances);
*
* ...
* </pre>
* <p>
*
* All methods that change a set of instances are safe, ie. a change of a set of
* instances does not affect any other sets of instances. All methods that
* change a datasets's attribute information clone the dataset before it is
* changed.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Instances extends AbstractList<Instance> implements Serializable, RevisionHandler {
/** for serialization */
static final long serialVersionUID = -19412345060742748L;
/** The filename extension that should be used for arff files */
public final static String FILE_EXTENSION = ".arff";
/**
* The filename extension that should be used for bin. serialized instances
* files
*/
public final static String SERIALIZED_OBJ_FILE_EXTENSION = ".bsi";
/** The keyword used to denote the start of an arff header */
public final static String ARFF_RELATION = "@relation";
/** The keyword used to denote the start of the arff data section */
public final static String ARFF_DATA = "@data";
/** The dataset's name. */
protected/* @spec_public non_null@ */String m_RelationName;
/** The attribute information. */
protected/* @spec_public non_null@ */ArrayList<Attribute> m_Attributes;
/*
* public invariant (\forall int i; 0 <= i && i < m_Attributes.size();
* m_Attributes.get(i) != null);
*/
/** A map to quickly find attribute indices based on their names. */
protected HashMap<String, Integer> m_NamesToAttributeIndices;
/** The instances. */
protected/* @spec_public non_null@ */ArrayList<Instance> m_Instances;
/** The class attribute's index */
protected int m_ClassIndex;
// @ protected invariant classIndex() == m_ClassIndex;
/**
* The lines read so far in case of incremental loading. Since the
* StreamTokenizer will be re-initialized with every instance that is read, we
* have to keep track of the number of lines read so far.
*
* @see #readInstance(Reader)
*/
protected int m_Lines = 0;
/**
* 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).
*
* @param reader the reader
* @throws IOException if the ARFF file is not read successfully
*/
public Instances(/* @non_null@ */final Reader reader) throws IOException {
ArffReader arff = new ArffReader(reader, 1000, false);
this.initialize(arff.getData(), 1000);
arff.setRetainStringValues(true);
Instance inst;
while ((inst = arff.readInstance(this)) != null) {
this.m_Instances.add(inst);
}
this.compactify();
}
/**
* Reads the header of an ARFF file from a reader and reserves space for the
* given number of instances. Lets the class index be undefined (negative).
*
* @param reader the reader
* @param capacity the capacity
* @throws IllegalArgumentException if the header is not read successfully or
* the capacity is negative.
* @throws IOException if there is a problem with the reader.
* @deprecated instead of using this method in conjunction with the
* <code>readInstance(Reader)</code> method, one should use the
* <code>ArffLoader</code> or <code>DataSource</code> class
* instead.
* @see weka.core.converters.ArffLoader
* @see weka.core.converters.ConverterUtils.DataSource
*/
// @ requires capacity >= 0;
// @ ensures classIndex() == -1;
@Deprecated
public Instances(/* @non_null@ */final Reader reader, final int capacity) throws IOException {
ArffReader arff = new ArffReader(reader, 0);
Instances header = arff.getStructure();
this.initialize(header, capacity);
this.m_Lines = arff.getLineNo();
}
/**
* Constructor copying all instances and references to the header information
* from the given set of instances.
*
* @param dataset the set to be copied
* @throws InterruptedException
*/
public Instances(/* @non_null@ */final Instances dataset) {
this(dataset, dataset.numInstances());
try {
dataset.copyInstances(0, this, dataset.numInstances());
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
/**
* Constructor creating an empty set of instances. Copies references to the
* header information from the given set of instances. Sets the capacity of
* the set of instances to 0 if its negative.
*
* @param dataset the instances from which the header information is to be
* taken
* @param capacity the capacity of the new dataset
*/
public Instances(/* @non_null@ */final Instances dataset, final int capacity) {
this.initialize(dataset, capacity);
}
/**
* initializes with the header information of the given dataset and sets the
* capacity of the set of instances.
*
* @param dataset the dataset to use as template
* @param capacity the number of rows to reserve
*/
protected void initialize(final Instances dataset, int capacity) {
if (capacity < 0) {
capacity = 0;
}
// Strings only have to be "shallow" copied because
// they can't be modified.
this.m_ClassIndex = dataset.m_ClassIndex;
this.m_RelationName = dataset.m_RelationName;
this.m_Attributes = dataset.m_Attributes;
this.m_NamesToAttributeIndices = dataset.m_NamesToAttributeIndices;
this.m_Instances = new ArrayList<Instance>(capacity);
}
/**
* Creates a new set of instances by copying a subset of another set.
*
* @param source the set of instances from which a subset is to be created
* @param first the index of the first instance to be copied
* @param toCopy the number of instances to be copied
* @throws InterruptedException
* @throws IllegalArgumentException if first and toCopy are out of range
*/
// @ requires 0 <= first;
// @ requires 0 <= toCopy;
// @ requires first + toCopy <= source.numInstances();
public Instances(/* @non_null@ */final Instances source, final int first, final int toCopy) {
this(source, toCopy);
if ((first < 0) || ((first + toCopy) > source.numInstances())) {
throw new IllegalArgumentException("Parameters first and/or toCopy out " + "of range");
}
try {
source.copyInstances(first, this, toCopy);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
}
/**
* Creates an empty set of instances. Uses the given attribute information.
* Sets the capacity of the set of instances to 0 if its negative. Given
* attribute information must not be changed after this constructor has been
* used.
*
* @param name the name of the relation
* @param attInfo the attribute information
* @param capacity the capacity of the set
* @throws IllegalArgumentException if attribute names are not unique
*/
public Instances(/* @non_null@ */final String name, /* @non_null@ */final ArrayList<Attribute> attInfo, final int capacity) {
// check whether the attribute names are unique
HashSet<String> names = new HashSet<String>();
StringBuffer nonUniqueNames = new StringBuffer();
for (Attribute att : attInfo) {
if (names.contains(att.name())) {
nonUniqueNames.append("'" + att.name() + "' ");
}
names.add(att.name());
}
if (names.size() != attInfo.size()) {
throw new IllegalArgumentException("Attribute names are not unique!" + " Causes: " + nonUniqueNames.toString());
}
names.clear();
this.m_RelationName = name;
this.m_ClassIndex = -1;
this.m_Attributes = attInfo;
this.m_NamesToAttributeIndices = new HashMap<String, Integer>((int) (this.numAttributes() / 0.75));
for (int i = 0; i < this.numAttributes(); i++) {
this.attribute(i).setIndex(i);
this.m_NamesToAttributeIndices.put(this.attribute(i).name(), i);
}
this.m_Instances = new ArrayList<Instance>(capacity);
}
/**
* Create a copy of the structure. If the data has string or relational
* attributes, theses are replaced by empty copies. Other attributes are left
* unmodified, but the underlying list structure holding references to the attributes
* is shallow-copied, so that other Instances objects with a reference to this list are not affected.
*
* @return a copy of the instance structure.
*/
public Instances stringFreeStructure() {
ArrayList<Attribute> newAtts = new ArrayList<Attribute>();
for (Attribute att : this.m_Attributes) {
if (att.type() == Attribute.STRING) {
newAtts.add(new Attribute(att.name(), (List<String>) null, att.index()));
} else if (att.type() == Attribute.RELATIONAL) {
newAtts.add(new Attribute(att.name(), new Instances(att.relation(), 0), att.index()));
}
}
if (newAtts.size() == 0) {
return new Instances(this, 0);
}
ArrayList<Attribute> atts = Utils.cast(this.m_Attributes.clone());
for (Attribute att : newAtts) {
atts.set(att.index(), att);
}
Instances result = new Instances(this, 0);
result.m_Attributes = atts;
return result;
}
/**
* Adds one instance to the end of the set. Shallow copies instance before it
* is added. Increases the size of the dataset if it is not large enough. Does
* not check if the instance is compatible with the dataset. Note: String or
* relational values are not transferred.
*
* @param instance the instance to be added
*/
@Override
public boolean add(/* @non_null@ */final Instance instance) {
Instance newInstance = (Instance) instance.copy();
newInstance.setDataset(this);
this.m_Instances.add(newInstance);
return true;
}
/**
* Adds one instance at the given position in the list. Shallow
* copies instance before it is added. Increases the size of the
* dataset if it is not large enough. Does not check if the instance
* is compatible with the dataset. Note: String or relational values
* are not transferred.
*
* @param index position where instance is to be inserted
* @param instance the instance to be added
*/
// @ requires 0 <= index;
// @ requires index < m_Instances.size();
@Override
public void add(final int index, /* @non_null@ */final Instance instance) {
Instance newInstance = (Instance) instance.copy();
newInstance.setDataset(this);
this.m_Instances.add(index, newInstance);
}
/**
* Returns true if all attribute weights are the same and false otherwise. Returns true if there are no attributes.
* The class attribute (if set) is skipped when this test is performed.
*/
public boolean allAttributeWeightsIdentical() {
boolean foundOne = false;
double weight = 0;
for (int i = 0; i < this.numAttributes(); i++) {
if (i != this.classIndex()) {
if (foundOne && (this.attribute(i).weight() != weight)) {
return false;
} else if (!foundOne) {
foundOne = true;
weight = this.attribute(i).weight();
}
}
}
return true;
}
/**
* Returns true if all instance weights are the same and false otherwise. Returns true if there are no instances.
*/
public boolean allInstanceWeightsIdentical() {
if (this.numInstances() == 0) {
return true;
} else {
double weight = this.instance(0).weight();
for (int i = 1; i < this.numInstances(); i++) {
if (this.instance(i).weight() != weight) {
return false;
}
}
return true;
}
}
/**
* Returns an attribute.
*
* @param index the attribute's index (index starts with 0)
* @return the attribute at the given position
*/
// @ requires 0 <= index;
// @ requires index < m_Attributes.size();
// @ ensures \result != null;
public/* @pure@ */Attribute attribute(final int index) {
return this.m_Attributes.get(index);
}
/**
* Returns an attribute given its name. If there is more than one attribute
* with the same name, it returns the first one. Returns null if the attribute
* can't be found.
*
* @param name the attribute's name
* @return the attribute with the given name, null if the attribute can't be
* found
*/
public/* @pure@ */Attribute attribute(final String name) {
Integer index = this.m_NamesToAttributeIndices.get(name);
if (index != null) {
return this.attribute(index);
}
return null;
}
/**
* Checks for attributes of the given type in the dataset
*
* @param attType the attribute type to look for
* @return true if attributes of the given type are present
*/
public boolean checkForAttributeType(final int attType) {
int i = 0;
while (i < this.m_Attributes.size()) {
if (this.attribute(i++).type() == attType) {
return true;
}
}
return false;
}
/**
* Checks for string attributes in the dataset
*
* @return true if string attributes are present, false otherwise
*/
public/* @pure@ */boolean checkForStringAttributes() {
return this.checkForAttributeType(Attribute.STRING);
}
/**
* Checks if the given instance is compatible with this dataset. Only looks at
* the size of the instance and the ranges of the values for nominal and
* string attributes.
*
* @param instance the instance to check
* @return true if the instance is compatible with the dataset
*/
public/* @pure@ */boolean checkInstance(final Instance instance) {
if (instance.numAttributes() != this.numAttributes()) {
return false;
}
for (int i = 0; i < this.numAttributes(); i++) {
if (instance.isMissing(i)) {
continue;
} else if (this.attribute(i).isNominal() || this.attribute(i).isString()) {
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), this.attribute(i).numValues())) {
return false;
}
}
}
return true;
}
/**
* Returns the class attribute.
*
* @return the class attribute
* @throws UnassignedClassException if the class is not set
*/
// @ requires classIndex() >= 0;
public/* @pure@ */Attribute classAttribute() {
if (this.m_ClassIndex < 0) {
throw new UnassignedClassException("Class index is negative (not set)!");
}
return this.attribute(this.m_ClassIndex);
}
/**
* Returns the class attribute's index. Returns negative number if it's
* undefined.
*
* @return the class index as an integer
*/
// ensures \result == m_ClassIndex;
public/* @pure@ */int classIndex() {
return this.m_ClassIndex;
}
/**
* Compactifies the set of instances. Decreases the capacity of the set so
* that it matches the number of instances in the set.
*/
public void compactify() {
this.m_Instances.trimToSize();
}
/**
* Removes all instances from the set.
*/
public void delete() {
this.m_Instances = new ArrayList<Instance>();
}
/**
* Removes an instance at the given position from the set.
*
* @param index the instance's position (index starts with 0)
*/
// @ requires 0 <= index && index < numInstances();
public void delete(final int index) {
this.m_Instances.remove(index);
}
/**
* Deletes an attribute at the given position (0 to numAttributes()
* - 1). Attribute objects after the deletion point are copied so
* that their indices can be decremented. Creates a fresh list to
* hold the old and new attribute objects.
* @param position the attribute's position (position starts with 0)
* @throws IllegalArgumentException if the given index is out of range or the
* class attribute is being deleted
*/
// @ requires 0 <= position && position < numAttributes();
// @ requires position != classIndex();
public void deleteAttributeAt(final int position) {
if ((position < 0) || (position >= this.m_Attributes.size())) {
throw new IllegalArgumentException("Index out of range");
}
if (position == this.m_ClassIndex) {
throw new IllegalArgumentException("Can't delete class attribute");
}
ArrayList<Attribute> newList = new ArrayList<Attribute>(this.m_Attributes.size() - 1);
HashMap<String, Integer> newMap = new HashMap<String, Integer>((int) ((this.m_Attributes.size() - 1) / 0.75));
for (int i = 0; i < position; i++) {
Attribute att = this.m_Attributes.get(i);
newList.add(att);
newMap.put(att.name(), i);
}
for (int i = position + 1; i < this.m_Attributes.size(); i++) {
Attribute newAtt = (Attribute) this.m_Attributes.get(i).copy();
newAtt.setIndex(i - 1);
newList.add(newAtt);
newMap.put(newAtt.name(), i - 1);
}
this.m_Attributes = newList;
this.m_NamesToAttributeIndices = newMap;
if (this.m_ClassIndex > position) {
this.m_ClassIndex--;
}
for (int i = 0; i < this.numInstances(); i++) {
this.instance(i).setDataset(null);
this.instance(i).deleteAttributeAt(position);
this.instance(i).setDataset(this);
}
}
/**
* Deletes all attributes of the given type in the dataset. A deep copy of the
* attribute information is performed before an attribute is deleted.
*
* @param attType the attribute type to delete
* @throws IllegalArgumentException if attribute couldn't be successfully
* deleted (probably because it is the class attribute).
*/
public void deleteAttributeType(final int attType) {
int i = 0;
while (i < this.m_Attributes.size()) {
if (this.attribute(i).type() == attType) {
this.deleteAttributeAt(i);
} else {
i++;
}
}
}
/**
* Deletes all string attributes in the dataset. A deep copy of the attribute
* information is performed before an attribute is deleted.
*
* @throws IllegalArgumentException if string attribute couldn't be
* successfully deleted (probably because it is the class
* attribute).
* @see #deleteAttributeType(int)
*/
public void deleteStringAttributes() {
this.deleteAttributeType(Attribute.STRING);
}
/**
* Removes all instances with missing values for a particular attribute from
* the dataset.
*
* @param attIndex the attribute's index (index starts with 0)
*/
// @ requires 0 <= attIndex && attIndex < numAttributes();
public void deleteWithMissing(final int attIndex) {
ArrayList<Instance> newInstances = new ArrayList<Instance>(this.numInstances());
for (int i = 0; i < this.numInstances(); i++) {
if (!this.instance(i).isMissing(attIndex)) {
newInstances.add(this.instance(i));
}
}
this.m_Instances = newInstances;
}
/**
* Removes all instances with missing values for a particular attribute from
* the dataset.
*
* @param att the attribute
*/
public void deleteWithMissing(/* @non_null@ */final Attribute att) {
this.deleteWithMissing(att.index());
}
/**
* Removes all instances with a missing class value from the dataset.
*
* @throws UnassignedClassException if class is not set
*/
public void deleteWithMissingClass() {
if (this.m_ClassIndex < 0) {
throw new UnassignedClassException("Class index is negative (not set)!");
}
this.deleteWithMissing(this.m_ClassIndex);
}
/**
* Returns an enumeration of all the attributes. The class attribute (if set)
* is skipped by this enumeration.
*
* @return enumeration of all the attributes.
*/
public/* @non_null pure@ */Enumeration<Attribute> enumerateAttributes() {
return new WekaEnumeration<Attribute>(this.m_Attributes, this.m_ClassIndex);
}
/**
* Returns an enumeration of all instances in the dataset.
*
* @return enumeration of all instances in the dataset
*/
public/* @non_null pure@ */Enumeration<Instance> enumerateInstances() {
return new WekaEnumeration<Instance>(this.m_Instances);
}
/**
* Checks if two headers are equivalent. If not, then returns a message why
* they differ.
*
* @param dataset another dataset
* @return null if the header of the given dataset is equivalent to this
* header, otherwise a message with details on why they differ
*/
public String equalHeadersMsg(final Instances dataset) {
// Check class and all attributes
if (this.m_ClassIndex != dataset.m_ClassIndex) {
return "Class index differ: " + (this.m_ClassIndex + 1) + " != " + (dataset.m_ClassIndex + 1);
}
if (this.m_Attributes.size() != dataset.m_Attributes.size()) {
return "Different number of attributes: " + this.m_Attributes.size() + " != " + dataset.m_Attributes.size();
}
for (int i = 0; i < this.m_Attributes.size(); i++) {
String msg = this.attribute(i).equalsMsg(dataset.attribute(i));
if (msg != null) {
return "Attributes differ at position " + (i + 1) + ":\n" + msg;
}
}
return null;
}
/**
* Checks if two headers are equivalent.
*
* @param dataset another dataset
* @return true if the header of the given dataset is equivalent to this
* header
*/
public/* @pure@ */boolean equalHeaders(final Instances dataset) {
return (this.equalHeadersMsg(dataset) == null);
}
/**
* Returns the first instance in the set.
*
* @return the first instance in the set
*/
// @ requires numInstances() > 0;
public/* @non_null pure@ */Instance firstInstance() {
return this.m_Instances.get(0);
}
/**
* Returns a random number generator. The initial seed of the random number
* generator depends on the given seed and the hash code of a string
* representation of a instances chosen based on the given seed.
*
* @param seed the given seed
* @return the random number generator
*/
public Random getRandomNumberGenerator(final long seed) {
Random r = new Random(seed);
r.setSeed(this.instance(r.nextInt(this.numInstances())).toStringNoWeight().hashCode() + seed);
return r;
}
/**
* Inserts an attribute at the given position (0 to numAttributes())
* and sets all values to be missing. Shallow copies the attribute
* before it is inserted. Existing attribute objects at and after
* the insertion point are also copied so that their indices can be
* incremented. Creates a fresh list to hold the old and new
* attribute objects.
*
* @param att the attribute to be inserted
* @param position the attribute's position (position starts with 0)
* @throws IllegalArgumentException if the given index is out of range
*/
// @ requires 0 <= position;
// @ requires position <= numAttributes();
public void insertAttributeAt(/* @non_null@ */Attribute att, final int position) {
if ((position < 0) || (position > this.m_Attributes.size())) {
throw new IllegalArgumentException("Index out of range");
}
if (this.attribute(att.name()) != null) {
throw new IllegalArgumentException("Attribute name '" + att.name() + "' already in use at position #" + this.attribute(att.name()).index());
}
att = (Attribute) att.copy();
att.setIndex(position);
ArrayList<Attribute> newList = new ArrayList<Attribute>(this.m_Attributes.size() + 1);
HashMap<String, Integer> newMap = new HashMap<String, Integer>((int) ((this.m_Attributes.size() + 1) / 0.75));
for (int i = 0; i < position; i++) {
Attribute oldAtt = this.m_Attributes.get(i);
newList.add(oldAtt);
newMap.put(oldAtt.name(), i);
}
newList.add(att);
newMap.put(att.name(), position);
for (int i = position; i < this.m_Attributes.size(); i++) {
Attribute newAtt = (Attribute) this.m_Attributes.get(i).copy();
newAtt.setIndex(i + 1);
newList.add(newAtt);
newMap.put(newAtt.name(), i + 1);
}
this.m_Attributes = newList;
this.m_NamesToAttributeIndices = newMap;
for (int i = 0; i < this.numInstances(); i++) {
this.instance(i).setDataset(null);
this.instance(i).insertAttributeAt(position);
this.instance(i).setDataset(this);
}
if (this.m_ClassIndex >= position) {
this.m_ClassIndex++;
}
}
/**
* Returns the instance at the given position.
*
* @param index the instance's index (index starts with 0)
* @return the instance at the given position
*/
// @ requires 0 <= index;
// @ requires index < numInstances();
public/* @non_null pure@ */Instance instance(final int index) {
return this.m_Instances.get(index);
}
/**
* Returns the instance at the given position.
*
* @param index the instance's index (index starts with 0)
* @return the instance at the given position
*/
// @ requires 0 <= index;
// @ requires index < numInstances();
@Override
public/* @non_null pure@ */Instance get(final int index) {
return this.m_Instances.get(index);
}
/**
* Returns the kth-smallest attribute value of a numeric attribute.
*
* @param att the Attribute object
* @param k the value of k
* @return the kth-smallest value
* @throws InterruptedException
*/
public double kthSmallestValue(final Attribute att, final int k) throws InterruptedException {
return this.kthSmallestValue(att.index(), k);
}
/**
* Returns the kth-smallest attribute value of a numeric attribute. NOTE
* CHANGE: Missing values (NaN values) are now treated as Double.MAX_VALUE.
* Also, the order of the instances in the data is no longer affected.
*
* @param attIndex the attribute's index
* @param k the value of k
* @return the kth-smallest value
* @throws InterruptedException
*/
public double kthSmallestValue(final int attIndex, final int k) throws InterruptedException {
if (!this.attribute(attIndex).isNumeric()) {
throw new IllegalArgumentException("Instances: attribute must be numeric to compute kth-smallest value.");
}
if ((k < 1) || (k > this.numInstances())) {
throw new IllegalArgumentException("Instances: value for k for computing kth-smallest value too large.");
}
double[] vals = new double[this.numInstances()];
for (int i = 0; i < vals.length; i++) {
double val = this.instance(i).value(attIndex);
if (Utils.isMissingValue(val)) {
vals[i] = Double.MAX_VALUE;
} else {
vals[i] = val;
}
}
return Utils.kthSmallestValue(vals, k);
}
/**
* Returns the last instance in the set.
*
* @return the last instance in the set
*/
// @ requires numInstances() > 0;
public/* @non_null pure@ */Instance lastInstance() {
return this.m_Instances.get(this.m_Instances.size() - 1);
}
/**
* Returns the mean (mode) for a numeric (nominal) attribute as a
* floating-point value. Returns 0 if the attribute is neither nominal nor
* numeric. If all values are missing it returns zero.
*
* @param attIndex the attribute's index (index starts with 0)
* @return the mean or the mode
*/
public/* @pure@ */double meanOrMode(final int attIndex) {
double result, found;
int[] counts;
if (this.attribute(attIndex).isNumeric()) {
result = found = 0;
for (int j = 0; j < this.numInstances(); j++) {
if (!this.instance(j).isMissing(attIndex)) {
found += this.instance(j).weight();
result += this.instance(j).weight() * this.instance(j).value(attIndex);
}
}
if (found <= 0) {
return 0;
} else {
return result / found;
}
} else if (this.attribute(attIndex).isNominal()) {
counts = new int[this.attribute(attIndex).numValues()];
for (int j = 0; j < this.numInstances(); j++) {
if (!this.instance(j).isMissing(attIndex)) {
counts[(int) this.instance(j).value(attIndex)] += this.instance(j).weight();
}
}
return Utils.maxIndex(counts);
} else {
return 0;
}
}
/**
* Returns the mean (mode) for a numeric (nominal) attribute as a
* floating-point value. Returns 0 if the attribute is neither nominal nor
* numeric. If all values are missing it returns zero.
*
* @param att the attribute
* @return the mean or the mode
*/
public/* @pure@ */double meanOrMode(final Attribute att) {
return this.meanOrMode(att.index());
}
/**
* Returns the number of attributes.
*
* @return the number of attributes as an integer
*/
// @ ensures \result == m_Attributes.size();
public/* @pure@ */int numAttributes() {
return this.m_Attributes.size();
}
/**
* Returns the number of class labels.
*
* @return the number of class labels as an integer if the class attribute is
* nominal, 1 otherwise.
* @throws UnassignedClassException if the class is not set
*/
// @ requires classIndex() >= 0;
public/* @pure@ */int numClasses() {
if (this.m_ClassIndex < 0) {
throw new UnassignedClassException("Class index is negative (not set)!");
}
if (!this.classAttribute().isNominal()) {
return 1;
} else {
return this.classAttribute().numValues();
}
}
/**
* Returns the number of distinct values of a given attribute. The value
* 'missing' is not counted.
*
* @param attIndex the attribute (index starts with 0)
* @return the number of distinct values of a given attribute
* @throws InterruptedException
*/
// @ requires 0 <= attIndex;
// @ requires attIndex < numAttributes();
public/* @pure@ */int numDistinctValues(final int attIndex) throws InterruptedException {
HashSet<Double> set = new HashSet<Double>(2 * this.numInstances());
for (Instance current : this) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
double key = current.value(attIndex);
if (!Utils.isMissingValue(key)) {
set.add(key);
}
}
return set.size();
}
/**
* Returns the number of distinct values of a given attribute. The value
* 'missing' is not counted.
*
* @param att the attribute
* @return the number of distinct values of a given attribute
* @throws InterruptedException
*/
public/* @pure@ */int numDistinctValues(/* @non_null@ */final Attribute att) throws InterruptedException {
return this.numDistinctValues(att.index());
}
/**
* Returns the number of instances in the dataset.
*
* @return the number of instances in the dataset as an integer
*/
// @ ensures \result == m_Instances.size();
public/* @pure@ */int numInstances() {
return this.m_Instances.size();
}
/**
* Returns the number of instances in the dataset.
*
* @return the number of instances in the dataset as an integer
*/
// @ ensures \result == m_Instances.size();
@Override
public/* @pure@ */int size() {
return this.m_Instances.size();
}
/**
* Shuffles the instances in the set so that they are ordered randomly.
*
* @param random a random number generator
* @throws InterruptedException
*/
public void randomize(final Random random) throws InterruptedException {
for (int j = this.numInstances() - 1; j > 0; j--) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
this.swap(j, random.nextInt(j + 1));
}
}
/**
* Reads a single instance from the reader and appends it to the dataset.
* Automatically expands the dataset if it is not large enough to hold the
* instance. This method does not check for carriage return at the end of the
* line.
*
* @param reader the reader
* @return false if end of file has been reached
* @throws IOException if the information is not read successfully
* @deprecated instead of using this method in conjunction with the
* <code>readInstance(Reader)</code> method, one should use the
* <code>ArffLoader</code> or <code>DataSource</code> class
* instead.
* @see weka.core.converters.ArffLoader
* @see weka.core.converters.ConverterUtils.DataSource
*/
@Deprecated
public boolean readInstance(final Reader reader) throws IOException {
ArffReader arff = new ArffReader(reader, this, this.m_Lines, 1);
Instance inst = arff.readInstance(arff.getData(), false);
this.m_Lines = arff.getLineNo();
if (inst != null) {
this.add(inst);
return true;
} else {
return false;
}
}
/**
* Replaces the attribute at the given position (0 to
* numAttributes()) with the given attribute and sets all its values to
* be missing. Shallow copies the given attribute before it is
* inserted. Creates a fresh list to hold the old and new
* attribute objects.
*
* @param att the attribute to be inserted
* @param position the attribute's position (position starts with 0)
* @throws IllegalArgumentException if the given index is out of range
*/
// @ requires 0 <= position;
// @ requires position <= numAttributes();
public void replaceAttributeAt(/* @non_null@ */Attribute att, final int position) {
if ((position < 0) || (position > this.m_Attributes.size())) {
throw new IllegalArgumentException("Index out of range");
}
// Does the new attribute have a different name?
if (!att.name().equals(this.m_Attributes.get(position).name())) {
// Need to check if attribute name already exists
Attribute candidate = this.attribute(att.name());
if ((candidate != null) && (position != candidate.index())) {
throw new IllegalArgumentException("Attribute name '" + att.name() + "' already in use at position #" + this.attribute(att.name()).index());
}
}
att = (Attribute) att.copy();
att.setIndex(position);
ArrayList<Attribute> newList = new ArrayList<Attribute>(this.m_Attributes.size());
HashMap<String, Integer> newMap = new HashMap<String, Integer>((int) ((this.m_Attributes.size() + 1) / 0.75));
for (int i = 0; i < position; i++) {
Attribute oldAtt = this.m_Attributes.get(i);
newList.add(oldAtt);
newMap.put(oldAtt.name(), i);
}
newList.add(att);
newMap.put(att.name(), position);
for (int i = position + 1; i < this.m_Attributes.size(); i++) {
Attribute newAtt = this.m_Attributes.get(i);
newList.add(newAtt);
newMap.put(newAtt.name(), i);
}
this.m_Attributes = newList;
this.m_NamesToAttributeIndices = newMap;
for (int i = 0; i < this.numInstances(); i++) {
this.instance(i).setDataset(null);
this.instance(i).setMissing(position);
this.instance(i).setDataset(this);
}
}
/**
* Returns the relation's name.
*
* @return the relation's name as a string
*/
// @ ensures \result == m_RelationName;
public/* @pure@ */String relationName() {
return this.m_RelationName;
}
/**
* Removes the instance at the given position.
*
* @param index the instance's index (index starts with 0)
* @return the instance at the given position
*/
// @ requires 0 <= index;
// @ requires index < numInstances();
@Override
public Instance remove(final int index) {
return this.m_Instances.remove(index);
}
/**
* Renames an attribute. This change only affects this dataset.
*
* @param att the attribute's index (index starts with 0)
* @param name the new name
*/
public void renameAttribute(final int att, final String name) {
Attribute existingAtt = this.attribute(name);
if (existingAtt != null) {
if (att == existingAtt.index()) {
return; // Old name is equal to new name
} else {
throw new IllegalArgumentException("Attribute name '" + name + "' already present at position #" + existingAtt.index());
}
}
Attribute newAtt = this.attribute(att).copy(name);
ArrayList<Attribute> newVec = new ArrayList<Attribute>(this.numAttributes());
HashMap<String, Integer> newMap = new HashMap<String, Integer>((int) (this.numAttributes() / 0.75));
for (Attribute attr : this.m_Attributes) {
if (attr.index() == att) {
newVec.add(newAtt);
newMap.put(name, att);
} else {
newVec.add(attr);
newMap.put(attr.name(), attr.index());
}
}
this.m_Attributes = newVec;
this.m_NamesToAttributeIndices = newMap;
}
/**
* Sets the weight of an attribute. This change only affects this dataset.
*
* @param att the attribute
* @param weight the new weight
*/
public void setAttributeWeight(final Attribute att, final double weight) {
this.setAttributeWeight(att.index(), weight);
}
/**
* Sets the weight of an attribute. This change only affects this dataset.
*
* @param att the attribute's index (index starts with 0)
* @param weight the new weight
*/
public void setAttributeWeight(final int att, final double weight) {
Attribute existingAtt = this.attribute(att);
if (existingAtt.weight() == weight) {
return;
}
Attribute newAtt = (Attribute) existingAtt.copy();
newAtt.setWeight(weight);
ArrayList<Attribute> newVec = new ArrayList<Attribute>(this.numAttributes());
HashMap<String, Integer> newMap = new HashMap<String, Integer>((int) (this.numAttributes() / 0.75));
for (Attribute attr : this.m_Attributes) {
if (attr.index() == att) {
newVec.add(newAtt);
newMap.put(newAtt.name(), att);
} else {
newVec.add(attr);
newMap.put(attr.name(), attr.index());
}
}
this.m_Attributes = newVec;
this.m_NamesToAttributeIndices = newMap;
}
/**
* Renames an attribute. This change only affects this dataset.
*
* @param att the attribute
* @param name the new name
*/
public void renameAttribute(final Attribute att, final String name) {
this.renameAttribute(att.index(), name);
}
/**
* Renames the value of a nominal (or string) attribute value. This change
* only affects this dataset.
*
* @param att the attribute's index (index starts with 0)
* @param val the value's index (index starts with 0)
* @param name the new name
*/
public void renameAttributeValue(final int att, final int val, final String name) {
Attribute newAtt = (Attribute) this.attribute(att).copy();
ArrayList<Attribute> newVec = new ArrayList<Attribute>(this.numAttributes());
newAtt.setValue(val, name);
for (Attribute attr : this.m_Attributes) {
if (attr.index() == att) {
newVec.add(newAtt);
} else {
newVec.add(attr);
}
}
this.m_Attributes = newVec;
}
/**
* Renames the value of a nominal (or string) attribute value. This change
* only affects this dataset.
*
* @param att the attribute
* @param val the value
* @param name the new name
*/
public void renameAttributeValue(final Attribute att, final String val, final String name) {
int v = att.indexOfValue(val);
if (v == -1) {
throw new IllegalArgumentException(val + " not found");
}
this.renameAttributeValue(att.index(), v, name);
}
/**
* Creates a new dataset of the same size using random sampling with
* replacement.
*
* @param random a random number generator
* @return the new dataset
*/
public Instances resample(final Random random) {
Instances newData = new Instances(this, this.numInstances());
while (newData.numInstances() < this.numInstances()) {
newData.add(this.instance(random.nextInt(this.numInstances())));
}
return newData;
}
/**
* Creates a new dataset of the same size using random sampling with
* replacement according to the current instance weights. The weights of the
* instances in the new dataset are set to one. See also
* resampleWithWeights(Random, double[], boolean[]).
*
* @param random a random number generator
* @return the new dataset
* @throws InterruptedException
*/
public Instances resampleWithWeights(final Random random) throws InterruptedException {
return this.resampleWithWeights(random, false);
}
/**
* Creates a new dataset of the same size using random sampling with
* replacement according to the current instance weights. The weights of the
* instances in the new dataset are set to one. See also
* resampleWithWeights(Random, double[], boolean[]).
*
* @param random a random number generator
* @param sampled an array indicating what has been sampled
* @return the new dataset
* @throws InterruptedException
*/
public Instances resampleWithWeights(final Random random, final boolean[] sampled) throws InterruptedException {
return this.resampleWithWeights(random, sampled, false);
}
/**
* Creates a new dataset of the same size using random sampling with
* replacement according to the current instance weights. The weights of the
* instances in the new dataset are set to one. See also
* resampleWithWeights(Random, double[], boolean[]).
*
* @param random a random number generator
* @param representUsingWeights if true, copies are represented using weights
* in resampled data
* @return the new dataset
* @throws InterruptedException
*/
public Instances resampleWithWeights(final Random random, final boolean representUsingWeights) throws InterruptedException {
return this.resampleWithWeights(random, null, representUsingWeights);
}
/**
* Creates a new dataset of the same size using random sampling with
* replacement according to the current instance weights. The weights of the
* instances in the new dataset are set to one. See also
* resampleWithWeights(Random, double[], boolean[]).
*
* @param random a random number generator
* @param sampled an array indicating what has been sampled
* @param representUsingWeights if true, copies are represented using weights
* in resampled data
* @return the new dataset
* @throws InterruptedException
*/
public Instances resampleWithWeights(final Random random, final boolean[] sampled, final boolean representUsingWeights) throws InterruptedException {
double[] weights = new double[this.numInstances()];
for (int i = 0; i < weights.length; i++) {
weights[i] = this.instance(i).weight();
}
return this.resampleWithWeights(random, weights, sampled, representUsingWeights);
}
/**
* Creates a new dataset of the same size using random sampling with
* replacement according to the given weight vector. See also
* resampleWithWeights(Random, double[], boolean[]).
*
* @param random a random number generator
* @param weights the weight vector
* @return the new dataset
* @throws InterruptedException
* @throws IllegalArgumentException if the weights array is of the wrong
* length or contains negative weights.
*/
public Instances resampleWithWeights(final Random random, final double[] weights) throws InterruptedException {
return this.resampleWithWeights(random, weights, null);
}
/**
* Creates a new dataset of the same size using random sampling with
* replacement according to the given weight vector. The weights of the
* instances in the new dataset are set to one. The length of the weight
* vector has to be the same as the number of instances in the dataset, and
* all weights have to be positive. Uses Walker's method, see pp. 232 of
* "Stochastic Simulation" by B.D. Ripley (1987).
*
* @param random a random number generator
* @param weights the weight vector
* @param sampled an array indicating what has been sampled, can be null
* @return the new dataset
* @throws InterruptedException
* @throws IllegalArgumentException if the weights array is of the wrong
* length or contains negative weights.
*/
public Instances resampleWithWeights(final Random random, final double[] weights, final boolean[] sampled) throws InterruptedException {
return this.resampleWithWeights(random, weights, sampled, false);
}
/**
* Creates a new dataset of the same size using random sampling with
* replacement according to the given weight vector. The weights of the
* instances in the new dataset are set to one. The length of the weight
* vector has to be the same as the number of instances in the dataset, and
* all weights have to be positive. Uses Walker's method, see pp. 232 of
* "Stochastic Simulation" by B.D. Ripley (1987).
*
* @param random a random number generator
* @param weights the weight vector
* @param sampled an array indicating what has been sampled, can be null
* @param representUsingWeights if true, copies are represented using weights
* in resampled data
* @return the new dataset
* @throws InterruptedException
* @throws IllegalArgumentException if the weights array is of the wrong
* length or contains negative weights.
*/
public Instances resampleWithWeights(final Random random, final double[] weights, final boolean[] sampled, final boolean representUsingWeights) throws InterruptedException {
if (weights.length != this.numInstances()) {
throw new IllegalArgumentException("weights.length != numInstances.");
}
Instances newData = new Instances(this, this.numInstances());
if (this.numInstances() == 0) {
return newData;
}
// Walker's method, see pp. 232 of "Stochastic Simulation" by B.D. Ripley
double[] P = new double[weights.length];
System.arraycopy(weights, 0, P, 0, weights.length);
Utils.normalize(P);
double[] Q = new double[weights.length];
int[] A = new int[weights.length];
int[] W = new int[weights.length];
int M = weights.length;
int NN = -1;
int NP = M;
for (int I = 0; I < M; I++) {
if (P[I] < 0) {
throw new IllegalArgumentException("Weights have to be positive.");
}
Q[I] = M * P[I];
if (Q[I] < 1.0) {
W[++NN] = I;
} else {
W[--NP] = I;
}
}
if (NN > -1 && NP < M) {
for (int S = 0; S < M - 1; S++) {
int I = W[S];
int J = W[NP];
A[I] = J;
Q[J] += Q[I] - 1.0;
if (Q[J] < 1.0) {
NP++;
}
if (NP >= M) {
break;
}
}
// A[W[M]] = W[M];
}
for (int I = 0; I < M; I++) {
Q[I] += I;
}
// Do we need to keep track of how many copies to use?
int[] counts = null;
if (representUsingWeights) {
counts = new int[M];
}
for (int i = 0; i < this.numInstances(); i++) {
int ALRV;
double U = M * random.nextDouble();
int I = (int) U;
if (U < Q[I]) {
ALRV = I;
} else {
ALRV = A[I];
}
if (representUsingWeights) {
counts[ALRV]++;
} else {
newData.add(this.instance(ALRV));
}
if (sampled != null) {
sampled[ALRV] = true;
}
if (!representUsingWeights) {
newData.instance(newData.numInstances() - 1).setWeight(1);
}
}
// Add data based on counts if weights should represent numbers of copies.
if (representUsingWeights) {
for (int i = 0; i < counts.length; i++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
if (counts[i] > 0) {
newData.add(this.instance(i));
newData.instance(newData.numInstances() - 1).setWeight(counts[i]);
}
}
}
return newData;
}
/**
* Replaces the instance at the given position. Shallow copies instance before
* it is added. Does not check if the instance is compatible with the dataset.
* Note: String or relational values are not transferred.
*
* @param index position where instance is to be inserted
* @param instance the instance to be inserted
* @return the instance previously at that position
*/
// @ requires 0 <= index;
// @ requires index < m_Instances.size();
@Override
public Instance set(final int index, /* @non_null@ */final Instance instance) {
Instance newInstance = (Instance) instance.copy();
Instance oldInstance = this.m_Instances.get(index);
newInstance.setDataset(this);
this.m_Instances.set(index, newInstance);
return oldInstance;
}
/**
* Sets the class attribute.
*
* @param att attribute to be the class
*/
public void setClass(final Attribute att) {
this.m_ClassIndex = att.index();
}
/**
* Sets the class index of the set. If the class index is negative there is
* assumed to be no class. (ie. it is undefined)
*
* @param classIndex the new class index (index starts with 0)
* @throws IllegalArgumentException if the class index is too big or < 0
*/
public void setClassIndex(final int classIndex) {
if (classIndex >= this.numAttributes()) {
throw new IllegalArgumentException("Invalid class index: " + classIndex);
}
this.m_ClassIndex = classIndex;
}
/**
* Sets the relation's name.
*
* @param newName the new relation name.
*/
public void setRelationName(/* @non_null@ */final String newName) {
this.m_RelationName = newName;
}
/**
* Sorts a nominal attribute (stable, linear-time sort). Instances
* are sorted based on the attribute label ordering specified in the header.
*
* @param attIndex the attribute's index (index starts with 0)
* @throws InterruptedException
*/
protected void sortBasedOnNominalAttribute(final int attIndex) throws InterruptedException {
// Figure out number of instances for each attribute value
// and store original list of instances away
int[] counts = new int[this.attribute(attIndex).numValues()];
Instance[] backup = new Instance[this.numInstances()];
int j = 0;
for (Instance inst : this) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
backup[j++] = inst;
if (!inst.isMissing(attIndex)) {
counts[(int) inst.value(attIndex)]++;
}
}
// Indices to figure out where to add instances
int[] indices = new int[counts.length];
int start = 0;
for (int i = 0; i < counts.length; i++) {
indices[i] = start;
start += counts[i];
}
for (Instance inst : backup) { // Use backup here
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
if (!inst.isMissing(attIndex)) {
this.m_Instances.set(indices[(int) inst.value(attIndex)]++, inst);
} else {
this.m_Instances.set(start++, inst);
}
}
}
/**
* Sorts the instances based on an attribute. For numeric attributes,
* instances are sorted in ascending order. For nominal attributes, instances
* are sorted based on the attribute label ordering specified in the header.
* Instances with missing values for the attribute are placed at the end of
* the dataset.
*
* @param attIndex the attribute's index (index starts with 0)
* @throws InterruptedException
*/
public void sort(final int attIndex) throws InterruptedException {
if (!this.attribute(attIndex).isNominal()) {
// Use quicksort from Utils class for sorting
double[] vals = new double[this.numInstances()];
Instance[] backup = new Instance[vals.length];
for (int i = 0; i < vals.length; i++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
Instance inst = this.instance(i);
backup[i] = inst;
double val = inst.value(attIndex);
if (Utils.isMissingValue(val)) {
vals[i] = Double.MAX_VALUE;
} else {
vals[i] = val;
}
}
int[] sortOrder = Utils.sortWithNoMissingValues(vals);
for (int i = 0; i < vals.length; i++) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
this.m_Instances.set(i, backup[sortOrder[i]]);
}
} else {
this.sortBasedOnNominalAttribute(attIndex);
}
}
/**
* Sorts the instances based on an attribute. For numeric attributes,
* instances are sorted into ascending order. For nominal attributes,
* instances are sorted based on the attribute label ordering specified in the
* header. Instances with missing values for the attribute are placed at the
* end of the dataset.
*
* @param att the attribute
* @throws InterruptedException
*/
public void sort(final Attribute att) throws InterruptedException {
this.sort(att.index());
}
/**
* Sorts the instances based on an attribute, using a stable sort. For numeric attributes,
* instances are sorted in ascending order. For nominal attributes, instances
* are sorted based on the attribute label ordering specified in the header.
* Instances with missing values for the attribute are placed at the end of
* the dataset.
*
* @param attIndex the attribute's index (index starts with 0)
* @throws InterruptedException
*/
public void stableSort(final int attIndex) throws InterruptedException {
if (!this.attribute(attIndex).isNominal()) {
// Use quicksort from Utils class for sorting
double[] vals = new double[this.numInstances()];
Instance[] backup = new Instance[vals.length];
for (int i = 0; i < vals.length; i++) {
Instance inst = this.instance(i);
backup[i] = inst;
vals[i] = inst.value(attIndex);
}
int[] sortOrder = Utils.stableSort(vals);
for (int i = 0; i < vals.length; i++) {
this.m_Instances.set(i, backup[sortOrder[i]]);
}
} else {
this.sortBasedOnNominalAttribute(attIndex);
}
}
/**
* Sorts the instances based on an attribute, using a stable sort. For numeric attributes,
* instances are sorted into ascending order. For nominal attributes,
* instances are sorted based on the attribute label ordering specified in the
* header. Instances with missing values for the attribute are placed at the
* end of the dataset.
*
* @param att the attribute
* @throws InterruptedException
*/
public void stableSort(final Attribute att) throws InterruptedException {
this.stableSort(att.index());
}
/**
* Stratifies a set of instances according to its class values if the class
* attribute is nominal (so that afterwards a stratified cross-validation can
* be performed).
*
* @param numFolds the number of folds in the cross-validation
* @throws InterruptedException
* @throws UnassignedClassException if the class is not set
*/
public void stratify(final int numFolds) throws InterruptedException {
if (numFolds <= 1) {
throw new IllegalArgumentException("Number of folds must be greater than 1");
}
if (this.m_ClassIndex < 0) {
throw new UnassignedClassException("Class index is negative (not set)!");
}
if (this.classAttribute().isNominal()) {
// sort by class
int index = 1;
while (index < this.numInstances()) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
Instance instance1 = this.instance(index - 1);
for (int j = index; j < this.numInstances(); j++) {
Instance instance2 = this.instance(j);
if ((instance1.classValue() == instance2.classValue()) || (instance1.classIsMissing() && instance2.classIsMissing())) {
this.swap(index, j);
index++;
}
}
index++;
}
this.stratStep(numFolds);
}
}
/**
* Computes the sum of all the instances' weights.
*
* @return the sum of all the instances' weights as a double
*/
public/* @pure@ */double sumOfWeights() {
double sum = 0;
for (int i = 0; i < this.numInstances(); i++) {
sum += this.instance(i).weight();
}
return sum;
}
/**
* Creates the test set for one fold of a cross-validation on the dataset.
*
* @param numFolds the number of folds in the cross-validation. Must be
* greater than 1.
* @param numFold 0 for the first fold, 1 for the second, ...
* @return the test set as a set of weighted instances
* @throws InterruptedException
* @throws IllegalArgumentException if the number of folds is less than 2 or
* greater than the number of instances.
*/
// @ requires 2 <= numFolds && numFolds < numInstances();
// @ requires 0 <= numFold && numFold < numFolds;
public Instances testCV(final int numFolds, final int numFold) throws InterruptedException {
int numInstForFold, first, offset;
Instances test;
if (numFolds < 2) {
throw new IllegalArgumentException("Number of folds must be at least 2!");
}
if (numFolds > this.numInstances()) {
throw new IllegalArgumentException("Can't have more folds than instances!");
}
numInstForFold = this.numInstances() / numFolds;
if (numFold < this.numInstances() % numFolds) {
numInstForFold++;
offset = numFold;
} else {
offset = this.numInstances() % numFolds;
}
test = new Instances(this, numInstForFold);
first = numFold * (this.numInstances() / numFolds) + offset;
this.copyInstances(first, test, numInstForFold);
return test;
}
/**
* Returns the dataset as a string in ARFF format. Strings are quoted if they
* contain whitespace characters, or if they are a question mark.
*
* @return the dataset in ARFF format as a string
*/
@Override
public String toString() {
StringBuffer text = new StringBuffer();
text.append(ARFF_RELATION).append(" ").append(Utils.quote(this.m_RelationName)).append("\n\n");
for (int i = 0; i < this.numAttributes(); i++) {
text.append(this.attribute(i)).append("\n");
}
text.append("\n").append(ARFF_DATA).append("\n");
text.append(this.stringWithoutHeader());
return text.toString();
}
/**
* Returns the instances in the dataset as a string in ARFF format. Strings
* are quoted if they contain whitespace characters, or if they are a question
* mark.
*
* @return the dataset in ARFF format as a string
*/
protected String stringWithoutHeader() {
StringBuffer text = new StringBuffer();
for (int i = 0; i < this.numInstances(); i++) {
text.append(this.instance(i));
if (i < this.numInstances() - 1) {
text.append('\n');
}
}
return text.toString();
}
/**
* Creates the training set for one fold of a cross-validation on the dataset.
*
* @param numFolds the number of folds in the cross-validation. Must be
* greater than 1.
* @param numFold 0 for the first fold, 1 for the second, ...
* @return the training set
* @throws InterruptedException
* @throws IllegalArgumentException if the number of folds is less than 2 or
* greater than the number of instances.
*/
// @ requires 2 <= numFolds && numFolds < numInstances();
// @ requires 0 <= numFold && numFold < numFolds;
public Instances trainCV(final int numFolds, final int numFold) throws InterruptedException {
int numInstForFold, first, offset;
Instances train;
if (numFolds < 2) {
throw new IllegalArgumentException("Number of folds must be at least 2!");
}
if (numFolds > this.numInstances()) {
throw new IllegalArgumentException("Can't have more folds than instances!");
}
numInstForFold = this.numInstances() / numFolds;
if (numFold < this.numInstances() % numFolds) {
numInstForFold++;
offset = numFold;
} else {
offset = this.numInstances() % numFolds;
}
train = new Instances(this, this.numInstances() - numInstForFold);
first = numFold * (this.numInstances() / numFolds) + offset;
this.copyInstances(0, train, first);
this.copyInstances(first + numInstForFold, train, this.numInstances() - first - numInstForFold);
return train;
}
/**
* Creates the training set for one fold of a cross-validation on the dataset.
* The data is subsequently randomized based on the given random number
* generator.
*
* @param numFolds the number of folds in the cross-validation. Must be
* greater than 1.
* @param numFold 0 for the first fold, 1 for the second, ...
* @param random the random number generator
* @return the training set
* @throws InterruptedException
* @throws IllegalArgumentException if the number of folds is less than 2 or
* greater than the number of instances.
*/
// @ requires 2 <= numFolds && numFolds < numInstances();
// @ requires 0 <= numFold && numFold < numFolds;
public Instances trainCV(final int numFolds, final int numFold, final Random random) throws InterruptedException {
Instances train = this.trainCV(numFolds, numFold);
train.randomize(random);
return train;
}
/**
* Computes the variance for all numeric attributes simultaneously.
* This is faster than calling variance() for each attribute.
* The resulting array has as many dimensions as there are attributes.
* Array elements corresponding to non-numeric attributes are set to 0.
*
* @return the array containing the variance values
*/
public/* @pure@ */double[] variances() {
double[] vars = new double[this.numAttributes()];
for (int i = 0; i < this.numAttributes(); i++) {
vars[i] = Double.NaN;
}
double[] means = new double[this.numAttributes()];
double[] sumWeights = new double[this.numAttributes()];
for (int i = 0; i < this.numInstances(); i++) {
double weight = this.instance(i).weight();
for (int attIndex = 0; attIndex < this.numAttributes(); attIndex++) {
if (this.attribute(attIndex).isNumeric()) {
if (!this.instance(i).isMissing(attIndex)) {
double value = this.instance(i).value(attIndex);
if (Double.isNaN(vars[attIndex])) {
// For the first value the mean can suffer from loss of precision
// so we treat it separately and make sure the calculation stays accurate
means[attIndex] = value;
sumWeights[attIndex] = weight;
vars[attIndex] = 0;
continue;
}
double delta = weight * (value - means[attIndex]);
sumWeights[attIndex] += weight;
means[attIndex] += delta / sumWeights[attIndex];
vars[attIndex] += delta * (value - means[attIndex]);
}
}
}
}
for (int attIndex = 0; attIndex < this.numAttributes(); attIndex++) {
if (this.attribute(attIndex).isNumeric()) {
if (sumWeights[attIndex] <= 1) {
vars[attIndex] = Double.NaN;
} else {
vars[attIndex] /= sumWeights[attIndex] - 1;
if (vars[attIndex] < 0) {
vars[attIndex] = 0;
}
}
}
}
return vars;
}
/**
* Computes the variance for a numeric attribute.
*
* @param attIndex the numeric attribute (index starts with 0)
* @return the variance if the attribute is numeric
* @throws IllegalArgumentException if the attribute is not numeric
*/
public/* @pure@ */double variance(final int attIndex) {
if (!this.attribute(attIndex).isNumeric()) {
throw new IllegalArgumentException("Can't compute variance because attribute is " + "not numeric!");
}
double mean = 0;
double var = Double.NaN;
double sumWeights = 0;
for (int i = 0; i < this.numInstances(); i++) {
if (!this.instance(i).isMissing(attIndex)) {
double weight = this.instance(i).weight();
double value = this.instance(i).value(attIndex);
if (Double.isNaN(var)) {
// For the first value the mean can suffer from loss of precision
// so we treat it separately and make sure the calculation stays accurate
mean = value;
sumWeights = weight;
var = 0;
continue;
}
double delta = weight * (value - mean);
sumWeights += weight;
mean += delta / sumWeights;
var += delta * (value - mean);
}
}
if (sumWeights <= 1) {
return Double.NaN;
}
var /= sumWeights - 1;
// We don't like negative variance
if (var < 0) {
return 0;
} else {
return var;
}
}
/**
* Computes the variance for a numeric attribute.
*
* @param att the numeric attribute
* @return the variance if the attribute is numeric
* @throws IllegalArgumentException if the attribute is not numeric
*/
public/* @pure@ */double variance(final Attribute att) {
return this.variance(att.index());
}
/**
* Calculates summary statistics on the values that appear in this set of
* instances for a specified attribute.
*
* @param index the index of the attribute to summarize (index starts with 0)
* @return an AttributeStats object with it's fields calculated.
* @throws InterruptedException
*/
// @ requires 0 <= index && index < numAttributes();
public AttributeStats attributeStats(final int index) throws InterruptedException {
AttributeStats result = new AttributeStats();
if (this.attribute(index).isNominal()) {
result.nominalCounts = new int[this.attribute(index).numValues()];
result.nominalWeights = new double[this.attribute(index).numValues()];
}
if (this.attribute(index).isNumeric()) {
result.numericStats = new weka.experiment.Stats();
}
result.totalCount = this.numInstances();
HashMap<Double, double[]> map = new HashMap<Double, double[]>(2 * result.totalCount);
for (Instance current : this) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
double key = current.value(index);
if (Utils.isMissingValue(key)) {
result.missingCount++;
} else {
double[] values = map.get(key);
if (values == null) {
values = new double[2];
values[0] = 1.0;
values[1] = current.weight();
map.put(key, values);
} else {
values[0]++;
values[1] += current.weight();
}
}
}
for (Entry<Double, double[]> entry : map.entrySet()) {
result.addDistinct(entry.getKey(), (int) entry.getValue()[0], entry.getValue()[1]);
}
return result;
}
/**
* Gets the value of all instances in this dataset for a particular attribute.
* Useful in conjunction with Utils.sort to allow iterating through the
* dataset in sorted order for some attribute.
*
* @param index the index of the attribute.
* @return an array containing the value of the desired attribute for each
* instance in the dataset.
*/
// @ requires 0 <= index && index < numAttributes();
public/* @pure@ */double[] attributeToDoubleArray(final int index) {
double[] result = new double[this.numInstances()];
for (int i = 0; i < result.length; i++) {
result[i] = this.instance(i).value(index);
}
return result;
}
/**
* Generates a string summarizing the set of instances. Gives a breakdown for
* each attribute indicating the number of missing/discrete/unique values and
* other information.
*
* @return a string summarizing the dataset
*/
public String toSummaryString() {
StringBuffer result = new StringBuffer();
result.append("Relation Name: ").append(this.relationName()).append('\n');
result.append("Num Instances: ").append(this.numInstances()).append('\n');
result.append("Num Attributes: ").append(this.numAttributes()).append('\n');
result.append('\n');
result.append(Utils.padLeft("", 5)).append(Utils.padRight("Name", 25));
result.append(Utils.padLeft("Type", 5)).append(Utils.padLeft("Nom", 5));
result.append(Utils.padLeft("Int", 5)).append(Utils.padLeft("Real", 5));
result.append(Utils.padLeft("Missing", 12));
result.append(Utils.padLeft("Unique", 12));
result.append(Utils.padLeft("Dist", 6)).append('\n');
// Figure out how many digits we need for the index
int numDigits = (int) Math.log10(this.numAttributes()) + 1;
for (int i = 0; i < this.numAttributes(); i++) {
Attribute a = this.attribute(i);
AttributeStats as;
try {
as = this.attributeStats(i);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
result.append(Utils.padLeft("" + (i + 1), numDigits)).append(' ');
result.append(Utils.padRight(a.name(), 25)).append(' ');
long percent;
switch (a.type()) {
case Attribute.NOMINAL:
result.append(Utils.padLeft("Nom", 4)).append(' ');
percent = Math.round(100.0 * as.intCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
result.append(Utils.padLeft("" + 0, 3)).append("% ");
percent = Math.round(100.0 * as.realCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
break;
case Attribute.NUMERIC:
result.append(Utils.padLeft("Num", 4)).append(' ');
result.append(Utils.padLeft("" + 0, 3)).append("% ");
percent = Math.round(100.0 * as.intCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
percent = Math.round(100.0 * as.realCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
break;
case Attribute.DATE:
result.append(Utils.padLeft("Dat", 4)).append(' ');
result.append(Utils.padLeft("" + 0, 3)).append("% ");
percent = Math.round(100.0 * as.intCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
percent = Math.round(100.0 * as.realCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
break;
case Attribute.STRING:
result.append(Utils.padLeft("Str", 4)).append(' ');
percent = Math.round(100.0 * as.intCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
result.append(Utils.padLeft("" + 0, 3)).append("% ");
percent = Math.round(100.0 * as.realCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
break;
case Attribute.RELATIONAL:
result.append(Utils.padLeft("Rel", 4)).append(' ');
percent = Math.round(100.0 * as.intCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
result.append(Utils.padLeft("" + 0, 3)).append("% ");
percent = Math.round(100.0 * as.realCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
break;
default:
result.append(Utils.padLeft("???", 4)).append(' ');
result.append(Utils.padLeft("" + 0, 3)).append("% ");
percent = Math.round(100.0 * as.intCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
percent = Math.round(100.0 * as.realCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
break;
}
result.append(Utils.padLeft("" + as.missingCount, 5)).append(" /");
percent = Math.round(100.0 * as.missingCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
result.append(Utils.padLeft("" + as.uniqueCount, 5)).append(" /");
percent = Math.round(100.0 * as.uniqueCount / as.totalCount);
result.append(Utils.padLeft("" + percent, 3)).append("% ");
result.append(Utils.padLeft("" + as.distinctCount, 5)).append(' ');
result.append('\n');
}
return result.toString();
}
/**
* Copies instances from one set to the end of another one.
*
* @param from the position of the first instance to be copied
* @param dest the destination for the instances
* @param num the number of instances to be copied
* @throws InterruptedException
*/
// @ requires 0 <= from && from <= numInstances() - num;
// @ requires 0 <= num;
protected void copyInstances(final int from, /* @non_null@ */final Instances dest, final int num) throws InterruptedException {
for (int i = 0; i < num; i++) {
if (Thread.interrupted()) {
throw new InterruptedException();
}
dest.add(this.instance(from + i));
}
}
/**
* Returns string including all instances, their weights and their indices in
* the original dataset.
*
* @return description of instance and its weight as a string
*/
protected/* @pure@ */String instancesAndWeights() {
StringBuffer text = new StringBuffer();
for (int i = 0; i < this.numInstances(); i++) {
text.append(this.instance(i) + " " + this.instance(i).weight());
if (i < this.numInstances() - 1) {
text.append("\n");
}
}
return text.toString();
}
/**
* Help function needed for stratification of set.
*
* @param numFolds the number of folds for the stratification
*/
protected void stratStep(final int numFolds) {
ArrayList<Instance> newVec = new ArrayList<Instance>(this.m_Instances.size());
int start = 0, j;
// create stratified batch
while (newVec.size() < this.numInstances()) {
j = start;
while (j < this.numInstances()) {
newVec.add(this.instance(j));
j = j + numFolds;
}
start++;
}
this.m_Instances = newVec;
}
/**
* Swaps two instances in the set.
*
* @param i the first instance's index (index starts with 0)
* @param j the second instance's index (index starts with 0)
*/
// @ requires 0 <= i && i < numInstances();
// @ requires 0 <= j && j < numInstances();
public void swap(final int i, final int j) {
Instance in = this.m_Instances.get(i);
this.m_Instances.set(i, this.m_Instances.get(j));
this.m_Instances.set(j, in);
}
/**
* Merges two sets of Instances together. The resulting set will have all the
* attributes of the first set plus all the attributes of the second set. The
* number of instances in both sets must be the same.
*
* @param first the first set of Instances
* @param second the second set of Instances
* @return the merged set of Instances
* @throws IllegalArgumentException if the datasets are not the same size
*/
public static Instances mergeInstances(final Instances first, final Instances second) {
if (first.numInstances() != second.numInstances()) {
throw new IllegalArgumentException("Instance sets must be of the same size");
}
// Create the vector of merged attributes
ArrayList<Attribute> newAttributes = new ArrayList<Attribute>(first.numAttributes() + second.numAttributes());
for (Attribute att : first.m_Attributes) {
newAttributes.add(att);
}
for (Attribute att : second.m_Attributes) {
newAttributes.add((Attribute) att.copy()); // Need to copy because indices will change.
}
// Create the set of Instances
Instances merged = new Instances(first.relationName() + '_' + 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)));
}
return merged;
}
/**
* Method for testing this class.
*
* @param argv should contain one element: the name of an ARFF file
*/
// @ requires argv != null;
// @ requires argv.length == 1;
// @ requires argv[0] != null;
public static void test(final String[] argv) {
Instances instances, secondInstances, train, test, empty;
Random random = new Random(2);
Reader reader;
int start, num;
ArrayList<Attribute> testAtts;
ArrayList<String> testVals;
int i, j;
try {
if (argv.length > 1) {
throw (new Exception("Usage: Instances [<filename>]"));
}
// Creating set of instances from scratch
testVals = new ArrayList<String>(2);
testVals.add("first_value");
testVals.add("second_value");
testAtts = new ArrayList<Attribute>(2);
testAtts.add(new Attribute("nominal_attribute", testVals));
testAtts.add(new Attribute("numeric_attribute"));
instances = new Instances("test_set", testAtts, 10);
instances.add(new DenseInstance(instances.numAttributes()));
instances.add(new DenseInstance(instances.numAttributes()));
instances.add(new DenseInstance(instances.numAttributes()));
instances.setClassIndex(0);
System.out.println("\nSet of instances created from scratch:\n");
System.out.println(instances);
if (argv.length == 1) {
String filename = argv[0];
reader = new FileReader(filename);
// Read first five instances and print them
System.out.println("\nFirst five instances from file:\n");
instances = new Instances(reader, 1);
instances.setClassIndex(instances.numAttributes() - 1);
i = 0;
while ((i < 5) && (instances.readInstance(reader))) {
i++;
}
System.out.println(instances);
// Read all the instances in the file
reader = new FileReader(filename);
instances = new Instances(reader);
// Make the last attribute be the class
instances.setClassIndex(instances.numAttributes() - 1);
// Print header and instances.
System.out.println("\nDataset:\n");
System.out.println(instances);
System.out.println("\nClass index: " + instances.classIndex());
}
// Test basic methods based on class index.
System.out.println("\nClass name: " + instances.classAttribute().name());
System.out.println("\nClass index: " + instances.classIndex());
System.out.println("\nClass is nominal: " + instances.classAttribute().isNominal());
System.out.println("\nClass is numeric: " + instances.classAttribute().isNumeric());
System.out.println("\nClasses:\n");
for (i = 0; i < instances.numClasses(); i++) {
System.out.println(instances.classAttribute().value(i));
}
System.out.println("\nClass values and labels of instances:\n");
for (i = 0; i < instances.numInstances(); i++) {
Instance inst = instances.instance(i);
System.out.print(inst.classValue() + "\t");
System.out.print(inst.toString(inst.classIndex()));
if (instances.instance(i).classIsMissing()) {
System.out.println("\tis missing");
} else {
System.out.println();
}
}
// Create random weights.
System.out.println("\nCreating random weights for instances.");
for (i = 0; i < instances.numInstances(); i++) {
instances.instance(i).setWeight(random.nextDouble());
}
// Print all instances and their weights (and the sum of weights).
System.out.println("\nInstances and their weights:\n");
System.out.println(instances.instancesAndWeights());
System.out.print("\nSum of weights: ");
System.out.println(instances.sumOfWeights());
// Insert an attribute
secondInstances = new Instances(instances);
Attribute testAtt = new Attribute("Inserted");
secondInstances.insertAttributeAt(testAtt, 0);
System.out.println("\nSet with inserted attribute:\n");
System.out.println(secondInstances);
System.out.println("\nClass 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());
// Test if headers are equal
System.out.println("\nHeaders equal: " + instances.equalHeaders(secondInstances) + "\n");
// Print data in internal format.
System.out.println("\nData (internal values):\n");
for (i = 0; i < instances.numInstances(); i++) {
for (j = 0; j < instances.numAttributes(); j++) {
if (instances.instance(i).isMissing(j)) {
System.out.print("? ");
} else {
System.out.print(instances.instance(i).value(j) + " ");
}
}
System.out.println();
}
// Just print header
System.out.println("\nEmpty dataset:\n");
empty = new Instances(instances, 0);
System.out.println(empty);
System.out.println("\nClass name: " + empty.classAttribute().name());
// Create copy and rename an attribute and a value (if possible)
if (empty.classAttribute().isNominal()) {
Instances copy = new Instances(empty, 0);
copy.renameAttribute(copy.classAttribute(), "new_name");
copy.renameAttributeValue(copy.classAttribute(), copy.classAttribute().value(0), "new_val_name");
System.out.println("\nDataset with names changed:\n" + copy);
System.out.println("\nOriginal dataset:\n" + empty);
}
// Create and prints subset of instances.
start = instances.numInstances() / 4;
num = instances.numInstances() / 2;
System.out.print("\nSubset of dataset: ");
System.out.println(num + " instances from " + (start + 1) + ". instance");
secondInstances = new Instances(instances, start, num);
System.out.println("\nClass name: " + secondInstances.classAttribute().name());
// Print all instances and their weights (and the sum of weights).
System.out.println("\nInstances and their weights:\n");
System.out.println(secondInstances.instancesAndWeights());
System.out.print("\nSum of weights: ");
System.out.println(secondInstances.sumOfWeights());
// Create and print training and test sets for 3-fold
// cross-validation.
System.out.println("\nTrain and test folds for 3-fold CV:");
if (instances.classAttribute().isNominal()) {
instances.stratify(3);
}
for (j = 0; j < 3; j++) {
train = instances.trainCV(3, j, new Random(1));
test = instances.testCV(3, j);
// Print all instances and their weights (and the sum of weights).
System.out.println("\nTrain: ");
System.out.println("\nInstances and their weights:\n");
System.out.println(train.instancesAndWeights());
System.out.print("\nSum of weights: ");
System.out.println(train.sumOfWeights());
System.out.println("\nClass name: " + train.classAttribute().name());
System.out.println("\nTest: ");
System.out.println("\nInstances and their weights:\n");
System.out.println(test.instancesAndWeights());
System.out.print("\nSum of weights: ");
System.out.println(test.sumOfWeights());
System.out.println("\nClass name: " + test.classAttribute().name());
}
// Randomize instances and print them.
System.out.println("\nRandomized dataset:");
instances.randomize(random);
// Print all instances and their weights (and the sum of weights).
System.out.println("\nInstances and their weights:\n");
System.out.println(instances.instancesAndWeights());
System.out.print("\nSum of weights: ");
System.out.println(instances.sumOfWeights());
// Sort instances according to first attribute and
// print them.
System.out.print("\nInstances sorted according to first attribute:\n ");
instances.sort(0);
// Print all instances and their weights (and the sum of weights).
System.out.println("\nInstances and their weights:\n");
System.out.println(instances.instancesAndWeights());
System.out.print("\nSum of weights: ");
System.out.println(instances.sumOfWeights());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Main method for this class. The following calls are possible:
* <ul>
* <li>
* <code>weka.core.Instances</code> help<br/>
* prints a short list of possible commands.</li>
* <li>
* <code>weka.core.Instances</code> <filename><br/>
* prints a summary of a set of instances.</li>
* <li>
* <code>weka.core.Instances</code> merge <filename1> <filename2><br/>
* merges the two datasets (must have same number of instances) and outputs
* the results on stdout.</li>
* <li>
* <code>weka.core.Instances</code> append <filename1> <filename2>
* <br/>
* appends the second dataset to the first one (must have same headers) and
* outputs the results on stdout.</li>
* <li>
* <code>weka.core.Instances</code> headers <filename1>
* <filename2><br/>
* Compares the headers of the two datasets and prints whether they match or
* not.</li>
* <li>
* <code>weka.core.Instances</code> randomize <seed> <filename><br/>
* randomizes the dataset with the given seed and outputs the result on
* stdout.</li>
* </ul>
*
* @param args the commandline parameters
*/
public static void main(final String[] args) {
try {
Instances i;
// read from stdin and print statistics
if (args.length == 0) {
DataSource source = new DataSource(System.in);
i = source.getDataSet();
System.out.println(i.toSummaryString());
}
// read file and print statistics
else if ((args.length == 1) && (!args[0].equals("-h")) && (!args[0].equals("help"))) {
DataSource source = new DataSource(args[0]);
i = source.getDataSet();
System.out.println(i.toSummaryString());
}
// read two files, merge them and print result to stdout
else if ((args.length == 3) && (args[0].toLowerCase().equals("merge"))) {
DataSource source1 = new DataSource(args[1]);
DataSource source2 = new DataSource(args[2]);
i = Instances.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]);
String msg = source1.getStructure().equalHeadersMsg(source2.getStructure());
if (msg != null) {
throw new Exception("The two datasets have different headers:\n" + msg);
}
Instances structure = source1.getStructure();
System.out.println(source1.getStructure());
while (source1.hasMoreElements(structure)) {
System.out.println(source1.nextElement(structure));
}
structure = source2.getStructure();
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]);
String msg = source1.getStructure().equalHeadersMsg(source2.getStructure());
if (msg == null) {
System.out.println("Headers match");
} else {
System.out.println("Headers don't match:\n" + msg);
}
}
// read file and seed value, randomize data and print result to stdout
else if ((args.length == 3) && (args[0].toLowerCase().equals("randomize"))) {
DataSource source = new DataSource(args[2]);
i = source.getDataSet();
i.randomize(new Random(Integer.parseInt(args[1])));
System.out.println(i);
}
// wrong parameters or help
else {
System.err.println("\nUsage:\n"
// help
+ "\tweka.core.Instances help\n" + "\t\tPrints this help\n"
// stats
+ "\tweka.core.Instances <filename>\n" + "\t\tOutputs dataset statistics\n"
// merge
+ "\tweka.core.Instances merge <filename1> <filename2>\n" + "\t\tMerges the datasets (must have same number of rows).\n" + "\t\tGenerated dataset gets output on stdout.\n"
// append
+ "\tweka.core.Instances append <filename1> <filename2>\n" + "\t\tAppends the second dataset to the first (must have same number of attributes).\n" + "\t\tGenerated dataset gets output on stdout.\n"
// headers
+ "\tweka.core.Instances headers <filename1> <filename2>\n" + "\t\tCompares the structure of the two datasets and outputs whether they\n" + "\t\tdiffer or not.\n"
// randomize
+ "\tweka.core.Instances randomize <seed> <filename>\n" + "\t\tRandomizes the dataset and outputs it on stdout.\n");
}
} catch (Exception ex) {
ex.printStackTrace();
System.err.println(ex.getMessage());
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Javadoc.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Javadoc.java
* Copyright (C) 2006-2012,2015 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Enumeration;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* Abstract superclass for classes that generate Javadoc comments and replace
* the content between certain comment tags.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public abstract class Javadoc implements OptionHandler, RevisionHandler {
/** the start tag */
protected String[] m_StartTag = null;
/** the end tag */
protected String[] m_EndTag = null;
/** the classname */
protected String m_Classname = Javadoc.class.getName();
/** whether to include the stars in the Javadoc */
protected boolean m_UseStars = true;
/** the directory above the class to update */
protected String m_Dir = "";
/** whether to suppress error messages (no printout in the console) */
protected boolean m_Silent = false;
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tThe class to load.", "W", 1,
"-W <classname>"));
result.addElement(new Option("\tSuppresses the '*' in the Javadoc.",
"nostars", 0, "-nostars"));
result.addElement(new Option(
"\tThe directory above the package hierarchy of the class.", "dir", 1,
"-dir <dir>"));
result.addElement(new Option("\tSuppresses printing in the console.",
"silent", 0, "-silent"));
return result.elements();
}
/**
* 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
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() > 0) {
setClassname(tmpStr);
} else {
setClassname(this.getClass().getName());
}
setUseStars(!Utils.getFlag("nostars", options));
setDir(Utils.getOption("dir", options));
setSilent(Utils.getFlag("silent", options));
}
/**
* Gets the current settings of this object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
result = new Vector<String>();
result.add("-W");
result.add(getClassname());
if (!getUseStars()) {
result.add("-nostars");
}
if (getDir().length() != 0) {
result.add("-dir");
result.add(getDir());
}
if (getSilent()) {
result.add("-silent");
}
return result.toArray(new String[result.size()]);
}
/**
* sets the classname of the class to generate the Javadoc for
*
* @param value the new classname
*/
public void setClassname(String value) {
m_Classname = value;
}
/**
* returns the current classname
*
* @return the current classname
*/
public String getClassname() {
return m_Classname;
}
/**
* sets whether to prefix the Javadoc with "*"
*
* @param value true if stars are used
*/
public void setUseStars(boolean value) {
m_UseStars = value;
}
/**
* whether the Javadoc is prefixed with "*"
*
* @return whether stars are used
*/
public boolean getUseStars() {
return m_UseStars;
}
/**
* sets the dir containing the file that is to be updated. It is the dir above
* the package hierarchy of the class.
*
* @param value the directory containing the classes
*/
public void setDir(String value) {
m_Dir = value;
}
/**
* returns the current dir containing the class to update. It is the dir above
* the package name of the class.
*
* @return the current directory
*/
public String getDir() {
return m_Dir;
}
/**
* sets whether to suppress output in the console
*
* @param value true if output is to be suppressed
*/
public void setSilent(boolean value) {
m_Silent = value;
}
/**
* whether output in the console is suppressed
*
* @return true if output is suppressed
*/
public boolean getSilent() {
return m_Silent;
}
/**
* prints the given object to System.err
*
* @param o the object to print
*/
protected void println(Object o) {
if (!getSilent()) {
System.err.println(o.toString());
}
}
/**
* returns true if the class can be instantiated, i.e., has a default
* constructor.
*
* @return true if the class can be instantiated
*/
protected boolean canInstantiateClass() {
boolean result;
Class<?> cls;
result = true;
cls = null;
try {
cls = Class.forName(getClassname());
} catch (Exception e) {
result = false;
println("Cannot instantiate '" + getClassname()
+ "'! Class in CLASSPATH?");
}
if (result) {
try {
cls.newInstance();
} catch (Exception e) {
result = false;
println("Cannot instantiate '" + getClassname()
+ "'! Missing default constructor?");
}
}
return result;
}
/**
* Returns a new instance of the class
*
* @return a new instance of the class
*/
protected Object getInstance() {
Object result;
Class<?> cls;
result = null;
try {
cls = Class.forName(getClassname());
result = cls.newInstance();
} catch (Exception e) {
result = null;
}
return result;
}
/**
* converts the given String into HTML, i.e., replacing some char entities
* with HTML entities.
*
* @param s the string to convert
* @return the HTML conform string
*/
protected String toHTML(String s) {
String result;
result = s;
result = result.replaceAll("&", "&");
result = result.replaceAll("<", "<");
result = result.replaceAll(">", ">");
result = result.replaceAll("@", "@");
result = result.replaceAll("\n", "<br>\n");
return result;
}
/**
* indents the given string by a given number of indention strings
*
* @param content the string to indent
* @param count the number of times to indent one line
* @param indentStr the indention string
* @return the indented content
*/
protected String indent(String content, int count, String indentStr) {
String result;
StringTokenizer tok;
int i;
tok = new StringTokenizer(content, "\n", true);
result = "";
while (tok.hasMoreTokens()) {
if (result.endsWith("\n") || (result.length() == 0)) {
for (i = 0; i < count; i++) {
result += indentStr;
}
}
result += tok.nextToken();
}
return result;
}
/**
* generates and returns the Javadoc for the specified start/end tag pair.
*
* @param index the index in the start/end tag array
* @return the generated Javadoc
* @throws Exception in case the generation fails
*/
protected abstract String generateJavadoc(int index) throws Exception;
/**
* generates and returns the Javadoc
*
* @return the generated Javadoc
* @throws Exception in case the generation fails
*/
protected String generateJavadoc() throws Exception {
String result;
int i;
result = "";
for (i = 0; i < m_StartTag.length; i++) {
if (i > 0) {
result += "\n\n";
}
result += generateJavadoc(i).trim();
}
return result;
}
/**
* determines the base string of the given indention string, whether it's
* either only spaces (one space will be retured) or mixed mode (tabs and
* spaces, in that case the same string will be returned)
*
* @param str the string to analyze
* @return the indention string
*/
protected String getIndentionString(String str) {
String result;
// only spaces?
if (str.replaceAll(" ", "").length() == 0) {
result = " ";
} else if (str.replaceAll("\t", "").length() == 0) {
result = "\t";
} else {
result = str;
}
return result;
}
/**
* determines the number of indention strings that have to be inserted to
* generated the given indention string.
*
* @param str the string to analyze
* @return the number of base indention strings to insert
*/
protected int getIndentionLength(String str) {
int result;
// only spaces?
if (str.replaceAll(" ", "").length() == 0) {
result = str.length();
} else if (str.replaceAll("\t", "").length() == 0) {
result = str.length();
} else {
result = 1;
}
return result;
}
/**
* generates and returns the Javadoc for the specified start/end tag pair
*
* @param content the current source code
* @param index the index in the start/end tag array
* @return the generated Javadoc
* @throws Exception in case the generation fails
*/
protected String updateJavadoc(String content, int index) throws Exception {
StringBuffer resultBuf;
int indentionLen;
String indentionStr;
String part;
String tmpStr;
// start and end tag?
if ((content.indexOf(m_StartTag[index]) == -1)
|| (content.indexOf(m_EndTag[index]) == -1)) {
println("No start and/or end tags found: " + m_StartTag[index] + "/"
+ m_EndTag[index]);
return content;
}
// replace option-tags
resultBuf = new StringBuffer();
while (content.length() > 0) {
if (content.indexOf(m_StartTag[index]) > -1) {
part = content.substring(0, content.indexOf(m_StartTag[index]));
// is it a Java constant? -> skip
if (part.endsWith("\"")) {
resultBuf.append(part);
resultBuf.append(m_StartTag[index]);
content = content.substring(part.length()
+ m_StartTag[index].length());
} else {
tmpStr = part.substring(part.lastIndexOf("\n") + 1);
indentionLen = getIndentionLength(tmpStr);
indentionStr = getIndentionString(tmpStr);
part = part.substring(0, part.lastIndexOf("\n") + 1);
resultBuf.append(part);
resultBuf
.append(indent(m_StartTag[index], indentionLen, indentionStr)
+ "\n");
resultBuf.append(indent(generateJavadoc(index), indentionLen,
indentionStr));
resultBuf.append(indent(m_EndTag[index], indentionLen, indentionStr));
content = content.substring(content.indexOf(m_EndTag[index]));
content = content.substring(m_EndTag[index].length());
}
} else {
resultBuf.append(content);
content = "";
}
}
return resultBuf.toString().trim();
}
/**
* updates the Javadoc in the given source code.
*
* @param content the source code
* @return the updated source code
* @throws Exception in case the generation fails
*/
protected String updateJavadoc(String content) throws Exception {
String result;
int i;
result = content;
for (i = 0; i < m_StartTag.length; i++) {
result = updateJavadoc(result, i);
}
return result;
}
/**
* generates the Javadoc and returns it applied to the source file if one was
* provided, otherwise an empty string.
*
* @return the generated Javadoc
* @throws Exception in case the generation fails
*/
public String updateJavadoc() throws Exception {
StringBuffer contentBuf;
BufferedReader reader;
String line;
String result;
File file;
result = "";
// non-existing?
file = new File(getDir() + "/" + getClassname().replaceAll("\\.", "/")
+ ".java");
if (!file.exists()) {
println("File '" + file.getAbsolutePath() + "' doesn't exist!");
return result;
}
try {
// load file
reader = new BufferedReader(new FileReader(file));
contentBuf = new StringBuffer();
while ((line = reader.readLine()) != null) {
contentBuf.append(line + "\n");
}
reader.close();
result = updateJavadoc(contentBuf.toString());
} catch (Exception e) {
e.printStackTrace();
}
return result.trim();
}
/**
* generates either the plain Javadoc (if no filename specified) or the
* updated file (if a filename is specified). The start and end tag for the
* global info have to be specified in the file in the latter case.
*
* @return either the plain Javadoc or the modified file
* @throws Exception in case the generation fails
*/
public String generate() throws Exception {
if (getDir().length() == 0) {
return generateJavadoc();
} else {
return updateJavadoc();
}
}
/**
* generates a string to print as help on the console
*
* @return the generated help
*/
public String generateHelp() {
String result;
Enumeration<Option> enm;
Option option;
result = getClass().getName().replaceAll(".*\\.", "") + " Options:\n\n";
enm = listOptions();
while (enm.hasMoreElements()) {
option = enm.nextElement();
result += option.synopsis() + "\n" + option.description() + "\n";
}
return result;
}
/**
* runs the javadoc producer with the given commandline options
*
* @param javadoc the javadoc producer to execute
* @param options the commandline options
*/
protected static void runJavadoc(Javadoc javadoc, String[] options) {
try {
try {
if (Utils.getFlag('h', options)) {
throw new Exception("Help requested");
}
javadoc.setOptions(options);
Utils.checkForRemainingOptions(options);
// directory is necessary!
if (javadoc.getDir().length() == 0) {
throw new Exception("No directory provided!");
}
} catch (Exception ex) {
String result = "\n" + ex.getMessage() + "\n\n"
+ javadoc.generateHelp();
throw new Exception(result);
}
System.out.println(javadoc.generate() + "\n");
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/ListOptions.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ListOptions.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.util.Enumeration;
import java.util.Vector;
/**
* Lists the options of an OptionHandler
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class ListOptions implements OptionHandler, RevisionHandler, CommandlineRunnable {
/** the classname */
protected String m_Classname = ListOptions.class.getName();
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tThe class to load.", "W", 1,
"-W <classname>"));
return result.elements();
}
/**
* 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
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() > 0) {
setClassname(tmpStr);
} else {
setClassname(this.getClass().getName());
}
}
/**
* Gets the current settings of this object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
result = new Vector<String>();
result.add("-W");
result.add(getClassname());
return result.toArray(new String[result.size()]);
}
/**
* sets the classname of the class to generate the Javadoc for
*
* @param value the new classname
*/
public void setClassname(String value) {
m_Classname = value;
}
/**
* returns the current classname
*
* @return the current classname
*/
public String getClassname() {
return m_Classname;
}
/**
* generates a string to print as help on the console
*
* @return the generated help
*/
public String generateHelp() {
String result;
Enumeration<Option> enm;
Option option;
result = getClass().getName().replaceAll(".*\\.", "") + " Options:\n\n";
enm = listOptions();
while (enm.hasMoreElements()) {
option = enm.nextElement();
result += option.synopsis() + "\n" + option.description() + "\n";
}
return result;
}
/**
* generates the options string.
*
* @return the options string
* @throws Exception in case the generation fails
*/
public String generate() throws Exception {
StringBuffer result;
OptionHandler handler;
Enumeration<Option> enm;
Option option;
result = new StringBuffer();
handler = (OptionHandler) Utils.forName(null, getClassname(), new String[0]);
enm = handler.listOptions();
while (enm.hasMoreElements()) {
option = enm.nextElement();
result.append(option.synopsis() + '\n');
result.append(option.description() + "\n");
}
return result.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* runs the javadoc producer with the given commandline options
*
* @param options the commandline options
*/
public static void main(String[] options) {
try {
ListOptions lo = new ListOptions();
lo.run(lo, options);
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override public void preExecution() throws Exception {
}
@Override public void run(Object toRun, String[] options) throws Exception {
if (!(toRun instanceof ListOptions)) {
throw new IllegalArgumentException("Object to run is not an instance "
+ "of ListOptions!");
}
ListOptions list = (ListOptions) toRun;
try {
try {
if (Utils.getFlag('h', options)) {
throw new Exception("Help requested");
}
list.setOptions(options);
Utils.checkForRemainingOptions(options);
} catch (Exception ex) {
String result = "\n" + ex.getMessage() + "\n\n" + list.generateHelp();
throw new Exception(result);
}
System.out.println("\n" + list.generate());
} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}
@Override public void postExecution() throws Exception {
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/LogHandler.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* LogHandler.java
* Copyright (C) 2011-2013 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import weka.gui.Logger;
/**
* Interface to something that can output messages to a log
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 47640 $
*/
public interface LogHandler {
/**
* Set the log to use
*
* @param log the log to use
*/
void setLog(Logger log);
/**
* Get the log in use
*
* @return the log in use
*/
Logger getLog();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/ManhattanDistance.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ManhattanDistance.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
/**
<!-- globalinfo-start -->
* Implements the Manhattan distance (or Taxicab geometry). The distance between two points is the sum of the (absolute) differences of their coordinates.<br/>
* <br/>
* For more information, see:<br/>
* <br/>
* Wikipedia. Taxicab geometry. URL http://en.wikipedia.org/wiki/Taxicab_geometry.
* <p/>
<!-- globalinfo-end -->
*
<!-- technical-bibtex-start -->
* BibTeX:
* <pre>
* @misc{missing_id,
* author = {Wikipedia},
* title = {Taxicab geometry},
* URL = {http://en.wikipedia.org/wiki/Taxicab_geometry}
* }
* </pre>
* <p/>
<!-- technical-bibtex-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -D
* Turns off the normalization of attribute
* values in distance calculation.</pre>
*
* <pre> -R <col1,col2-col4,...>
* Specifies list of columns to used in the calculation of the
* distance. 'first' and 'last' are valid indices.
* (default: first-last)</pre>
*
* <pre> -V
* Invert matching sense of column indices.</pre>
*
<!-- options-end -->
*
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class ManhattanDistance
extends NormalizableDistance
implements TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = 6783782554224000243L;
/**
* Constructs an Manhattan Distance object, Instances must be still set.
*/
public ManhattanDistance() {
super();
}
/**
* Constructs an Manhattan Distance object and automatically initializes the
* ranges.
*
* @param data the instances the distance function should work on
*/
public ManhattanDistance(Instances data) {
super(data);
}
/**
* Returns a string describing this object.
*
* @return a description of the evaluator suitable for
* displaying in the explorer/experimenter gui
*/
public String globalInfo() {
return
"Implements the Manhattan distance (or Taxicab geometry). The distance "
+ "between two points is the sum of the (absolute) differences of their "
+ "coordinates.\n\n"
+ "For more information, see:\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.
*
* @return the technical information about this class
*/
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.MISC);
result.setValue(Field.AUTHOR, "Wikipedia");
result.setValue(Field.TITLE, "Taxicab geometry");
result.setValue(Field.URL, "http://en.wikipedia.org/wiki/Taxicab_geometry");
return result;
}
/**
* Updates the current distance calculated so far with the new difference
* 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)
*/
protected double updateDistance(double currDist, double diff) {
double result;
result = currDist;
result += Math.abs(diff);
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Matchable.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Matchable.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Interface to something that can be matched with tree matching
* algorithms.
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface Matchable {
/**
* Returns a string that describes a tree representing
* the object in prefix order.
*
* @return the tree described as a string
* @exception Exception if the tree can't be computed
*/
String prefix() throws Exception;
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Matrix.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Matrix.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.Reader;
import java.io.Serializable;
import java.io.Writer;
/**
* Class for performing operations on a matrix of floating-point values.
* <p/>
* Deprecated: Uses internally the code of the sub-package
* <code>weka.core.matrix</code> - only for backwards compatibility.
*
* @author Gabi Schmidberger (gabi@cs.waikato.ac.nz)
* @author Yong Wang (yongwang@cs.waikato.ac.nz)
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author Len Trigg (eibe@cs.waikato.ac.nz)
* @author Fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @deprecated Use <code>weka.core.matrix.Matrix</code> instead - only for
* backwards compatibility.
*/
@Deprecated
public class Matrix implements Cloneable, Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -3604757095849145838L;
/**
* The actual matrix
*/
protected weka.core.matrix.Matrix m_Matrix = null;
/**
* Constructs a matrix and initializes it with default values.
*
* @param nr the number of rows
* @param nc the number of columns
*/
public Matrix(int nr, int nc) {
m_Matrix = new weka.core.matrix.Matrix(nr, nc);
}
/**
* Constructs a matrix using a given array.
*
* @param array the values of the matrix
*/
public Matrix(double[][] array) throws Exception {
m_Matrix = new weka.core.matrix.Matrix(array);
}
/**
* Reads a matrix from a reader. The first line in the file should contain the
* number of rows and columns. Subsequent lines contain elements of the
* matrix.
*
* @param r the reader containing the matrix
* @throws Exception if an error occurs
*/
public Matrix(Reader r) throws Exception {
m_Matrix = new weka.core.matrix.Matrix(r);
}
/**
* Creates and returns a clone of this object.
*
* @return a clone of this instance.
* @throws Exception if an error occurs
*/
@Override
public Object clone() {
try {
return new Matrix(m_Matrix.getArrayCopy());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Writes out a matrix.
*
* @param w the output Writer
* @throws Exception if an error occurs
*/
public void write(Writer w) throws Exception {
m_Matrix.write(w);
}
/**
* returns the internal matrix
*
* @see #m_Matrix
*/
protected weka.core.matrix.Matrix getMatrix() {
return m_Matrix;
}
/**
* Returns the value of a cell in the matrix.
*
* @param rowIndex the row's index
* @param columnIndex the column's index
* @return the value of the cell of the matrix
*/
public final double getElement(int rowIndex, int columnIndex) {
return m_Matrix.get(rowIndex, columnIndex);
}
/**
* Add a value to an element.
*
* @param rowIndex the row's index.
* @param columnIndex the column's index.
* @param value the value to add.
*/
public final void addElement(int rowIndex, int columnIndex, double value) {
m_Matrix.set(rowIndex, columnIndex, m_Matrix.get(rowIndex, columnIndex)
+ value);
}
/**
* Returns the number of rows in the matrix.
*
* @return the number of rows
*/
public final int numRows() {
return m_Matrix.getRowDimension();
}
/**
* Returns the number of columns in the matrix.
*
* @return the number of columns
*/
public final int numColumns() {
return m_Matrix.getColumnDimension();
}
/**
* Sets an element of the matrix to the given value.
*
* @param rowIndex the row's index
* @param columnIndex the column's index
* @param value the value
*/
public final void setElement(int rowIndex, int columnIndex, double value) {
m_Matrix.set(rowIndex, columnIndex, value);
}
/**
* Sets a row of the matrix to the given row. Performs a deep copy.
*
* @param index the row's index
* @param newRow an array of doubles
*/
public final void setRow(int index, double[] newRow) {
for (int i = 0; i < newRow.length; i++) {
m_Matrix.set(index, i, newRow[i]);
}
}
/**
* Gets a row of the matrix and returns it as double array.
*
* @param index the row's index
* @return an array of doubles
*/
public double[] getRow(int index) {
double[] newRow = new double[this.numColumns()];
for (int i = 0; i < newRow.length; i++) {
newRow[i] = getElement(index, i);
}
return newRow;
}
/**
* Gets a column of the matrix and returns it as a double array.
*
* @param index the column's index
* @return an array of doubles
*/
public double[] getColumn(int index) {
double[] newColumn = new double[this.numRows()];
for (int i = 0; i < newColumn.length; i++) {
newColumn[i] = getElement(i, index);
}
return newColumn;
}
/**
* Sets a column of the matrix to the given column. Performs a deep copy.
*
* @param index the column's index
* @param newColumn an array of doubles
*/
public final void setColumn(int index, double[] newColumn) {
for (int i = 0; i < numRows(); i++) {
m_Matrix.set(i, index, newColumn[i]);
}
}
/**
* Converts a matrix to a string
*
* @return the converted string
*/
@Override
public String toString() {
return m_Matrix.toString();
}
/**
* Returns the sum of this matrix with another.
*
* @return a matrix containing the sum.
*/
public final Matrix add(Matrix other) {
try {
return new Matrix(m_Matrix.plus(other.getMatrix()).getArrayCopy());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns the transpose of a matrix.
*
* @return the transposition of this instance.
*/
public final Matrix transpose() {
try {
return new Matrix(m_Matrix.transpose().getArrayCopy());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns true if the matrix is symmetric.
*
* @return boolean true if matrix is symmetric.
*/
public boolean isSymmetric() {
return m_Matrix.isSymmetric();
}
/**
* Returns the multiplication of two matrices
*
* @param b the multiplication matrix
* @return the product matrix
*/
public final Matrix multiply(Matrix b) {
try {
return new Matrix(getMatrix().times(b.getMatrix()).getArrayCopy());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Performs a (ridged) linear regression.
*
* @param y the dependent variable vector
* @param ridge the ridge parameter
* @return the coefficients
* @throws IllegalArgumentException if not successful
*/
public final double[] regression(Matrix y, double ridge) {
return getMatrix().regression(y.getMatrix(), ridge).getCoefficients();
}
/**
* Performs a weighted (ridged) linear regression.
*
* @param y the dependent variable vector
* @param w the array of data point weights
* @param ridge the ridge parameter
* @return the coefficients
* @throws IllegalArgumentException if the wrong number of weights were
* provided.
*/
public final double[] regression(Matrix y, double[] w, double ridge) {
return getMatrix().regression(y.getMatrix(), w, ridge).getCoefficients();
}
/**
* Returns the L part of the matrix. This does only make sense after LU
* decomposition.
*
* @return matrix with the L part of the matrix;
* @see #LUDecomposition()
*/
public Matrix getL() throws Exception {
int nr = numRows(); // num of rows
int nc = numColumns(); // num of columns
double[][] ld = new double[nr][nc];
for (int i = 0; i < nr; i++) {
for (int j = 0; (j < i) && (j < nc); j++) {
ld[i][j] = getElement(i, j);
}
if (i < nc) {
ld[i][i] = 1;
}
}
Matrix l = new Matrix(ld);
return l;
}
/**
* Returns the U part of the matrix. This does only make sense after LU
* decomposition.
*
* @return matrix with the U part of a matrix;
* @see #LUDecomposition()
*/
public Matrix getU() throws Exception {
int nr = numRows(); // num of rows
int nc = numColumns(); // num of columns
double[][] ud = new double[nr][nc];
for (int i = 0; i < nr; i++) {
for (int j = i; j < nc; j++) {
ud[i][j] = getElement(i, j);
}
}
Matrix u = new Matrix(ud);
return u;
}
/**
* Performs a LUDecomposition on the matrix. It changes the matrix into its LU
* decomposition.
*
* @return the indices of the row permutation
*/
public int[] LUDecomposition() throws Exception {
// decompose
weka.core.matrix.LUDecomposition lu = m_Matrix.lu();
// singular? old class throws Exception!
if (!lu.isNonsingular()) {
throw new Exception("Matrix is singular");
}
weka.core.matrix.Matrix u = lu.getU();
weka.core.matrix.Matrix l = lu.getL();
// modify internal matrix
int nr = numRows();
int nc = numColumns();
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
if (j < i) {
setElement(i, j, l.get(i, j));
} else {
setElement(i, j, u.get(i, j));
}
}
}
u = null;
l = null;
return lu.getPivot();
}
/**
* Solve A*X = B using backward substitution. A is current object (this). Note
* that this matrix will be changed! B parameter bb. X returned in parameter
* bb.
*
* @param bb first vector B in above equation then X in same equation.
*/
public void solve(double[] bb) throws Exception {
// solve
weka.core.matrix.Matrix x = m_Matrix.solve(new weka.core.matrix.Matrix(bb,
bb.length));
// move X into bb
int nr = x.getRowDimension();
for (int i = 0; i < nr; i++) {
bb[i] = x.get(i, 0);
}
}
/**
* Performs Eigenvalue Decomposition using Householder QR Factorization
*
* Matrix must be symmetrical. Eigenvectors are return in parameter V, as
* columns of the 2D array. (Real parts of) Eigenvalues are returned in
* parameter d.
*
* @param V double array in which the eigenvectors are returned
* @param d array in which the eigenvalues are returned
* @throws Exception if matrix is not symmetric
*/
public void eigenvalueDecomposition(double[][] V, double[] d)
throws Exception {
// old class only worked with symmetric matrices!
if (!this.isSymmetric()) {
throw new Exception("EigenvalueDecomposition: Matrix must be symmetric.");
}
// perform eigenvalue decomposition
weka.core.matrix.EigenvalueDecomposition eig = m_Matrix.eig();
weka.core.matrix.Matrix v = eig.getV();
double[] d2 = eig.getRealEigenvalues();
// transfer data
int nr = numRows();
int nc = numColumns();
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
V[i][j] = v.get(i, j);
}
}
for (int i = 0; i < d2.length; i++) {
d[i] = d2[i];
}
}
/**
* Returns sqrt(a^2 + b^2) without under/overflow.
*
* @param a length of one side of rectangular triangle
* @param b length of other side of rectangular triangle
* @return lenght of third side
*/
protected static double hypot(double a, double b) {
return weka.core.matrix.Maths.hypot(a, b);
}
/**
* converts the Matrix into a single line Matlab string: matrix is enclosed by
* parentheses, rows are separated by semicolon and single cells by blanks,
* e.g., [1 2; 3 4].
*
* @return the matrix in Matlab single line format
*/
public String toMatlab() {
return getMatrix().toMatlab();
}
/**
* creates a matrix from the given Matlab string.
*
* @param matlab the matrix in matlab format
* @return the matrix represented by the given string
* @see #toMatlab()
*/
public static Matrix parseMatlab(String matlab) throws Exception {
return new Matrix(weka.core.matrix.Matrix.parseMatlab(matlab).getArray());
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*/
public static void main(String[] ops) {
double[] first = { 2.3, 1.2, 5 };
double[] second = { 5.2, 1.4, 9 };
double[] response = { 4, 7, 8 };
double[] weights = { 1, 2, 3 };
try {
// test eigenvaluedecomposition
double[][] m = { { 1, 2, 3 }, { 2, 5, 6 }, { 3, 6, 9 } };
Matrix M = new Matrix(m);
int n = M.numRows();
double[][] V = new double[n][n];
double[] d = new double[n];
M.eigenvalueDecomposition(V, d);
Matrix a = new Matrix(2, 3);
Matrix b = new Matrix(3, 2);
System.out.println("Number of columns for a: " + a.numColumns());
System.out.println("Number of rows for a: " + a.numRows());
a.setRow(0, first);
a.setRow(1, second);
b.setColumn(0, first);
b.setColumn(1, second);
System.out.println("a:\n " + a);
System.out.println("b:\n " + b);
System.out.println("a (0, 0): " + a.getElement(0, 0));
System.out.println("a transposed:\n " + a.transpose());
System.out.println("a * b:\n " + a.multiply(b));
Matrix r = new Matrix(3, 1);
r.setColumn(0, response);
System.out.println("r:\n " + r);
System.out.println("Coefficients of regression of b on r: ");
double[] coefficients = b.regression(r, 1.0e-8);
for (double coefficient : coefficients) {
System.out.print(coefficient + " ");
}
System.out.println();
System.out.println("Weights: ");
for (double weight : weights) {
System.out.print(weight + " ");
}
System.out.println();
System.out.println("Coefficients of weighted regression of b on r: ");
coefficients = b.regression(r, weights, 1.0e-8);
for (double coefficient : coefficients) {
System.out.print(coefficient + " ");
}
System.out.println();
a.setElement(0, 0, 6);
System.out.println("a with (0, 0) set to 6:\n " + a);
a.write(new java.io.FileWriter("main.matrix"));
System.out.println("wrote matrix to \"main.matrix\"\n" + a);
a = new Matrix(new java.io.FileReader("main.matrix"));
System.out.println("read matrix from \"main.matrix\"\n" + a);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Memory.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Memory.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import javax.swing.JCheckBox;
import javax.swing.JOptionPane;
/**
* A little helper class for Memory management. The memory management can be
* disabled by using the setEnabled(boolean) method.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see #setEnabled(boolean)
*/
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 boolean m_Enabled = true;
/** whether a GUI is present */
protected boolean m_UseGUI = false;
/** the managed bean to use */
protected static MemoryMXBean m_MemoryMXBean = ManagementFactory
.getMemoryMXBean();
/** the last MemoryUsage object obtained */
protected MemoryUsage m_MemoryUsage = null;
/** the delay before testing for out of memory */
protected long m_SleepTime = MAX_SLEEP_TIME;
/**
* initializes the memory management without GUI support
*/
public Memory() {
this(false);
}
/**
* initializes the memory management
*
* @param useGUI whether a GUI is present
*/
public Memory(boolean useGUI) {
m_UseGUI = useGUI;
}
/**
* returns whether the memory management is enabled
*
* @return true if enabled
*/
public boolean isEnabled() {
return m_Enabled;
}
/**
* sets whether the memory management is enabled
*
* @param value true if the management should be enabled
*/
public void setEnabled(boolean value) {
m_Enabled = value;
}
/**
* whether to display a dialog in case of a problem (= TRUE) or just print on
* stderr (= FALSE)
*
* @return true if the GUI is used
*/
public boolean getUseGUI() {
return m_UseGUI;
}
/**
* returns the initial size of the JVM heap, obtains a fresh MemoryUsage
* object to do so.
*
* @return the initial size in bytes
*/
public long getInitial() {
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
return m_MemoryUsage.getInit();
}
/**
* returns the currently used size of the JVM heap, obtains a fresh
* MemoryUsage object to do so.
*
* @return the used size in bytes
*/
public long getCurrent() {
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
return m_MemoryUsage.getUsed();
}
/**
* returns the maximum size of the JVM heap, obtains a fresh MemoryUsage
* object to do so.
*
* @return the maximum size in bytes
*/
public long getMax() {
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
return m_MemoryUsage.getMax();
}
/**
* checks if there's still enough memory left by checking whether there is
* still a 50MB margin between getUsed() and getMax(). if ENABLED is true,
* then false is returned always. updates the MemoryUsage variable before
* checking.
*
* @return true if out of memory (only if management enabled, otherwise always
* false)
*/
public boolean isOutOfMemory() {
try {
Thread.sleep(m_SleepTime);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
if (isEnabled()) {
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;
}
}
/**
* Checks to see if memory is running low. Low is defined as available memory
* less than 20% of max memory.
*
* @return true if memory is running low
*/
public boolean memoryIsLow() {
m_MemoryUsage = m_MemoryMXBean.getHeapMemoryUsage();
if (isEnabled()) {
long lowThreshold = (long) (0.2 * m_MemoryUsage.getMax());
// min threshold of 100Mb
if (lowThreshold < LOW_MEMORY_MINIMUM) {
lowThreshold = LOW_MEMORY_MINIMUM;
}
long avail = m_MemoryUsage.getMax() - m_MemoryUsage.getUsed();
return (avail < lowThreshold);
} else {
return false;
}
}
/**
* returns the amount of bytes as MB
*
* @return the MB amount
*/
public static double toMegaByte(long bytes) {
return (bytes / (double) (1024 * 1024));
}
/**
* prints an error message if OutOfMemory (and if GUI is present a dialog),
* otherwise nothing happens. isOutOfMemory() has to be called beforehand,
* since it sets all the memory parameters.
*
* @see #isOutOfMemory()
* @see #m_Enabled
*/
public void showOutOfMemory() {
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.";
System.err.println(msg);
if (getUseGUI()) {
JOptionPane.showMessageDialog(null, msg, "OutOfMemory",
JOptionPane.WARNING_MESSAGE);
}
}
/**
* Prints a warning message if memoryIsLow (and if GUI is present a dialog).
*
* @return true if user opts to continue, disabled or GUI is not present.
*/
public boolean showMemoryIsLow() {
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";
System.err.println(msg);
if (getUseGUI()) {
if (!Utils.getDontShowDialog("weka.core.Memory.LowMemoryWarning")) {
JCheckBox dontShow = new JCheckBox("Do not show this message again");
Object[] stuff = new Object[2];
stuff[0] = msg;
stuff[1] = dontShow;
int result = JOptionPane.showConfirmDialog(null, stuff, "Memory",
JOptionPane.YES_NO_OPTION);
if (dontShow.isSelected()) {
try {
Utils.setDontShowDialog("weka.core.Memory.LowMemoryWarning");
} catch (Exception ex) {
// quietly ignore
}
}
return (result == JOptionPane.YES_OPTION);
}
}
return true;
}
/**
* stops all the current threads, to make a restart possible
*/
@SuppressWarnings("deprecation")
public void stopThreads() {
int i;
Thread[] thGroup;
Thread t;
thGroup = new Thread[Thread.activeCount()];
Thread.enumerate(thGroup);
for (i = 0; i < thGroup.length; i++) {
t = thGroup[i];
if (t != null) {
if (t != Thread.currentThread()) {
if (t.getName().startsWith("Thread")) {
t.stop();
} else if (t.getName().startsWith("AWT-EventQueue")) {
t.stop();
}
}
}
}
thGroup = null;
System.gc();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* prints only some statistics
*
* @param args the commandline arguments - ignored
*/
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() + ")");
System.out.println("Max memory: "
+ Utils.doubleToString(Memory.toMegaByte(mem.getMax()), 1) + "MB" + " ("
+ mem.getMax() + ")");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/MinkowskiDistance.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* MinkowskiDistance.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.neighboursearch.PerformanceStats;
/**
* <!-- globalinfo-start --> Implementing Minkowski distance (or similarity)
* function.<br/>
* <br/>
* One object defines not one distance but the data model in which the distances
* between objects of that data model can be computed.<br/>
* <br/>
* Attention: For efficiency reasons the use of consistency checks (like are the
* data models of the two instances exactly the same), is low.<br/>
* <br/>
* For more information, see:<br/>
* <br/>
* Wikipedia. Minkowski distance. URL
* http://en.wikipedia.org/wiki/Minkowski_distance.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- technical-bibtex-start --> BibTeX:
*
* <pre>
* @misc{missing_id,
* author = {Wikipedia},
* title = {Minkowski distance},
* URL = {http://en.wikipedia.org/wiki/Minkowski_distance}
* }
* </pre>
* <p/>
* <!-- technical-bibtex-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -P <order>
* The order 'p'. With '1' being the Manhattan distance and '2'
* the Euclidean distance.
* (default: 2)
* </pre>
*
* <pre>
* -D
* Turns off the normalization of attribute
* values in distance calculation.
* </pre>
*
* <pre>
* -R <col1,col2-col4,...>
* Specifies list of columns to used in the calculation of the
* distance. 'first' and 'last' are valid indices.
* (default: first-last)
* </pre>
*
* <pre>
* -V
* Invert matching sense of column indices.
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class MinkowskiDistance extends NormalizableDistance implements
Cloneable, TechnicalInformationHandler {
/** for serialization. */
private static final long serialVersionUID = -7446019339455453893L;
/** the order of the minkowski distance. */
protected double m_Order = 2;
/**
* Constructs an Minkowski Distance object, Instances must be still set.
*/
public MinkowskiDistance() {
super();
}
/**
* Constructs an Minkowski Distance object and automatically initializes the
* ranges.
*
* @param data the instances the distance function should work on
*/
public MinkowskiDistance(Instances data) {
super(data);
}
/**
* Returns a string describing this object.
*
* @return a description of the evaluator suitable for displaying in the
* explorer/experimenter gui
*/
@Override
public String globalInfo() {
return "Implementing Minkowski distance (or similarity) function.\n\n"
+ "One object defines not one distance but the data model in which "
+ "the distances between objects of that data model can be computed.\n\n"
+ "Attention: For efficiency reasons the use of consistency checks "
+ "(like are the data models of the two instances exactly the same), "
+ "is low.\n\n" + "For more information, see:\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.
*
* @return the technical information about this class
*/
@Override
public TechnicalInformation getTechnicalInformation() {
TechnicalInformation result;
result = new TechnicalInformation(Type.MISC);
result.setValue(Field.AUTHOR, "Wikipedia");
result.setValue(Field.TITLE, "Minkowski distance");
result.setValue(Field.URL,
"http://en.wikipedia.org/wiki/Minkowski_distance");
return result;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option(
"\tThe order 'p'. With '1' being the Manhattan distance and '2'\n"
+ "\tthe Euclidean distance.\n" + "\t(default: 2)", "P", 1,
"-P <order>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* 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
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
tmpStr = Utils.getOption('P', options);
if (tmpStr.length() > 0) {
setOrder(Double.parseDouble(tmpStr));
} else {
setOrder(2);
}
super.setOptions(options);
}
/**
* Gets the current settings of this object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
result = new Vector<String>();
result.add("-P");
result.add("" + getOrder());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String orderTipText() {
return "The order of the Minkowski distance ('1' is Manhattan distance and "
+ "'2' the Euclidean distance).";
}
/**
* Sets the order.
*
* @param value the new order
*/
public void setOrder(double value) {
if (m_Order != 0.0) {
m_Order = value;
invalidate();
} else {
System.err.println("Order cannot be zero!");
}
}
/**
* Gets the order.
*
* @return the order
*/
public double getOrder() {
return m_Order;
}
/**
* Calculates the distance between two 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 Math.pow(distance(first, second, Double.POSITIVE_INFINITY),
1 / m_Order);
}
/**
* Calculates the distance (or similarity) between two instances. Need to pass
* this returned distance later on to postprocess method to set it on correct
* scale. <br/>
* P.S.: Please don't mix the use of this function with distance(Instance
* first, Instance second), as that already does post processing. Please
* consider passing Double.POSITIVE_INFINITY as the cutOffValue to this
* function and then later on do the post processing on all the distances.
*
* @param first the first instance
* @param second the second instance
* @param stats the structure for storing performance statistics.
* @return the distance between the two given instances or
* Double.POSITIVE_INFINITY.
*/
@Override
public double distance(Instance first, Instance second, PerformanceStats stats) { // debug
// method
// pls
// remove
// after
// use
return Math.pow(distance(first, second, Double.POSITIVE_INFINITY, stats),
1 / m_Order);
}
/**
* Updates the current distance calculated so far with the new difference
* 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)
*/
@Override
protected double updateDistance(double currDist, double diff) {
double result;
result = currDist;
result += Math.pow(Math.abs(diff), m_Order);
return result;
}
/**
* Does post processing of the distances (if necessary) returned by
* distance(distance(Instance first, Instance second, double cutOffValue). It
* is necessary to do so to get the correct distances if
* distance(distance(Instance first, Instance second, double cutOffValue) is
* used. This is because that function actually returns the squared distance
* to avoid inaccuracies arising from floating point comparison.
*
* @param distances the distances to post-process
*/
@Override
public void postProcessDistances(double distances[]) {
for (int i = 0; i < distances.length; i++) {
distances[i] = Math.pow(distances[i], 1 / m_Order);
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision: 0$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/MultiInstanceCapabilitiesHandler.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* MultiInstanceClassifier.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
/**
* Multi-Instance classifiers can specify an additional Capabilities object
* for the data in the relational attribute, since the format of multi-instance
* data is fixed to "bag/NOMINAL,data/RELATIONAL,class".
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public interface MultiInstanceCapabilitiesHandler
extends CapabilitiesHandler {
/**
* Returns the capabilities of this multi-instance classifier for the
* relational data (i.e., the bags).
*
* @return the capabilities of this object
* @see Capabilities
*/
public Capabilities getMultiInstanceCapabilities();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/NoSupportForMissingValuesException.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* NoSupportForMissingValuesException.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Exception that is raised by an object that is unable to process
* data with missing values.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class NoSupportForMissingValuesException
extends WekaException {
/** for serialization */
private static final long serialVersionUID = 5161175307725893973L;
/**
* Creates a new NoSupportForMissingValuesException with no message.
*
*/
public NoSupportForMissingValuesException() {
super();
}
/**
* Creates a new NoSupportForMissingValuesException.
*
* @param message the reason for raising an exception.
*/
public NoSupportForMissingValuesException(String message) {
super(message);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/NominalAttributeInfo.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* NominalAttributeInfo.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
/**
* Stores information for nominal and string attributes.
*/
public class NominalAttributeInfo implements AttributeInfo {
/** The attribute's values. */
protected/* @ spec_public @ */ArrayList<Object> m_Values;
/** Mapping of values to indices. */
protected Hashtable<Object, Integer> m_Hashtable;
/**
* Constructs the info based on argument.
*/
public NominalAttributeInfo(List<String> attributeValues, String attributeName) {
if (attributeValues == null) {
m_Values = new ArrayList<Object>();
m_Hashtable = new Hashtable<Object, Integer>();
} else {
m_Values = new ArrayList<Object>(attributeValues.size());
m_Hashtable = new Hashtable<Object, Integer>(attributeValues.size());
for (int i = 0; i < attributeValues.size(); i++) {
Object store = attributeValues.get(i);
if (((String) store).length() > Attribute.STRING_COMPRESS_THRESHOLD) {
try {
store = new SerializedObject(attributeValues.get(i), true);
} catch (Exception ex) {
System.err.println("Couldn't compress nominal attribute value -"
+ " storing uncompressed.");
}
}
if (m_Hashtable.containsKey(store)) {
throw new IllegalArgumentException("A nominal attribute ("
+ attributeName + ") cannot" + " have duplicate labels (" + store
+ ").");
}
m_Values.add(store);
m_Hashtable.put(store, new Integer(i));
}
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/NormalizableDistance.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* NormalizableDistance.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
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@cs.waikato.ac.nz) -- original code from
* weka.core.EuclideanDistance
* @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz) -- original code from
* weka.core.EuclideanDistance
* @version $Revision$
*/
public abstract class NormalizableDistance implements DistanceFunction,
OptionHandler, Serializable, RevisionHandler {
/** Serial version id to avoid warning */
private static final long serialVersionUID = -2806520224161351708L;
/** 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). */
protected boolean m_DontNormalize = false;
/** The range of the attributes. */
protected double[][] m_Ranges;
/** The range of attributes to use for calculating the distance. */
protected Range m_AttributeIndices = new Range("first-last");
/** 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;
/**
* Invalidates the distance function, Instances must be still set.
*/
public NormalizableDistance() {
invalidate();
}
/**
* Initializes the distance function and automatically initializes the ranges.
*
* @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
*/
public abstract String globalInfo();
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
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.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()
*/
@Override
public String[] getOptions() {
Vector<String> result;
result = new Vector<String>();
if (getDontNormalize()) {
result.add("-D");
}
result.add("-R");
result.add(getAttributeIndices());
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
*/
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
setDontNormalize(Utils.getFlag('D', options));
tmpStr = Utils.getOption('R', options);
if (tmpStr.length() != 0) {
setAttributeIndices(tmpStr);
} 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
*/
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). ";
}
/**
* Sets whether if the attribute values are to be normalized in distance
* calculation.
*
* @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
*/
public boolean getDontNormalize() {
return m_DontNormalize;
}
/**
* Returns the tip text for this property.
*
* @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. "
+ "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
*
* @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
*/
@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
*/
public String invertSelectionTipText() {
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
*/
@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
*/
@Override
public boolean getInvertSelection() {
return m_AttributeIndices.getInvert();
}
/**
* invalidates all initializations.
*/
protected void invalidate() {
m_Validated = false;
}
/**
* performs the initializations if necessary.
*/
protected void validate() {
if (!m_Validated) {
initialize();
m_Validated = true;
}
}
/**
* initializes the ranges and the attributes being used.
*/
protected void initialize() {
initializeAttributeIndices();
initializeRanges();
}
/**
* initializes the attribute indices.
*/
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++) {
m_ActiveIndices[i] = m_AttributeIndices.isInRange(i);
}
}
/**
* Sets the instances.
*
* @param insts the instances to use
*/
@Override
public void setInstances(Instances insts) {
m_Data = insts;
invalidate();
}
/**
* returns the instances currently set.
*
* @return the current instances
*/
@Override
public Instances getInstances() {
return m_Data;
}
/**
* Does nothing, derived classes may override it though.
*
* @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
*/
@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
*/
@Override
public double distance(Instance first, Instance second) {
return distance(first, second, null);
}
/**
* 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
*/
@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
* 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.
*/
@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
* 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.
*/
@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);
}
if (firstI == classIndex) {
p1++;
continue;
}
if ((firstI < numAttributes) && !m_ActiveIndices[firstI]) {
p1++;
continue;
}
if (secondI == classIndex) {
p2++;
continue;
}
if ((secondI < numAttributes) && !m_ActiveIndices[secondI]) {
p2++;
continue;
}
double diff;
if (firstI == secondI) {
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++;
}
if (stats != null) {
stats.incrCoordCount();
}
distance = updateDistance(distance, diff);
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
* 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)
*/
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
*/
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])) {
return 0;
} else {
return (x - m_Ranges[i][R_MIN]) / (m_Ranges[i][R_WIDTH]);
}
}
/**
* 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
*/
protected double difference(int index, double val1, double val2) {
switch (m_Data.attribute(index).type()) {
case Attribute.NOMINAL:
if (Utils.isMissingValue(val1) || Utils.isMissingValue(val2)
|| ((int) val1 != (int) val2)) {
return 1;
} else {
return 0;
}
case Attribute.NUMERIC:
if (Utils.isMissingValue(val1) || Utils.isMissingValue(val2)) {
if (Utils.isMissingValue(val1) && Utils.isMissingValue(val2)) {
if (!m_DontNormalize) {
return 1;
} else {
return (m_Ranges[index][R_MAX] - m_Ranges[index][R_MIN]);
}
} else {
double diff;
if (Utils.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;
}
} 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.
*
* @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];
if (m_Data.numInstances() <= 0) {
initializeRangesEmpty(numAtt, ranges);
m_Ranges = ranges;
return m_Ranges;
} 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++) {
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.
*
* @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++) {
if (!instance.isMissing(j)) {
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
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
*/
public void updateRanges(Instance instance, int numAtt, double[][] ranges) {
// updateRangesFirst must have been called on ranges
for (int j = 0; j < numAtt; j++) {
double value = instance.value(j);
if (!instance.isMissing(j)) {
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
ranges[j][R_WIDTH] = ranges[j][R_MAX] - ranges[j][R_MIN];
}
} else {
if (value > ranges[j][R_MAX]) {
ranges[j][R_MAX] = value;
ranges[j][R_WIDTH] = ranges[j][R_MAX] - ranges[j][R_MIN];
}
}
}
}
}
/**
* Used to initialize the ranges.
*
* @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++) {
ranges[j][R_MIN] = Double.POSITIVE_INFINITY;
ranges[j][R_MAX] = -Double.POSITIVE_INFINITY;
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
*/
public double[][] updateRanges(Instance instance, double[][] ranges) {
// updateRangesFirst must have been called on ranges
for (int j = 0; j < ranges.length; j++) {
double value = instance.value(j);
if (!instance.isMissing(j)) {
if (value < ranges[j][R_MIN]) {
ranges[j][R_MIN] = value;
ranges[j][R_WIDTH] = ranges[j][R_MAX] - ranges[j][R_MIN];
} else {
if (instance.value(j) > ranges[j][R_MAX]) {
ranges[j][R_MAX] = value;
ranges[j][R_WIDTH] = ranges[j][R_MAX] - ranges[j][R_MIN];
}
}
}
}
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
*/
public double[][] initializeRanges(int[] instList) throws Exception {
if (m_Data == null) {
throw new Exception("No instances supplied.");
}
int numAtt = m_Data.numAttributes();
double[][] ranges = new double[numAtt][3];
if (m_Data.numInstances() <= 0) {
initializeRangesEmpty(numAtt, ranges);
return ranges;
} else {
// initialize ranges using the first instance
updateRangesFirst(m_Data.instance(instList[0]), numAtt, ranges);
// update ranges, starting from the second
for (int i = 1; i < instList.length; i++) {
updateRanges(m_Data.instance(instList[i]), numAtt, ranges);
}
}
return ranges;
}
/**
* 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) {
throw new Exception("No instances supplied.");
}
int numAtt = m_Data.numAttributes();
double[][] ranges = new double[numAtt][3];
if (m_Data.numInstances() <= 0) {
initializeRangesEmpty(numAtt, ranges);
return ranges;
} 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++) {
updateRanges(m_Data.instance(instList[i]), numAtt, ranges);
}
}
return ranges;
}
/**
* Update the ranges if a new instance comes.
*
* @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
*/
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];
}
}
}
return isIn;
}
/**
* Check 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
*/
public double[][] getRanges() throws Exception {
validate();
if (m_Ranges == null) {
throw new Exception("Ranges not yet set.");
}
return m_Ranges;
}
@Override
public void clean() {
m_Data = new Instances(m_Data, 0);
}
/**
* Returns an empty string.
*
* @return an empty string
*/
@Override
public String toString() {
return "";
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Optimization.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Optimization.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import weka.core.TechnicalInformation.Field;
import weka.core.TechnicalInformation.Type;
import weka.core.matrix.Matrix;
/**
* Implementation of Active-sets method with BFGS update to solve optimization problem with only bounds constraints in multi-dimensions. In this implementation we consider both the lower and higher bound constraints.
* <p/>
*
* Here is the sketch of our searching strategy, and the detailed description of the algorithm can be found in the Appendix of Xin Xu's MSc thesis:
* <p/>
* Initialize everything, incl. initial value, direction, etc.
* <p/>
* LOOP (main algorithm):<br/>
*
* 1. Perform the line search using the directions for free variables<br/>
* 1.1 Check all the bounds that are not "active" (i.e. binding variables) and compute the feasible step length to the bound for each of them<br/>
* 1.2 Pick up the least feasible step length, say \alpha, and set it as the upper bound of the current step length, i.e. 0<\lambda<=\alpha<br/>
* 1.3 Search for any possible step length<=\alpha that can result the "sufficient function decrease" (\alpha condition) AND "positive definite inverse Hessian" (\beta condition), if possible, using SAFEGUARDED polynomial interpolation.
* This step length is "safe" and thus is used to compute the next value of the free variables .<br/>
* 1.4 Fix the variable(s) that are newly bound to its constraint(s).
* <p/>
*
* 2. Check whether there is convergence of all variables or their gradients. If there is, check the possibilities to release any current bindings of the fixed variables to their bounds based on the "reliable" second-order Lagarange
* multipliers if available. If it's available and negative for one variable, then release it. If not available, use first-order Lagarange multiplier to test release. If there is any released variables, STOP the loop. Otherwise update the
* inverse of Hessian matrix and gradient for the newly released variables and CONTINUE LOOP.
* <p/>
*
* 3. Use BFGS formula to update the inverse of Hessian matrix. Note the already-fixed variables must have zeros in the corresponding entries in the inverse Hessian.
* <p/>
*
* 4. Compute the new (newton) search direction d=H^{-1}*g, where H^{-1} is the inverse Hessian and g is the Jacobian. Note that again, the already- fixed variables will have zero direction.
* <p/>
*
* ENDLOOP
* <p/>
*
* A typical usage of this class is to create your own subclass of this class and provide the objective function and gradients as follows:
* <p/>
*
* <pre>
* class MyOpt extends Optimization {
* // Provide the objective function
* protected double objectiveFunction(double[] x) {
* // How to calculate your objective function...
* // ...
* }
*
* // Provide the first derivatives
* protected double[] evaluateGradient(double[] x) {
* // How to calculate the gradient of the objective function...
* // ...
* }
*
* // If possible, provide the indexˆ{th} row of the Hessian matrix
* protected double[] evaluateHessian(double[] x, int index) {
* // How to calculate the indexˆth variable's second derivative
* // ...
* }
* }
* </pre>
*
* When it's the time to use it, in some routine(s) of other class...
*
* <pre>
* MyOpt opt = new MyOpt();
*
* // Set up initial variable values and bound constraints
* double[] x = new double[numVariables];
* // Lower and upper bounds: 1st row is lower bounds, 2nd is upper
* double[] constraints = new double[2][numVariables];
* ...
*
* // Find the minimum, 200 iterations as default
* x = opt.findArgmin(x, constraints);
* while(x == null){ // 200 iterations are not enough
* x = opt.getVarbValues(); // Try another 200 iterations
* x = opt.findArgmin(x, constraints);
* }
*
* // The minimal function value
* double minFunction = opt.getMinFunction();
* ...
* </pre>
*
* It is recommended that Hessian values be provided so that the second-order Lagrangian multiplier estimate can be calcluated. However, if it is not provided, there is no need to override the <code>evaluateHessian()</code> function.
* <p/>
*
* REFERENCES (see also the <code>getTechnicalInformation()</code> method):<br/>
* The whole model algorithm is adapted from Chapter 5 and other related chapters in Gill, Murray and Wright(1981) "Practical Optimization", Academic Press. and Gill and Murray(1976) "Minimization Subject to Bounds on the Variables", NPL
* Report NAC72, while Chong and Zak(1996) "An Introduction to Optimization", John Wiley & Sons, Inc. provides us a brief but helpful introduction to the method.
* <p/>
*
* Dennis and Schnabel(1983) "Numerical Methods for Unconstrained Optimization and Nonlinear Equations", Prentice-Hall Inc. and Press et al.(1992) "Numeric Recipe in C", Second Edition, Cambridge University Press. are consulted for the
* polynomial interpolation used in the line search implementation.
* <p/>
*
* The Hessian modification in BFGS update uses Cholesky factorization and two rank-one modifications:<br/>
* Bk+1 = Bk + (Gk*Gk')/(Gk'Dk) + (dGk*(dGk)'))/[alpha*(dGk)'*Dk]. <br/>
* where Gk is the gradient vector, Dk is the direction vector and alpha is the step rate. <br/>
* This method is due to Gill, Golub, Murray and Saunders(1974) ``Methods for Modifying Matrix Factorizations'', Mathematics of Computation, Vol.28, No.126, pp 505-535.
* <p/>
*
* @author Xin Xu (xx5@cs.waikato.ac.nz)
* @version $Revision$
* @see #getTechnicalInformation()
*/
public abstract class Optimization implements TechnicalInformationHandler, RevisionHandler {
protected double m_ALF = 1.0e-4;
protected double m_BETA = 0.9;
protected double m_TOLX = 1.0e-6;
protected double m_STPMX = 100.0;
protected int m_MAXITS = 200;
protected boolean m_Debug = false;
/** function value */
protected double m_f;
/** G'*p */
private double m_Slope;
/** Test if zero step in lnsrch */
protected boolean m_IsZeroStep = false;
/** Used when iteration overflow occurs */
protected double[] m_X;
/** Compute machine precision */
protected static double m_Epsilon, m_Zero;
static {
m_Epsilon = 1.0;
while (1.0 + m_Epsilon > 1.0) {
m_Epsilon /= 2.0;
}
m_Epsilon *= 2.0;
m_Zero = Math.sqrt(m_Epsilon);
}
/**
* 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;
result = new TechnicalInformation(Type.MASTERSTHESIS);
result.setValue(Field.AUTHOR, "Xin Xu");
result.setValue(Field.YEAR, "2003");
result.setValue(Field.TITLE, "Statistical learning in multiple instance problem");
result.setValue(Field.SCHOOL, "University of Waikato");
result.setValue(Field.ADDRESS, "Hamilton, NZ");
result.setValue(Field.NOTE, "0657.594");
additional = result.add(Type.BOOK);
additional.setValue(Field.AUTHOR, "P. E. Gill and W. Murray and M. H. Wright");
additional.setValue(Field.YEAR, "1981");
additional.setValue(Field.TITLE, "Practical Optimization");
additional.setValue(Field.PUBLISHER, "Academic Press");
additional.setValue(Field.ADDRESS, "London and New York");
additional = result.add(Type.TECHREPORT);
additional.setValue(Field.AUTHOR, "P. E. Gill and W. Murray");
additional.setValue(Field.YEAR, "1976");
additional.setValue(Field.TITLE, "Minimization subject to bounds on the variables");
additional.setValue(Field.INSTITUTION, "National Physical Laboratory");
additional.setValue(Field.NUMBER, "NAC 72");
additional = result.add(Type.BOOK);
additional.setValue(Field.AUTHOR, "E. K. P. Chong and S. H. Zak");
additional.setValue(Field.YEAR, "1996");
additional.setValue(Field.TITLE, "An Introduction to Optimization");
additional.setValue(Field.PUBLISHER, "John Wiley and Sons");
additional.setValue(Field.ADDRESS, "New York");
additional = result.add(Type.BOOK);
additional.setValue(Field.AUTHOR, "J. E. Dennis and R. B. Schnabel");
additional.setValue(Field.YEAR, "1983");
additional.setValue(Field.TITLE, "Numerical Methods for Unconstrained Optimization and Nonlinear Equations");
additional.setValue(Field.PUBLISHER, "Prentice-Hall");
additional = result.add(Type.BOOK);
additional.setValue(Field.AUTHOR, "W. H. Press and B. P. Flannery and S. A. Teukolsky and W. T. Vetterling");
additional.setValue(Field.YEAR, "1992");
additional.setValue(Field.TITLE, "Numerical Recipes in C");
additional.setValue(Field.PUBLISHER, "Cambridge University Press");
additional.setValue(Field.EDITION, "Second");
additional = result.add(Type.ARTICLE);
additional.setValue(Field.AUTHOR, "P. E. Gill and G. H. Golub and W. Murray and M. A. Saunders");
additional.setValue(Field.YEAR, "1974");
additional.setValue(Field.TITLE, "Methods for modifying matrix factorizations");
additional.setValue(Field.JOURNAL, "Mathematics of Computation");
additional.setValue(Field.VOLUME, "28");
additional.setValue(Field.NUMBER, "126");
additional.setValue(Field.PAGES, "505-535");
return result;
}
/**
* Subclass should implement this procedure to evaluate objective function to be minimized
*
* @param x
* the variable values
* @return the objective function value
* @throws Exception
* if something goes wrong
*/
protected abstract double objectiveFunction(double[] x) throws Exception;
/**
* Subclass should implement this procedure to evaluate gradient of the objective function
*
* @param x
* the variable values
* @return the gradient vector
* @throws Exception
* if something goes wrong
*/
protected abstract double[] evaluateGradient(double[] x) throws Exception;
/**
* Subclass is recommended to override this procedure to evaluate second-order gradient of the objective function. If it's not provided, it returns null.
*
* @param x
* the variables
* @param index
* the row index in the Hessian matrix
* @return one row (the row #index) of the Hessian matrix, null as default
* @throws Exception
* if something goes wrong
*/
protected double[] evaluateHessian(final double[] x, final int index) throws Exception {
return null;
}
/**
* Get the minimal function value
*
* @return minimal function value found
*/
public double getMinFunction() {
return this.m_f;
}
/**
* Set the maximal number of iterations in searching (Default 200)
*
* @param it
* the maximal number of iterations
*/
public void setMaxIteration(final int it) {
this.m_MAXITS = it;
}
/**
* Set whether in debug mode
*
* @param db
* use debug or not
*/
public void setDebug(final boolean db) {
this.m_Debug = db;
}
/**
* Get the variable values. Only needed when iterations exceeds the max threshold.
*
* @return the current variable values
*/
public double[] getVarbValues() {
return this.m_X;
}
/**
* Find a new point x in the direction p from a point xold at which the value of the function has decreased sufficiently, the positive definiteness of B matrix (approximation of the inverse of the Hessian) is preserved and no bound
* constraints are violated. Details see "Numerical Methods for Unconstrained Optimization and Nonlinear Equations". "Numeric Recipes in C" was also consulted.
*
* @param xold
* old x value
* @param gradient
* gradient at that point
* @param direct
* direction vector
* @param stpmax
* maximum step length
* @param isFixed
* indicating whether a variable has been fixed
* @param nwsBounds
* non-working set bounds. Means these variables are free and subject to the bound constraints in this step
* @param wsBdsIndx
* index of variables that has working-set bounds. Means these variables are already fixed and no longer subject to the constraints
* @return new value along direction p from xold, null if no step was taken
* @throws Exception
* if an error occurs
*/
public double[] lnsrch(final double[] xold, final double[] gradient, final double[] direct, final double stpmax, final boolean[] isFixed, final double[][] nwsBounds, final DynamicIntArray wsBdsIndx) throws Exception {
if (this.m_Debug) {
System.err.print("Machine precision is " + m_Epsilon + " and zero set to " + m_Zero);
}
int i, k, len = xold.length, fixedOne = -1; // idx of variable to be fixed
double alam, alamin; // lambda to be found, and its lower bound
// For convergence and bound test
double temp, test, alpha = Double.POSITIVE_INFINITY, fold = this.m_f, sum;
// For cubic interpolation
double a, alam2 = 0, b, disc = 0, maxalam = 1.0, rhs1, rhs2, tmplam;
double[] x = new double[len]; // New variable values
// Scale the step
for (sum = 0.0, i = 0; i < len; i++) {
if (!isFixed[i]) {
sum += direct[i] * direct[i];
}
}
sum = Math.sqrt(sum);
if (this.m_Debug) {
System.err.println("fold: " + Utils.doubleToString(fold, 10, 7) + "\n" + "sum: " + Utils.doubleToString(sum, 10, 7) + "\n" + "stpmax: " + Utils.doubleToString(stpmax, 10, 7));
}
if (sum > stpmax) {
for (i = 0; i < len; i++) {
if (!isFixed[i]) {
direct[i] *= stpmax / sum;
}
}
} else {
maxalam = stpmax / sum;
}
// Compute initial rate of decrease, g'*d
this.m_Slope = 0.0;
for (i = 0; i < len; i++) {
x[i] = xold[i];
if (!isFixed[i]) {
this.m_Slope += gradient[i] * direct[i];
}
}
if (this.m_Debug) {
System.err.print("slope: " + Utils.doubleToString(this.m_Slope, 10, 7) + "\n");
}
// Slope too small
if (Math.abs(this.m_Slope) <= m_Zero) {
if (this.m_Debug) {
System.err.println("Gradient and direction orthogonal -- " + "Min. found with current fixed variables" + " (or all variables fixed). Try to release" + " some variables now.");
}
return x;
}
// Err: slope > 0
if (this.m_Slope > m_Zero) {
if (this.m_Debug) {
for (int h = 0; h < x.length; h++) {
System.err.println(h + ": isFixed=" + isFixed[h] + ", x=" + x[h] + ", grad=" + gradient[h] + ", direct=" + direct[h]);
}
}
throw new Exception("g'*p positive! -- Try to debug from here: line 327.");
}
// Compute LAMBDAmin and upper bound of lambda--alpha
test = 0.0;
for (i = 0; i < len; i++) {
if (!isFixed[i]) {// No need for fixed variables
temp = Math.abs(direct[i]) / Math.max(Math.abs(x[i]), 1.0);
if (temp > test) {
test = temp;
}
}
}
if (test > m_Zero) {
alamin = this.m_TOLX / test;
} else {
if (this.m_Debug) {
System.err.println("Zero directions for all free variables -- " + "Min. found with current fixed variables" + " (or all variables fixed). Try to release" + " some variables now.");
}
return x;
}
// Check whether any non-working-set bounds are "binding"
for (i = 0; i < len; i++) {
if (!isFixed[i]) {// No need for fixed variables
double alpi;
if ((direct[i] < -m_Epsilon) && !Double.isNaN(nwsBounds[0][i])) {// Not
// feasible
alpi = (nwsBounds[0][i] - xold[i]) / direct[i];
if (alpi <= m_Zero) { // Zero
if (this.m_Debug) {
System.err.println("Fix variable " + i + " to lower bound " + nwsBounds[0][i] + " from value " + xold[i]);
}
x[i] = nwsBounds[0][i];
isFixed[i] = true; // Fix this variable
alpha = 0.0;
nwsBounds[0][i] = Double.NaN; // Add cons. to working set
wsBdsIndx.addElement(i);
} else if (alpha > alpi) { // Fix one variable in one iteration
alpha = alpi;
fixedOne = i;
}
} else if ((direct[i] > m_Epsilon) && !Double.isNaN(nwsBounds[1][i])) {// Not
// feasible
alpi = (nwsBounds[1][i] - xold[i]) / direct[i];
if (alpi <= m_Zero) { // Zero
if (this.m_Debug) {
System.err.println("Fix variable " + i + " to upper bound " + nwsBounds[1][i] + " from value " + xold[i]);
}
x[i] = nwsBounds[1][i];
isFixed[i] = true; // Fix this variable
alpha = 0.0;
nwsBounds[1][i] = Double.NaN; // Add cons. to working set
wsBdsIndx.addElement(i);
} else if (alpha > alpi) {
alpha = alpi;
fixedOne = i;
}
}
}
}
if (this.m_Debug) {
System.err.println("alamin: " + Utils.doubleToString(alamin, 10, 7));
System.err.println("alpha: " + Utils.doubleToString(alpha, 10, 7));
}
if (alpha <= m_Zero) { // Zero
this.m_IsZeroStep = true;
if (this.m_Debug) {
System.err.println("Alpha too small, try again");
}
return x;
}
alam = alpha; // Always try full feasible newton step
if (alam > 1.0) {
alam = 1.0;
}
// Iteration of one newton step, if necessary, backtracking is done
double initF = fold, // Initial function value
hi = alam, lo = alam, newSlope = 0, fhi = this.m_f, flo = this.m_f;// Variables used
// for beta
// condition
double[] newGrad; // Gradient on the new variable values
kloop: for (k = 0;; k++) {
if (this.m_Debug) {
System.err.println("\nLine search iteration: " + k);
}
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
for (i = 0; i < len; i++) {
if (!isFixed[i]) {
x[i] = xold[i] + alam * direct[i]; // Compute xnew
if (!Double.isNaN(nwsBounds[0][i]) && (x[i] < nwsBounds[0][i])) {
x[i] = nwsBounds[0][i]; // Rounding error
} else if (!Double.isNaN(nwsBounds[1][i]) && (x[i] > nwsBounds[1][i])) {
x[i] = nwsBounds[1][i]; // Rounding error
}
}
}
this.m_f = this.objectiveFunction(x); // Compute fnew
if (Double.isNaN(this.m_f)) {
throw new Exception("Objective function value is NaN!");
}
while (Double.isInfinite(this.m_f)) { // Avoid infinity
if (this.m_Debug) {
System.err.println("Too large m_f. Shrink step by half.");
}
alam *= 0.5; // Shrink by half
if (alam <= m_Epsilon) {
if (this.m_Debug) {
System.err.println("Wrong starting points, change them!");
}
return x;
}
for (i = 0; i < len; i++) {
if (!isFixed[i]) {
x[i] = xold[i] + alam * direct[i];
}
}
this.m_f = this.objectiveFunction(x);
if (Double.isNaN(this.m_f)) {
throw new Exception("Objective function value is NaN!");
}
initF = Double.POSITIVE_INFINITY;
}
if (this.m_Debug) {
System.err.println("obj. function: " + Utils.doubleToString(this.m_f, 10, 7));
System.err.println("threshold: " + Utils.doubleToString(fold + this.m_ALF * alam * this.m_Slope, 10, 7));
}
if (this.m_f <= fold + this.m_ALF * alam * this.m_Slope) {// Alpha condition: sufficient
// function decrease
if (this.m_Debug) {
System.err.println("Sufficient function decrease (alpha condition): ");
}
newGrad = this.evaluateGradient(x);
for (newSlope = 0.0, i = 0; i < len; i++) {
if (!isFixed[i]) {
newSlope += newGrad[i] * direct[i];
}
}
if (this.m_Debug) {
System.err.println("newSlope: " + newSlope);
}
if (newSlope >= this.m_BETA * this.m_Slope) { // Beta condition: ensure pos.
// defnty.
if (this.m_Debug) {
System.err.println("Increasing derivatives (beta condition): ");
}
if ((fixedOne != -1) && (alam >= alpha)) { // Has bounds and over
if (direct[fixedOne] > 0) {
x[fixedOne] = nwsBounds[1][fixedOne]; // Avoid rounding error
nwsBounds[1][fixedOne] = Double.NaN; // Add cons. to working set
} else {
x[fixedOne] = nwsBounds[0][fixedOne]; // Avoid rounding error
nwsBounds[0][fixedOne] = Double.NaN; // Add cons. to working set
}
if (this.m_Debug) {
System.err.println("Fix variable " + fixedOne + " to bound " + x[fixedOne] + " from value " + xold[fixedOne]);
}
isFixed[fixedOne] = true; // Fix the variable
wsBdsIndx.addElement(fixedOne);
}
return x;
} else if (k == 0) { // First time: increase alam
// Search for the smallest value not complying with alpha condition
double upper = Math.min(alpha, maxalam);
if (this.m_Debug) {
System.err.println("Alpha condition holds, increase alpha... ");
}
while (!((alam >= upper) || (this.m_f > fold + this.m_ALF * alam * this.m_Slope))) {
lo = alam;
flo = this.m_f;
alam *= 2.0;
if (alam >= upper) {
alam = upper;
}
for (i = 0; i < len; i++) {
if (!isFixed[i]) {
x[i] = xold[i] + alam * direct[i];
}
}
this.m_f = this.objectiveFunction(x);
if (Double.isNaN(this.m_f)) {
throw new Exception("Objective function value is NaN!");
}
newGrad = this.evaluateGradient(x);
for (newSlope = 0.0, i = 0; i < len; i++) {
if (!isFixed[i]) {
newSlope += newGrad[i] * direct[i];
}
}
if (newSlope >= this.m_BETA * this.m_Slope) {
if (this.m_Debug) {
System.err.println("Increasing derivatives (beta condition): \n" + "newSlope = " + Utils.doubleToString(newSlope, 10, 7));
}
if ((fixedOne != -1) && (alam >= alpha)) { // Has bounds and over
if (direct[fixedOne] > 0) {
x[fixedOne] = nwsBounds[1][fixedOne]; // Avoid rounding error
nwsBounds[1][fixedOne] = Double.NaN; // Add cons. to working
// set
} else {
x[fixedOne] = nwsBounds[0][fixedOne]; // Avoid rounding error
nwsBounds[0][fixedOne] = Double.NaN; // Add cons. to working
// set
}
if (this.m_Debug) {
System.err.println("Fix variable " + fixedOne + " to bound " + x[fixedOne] + " from value " + xold[fixedOne]);
}
isFixed[fixedOne] = true; // Fix the variable
wsBdsIndx.addElement(fixedOne);
}
return x;
}
}
hi = alam;
fhi = this.m_f;
break kloop;
} else {
if (this.m_Debug) {
System.err.println("Alpha condition holds.");
}
hi = alam2;
lo = alam;
flo = this.m_f;
break kloop;
}
} else if (alam < alamin) { // No feasible lambda found
if (initF < fold) {
alam = Math.min(1.0, alpha);
for (i = 0; i < len; i++) {
if (!isFixed[i]) {
x[i] = xold[i] + alam * direct[i]; // Still take Alpha
}
}
if (this.m_Debug) {
System.err.println("No feasible lambda: still take" + " alpha=" + alam);
}
if ((fixedOne != -1) && (alam >= alpha)) { // Has bounds and over
if (direct[fixedOne] > 0) {
x[fixedOne] = nwsBounds[1][fixedOne]; // Avoid rounding error
nwsBounds[1][fixedOne] = Double.NaN; // Add cons. to working set
} else {
x[fixedOne] = nwsBounds[0][fixedOne]; // Avoid rounding error
nwsBounds[0][fixedOne] = Double.NaN; // Add cons. to working set
}
if (this.m_Debug) {
System.err.println("Fix variable " + fixedOne + " to bound " + x[fixedOne] + " from value " + xold[fixedOne]);
}
isFixed[fixedOne] = true; // Fix the variable
wsBdsIndx.addElement(fixedOne);
}
} else { // Convergence on delta(x)
for (i = 0; i < len; i++) {
x[i] = xold[i];
}
this.m_f = fold;
if (this.m_Debug) {
System.err.println("Cannot find feasible lambda");
}
}
return x;
} else { // Backtracking by polynomial interpolation
if (k == 0) { // First time backtrack: quadratic interpolation
if (!Double.isInfinite(initF)) {
initF = this.m_f;
}
// lambda = -g'(0)/(2*g''(0))
tmplam = -0.5 * alam * this.m_Slope / ((this.m_f - fold) / alam - this.m_Slope);
} else { // Subsequent backtrack: cubic interpolation
rhs1 = this.m_f - fold - alam * this.m_Slope;
rhs2 = fhi - fold - alam2 * this.m_Slope;
a = (rhs1 / (alam * alam) - rhs2 / (alam2 * alam2)) / (alam - alam2);
b = (-alam2 * rhs1 / (alam * alam) + alam * rhs2 / (alam2 * alam2)) / (alam - alam2);
if (a == 0.0) {
tmplam = -this.m_Slope / (2.0 * b);
} else {
disc = b * b - 3.0 * a * this.m_Slope;
if (disc < 0.0) {
disc = 0.0;
}
double numerator = -b + Math.sqrt(disc);
if (numerator >= Double.MAX_VALUE) {
numerator = Double.MAX_VALUE;
if (this.m_Debug) {
System.err.print("-b+sqrt(disc) too large! Set it to MAX_VALUE.");
}
}
tmplam = numerator / (3.0 * a);
}
if (this.m_Debug) {
System.err.print("Cubic interpolation: \n" + "a: " + Utils.doubleToString(a, 10, 7) + "\n" + "b: " + Utils.doubleToString(b, 10, 7) + "\n" + "disc: " + Utils.doubleToString(disc, 10, 7) + "\n" + "tmplam: "
+ tmplam + "\n" + "alam: " + Utils.doubleToString(alam, 10, 7) + "\n");
}
if (tmplam > 0.5 * alam) {
tmplam = 0.5 * alam; // lambda <= 0.5*lambda_old
}
}
}
alam2 = alam;
fhi = this.m_f;
alam = Math.max(tmplam, 0.1 * alam); // lambda >= 0.1*lambda_old
if (alam > alpha) {
throw new Exception("Sth. wrong in lnsrch:" + "Lambda infeasible!(lambda=" + alam + ", alpha=" + alpha + ", upper=" + tmplam + "|" + (-alpha * this.m_Slope / (2.0 * ((this.m_f - fold) / alpha - this.m_Slope))) + ", m_f="
+ this.m_f + ", fold=" + fold + ", slope=" + this.m_Slope);
}
} // Endfor(k=0;;k++)
// Quadratic interpolation between lamda values between lo and hi.
// If cannot find a value satisfying beta condition, use lo.
double ldiff = hi - lo, lincr;
if (this.m_Debug) {
System.err.println("Last stage of searching for beta condition (alam between " + Utils.doubleToString(lo, 10, 7) + " and " + Utils.doubleToString(hi, 10, 7) + ")...\n" + "Quadratic Interpolation(QI):\n" + "Last newSlope = "
+ Utils.doubleToString(newSlope, 10, 7));
}
while ((newSlope < this.m_BETA * this.m_Slope) && (ldiff >= alamin)) {
lincr = -0.5 * newSlope * ldiff * ldiff / (fhi - flo - newSlope * ldiff);
if (this.m_Debug) {
System.err.println("fhi = " + fhi + "\n" + "flo = " + flo + "\n" + "ldiff = " + ldiff + "\n" + "lincr (using QI) = " + lincr + "\n");
}
if (lincr < 0.2 * ldiff) {
lincr = 0.2 * ldiff;
}
alam = lo + lincr;
if (alam >= hi) { // We cannot go beyond the bounds, so the best we can
// try is hi
alam = hi;
lincr = ldiff;
}
for (i = 0; i < len; i++) {
if (!isFixed[i]) {
x[i] = xold[i] + alam * direct[i];
}
}
this.m_f = this.objectiveFunction(x);
if (Double.isNaN(this.m_f)) {
throw new Exception("Objective function value is NaN!");
}
if (this.m_f > fold + this.m_ALF * alam * this.m_Slope) {
// Alpha condition fails, shrink lambda_upper
ldiff = lincr;
fhi = this.m_f;
} else { // Alpha condition holds
newGrad = this.evaluateGradient(x);
for (newSlope = 0.0, i = 0; i < len; i++) {
if (!isFixed[i]) {
newSlope += newGrad[i] * direct[i];
}
}
if (newSlope < this.m_BETA * this.m_Slope) {
// Beta condition fails, shrink lambda_lower
lo = alam;
ldiff -= lincr;
flo = this.m_f;
}
}
}
if (newSlope < this.m_BETA * this.m_Slope) { // Cannot satisfy beta condition, take lo
if (this.m_Debug) {
System.err.println("Beta condition cannot be satisfied, take alpha condition");
}
alam = lo;
for (i = 0; i < len; i++) {
if (!isFixed[i]) {
x[i] = xold[i] + alam * direct[i];
}
}
this.m_f = flo;
} else if (this.m_Debug) {
System.err.println("Both alpha and beta conditions are satisfied. alam=" + Utils.doubleToString(alam, 10, 7));
}
if ((fixedOne != -1) && (alam >= alpha)) { // Has bounds and over
if (direct[fixedOne] > 0) {
x[fixedOne] = nwsBounds[1][fixedOne]; // Avoid rounding error
nwsBounds[1][fixedOne] = Double.NaN; // Add cons. to working set
} else {
x[fixedOne] = nwsBounds[0][fixedOne]; // Avoid rounding error
nwsBounds[0][fixedOne] = Double.NaN; // Add cons. to working set
}
if (this.m_Debug) {
System.err.println("Fix variable " + fixedOne + " to bound " + x[fixedOne] + " from value " + xold[fixedOne]);
}
isFixed[fixedOne] = true; // Fix the variable
wsBdsIndx.addElement(fixedOne);
}
return x;
}
/**
* Main algorithm. Descriptions see "Practical Optimization"
*
* @param initX
* initial point of x, assuming no value's on the bound!
* @param constraints
* the bound constraints of each variable constraints[0] is the lower bounds and constraints[1] is the upper bounds
* @return the solution of x, null if number of iterations not enough
* @throws Exception
* if an error occurs
*/
public double[] findArgmin(final double[] initX, final double[][] constraints) throws Exception {
int l = initX.length;
// Initially all variables are free, all bounds are constraints of
// non-working-set constraints
boolean[] isFixed = new boolean[l];
double[][] nwsBounds = new double[2][l];
// Record indice of fixed variables, simply for efficiency
DynamicIntArray wsBdsIndx = new DynamicIntArray(constraints.length);
// Vectors used to record the variable indices to be freed
DynamicIntArray toFree = null, oldToFree = null;
// Initial value of obj. function, gradient and inverse of the Hessian
this.m_f = this.objectiveFunction(initX);
if (Double.isNaN(this.m_f)) {
throw new Exception("Objective function value is NaN!");
}
double sum = 0;
double[] grad = this.evaluateGradient(initX), oldGrad, oldX, deltaGrad = new double[l], deltaX = new double[l], direct = new double[l], x = new double[l];
Matrix L = new Matrix(l, l); // Lower triangle of Cholesky factor
double[] D = new double[l]; // Diagonal of Cholesky factor
for (int i = 0; i < l; i++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
// L.setRow(i, new double[l]); Not necessary
L.set(i, i, 1.0);
D[i] = 1.0;
direct[i] = -grad[i];
sum += grad[i] * grad[i];
x[i] = initX[i];
nwsBounds[0][i] = constraints[0][i];
nwsBounds[1][i] = constraints[1][i];
isFixed[i] = false;
}
double stpmax = this.m_STPMX * Math.max(Math.sqrt(sum), l);
for (int step = 0; step < this.m_MAXITS; step++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
if (this.m_Debug) {
System.err.println("\nIteration # " + step + ":");
}
// Try at most one feasible newton step, i.e. 0<lamda<=alpha
oldX = x;
oldGrad = grad;
// Also update grad
if (this.m_Debug) {
System.err.println("Line search ... ");
}
this.m_IsZeroStep = false;
x = this.lnsrch(x, grad, direct, stpmax, isFixed, nwsBounds, wsBdsIndx);
if (this.m_Debug) {
System.err.println("Line search finished.");
}
if (this.m_IsZeroStep) { // Zero step, simply delete rows/cols of D and L
for (int f = 0; f < wsBdsIndx.size(); f++) {
int[] idx = new int[1];
// int idx=wsBdsIndx.elementAt(f);
idx[0] = wsBdsIndx.elementAt(f);
L.setMatrix(idx, 0, l - 1, new Matrix(1, l));
// L.setRow(idx, new double[l]);
L.setMatrix(0, l - 1, idx, new Matrix(l, 1));
// L.setColumn(idx, new double[l]);
D[idx[0]] = 0.0;
// D[idx] = 0.0;
}
grad = this.evaluateGradient(x);
step--;
} else {
// Check converge on x
boolean finish = false;
double test = 0.0;
for (int h = 0; h < l; h++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
deltaX[h] = x[h] - oldX[h];
double tmp = Math.abs(deltaX[h]) / Math.max(Math.abs(x[h]), 1.0);
if (tmp > test) {
test = tmp;
}
}
if (test < m_Zero) {
if (this.m_Debug) {
System.err.println("\nDeltaX converge: " + test);
}
finish = true;
}
// Check zero gradient
grad = this.evaluateGradient(x);
test = 0.0;
double denom = 0.0, dxSq = 0.0, dgSq = 0.0, newlyBounded = 0.0;
for (int g = 0; g < l; g++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
if (!isFixed[g]) {
deltaGrad[g] = grad[g] - oldGrad[g];
// Calculate the denominators
denom += deltaX[g] * deltaGrad[g];
dxSq += deltaX[g] * deltaX[g];
dgSq += deltaGrad[g] * deltaGrad[g];
} else {
newlyBounded += deltaX[g] * (grad[g] - oldGrad[g]);
}
// Note: CANNOT use projected gradient for testing
// convergence because of newly bounded variables
double tmp = Math.abs(grad[g]) * Math.max(Math.abs(direct[g]), 1.0) / Math.max(Math.abs(this.m_f), 1.0);
if (tmp > test) {
test = tmp;
}
}
if (test < m_Zero) {
if (this.m_Debug) {
System.err.println("Gradient converge: " + test);
}
finish = true;
}
// dg'*dx could be < 0 using inexact lnsrch
if (this.m_Debug) {
System.err.println("dg'*dx=" + (denom + newlyBounded));
}
// dg'*dx = 0
if (Math.abs(denom + newlyBounded) < m_Zero) {
finish = true;
}
int size = wsBdsIndx.size();
boolean isUpdate = true; // Whether to update BFGS formula
// Converge: check whether release any current constraints
if (finish) {
if (this.m_Debug) {
System.err.println("Test any release possible ...");
}
if (toFree != null) {
oldToFree = (DynamicIntArray) toFree.copy();
}
toFree = new DynamicIntArray(wsBdsIndx.size());
for (int m = size - 1; m >= 0; m--) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
int index = wsBdsIndx.elementAt(m);
double[] hessian = this.evaluateHessian(x, index);
double deltaL = 0.0;
if (hessian != null) {
for (int mm = 0; mm < hessian.length; mm++) {
if (!isFixed[mm]) {
deltaL += hessian[mm] * direct[mm];
}
}
}
// First and second order Lagrangian multiplier estimate
// If user didn't provide Hessian, use first-order only
double L1, L2;
if (x[index] >= constraints[1][index]) {
L1 = -grad[index];
} else if (x[index] <= constraints[0][index]) {
L1 = grad[index];
} else {
throw new Exception("x[" + index + "] not fixed on the" + " bounds where it should have been!");
}
// L2 = L1 + deltaL
L2 = L1 + deltaL;
if (this.m_Debug) {
System.err.println("Variable " + index + ": Lagrangian=" + L1 + "|" + L2);
}
// Check validity of Lagrangian multiplier estimate
boolean isConverge = (2.0 * Math.abs(deltaL)) < Math.min(Math.abs(L1), Math.abs(L2));
if ((L1 * L2 > 0.0) && isConverge) { // Same sign and converge:
// valid
if (L2 < 0.0) {// Negative Lagrangian: feasible
toFree.addElement(index);
wsBdsIndx.removeElementAt(m);
finish = false; // Not optimal, cannot finish
}
}
// Although hardly happen, better check it
// If the first-order Lagrangian multiplier estimate is wrong,
// avoid zigzagging
if ((hessian == null) && (toFree != null) && toFree.equal(oldToFree)) {
finish = true;
}
}
if (finish) {// Min. found
if (this.m_Debug) {
System.err.println("Minimum found.");
}
this.m_f = this.objectiveFunction(x);
if (Double.isNaN(this.m_f)) {
throw new Exception("Objective function value is NaN!");
}
return x;
}
// Free some variables
for (int mmm = 0; mmm < toFree.size(); mmm++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
int freeIndx = toFree.elementAt(mmm);
isFixed[freeIndx] = false; // Free this variable
if (x[freeIndx] <= constraints[0][freeIndx]) {// Lower bound
nwsBounds[0][freeIndx] = constraints[0][freeIndx];
if (this.m_Debug) {
System.err.println("Free variable " + freeIndx + " from bound " + nwsBounds[0][freeIndx]);
}
} else { // Upper bound
nwsBounds[1][freeIndx] = constraints[1][freeIndx];
if (this.m_Debug) {
System.err.println("Free variable " + freeIndx + " from bound " + nwsBounds[1][freeIndx]);
}
}
L.set(freeIndx, freeIndx, 1.0);
D[freeIndx] = 1.0;
isUpdate = false;
}
}
if (denom < Math.max(m_Zero * Math.sqrt(dxSq) * Math.sqrt(dgSq), m_Zero)) {
if (this.m_Debug) {
System.err.println("dg'*dx negative!");
}
isUpdate = false; // Do not update
}
// If Hessian will be positive definite, update it
if (isUpdate) {
// modify once: dg*dg'/(dg'*dx)
double coeff = 1.0 / denom; // 1/(dg'*dx)
this.updateCholeskyFactor(L, D, deltaGrad, coeff, isFixed);
// modify twice: g*g'/(g'*p)
coeff = 1.0 / this.m_Slope; // 1/(g'*p)
this.updateCholeskyFactor(L, D, oldGrad, coeff, isFixed);
}
}
// Find new direction
Matrix LD = new Matrix(l, l); // L*D
double[] b = new double[l];
for (int k = 0; k < l; k++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
if (!isFixed[k]) {
b[k] = -grad[k];
} else {
b[k] = 0.0;
}
for (int j = k; j < l; j++) { // Lower triangle
if (!isFixed[j] && !isFixed[k]) {
LD.set(j, k, L.get(j, k) * D[k]);
}
}
}
// Solve (LD)*y = -g, where y=L'*direct
double[] LDIR = solveTriangle(LD, b, true, isFixed);
LD = null;
for (int m = 0; m < LDIR.length; m++) {
// XXX kill weka execution
if (Thread.interrupted()) {
throw new InterruptedException("Thread got interrupted, thus, kill WEKA.");
}
if (Double.isNaN(LDIR[m])) {
throw new Exception("L*direct[" + m + "] is NaN!" + "|-g=" + b[m] + "|" + isFixed[m] + "|diag=" + D[m]);
}
}
// Solve L'*direct = y
direct = solveTriangle(L, LDIR, false, isFixed);
for (double element : direct) {
if (Double.isNaN(element)) {
throw new Exception("direct is NaN!");
}
}
// System.gc();
}
if (this.m_Debug) {
System.err.println("Cannot find minimum" + " -- too many interations!");
}
this.m_X = x;
return null;
}
/**
* Solve the linear equation of TX=B where T is a triangle matrix It can be solved using back/forward substitution, with O(N^2) complexity
*
* @param t
* the matrix T
* @param b
* the vector B
* @param isLower
* whether T is a lower or higher triangle matrix
* @param isZero
* which row(s) of T are not used when solving the equation. If it's null or all 'false', then every row is used.
* @return the solution of X
*/
public static double[] solveTriangle(final Matrix t, final double[] b, final boolean isLower, boolean[] isZero) {
int n = b.length;
double[] result = new double[n];
if (isZero == null) {
isZero = new boolean[n];
}
if (isLower) { // lower triangle, forward-substitution
int j = 0;
while ((j < n) && isZero[j]) {
result[j] = 0.0;
j++;
} // go to the first row
if (j < n) {
result[j] = b[j] / t.get(j, j);
for (; j < n; j++) {
if (!isZero[j]) {
double numerator = b[j];
for (int k = 0; k < j; k++) {
numerator -= t.get(j, k) * result[k];
}
result[j] = numerator / t.get(j, j);
} else {
result[j] = 0.0;
}
}
}
} else { // Upper triangle, back-substitution
int j = n - 1;
while ((j >= 0) && isZero[j]) {
result[j] = 0.0;
j--;
} // go to the last row
if (j >= 0) {
result[j] = b[j] / t.get(j, j);
for (; j >= 0; j--) {
if (!isZero[j]) {
double numerator = b[j];
for (int k = j + 1; k < n; k++) {
numerator -= t.get(k, j) * result[k];
}
result[j] = numerator / t.get(j, j);
} else {
result[j] = 0.0;
}
}
}
}
return result;
}
/**
* One rank update of the Cholesky factorization of B matrix in BFGS updates, i.e. B = LDL', and B_{new} = LDL' + coeff*(vv') where L is a unit lower triangle matrix and D is a diagonal matrix, and v is a vector.<br/>
* When coeff > 0, we use C1 algorithm, and otherwise we use C2 algorithm described in ``Methods for Modifying Matrix Factorizations''
*
* @param L
* the unit triangle matrix L
* @param D
* the diagonal matrix D
* @param v
* the update vector v
* @param coeff
* the coeffcient of update
* @param isFixed
* which variables are not to be updated
*/
protected void updateCholeskyFactor(final Matrix L, final double[] D, final double[] v, final double coeff, final boolean[] isFixed) throws Exception {
double t, p, b;
int n = v.length;
double[] vp = new double[n];
for (int i = 0; i < v.length; i++) {
if (!isFixed[i]) {
vp[i] = v[i];
} else {
vp[i] = 0.0;
}
}
if (coeff > 0.0) {
t = coeff;
for (int j = 0; j < n; j++) {
if (isFixed[j]) {
continue;
}
p = vp[j];
double d = D[j], dbarj = d + t * p * p;
D[j] = dbarj;
b = p * t / dbarj;
t *= d / dbarj;
for (int r = j + 1; r < n; r++) {
if (!isFixed[r]) {
double l = L.get(r, j);
vp[r] -= p * l;
L.set(r, j, l + b * vp[r]);
} else {
L.set(r, j, 0.0);
}
}
}
} else {
double[] P = solveTriangle(L, v, true, isFixed);
t = 0.0;
for (int i = 0; i < n; i++) {
if (!isFixed[i]) {
t += P[i] * P[i] / D[i];
}
}
double sqrt = 1.0 + coeff * t;
sqrt = (sqrt < 0.0) ? 0.0 : Math.sqrt(sqrt);
double alpha = coeff, sigma = coeff / (1.0 + sqrt), rho, theta;
for (int j = 0; j < n; j++) {
if (isFixed[j]) {
continue;
}
double d = D[j];
p = P[j] * P[j] / d;
theta = 1.0 + sigma * p;
t -= p;
if (t < 0.0) {
t = 0.0; // Rounding error
}
double plus = sigma * sigma * p * t;
if ((j < n - 1) && (plus <= m_Zero)) {
plus = m_Zero; // Avoid rounding error
}
rho = theta * theta + plus;
D[j] = rho * d;
if (Double.isNaN(D[j])) {
throw new Exception("d[" + j + "] NaN! P=" + P[j] + ",d=" + d + ",t=" + t + ",p=" + p + ",sigma=" + sigma + ",sclar=" + coeff);
}
b = alpha * P[j] / (rho * d);
alpha /= rho;
rho = Math.sqrt(rho);
double sigmaOld = sigma;
sigma *= (1.0 + rho) / (rho * (theta + rho));
if ((j < n - 1) && (Double.isNaN(sigma) || Double.isInfinite(sigma))) {
throw new Exception("sigma NaN/Inf! rho=" + rho + ",theta=" + theta + ",P[" + j + "]=" + P[j] + ",p=" + p + ",d=" + d + ",t=" + t + ",oldsigma=" + sigmaOld);
}
for (int r = j + 1; r < n; r++) {
if (!isFixed[r]) {
double l = L.get(r, j);
vp[r] -= P[j] * l;
L.set(r, j, l + b * vp[r]);
} else {
L.set(r, j, 0.0);
}
}
}
}
}
/**
* Implements a simple dynamic array for ints.
*/
protected class DynamicIntArray implements RevisionHandler {
/** The int array. */
private int[] m_Objects;
/** The current size; */
private int m_Size = 0;
/** The capacity increment */
private int m_CapacityIncrement = 1;
/** The capacity multiplier. */
private int m_CapacityMultiplier = 2;
/**
* Constructs a vector with the given capacity.
*
* @param capacity
* the vector's initial capacity
*/
public DynamicIntArray(final int capacity) {
this.m_Objects = new int[capacity];
}
/**
* Adds an element to this vector. Increases its capacity if its not large enough.
*
* @param element
* the element to add
*/
public final void addElement(final int element) {
if (this.m_Size == this.m_Objects.length) {
int[] newObjects;
newObjects = new int[this.m_CapacityMultiplier * (this.m_Objects.length + this.m_CapacityIncrement)];
System.arraycopy(this.m_Objects, 0, newObjects, 0, this.m_Size);
this.m_Objects = newObjects;
}
this.m_Objects[this.m_Size] = element;
this.m_Size++;
}
/**
* Produces a copy of this vector.
*
* @return the new vector
*/
public final Object copy() {
DynamicIntArray copy = new DynamicIntArray(this.m_Objects.length);
copy.m_Size = this.m_Size;
copy.m_CapacityIncrement = this.m_CapacityIncrement;
copy.m_CapacityMultiplier = this.m_CapacityMultiplier;
System.arraycopy(this.m_Objects, 0, copy.m_Objects, 0, this.m_Size);
return copy;
}
/**
* Returns the element at the given position.
*
* @param index
* the element's index
* @return the element with the given index
*/
public final int elementAt(final int index) {
return this.m_Objects[index];
}
/**
* Check whether the two integer vectors equal to each other Two integer vectors are equal if all the elements are the same, regardless of the order of the elements
*
* @param b
* another integer vector
* @return whether they are equal
*/
private boolean equal(final DynamicIntArray b) {
if ((b == null) || (this.size() != b.size())) {
return false;
}
int size = this.size();
// Only values matter, order does not matter
int[] sorta = Utils.sort(this.m_Objects), sortb = Utils.sort(b.m_Objects);
for (int j = 0; j < size; j++) {
if (this.m_Objects[sorta[j]] != b.m_Objects[sortb[j]]) {
return false;
}
}
return true;
}
/**
* Deletes an element from this vector.
*
* @param index
* the index of the element to be deleted
*/
public final void removeElementAt(final int index) {
System.arraycopy(this.m_Objects, index + 1, this.m_Objects, index, this.m_Size - index - 1);
this.m_Size--;
}
/**
* Removes all components from this vector and sets its size to zero.
*/
public final void removeAllElements() {
this.m_Objects = new int[this.m_Objects.length];
this.m_Size = 0;
}
/**
* Returns the vector's current size.
*
* @return the vector's current size
*/
public final int size() {
return this.m_Size;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Option.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Option.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.File;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
/**
* Class to store information about an option.
* <p>
*
* Typical usage:
* <p>
*
* <code>Option myOption = new Option("Uses extended mode.", "E", 0, "-E")); </code>
* <p>
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Option implements RevisionHandler {
/** A cache of property descriptors */
private static final Map<Class<?>, PropertyDescriptor[]> s_descriptorCache =
new HashMap<Class<?>, PropertyDescriptor[]>();
/** What does this option do? */
private String m_Description;
/** The synopsis. */
private String m_Synopsis;
/** What's the option's name? */
private String m_Name;
/** How many arguments does it take? */
private int m_NumArguments;
/**
* Creates new option with the given parameters.
*
* @param description the option's description
* @param name the option's name
* @param numArguments the number of arguments
* @param synopsis the option's synopsis
*/
public Option(String description, String name, int numArguments,
String synopsis) {
m_Description = description;
m_Name = name;
m_NumArguments = numArguments;
m_Synopsis = synopsis;
}
/**
* Get a list of options for a class. Options identified by this method are
* bean properties (with get/set methods) annotated using the OptionMetadata
* annotation. All options from the class up to, but not including, the
* supplied oldest superclass are returned.
*
*
* @param childClazz the class to get options for
* @param oldestAncestorClazz the oldest superclass (inclusive) at which to
* stop getting options from
* @return a list of options
*/
public static Vector<Option> listOptionsForClassHierarchy(
Class<?> childClazz, Class<?> oldestAncestorClazz) {
Vector<Option> results = listOptionsForClass(childClazz);
Class<?> parent = childClazz;
do {
parent = parent.getSuperclass();
if (parent == null) {
break;
}
results.addAll(listOptionsForClass(parent));
} while (!parent.equals(oldestAncestorClazz));
return results;
}
/**
* Adds all methods from the supplied class to the supplied list of methods.
*
* @param clazz the class to get methods from
* @param methList the list to add them to
*/
protected static void addMethodsToList(Class<?> clazz, List<Method> methList) {
Method[] methods = clazz.getDeclaredMethods();
for (Method m : methods) {
methList.add(m);
}
}
/**
* Gets a list of options for the supplied class. Only examines immediate
* methods in the class (does not consider superclasses). Options identified
* by this method are bean properties (with get/set methods) annotated using
* the OptionMetadata annotation.
*
* @param clazz the class to examine for options
* @return a list of options
*/
public static Vector<Option> listOptionsForClass(Class<?> clazz) {
Vector<Option> results = new Vector<Option>();
List<Method> allMethods = new ArrayList<Method>();
addMethodsToList(clazz, allMethods);
Class<?>[] interfaces = clazz.getInterfaces();
for (Class c : interfaces) {
addMethodsToList(c, allMethods);
}
Option[] unsorted = new Option[allMethods.size()];
int[] opOrder = new int[allMethods.size()];
for (int i = 0; i < opOrder.length; i++) {
opOrder[i] = Integer.MAX_VALUE;
}
int index = 0;
for (Method m : allMethods) {
OptionMetadata o = m.getAnnotation(OptionMetadata.class);
if (o != null) {
if (o.commandLineParamName().length() > 0) {
opOrder[index] = o.displayOrder();
String description = o.description();
if (!description.startsWith("\t")) {
description = "\t" + description;
}
description = description.replace("\n", "\n\t");
String name = o.commandLineParamName();
if (name.startsWith("-")) {
name = name.substring(1, name.length());
}
String synopsis = o.commandLineParamSynopsis();
if (!synopsis.startsWith("-")) {
synopsis = "-" + synopsis;
}
int numParams = o.commandLineParamIsFlag() ? 0 : 1;
Option option = new Option(description, name, numParams, synopsis);
unsorted[index] = option;
index++;
}
}
}
int[] sortedOpts = Utils.sort(opOrder);
for (int i = 0; i < opOrder.length; i++) {
if (opOrder[i] < Integer.MAX_VALUE) {
results.add(unsorted[sortedOpts[i]]);
}
}
return results;
}
/**
* Get the settings of the supplied object. Settings identified by this method
* are bean properties (with get/set methods) annotated using the
* OptionMetadata annotation. All options from the class up to, but not
* including, the supplied oldest superclass are returned.
*
* @param target the target object to get settings for
* @param oldestAncestorClazz the oldest superclass at which to stop getting
* options from
* @return
*/
public static String[] getOptionsForHierarchy(Object target,
Class<?> oldestAncestorClazz) {
ArrayList<String> options = new ArrayList<String>();
for (String s : getOptions(target, target.getClass())) {
options.add(s);
}
Class<?> parent = target.getClass();
do {
parent = parent.getSuperclass();
if (parent == null) {
break;
}
for (String s : getOptions(target, parent)) {
options.add(s);
}
} while (!parent.equals(oldestAncestorClazz));
return options.toArray(new String[options.size()]);
}
/**
* Get the settings of the supplied object. Settings identified by this method
* are bean properties (with get/set methods) annotated using the
* OptionMetadata annotation. Options belonging to the targetClazz (either the
* class of the target or one of its superclasses) are returned.
*
* @param target the target to extract settings from
* @param targetClazz the class to consider for obtaining settings - i.e.
* annotated methods from this class will have their values
* extracted. This class is expected to be either the class of the
* target or one of its superclasses
* @return an array of settings
*/
public static String[] getOptions(Object target, Class<?> targetClazz) {
ArrayList<String> options = new ArrayList<String>();
try {
Object[] args = {};
Class<?> parent = targetClazz.getSuperclass();
PropertyDescriptor[] properties =
getPropertyDescriptors(targetClazz, parent);
for (PropertyDescriptor p : properties) {
Method getter = p.getReadMethod();
Method setter = p.getWriteMethod();
if (getter == null || setter == null) {
continue;
}
OptionMetadata parameterDescription = null;
parameterDescription = getter.getAnnotation(OptionMetadata.class);
if (parameterDescription == null) {
parameterDescription = setter.getAnnotation(OptionMetadata.class);
}
if (parameterDescription != null
&& parameterDescription.commandLineParamName().length() > 0) {
Object value = getter.invoke(target, args);
if (value != null) {
if (!parameterDescription.commandLineParamIsFlag()) {
options.add("-" + parameterDescription.commandLineParamName());
}
if (value.getClass().isArray()) {
if (parameterDescription.commandLineParamIsFlag()) {
throw new IllegalArgumentException(
"Getter method for a command "
+ "line flag should return a boolean value");
}
if (((Object[]) value).length == 0) {
// remove the initial option identifier (added above)
// as the array is empty
options.remove(options.size() - 1);
}
int index = 0;
for (Object element : (Object[]) value) {
if (index > 0) {
options
.add("-" + parameterDescription.commandLineParamName());
}
if (element instanceof OptionHandler) {
options
.add(getOptionStringForOptionHandler((OptionHandler) element));
} else {
options.add(element.toString());
}
index++;
}
} else if (value instanceof OptionHandler) {
if (parameterDescription.commandLineParamIsFlag()) {
throw new IllegalArgumentException(
"Getter method for a command "
+ "line flag should return a boolean value");
}
options
.add(getOptionStringForOptionHandler((OptionHandler) value));
} else if (value instanceof SelectedTag) {
options.add(""
+ ((SelectedTag) value).getSelectedTag().getReadable());
} else {
// check for boolean/flag
if (parameterDescription.commandLineParamIsFlag()) {
if (!(value instanceof Boolean)) {
throw new IllegalArgumentException(
"Getter method for a command "
+ "line flag should return a boolean value");
}
if (((Boolean) value).booleanValue()) {
options
.add("-" + parameterDescription.commandLineParamName());
}
} else {
if (value.toString().length() > 0) {
options.add(value.toString());
} else {
// don't allow empty strings
options.remove(options.size() - 1);
}
}
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return options.toArray(new String[options.size()]);
}
/**
* Construct a String containing the class name of an OptionHandler and its
* option settings
*
* @param handler the OptionHandler to construct an option string for
* @return a String containing the name of the handler class and its options
*/
protected static String
getOptionStringForOptionHandler(OptionHandler handler) {
String optHandlerClassName = handler.getClass().getCanonicalName();
String optsVal = Utils.joinOptions(handler.getOptions());
String totalOptVal = optHandlerClassName + " " + optsVal;
return totalOptVal;
}
/**
* Sets options on the target object. Settings identified by this method are
* bean properties (with get/set methods) annotated using the OptionMetadata
* annotation. All options from the class up to, but not including, the
* supplied oldest superclass are processed in order.
*
* @param options the options to set
* @param target the target on which to set options
* @param oldestAncestorClazz the oldest superclass at which to stop setting
* options
*/
public static void setOptionsForHierarchy(String[] options, Object target,
Class<?> oldestAncestorClazz) {
setOptions(options, target, target.getClass());
Class<?> parent = target.getClass();
do {
parent = parent.getSuperclass();
if (parent == null) {
break;
}
setOptions(options, target, parent);
} while (!parent.equals(oldestAncestorClazz));
}
/**
* Get property descriptors for a target class. Checks a cache first before
* using introspection.
*
* @param targetClazz the target to get the descriptors for
* @param parent the parent class at which to stop getting descriptors
* @return an array of property descriptors
* @throws IntrospectionException if a problem occurs
*/
private static PropertyDescriptor[] getPropertyDescriptors(
Class<?> targetClazz, Class<?> parent) throws IntrospectionException {
PropertyDescriptor[] result = s_descriptorCache.get(targetClazz);
if (result == null) {
BeanInfo bi = Introspector.getBeanInfo(targetClazz, parent);
result = bi.getPropertyDescriptors();
s_descriptorCache.put(targetClazz, result);
}
return result;
}
/**
* Sets options on the target object. Settings identified by this method are
* bean properties (with get/set methods) annotated using the OptionMetadata
* annotation. Options from just the supplied targetClazz (which is expected
* to be either the class of the target or one of its superclasses) are set.
*
* @param options the options to set
* @param target the target on which to set options
* @param targetClazz the class containing options to be be set - i.e.
* annotated option methods in this class will have their values set.
* This class is expected to be either the class of the target or one
* of its superclasses
*/
public static void setOptions(String[] options, Object target,
Class<?> targetClazz) {
if (options != null && options.length > 0) {
// Set the options just for this class
try {
Object[] getterArgs = {};
Class<?> parent = targetClazz.getSuperclass();
PropertyDescriptor[] properties =
getPropertyDescriptors(targetClazz, parent);
for (PropertyDescriptor p : properties) {
Method getter = p.getReadMethod();
Method setter = p.getWriteMethod();
if (getter == null || setter == null) {
continue;
}
OptionMetadata parameterDescription = null;
parameterDescription = getter.getAnnotation(OptionMetadata.class);
if (parameterDescription == null) {
parameterDescription = setter.getAnnotation(OptionMetadata.class);
}
if (parameterDescription != null
&& parameterDescription.commandLineParamName().length() > 0) {
boolean processOpt = false;
String optionValue = "";
Object valueToSet = null;
if (parameterDescription.commandLineParamIsFlag()) {
processOpt = true;
valueToSet =
(Utils.getFlag(parameterDescription.commandLineParamName(),
options));
} else {
optionValue =
Utils.getOption(parameterDescription.commandLineParamName(),
options);
processOpt = optionValue.length() > 0;
}
// grab the default/current return value so that we can determine
// the type
Object value = getter.invoke(target, getterArgs);
if (value != null && processOpt) {
if (value.getClass().isArray() && ((Object[]) value).length >= 0) {
// We're interested in the actual element type...
Class<?> elementType =
getter.getReturnType().getComponentType();
// handle arrays by looking for the option multiple times
List<String> optionValues = new ArrayList<String>();
optionValues.add(optionValue);
while (true) {
optionValue =
Utils.getOption(
parameterDescription.commandLineParamName(), options);
if (optionValue.length() == 0) {
break;
}
optionValues.add(optionValue);
}
valueToSet =
Array.newInstance(elementType, optionValues.size());
for (int i = 0; i < optionValues.size(); i++) {
Object elementObject = null;
if (elementType.isAssignableFrom(File.class)) {
elementObject = new File(optionValues.get(i));
} else {
elementObject =
constructOptionHandlerValue(optionValues.get(i));
}
Array.set(valueToSet, i, elementObject);
}
} else if (value instanceof SelectedTag) {
Tag[] legalTags = ((SelectedTag) value).getTags();
int tagIndex = Integer.MAX_VALUE;
// first try and parse as an integer
try {
int specifiedID = Integer.parseInt(optionValue);
for (int z = 0; z < legalTags.length; z++) {
if (legalTags[z].getID() == specifiedID) {
tagIndex = z;
break;
}
}
} catch (NumberFormatException e) {
// try to match tag strings
for (int z = 0; z < legalTags.length; z++) {
if (legalTags[z].getReadable().equals(optionValue.trim())) {
tagIndex = z;
break;
}
}
}
if (tagIndex != Integer.MAX_VALUE) {
valueToSet = new SelectedTag(tagIndex, legalTags);
} else {
throw new Exception("Unable to set option: '"
+ parameterDescription.commandLineParamName()
+ "'. This option takes a SelectedTag argument, and "
+ "the supplied value of '" + optionValue + "' "
+ "does not match any of the legal IDs or strings "
+ "for it.");
}
} else if (value instanceof Enum) {
EnumHelper helper = new EnumHelper((Enum) value);
valueToSet =
EnumHelper
.valueFromString(helper.getEnumClass(), optionValue);
} else if (value instanceof OptionHandler) {
valueToSet = constructOptionHandlerValue(optionValue);
} else if (value instanceof Number) {
try {
if (value instanceof Integer) {
valueToSet = new Integer(optionValue);
} else if (value instanceof Long) {
valueToSet = new Long(optionValue);
} else if (value instanceof Double) {
valueToSet = new Double(optionValue);
} else if (value instanceof Float) {
valueToSet = new Float(optionValue);
}
} catch (NumberFormatException e) {
throw new Exception("Option: '"
+ parameterDescription.commandLineParamName()
+ "' requires a " + value.getClass().getCanonicalName()
+ " argument");
}
} else if (value instanceof String) {
valueToSet = optionValue;
} else if (value instanceof File) {
valueToSet = new File(optionValue);
}
if (valueToSet != null) {
// set it!
// System.err.println("Setter: " + setter.getName());
// System.err.println("Argument: " +
// valueToSet.getClass().getCanonicalName());
setOption(setter, target, valueToSet);
}
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
/**
* Construct an instance of an option handler from a String specifying its
* class name and option values
*
* @param optionValue a String containing the class of the option handler
* followed by its options
* @return an instantiated option handling object
* @throws Exception if a problem occurs
*/
protected static Object constructOptionHandlerValue(String optionValue)
throws Exception {
String[] optHandlerSpec = Utils.splitOptions(optionValue);
if (optHandlerSpec.length == 0) {
throw new Exception("Invalid option handler specification " + "string '"
+ optionValue);
}
String optionHandler = optHandlerSpec[0];
optHandlerSpec[0] = "";
Object handler = Utils.forName(null, optionHandler, optHandlerSpec);
return handler;
}
/**
* Removes an option from a given list of options.
*
* @param list the list to reduce
* @param name the name of the option
*/
public static void deleteOption(List<Option> list, String name) {
for (Iterator<Option> iter = list.listIterator(); iter.hasNext();) {
Option a = iter.next();
if (a.name().equals(name)) {
iter.remove();
}
}
}
/**
* Removes an option from a given list of strings that specifies options. This
* method is for an option that has a parameter value.
*
* @param list the list to reduce
* @param name the name of the option (including hyphen)
*/
public static void deleteOptionString(List<String> list, String name) {
for (Iterator<String> iter = list.listIterator(); iter.hasNext();) {
String a = iter.next();
if (a.equals(name)) {
iter.remove();
iter.next();
iter.remove();
}
}
}
/**
* Removes an option from a given list of strings that specifies options. This
* method is for an option without a parameter value (i.e., a flag).
*
* @param list the list to reduce
* @param name the name of the option (including hyphen)
*/
public static void deleteFlagString(List<String> list, String name) {
for (Iterator<String> iter = list.listIterator(); iter.hasNext();) {
String a = iter.next();
if (a.equals(name)) {
iter.remove();
}
}
}
/**
* Set an option value on a target object
*
* @param setter the Method object for the setter method of the option to set
* @param target the target object on which to set the option
* @param valueToSet the value of the option to set
* @throws InvocationTargetException if a problem occurs
* @throws IllegalAccessException if a problem occurs
*/
protected static void setOption(Method setter, Object target,
Object valueToSet) throws InvocationTargetException, IllegalAccessException {
Object[] setterArgs = { valueToSet };
setter.invoke(target, setterArgs);
}
/**
* Returns the option's description.
*
* @return the option's description
*/
public String description() {
return m_Description;
}
/**
* Returns the option's name.
*
* @return the option's name
*/
public String name() {
return m_Name;
}
/**
* Returns the option's number of arguments.
*
* @return the option's number of arguments
*/
public int numArguments() {
return m_NumArguments;
}
/**
* Returns the option's synopsis.
*
* @return the option's synopsis
*/
public String synopsis() {
return m_Synopsis;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/OptionHandler.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* OptionHandler.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.Enumeration;
/**
* Interface to something that understands options.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface OptionHandler {
/**
* Returns an enumeration of all the available options..
*
* @return an enumeration of all available options.
*/
Enumeration<Option> listOptions();
/**
* Sets the OptionHandler's options using the given list. All options
* will be set (or reset) during this call (i.e. incremental setting
* of options is not possible).
*
* @param options the list of options as an array of strings
* @exception Exception if an option is not supported
*/
//@ requires options != null;
//@ requires \nonnullelements(options);
void setOptions(String[] options) throws Exception;
/**
* Gets the current option settings for the OptionHandler.
*
* @return the list of current option settings as an array of strings
*/
//@ ensures \result != null;
//@ ensures \nonnullelements(\result);
/*@pure@*/ String[] getOptions();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/OptionHandlerJavadoc.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* OptionHandlerJavadoc.java
* Copyright (C) 2006-2012,2015 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
/**
* Generates Javadoc comments from the OptionHandler's options. Can
* automatically update the option comments if they're surrounded by the
* OPTIONS_STARTTAG and OPTIONS_ENDTAG (the indention is determined via the
* OPTIONS_STARTTAG).
* <p>
*
* <!-- options-start --> Valid options are:
* <p>
*
* <pre>
* -W <classname>
* The class to load.
* </pre>
*
* <pre>
* -nostars
* Suppresses the '*' in the Javadoc.
* </pre>
*
* <pre>
* -dir <dir>
* The directory above the package hierarchy of the class.
* </pre>
*
* <pre>
* -silent
* Suppresses printing in the console.
* </pre>
*
* <pre>
* -noprolog
* Suppresses the 'Valid options are...' prolog in the Javadoc.
* </pre>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see #OPTIONS_STARTTAG
* @see #OPTIONS_ENDTAG
*/
public class OptionHandlerJavadoc extends Javadoc {
/** the start comment tag for inserting the generated Javadoc */
public final static String OPTIONS_STARTTAG = "<!-- options-start -->";
/** the end comment tag for inserting the generated Javadoc */
public final static String OPTIONS_ENDTAG = "<!-- options-end -->";
/** whether to include the "Valid options..." prolog in the Javadoc */
protected boolean m_Prolog = true;
/**
* default constructor
*/
public OptionHandlerJavadoc() {
super();
m_StartTag = new String[1];
m_EndTag = new String[1];
m_StartTag[0] = OPTIONS_STARTTAG;
m_EndTag[0] = OPTIONS_ENDTAG;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addAll(Collections.list(super.listOptions()));
result.addElement(new Option(
"\tSuppresses the 'Valid options are...' prolog in the Javadoc.",
"noprolog", 0, "-noprolog"));
return result.elements();
}
/**
* 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
*/
@Override
public void setOptions(String[] options) throws Exception {
super.setOptions(options);
setProlog(!Utils.getFlag("noprolog", options));
}
/**
* Gets the current settings of this object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
Collections.addAll(result, super.getOptions());
if (!getProlog()) {
result.add("-noprolog");
}
return result.toArray(new String[result.size()]);
}
/**
* sets whether to add the "Valid options are..." prolog
*
* @param value true if the prolog is to be added
*/
public void setProlog(boolean value) {
m_Prolog = value;
}
/**
* whether "Valid options are..." prolog is included in the Javadoc
*
* @return true if the prolog is printed
*/
public boolean getProlog() {
return m_Prolog;
}
/**
* generates and returns the Javadoc for the specified start/end tag pair.
*
* @param index the index in the start/end tag array
* @return the generated Javadoc
* @throws Exception in case the generation fails
*/
@Override
protected String generateJavadoc(int index) throws Exception {
String result;
OptionHandler handler;
String optionStr;
result = "";
if (index == 0) {
if (!canInstantiateClass()) {
return result;
}
if (!InheritanceUtils.hasInterface(OptionHandler.class, getInstance()
.getClass())) {
throw new Exception("Class '" + getClassname()
+ "' is not an OptionHandler!");
}
// any options at all?
handler = (OptionHandler) getInstance();
Enumeration<Option> enm = handler.listOptions();
if (!enm.hasMoreElements()) {
return result;
}
// prolog?
if (getProlog()) {
result = "Valid options are: <p>\n\n";
}
// options
enm = handler.listOptions();
while (enm.hasMoreElements()) {
Option option = enm.nextElement();
optionStr = toHTML(option.synopsis()) + "\n"
+ toHTML(option.description().replaceAll("\\t", " "));
result += "<pre> " + optionStr.replaceAll("<br>", "") + "</pre>\n\n";
}
// stars?
if (getUseStars()) {
result = indent(result, 1, "* ");
}
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Parses the given commandline parameters and generates the Javadoc.
*
* @param args the commandline parameters for the object
*/
public static void main(String[] args) {
runJavadoc(new OptionHandlerJavadoc(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/OptionMetadata.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* OptionMetadata.java
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.lang.annotation.*;
/**
* Method annotation that can be used with scheme parameters to provide a nice
* display-ready name for the parameter, help information and, if applicable,
* command line option details
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface OptionMetadata {
/**
* The nice GUI displayable name for this parameter
*
* @return a nice displayable name
*/
String displayName();
/**
* Description of this parameter. Displayed as a tool tip and help in the GUI,
* and on the command line.
*
* @return the description text of this parameter
*/
String description();
/**
* The order (low to high), relative to other parameters, that this property
* should be displayed in the GUI and, if applicable, on the command line help
*
* @return the order (default 100)
*/
int displayOrder() default 100;
/**
* The name of the command line version of this parameter (without leading -).
* If this parameter is not a command line one, then just leave at the default
* empty string.
*
* @return the name of the command line version of this parameter
*/
String commandLineParamName() default "";
/**
* True if the command line version of this parameter is a flag (i.e. binary
* parameter).
*
* @return true if the command line version of this parameter is a flag
*/
boolean commandLineParamIsFlag() default false;
/**
* The synopsis to display on in the command line help for this parameter
* (e.g. -Z <integer>). If this parameter is not a command line one, then just
* leave at the default empty string.
*
* @return the command line synopsis for this parameter
*/
String commandLineParamSynopsis() default "";
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/PartitionGenerator.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* PartitionGenerator.java
* Copyright (C) 2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* This interface can be implemented by algorithms that generate
* a partition of the instance space (e.g., decision trees).
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface PartitionGenerator extends CapabilitiesHandler {
/**
* Builds the classifier to generate a partition.
*/
public void generatePartition(Instances data) throws Exception;
/**
* Computes an array that has a value for each element in the partition.
*/
public double[] getMembershipValues(Instance inst) throws Exception;
/**
* Returns the number of elements in the partition.
*/
public int numElements() throws Exception;
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/PluginManager.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* PluginManager.java
* Copyright (C) 2011-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
/**
* Class that manages a global map of plugins. Provides static methods for
* registering and instantiating plugins. The package manager looks for, and
* processes, a PluginManager.props file in the top-level of a package.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: 12312 $
*/
public class PluginManager {
/**
* Global map of plugin classes that is keyed by plugin base class/interface
* type. The inner Map then stores individual plugin instances of the
* interface type, keyed by plugin name/short title with values the actual
* fully qualified class name
*/
protected static Map<String, Map<String, String>> PLUGINS =
new HashMap<String, Map<String, String>>();
/**
* Set of concrete fully qualified class names or abstract/interface base
* types to "disable". Entries in this list wont ever be returned by any of
* the getPlugin() methods. Registering an abstract/interface base name will
* disable all concrete implementations of that type
*/
protected static Set<String> DISABLED = new HashSet<String>();
/**
* Global map of plugin resources (loadable from the classpath). Outer map is
* keyed by group ID, i.e. an ID of a logical group of resources (e.g.
* knowledge flow template files). The inner map then stores individual
* resource paths keyed by their short description.
*/
protected static Map<String, Map<String, String>> RESOURCES =
new HashMap<String, Map<String, String>>();
/**
* Global lookup map to locate a package owner for resources. Keyed by group
* ID:resource description. Used to see if a package owns a resource, in which
* case the package classloader should be used to load the resource rather
* than the application classloader
*/
protected static Map<String, String> RESOURCE_OWNER_PACKAGE = new HashMap<>();
/**
* Add the supplied list of fully qualified class names to the disabled list
*
* @param classnames a list of class names to add
*/
public static synchronized void addToDisabledList(List<String> classnames) {
for (String s : classnames) {
addToDisabledList(s);
}
}
/**
* Add the supplied fully qualified class name to the list of disabled plugins
*
* @param classname the fully qualified name of a class to add
*/
public static synchronized void addToDisabledList(String classname) {
DISABLED.add(classname);
}
/**
* Remove the supplied list of fully qualified class names to the disabled
* list
*
* @param classnames a list of class names to remove
*/
public static synchronized void
removeFromDisabledList(List<String> classnames) {
for (String s : classnames) {
removeFromDisabledList(s);
}
}
/**
* Remove the supplied fully qualified class name from the list of disabled
* plugins
*
* @param classname the fully qualified name of a class to remove
*/
public static synchronized void removeFromDisabledList(String classname) {
DISABLED.remove(classname);
}
/**
* Returns true if the supplied fully qualified class name is in the disabled
* list
*
* @param classname the name of the class to check
* @return true if the supplied class name is in the disabled list
*/
public static boolean isInDisabledList(String classname) {
return DISABLED.contains(classname);
}
/**
* Add all key value pairs from the supplied property file
*
* @param propsFile the properties file to add
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(File propsFile)
throws Exception {
addFromProperties(null, propsFile);
}
/**
* Add all key value pairs from the supplied property file
*
* @param packageName the name of the Weka package that owns this properties
* object. Can be null if not owned by a Weka package
* @param propsFile the properties file to add
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(String packageName,
File propsFile) throws Exception {
addFromProperties(packageName, propsFile, false);
}
/**
* Add all key value pairs from the supplied property file
*
* @param propsFile the properties file to add
* @param maintainInsertionOrder true if the order of insertion of
* implementations is to be preserved (rather than sorted order)
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(File propsFile,
boolean maintainInsertionOrder) throws Exception {
addFromProperties(null, propsFile, maintainInsertionOrder);
}
/**
* Add all key value pairs from the supplied property file
*
* @param packageName the name of the Weka package that owns this properties
* object. Can be null if not owned by a Weka package
* @param propsFile the properties file to add
* @param maintainInsertionOrder true if the order of insertion of
* implementations is to be preserved (rather than sorted order)
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(String packageName,
File propsFile, boolean maintainInsertionOrder) throws Exception {
BufferedInputStream bi =
new BufferedInputStream(new FileInputStream(propsFile));
addFromProperties(packageName, bi, maintainInsertionOrder);
}
/**
* Add all key value pairs from the supplied properties stream
*
* @param propsStream an input stream to a properties file
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(InputStream propsStream)
throws Exception {
addFromProperties(null, propsStream);
}
/**
* Add all key value pairs from the supplied properties stream
*
* @param packageName the name of the Weka package that owns this properties
* object. Can be null if not owned by a Weka package
* @param propsStream an input stream to a properties file
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(String packageName,
InputStream propsStream) throws Exception {
addFromProperties(packageName, propsStream, false);
}
/**
* Add all key value pairs from the supplied properties stream
*
* @param propsStream an input stream to a properties file
* @param maintainInsertionOrder true if the order of insertion of
* implementations is to be preserved (rather than sorted order)
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(InputStream propsStream,
boolean maintainInsertionOrder) throws Exception {
addFromProperties(null, propsStream, maintainInsertionOrder);
}
/**
* Add all key value pairs from the supplied properties stream
*
* @param packageName the name of the Weka package that owns this properties
* object. Can be null if not owned by a Weka package
* @param propsStream an input stream to a properties file
* @param maintainInsertionOrder true if the order of insertion of
* implementations is to be preserved (rather than sorted order)
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(String packageName,
InputStream propsStream, boolean maintainInsertionOrder) throws Exception {
Properties expProps = new Properties();
expProps.load(propsStream);
propsStream.close();
propsStream = null;
addFromProperties(packageName, expProps, maintainInsertionOrder);
}
/**
* Add all key value pairs from the supplied properties object
*
* @param props a Properties object
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(Properties props)
throws Exception {
addFromProperties(props, false);
}
/**
* Add all key value pairs from the supplied properties object
*
* @param packageName the name of the Weka package that owns this properties
* object. Can be null if not owned by a Weka package
* @param props a Properties object
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(String packageName,
Properties props) throws Exception {
addFromProperties(packageName, props, false);
}
/**
* Add all key value pairs from the supplied properties object
*
* @param props a Properties object
* @param maintainInsertionOrder true if the order of insertion of
* implementations is to be preserved (rather than sorted order)
* @throws Exception if a problem occurs
*/
public synchronized static void addFromProperties(Properties props,
boolean maintainInsertionOrder) throws Exception {
addFromProperties(null, props, maintainInsertionOrder);
}
/**
* Add all key value pairs from the supplied properties object
*
* @param packageName the name of the Weka package that owns this properties
* object. Can be null if not owned by a Weka package
* @param props a Properties object
* @param maintainInsertionOrder true if the order of insertion of
* implementations is to be preserved (rather than sorted order)
* @throws Exception if a problem occurs
*/
public static synchronized void addFromProperties(String packageName,
Properties props, boolean maintainInsertionOrder) throws Exception {
java.util.Enumeration<?> keys = props.propertyNames();
while (keys.hasMoreElements()) {
String baseType = (String) keys.nextElement();
String implementations = props.getProperty(baseType);
if (baseType.equalsIgnoreCase("*resources*")) {
addPluginResourcesFromProperty(packageName, implementations);
} else {
if (implementations != null && implementations.length() > 0) {
String[] parts = implementations.split(",");
for (String impl : parts) {
impl = impl.trim();
String name = impl;
if (impl.charAt(0) == '[') {
name = impl.substring(1, impl.indexOf(']'));
impl = impl.substring(impl.indexOf(']') + 1);
}
PluginManager.addPlugin(baseType, name.trim(), impl,
maintainInsertionOrder);
}
}
}
}
}
/**
* Add resources from a list. String format for a list of resources (as might
* be supplied from a *resources* entry in an property file:<br>
* <br>
*
* <pre>
* [groupID|description|path],[groupID|description|path],...
* </pre>
*
* @param resourceList a list of resources to add
*/
public static void addPluginResourcesFromProperty(String resourceList) {
addPluginResourcesFromProperty(null, resourceList);
}
/**
* Add resources from a list. String format for a list of resources (as might
* be supplied from a *resources* entry in an property file:<br>
* <br>
*
* <pre>
* [groupID|description|path],[groupID|description|path],...
* </pre>
*
* @param packageName the Weka package that owns these resources. Can be null
* if not owned by a Weka package
* @param resourceList a list of resources to add
*/
protected static synchronized void addPluginResourcesFromProperty(
String packageName, String resourceList) {
// Format: [groupID|description|path],[...],...
String[] resources = resourceList.split(",");
for (String r : resources) {
r = r.trim();
if (!r.startsWith("[") || !r.endsWith("]")) {
System.err.println("[PluginManager] Malformed resource in: "
+ resourceList);
continue;
}
r = r.replace("[", "").replace("]", "");
String[] rParts = r.split("\\|");
if (rParts.length != 3) {
System.err
.println("[PluginManager] Was expecting 3 pipe separated parts in "
+ "resource spec: " + r);
continue;
}
String groupID = rParts[0].trim();
String resourceDesc = rParts[1].trim();
String resourcePath = rParts[2].trim();
if (groupID.length() == 0 || resourceDesc.length() == 0
|| resourcePath.length() == 0) {
System.err.println("[PluginManager] Empty part in resource spec: " + r);
continue;
}
addPluginResource(packageName, groupID, resourceDesc, resourcePath);
}
}
/**
* Add a resource.
*
* @param resourceGroupID the ID of the group under which the resource should
* be stored
* @param resourceDescription the description/ID of the resource
* @param resourcePath the path to the resource
*/
public static void addPluginResource(String resourceGroupID,
String resourceDescription, String resourcePath) {
addPluginResource(null, resourceGroupID, resourceDescription, resourcePath);
}
/**
* Add a resource.
*
* @param packageName the name of the package that owns this resource. Can be
* null if not owned by a package, in which case the current
* classloader will be used to load the resource.
* @param resourceGroupID the ID of the group under which the resource should
* be stored
* @param resourceDescription the description/ID of the resource
* @param resourcePath the path to the resource
*/
public static synchronized void addPluginResource(String packageName,
String resourceGroupID, String resourceDescription, String resourcePath) {
Map<String, String> groupMap = RESOURCES.get(resourceGroupID);
if (groupMap == null) {
groupMap = new LinkedHashMap<String, String>();
RESOURCES.put(resourceGroupID, groupMap);
}
groupMap.put(resourceDescription, resourcePath);
if (packageName != null && packageName.length() > 0) {
RESOURCE_OWNER_PACKAGE.put(resourceGroupID + ":" + resourceDescription,
packageName);
}
}
/**
* Get an input stream for a named resource under a given resource group ID.
*
* @param resourceGroupID the group ID that the resource falls under
* @param resourceDescription the description/ID of the resource
* @return an InputStream for the resource
* @throws IOException if the group ID or resource description/ID are not
* known to the PluginManager, or a problem occurs while trying to
* open an input stream
*/
public static InputStream getPluginResourceAsStream(String resourceGroupID,
String resourceDescription) throws IOException {
Map<String, String> groupMap = RESOURCES.get(resourceGroupID);
if (groupMap == null) {
throw new IOException("Unknown resource group ID: " + resourceGroupID);
}
String resourcePath = groupMap.get(resourceDescription);
if (resourcePath == null) {
throw new IOException("Unknown resource: " + resourceDescription);
}
// owned by a package?
String ownerPackage =
RESOURCE_OWNER_PACKAGE.get(resourceGroupID + ":" + resourceDescription);
if (ownerPackage == null) {
return PluginManager.class.getClassLoader().getResourceAsStream(
resourcePath);
}
return WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.getPackageClassLoader(ownerPackage).getResourceAsStream(resourcePath);
}
/**
* Get the number of resources available under a given resource group ID.
*
* @param resourceGroupID the group ID of the resources
* @return the number of resources registered under the supplied group ID
*/
public static int numResourcesForWithGroupID(String resourceGroupID) {
Map<String, String> groupMap = RESOURCES.get(resourceGroupID);
return groupMap == null ? 0 : groupMap.size();
}
/**
* Get a map of resources (description,path) registered under a given resource
* group ID.
*
* @param resourceGroupID the group ID of the resources to get
* @return a map of resources registered under the supplied group ID, or null
* if the resourceGroupID is not known to the plugin manager
*/
public static Map<String, String> getResourcesWithGroupID(
String resourceGroupID) {
return RESOURCES.get(resourceGroupID);
}
/**
* Get a set of names of plugins that implement the supplied interface.
*
* @param interfaceName the fully qualified name of the interface to list
* plugins for
*
* @return a set of names of plugins
*/
public static Set<String> getPluginNamesOfType(String interfaceName) {
if (PLUGINS.get(interfaceName) != null) {
Set<String> match = PLUGINS.get(interfaceName).keySet();
Set<String> result = new LinkedHashSet<String>();
for (String s : match) {
String impl = PLUGINS.get(interfaceName).get(s);
if (!DISABLED.contains(impl)) {
result.add(s);
}
}
// return PLUGINS.get(interfaceName).keySet();
return result;
}
return null;
}
/**
* Get a sorted list of names of plugins that implement the supplied interface.
*
* @param interfaceName the fully qualified name of the interface to list
* plugins for
*
* @return a set of names of plugins
*/
public static List<String> getPluginNamesOfTypeList(String interfaceName) {
List<String> result;
Set<String> r = getPluginNamesOfType(interfaceName);
result = new ArrayList<String>();
if (r != null) {
result.addAll(r);
}
Collections.sort(result, new ClassDiscovery.StringCompare());
return result;
}
/**
* Add a plugin.
*
* @param interfaceName the fully qualified interface name that the plugin
* implements
*
* @param name the name/short description of the plugin
* @param concreteType the fully qualified class name of the actual concrete
* implementation
*/
public static void addPlugin(String interfaceName, String name,
String concreteType) {
addPlugin(interfaceName, name, concreteType, false);
}
/**
* Add a plugin.
*
* @param interfaceName the fully qualified interface name that the plugin
* implements
*
* @param name the name/short description of the plugin
* @param concreteType the fully qualified class name of the actual concrete
* implementation
* @param maintainInsertionOrder true if the order of insertion of
* implementations is to be preserved (rather than sorted order)
*/
public static void addPlugin(String interfaceName, String name,
String concreteType, boolean maintainInsertionOrder) {
if (PLUGINS.get(interfaceName) == null) {
Map<String, String> pluginsOfInterfaceType =
maintainInsertionOrder ? new LinkedHashMap<String, String>()
: new TreeMap<String, String>();
pluginsOfInterfaceType.put(name, concreteType);
PLUGINS.put(interfaceName, pluginsOfInterfaceType);
} else {
PLUGINS.get(interfaceName).put(name, concreteType);
}
}
/**
* Remove plugins of a specific type.
*
* @param interfaceName the fully qualified interface name that the plugins to
* be remove implement
* @param names a list of named plugins to remove
*/
public static void removePlugins(String interfaceName, List<String> names) {
for (String name : names) {
removePlugin(interfaceName, name);
}
}
/**
* Remove a plugin.
*
* @param interfaceName the fully qualified interface name that the plugin
* implements
*
* @param name the name/short description of the plugin
*/
public static void removePlugin(String interfaceName, String name) {
if (PLUGINS.get(interfaceName) != null) {
PLUGINS.get(interfaceName).remove(name);
}
}
/**
* Checks if a named plugin exists in the map of registered plugins
*
* @param interfaceType the fully qualified interface name of the plugin type
* @param name the name/short description of the plugin to get
* @return true if the named plugin exists
*/
public static boolean pluginRegistered(String interfaceType, String name) {
Map<String, String> pluginsOfInterfaceType = PLUGINS.get(interfaceType);
return pluginsOfInterfaceType.get(name) != null;
}
/**
* Get an instance of a concrete implementation of a plugin type
*
* @param interfaceType the fully qualified interface name of the plugin type
* @param name the name/short description of the plugin to get
* @return the concrete plugin or null if the plugin is disabled
* @throws Exception if the plugin can't be found or instantiated
*/
public static Object getPluginInstance(String interfaceType, String name)
throws Exception {
if (PLUGINS.get(interfaceType) == null
|| PLUGINS.get(interfaceType).size() == 0) {
throw new Exception("No plugins of interface type: " + interfaceType
+ " available!!");
}
Map<String, String> pluginsOfInterfaceType = PLUGINS.get(interfaceType);
if (pluginsOfInterfaceType.get(name) == null) {
throw new Exception("Can't find named plugin '" + name + "' of type '"
+ interfaceType + "'!");
}
String concreteImpl = pluginsOfInterfaceType.get(name);
Object plugin = null;
if (!DISABLED.contains(concreteImpl)) {
plugin =
WekaPackageClassLoaderManager.forName(concreteImpl).newInstance();
}
return plugin;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/PropertyPath.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* PropertyPath.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* A helper class for accessing properties in nested objects, e.g., accessing
* the "getRidge" method of a LinearRegression classifier part of
* MultipleClassifierCombiner, e.g., Vote. For doing so, one needs to
* supply the object to work on and a property path. The property path is a
* dot delimited path of property names ("getFoo()" and "setFoo(int)" have
* "foo" as property name), indices of arrays are 0-based. E.g.: <p/>
*
* <code>getPropertyDescriptor(vote, "classifiers[1].ridge")</code> will return
* the second classifier (which should be our LinearRegression) of the given
* Vote meta-classifier and there the property descriptor of the "ridge"
* property. <code>getValue(...)</code> will return the actual value of the
* ridge parameter and <code>setValue(...)</code> will set it.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class PropertyPath
implements RevisionHandler {
/**
* Represents a single element of a property path
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public static class PathElement
implements Cloneable, RevisionHandler {
/** the property */
protected String m_Name;
/** the index of the array (-1 for none) */
protected int m_Index;
/**
* initializes the path element with the given property
*
* @param property the property to initialize with
*/
public PathElement(String property) {
super();
if (property.indexOf("[") > -1) {
m_Name = property.replaceAll("\\[.*$", "");
m_Index = Integer.parseInt(
property.replaceAll(".*\\[", "").replaceAll("\\].*", ""));
}
else {
m_Name = property;
m_Index = -1;
}
}
/**
* returns a clone of the current object
*
* @return the clone of the current state
*/
public Object clone() {
return new PathElement(this.toString());
}
/**
* returns the name of the property
*
* @return the name of the property
*/
public String getName() {
return m_Name;
}
/**
* returns whether the property is an index-based one
*
* @return true if the property has an index
*/
public boolean hasIndex() {
return (getIndex() > -1);
}
/**
* returns the index of the property, -1 if the property is not an
* index-based one
*
* @return the index of the property
*/
public int getIndex() {
return m_Index;
}
/**
* returns the element once again as string
*
* @return the property as string
*/
public String toString() {
String result;
result = getName();
if (hasIndex())
result += "[" + getIndex() + "]";
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* Contains a (property) path structure
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public static class Path
implements RevisionHandler {
/** the structure */
protected Vector<PathElement> m_Elements;
/**
* default constructor, only used internally
*/
protected Path() {
super();
m_Elements = new Vector<PathElement>();
}
/**
* uses the given dot-path
*
* @param path path in dot-notation
*/
public Path(String path) {
this();
m_Elements = breakUp(path);
}
/**
* uses the vector with PathElement objects to initialize with
*
* @param elements the PathElements to use
*/
public Path(Vector<PathElement> elements) {
this();
for (int i = 0; i < elements.size(); i++)
m_Elements.add((PathElement) elements.get(i).clone());
}
/**
* uses the given array as elements for the path
*
* @param elements the path elements to use
*/
public Path(String[] elements) {
this();
for (int i = 0; i < elements.length; i++)
m_Elements.add(new PathElement(elements[i]));
}
/**
* breaks up the given path and returns it as vector
*
* @param path the path to break up
* @return the single elements of the path
*/
protected Vector<PathElement> breakUp(String path) {
Vector<PathElement> result;
StringTokenizer tok;
result = new Vector<PathElement>();
tok = new StringTokenizer(path, ".");
while (tok.hasMoreTokens())
result.add(new PathElement(tok.nextToken()));
return result;
}
/**
* returns the element at the given index
*
* @param index the index of the element to return
* @return the specified element
*/
public PathElement get(int index) {
return (PathElement) m_Elements.get(index);
}
/**
* returns the number of path elements of this structure
*
* @return the number of path elements
*/
public int size() {
return m_Elements.size();
}
/**
* returns a path object based on the given path string
*
* @param path path to work on
* @return the path structure
*/
public static Path parsePath(String path) {
return new Path(path);
}
/**
* returns a subpath of the current structure, starting with the specified
* element index up to the end
*
* @param startIndex the first element of the subpath
* @return the new subpath
*/
public Path subpath(int startIndex) {
return subpath(startIndex, size());
}
/**
* returns a subpath of the current structure, starting with the specified
* element index up. The endIndex specifies the element that is not part
* of the new subpath. In other words, the new path contains the elements
* from "startIndex" up to "(endIndex-1)".
*
* @param startIndex the first element of the subpath
* @param endIndex the element that is after the last added element
* @return the new subpath
*/
public Path subpath(int startIndex, int endIndex) {
Vector<PathElement> list;
int i;
list = new Vector<PathElement>();
for (i = startIndex; i < endIndex; i++)
list.add(get(i));
return new Path(list);
}
/**
* returns the structure again as a dot-path
*
* @return the path structure as dot-path
*/
public String toString() {
String result;
int i;
result = "";
for (i = 0; i < m_Elements.size(); i++) {
if (i > 0)
result += ".";
result += m_Elements.get(i);
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* A helper class that stores Object and PropertyDescriptor together.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
protected static class PropertyContainer
implements RevisionHandler {
/** the descriptor */
protected PropertyDescriptor m_Descriptor;
/** the associated object */
protected Object m_Object;
/**
* initializes the container
*
* @param desc the property descriptor
* @param obj the associated object
*/
public PropertyContainer(PropertyDescriptor desc, Object obj) {
super();
m_Descriptor = desc;
m_Object = obj;
}
/**
* returns the stored descriptor
*
* @return the stored descriptor
*/
public PropertyDescriptor getDescriptor() {
return m_Descriptor;
}
/**
* returns the stored object
*
* @return the stored object
*/
public Object getObject() {
return m_Object;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* returns the property and object associated with the given path, null if
* a problem occurred.
*
* @param src the object to start from
* @param path the path to follow
* @return not null, if the property could be found
*/
public static PropertyContainer find(Object src, Path path) {
PropertyContainer result;
PropertyDescriptor desc;
Object newSrc;
PathElement part;
Method method;
Object methodResult;
// get descriptor
part = path.get(0);
try {
desc = new PropertyDescriptor(part.getName(), src.getClass());
}
catch (Exception e) {
desc = null;
e.printStackTrace();
}
// problem occurred? -> stop
if (desc == null)
return null;
// end of path reached?
if (path.size() == 1) {
result = new PropertyContainer(desc, src);
}
// recurse further
else {
try {
method = desc.getReadMethod();
methodResult = method.invoke(src, (Object[]) null);
if (part.hasIndex())
newSrc = Array.get(methodResult, part.getIndex());
else
newSrc = methodResult;
result = find(newSrc, path.subpath(1));
}
catch (Exception e) {
result = null;
e.printStackTrace();
}
}
return result;
}
/**
* returns the property associated with the given path, null if a problem
* occurred.
*
* @param src the object to start from
* @param path the path to follow
* @return not null, if the property could be found
*/
public static PropertyDescriptor getPropertyDescriptor(Object src, Path path) {
PropertyContainer cont;
cont = find(src, path);
if (cont == null)
return null;
else
return cont.getDescriptor();
}
/**
* returns the property associated with the given path
*
* @param src the object to start from
* @param path the path to follow
* @return not null, if the property could be found
*/
public static PropertyDescriptor getPropertyDescriptor(Object src, String path) {
return getPropertyDescriptor(src, new Path(path));
}
/**
* returns the value specified by the given path from the object
*
* @param src the object to work on
* @param path the retrieval path
* @return the value, null if an error occurred
*/
public static Object getValue(Object src, Path path) {
Object result;
PropertyContainer cont;
Method method;
Object methodResult;
PathElement part;
result = null;
cont = find(src, path);
// problem?
if (cont == null)
return null;
// retrieve the value
try {
part = path.get(path.size() - 1);
method = cont.getDescriptor().getReadMethod();
methodResult = method.invoke(cont.getObject(), (Object[]) null);
if (part.hasIndex())
result = Array.get(methodResult, part.getIndex());
else
result = methodResult;
}
catch (Exception e) {
result = null;
e.printStackTrace();
}
return result;
}
/**
* returns the value specified by the given path from the object
*
* @param src the object to work on
* @param path the retrieval path
* @return the value, null if an error occurred
*/
public static Object getValue(Object src, String path) {
return getValue(src, new Path(path));
}
/**
* set the given value specified by the given path in the object
*
* @param src the object to work on
* @param path the retrieval path
* @param value the value to set
* @return true if the value could be set
*/
public static boolean setValue(Object src, Path path, Object value) {
boolean result;
PropertyContainer cont;
Method methodRead;
Method methodWrite;
Object methodResult;
PathElement part;
result = false;
cont = find(src, path);
// problem?
if (cont == null)
return result;
// set the value
try {
part = path.get(path.size() - 1);
methodRead = cont.getDescriptor().getReadMethod();
methodWrite = cont.getDescriptor().getWriteMethod();
if (part.hasIndex()) {
methodResult = methodRead.invoke(cont.getObject(), (Object[]) null);
Array.set(methodResult, part.getIndex(), value);
methodWrite.invoke(cont.getObject(), new Object[]{methodResult});
}
else {
methodWrite.invoke(cont.getObject(), new Object[]{value});
}
result = true;
}
catch (Exception e) {
result = false;
e.printStackTrace();
}
return result;
}
/**
* set the given value specified by the given path in the object
*
* @param src the object to work on
* @param path the retrieval path
* @param value the value to set
*/
public static void setValue(Object src, String path, Object value) {
setValue(src, new Path(path), value);
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* for testing only
*
* @param args the commandline options - ignored
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
// Path
Path path = new Path("hello.world[2].nothing");
System.out.println("Path: " + path);
System.out.println(" -size: " + path.size());
System.out.println(" -elements:");
for (int i = 0; i < path.size(); i++)
System.out.println(
" " + i + ". " + path.get(i).getName()
+ " -> " + path.get(i).getIndex());
/*
// retrieving ridge with path
weka.classifiers.meta.Vote vote = new weka.classifiers.meta.Vote();
vote.setClassifiers(
new weka.classifiers.Classifier[]{
new weka.classifiers.trees.J48(),
new weka.classifiers.functions.LinearRegression()});
path = new Path("classifiers[1].ridge");
System.out.println("path: " + path + " -> " + getValue(vote, path));
// setting ridge with path and retrieving it again
setValue(vote, path.toString(), new Double(0.1));
System.out.println("path: " + path + " -> " + getValue(vote, path));
*/
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/ProtectedProperties.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ProtectedProperties.java
* Copyright (C) 2001-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
/**
* Simple class that extends the Properties class so that the properties are
* unable to be modified.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class ProtectedProperties extends Properties implements RevisionHandler {
/** for serialization */
private static final long serialVersionUID = 3876658672657323985L;
/** the properties need to be open during construction of the object */
private boolean closed = false;
/**
* Creates a set of protected properties from a set of normal ones.
*
* @param props the properties to be stored and protected.
*/
public ProtectedProperties(Properties props) {
Enumeration<?> propEnum = props.propertyNames();
while (propEnum.hasMoreElements()) {
String propName = (String) propEnum.nextElement();
String propValue = props.getProperty(propName);
super.setProperty(propName, propValue);
}
closed = true; // no modifications allowed from now on
}
/**
* Overrides a method to prevent the properties from being modified.
*
* @return never returns without throwing an exception.
* @throws UnsupportedOperationException always.
*/
@Override
public Object setProperty(String key, String value) {
if (closed) {
throw new UnsupportedOperationException(
"ProtectedProperties cannot be modified!");
} else {
return super.setProperty(key, value);
}
}
/**
* Overrides a method to prevent the properties from being modified.
*
* @throws UnsupportedOperationException always.
*/
@Override
public void load(InputStream inStream) {
throw new UnsupportedOperationException(
"ProtectedProperties cannot be modified!");
}
/**
* Overrides a method to prevent the properties from being modified.
*
* @throws UnsupportedOperationException always.
*/
@Override
public void clear() {
throw new UnsupportedOperationException(
"ProtectedProperties cannot be modified!");
}
/**
* Overrides a method to prevent the properties from being modified.
*
* @return never returns without throwing an exception.
* @throws UnsupportedOperationException always.
*/
@Override
public Object put(Object key, Object value) {
if (closed) {
throw new UnsupportedOperationException(
"ProtectedProperties cannot be modified!");
} else {
return super.put(key, value);
}
}
/**
* Overrides a method to prevent the properties from being modified.
*
* @throws UnsupportedOperationException always.
*/
@Override
public void putAll(Map<? extends Object, ? extends Object> t) {
throw new UnsupportedOperationException(
"ProtectedProperties cannot be modified!");
}
/**
* Overrides a method to prevent the properties from being modified.
*
* @return never returns without throwing an exception.
* @throws UnsupportedOperationException always.
*/
@Override
public Object remove(Object key) {
throw new UnsupportedOperationException(
"ProtectedProperties cannot be modified!");
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Queue.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Queue.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
* Modified March-May 2004 by Mark Utting to add JML specs
* (this was done as the example solution of an assignment for a
* software engineering course, so the specifications are more precise
* and complete than one would normally do).
* Passed a static analysis using ESC/Java-2.0a6 with no warnings.
*/
package weka.core;
import java.io.Serializable;
/**
* Class representing a FIFO queue.
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Queue
extends Object
implements Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -1141282001146389780L;
/**
* Represents one node in the queue.
*/
protected class QueueNode
implements Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -5119358279412097455L;
/** The next node in the queue */
protected /*@ spec_public @*/ QueueNode m_Next;
/** The nodes contents
*/
protected /*@ non_null spec_public @*/ Object m_Contents;
/**
* Creates a queue node with the given contents
*/
//@ requires contents != null;
//@ assignable m_Contents, m_Next;
//@ ensures m_Contents == contents;
//@ ensures m_Next == null;
public QueueNode(Object contents) {
m_Contents = contents;
next(null);
}
/**
* Sets the next node in the queue, and returns it.
*/
//@ requires next != this ;
//@ assignable m_Next;
//@ ensures m_Next==next && \result==next;
public QueueNode next(QueueNode next) {
return m_Next = next;
} //@ nowarn Invariant; // Because it stupidly checks the Queue invariant!
/**
* Gets the next node in the queue.
*/
//@ ensures \result == m_Next;
public /*@ pure @*/ QueueNode next() {
return m_Next;
}
/**
* Sets the contents of the node.
*/
//@ requires contents != null;
//@ assignable m_Contents;
//@ ensures m_Contents == contents && \result == contents;
public Object contents(Object contents) {
return m_Contents = contents;
}
/**
* Returns the contents in the node.
*/
//@ ensures \result == m_Contents;
public /*@ pure @*/ Object contents() {
return m_Contents;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/** Store a reference to the head of the queue */
protected /*@ spec_public @*/ QueueNode m_Head = null;
/** Store a reference to the tail of the queue */
protected /*@ spec_public @*/ QueueNode m_Tail = null;
/** Store the c m_Tail.m_Nexturrent number of elements in the queue */
protected /*@ spec_public @*/ int m_Size = 0;
//@ public invariant m_Head == null <==> m_Tail == null;
//@public invariant m_Tail != null ==> m_Tail.m_Next == null;
//@ public invariant m_Size >= 0;
//@ public invariant m_Size == 0 <==> m_Head == null;
//@ public invariant m_Size == 1 <==> m_Head != null && m_Head == m_Tail;
//@ public invariant m_Size > 1 ==> m_Head != m_Tail;
//@ public invariant m_Size > 1 <== m_Head != m_Tail;
/**
* Removes all objects from the queue m_Tail.m_Next.
*/
//@ assignable m_Size, m_Head, m_Tail;
//@ ensures m_Size == 0;
//@ ensures m_Head == null;
//@ ensures m_Tail == null;
public final synchronized void removeAllElements() {
m_Size = 0;
m_Head = null;
m_Tail = null;
}
/**
* Appends an object to the back of the queue.
*
* @param item the object to be appended
* @return the object appended
*/
//@ requires item != null;
//@ assignable m_Head, m_Tail, m_Tail.m_Next, m_Head.m_Next, m_Size;
//@ ensures m_Head != null;
//@ ensures m_Tail != \old(m_Tail);
//@ ensures m_Size == \old(m_Size) + 1;
//@ ensures \old(m_Size) == 0 ==> m_Head == m_Tail;
//@ ensures \old(m_Size) != 0 ==> m_Head == \old(m_Head);
//@ ensures m_Tail.contents() == \old(item);
//@ ensures \result == item;
public synchronized Object push(Object item) {
QueueNode newNode = new QueueNode(item);
if (m_Head == null) {
m_Head = m_Tail = newNode;
} else {
m_Tail = m_Tail.next(newNode);
}
m_Size++;
return item;
}
/**
* Pops an object from the front of the queue.
*
* @return the object at the front of the queue
* @exception RuntimeException if the queue is empty
*/
//@ assignable m_Head, m_Tail, m_Size;
//@ ensures m_Size == \old(m_Size) - 1;
//@ ensures m_Head == \old(m_Head.m_Next);
//@ ensures m_Head != null ==> m_Tail == \old(m_Tail);
//@ ensures \result == \old(m_Head.m_Contents);
//@ signals (RuntimeException) \old(m_Head) == null;
public synchronized Object pop()
throws RuntimeException // REDUNDANT, BUT ESCJAVA REQUIRES THIS
{
if (m_Head == null) {
throw new RuntimeException("Queue is empty");
}
Object retval = m_Head.contents();
m_Size--;
m_Head = m_Head.next();
// Here we need to either tell ESC/Java some facts about
// the contents of the list after popping off the head,
// or turn off the 'invariant' warnings.
//
//@ assume m_Size == 0 <==> m_Head == null;
//@ assume m_Size == 1 <==> m_Head == m_Tail;
if (m_Head == null) {
m_Tail = null;
}
return retval;
}
/**
* Gets object from the front of the queue.
*
* @return the object at the front of the queue
* @exception RuntimeException if the queue is empty
*/
//@ ensures \result == \old(m_Head.m_Contents);
//@ signals (RuntimeException) \old(m_Head) == null;
public /*@ pure @*/ synchronized Object peek()
throws RuntimeException
{
if (m_Head == null) {
throw new RuntimeException("Queue is empty");
}
return m_Head.contents();
}
/**
* Checks if queue is empty.
*
* @return true if queue is empty
*/
//@ ensures \result <==> m_Head == null;
public /*@ pure @*/ boolean empty() {
return m_Head == null;
}
/**
* Gets queue's size.
*
* @return size of queue
*/
//@ ensures \result == m_Size;
public /*@ pure @*/ int size() {
return m_Size;
}
/**
* Produces textual description of queue.
*
* @return textual description of queue
*/
//@ also
//@ ensures \result != null;
//@ ensures (* \result == textual description of the queue *);
public /*@ pure @*/ String toString() {
String retval = "Queue Contents "+m_Size+" elements\n";
QueueNode current = m_Head;
if (current == null) {
return retval + "Empty\n";
} else {
while (current != null) {
retval += current.contents().toString()+"\n"; //@nowarn Modifies;
current = current.next();
}
}
return retval;
} //@ nowarn Post;
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param argv a set of strings that are pushed on a test queue
*/
//@ requires argv.length >= 0;
//@ requires argv != null;
//@ requires (\forall int i; 0 <= i && i < argv.length; argv[i] != null);
public static void main(String [] argv) {
try {
Queue queue = new Queue();
for(int i = 0; i < argv.length; i++) {
queue.push(argv[i]);
}
System.out.println("After pushing command line arguments");
System.out.println(queue.toString());
while (!queue.empty()) {
System.out.println("Pop: " + queue.pop().toString());
}
// try one more pop, to make sure we get an exception
try
{
queue.pop();
System.out.println("ERROR: pop did not throw exception!");
}
catch (RuntimeException ex)
{
System.out.println("Pop on empty queue correctly gave exception.");
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/RandomVariates.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* RandomVariates.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.Random;
/**
* Class implementing some simple random variates generator.
*
* @author Xin Xu (xx5@cs.waikato.ac.nz)
* @version $Revision$
*/
public final class RandomVariates extends Random implements RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -4763742718209460354L;
/**
* Simply the constructor of super class
*/
public RandomVariates(){ super(); }
/**
* Simply the constructor of super class
*
* @param seed the seed in this random object
*/
public RandomVariates(long seed){ super(seed); }
/**
* Simply use the method of the super class
*
* @param bits - random bits
* @return the next pseudorandom value from this random number
* generator's sequence.
*/
protected int next(int bits) {return super.next(bits);}
/**
* Generate a value of a variate following standard exponential
* distribution using simple inverse method.<p>
*
* Variates related to standard Exponential can be generated using simple
* transformations.
* @return a value of the variate
*/
public double nextExponential(){
return -Math.log(1.0-super.nextDouble());
}
/**
* Generate a value of a variate following standard Erlang distribution.
* It can be used when the shape parameter is an integer and not too large,
* say, <100. When the parameter is not an integer (which is often named
* Gamma distribution) or is large, use <code>nextGamma(double a)</code>
* instead.
*
* @param a the shape parameter, must be no less than 1
* @return a value of the variate
* @exception Exception if parameter less than 1
*/
public double nextErlang(int a) throws Exception{
if(a<1)
throw new Exception("Shape parameter of Erlang distribution must be greater than 1!");
double product = 1.0;
for(int i=1; i<=a; i++)
product *= super.nextDouble();
return -Math.log(product);
}
/**
* Generate a value of a variate following standard Gamma distribution
* with shape parameter a.<p>
* If a>1, it uses a rejection method developed by Minh(1988)"Generating
* Gamma Variates", ACM Trans. on Math. Software, Vol.14, No.3, pp261-266.
* <br>
* If a<1, it uses the algorithm "GS" developed by Ahrens and Dieter(1974)
* "COMPUTER METHODS FOR SAMPLING FROM GAMMA, BETA, POISSON AND BINOMIAL
* DISTRIBUTIONS", COMPUTING, 12 (1974), pp223-246, and further implemented
* in Fortran by Ahrens, Kohrt and Dieter(1983) "Algorithm 599: sampling
* from Gamma and Poisson distributions", ACM Trans. on Math. Software,
* Vol.9 No.2, pp255-257.<p>
*
* Variates related to standard Gamma can be generated using simple
* transformations.
*
* @param a the shape parameter, must be greater than 1
* @return a value of the variate
* @exception Exception if parameter not greater than 1
*/
public double nextGamma(double a) throws Exception{
if(a<=0.0)
throw new Exception("Shape parameter of Gamma distribution"+
"must be greater than 0!");
else if (a==1.0)
return nextExponential();
else if (a<1.0){
double b=1.0+Math.exp(-1.0)*a, p,x, condition;
do{
p=b*super.nextDouble();
if(p<1.0){
x = Math.exp(Math.log(p)/a);
condition = x;
}
else{
x = -Math.log((b-p)/a);
condition = (1.0-a)*Math.log(x);
}
}
while(nextExponential() < condition);
return x;
}
else{ // a>1
double b=a-1.0, D=Math.sqrt(b), D1,x1,x2,xl,f1,f2,x4,x5,xr,f4,f5,
p1,p2,p3,p4;
// Initialization
if(a<=2.0){
D1 = b/2.0;
x1 = 0.0;
x2 = D1;
xl = -1.0;
f1 = 0.0;
}
else{
D1 = D-0.5;
x2 = b-D1;
x1 = x2-D1;
xl = 1.0-b/x1;
f1 = Math.exp(b*Math.log(x1/b)+2.0*D1);
}
f2=Math.exp(b*Math.log(x2/b)+D1);
x4 = b+D;
x5 = x4+D;
xr = 1.0-b/x5;
f4 = Math.exp(b*Math.log(x4/b)-D);
f5 = Math.exp(b*Math.log(x5/b)-2.0*D);
p1 = 2.0*f4*D;
p2 = 2.0*f2*D1+p1;
p3 = f5/xr+p2;
p4 = -f1/xl+p3;
// Generation
double u, w=Double.MAX_VALUE, x=b, v, xp;
while(Math.log(w) > (b*Math.log(x/b)+b-x) || x < 0.0){
u=super.nextDouble()*p4;
if(u<=p1){ // step 5-6
w = u/D-f4;
if(w<=0.0) return (b+u/f4);
if(w<=f5) return (x4+(w*D)/f5);
v = super.nextDouble();
x=x4+v*D;
xp=2.0*x4-x;
if(w >= f4+(f4-1)*(x-x4)/(x4-b))
return xp;
if(w <= f4+(b/x4-1)*f4*(x-x4))
return x;
if((w < 2.0*f4-1.0) ||
(w < 2.0*f4-Math.exp(b*Math.log(xp/b)+b-xp)))
continue;
return xp;
}
else if(u<=p2){ // step 7-8
w = (u-p1)/D1-f2;
if(w<=0.0) return (b-(u-p1)/f2);
if(w<=f1) return (x1+w*D1/f1);
v = super.nextDouble();
x=x1+v*D1;
xp=2.0*x2-x;
if(w >= f2+(f2-1)*(x-x2)/(x2-b))
return xp;
if(w <= f2*(x-x1)/D1)
return x;
if((w < 2.0*f2-1.0) ||
(w < 2.0*f2-Math.exp(b*Math.log(xp/b)+b-xp)))
continue;
return xp;
}
else if(u<p3){ // step 9
w = super.nextDouble();
u = (p3-u)/(p3-p2);
x = x5-Math.log(u)/xr;
if(w <= (xr*(x5-x)+1.0)/u) return x;
w = w*f5*u;
}
else{ // step 10
w = super.nextDouble();
u = (p4-u)/(p4-p3);
x = x1-Math.log(u)/xl;
if(x<0.0) continue;
if(w <= (xl*(x1-x)+1.0)/u) return x;
w = w*f1*u;
}
}
return x;
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param ops # of variates/seed, default is 10/45
*/
public static void main(String[] ops) {
int n = Integer.parseInt(ops[0]);
if(n<=0)
n=10;
long seed = Long.parseLong(ops[1]);
if(seed <= 0)
seed = 45;
RandomVariates var = new RandomVariates(seed);
double varb[] = new double[n];
try {
System.out.println("Generate "+n+" values with std. exp dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextExponential();
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+
"\n\nGenerate "+n+" values with"+
" std. Erlang-5 dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextErlang(5);
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+
"\n\nGenerate "+n+" values with"+
" std. Gamma(4.5) dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextGamma(4.5);
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+
"\n\nGenerate "+n+" values with"+
" std. Gamma(0.5) dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextGamma(0.5);
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+
"\n\nGenerate "+n+" values with"+
" std. Gaussian(5, 2) dist:");
for(int i=0; i<n; i++){
varb[i] = var.nextGaussian()*2.0+5.0;
System.out.print("["+i+"] "+varb[i]+", ");
}
System.out.println("\nMean is "+Utils.mean(varb)+
", Variance is "+Utils.variance(varb)+"\n");
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Randomizable.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Randomizable.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Interface to something that has random behaviour that is able to be
* seeded with an integer.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface Randomizable {
/**
* Set the seed for random number generation.
*
* @param seed the seed
*/
void setSeed(int seed);
/**
* Gets the seed for the random number generations
*
* @return the seed for the random number generation
*/
int getSeed();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Range.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Range.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
/**
* Class representing a range of cardinal numbers. The range is set by a string
* representation such as:
* <P>
*
* <code>
* first-last
* 1,2,3,4
* </code>
* <P>
* or combinations thereof. The range is internally converted from 1-based to
* 0-based (so methods that set or get numbers not in string format should use
* 0-based numbers).
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Range implements Serializable, RevisionHandler,
CustomDisplayStringProvider {
/** for serialization. */
static final long serialVersionUID = 3667337062176835900L;
/** Record the string representations of the columns to delete. */
/* @non_null spec_public@ */ArrayList<String> m_RangeStrings = new ArrayList<String>();
/** Whether matching should be inverted. */
/* @spec_public@ */boolean m_Invert;
/** The array of flags for whether an column is selected. */
/* @spec_public@ */boolean[] m_SelectFlags;
/**
* Store the maximum value permitted in the range. -1 indicates that no upper
* value has been set
*/
/* @spec_public@ */int m_Upper = -1;
/** Default constructor. */
// @assignable this.*;
public Range() {
}
/**
* Constructor to set initial range.
*
* @param rangeList the initial range
* @throws IllegalArgumentException if the range list is invalid
*/
public Range(/* @non_null@ */String rangeList) {
setRanges(rangeList);
}
/**
* Sets the value of "last".
*
* @param newUpper the value of "last"
*/
public void setUpper(int newUpper) {
if (newUpper >= 0) {
m_Upper = newUpper;
setFlags();
}
}
/**
* Gets whether the range sense is inverted, i.e. all <i>except</i> the values
* included by the range string are selected.
*
* @return whether the matching sense is inverted
*/
// @ensures \result <==> m_Invert;
public/* @pure@ */boolean getInvert() {
return m_Invert;
}
/**
* Sets whether the range sense is inverted, i.e. all <i>except</i> the values
* included by the range string are selected.
*
* @param newSetting true if the matching sense is inverted
*/
public void setInvert(boolean newSetting) {
m_Invert = newSetting;
}
/**
* Gets the string representing the selected range of values.
*
* @return the range selection string
*/
public/* @non_null pure@ */String getRanges() {
StringBuffer result = new StringBuffer(m_RangeStrings.size() * 4);
boolean first = true;
char sep = ',';
for (int i = 0; i < m_RangeStrings.size(); i++) {
if (first) {
result.append(m_RangeStrings.get(i));
first = false;
} else {
result.append(sep + m_RangeStrings.get(i));
}
}
return result.toString();
}
/**
* Sets the ranges from a string representation. Note that setUpper() must be
* called afterwards for ranges to be actually set internally.
*
* @param rangeList the comma separated list of ranges. The empty string sets
* the range to empty.
* @throws IllegalArgumentException if the rangeList was not well formed
*/
// @requires rangeList != null;
// @assignable m_RangeStrings,m_SelectFlags;
public void setRanges(String rangeList) {
ArrayList<String> ranges = new ArrayList<String>(10);
// Split the rangeList up into the vector
while (!rangeList.equals("")) {
String range = rangeList.trim();
int commaLoc = rangeList.indexOf(',');
if (commaLoc != -1) {
range = rangeList.substring(0, commaLoc).trim();
rangeList = rangeList.substring(commaLoc + 1).trim();
} else {
rangeList = "";
}
if (!range.equals("")) {
ranges.add(range);
}
}
m_RangeStrings = ranges;
m_SelectFlags = null;
}
/**
* Gets whether the supplied cardinal number is included in the current range.
*
* @param index the number of interest
* @return true if index is in the current range
* @throws RuntimeException if the upper limit of the range hasn't been
* defined
*/
// @requires m_Upper >= 0;
// @requires 0 <= index && index < m_SelectFlags.length;
public/* @pure@ */boolean isInRange(int index) {
if (m_Upper == -1) {
throw new RuntimeException("No upper limit has been specified for range");
}
if (m_Invert) {
return !m_SelectFlags[index];
} else {
return m_SelectFlags[index];
}
}
/**
* Constructs a representation of the current range. Being a string
* representation, the numbers are based from 1.
*
* @return the string representation of the current range
*/
@Override
public/* @non_null pure@ */String toString() {
if (m_RangeStrings.size() == 0) {
return "Empty";
}
String result = "Strings: ";
Iterator<String> enu = m_RangeStrings.iterator();
while (enu.hasNext()) {
result += enu.next() + " ";
}
result += "\n";
result += "Invert: " + m_Invert + "\n";
try {
if (m_Upper == -1) {
throw new RuntimeException("Upper limit has not been specified");
}
String cols = null;
for (int i = 0; i < m_SelectFlags.length; i++) {
if (isInRange(i)) {
if (cols == null) {
cols = "Cols: " + (i + 1);
} else {
cols += "," + (i + 1);
}
}
}
if (cols != null) {
result += cols + "\n";
}
} catch (Exception ex) {
result += ex.getMessage();
}
return result;
}
/**
* Gets an array containing all the selected values, in the order that they
* were selected (or ascending order if range inversion is on).
*
* @return the array of selected values
* @throws RuntimeException if the upper limit of the range hasn't been
* defined
*/
// @requires m_Upper >= 0;
public/* @non_null@ */int[] getSelection() {
if (m_Upper == -1) {
throw new RuntimeException("No upper limit has been specified for range");
}
int[] selectIndices = new int[m_Upper + 1];
int numSelected = 0;
if (m_Invert) {
for (int i = 0; i <= m_Upper; i++) {
if (!m_SelectFlags[i]) {
selectIndices[numSelected++] = i;
}
}
} else {
Iterator<String> enu = m_RangeStrings.iterator();
while (enu.hasNext()) {
String currentRange = enu.next();
int start = rangeLower(currentRange);
int end = rangeUpper(currentRange);
for (int i = start; (i <= m_Upper) && (i <= end); i++) {
if (m_SelectFlags[i]) {
selectIndices[numSelected++] = i;
}
}
}
}
int[] result = new int[numSelected];
System.arraycopy(selectIndices, 0, result, 0, numSelected);
return result;
}
/**
* Creates a string representation of the indices in the supplied array.
*
* @param indices an array containing indices to select. Since the array will
* typically come from a program, indices are assumed from 0, and
* thus will have 1 added in the String representation.
* @return the string representation of the indices
*/
public static/* @non_null pure@ */String indicesToRangeList(
/* @non_null@ */int[] indices) {
StringBuffer rl = new StringBuffer();
int last = -2;
boolean range = false;
for (int i = 0; i < indices.length; i++) {
if (i == 0) {
rl.append(indices[i] + 1);
} else if (indices[i] == last) {
range = true;
} else {
if (range) {
rl.append('-').append(last);
range = false;
}
rl.append(',').append(indices[i] + 1);
}
last = indices[i] + 1;
}
if (range) {
rl.append('-').append(last);
}
return rl.toString();
}
/** Sets the flags array. */
protected void setFlags() {
m_SelectFlags = new boolean[m_Upper + 1];
Iterator<String> enu = m_RangeStrings.iterator();
while (enu.hasNext()) {
String currentRange = enu.next();
if (!isValidRange(currentRange)) {
throw new IllegalArgumentException("Invalid range list at "
+ currentRange);
}
int start = rangeLower(currentRange);
int end = rangeUpper(currentRange);
for (int i = start; (i <= m_Upper) && (i <= end); i++) {
m_SelectFlags[i] = true;
}
}
}
/**
* Translates a single string selection into it's internal 0-based equivalent.
*
* @param single the string representing the selection (eg: 1 first last)
* @return the number corresponding to the selected value
*/
protected/* @pure@ */int rangeSingle(/* @non_null@ */String single) {
if (single.toLowerCase().equals("first")) {
return 0;
}
if (single.toLowerCase().equals("last")) {
return m_Upper;
}
int index = Integer.parseInt(single) - 1;
if (index < 0) {
index = 0;
}
if (index > m_Upper) {
index = m_Upper;
}
return index;
}
/**
* Translates a range into it's lower index.
*
* @param range the string representation of the range
* @return the lower index of the range
*/
protected int rangeLower(/* @non_null@ */String range) {
int hyphenIndex;
if ((hyphenIndex = range.indexOf('-')) >= 0) {
return Math.min(rangeLower(range.substring(0, hyphenIndex)),
rangeLower(range.substring(hyphenIndex + 1)));
}
return rangeSingle(range);
}
/**
* Translates a range into it's upper index. Must only be called once setUpper
* has been called.
*
* @param range the string representation of the range
* @return the upper index of the range
*/
protected int rangeUpper(/* @non_null@ */String range) {
int hyphenIndex;
if ((hyphenIndex = range.indexOf('-')) >= 0) {
return Math.max(rangeUpper(range.substring(0, hyphenIndex)),
rangeUpper(range.substring(hyphenIndex + 1)));
}
return rangeSingle(range);
}
/**
* Determines if a string represents a valid index or simple range. Examples:
* <code>first last 2 first-last first-4 4-last</code> Doesn't check
* that a < b for a-b
*
* @param range the string to check
* @return true if the range is valid
*/
protected boolean isValidRange(String range) {
if (range == null) {
return false;
}
int hyphenIndex;
if ((hyphenIndex = range.indexOf('-')) >= 0) {
if (isValidRange(range.substring(0, hyphenIndex))
&& isValidRange(range.substring(hyphenIndex + 1))) {
return true;
}
return false;
}
if (range.toLowerCase().equals("first")) {
return true;
}
if (range.toLowerCase().equals("last")) {
return true;
}
try {
int index = Integer.parseInt(range);
if ((index > 0) && (index <= m_Upper + 1)) {
return true;
}
return false;
} catch (NumberFormatException ex) {
return false;
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Returns the custom display string.
*
* @return the string
*/
@Override
public String toDisplay() {
if (getInvert()) {
return "inv(" + getRanges() + ")";
} else {
return getRanges();
}
}
/**
* Main method for testing this class.
*
* @param argv one parameter: a test range specification
*/
public static void main(String[] argv) {
try {
if (argv.length == 0) {
throw new Exception("Usage: Range <rangespec>");
}
Range range = new Range();
range.setRanges(argv[0]);
range.setUpper(9);
range.setInvert(false);
System.out.println("Input: " + argv[0] + "\n" + range.toString());
int[] rangeIndices = range.getSelection();
for (int rangeIndice : rangeIndices) {
System.out.print(" " + (rangeIndice + 1));
}
System.out.println("");
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/RelationalAttributeInfo.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* RelationalAttributeInfo.java
* Copyright (C) 2014 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Stores information for relational attributes.
*/
public class RelationalAttributeInfo extends NominalAttributeInfo {
/** The header information for a relation-valued attribute. */
protected Instances m_Header;
/**
* Constructs the information object based on the given parameter.
*/
public RelationalAttributeInfo(Instances header) {
super(null, null);
m_Header = header;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/RelationalLocator.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* RelationalLocator.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
/**
* This class locates and records the indices of relational attributes,
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Attribute#RELATIONAL
*/
public class RelationalLocator extends AttributeLocator {
/** for serialization */
private static final long serialVersionUID = 4646872277151854732L;
/**
* Initializes the RelationalLocator with the given data.
*
* @param data the data to work on
*/
public RelationalLocator(Instances data) {
super(data, Attribute.RELATIONAL);
}
/**
* Initializes the RelationalLocator with the given data. Checks only the
* given range.
*
* @param data the data to work on
* @param fromIndex the first index to inspect (including)
* @param toIndex the last index to check (including)
*/
public RelationalLocator(Instances data, int fromIndex, int toIndex) {
super(data, Attribute.RELATIONAL, fromIndex, toIndex);
}
/**
* Initializes the RelationalLocator with the given data. Checks only the
* specified attribute indices.
*
* @param data the data to work on
* @param indices the attribute indices to check
*/
public RelationalLocator(Instances data, int[] indices) {
super(data, Attribute.RELATIONAL, indices);
}
/**
* Copies relational values contained in the instance copied to a new dataset.
* The Instance must already be assigned to a dataset. This dataset and the
* destination dataset must have the same structure.
*
* @param inst the Instance containing the relational values to copy.
* @param destDataset the destination set of Instances
* @param strAtts an AttributeLocator containing the indices of any relational
* attributes in the dataset.
*/
public static void copyRelationalValues(Instance inst, Instances destDataset,
AttributeLocator strAtts) {
if (inst.dataset() == null) {
throw new IllegalArgumentException("Instance has no dataset assigned!!");
} else if (inst.dataset().numAttributes() != destDataset.numAttributes()) {
throw new IllegalArgumentException(
"Src and Dest differ in # of attributes: "
+ inst.dataset().numAttributes() + " != "
+ destDataset.numAttributes());
}
copyRelationalValues(inst, true, inst.dataset(), strAtts, destDataset,
strAtts);
}
/**
* Takes relational values referenced by an Instance and copies them from a
* source dataset to a destination dataset. The instance references are
* updated to be valid for the destination dataset. The instance may have the
* structure (i.e. number and attribute position) of either dataset (this
* affects where references are obtained from). Only works if the number of
* relational attributes is the same in both indices (implicitly these
* relational attributes should be semantically same but just with shifted
* positions).
*
* @param instance the instance containing references to relations in the
* source dataset that will have references updated to be valid for
* the destination dataset.
* @param instSrcCompat true if the instance structure is the same as the
* source, or false if it is the same as the destination (i.e. which
* of the relational attribute indices contains the correct locations
* for this instance).
* @param srcDataset the dataset for which the current instance relationvalue
* references are valid (after any position mapping if needed)
* @param srcLoc an AttributeLocator containing the indices of relational
* attributes in the source datset.
* @param destDataset the dataset for which the current instance relation
* references need to be inserted (after any position mapping if
* needed)
* @param destLoc an AttributeLocator containing the indices of relational
* attributes in the destination datset.
*/
public static void copyRelationalValues(Instance instance,
boolean instSrcCompat, Instances srcDataset, AttributeLocator srcLoc,
Instances destDataset, AttributeLocator destLoc) {
if (srcDataset == destDataset) {
return;
}
if (srcLoc.getAttributeIndices().length != destLoc.getAttributeIndices().length) {
throw new IllegalArgumentException(
"Src and Dest relational indices differ in length: "
+ srcLoc.getAttributeIndices().length + " != "
+ destLoc.getAttributeIndices().length);
}
if (srcLoc.getLocatorIndices().length != destLoc.getLocatorIndices().length) {
throw new IllegalArgumentException(
"Src and Dest locator indices differ in length: "
+ srcLoc.getLocatorIndices().length + " != "
+ destLoc.getLocatorIndices().length);
}
for (int i = 0; i < srcLoc.getAttributeIndices().length; i++) {
int instIndex = instSrcCompat ? srcLoc.getActualIndex(srcLoc
.getAttributeIndices()[i]) : destLoc.getActualIndex(destLoc
.getAttributeIndices()[i]);
Attribute src = srcDataset.attribute(srcLoc.getActualIndex(srcLoc
.getAttributeIndices()[i]));
Attribute dest = destDataset.attribute(destLoc.getActualIndex(destLoc
.getAttributeIndices()[i]));
if (!instance.isMissing(instIndex)) {
int valIndex = dest.addRelation(src.relation((int) instance
.value(instIndex)));
instance.setValue(instIndex, valIndex);
}
}
// recurse if necessary
int[] srcIndices = srcLoc.getLocatorIndices();
int[] destIndices = destLoc.getLocatorIndices();
for (int i = 0; i < srcIndices.length; i++) {
int index = instSrcCompat ? srcLoc.getActualIndex(srcIndices[i])
: destLoc.getActualIndex(destIndices[i]);
if (instance.isMissing(index)) {
continue;
}
int valueIndex = (int)instance.value(index);
Instances rel = instSrcCompat ? srcDataset.attribute(index).relation(valueIndex)
: destDataset.attribute(index).relation(valueIndex);
AttributeLocator srcRelAttsNew = srcLoc.getLocator(srcIndices[i]);
Instances srcDatasetNew = srcRelAttsNew.getData();
AttributeLocator destRelAttsNew = destLoc.getLocator(destIndices[i]);
Instances destDatasetNew = destRelAttsNew.getData();
for (int n = 0; n < rel.numInstances(); n++) {
copyRelationalValues(rel.instance(n), instSrcCompat, srcDatasetNew,
srcRelAttsNew, destDatasetNew, destRelAttsNew);
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/RepositoryIndexGenerator.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* RepositoryIndexGenerator.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Class for generating html index files and supporting text files for a Weka
* package meta data repository. To Run<br>
* <br>
*
* <code>java weka.core.RepositoryIndexGenerator <path to repository></code>
* <br><br>
* A file called "forcedRefreshCount.txt" can be used to force a cache-refresh
* for all internet connected users. Just increment the number in this file by
* 1 (or create the file with an initial value of 1 if it doesn't exist yet).
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class RepositoryIndexGenerator {
public static String HEADER =
"<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"
+ "<html>\n<head>\n<title>Waikato Environment for Knowledge Analysis (WEKA)</title>\n"
+ "<!-- CSS Stylesheet -->\n<style>body\n{\nbackground: #ededed;\ncolor: #666666;\n"
+ "font: 14px Tahoma, Helvetica, sans-serif;;\nmargin: 5px 10px 5px 10px;\npadding: 0px;\n"
+ "}\n</style>\n\n</head>\n<body bgcolor=\"#ededed\" text=\"#666666\">\n";
public static String BIRD_IMAGE1 = "<img src=\"Title-Bird-Header.gif\">\n";
public static String BIRD_IMAGE2 = "<img src=\"../Title-Bird-Header.gif\">\n";
public static String PENTAHO_IMAGE1 =
"<img src=\"pentaho_logo_rgb_sm.png\">\n\n";
public static String PENTAHO_IMAGE2 =
"<img src=\"../pentaho_logo_rgb_sm.png\">\n\n";
private static int[] parseVersion(String version) {
int major = 0;
int minor = 0;
int revision = 0;
int[] majMinRev = new int[3];
try {
String tmpStr = version;
tmpStr = tmpStr.replace('-', '.');
if (tmpStr.indexOf(".") > -1) {
major = Integer.parseInt(tmpStr.substring(0, tmpStr.indexOf(".")));
tmpStr = tmpStr.substring(tmpStr.indexOf(".") + 1);
if (tmpStr.indexOf(".") > -1) {
minor = Integer.parseInt(tmpStr.substring(0, tmpStr.indexOf(".")));
tmpStr = tmpStr.substring(tmpStr.indexOf(".") + 1);
if (!tmpStr.equals("")) {
revision = Integer.parseInt(tmpStr);
} else {
revision = 0;
}
} else {
if (!tmpStr.equals("")) {
minor = Integer.parseInt(tmpStr);
} else {
minor = 0;
}
}
} else {
if (!tmpStr.equals("")) {
major = Integer.parseInt(tmpStr);
} else {
major = 0;
}
}
} catch (Exception e) {
e.printStackTrace();
major = -1;
minor = -1;
revision = -1;
} finally {
majMinRev[0] = major;
majMinRev[1] = minor;
majMinRev[2] = revision;
}
return majMinRev;
}
private static String cleansePropertyValue(String propVal) {
propVal = propVal.replace("<", "<");
propVal = propVal.replace(">", ">");
propVal = propVal.replace("@", "{[at]}");
propVal = propVal.replace("\n", "<br/>");
return propVal;
}
protected static int compare(String version1, String version2) {
// parse both of the versions
int[] majMinRev1 = parseVersion(version1);
int[] majMinRev2 = parseVersion(version2);
int result;
if (majMinRev1[0] < majMinRev2[0]) {
result = -1;
} else if (majMinRev1[0] == majMinRev2[0]) {
if (majMinRev1[1] < majMinRev2[1]) {
result = -1;
} else if (majMinRev1[1] == majMinRev2[1]) {
if (majMinRev1[2] < majMinRev2[2]) {
result = -1;
} else if (majMinRev1[2] == majMinRev2[2]) {
result = 0;
} else {
result = 1;
}
} else {
result = 1;
}
} else {
result = 1;
}
return result;
}
private static String[] processPackage(File packageDirectory)
throws Exception {
System.err.println("Processing " + packageDirectory);
File[] contents = packageDirectory.listFiles();
File latest = null;
ArrayList<File> propsFiles = new ArrayList<File>();
StringBuffer versionsTextBuffer = new StringBuffer();
for (File content : contents) {
if (content.isFile() && content.getName().endsWith(".props")) {
propsFiles.add(content);
if (content.getName().equals("Latest.props")) {
latest = content;
} /*
* else { String versionNumber = contents[i].getName().substring(0,
* contents[i].getName().indexOf(".props"));
* versionsTextBuffer.append(versionNumber + "\n"); }
*/
}
}
File[] sortedPropsFiles = propsFiles.toArray(new File[0]);
Arrays.sort(sortedPropsFiles, new Comparator<File>() {
@Override
public int compare(File first, File second) {
String firstV =
first.getName().substring(0, first.getName().indexOf(".props"));
String secondV =
second.getName().substring(0, second.getName().indexOf(".props"));
if (firstV.equalsIgnoreCase("Latest")) {
return -1;
} else if (secondV.equalsIgnoreCase("Latest")) {
return 1;
}
return -RepositoryIndexGenerator.compare(firstV, secondV);
}
});
StringBuffer indexBuff = new StringBuffer();
indexBuff.append(HEADER + "\n\n");
// indexBuff.append(HEADER + BIRD_IMAGE2);
// indexBuff.append(PENTAHO_IMAGE2);
Properties latestProps = new Properties();
latestProps.load(new BufferedReader(new FileReader(latest)));
String packageName = latestProps.getProperty("PackageName") + ": ";
String packageTitle = latestProps.getProperty("Title");
String packageCategory = latestProps.getProperty("Category");
String latestVersion = latestProps.getProperty("Version");
if (packageCategory == null) {
packageCategory = "";
}
indexBuff.append("<h2>" + packageName + packageTitle + "</h2>\n\n");
String author = latestProps.getProperty("Author");
author = cleansePropertyValue(author);
String URL = latestProps.getProperty("URL");
if (URL != null) {
URL = cleansePropertyValue(URL);
}
String maintainer = latestProps.getProperty("Maintainer");
maintainer = cleansePropertyValue(maintainer);
indexBuff.append("\n<table>\n");
if (URL != null && URL.length() > 0) {
indexBuff.append("<tr><td valign=top>" + "URL"
+ ":</td><td width=50></td>");
URL = "<a href=\"" + URL + "\">" + URL + "</a>";
indexBuff.append("<td>" + URL + "</td></tr>\n");
}
indexBuff.append("<tr><td valign=top>" + "Author"
+ ":</td><td width=50></td>");
indexBuff.append("<td>" + author + "</td></tr>\n");
indexBuff.append("<tr><td valign=top>" + "Maintainer"
+ ":</td><td width=50></td>");
indexBuff.append("<td>" + maintainer + "</td></tr>\n");
indexBuff.append("</table>\n<p>\n");
String description = latestProps.getProperty("Description");
indexBuff.append("<p>" + description.replace("\n", "<br/>") + "</p>\n\n");
indexBuff.append("<p>All available versions:<br>\n");
for (int i = 0; i < sortedPropsFiles.length; i++) {
if (i > 0) {
String versionNumber =
sortedPropsFiles[i].getName().substring(0,
sortedPropsFiles[i].getName().indexOf(".props"));
versionsTextBuffer.append(versionNumber + "\n");
System.err.println(versionNumber);
}
String name = sortedPropsFiles[i].getName();
name = name.substring(0, name.indexOf(".props"));
indexBuff.append("<a href=\"" + name + ".html" + "\">" + name
+ "</a><br>\n");
StringBuffer version = new StringBuffer();
version.append(HEADER + "\n\n");
// version.append(HEADER + BIRD_IMAGE2);
// version.append(PENTAHO_IMAGE2);
version.append("<table summary=\"Package " + packageName
+ " summary\">\n");
Properties versionProps = new Properties();
versionProps
.load(new BufferedReader(new FileReader(sortedPropsFiles[i])));
Set<Object> keys = versionProps.keySet();
String[] sortedKeys = keys.toArray(new String[0]);
Arrays.sort(sortedKeys);
// Iterator<Object> keyI = keys.iterator();
// while (keyI.hasNext()) {
for (String key : sortedKeys) {
// String key = (String)keyI.next();
if (key.equalsIgnoreCase("PackageName")
|| key.equalsIgnoreCase("Title") ||
/* key.equalsIgnoreCase("Description") || */
key.equalsIgnoreCase("DoNotLoadIfFileNotPresentMessage")
|| key.equalsIgnoreCase("DoNotLoadIfClassNotPresentMessage")
|| key.equalsIgnoreCase("DoNotLoadIfEnvVarNotSetMessage")) {
} else {
version.append("<tr><td valign=top>" + key
+ ":</td><td width=50></td>");
String propValue = versionProps.getProperty(key);
if (!key.equalsIgnoreCase("Description")) {
propValue = propValue.replace("<", "<");
propValue = propValue.replace(">", ">");
propValue = propValue.replace("@", "{[at]}");
propValue = propValue.replace("\n", "<br/>");
}
/*
* if (key.equals("Author") || key.equals("Maintainer")) { propValue =
* propValue.replace(".", "{[dot]}"); }
*/
if (key.equals("PackageURL") || key.equals("URL")) {
propValue = "<a href=\"" + propValue + "\">" + propValue + "</a>";
}
version.append("<td>" + propValue + "</td></tr>\n");
}
}
version.append("</table>\n</body>\n</html>\n");
String versionHTMLFileName =
packageDirectory.getAbsolutePath() + File.separator + name + ".html";
BufferedWriter br =
new BufferedWriter(new FileWriter(versionHTMLFileName));
br.write(version.toString());
br.flush();
br.close();
}
indexBuff.append("</body>\n</html>\n");
String packageIndexName =
packageDirectory.getAbsolutePath() + File.separator + "index.html";
BufferedWriter br = new BufferedWriter(new FileWriter(packageIndexName));
br.write(indexBuff.toString());
br.flush();
br.close();
// write the versions file to the directory
String packageVersionsName =
packageDirectory.getAbsolutePath() + File.separator + "versions.txt";
br = new BufferedWriter(new FileWriter(packageVersionsName));
br.write(versionsTextBuffer.toString());
br.flush();
br.close();
// return indexBuff.toString();
String[] returnInfo = new String[3];
returnInfo[0] = packageTitle;
returnInfo[1] = packageCategory;
returnInfo[2] = latestVersion;
return returnInfo;
}
private static void writeMainIndex(Map<String, String[]> packages,
File repositoryHome) throws Exception {
StringBuffer indexBuf = new StringBuffer();
StringBuffer packageList = new StringBuffer();
// new package list that includes version number of latest version of each
// package. We keep the old package list as well for backwards compatibility
StringBuffer packageListPlusVersion = new StringBuffer();
indexBuf.append(HEADER + BIRD_IMAGE1);
indexBuf.append(PENTAHO_IMAGE1);
indexBuf.append("<h1>WEKA Packages </h1>\n\n");
indexBuf.append(/*
* "<h3>Download WekaLite</h3>\n<a href=\"wekaLite.jar\">wekaLite.jar</a>"
* +
*/
"<p><b>IMPORTANT: make sure there are no old versions of Weka (<3.7.2) in "
+ "your CLASSPATH before starting Weka</b>\n\n");
indexBuf.append("<h3>Installation of Packages</h3>\n");
indexBuf
.append("A GUI package manager is available from the \"Tools\" menu of"
+ " the GUIChooser<br><br><code>java -jar weka.jar</code><p>\n\n");
indexBuf.append("For a command line package manager type"
+ ":<br><br<code>java weka.core.WekaPackageManager -h"
+ "</code><br><br>\n");
indexBuf.append("<hr/>\n");
indexBuf
.append("<h3>Running packaged algorithms from the command line</h3>"
+ "<code>java weka.Run [algorithm name]</code><p>"
+ "Substring matching is also supported. E.g. try:<br><br>"
+ "<code>java weka.Run Bayes</code><hr/>");
Set<String> names = packages.keySet();
indexBuf.append("<h3>Available Packages (" + packages.keySet().size()
+ ")</h3>\n\n");
indexBuf.append("<table>\n");
Iterator<String> i = names.iterator();
while (i.hasNext()) {
String packageName = i.next();
String[] info = packages.get(packageName);
String packageTitle = info[0];
String packageCategory = info[1];
String latestVersion = info[2];
String href =
"<a href=\"./" + packageName + "/index.html\">" + packageName + "</a>";
indexBuf.append("<tr valign=\"top\">\n");
indexBuf.append("<td>" + href + "</td><td width=50></td><td>"
+ packageCategory + "</td><td width=50></td><td>" + packageTitle
+ "</td></tr>\n");
// append to the package list
packageList.append(packageName + "\n");
packageListPlusVersion.append(packageName).append(":")
.append(latestVersion).append("\n");
}
indexBuf.append("</table>\n<hr/>\n</body></html>\n");
String indexName =
repositoryHome.getAbsolutePath() + File.separator + "index.html";
BufferedWriter br = new BufferedWriter(new FileWriter(indexName));
br.write(indexBuf.toString());
br.flush();
br.close();
String packageListName =
repositoryHome.getAbsolutePath() + File.separator + "packageList.txt";
br = new BufferedWriter(new FileWriter(packageListName));
br.write(packageList.toString());
br.flush();
br.close();
packageListName =
repositoryHome.getAbsolutePath() + File.separator
+ "packageListWithVersion.txt";
br = new BufferedWriter(new FileWriter(packageListName));
br.write(packageListPlusVersion.toString());
br.flush();
br.close();
String numPackagesName =
repositoryHome.getAbsolutePath() + File.separator + "numPackages.txt";
br = new BufferedWriter(new FileWriter(numPackagesName));
br.write(packages.keySet().size() + "\n");
br.flush();
br.close();
// create zip archive
writeRepoZipFile(repositoryHome, packageList);
}
private static void transBytes(BufferedInputStream bi, ZipOutputStream z)
throws Exception {
int b;
while ((b = bi.read()) != -1) {
z.write(b);
}
}
protected static void writeZipEntryForPackage(File repositoryHome,
String packageName, ZipOutputStream zos) throws Exception {
ZipEntry packageDir = new ZipEntry(packageName + "/");
zos.putNextEntry(packageDir);
ZipEntry z = new ZipEntry(packageName + "/Latest.props");
ZipEntry z2 = new ZipEntry(packageName + "/Latest.html");
FileInputStream fi =
new FileInputStream(repositoryHome.getAbsolutePath() + File.separator
+ packageName + File.separator + "Latest.props");
BufferedInputStream bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
fi =
new FileInputStream(repositoryHome.getAbsolutePath() + File.separator
+ packageName + File.separator + "Latest.html");
bi = new BufferedInputStream(fi);
zos.putNextEntry(z2);
transBytes(bi, zos);
bi.close();
// write the versions.txt file to the zip
z = new ZipEntry(packageName + "/versions.txt");
fi = new FileInputStream(packageName + File.separator + "versions.txt");
bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
// write the index.html to the zip
z = new ZipEntry(packageName + "/index.html");
fi =
new FileInputStream(repositoryHome.getAbsolutePath() + File.separator
+ packageName + File.separator + "index.html");
bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
// Now process the available versions
FileReader vi =
new FileReader(repositoryHome.getAbsolutePath() + File.separator
+ packageName + File.separator + "versions.txt");
BufferedReader bvi = new BufferedReader(vi);
String version;
while ((version = bvi.readLine()) != null) {
z = new ZipEntry(packageName + "/" + version + ".props");
fi =
new FileInputStream(repositoryHome.getAbsolutePath() + File.separator
+ packageName + File.separator + version + ".props");
bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
z = new ZipEntry(packageName + "/" + version + ".html");
fi =
new FileInputStream(repositoryHome.getAbsolutePath() + File.separator
+ packageName + File.separator + version + ".html");
bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
}
bvi.close();
}
protected static void writeRepoZipFile(File repositoryHome,
StringBuffer packagesList) {
System.out.print("Writing repo archive");
StringReader r = new StringReader(packagesList.toString());
BufferedReader br = new BufferedReader(r);
String packageName;
try {
FileOutputStream fo =
new FileOutputStream(repositoryHome.getAbsolutePath() + File.separator
+ "repo.zip");
ZipOutputStream zos = new ZipOutputStream(fo);
while ((packageName = br.readLine()) != null) {
writeZipEntryForPackage(repositoryHome, packageName, zos);
System.out.print(".");
}
System.out.println();
// include the package list (legacy) in the zip
ZipEntry z = new ZipEntry("packageList.txt");
FileInputStream fi =
new FileInputStream(repositoryHome.getAbsolutePath() + File.separator
+ "packageList.txt");
BufferedInputStream bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
// include the package list with latest version numbers
z = new ZipEntry("packageListWithVersion.txt");
fi =
new FileInputStream(repositoryHome.getAbsolutePath() + File.separator
+ "packageListWithVersion.txt");
bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
// include the forced refresh count file (if it exists)
File forced =
new File(repositoryHome.getAbsolutePath() + File.separator
+ WekaPackageManager.FORCED_REFRESH_COUNT_FILE);
if (forced.exists()) {
z = new ZipEntry(WekaPackageManager.FORCED_REFRESH_COUNT_FILE);
fi = new FileInputStream(forced);
bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
}
// Include the top level images
FileReader fr =
new FileReader(repositoryHome.getAbsolutePath() + File.separator
+ "images.txt");
br = new BufferedReader(fr);
String imageName;
while ((imageName = br.readLine()) != null) {
z = new ZipEntry(imageName);
fi =
new FileInputStream(repositoryHome.getAbsolutePath() + File.separator
+ imageName);
bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
}
// include the image list in the zip
z = new ZipEntry("images.txt");
fi =
new FileInputStream(repositoryHome.getAbsolutePath() + File.separator
+ "images.txt");
bi = new BufferedInputStream(fi);
zos.putNextEntry(z);
transBytes(bi, zos);
bi.close();
zos.close();
File f =
new File(repositoryHome.getAbsolutePath() + File.separator + "repo.zip");
long size = f.length();
// write the size of the repo (in KB) to a file
FileWriter fw =
new FileWriter(repositoryHome.getAbsolutePath() + File.separator
+ "repoSize.txt");
if (size > 1024) {
size /= 1024;
}
fw.write("" + size);
fw.flush();
fw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Main method for running the RepositoryIndexGenerator
*
* @param args first argument needs to be the path the the repository.
*/
public static void main(String[] args) {
try {
if (args.length < 1) {
System.err
.println("Usage:\n\n\tRepositoryIndexGenerator <path to repository>");
System.exit(1);
}
File repositoryHome = new File(args[0]);
TreeMap<String, String[]> packages = new TreeMap<String, String[]>();
// ArrayList<File> packages = new ArrayList<File>();
File[] contents = repositoryHome.listFiles();
for (File content : contents) {
if (content.isDirectory()) {
// packages.add(contents[i]);
// process this package and create its index
String[] packageInfo = processPackage(content);
packages.put(content.getName(), packageInfo);
}
}
// write the main index file
writeMainIndex(packages, repositoryHome);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/ResampleUtils.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* ResampleUtils.java
* Copyright (C) 2015 University of Waikato, Hamilton, NZ
*/
package weka.core;
import java.util.Random;
/**
* Helper class for resampling.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class ResampleUtils {
/**
* Checks whether there are any instance weights other than 1.0 set.
*
* @param insts the dataset to check
* @return true if instance weights other than 1.0 are set
*/
public static boolean hasInstanceWeights(final Instances insts) {
boolean result = false;
for (int i = 0; i < insts.numInstances(); i++) {
if (insts.instance(i).weight() != 1.0) {
result = true;
break;
}
}
return result;
}
/**
* Resamples the dataset using {@link Instances#resampleWithWeights(Random)}
* if there are any instance weights other than 1.0 set. Simply returns the
* dataset if no instance weights other than 1.0 are set.
*
* @param insts the dataset to resample
* @param rand the random number generator to use
* @return the (potentially) resampled dataset
* @throws InterruptedException
*/
public static Instances resampleWithWeightIfNecessary(final Instances insts, final Random rand) throws InterruptedException {
if (hasInstanceWeights(insts)) {
return insts.resampleWithWeights(rand);
} else {
return insts;
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/ResourceUtils.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* ResourceUtils.java
* Copyright (C) 2017 University of Waikato, Hamilton, NZ
*/
package weka.core;
import weka.Run;
import java.io.File;
import java.io.FileInputStream;
import java.lang.reflect.Array;
import java.net.URL;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
/**
* Helper for resources.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class ResourceUtils {
/**
* Creates a new instance of an object given it's class name and (optional)
* arguments to pass to it's setOptions method. If the object implements
* OptionHandler and the options parameter is non-null, the object will have
* it's options set. Example use:
* <p>
*
* <code> <pre>
* String classifierName = Utils.getOption('W', options);
* Classifier c = (Classifier)Utils.forName(Classifier.class,
* classifierName,
* options);
* setClassifier(c);
* </pre></code>
*
* @param classType the class that the instantiated object should be
* assignable to -- an exception is thrown if this is not the case
* @param className the fully qualified class name of the object
* @param options an array of options suitable for passing to setOptions. May
* be null. Any options accepted by the object will be removed from
* the array.
* @return the newly created object, ready for use (if it is an array, it will
* have size zero).
* @exception Exception if the class name is invalid, or if the class is not
* assignable to the desired class type, or the options supplied
* are not acceptable to the object
*/
public static Object forName(Class<?> classType, String className,
String[] options) throws Exception {
if (System.getProperty("weka.test.maventest", "").equalsIgnoreCase("true")) {
return forNameNoSchemeMatch(classType, className, options);
}
List<String> matches =
Run.findSchemeMatch(classType, className, false, true);
if (matches.size() == 0) {
// Could be an array class type, which is not covered by findSchemeMatch()
Class c = WekaPackageClassLoaderManager.forName(className);
if (c.isArray() && (classType == null || classType.isAssignableFrom(c))) {
return Array.newInstance(c.getComponentType(), 0);
}
throw new Exception("Can't find a permissible class called: " + className);
}
if (matches.size() > 1) {
StringBuffer sb =
new StringBuffer("More than one possibility matched '" + className
+ "':\n");
for (String s : matches) {
sb.append(" " + s + '\n');
}
throw new Exception(sb.toString());
}
className = matches.get(0);
Class<?> c = null;
try {
// c = Class.forName(className);
c = WekaPackageClassLoaderManager.forName(className);
} catch (Exception ex) {
throw new Exception("Can't find a permissible class called: " + className);
}
Object o = c.newInstance();
if ((o instanceof OptionHandler) && (options != null)) {
((OptionHandler) o).setOptions(options);
Utils.checkForRemainingOptions(options);
}
return o;
}
/**
* Creates a new instance of an object given it's class name and (optional)
* arguments to pass to it's setOptions method. If the object implements
* OptionHandler and the options parameter is non-null, the object will have
* it's options set. Example use:
* <p>
*
* <code> <pre>
* String classifierName = Utils.getOption('W', options);
* Classifier c = (Classifier)Utils.forName(Classifier.class,
* classifierName,
* options);
* setClassifier(c);
* </pre></code>
*
* @param classType the class that the instantiated object should be
* assignable to -- an exception is thrown if this is not the case
* @param className the fully qualified class name of the object
* @param options an array of options suitable for passing to setOptions. May
* be null. Any options accepted by the object will be removed from
* the array.
* @return the newly created object, ready for use.
* @exception Exception if the class name is invalid, or if the class is not
* assignable to the desired class type, or the options supplied
* are not acceptable to the object
*/
@SuppressWarnings("unchecked")
protected static Object forNameNoSchemeMatch(Class classType,
String className, String[] options) throws Exception {
Class c = null;
try {
// c = Class.forName(className);
c = WekaPackageClassLoaderManager.forName(className);
} catch (Exception ex) {
throw new Exception("Can't find class called: " + className);
}
if (classType != null && !classType.isAssignableFrom(c)) {
throw new Exception(classType.getName() + " is not assignable from "
+ className);
}
Object o = c.newInstance();
if ((o instanceof OptionHandler) && (options != null)) {
((OptionHandler) o).setOptions(options);
Utils.checkForRemainingOptions(options);
}
return o;
}
/**
* Reads properties that inherit from three locations. Properties are first
* defined in the system resource location (i.e. in the CLASSPATH). These
* default properties must exist. Properties optionally defined in the user
* properties location (WekaPackageManager.PROPERTIES_DIR) override default
* settings. Properties defined in the current directory (optional) override
* all these settings.
*
* @param resourceName the location of the resource that should be loaded.
* e.g.: "weka/core/Utils.props". (The use of hardcoded forward
* slashes here is OK - see jdk1.1/docs/guide/misc/resources.html)
* This routine will also look for the file (in this case)
* "Utils.props" in the users home directory and the current
* directory.
* @return the Properties
* @exception Exception if no default properties are defined, or if an error
* occurs reading the properties files.
*/
public static Properties readProperties(String resourceName) throws Exception {
Utils utils = new Utils();
return readProperties(resourceName, utils.getClass().getClassLoader());
}
/**
* Reads properties that inherit from three locations. Properties are first
* defined in the system resource location (i.e. in the CLASSPATH). These
* default properties must exist. Properties optionally defined in the user
* properties location (WekaPackageManager.PROPERTIES_DIR) override default
* settings. Properties defined in the current directory (optional) override
* all these settings.
*
* @param resourceName the location of the resource that should be loaded.
* e.g.: "weka/core/Utils.props". (The use of hardcoded forward
* slashes here is OK - see jdk1.1/docs/guide/misc/resources.html)
* This routine will also look for the file (in this case)
* "Utils.props" in the users home directory and the current
* directory.
* @param loader the class loader to use when loading properties
* @return the Properties
* @exception Exception if no default properties are defined, or if an error
* occurs reading the properties files.
*/
public static Properties readProperties(String resourceName,
ClassLoader loader) throws Exception {
Properties defaultProps = new Properties();
try {
// Apparently hardcoded slashes are OK here
// jdk1.1/docs/guide/misc/resources.html
Enumeration<URL> urls = loader.getResources(resourceName);
boolean first = true;
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
if (first) {
defaultProps.load(url.openStream());
first = false;
} else {
Properties props = new Properties(defaultProps);
props.load(url.openStream());
defaultProps = props;
}
}
} catch (Exception ex) {
System.err.println("Warning, unable to load properties file(s) from "
+ "system resource (Utils.java): " + resourceName);
}
// Hardcoded slash is OK here
// eg: see jdk1.1/docs/guide/misc/resources.html
int slInd = resourceName.lastIndexOf('/');
if (slInd != -1) {
resourceName = resourceName.substring(slInd + 1);
}
// Allow a properties file in the WekaPackageManager.PROPERTIES_DIR to
// override
Properties userProps = new Properties(defaultProps);
if (!WekaPackageManager.PROPERTIES_DIR.exists()) {
WekaPackageManager.PROPERTIES_DIR.mkdir();
}
File propFile =
new File(WekaPackageManager.PROPERTIES_DIR.toString() + File.separator
+ resourceName);
if (propFile.exists()) {
try {
userProps.load(new FileInputStream(propFile));
} catch (Exception ex) {
throw new Exception("Problem reading user properties: " + propFile);
}
}
// Allow a properties file in the current directory to override
Properties localProps = new Properties(userProps);
propFile = new File(resourceName);
if (propFile.exists()) {
try {
localProps.load(new FileInputStream(propFile));
} catch (Exception ex) {
throw new Exception("Problem reading local properties: " + propFile);
}
}
return new EnvironmentProperties(localProps);
}
/**
* Returns the Weka home directory.
*
* @return the home directory
*/
public static File getWekaHome() {
return WekaPackageManager.WEKA_HOME;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/RevisionHandler.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* RevisionHandler.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
/**
* For classes that should return their source control revision.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see weka.core.RevisionUtils
*/
public interface RevisionHandler {
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/RevisionUtils.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* RevisionUtils.java
* Copyright (C) 2008-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
/**
* Contains utility functions for handling revisions.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class RevisionUtils {
/**
* Enumeration of source control types.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public enum Type {
/** unknown source control revision. */
UNKNOWN,
/** CVS. */
CVS,
/** Subversion. */
SUBVERSION;
}
/**
* Extracts the revision string returned by the RevisionHandler.
*
* @param handler the RevisionHandler to get the revision for
* @return the actual revision string
*/
public static String extract(RevisionHandler handler) {
return extract(handler.getRevision());
}
/**
* Extracts the revision string.
*
* @param s the string to get the revision string from
* @return the actual revision string
*/
public static String extract(String s) {
String result;
result = s;
result = result.replaceAll("\\$Revision:", "");
result = result.replaceAll("\\$", "");
result = result.replaceAll(" ", "");
return result;
}
/**
* Determines the type of a (sanitized) revision string returned by the
* RevisionHandler.
*
* @param handler the RevisionHandler to determine the type for
* @return the type, UNKNOWN if it cannot be determined
*/
public static Type getType(RevisionHandler handler) {
return getType(extract(handler));
}
/**
* Determines the type of a (sanitized) revision string. Use extract(String)
* method to extract the revision first before calling this method.
*
* @param revision the revision to get the type for
* @return the type, UNKNOWN if it cannot be determined
* @see #extract(String)
*/
public static Type getType(String revision) {
Type result;
String[] parts;
int i;
result = Type.UNKNOWN;
// subversion?
try {
Integer.parseInt(revision);
result = Type.SUBVERSION;
}
catch (Exception e) {
// ignored
}
// CVS?
if (result == Type.UNKNOWN) {
try {
// must contain at least ONE dot
if (revision.indexOf('.') == -1)
throw new Exception("invalid CVS revision - not dots!");
parts = revision.split("\\.");
// must consist of at least TWO parts/integers
if (parts.length < 2)
throw new Exception("invalid CVS revision - not enough parts separated by dots!");
// try parsing parts of revision string - must be ALL integers
for (i = 0; i < parts.length; i++)
Integer.parseInt(parts[i]);
result = Type.CVS;
}
catch (Exception e) {
// ignored
}
}
return result;
}
/**
* For testing only. The first parameter must be a classname of a
* class implementing the weka.core.RevisionHandler interface.
*
* @param args the commandline arguments
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("\nUsage: " + RevisionUtils.class.getName() + " <classname>\n");
System.exit(1);
}
RevisionHandler handler = (RevisionHandler) Class.forName(args[0]).newInstance();
System.out.println("Type: " + getType(handler));
System.out.println("Revision: " + extract(handler));
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/SelectedTag.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* SelectedTag.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.Serializable;
import java.util.HashSet;
/**
* Represents a selected value from a finite set of values, where each
* value is a Tag (i.e. has some string associated with it). Primarily
* used in schemes to select between alternative behaviours,
* associating names with the alternative behaviours.
*
* @author <a href="mailto:len@reeltwo.com">Len Trigg</a>
* @version $Revision$
*/
public class SelectedTag
implements RevisionHandler, Serializable {
private static final long serialVersionUID = 6947341624626504975L;
/** The index of the selected tag */
protected int m_Selected;
/** The set of tags to choose from */
protected Tag[] m_Tags;
/**
* Creates a new <code>SelectedTag</code> instance.
*
* @param tagID the id of the selected tag.
* @param tags an array containing the possible valid Tags.
* @throws IllegalArgumentException if the selected tag isn't in the array
* of valid values or the IDs/IDStrs are not unique.
*/
public SelectedTag(int tagID, Tag[] tags) {
// are IDs unique?
HashSet<Integer> ID = new HashSet<Integer>();
HashSet<String> IDStr = new HashSet<String>();
for (int i = 0; i < tags.length; i++) {
Integer newID = new Integer(tags[i].getID());
if (!ID.contains(newID)) {
ID.add(newID);
} else {
throw new IllegalArgumentException("The IDs are not unique: " + newID + "!");
}
String IDstring = tags[i].getIDStr();
if (!IDStr.contains(IDstring)) {
IDStr.add(IDstring);
} else {
throw new IllegalArgumentException("The ID strings are not unique: " + IDstring + "!");
}
}
for (int i = 0; i < tags.length; i++) {
if (tags[i].getID() == tagID) {
m_Selected = i;
m_Tags = tags;
return;
}
}
throw new IllegalArgumentException("Selected tag is not valid");
}
/**
* Creates a new <code>SelectedTag</code> instance.
*
* @param tagText the text of the selected tag (case-insensitive).
* @param tags an array containing the possible valid Tags.
* @throws IllegalArgumentException if the selected tag isn't in the array
* of valid values.
*/
public SelectedTag(String tagText, Tag[] tags) {
for (int i = 0; i < tags.length; i++) {
if ( tags[i].getReadable().equalsIgnoreCase(tagText)
|| tags[i].getIDStr().equalsIgnoreCase(tagText) ) {
m_Selected = i;
m_Tags = tags;
return;
}
}
throw new IllegalArgumentException("Selected tag is not valid");
}
/**
* Returns true if this SelectedTag equals another object
*
* @param o the object to compare with
* @return true if the tags and the selected tag are the same
*/
public boolean equals(Object o) {
if ((o == null) || !(o.getClass().equals(this.getClass()))) {
return false;
}
SelectedTag s = (SelectedTag)o;
if ((s.getTags() == m_Tags)
&& (s.getSelectedTag() == m_Tags[m_Selected])) {
return true;
} else {
return false;
}
}
/**
* Gets the selected Tag.
*
* @return the selected Tag.
*/
public Tag getSelectedTag() {
return m_Tags[m_Selected];
}
/**
* Gets the set of all valid Tags.
*
* @return an array containing the valid Tags.
*/
public Tag[] getTags() {
return m_Tags;
}
/**
* returns the selected tag in string representation
*
* @return the selected tag as string
*/
public String toString() {
return getSelectedTag().toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/SerializationHelper.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* SerializationHelper.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.io.*;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.Vector;
/**
* A helper class for determining serialVersionUIDs and checking whether classes
* contain one and/or need one. One can also serialize and deserialize objects
* to and from files or streams.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class SerializationHelper implements RevisionHandler {
/** the field name of serialVersionUID. */
public final static String SERIAL_VERSION_UID = "serialVersionUID";
/**
* checks whether a class is serializable.
*
* @param classname the class to check
* @return true if the class or one of its ancestors implements the
* Serializable interface, otherwise false (also if the class cannot
* be loaded)
*/
public static boolean isSerializable(String classname) {
boolean result;
try {
// result = isSerializable(Class.forName(classname));
result = isSerializable(WekaPackageClassLoaderManager.forName(classname));
} catch (Exception e) {
result = false;
}
return result;
}
/**
* checks whether a class is serializable.
*
* @param c the class to check
* @return true if the class or one of its ancestors implements the
* Serializable interface, otherwise false
*/
public static boolean isSerializable(Class<?> c) {
return InheritanceUtils.hasInterface(Serializable.class, c);
}
/**
* checks whether the given class contains a serialVersionUID.
*
* @param classname the class to check
* @return true if the class contains a serialVersionUID, otherwise false
* (also if the class is not implementing serializable or cannot be
* loaded)
*/
public static boolean hasUID(String classname) {
boolean result;
try {
// result = hasUID(Class.forName(classname));
result = hasUID(WekaPackageClassLoaderManager.forName(classname));
} catch (Exception e) {
result = false;
}
return result;
}
/**
* checks whether the given class contains a serialVersionUID.
*
* @param c the class to check
* @return true if the class contains a serialVersionUID, otherwise false
* (also if the class is not implementing serializable)
*/
public static boolean hasUID(Class<?> c) {
boolean result;
result = false;
if (isSerializable(c)) {
try {
c.getDeclaredField(SERIAL_VERSION_UID);
result = true;
} catch (Exception e) {
result = false;
}
}
return result;
}
/**
* checks whether a class needs to declare a serialVersionUID, i.e., it
* implements the java.io.Serializable interface but doesn't declare a
* serialVersionUID.
*
* @param classname the class to check
* @return true if the class needs to declare one, false otherwise (also if
* the class cannot be loaded!)
*/
public static boolean needsUID(String classname) {
boolean result;
try {
// result = needsUID(Class.forName(classname));
result = needsUID(WekaPackageClassLoaderManager.forName(classname));
} catch (Exception e) {
result = false;
}
return result;
}
/**
* checks whether a class needs to declare a serialVersionUID, i.e., it
* implements the java.io.Serializable interface but doesn't declare a
* serialVersionUID.
*
* @param c the class to check
* @return true if the class needs to declare one, false otherwise
*/
public static boolean needsUID(Class<?> c) {
boolean result;
if (isSerializable(c)) {
result = !hasUID(c);
} else {
result = false;
}
return result;
}
/**
* reads or creates the serialVersionUID for the given class.
*
* @param classname the class to get the serialVersionUID for
* @return the UID, 0L for non-serializable classes (or if the class cannot be
* loaded)
*/
public static long getUID(String classname) {
long result;
try {
// result = getUID(Class.forName(classname));
result = getUID(WekaPackageClassLoaderManager.forName(classname));
} catch (Exception e) {
result = 0L;
}
return result;
}
/**
* reads or creates the serialVersionUID for the given class.
*
* @param c the class to get the serialVersionUID for
* @return the UID, 0L for non-serializable classes
*/
public static long getUID(Class<?> c) {
return ObjectStreamClass.lookup(c).getSerialVersionUID();
}
/**
* serializes the given object to the specified file.
*
* @param filename the file to write the object to
* @param o the object to serialize
* @throws Exception if serialization fails
*/
public static void write(String filename, Object o) throws Exception {
write(new FileOutputStream(filename), o);
}
/**
* serializes the given object to the specified stream.
*
* @param stream the stream to write the object to
* @param o the object to serialize
* @throws Exception if serialization fails
*/
public static void write(OutputStream stream, Object o) throws Exception {
ObjectOutputStream oos;
if (!(stream instanceof BufferedOutputStream)) {
stream = new BufferedOutputStream(stream);
}
oos = new ObjectOutputStream(stream);
oos.writeObject(o);
oos.flush();
oos.close();
}
/**
* serializes the given objects to the specified file.
*
* @param filename the file to write the object to
* @param o the objects to serialize
* @throws Exception if serialization fails
*/
public static void writeAll(String filename, Object[] o) throws Exception {
writeAll(new FileOutputStream(filename), o);
}
/**
* serializes the given objects to the specified stream.
*
* @param stream the stream to write the object to
* @param o the objects to serialize
* @throws Exception if serialization fails
*/
public static void writeAll(OutputStream stream, Object[] o) throws Exception {
ObjectOutputStream oos;
int i;
if (!(stream instanceof BufferedOutputStream)) {
stream = new BufferedOutputStream(stream);
}
oos = new ObjectOutputStream(stream);
for (i = 0; i < o.length; i++) {
oos.writeObject(o[i]);
}
oos.flush();
oos.close();
}
/**
* deserializes the given file and returns the object from it.
*
* @param filename the file to deserialize from
* @return the deserialized object
* @throws Exception if deserialization fails
*/
public static Object read(String filename) throws Exception {
return read(new FileInputStream(filename));
}
/**
* deserializes from the given stream and returns the object from it.
*
* @param stream the stream to deserialize from
* @return the deserialized object
* @throws Exception if deserialization fails
*/
public static Object read(InputStream stream) throws Exception {
ObjectInputStream ois;
Object result;
ois = getObjectInputStream(stream);
result = ois.readObject();
ois.close();
return result;
}
/**
* Checks to see if the supplied package class loader (or any of its dependent
* package class loaders) has the given third party class.
*
* @param className the name of the third-party class to check for
* @param l the third party class loader
* @return the class loader that owns the named third-party class, or null if
* not found.
*/
public static ClassLoader checkForThirdPartyClass(String className,
WekaPackageLibIsolatingClassLoader l) {
ClassLoader result = null;
if (l.hasThirdPartyClass(className)) {
return l;
}
for (WekaPackageLibIsolatingClassLoader dep : l
.getPackageClassLoadersForDependencies()) {
result = checkForThirdPartyClass(className, dep);
if (result != null) {
break;
}
}
return result;
}
/**
* Get a (Weka package classloader aware) {@code ObjectInputStream} instance
* for reading objects from the supplied input stream
*
* @param stream the stream to wrap
* @return an {@code ObjectInputStream} instance that is aware of of Weka
* package classloaders
* @throws IOException if a problem occurs
*/
public static ObjectInputStream getObjectInputStream(InputStream stream)
throws IOException {
if (!(stream instanceof BufferedInputStream)) {
stream = new BufferedInputStream(stream);
}
return new ObjectInputStream(stream) {
protected Set<WekaPackageLibIsolatingClassLoader> m_thirdPartyLoaders =
new LinkedHashSet<>();
@Override
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
// make sure that the type descriptor for arrays gets removed from
// what we're going to look up!
String arrayStripped =
desc.getName().replace("[L", "").replace("[", "").replace(";", "");
ClassLoader cl =
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.getLoaderForClass(arrayStripped);
if (cl instanceof WekaPackageLibIsolatingClassLoader) {
// might be third-party classes involved, store the classloader
m_thirdPartyLoaders
.add((WekaPackageLibIsolatingClassLoader) cl);
}
Class<?> result = null;
try {
result = Class.forName(desc.getName(), true, cl);
} catch (ClassNotFoundException ex) {
for (WekaPackageLibIsolatingClassLoader l : m_thirdPartyLoaders) {
ClassLoader checked =
checkForThirdPartyClass(arrayStripped, l);
if (checked != null) {
result = Class.forName(desc.getName(), true, checked);
}
}
}
if (result == null) {
throw new ClassNotFoundException("Unable to find class "
+ arrayStripped);
}
return result;
}
};
}
/**
* deserializes the given file and returns the objects from it.
*
* @param filename the file to deserialize from
* @return the deserialized objects
* @throws Exception if deserialization fails
*/
public static Object[] readAll(String filename) throws Exception {
return readAll(new FileInputStream(filename));
}
/**
* deserializes from the given stream and returns the object from it.
*
* @param stream the stream to deserialize from
* @return the deserialized object
* @throws Exception if deserialization fails
*/
public static Object[] readAll(InputStream stream) throws Exception {
ObjectInputStream ois;
Vector<Object> result;
ois = getObjectInputStream(stream);
result = new Vector<Object>();
try {
while (true) {
result.add(ois.readObject());
}
} catch (IOException e) {
// ignored
}
ois.close();
return result.toArray(new Object[result.size()]);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Outputs information about a class on the commandline, takes class name as
* arguments.
*
* @param args the classnames to check
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
if (args.length == 0) {
System.out.println("\nUsage: " + SerializationHelper.class.getName()
+ " classname [classname [classname [...]]]\n");
System.exit(1);
}
// check all the classes
System.out.println();
for (String arg : args) {
System.out.println(arg);
System.out.println("- is serializable: " + isSerializable(arg));
System.out.println("- has " + SERIAL_VERSION_UID + ": " + hasUID(arg));
System.out
.println("- needs " + SERIAL_VERSION_UID + ": " + needsUID(arg));
System.out.println("- " + SERIAL_VERSION_UID
+ ": private static final long serialVersionUID = " + getUID(arg)
+ "L;");
System.out.println();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/SerializedObject.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* SerializedObject.java
* Copyright (C) 2001-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import weka.core.scripting.Jython;
import weka.core.scripting.JythonSerializableObject;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Class for storing an object in serialized form in memory. It can be used to
* make deep copies of objects, and also allows compression to conserve memory.
* <p>
*
* @author Richard Kirkby (rbk1@cs.waikato.ac.nz)
* @version $Revision$
*/
public class SerializedObject implements Serializable, RevisionHandler {
/** for serialization */
private static final long serialVersionUID = 6635502953928860434L;
/** The array storing the object. */
private byte[] m_storedObjectArray;
/** Whether or not the object is compressed. */
private boolean m_isCompressed;
/** Whether it is a Jython object or not */
private boolean m_isJython;
/**
* Creates a new serialized object (without compression).
*
* @param toStore the object to store
* @exception Exception if the object couldn't be serialized
*/
public SerializedObject(Object toStore) throws Exception {
this(toStore, false);
}
/**
* Creates a new serialized object.
*
* @param toStore the object to store
* @param compress whether or not to use compression
* @exception Exception if the object couldn't be serialized
*/
public SerializedObject(Object toStore, boolean compress) throws Exception {
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
OutputStream os = ostream;
ObjectOutputStream p;
if (!compress)
p = new ObjectOutputStream(new BufferedOutputStream(os));
else
p =
new ObjectOutputStream(new BufferedOutputStream(
new GZIPOutputStream(os)));
p.writeObject(toStore);
p.flush();
p.close(); // used to be ostream.close() !
m_storedObjectArray = ostream.toByteArray();
m_isCompressed = compress;
m_isJython = (toStore instanceof JythonSerializableObject);
}
/*
* Checks to see whether this object is equal to another.
*
* @param compareTo the object to compare to
*
* @return whether or not the objects are equal
*/
public final boolean equals(Object compareTo) {
if (compareTo == null)
return false;
if (!compareTo.getClass().equals(this.getClass()))
return false;
byte[] compareArray = ((SerializedObject) compareTo).m_storedObjectArray;
if (compareArray.length != m_storedObjectArray.length)
return false;
for (int i = 0; i < compareArray.length; i++) {
if (compareArray[i] != m_storedObjectArray[i])
return false;
}
return true;
}
/**
* Returns a hashcode for this object.
*
* @return the hashcode
*/
public int hashCode() {
return m_storedObjectArray.length;
}
/**
* Returns a serialized object. Uses org.python.util.PythonObjectInputStream
* for Jython objects (read <a
* href="http://aspn.activestate.com/ASPN/Mail/Message/Jython-users/1001401"
* >here</a> for more details).
*
* @return the restored object
*/
public Object getObject() {
try {
ByteArrayInputStream istream =
new ByteArrayInputStream(m_storedObjectArray);
ObjectInputStream p;
Object toReturn = null;
if (m_isJython) {
if (!m_isCompressed)
toReturn = Jython.deserialize(new BufferedInputStream(istream));
else
toReturn =
Jython.deserialize(new BufferedInputStream(new GZIPInputStream(
istream)));
} else {
if (!m_isCompressed)
p = new ObjectInputStream(new BufferedInputStream(istream)) {
protected Set<WekaPackageLibIsolatingClassLoader> m_thirdPartyLoaders =
new LinkedHashSet<>();
@Override
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
// make sure that the type descriptor for arrays gets removed from
// what we're going to look up!
String arrayStripped =
desc.getName().replace("[L", "").replace("[", "")
.replace(";", "");
ClassLoader cl =
WekaPackageClassLoaderManager
.getWekaPackageClassLoaderManager().getLoaderForClass(
arrayStripped);
if (cl instanceof WekaPackageLibIsolatingClassLoader) {
// might be third-party classes involved, store the classloader
m_thirdPartyLoaders
.add((WekaPackageLibIsolatingClassLoader) cl);
}
Class<?> result = null;
try {
result = Class.forName(desc.getName(), true, cl);
} catch (ClassNotFoundException ex) {
for (WekaPackageLibIsolatingClassLoader l : m_thirdPartyLoaders) {
ClassLoader checked =
SerializationHelper.checkForThirdPartyClass(arrayStripped,
l);
if (checked != null) {
result = Class.forName(desc.getName(), true, checked);
}
}
}
if (result == null) {
result = super.resolveClass(desc);
if (result == null) {
throw new ClassNotFoundException("Unable to find class "
+ arrayStripped);
}
}
return result;
}
};
else
p =
new ObjectInputStream(new BufferedInputStream(new GZIPInputStream(
istream))) {
protected Set<WekaPackageLibIsolatingClassLoader> m_thirdPartyLoaders =
new LinkedHashSet<>();
protected WekaPackageLibIsolatingClassLoader m_firstLoader = null;
@Override
protected Class<?> resolveClass(ObjectStreamClass desc)
throws IOException, ClassNotFoundException {
// make sure that the type descriptor for arrays gets removed
// from what we're going to look up!
String arrayStripped =
desc.getName().replace("[L", "").replace("[", "")
.replace(";", "");
ClassLoader cl =
WekaPackageClassLoaderManager
.getWekaPackageClassLoaderManager().getLoaderForClass(
arrayStripped);
if (cl instanceof WekaPackageLibIsolatingClassLoader) {
// might be third-party classes involved, store the
// classloader
m_thirdPartyLoaders
.add((WekaPackageLibIsolatingClassLoader) cl);
}
Class<?> result = null;
try {
result = Class.forName(desc.getName(), true, cl);
} catch (ClassNotFoundException ex) {
for (WekaPackageLibIsolatingClassLoader l : m_thirdPartyLoaders) {
ClassLoader checked =
SerializationHelper.checkForThirdPartyClass(
arrayStripped, l);
if (checked != null) {
result = Class.forName(desc.getName(), true, checked);
}
}
}
if (result == null) {
result = super.resolveClass(desc);
if (result == null) {
throw new ClassNotFoundException("Unable to find class "
+ arrayStripped);
}
}
return result;
}
};
toReturn = p.readObject();
}
istream.close();
return toReturn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Settings.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Settings
* Copyright (C) 2015 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import weka.core.metastore.MetaStore;
import weka.core.metastore.XMLFileBasedMetaStore;
import weka.knowledgeflow.LoggingLevel;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Maintains a collection of settings. Settings are key value pairs which can be
* grouped together under a given name. All settings managed by an instance
* of this class are persisted in the central metastore under a given store
* name. For example, the store name could be the name/ID of an application/
* system, and settings could be grouped according to applications, components,
* panels etc. Default settings (managed by {@code Defaults}
* objects) can be applied to provide initial defaults (or to allow new settings
* that have yet to be persisted to be added in the future).
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: $
*/
public class Settings implements Serializable {
/**
* For serialization
*/
private static final long serialVersionUID = -4005372566372478008L;
/**
* outer map keyed by perspective ID. Inner map - settings for a perspective.
*/
protected Map<String, Map<SettingKey, Object>> m_settings =
new LinkedHashMap<String, Map<SettingKey, Object>>();
/**
* The name of the store that these settings should be saved/loaded to/from
*/
protected String m_storeName = "";
/**
* The name of the entry within the store to save to
*/
protected String m_ID = "";
/**
* Load the settings with ID m_ID from store m_storeName.
*
* @throws IOException if a problem occurs
*/
@SuppressWarnings("unchecked")
public void loadSettings() throws IOException {
MetaStore store = new XMLFileBasedMetaStore();
Map<String, Map<SettingKey, Object>> loaded =
(Map<String, Map<SettingKey, Object>>) store.getEntry(m_storeName, m_ID,
Map.class);
if (loaded != null) {
m_settings = loaded;
}
// unwrap EnumHelper/FontHelper/FileHelper instances
for (Map<SettingKey, Object> s : m_settings.values()) {
for (Map.Entry<SettingKey, Object> e : s.entrySet()) {
if (e.getValue() instanceof EnumHelper) {
SettingKey key = e.getKey();
EnumHelper eHelper = (EnumHelper) e.getValue();
try {
// get the actual enumerated value
Object actualValue =
EnumHelper.valueFromString(eHelper.getEnumClass(),
eHelper.getSelectedEnumValue());
s.put(key, actualValue);
} catch (Exception ex) {
throw new IOException(ex);
}
} else if (e.getValue() instanceof FontHelper) {
SettingKey key = e.getKey();
FontHelper fHelper = (FontHelper) e.getValue();
Font f = fHelper.getFont();
s.put(key, f);
} else if (e.getValue() instanceof FileHelper) {
SettingKey key = e.getKey();
FileHelper fileHelper = (FileHelper) e.getValue();
File f = fileHelper.getFile();
s.put(key, f);
}
}
}
}
/**
* Construct a new Settings object to be stored in the supplied store under
* the given ID/name
*
* @param storeName the name of the store to load/save to in the metastore
* @param ID the ID/name to use
*/
public Settings(String storeName, String ID) {
m_storeName = storeName;
m_ID = ID;
try {
loadSettings();
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
/**
* Get the ID used for these settings
*
* @return the ID used
*/
public String getID() {
return m_ID;
}
/**
* Get the store name for these settings
*
* @return the store name
*/
public String getStoreName() {
return m_storeName;
}
/**
* Applies a set of default settings. If the ID of default settings is not
* known then a new entry is made for it. Otherwise we examine all settings in
* the default set supplied and add any that we don't have a value for.
*
* @param defaults the defaults to apply
*/
public void applyDefaults(Defaults defaults) {
if (defaults == null) {
return;
}
Map<SettingKey, Object> settingsForID = m_settings.get(defaults.getID());
if (settingsForID == null) {
settingsForID = new LinkedHashMap<SettingKey, Object>();
m_settings.put(defaults.getID(), settingsForID);
}
// add all settings that don't exist in the set we loaded for this ID
for (Map.Entry<SettingKey, Object> e : defaults.getDefaults().entrySet()) {
if (!settingsForID.containsKey(e.getKey())) {
settingsForID.put(e.getKey(), e.getValue());
}
}
}
/**
* Get the settings for a given ID
*
* @param settingsID the ID to get settings for
* @return a map of settings, or null if the given ID is unknown
*/
public Map<SettingKey, Object> getSettings(String settingsID) {
return m_settings.get(settingsID);
}
/**
* Get a list of settings IDs
*
* @return a list of the settings IDs managed by this settings instance
*/
public Set<String> getSettingsIDs() {
return m_settings.keySet();
}
public <T> T
getSetting(String ID, String key, T defaultValue, Environment env) {
SettingKey tempKey = new SettingKey(key, "", "");
return getSetting(ID, tempKey, defaultValue, env);
}
/**
* Get the value of a setting
*
* @param ID the ID for settings map to lookup (typically the ID of a
* perspective)
* @param key the name of the setting value to lookup
* @param defaultValue the default value to use if the setting is not known
* @param <T> the type of the vaue
* @return the setting value, or the default value if not found
*/
public <T> T getSetting(String ID, SettingKey key, T defaultValue) {
return getSetting(ID, key, defaultValue, Environment.getSystemWide());
}
/**
* Get the value of a setting
*
* @param ID the ID for settings map to lookup (typically the ID of a
* perspective)
* @param key the name of the setting value to lookup
* @param defaultValue the default value to use if the setting is not known
* @param env environment variables to use. String setting values will have
* environment variables replaced automatically
* @param <T> the type of the vaue
* @return the setting value, or the default value if not found
*/
// TOOD new...
@SuppressWarnings("unchecked")
public <T> T getSetting(String ID, SettingKey key, T defaultValue,
Environment env) {
Map<SettingKey, Object> settingsForID = m_settings.get(ID);
T value = null;
if (settingsForID != null && settingsForID.size() > 0) {
value = (T) settingsForID.get(key);
if (value instanceof String) {
try {
value = (T) env.substitute((String) value);
} catch (Exception ex) {
// ignore
}
}
}
if (value == null) {
// Next is environment
if (env != null) {
String val = env.getVariableValue(key.getKey());
if (val != null) {
value = stringToT(val, defaultValue);
}
}
}
// Try system props
if (value == null) {
String val = System.getProperty(key.getKey());
if (val != null) {
value = stringToT(val, defaultValue);
}
}
return value != null ? value : defaultValue;
}
/**
* Set a value for a setting.
*
* @param ID the for the settings map to store the setting in (typically the
* ID of a perspective or application)
* @param propName the name of the setting to store
* @param value the value of the setting to store
*/
public void setSetting(String ID, SettingKey propName, Object value) {
Map<SettingKey, Object> settingsForID = m_settings.get(ID);
if (settingsForID == null) {
settingsForID = new LinkedHashMap<SettingKey, Object>();
m_settings.put(ID, settingsForID);
}
settingsForID.put(propName, value);
}
/**
* Returns true if there are settings available for a given ID
*
* @param settingsID the ID to check
* @return true if there are settings available for that ID
*/
public boolean hasSettings(String settingsID) {
return m_settings.containsKey(settingsID);
}
/**
* Returns true if a given setting has a value
*
* @param settingsID the ID of the settings group
* @param propName the actual setting to check for
* @return true if the setting has a value
*/
public boolean hasSetting(String settingsID, String propName) {
if (!hasSettings(settingsID)) {
return false;
}
return m_settings.get(settingsID).containsKey(propName);
}
/**
* Save the settings to the metastore
*
* @throws IOException if a problem occurs
*/
public void saveSettings() throws IOException {
// shallow copy settings so that we can wrap any enums in EnumHelper
// objects before persisting
Map<String, Map<SettingKey, Object>> settingsCopy =
new LinkedHashMap<String, Map<SettingKey, Object>>();
for (Map.Entry<String, Map<SettingKey, Object>> e : m_settings.entrySet()) {
Map<SettingKey, Object> s = new LinkedHashMap<SettingKey, Object>();
settingsCopy.put(e.getKey(), s);
for (Map.Entry<SettingKey, Object> ee : e.getValue().entrySet()) {
if (ee.getValue() instanceof Enum) {
EnumHelper wrapper = new EnumHelper((Enum) ee.getValue());
s.put(ee.getKey(), wrapper);
} else if (ee.getValue() instanceof Font) {
FontHelper wrapper = new FontHelper((Font) ee.getValue());
s.put(ee.getKey(), wrapper);
} else if (ee.getValue() instanceof File) {
FileHelper wrapper = new FileHelper((File) ee.getValue());
s.put(ee.getKey(), wrapper);
} else {
s.put(ee.getKey(), ee.getValue());
}
}
}
XMLFileBasedMetaStore store = new XMLFileBasedMetaStore();
if (m_settings.size() > 0) {
store.storeEntry(m_storeName, m_ID, settingsCopy);
}
}
/**
* Convert a setting value stored in a string to type T
*
* @param propVal the value of the setting as a string
* @param defaultVal the default value for the setting (of type T)
* @param <T> the type of the setting
* @return the setting as an instance of type T
*/
protected static <T> T stringToT(String propVal, T defaultVal) {
if (defaultVal instanceof String) {
return (T) propVal;
}
if (defaultVal instanceof Boolean) {
return (T) (Boolean.valueOf(propVal));
}
if (defaultVal instanceof Double) {
return (T) (Double.valueOf(propVal));
}
if (defaultVal instanceof Integer) {
return (T) (Integer.valueOf(propVal));
}
if (defaultVal instanceof Long) {
return (T) (Long.valueOf(propVal));
}
if (defaultVal instanceof LoggingLevel) {
return (T) (LoggingLevel.stringToLevel(propVal));
}
return null;
}
/**
* Class implementing a key for a setting. Has a unique key, description, tool
* tip text and map of arbitrary other metadata
*/
public static class SettingKey implements java.io.Serializable {
/** Key for this setting */
protected String m_key;
/** Description/display name of the seting */
protected String m_description;
/** Tool tip for the setting */
protected String m_toolTip;
/** Pick list (can be null if not applicable) for a string-based setting */
protected List<String> m_pickList;
/**
* Metadata for this setting - e.g. file property could specify whether it
* is files only, directories only or both
*/
protected Map<String, String> m_meta;
/**
* Construct a new empty setting key
*/
public SettingKey() {
this("", "", "");
}
/**
* Construct a new SettingKey with the given key, description and tool tip
* text
*
* @param key the key of this SettingKey
* @param description the description (display name of the setting)
* @param toolTip the tool tip text for the setting
*/
public SettingKey(String key, String description, String toolTip) {
this(key, description, toolTip, null);
}
/**
* Construct a new SettingKey with the given key, description, tool tip and
* pick list
*
* @param key the key of this SettingKey
* @param description the description (display name of the setting)
* @param toolTip the tool tip for the setting
* @param pickList an optional list of legal values for a string setting
*/
public SettingKey(String key, String description, String toolTip,
List<String> pickList) {
m_key = key;
m_description = description;
m_toolTip = toolTip;
m_pickList = pickList;
}
/**
* set the key of this setting
*
* @param key the key to use
*/
public void setKey(String key) {
m_key = key;
}
/**
* Get the key of this setting
*
* @return the key of this setting
*/
public String getKey() {
return m_key;
}
/**
* Set the description (display name) of this setting
*
* @param description the description of this setting
*/
public void setDescription(String description) {
m_description = description;
}
/**
* Get the description (display name) of this setting
*
* @return the description of this setting
*/
public String getDescription() {
return m_description;
}
/**
* Set the tool tip text for this setting
*
* @param toolTip the tool tip text to use
*/
public void setToolTip(String toolTip) {
m_toolTip = toolTip;
}
/**
* Get the tool tip text for this setting
*
* @return the tool tip text to use
*/
public String getToolTip() {
return m_toolTip;
}
/**
* Set the value of a piece of metadata for this setting
*
* @param key the key for the metadata
* @param value the value of the metadata
*/
public void setMetadataElement(String key, String value) {
if (m_meta == null) {
m_meta = new HashMap<String, String>();
}
m_meta.put(key, value);
}
/**
* Get a piece of metadata for this setting
*
* @param key the key of the metadata
* @return the corresponding value, or null if the key is not known
*/
public String getMetadataElement(String key) {
if (m_meta == null) {
return null;
}
return m_meta.get(key);
}
/**
* Get a peice of metadata for this setting
*
* @param key the key of the metadata
* @param defaultValue the default value for the metadata
* @return the corresponding value, or the default value if the key is not
* known
*/
public String getMetadataElement(String key, String defaultValue) {
String result = getMetadataElement(key);
return result == null ? defaultValue : result;
}
/**
* Set the metadata for this setting
*
* @param metadata the metadata for this setting
*/
public void setMetadata(Map<String, String> metadata) {
m_meta = metadata;
}
/**
* Get the metadata for this setting
*
* @return the metadata for this setting
*/
public Map<String, String> getMetadata() {
return m_meta;
}
/**
* Get the optional pick list for the setting
*
* @return the optional pick list for the setting (can be null if not
* applicable)
*/
public List<String> getPickList() {
return m_pickList;
}
/**
* Set the optional pick list for the setting
*
* @param pickList the optional pick list for the setting (can be null if
* not applicable)
*/
public void setPickList(List<String> pickList) {
m_pickList = pickList;
}
/**
* Hashcode based on the key
*
* @return the hashcode of this setting
*/
@Override
public int hashCode() {
return m_key.hashCode();
}
/**
* Compares two setting keys for equality
*
* @param other the other setting key to compare to
* @return true if this setting key is equal to the supplied one
*/
@Override
public boolean equals(Object other) {
if (!(other instanceof SettingKey)) {
return false;
}
return m_key.equals(((SettingKey) other).getKey());
}
/**
* Return the description (display name) of this setting
*
* @return the description of this setting
*/
@Override
public String toString() {
return m_description;
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/SingleIndex.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* SingleIndex.java
* Copyright (C) 2003-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.Serializable;
/**
* Class representing a single cardinal number. The number is set by a
* string representation such as: <P>
*
* <code>
* first
* last
* 1
* 3
* </code> <P>
* The number is internally converted from 1-based to 0-based (so methods that
* set or get numbers not in string format should use 0-based numbers).
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public class SingleIndex
implements Serializable, RevisionHandler, CustomDisplayStringProvider {
/** for serialization. */
static final long serialVersionUID = 5285169134430839303L;
/** Record the string representation of the number. */
protected /*@non_null spec_public@*/ String m_IndexString = "";
/** The selected index. */
protected /*@ spec_public @*/ int m_SelectedIndex = -1;
/** Store the maximum value permitted. -1 indicates that no upper
value has been set */
protected /*@ spec_public @*/ int m_Upper = -1;
/**
* Default constructor.
*
*/
//@ assignable m_IndexString, m_SelectedIndex, m_Upper;
//@ ensures m_SelectedIndex == -1;
//@ ensures m_Upper == -1;
public SingleIndex() {
}
/**
* Constructor to set initial index.
*
* @param index the initial index
* @throws IllegalArgumentException if the index is invalid
*/
//@ assignable m_IndexString, m_SelectedIndex, m_Upper;
//@ ensures m_IndexString == index;
//@ ensures m_SelectedIndex == -1;
//@ ensures m_Upper == -1;
public SingleIndex(/*@non_null@*/ String index) {
setSingleIndex(index);
}
/**
* Sets the value of "last".
*
* @param newUpper the value of "last"
*/
//@ assignable m_Upper, m_IndexString, m_SelectedIndex;
//@ ensures newUpper < 0 ==> m_Upper == \old(m_Upper);
//@ ensures newUpper >= 0 ==> m_Upper == newUpper;
public void setUpper(int newUpper) {
if (newUpper >= 0) {
m_Upper = newUpper;
setValue();
}
}
/**
* Gets the string representing the selected range of values.
*
* @return the range selection string
*/
//@ ensures \result == m_IndexString;
public /*@pure@*/ String getSingleIndex() {
return m_IndexString;
}
/**
* Sets the index from a string representation. Note that setUpper()
* must be called for the value to be actually set
*
* @param index the index set
* @throws IllegalArgumentException if the index was not well formed
*/
//@ assignable m_IndexString, m_SelectedIndex;
//@ ensures m_IndexString == index;
//@ ensures m_SelectedIndex == -1;
public void setSingleIndex(/*@non_null@*/ String index) {
m_IndexString = index;
m_SelectedIndex = -1;
}
/**
* Constructs a representation of the current range. Being a string
* representation, the numbers are based from 1.
*
* @return the string representation of the current range
*/
//@ also signals (RuntimeException e) \old(m_Upper) < 0;
//@ ensures \result != null;
public /*@pure@*/ String toString() {
if (m_IndexString.equals("")) {
return "No index set";
}
if (m_Upper == -1) {
throw new RuntimeException("Upper limit has not been specified");
}
return m_IndexString;
}
/**
* Gets the selected index.
*
* @return the selected index
* @throws RuntimeException if the upper limit of the index hasn't been defined
*/
//@ requires m_Upper >= 0;
//@ requires m_IndexString.length() > 0;
//@ ensures \result == m_SelectedIndex;
public /*@pure@*/ int getIndex() {
if (m_IndexString.equals("")) {
throw new RuntimeException("No index set");
}
if (m_Upper == -1) {
throw new RuntimeException("No upper limit has been specified for index");
}
return m_SelectedIndex;
}
/**
* Creates a string representation of the given index.
*
* @param index the index to turn into a string.
* Since the index will typically come from a program, indices are assumed
* from 0, and thus will have 1 added in the String representation.
* @return the string representation
*/
//@ requires index >= 0;
public static /*@pure non_null@*/ String indexToString(int index) {
return "" + (index + 1);
}
/**
* Translates a single string selection into it's internal 0-based equivalent.
*/
//@ assignable m_SelectedIndex, m_IndexString;
protected void setValue() {
if (m_IndexString.equals("")) {
throw new RuntimeException("No index set");
}
if (m_IndexString.toLowerCase().equals("first")) {
m_SelectedIndex = 0;
} else if (m_IndexString.toLowerCase().equals("last")) {
m_SelectedIndex = m_Upper;
} else {
m_SelectedIndex = Integer.parseInt(m_IndexString) - 1;
if (m_SelectedIndex < 0) {
m_IndexString = "";
throw new IllegalArgumentException("Index must be greater than zero");
}
if (m_SelectedIndex > m_Upper) {
m_IndexString = "";
throw new IllegalArgumentException("Index is too large");
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Returns the custom display string.
*
* @return the string
*/
public String toDisplay() {
return getSingleIndex();
}
/**
* Main method for testing this class.
*
* @param argv one parameter: a test index specification
*/
//@ requires \nonnullelements(argv);
public static void main(/*@non_null@*/ String [] argv) {
try {
if (argv.length == 0) {
throw new Exception("Usage: SingleIndex <indexspec>");
}
SingleIndex singleIndex = new SingleIndex();
singleIndex.setSingleIndex(argv[0]);
singleIndex.setUpper(9);
System.out.println("Input: " + argv[0] + "\n"
+ singleIndex.toString());
int selectedIndex = singleIndex.getIndex();
System.out.println(selectedIndex + "");
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/SparseInstance.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* SparseInstance.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.ArrayList;
import java.util.Enumeration;
/**
* Class for storing an instance as a sparse vector. A sparse instance only
* requires storage for those attribute values that are non-zero. Since the
* objective is to reduce storage requirements for datasets with large numbers
* of default values, this also includes nominal attributes -- the first nominal
* value (i.e. that which has index 0) will not require explicit storage, so
* rearrange your nominal attribute value orderings if necessary. Missing values
* will be stored explicitly.
*
* @author Eibe Frank
* @version $Revision$
*/
public class SparseInstance extends AbstractInstance {
/** for serialization */
private static final long serialVersionUID = -3579051291332630149L;
/** The index of the attribute associated with each stored value. */
protected int[] m_Indices;
/** The maximum number of values that can be stored. */
protected int m_NumAttributes;
/**
* Constructor that generates a sparse instance from the given instance.
* Reference to the dataset is set to null. (ie. the instance doesn't have
* access to information about the attribute types)
*
* @param instance the instance from which the attribute values and the weight
* are to be copied
*/
public SparseInstance(Instance instance) {
m_Weight = instance.weight();
m_Dataset = null;
m_NumAttributes = instance.numAttributes();
if (instance instanceof SparseInstance) {
m_AttValues = ((SparseInstance) instance).m_AttValues;
m_Indices = ((SparseInstance) instance).m_Indices;
} else {
double[] tempValues = new double[instance.numAttributes()];
int[] tempIndices = new int[instance.numAttributes()];
int vals = 0;
for (int i = 0; i < instance.numAttributes(); i++) {
if (instance.value(i) != 0) {
tempValues[vals] = instance.value(i);
tempIndices[vals] = i;
vals++;
}
}
m_AttValues = new double[vals];
m_Indices = new int[vals];
System.arraycopy(tempValues, 0, m_AttValues, 0, vals);
System.arraycopy(tempIndices, 0, m_Indices, 0, vals);
}
}
/**
* Constructor that copies the info from the given instance. Reference to the
* dataset is set to null. (ie. the instance doesn't have access to
* information about the attribute types)
*
* @param instance the instance from which the attribute info is to be copied
*/
public SparseInstance(SparseInstance instance) {
m_AttValues = instance.m_AttValues;
m_Indices = instance.m_Indices;
m_Weight = instance.m_Weight;
m_NumAttributes = instance.m_NumAttributes;
m_Dataset = null;
}
/**
* Constructor that generates a sparse instance from the given parameters.
* Reference to the dataset is set to null. (ie. the instance doesn't have
* access to information about the attribute types)
*
* @param weight the instance's weight
* @param attValues a vector of attribute values
*/
public SparseInstance(double weight, double[] attValues) {
m_Weight = weight;
m_Dataset = null;
m_NumAttributes = attValues.length;
double[] tempValues = new double[m_NumAttributes];
int[] tempIndices = new int[m_NumAttributes];
int vals = 0;
for (int i = 0; i < m_NumAttributes; i++) {
if (attValues[i] != 0) {
tempValues[vals] = attValues[i];
tempIndices[vals] = i;
vals++;
}
}
m_AttValues = new double[vals];
m_Indices = new int[vals];
System.arraycopy(tempValues, 0, m_AttValues, 0, vals);
System.arraycopy(tempIndices, 0, m_Indices, 0, vals);
}
/**
* Constructor that initializes instance variable with given values.
* Reference to the dataset is set to null. (ie. the instance doesn't have
* access to information about the attribute types) Note that the indices need
* to be sorted in ascending order. Otherwise things won't work properly.
*
* @param weight the instance's weight
* @param attValues a vector of attribute values (just the ones to be stored)
* @param indices the indices of the given values in the full vector (need to
* be sorted in ascending order)
* @param maxNumValues the maximum number of values that can be stored
*/
public SparseInstance(double weight, double[] attValues, int[] indices,
int maxNumValues) {
int vals = 0;
m_AttValues = new double[attValues.length];
m_Indices = new int[indices.length];
for (int i = 0; i < attValues.length; i++) {
if (attValues[i] != 0) {
m_AttValues[vals] = attValues[i];
m_Indices[vals] = indices[i];
vals++;
}
}
if (vals != attValues.length) {
// Need to truncate.
double[] newVals = new double[vals];
System.arraycopy(m_AttValues, 0, newVals, 0, vals);
m_AttValues = newVals;
int[] newIndices = new int[vals];
System.arraycopy(m_Indices, 0, newIndices, 0, vals);
m_Indices = newIndices;
}
m_Weight = weight;
m_NumAttributes = maxNumValues;
m_Dataset = null;
}
/**
* Constructor of an instance that sets weight to one, all values to be
* missing, and the reference to the dataset to null. (ie. the instance
* doesn't have access to information about the attribute types)
*
* @param numAttributes the size of the instance
*/
public SparseInstance(int numAttributes) {
m_AttValues = new double[numAttributes];
m_NumAttributes = numAttributes;
m_Indices = new int[numAttributes];
for (int i = 0; i < m_AttValues.length; i++) {
m_AttValues[i] = Utils.missingValue();
m_Indices[i] = i;
}
m_Weight = 1;
m_Dataset = null;
}
/**
* Produces a shallow copy of this instance. The copy has access to the same
* dataset. (if you want to make a copy that doesn't have access to the
* dataset, use <code>new SparseInstance(instance)</code>
*
* @return the shallow copy
*/
@Override
public Object copy() {
SparseInstance result = new SparseInstance(this);
result.m_Dataset = m_Dataset;
return result;
}
/**
* Copies the instance but fills up its values based on the given array
* of doubles. The copy has access to the same dataset.
*
* @param values the array with new values
* @return the new instance
*/
public Instance copy(double[] values) {
SparseInstance result = new SparseInstance(this.m_Weight, values);
result.m_Dataset = m_Dataset;
return result;
}
/**
* Returns the index of the attribute stored at the given position.
*
* @param position the position
* @return the index of the attribute stored at the given position
*/
@Override
public int index(int position) {
return m_Indices[position];
}
/**
* Locates the greatest index that is not greater than the given index.
*
* @return the internal index of the attribute index. Returns -1 if no index
* with this property could be found
*/
public int locateIndex(int index) {
int min = 0, max = m_Indices.length - 1;
if (max == -1) {
return -1;
}
// Binary search
while ((m_Indices[min] <= index) && (m_Indices[max] >= index)) {
int current = (max + min) / 2;
if (m_Indices[current] > index) {
max = current - 1;
} else if (m_Indices[current] < index) {
min = current + 1;
} else {
return current;
}
}
if (m_Indices[max] < index) {
return max;
} else {
return min - 1;
}
}
/**
* Merges this instance with the given instance and returns the result.
* Dataset is set to null.
*
* @param inst the instance to be merged with this one
* @return the merged instances
*/
@Override
public Instance mergeInstance(Instance inst) {
double[] values = new double[numValues() + inst.numValues()];
int[] indices = new int[numValues() + inst.numValues()];
int m = 0;
for (int j = 0; j < numValues(); j++, m++) {
values[m] = valueSparse(j);
indices[m] = index(j);
}
for (int j = 0; j < inst.numValues(); j++, m++) {
values[m] = inst.valueSparse(j);
indices[m] = numAttributes() + inst.index(j);
}
return new SparseInstance(1.0, values, indices, numAttributes()
+ inst.numAttributes());
}
/**
* Returns the number of attributes.
*
* @return the number of attributes as an integer
*/
@Override
public int numAttributes() {
return m_NumAttributes;
}
/**
* Returns the number of values in the sparse vector.
*
* @return the number of values
*/
@Override
public int numValues() {
return m_Indices.length;
}
/**
* Replaces all missing values in the instance with the values contained in
* the given array. A deep copy of the vector of attribute values is performed
* before the values are replaced.
*
* @param array containing the means and modes
* @exception IllegalArgumentException if numbers of attributes are unequal
*/
@Override
public void replaceMissingValues(double[] array) {
if ((array == null) || (array.length != m_NumAttributes)) {
throw new IllegalArgumentException("Unequal number of attributes!");
}
double[] tempValues = new double[m_AttValues.length];
int[] tempIndices = new int[m_AttValues.length];
int vals = 0;
for (int i = 0; i < m_AttValues.length; i++) {
if (isMissingSparse(i)) {
if (array[m_Indices[i]] != 0) {
tempValues[vals] = array[m_Indices[i]];
tempIndices[vals] = m_Indices[i];
vals++;
}
} else {
tempValues[vals] = m_AttValues[i];
tempIndices[vals] = m_Indices[i];
vals++;
}
}
m_AttValues = new double[vals];
m_Indices = new int[vals];
System.arraycopy(tempValues, 0, m_AttValues, 0, vals);
System.arraycopy(tempIndices, 0, m_Indices, 0, vals);
}
/**
* Sets a specific value in the instance to the given value (internal
* floating-point format). Performs a deep copy of the vector of attribute
* values before the value is set.
*
* @param attIndex the attribute's index
* @param value the new attribute value (If the corresponding attribute is
* nominal (or a string) then this is the new value's index as a
* double).
*/
@Override
public void setValue(int attIndex, double value) {
int index = locateIndex(attIndex);
if ((index >= 0) && (m_Indices[index] == attIndex)) {
if (value != 0) {
double[] tempValues = new double[m_AttValues.length];
System.arraycopy(m_AttValues, 0, tempValues, 0, m_AttValues.length);
tempValues[index] = value;
m_AttValues = tempValues;
} else {
double[] tempValues = new double[m_AttValues.length - 1];
int[] tempIndices = new int[m_Indices.length - 1];
System.arraycopy(m_AttValues, 0, tempValues, 0, index);
System.arraycopy(m_Indices, 0, tempIndices, 0, index);
System.arraycopy(m_AttValues, index + 1, tempValues, index,
m_AttValues.length - index - 1);
System.arraycopy(m_Indices, index + 1, tempIndices, index,
m_Indices.length - index - 1);
m_AttValues = tempValues;
m_Indices = tempIndices;
}
} else {
if (value != 0) {
double[] tempValues = new double[m_AttValues.length + 1];
int[] tempIndices = new int[m_Indices.length + 1];
System.arraycopy(m_AttValues, 0, tempValues, 0, index + 1);
System.arraycopy(m_Indices, 0, tempIndices, 0, index + 1);
tempIndices[index + 1] = attIndex;
tempValues[index + 1] = value;
System.arraycopy(m_AttValues, index + 1, tempValues, index + 2,
m_AttValues.length - index - 1);
System.arraycopy(m_Indices, index + 1, tempIndices, index + 2,
m_Indices.length - index - 1);
m_AttValues = tempValues;
m_Indices = tempIndices;
}
}
}
/**
* Sets a specific value in the instance to the given value (internal
* floating-point format). Performs a deep copy of the vector of attribute
* values before the value is set.
*
* @param indexOfIndex the index of the attribute's index
* @param value the new attribute value (If the corresponding attribute is
* nominal (or a string) then this is the new value's index as a
* double).
*/
@Override
public void setValueSparse(int indexOfIndex, double value) {
if (value != 0) {
double[] tempValues = new double[m_AttValues.length];
System.arraycopy(m_AttValues, 0, tempValues, 0, m_AttValues.length);
m_AttValues = tempValues;
m_AttValues[indexOfIndex] = value;
} else {
double[] tempValues = new double[m_AttValues.length - 1];
int[] tempIndices = new int[m_Indices.length - 1];
System.arraycopy(m_AttValues, 0, tempValues, 0, indexOfIndex);
System.arraycopy(m_Indices, 0, tempIndices, 0, indexOfIndex);
System.arraycopy(m_AttValues, indexOfIndex + 1, tempValues, indexOfIndex,
m_AttValues.length - indexOfIndex - 1);
System.arraycopy(m_Indices, indexOfIndex + 1, tempIndices, indexOfIndex,
m_Indices.length - indexOfIndex - 1);
m_AttValues = tempValues;
m_Indices = tempIndices;
}
}
/**
* Returns the values of each attribute as an array of doubles.
*
* @return an array containing all the instance attribute values
*/
@Override
public double[] toDoubleArray() {
double[] newValues = new double[m_NumAttributes];
for (int i = 0; i < m_AttValues.length; i++) {
newValues[m_Indices[i]] = m_AttValues[i];
}
return newValues;
}
/**
* Returns the description of one instance in sparse format. If the instance
* doesn't have access to a dataset, it returns the internal floating-point
* values. Quotes string values that contain whitespace characters.
*
* @return the instance's description as a string
*/
@Override
public String toStringNoWeight() {
return toStringNoWeight(AbstractInstance.s_numericAfterDecimalPoint);
}
/**
* Returns the description of one instance in sparse format. If the instance
* doesn't have access to a dataset, it returns the internal floating-point
* values. Quotes string values that contain whitespace characters.
*
* @param afterDecimalPoint maximum number of digits permitted after the
* decimal point for numeric values
*
* @return the instance's description as a string
*/
@Override
public String toStringNoWeight(int afterDecimalPoint) {
StringBuilder text = new StringBuilder();
text.append('{');
String prefix = "";
int sparseIndex = 0;
for (int i = 0; i < m_NumAttributes; i++) {
// Have we already output some values?
if (text.length() > 1) {
prefix = ",";
}
double value = 0;
try {
// Get the actual attribute value
if (sparseIndex < m_Indices.length && m_Indices[sparseIndex] == i) {
value = m_AttValues[sparseIndex++];
if (Utils.isMissingValue(value)) {
text.append(prefix).append(i).append(" ?");
continue;
}
}
// Have to treat all attributes as numeric if we don't have access to a dataset
if (m_Dataset == null) {
if (value != 0) {
text.append(prefix).append(i).append(" ").append(Utils.doubleToString(value, afterDecimalPoint));
}
} else {
Attribute att = m_Dataset.attribute(i);
if (att.isString()) { // Output string value regardless
text.append(prefix).append(i).append(" ").append(Utils.quote(att.value((int) value)));
} else if (att.isRelationValued()) { // Output relational value regardless
text.append(prefix).append(i).append(" ").append(Utils.quote(att.relation((int) value).stringWithoutHeader()));
} else if (value != 0) { // Only output other attribute types if value != 0
if (att.isNominal()) {
text.append(prefix).append(i).append(" ").append(Utils.quote(att.value((int) value)));
} else if (att.isDate()) {
text.append(prefix).append(i).append(" ").append(Utils.quote(att.formatDate(value)));
} else {
text.append(prefix).append(i).append(" ").append(Utils.doubleToString(value, afterDecimalPoint));
}
}
}
} catch (Exception e) {
e.printStackTrace();
System.err.println(new Instances(m_Dataset, 0) + "\n" + "Att: " + i + " Val: " + value);
throw new Error("This should never happen!");
}
}
text.append('}');
return text.toString();
}
/**
* Returns an instance's attribute value in internal format.
*
* @param attIndex the attribute's index
* @return the specified value as a double (If the corresponding attribute is
* nominal (or a string) then it returns the value's index as a
* double).
*/
@Override
public double value(int attIndex) {
int index = locateIndex(attIndex);
if ((index >= 0) && (m_Indices[index] == attIndex)) {
return m_AttValues[index];
} else {
return 0.0;
}
}
/**
* Deletes an attribute at the given position (0 to numAttributes() - 1).
*
* @param position the attribute's position
*/
@Override
protected void forceDeleteAttributeAt(int position) {
int index = locateIndex(position);
m_NumAttributes--;
if ((index >= 0) && (m_Indices[index] == position)) {
int[] tempIndices = new int[m_Indices.length - 1];
double[] tempValues = new double[m_AttValues.length - 1];
System.arraycopy(m_Indices, 0, tempIndices, 0, index);
System.arraycopy(m_AttValues, 0, tempValues, 0, index);
for (int i = index; i < m_Indices.length - 1; i++) {
tempIndices[i] = m_Indices[i + 1] - 1;
tempValues[i] = m_AttValues[i + 1];
}
m_Indices = tempIndices;
m_AttValues = tempValues;
} else {
int[] tempIndices = new int[m_Indices.length];
double[] tempValues = new double[m_AttValues.length];
System.arraycopy(m_Indices, 0, tempIndices, 0, index + 1);
System.arraycopy(m_AttValues, 0, tempValues, 0, index + 1);
for (int i = index + 1; i < m_Indices.length; i++) {
tempIndices[i] = m_Indices[i] - 1;
tempValues[i] = m_AttValues[i];
}
m_Indices = tempIndices;
m_AttValues = tempValues;
}
}
/**
* Inserts an attribute at the given position (0 to numAttributes()) and sets
* its value to be missing.
*
* @param position the attribute's position
*/
@Override
protected void forceInsertAttributeAt(int position) {
int index = locateIndex(position);
m_NumAttributes++;
if ((index >= 0) && (m_Indices[index] == position)) {
int[] tempIndices = new int[m_Indices.length + 1];
double[] tempValues = new double[m_AttValues.length + 1];
System.arraycopy(m_Indices, 0, tempIndices, 0, index);
System.arraycopy(m_AttValues, 0, tempValues, 0, index);
tempIndices[index] = position;
tempValues[index] = Utils.missingValue();
for (int i = index; i < m_Indices.length; i++) {
tempIndices[i + 1] = m_Indices[i] + 1;
tempValues[i + 1] = m_AttValues[i];
}
m_Indices = tempIndices;
m_AttValues = tempValues;
} else {
int[] tempIndices = new int[m_Indices.length + 1];
double[] tempValues = new double[m_AttValues.length + 1];
System.arraycopy(m_Indices, 0, tempIndices, 0, index + 1);
System.arraycopy(m_AttValues, 0, tempValues, 0, index + 1);
tempIndices[index + 1] = position;
tempValues[index + 1] = Utils.missingValue();
for (int i = index + 1; i < m_Indices.length; i++) {
tempIndices[i + 1] = m_Indices[i] + 1;
tempValues[i + 1] = m_AttValues[i];
}
m_Indices = tempIndices;
m_AttValues = tempValues;
}
}
/**
* Constructor for sub classes.
*/
protected SparseInstance() {
};
/**
* Main method for testing this class.
*/
public static void main(String[] options) {
try {
// Create numeric attributes "length" and "weight"
Attribute length = new Attribute("length");
Attribute weight = new Attribute("weight");
// Create vector to hold nominal values "first", "second", "third"
ArrayList<String> my_nominal_values = new ArrayList<String>(3);
my_nominal_values.add("first");
my_nominal_values.add("second");
my_nominal_values.add("third");
// Create nominal attribute "position"
Attribute position = new Attribute("position", my_nominal_values);
// Create vector of the above attributes
ArrayList<Attribute> attributes = new ArrayList<Attribute>(3);
attributes.add(length);
attributes.add(weight);
attributes.add(position);
// Create the empty dataset "race" with above attributes
Instances race = new Instances("race", attributes, 0);
// Make position the class attribute
race.setClassIndex(position.index());
// Create empty instance with three attribute values
SparseInstance inst = new SparseInstance(3);
// Set instance's values for the attributes "length", "weight", and
// "position"
inst.setValue(length, 5.3);
inst.setValue(weight, 300);
inst.setValue(position, "first");
// Set instance's dataset to be the dataset "race"
inst.setDataset(race);
// Print the instance
System.out.println("The instance: " + inst);
// Print the first attribute
System.out.println("First attribute: " + inst.attribute(0));
// Print the class attribute
System.out.println("Class attribute: " + inst.classAttribute());
// Print the class index
System.out.println("Class index: " + inst.classIndex());
// Say if class is missing
System.out.println("Class is missing: " + inst.classIsMissing());
// Print the instance's class value in internal format
System.out.println("Class value (internal format): " + inst.classValue());
// Print a shallow copy of this instance
SparseInstance copy = (SparseInstance) inst.copy();
System.out.println("Shallow copy: " + copy);
// Set dataset for shallow copy
copy.setDataset(inst.dataset());
System.out.println("Shallow copy with dataset set: " + copy);
// Print out all values in internal format
System.out.print("All stored values in internal format: ");
for (int i = 0; i < inst.numValues(); i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(inst.valueSparse(i));
}
System.out.println();
// Set all values to zero
System.out.print("All values set to zero: ");
while (inst.numValues() > 0) {
inst.setValueSparse(0, 0);
}
for (int i = 0; i < inst.numValues(); i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(inst.valueSparse(i));
}
System.out.println();
// Set all values to one
System.out.print("All values set to one: ");
for (int i = 0; i < inst.numAttributes(); i++) {
inst.setValue(i, 1);
}
for (int i = 0; i < inst.numValues(); i++) {
if (i > 0) {
System.out.print(",");
}
System.out.print(inst.valueSparse(i));
}
System.out.println();
// Unset dataset for copy, delete first attribute, and insert it again
copy.setDataset(null);
copy.deleteAttributeAt(0);
copy.insertAttributeAt(0);
copy.setDataset(inst.dataset());
System.out.println("Copy with first attribute deleted and inserted: "
+ copy);
// Same for second attribute
copy.setDataset(null);
copy.deleteAttributeAt(1);
copy.insertAttributeAt(1);
copy.setDataset(inst.dataset());
System.out.println("Copy with second attribute deleted and inserted: "
+ copy);
// Same for last attribute
copy.setDataset(null);
copy.deleteAttributeAt(2);
copy.insertAttributeAt(2);
copy.setDataset(inst.dataset());
System.out.println("Copy with third attribute deleted and inserted: "
+ copy);
// Enumerate attributes (leaving out the class attribute)
System.out.println("Enumerating attributes (leaving out class):");
Enumeration<Attribute> enu = inst.enumerateAttributes();
while (enu.hasMoreElements()) {
Attribute att = enu.nextElement();
System.out.println(att);
}
// Headers are equivalent?
System.out.println("Header of original and copy equivalent: "
+ inst.equalHeaders(copy));
// Test for missing values
System.out.println("Length of copy missing: " + copy.isMissing(length));
System.out.println("Weight of copy missing: "
+ copy.isMissing(weight.index()));
System.out.println("Length of copy missing: "
+ Utils.isMissingValue(copy.value(length)));
// Prints number of attributes and classes
System.out.println("Number of attributes: " + copy.numAttributes());
System.out.println("Number of classes: " + copy.numClasses());
// Replace missing values
double[] meansAndModes = { 2, 3, 0 };
copy.replaceMissingValues(meansAndModes);
System.out.println("Copy with missing value replaced: " + copy);
// Setting and getting values and weights
copy.setClassMissing();
System.out.println("Copy with missing class: " + copy);
copy.setClassValue(0);
System.out.println("Copy with class value set to first value: " + copy);
copy.setClassValue("third");
System.out.println("Copy with class value set to \"third\": " + copy);
copy.setMissing(1);
System.out.println("Copy with second attribute set to be missing: "
+ copy);
copy.setMissing(length);
System.out.println("Copy with length set to be missing: " + copy);
copy.setValue(0, 0);
System.out.println("Copy with first attribute set to 0: " + copy);
copy.setValue(weight, 1);
System.out.println("Copy with weight attribute set to 1: " + copy);
copy.setValue(position, "second");
System.out.println("Copy with position set to \"second\": " + copy);
copy.setValue(2, "first");
System.out.println("Copy with last attribute set to \"first\": " + copy);
System.out.println("Current weight of instance copy: " + copy.weight());
copy.setWeight(2);
System.out.println("Current weight of instance copy (set to 2): "
+ copy.weight());
System.out.println("Last value of copy: " + copy.toString(2));
System.out.println("Value of position for copy: "
+ copy.toString(position));
System.out.println("Last value of copy (internal format): "
+ copy.value(2));
System.out.println("Value of position for copy (internal format): "
+ copy.value(position));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/SpecialFunctions.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* SpecialFunctions.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Class implementing some mathematical functions.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public final class SpecialFunctions
implements RevisionHandler {
/** Some constants */
private static double log2 = Math.log(2);
/**
* Returns natural logarithm of factorial using gamma function.
*
* @param x the value
* @return natural logarithm of factorial
*/
public static double lnFactorial(double x){
return Statistics.lnGamma(x+1);
}
/**
* Returns base 2 logarithm of binomial coefficient using gamma function.
*
* @param a upper part of binomial coefficient
* @param b lower part
* @return the base 2 logarithm of the binominal coefficient a over b
*/
public static double log2Binomial(double a, double b) {
if (Utils.gr(b,a)) {
throw new ArithmeticException("Can't compute binomial coefficient.");
}
return (lnFactorial(a)-lnFactorial(b)-lnFactorial(a-b))/log2;
}
/**
* Returns base 2 logarithm of multinomial using gamma function.
*
* @param a upper part of multinomial coefficient
* @param bs lower part
* @return multinomial coefficient of a over the bs
*/
public static double log2Multinomial(double a, double[] bs)
{
double sum = 0;
int i;
for (i=0;i<bs.length;i++) {
if (Utils.gr(bs[i],a)) {
throw
new ArithmeticException("Can't compute multinomial coefficient.");
} else {
sum = sum+lnFactorial(bs[i]);
}
}
return (lnFactorial(a)-sum)/log2;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*/
public static void main(String[] ops) {
double[] doubles = {1, 2, 3};
System.out.println("6!: " + Math.exp(SpecialFunctions.lnFactorial(6)));
System.out.println("Binomial 6 over 2: " +
Math.pow(2, SpecialFunctions.log2Binomial(6, 2)));
System.out.println("Multinomial 6 over 1, 2, 3: " +
Math.pow(2, SpecialFunctions.log2Multinomial(6, doubles)));
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Statistics.java
|
package weka.core;
/**
* Class implementing some distributions, tests, etc. The code is mostly adapted
* from the CERN Jet Java libraries:
*
* Copyright 2001 University of Waikato Copyright 1999 CERN - European
* Organization for Nuclear Research. Permission to use, copy, modify,
* distribute and sell this software and its documentation for any purpose is
* hereby granted without fee, provided that the above copyright notice appear
* in all copies and that both that copyright notice and this permission notice
* appear in supporting documentation. CERN and the University of Waikato make
* no representations about the suitability of this software for any purpose. It
* is provided "as is" without expressed or implied warranty.
*
* @author peter.gedeck@pharma.Novartis.com
* @author wolfgang.hoschek@cern.ch
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class Statistics implements RevisionHandler {
/** Some constants */
protected static final double MACHEP = 1.11022302462515654042E-16;
protected static final double MAXLOG = 7.09782712893383996732E2;
protected static final double MINLOG = -7.451332191019412076235E2;
protected static final double MAXGAM = 171.624376956302725;
protected static final double SQTPI = 2.50662827463100050242E0;
protected static final double SQRTH = 7.07106781186547524401E-1;
protected static final double LOGPI = 1.14472988584940017414;
protected static final double big = 4.503599627370496e15;
protected static final double biginv = 2.22044604925031308085e-16;
/*************************************************
* COEFFICIENTS FOR METHOD normalInverse() *
*************************************************/
/* approximation for 0 <= |y - 0.5| <= 3/8 */
protected static final double P0[] = { -5.99633501014107895267E1,
9.80010754185999661536E1, -5.66762857469070293439E1,
1.39312609387279679503E1, -1.23916583867381258016E0, };
protected static final double Q0[] = {
/* 1.00000000000000000000E0, */
1.95448858338141759834E0, 4.67627912898881538453E0, 8.63602421390890590575E1,
-2.25462687854119370527E2, 2.00260212380060660359E2,
-8.20372256168333339912E1, 1.59056225126211695515E1,
-1.18331621121330003142E0, };
/*
* Approximation for interval z = sqrt(-2 log y ) between 2 and 8 i.e., y
* between exp(-2) = .135 and exp(-32) = 1.27e-14.
*/
protected static final double P1[] = { 4.05544892305962419923E0,
3.15251094599893866154E1, 5.71628192246421288162E1,
4.40805073893200834700E1, 1.46849561928858024014E1,
2.18663306850790267539E0, -1.40256079171354495875E-1,
-3.50424626827848203418E-2, -8.57456785154685413611E-4, };
protected static final double Q1[] = {
/* 1.00000000000000000000E0, */
1.57799883256466749731E1, 4.53907635128879210584E1, 4.13172038254672030440E1,
1.50425385692907503408E1, 2.50464946208309415979E0,
-1.42182922854787788574E-1, -3.80806407691578277194E-2,
-9.33259480895457427372E-4, };
/*
* Approximation for interval z = sqrt(-2 log y ) between 8 and 64 i.e., y
* between exp(-32) = 1.27e-14 and exp(-2048) = 3.67e-890.
*/
protected static final double P2[] = { 3.23774891776946035970E0,
6.91522889068984211695E0, 3.93881025292474443415E0,
1.33303460815807542389E0, 2.01485389549179081538E-1,
1.23716634817820021358E-2, 3.01581553508235416007E-4,
2.65806974686737550832E-6, 6.23974539184983293730E-9, };
protected static final double Q2[] = {
/* 1.00000000000000000000E0, */
6.02427039364742014255E0, 3.67983563856160859403E0, 1.37702099489081330271E0,
2.16236993594496635890E-1, 1.34204006088543189037E-2,
3.28014464682127739104E-4, 2.89247864745380683936E-6,
6.79019408009981274425E-9, };
/**
* Computes standard error for observed values of a binomial random variable.
*
* @param p the probability of success
* @param n the size of the sample
* @return the standard error
*/
public static double binomialStandardError(double p, int n) {
if (n == 0) {
return 0;
}
return Math.sqrt((p * (1 - p)) / n);
}
/**
* Returns chi-squared probability for given value and degrees of freedom.
* (The probability that the chi-squared variate will be greater than x for
* the given degrees of freedom.)
*
* @param x the value
* @param v the number of degrees of freedom
* @return the chi-squared probability
*/
public static double chiSquaredProbability(double x, double v) {
if (x < 0.0 || v < 1.0) {
return 0.0;
}
return incompleteGammaComplement(v / 2.0, x / 2.0);
}
/**
* Computes probability of F-ratio.
*
* @param F the F-ratio
* @param df1 the first number of degrees of freedom
* @param df2 the second number of degrees of freedom
* @return the probability of the F-ratio.
*/
public static double FProbability(double F, int df1, int df2) {
return incompleteBeta(df2 / 2.0, df1 / 2.0, df2 / (df2 + df1 * F));
}
/**
* Returns the area under the Normal (Gaussian) probability density function,
* integrated from minus infinity to <tt>x</tt> (assumes mean is zero,
* variance is one).
*
* <pre>
* x
* -
* 1 | | 2
* normal(x) = --------- | exp( - t /2 ) dt
* sqrt(2pi) | |
* -
* -inf.
*
* = ( 1 + erf(z) ) / 2
* = erfc(z) / 2
* </pre>
*
* where <tt>z = x/sqrt(2)</tt>. Computation is via the functions
* <tt>errorFunction</tt> and <tt>errorFunctionComplement</tt>.
*
* @param a the z-value
* @return the probability of the z value according to the normal pdf
*/
public static double normalProbability(double a) {
double x, y, z;
x = a * SQRTH;
z = Math.abs(x);
if (z < SQRTH) {
y = 0.5 + 0.5 * errorFunction(x);
} else {
y = 0.5 * errorFunctionComplemented(z);
if (x > 0) {
y = 1.0 - y;
}
}
return y;
}
/**
* Returns the value, <tt>x</tt>, for which the area under the Normal
* (Gaussian) probability density function (integrated from minus infinity to
* <tt>x</tt>) is equal to the argument <tt>y</tt> (assumes mean is zero,
* variance is one).
* <p>
* For small arguments <tt>0 < y < exp(-2)</tt>, the program computes
* <tt>z = sqrt( -2.0 * log(y) )</tt>; then the approximation is
* <tt>x = z - log(z)/z - (1/z) P(1/z) / Q(1/z)</tt>. There are two rational
* functions P/Q, one for <tt>0 < y < exp(-32)</tt> and the other for
* <tt>y</tt> up to <tt>exp(-2)</tt>. For larger arguments,
* <tt>w = y - 0.5</tt>, and <tt>x/sqrt(2pi) = w + w**3 R(w**2)/S(w**2))</tt>.
*
* @param y0 the area under the normal pdf
* @return the z-value
*/
public static double normalInverse(double y0) {
double x, y, z, y2, x0, x1;
int code;
final double s2pi = Math.sqrt(2.0 * Math.PI);
if (y0 <= 0.0) {
throw new IllegalArgumentException();
}
if (y0 >= 1.0) {
throw new IllegalArgumentException();
}
code = 1;
y = y0;
if (y > (1.0 - 0.13533528323661269189)) { /* 0.135... = exp(-2) */
y = 1.0 - y;
code = 0;
}
if (y > 0.13533528323661269189) {
y = y - 0.5;
y2 = y * y;
x = y + y * (y2 * polevl(y2, P0, 4) / p1evl(y2, Q0, 8));
x = x * s2pi;
return (x);
}
x = Math.sqrt(-2.0 * Math.log(y));
x0 = x - Math.log(x) / x;
z = 1.0 / x;
if (x < 8.0) {
x1 = z * polevl(z, P1, 8) / p1evl(z, Q1, 8);
} else {
x1 = z * polevl(z, P2, 8) / p1evl(z, Q2, 8);
}
x = x0 - x1;
if (code != 0) {
x = -x;
}
return (x);
}
/**
* Returns natural logarithm of gamma function.
*
* @param x the value
* @return natural logarithm of gamma function
*/
public static double lnGamma(double x) {
double p, q, w, z;
double A[] = { 8.11614167470508450300E-4, -5.95061904284301438324E-4,
7.93650340457716943945E-4, -2.77777777730099687205E-3,
8.33333333333331927722E-2 };
double B[] = { -1.37825152569120859100E3, -3.88016315134637840924E4,
-3.31612992738871184744E5, -1.16237097492762307383E6,
-1.72173700820839662146E6, -8.53555664245765465627E5 };
double C[] = {
/* 1.00000000000000000000E0, */
-3.51815701436523470549E2, -1.70642106651881159223E4,
-2.20528590553854454839E5, -1.13933444367982507207E6,
-2.53252307177582951285E6, -2.01889141433532773231E6 };
if (x < -34.0) {
q = -x;
w = lnGamma(q);
p = Math.floor(q);
if (p == q) {
throw new ArithmeticException("lnGamma: Overflow");
}
z = q - p;
if (z > 0.5) {
p += 1.0;
z = p - q;
}
z = q * Math.sin(Math.PI * z);
if (z == 0.0) {
throw new ArithmeticException("lnGamma: Overflow");
}
z = LOGPI - Math.log(z) - w;
return z;
}
if (x < 13.0) {
z = 1.0;
while (x >= 3.0) {
x -= 1.0;
z *= x;
}
while (x < 2.0) {
if (x == 0.0) {
throw new ArithmeticException("lnGamma: Overflow");
}
z /= x;
x += 1.0;
}
if (z < 0.0) {
z = -z;
}
if (x == 2.0) {
return Math.log(z);
}
x -= 2.0;
p = x * polevl(x, B, 5) / p1evl(x, C, 6);
return (Math.log(z) + p);
}
if (x > 2.556348e305) {
throw new ArithmeticException("lnGamma: Overflow");
}
q = (x - 0.5) * Math.log(x) - x + 0.91893853320467274178;
if (x > 1.0e8) {
return (q);
}
p = 1.0 / (x * x);
if (x >= 1000.0) {
q += ((7.9365079365079365079365e-4 * p - 2.7777777777777777777778e-3) * p + 0.0833333333333333333333)
/ x;
} else {
q += polevl(p, A, 4) / x;
}
return q;
}
/**
* Returns the error function of the normal distribution. The integral is
*
* <pre>
* x
* -
* 2 | | 2
* erf(x) = -------- | exp( - t ) dt.
* sqrt(pi) | |
* -
* 0
* </pre>
*
* <b>Implementation:</b> For
* <tt>0 <= |x| < 1, erf(x) = x * P4(x**2)/Q5(x**2)</tt>; otherwise
* <tt>erf(x) = 1 - erfc(x)</tt>.
* <p>
* Code adapted from the <A
* HREF="http://www.sci.usq.edu.au/staff/leighb/graph/Top.html"> Java 2D Graph
* Package 2.4</A>, which in turn is a port from the <A
* HREF="http://people.ne.mediaone.net/moshier/index.html#Cephes">Cephes
* 2.2</A> Math Library (C).
*
* @param a the argument to the function.
*/
public static double errorFunction(double x) {
double y, z;
final double T[] = { 9.60497373987051638749E0, 9.00260197203842689217E1,
2.23200534594684319226E3, 7.00332514112805075473E3,
5.55923013010394962768E4 };
final double U[] = {
// 1.00000000000000000000E0,
3.35617141647503099647E1, 5.21357949780152679795E2,
4.59432382970980127987E3, 2.26290000613890934246E4,
4.92673942608635921086E4 };
if (Math.abs(x) > 1.0) {
return (1.0 - errorFunctionComplemented(x));
}
z = x * x;
y = x * polevl(z, T, 4) / p1evl(z, U, 5);
return y;
}
/**
* Returns the complementary Error function of the normal distribution.
*
* <pre>
* 1 - erf(x) =
*
* inf.
* -
* 2 | | 2
* erfc(x) = -------- | exp( - t ) dt
* sqrt(pi) | |
* -
* x
* </pre>
*
* <b>Implementation:</b> For small x, <tt>erfc(x) = 1 - erf(x)</tt>;
* otherwise rational approximations are computed.
* <p>
* Code adapted from the <A
* HREF="http://www.sci.usq.edu.au/staff/leighb/graph/Top.html"> Java 2D Graph
* Package 2.4</A>, which in turn is a port from the <A
* HREF="http://people.ne.mediaone.net/moshier/index.html#Cephes">Cephes
* 2.2</A> Math Library (C).
*
* @param a the argument to the function.
*/
public static double errorFunctionComplemented(double a) {
double x, y, z, p, q;
double P[] = { 2.46196981473530512524E-10, 5.64189564831068821977E-1,
7.46321056442269912687E0, 4.86371970985681366614E1,
1.96520832956077098242E2, 5.26445194995477358631E2,
9.34528527171957607540E2, 1.02755188689515710272E3,
5.57535335369399327526E2 };
double Q[] = {
// 1.0
1.32281951154744992508E1, 8.67072140885989742329E1,
3.54937778887819891062E2, 9.75708501743205489753E2,
1.82390916687909736289E3, 2.24633760818710981792E3,
1.65666309194161350182E3, 5.57535340817727675546E2 };
double R[] = { 5.64189583547755073984E-1, 1.27536670759978104416E0,
5.01905042251180477414E0, 6.16021097993053585195E0,
7.40974269950448939160E0, 2.97886665372100240670E0 };
double S[] = {
// 1.00000000000000000000E0,
2.26052863220117276590E0, 9.39603524938001434673E0,
1.20489539808096656605E1, 1.70814450747565897222E1,
9.60896809063285878198E0, 3.36907645100081516050E0 };
if (a < 0.0) {
x = -a;
} else {
x = a;
}
if (x < 1.0) {
return 1.0 - errorFunction(a);
}
z = -a * a;
if (z < -MAXLOG) {
if (a < 0) {
return (2.0);
} else {
return (0.0);
}
}
z = Math.exp(z);
if (x < 8.0) {
p = polevl(x, P, 8);
q = p1evl(x, Q, 8);
} else {
p = polevl(x, R, 5);
q = p1evl(x, S, 6);
}
y = (z * p) / q;
if (a < 0) {
y = 2.0 - y;
}
if (y == 0.0) {
if (a < 0) {
return 2.0;
} else {
return (0.0);
}
}
return y;
}
/**
* Evaluates the given polynomial of degree <tt>N</tt> at <tt>x</tt>.
* Evaluates polynomial when coefficient of N is 1.0. Otherwise same as
* <tt>polevl()</tt>.
*
* <pre>
* 2 N
* y = C + C x + C x +...+ C x
* 0 1 2 N
*
* Coefficients are stored in reverse order:
*
* coef[0] = C , ..., coef[N] = C .
* N 0
* </pre>
*
* The function <tt>p1evl()</tt> assumes that <tt>coef[N] = 1.0</tt> and is
* omitted from the array. Its calling arguments are otherwise the same as
* <tt>polevl()</tt>.
* <p>
* In the interest of speed, there are no checks for out of bounds arithmetic.
*
* @param x argument to the polynomial.
* @param coef the coefficients of the polynomial.
* @param N the degree of the polynomial.
*/
public static double p1evl(double x, double coef[], int N) {
double ans;
ans = x + coef[0];
for (int i = 1; i < N; i++) {
ans = ans * x + coef[i];
}
return ans;
}
/**
* Evaluates the given polynomial of degree <tt>N</tt> at <tt>x</tt>.
*
* <pre>
* 2 N
* y = C + C x + C x +...+ C x
* 0 1 2 N
*
* Coefficients are stored in reverse order:
*
* coef[0] = C , ..., coef[N] = C .
* N 0
* </pre>
*
* In the interest of speed, there are no checks for out of bounds arithmetic.
*
* @param x argument to the polynomial.
* @param coef the coefficients of the polynomial.
* @param N the degree of the polynomial.
*/
public static double polevl(double x, double coef[], int N) {
double ans;
ans = coef[0];
for (int i = 1; i <= N; i++) {
ans = ans * x + coef[i];
}
return ans;
}
/**
* Returns the Incomplete Gamma function.
*
* @param a the parameter of the gamma distribution.
* @param x the integration end point.
*/
public static double incompleteGamma(double a, double x) {
double ans, ax, c, r;
if (x <= 0 || a <= 0) {
return 0.0;
}
if (x > 1.0 && x > a) {
return 1.0 - incompleteGammaComplement(a, x);
}
/* Compute x**a * exp(-x) / gamma(a) */
ax = a * Math.log(x) - x - lnGamma(a);
if (ax < -MAXLOG) {
return (0.0);
}
ax = Math.exp(ax);
/* power series */
r = a;
c = 1.0;
ans = 1.0;
do {
r += 1.0;
c *= x / r;
ans += c;
} while (c / ans > MACHEP);
return (ans * ax / a);
}
/**
* Returns the Complemented Incomplete Gamma function.
*
* @param a the parameter of the gamma distribution.
* @param x the integration start point.
*/
public static double incompleteGammaComplement(double a, double x) {
double ans, ax, c, yc, r, t, y, z;
double pk, pkm1, pkm2, qk, qkm1, qkm2;
if (x <= 0 || a <= 0) {
return 1.0;
}
if (x < 1.0 || x < a) {
return 1.0 - incompleteGamma(a, x);
}
ax = a * Math.log(x) - x - lnGamma(a);
if (ax < -MAXLOG) {
return 0.0;
}
ax = Math.exp(ax);
/* continued fraction */
y = 1.0 - a;
z = x + y + 1.0;
c = 0.0;
pkm2 = 1.0;
qkm2 = x;
pkm1 = x + 1.0;
qkm1 = z * x;
ans = pkm1 / qkm1;
do {
c += 1.0;
y += 1.0;
z += 2.0;
yc = y * c;
pk = pkm1 * z - pkm2 * yc;
qk = qkm1 * z - qkm2 * yc;
if (qk != 0) {
r = pk / qk;
t = Math.abs((ans - r) / r);
ans = r;
} else {
t = 1.0;
}
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if (Math.abs(pk) > big) {
pkm2 *= biginv;
pkm1 *= biginv;
qkm2 *= biginv;
qkm1 *= biginv;
}
} while (t > MACHEP);
return ans * ax;
}
/**
* Returns the Gamma function of the argument.
*/
public static double gamma(double x) {
double P[] = { 1.60119522476751861407E-4, 1.19135147006586384913E-3,
1.04213797561761569935E-2, 4.76367800457137231464E-2,
2.07448227648435975150E-1, 4.94214826801497100753E-1,
9.99999999999999996796E-1 };
double Q[] = { -2.31581873324120129819E-5, 5.39605580493303397842E-4,
-4.45641913851797240494E-3, 1.18139785222060435552E-2,
3.58236398605498653373E-2, -2.34591795718243348568E-1,
7.14304917030273074085E-2, 1.00000000000000000320E0 };
double p, z;
double q = Math.abs(x);
if (q > 33.0) {
if (x < 0.0) {
p = Math.floor(q);
if (p == q) {
throw new ArithmeticException("gamma: overflow");
}
z = q - p;
if (z > 0.5) {
p += 1.0;
z = q - p;
}
z = q * Math.sin(Math.PI * z);
if (z == 0.0) {
throw new ArithmeticException("gamma: overflow");
}
z = Math.abs(z);
z = Math.PI / (z * stirlingFormula(q));
return -z;
} else {
return stirlingFormula(x);
}
}
z = 1.0;
while (x >= 3.0) {
x -= 1.0;
z *= x;
}
while (x < 0.0) {
if (x == 0.0) {
throw new ArithmeticException("gamma: singular");
} else if (x > -1.E-9) {
return (z / ((1.0 + 0.5772156649015329 * x) * x));
}
z /= x;
x += 1.0;
}
while (x < 2.0) {
if (x == 0.0) {
throw new ArithmeticException("gamma: singular");
} else if (x < 1.e-9) {
return (z / ((1.0 + 0.5772156649015329 * x) * x));
}
z /= x;
x += 1.0;
}
if ((x == 2.0) || (x == 3.0)) {
return z;
}
x -= 2.0;
p = polevl(x, P, 6);
q = polevl(x, Q, 7);
return z * p / q;
}
/**
* Returns the Gamma function computed by Stirling's formula. The polynomial
* STIR is valid for 33 <= x <= 172.
*/
public static double stirlingFormula(double x) {
double STIR[] = { 7.87311395793093628397E-4, -2.29549961613378126380E-4,
-2.68132617805781232825E-3, 3.47222221605458667310E-3,
8.33333333333482257126E-2, };
double MAXSTIR = 143.01608;
double w = 1.0 / x;
double y = Math.exp(x);
w = 1.0 + w * polevl(w, STIR, 4);
if (x > MAXSTIR) {
/* Avoid overflow in Math.pow() */
double v = Math.pow(x, 0.5 * x - 0.25);
y = v * (v / y);
} else {
y = Math.pow(x, x - 0.5) / y;
}
y = SQTPI * y * w;
return y;
}
/**
* Returns the Incomplete Beta Function evaluated from zero to <tt>xx</tt>.
*
* @param aa the alpha parameter of the beta distribution.
* @param bb the beta parameter of the beta distribution.
* @param xx the integration end point.
*/
public static double incompleteBeta(double aa, double bb, double xx) {
double a, b, t, x, xc, w, y;
boolean flag;
if (aa <= 0.0 || bb <= 0.0) {
throw new ArithmeticException("ibeta: Domain error!");
}
if ((xx <= 0.0) || (xx >= 1.0)) {
if (xx == 0.0) {
return 0.0;
}
if (xx == 1.0) {
return 1.0;
}
throw new ArithmeticException("ibeta: Domain error!");
}
flag = false;
if ((bb * xx) <= 1.0 && xx <= 0.95) {
t = powerSeries(aa, bb, xx);
return t;
}
w = 1.0 - xx;
/* Reverse a and b if x is greater than the mean. */
if (xx > (aa / (aa + bb))) {
flag = true;
a = bb;
b = aa;
xc = xx;
x = w;
} else {
a = aa;
b = bb;
xc = w;
x = xx;
}
if (flag && (b * x) <= 1.0 && x <= 0.95) {
t = powerSeries(a, b, x);
if (t <= MACHEP) {
t = 1.0 - MACHEP;
} else {
t = 1.0 - t;
}
return t;
}
/* Choose expansion for better convergence. */
y = x * (a + b - 2.0) - (a - 1.0);
if (y < 0.0) {
w = incompleteBetaFraction1(a, b, x);
} else {
w = incompleteBetaFraction2(a, b, x) / xc;
}
/*
* Multiply w by the factor a b _ _ _ x (1-x) | (a+b) / ( a | (a) | (b) ) .
*/
y = a * Math.log(x);
t = b * Math.log(xc);
if ((a + b) < MAXGAM && Math.abs(y) < MAXLOG && Math.abs(t) < MAXLOG) {
t = Math.pow(xc, b);
t *= Math.pow(x, a);
t /= a;
t *= w;
t *= gamma(a + b) / (gamma(a) * gamma(b));
if (flag) {
if (t <= MACHEP) {
t = 1.0 - MACHEP;
} else {
t = 1.0 - t;
}
}
return t;
}
/* Resort to logarithms. */
y += t + lnGamma(a + b) - lnGamma(a) - lnGamma(b);
y += Math.log(w / a);
if (y < MINLOG) {
t = 0.0;
} else {
t = Math.exp(y);
}
if (flag) {
if (t <= MACHEP) {
t = 1.0 - MACHEP;
} else {
t = 1.0 - t;
}
}
return t;
}
/**
* Continued fraction expansion #1 for incomplete beta integral.
*/
public static double incompleteBetaFraction1(double a, double b, double x) {
double xk, pk, pkm1, pkm2, qk, qkm1, qkm2;
double k1, k2, k3, k4, k5, k6, k7, k8;
double r, t, ans, thresh;
int n;
k1 = a;
k2 = a + b;
k3 = a;
k4 = a + 1.0;
k5 = 1.0;
k6 = b - 1.0;
k7 = k4;
k8 = a + 2.0;
pkm2 = 0.0;
qkm2 = 1.0;
pkm1 = 1.0;
qkm1 = 1.0;
ans = 1.0;
r = 1.0;
n = 0;
thresh = 3.0 * MACHEP;
do {
xk = -(x * k1 * k2) / (k3 * k4);
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
xk = (x * k5 * k6) / (k7 * k8);
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if (qk != 0) {
r = pk / qk;
}
if (r != 0) {
t = Math.abs((ans - r) / r);
ans = r;
} else {
t = 1.0;
}
if (t < thresh) {
return ans;
}
k1 += 1.0;
k2 += 1.0;
k3 += 2.0;
k4 += 2.0;
k5 += 1.0;
k6 -= 1.0;
k7 += 2.0;
k8 += 2.0;
if ((Math.abs(qk) + Math.abs(pk)) > big) {
pkm2 *= biginv;
pkm1 *= biginv;
qkm2 *= biginv;
qkm1 *= biginv;
}
if ((Math.abs(qk) < biginv) || (Math.abs(pk) < biginv)) {
pkm2 *= big;
pkm1 *= big;
qkm2 *= big;
qkm1 *= big;
}
} while (++n < 300);
return ans;
}
/**
* Continued fraction expansion #2 for incomplete beta integral.
*/
public static double incompleteBetaFraction2(double a, double b, double x) {
double xk, pk, pkm1, pkm2, qk, qkm1, qkm2;
double k1, k2, k3, k4, k5, k6, k7, k8;
double r, t, ans, z, thresh;
int n;
k1 = a;
k2 = b - 1.0;
k3 = a;
k4 = a + 1.0;
k5 = 1.0;
k6 = a + b;
k7 = a + 1.0;
;
k8 = a + 2.0;
pkm2 = 0.0;
qkm2 = 1.0;
pkm1 = 1.0;
qkm1 = 1.0;
z = x / (1.0 - x);
ans = 1.0;
r = 1.0;
n = 0;
thresh = 3.0 * MACHEP;
do {
xk = -(z * k1 * k2) / (k3 * k4);
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
xk = (z * k5 * k6) / (k7 * k8);
pk = pkm1 + pkm2 * xk;
qk = qkm1 + qkm2 * xk;
pkm2 = pkm1;
pkm1 = pk;
qkm2 = qkm1;
qkm1 = qk;
if (qk != 0) {
r = pk / qk;
}
if (r != 0) {
t = Math.abs((ans - r) / r);
ans = r;
} else {
t = 1.0;
}
if (t < thresh) {
return ans;
}
k1 += 1.0;
k2 -= 1.0;
k3 += 2.0;
k4 += 2.0;
k5 += 1.0;
k6 += 1.0;
k7 += 2.0;
k8 += 2.0;
if ((Math.abs(qk) + Math.abs(pk)) > big) {
pkm2 *= biginv;
pkm1 *= biginv;
qkm2 *= biginv;
qkm1 *= biginv;
}
if ((Math.abs(qk) < biginv) || (Math.abs(pk) < biginv)) {
pkm2 *= big;
pkm1 *= big;
qkm2 *= big;
qkm1 *= big;
}
} while (++n < 300);
return ans;
}
/**
* Power series for incomplete beta integral. Use when b*x is small and x not
* too close to 1.
*/
public static double powerSeries(double a, double b, double x) {
double s, t, u, v, n, t1, z, ai;
ai = 1.0 / a;
u = (1.0 - b) * x;
v = u / (a + 1.0);
t1 = v;
t = u;
n = 2.0;
s = 0.0;
z = MACHEP * ai;
while (Math.abs(v) > z) {
u = (n - b) * x / n;
t *= u;
v = t / (a + n);
s += v;
n += 1.0;
}
s += t1;
s += ai;
u = a * Math.log(x);
if ((a + b) < MAXGAM && Math.abs(u) < MAXLOG) {
t = gamma(a + b) / (gamma(a) * gamma(b));
s = s * t * Math.pow(x, a);
} else {
t = lnGamma(a + b) - lnGamma(a) - lnGamma(b) + u + Math.log(s);
if (t < MINLOG) {
s = 0.0;
} else {
s = Math.exp(t);
}
}
return s;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*/
public static void main(String[] ops) {
System.out.println("Binomial standard error (0.5, 100): "
+ Statistics.binomialStandardError(0.5, 100));
System.out.println("Chi-squared probability (2.558, 10): "
+ Statistics.chiSquaredProbability(2.558, 10));
System.out.println("Normal probability (0.2): "
+ Statistics.normalProbability(0.2));
System.out.println("F probability (5.1922, 4, 5): "
+ Statistics.FProbability(5.1922, 4, 5));
System.out.println("lnGamma(6): " + Statistics.lnGamma(6));
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Stopwords.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Stopwords.java
* Copyright (C) 2001-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Vector;
/**
* Class that can test whether a given string is a stop word. Lowercases all
* words before the test.
* <p/>
* The format for reading and writing is one word per line, lines starting with
* '#' are interpreted as comments and therefore skipped.
* <p/>
* The default stopwords are based on <a
* href="http://www.cs.cmu.edu/~mccallum/bow/rainbow/"
* target="_blank">Rainbow</a>.
* <p/>
*
* Accepts the following parameter:
* <p/>
*
* -i file <br/>
* loads the stopwords from the given file
* <p/>
*
* -o file <br/>
* saves the stopwords to the given file
* <p/>
*
* -p <br/>
* outputs the current stopwords on stdout
* <p/>
*
* Any additional parameters are interpreted as words to test as stopwords.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author Ashraf M. Kibriya (amk14@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Stopwords implements RevisionHandler {
/** The hash set containing the list of stopwords */
protected HashSet<String> m_Words = null;
/** The default stopwords object (stoplist based on Rainbow) */
protected static Stopwords m_Stopwords;
static {
if (m_Stopwords == null) {
m_Stopwords = new Stopwords();
}
}
/**
* initializes the stopwords (based on <a
* href="http://www.cs.cmu.edu/~mccallum/bow/rainbow/"
* target="_blank">Rainbow</a>).
*/
public Stopwords() {
m_Words = new HashSet<String>();
// Stopwords list from Rainbow
add("a");
add("able");
add("about");
add("above");
add("according");
add("accordingly");
add("across");
add("actually");
add("after");
add("afterwards");
add("again");
add("against");
add("all");
add("allow");
add("allows");
add("almost");
add("alone");
add("along");
add("already");
add("also");
add("although");
add("always");
add("am");
add("among");
add("amongst");
add("an");
add("and");
add("another");
add("any");
add("anybody");
add("anyhow");
add("anyone");
add("anything");
add("anyway");
add("anyways");
add("anywhere");
add("apart");
add("appear");
add("appreciate");
add("appropriate");
add("are");
add("around");
add("as");
add("aside");
add("ask");
add("asking");
add("associated");
add("at");
add("available");
add("away");
add("awfully");
add("b");
add("be");
add("became");
add("because");
add("become");
add("becomes");
add("becoming");
add("been");
add("before");
add("beforehand");
add("behind");
add("being");
add("believe");
add("below");
add("beside");
add("besides");
add("best");
add("better");
add("between");
add("beyond");
add("both");
add("brief");
add("but");
add("by");
add("c");
add("came");
add("can");
add("cannot");
add("cant");
add("cause");
add("causes");
add("certain");
add("certainly");
add("changes");
add("clearly");
add("co");
add("com");
add("come");
add("comes");
add("concerning");
add("consequently");
add("consider");
add("considering");
add("contain");
add("containing");
add("contains");
add("corresponding");
add("could");
add("course");
add("currently");
add("d");
add("definitely");
add("described");
add("despite");
add("did");
add("different");
add("do");
add("does");
add("doing");
add("done");
add("down");
add("downwards");
add("during");
add("e");
add("each");
add("edu");
add("eg");
add("eight");
add("either");
add("else");
add("elsewhere");
add("enough");
add("entirely");
add("especially");
add("et");
add("etc");
add("even");
add("ever");
add("every");
add("everybody");
add("everyone");
add("everything");
add("everywhere");
add("ex");
add("exactly");
add("example");
add("except");
add("f");
add("far");
add("few");
add("fifth");
add("first");
add("five");
add("followed");
add("following");
add("follows");
add("for");
add("former");
add("formerly");
add("forth");
add("four");
add("from");
add("further");
add("furthermore");
add("g");
add("get");
add("gets");
add("getting");
add("given");
add("gives");
add("go");
add("goes");
add("going");
add("gone");
add("got");
add("gotten");
add("greetings");
add("h");
add("had");
add("happens");
add("hardly");
add("has");
add("have");
add("having");
add("he");
add("hello");
add("help");
add("hence");
add("her");
add("here");
add("hereafter");
add("hereby");
add("herein");
add("hereupon");
add("hers");
add("herself");
add("hi");
add("him");
add("himself");
add("his");
add("hither");
add("hopefully");
add("how");
add("howbeit");
add("however");
add("i");
add("ie");
add("if");
add("ignored");
add("immediate");
add("in");
add("inasmuch");
add("inc");
add("indeed");
add("indicate");
add("indicated");
add("indicates");
add("inner");
add("insofar");
add("instead");
add("into");
add("inward");
add("is");
add("it");
add("its");
add("itself");
add("j");
add("just");
add("k");
add("keep");
add("keeps");
add("kept");
add("know");
add("knows");
add("known");
add("l");
add("last");
add("lately");
add("later");
add("latter");
add("latterly");
add("least");
add("less");
add("lest");
add("let");
add("like");
add("liked");
add("likely");
add("little");
add("ll"); // added to avoid words like you'll,I'll etc.
add("look");
add("looking");
add("looks");
add("ltd");
add("m");
add("mainly");
add("many");
add("may");
add("maybe");
add("me");
add("mean");
add("meanwhile");
add("merely");
add("might");
add("more");
add("moreover");
add("most");
add("mostly");
add("much");
add("must");
add("my");
add("myself");
add("n");
add("name");
add("namely");
add("nd");
add("near");
add("nearly");
add("necessary");
add("need");
add("needs");
add("neither");
add("never");
add("nevertheless");
add("new");
add("next");
add("nine");
add("no");
add("nobody");
add("non");
add("none");
add("noone");
add("nor");
add("normally");
add("not");
add("nothing");
add("novel");
add("now");
add("nowhere");
add("o");
add("obviously");
add("of");
add("off");
add("often");
add("oh");
add("ok");
add("okay");
add("old");
add("on");
add("once");
add("one");
add("ones");
add("only");
add("onto");
add("or");
add("other");
add("others");
add("otherwise");
add("ought");
add("our");
add("ours");
add("ourselves");
add("out");
add("outside");
add("over");
add("overall");
add("own");
add("p");
add("particular");
add("particularly");
add("per");
add("perhaps");
add("placed");
add("please");
add("plus");
add("possible");
add("presumably");
add("probably");
add("provides");
add("q");
add("que");
add("quite");
add("qv");
add("r");
add("rather");
add("rd");
add("re");
add("really");
add("reasonably");
add("regarding");
add("regardless");
add("regards");
add("relatively");
add("respectively");
add("right");
add("s");
add("said");
add("same");
add("saw");
add("say");
add("saying");
add("says");
add("second");
add("secondly");
add("see");
add("seeing");
add("seem");
add("seemed");
add("seeming");
add("seems");
add("seen");
add("self");
add("selves");
add("sensible");
add("sent");
add("serious");
add("seriously");
add("seven");
add("several");
add("shall");
add("she");
add("should");
add("since");
add("six");
add("so");
add("some");
add("somebody");
add("somehow");
add("someone");
add("something");
add("sometime");
add("sometimes");
add("somewhat");
add("somewhere");
add("soon");
add("sorry");
add("specified");
add("specify");
add("specifying");
add("still");
add("sub");
add("such");
add("sup");
add("sure");
add("t");
add("take");
add("taken");
add("tell");
add("tends");
add("th");
add("than");
add("thank");
add("thanks");
add("thanx");
add("that");
add("thats");
add("the");
add("their");
add("theirs");
add("them");
add("themselves");
add("then");
add("thence");
add("there");
add("thereafter");
add("thereby");
add("therefore");
add("therein");
add("theres");
add("thereupon");
add("these");
add("they");
add("think");
add("third");
add("this");
add("thorough");
add("thoroughly");
add("those");
add("though");
add("three");
add("through");
add("throughout");
add("thru");
add("thus");
add("to");
add("together");
add("too");
add("took");
add("toward");
add("towards");
add("tried");
add("tries");
add("truly");
add("try");
add("trying");
add("twice");
add("two");
add("u");
add("un");
add("under");
add("unfortunately");
add("unless");
add("unlikely");
add("until");
add("unto");
add("up");
add("upon");
add("us");
add("use");
add("used");
add("useful");
add("uses");
add("using");
add("usually");
add("uucp");
add("v");
add("value");
add("various");
add("ve"); // added to avoid words like I've,you've etc.
add("very");
add("via");
add("viz");
add("vs");
add("w");
add("want");
add("wants");
add("was");
add("way");
add("we");
add("welcome");
add("well");
add("went");
add("were");
add("what");
add("whatever");
add("when");
add("whence");
add("whenever");
add("where");
add("whereafter");
add("whereas");
add("whereby");
add("wherein");
add("whereupon");
add("wherever");
add("whether");
add("which");
add("while");
add("whither");
add("who");
add("whoever");
add("whole");
add("whom");
add("whose");
add("why");
add("will");
add("willing");
add("wish");
add("with");
add("within");
add("without");
add("wonder");
add("would");
add("would");
add("x");
add("y");
add("yes");
add("yet");
add("you");
add("your");
add("yours");
add("yourself");
add("yourselves");
add("z");
add("zero");
}
/**
* removes all stopwords
*/
public void clear() {
m_Words.clear();
}
/**
* adds the given word to the stopword list (is automatically converted to
* lower case and trimmed)
*
* @param word the word to add
*/
public void add(String word) {
if (word.trim().length() > 0) {
m_Words.add(word.trim().toLowerCase());
}
}
/**
* removes the word from the stopword list
*
* @param word the word to remove
* @return true if the word was found in the list and then removed
*/
public boolean remove(String word) {
return m_Words.remove(word);
}
/**
* Returns true if the given string is a stop word.
*
* @param word the word to test
* @return true if the word is a stopword
*/
public boolean is(String word) {
return m_Words.contains(word.toLowerCase());
}
/**
* Returns a sorted enumeration over all stored stopwords
*
* @return the enumeration over all stopwords
*/
public Enumeration<String> elements() {
Vector<String> list = new Vector<String>();
list.addAll(m_Words);
// sort list
Collections.sort(list);
return list.elements();
}
/**
* Generates a new Stopwords object from the given file
*
* @param filename the file to read the stopwords from
* @throws Exception if reading fails
*/
public void read(String filename) throws Exception {
read(new File(filename));
}
/**
* Generates a new Stopwords object from the given file
*
* @param file the file to read the stopwords from
* @throws Exception if reading fails
*/
public void read(File file) throws Exception {
read(new BufferedReader(new FileReader(file)));
}
/**
* Generates a new Stopwords object from the reader. The reader is closed
* automatically.
*
* @param reader the reader to get the stopwords from
* @throws Exception if reading fails
*/
public void read(BufferedReader reader) throws Exception {
String line;
clear();
while ((line = reader.readLine()) != null) {
line = line.trim();
// comment?
if (line.startsWith("#")) {
continue;
}
add(line);
}
reader.close();
}
/**
* Writes the current stopwords to the given file
*
* @param filename the file to write the stopwords to
* @throws Exception if writing fails
*/
public void write(String filename) throws Exception {
write(new File(filename));
}
/**
* Writes the current stopwords to the given file
*
* @param file the file to write the stopwords to
* @throws Exception if writing fails
*/
public void write(File file) throws Exception {
write(new BufferedWriter(new FileWriter(file)));
}
/**
* Writes the current stopwords to the given writer. The writer is closed
* automatically.
*
* @param writer the writer to get the stopwords from
* @throws Exception if writing fails
*/
public void write(BufferedWriter writer) throws Exception {
Enumeration<String> enm;
// header
writer.write("# generated " + new Date());
writer.newLine();
enm = elements();
while (enm.hasMoreElements()) {
writer.write(enm.nextElement().toString());
writer.newLine();
}
writer.flush();
writer.close();
}
/**
* returns the current stopwords in a string
*
* @return the current stopwords
*/
@Override
public String toString() {
Enumeration<String> enm;
StringBuffer result;
result = new StringBuffer();
enm = elements();
while (enm.hasMoreElements()) {
result.append(enm.nextElement().toString());
if (enm.hasMoreElements()) {
result.append(",");
}
}
return result.toString();
}
/**
* Returns true if the given string is a stop word.
*
* @param str the word to test
* @return true if the word is a stopword
*/
public static boolean isStopword(String str) {
return m_Stopwords.is(str.toLowerCase());
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Accepts the following parameter:
* <p/>
*
* -i file <br/>
* loads the stopwords from the given file
* <p/>
*
* -o file <br/>
* saves the stopwords to the given file
* <p/>
*
* -p <br/>
* outputs the current stopwords on stdout
* <p/>
*
* Any additional parameters are interpreted as words to test as stopwords.
*
* @param args commandline parameters
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
String input = Utils.getOption('i', args);
String output = Utils.getOption('o', args);
boolean print = Utils.getFlag('p', args);
// words to process?
Vector<String> words = new Vector<String>();
for (String arg : args) {
if (arg.trim().length() > 0) {
words.add(arg.trim());
}
}
Stopwords stopwords = new Stopwords();
// load from file?
if (input.length() != 0) {
stopwords.read(input);
}
// write to file?
if (output.length() != 0) {
stopwords.write(output);
}
// output to stdout?
if (print) {
System.out.println("\nStopwords:");
Enumeration<String> enm = stopwords.elements();
int i = 0;
while (enm.hasMoreElements()) {
System.out.println((i + 1) + ". " + enm.nextElement());
i++;
}
}
// check words for being a stopword
if (words.size() > 0) {
System.out.println("\nChecking for stopwords:");
for (int i = 0; i < words.size(); i++) {
System.out.println((i + 1) + ". " + words.get(i) + ": "
+ stopwords.is(words.get(i).toString()));
}
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/StringLocator.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* StringLocator.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
/**
* This class locates and records the indices of String attributes, recursively
* in case of Relational attributes. The indices are normally used for copying
* the Strings from one Instances object to another.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Attribute#STRING
* @see Attribute#RELATIONAL
*/
public class StringLocator extends AttributeLocator {
/** for serialization */
private static final long serialVersionUID = 7805522230268783972L;
/**
* initializes the StringLocator with the given data
*
* @param data the data to work on
*/
public StringLocator(Instances data) {
super(data, Attribute.STRING);
}
/**
* Initializes the StringLocator with the given data. Checks only the given
* range.
*
* @param data the data to work on
* @param fromIndex the first index to inspect (including)
* @param toIndex the last index to check (including)
*/
public StringLocator(Instances data, int fromIndex, int toIndex) {
super(data, Attribute.STRING, fromIndex, toIndex);
}
/**
* Initializes the AttributeLocator with the given data. Checks only the
* specified attribute indices.
*
* @param data the data to work on
* @param indices the attribute indices to check
*/
public StringLocator(Instances data, int[] indices) {
super(data, Attribute.STRING, indices);
}
/**
* Copies string values contained in the instance copied to a new dataset. The
* Instance must already be assigned to a dataset. This dataset and the
* destination dataset must have the same structure.
*
* @param inst the Instance containing the string values to copy.
* @param destDataset the destination set of Instances
* @param strAtts an AttributeLocator containing the indices of any string
* attributes in the dataset.
*/
public static void copyStringValues(Instance inst, Instances destDataset,
AttributeLocator strAtts) {
if (inst.dataset() == null) {
throw new IllegalArgumentException("Instance has no dataset assigned!!");
} else if (inst.dataset().numAttributes() != destDataset.numAttributes()) {
throw new IllegalArgumentException(
"Src and Dest differ in # of attributes: "
+ inst.dataset().numAttributes() + " != "
+ destDataset.numAttributes());
}
copyStringValues(inst, true, inst.dataset(), strAtts, destDataset, strAtts);
}
/**
* Takes string values referenced by an Instance and copies them from a source
* dataset to a destination dataset. The instance references are updated to be
* valid for the destination dataset. The instance may have the structure
* (i.e. number and attribute position) of either dataset (this affects where
* references are obtained from). Only works if the number of string
* attributes is the same in both indices (implicitly these string attributes
* should be semantically same but just with shifted positions).
*
* @param instance the instance containing references to strings in the source
* dataset that will have references updated to be valid for the
* destination dataset.
* @param instSrcCompat true if the instance structure is the same as the
* source, or false if it is the same as the destination (i.e. which
* of the string attribute indices contains the correct locations for
* this instance).
* @param srcDataset the dataset for which the current instance string
* references are valid (after any position mapping if needed)
* @param srcLoc an AttributeLocator containing the indices of string
* attributes in the source datset.
* @param destDataset the dataset for which the current instance string
* references need to be inserted (after any position mapping if
* needed)
* @param destLoc an AttributeLocator containing the indices of string
* attributes in the destination datset.
*/
public static void copyStringValues(Instance instance, boolean instSrcCompat,
Instances srcDataset, AttributeLocator srcLoc, Instances destDataset,
AttributeLocator destLoc) {
if (srcDataset == destDataset) {
return;
}
if (srcLoc.getAttributeIndices().length != destLoc.getAttributeIndices().length) {
throw new IllegalArgumentException(
"Src and Dest string indices differ in length: "
+ srcLoc.getAttributeIndices().length + " != "
+ destLoc.getAttributeIndices().length);
}
if (srcLoc.getLocatorIndices().length != destLoc.getLocatorIndices().length) {
throw new IllegalArgumentException(
"Src and Dest locator indices differ in length: "
+ srcLoc.getLocatorIndices().length + " != "
+ destLoc.getLocatorIndices().length);
}
for (int i = 0; i < srcLoc.getAttributeIndices().length; i++) {
int instIndex = instSrcCompat ? srcLoc.getActualIndex(srcLoc
.getAttributeIndices()[i]) : destLoc.getActualIndex(destLoc
.getAttributeIndices()[i]);
Attribute src = srcDataset.attribute(srcLoc.getActualIndex(srcLoc
.getAttributeIndices()[i]));
Attribute dest = destDataset.attribute(destLoc.getActualIndex(destLoc
.getAttributeIndices()[i]));
if (!instance.isMissing(instIndex)) {
int valIndex = dest.addStringValue(src, (int) instance.value(instIndex));
instance.setValue(instIndex, valIndex);
}
}
// recurse if necessary
int[] srcIndices = srcLoc.getLocatorIndices();
int[] destIndices = destLoc.getLocatorIndices();
for (int i = 0; i < srcIndices.length; i++) {
int index = instSrcCompat ? srcLoc.getActualIndex(srcIndices[i])
: destLoc.getActualIndex(destIndices[i]);
if (instance.isMissing(index)) {
continue;
}
int valueIndex = (int)instance.value(index);
Instances rel = instSrcCompat ? srcDataset.attribute(index).relation(valueIndex)
: destDataset.attribute(index).relation(valueIndex);
AttributeLocator srcStrAttsNew = srcLoc.getLocator(srcIndices[i]);
Instances srcDatasetNew = srcStrAttsNew.getData();
AttributeLocator destStrAttsNew = destLoc.getLocator(destIndices[i]);
Instances destDatasetNew = destStrAttsNew.getData();
for (int n = 0; n < rel.numInstances(); n++) {
copyStringValues(rel.instance(n), instSrcCompat, srcDatasetNew,
srcStrAttsNew, destDatasetNew, destStrAttsNew);
}
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Summarizable.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Summarizable.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Interface to something that provides a short textual summary (as opposed
* to toString() which is usually a fairly complete description) of itself.
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface Summarizable {
/**
* Returns a string that summarizes the object.
*
* @return the object summarized as a string
*/
String toSummaryString();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/SystemInfo.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* SystemInfo.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.Vector;
import weka.gui.LookAndFeel;
/**
* This class prints some information about the system setup, like Java version,
* JVM settings etc. Useful for Bug-Reports.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class SystemInfo implements RevisionHandler {
/** for storing the information */
private Hashtable<String, String> m_Info = null;
/**
* initializes the object and reads the system information
*/
public SystemInfo() {
m_Info = new Hashtable<String, String>();
readProperties();
}
/**
* reads all the properties and stores them in the hashtable
*/
private void readProperties() {
Properties props;
Enumeration<?> enm;
String name;
String[] laf;
String tmpStr;
int i;
Memory mem;
m_Info.clear();
// System information
props = System.getProperties();
enm = props.propertyNames();
while (enm.hasMoreElements()) {
name = (String) enm.nextElement();
m_Info.put(name, (String) props.get(name));
}
// additional WEKA info
m_Info.put("weka.version", Version.VERSION);
// look and feel info
laf = LookAndFeel.getInstalledLookAndFeels();
tmpStr = "";
for (i = 0; i < laf.length; i++) {
if (i > 0) {
tmpStr += ",";
}
tmpStr += laf[i];
}
m_Info.put("ui.installedLookAndFeels", tmpStr);
m_Info.put("ui.currentLookAndFeel", LookAndFeel.getSystemLookAndFeel());
// memory info
mem = new Memory();
m_Info.put("memory.initial",
"" + Utils.doubleToString(Memory.toMegaByte(mem.getInitial()), 1) + "MB"
+ " (" + mem.getInitial() + ")");
m_Info.put("memory.max",
"" + Utils.doubleToString(Memory.toMegaByte(mem.getMax()), 1) + "MB"
+ " (" + mem.getMax() + ")");
}
/**
* returns a copy of the system info. the key is the name of the property and
* the associated object is the value of the property (a string).
*/
public Hashtable<String, String> getSystemInfo() {
return new Hashtable<String, String>(m_Info);
}
/**
* returns a string representation of all the system properties
*/
@Override
public String toString() {
Enumeration<String> enm;
String result;
String key;
Vector<String> keys;
int i;
String value;
result = "";
keys = new Vector<String>();
// get names and sort them
enm = m_Info.keys();
while (enm.hasMoreElements()) {
keys.add(enm.nextElement());
}
Collections.sort(keys);
// generate result
for (i = 0; i < keys.size(); i++) {
key = keys.get(i).toString();
value = m_Info.get(key).toString();
if (key.equals("line.separator")) {
value = Utils.backQuoteChars(value);
}
result += key + ": " + value + "\n";
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* for printing the system info to stdout.
*/
public static void main(String[] args) {
System.out.println(new SystemInfo());
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Tag.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Tag.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.Serializable;
/**
* A <code>Tag</code> simply associates a numeric ID with a String description.
*
* @author <a href="mailto:len@reeltwo.com">Len Trigg</a>
* @version $Revision$
*/
public class Tag implements Serializable, RevisionHandler {
/** for serialization. */
private static final long serialVersionUID = 3326379903447135320L;
/** The ID */
protected int m_ID;
/** The unique string for this tag, doesn't have to be numeric */
protected String m_IDStr;
/** The descriptive text */
protected String m_Readable;
/**
* Creates a new default Tag
*
*/
public Tag() {
this(0, "A new tag", "A new tag", true);
}
/**
* Creates a new <code>Tag</code> instance.
*
* @param ident the ID for the new Tag.
* @param readable the description for the new Tag.
*/
public Tag(int ident, String readable) {
this(ident, "", readable);
}
/**
* Creates a new <code>Tag</code> instance.
*
* @param ident the ID for the new Tag.
* @param identStr the ID string for the new Tag (case-insensitive).
* @param readable the description for the new Tag.
*/
public Tag(int ident, String identStr, String readable) {
this(ident, identStr, readable, true);
}
public Tag(int ident, String identStr, String readable, boolean upperCase) {
m_ID = ident;
if (identStr.length() == 0) {
m_IDStr = "" + ident;
} else {
m_IDStr = identStr;
if (upperCase) {
m_IDStr = identStr.toUpperCase();
}
}
m_Readable = readable;
}
/**
* Gets the numeric ID of the Tag.
*
* @return the ID of the Tag.
*/
public int getID() {
return m_ID;
}
/**
* Sets the numeric ID of the Tag.
*
* @param id the ID of the Tag.
*/
public void setID(int id) {
m_ID = id;
}
/**
* Gets the string ID of the Tag.
*
* @return the string ID of the Tag.
*/
public String getIDStr() {
return m_IDStr;
}
/**
* Sets the string ID of the Tag.
*
* @param str the string ID of the Tag.
*/
public void setIDStr(String str) {
m_IDStr = str;
}
/**
* Gets the string description of the Tag.
*
* @return the description of the Tag.
*/
public String getReadable() {
return m_Readable;
}
/**
* Sets the string description of the Tag.
*
* @param r the description of the Tag.
*/
public void setReadable(String r) {
m_Readable = r;
}
/**
* returns the IDStr
*
* @return the IDStr
*/
public String toString() {
return m_IDStr;
}
/**
* returns a list that can be used in the listOption methods to list all
* the available ID strings, e.g.: <0|1|2> or <what|ever>
*
* @param tags the tags to create the list for
* @return a list of all ID strings
*/
public static String toOptionList(Tag[] tags) {
String result;
int i;
result = "<";
for (i = 0; i < tags.length; i++) {
if (i > 0)
result += "|";
result += tags[i];
}
result += ">";
return result;
}
/**
* returns a string that can be used in the listOption methods to list all
* the available options, i.e., "\t\tID = Text\n" for each option
*
* @param tags the tags to create the string for
* @return a string explaining the tags
*/
public static String toOptionSynopsis(Tag[] tags) {
String result;
int i;
result = "";
for (i = 0; i < tags.length; i++) {
result += "\t\t" + tags[i].getIDStr() + " = " + tags[i].getReadable() + "\n";
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/TechnicalInformation.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* TechnicalInformation.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* Used for paper references in the Javadoc and for BibTex generation. Based on
* documentation found here:
* <p/>
* <a href="http://www.ecst.csuchico.edu/~jacobsd/bib/formats/bibtex.html"
* target
* ="_blank">http://www.ecst.csuchico.edu/~jacobsd/bib/formats/bibtex.html</a>
* <p/>
* BibTex examples can be found here:
* <p/>
* <a href="http://bib2web.djvuzone.org/bibtex.html"
* target="_blank">http://bib2web.djvuzone.org/bibtex.html</a>
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see TechnicalInformationHandler
*/
public class TechnicalInformation implements RevisionHandler {
/** the different types of information */
public enum Type {
/** An article from a journal or magazine. */
ARTICLE("article", "An article from a journal or magazine."),
/** A book with an explicit publisher. */
BOOK("book", "A book with an explicit publisher."),
/**
* A work that is printed and bound, but without a named publisher or
* sponsoring institution.
*/
BOOKLET(
"booklet",
"A work that is printed and bound, but without a named publisher or sponsoring institution."),
/** The same as inproceedings. */
CONFERENCE("conference", "The same as inproceedings."),
/**
* A part of a book, which may be a chapter (or section or whatever) and/or
* a range of pages.
*/
INBOOK(
"inbook",
"A part of a book, which may be a chapter (or section or whatever) and/or a range of pages."),
/** A part of a book having its own title. */
INCOLLECTION("incollection", "A part of a book having its own title."),
/** An article in a conference proceedings. */
INPROCEEDINGS("inproceedings", "An article in a conference proceedings."),
/** Technical documentation. */
MANUAL("manual", "Technical documentation."),
/** A Master's thesis. */
MASTERSTHESIS("mastersthesis", "A Master's thesis."),
/** Use this type when nothing else fits. */
MISC("misc", "Use this type when nothing else fits."),
/** A PhD thesis. */
PHDTHESIS("phdthesis", "A PhD thesis."),
/** The proceedings of a conference. */
PROCEEDINGS("proceedings", "The proceedings of a conference."),
/**
* A report published by a school or other institution, usually numbered
* within a series.
*/
TECHREPORT(
"techreport",
"A report published by a school or other institution, usually numbered within a series."),
/** A document having an author and title, but not formally published. */
UNPUBLISHED("unpublished",
"A document having an author and title, but not formally published.");
/** the string used in toString() */
protected String m_Display;
/** the comment about this type */
protected String m_Comment;
/**
* the constructor
*
* @param display the string to return in toString()
* @param comment a comment about the type
*/
private Type(String display, String comment) {
m_Display = display;
m_Comment = comment;
}
/**
* returns the display string
*
* @return the display string
*/
public String getDisplay() {
return m_Display;
}
/**
* returns the comment string
*
* @return the comment string
*/
public String getComment() {
return m_Comment;
}
/**
* returns the display string of the Type
*
* @return the display string
*/
@Override
public String toString() {
return m_Display;
}
}
/** the possible fields */
public enum Field {
/**
* Usually the address of the publisher or other type of institution. For
* major publishing houses, van Leunen recommends omitting the information
* entirely. For small publishers, on the other hand, you can help the reader
* by giving the complete address.
*/
ADDRESS(
"address",
"Usually the address of the publisher or other type of institution. For major publishing houses, van Leunen recommends omitting the information entirely. For small publishers, on the other hand, you can help the reader by giving the complete address."),
/**
* An annotation. It is not used by the standard bibliography styles, but
* may be used by others that produce an annotated bibliography.
*/
ANNOTE(
"annote",
"An annotation. It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography."),
/** The name(s) of the author(s), in the format described in the LaTeX book. */
AUTHOR("author",
"The name(s) of the author(s), in the format described in the LaTeX book."),
/**
* Title of a book, part of which is being cited. See the LaTeX book for how
* to type titles. For book entries, use the title field instead.
*/
BOOKTITLE(
"booktitle",
"Title of a book, part of which is being cited. See the LaTeX book for how to type titles. For book entries, use the title field instead."),
/** A chapter (or section or whatever) number. */
CHAPTER("chapter", "A chapter (or section or whatever) number."),
/**
* The database key of the entry being cross referenced. Any fields that are
* missing from the current record are inherited from the field being cross
* referenced.
*/
CROSSREF(
"crossref",
"The database key of the entry being cross referenced. Any fields that are missing from the current record are inherited from the field being cross referenced."),
/**
* The edition of a book---for example, ``Second''. This should be an
* ordinal, and should have the first letter capitalized, as shown here; the
* standard styles convert to lower case when necessary.
*/
EDITION(
"edition",
"The edition of a book---for example, ``Second''. This should be an ordinal, and should have the first letter capitalized, as shown here; the standard styles convert to lower case when necessary."),
/**
* Name(s) of editor(s), typed as indicated in the LaTeX book. If there is
* also an author field, then the editor field gives the editor of the book
* or collection in which the reference appears.
*/
EDITOR(
"editor",
"Name(s) of editor(s), typed as indicated in the LaTeX book. If there is also an author field, then the editor field gives the editor of the book or collection in which the reference appears."),
/**
* How something strange has been published. The first word should be
* capitalized.
*/
HOWPUBLISHED(
"howpublished",
"How something strange has been published. The first word should be capitalized."),
/** The sponsoring institution of a technical report. */
INSTITUTION("institution",
"The sponsoring institution of a technical report."),
/** A journal name. Abbreviations are provided for many journals. */
JOURNAL("journal",
"A journal name. Abbreviations are provided for many journals."),
/**
* Used for alphabetizing, cross referencing, and creating a label when the
* ``author'' information is missing. This field should not be confused with
* the key that appears in the cite command and at the beginning of the
* database entry.
*/
KEY(
"key",
"Used for alphabetizing, cross referencing, and creating a label when the ``author'' information is missing. This field should not be confused with the key that appears in the cite command and at the beginning of the database entry."),
/**
* The month in which the work was published or, for an unpublished work, in
* which it was written. You should use the standard three-letter
* abbreviation, as described in Appendix B.1.3 of the LaTeX book.
*/
MONTH(
"month",
"The month in which the work was published or, for an unpublished work, in which it was written. You should use the standard three-letter abbreviation, as described in Appendix B.1.3 of the LaTeX book."),
/**
* Any additional information that can help the reader. The first word
* should be capitalized.
*/
NOTE(
"note",
"Any additional information that can help the reader. The first word should be capitalized."),
/**
* The number of a journal, magazine, technical report, or of a work in a
* series. An issue of a journal or magazine is usually identified by its
* volume and number; the organization that issues a technical report usually
* gives it a number; and sometimes books are given numbers in a named
* series.
*/
NUMBER(
"number",
"The number of a journal, magazine, technical report, or of a work in a series. An issue of a journal or magazine is usually identified by its volume and number; the organization that issues a technical report usually gives it a number; and sometimes books are given numbers in a named series."),
/** The organization that sponsors a conference or that publishes a manual. */
ORGANIZATION("organization",
"The organization that sponsors a conference or that publishes a manual."),
/**
* One or more page numbers or range of numbers, such as 42--111 or
* 7,41,73--97 or 43+ (the `+' in this last example indicates pages
* following that don't form a simple range). To make it easier to maintain
* Scribe-compatible databases, the standard styles convert a single dash (as
* in 7-33) to the double dash used in TeX to denote number ranges (as in
* 7--33).
*/
PAGES(
"pages",
"One or more page numbers or range of numbers, such as 42--111 or 7,41,73--97 or 43+ (the `+' in this last example indicates pages following that don't form a simple range). To make it easier to maintain Scribe-compatible databases, the standard styles convert a single dash (as in 7-33) to the double dash used in TeX to denote number ranges (as in 7--33)."),
/** The publisher's name. */
PUBLISHER("publisher", "The publisher's name."),
/** The name of the school where a thesis was written. */
SCHOOL("school", "The name of the school where a thesis was written."),
/**
* The name of a series or set of books. When citing an entire book, the the
* title field gives its title and an optional series field gives the name
* of a series or multi-volume set in which the book is published.
*/
SERIES(
"series",
"The name of a series or set of books. When citing an entire book, the the title field gives its title and an optional series field gives the name of a series or multi-volume set in which the book is published."),
/** The work's title, typed as explained in the LaTeX book. */
TITLE("title", "The work's title, typed as explained in the LaTeX book."),
/** The type of a technical report---for example, ``Research Note''. */
TYPE("type",
"The type of a technical report---for example, ``Research Note''."),
/** The volume of a journal or multi-volume book. */
VOLUME("volume", "The volume of a journal or multi-volume book."),
/**
* The year of publication or, for an unpublished work, the year it was
* written. Generally it should consist of four numerals, such as 1984,
* although the standard styles can handle any year whose last four
* nonpunctuation characters are numerals, such as `\\hbox{(about 1984)}'.
*/
YEAR(
"year",
"The year of publication or, for an unpublished work, the year it was written. Generally it should consist of four numerals, such as 1984, although the standard styles can handle any year whose last four nonpunctuation characters are numerals, such as `\\hbox{(about 1984)}'."),
// other fields
/** The authors affiliation. */
AFFILIATION("affiliation", "The authors affiliation."),
/** An abstract of the work. */
ABSTRACT("abstract", "An abstract of the work."),
/** A Table of Contents. */
CONTENTS("contents", "A Table of Contents "),
/** Copyright information. */
COPYRIGHT("copyright", "Copyright information."),
/** The International Standard Book Number (10 digits). */
ISBN("ISBN", "The International Standard Book Number (10 digits)."),
/** The International Standard Book Number (13 digits). */
ISBN13("ISBN-13", "The International Standard Book Number (13 digits)."),
/** The International Standard Serial Number. Used to identify a journal. */
ISSN("ISSN",
"The International Standard Serial Number. Used to identify a journal."),
/** Key words used for searching or possibly for annotation. */
KEYWORDS("keywords",
"Key words used for searching or possibly for annotation."),
/** The language the document is in. */
LANGUAGE("language", "The language the document is in."),
/**
* A location associated with the entry, such as the city in which a
* conference took place.
*/
LOCATION(
"location",
"A location associated with the entry, such as the city in which a conference took place."),
/**
* The Library of Congress Call Number. I've also seen this as lib-congress.
*/
LCCN("LCCN",
"The Library of Congress Call Number. I've also seen this as lib-congress."),
/** The Mathematical Reviews number. */
MRNUMBER("mrnumber", "The Mathematical Reviews number."),
/** The price of the document. */
PRICE("price", "The price of the document."),
/** The physical dimensions of a work. */
SIZE("size", "The physical dimensions of a work."),
/**
* The WWW Universal Resource Locator that points to the item being
* referenced. This often is used for technical reports to point to the ftp
* site where the postscript source of the report is located.
*/
URL(
"URL",
"The WWW Universal Resource Locator that points to the item being referenced. This often is used for technical reports to point to the ftp site where the postscript source of the report is located."),
// additional fields
/** A link to a postscript file. */
PS("PS", "A link to a postscript file."),
/** A link to a postscript file. */
PDF("PDF", "A link to a PDF file."),
/** A link to a postscript file. */
HTTP("HTTP", "A hyperlink to a resource.");
/** the string used in toString() */
protected String m_Display;
/** the comment about this type */
protected String m_Comment;
/**
* the constructor
*
* @param display the string to return in toString()
* @param comment a comment about the type
*/
private Field(String display, String comment) {
m_Display = display;
m_Comment = comment;
}
/**
* returns the display string
*
* @return the display string
*/
public String getDisplay() {
return m_Display;
}
/**
* returns the comment string
*
* @return the comment string
*/
public String getComment() {
return m_Comment;
}
/**
* returns the display string of the Type
*
* @return the display string
*/
@Override
public String toString() {
return m_Display;
}
}
/** will be returned if no ID can be generated */
protected final static String MISSING_ID = "missing_id";
/** the type of this technical information */
protected Type m_Type = null;
/**
* the unique identifier of this information, will be generated automatically
* if left empty
*/
protected String m_ID = "";
/** stores all the values associated with the fields (FIELD - String) */
protected Hashtable<Field, String> m_Values = new Hashtable<Field, String>();
/** additional technical informations */
protected Vector<TechnicalInformation> m_Additional = new Vector<TechnicalInformation>();
/**
* Initializes the information with the given type
*
* @param type the type of this information
* @see Type
*/
public TechnicalInformation(Type type) {
this(type, "");
}
/**
* Initializes the information with the given type
*
* @param type the type of this information
* @param id the unique ID (for BibTex), can be empty
* @see Type
*/
public TechnicalInformation(Type type, String id) {
m_Type = type;
m_ID = id;
}
/**
* returns the type of this technical information
*
* @return the type of this information
*/
public Type getType() {
return m_Type;
}
/**
* splits the authors on the " and " and returns a vector with the names
*
* @return the authors in an array
*/
protected String[] getAuthors() {
return getValue(Field.AUTHOR).split(" and ");
}
/**
* Generates an ID based on the current settings and returns it. If nothing
* can be generated the MISSING_ID string will be returned
*
* @return the ID
* @see #MISSING_ID
*/
protected String generateID() {
String result;
String[] authors;
String[] parts;
result = m_ID;
// try surname of first author and year
if (result.length() == 0) {
if (exists(Field.AUTHOR) && exists(Field.YEAR)) {
authors = getAuthors();
if (authors[0].indexOf(",") > -1) {
parts = authors[0].split(",");
result = parts[0];
} else {
parts = authors[0].split(" ");
if (parts.length == 1) {
result = parts[0];
} else {
result = parts[parts.length - 1];
}
}
result += getValue(Field.YEAR);
result = result.replaceAll(" ", "");
}
}
// still nothing?
if (result.length() == 0) {
result = MISSING_ID;
}
return result;
}
/**
* returns the unique ID (either the one used in creating this instance or the
* automatically generated one)
*
* @return the ID for this information
*/
public String getID() {
return generateID();
}
/**
* sets the value for the given field, overwrites any previously existing one.
*
* @param field the field to set the value for
* @param value the value of the field
*/
public void setValue(Field field, String value) {
m_Values.put(field, value);
}
/**
* returns the value associated with the given field, or empty if field is not
* currently stored.
*
* @param field the field to retrieve the value for
* @return the value associated with this field, empty if not existing
*/
public String getValue(Field field) {
if (m_Values.containsKey(field)) {
return m_Values.get(field);
} else {
return "";
}
}
/**
* returns TRUE if the field is stored and has a value different from the
* empty string.
*
* @param field the field to check
* @return true if a value is stored for the field and non-empty
*/
public boolean exists(Field field) {
return (m_Values.containsKey(field) && (m_Values.get(field).length() != 0));
}
/**
* returns an enumeration over all the stored fields
*
* @return all currently stored fields
*/
public Enumeration<Field> fields() {
return m_Values.keys();
}
/**
* returns true if there are further technical informations stored in this
*
* @return true if there are further technical informations available
*/
public boolean hasAdditional() {
return (m_Additional.size() > 0);
}
/**
* returns an enumeration of all the additional technical informations (if
* there are any)
*
* @return an enumeration over all additional technical informations
*/
public Enumeration<TechnicalInformation> additional() {
return m_Additional.elements();
}
/**
* adds the given information to the list of additional technical informations
*
* @param value the information to add
*/
public void add(TechnicalInformation value) {
if (value == this) {
throw new IllegalArgumentException("Can't add object to itself!");
}
m_Additional.add(value);
}
/**
* Adds an empty technical information with the given type to the list of
* additional informations and returns the instance.
*
* @param type the type of the new information to add
* @return the generated information
*/
public TechnicalInformation add(Type type) {
TechnicalInformation result;
result = new TechnicalInformation(type);
add(result);
return result;
}
/**
* Returns a plain-text string representing this technical information. Note:
* it only returns a string based on some fields. At least AUTHOR, YEAR and
* TITLE are necessary.
*
* @return a string representation of this information
*/
@Override
public String toString() {
String result;
String[] authors;
int i;
Enumeration<TechnicalInformation> enm;
result = "";
authors = getAuthors();
// BOOK
if (getType() == Type.BOOK) {
for (i = 0; i < authors.length; i++) {
if (i > 0) {
result += ", ";
}
result += authors[i];
}
if (exists(Field.YEAR)) {
result += " (" + getValue(Field.YEAR) + ").";
} else {
result += ".";
}
result += " " + getValue(Field.TITLE) + ".";
result += " " + getValue(Field.PUBLISHER);
if (exists(Field.ADDRESS)) {
result += ", " + getValue(Field.ADDRESS);
}
result += ".";
}
// ARTICLE
else if (getType() == Type.ARTICLE) {
for (i = 0; i < authors.length; i++) {
if (i > 0) {
result += ", ";
}
result += authors[i];
}
if (exists(Field.YEAR)) {
result += " (" + getValue(Field.YEAR) + ").";
} else {
result += ".";
}
result += " " + getValue(Field.TITLE) + ".";
// journal
if (exists(Field.JOURNAL)) {
result += " " + getValue(Field.JOURNAL) + ".";
if (exists(Field.VOLUME)) {
result += " " + getValue(Field.VOLUME);
}
if (exists(Field.NUMBER)) {
result += "(" + getValue(Field.NUMBER) + ")";
}
if (exists(Field.PAGES)) {
result += ":" + getValue(Field.PAGES);
}
result += ".";
}
// other than JOURNAL???
// URL
if (exists(Field.URL)) {
result += " URL " + getValue(Field.URL) + ".";
}
}
// CONFERENCE/INPROCEEDINGS
else if ((getType() == Type.CONFERENCE)
|| (getType() == Type.INPROCEEDINGS)) {
for (i = 0; i < authors.length; i++) {
if (i > 0) {
result += ", ";
}
result += authors[i];
}
result += ": " + getValue(Field.TITLE) + ".";
result += " In: " + getValue(Field.BOOKTITLE);
if (exists(Field.ADDRESS)) {
result += ", " + getValue(Field.ADDRESS);
}
if (exists(Field.PAGES)) {
result += ", " + getValue(Field.PAGES);
}
if (exists(Field.YEAR)) {
result += ", " + getValue(Field.YEAR) + ".";
} else {
result += ".";
}
}
// INCOLLECTION
else if (getType() == Type.INCOLLECTION) {
for (i = 0; i < authors.length; i++) {
if (i > 0) {
result += ", ";
}
result += authors[i];
}
result += ": " + getValue(Field.TITLE) + ".";
result += " In ";
if (exists(Field.EDITOR)) {
result += getValue(Field.EDITOR) + ", editors, ";
}
result += getValue(Field.BOOKTITLE);
if (exists(Field.ADDRESS)) {
result += ", " + getValue(Field.ADDRESS);
}
if (exists(Field.PAGES)) {
result += ", " + getValue(Field.PAGES);
}
if (exists(Field.YEAR)) {
result += ", " + getValue(Field.YEAR) + ".";
} else {
result += ".";
}
}
// default
else {
for (i = 0; i < authors.length; i++) {
if (i > 0) {
result += ", ";
}
result += authors[i];
}
if (exists(Field.YEAR)) {
result += " (" + getValue(Field.YEAR) + ").";
} else {
result += ".";
}
result += " " + getValue(Field.TITLE) + ".";
if (exists(Field.ADDRESS)) {
result += " " + getValue(Field.ADDRESS) + ".";
}
if (exists(Field.URL)) {
result += " URL " + getValue(Field.URL) + ".";
}
}
// additional informations?
enm = additional();
while (enm.hasMoreElements()) {
result += "\n\n" + enm.nextElement().toString();
}
return result;
}
/**
* Returns a BibTex string representing this technical information. Note: this
* is just a very raw implementation, special characters need to be escaped
* manually for LaTeX.
*
* @return the BibTeX representation of this information
*/
public String toBibTex() {
String result;
Field field;
Vector<Field> list;
int i;
String value;
result = "@" + getType() + "{" + getID() + "";
// sort the fields
list = new Vector<Field>();
Enumeration<Field> enm = fields();
while (enm.hasMoreElements()) {
list.add(enm.nextElement());
}
Collections.sort(list);
// list field=value pairs
for (i = 0; i < list.size(); i++) {
field = list.get(i);
if (!exists(field)) {
continue;
}
value = getValue(field);
value = value.replaceAll("\\~", "\\\\~");
result += ",\n " + field + " = {" + value + "}";
}
result += "\n}";
// additional informations?
Enumeration<TechnicalInformation> enm2 = additional();
while (enm2.hasMoreElements()) {
result += "\n\n" + enm2.nextElement().toBibTex();
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Prints some examples of technical informations if there are no commandline
* options given. Otherwise the information of a given
* TechnicalInformationHandler can be printed.
* <p/>
*
* Valid options are:
* <p/>
*
* -W classname <br/>
* The classname of the TechnicalInformationHandler to print the information
* for
* <p/>
*
* -bibtex <br/>
* Print the information in BibTeX format
* <p/>
*
* -plaintext <br/>
* Print the information in plain text format
* <p/>
*
* @param args the commandline options
* @throws Exception if the option parsing fails
*/
public static void main(String[] args) throws Exception {
TechnicalInformation info;
TechnicalInformation additional;
String tmpStr;
Class<?> cls;
TechnicalInformationHandler handler;
// example from command line
if (args.length != 0) {
info = null;
tmpStr = Utils.getOption('W', args);
if (tmpStr.length() != 0) {
cls = Class.forName(tmpStr);
handler = (TechnicalInformationHandler) cls.newInstance();
info = handler.getTechnicalInformation();
} else {
throw new IllegalArgumentException(
"A classname has to be provided with the -W option!");
}
if (Utils.getFlag("bibtex", args)) {
System.out.println("\n" + handler.getClass().getName() + ":\n"
+ info.toBibTex());
}
if (Utils.getFlag("plaintext", args)) {
System.out.println("\n" + handler.getClass().getName() + ":\n"
+ info.toString());
}
} else {
// first example
info = new TechnicalInformation(Type.BOOK);
info.setValue(Field.AUTHOR, "Ross Quinlan");
info.setValue(Field.YEAR, "1993");
info.setValue(Field.TITLE, "C4.5: Programs for Machine Learning");
info.setValue(Field.PUBLISHER, "Morgan Kaufmann Publishers");
info.setValue(Field.ADDRESS, "San Mateo, CA");
additional = info;
System.out.println("\ntoString():\n" + info.toString());
System.out.println("\ntoBibTex():\n" + info.toBibTex());
// second example
info = new TechnicalInformation(Type.INPROCEEDINGS);
info.setValue(Field.AUTHOR, "Freund, Y. and Mason, L.");
info.setValue(Field.YEAR, "1999");
info.setValue(Field.TITLE,
"The alternating decision tree learning algorithm");
info
.setValue(Field.BOOKTITLE,
"Proceeding of the Sixteenth International Conference on Machine Learning");
info.setValue(Field.ADDRESS, "Bled, Slovenia");
info.setValue(Field.PAGES, "124-133");
System.out.println("\ntoString():\n" + info.toString());
System.out.println("\ntoBibTex():\n" + info.toBibTex());
// third example
info = new TechnicalInformation(Type.ARTICLE);
info.setValue(Field.AUTHOR, "R. Quinlan");
info.setValue(Field.YEAR, "1986");
info.setValue(Field.TITLE, "Induction of decision trees");
info.setValue(Field.JOURNAL, "Machine Learning");
info.setValue(Field.VOLUME, "1");
info.setValue(Field.NUMBER, "1");
info.setValue(Field.PAGES, "81-106");
additional = new TechnicalInformation(Type.BOOK);
additional.setValue(Field.AUTHOR, "Ross Quinlan");
additional.setValue(Field.YEAR, "1993");
additional.setValue(Field.TITLE, "C4.5: Programs for Machine Learning");
additional.setValue(Field.PUBLISHER, "Morgan Kaufmann Publishers");
additional.setValue(Field.ADDRESS, "San Mateo, CA");
info.add(additional);
System.out.println("\ntoString():\n" + info.toString());
System.out.println("\ntoBibTex():\n" + info.toBibTex());
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/TechnicalInformationHandler.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* TechnicalInformationHandler.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
/**
* For classes that are based on some kind of publications. They return
* a TechnicalInformation object filled with the data of the publication.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see TechnicalInformation
*/
public interface TechnicalInformationHandler {
/**
* 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
*/
public TechnicalInformation getTechnicalInformation();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/TechnicalInformationHandlerJavadoc.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* TechnicalInformationHandlerJavadoc.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
/**
* Generates Javadoc comments from the TechnicalInformationHandler's data.
* Update the BibTex references and the plaintext techincal information.
* <br><br>
*
* <!-- options-start --> Valid options are:
* <br>
*
* <pre>
* -W <classname>
* The class to load.
* </pre>
*
* <pre>
* -nostars
* Suppresses the '*' in the Javadoc.
* </pre>
*
* <pre>
* -dir <dir>
* The directory above the package hierarchy of the class.
* </pre>
*
* <pre>
* -silent
* Suppresses printing in the console.
* </pre>
*
* <pre>
* -noprolog
* Suppresses the 'BibTex:' prolog in the Javadoc.
* </pre>
*
* <!-- options-end -->
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see #PLAINTEXT_STARTTAG
* @see #PLAINTEXT_ENDTAG
* @see #BIBTEX_STARTTAG
* @see #BIBTEX_ENDTAG
*/
public class TechnicalInformationHandlerJavadoc extends Javadoc {
/** the start comment tag for inserting the generated BibTex */
public final static String PLAINTEXT_STARTTAG = "<!-- technical-plaintext-start -->";
/** the end comment tag for inserting the generated BibTex */
public final static String PLAINTEXT_ENDTAG = "<!-- technical-plaintext-end -->";
/** the start comment tag for inserting the generated BibTex */
public final static String BIBTEX_STARTTAG = "<!-- technical-bibtex-start -->";
/** the end comment tag for inserting the generated BibTex */
public final static String BIBTEX_ENDTAG = "<!-- technical-bibtex-end -->";
/** whether to include the "Valid options..." prolog in the Javadoc */
protected boolean m_Prolog = true;
/**
* default constructor
*/
public TechnicalInformationHandlerJavadoc() {
super();
m_StartTag = new String[2];
m_EndTag = new String[2];
m_StartTag[0] = PLAINTEXT_STARTTAG;
m_EndTag[0] = PLAINTEXT_ENDTAG;
m_StartTag[1] = BIBTEX_STARTTAG;
m_EndTag[1] = BIBTEX_ENDTAG;
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addAll(Collections.list(super.listOptions()));
result.addElement(new Option(
"\tSuppresses the 'BibTex:' prolog in the Javadoc.", "noprolog", 0,
"-noprolog"));
return result.elements();
}
/**
* 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
*/
@Override
public void setOptions(String[] options) throws Exception {
super.setOptions(options);
setProlog(!Utils.getFlag("noprolog", options));
}
/**
* Gets the current settings of this object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
String[] options;
int i;
result = new Vector<String>();
options = super.getOptions();
for (i = 0; i < options.length; i++) {
result.add(options[i]);
}
if (!getProlog()) {
result.add("-noprolog");
}
return result.toArray(new String[result.size()]);
}
/**
* sets whether to add the "Valid options are..." prolog
*
* @param value true if the prolog is to be used
*/
public void setProlog(boolean value) {
m_Prolog = value;
}
/**
* whether "Valid options are..." prolog is included in the Javadoc
*
* @return whether the prolog is currently used
*/
public boolean getProlog() {
return m_Prolog;
}
/**
* generates and returns the Javadoc for the specified start/end tag pair.
*
* @param index the index in the start/end tag array
* @return the generated Javadoc
* @throws Exception in case the generation fails
*/
@Override
protected String generateJavadoc(int index) throws Exception {
String result;
TechnicalInformationHandler handler;
result = "";
if (!canInstantiateClass()) {
return result;
}
if (!InheritanceUtils.hasInterface(TechnicalInformationHandler.class,
getInstance().getClass())) {
throw new Exception("Class '" + getClassname()
+ "' is not a TechnicalInformationHandler!");
}
handler = (TechnicalInformationHandler) getInstance();
switch (index) {
case 0: // plain text
result = toHTML(handler.getTechnicalInformation().toString()) + "\n";
break;
case 1: // bibtex
// prolog?
if (getProlog()) {
result = "BibTeX:\n";
}
result += "<pre>\n";
result += toHTML(handler.getTechnicalInformation().toBibTex())
.replaceAll("<br>", "") + "\n";
result += "</pre>\n<br><br>\n";
break;
}
// stars?
if (getUseStars()) {
result = indent(result, 1, "* ");
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Parses the given commandline parameters and generates the Javadoc.
*
* @param args the commandline parameters for the object
*/
public static void main(String[] args) {
runJavadoc(new TechnicalInformationHandlerJavadoc(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Tee.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Tee.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.PrintStream;
import java.util.Date;
import java.util.Vector;
/**
* This class pipelines print/println's to several PrintStreams. Useful for
* redirecting System.out and System.err to files etc.<br/>
* E.g., for redirecting stderr/stdout to files with timestamps and:<br/>
* <pre>
* import java.io.*;
* import weka.core.Tee;
*
* ...
* // stdout
* Tee teeOut = new Tee(System.out);
* teeOut.add(new PrintStream(new FileOutputStream("out.txt")), true);
* System.setOut(teeOut);
*
* // stderr
* Tee teeErr = new Tee(System.err);
* teeErr.add(new PrintStream(new FileOutputStream("err.txt")), true);
* System.setOut(teeErr);
* ...
* </pre>
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Tee
extends PrintStream
implements RevisionHandler {
/** the different PrintStreams. */
protected Vector<PrintStream> m_Streams = new Vector<PrintStream>();
/** whether to add timestamps or not. */
protected Vector<Boolean> m_Timestamps = new Vector<Boolean>();
/** whether to add a prefix or not. */
protected Vector<String> m_Prefixes = new Vector<String>();
/** the default printstream. */
protected PrintStream m_Default = null;
/**
* initializes the object, with a default printstream.
*/
public Tee() {
this(System.out);
}
/**
* initializes the object with the given default printstream, e.g.,
* System.out.
*
* @param def the default printstream, remains also after calling clear()
*/
public Tee(PrintStream def) {
super(def);
m_Default = def;
clear();
}
/**
* removes all streams and places the default printstream, if any, again in
* the list.
*
* @see #getDefault()
*/
public void clear() {
m_Streams.clear();
m_Timestamps.clear();
m_Prefixes.clear();
if (getDefault() != null)
add(getDefault());
}
/**
* returns the default printstrean, can be NULL.
*
* @return the default printstream
* @see #m_Default
*/
public PrintStream getDefault() {
return m_Default;
}
/**
* adds the given PrintStream to the list of streams, with NO timestamp and
* NO prefix.
*
* @param p the printstream to add
*/
public void add(PrintStream p) {
add(p, false);
}
/**
* adds the given PrintStream to the list of streams, with NO prefix.
*
* @param p the printstream to add
* @param timestamp whether to use timestamps or not
*/
public void add(PrintStream p, boolean timestamp) {
add(p, timestamp, "");
}
/**
* adds the given PrintStream to the list of streams.
*
* @param p the printstream to add
* @param timestamp whether to use timestamps or not
* @param prefix the prefix to use
*/
public void add(PrintStream p, boolean timestamp, String prefix) {
if (m_Streams.contains(p))
remove(p);
// make sure it's not null
if (prefix == null)
prefix = "";
m_Streams.add(p);
m_Timestamps.add(new Boolean(timestamp));
m_Prefixes.add(prefix);
}
/**
* returns the specified PrintStream from the list.
*
* @param index the index of the PrintStream to return
* @return the specified PrintStream, or null if invalid index
*/
public PrintStream get(int index) {
if ( (index >= 0) && (index < size()) )
return (PrintStream) m_Streams.get(index);
else
return null;
}
/**
* removes the given PrintStream from the list.
*
* @param p the PrintStream to remove
* @return returns the removed PrintStream if it could be removed, null otherwise
*/
public PrintStream remove(PrintStream p) {
int index;
if (contains(p)) {
index = m_Streams.indexOf(p);
m_Timestamps.remove(index);
m_Prefixes.remove(index);
return (PrintStream) m_Streams.remove(index);
}
else {
return null;
}
}
/**
* removes the given PrintStream from the list.
*
* @param index the index of the PrintStream to remove
* @return returns the removed PrintStream if it could be removed, null otherwise
*/
public PrintStream remove(int index) {
if ( (index >= 0) && (index < size()) ) {
m_Timestamps.remove(index);
m_Prefixes.remove(index);
return (PrintStream) m_Streams.remove(index);
}
else {
return null;
}
}
/**
* checks whether the given PrintStream is already in the list.
*
* @param p the PrintStream to look for
* @return true if the PrintStream is in the list
*/
public boolean contains(PrintStream p) {
return m_Streams.contains(p);
}
/**
* returns the number of streams currently in the list.
*
* @return the number of streams in the list
*/
public int size() {
return m_Streams.size();
}
/**
* prints the prefix/timestamp (timestampe only to those streams that want
* one).
*/
private void printHeader() {
for (int i = 0; i < size(); i++) {
// prefix
if (!((String) m_Prefixes.get(i)).equals(""))
((PrintStream) m_Streams.get(i)).print("[" + m_Prefixes.get(i) + "]\t");
// timestamp
if (((Boolean) m_Timestamps.get(i)).booleanValue())
((PrintStream) m_Streams.get(i)).print("[" + new Date() + "]\t");
}
}
/**
* flushes all the printstreams.
*/
public void flush() {
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).flush();
}
/**
* prints the given int to the streams.
*
* @param x the object to print
*/
public void print(int x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).print(x);
flush();
}
/**
* prints the given long to the streams.
*
* @param x the object to print
*/
public void print(long x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).print(x);
flush();
}
/**
* prints the given float to the streams.
*
* @param x the object to print
*/
public void print(float x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).print(x);
flush();
}
/**
* prints the given double to the streams.
*
* @param x the object to print
*/
public void print(double x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).print(x);
flush();
}
/**
* prints the given boolean to the streams.
*
* @param x the object to print
*/
public void print(boolean x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).print(x);
flush();
}
/**
* prints the given char to the streams.
*
* @param x the object to print
*/
public void print(char x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).print(x);
flush();
}
/**
* prints the given char array to the streams.
*
* @param x the object to print
*/
public void print(char[] x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).print(x);
flush();
}
/**
* prints the given string to the streams.
*
* @param x the object to print
*/
public void print(String x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).print(x);
flush();
}
/**
* prints the given object to the streams.
*
* @param x the object to print
*/
public void print(Object x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).print(x);
flush();
}
/**
* prints a new line to the streams.
*/
public void println() {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println();
flush();
}
/**
* prints the given int to the streams.
*
* @param x the object to print
*/
public void println(int x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println(x);
flush();
}
/**
* prints the given long to the streams.
*
* @param x the object to print
*/
public void println(long x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println(x);
flush();
}
/**
* prints the given float to the streams.
*
* @param x the object to print
*/
public void println(float x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println(x);
flush();
}
/**
* prints the given double to the streams.
*
* @param x the object to print
*/
public void println(double x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println(x);
flush();
}
/**
* prints the given boolean to the streams.
*
* @param x the object to print
*/
public void println(boolean x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println(x);
flush();
}
/**
* prints the given char to the streams.
*
* @param x the object to print
*/
public void println(char x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println(x);
flush();
}
/**
* prints the given char array to the streams.
*
* @param x the object to print
*/
public void println(char[] x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println(x);
flush();
}
/**
* prints the given string to the streams.
*
* @param x the object to print
*/
public void println(String x) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println(x);
flush();
}
/**
* prints the given object to the streams (for Throwables we print the stack
* trace).
*
* @param x the object to print
*/
public void println(Object x) {
String line;
Throwable t;
StackTraceElement[] trace;
int i;
if (x instanceof Throwable) {
t = (Throwable) x;
trace = t.getStackTrace();
line = t.toString() + "\n";
for (i = 0; i < trace.length; i++)
line += "\t" + trace[i].toString() + "\n";
x = line;
}
printHeader();
for (i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).println(x);
flush();
}
/**
* Writes <code>len</code> bytes from the specified byte array starting at
* offset <code>off</code> to this stream. If automatic flushing is
* enabled then the <code>flush</code> method will be invoked.
*
* <p> Note that the bytes will be written as given; to write characters
* that will be translated according to the platform's default character
* encoding, use the <code>print(char)</code> or <code>println(char)</code>
* methods.
*
* @param buf A byte array
* @param off Offset from which to start taking bytes
* @param len Number of bytes to write
*/
public void write(byte buf[], int off, int len) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).write(buf, off, len);
flush();
}
/**
* Writes the specified byte to this stream. If the byte is a newline and
* automatic flushing is enabled then the <code>flush</code> method will be
* invoked.
*
* <p> Note that the byte is written as given; to write a character that
* will be translated according to the platform's default character
* encoding, use the <code>print(char)</code> or <code>println(char)</code>
* methods.
*
* @param b The byte to be written
* @see #print(char)
* @see #println(char)
*/
public void write(int b) {
printHeader();
for (int i = 0; i < size(); i++)
((PrintStream) m_Streams.get(i)).write(b);
flush();
}
/**
* returns only the classname and the number of streams.
*
* @return only the classname and the number of streams
*/
public String toString() {
return this.getClass().getName() + ": " + m_Streams.size();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/TestInstances.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* TestInstances.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import weka.core.Capabilities.Capability;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* Generates artificial datasets for testing. In case of Multi-Instance data the
* settings for the number of attributes applies to the data inside the bag.
* Originally based on code from the CheckClassifier.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -relation <name>
* The name of the data set.
* </pre>
*
* <pre>
* -seed <num>
* The seed value.
* </pre>
*
* <pre>
* -num-instances <num>
* The number of instances in the datasets (default 20).
* </pre>
*
* <pre>
* -class-type <num>
* The class type, see constants in weka.core.Attribute
* (default 1=nominal).
* </pre>
*
* <pre>
* -class-values <num>
* The number of classes to generate (for nominal classes only)
* (default 2).
* </pre>
*
* <pre>
* -class-index <num>
* The class index, with -1=last, (default -1).
* </pre>
*
* <pre>
* -no-class
* Doesn't include a class attribute in the output.
* </pre>
*
* <pre>
* -nominal <num>
* The number of nominal attributes (default 1).
* </pre>
*
* <pre>
* -nominal-values <num>
* The number of values for nominal attributes (default 2).
* </pre>
*
* <pre>
* -numeric <num>
* The number of numeric attributes (default 0).
* </pre>
*
* <pre>
* -string <num>
* The number of string attributes (default 0).
* </pre>
*
* <pre>
* -words <comma-separated-list>
* The words to use in string attributes.
* </pre>
*
* <pre>
* -word-separators <chars>
* The word separators to use in string attributes.
* </pre>
*
* <pre>
* -date <num>
* The number of date attributes (default 0).
* </pre>
*
* <pre>
* -relational <num>
* The number of relational attributes (default 0).
* </pre>
*
* <pre>
* -relational-nominal <num>
* The number of nominal attributes in a rel. attribute (default 1).
* </pre>
*
* <pre>
* -relational-nominal-values <num>
* The number of values for nominal attributes in a rel. attribute (default 2).
* </pre>
*
* <pre>
* -relational-numeric <num>
* The number of numeric attributes in a rel. attribute (default 0).
* </pre>
*
* <pre>
* -relational-string <num>
* The number of string attributes in a rel. attribute (default 0).
* </pre>
*
* <pre>
* -relational-date <num>
* The number of date attributes in a rel. attribute (default 0).
* </pre>
*
* <pre>
* -num-instances-relational <num>
* The number of instances in relational/bag attributes (default 10).
* </pre>
*
* <pre>
* -multi-instance
* Generates multi-instance data.
* </pre>
*
* <pre>
* -W <classname>
* The Capabilities handler to base the dataset on.
* The other parameters can be used to override the ones
* determined from the handler. Additional parameters for
* handler can be passed on after the '--'.
* </pre>
*
* <!-- options-end -->
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see weka.classifiers.CheckClassifier
*/
public class TestInstances implements Cloneable, Serializable, OptionHandler,
RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -6263968936330390469L;
/**
* can be used for settting the class attribute index to last
*
* @see #setClassIndex(int)
*/
public final static int CLASS_IS_LAST = -1;
/**
* can be used to avoid generating a class attribute
*
* @see #setClassIndex(int)
*/
public final static int NO_CLASS = -2;
/** the default list of words used in strings */
public final static String[] DEFAULT_WORDS = { "The", "quick", "brown",
"fox", "jumps", "over", "the", "lazy", "dog" };
/** the default word separators used in strings */
public final static String DEFAULT_SEPARATORS = " ";
/** for generating String attributes/classes */
protected String[] m_Words = DEFAULT_WORDS;
/** for generating String attributes/classes */
protected String m_WordSeparators = DEFAULT_SEPARATORS;
/** the name of the relation */
protected String m_Relation = "Testdata";
/** the seed value */
protected int m_Seed = 1;
/** the random number generator */
protected Random m_Random = new Random(m_Seed);
/** the number of instances */
protected int m_NumInstances = 20;
/** the class type */
protected int m_ClassType = Attribute.NOMINAL;
/** the number of classes (in case of NOMINAL class) */
protected int m_NumClasses = 2;
/**
* the class index (-1 is LAST, -2 means no class)
*
* @see #CLASS_IS_LAST
* @see #NO_CLASS
*/
protected int m_ClassIndex = CLASS_IS_LAST;
/** the number of nominal attributes */
protected int m_NumNominal = 1;
/** the number of values for nominal attributes */
protected int m_NumNominalValues = 2;
/** the number of numeric attributes */
protected int m_NumNumeric = 0;
/** the number of string attributes */
protected int m_NumString = 0;
/** the number of date attributes */
protected int m_NumDate = 0;
/** the number of relational attributes */
protected int m_NumRelational = 0;
/** the number of nominal attributes in a relational attribute */
protected int m_NumRelationalNominal = 1;
/** the number of values for nominal attributes in relational attributes */
protected int m_NumRelationalNominalValues = 2;
/** the number of numeric attributes in a relational attribute */
protected int m_NumRelationalNumeric = 0;
/** the number of string attributes in a relational attribute */
protected int m_NumRelationalString = 0;
/** the number of date attributes in a relational attribute */
protected int m_NumRelationalDate = 0;
/** whether to generate Multi-Instance data or not */
protected boolean m_MultiInstance = false;
/**
* the number of instances in relational attributes (applies also for bags in
* multi-instance)
*/
protected int m_NumInstancesRelational = 10;
/** the format of the multi-instance data */
protected Instances[] m_RelationalFormat = null;
/** the format of the multi-instance data of the class */
protected Instances m_RelationalClassFormat = null;
/** the generated data */
protected Instances m_Data = null;
/** the CapabilitiesHandler to get the Capabilities from */
protected CapabilitiesHandler m_Handler = null;
/**
* the default constructor
*/
public TestInstances() {
super();
setRelation("Testdata");
setSeed(1);
setNumInstances(20);
setClassType(Attribute.NOMINAL);
setNumClasses(2);
setClassIndex(CLASS_IS_LAST);
setNumNominal(1);
setNumNominalValues(2);
setNumNumeric(0);
setNumString(0);
setNumDate(0);
setNumRelational(0);
setNumRelationalNominal(1);
setNumRelationalNominalValues(2);
setNumRelationalNumeric(0);
setNumRelationalString(0);
setNumRelationalDate(0);
setNumInstancesRelational(10);
setMultiInstance(false);
setWords(arrayToList(DEFAULT_WORDS));
setWordSeparators(DEFAULT_SEPARATORS);
}
/**
* creates a clone of the current object
*
* @return a clone of the current object
*/
@Override
public Object clone() {
TestInstances result;
result = new TestInstances();
result.assign(this);
return result;
}
/**
* updates itself with all the settings from the given TestInstances object
*
* @param t the object to get the settings from
*/
public void assign(TestInstances t) {
setRelation(t.getRelation());
setSeed(t.getSeed());
setNumInstances(t.getNumInstances());
setClassType(t.getClassType());
setNumClasses(t.getNumClasses());
setClassIndex(t.getClassIndex());
setNumNominal(t.getNumNominal());
setNumNominalValues(t.getNumNominalValues());
setNumNumeric(t.getNumNumeric());
setNumString(t.getNumString());
setNumDate(t.getNumDate());
setNumRelational(t.getNumRelational());
setNumRelationalNominal(t.getNumRelationalNominal());
setNumRelationalNominalValues(t.getNumRelationalNominalValues());
setNumRelationalNumeric(t.getNumRelationalNumeric());
setNumRelationalString(t.getNumRelationalString());
setNumRelationalDate(t.getNumRelationalDate());
setMultiInstance(t.getMultiInstance());
for (int i = 0; i < t.getNumRelational(); i++) {
setRelationalFormat(i, t.getRelationalFormat(i));
}
setRelationalClassFormat(t.getRelationalClassFormat());
setNumInstancesRelational(t.getNumInstancesRelational());
setWords(t.getWords());
setWordSeparators(t.getWordSeparators());
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.add(new Option("\tThe name of the data set.", "relation", 1,
"-relation <name>"));
result.add(new Option("\tThe seed value.", "seed", 1, "-seed <num>"));
result.add(new Option(
"\tThe number of instances in the datasets (default 20).",
"num-instances", 1, "-num-instances <num>"));
result.add(new Option(
"\tThe class type, see constants in weka.core.Attribute\n"
+ "\t(default 1=nominal).", "class-type", 1, "-class-type <num>"));
result.add(new Option(
"\tThe number of classes to generate (for nominal classes only)\n"
+ "\t(default 2).", "class-values", 1, "-class-values <num>"));
result.add(new Option("\tThe class index, with -1=last, (default -1).",
"class-index", 1, "-class-index <num>"));
result.add(new Option("\tDoesn't include a class attribute in the output.",
"no-class", 0, "-no-class"));
result.add(new Option("\tThe number of nominal attributes (default 1).",
"nominal", 1, "-nominal <num>"));
result.add(new Option(
"\tThe number of values for nominal attributes (default 2).",
"nominal-values", 1, "-nominal-values <num>"));
result.add(new Option("\tThe number of numeric attributes (default 0).",
"numeric", 1, "-numeric <num>"));
result.add(new Option("\tThe number of string attributes (default 0).",
"string", 1, "-string <num>"));
result.add(new Option("\tThe words to use in string attributes.", "words",
1, "-words <comma-separated-list>"));
result.add(new Option("\tThe word separators to use in string attributes.",
"word-separators", 1, "-word-separators <chars>"));
result.add(new Option("\tThe number of date attributes (default 0).",
"date", 1, "-date <num>"));
result.add(new Option("\tThe number of relational attributes (default 0).",
"relational", 1, "-relational <num>"));
result.add(new Option(
"\tThe number of nominal attributes in a rel. attribute (default 1).",
"relational-nominal", 1, "-relational-nominal <num>"));
result
.add(new Option(
"\tThe number of values for nominal attributes in a rel. attribute (default 2).",
"relational-nominal-values", 1, "-relational-nominal-values <num>"));
result.add(new Option(
"\tThe number of numeric attributes in a rel. attribute (default 0).",
"relational-numeric", 1, "-relational-numeric <num>"));
result.add(new Option(
"\tThe number of string attributes in a rel. attribute (default 0).",
"relational-string", 1, "-relational-string <num>"));
result.add(new Option(
"\tThe number of date attributes in a rel. attribute (default 0).",
"relational-date", 1, "-relational-date <num>"));
result.add(new Option(
"\tThe number of instances in relational/bag attributes (default 10).",
"num-instances-relational", 1, "-num-instances-relational <num>"));
result.add(new Option("\tGenerates multi-instance data.", "multi-instance",
0, "-multi-instance"));
result.add(new Option(
"\tThe Capabilities handler to base the dataset on.\n"
+ "\tThe other parameters can be used to override the ones\n"
+ "\tdetermined from the handler. Additional parameters for\n"
+ "\thandler can be passed on after the '--'.", "W", 1,
"-W <classname>"));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -relation <name>
* The name of the data set.
* </pre>
*
* <pre>
* -seed <num>
* The seed value.
* </pre>
*
* <pre>
* -num-instances <num>
* The number of instances in the datasets (default 20).
* </pre>
*
* <pre>
* -class-type <num>
* The class type, see constants in weka.core.Attribute
* (default 1=nominal).
* </pre>
*
* <pre>
* -class-values <num>
* The number of classes to generate (for nominal classes only)
* (default 2).
* </pre>
*
* <pre>
* -class-index <num>
* The class index, with -1=last, (default -1).
* </pre>
*
* <pre>
* -no-class
* Doesn't include a class attribute in the output.
* </pre>
*
* <pre>
* -nominal <num>
* The number of nominal attributes (default 1).
* </pre>
*
* <pre>
* -nominal-values <num>
* The number of values for nominal attributes (default 2).
* </pre>
*
* <pre>
* -numeric <num>
* The number of numeric attributes (default 0).
* </pre>
*
* <pre>
* -string <num>
* The number of string attributes (default 0).
* </pre>
*
* <pre>
* -words <comma-separated-list>
* The words to use in string attributes.
* </pre>
*
* <pre>
* -word-separators <chars>
* The word separators to use in string attributes.
* </pre>
*
* <pre>
* -date <num>
* The number of date attributes (default 0).
* </pre>
*
* <pre>
* -relational <num>
* The number of relational attributes (default 0).
* </pre>
*
* <pre>
* -relational-nominal <num>
* The number of nominal attributes in a rel. attribute (default 1).
* </pre>
*
* <pre>
* -relational-nominal-values <num>
* The number of values for nominal attributes in a rel. attribute (default 2).
* </pre>
*
* <pre>
* -relational-numeric <num>
* The number of numeric attributes in a rel. attribute (default 0).
* </pre>
*
* <pre>
* -relational-string <num>
* The number of string attributes in a rel. attribute (default 0).
* </pre>
*
* <pre>
* -relational-date <num>
* The number of date attributes in a rel. attribute (default 0).
* </pre>
*
* <pre>
* -num-instances-relational <num>
* The number of instances in relational/bag attributes (default 10).
* </pre>
*
* <pre>
* -multi-instance
* Generates multi-instance data.
* </pre>
*
* <pre>
* -W <classname>
* The Capabilities handler to base the dataset on.
* The other parameters can be used to override the ones
* determined from the handler. Additional parameters for
* handler can be passed on after the '--'.
* </pre>
*
* <!-- 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;
Class<?> cls;
CapabilitiesHandler handler;
boolean initialized;
initialized = false;
tmpStr = Utils.getOption('W', options);
if (tmpStr.length() > 0) {
cls = Class.forName(tmpStr);
if (InheritanceUtils.hasInterface(CapabilitiesHandler.class, cls)) {
initialized = true;
handler = (CapabilitiesHandler) cls.newInstance();
if (handler instanceof OptionHandler) {
((OptionHandler) handler).setOptions(Utils.partitionOptions(options));
}
setHandler(handler);
// initialize
this.assign(forCapabilities(handler.getCapabilities()));
} else {
throw new IllegalArgumentException("Class '" + tmpStr
+ "' is not a CapabilitiesHandler!");
}
}
tmpStr = Utils.getOption("relation", options);
if (tmpStr.length() != 0) {
setRelation(tmpStr);
} else if (!initialized) {
setRelation("Testdata");
}
tmpStr = Utils.getOption("seed", options);
if (tmpStr.length() != 0) {
setSeed(Integer.parseInt(tmpStr));
} else if (!initialized) {
setSeed(1);
}
tmpStr = Utils.getOption("num-instances", options);
if (tmpStr.length() != 0) {
setNumInstances(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumInstances(20);
}
setNoClass(Utils.getFlag("no-class", options));
if (!getNoClass()) {
tmpStr = Utils.getOption("class-type", options);
if (tmpStr.length() != 0) {
setClassType(Integer.parseInt(tmpStr));
} else if (!initialized) {
setClassType(Attribute.NOMINAL);
}
tmpStr = Utils.getOption("class-values", options);
if (tmpStr.length() != 0) {
setNumClasses(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumClasses(2);
}
tmpStr = Utils.getOption("class-index", options);
if (tmpStr.length() != 0) {
setClassIndex(Integer.parseInt(tmpStr));
} else if (!initialized) {
setClassIndex(-1);
}
}
tmpStr = Utils.getOption("nominal", options);
if (tmpStr.length() != 0) {
setNumNominal(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumNominal(1);
}
tmpStr = Utils.getOption("nominal-values", options);
if (tmpStr.length() != 0) {
setNumNominalValues(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumNominalValues(2);
}
tmpStr = Utils.getOption("numeric", options);
if (tmpStr.length() != 0) {
setNumNumeric(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumNumeric(0);
}
tmpStr = Utils.getOption("string", options);
if (tmpStr.length() != 0) {
setNumString(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumString(0);
}
tmpStr = Utils.getOption("words", options);
if (tmpStr.length() != 0) {
setWords(tmpStr);
} else if (!initialized) {
setWords(arrayToList(DEFAULT_WORDS));
}
if (Utils.getOptionPos("word-separators", options) > -1) {
tmpStr = Utils.getOption("word-separators", options);
setWordSeparators(tmpStr);
} else if (!initialized) {
setWordSeparators(DEFAULT_SEPARATORS);
}
tmpStr = Utils.getOption("date", options);
if (tmpStr.length() != 0) {
setNumDate(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumDate(0);
}
tmpStr = Utils.getOption("relational", options);
if (tmpStr.length() != 0) {
setNumRelational(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumRelational(0);
}
tmpStr = Utils.getOption("relational-nominal", options);
if (tmpStr.length() != 0) {
setNumRelationalNominal(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumRelationalNominal(1);
}
tmpStr = Utils.getOption("relational-nominal-values", options);
if (tmpStr.length() != 0) {
setNumRelationalNominalValues(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumRelationalNominalValues(2);
}
tmpStr = Utils.getOption("relational-numeric", options);
if (tmpStr.length() != 0) {
setNumRelationalNumeric(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumRelationalNumeric(0);
}
tmpStr = Utils.getOption("relational-string", options);
if (tmpStr.length() != 0) {
setNumRelationalString(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumRelationalString(0);
}
tmpStr = Utils.getOption("num-instances-relational", options);
if (tmpStr.length() != 0) {
setNumInstancesRelational(Integer.parseInt(tmpStr));
} else if (!initialized) {
setNumInstancesRelational(10);
}
if (!initialized) {
setMultiInstance(Utils.getFlag("multi-instance", options));
}
}
/**
* Gets the current settings of this object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
String[] options;
int i;
result = new Vector<String>();
result.add("-relation");
result.add(getRelation());
result.add("-seed");
result.add("" + getSeed());
result.add("-num-instances");
result.add("" + getNumInstances());
if (getNoClass()) {
result.add("-no-class");
} else {
result.add("-class-type");
result.add("" + getClassType());
result.add("-class-values");
result.add("" + getNumClasses());
result.add("-class-index");
result.add("" + getClassIndex());
}
result.add("-nominal");
result.add("" + getNumNominal());
result.add("-nominal-values");
result.add("" + getNumNominalValues());
result.add("-numeric");
result.add("" + getNumNumeric());
result.add("-string");
result.add("" + getNumString());
result.add("-words");
result.add("" + getWords());
result.add("-word-separators");
result.add("" + getWordSeparators());
result.add("-date");
result.add("" + getNumDate());
result.add("-relational");
result.add("" + getNumRelational());
result.add("-relational-nominal");
result.add("" + getNumRelationalNominal());
result.add("-relational-nominal-values");
result.add("" + getNumRelationalNominalValues());
result.add("-relational-numeric");
result.add("" + getNumRelationalNumeric());
result.add("-relational-string");
result.add("" + getNumRelationalString());
result.add("-relational-date");
result.add("" + getNumRelationalDate());
result.add("-num-instances-relational");
result.add("" + getNumInstancesRelational());
if (getMultiInstance()) {
result.add("-multi-instance");
}
if (getHandler() != null) {
result.add("-W");
result.add(getHandler().getClass().getName());
if (getHandler() instanceof OptionHandler) {
result.add("--");
options = ((OptionHandler) getHandler()).getOptions();
for (i = 0; i < options.length; i++) {
result.add(options[i]);
}
}
}
return result.toArray(new String[result.size()]);
}
/**
* sets the name of the relation
*
* @param value the name of the relation
*/
public void setRelation(String value) {
m_Relation = value;
}
/**
* returns the current name of the relation
*
* @return the name of the relation
*/
public String getRelation() {
return m_Relation;
}
/**
* sets the seed value for the random number generator
*
* @param value the seed
*/
public void setSeed(int value) {
m_Seed = value;
m_Random = new Random(m_Seed);
}
/**
* returns the current seed value
*
* @return the seed value
*/
public int getSeed() {
return m_Seed;
}
/**
* sets the number of instances to produce
*
* @param value the number of instances
*/
public void setNumInstances(int value) {
m_NumInstances = value;
}
/**
* returns the current number of instances to produce
*
* @return the number of instances
*/
public int getNumInstances() {
return m_NumInstances;
}
/**
* sets the class attribute type
*
* @param value the class attribute type
*/
public void setClassType(int value) {
m_ClassType = value;
m_RelationalClassFormat = null;
}
/**
* returns the current class type
*
* @return the class attribute type
*/
public int getClassType() {
return m_ClassType;
}
/**
* sets the number of classes
*
* @param value the number of classes
*/
public void setNumClasses(int value) {
m_NumClasses = value;
}
/**
* returns the current number of classes
*
* @return the number of classes
*/
public int getNumClasses() {
return m_NumClasses;
}
/**
* sets the class index (0-based)
*
* @param value the class index
* @see #CLASS_IS_LAST
* @see #NO_CLASS
*/
public void setClassIndex(int value) {
m_ClassIndex = value;
}
/**
* returns the current class index (0-based), -1 is last attribute
*
* @return the class index
* @see #CLASS_IS_LAST
* @see #NO_CLASS
*/
public int getClassIndex() {
return m_ClassIndex;
}
/**
* whether to have no class, e.g., for clusterers; otherwise the class
* attribute index is set to last
*
* @param value whether to have no class
* @see #CLASS_IS_LAST
* @see #NO_CLASS
*/
public void setNoClass(boolean value) {
if (value) {
setClassIndex(NO_CLASS);
} else {
setClassIndex(CLASS_IS_LAST);
}
}
/**
* whether no class attribute is generated
*
* @return true if no class attribute is generated
*/
public boolean getNoClass() {
return (getClassIndex() == NO_CLASS);
}
/**
* sets the number of nominal attributes
*
* @param value the number of nominal attributes
*/
public void setNumNominal(int value) {
m_NumNominal = value;
}
/**
* returns the current number of nominal attributes
*
* @return the number of nominal attributes
*/
public int getNumNominal() {
return m_NumNominal;
}
/**
* sets the number of values for nominal attributes
*
* @param value the number of values
*/
public void setNumNominalValues(int value) {
m_NumNominalValues = value;
}
/**
* returns the current number of values for nominal attributes
*
* @return the number of values
*/
public int getNumNominalValues() {
return m_NumNominalValues;
}
/**
* sets the number of numeric attributes
*
* @param value the number of numeric attributes
*/
public void setNumNumeric(int value) {
m_NumNumeric = value;
}
/**
* returns the current number of numeric attributes
*
* @return the number of numeric attributes
*/
public int getNumNumeric() {
return m_NumNumeric;
}
/**
* sets the number of string attributes
*
* @param value the number of string attributes
*/
public void setNumString(int value) {
m_NumString = value;
}
/**
* returns the current number of string attributes
*
* @return the number of string attributes
*/
public int getNumString() {
return m_NumString;
}
/**
* turns the comma-separated list into an array
*
* @param value the list to process
* @return the list as array
*/
protected static String[] listToArray(String value) {
StringTokenizer tok;
Vector<String> list;
list = new Vector<String>();
tok = new StringTokenizer(value, ",");
while (tok.hasMoreTokens()) {
list.add(tok.nextToken());
}
return list.toArray(new String[list.size()]);
}
/**
* turns the array into a comma-separated list
*
* @param value the array to process
* @return the array as list
*/
protected static String arrayToList(String[] value) {
String result;
int i;
result = "";
for (i = 0; i < value.length; i++) {
if (i > 0) {
result += ",";
}
result += value[i];
}
return result;
}
/**
* Sets the comma-separated list of words to use for generating strings. The
* list must contain at least 2 words, otherwise an exception will be thrown.
*
* @param value the list of words
* @throws IllegalArgumentException if not at least 2 words are provided
*/
public void setWords(String value) {
if (listToArray(value).length < 2) {
throw new IllegalArgumentException("At least 2 words must be provided!");
}
m_Words = listToArray(value);
}
/**
* returns the words used for assembling strings in a comma-separated list.
*
* @return the words as comma-separated list
*/
public String getWords() {
return arrayToList(m_Words);
}
/**
* sets the word separators (chars) to use for assembling strings.
*
* @param value the characters to use as separators
*/
public void setWordSeparators(String value) {
m_WordSeparators = value;
}
/**
* returns the word separators (chars) to use for assembling strings.
*
* @return the current separators
*/
public String getWordSeparators() {
return m_WordSeparators;
}
/**
* sets the number of date attributes
*
* @param value the number of date attributes
*/
public void setNumDate(int value) {
m_NumDate = value;
}
/**
* returns the current number of date attributes
*
* @return the number of date attributes
*/
public int getNumDate() {
return m_NumDate;
}
/**
* sets the number of relational attributes
*
* @param value the number of relational attributes
*/
public void setNumRelational(int value) {
m_NumRelational = value;
m_RelationalFormat = new Instances[value];
}
/**
* returns the current number of relational attributes
*
* @return the number of relational attributes
*/
public int getNumRelational() {
return m_NumRelational;
}
/**
* sets the number of nominal attributes in a relational attribute
*
* @param value the number of nominal attributes
*/
public void setNumRelationalNominal(int value) {
m_NumRelationalNominal = value;
}
/**
* returns the current number of nominal attributes in a relational attribute
*
* @return the number of nominal attributes
*/
public int getNumRelationalNominal() {
return m_NumRelationalNominal;
}
/**
* sets the number of values for nominal attributes in a relational attribute
*
* @param value the number of values
*/
public void setNumRelationalNominalValues(int value) {
m_NumRelationalNominalValues = value;
}
/**
* returns the current number of values for nominal attributes in a relational
* attribute
*
* @return the number of values
*/
public int getNumRelationalNominalValues() {
return m_NumRelationalNominalValues;
}
/**
* sets the number of numeric attributes in a relational attribute
*
* @param value the number of numeric attributes
*/
public void setNumRelationalNumeric(int value) {
m_NumRelationalNumeric = value;
}
/**
* returns the current number of numeric attributes in a relational attribute
*
* @return the number of numeric attributes
*/
public int getNumRelationalNumeric() {
return m_NumRelationalNumeric;
}
/**
* sets the number of string attributes in a relational attribute
*
* @param value the number of string attributes
*/
public void setNumRelationalString(int value) {
m_NumRelationalString = value;
}
/**
* returns the current number of string attributes in a relational attribute
*
* @return the number of string attributes
*/
public int getNumRelationalString() {
return m_NumRelationalString;
}
/**
* sets the number of date attributes in a relational attribute
*
* @param value the number of date attributes
*/
public void setNumRelationalDate(int value) {
m_NumRelationalDate = value;
}
/**
* returns the current number of date attributes in a relational attribute
*
* @return the number of date attributes
*/
public int getNumRelationalDate() {
return m_NumRelationalDate;
}
/**
* sets the number of instances in relational/bag attributes to produce
*
* @param value the number of instances
*/
public void setNumInstancesRelational(int value) {
m_NumInstancesRelational = value;
}
/**
* returns the current number of instances in relational/bag attributes to
* produce
*
* @return the number of instances
*/
public int getNumInstancesRelational() {
return m_NumInstancesRelational;
}
/**
* sets whether multi-instance data should be generated (with a fixed data
* structure)
*
* @param value whether multi-instance data is generated
*/
public void setMultiInstance(boolean value) {
m_MultiInstance = value;
}
/**
* Gets whether multi-instance data (with a fixed structure) is generated
*
* @return true if multi-instance data is generated
*/
public boolean getMultiInstance() {
return m_MultiInstance;
}
/**
* sets the structure for the bags for the relational attribute
*
* @param index the index of the relational attribute
* @param value the new structure
*/
public void setRelationalFormat(int index, Instances value) {
if (value != null) {
m_RelationalFormat[index] = new Instances(value, 0);
} else {
m_RelationalFormat[index] = null;
}
}
/**
* returns the format for the specified relational attribute, can be null
*
* @param index the index of the relational attribute
* @return the current structure
*/
public Instances getRelationalFormat(int index) {
return m_RelationalFormat[index];
}
/**
* sets the structure for the relational class attribute
*
* @param value the structure for the relational attribute
*/
public void setRelationalClassFormat(Instances value) {
if (value != null) {
m_RelationalClassFormat = new Instances(value, 0);
} else {
m_RelationalClassFormat = null;
}
}
/**
* returns the current strcuture of the relational class attribute, can be
* null
*
* @return the relational structure of the class attribute
*/
public Instances getRelationalClassFormat() {
return m_RelationalClassFormat;
}
/**
* returns the overall number of attributes (incl. class, if that is also
* generated)
*
* @return the overall number of attributes
*/
public int getNumAttributes() {
int result;
result = m_NumNominal + m_NumNumeric + m_NumString + m_NumDate
+ m_NumRelational;
if (!getNoClass()) {
result++;
}
return result;
}
/**
* returns the current dataset, can be null
*
* @return the current dataset
*/
public Instances getData() {
return m_Data;
}
/**
* sets the Capabilities handler to generate the data for
*
* @param value the handler to generate the data for
*/
public void setHandler(CapabilitiesHandler value) {
m_Handler = value;
}
/**
* returns the current set CapabilitiesHandler to generate the dataset for,
* can be null
*
* @return the handler to generate the data for
*/
public CapabilitiesHandler getHandler() {
return m_Handler;
}
/**
* creates a new Attribute of the given type
*
* @param index the index of the current attribute (0-based)
* @param attType the attribute type (NUMERIC, NOMINAL, etc.)
* @return the configured attribute
* @throws Exception if something goes wrong, e.g., an unknown attribute type
*
* @see Attribute#type()
* @see #CLASS_IS_LAST
* @see #NO_CLASS
*/
protected Attribute generateAttribute(int index, int attType,
String namePrefix) throws Exception {
Attribute result;
String name;
int valIndex;
int nomCount;
String prefix;
result = null;
// determine name and start-index
if (index == CLASS_IS_LAST) {
valIndex = 0;
name = "Class";
prefix = "class";
nomCount = getNumClasses();
} else {
valIndex = index;
nomCount = getNumNominalValues();
prefix = "att" + (valIndex + 1) + "val";
switch (attType) {
case Attribute.NOMINAL:
name = "Nominal" + (valIndex + 1);
break;
case Attribute.NUMERIC:
name = "Numeric" + (valIndex + 1);
break;
case Attribute.STRING:
name = "String" + (valIndex + 1);
break;
case Attribute.DATE:
name = "Date" + (valIndex + 1);
break;
case Attribute.RELATIONAL:
name = "Relational" + (valIndex + 1);
break;
default:
throw new IllegalArgumentException("Attribute type '" + attType
+ "' unknown!");
}
}
switch (attType) {
case Attribute.NOMINAL:
ArrayList<String> nomStrings = new ArrayList<String>(valIndex + 1);
for (int j = 0; j < nomCount; j++) {
nomStrings.add(prefix + (j + 1));
}
result = new Attribute(namePrefix + name, nomStrings);
break;
case Attribute.NUMERIC:
result = new Attribute(namePrefix + name);
break;
case Attribute.STRING:
result = new Attribute(namePrefix + name, (ArrayList<String>) null);
break;
case Attribute.DATE:
result = new Attribute(namePrefix + name, "yyyy-mm-dd");
break;
case Attribute.RELATIONAL:
Instances rel;
if (index == CLASS_IS_LAST) {
rel = getRelationalClassFormat();
} else {
rel = getRelationalFormat(index);
}
if (rel == null) {
TestInstances dataset = new TestInstances();
dataset.setNumNominal(getNumRelationalNominal());
dataset.setNumNominalValues(getNumRelationalNominalValues());
dataset.setNumNumeric(getNumRelationalNumeric());
dataset.setNumString(getNumRelationalString());
dataset.setNumDate(getNumRelationalDate());
dataset.setNumInstances(0);
dataset.setClassType(Attribute.NOMINAL); // dummy to avoid endless
// recursion, will be deleted
// anyway
rel = new Instances(dataset.generate());
if (!getNoClass()) {
int clsIndex = rel.classIndex();
rel.setClassIndex(-1);
rel.deleteAttributeAt(clsIndex);
}
}
result = new Attribute(namePrefix + name, rel);
break;
default:
throw new IllegalArgumentException("Attribute type '" + attType
+ "' unknown!");
}
return result;
}
/**
* Generates the class value
*
* @param data the dataset to work on
* @return the new class value
* @throws Exception if something goes wrong
*/
protected double generateClassValue(Instances data) throws Exception {
double result = Double.NaN;
switch (m_ClassType) {
case Attribute.NUMERIC:
result = m_Random.nextFloat() * 0.25 + m_Random.nextInt(Math.max(2, m_NumNominal));
break;
case Attribute.NOMINAL:
result = m_Random.nextInt(data.numClasses());
break;
case Attribute.STRING:
String str = "";
for (int n = 0; n < m_Words.length; n++) {
if ((n > 0) && (m_WordSeparators.length() != 0)) {
str += m_WordSeparators.charAt(m_Random.nextInt(m_WordSeparators
.length()));
}
str += m_Words[m_Random.nextInt(m_Words.length)];
}
result = data.classAttribute().addStringValue(str);
break;
case Attribute.DATE:
result = data.classAttribute().parseDate(
(2000 + m_Random.nextInt(100)) + "-01-01");
break;
case Attribute.RELATIONAL:
if (getRelationalClassFormat() != null) {
result = data.classAttribute().addRelation(getRelationalClassFormat());
} else {
TestInstances dataset = new TestInstances();
dataset.setNumNominal(getNumRelationalNominal());
dataset.setNumNominalValues(getNumRelationalNominalValues());
dataset.setNumNumeric(getNumRelationalNumeric());
dataset.setNumString(getNumRelationalString());
dataset.setNumDate(getNumRelationalDate());
dataset.setNumInstances(getNumInstancesRelational());
dataset.setClassType(Attribute.NOMINAL); // dummy to avoid endless
// recursion, will be deleted
// anyway
Instances rel = new Instances(dataset.generate());
int clsIndex = rel.classIndex();
rel.setClassIndex(-1);
rel.deleteAttributeAt(clsIndex);
result = data.classAttribute().addRelation(rel);
}
break;
}
return result;
}
/**
* Generates a new value for the specified attribute. The classValue might be
* used in the process.
*
* @param data the dataset to work on
* @param index the index of the attribute
* @param classVal the class value for the current instance, might be used in
* the calculation
* @return the new attribute value
* @throws Exception if something goes wrong
*/
protected double generateAttributeValue(Instances data, int index,
double classVal) throws Exception {
double result = Double.NaN;
switch (data.attribute(index).type()) {
case Attribute.NUMERIC:
result = classVal * 4 + m_Random.nextFloat() * 1 - 0.5;
break;
case Attribute.NOMINAL:
if (m_Random.nextFloat() < 0.2) {
result = m_Random.nextInt(data.attribute(index).numValues());
} else {
result = ((int) classVal) % data.attribute(index).numValues();
}
// result = m_Random.nextInt(data.attribute(index).numValues());
break;
case Attribute.STRING:
String str = "";
for (int n = 0; n < m_Words.length; n++) {
if ((n > 0) && (m_WordSeparators.length() != 0)) {
str += m_WordSeparators.charAt(m_Random.nextInt(m_WordSeparators
.length()));
}
str += m_Words[m_Random.nextInt(m_Words.length)];
}
result = data.attribute(index).addStringValue(str);
break;
case Attribute.DATE:
result = data.attribute(index).parseDate(
(2000 + m_Random.nextInt(100)) + "-01-01");
break;
case Attribute.RELATIONAL:
Instances rel = new Instances(data.attribute(index).relation(), 0);
for (int n = 0; n < getNumInstancesRelational(); n++) {
Instance inst = new DenseInstance(rel.numAttributes());
inst.setDataset(data);
for (int i = 0; i < rel.numAttributes(); i++) {
inst.setValue(i, generateAttributeValue(rel, i, 0));
}
rel.add(inst);
}
result = data.attribute(index).addRelation(rel);
break;
}
return result;
}
/**
* Generates a new dataset
*
* @return the generated data
* @throws Exception if something goes wrong
*/
public Instances generate() throws Exception {
return generate("");
}
/**
* generates a new dataset.
*
* @param namePrefix the prefix to add to the name of an attribute
* @return the generated data
* @throws Exception if something goes wrong
*/
public Instances generate(String namePrefix) throws Exception {
if (getMultiInstance()) {
TestInstances bag = (TestInstances) this.clone();
bag.setMultiInstance(false);
bag.setNumInstances(0);
bag.setSeed(m_Random.nextInt());
Instances bagFormat = bag.generate("bagAtt_");
bagFormat.setClassIndex(-1);
bagFormat.deleteAttributeAt(bagFormat.numAttributes() - 1);
// generate multi-instance structure
TestInstances structure = new TestInstances();
structure.setSeed(m_Random.nextInt());
structure.setNumNominal(1);
structure.setNumRelational(1);
structure.setRelationalFormat(0, bagFormat);
structure.setClassType(getClassType());
structure.setNumClasses(getNumClasses());
structure.setRelationalClassFormat(getRelationalClassFormat());
structure.setNumInstances(getNumInstances());
m_Data = structure.generate();
// generate bags
bag.setNumInstances(getNumInstancesRelational());
for (int i = 0; i < getNumInstances(); i++) {
bag.setSeed(m_Random.nextInt());
Instances bagData = new Instances(bag.generate("bagAtt_"));
bagData.setClassIndex(-1);
bagData.deleteAttributeAt(bagData.numAttributes() - 1);
double val = m_Data.attribute(1).addRelation(bagData);
m_Data.instance(i).setValue(1, val);
}
} else {
// initialize
int clsIndex = m_ClassIndex;
if (clsIndex == CLASS_IS_LAST) {
clsIndex = getNumAttributes() - 1;
}
// generate attributes
ArrayList<Attribute> attributes = new ArrayList<Attribute>(
getNumAttributes());
// Add Nominal attributes
for (int i = 0; i < getNumNominal(); i++) {
attributes.add(generateAttribute(i, Attribute.NOMINAL, namePrefix));
}
// Add m_Numeric attributes
for (int i = 0; i < getNumNumeric(); i++) {
attributes.add(generateAttribute(i, Attribute.NUMERIC, namePrefix));
}
// Add some String attributes...
for (int i = 0; i < getNumString(); i++) {
attributes.add(generateAttribute(i, Attribute.STRING, namePrefix));
}
// Add some Date attributes...
for (int i = 0; i < getNumDate(); i++) {
attributes.add(generateAttribute(i, Attribute.DATE, namePrefix));
}
// Add some Relational attributes...
for (int i = 0; i < getNumRelational(); i++) {
attributes.add(generateAttribute(i, Attribute.RELATIONAL, namePrefix));
}
// Add class attribute
if (clsIndex != NO_CLASS) {
attributes.add(clsIndex,
generateAttribute(CLASS_IS_LAST, getClassType(), namePrefix));
}
m_Data = new Instances(getRelation(), attributes, getNumInstances());
m_Data.setClassIndex(clsIndex);
// generate instances
for (int i = 0; i < getNumInstances(); i++) {
Instance current = new DenseInstance(getNumAttributes());
current.setDataset(m_Data);
// class
double classVal;
if (clsIndex != NO_CLASS) {
classVal = generateClassValue(m_Data);
current.setClassValue(classVal);
} else {
classVal = m_Random.nextFloat();
}
if ((clsIndex != NO_CLASS) && (m_Data.classAttribute().isString()))
classVal++; // Hack to make regression tests pass after eliminating dummy value for string attributes
// other attributes
for (int n = 0; n < getNumAttributes(); n++) {
if (clsIndex == n) {
continue;
}
current.setValue(n, generateAttributeValue(m_Data, n, classVal));
}
m_Data.add(current);
}
}
if (m_Data.classIndex() == NO_CLASS) {
m_Data.setClassIndex(-1);
}
return getData();
}
/**
* returns a TestInstances instance setup already for the the given
* capabilities.
*
* @param c the capabilities to base the TestInstances on
* @return the configured TestInstances object
*/
public static TestInstances forCapabilities(Capabilities c) {
TestInstances result;
result = new TestInstances();
// multi-instance?
if (c.getOwner() instanceof MultiInstanceCapabilitiesHandler) {
Capabilities multi = (Capabilities) ((MultiInstanceCapabilitiesHandler) c
.getOwner()).getMultiInstanceCapabilities().clone();
multi.setOwner(null); // otherwise recursive!
result = forCapabilities(multi);
result.setMultiInstance(true);
} else {
// class
if (c.handles(Capability.NO_CLASS)) {
result.setClassIndex(NO_CLASS);
} else if (c.handles(Capability.NOMINAL_CLASS)) {
result.setClassType(Attribute.NOMINAL);
} else if (c.handles(Capability.BINARY_CLASS)) {
result.setClassType(Attribute.NOMINAL);
} else if (c.handles(Capability.NUMERIC_CLASS)) {
result.setClassType(Attribute.NUMERIC);
} else if (c.handles(Capability.DATE_CLASS)) {
result.setClassType(Attribute.DATE);
} else if (c.handles(Capability.STRING_CLASS)) {
result.setClassType(Attribute.STRING);
} else if (c.handles(Capability.RELATIONAL_CLASS)) {
result.setClassType(Attribute.RELATIONAL);
}
// # of classes
if (c.handles(Capability.UNARY_CLASS)) {
result.setNumClasses(1);
}
if (c.handles(Capability.BINARY_CLASS)) {
result.setNumClasses(2);
}
if (c.handles(Capability.NOMINAL_CLASS)) {
result.setNumClasses(4);
}
// attributes
if (c.handles(Capability.NOMINAL_ATTRIBUTES)) {
result.setNumNominal(1);
result.setNumRelationalNominal(1);
} else {
result.setNumNominal(0);
result.setNumRelationalNominal(0);
}
if (c.handles(Capability.NUMERIC_ATTRIBUTES)) {
result.setNumNumeric(1);
result.setNumRelationalNumeric(1);
} else {
result.setNumNumeric(0);
result.setNumRelationalNumeric(0);
}
if (c.handles(Capability.DATE_ATTRIBUTES)) {
result.setNumDate(1);
result.setNumRelationalDate(1);
} else {
result.setNumDate(0);
result.setNumRelationalDate(0);
}
if (c.handles(Capability.STRING_ATTRIBUTES)) {
result.setNumString(1);
result.setNumRelationalString(1);
} else {
result.setNumString(0);
result.setNumRelationalString(0);
}
if (c.handles(Capability.RELATIONAL_ATTRIBUTES)) {
result.setNumRelational(1);
} else {
result.setNumRelational(0);
}
}
return result;
}
/**
* returns a string representation of the object
*
* @return a string representation of the object
*/
@Override
public String toString() {
String result;
result = "";
result += "Relation: " + getRelation() + "\n";
result += "Seed: " + getSeed() + "\n";
result += "# Instances: " + getNumInstances() + "\n";
result += "ClassType: " + getClassType() + "\n";
result += "# Classes: " + getNumClasses() + "\n";
result += "Class index: " + getClassIndex() + "\n";
result += "# Nominal: " + getNumNominal() + "\n";
result += "# Nominal values: " + getNumNominalValues() + "\n";
result += "# Numeric: " + getNumNumeric() + "\n";
result += "# String: " + getNumString() + "\n";
result += "# Date: " + getNumDate() + "\n";
result += "# Relational: " + getNumRelational() + "\n";
result += " - # Nominal: " + getNumRelationalNominal() + "\n";
result += " - # Nominal values: " + getNumRelationalNominalValues() + "\n";
result += " - # Numeric: " + getNumRelationalNumeric() + "\n";
result += " - # String: " + getNumRelationalString() + "\n";
result += " - # Date: " + getNumRelationalDate() + "\n";
result += " - # Instances: " + getNumInstancesRelational() + "\n";
result += "Multi-Instance: " + getMultiInstance() + "\n";
result += "Words: " + getWords() + "\n";
result += "Word separators: " + getWordSeparators() + "\n";
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* for running the class from commandline, prints the generated data to stdout
*
* @param args the commandline parameters
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
TestInstances inst;
inst = new TestInstances();
// help requested?
if (Utils.getFlag("h", args) || Utils.getFlag("help", args)) {
StringBuffer result = new StringBuffer();
result.append("\nTest data generator options:\n\n");
result.append("-h|-help\n\tprints this help\n");
Enumeration<Option> enm = inst.listOptions();
while (enm.hasMoreElements()) {
Option option = enm.nextElement();
result.append(option.synopsis() + "\n" + option.description() + "\n");
}
System.out.println(result);
System.exit(0);
}
// generate data
inst.setOptions(args);
System.out.println(inst.generate());
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/ThreadSafe.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ThreadSafe.java
* Copyright (C) 2013 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Interface to something that is thread safe
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public interface ThreadSafe {
// marker interface only
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Trie.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Trie.java
* Copyright (C) 2007-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.tree.DefaultMutableTreeNode;
/**
* A class representing a Trie data structure for strings. See also <a
* href="http://en.wikipedia.org/wiki/Trie" target="_blank">Trie</a> on
* WikiPedia.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Trie implements Serializable, Cloneable, Collection<String>,
RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -5897980928817779048L;
/**
* Represents a node in the trie.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public static class TrieNode extends DefaultMutableTreeNode implements
RevisionHandler {
/** for serialization */
private static final long serialVersionUID = -2252907099391881148L;
/** the stop character */
public final static Character STOP = '\0';
/** for fast access to the children */
protected Hashtable<Character, TrieNode> m_Children;
/**
* initializes the node
*
* @param c the value of this node
*/
public TrieNode(char c) {
this(new Character(c));
}
/**
* initializes the node
*
* @param c the value of this node
*/
public TrieNode(Character c) {
super(c);
m_Children = new Hashtable<Character, TrieNode>(100);
}
/**
* returns the stored character
*
* @return the stored character
*/
public Character getChar() {
return (Character) getUserObject();
}
/**
* sets the character this node represents
*
* @param value the character to store
*/
public void setChar(Character value) {
setUserObject(value);
}
/**
* adds the given string to its children (creates children if necessary)
*
* @param suffix the suffix to add to its children
* @return true if the add operation changed the structure
*/
public boolean add(String suffix) {
boolean result;
Character c;
String newSuffix;
TrieNode child;
result = false;
c = suffix.charAt(0);
newSuffix = suffix.substring(1);
// find child and add if necessary
child = m_Children.get(c);
if (child == null) {
result = true;
child = add(c);
}
// propagate remaining suffix
if (newSuffix.length() > 0) {
result = child.add(newSuffix) || result;
}
return result;
}
/**
* adds the given charater to its children
*
* @param c the character to add
* @return the generated child node
*/
protected TrieNode add(Character c) {
TrieNode child;
child = new TrieNode(c);
add(child);
m_Children.put(c, child);
return child;
}
/**
* removes the given characted from its children
*
* @param c the character to remove
*/
protected void remove(Character c) {
TrieNode child;
child = m_Children.get(c);
remove(child);
m_Children.remove(c);
}
/**
* Removes a suffix from the trie.
*
* @param suffix the suffix to remove
* @return true if this trie changed as a result of the call
*/
public boolean remove(String suffix) {
boolean result;
Character c;
String newSuffix;
TrieNode child;
c = suffix.charAt(0);
newSuffix = suffix.substring(1);
child = m_Children.get(c);
if (child == null) {
result = false;
} else if (newSuffix.length() == 0) {
remove(c);
result = true;
} else {
result = child.remove(newSuffix);
if (child.getChildCount() == 0) {
remove(child.getChar());
}
}
return result;
}
/**
* checks whether a suffix can be found in its children
*
* @param suffix the suffix to look for
* @return true if suffix was found
*/
public boolean contains(String suffix) {
boolean result;
Character c;
String newSuffix;
TrieNode child;
c = suffix.charAt(0);
newSuffix = suffix.substring(1);
child = m_Children.get(c);
if (child == null) {
result = false;
} else if (newSuffix.length() == 0) {
result = true;
} else {
result = child.contains(newSuffix);
}
return result;
}
/**
* creates a deep copy of itself
*
* @return a deep copy of itself
*/
@Override
public Object clone() {
TrieNode result;
Enumeration<Character> keys;
Character key;
TrieNode child;
result = new TrieNode(getChar());
keys = m_Children.keys();
while (keys.hasMoreElements()) {
key = keys.nextElement();
child = (TrieNode) m_Children.get(key).clone();
result.add(child);
result.m_Children.put(key, child);
}
return result;
}
/**
* Indicates whether some other object is "equal to" this one.
*
* @param obj the object to check for equality
* @return true if equal
*/
@Override
public boolean equals(Object obj) {
boolean result;
TrieNode node;
Enumeration<Character> keys;
Character key;
node = (TrieNode) obj;
// is payload the same?
if (getChar() == null) {
result = (node.getChar() == null);
} else {
result = getChar().equals(node.getChar());
}
// check children
if (result) {
keys = m_Children.keys();
while (keys.hasMoreElements()) {
key = keys.nextElement();
result = m_Children.get(key).equals(node.m_Children.get(key));
if (!result) {
break;
}
}
}
return result;
}
/**
* returns the node with the given suffix
*
* @param suffix the suffix to look for
* @return null if unsuccessful otherwise the corresponding node
*/
public TrieNode find(String suffix) {
TrieNode result;
Character c;
String newSuffix;
TrieNode child;
c = suffix.charAt(0);
newSuffix = suffix.substring(1);
child = m_Children.get(c);
if (child == null) {
result = null;
} else if (newSuffix.length() == 0) {
result = child;
} else {
result = child.find(newSuffix);
}
return result;
}
/**
* returns the common prefix for all the nodes starting with this node. The
* result includes this node, unless it's the root node or a STOP node.
*
* @return the result of the search
*/
public String getCommonPrefix() {
return getCommonPrefix("");
}
/**
* returns the common prefix for all the nodes starting with the node for
* the specified prefix. Can be null if initial prefix is not found. The
* result includes this node, unless it's the root node or a STOP node.
* Using the empty string means starting with this node.
*
* @param startPrefix the prefix of the node to start the search from
* @return the result of the search, null if startPrefix cannot be found
*/
public String getCommonPrefix(String startPrefix) {
String result;
TrieNode startNode;
if (startPrefix.length() == 0) {
startNode = this;
} else {
startNode = find(startPrefix);
}
if (startNode == null) {
result = null;
} else {
result = startPrefix + startNode.determineCommonPrefix("");
}
return result;
}
/**
* determines the common prefix of the nodes.
*
* @param currentPrefix the common prefix found so far
* @return the result of the search
*/
protected String determineCommonPrefix(String currentPrefix) {
String result;
String newPrefix;
if (!isRoot() && (getChar() != STOP)) {
newPrefix = currentPrefix + getChar();
} else {
newPrefix = currentPrefix;
}
if (m_Children.size() == 1) {
result = ((TrieNode) getChildAt(0)).determineCommonPrefix(newPrefix);
} else {
result = newPrefix;
}
return result;
}
/**
* returns the number of stored strings, i.e., leaves
*
* @return the number of stored strings
*/
public int size() {
int result;
TrieNode leaf;
result = 0;
leaf = (TrieNode) getFirstLeaf();
while (leaf != null) {
if (leaf != getRoot()) {
result++;
}
leaf = (TrieNode) leaf.getNextLeaf();
}
return result;
}
/**
* returns the full string up to the root
*
* @return the full string to the root
*/
public String getString() {
char[] result;
TrieNode node;
result = new char[this.getLevel()];
node = this;
while (node.getParent() != null) {
if (node.isRoot()) {
break;
} else {
result[node.getLevel() - 1] = node.getChar();
}
node = (TrieNode) node.getParent();
}
return new String(result);
}
/**
* returns the node in a string representation
*
* @return the node as string
*/
@Override
public String toString() {
return "" + getChar();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* Represents an iterator over a trie
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public static class TrieIterator implements Iterator<String>, RevisionHandler {
/** the node to use as root */
protected TrieNode m_Root;
/** the last leaf for this root node */
protected TrieNode m_LastLeaf;
/** the current leaf node */
protected TrieNode m_CurrentLeaf;
/**
* initializes the iterator
*
* @param node the node to use as root
*/
public TrieIterator(TrieNode node) {
super();
m_Root = node;
m_CurrentLeaf = (TrieNode) m_Root.getFirstLeaf();
m_LastLeaf = (TrieNode) m_Root.getLastLeaf();
}
/**
* Returns true if the iteration has more elements.
*
* @return true if there is at least one more element
*/
@Override
public boolean hasNext() {
return (m_CurrentLeaf != null);
}
/**
* Returns the next element in the iteration.
*
* @return the next element
*/
@Override
public String next() {
String result;
result = m_CurrentLeaf.getString();
result = result.substring(0, result.length() - 1); // remove STOP
if (m_CurrentLeaf != m_LastLeaf) {
m_CurrentLeaf = (TrieNode) m_CurrentLeaf.getNextLeaf();
} else {
m_CurrentLeaf = null;
}
return result;
}
/**
* ignored
*/
@Override
public void remove() {
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/** the root node */
protected TrieNode m_Root;
/** the hash code */
protected int m_HashCode;
/**
* whether the structure got modified and the hash code needs to be
* re-calculated
*/
protected boolean m_RecalcHashCode;
/**
* initializes the data structure
*/
public Trie() {
super();
m_Root = new TrieNode(null);
m_RecalcHashCode = true;
}
/**
* Ensures that this collection contains the specified element.
*
* @param o the string to add
* @return true if the structure changed
*/
@Override
public boolean add(String o) {
return m_Root.add(o + TrieNode.STOP);
}
/**
* Adds all of the elements in the specified collection to this collection
*
* @param c the collection to add
*/
@Override
public boolean addAll(Collection<? extends String> c) {
boolean result;
Iterator<? extends String> iter;
result = false;
iter = c.iterator();
while (iter.hasNext()) {
result = add(iter.next()) || result;
}
return result;
}
/**
* Removes all of the elements from this collection
*/
@Override
public void clear() {
m_Root.removeAllChildren();
m_RecalcHashCode = true;
}
/**
* returns a deep copy of itself
*
* @return a copy of itself
*/
@Override
public Object clone() {
Trie result;
result = new Trie();
result.m_Root = (TrieNode) m_Root.clone();
return result;
}
/**
* Returns true if this collection contains the specified element.
*
* @param o the object to check for in trie
* @return true if found
*/
@Override
public boolean contains(Object o) {
return m_Root.contains(((String) o) + TrieNode.STOP);
}
/**
* Returns true if this collection contains all of the elements in the
* specified collection.
*
* @param c the collection to look for in the trie
* @return true if all elements were found
*/
@Override
public boolean containsAll(Collection<?> c) {
boolean result;
Iterator<?> iter;
result = true;
iter = c.iterator();
while (iter.hasNext()) {
if (!contains(iter.next())) {
result = false;
break;
}
}
return result;
}
/**
* checks whether the given prefix is stored in the trie
*
* @param prefix the prefix to check
* @return true if the prefix is part of the trie
*/
public boolean containsPrefix(String prefix) {
return m_Root.contains(prefix);
}
/**
* Compares the specified object with this collection for equality.
*
* @param o the object to check for equality
*/
@Override
public boolean equals(Object o) {
return m_Root.equals(((Trie) o).getRoot());
}
/**
* returns the common prefix for all the nodes
*
* @return the result of the search
*/
public String getCommonPrefix() {
return m_Root.getCommonPrefix();
}
/**
* returns the root node of the trie
*
* @return the root node
*/
public TrieNode getRoot() {
return m_Root;
}
/**
* returns all stored strings that match the given prefix
*
* @param prefix the prefix that all strings must have
* @return all strings that match the prefix
*/
public Vector<String> getWithPrefix(String prefix) {
Vector<String> result;
TrieNode node;
TrieIterator iter;
result = new Vector<String>();
if (containsPrefix(prefix)) {
node = m_Root.find(prefix);
iter = new TrieIterator(node);
while (iter.hasNext()) {
result.add(iter.next());
}
}
return result;
}
/**
* Returns the hash code value for this collection.
*
* @return the hash code
*/
@Override
public int hashCode() {
if (m_RecalcHashCode) {
m_HashCode = toString().hashCode();
m_RecalcHashCode = false;
}
return m_HashCode;
}
/**
* Returns true if this collection contains no elements.
*
* @return true if empty
*/
@Override
public boolean isEmpty() {
return (m_Root.getChildCount() == 0);
}
/**
* Returns an iterator over the elements in this collection.
*
* @return returns an iterator over all the stored strings
*/
@Override
public Iterator<String> iterator() {
return new TrieIterator(m_Root);
}
/**
* Removes a single instance of the specified element from this collection, if
* it is present.
*
* @param o the object to remove
* @return true if this collection changed as a result of the call
*/
@Override
public boolean remove(Object o) {
boolean result;
result = m_Root.remove(((String) o) + TrieNode.STOP);
m_RecalcHashCode = result;
return result;
}
/**
* Removes all this collection's elements that are also contained in the
* specified collection
*
* @param c the collection to remove
* @return true if the collection changed
*/
@Override
public boolean removeAll(Collection<?> c) {
boolean result;
Iterator<?> iter;
result = false;
iter = c.iterator();
while (iter.hasNext()) {
result = remove(iter.next()) || result;
}
m_RecalcHashCode = result;
return result;
}
/**
* Retains only the elements in this collection that are contained in the
* specified collection
*
* @param c the collection to use as reference
* @return true if this collection changed as a result of the call
*/
@Override
public boolean retainAll(Collection<?> c) {
boolean result;
Iterator<?> iter;
Object o;
result = false;
iter = iterator();
while (iter.hasNext()) {
o = iter.next();
if (!c.contains(o)) {
result = remove(o) || result;
}
}
m_RecalcHashCode = result;
return result;
}
/**
* Returns the number of elements in this collection.
*
* @return the number of nodes in the tree
*/
@Override
public int size() {
return m_Root.size();
}
/**
* Returns an array containing all of the elements in this collection.
*
* @return the stored strings as array
*/
@Override
public Object[] toArray() {
return toArray(new String[0]);
}
/**
* Returns an array containing all of the elements in this collection; the
* runtime type of the returned array is that of the specified array.
*
* @param a the array into which the elements of this collection are to be
* stored
* @return an array containing the elements of this collection
*/
@Override
public <T> T[] toArray(T[] a) {
T[] result;
Iterator<T> iter;
Vector<T> list;
int i;
list = new Vector<T>();
iter = Utils.<Iterator<T>> cast(iterator());
while (iter.hasNext()) {
list.add(iter.next());
}
if (Array.getLength(a) != list.size()) {
result = Utils.<T[]> cast(Array.newInstance(a.getClass()
.getComponentType(), list.size()));
} else {
result = a;
}
for (i = 0; i < list.size(); i++) {
result[i] = list.get(i);
}
return result;
}
/**
* returns the node as String
*
* @param node the node to turn into a string
* @return the node as string
*/
protected String toString(TrieNode node) {
StringBuffer result;
int i;
StringBuffer indentation;
result = new StringBuffer();
// indent the node
indentation = new StringBuffer();
for (i = 0; i < node.getLevel(); i++) {
indentation.append(" | ");
}
result.append(indentation.toString());
// add the node label
if (node.getChar() == null) {
result.append("<root>");
} else if (node.getChar() == TrieNode.STOP) {
result.append("STOP");
} else {
result.append("'" + node.getChar() + "'");
}
result.append("\n");
// add the children
for (i = 0; i < node.getChildCount(); i++) {
result.append(toString((TrieNode) node.getChildAt(i)));
}
return result.toString();
}
/**
* returns the trie in string representation
*
* @return the trie as string
*/
@Override
public String toString() {
return toString(m_Root);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Only for testing (prints the built Trie). Arguments are added to the Trie.
* If not arguments provided then a few default strings are uses for building.
*
* @param args commandline arguments
*/
public static void main(String[] args) {
String[] data;
if (args.length == 0) {
data = new String[3];
data[0] = "this is a test";
data[1] = "this is another test";
data[2] = "and something else";
} else {
data = args.clone();
}
// build trie
Trie t = new Trie();
for (String element : data) {
t.add(element);
}
System.out.println(t);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/UnassignedClassException.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* UnassignedClassException.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Exception that is raised when trying to use some data that has no
* class assigned to it, but a class is needed to perform the operation.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class UnassignedClassException
extends RuntimeException {
/** for serialization */
private static final long serialVersionUID = 6268278694768818235L;
/**
* Creates a new UnassignedClassException with no message.
*
*/
public UnassignedClassException() {
super();
}
/**
* Creates a new UnassignedClassException.
*
* @param message the reason for raising an exception.
*/
public UnassignedClassException(String message) {
super(message);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/UnassignedDatasetException.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* UnassignedDatasetException.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Exception that is raised when trying to use something that has no
* reference to a dataset, when one is required.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class UnassignedDatasetException
extends RuntimeException {
/** for serialization */
private static final long serialVersionUID = -9000116786626328854L;
/**
* Creates a new UnassignedDatasetException with no message.
*
*/
public UnassignedDatasetException() {
super();
}
/**
* Creates a new UnassignedDatasetException.
*
* @param message the reason for raising an exception.
*/
public UnassignedDatasetException(String message) {
super(message);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Undoable.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Copyable.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Interface implemented by classes that support undo.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public interface Undoable {
/**
* returns whether undo support is enabled
*/
public boolean isUndoEnabled();
/**
* sets whether undo support is enabled
*/
public void setUndoEnabled(boolean enabled);
/**
* removes the undo history
*/
public void clearUndo();
/**
* returns whether an undo is possible, i.e. whether there are any undo points
* saved so far
*
* @return returns TRUE if there is an undo possible
*/
public boolean canUndo();
/**
* undoes the last action
*/
public void undo();
/**
* adds an undo point to the undo history
*/
public void addUndoPoint();
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/UnsupportedAttributeTypeException.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* UnsuppotedAttributeTypeException.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Exception that is raised by an object that is unable to process some of the
* attribute types it has been passed.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class UnsupportedAttributeTypeException
extends WekaException {
/** for serialization */
private static final long serialVersionUID = 2658987325328414838L;
/**
* Creates a new UnsupportedAttributeTypeException with no message.
*
*/
public UnsupportedAttributeTypeException() {
super();
}
/**
* Creates a new UnsupportedAttributeTypeException.
*
* @param message the reason for raising an exception.
*/
public UnsupportedAttributeTypeException(String message) {
super(message);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/UnsupportedClassTypeException.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* UnsuppotedClassTypeException.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Exception that is raised by an object that is unable to process the
* class type of the data it has been passed.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class UnsupportedClassTypeException
extends WekaException {
/** for serialization */
private static final long serialVersionUID = 5175741076972192151L;
/**
* Creates a new UnsupportedClassTypeException with no message.
*
*/
public UnsupportedClassTypeException() {
super();
}
/**
* Creates a new UnsupportedClassTypeException.
*
* @param message the reason for raising an exception.
*/
public UnsupportedClassTypeException(String message) {
super(message);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Utils.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Utils.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Window;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.MethodDescriptor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.math.RoundingMode;
import java.text.BreakIterator;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.Properties;
import java.util.Random;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
/**
* Class implementing some simple utility methods.
*
* @author Eibe Frank
* @author Yong Wang
* @author Len Trigg
* @author Julien Prados
* @version $Revision$
*/
public final class Utils implements RevisionHandler {
/**
* The natural logarithm of 2.
*/
public static double log2 = Math.log(2);
/**
* The small deviation allowed in double comparisons.
*/
public static double SMALL = 1e-6;
/** Decimal format */
private static final ThreadLocal<DecimalFormat> DF = new ThreadLocal<DecimalFormat>() {
@Override
protected DecimalFormat initialValue() {
DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols dfs = df.getDecimalFormatSymbols();
dfs.setDecimalSeparator('.');
dfs.setNaN("NaN");
dfs.setInfinity("Infinity");
df.setGroupingUsed(false);
df.setRoundingMode(RoundingMode.HALF_UP);
df.setDecimalFormatSymbols(dfs);
return df;
}
};
/**
* Turns a given date string into Java's internal representation (milliseconds
* from 1 January 1970).
*
* @param dateString the string representing the date
* @param dateFormat the date format as a string
*
* @return milliseconds since 1 January 1970 (as a double converted from long)
*/
public static double dateToMillis(final String dateString, final String dateFormat) throws ParseException {
return new java.text.SimpleDateFormat(dateFormat).parse(dateString).getTime();
}
/**
* Tests if the given value codes "missing".
*
* @param val the value to be tested
* @return true if val codes "missing"
*/
public static boolean isMissingValue(final double val) {
return Double.isNaN(val);
}
/**
* Returns the value used to code a missing value. Note that equality tests on
* this value will always return false, so use isMissingValue(double val) for
* testing..
*
* @return the value used as missing value.
*/
public static double missingValue() {
return Double.NaN;
}
/**
* Casting an object without "unchecked" compile-time warnings. Use only when
* absolutely necessary (e.g. when using clone()).
*/
@SuppressWarnings("unchecked")
public static <T> T cast(final Object x) {
return (T) x;
}
/**
* Reads properties that inherit from three locations. Properties are first
* defined in the system resource location (i.e. in the CLASSPATH). These
* default properties must exist. Properties optionally defined in the user
* properties location (WekaPackageManager.PROPERTIES_DIR) override default
* settings. Properties defined in the current directory (optional) override
* all these settings.
*
* @param resourceName the location of the resource that should be loaded.
* e.g.: "weka/core/Utils.props". (The use of hardcoded forward
* slashes here is OK - see jdk1.1/docs/guide/misc/resources.html)
* This routine will also look for the file (in this case)
* "Utils.props" in the users home directory and the current
* directory.
* @return the Properties
* @exception Exception if no default properties are defined, or if an error
* occurs reading the properties files.
*/
public static Properties readProperties(final String resourceName) throws Exception {
return ResourceUtils.readProperties(resourceName);
}
/**
* Reads properties that inherit from three locations. Properties are first
* defined in the system resource location (i.e. in the CLASSPATH). These
* default properties must exist. Properties optionally defined in the user
* properties location (WekaPackageManager.PROPERTIES_DIR) override default
* settings. Properties defined in the current directory (optional) override
* all these settings.
*
* @param resourceName the location of the resource that should be loaded.
* e.g.: "weka/core/Utils.props". (The use of hardcoded forward
* slashes here is OK - see jdk1.1/docs/guide/misc/resources.html)
* This routine will also look for the file (in this case)
* "Utils.props" in the users home directory and the current
* directory.
* @param loader the class loader to use when loading properties
* @return the Properties
* @exception Exception if no default properties are defined, or if an error
* occurs reading the properties files.
*/
public static Properties readProperties(final String resourceName, final ClassLoader loader) throws Exception {
return ResourceUtils.readProperties(resourceName, loader);
}
/**
* Returns the correlation coefficient of two double vectors.
*
* @param y1 double vector 1
* @param y2 double vector 2
* @param n the length of two double vectors
* @return the correlation coefficient
*/
public static final double correlation(final double y1[], final double y2[], final int n) {
int i;
double av1 = 0.0, av2 = 0.0, y11 = 0.0, y22 = 0.0, y12 = 0.0, c;
if (n <= 1) {
return 1.0;
}
for (i = 0; i < n; i++) {
av1 += y1[i];
av2 += y2[i];
}
av1 /= n;
av2 /= n;
for (i = 0; i < n; i++) {
y11 += (y1[i] - av1) * (y1[i] - av1);
y22 += (y2[i] - av2) * (y2[i] - av2);
y12 += (y1[i] - av1) * (y2[i] - av2);
}
if (y11 * y22 == 0.0) {
c = 1.0;
} else {
c = y12 / Math.sqrt(Math.abs(y11 * y22));
}
return c;
}
/**
* Removes all occurrences of a string from another string.
*
* @param inString the string to remove substrings from.
* @param substring the substring to remove.
* @return the input string with occurrences of substring removed.
*/
public static String removeSubstring(final String inString, final String substring) {
StringBuffer result = new StringBuffer();
int oldLoc = 0, loc = 0;
while ((loc = inString.indexOf(substring, oldLoc)) != -1) {
result.append(inString.substring(oldLoc, loc));
oldLoc = loc + substring.length();
}
result.append(inString.substring(oldLoc));
return result.toString();
}
/**
* Replaces with a new string, all occurrences of a string from another
* string.
*
* @param inString the string to replace substrings in.
* @param subString the substring to replace.
* @param replaceString the replacement substring
* @return the input string with occurrences of substring replaced.
*/
public static String replaceSubstring(final String inString, final String subString, final String replaceString) {
StringBuffer result = new StringBuffer();
int oldLoc = 0, loc = 0;
while ((loc = inString.indexOf(subString, oldLoc)) != -1) {
result.append(inString.substring(oldLoc, loc));
result.append(replaceString);
oldLoc = loc + subString.length();
}
result.append(inString.substring(oldLoc));
return result.toString();
}
/**
* Pads a string to a specified length, inserting spaces on the left as
* required. If the string is too long, it is simply returned unchanged.
*
* @param inString the input string
* @param length the desired length of the output string
* @return the output string
*/
public static String padLeftAndAllowOverflow(final String inString, final int length) {
return String.format("%1$" + length + "s", inString);
}
/**
* Pads a string to a specified length, inserting spaces on the right as
* required. If the string is too long, it is simply returned unchanged.
*
* @param inString the input string
* @param length the desired length of the output string
* @return the output string
*/
public static String padRightAndAllowOverflow(final String inString, final int length) {
return String.format("%1$-" + length + "s", inString);
}
/**
* Pads a string to a specified length, inserting spaces on the left as
* required. If the string is too long, characters are removed (from the
* right).
*
* @param inString the input string
* @param length the desired length of the output string
* @return the output string
*/
public static String padLeft(final String inString, final int length) {
return String.format("%1$" + length + "." + length + "s", inString);
}
/**
* Pads a string to a specified length, inserting spaces on the right as
* required. If the string is too long, characters are removed (from the
* right).
*
* @param inString the input string
* @param length the desired length of the output string
* @return the output string
*/
public static String padRight(final String inString, final int length) {
return String.format("%1$-" + length + "." + length + "s", inString);
}
/**
* Rounds a double and converts it into String.
*
* @param value the double value
* @param afterDecimalPoint the (maximum) number of digits permitted after the
* decimal point
* @return the double as a formatted string
*/
public static/* @pure@ */String doubleToString(final double value, final int afterDecimalPoint) {
DF.get().setMaximumFractionDigits(afterDecimalPoint);
return DF.get().format(value);
}
/**
* Rounds a double and converts it into a formatted decimal-justified String.
* Trailing 0's are replaced with spaces.
*
* @param value the double value
* @param width the width of the string
* @param afterDecimalPoint the number of digits after the decimal point
* @return the double as a formatted string
*/
public static/* @pure@ */String doubleToString(final double value, final int width, final int afterDecimalPoint) {
String tempString = doubleToString(value, afterDecimalPoint);
char[] result;
int dotPosition;
if (afterDecimalPoint >= width) {
return tempString;
}
// Initialize result
result = new char[width];
for (int i = 0; i < result.length; i++) {
result[i] = ' ';
}
if (afterDecimalPoint > 0) {
// Get position of decimal point and insert decimal point
dotPosition = tempString.indexOf('.');
if (dotPosition == -1) {
dotPosition = tempString.length();
} else {
result[width - afterDecimalPoint - 1] = '.';
}
} else {
dotPosition = tempString.length();
}
int offset = width - afterDecimalPoint - dotPosition;
if (afterDecimalPoint > 0) {
offset--;
}
// Not enough room to decimal align within the supplied width
if (offset < 0) {
return tempString;
}
// Copy characters before decimal point
for (int i = 0; i < dotPosition; i++) {
result[offset + i] = tempString.charAt(i);
}
// Copy characters after decimal point
for (int i = dotPosition + 1; i < tempString.length(); i++) {
result[offset + i] = tempString.charAt(i);
}
return new String(result);
}
/**
* Returns the basic class of an array class (handles multi-dimensional
* arrays).
*
* @param c the array to inspect
* @return the class of the innermost elements
*/
public static Class<?> getArrayClass(final Class<?> c) {
if (c.getComponentType().isArray()) {
return getArrayClass(c.getComponentType());
} else {
return c.getComponentType();
}
}
/**
* Returns the dimensions of the given array. Even though the parameter is of
* type "Object" one can hand over primitve arrays, e.g. int[3] or
* double[2][4].
*
* @param array the array to determine the dimensions for
* @return the dimensions of the array
*/
public static int getArrayDimensions(final Class<?> array) {
if (array.getComponentType().isArray()) {
return 1 + getArrayDimensions(array.getComponentType());
} else {
return 1;
}
}
/**
* Returns the dimensions of the given array. Even though the parameter is of
* type "Object" one can hand over primitve arrays, e.g. int[3] or
* double[2][4].
*
* @param array the array to determine the dimensions for
* @return the dimensions of the array
*/
public static int getArrayDimensions(final Object array) {
return getArrayDimensions(array.getClass());
}
/**
* Returns the given Array in a string representation. Even though the
* parameter is of type "Object" one can hand over primitve arrays, e.g.
* int[3] or double[2][4].
*
* @param array the array to return in a string representation
* @return the array as string
*/
public static String arrayToString(final Object array) {
String result;
int dimensions;
int i;
result = "";
dimensions = getArrayDimensions(array);
if (dimensions == 0) {
result = "null";
} else if (dimensions == 1) {
for (i = 0; i < Array.getLength(array); i++) {
if (i > 0) {
result += ",";
}
if (Array.get(array, i) == null) {
result += "null";
} else {
result += Array.get(array, i).toString();
}
}
} else {
for (i = 0; i < Array.getLength(array); i++) {
if (i > 0) {
result += ",";
}
result += "[" + arrayToString(Array.get(array, i)) + "]";
}
}
return result;
}
/**
* Tests if a is equal to b.
*
* @param a a double
* @param b a double
*/
public static/* @pure@ */boolean eq(final double a, final double b) {
return (a == b) || ((a - b < SMALL) && (b - a < SMALL));
}
/**
* Checks if the given array contains any non-empty options.
*
* @param options an array of strings
* @exception Exception if there are any non-empty options
*/
public static void checkForRemainingOptions(final String[] options) throws Exception {
int illegalOptionsFound = 0;
StringBuffer text = new StringBuffer();
if (options == null) {
return;
}
for (String option : options) {
if (option.length() > 0) {
illegalOptionsFound++;
text.append(option + ' ');
}
}
if (illegalOptionsFound > 0) {
throw new Exception("Illegal options: " + text);
}
}
/**
* Checks if the given array contains the flag "-Char". Stops searching at the
* first marker "--". If the flag is found, it is replaced with the empty
* string.
*
* @param flag the character indicating the flag.
* @param options the array of strings containing all the options.
* @return true if the flag was found
* @exception Exception if an illegal option was found
*/
public static boolean getFlag(final char flag, final String[] options) throws Exception {
return getFlag("" + flag, options);
}
/**
* Checks if the given array contains the flag "-String". Stops searching at
* the first marker "--". If the flag is found, it is replaced with the empty
* string.
*
* @param flag the String indicating the flag.
* @param options the array of strings containing all the options.
* @return true if the flag was found
* @exception Exception if an illegal option was found
*/
public static boolean getFlag(final String flag, final String[] options) throws Exception {
int pos = getOptionPos(flag, options);
if (pos > -1) {
options[pos] = "";
}
return (pos > -1);
}
/**
* Gets an option indicated by a flag "-Char" from the given array of strings.
* Stops searching at the first marker "--". Replaces flag and option with
* empty strings.
*
* @param flag the character indicating the option.
* @param options the array of strings containing all the options.
* @return the indicated option or an empty string
* @exception Exception if the option indicated by the flag can't be found
*/
public static/* @non_null@ */String getOption(final char flag, final String[] options) throws Exception {
return getOption("" + flag, options);
}
/**
* Gets an option indicated by a flag "-String" from the given array of
* strings. Stops searching at the first marker "--". Replaces flag and option
* with empty strings.
*
* @param flag the String indicating the option.
* @param options the array of strings containing all the options.
* @return the indicated option or an empty string
* @exception Exception if the option indicated by the flag can't be found
*/
public static/* @non_null@ */String getOption(final String flag, final String[] options) throws Exception {
String newString;
int i = getOptionPos(flag, options);
if (i > -1) {
if (options[i].equals("-" + flag)) {
if (i + 1 == options.length) {
throw new Exception("No value given for -" + flag + " option.");
}
options[i] = "";
newString = new String(options[i + 1]);
options[i + 1] = "";
return newString;
}
if (options[i].charAt(1) == '-') {
return "";
}
}
return "";
}
/**
* Gets the index of an option or flag indicated by a flag "-Char" from the
* given array of strings. Stops searching at the first marker "--".
*
* @param flag the character indicating the option.
* @param options the array of strings containing all the options.
* @return the position if found, or -1 otherwise
*/
public static int getOptionPos(final char flag, final String[] options) {
return getOptionPos("" + flag, options);
}
/**
* Gets the index of an option or flag indicated by a flag "-String" from the
* given array of strings. Stops searching at the first marker "--".
*
* @param flag the String indicating the option.
* @param options the array of strings containing all the options.
* @return the position if found, or -1 otherwise
*/
public static int getOptionPos(final String flag, final String[] options) {
if (options == null) {
return -1;
}
for (int i = 0; i < options.length; i++) {
if ((options[i].length() > 0) && (options[i].charAt(0) == '-')) {
// Check if it is a negative number
try {
Double.valueOf(options[i]);
} catch (NumberFormatException e) {
// found?
if (options[i].equals("-" + flag)) {
return i;
}
// did we reach "--"?
if (options[i].charAt(1) == '-') {
return -1;
}
}
}
}
return -1;
}
/**
* Quotes a string if it contains special characters.
*
* The following rules are applied:
*
* A character is backquoted version of it is one of <tt>" ' % \ \n \r \t</tt>
* .
*
* A string is enclosed within single quotes if a character has been
* backquoted using the previous rule above or contains <tt>{ }</tt> or is
* exactly equal to the strings <tt>, ? space or ""</tt> (empty string).
*
* A quoted question mark distinguishes it from the missing value which is
* represented as an unquoted question mark in arff files.
*
* @param string the string to be quoted
* @return the string (possibly quoted)
* @see #unquote(String)
*/
public static/* @pure@ */String quote(String string) {
boolean quote = false;
// 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 = backQuoteChars(string);
quote = true;
}
// 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 = ("'".concat(string)).concat("'");
}
return string;
}
/**
* unquotes are previously quoted string (but only if necessary), i.e., it
* removes the single quotes around it. Inverse to quote(String).
*
* @param string the string to process
* @return the unquoted string
* @see #quote(String)
*/
public static String unquote(String string) {
if (string.startsWith("'") && string.endsWith("'")) {
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 = unbackQuoteChars(string);
}
}
return string;
}
/**
* Converts carriage returns and new lines in a string into \r and \n.
* Backquotes the following characters: ` " \ \t and %
*
* @param string the string
* @return the converted string
* @see #unbackQuoteChars(String)
*/
public static/* @pure@ */String backQuoteChars(String string) {
int index;
StringBuffer newStringBuffer;
// replace each of the following characters with the backquoted version
char charsFind[] = { '\\', '\'', '\t', '\n', '\r', '"', '%', '\u001E' };
String charsReplace[] = { "\\\\", "\\'", "\\t", "\\n", "\\r", "\\\"", "\\%", "\\u001E" };
for (int i = 0; i < charsFind.length; i++) {
if (string.indexOf(charsFind[i]) != -1) {
newStringBuffer = new StringBuffer();
while ((index = string.indexOf(charsFind[i])) != -1) {
if (index > 0) {
newStringBuffer.append(string.substring(0, index));
}
newStringBuffer.append(charsReplace[i]);
if ((index + 1) < string.length()) {
string = string.substring(index + 1);
} else {
string = "";
}
}
newStringBuffer.append(string);
string = newStringBuffer.toString();
}
}
return string;
}
/**
* Converts carriage returns and new lines in a string into \r and \n.
*
* @param string the string
* @return the converted string
*/
public static String convertNewLines(String string) {
int index;
// Replace with \n
StringBuffer newStringBuffer = new StringBuffer();
while ((index = string.indexOf('\n')) != -1) {
if (index > 0) {
newStringBuffer.append(string.substring(0, index));
}
newStringBuffer.append('\\');
newStringBuffer.append('n');
if ((index + 1) < string.length()) {
string = string.substring(index + 1);
} else {
string = "";
}
}
newStringBuffer.append(string);
string = newStringBuffer.toString();
// Replace with \r
newStringBuffer = new StringBuffer();
while ((index = string.indexOf('\r')) != -1) {
if (index > 0) {
newStringBuffer.append(string.substring(0, index));
}
newStringBuffer.append('\\');
newStringBuffer.append('r');
if ((index + 1) < string.length()) {
string = string.substring(index + 1);
} else {
string = "";
}
}
newStringBuffer.append(string);
return newStringBuffer.toString();
}
/**
* Reverts \r and \n in a string into carriage returns and new lines.
*
* @param string the string
* @return the converted string
*/
public static String revertNewLines(String string) {
int index;
// Replace with \n
StringBuffer newStringBuffer = new StringBuffer();
while ((index = string.indexOf("\\n")) != -1) {
if (index > 0) {
newStringBuffer.append(string.substring(0, index));
}
newStringBuffer.append('\n');
if ((index + 2) < string.length()) {
string = string.substring(index + 2);
} else {
string = "";
}
}
newStringBuffer.append(string);
string = newStringBuffer.toString();
// Replace with \r
newStringBuffer = new StringBuffer();
while ((index = string.indexOf("\\r")) != -1) {
if (index > 0) {
newStringBuffer.append(string.substring(0, index));
}
newStringBuffer.append('\r');
if ((index + 2) < string.length()) {
string = string.substring(index + 2);
} else {
string = "";
}
}
newStringBuffer.append(string);
return newStringBuffer.toString();
}
/**
* Returns the secondary set of options (if any) contained in the supplied
* options array. The secondary set is defined to be any options after the
* first "--". These options are removed from the original options array.
*
* @param options the input array of options
* @return the array of secondary options
*/
public static String[] partitionOptions(final String[] options) {
for (int i = 0; i < options.length; i++) {
if (options[i].equals("--")) {
options[i++] = "";
String[] result = new String[options.length - i];
for (int j = i; j < options.length; j++) {
result[j - i] = options[j];
options[j] = "";
}
return result;
}
}
return new String[0];
}
/**
* The inverse operation of backQuoteChars(). Converts back-quoted carriage
* returns and new lines in a string to the corresponding character ('\r' and
* '\n'). Also "un"-back-quotes the following characters: ` " \ \t and %
*
* @param string the string
* @return the converted string
* @see #backQuoteChars(String)
*/
public static String unbackQuoteChars(final String string) {
int index;
StringBuffer newStringBuffer;
// replace each of the following characters with the backquoted version
String charsFind[] = { "\\\\", "\\'", "\\t", "\\n", "\\r", "\\\"", "\\%", "\\u001E" };
char charsReplace[] = { '\\', '\'', '\t', '\n', '\r', '"', '%', '\u001E' };
int pos[] = new int[charsFind.length];
int curPos;
String str = new String(string);
newStringBuffer = new StringBuffer();
while (str.length() > 0) {
// get positions and closest character to replace
curPos = str.length();
index = -1;
for (int i = 0; i < pos.length; i++) {
pos[i] = str.indexOf(charsFind[i]);
if ((pos[i] > -1) && (pos[i] < curPos)) {
index = i;
curPos = pos[i];
}
}
// replace character if found, otherwise finished
if (index == -1) {
newStringBuffer.append(str);
str = "";
} else {
newStringBuffer.append(str.substring(0, pos[index]));
newStringBuffer.append(charsReplace[index]);
str = str.substring(pos[index] + charsFind[index].length());
}
}
return newStringBuffer.toString();
}
/**
* Split up a string containing options into an array of strings, one for each
* option.
*
* @param quotedOptionString the string containing the options
* @return the array of options
* @throws Exception in case of an unterminated string, unknown character or a
* parse error
*/
public static String[] splitOptions(final String quotedOptionString) throws Exception {
Vector<String> optionsVec = new Vector<String>();
String str = new String(quotedOptionString);
int i;
while (true) {
// trimLeft
i = 0;
while ((i < str.length()) && (Character.isWhitespace(str.charAt(i)))) {
i++;
}
str = str.substring(i);
// stop when str is empty
if (str.length() == 0) {
break;
}
// if str start with a double quote
if (str.charAt(0) == '"') {
// find the first not anti-slached double quote
i = 1;
while (i < str.length()) {
if (str.charAt(i) == str.charAt(0)) {
break;
}
if (str.charAt(i) == '\\') {
i += 1;
if (i >= str.length()) {
throw new Exception("String should not finish with \\");
}
}
i += 1;
}
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);
optStr = unbackQuoteChars(optStr);
optionsVec.addElement(optStr);
str = str.substring(i + 1);
} else {
// find first whiteSpace
i = 0;
while ((i < str.length()) && (!Character.isWhitespace(str.charAt(i)))) {
i++;
}
// add the founded string to the option vector
String optStr = str.substring(0, i);
optionsVec.addElement(optStr);
str = str.substring(i);
}
}
// convert optionsVec to an array of String
String[] options = new String[optionsVec.size()];
for (i = 0; i < optionsVec.size(); i++) {
options[i] = optionsVec.elementAt(i);
}
return options;
}
/**
* Joins all the options in an option array into a single string, as might be
* used on the command line.
*
* @param optionArray the array of options
* @return the string containing all options.
*/
public static String joinOptions(final String[] optionArray) {
String optionString = "";
for (String element : optionArray) {
if (element.equals("")) {
continue;
}
boolean escape = false;
for (int n = 0; n < element.length(); n++) {
if (Character.isWhitespace(element.charAt(n)) || element.charAt(n) == '"' || element.charAt(n) == '\'') {
escape = true;
break;
}
}
if (escape) {
optionString += '"' + backQuoteChars(element) + '"';
} else {
optionString += element;
}
optionString += " ";
}
return optionString.trim();
}
/**
* Creates a new instance of an object given it's class name and (optional)
* arguments to pass to it's setOptions method. If the object implements
* OptionHandler and the options parameter is non-null, the object will have
* it's options set. Example use:
* <p>
*
* <code> <pre>
* String classifierName = Utils.getOption('W', options);
* Classifier c = (Classifier)Utils.forName(Classifier.class,
* classifierName,
* options);
* setClassifier(c);
* </pre></code>
*
* @param classType the class that the instantiated object should be
* assignable to -- an exception is thrown if this is not the case
* @param className the fully qualified class name of the object
* @param options an array of options suitable for passing to setOptions. May
* be null. Any options accepted by the object will be removed from
* the array.
* @return the newly created object, ready for use (if it is an array, it will
* have size zero).
* @exception Exception if the class name is invalid, or if the class is not
* assignable to the desired class type, or the options supplied
* are not acceptable to the object
*/
public static Object forName(final Class<?> classType, final String className, final String[] options) throws Exception {
return ResourceUtils.forName(classType, className, options);
}
/**
* Returns a JFrame with the given title. The JFrame will be placed relative
* to the ancestor window of the given component (or relative to the given component itself, if it is a window),
* and will receive the icon image from that window if the window is a frame.
*
* @param title the title of the window
* @param component the component for which the ancestor window is found
* @return the JFrame
*/
public static JFrame getWekaJFrame(final String title, final Component component) {
JFrame jf = new JFrame(title);
Window windowAncestor = null;
if (component != null) {
if (component instanceof Window) {
windowAncestor = (Window) component;
} else {
windowAncestor = SwingUtilities.getWindowAncestor(component);
}
if (windowAncestor instanceof Frame) {
jf.setIconImage(((Frame) windowAncestor).getIconImage());
}
}
return jf;
}
/**
* Generates a commandline of the given object. If the object is not
* implementing OptionHandler, then it will only return the classname,
* otherwise also the options.
*
* @param obj the object to turn into a commandline
* @return the commandline
*/
public static String toCommandLine(final Object obj) {
StringBuffer result;
result = new StringBuffer();
if (obj != null) {
result.append(obj.getClass().getName());
if (obj instanceof OptionHandler) {
result.append(" " + joinOptions(((OptionHandler) obj).getOptions()));
}
}
return result.toString().trim();
}
/**
* Computes entropy for an array of integers.
*
* @param counts array of counts
* @return - a log2 a - b log2 b - c log2 c + (a+b+c) log2 (a+b+c) when given
* array [a b c]
*/
public static/* @pure@ */double info(final int counts[]) {
int total = 0;
double x = 0;
for (int count : counts) {
x -= xlogx(count);
total += count;
}
return x + xlogx(total);
}
/**
* Tests if a is smaller or equal to b.
*
* @param a a double
* @param b a double
*/
public static/* @pure@ */boolean smOrEq(final double a, final double b) {
return (a - b < SMALL) || (a <= b);
}
/**
* Tests if a is greater or equal to b.
*
* @param a a double
* @param b a double
*/
public static/* @pure@ */boolean grOrEq(final double a, final double b) {
return (b - a < SMALL) || (a >= b);
}
/**
* Tests if a is smaller than b.
*
* @param a a double
* @param b a double
*/
public static/* @pure@ */boolean sm(final double a, final double b) {
return (b - a > SMALL);
}
/**
* Tests if a is greater than b.
*
* @param a a double
* @param b a double
*/
public static/* @pure@ */boolean gr(final double a, final double b) {
return (a - b > SMALL);
}
/**
* Returns the kth-smallest value in the array.
*
* @param array the array of integers
* @param k the value of k
* @return the kth-smallest value
*/
public static int kthSmallestValue(final int[] array, final int k) {
int[] index = initialIndex(array.length);
return array[index[select(array, index, 0, array.length - 1, k)]];
}
/**
* Returns the kth-smallest value in the array
*
* @param array the array of double
* @param k the value of k
* @return the kth-smallest value
* @throws InterruptedException
*/
public static double kthSmallestValue(final double[] array, final int k) throws InterruptedException {
int[] index = initialIndex(array.length);
return array[index[select(array, index, 0, array.length - 1, k)]];
}
/**
* Returns the logarithm of a for base 2.
*
* @param a a double
* @return the logarithm for base 2
*/
public static/* @pure@ */double log2(final double a) {
return Math.log(a) / log2;
}
/**
* Returns index of maximum element in a given array of doubles. First maximum
* is returned.
*
* @param doubles the array of doubles
* @return the index of the maximum element
*/
public static/* @pure@ */int maxIndex(final double[] doubles) {
double maximum = 0;
int maxIndex = 0;
for (int i = 0; i < doubles.length; i++) {
if ((i == 0) || (doubles[i] > maximum)) {
maxIndex = i;
maximum = doubles[i];
}
}
return maxIndex;
}
/**
* Returns index of maximum element in a given array of integers. First
* maximum is returned.
*
* @param ints the array of integers
* @return the index of the maximum element
*/
public static/* @pure@ */int maxIndex(final int[] ints) {
int maximum = 0;
int maxIndex = 0;
for (int i = 0; i < ints.length; i++) {
if ((i == 0) || (ints[i] > maximum)) {
maxIndex = i;
maximum = ints[i];
}
}
return maxIndex;
}
/**
* Computes the mean for an array of doubles.
*
* @param vector the array
* @return the mean
*/
public static/* @pure@ */double mean(final double[] vector) {
double sum = 0;
if (vector.length == 0) {
return 0;
}
for (double element : vector) {
sum += element;
}
return sum / vector.length;
}
/**
* Returns index of minimum element in a given array of integers. First
* minimum is returned.
*
* @param ints the array of integers
* @return the index of the minimum element
*/
public static/* @pure@ */int minIndex(final int[] ints) {
int minimum = 0;
int minIndex = 0;
for (int i = 0; i < ints.length; i++) {
if ((i == 0) || (ints[i] < minimum)) {
minIndex = i;
minimum = ints[i];
}
}
return minIndex;
}
/**
* Returns index of minimum element in a given array of doubles. First minimum
* is returned.
*
* @param doubles the array of doubles
* @return the index of the minimum element
*/
public static/* @pure@ */int minIndex(final double[] doubles) {
double minimum = 0;
int minIndex = 0;
for (int i = 0; i < doubles.length; i++) {
if ((i == 0) || (doubles[i] < minimum)) {
minIndex = i;
minimum = doubles[i];
}
}
return minIndex;
}
/**
* Normalizes the doubles in the array by their sum.
*
* @param doubles the array of double
* @exception IllegalArgumentException if sum is Zero or NaN
*/
public static void normalize(final double[] doubles) {
double sum = 0;
for (double d : doubles) {
sum += d;
}
normalize(doubles, sum);
}
/**
* Normalizes the doubles in the array using the given value.
*
* @param doubles the array of double
* @param sum the value by which the doubles are to be normalized
* @exception IllegalArgumentException if sum is zero or NaN
*/
public static void normalize(final double[] doubles, final double sum) {
if (Double.isNaN(sum)) {
throw new IllegalArgumentException("Can't normalize array. Sum is NaN.");
}
if (sum == 0) {
// Maybe this should just be a return.
throw new IllegalArgumentException("Can't normalize array. Sum is zero.");
}
for (int i = 0; i < doubles.length; i++) {
doubles[i] /= sum;
}
}
/**
* Converts an array containing the natural logarithms of probabilities stored
* in a vector back into probabilities. The probabilities are assumed to sum
* to one.
*
* @param a an array holding the natural logarithms of the probabilities
* @return the converted array
*/
public static double[] logs2probs(final double[] a) {
double max = a[maxIndex(a)];
double sum = 0.0;
double[] result = new double[a.length];
for (int i = 0; i < a.length; i++) {
result[i] = Math.exp(a[i] - max);
sum += result[i];
}
normalize(result, sum);
return result;
}
/**
* Returns the log-odds for a given probabilitiy.
*
* @param prob the probabilitiy
*
* @return the log-odds after the probability has been mapped to [Utils.SMALL,
* 1-Utils.SMALL]
*/
public static/* @pure@ */double probToLogOdds(final double prob) {
if (gr(prob, 1) || (sm(prob, 0))) {
throw new IllegalArgumentException("probToLogOdds: probability must " + "be in [0,1] " + prob);
}
double p = SMALL + (1.0 - 2 * SMALL) * prob;
return Math.log(p / (1 - p));
}
/**
* Rounds a double to the next nearest integer value. The JDK version of it
* doesn't work properly.
*
* @param value the double value
* @return the resulting integer value
*/
public static/* @pure@ */int round(final double value) {
int roundedValue = value > 0 ? (int) (value + 0.5) : -(int) (Math.abs(value) + 0.5);
return roundedValue;
}
/**
* Rounds a double to the next nearest integer value in a probabilistic
* fashion (e.g. 0.8 has a 20% chance of being rounded down to 0 and a 80%
* chance of being rounded up to 1). In the limit, the average of the rounded
* numbers generated by this procedure should converge to the original double.
*
* @param value the double value
* @param rand the random number generator
* @return the resulting integer value
*/
public static int probRound(final double value, final Random rand) {
if (value >= 0) {
double lower = Math.floor(value);
double prob = value - lower;
if (rand.nextDouble() < prob) {
return (int) lower + 1;
} else {
return (int) lower;
}
} else {
double lower = Math.floor(Math.abs(value));
double prob = Math.abs(value) - lower;
if (rand.nextDouble() < prob) {
return -((int) lower + 1);
} else {
return -(int) lower;
}
}
}
/**
* Replaces all "missing values" in the given array of double values with
* MAX_VALUE.
*
* @param array the array to be modified.
*/
public static void replaceMissingWithMAX_VALUE(final double[] array) {
for (int i = 0; i < array.length; i++) {
if (isMissingValue(array[i])) {
array[i] = Double.MAX_VALUE;
}
}
}
/**
* Rounds a double to the given number of decimal places.
*
* @param value the double value
* @param afterDecimalPoint the number of digits after the decimal point
* @return the double rounded to the given precision
*/
public static/* @pure@ */double roundDouble(final double value, final int afterDecimalPoint) {
double mask = Math.pow(10.0, afterDecimalPoint);
return (Math.round(value * mask)) / mask;
}
/**
* Sorts a given array of integers in ascending order and returns an array of
* integers with the positions of the elements of the original array in the
* sorted array. The sort is stable. (Equal elements remain in their original
* order.)
*
* @param array this array is not changed by the method!
* @return an array of integers with the positions in the sorted array.
*/
public static/* @pure@ */int[] sort(final int[] array) {
int[] index = initialIndex(array.length);
int[] newIndex = new int[array.length];
int[] helpIndex;
int numEqual;
quickSort(array, index, 0, array.length - 1);
// Make sort stable
int i = 0;
while (i < index.length) {
numEqual = 1;
for (int j = i + 1; ((j < index.length) && (array[index[i]] == array[index[j]])); j++) {
numEqual++;
}
if (numEqual > 1) {
helpIndex = new int[numEqual];
for (int j = 0; j < numEqual; j++) {
helpIndex[j] = i + j;
}
quickSort(index, helpIndex, 0, numEqual - 1);
for (int j = 0; j < numEqual; j++) {
newIndex[i + j] = index[helpIndex[j]];
}
i += numEqual;
} else {
newIndex[i] = index[i];
i++;
}
}
return newIndex;
}
/**
* Sorts a given array of doubles in ascending order and returns an array of
* integers with the positions of the elements of the original array in the
* sorted array. NOTE THESE CHANGES: the sort is no longer stable and it
* doesn't use safe floating-point comparisons anymore. Occurrences of
* Double.NaN are treated as Double.MAX_VALUE.
*
* @param array this array is not changed by the method!
* @return an array of integers with the positions in the sorted array.
* @throws InterruptedException
*/
public static/* @pure@ */int[] sort(/* @non_null@ */double[] array) throws InterruptedException {
int[] index = initialIndex(array.length);
if (array.length > 1) {
array = array.clone();
replaceMissingWithMAX_VALUE(array);
quickSort(array, index, 0, array.length - 1);
}
return index;
}
/**
* Sorts a given array of doubles in ascending order and returns an array of
* integers with the positions of the elements of the original array in the
* sorted array. Missing values in the given array are replaced by
* Double.MAX_VALUE, so the array is modified in that case!
*
* @param array the array to be sorted, which is modified if it has missing
* values
* @return an array of integers with the positions in the sorted array.
* @throws InterruptedException
*/
public static/* @pure@ */int[] sortWithNoMissingValues(/* @non_null@ */final double[] array) throws InterruptedException {
int[] index = initialIndex(array.length);
if (array.length > 1) {
quickSort(array, index, 0, array.length - 1);
}
return index;
}
/**
* Sorts a given array of doubles in ascending order and returns an array of
* integers with the positions of the elements of the original array in the
* sorted array. The sort is stable (Equal elements remain in their original
* order.) Occurrences of Double.NaN are treated as Double.MAX_VALUE
*
* @param array this array is not changed by the method!
* @return an array of integers with the positions in the sorted array.
* @throws InterruptedException
*/
public static/* @pure@ */int[] stableSort(double[] array) throws InterruptedException {
int[] index = initialIndex(array.length);
if (array.length > 1) {
int[] newIndex = new int[array.length];
int[] helpIndex;
int numEqual;
array = array.clone();
replaceMissingWithMAX_VALUE(array);
quickSort(array, index, 0, array.length - 1);
// Make sort stable
int i = 0;
while (i < index.length) {
numEqual = 1;
for (int j = i + 1; ((j < index.length) && Utils.eq(array[index[i]], array[index[j]])); j++) {
numEqual++;
}
if (numEqual > 1) {
helpIndex = new int[numEqual];
for (int j = 0; j < numEqual; j++) {
helpIndex[j] = i + j;
}
quickSort(index, helpIndex, 0, numEqual - 1);
for (int j = 0; j < numEqual; j++) {
newIndex[i + j] = index[helpIndex[j]];
}
i += numEqual;
} else {
newIndex[i] = index[i];
i++;
}
}
return newIndex;
} else {
return index;
}
}
/**
* Computes the variance for an array of doubles.
*
* @param vector the array
* @return the variance
*/
public static/* @pure@ */double variance(final double[] vector) {
if (vector.length <= 1) {
return Double.NaN;
}
double mean = 0;
double var = 0;
for (int i = 0; i < vector.length; i++) {
double delta = vector[i] - mean;
mean += delta / (i + 1);
var += (vector[i] - mean) * delta;
}
var /= vector.length - 1;
// We don't like negative variance
if (var < 0) {
return 0;
} else {
return var;
}
}
/**
* Computes the sum of the elements of an array of doubles.
*
* @param doubles the array of double
* @return the sum of the elements
*/
public static/* @pure@ */double sum(final double[] doubles) {
double sum = 0;
for (double d : doubles) {
sum += d;
}
return sum;
}
/**
* Computes the sum of the elements of an array of integers.
*
* @param ints the array of integers
* @return the sum of the elements
*/
public static/* @pure@ */int sum(final int[] ints) {
int sum = 0;
for (int j : ints) {
sum += j;
}
return sum;
}
/**
* Returns c*log2(c) for a given integer value c.
*
* @param c an integer value
* @return c*log2(c) (but is careful to return 0 if c is 0)
*/
public static/* @pure@ */double xlogx(final int c) {
if (c == 0) {
return 0.0;
}
return c * Utils.log2(c);
}
/**
* Initial index, filled with values from 0 to size - 1.
*/
private static int[] initialIndex(final int size) {
int[] index = new int[size];
for (int i = 0; i < size; i++) {
index[i] = i;
}
return index;
}
/**
* Sorts left, right, and center elements only, returns resulting center as
* pivot.
*/
private static int sortLeftRightAndCenter(final double[] array, final int[] index, final int l, final int r) {
int c = (l + r) / 2;
conditionalSwap(array, index, l, c);
conditionalSwap(array, index, l, r);
conditionalSwap(array, index, c, r);
return c;
}
/**
* Swaps two elements in the given integer array.
*/
private static void swap(final int[] index, final int l, final int r) {
int help = index[l];
index[l] = index[r];
index[r] = help;
}
/**
* Conditional swap for quick sort.
*/
private static void conditionalSwap(final double[] array, final int[] index, final int left, final int right) {
if (array[index[left]] > array[index[right]]) {
int help = index[left];
index[left] = index[right];
index[right] = help;
}
}
/**
* Partitions the instances around a pivot. Used by quicksort and
* kthSmallestValue.
*
* @param array the array of doubles to be sorted
* @param index the index into the array of doubles
* @param l the first index of the subset
* @param r the last index of the subset
*
* @return the index of the middle element
* @throws InterruptedException
*/
private static int partition(final double[] array, final int[] index, int l, int r, final double pivot) throws InterruptedException {
r--;
while (true) {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
while ((array[index[++l]] < pivot)) {
;
}
while ((array[index[--r]] > pivot)) {
;
}
if (l >= r) {
return l;
}
swap(index, l, r);
}
}
/**
* Partitions the instances around a pivot. Used by quicksort and
* kthSmallestValue.
*
* @param array the array of integers to be sorted
* @param index the index into the array of integers
* @param l the first index of the subset
* @param r the last index of the subset
*
* @return the index of the middle element
*/
private static int partition(final int[] array, final int[] index, int l, int r) {
double pivot = array[index[(l + r) / 2]];
int help;
while (l < r) {
while ((array[index[l]] < pivot) && (l < r)) {
l++;
}
while ((array[index[r]] > pivot) && (l < r)) {
r--;
}
if (l < r) {
help = index[l];
index[l] = index[r];
index[r] = help;
l++;
r--;
}
}
if ((l == r) && (array[index[r]] > pivot)) {
r--;
}
return r;
}
/**
* Implements quicksort with median-of-three method and explicit sort for
* problems of size three or less.
*
* @param array the array of doubles to be sorted
* @param index the index into the array of doubles
* @param left the first index of the subset to be sorted
* @param right the last index of the subset to be sorted
* @throws InterruptedException
*/
// @ requires 0 <= first && first <= right && right < array.length;
// @ requires (\forall int i; 0 <= i && i < index.length; 0 <= index[i] &&
// index[i] < array.length);
// @ requires array != index;
// assignable index;
private static void quickSort(/* @non_null@ */final double[] array, /* @non_null@ */
final int[] index, final int left, final int right) throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException("Killed WEKA!");
}
int diff = right - left;
switch (diff) {
case 0:
// No need to do anything
return;
case 1:
// Swap two elements if necessary
conditionalSwap(array, index, left, right);
return;
case 2:
// Just need to sort three elements
conditionalSwap(array, index, left, left + 1);
conditionalSwap(array, index, left, right);
conditionalSwap(array, index, left + 1, right);
return;
default:
// Establish pivot
int pivotLocation = sortLeftRightAndCenter(array, index, left, right);
// Move pivot to the right, partition, and restore pivot
swap(index, pivotLocation, right - 1);
int center = partition(array, index, left, right, array[index[right - 1]]);
swap(index, center, right - 1);
// Sort recursively
quickSort(array, index, left, center - 1);
quickSort(array, index, center + 1, right);
}
}
/**
* Implements quicksort according to Manber's "Introduction to Algorithms".
*
* @param array the array of integers to be sorted
* @param index the index into the array of integers
* @param left the first index of the subset to be sorted
* @param right the last index of the subset to be sorted
*/
// @ requires 0 <= first && first <= right && right < array.length;
// @ requires (\forall int i; 0 <= i && i < index.length; 0 <= index[i] &&
// index[i] < array.length);
// @ requires array != index;
// assignable index;
private static void quickSort(/* @non_null@ */final int[] array, /* @non_null@ */
final int[] index, final int left, final int right) {
if (left < right) {
int middle = partition(array, index, left, right);
quickSort(array, index, left, middle);
quickSort(array, index, middle + 1, right);
}
}
/**
* Implements computation of the kth-smallest element according to Manber's
* "Introduction to Algorithms".
*
* @param array the array of double
* @param index the index into the array of doubles
* @param left the first index of the subset
* @param right the last index of the subset
* @param k the value of k
*
* @return the index of the kth-smallest element
* @throws InterruptedException
*/
// @ requires 0 <= first && first <= right && right < array.length;
private static int select(/* @non_null@ */final double[] array, /* @non_null@ */
final int[] index, final int left, final int right, final int k) throws InterruptedException {
int diff = right - left;
switch (diff) {
case 0:
// Nothing to be done
return left;
case 1:
// Swap two elements if necessary
conditionalSwap(array, index, left, right);
return left + k - 1;
case 2:
// Just need to sort three elements
conditionalSwap(array, index, left, left + 1);
conditionalSwap(array, index, left, right);
conditionalSwap(array, index, left + 1, right);
return left + k - 1;
default:
// Establish pivot
int pivotLocation = sortLeftRightAndCenter(array, index, left, right);
// Move pivot to the right, partition, and restore pivot
swap(index, pivotLocation, right - 1);
int center = partition(array, index, left, right, array[index[right - 1]]);
swap(index, center, right - 1);
// Proceed recursively
if ((center - left + 1) >= k) {
return select(array, index, left, center, k);
} else {
return select(array, index, center + 1, right, k - (center - left + 1));
}
}
}
/**
* Converts a File's absolute path to a path relative to the user (ie start)
* directory. Includes an additional workaround for Cygwin, which doesn't like
* upper case drive letters.
*
* @param absolute the File to convert to relative path
* @return a File with a path that is relative to the user's directory
* @exception Exception if the path cannot be constructed
*/
public static File convertToRelativePath(final File absolute) throws Exception {
File result;
String fileStr;
result = null;
// if we're running windows, it could be Cygwin
if (File.separator.equals("\\")) {
// Cygwin doesn't like upper case drives -> try lower case drive
try {
fileStr = absolute.getPath();
fileStr = fileStr.substring(0, 1).toLowerCase() + fileStr.substring(1);
result = createRelativePath(new File(fileStr));
} catch (Exception e) {
// no luck with Cygwin workaround, convert it like it is
result = createRelativePath(absolute);
}
} else {
result = createRelativePath(absolute);
}
return result;
}
/**
* Converts a File's absolute path to a path relative to the user (ie start)
* directory.
*
* @param absolute the File to convert to relative path
* @return a File with a path that is relative to the user's directory
* @exception Exception if the path cannot be constructed
*/
protected static File createRelativePath(final File absolute) throws Exception {
File userDir = new File(System.getProperty("user.dir"));
String userPath = userDir.getAbsolutePath() + File.separator;
String targetPath = (new File(absolute.getParent())).getPath() + File.separator;
String fileName = absolute.getName();
StringBuffer relativePath = new StringBuffer();
// relativePath.append("."+File.separator);
// System.err.println("User dir "+userPath);
// System.err.println("Target path "+targetPath);
// file is in user dir (or subdir)
int subdir = targetPath.indexOf(userPath);
if (subdir == 0) {
if (userPath.length() == targetPath.length()) {
relativePath.append(fileName);
} else {
int ll = userPath.length();
relativePath.append(targetPath.substring(ll));
relativePath.append(fileName);
}
} else {
int sepCount = 0;
String temp = new String(userPath);
while (temp.indexOf(File.separator) != -1) {
int ind = temp.indexOf(File.separator);
sepCount++;
temp = temp.substring(ind + 1, temp.length());
}
String targetTemp = new String(targetPath);
String userTemp = new String(userPath);
int tcount = 0;
while (targetTemp.indexOf(File.separator) != -1) {
int ind = targetTemp.indexOf(File.separator);
int ind2 = userTemp.indexOf(File.separator);
String tpart = targetTemp.substring(0, ind + 1);
String upart = userTemp.substring(0, ind2 + 1);
if (tpart.compareTo(upart) != 0) {
if (tcount == 0) {
tcount = -1;
}
break;
}
tcount++;
targetTemp = targetTemp.substring(ind + 1, targetTemp.length());
userTemp = userTemp.substring(ind2 + 1, userTemp.length());
}
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.");
}
if (targetTemp.indexOf(File.separator) == -1) {
targetTemp = "";
}
for (int i = 0; i < sepCount - tcount; i++) {
relativePath.append(".." + File.separator);
}
relativePath.append(targetTemp + fileName);
}
// System.err.println("new path : "+relativePath.toString());
return new File(relativePath.toString());
}
/**
* Implements computation of the kth-smallest element according to Manber's
* "Introduction to Algorithms".
*
* @param array the array of integers
* @param index the index into the array of integers
* @param left the first index of the subset
* @param right the last index of the subset
* @param k the value of k
*
* @return the index of the kth-smallest element
*/
// @ requires 0 <= first && first <= right && right < array.length;
private static int select(/* @non_null@ */final int[] array, /* @non_null@ */
final int[] index, final int left, final int right, final int k) {
if (left == right) {
return left;
} else {
int middle = partition(array, index, left, right);
if ((middle - left + 1) >= k) {
return select(array, index, left, middle, k);
} else {
return select(array, index, middle + 1, right, k - (middle - left + 1));
}
}
}
/**
* For a named dialog, returns true if the user has opted not to view it again
* in the future.
*
* @param dialogName the name of the dialog to check (e.g.
* weka.gui.GUICHooser.HowToFindPackageManager).
* @return true if the user has opted not to view the named dialog in the
* future.
*/
public static boolean getDontShowDialog(final String dialogName) {
File wekaHome = ResourceUtils.getWekaHome();
if (!wekaHome.exists()) {
return false;
}
File dialogSubDir = new File(wekaHome.toString() + File.separator + "systemDialogs");
if (!dialogSubDir.exists()) {
return false;
}
File dialogFile = new File(dialogSubDir.toString() + File.separator + dialogName);
return dialogFile.exists();
}
/**
* Specify that the named dialog is not to be displayed in the future.
*
* @param dialogName the name of the dialog not to show again (e.g.
* weka.gui.GUIChooser.HowToFindPackageManager).
* @throws Exception if the marker file that is used to indicate that a named
* dialog is not to be shown can't be created. This file lives in
* $WEKA_HOME/systemDialogs
*/
public static void setDontShowDialog(final String dialogName) throws Exception {
File wekaHome = ResourceUtils.getWekaHome();
if (!wekaHome.exists()) {
return;
}
File dialogSubDir = new File(wekaHome.toString() + File.separator + "systemDialogs");
if (!dialogSubDir.exists()) {
if (!dialogSubDir.mkdir()) {
return;
}
}
File dialogFile = new File(dialogSubDir.toString() + File.separator + dialogName);
dialogFile.createNewFile();
}
/**
* For a named dialog, if the user has opted not to view it again, returns the
* answer the answer the user supplied when they closed the dialog. Returns
* null if the user did opt to view the dialog again.
*
* @param dialogName the name of the dialog to check (e.g.
* weka.gui.GUICHooser.HowToFindPackageManager).
* @return the answer the user supplied the last time they viewed the named
* dialog (if they opted not to view it again in the future) or null
* if the user opted to view the dialog again in the future.
*/
public static String getDontShowDialogResponse(final String dialogName) throws Exception {
if (!getDontShowDialog(dialogName)) {
return null; // This must be the first time - no file recorded yet.
}
File wekaHome = ResourceUtils.getWekaHome();
File dialogSubDir = new File(wekaHome.toString() + File.separator + "systemDialogs" + File.separator + dialogName);
BufferedReader br = new BufferedReader(new FileReader(dialogSubDir));
String response = br.readLine();
br.close();
return response;
}
/**
* Specify that the named dialog is not to be shown again in the future. Also
* records the answer that the user chose when closing the dialog.
*
* @param dialogName the name of the dialog to no longer display
* @param response the user selected response when they closed the dialog
* @throws Exception if there is a problem saving the information
*/
public static void setDontShowDialogResponse(final String dialogName, final String response) throws Exception {
File wekaHome = ResourceUtils.getWekaHome();
if (!wekaHome.exists()) {
return;
}
File dialogSubDir = new File(wekaHome.toString() + File.separator + "systemDialogs");
if (!dialogSubDir.exists()) {
if (!dialogSubDir.mkdir()) {
return;
}
}
File dialogFile = new File(dialogSubDir.toString() + File.separator + dialogName);
BufferedWriter br = new BufferedWriter(new FileWriter(dialogFile));
br.write(response + "\n");
br.flush();
br.close();
}
/**
* Breaks up the string, if wider than "columns" characters.
*
* @param s the string to process
* @param columns the width in columns
* @return the processed string
*/
public static String[] breakUp(final String s, final int columns) {
Vector<String> result;
String line;
BreakIterator boundary;
int boundaryStart;
int boundaryEnd;
String word;
String punctuation;
int i;
String[] lines;
result = new Vector<String>();
punctuation = " .,;:!?'\"";
lines = s.split("\n");
for (i = 0; i < lines.length; i++) {
boundary = BreakIterator.getWordInstance();
boundary.setText(lines[i]);
boundaryStart = boundary.first();
boundaryEnd = boundary.next();
line = "";
while (boundaryEnd != BreakIterator.DONE) {
word = lines[i].substring(boundaryStart, boundaryEnd);
if (line.length() >= columns) {
if (word.length() == 1) {
if (punctuation.indexOf(word.charAt(0)) > -1) {
line += word;
word = "";
}
}
result.add(line);
line = "";
}
line += word;
boundaryStart = boundaryEnd;
boundaryEnd = boundary.next();
}
if (line.length() > 0) {
result.add(line);
}
}
return result.toArray(new String[result.size()]);
}
/**
* 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(final Object object, final 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 = CapabilitiesUtils.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 = CapabilitiesUtils.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(final String input, final 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 a configured Range object given a 1-based range index string (such
* as 1-20,35,last) or a comma-separated list of attribute names.
*
* @param instanceInfo the header of the instances to configure the range for
* @param rangeString a string containing a range of attribute indexes, or a
* comma-separated list of attribute names
* @return a Range object configured to cover the supplied rangeString
* @throws Exception if a problem occured
*/
public static Range configureRangeFromRangeStringOrAttributeNameList(final Instances instanceInfo, final String rangeString) throws Exception {
Range result = new Range(rangeString);
try {
result.setUpper(instanceInfo.numAttributes() - 1);
} catch (IllegalArgumentException e) {
// now try as a list of named attributes
String[] parts = rangeString.split(",");
if (parts.length == 0) {
throw new Exception("Must specify a list of attributes to configure the range object " + "with!");
}
StringBuilder indexList = new StringBuilder();
for (String att : parts) {
att = att.trim();
Attribute a = instanceInfo.attribute(att);
if (a == null) {
throw new Exception("I can't find the requested attribute '" + att + "' in the supplied instances information.");
}
indexList.append(a.index() + 1).append(",");
}
if (indexList.length() > 0) {
indexList.setLength(indexList.length() - 1);
}
result = new Range(indexList.toString());
result.setUpper(instanceInfo.numAttributes() - 1);
}
return result;
}
/**
* Takes a sample based on the given array of weights based on Walker's method.
* Returns an array of the same size that gives the frequency of each item in the sample.
* For Walker's method, see pp. 232 of "Stochastic Simulation" by B.D. Ripley (1987).
*
* @param weights the (positive) weights to be used to determine sample probabilities by normalization
* @param random the random number generator to be used
*
* @return the histogram of items in the sample
*/
public static int[] takeSample(final double[] weights, final Random random) {
// Walker's method, see pp. 232 of "Stochastic Simulation" by B.D. Ripley
double[] P = new double[weights.length];
System.arraycopy(weights, 0, P, 0, weights.length);
Utils.normalize(P);
double[] Q = new double[weights.length];
int[] A = new int[weights.length];
int[] W = new int[weights.length];
int M = weights.length;
int NN = -1;
int NP = M;
for (int I = 0; I < M; I++) {
if (P[I] < 0) {
throw new IllegalArgumentException("Weights have to be positive.");
}
Q[I] = M * P[I];
if (Q[I] < 1.0) {
W[++NN] = I;
} else {
W[--NP] = I;
}
}
if (NN > -1 && NP < M) {
for (int S = 0; S < M - 1; S++) {
int I = W[S];
int J = W[NP];
A[I] = J;
Q[J] += Q[I] - 1.0;
if (Q[J] < 1.0) {
NP++;
}
if (NP >= M) {
break;
}
}
// A[W[M]] = W[M];
}
for (int I = 0; I < M; I++) {
Q[I] += I;
}
int[] result = new int[weights.length];
for (int i = 0; i < weights.length; i++) {
int ALRV;
double U = M * random.nextDouble();
int I = (int) U;
if (U < Q[I]) {
ALRV = I;
} else {
ALRV = A[I];
}
result[ALRV]++;
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param ops some dummy options
*/
public static void main(final String[] ops) {
double[] doublesWithNaN = { 4.5, 6.7, Double.NaN, 3.4, 4.8, 1.2, 3.4 };
double[] doubles = { 4.5, 6.7, 6.7, 3.4, 4.8, 1.2, 3.4, 6.7, 6.7, 3.4 };
int[] ints = { 12, 6, 2, 18, 16, 6, 7, 5, 18, 18, 17 };
try {
// Option handling
System.out.println("First option split up:");
if (ops.length > 0) {
String[] firstOptionSplitUp = Utils.splitOptions(ops[0]);
for (String element : firstOptionSplitUp) {
System.out.println(element);
}
}
System.out.println("Partitioned options: ");
String[] partitionedOptions = Utils.partitionOptions(ops);
for (String partitionedOption : partitionedOptions) {
System.out.println(partitionedOption);
}
System.out.println("Get position of flag -f: " + 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));
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 (double element : doublesWithNaN) {
System.out.print(element + " ");
}
System.out.println();
System.out.println("Original array (doubles): ");
for (double d : doubles) {
System.out.print(d + " ");
}
System.out.println();
System.out.println("Original array (ints): ");
for (int j : ints) {
System.out.print(j + " ");
}
System.out.println();
System.out.println("Correlation: " + 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));
System.out.println("Sum (ints): " + Utils.sum(ints));
System.out.println("Max index (doubles): " + Utils.maxIndex(doubles));
System.out.println("Max index (ints): " + Utils.maxIndex(ints));
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));
System.out.println("Median (ints): " + Utils.kthSmallestValue(ints, ints.length / 2));
// Sorting and normalizing
System.out.println("Sorted array with NaN (doubles): ");
int[] sorted = Utils.sort(doublesWithNaN);
for (int i = 0; i < doublesWithNaN.length; i++) {
System.out.print(doublesWithNaN[sorted[i]] + " ");
}
System.out.println();
System.out.println("Sorted array (doubles): ");
sorted = Utils.sort(doubles);
for (int i = 0; i < doubles.length; i++) {
System.out.print(doubles[sorted[i]] + " ");
}
System.out.println();
System.out.println("Sorted array (ints): ");
sorted = Utils.sort(ints);
for (int i = 0; i < ints.length; i++) {
System.out.print(ints[sorted[i]] + " ");
}
System.out.println();
System.out.println("Indices from stable sort (doubles): ");
sorted = Utils.stableSort(doubles);
for (int i = 0; i < doubles.length; i++) {
System.out.print(sorted[i] + " ");
}
System.out.println();
System.out.println("Indices from sort (ints): ");
sorted = Utils.sort(ints);
for (int i = 0; i < ints.length; i++) {
System.out.print(sorted[i] + " ");
}
System.out.println();
System.out.println("Normalized array (doubles): ");
Utils.normalize(doubles);
for (double d : doubles) {
System.out.print(d + " ");
}
System.out.println();
System.out.println("Normalized again (doubles): ");
Utils.normalize(doubles, Utils.sum(doubles));
for (double d : doubles) {
System.out.print(d + " ");
}
System.out.println();
// Pretty-printing
System.out.println("-4.58: " + Utils.doubleToString(-4.57826535, 2));
System.out.println("-6.78: " + Utils.doubleToString(-6.78214234, 6, 2));
// Comparisons
System.out.println("5.70001 == 5.7 ? " + Utils.eq(5.70001, 5.7));
System.out.println("5.70001 > 5.7 ? " + Utils.gr(5.70001, 5.7));
System.out.println("5.70001 >= 5.7 ? " + Utils.grOrEq(5.70001, 5.7));
System.out.println("5.7 < 5.70001 ? " + Utils.sm(5.7, 5.70001));
System.out.println("5.7 <= 5.70001 ? " + Utils.smOrEq(5.7, 5.70001));
// Math
System.out.println("Info (ints): " + Utils.info(ints));
System.out.println("log2(4.6): " + Utils.log2(4.6));
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));
// Arrays
System.out.println("Array-Dimensions of '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 } }));
String[][][] s = new String[3][4][];
System.out.println("Array-Dimensions of 'new String[3][4][]': " + Utils.getArrayDimensions(s));
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/Version.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Version.java
* Copyright (C) 2005-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
/**
* This class contains the version number of the current WEKA release and some
* methods for comparing another version string. The normal layout of a version
* string is "MAJOR.MINOR.REVISION", but it can also handle partial version
* strings, e.g. "3.4". <br/>
* Should be used e.g. in exports to XML for keeping track, with which version
* of WEKA the file was produced.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class Version implements Comparable<String>, RevisionHandler {
/** the version file */
public final static String VERSION_FILE = "weka/core/version.txt";
/** the major version */
public static int MAJOR = 3;
/** the minor version */
public static int MINOR = 4;
/** the revision */
public static int REVISION = 3;
/** point revision */
public static int POINT = 0;
/** True if snapshot */
public static boolean SNAPSHOT = false;
protected static final String SNAPSHOT_STRING = "-SNAPSHOT";
static {
try {
InputStream inR = (new Version()).getClass().getClassLoader()
.getResourceAsStream(VERSION_FILE);
// InputStream inR = ClassLoader.getSystemResourceAsStream(VERSION_FILE);
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(inR));
String line = lnr.readLine();
int[] maj = new int[1];
int[] min = new int[1];
int[] rev = new int[1];
int[] point = new int[1];
SNAPSHOT = parseVersion(line, maj, min, rev, point);
MAJOR = maj[0];
MINOR = min[0];
REVISION = rev[0];
POINT = point[0];
lnr.close();
} catch (Exception e) {
System.err.println(Version.class.getName()
+ ": Unable to load version information!");
}
}
/** the complete version */
public static String VERSION = MAJOR + "." + MINOR + "." + REVISION
+ (POINT > 0 ? "." + POINT : "") + (SNAPSHOT ? SNAPSHOT_STRING : "");
/**
* parses the version and stores the result in the arrays
*
* @param version the version string to parse (contains "-" instead of "."!)
* @param maj the major version
* @param min the minor version
* @param rev the revision version
*/
private static boolean parseVersion(String version, int[] maj, int[] min,
int[] rev, int[] point) {
int major = 0;
int minor = 0;
int revision = 0;
int pnt = 0;
boolean isSnapshot = false;
try {
String tmpStr = version;
if (tmpStr.toLowerCase().endsWith("-snapshot")) {
tmpStr = tmpStr.substring(0, tmpStr.toLowerCase().indexOf("-snapshot"));
isSnapshot = true;
}
tmpStr = tmpStr.replace('-', '.');
if (tmpStr.indexOf(".") > -1) {
major = Integer.parseInt(tmpStr.substring(0, tmpStr.indexOf(".")));
tmpStr = tmpStr.substring(tmpStr.indexOf(".") + 1);
if (tmpStr.indexOf(".") > -1) {
minor = Integer.parseInt(tmpStr.substring(0, tmpStr.indexOf(".")));
tmpStr = tmpStr.substring(tmpStr.indexOf(".") + 1);
if (tmpStr.indexOf(".") > 0) {
revision = Integer
.parseInt(tmpStr.substring(0, tmpStr.indexOf(".")));
tmpStr = tmpStr.substring(tmpStr.indexOf(".") + 1);
if (!tmpStr.equals("")) {
pnt = Integer.parseInt(tmpStr);
} else {
pnt = 0;
}
} else {
if (!tmpStr.equals("")) {
revision = Integer.parseInt(tmpStr);
} else {
revision = 0;
}
}
} else {
if (!tmpStr.equals("")) {
minor = Integer.parseInt(tmpStr);
} else {
minor = 0;
}
}
} else {
if (!tmpStr.equals("")) {
major = Integer.parseInt(tmpStr);
} else {
major = 0;
}
}
} catch (Exception e) {
e.printStackTrace();
major = -1;
minor = -1;
revision = -1;
} finally {
maj[0] = major;
min[0] = minor;
rev[0] = revision;
point[0] = pnt;
}
return isSnapshot;
}
/**
* checks the version of this class against the given version-string
*
* @param o the version-string to compare with
* @return -1 if this version is less, 0 if equal and +1 if greater than the
* provided version
*/
@Override
public int compareTo(String o) {
int result;
int major;
int minor;
int revision;
int pnt;
int[] maj = new int[1];
int[] min = new int[1];
int[] rev = new int[1];
int[] point = new int[1];
// do we have a string?
parseVersion(o, maj, min, rev, point);
major = maj[0];
minor = min[0];
revision = rev[0];
pnt = point[0];
if (MAJOR < major) {
result = -1;
} else if (MAJOR == major) {
if (MINOR < minor) {
result = -1;
} else if (MINOR == minor) {
if (REVISION < revision) {
result = -1;
} else if (REVISION == revision) {
if (POINT < pnt) {
result = -1;
} else if (POINT == pnt) {
result = 0;
} else {
result = 1;
}
} else {
result = 1;
}
} else {
result = 1;
}
} else {
result = 1;
}
return result;
}
/**
* whether the given version string is equal to this version
*
* @param o the version-string to compare to
* @return TRUE if the version-string is equals to its own
*/
@Override
public boolean equals(Object o) {
return (compareTo((String) o) == 0);
}
/**
* checks whether this version is older than the one from the given version
* string
*
* @param o the version-string to compare with
* @return TRUE if this version is older than the given one
*/
public boolean isOlder(String o) {
return (compareTo(o) == -1);
}
/**
* checks whether this version is newer than the one from the given version
* string
*
* @param o the version-string to compare with
* @return TRUE if this version is newer than the given one
*/
public boolean isNewer(String o) {
return (compareTo(o) == 1);
}
/**
* returns the current version as string
*
* @return the current version
*/
@Override
public String toString() {
return VERSION;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* only for testing
*
* @param args the commandline arguments - ignored
*/
public static void main(String[] args) {
Version v;
String tmpStr;
// print version
System.out.println(VERSION + "\n");
// test on different versions
v = new Version();
System.out.println("-1? " + v.compareTo("5.0.1"));
System.out.println(" 0? " + v.compareTo(VERSION));
System.out.println("+1? " + v.compareTo("3.4.0"));
tmpStr = "5.0.1";
System.out.println("\ncomparing with " + tmpStr);
System.out.println("isOlder? " + v.isOlder(tmpStr));
System.out.println("equals ? " + v.equals(tmpStr));
System.out.println("isNewer? " + v.isNewer(tmpStr));
tmpStr = VERSION;
System.out.println("\ncomparing with " + tmpStr);
System.out.println("isOlder? " + v.isOlder(tmpStr));
System.out.println("equals ? " + v.equals(tmpStr));
System.out.println("isNewer? " + v.isNewer(tmpStr));
tmpStr = "3.4.0";
System.out.println("\ncomparing with " + tmpStr);
System.out.println("isOlder? " + v.isOlder(tmpStr));
System.out.println("equals ? " + v.equals(tmpStr));
System.out.println("isNewer? " + v.isNewer(tmpStr));
tmpStr = "3.4";
System.out.println("\ncomparing with " + tmpStr);
System.out.println("isOlder? " + v.isOlder(tmpStr));
System.out.println("equals ? " + v.equals(tmpStr));
System.out.println("isNewer? " + v.isNewer(tmpStr));
tmpStr = "5";
System.out.println("\ncomparing with " + tmpStr);
System.out.println("isOlder? " + v.isOlder(tmpStr));
System.out.println("equals ? " + v.equals(tmpStr));
System.out.println("isNewer? " + v.isNewer(tmpStr));
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/WeightedAttributesHandler.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* WeightedAttributesHandler.java
* Copyright (C) 2017 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Interface to something that makes use of the information provided
* by attribute weights.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision: 8034 $
*/
public interface WeightedAttributesHandler {
// Nothing in here, because the class is just used as an indicator
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/WeightedInstancesHandler.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* WeightedInstancesHandler.java
* Copyright (C) 1999-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Interface to something that makes use of the information provided
* by instance weights.
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @version $Revision$
*/
public interface WeightedInstancesHandler {
// Nothing in here, because the class is just used as an indicator
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/WekaEnumeration.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* WekaEnumeration.java
* Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.util.Enumeration;
import java.util.List;
/**
* Class for enumerating an array list's elements.
*/
public class WekaEnumeration<E> implements Enumeration<E>, RevisionHandler {
/** The counter. */
private int m_Counter;
// These JML commands say how m_Counter implements Enumeration
// @ in moreElements;
// @ private represents moreElements = m_Counter < m_Vector.size();
// @ private invariant 0 <= m_Counter && m_Counter <= m_Vector.size();
/** The vector. */
private final/* @non_null@ */List<E> m_Vector;
/** Special element. Skipped during enumeration. */
private final int m_SpecialElement;
// @ private invariant -1 <= m_SpecialElement;
// @ private invariant m_SpecialElement < m_Vector.size();
// @ private invariant m_SpecialElement>=0 ==> m_Counter!=m_SpecialElement;
/**
* Constructs an enumeration.
*
* @param vector the vector which is to be enumerated
*/
public WekaEnumeration(/* @non_null@ */List<E> vector) {
m_Counter = 0;
m_Vector = vector;
m_SpecialElement = -1;
}
/**
* Constructs an enumeration with a special element. The special element is
* skipped during the enumeration.
*
* @param vector the vector which is to be enumerated
* @param special the index of the special element
*/
// @ requires 0 <= special && special < vector.size();
public WekaEnumeration(/* @non_null@ */List<E> vector, int special) {
m_Vector = vector;
m_SpecialElement = special;
if (special == 0) {
m_Counter = 1;
} else {
m_Counter = 0;
}
}
/**
* Tests if there are any more elements to enumerate.
*
* @return true if there are some elements left
*/
@Override
public final/* @pure@ */boolean hasMoreElements() {
if (m_Counter < m_Vector.size()) {
return true;
}
return false;
}
/**
* Returns the next element.
*
* @return the next element to be enumerated
*/
// @ also requires hasMoreElements();
@Override
public final E nextElement() {
E result = m_Vector.get(m_Counter);
m_Counter++;
if (m_Counter == m_SpecialElement) {
m_Counter++;
}
return result;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/WekaException.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* WekaException.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
/**
* Class for Weka-specific exceptions.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public class WekaException
extends Exception {
/** for serialization */
private static final long serialVersionUID = 6428269989006208585L;
/**
* Creates a new WekaException with no message.
*
*/
public WekaException() {
super();
}
/**
* Creates a new WekaException.
*
* @param message the reason for raising an exception.
*/
public WekaException(String message) {
super(message);
}
/**
* Constructor with message and cause
*
* @param message the message for the exception
* @param cause the root cause Throwable
*/
public WekaException(String message, Throwable cause) {
this(message);
initCause(cause);
fillInStackTrace();
}
/**
* Constructor with cause argument
*
* @param cause the root cause Throwable
*/
public WekaException(Throwable cause) {
this(cause.getMessage(), cause);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/WekaPackageClassLoaderManager.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* WekaPackageClassLoaderManager.java
* Copyright (C) 2016 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Class that manages classloaders from individual Weka plugin packages.
* Maintains a collection of {@code WekaPackageLibIsolatingClassLoader}s - one
* for each package. {@code Utils.forName()} and {@code weka.Run} use this
* classloader to find/instantiate schemes exposed in top-level package jar
* files. Client code in a package should do the same, unless directly referring
* to classes in other packages, in which case the other packages should be
* explicit dependencies. This classloader will not find classes in third-party
* libraries inside a package's lib directory.<br>
* <br>
* Classes are searched for first in the parent classloader and then in the
* top-level package jar files.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: $
* @see WekaPackageLibIsolatingClassLoader
*/
public class WekaPackageClassLoaderManager {
protected static final WekaPackageClassLoaderManager s_singletonLoader =
new WekaPackageClassLoaderManager();
/** Map of package classloaders keyed by package name */
protected Map<String, WekaPackageLibIsolatingClassLoader> m_packageJarClassLoaders =
new HashMap<>();
/**
* Lookup for classloaders keyed by class names from top-level package jar
* files
*/
protected Map<String, WekaPackageLibIsolatingClassLoader> m_classBasedClassLoaderLookup =
new HashMap<>();
/** Path to the weka.jar file on the classpath */
protected File m_pathToWekaJarFile;
private WekaPackageClassLoaderManager() {
}
/**
* Injects the MTJ core classes into the root classloader. This is so that
* they are visible to the MTJ native library loader (if a MTJ native package
* is installed).
*/
protected void injectMTJCoreClasses() {
if (!WekaPackageClassLoaderManager
.classExists("com.github.fommil.netlib.ARPACK")) {
// inject core MTJ classes into the root classloader
String debugS =
System.getProperty("weka.core.classloader.debug", "false");
boolean debug = debugS.equalsIgnoreCase("true");
InputStream mtjCoreInputStream =
getClass().getClassLoader().getResourceAsStream("core.jar");
InputStream arpackAllInputStream =
getClass().getClassLoader().getResourceAsStream(
"arpack_combined.jar");
InputStream mtjInputStream =
getClass().getClassLoader().getResourceAsStream("mtj.jar");
if (mtjCoreInputStream != null && arpackAllInputStream != null
&& mtjInputStream != null) {
if (debug) {
System.out.println("[WekaPackageClassLoaderManager] injecting "
+ "mtj-related core classes into root classloader");
}
try {
if (debug) {
System.out
.println("[WekaPackageClassLoaderManager] Injecting arpack");
}
injectAllClassesInFromStream(arpackAllInputStream);
if (debug) {
System.out.println("[WekaPackageClassLoaderManager] Injecting mtj "
+ "core");
}
injectAllClassesInFromStream(mtjCoreInputStream);
if (debug) {
System.out.println("[WekaPackageClassLoaderManager] Injecting mtj");
}
injectAllClassesInFromStream(mtjInputStream);
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
System.out.println("WARNING: core mtj jar files are not available as "
+ "resources to this classloader ("
+ WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.getClass().getClassLoader() + ")");
}
}
}
/**
* Gets the singleton instance of the WekaPackageClassLoaderManager
*
* @return the singleton instance of hte WekaPackageClassLoaderManager
*/
public static WekaPackageClassLoaderManager
getWekaPackageClassLoaderManager() {
return s_singletonLoader;
}
/**
* Return an instantiated instance of the supplied class name. This method
* will attempt to find a package that owns the named class first, before
* falling back on the current and then parent class loader. Use this method
* instead of Class.forName().newInstance().
*
* @param className the name of the class to get an instance of
* @return an instantiated object
* @throws Exception if the class cannot be found, or a problem occurs during
* instantiation
*/
public static Object objectForName(String className) throws Exception {
return forName(className).newInstance();
}
/**
* Return the class object for the supplied class name. This method will
* attempt to find a package that owns the named class first, before falling
* back on the current, and then parent, class loader. Use this method instead
* of Class.forName().
*
* @param className the name of hte class to get an instance of
* @return a class object
* @throws ClassNotFoundException if the named class cannot be found.
*/
public static Class<?> forName(String className)
throws ClassNotFoundException {
return forName(className, true);
}
/**
* Return the class object for the supplied class name. This method will
* attempt to find a package that owns the named class first, before falling
* back on the current, and then parent, class loader. Use this method instead
* of Class.forName().
*
* @param className the name of hte class to get an instance of
* @param initialize true if the class should be initialized
* @return a class object
* @throws ClassNotFoundException if the named class cannot be found.
*/
public static Class<?> forName(String className, boolean initialize)
throws ClassNotFoundException {
WekaPackageClassLoaderManager cl =
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager();
ClassLoader toUse = cl.getLoaderForClass(className);
return Class.forName(className, initialize, toUse);
}
/**
* Return the path to the weka.jar file (if found) on the classpath.
*
* @return the path to the weka.jar file on the classpath, or null if no
* weka.jar file was found.
*/
public File getPathToWekaJarFile() {
return m_pathToWekaJarFile;
}
/**
* Get the entries in the Weka class loader (i.e. the class loader that loads
* the core weka classes) as an array of URLs. This is primarily used by
* Weka's dynamic class discovery mechanism, so that all Weka schemes on the
* classpath can be discovered. If the Weka class loader is an instance of
* URLClassLoader then the URLs encapsulated within are returned. Otherwise,
* if the system class loader is the classloader that loads Weka then the
* entries from java.class.path are returned. Failing that, we assume that
* Weka and any other supporting classes (not including packages) can be found
* in the WEKA_CLASSPATH environment variable. This latter case can be used to
* handle the situation where the weka.jar is loaded by a custom
* (non-URLClassLoader) withn an app server (for example).
*
* @return an array of URLs containing the entries available to the
* classloader that loads the core weka classes
*/
public URL[] getWekaClassloaderClasspathEntries() {
ClassLoader parent = getClass().getClassLoader();
// easy case
if (parent instanceof URLClassLoader) {
URL[] result = ((URLClassLoader) parent).getURLs();
// scan for weka.jar
for (URL u : result) {
if (u.toString().endsWith("weka.jar")) {
try {
m_pathToWekaJarFile = new File(u.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
return result;
}
// otherwise, see if we've been loaded by the system classloader
if (ClassLoader.getSystemClassLoader().equals(getClass().getClassLoader())) {
// we can process the java.class.path property for weka core stuff
return getSystemClasspathEntries();
} else {
// have to have the WEKA_CLASSPATH property set
return getWekaClasspathEntries();
}
}
/**
* Get a set of all classes contained in all top-level jar files from Weka
* packages. These classes are globally visible across all packages.
*
* @return a set of all classes in all top-level package jar files
*/
public Set<String> getPackageJarFileClasses() {
return m_classBasedClassLoaderLookup.keySet();
}
/**
* Returns a list of URLs made up from the entries available in the
* java.class.path property. This will contain the weka.jar (or directory
* containing weka classes) if Weka is launched as an application. It won't
* contain Weka if weka is loaded by a child classloader (in an app server or
* similar). In this case, if the child classloader is a URLClassLoader then
* the original class discovery mechanism will work; if not, then the
* WEKA_CLASSPATH environment variable will need to be set to point to the
* location of the weka.jar file on the file system.
*
* @return an array of URLs containing the entries in the java.class.path
* property
*/
private URL[] getSystemClasspathEntries() {
String cp = System.getProperty("java.class.path", "");
String sep = System.getProperty("path.separator", ":");
return getParts(cp, sep);
}
/**
* Returns entries from the WEKA_CLASSPATH property (if set).
*
* @return an array of URLs, one for each part of the WEKA_CLASSPATH
*/
private URL[] getWekaClasspathEntries() {
String wekaCp =
Environment.getSystemWide().getVariableValue("WEKA_CLASSPATH");
// assume the system separator is being used
String sep = System.getProperty("path.separator", ":");
if (wekaCp != null) {
return getParts(wekaCp, sep);
}
return new URL[0];
}
/**
* Splits a supplied string classpath and returns an array of URLs
* representing the entries.
*
* @param cp the classpath to process
* @param sep the path separator
* @return an array of URLs
*/
private URL[] getParts(String cp, String sep) {
String[] cpParts = cp.split(sep);
List<URL> uList = new ArrayList<>();
for (String part : cpParts) {
try {
URL url;
if (part.startsWith("file:")) {
part = part.replace(" ", "%20");
url = new URI(part).toURL();
} else {
url = new File(part).toURI().toURL();
uList.add(url);
}
if (part.endsWith("weka.jar")) {
m_pathToWekaJarFile = new File(url.toURI());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
return uList.toArray(new URL[uList.size()]);
}
/**
* Removes the named package classloader from those managed by this class.
* Attempts to close the classloader and remove any file locks (under Windows)
* that it might be holding
*
* @param packageName the name of the package to remove the classloader for
*/
public synchronized void removeClassLoaderForPackage(String packageName) {
WekaPackageLibIsolatingClassLoader loader =
m_packageJarClassLoaders.get(packageName);
if (loader != null) {
loader.closeClassLoader();
m_packageJarClassLoaders.remove(packageName);
}
}
/**
* Create a class loader for the given package directory
*
* @param packageDir the directory of a Weka package to create a class loader
* for
* @preturn the newly created class loader
* @throws Exception if a problem occurs
*/
public synchronized ClassLoader addPackageToClassLoader(File packageDir)
throws Exception {
if (m_packageJarClassLoaders.containsKey(packageDir.getName())) {
m_packageJarClassLoaders.get(packageDir.getName()).closeClassLoader();
}
WekaPackageLibIsolatingClassLoader packageLoader =
new WekaPackageLibIsolatingClassLoader(this, packageDir);
m_packageJarClassLoaders.put(packageDir.getName(), packageLoader);
Set<String> classes = packageLoader.getPackageJarEntries();
for (String c : classes) {
m_classBasedClassLoaderLookup.put(c, packageLoader);
}
return packageLoader;
}
/**
* Attempts to locate a classloader for the named class. Tries the Weka
* classloader and globally visible package classes first. Note that this also
* finds classes that are contained in a package's lib directory. General code
* should not be looking directly for such third-party classes. Instead, if
* they require third-party classes they should reference them directly (and
* compile against the libraries in question), and then either include the
* third party libraries in their own lib directory or declare a dependency on
* the package that contains them.
*
* This method is used by Weka's deserialization routines (in
* SerializationHelper and SerializedObject) that need to locate classes
* (including third-party library ones) that might have been serialized when
* saving a learning scheme.
*
* @param className the name of the class to locate a classloader for
* @return a classloader
*/
public ClassLoader getLoaderForClass(String className) {
className = className.replace("[L", "").replace("[", "").replace(";", "");
// try the Weka classloader and globally visible package classes first
ClassLoader result = getClass().getClassLoader();
try {
Class<?> cl = findClass(className);
return cl.getClassLoader();
} catch (Exception ex) {
}
result = m_classBasedClassLoaderLookup.get(className);
if (result == null) {
result = getClass().getClassLoader();
}
return result;
}
/**
* Get the classloader for the named package
*
* @param packageName the name of the package to get the classloader for
* @return the package's classloader, or null if the package is not known (or
* perhaps was not loaded for some reason)
*/
public WekaPackageLibIsolatingClassLoader getPackageClassLoader(
String packageName) {
return m_packageJarClassLoaders.get(packageName);
}
/**
* Attempts to find the named class. Tries the Weka classloader first (for
* core Weka classes and general Java classes) and then tries package
* classloaders (with respect to the globally visible classes contained in
* their top-level jar files). Note that this method will not find classes
* contained in third-party libraries that reside in lib directories).
*
* @param name the name of the class to find
* @return the class object
* @throws ClassNotFoundException if the named class cannot be found
*/
protected Class<?> findClass(String name) throws ClassNotFoundException {
Class<?> result = null;
// try the Weka classloader first (for general java stuff and core Weka
// stuff)
try {
// result = super.findClass(name);
result = getClass().getClassLoader().loadClass(name);
} catch (ClassNotFoundException e) {
// ignore
}
if (result == null) {
// now ask the package top-level classloaders
for (Map.Entry<String, WekaPackageLibIsolatingClassLoader> e : m_packageJarClassLoaders
.entrySet()) {
result = e.getValue().findGloballyVisiblePackageClass(name);
if (result != null) {
break;
}
}
}
if (result == null) {
throw new ClassNotFoundException("Unable to find class '" + name + "'");
}
return result;
}
/**
* Find a named resource. This searches the Weka classloader and all package
* classloaders. Note that it will only find resources contained in a
* package's top-level jar file(s).
*
* @param name the name of the resource to find
* @return a URL to the resource, or null if the resource could not be located
*/
public URL findResource(String name) {
URL result = null;
// TODO might want to allow package resources to override parent classpath
// ones?
// try the parent classloader first (for general java stuff and core Weka)
// result = super.findResource(name);
result = getClass().getClassLoader().getResource(name);
if (result == null) {
// now ask the package top-level classloaders
for (Map.Entry<String, WekaPackageLibIsolatingClassLoader> e : m_packageJarClassLoaders
.entrySet()) {
result = e.getValue().findGloballyVisiblePackageResource(name);
if (result != null) {
break;
}
}
}
return result;
}
/**
* Get the classloader that covers the jar that contains the named resource.
* Note that this considers the Weka classloader and package classloaders
* (with respect to resources contained in their top-level jar file(s))
*
* @param name the name of the resource to get the owning classloader for
* @return the classloader that "owns" the resource
*/
public ClassLoader findClassloaderForResource(String name) {
ClassLoader result = null;
if (getClass().getClassLoader().getResource(name) != null) {
result = getClass().getClassLoader();
} else {
// now ask the package top-level classloaders
for (Map.Entry<String, WekaPackageLibIsolatingClassLoader> e : m_packageJarClassLoaders
.entrySet()) {
if (e.getValue().findGloballyVisiblePackageResource(name) != null) {
result = e.getValue();
}
}
}
return result;
}
/**
* Find a named resource. This searches the Weka classloader and all package
* classloaders. Note that it will only find resources contained in a
* package's top-level jar file(s).
*
* @param name the name of the resource to find
* @return an enumeration of URLs to the resource, or null if the resource
* could not be located
*/
public Enumeration<URL> findResources(String name) throws IOException {
Enumeration<URL> result = null;
// TODO might want to allow package resources to override parent classpath
// ones?
try {
// result = super.findResources(name);
result = getClass().getClassLoader().getResources(name);
} catch (IOException ex) {
// just ignore
}
if (result == null) {
for (Map.Entry<String, WekaPackageLibIsolatingClassLoader> e : m_packageJarClassLoaders
.entrySet()) {
try {
result = e.getValue().findGloballyVisiblePackageResources(name);
if (result != null) {
break;
}
} catch (IOException ex) {
// ignore
}
}
}
return result;
}
/**
* Try to find a class from the classloader for the named package. Note that
* this will traverse transitive package dependencies
*
* @param packageName the name of the package to check for the class
* @param className the name of the class to search for
* @return the named class or null if the class could not be found
*/
protected Class<?> findClass(String packageName, String className) {
Class<?> result = null;
WekaPackageLibIsolatingClassLoader toTry =
getPackageClassLoader(packageName);
if (toTry != null) {
try {
// System.err.println("Looking for " + className + " in classloader: " +
// toTry.toString());
result = toTry.findClass(className);
} catch (ClassNotFoundException ex) {
// ignore here
}
}
return result;
}
/**
* Try to find a resource from the classloader for the named package. Note
* that this will traverse transitive package dependencies
*
* @param packageName the name of the package to check for the resource
* @param name the name of the resource to search for
* @return a URL to the resource, or null if the resource could not be found
*/
protected URL findResource(String packageName, String name) {
URL result = null;
WekaPackageLibIsolatingClassLoader toTry =
getPackageClassLoader(packageName);
if (toTry != null) {
result = toTry.getResource(name);
}
return result;
}
/**
* Try to find a resource from the classloader for the named package. Note
* that this will traverse transitive package dependencies
*
* @param packageName the name of the package to check for the resource
* @param name the name of the resource to search for
* @return an enumeration of URLs to the resource, or null if the resource
* could not be found
*/
protected Enumeration<URL> findResources(String packageName, String name) {
Enumeration<URL> result = null;
WekaPackageLibIsolatingClassLoader toTry =
getPackageClassLoader(packageName);
if (toTry != null) {
try {
result = toTry.getResources(name);
} catch (IOException ex) {
// ignore here
}
}
return result;
}
/**
* Check to see if the named class exists in this classloader
*
* @param className the name of the class to check for
* @return true if the class exists in this classloader
*/
protected static boolean classExists(String className) {
boolean result = false;
try {
Class<?> cls = Class.forName(className);
result = true;
} catch (ClassNotFoundException e) {
// ignore - means class is not visible/available here
}
return result;
}
/**
* Inject all classes in the supplied jar file into the parent or root
* classloader
*
* @param jarPath the path to the jar in question
* @param injectToRootClassLoader true to inject right up to the root
* @throws Exception if a problem occurs
*/
protected static void injectAllClassesInJar(File jarPath,
boolean injectToRootClassLoader) throws Exception {
injectClasses(jarPath, null, null, injectToRootClassLoader);
}
/**
* Inject all classes in the supplied jar file into the root classloader
*
* @param jarPath the path to the jar in question
* @throws Exception if a problem occurs
*/
protected static void injectAllClassesInJar(File jarPath) throws Exception {
injectAllClassesInJar(jarPath, true);
}
/**
* Inject all classes from the supplied input stream into the root
* classloader. Assumes that the zip entries can be read from the input stream
* (i.e. a jar/zip file is the target)
*
* @param inStream the input stream to process
* @throws Exception if a problem occurs
*/
protected static void injectAllClassesInFromStream(InputStream inStream)
throws Exception {
injectClasses(new BufferedInputStream(inStream), null, null, true);
}
/**
* Inject classes from the supplied jar file into the Weka or root
* classloader.
*
* @param jarPath the path to the jar file to process
* @param classJarPaths an optional list of paths to classes in the jar file
* to inject (if null then all classes in the jar file are injected)
* @param classes an optional list of fully qualified class names. This should
* correspond to the paths in classJarPaths, but contain just the
* class name along with slashes replaced by "." and the .class
* extension removed.
* @param injectToRootClassLoader true if the classes are to be injected into
* the root classloader rather than the Weka classloader
* @throws Exception if a problem occurs
*/
protected static void injectClasses(File jarPath, List<String> classJarPaths,
List<String> classes, boolean injectToRootClassLoader) throws Exception {
if (!jarPath.exists()) {
System.err.println("Path for jar file to inject '" + jarPath.toString()
+ "' does not seem to exist - skipping");
return;
}
InputStream inStream = new FileInputStream(jarPath);
injectClasses(inStream, classJarPaths, classes, injectToRootClassLoader);
}
/**
* Inject classes from the supplied stream into the Weka or root classloader.
*
* @param jarStream input stream to process. Is expected that jar/zip entries
* can be read from the stream
* @param classJarPaths an optional list of paths to classes in the jar file
* to inject (if null then all classes in the jar file are injected)
* @param classes an optional list of fully qualified class names. This should
* correspond to the paths in classJarPaths, but contain just the
* class name along with slashes replaced by "." and the .class
* extension removed.
* @param injectToRootClassLoader true if the classes are to be injected into
* the root classloader rather than the Weka classloader
* @throws Exception if a problem occurs
*/
protected static void injectClasses(InputStream jarStream,
List<String> classJarPaths, List<String> classes,
boolean injectToRootClassLoader) throws Exception {
String debugS = System.getProperty("weka.core.classloader.debug", "false");
boolean debug = debugS.equalsIgnoreCase("true");
boolean processAllClasses = classes == null || classJarPaths == null;
if (processAllClasses) {
classes = new ArrayList<>();
classJarPaths = new ArrayList<>();
}
List<byte[]> preloadClassByteCode = new ArrayList<>();
ZipInputStream zi = new ZipInputStream(jarStream);
ZipEntry zipEntry = null;
while ((zipEntry = zi.getNextEntry()) != null) {
if (!zipEntry.isDirectory() && zipEntry.getName().endsWith(".class")) {
String zipPart = zipEntry.getName().replace("\\", "/");
if (classJarPaths.contains(zipPart) || processAllClasses) {
preloadClassByteCode.add(getByteCode(zi, false));
zi.closeEntry(); // move to next entry in zip
if (processAllClasses) {
classes.add(zipEntry.getName().replace(".class", "")
.replace("\\", "/").replace("/", "."));
}
}
}
}
zi.close();
List<byte[]> okBytes = new ArrayList<>();
List<String> okClasses = new ArrayList<>();
for (int i = 0; i < classes.size(); i++) {
if (!classExists(classes.get(i))) {
okClasses.add(classes.get(i));
okBytes.add(preloadClassByteCode.get(i));
}
}
preloadClassByteCode = okBytes;
classes = okClasses;
if (preloadClassByteCode.size() > 0) {
ClassLoader rootClassloader =
injectToRootClassLoader ? getRootClassLoader()
: getWekaLevelClassloader();
Class<?> classLoader = Class.forName("java.lang.ClassLoader");
Method defineClass =
classLoader.getDeclaredMethod("defineClass", String.class,
byte[].class, int.class, int.class, ProtectionDomain.class);
ProtectionDomain pd = System.class.getProtectionDomain();
// ClassLoader.defineClass is a protected method, so we have to make it
// accessible
defineClass.setAccessible(true);
List<byte[]> failedToInject = new ArrayList<>();
List<String> classesF = new ArrayList<>();
boolean cont = true;
int numLeft = classes.size();
try {
do {
if (debug) {
System.out
.println("[WekaPackageClassLoaderManager] Injecting classes "
+ "into the "
+ (injectToRootClassLoader ? "root classloader..."
: "weka-level classloader..."));
}
for (int i = 0; i < classes.size(); i++) {
if (debug) {
System.out.println("** Injecting " + classes.get(i));
}
byte[] b = preloadClassByteCode.get(i);
try {
defineClass.invoke(rootClassloader, classes.get(i), b, 0,
b.length, pd);
} catch (Exception ex) {
failedToInject.add(b);
classesF.add(classes.get(i));
}
}
cont = failedToInject.size() < numLeft;
preloadClassByteCode = failedToInject;
classes = classesF;
numLeft = failedToInject.size();
failedToInject = new ArrayList<>();
classesF = new ArrayList<>();
} while (classes.size() > 0 && cont);
} finally {
defineClass.setAccessible(false);
}
}
}
private static byte[] getByteCode(InputStream in) throws IOException {
return getByteCode(in, true);
}
private static byte[] getByteCode(InputStream in, boolean closeInput)
throws IOException {
byte[] buf = new byte[1024];
ByteArrayOutputStream byteCodeBuf = new ByteArrayOutputStream();
for (int readLength; (readLength = in.read(buf)) != -1;) {
byteCodeBuf.write(buf, 0, readLength);
}
if (closeInput) {
in.close();
}
return byteCodeBuf.toByteArray();
}
private static ClassLoader getRootClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
while (cl.getParent() != null) {
// System.err.println("Getting parent classloader....");
cl = cl.getParent();
}
return cl;
}
private static ClassLoader getWekaLevelClassloader() {
return weka.core.Version.class.getClassLoader();
}
/**
* Checks each classloader to make sure that their dependencies are available
* (i.e. a classloader for each dependency is present). This method is called
* by WekaPackageManager after loading all packages, but before dynamic class
* discovery is invoked. This takes care of any issues that might arise from
* the user toggling the load status of a package, or perhaps manually
* installing packages that preclude one another, which might make one or more
* dependencies unavailable
*/
protected void performIntegrityCheck() {
List<String> problems = new ArrayList<>();
for (Map.Entry<String, WekaPackageLibIsolatingClassLoader> e : m_packageJarClassLoaders
.entrySet()) {
String packageName = e.getKey();
WekaPackageLibIsolatingClassLoader child = e.getValue();
try {
if (!child.integrityCheck()) {
problems.add(packageName);
}
} catch (Exception ex) {
problems.add(packageName);
}
}
List<String> classKeys = new ArrayList<>();
for (String p : problems) {
System.err.println("[Weka] Integrity: removing classloader for: " + p);
// remove from lookups
m_packageJarClassLoaders.remove(p);
for (Map.Entry<String, WekaPackageLibIsolatingClassLoader> e : m_classBasedClassLoaderLookup
.entrySet()) {
if (e.getValue().getPackageName().equals(p)) {
classKeys.add(e.getKey());
}
}
for (String k : classKeys) {
m_classBasedClassLoaderLookup.remove(k);
}
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/WekaPackageLibIsolatingClassLoader.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* WekaPackageLibIsolatingClassLoader.java
* Copyright (C) 2016 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core;
import weka.core.packageManagement.Dependency;
import weka.core.packageManagement.Package;
import weka.core.packageManagement.PackageConstraint;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.ProtectionDomain;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import static weka.core.WekaPackageManager.DO_NOT_LOAD_IF_CLASS_NOT_PRESENT_KEY;
import static weka.core.WekaPackageManager.DO_NOT_LOAD_IF_ENV_VAR_NOT_SET_KEY;
import static weka.core.WekaPackageManager.DO_NOT_LOAD_IF_ENV_VAR_NOT_SET_MESSAGE_KEY;
import static weka.core.WekaPackageManager.DO_NOT_LOAD_IF_FILE_NOT_PRESENT_KEY;
import static weka.core.WekaPackageManager.DO_NOT_LOAD_IF_FILE_NOT_PRESENT_MESSAGE_KEY;
/**
* <p>
* A ClassLoader that loads/finds classes from one Weka plugin package. This
* includes the top-level jar file(s) and third-party libraries in the package's
* lib directory. First checks the parent classloader (typically application
* classloader) - covers general stuff and weka core classes. Next tries the
* package jar files and third-party libs covered by this classloader/package.
* Next tries packages this one depends on and their third-party libs - this is
* transitive. Finally tries all top-level package jar files over all packages.
* </p>
*
* <p>
* The basic assumption for Weka packages is that classes present in top-level
* jar package jar files contain Weka-related code (schemes, filters, GUI
* panels, tools, etc.), that is visible to all other packages via Weka's
* dynamic class discovery mechanism. A top-level jar file should not contain
* any third-party library code. If package A needs to compile against (and
* explicitly reference) classes provided by package B (either top-level jar or
* third-party library), then it should declare a dependency on package B.
* </p>
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision: $
*/
public class WekaPackageLibIsolatingClassLoader extends URLClassLoader {
/** The name of the package that this classloader loads classes from */
protected String m_packageName = "";
/** A reference to the classloader manager */
protected WekaPackageClassLoaderManager m_classloaderRepo;
/** Classes in the top-level jar file(s) */
protected Set<String> m_packageJarEntries = new HashSet<>();
/** Resources in the top-level jar file(s) */
protected Set<String> m_packageJarResources = new HashSet<>();
/** Classes in the lib jar file(s) */
protected Set<String> m_libJarEntries = new HashSet<>();
/** True to output debugging info */
protected boolean m_debug;
/** Which packages this one depends on */
protected Set<String> m_packageDependencies = new HashSet<>();
/**
* Constructor
*
* @param repo a reference to the classloader manager
* @param packageDir the package directory for the package covered by this
* classloader
* @throws Exception if a problem occurs
*/
public WekaPackageLibIsolatingClassLoader(WekaPackageClassLoaderManager repo,
File packageDir) throws Exception {
// we don't allow any URLs prior to processing the package
super(new URL[0]);
String debug = System.getProperty("weka.core.classloader.debug", "false");
m_debug = debug.equalsIgnoreCase("true");
m_classloaderRepo = repo;
init(packageDir);
}
/**
* Initializes the classloader from the package directory. Checks for, and
* processes, any native libraries and loaders specified in the
* Description.props file; Assembles a list of packages that this one depends
* on; processes top-level jar files and third party libraries in the lib
* directory.
*
* @param packageDir the home directory for the package
* @throws Exception if a problem occurs
*/
protected void init(File packageDir) throws Exception {
m_packageName = packageDir.getName();
Package toLoad = WekaPackageManager.getInstalledPackageInfo(m_packageName);
// Process any native libs before anything else!
List<String> jarsToBeIgnoredWhenLoadingClasses =
checkForNativeLibs(toLoad, packageDir);
List<Dependency> deps = toLoad.getDependencies();
for (Dependency d : deps) {
PackageConstraint target = d.getTarget();
m_packageDependencies.add(target.getPackage().getName());
}
if (m_debug) {
System.out.println("WekaPackageLibIsolatingClassLoader for: "
+ m_packageName);
System.out.print("\tDependencies:");
for (String dep : m_packageDependencies) {
System.out.print(" " + dep);
}
System.out.println();
}
processDir(packageDir, jarsToBeIgnoredWhenLoadingClasses, true);
if (m_debug) {
System.out.println("\nPackage jar(s) classes:");
for (String c : m_packageJarEntries) {
System.out.println("\t" + c);
}
System.out.println("\nPackage jar(s) resources:");
for (String r : m_packageJarResources) {
System.out.println("\t" + r);
}
System.out.println("\nLib jar(s) classes:");
for (String c : m_libJarEntries) {
System.out.println("\t" + c);
}
}
}
/**
* Add a package dependency to this classloader
*
* @param packageName the name of the package to add as a dependency
*/
protected void addPackageDependency(String packageName) {
m_packageDependencies.add(packageName);
}
/**
* Gets a list of class loaders for the packages that this one depends on
*
* @return a list of class loaders for the packages that this one depends on
*/
public List<WekaPackageLibIsolatingClassLoader> getPackageClassLoadersForDependencies() {
List<WekaPackageLibIsolatingClassLoader> result = new ArrayList<>();
for (String d : m_packageDependencies) {
result.add(m_classloaderRepo.getPackageClassLoader(d));
}
return result;
}
/**
* Checks for native libraries and any native library loader classes, as
* specified by the presence of "NativeLibs" and "InjectLoader" entries in the
* package's Description.props file respectively. Native libraries are copied
* to $WEKA_HOME/native (if not already present therein). Classes specified by
* "InjectLoader" are injected into the root classloader.
*
* @param toLoad the package object for the this package
* @param packageDir the home directory of the package
* @return a list of jar files that should be ignored by this classloader when
* loading classes (i.e. all jar files specified in the "InjectLoader"
* entry)
*/
protected List<String> checkForNativeLibs(Package toLoad, File packageDir) {
List<String> jarsForClassloaderToIgnore = new ArrayList<>();
if (toLoad.getPackageMetaDataElement("NativeLibs") != null) {
String nativeLibs =
toLoad.getPackageMetaDataElement("NativeLibs").toString();
if (nativeLibs.length() > 0) {
String[] jarsWithLibs = nativeLibs.split(";");
for (String entry : jarsWithLibs) {
String[] jarAndEntries = entry.split(":");
if (jarAndEntries.length != 2) {
System.err
.println("Was expecting two entries for native lib spec - "
+ "jar:comma-separated lib paths");
continue;
}
String jarPath = jarAndEntries[0].trim();
String[] libPathsInJar = jarAndEntries[1].split(",");
List<String> libsToInstall = new ArrayList<>();
// look at named libs and check if they are already in
// $WEKA_HOME/native-libs - don't extract a second time, but DO
// add entries to java.library.path
for (String lib : libPathsInJar) {
String libName = lib.trim().replace("\\", "/");
if (!nativeLibInstalled(libName.substring(
libName.lastIndexOf("/") + 1, libName.length()))) {
libsToInstall.add(libName.substring(libName.lastIndexOf("/") + 1,
libName.length()));
}
}
if (libsToInstall.size() > 0) {
try {
installNativeLibs(packageDir, jarPath, libsToInstall);
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* if (libsToAddToPath.size() > 0) {
* addNativeLibsToLibsProp(libsToAddToPath); }
*/
}
}
}
// now check to see if there is a native loader to inject into the
// root class loader
if (toLoad.getPackageMetaDataElement("InjectLoader") != null) {
String injectDetails =
toLoad.getPackageMetaDataElement("InjectLoader").toString();
String[] entries = injectDetails.split(";");
for (String entry : entries) {
String jarPath = entry.trim();
boolean rootClassLoader = false;
if (jarPath.startsWith("root|")) {
jarPath = jarPath.replace("root|", "");
rootClassLoader = true;
}
String ignoreJar = jarPath.replace("\\", "/");
ignoreJar = ignoreJar.substring(ignoreJar.lastIndexOf("/") + 1);
jarsForClassloaderToIgnore.add(ignoreJar);
try {
WekaPackageClassLoaderManager.injectAllClassesInJar(new File(
packageDir.toString() + File.separator + jarPath.trim()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
return jarsForClassloaderToIgnore;
}
private static byte[] getByteCode(InputStream in) throws IOException {
byte[] buf = new byte[1024];
ByteArrayOutputStream byteCodeBuf = new ByteArrayOutputStream();
for (int readLength; (readLength = in.read(buf)) != -1;) {
byteCodeBuf.write(buf, 0, readLength);
}
in.close();
return byteCodeBuf.toByteArray();
}
/**
* Installs any native libraries in the specified jar to $WEKA_HOME/native, if
* not already present therein.
*
* @param packageDir the home directory of this package
* @param libJar the path to the jar that contains the libs (relative to the
* package home directory)
* @param libJarPaths paths to libraries to install within the jar
* @throws IOException if a problem occurs
*/
protected void installNativeLibs(File packageDir, String libJar,
List<String> libJarPaths) throws IOException {
File libJarFile =
new File(packageDir.toString() + File.separator + libJar.trim());
if (!libJarFile.exists()) {
System.err.println("Native lib jar file '" + libJarFile.toString()
+ "' does " + "not seem to exist - skipping");
return;
}
ZipFile libZip = new ZipFile(libJarFile);
Enumeration enumeration = libZip.entries();
List<String> libNames = new ArrayList<>();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
if (!zipEntry.isDirectory()) {
String lastPart = zipEntry.getName().replace("\\", "/");
lastPart = lastPart.substring(lastPart.lastIndexOf("/") + 1);
if (libJarPaths.contains(lastPart)) {
// check to see if it is already installed
File installPath =
new File(WekaPackageManager.NATIVE_LIBS_DIR, lastPart);
if (!installPath.exists()) {
InputStream inS =
new BufferedInputStream(libZip.getInputStream(zipEntry));
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(installPath));
try {
copyStreams(inS, bos);
} finally {
inS.close();
bos.flush();
bos.close();
}
}
libNames.add(lastPart);
}
}
if (libNames.size() == libJarPaths.size()) {
break;
}
}
libZip.close();
}
private static void copyStreams(InputStream input, OutputStream output)
throws IOException {
int count;
byte data[] = new byte[1024];
while ((count = input.read(data, 0, 1024)) != -1) {
output.write(data, 0, count);
}
}
/**
* Returns true if a named native library is already present in
* $WEKA_HOME/native
*
* @param libName the name of the library to check
* @return true if the library is already present in $WEKA_HOME/native
*/
protected boolean nativeLibInstalled(String libName) {
boolean result = false;
File[] contents = WekaPackageManager.NATIVE_LIBS_DIR.listFiles();
if (contents != null) {
for (File f : contents) {
if (f.getName().equals(libName)) {
result = true;
break;
}
}
}
return result;
}
/**
* Process jar files in a directory of this package. Jar files at the
* top-level and those in the lib directory are added to this URLClassLoader's
* list, unless specified in the list of jars to ignore.
*
* @param dir the directory to process
* @param jarsToIgnore a list of jar files to ignore
* @param topLevel true if this is the top-level (home) directory of the
* package
* @throws MalformedURLException if a problem occurs
*/
protected void processDir(File dir, List<String> jarsToIgnore,
boolean topLevel) throws MalformedURLException {
File[] contents = dir.listFiles();
if (contents != null) {
for (File content : contents) {
if (content.isFile()
&& content.getPath().toLowerCase().endsWith(".jar")) {
if (jarsToIgnore.contains(content.getName())) {
continue;
}
URL url = content.toURI().toURL();
addURL(url);
if (topLevel) {
// m_packageJarURLs.add(url);
storeJarContents(content, m_packageJarEntries, true);
if (m_debug) {
System.out.println("Package jar: " + content.getName());
}
} else {
if (m_debug) {
System.out.println("Lib jar: " + content.toString());
}
storeJarContents(content, m_libJarEntries, false);
}
} else if (content.isDirectory()
&& content.getName().equalsIgnoreCase("lib")) {
processDir(content, jarsToIgnore, false);
}
}
}
}
/**
* Stores all the names of all classes in the supplied jar file in the
* supplied set. Non-class, non-directory entries in jar files at the
* top-level of the package are stored as resources in a separate lookup set.
*
* @param jarFile jar file to process
* @param repo a set to store class names in
* @param isTopLevelPackageJar true if this jar file is at the top-level of
* the package.
*/
protected void storeJarContents(File jarFile, Set<String> repo,
boolean isTopLevelPackageJar) {
if (jarFile.exists()) {
try {
JarFile jar = new JarFile(jarFile);
Enumeration<JarEntry> enm = jar.entries();
while (enm.hasMoreElements()) {
JarEntry entry = enm.nextElement();
if (entry.getName().endsWith(".class")) {
String cleanedUp = ClassCache.cleanUp(entry.getName());
repo.add(cleanedUp);
} else if (!entry.isDirectory()
&& !entry.getName().contains("META-INF") && isTopLevelPackageJar) {
String resource = entry.getName();
resource = resource.replace("\\", "/");
m_packageJarResources.add(entry.getName());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Find a class using this package classloader. First checks the parent
* classloader (typically application classloader) - covers general stuff and
* weka core classes. Next tries the package jar files and third-party libs
* covered by this classloader. Next tries packages this one depends on and
* their third-party libs - this is transitive. Finally tries all top-level
* package jar files over all packages.
*
* @param name the name of the class to find
* @return the class
* @throws ClassNotFoundException if the class cannot be found
*/
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
// check to see if it has already been loaded/cached first
Class<?> result = findLoadedClass(name);
if (result == null) {
try {
result = super.findClass(name);
} catch (ClassNotFoundException ex) {
// try dependencies (NOTE that this also processes transitive
// dependencies)
for (String packageName : m_packageDependencies) {
result = m_classloaderRepo.findClass(packageName, name);
if (result != null) {
break;
}
}
}
}
if (result == null) {
// try only top-level jars of all other known packages
try {
result = m_classloaderRepo.findClass(name);
} catch (ClassNotFoundException ex) {
//
}
}
if (result == null) {
throw new ClassNotFoundException("[" + toString()
+ "] Unable to find class: " + name);
}
return result;
}
/**
* Find a named resource. First checks parent classloader and stuff covered by
* this classloader. Next tries packages that this one depends on.
*
* @param name the name of the resource to look for
* @return the URL of the resource, or null if the resource is not found
*/
@Override
public URL getResource(String name) {
URL result = super.getResource(name);
if (result == null) {
for (String packageName : m_packageDependencies) {
result = m_classloaderRepo.findResource(packageName, name);
if (result != null) {
break;
}
}
}
if (result == null) {
// Using SomeObject.getClass().getClassLoader is not the same as
// SomeClass.class.getClassLoader()
if (m_debug) {
System.out.println("Trying parent classloader ("
+ m_classloaderRepo.getClass().getClassLoader() + ") for resource '"
+ name + "'");
}
result = m_classloaderRepo.getClass().getClassLoader().getResource(name);
if (result == null && m_debug) {
System.out.println("Failed...");
}
}
if (m_debug) {
System.out.println(m_packageName + " classloader searching for resource "
+ name + (result != null ? " - found" : " - not found"));
}
return result;
}
/**
* Find an enumeration of resources matching the supplied name. First checks
* parent classloader and stuff covered by this classloader. Next tries
* packages that this one depends on.
*
* @param name the name to look for
* @return an enumeration of URLs
* @throws IOException if a problem occurs
*/
@Override
public Enumeration<URL> getResources(String name) throws IOException {
Enumeration<URL> result = null;
java.util.ServiceLoader l;
result = super.getResources(name);
if (result == null || !result.hasMoreElements()) {
for (String packageName : m_packageDependencies) {
result = m_classloaderRepo.findResources(packageName, name);
if (result != null && result.hasMoreElements()) {
break;
}
}
}
if (result == null || !result.hasMoreElements()) {
if (m_debug) {
System.out.println("Trying parent classloader ("
+ m_classloaderRepo.getClass().getClassLoader() + ") for resources '"
+ name + "'");
}
result = m_classloaderRepo.getClass().getClassLoader().getResources(name);
if ((result == null || !result.hasMoreElements()) && m_debug) {
System.out.println("Failed...");
}
}
if (m_debug) {
System.out.println(m_packageName
+ " classloader searching for resources " + name
+ (result != null ? " - found" : " - not found"));
}
return result;
}
/**
* Returns true if this classloader is covering the named third-party class
*
* @param className the third-party classname to check for
* @return true if this classloader is covering the named third-party class
*/
public boolean hasThirdPartyClass(String className) {
return m_libJarEntries.contains(className);
}
/**
* Returns a Class object if this classloader covers the named globally
* visible class (i.e. its top-level jar(s) contain the class), or null
* otherwise.
*
* @param name the name of the class to check for
* @return the Class or null.
*/
protected Class<?> findGloballyVisiblePackageClass(String name) {
Class<?> result = null;
// check only entries in top-level package jar files
if (classExistsInPackageJarFiles(name)) {
try {
// check to see if it has already been loaded/cached first
result = findLoadedClass(name);
if (result == null) {
result = super.findClass(name);
}
} catch (ClassNotFoundException e) {
// ignore here
}
}
return result;
}
/**
* Returns a URL a resource if this classloader covers the named globally
* visible resource (i.e. its top-level jar(s) contain the resource), or null
* otherwise
*
* @param name the path to the resource
* @return a URL to the resource, or null if not covered by this package.
*/
protected URL findGloballyVisiblePackageResource(String name) {
URL result = null;
if (resourceExistsInPackageJarFiles(name)) {
result = super.findResource(name);
}
return result;
}
/**
* return an enumeration of URLS if this classloader covers the named globally
* visible resource, or null otherwise.
*
* @param name the path of the resource to check for
* @return an enumeration of URLs, or null
* @throws IOException if a problem occurs
*/
protected Enumeration<URL> findGloballyVisiblePackageResources(String name)
throws IOException {
Enumeration<URL> result = null;
if (resourceExistsInPackageJarFiles(name)) {
result = super.findResources(name);
}
return result;
}
private static Object getFieldObject(Class<?> clazz, String name, Object obj)
throws Exception {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field.get(obj);
}
/**
* Try to clear classloader file locks under Windows
*/
protected void closeClassLoader() {
try {
super.close();
} catch (Exception ex) {
System.err.println("Failed to close class loader.");
ex.printStackTrace();
}
HashSet<String> closedFiles = new HashSet<String>();
try {
Object obj = getFieldObject(URLClassLoader.class, "ucp", this);
ArrayList<?> loaders =
(ArrayList<?>) getFieldObject(obj.getClass(), "loaders", obj);
for (Object ldr : loaders) {
try {
JarFile file = (JarFile) getFieldObject(ldr.getClass(), "jar", ldr);
closedFiles.add(file.getName());
file.close();
} catch (Exception e) {
// skip
}
}
} catch (Exception e) {
// skip
}
try {
Vector<?> nativeLibArr =
(Vector<?>) getFieldObject(ClassLoader.class, "nativeLibraries", this);
for (Object lib : nativeLibArr) {
try {
Method fMethod =
lib.getClass().getDeclaredMethod("finalize", new Class<?>[0]);
fMethod.setAccessible(true);
fMethod.invoke(lib, new Object[0]);
} catch (Exception e) {
// skip
}
}
} catch (Exception e) {
// skip
}
HashMap<?, ?> uCache = null;
HashMap<?, ?> fCache = null;
try {
Class<?> jarUrlConnClass = null;
try {
ClassLoader contextClassLoader =
Thread.currentThread().getContextClassLoader();
jarUrlConnClass =
contextClassLoader
.loadClass("sun.net.www.protocol.jar.JarURLConnection");
} catch (Throwable skip) {
// skip
}
if (jarUrlConnClass == null) {
jarUrlConnClass =
Class.forName("sun.net.www.protocol.jar.JarURLConnection");
}
Class<?> factory =
getFieldObject(jarUrlConnClass, "factory", null).getClass();
try {
fCache = (HashMap<?, ?>) getFieldObject(factory, "fileCache", null);
} catch (Exception e) {
// skip
}
try {
uCache = (HashMap<?, ?>) getFieldObject(factory, "urlCache", null);
} catch (Exception e) {
// skip
}
if (uCache != null) {
Set<?> set = null;
while (set == null) {
try {
set = ((HashMap<?, ?>) uCache.clone()).keySet();
} catch (ConcurrentModificationException e) {
// Fix for BACKLOG-2149 - Do nothing - while loop will try again.
}
}
for (Object file : set) {
if (file instanceof JarFile) {
JarFile jar = (JarFile) file;
if (!closedFiles.contains(jar.getName())) {
continue;
}
try {
jar.close();
} catch (IOException e) {
// skip
}
if (fCache != null) {
fCache.remove(uCache.get(jar));
}
uCache.remove(jar);
}
}
} else if (fCache != null) {
for (Object key : ((HashMap<?, ?>) fCache.clone()).keySet()) {
Object file = fCache.get(key);
if (file instanceof JarFile) {
JarFile jar = (JarFile) file;
if (!closedFiles.contains(jar.getName())) {
continue;
}
try {
jar.close();
} catch (IOException e) {
// ignore
}
fCache.remove(key);
}
}
}
} catch (Exception e) {
// skip
e.printStackTrace();
}
}
private boolean classExistsInPackageJarFiles(String name) {
return m_packageJarEntries.contains(name);
}
private boolean resourceExistsInPackageJarFiles(String name) {
return m_packageJarResources.contains(name);
}
/**
* String representation of this classloader
*
* @return the string representation of this classloader
*/
public String toString() {
return "" + getClass().getCanonicalName() + " (" + m_packageName + ")";
}
/**
* Return the name of the package that this classloader loads classes for
*
* @return return the name of the package that this classloader loads classes
* for
*/
public String getPackageName() {
return m_packageName;
}
/**
* Get a Set of the names of all classes contained within top-level jar files
* in this package
*
* @return a Set of the names of classes contained in top-level jar files in
* this package
*/
public Set<String> getPackageJarEntries() {
return m_packageJarEntries;
}
/**
* Check the integrity of this classloader (typically done for each
* classloader after all packages have been loaded by the package manager).
* Checks to see that a classloader for each dependency is available
*
* @return true if a classloader for each dependency is available
*/
protected boolean integrityCheck() throws Exception {
for (String dep : m_packageDependencies) {
if (m_classloaderRepo.getPackageClassLoader(dep) == null) {
return false;
}
}
// now check for missing classes, unset env vars etc.
Package p = WekaPackageManager.getInstalledPackageInfo(m_packageName);
if (!checkForMissingClasses(p, System.err)) {
return false;
}
if (!checkForUnsetEnvVar(p)) {
return false;
}
if (!checkForMissingFiles(p, new File(WekaPackageManager.getPackageHome()
.toString() + File.separator + p.getName()), System.err)) {
return false;
}
setSystemProperties(p, System.out);
return true;
}
/**
* Set any system properties specified in the metadata for this package
*
* @param toLoad the package in question
* @param progress for printing progress/debug info
*/
protected void setSystemProperties(Package toLoad, PrintStream... progress) {
Object sysProps =
toLoad
.getPackageMetaDataElement(WekaPackageManager.SET_SYSTEM_PROPERTIES_KEY);
if (sysProps != null && sysProps.toString().length() > 0) {
// individual props separated by ;'s
String[] propsToSet = sysProps.toString().split(";");
for (String prop : propsToSet) {
String[] keyVals = prop.split("=");
if (keyVals.length == 2) {
String key = keyVals[0].trim();
String val = keyVals[1].trim();
if (m_debug) {
for (PrintStream p : progress) {
p.println("[" + toString() + "] setting property: " + prop);
}
}
System.setProperty(key, val);
}
}
}
}
/**
* Checks to see if there are any classes that we should try to instantiate
* before allowing this package to be loaded. This is useful for checking to
* see if third-party classes are accessible. An example would be Java3D,
* which has an installer that installs into the JRE/JDK.
*
* @param toCheck the package in question
* @param progress for printing progress/error info
*
* @return true if good to go
* @throws Exception if there is a problem
*/
protected boolean checkForMissingClasses(Package toCheck,
PrintStream... progress) throws Exception {
boolean result = true;
Object doNotLoadIfClassNotInstantiable =
toCheck.getPackageMetaDataElement(DO_NOT_LOAD_IF_CLASS_NOT_PRESENT_KEY);
if (doNotLoadIfClassNotInstantiable != null
&& doNotLoadIfClassNotInstantiable.toString().length() > 0) {
StringTokenizer tok =
new StringTokenizer(doNotLoadIfClassNotInstantiable.toString(), ",");
while (tok.hasMoreTokens()) {
String nextT = tok.nextToken().trim();
try {
findClass(nextT);
} catch (Exception ex) {
for (PrintStream p : progress) {
p.println("[WekaPackageLibIsolatingClassLoader] "
+ toCheck.getName() + " can't be loaded because " + nextT
+ " can't be instantiated.");
}
result = false;
break;
}
}
}
if (!result) {
// grab the message to print to the log (if any)
Object doNotLoadMessage =
toCheck
.getPackageMetaDataElement(DO_NOT_LOAD_IF_ENV_VAR_NOT_SET_MESSAGE_KEY);
if (doNotLoadMessage != null && doNotLoadMessage.toString().length() > 0) {
for (PrintStream p : progress) {
String dnlM = doNotLoadMessage.toString();
try {
dnlM = Environment.getSystemWide().substitute(dnlM);
} catch (Exception e) {
// quietly ignore
}
p.println("[Weka] " + dnlM);
}
}
}
return result;
}
/**
* Checks to see if there are any missing files/directories for a given
* package. If there are missing files, then the package can't be loaded. An
* example would be a connector package that, for whatever reason, can't
* include a necessary third-party jar file in its lib folder, and requires
* the user to download and install this jar file manually.
*
* @param toLoad the package to check
* @param packageRoot the root directory of the package
* @param progress for printing progress/error info
* @return true if good to go
*/
public static boolean checkForMissingFiles(Package toLoad, File packageRoot,
PrintStream... progress) {
boolean result = true;
Object doNotLoadIfFileMissing =
toLoad.getPackageMetaDataElement(DO_NOT_LOAD_IF_FILE_NOT_PRESENT_KEY);
String packageRootPath = packageRoot.getPath() + File.separator;
if (doNotLoadIfFileMissing != null
&& doNotLoadIfFileMissing.toString().length() > 0) {
StringTokenizer tok =
new StringTokenizer(doNotLoadIfFileMissing.toString(), ",");
while (tok.hasMoreTokens()) {
String nextT = tok.nextToken().trim();
File toCheck = new File(packageRootPath + nextT);
if (!toCheck.exists()) {
for (PrintStream p : progress) {
p.println("[Weka] " + toLoad.getName()
+ " can't be loaded because " + toCheck.getPath()
+ " appears to be missing.");
}
result = false;
break;
}
}
}
if (!result) {
// grab the message to print to the log (if any)
Object doNotLoadMessage =
toLoad
.getPackageMetaDataElement(DO_NOT_LOAD_IF_FILE_NOT_PRESENT_MESSAGE_KEY);
if (doNotLoadMessage != null && doNotLoadMessage.toString().length() > 0) {
String dnlM = doNotLoadMessage.toString();
try {
dnlM = Environment.getSystemWide().substitute(dnlM);
} catch (Exception ex) {
// quietly ignore
}
for (PrintStream p : progress) {
p.println("[Weka] " + dnlM);
}
}
}
return result;
}
/**
* Checks to see if there are any environment variables or properties that
* should be set at startup before allowing this package to be loaded. This is
* useful for packages that might not be able to function correctly if certain
* variables are not set correctly.
*
* @param toLoad the package to check
* @return true if good to go
*/
protected static boolean checkForUnsetEnvVar(Package toLoad) {
Object doNotLoadIfUnsetVar =
toLoad.getPackageMetaDataElement(DO_NOT_LOAD_IF_ENV_VAR_NOT_SET_KEY);
boolean result = true;
if (doNotLoadIfUnsetVar != null
&& doNotLoadIfUnsetVar.toString().length() > 0) {
String[] elements = doNotLoadIfUnsetVar.toString().split(",");
Environment env = Environment.getSystemWide();
for (String var : elements) {
if (env.getVariableValue(var.trim()) == null) {
System.err.println("[Weka] " + toLoad.getName()
+ " can't be loaded because " + "the environment variable " + var
+ " is not set.");
result = false;
break;
}
}
}
if (!result) {
// grab the message to print to the log (if any)
Object doNotLoadMessage =
toLoad
.getPackageMetaDataElement(DO_NOT_LOAD_IF_ENV_VAR_NOT_SET_MESSAGE_KEY);
if (doNotLoadMessage != null && doNotLoadMessage.toString().length() > 0) {
String dnlM = doNotLoadMessage.toString();
try {
dnlM = Environment.getSystemWide().substitute(dnlM);
} catch (Exception e) {
// quietly ignore
}
System.err.println("[Weka] " + dnlM);
}
}
return result;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/WekaPackageManager.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* WekaPackageManager.java
* Copyright (C) 2009-2013 University of Waikato, Hamilton, New Zealand
*/
package weka.core;
import weka.core.converters.ConverterUtils;
import weka.core.logging.Logger;
import weka.core.packageManagement.DefaultPackageManager;
import weka.core.packageManagement.Dependency;
import weka.core.packageManagement.Package;
import weka.core.packageManagement.PackageConstraint;
import weka.core.packageManagement.PackageManager;
import weka.core.packageManagement.VersionPackageConstraint;
import weka.gui.ConverterFileChooser;
import weka.gui.GenericObjectEditor;
import weka.gui.GenericPropertiesCreator;
import weka.gui.beans.BeansProperties;
import weka.gui.beans.KnowledgeFlowApp;
import weka.gui.explorer.ExplorerDefaults;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
* Class providing package management and manipulation routines. Also provides a
* command line interface for package management.
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class WekaPackageManager {
/** Package metadata key for dependency injection */
public static final String INJECT_DEPENDENCY_KEY = "InjectDependencies";
/** Package metadata key for version info */
public static final String VERSION_KEY = "Version";
/** Package metadata key for package disablement */
public static final String DISABLE_KEY = "Disable";
/** Package metadata key for package disablement */
public static final String DISABLED_KEY = "Disabled";
/** Package metadata key for package preclusion */
public static final String PRECLUDES_KEY = "Precludes";
/**
* Package metadata key for OS name. Entries in this list are checked against
* the java property os.name using a String.contains() operation - any match
* in the list is taken as passing the test.
*/
public static final String OS_NAME_KEY = "OSName";
/**
* Package metadata key for OS architecture. Entries in this list are checked
* against the java property os.arch using a String.equalsIgnoreCase()
* operation, with the exception of entries that are either "64" or "32" in
* which case the os.arch is checked to see if it contains these numbers. Any
* match in the list is considered as passing the test.
*/
public static final String OS_ARCH_KEY = "OSArch";
/**
* Package metadata key for preventing load if an environment variable is not
* set
*/
public static final String DO_NOT_LOAD_IF_ENV_VAR_NOT_SET_KEY =
"DoNotLoadIfEnvVarNotSet";
/**
* Package metadata key for preventing load if an environment variable is not
* set
*/
public static final String DO_NOT_LOAD_IF_ENV_VAR_NOT_SET_MESSAGE_KEY =
"DoNotLoadIfEnvVarNotSetMessage";
/** Package metadata key for preventing load if a class is not available */
public static final String DO_NOT_LOAD_IF_CLASS_NOT_PRESENT_KEY =
"DoNotLoadIfClassNotPresent";
/** Package metadata key for preventing load if a class is not available */
public static final String DO_NOT_LOAD_IF_CLASS_NOT_PRESENT_MESSAGE_KEY =
"DoNotLoadIfClassNotPresentMessage";
/** Package metadata key for preventing load if a file is not present */
public static final String DO_NOT_LOAD_IF_FILE_NOT_PRESENT_KEY =
"DoNotLoadIfFileNotPresent";
/** Package metadata key for preventing load if a file is not present */
public static final String DO_NOT_LOAD_IF_FILE_NOT_PRESENT_MESSAGE_KEY =
"DoNotLoadIfFileNotPresentMessage";
/** Package metadata key for a message to display on installation */
public static final String MESSAGE_TO_DISPLAY_ON_INSTALLATION_KEY =
"MessageToDisplayOnInstallation";
/** Package metadata key for setting system properties */
public static final String SET_SYSTEM_PROPERTIES_KEY = "SetSystemProperties";
/** The default folder name for Weka bits and bobs */
private static String WEKAFILES_DIR_NAME = "wekafiles";
/** Default path to where Weka's configuration and packages are stored */
public static File WEKA_HOME = new File(System.getProperty("user.home")
+ File.separator + WEKAFILES_DIR_NAME);
/** The default packages directory */
public static File PACKAGES_DIR = new File(WEKA_HOME.toString()
+ File.separator + "packages");
/** The default props dir name */
private static String PROPERTIES_DIR_NAME = "props";
/** The default properties directory */
public static File PROPERTIES_DIR = new File(WEKA_HOME.toString()
+ File.separator + PROPERTIES_DIR_NAME);
public static String NATIVE_LIBS_DIR_NAME = "native";
/** The default native libraries directory */
public static File NATIVE_LIBS_DIR = new File(WEKA_HOME.toString()
+ File.separator + NATIVE_LIBS_DIR_NAME);
/** The underlying package manager */
private static PackageManager PACKAGE_MANAGER = PackageManager.create();
/** Current repository URL to use */
private static URL REP_URL;
/** Location of the repository cache */
private static URL CACHE_URL;
/** True if a cache build is required */
private static boolean INITIAL_CACHE_BUILD_NEEDED = false;
/**
* The name of the file that contains the list of packages in the repository
*/
private static String PACKAGE_LIST_FILENAME = "packageListWithVersion.txt";
/** Primary repository */
private static String PRIMARY_REPOSITORY =
"http://weka.sourceforge.net/packageMetaData";
/** Backup mirror of the repository */
private static String REP_MIRROR;
/**
* True if the user has specified a custom repository via a property in
* PackageManager.props
*/
private static boolean USER_SET_REPO = false;
/** The package manager's property file */
private static String PACKAGE_MANAGER_PROPS_FILE_NAME =
"PackageManager.props";
/** Operating offline? */
public static boolean m_offline;
/** Load packages? */
private static boolean m_loadPackages = true;
/** Established WEKA_HOME successfully? */
protected static boolean m_wekaHomeEstablished;
/** Packages loaded OK? */
protected static boolean m_packagesLoaded;
/** File to check against server for new/updated packages */
protected static final String PACKAGE_LIST_WITH_VERSION_FILE =
"packageListWithVersion.txt";
/** File to check against server equivalent for forced refresh */
protected static final String FORCED_REFRESH_COUNT_FILE =
"forcedRefreshCount.txt";
/** Package loading in progress? */
public static boolean m_initialPackageLoadingInProcess = false;
/* True if an initial cache build is needed and working offline */
public static boolean m_noPackageMetaDataAvailable;
/** The set of packages that the user has requested not to load */
public static Set<String> m_doNotLoadList;
static {
establishWekaHome();
// make sure MTJ classes are injected to the root classloader
// so that MTJ native library loading can see them
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.injectMTJCoreClasses();
}
/**
* Establish WEKA_HOME if needed
*
* @return true if WEKA_HOME was successfully established
*/
protected static boolean establishWekaHome() {
if (m_wekaHomeEstablished) {
return true;
}
// process core PluginManager.props before any from packages.
// This is to have some control over the order of certain plugins
try {
PluginManager.addFromProperties(WekaPackageManager.class.getClassLoader()
.getResourceAsStream("weka/PluginManager.props"), true);
} catch (Exception ex) {
log(Logger.Level.WARNING,
"[WekaPackageManager] unable to read weka/PluginManager.props");
}
// look to see if WEKA_HOME has been defined as an environment
// variable
Environment env = Environment.getSystemWide();
String wh = env.getVariableValue("WEKA_HOME");
if (wh != null) {
WEKA_HOME = new File(wh);
PACKAGES_DIR = new File(wh + File.separator + "packages");
PROPERTIES_DIR = new File(wh + File.separator + PROPERTIES_DIR_NAME);
NATIVE_LIBS_DIR = new File(wh + File.separator + NATIVE_LIBS_DIR_NAME);
} else {
env.addVariableSystemWide("WEKA_HOME", WEKA_HOME.toString());
}
String nativePath = System.getProperty("java.library.path", "");
if (!nativePath.contains(NATIVE_LIBS_DIR.toString())) {
nativePath += File.pathSeparator + NATIVE_LIBS_DIR.toString();
System.setProperty("java.library.path", nativePath);
}
boolean ok = true;
if (!WEKA_HOME.exists()) {
// create it for the user
if (!WEKA_HOME.mkdir()) {
System.err.println("Unable to create WEKA_HOME ("
+ WEKA_HOME.getAbsolutePath() + ")");
ok = false;
}
}
if (!PACKAGES_DIR.exists()) {
// create the packages dir
if (!PACKAGES_DIR.mkdir()) {
System.err.println("Unable to create packages directory ("
+ PACKAGES_DIR.getAbsolutePath() + ")");
ok = false;
}
}
if (!NATIVE_LIBS_DIR.exists()) {
if (!NATIVE_LIBS_DIR.mkdir()) {
System.err.println("Unable to create native libs directory ("
+ NATIVE_LIBS_DIR.getAbsolutePath() + ")");
}
}
m_wekaHomeEstablished = ok;
PACKAGE_MANAGER.setPackageHome(PACKAGES_DIR);
m_doNotLoadList = getDoNotLoadList();
try {
// setup the backup mirror first
// establishMirror();
// user-supplied repository URL takes precedence over anything else
String repURL =
env.getVariableValue("weka.core.wekaPackageRepositoryURL");
if (repURL == null || repURL.length() == 0) {
// See if there is a URL named in
// $WEKA_HOME/props/PackageRepository.props
File repPropsFile =
new File(PROPERTIES_DIR.toString() + File.separator
+ "PackageRepository.props");
if (repPropsFile.exists()) {
Properties repProps = new Properties();
repProps.load(new FileInputStream(repPropsFile));
repURL = repProps.getProperty("weka.core.wekaPackageRepositoryURL");
}
}
if (repURL == null || repURL.length() == 0) {
repURL = PRIMARY_REPOSITORY;
} else {
log(weka.core.logging.Logger.Level.INFO,
"[WekaPackageManager] weka.core.WekaPackageRepositoryURL = " + repURL);
// System.err.println("[WekaPackageManager]
// weka.core.WekaPackageRepositoryURL = "
// + repURL);
USER_SET_REPO = true;
}
REP_URL = new URL(repURL);
PACKAGE_MANAGER.setPackageRepositoryURL(REP_URL);
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
PACKAGE_MANAGER.setBaseSystemName("weka");
PACKAGE_MANAGER.setBaseSystemVersion(weka.core.Version.VERSION);
// Now check the cache and establish it if necessary
File cacheDir =
new File(WEKA_HOME.toString() + File.separator + "repCache");
try {
String tempCacheString = "file://" + cacheDir.toString();
// sanitize URI and fix slashes (for Windows)
tempCacheString = tempCacheString.replace(" ", "%20");
tempCacheString = tempCacheString.replace('\\', '/');
if (tempCacheString.startsWith("file://")
&& !tempCacheString.startsWith("file:///")) {
tempCacheString = tempCacheString.substring(7);
tempCacheString = "file:///" + tempCacheString;
}
URI tempURI = new URI(tempCacheString);
// System.err.println(" -- " + tempURI.toString());
CACHE_URL = tempURI.toURL();
} catch (Exception e) {
e.printStackTrace();
}
File packagesList =
new File(cacheDir.getAbsolutePath() + File.separator
+ PACKAGE_LIST_FILENAME);
if (!cacheDir.exists()) {
if (!cacheDir.mkdir()) {
System.err.println("Unable to create repository cache directory ("
+ cacheDir.getAbsolutePath() + ")");
log(
weka.core.logging.Logger.Level.WARNING,
"Unable to create repository cache directory ("
+ cacheDir.getAbsolutePath() + ")");
CACHE_URL = null;
} else {
// refreshCache();
INITIAL_CACHE_BUILD_NEEDED = true;
}
}
if (!packagesList.exists()) {
INITIAL_CACHE_BUILD_NEEDED = true;
}
// Package manager general properties
// Set via system props first
String offline = env.getVariableValue("weka.packageManager.offline");
if (offline != null) {
m_offline = offline.equalsIgnoreCase("true");
}
String loadPackages =
env.getVariableValue("weka.packageManager.loadPackages");
if (loadPackages == null) {
// try legacy
loadPackages = env.getVariableValue("weka.core.loadPackages");
}
if (loadPackages != null) {
m_loadPackages = loadPackages.equalsIgnoreCase("true");
}
// load any general package manager properties from props file
File generalProps =
new File(PROPERTIES_DIR.toString() + File.separator
+ PACKAGE_MANAGER_PROPS_FILE_NAME);
if (generalProps.exists()) {
Properties gProps = new Properties();
try {
gProps.load(new FileInputStream(generalProps));
// this one takes precedence over the legacy one
String repURL =
gProps.getProperty("weka.core.wekaPackageRepositoryURL");
if (repURL != null && repURL.length() > 0) {
REP_URL = new URL(repURL);
PACKAGE_MANAGER.setPackageRepositoryURL(REP_URL);
}
offline = gProps.getProperty("weka.packageManager.offline");
if (offline != null && offline.length() > 0) {
m_offline = offline.equalsIgnoreCase("true");
}
loadPackages = gProps.getProperty("weka.packageManager.loadPackages");
if (loadPackages == null) {
// try legacy
loadPackages = env.getVariableValue("weka.core.loadPackages");
}
if (loadPackages != null) {
m_loadPackages = loadPackages.equalsIgnoreCase("true");
}
String pluginManagerDisableList =
gProps.getProperty("weka.pluginManager.disable");
if (pluginManagerDisableList != null
&& pluginManagerDisableList.length() > 0) {
List<String> disable = new ArrayList<String>();
String[] parts = pluginManagerDisableList.split(",");
for (String s : parts) {
disable.add(s.trim());
}
PluginManager.addToDisabledList(disable);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if (INITIAL_CACHE_BUILD_NEEDED && m_offline) {
m_noPackageMetaDataAvailable = true;
}
// Pass a valid http URL to the setProxyAuthentication()
// method to ensure that a proxy or direct connection
// is configured initially. This will prevent this method from
// trying to configure the ProxySelector and proxy
// via the file-based CACHE_URL somewhere down the track
PACKAGE_MANAGER.setPackageRepositoryURL(REP_URL);
PACKAGE_MANAGER.setProxyAuthentication(REP_URL);
return ok;
}
/**
* Establish the location of a mirror
*/
protected static void establishMirror() {
if (m_offline) {
return;
}
try {
String mirrorListURL =
"http://www.cs.waikato.ac.nz/ml/weka/packageMetaDataMirror.txt";
URLConnection conn = null;
URL connURL = new URL(mirrorListURL);
if (PACKAGE_MANAGER.setProxyAuthentication(connURL)) {
conn = connURL.openConnection(PACKAGE_MANAGER.getProxy());
} else {
conn = connURL.openConnection();
}
conn.setConnectTimeout(10000); // timeout after 10 seconds
conn.setReadTimeout(10000);
BufferedReader bi =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
REP_MIRROR = bi.readLine();
bi.close();
if (REP_MIRROR != null && REP_MIRROR.length() > 0) {
// use the mirror if it is different from the primary repo
// and the user hasn't specified an explicit repo via the
// property
if (!REP_MIRROR.equals(PRIMARY_REPOSITORY) && !USER_SET_REPO) {
log(weka.core.logging.Logger.Level.INFO,
"[WekaPackageManager] Package manager using repository mirror: "
+ REP_MIRROR);
REP_URL = new URL(REP_MIRROR);
}
}
} catch (Exception ex) {
log(weka.core.logging.Logger.Level.WARNING,
"[WekaPackageManager] The repository meta data mirror file seems "
+ "to be unavailable (" + ex.getMessage() + ")");
}
}
/**
* Write to the weka log
*
* @param level logging level
* @param message message to write
*/
protected static void
log(weka.core.logging.Logger.Level level, String message) {
try {
File logFile =
new File(WEKA_HOME.toString() + File.separator + "weka.log");
BufferedWriter writer = new BufferedWriter(new FileWriter(logFile, true));
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String linefeed = System.getProperty("line.separator");
String m =
format.format(new Date()) + " " + level + ": " + message + linefeed;
writer.write(m);
writer.flush();
writer.close();
} catch (Exception ex) {
}
}
/**
* Remove any ExplorerDefaults properties specified in the supplied package
*
* @param installedPackageName the package specifying properties that should
* be removed from ExplorerDefaults
*/
public static void removeExplorerProps(String installedPackageName) {
try {
Properties expProps = new Properties();
String explorerProps =
getPackageHome().getAbsolutePath() + File.separator
+ installedPackageName + File.separator + "Explorer.props";
BufferedInputStream bi =
new BufferedInputStream(new FileInputStream(explorerProps));
expProps.load(bi);
bi.close();
bi = null;
Set<Object> keys = expProps.keySet();
Iterator<Object> keysI = keys.iterator();
while (keysI.hasNext()) {
String key = (String) keysI.next();
if (!key.endsWith("Policy")) {
// See if this key is in the Explorer props
String existingVal = ExplorerDefaults.get(key, "");
String toRemove = expProps.getProperty(key);
if (existingVal.length() > 0) {
// cover the case when the value to remove is at the start
// or middle of a list
existingVal = existingVal.replace(toRemove + ",", "");
// the case when it's at the end
existingVal = existingVal.replace("," + toRemove, "");
ExplorerDefaults.set(key, existingVal);
}
}
}
} catch (Exception ex) {
}
}
/**
* Process a package's GenericPropertiesCreator.props file
*
* @param propsFile the props file to process
*/
protected static void processGenericPropertiesCreatorProps(File propsFile) {
try {
Properties expProps = new Properties();
BufferedInputStream bi =
new BufferedInputStream(new FileInputStream(propsFile));
expProps.load(bi);
bi.close();
bi = null;
Properties GPCInputProps =
GenericPropertiesCreator.getGlobalInputProperties();
Set<Object> keys = expProps.keySet();
Iterator<Object> keysI = keys.iterator();
while (keysI.hasNext()) {
String key = (String) keysI.next();
// see if this key is in the GPC input props
String existingVal = GPCInputProps.getProperty(key, "");
if (existingVal.length() > 0) {
// append
String newVal = expProps.getProperty(key);
// only append if this value is not already there!!
if (existingVal.indexOf(newVal) < 0) {
newVal = existingVal + "," + newVal;
GPCInputProps.put(key, newVal);
}
} else {
// simply add this new key/value combo
String newVal = expProps.getProperty(key);
GPCInputProps.put(key, newVal);
}
}
} catch (Exception ex) {
// ignore
}
}
/**
* Process a package's Explorer.props file
*
* @param propsFile the properties file to process
*/
protected static void processExplorerProps(File propsFile) {
try {
Properties expProps = new Properties();
BufferedInputStream bi =
new BufferedInputStream(new FileInputStream(propsFile));
expProps.load(bi);
bi.close();
bi = null;
Set<Object> keys = expProps.keySet();
Iterator<Object> keysI = keys.iterator();
while (keysI.hasNext()) {
String key = (String) keysI.next();
if (!key.endsWith("Policy")) {
// See if this key is in the Explorer props
String existingVal = ExplorerDefaults.get(key, "");
if (existingVal.length() > 0) {
// get the replacement policy (if any)
String replacePolicy = expProps.getProperty(key + "Policy");
if (replacePolicy != null && replacePolicy.length() > 0) {
if (replacePolicy.equalsIgnoreCase("replace")) {
String newVal = expProps.getProperty(key);
ExplorerDefaults.set(key, newVal);
} else {
// default to append
String newVal = expProps.getProperty(key);
// only append if this value is not already there!!
if (existingVal.indexOf(newVal) < 0) {
newVal = existingVal + "," + newVal;
ExplorerDefaults.set(key, newVal);
}
}
} else {
// default to append
String newVal = expProps.getProperty(key);
// only append if this value is not already there!!
if (existingVal.indexOf(newVal) < 0) {
newVal = existingVal + "," + newVal;
ExplorerDefaults.set(key, newVal);
}
}
} else {
// simply add this new key/value combo
String newVal = expProps.getProperty(key);
ExplorerDefaults.set(key, newVal);
}
}
}
} catch (Exception ex) {
// ignore
}
}
/**
* Process a package's GUIEditors.props file
*
* @param propsFile the properties file to process
* @param verbose true to output more info
*/
protected static void processGUIEditorsProps(File propsFile, boolean verbose) {
GenericObjectEditor.registerEditors();
try {
Properties editorProps = new Properties();
BufferedInputStream bi =
new BufferedInputStream(new FileInputStream(propsFile));
editorProps.load(bi);
bi.close();
bi = null;
Enumeration<?> enm = editorProps.propertyNames();
while (enm.hasMoreElements()) {
String name = enm.nextElement().toString();
String value = editorProps.getProperty(name, "");
if (verbose) {
System.err.println("Registering " + name + " " + value);
}
GenericObjectEditor.registerEditor(name, value);
}
} catch (Exception ex) {
// ignore
}
}
/**
* Process a package's PluginManager.props file
*
* @param packageName the name of the package that owns this PluginManager
* props file
* @param propsFile the properties file to process
*/
protected static void processPluginManagerProps(String packageName,
File propsFile) {
try {
PluginManager.addFromProperties(packageName, propsFile);
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* Process properties in a package directory
*
* @param directory the package directory to process
* @param verbose true for verbose output
* @param goePropsFiles store any GenericObjectEditor.props files for
* post-processing after all jars have been loaded
* @throws Exception if a problem occurs
*/
protected static void processPackageDirectory(File directory,
boolean verbose, List<File> goePropsFiles,
boolean avoidTriggeringFullClassDiscovery) throws Exception {
File[] contents = directory.listFiles();
if (contents != null) {
// make sure that jar files and lib directory get processed first
/*
* for (File content : contents) { if (content.isFile() &&
* content.getPath().endsWith(".jar")) { if (verbose) {
* System.out.println("[WekaPackageManager] loading " +
* content.getPath()); } ClassloaderUtil.addFile(content.getPath());
*
* } else if (content.isDirectory() &&
* content.getName().equalsIgnoreCase("lib")) { // add any jar files in
* the lib directory to the classpath processPackageDirectory(content,
* verbose, goePropsFiles, avoidTriggeringFullClassDiscovery); } }
*/
// now any auxilliary files
for (File content : contents) {
if (content.isFile() && content.getPath().endsWith("Beans.props")) {
// KnowledgeFlow plugin -- add the Beans.props file to the list of
// bean plugin props
BeansProperties.addToPluginBeanProps(content);
if (!avoidTriggeringFullClassDiscovery) {
KnowledgeFlowApp.disposeSingleton();
}
} else if (content.isFile()
&& content.getPath().endsWith("Explorer.props")
&& !avoidTriggeringFullClassDiscovery) {
// Explorer tabs plugin
// process the keys in the properties file and append/add values
processExplorerProps(content);
} else if (content.isFile()
&& content.getPath().endsWith("GUIEditors.props")
&& !avoidTriggeringFullClassDiscovery) {
// Editor for a particular component
processGUIEditorsProps(content, verbose);
} else if (content.isFile()
&& content.getPath().endsWith("GenericPropertiesCreator.props")
&& !avoidTriggeringFullClassDiscovery) {
if (goePropsFiles != null) {
goePropsFiles.add(content);
} else {
processGenericPropertiesCreatorProps(content);
}
} else if (content.isFile()
&& content.getPath().endsWith("PluginManager.props")) {
processPluginManagerProps(directory.getName(), content);
}
}
}
}
/**
* Check to see if the named package has been loaded successfully
*
* @param toCheck the name of the package to check for
* @return true if the named package has been loaded successfully
*/
public static boolean hasBeenLoaded(Package toCheck) {
// if it loaded successfully, passed all integrity checks etc., then there
// will be package classloader for it
return WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.getPackageClassLoader(toCheck.getName()) != null;
}
/**
* Check whether a package should be loaded or not. Checks for missing
* classes, unset environment variables, missing dependencies etc.
*
* @param toLoad the package to check
* @param packageRoot the root directory of the package
* @param progress for reporting loading progress
* @return true if the package is good to load
*/
public static boolean loadCheck(Package toLoad, File packageRoot,
PrintStream... progress) {
// first check against the base version of the system
boolean load;
try {
load = toLoad.isCompatibleBaseSystem();
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
if (!load) {
for (PrintStream p : progress) {
p.println("[WekaPackageManager] Skipping package " + toLoad.getName()
+ " because it is not compatible with Weka "
+ PACKAGE_MANAGER.getBaseSystemVersion().toString());
}
return false;
}
// check to see if this package has been disabled for all users
try {
Package repoP =
getRepositoryPackageInfo(toLoad.getName(), toLoad
.getPackageMetaDataElement(VERSION_KEY).toString());
if (repoP != null) {
Object disabled = repoP.getPackageMetaDataElement(DISABLED_KEY);
if (disabled == null) {
disabled = repoP.getPackageMetaDataElement(DISABLE_KEY);
}
if (disabled != null && disabled.toString().equalsIgnoreCase("true")) {
for (PrintStream p : progress) {
p.println("[WekaPackageManager] Skipping package "
+ toLoad.getName()
+ " because it has been marked as disabled at the repository");
}
return false;
}
}
} catch (Exception ex) {
// Ignore - we will get an exception when checking for an unofficial
// package
return true;
}
if (!osAndArchCheck(toLoad, progress)) {
return false;
}
// check for precludes
Object precludes = toLoad.getPackageMetaDataElement(PRECLUDES_KEY);
if (precludes != null) {
try {
List<Package> installed = getInstalledPackages();
List<Package> preclusions = toLoad.getPrecludedPackages(installed);
if (preclusions.size() > 0) {
for (PrintStream p : progress) {
p.println("[WekaPackageManager] Skipping package "
+ toLoad.getName()
+ " because it precludes one or more packages that are "
+ "already installed: ");
for (Package prec : preclusions) {
p.println("\t" + prec);
}
}
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
load = !m_doNotLoadList.contains(toLoad.getName());
if (!load) {
for (PrintStream p : progress) {
p.println("[WekaPackageManager] Skipping package " + toLoad.getName()
+ " because it is has been marked as do not load");
}
return false;
}
if (m_offline) {
return true;
}
// now check for missing dependencies
try {
List<Dependency> missing = toLoad.getMissingDependencies();
if (missing.size() > 0) {
for (PrintStream p : progress) {
p.println("[WekaPackageManager] " + toLoad.getName()
+ " can't be loaded because the following"
+ " packages are missing:");
for (Dependency d : missing) {
p.println(d.getTarget());
}
}
return false;
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
// now check for buggered dependencies
try {
List<Dependency> depends = toLoad.getDependencies();
for (Dependency d : depends) {
if (d.getTarget().getPackage().isInstalled()) {
if (!loadCheck(d.getTarget().getPackage(), packageRoot, progress)) {
for (PrintStream p : progress) {
p.println("[WekaPackageManager] Can't load " + toLoad.getName()
+ " because " + d.getTarget() + " can't be loaded.");
}
return false;
}
// check that the version of installed dependency is OK
Package installedD =
getInstalledPackageInfo(d.getTarget().getPackage().getName());
if (!d.getTarget().checkConstraint(installedD)) {
for (PrintStream p : progress) {
p.println("[WekaPackageManager] Can't load " + toLoad.getName()
+ " because the installed "
+ d.getTarget().getPackage().getName()
+ " is not compatible (requires: " + d.getTarget() + ")");
}
return false;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
/**
* Checks the supplied package against the current OS and architecture.
* Packages that don't specify OS and (optionally) architecture constraints
* are assumed to be OK. OS names in the OSName entry of the package's
* Description.props are checked against System.getProperty("os.name") via a
* String.contains() comparison. Any single match results in a pass. If
* supplied, the package's OSArch entries are checked against
* System.getProperty("os.arch") using a String.equalsIgnoreCase() comparison,
* with the exception of the values "64" and "32" which are checked for with
* String.contains().
*
* @param toLoad the package to check
* @param progress PrintStream for progress info
* @return true if the supplied package passes OS/arch constraints.
*/
public static boolean osAndArchCheck(Package toLoad,
PrintStream... progress) {
// check for OS restrictions
try {
Object osNames = toLoad.getPackageMetaDataElement(OS_NAME_KEY);
Object archNames = toLoad.getPackageMetaDataElement(OS_ARCH_KEY);
if (osNames != null) {
boolean osCheck = false;
String[] osElements = osNames.toString().split(",");
String thisOs = System.getProperty("os.name");
if (thisOs != null) {
for (String osEntry : osElements) {
if (thisOs.toLowerCase().contains(osEntry.trim().toLowerCase())) {
osCheck = true;
break;
}
}
String thisArch = System.getProperty("os.arch");
if (osCheck && archNames != null) {
String[] archElements = archNames.toString().split(",");
if (thisArch != null) {
boolean archCheck = false;
for (String archEntry : archElements) {
if (archEntry.trim().equalsIgnoreCase("32")
|| archEntry.trim().equalsIgnoreCase("64")) {
if (thisArch.toLowerCase().contains(archEntry.trim())) {
archCheck = true;
break;
}
} else {
if (thisArch.trim().equalsIgnoreCase(archEntry.trim())) {
archCheck = true;
break;
}
}
}
osCheck = archCheck;
}
}
if (!osCheck) {
for (PrintStream p : progress) {
p.println("[WekaPackageManager] Skipping package "
+ toLoad.getName() + " because the OS/arch (" + thisOs + " "
+ (thisArch != null ? thisArch : "")
+ ") does not meet package OS/arch constraints: "
+ osNames.toString() + " "
+ (archNames != null ? archNames.toString() : ""));
}
return false;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/**
* Checks to see if there are any missing files/directories for a given
* package. If there are missing files, then the package can't be loaded. An
* example would be a connector package that, for whatever reason, can't
* include a necessary third-party jar file in its lib folder, and requires
* the user to download and install this jar file manually.
*
* @param toLoad the package to check
* @param packageRoot the root directory of the package
* @return true if good to go
*/
public static boolean checkForMissingFiles(Package toLoad, File packageRoot,
PrintStream... progress) {
boolean result = true;
Object doNotLoadIfFileMissing =
toLoad.getPackageMetaDataElement(DO_NOT_LOAD_IF_FILE_NOT_PRESENT_KEY);
String packageRootPath = packageRoot.getPath() + File.separator;
if (doNotLoadIfFileMissing != null
&& doNotLoadIfFileMissing.toString().length() > 0) {
StringTokenizer tok =
new StringTokenizer(doNotLoadIfFileMissing.toString(), ",");
while (tok.hasMoreTokens()) {
String nextT = tok.nextToken().trim();
File toCheck = new File(packageRootPath + nextT);
if (!toCheck.exists()) {
for (PrintStream p : progress) {
p.println("[WekaPackageManager] " + toLoad.getName()
+ " can't be loaded because " + toCheck.getPath()
+ " appears to be missing.");
}
result = false;
break;
}
}
}
if (!result) {
// grab the message to print to the log (if any)
Object doNotLoadMessage =
toLoad
.getPackageMetaDataElement(DO_NOT_LOAD_IF_FILE_NOT_PRESENT_MESSAGE_KEY);
if (doNotLoadMessage != null && doNotLoadMessage.toString().length() > 0) {
String dnlM = doNotLoadMessage.toString();
try {
dnlM = Environment.getSystemWide().substitute(dnlM);
} catch (Exception ex) {
// quietly ignore
}
for (PrintStream p : progress) {
p.println("[WekaPackageManager] " + dnlM);
}
}
}
return result;
}
/**
* Reads the doNotLoad list (if it exists) from the packages directory
*
* @return a set of package names that should not be loaded. This will be
* empty if the doNotLoadList does not exist on disk.
*/
@SuppressWarnings("unchecked")
protected static Set<String> getDoNotLoadList() {
Set<String> doNotLoad = new HashSet<String>();
File doNotLoadList =
new File(PACKAGES_DIR.toString() + File.separator + "doNotLoad.ser");
if (doNotLoadList.exists() && doNotLoadList.isFile()) {
ObjectInputStream ois = null;
try {
ois =
new ObjectInputStream(new BufferedInputStream(new FileInputStream(
doNotLoadList)));
doNotLoad = (Set<String>) ois.readObject();
} catch (FileNotFoundException ex) {
} catch (IOException e) {
System.err
.println("An error occurred while reading the doNotLoad list: "
+ e.getMessage());
} catch (ClassNotFoundException e) {
System.err
.println("An error occurred while reading the doNotLoad list: "
+ e.getMessage());
} finally {
if (ois != null) {
try {
ois.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
return doNotLoad;
}
/**
* Toggle the load status of the supplied list of package names
*
* @param packageNames the packages to toggle the load status for
* @return a list of unknown packages (i.e. any supplied package names that
* don't appear to be installed)
* @throws Exception if a problem occurs
*/
public static List<String> toggleLoadStatus(List<String> packageNames)
throws Exception {
List<String> unknownPackages = new ArrayList<String>();
boolean changeMade = false;
for (String s : packageNames) {
Package p = PACKAGE_MANAGER.getInstalledPackageInfo(s);
if (p == null) {
unknownPackages.add(s);
} else {
if (m_doNotLoadList.contains(s)) {
m_doNotLoadList.remove(s);
} else {
// only mark as do not load if a package is loadable
if (loadCheck(p, new File(WekaPackageManager.getPackageHome()
.toString() + File.separator + s))) {
m_doNotLoadList.add(s);
}
}
changeMade = true;
}
}
if (changeMade) {
// write the list back to disk
File doNotLoadList =
new File(PACKAGES_DIR.toString() + File.separator + "doNotLoad.ser");
ObjectOutputStream oos = null;
try {
oos =
new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(
doNotLoadList)));
oos.writeObject(m_doNotLoadList);
} finally {
if (oos != null) {
oos.flush();
oos.close();
}
}
}
return unknownPackages;
}
/**
* Load all packages
*
* @param verbose true if loading progress should be output
*/
public static synchronized void loadPackages(boolean verbose) {
loadPackages(verbose, false, true);
}
/**
* Load all packages
*
* @param verbose true if loading progress should be output
* @param avoidTriggeringFullClassDiscovery true if we should avoid processing
* any properties files that might cause a full class discovery run,
* and may involve instantiating GUI classes.
* @param refreshGOEProperties true if the GOE properties should be refreshed
* after loading (i.e. a re-run of the class discovery mechanism,
* re-initialization of the Knowledge Flow etc.)
*/
public static synchronized void loadPackages(boolean verbose,
boolean avoidTriggeringFullClassDiscovery, boolean refreshGOEProperties) {
if (!verbose) {
// debug property overrides
String debug = System.getProperty("weka.core.classloader.debug", "false");
verbose = debug.equalsIgnoreCase("true");
} else {
System.setProperty("weka.core.classloader.debug", "true");
}
List<File> goePropsFiles = new ArrayList<File>();
if (!m_loadPackages) {
return;
}
if (m_packagesLoaded) {
return;
}
m_packagesLoaded = true;
m_initialPackageLoadingInProcess = true;
if (establishWekaHome()) {
// try and load any jar files and add to the classpath
File[] contents = PACKAGES_DIR.listFiles();
// if we have a non-empty packages dir then check
// the integrity of our cache first
if (contents.length > 0) {
establishCacheIfNeeded(System.out);
}
// dynamic injection of dependencies between packages
Map<String, List<String>> injectDependencies = new HashMap<>();
for (File content : contents) {
if (content.isDirectory()) {
try {
Package toLoad = getInstalledPackageInfo(content.getName());
boolean load;
// Only perform the check against the current version of Weka if
// there exists
// a Description.props file
if (toLoad != null) {
load = loadCheck(toLoad, content, System.err);
if (load) {
if (verbose) {
System.out.println("[WekaPackageManager] loading package "
+ content.getName());
}
checkForInjectDependencies(toLoad, injectDependencies);
WekaPackageClassLoaderManager
.getWekaPackageClassLoaderManager().addPackageToClassLoader(
content);
}
}
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("[WekaPackageManager] Problem loading package "
+ content.getName() + " skipping...");
}
}
}
// now inject any package dependencies
injectPackageDependencies(injectDependencies);
// now check overall integrity
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.performIntegrityCheck();
// now process the various properties files in the packages
for (File content : contents) {
try {
if (content.isDirectory()
&& WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.getPackageClassLoader(content.getName()) != null) {
processPackageDirectory(content, verbose, goePropsFiles,
avoidTriggeringFullClassDiscovery);
}
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("[WekaPackageManager] Problem loading package "
+ content.getName() + " skipping...");
}
}
}
m_initialPackageLoadingInProcess = false;
// it is best to process all of these after all jars have been
// inserted into the classpath since the dynamic class discovery
// mechanism will load classes during the process of determining
// all implementations of base types, and this can cause problems
// if processed at the time of package loading and there are
// dependencies between packages
if (!avoidTriggeringFullClassDiscovery) {
for (File f : goePropsFiles) {
processGenericPropertiesCreatorProps(f);
}
}
// do we need to regenerate the list of available schemes for
// the GUIs (this is not necessary when executing stuff from
// the command line)
if (refreshGOEProperties) {
if (verbose) {
System.err.println("Refreshing GOE props...");
}
refreshGOEProperties();
}
}
/**
* Checks a package for the presence of any specified package dependencies to
* inject at load time
*
* @param toLoad the package to check
* @param injectDeps a map (keyed by source package name) containing lists of
* target packages. Each source package will have the entries in its
* target package list injected (via the WekaLibIsolatingClassLoader)
* as dependencies.
*/
protected static void checkForInjectDependencies(Package toLoad,
Map<String, List<String>> injectDeps) {
Object injectList = toLoad.getPackageMetaDataElement(INJECT_DEPENDENCY_KEY);
if (injectList != null) {
String[] deps = injectList.toString().split(",");
for (String dep : deps) {
String[] sourceAndTarget = dep.split(":");
if (sourceAndTarget.length == 2) {
String depender = sourceAndTarget[0].trim();
String dependee = sourceAndTarget[1].trim();
List<String> depList = injectDeps.get(depender);
if (depList == null) {
depList = new ArrayList<>();
injectDeps.put(depender, depList);
}
depList.add(dependee);
}
}
}
}
/**
* Processes a map of dependencies to inject. Each source package (key) will
* have the packages named in the associated list (value) injected as
* dependencies at load time.
*
* @param injectDependencies a map of source to target dependencies.
*/
protected static void injectPackageDependencies(
Map<String, List<String>> injectDependencies) {
for (Map.Entry<String, List<String>> e : injectDependencies.entrySet()) {
String source = e.getKey();
List<String> targets = e.getValue();
WekaPackageLibIsolatingClassLoader sourceLoader =
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.getPackageClassLoader(source);
if (sourceLoader != null) {
String debugS =
System.getProperty("weka.core.classloader.debug", "false");
boolean debug = debugS.equalsIgnoreCase("true");
for (String targetPackage : targets) {
if (WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.getPackageClassLoader(targetPackage) != null) {
if (debug) {
System.out
.println("[WekaPackageManager] Added a dependency between "
+ source + " and " + targetPackage);
}
sourceLoader.addPackageDependency(targetPackage);
}
}
}
}
}
/**
* Refresh the generic object editor properties via re-running of the dynamic
* class discovery process.
*/
public static void refreshGOEProperties() {
ClassDiscovery.clearClassCache();
GenericPropertiesCreator.regenerateGlobalOutputProperties();
GenericObjectEditor.determineClasses();
ConverterUtils.initialize();
ConverterFileChooser.initDefaultFilters();
KnowledgeFlowApp.disposeSingleton();
KnowledgeFlowApp.reInitialize();
}
/**
* Get the underlying package manager implementation
*
* @return the underlying concrete package management implementation.
*/
public static PackageManager getUnderlyingPackageManager() {
return PACKAGE_MANAGER;
}
/**
* Retrieves the size (in KB) of the repository zip archive stored on the
* server.
*
* @return the size of the repository zip archive in KB.
*/
public static int repoZipArchiveSize() {
int size = -1;
try {
PACKAGE_MANAGER.setPackageRepositoryURL(REP_URL);
String numPackagesS =
PACKAGE_MANAGER.getPackageRepositoryURL().toString() + "/repoSize.txt";
URLConnection conn = null;
URL connURL = new URL(numPackagesS);
if (PACKAGE_MANAGER.setProxyAuthentication(connURL)) {
conn = connURL.openConnection(PACKAGE_MANAGER.getProxy());
} else {
conn = connURL.openConnection();
}
conn.setConnectTimeout(30000); // timeout after 30 seconds
BufferedReader bi =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String n = bi.readLine();
try {
size = Integer.parseInt(n);
} catch (NumberFormatException ne) {
System.err.println("[WekaPackageManager] problem parsing the size "
+ "of repository zip archive from the server.");
}
bi.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return size;
}
/**
* Get the number of packages that are available at the repository.
*
* @return the number of packages that are available (or -1 if this can't be
* determined for some reason.
*/
public static int numRepositoryPackages() {
if (m_offline) {
return -1;
}
int numPackages = -1;
try {
PACKAGE_MANAGER.setPackageRepositoryURL(REP_URL);
String numPackagesS =
PACKAGE_MANAGER.getPackageRepositoryURL().toString()
+ "/numPackages.txt";
URLConnection conn = null;
URL connURL = new URL(numPackagesS);
if (PACKAGE_MANAGER.setProxyAuthentication(connURL)) {
conn = connURL.openConnection(PACKAGE_MANAGER.getProxy());
} else {
conn = connURL.openConnection();
}
conn.setConnectTimeout(30000); // timeout after 30 seconds
BufferedReader bi =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String n = bi.readLine();
try {
numPackages = Integer.parseInt(n);
} catch (NumberFormatException ne) {
System.err.println("[WekaPackageManager] problem parsing number "
+ "of packages from server.");
}
bi.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return numPackages;
}
/**
* Just get a list of the package names. This is faster than calling
* getAllPackages(), especially if fetching from the online repository, since
* the full meta data for each package doesn't have to be read.
*
* @param local true if the local package list in the cache should be read
* rather than the online repository
*
* @return a Map<String, String> of all the package names available either
* locally or at the repository
*/
public static Map<String, String> getPackageList(boolean local) {
Map<String, String> result = new HashMap<String, String>();
try {
useCacheOrOnlineRepository();
if (!local) {
PACKAGE_MANAGER.setPackageRepositoryURL(REP_URL);
}
String packageListS =
PACKAGE_MANAGER.getPackageRepositoryURL().toString() + "/"
+ PACKAGE_LIST_WITH_VERSION_FILE;
URLConnection conn = null;
URL connURL = new URL(packageListS);
if (PACKAGE_MANAGER.setProxyAuthentication(connURL)) {
conn = connURL.openConnection(PACKAGE_MANAGER.getProxy());
} else {
conn = connURL.openConnection();
}
conn.setConnectTimeout(30000); // timeout after 30 seconds
BufferedReader bi =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String l = null;
while ((l = bi.readLine()) != null) {
String[] parts = l.split(":");
if (parts.length == 2) {
result.put(parts[0], parts[1]);
}
}
bi.close();
} catch (Exception ex) {
// ex.printStackTrace();
result = null;
}
return result;
}
/**
* Establish the local copy of the package meta data if needed
*
* @param progress for reporting progress
* @return any Exception raised or null if all is good
*/
public static Exception establishCacheIfNeeded(PrintStream... progress) {
if (m_offline) {
return null;
}
if (REP_MIRROR == null) {
establishMirror();
}
Exception problem = null;
if (INITIAL_CACHE_BUILD_NEEDED) {
for (PrintStream p : progress) {
p.println("Caching repository metadata, please wait...");
}
problem = refreshCache(progress);
INITIAL_CACHE_BUILD_NEEDED = false;
} else {
// if no initial build needed then check for a server-side forced
// refresh...
try {
if (checkForForcedCacheRefresh()) {
for (PrintStream p : progress) {
p.println("Forced repository metadata refresh, please wait...");
}
problem = refreshCache(progress);
}
} catch (MalformedURLException ex) {
problem = ex;
}
}
return problem;
}
protected static boolean checkForForcedCacheRefresh()
throws MalformedURLException {
int refreshCountServer = getForcedRefreshCount(false);
if (refreshCountServer > 0) {
// now check local version of this file...
int refreshCountLocal = getForcedRefreshCount(true);
return refreshCountServer > refreshCountLocal;
}
return false;
}
protected static int getForcedRefreshCount(boolean local)
throws MalformedURLException {
useCacheOrOnlineRepository();
if (!local) {
PACKAGE_MANAGER.setPackageRepositoryURL(REP_URL);
}
String refreshCountS =
PACKAGE_MANAGER.getPackageRepositoryURL().toString() + "/"
+ FORCED_REFRESH_COUNT_FILE;
int refreshCount = -1;
URLConnection conn = null;
URL connURL = new URL(refreshCountS);
try {
if (PACKAGE_MANAGER.setProxyAuthentication(connURL)) {
conn = connURL.openConnection(PACKAGE_MANAGER.getProxy());
} else {
conn = connURL.openConnection();
}
conn.setConnectTimeout(30000); // timeout after 30 seconds
BufferedReader bi =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String countS = bi.readLine();
if (countS != null && countS.length() > 0) {
try {
refreshCount = Integer.parseInt(countS);
} catch (NumberFormatException ne) {
// ignore
}
}
} catch (IOException ex) {
// ignore
}
return refreshCount;
}
/**
* Check for new packages on the server and refresh the local cache if needed
*
* @param progress to report progress to
* @return any Exception raised or null if all is good
*/
public static Exception checkForNewPackages(PrintStream... progress) {
if (m_offline) {
return null;
}
Exception problem = null;
Map<String, String> localPackageNameList = getPackageList(true);
if (localPackageNameList == null) {
System.err.println("Local package list is missing, trying a "
+ "cache refresh to restore...");
refreshCache(progress);
localPackageNameList = getPackageList(true);
if (localPackageNameList == null) {
// quietly return and see if we can continue anyway
return null;
}
}
Map<String, String> repositoryPackageNameList = getPackageList(false);
if (repositoryPackageNameList == null) {
// quietly return and see if we can continue anyway
return null;
}
if (repositoryPackageNameList.keySet().size() != localPackageNameList
.keySet().size()) {
// package(s) have disappeared from the repository.
// Force a cache refresh...
if (repositoryPackageNameList.keySet().size() < localPackageNameList
.keySet().size()) {
for (PrintStream p : progress) {
p.println("Some packages no longer exist at the repository. "
+ "Refreshing cache...");
}
} else {
for (PrintStream p : progress) {
p.println("There are new packages at the repository. "
+ "Refreshing cache...");
}
}
problem = refreshCache(progress);
} else {
// check for new versions of packages
boolean refresh = false;
for (String localPackage : localPackageNameList.keySet()) {
String localVersion = localPackageNameList.get(localPackage);
String repoVersion = repositoryPackageNameList.get(localPackage);
if (repoVersion == null) {
continue;
}
// a difference here indicates a newer version on the server
if (!localVersion.equals(repoVersion)) {
refresh = true;
break;
}
}
if (refresh) {
for (PrintStream p : progress) {
p.println("There are newer versions of existing packages "
+ "at the repository. Refreshing cache...");
}
problem = refreshCache(progress);
}
}
return problem;
}
/**
* Deletes the contents of $WEKA_HOME/repCache
*/
protected static void cleanRepCacheDir() {
String cacheDir = WEKA_HOME.toString() + File.separator + "repCache";
File cacheDirF = new File(cacheDir);
if (cacheDirF.exists()) {
File[] contents = cacheDirF.listFiles();
if (contents != null) {
for (File f : contents) {
if (f.isDirectory()) {
File[] packageMetaDirContents = f.listFiles();
if (packageMetaDirContents != null) {
for (File pf : packageMetaDirContents) {
pf.delete();
}
}
}
f.delete();
}
}
}
}
/**
* Refresh the local copy of the package meta data
*
* @param progress to report progress to
* @return any Exception raised or null if all is successful
*/
public static Exception refreshCache(PrintStream... progress) {
Exception problem = null;
if (CACHE_URL == null) {
return null;
}
PACKAGE_MANAGER.setPackageRepositoryURL(REP_URL);
String cacheDir = WEKA_HOME.toString() + File.separator + "repCache";
try {
for (PrintStream p : progress) {
p.println("Refresh in progress. Please wait...");
}
byte[] zip =
PACKAGE_MANAGER.getRepositoryPackageMetaDataOnlyAsZip(progress);
// only blow away the repCache if we successfully get a new zip!
cleanRepCacheDir();
ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zip));
ZipEntry ze;
final byte[] buff = new byte[1024];
while ((ze = zis.getNextEntry()) != null) {
// System.out.println("Cache: inflating " + ze.getName());
if (ze.isDirectory()) {
new File(cacheDir, ze.getName()).mkdir();
continue;
}
BufferedOutputStream bo =
new BufferedOutputStream(new FileOutputStream(new File(cacheDir,
ze.getName())));
while (true) {
int amountRead = zis.read(buff);
if (amountRead == -1) {
break;
}
// write the data here
bo.write(buff, 0, amountRead);
}
bo.close();
}
} catch (Exception e) {
e.printStackTrace();
// OK, we have a problem with the repository cache - use
// the repository itself instead and delete repCache
CACHE_URL = null;
try {
DefaultPackageManager.deleteDir(new File(cacheDir), System.out);
} catch (Exception e1) {
e1.printStackTrace();
}
return e;
}
return problem;
}
/**
* Check if a named resource exists in an installed package
*
* @param packageName the name of the package in question
* @param resourceName the name of the resource to check for
* @return true if the resource exists in the package
*/
public static boolean installedPackageResourceExists(String packageName,
String resourceName) {
String fullResourcePath =
getPackageHome().toString() + File.separator + packageName
+ File.separator + resourceName;
return new File(fullResourcePath).exists();
}
/**
* Determines whether to use the local cache or online repository for meta
* data
*/
private static void useCacheOrOnlineRepository() {
if (REP_MIRROR == null) {
establishMirror();
}
if (CACHE_URL != null) {
PACKAGE_MANAGER.setPackageRepositoryURL(CACHE_URL);
} else if (REP_URL != null) {
PACKAGE_MANAGER.setPackageRepositoryURL(REP_URL);
}
}
public static File getPackageHome() {
return PACKAGE_MANAGER.getPackageHome();
}
/**
* Find the most recent version of the package encapsulated in the supplied
* PackageConstraint argument that satisfies the constraint
*
* @param toCheck the PackageConstraint containing the package in question
* @return the most recent version of the package satisfying the constraint
* @throws Exception if a version can't be found that satisfies the constraint
* or an error occurs while communicating with the respository
*/
public static Package mostRecentVersionWithRespectToConstraint(
PackageConstraint toCheck) throws Exception {
Package target = toCheck.getPackage();
Package result = null;
List<Object> availableVersions =
PACKAGE_MANAGER.getRepositoryPackageVersions(target.getName());
// version numbers will be in descending sorted order from the repository
// we want the most recent version that meets the target constraint
for (Object version : availableVersions) {
Package candidate =
PACKAGE_MANAGER.getRepositoryPackageInfo(target.getName(), version);
if (toCheck.checkConstraint(candidate)
&& candidate.isCompatibleBaseSystem()) {
result = candidate;
break;
}
}
if (result == null) {
throw new Exception("[WekaPackageManager] unable to find a version of "
+ "package " + target.getName() + " that meets constraint "
+ toCheck.toString());
}
return result;
}
/**
* Install the supplied list of packages
*
* @param toInstall packages to install
* @param progress to report progress to
* @return true if successful
* @throws Exception if a problem occurs
*/
public static boolean installPackages(List<Package> toInstall,
PrintStream... progress) throws Exception {
useCacheOrOnlineRepository();
List<Boolean> upgrades = new ArrayList<Boolean>();
for (Package p : toInstall) {
if (p.isInstalled()) {
upgrades.add(new Boolean(true));
} else {
upgrades.add(new Boolean(false));
}
}
PACKAGE_MANAGER.installPackages(toInstall, progress);
boolean atLeastOneUpgrade = false;
List<File> gpcFiles = new ArrayList<File>();
int i = 0;
Map<String, List<String>> injectDependencies = new HashMap<>();
for (Package p : toInstall) {
boolean isAnUpgrade = upgrades.get(i++);
if (isAnUpgrade) {
atLeastOneUpgrade = true;
}
String packageName = p.getName();
File packageDir =
new File(PACKAGE_MANAGER.getPackageHome().toString() + File.separator
+ packageName);
checkForInjectDependencies(p, injectDependencies);
boolean loadIt = loadCheck(p, packageDir, progress);
if (loadIt & !isAnUpgrade) {
processPackageDirectory(packageDir, false, gpcFiles, false);
}
}
// inject dependencies before triggering any class discovery
injectPackageDependencies(injectDependencies);
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.performIntegrityCheck();
for (File f : gpcFiles) {
processGenericPropertiesCreatorProps(f);
}
return atLeastOneUpgrade;
}
/**
* Get the versions of the supplied package available on the server
*
* @param packageName the package name to get available versions for
* @return a list of available versions
* @throws Exception if a problem occurs
*/
public static List<Object> getRepositoryPackageVersions(String packageName)
throws Exception {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getRepositoryPackageVersions(packageName);
}
/**
* Get the package repository URL
*
* @return the package repository URL
*/
public static URL getPackageRepositoryURL() {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getPackageRepositoryURL();
}
/**
* Get a list of all packages
*
* @return a list of all packages
* @throws Exception if a problem occurs
*/
public static List<Package> getAllPackages() throws Exception {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getAllPackages();
}
/**
* Get a list of all available packages (i.e. those not yet installed(.
*
* @return a list of all available packages
* @throws Exception if a problem occurs
*/
public static List<Package> getAvailablePackages() throws Exception {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getAvailablePackages();
}
/**
* Get a list of the most recent version of all available packages (i.e. those
* not yet installed or there is a higher version in the repository) that are
* compatible with the version of Weka that is installed.
*
* @return a list of packages that are compatible with the installed version
* of Weka
* @throws Exception if a problem occurs
*/
public static List<Package> getAvailableCompatiblePackages() throws Exception {
// List<Package> allAvail = getAvailablePackages();
List<Package> allAvail = getAllPackages();
List<Package> compatible = new ArrayList<Package>();
for (Package p : allAvail) {
List<Object> availableVersions =
PACKAGE_MANAGER.getRepositoryPackageVersions(p.getName());
// version numbers will be in descending sorted order from the repository
// we want the most recent version that is compatible with the base weka
// version
for (Object version : availableVersions) {
Package versionedPackage =
getRepositoryPackageInfo(p.getName(), version.toString());
if (versionedPackage.isCompatibleBaseSystem()) {
if (p.isInstalled()) {
// see if the latest compatible version is newer than the installed
// version
Package installed = getInstalledPackageInfo(p.getName());
String installedV =
installed.getPackageMetaDataElement(
VersionPackageConstraint.VERSION_KEY).toString();
String versionedV =
versionedPackage.getPackageMetaDataElement(
VersionPackageConstraint.VERSION_KEY).toString();
VersionPackageConstraint.VersionComparison v =
VersionPackageConstraint.compare(versionedV, installedV);
if (v == VersionPackageConstraint.VersionComparison.GREATERTHAN) {
compatible.add(versionedPackage);
}
} else {
compatible.add(versionedPackage);
}
break;
}
}
}
return compatible;
}
/**
* Get the latest version of the named package that is compatible with the
* base version of Weka being used.
*
* @param packageName the name of the package to get the latest compatible
* version of
* @return the latest compatible version or null if there is no compatible
* package
* @throws Exception if a problem occurs
*/
public static Package getLatestCompatibleVersion(String packageName)
throws Exception {
Package latest = null;
List<Object> availableVersions =
PACKAGE_MANAGER.getRepositoryPackageVersions(packageName);
for (Object version : availableVersions) {
Package versionedPackage =
getRepositoryPackageInfo(packageName, version.toString());
if (versionedPackage.isCompatibleBaseSystem()) {
latest = versionedPackage;
break;
}
}
return latest;
}
/**
* Get a list of installed packages
*
* @return a list of installed packages
* @throws Exception if a problem occurs
*/
public static List<Package> getInstalledPackages() throws Exception {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getInstalledPackages();
}
/**
* Get a list of dependencies for a given package
*
* @param target the package to get the dependencies for
* @param conflicts will hold any conflicts
* @return a list of dependencies for the target package
* @throws Exception if a problem occurs
*/
public static List<Dependency> getAllDependenciesForPackage(Package target,
Map<String, List<Dependency>> conflicts) throws Exception {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getAllDependenciesForPackage(target, conflicts);
}
/**
* Extract meta data from a package archive
*
* @param packageArchivePath the path to the package archive
* @return the meta data for the package
* @throws Exception if a problem occurs
*/
public static Package getPackageArchiveInfo(String packageArchivePath)
throws Exception {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getPackageArchiveInfo(packageArchivePath);
}
/**
* Get meta data for an installed package
*
* @param packageName the name of the package
* @return the meta data for the package
* @throws Exception if a problem occurs
*/
public static Package getInstalledPackageInfo(String packageName)
throws Exception {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getInstalledPackageInfo(packageName);
}
/**
* Get meta data for the latest version of a package from the repository
*
* @param packageName the name of the package
* @return the meta data for the package
* @throws Exception if a problem occurs
*/
public static Package getRepositoryPackageInfo(String packageName)
throws Exception {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getRepositoryPackageInfo(packageName);
}
/**
* Get meta data for a specific version of a package from the repository
*
* @param packageName the name of the package
* @param version the version to get meta data for
* @return the meta data for the package
* @throws Exception if a problem occurs
*/
public static Package getRepositoryPackageInfo(String packageName,
String version) throws Exception {
useCacheOrOnlineRepository();
return PACKAGE_MANAGER.getRepositoryPackageInfo(packageName, version);
}
/**
* Install a named package by retrieving the location of the archive from the
* meta data stored in the repository
*
* @param packageName the name of the package to install
* @param version the version of the package to install
* @param progress for reporting progress
* @return true if the package was installed successfully
* @throws Exception if a problem occurs
*/
public static boolean installPackageFromRepository(String packageName,
String version, PrintStream... progress) throws Exception {
useCacheOrOnlineRepository();
Package toLoad = getRepositoryPackageInfo(packageName);
// check to see if a version is already installed. If so, we
// wont load the updated version into the classpath immediately in
// order to avoid conflicts, class not found exceptions etc. The
// user is told to restart Weka for the changes to come into affect
// anyway, so there is no point in loading the updated package now.
boolean isAnUpgrade = toLoad.isInstalled();
Object specialInstallMessage =
toLoad.getPackageMetaDataElement(MESSAGE_TO_DISPLAY_ON_INSTALLATION_KEY);
if (specialInstallMessage != null
&& specialInstallMessage.toString().length() > 0) {
String siM = specialInstallMessage.toString();
try {
siM = Environment.getSystemWide().substitute(siM);
} catch (Exception ex) {
// quietly ignore
}
String message =
"**** Special installation message ****\n" + siM
+ "\n**** Special installation message ****";
for (PrintStream p : progress) {
p.println(message);
}
}
PACKAGE_MANAGER
.installPackageFromRepository(packageName, version, progress);
File packageDir =
new File(PACKAGE_MANAGER.getPackageHome().toString() + File.separator
+ packageName);
if (loadCheck(getInstalledPackageInfo(packageName), packageDir, progress)) {
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.addPackageToClassLoader(packageDir);
}
Map<String, List<String>> injectDependencies = new HashMap<>();
checkForInjectDependencies(toLoad, injectDependencies);
// inject dependencies before triggering any class discovery
injectPackageDependencies(injectDependencies);
// check that all dependencies are available, there are no missing classes
// and files etc.
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.performIntegrityCheck();
// If the classloader for the package is still in play then
// process all props files
if (WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.getPackageClassLoader(packageName) != null) {
processPackageDirectory(packageDir, false, null, false);
}
return isAnUpgrade;
}
/**
* Install a package from an archive (unofficial package install route)
*
* @param packageArchivePath the path to the package archive file to install
* @param progress for reporting progress
* @return true if the package was installed successfully
* @throws Exception if a problem occurs
*/
public static String installPackageFromArchive(String packageArchivePath,
PrintStream... progress) throws Exception {
useCacheOrOnlineRepository();
Package toInstall =
PACKAGE_MANAGER.getPackageArchiveInfo(packageArchivePath);
Object specialInstallMessage =
toInstall
.getPackageMetaDataElement(MESSAGE_TO_DISPLAY_ON_INSTALLATION_KEY);
if (specialInstallMessage != null
&& specialInstallMessage.toString().length() > 0) {
String siM = specialInstallMessage.toString();
try {
siM = Environment.getSystemWide().substitute(siM);
} catch (Exception ex) {
// quietly ignore
}
String message =
"**** Special installation message ****\n" + siM
+ "\n**** Special installation message ****";
for (PrintStream p : progress) {
p.println(message);
}
}
PACKAGE_MANAGER.installPackageFromArchive(packageArchivePath, progress);
return initializeAndLoadUnofficialPackage(toInstall, progress);
}
private static String initializeAndLoadUnofficialPackage(Package toInstall,
PrintStream... progress) throws Exception {
File packageDir =
new File(PACKAGE_MANAGER.getPackageHome() + File.separator
+ toInstall.getName());
Package toLoad = getInstalledPackageInfo(toInstall.getName());
// no load check here as those checks involve the central repository (and
// this is an unofficial package)
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.addPackageToClassLoader(packageDir);
Map<String, List<String>> injectDependencies = new HashMap<>();
checkForInjectDependencies(toLoad, injectDependencies);
// inject dependencies before triggering any class discovery
injectPackageDependencies(injectDependencies);
// check that all dependencies are available, there are no missing classes
// and files etc.
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.performIntegrityCheck();
// If the classloader for the package is still in play then
// process all props files
if (WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.getPackageClassLoader(toInstall.getName()) != null) {
processPackageDirectory(packageDir, false, null, false);
}
return toInstall.getName();
}
/**
* Install a package from the supplied URL
*
* @param packageURL the URL to the package archive to install
* @param progress for reporting progress
* @return true if the package was installed successfully
* @throws Exception if a problem occurs
*/
public static String installPackageFromURL(URL packageURL,
PrintStream... progress) throws Exception {
useCacheOrOnlineRepository();
String packageName =
PACKAGE_MANAGER.installPackageFromURL(packageURL, progress);
Package installed = PACKAGE_MANAGER.getInstalledPackageInfo(packageName);
Object specialInstallMessage =
installed
.getPackageMetaDataElement(MESSAGE_TO_DISPLAY_ON_INSTALLATION_KEY);
if (specialInstallMessage != null
&& specialInstallMessage.toString().length() > 0) {
String message =
"**** Special installation message ****\n"
+ specialInstallMessage.toString()
+ "\n**** Special installation message ****";
for (PrintStream p : progress) {
p.println(message);
}
}
return initializeAndLoadUnofficialPackage(installed, progress);
}
/**
* Uninstall a named package
*
* @param packageName the name of the package to remove
* @param updateKnowledgeFlow true if any Knowledge Flow beans provided by the
* package should be deregistered from the KnoweledgeFlow
* @param progress for reporting progress
* @throws Exception if a problem occurs
*/
public static void uninstallPackage(String packageName,
boolean updateKnowledgeFlow, PrintStream... progress) throws Exception {
// check to see if this is a KnowledgeFlow package (presence of Beans.props
// file)
if (updateKnowledgeFlow) {
File packageToDel =
new File(PACKAGE_MANAGER.getPackageHome().toString() + File.separator
+ packageName);
if (packageToDel.exists() && packageToDel.isDirectory()) {
File[] contents = packageToDel.listFiles();
if (contents != null) {
for (File content : contents) {
if (content.isFile() && content.getPath().endsWith("Beans.props")) {
// KnowledgeFlow plugin -- remove this properties file from the
// list
// of
// bean plugin props
KnowledgeFlowApp.removeFromPluginBeanProps(content);
KnowledgeFlowApp.disposeSingleton();
break;
}
}
}
WekaPackageClassLoaderManager.getWekaPackageClassLoaderManager()
.removeClassLoaderForPackage(packageName);
}
}
PACKAGE_MANAGER.uninstallPackage(packageName, progress);
}
private static void printPackageInfo(Map<?, ?> packageProps) {
Set<?> keys = packageProps.keySet();
Iterator<?> i = keys.iterator();
while (i.hasNext()) {
Object key = i.next();
Object value = packageProps.get(key);
System.out.println(Utils.padLeft(key.toString(), 11) + ":\t"
+ value.toString());
}
}
/**
* Print meta data on a package
*
* @param packagePath the path to the package to print meta data for
* @throws Exception if a problem occurs
*/
protected static void printPackageArchiveInfo(String packagePath)
throws Exception {
Map<?, ?> packageProps =
getPackageArchiveInfo(packagePath).getPackageMetaData();
printPackageInfo(packageProps);
}
/**
* Print meta data for an installed package
*
* @param packageName the name of the package to print meta data for
* @throws Exception if a problem occurs
*/
protected static void printInstalledPackageInfo(String packageName)
throws Exception {
Map<?, ?> packageProps =
getInstalledPackageInfo(packageName).getPackageMetaData();
printPackageInfo(packageProps);
}
/**
* Print meta data for a package listed in the repository
*
* @param packageName the name of the package to print meta data for
* @param version the version of the package
* @throws Exception if a problem occurs
*/
protected static void printRepositoryPackageInfo(String packageName,
String version) throws Exception {
Map<?, ?> packageProps =
getRepositoryPackageInfo(packageName, version).getPackageMetaData();
printPackageInfo(packageProps);
}
private static String queryUser() {
java.io.BufferedReader br =
new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
String result = null;
try {
result = br.readLine();
} catch (java.io.IOException ex) {
// ignore
}
return result;
}
private static void removeInstalledPackage(String packageName, boolean force,
PrintStream... progress) throws Exception {
List<Package> compromised = new ArrayList<Package>();
// Now check to see which other installed packages depend on this one
List<Package> installedPackages = null;
if (!force) {
installedPackages = getInstalledPackages();
for (Package p : installedPackages) {
List<Dependency> tempDeps = p.getDependencies();
for (Dependency d : tempDeps) {
if (d.getTarget().getPackage().getName().equals(packageName)) {
// add this installed package to the list
compromised.add(p);
break;
}
}
}
if (compromised.size() > 0) {
System.out.println("The following installed packages depend on "
+ packageName + " :\n");
for (Package p : compromised) {
System.out.println("\t" + p.getName());
}
System.out.println("\nDo you wish to proceed [y/n]?");
String response = queryUser();
if (response != null
&& (response.equalsIgnoreCase("n") || response.equalsIgnoreCase("no"))) {
return; // bail out here
}
}
}
if (force) {
System.out.println("Forced uninstall.");
}
compromised = null;
installedPackages = null;
uninstallPackage(packageName, false, progress);
}
private static void installPackageFromRepository(String packageName,
String version, boolean force) throws Exception {
if (version.equals("Latest")) {
// if no version/latest has been specified by the user then
// look for the latest version of the package that is compatible
// with the installed version of Weka.
version = "none";
List<Object> availableVersions =
PACKAGE_MANAGER.getRepositoryPackageVersions(packageName);
// version numbers will be in descending sorted order from the
// repository. We want the most recent version that is compatible
// with the base weka install
for (Object v : availableVersions) {
Package versionedPackage =
getRepositoryPackageInfo(packageName, v.toString());
if (versionedPackage.isCompatibleBaseSystem()) {
version =
versionedPackage.getPackageMetaDataElement(
VersionPackageConstraint.VERSION_KEY).toString();
break;
}
}
if (version.equals("none")) {
throw new Exception("Was unable to find a version of '" + packageName
+ "' that is compatible with Weka " + Version.VERSION);
}
}
Package toInstall = null;
try {
toInstall = getRepositoryPackageInfo(packageName, version);
} catch (Exception ex) {
System.err.println("[WekaPackageManager] Package " + packageName
+ " at version " + version + " doesn't seem to exist!");
// System.exit(1);
return;
}
// First check to see if this package is compatible with the base system
if (!force) {
// check to see if it's disabled
Object disabled = toInstall.getPackageMetaDataElement(DISABLE_KEY);
if (disabled == null) {
disabled = toInstall.getPackageMetaDataElement(DISABLED_KEY);
}
if (disabled != null && disabled.toString().equalsIgnoreCase("true")) {
System.err.println("Can't install package " + packageName
+ " because it " + "has been disabled at the repository.");
return;
}
boolean ok = toInstall.isCompatibleBaseSystem();
if (!ok) {
List<Dependency> baseSysDep = toInstall.getBaseSystemDependency();
StringBuffer depList = new StringBuffer();
for (Dependency bd : baseSysDep) {
depList.append(bd.getTarget().toString() + " ");
}
System.err.println("Can't install package " + packageName
+ " because it requires " + depList.toString());
return;
}
if (!osAndArchCheck(toInstall, System.out)) {
return; // bail out here
}
if (toInstall.isInstalled()) {
Package installedVersion = getInstalledPackageInfo(packageName);
if (!toInstall.equals(installedVersion)) {
System.out.println("Package " + packageName + "[" + installedVersion
+ "] is already installed. Replace with " + toInstall + " [y/n]?");
String response = queryUser();
if (response != null
&& (response.equalsIgnoreCase("n") || response
.equalsIgnoreCase("no"))) {
return; // bail out here
}
} else {
System.out.println("Package " + packageName + "[" + installedVersion
+ "] is already installed. Install again [y/n]?");
String response = queryUser();
if (response != null
&& (response.equalsIgnoreCase("n") || response
.equalsIgnoreCase("no"))) {
return; // bail out here
}
}
}
// Now get a full list of dependencies for this package and
// check for any conflicts
Map<String, List<Dependency>> conflicts =
new HashMap<String, List<Dependency>>();
List<Dependency> dependencies =
getAllDependenciesForPackage(toInstall, conflicts);
if (conflicts.size() > 0) {
System.err.println("Package " + packageName
+ " requires the following packages:\n");
Iterator<Dependency> depI = dependencies.iterator();
while (depI.hasNext()) {
Dependency d = depI.next();
System.err.println("\t" + d);
}
System.err.println("\nThere are conflicting dependencies:\n");
Set<String> pNames = conflicts.keySet();
Iterator<String> pNameI = pNames.iterator();
while (pNameI.hasNext()) {
String pName = pNameI.next();
System.err.println("Conflicts for " + pName);
List<Dependency> confsForPackage = conflicts.get(pName);
Iterator<Dependency> confs = confsForPackage.iterator();
while (confs.hasNext()) {
Dependency problem = confs.next();
System.err.println("\t" + problem);
}
}
System.err.println("Unable to continue with installation.");
return; // bail out here.
}
// Next check all dependencies against what is installed and
// inform the user about which installed packages will be altered. Also
// build the list of only those packages that need to be installed or
// upgraded (excluding those that are already installed and are OK).
List<PackageConstraint> needsUpgrade = new ArrayList<PackageConstraint>();
List<Package> finalListToInstall = new ArrayList<Package>();
Iterator<Dependency> depI = dependencies.iterator();
while (depI.hasNext()) {
Dependency toCheck = depI.next();
if (toCheck.getTarget().getPackage().isInstalled()) {
String toCheckName =
toCheck.getTarget().getPackage()
.getPackageMetaDataElement("PackageName").toString();
Package installedVersion =
PACKAGE_MANAGER.getInstalledPackageInfo(toCheckName);
if (!toCheck.getTarget().checkConstraint(installedVersion)) {
needsUpgrade.add(toCheck.getTarget());
Package mostRecent = toCheck.getTarget().getPackage();
if (toCheck.getTarget() instanceof weka.core.packageManagement.VersionPackageConstraint) {
mostRecent =
WekaPackageManager
.mostRecentVersionWithRespectToConstraint(toCheck.getTarget());
}
finalListToInstall.add(mostRecent);
}
} else {
Package mostRecent = toCheck.getTarget().getPackage();
if (toCheck.getTarget() instanceof weka.core.packageManagement.VersionPackageConstraint) {
mostRecent =
WekaPackageManager
.mostRecentVersionWithRespectToConstraint(toCheck.getTarget());
}
finalListToInstall.add(mostRecent);
}
}
// now check for precludes - first add compile all installed packages and
// then potentially overwrite with what's in the finalListToInstall
if (toInstall.getPackageMetaDataElement(PRECLUDES_KEY) != null) {
List<Package> installed = getInstalledPackages();
Map<String, Package> packageMap = new HashMap<>();
for (Package p : installed) {
packageMap.put(p.getName(), p);
}
for (Package p : finalListToInstall) {
packageMap.put(p.getName(), p);
}
List<Package> precluded =
toInstall.getPrecludedPackages(new ArrayList<Package>(packageMap
.values()));
if (precluded.size() > 0) {
List<Package> finalPrecluded = new ArrayList<>();
Set<String> doNotLoadList = getDoNotLoadList();
for (Package p : precluded) {
if (!doNotLoadList.contains(p.getName())) {
finalPrecluded.add(p);
}
}
if (finalPrecluded.size() > 0) {
System.out.println("\nPackage " + toInstall.getName()
+ " cannot be "
+ "installed because it precludes the following packages:\n");
for (Package p : finalPrecluded) {
System.out.println("\n\t" + p.toString());
}
System.out
.println("Either uninstall or disable these packages before "
+ "continuing.");
return; // bail out here
}
}
}
if (needsUpgrade.size() > 0) {
System.out
.println("The following packages will be upgraded in order to install "
+ packageName);
Iterator<PackageConstraint> upI = needsUpgrade.iterator();
while (upI.hasNext()) {
PackageConstraint tempC = upI.next();
System.out.println("\t" + tempC);
}
System.out.print("\nOK to continue [y/n]? > ");
String response = queryUser();
if (response != null
&& (response.equalsIgnoreCase("n") || response.equalsIgnoreCase("no"))) {
return; // bail out here
}
// now take a look at the other installed packages and see if
// any would have a problem when these ones are upgraded
boolean conflictsAfterUpgrade = false;
List<Package> installed = getInstalledPackages();
List<Package> toUpgrade = new ArrayList<Package>();
upI = needsUpgrade.iterator();
while (upI.hasNext()) {
toUpgrade.add(upI.next().getPackage());
}
// add the actual package the user is wanting to install if it
// is going to be an up/downgrade rather than a first install since
// other installed packages may depend on the currently installed
// version
// and thus could be affected after the up/downgrade
toUpgrade.add(toInstall);
for (int i = 0; i < installed.size(); i++) {
Package tempP = installed.get(i);
String tempPName = tempP.getName();
boolean checkIt = true;
for (int j = 0; j < needsUpgrade.size(); j++) {
if (tempPName.equals(needsUpgrade.get(j).getPackage().getName())) {
checkIt = false;
break;
}
}
if (checkIt) {
List<Dependency> problem =
tempP.getIncompatibleDependencies(toUpgrade);
if (problem.size() > 0) {
conflictsAfterUpgrade = true;
System.err.println("Package " + tempP.getName()
+ " will have a compatibility"
+ "problem with the following packages after upgrading them:");
Iterator<Dependency> dI = problem.iterator();
while (dI.hasNext()) {
System.err.println("\t" + dI.next().getTarget().getPackage());
}
}
}
}
if (conflictsAfterUpgrade) {
System.err.println("Unable to continue with installation.");
return; // bail out here
}
}
if (finalListToInstall.size() > 0) {
System.out.println("To install " + packageName
+ " the following packages will" + " be installed/upgraded:\n\n");
Iterator<Package> i = finalListToInstall.iterator();
while (i.hasNext()) {
System.out.println("\t" + i.next());
}
System.out.print("\nOK to proceed [y/n]? > ");
String response = queryUser();
if (response != null
&& (response.equalsIgnoreCase("n") || response.equalsIgnoreCase("no"))) {
return; // bail out here
}
}
// OK, now we can download and install everything
// First install the final list of dependencies
installPackages(finalListToInstall, System.out);
// Now install the package itself
installPackageFromRepository(packageName, version, System.out);
} else {
// just install this package without checking/downloading dependencies
// etc.
installPackageFromRepository(packageName, version, System.out);
}
}
private static void listPackages(String arg) throws Exception {
if (m_offline
&& (arg.equalsIgnoreCase("all") || arg.equalsIgnoreCase("available"))) {
System.out.println("Running offline - unable to display "
+ "available or all package information");
return;
}
List<Package> packageList = null;
useCacheOrOnlineRepository();
if (arg.equalsIgnoreCase("all")) {
packageList = PACKAGE_MANAGER.getAllPackages();
} else if (arg.equals("installed")) {
packageList = PACKAGE_MANAGER.getInstalledPackages();
} else if (arg.equals("available")) {
// packageList = PACKAGE_MANAGER.getAvailablePackages();
packageList = getAvailableCompatiblePackages();
} else {
System.err.println("[WekaPackageManager] Unknown argument " + arg);
printUsage();
// System.exit(1);
return;
}
StringBuffer result = new StringBuffer();
result.append("Installed\tRepository\tLoaded\tPackage\n");
result.append("=========\t==========\t======\t=======\n");
boolean userOptedNoLoad = false;
Iterator<Package> i = packageList.iterator();
while (i.hasNext()) {
Package p = i.next();
String installedV = "----- ";
String repositoryV = "----- ";
String loaded = "No";
if (p.isInstalled()) {
Package installedP = getInstalledPackageInfo(p.getName());
if (loadCheck(installedP, new File(WekaPackageManager.getPackageHome()
.toString() + File.separator + p.getName()))) {
loaded = "Yes";
} else {
if (m_doNotLoadList.contains(installedP.getName())) {
loaded = "No*";
userOptedNoLoad = true;
}
}
installedV =
installedP.getPackageMetaDataElement(VERSION_KEY).toString() + " ";
try {
if (!m_offline) {
Package repP = getRepositoryPackageInfo(p.getName());
repositoryV =
repP.getPackageMetaDataElement(VERSION_KEY).toString() + " ";
}
} catch (Exception ex) {
// not at the repository
}
} else {
repositoryV =
p.getPackageMetaDataElement(VERSION_KEY).toString() + " ";
}
String title = p.getPackageMetaDataElement("Title").toString();
result.append(installedV + "\t" + repositoryV + "\t" + loaded + "\t"
+ p.getName() + ": " + title + "\n");
}
if (userOptedNoLoad) {
result.append("* User flagged as no load\n");
}
System.out.println(result.toString());
}
private static void printUsage() {
System.out
.println("Usage: weka.core.WekaPackageManager [-offline] [option]");
System.out
.println("Options:\n"
+ "\t-list-packages <all | installed | available>\n"
+ "\t-package-info <repository | installed | archive> "
+ "<packageName | packageZip>\n\t-install-package <packageName | packageZip | URL> [version]\n"
+ "\t-uninstall-package packageName\n"
+ "\t-toggle-load-status packageName [packageName packageName ...]\n"
+ "\t-refresh-cache");
}
/**
* Main method for using the package manager from the command line
*
* @param args command line arguments
*/
public static void main(String[] args) {
weka.core.logging.Logger.log(weka.core.logging.Logger.Level.INFO,
"Logging started");
try {
// scan for -offline
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-offline")) {
m_offline = true;
String[] temp = new String[args.length - 1];
if (i > 0) {
System.arraycopy(args, 0, temp, 0, i);
}
System.arraycopy(args, i + 1, temp, i, args.length - (i + 1));
args = temp;
}
}
establishCacheIfNeeded(System.out);
checkForNewPackages(System.out);
if (args.length == 0 || args[0].equalsIgnoreCase("-h")
|| args[0].equalsIgnoreCase("-help")) {
printUsage();
// System.exit(1);
return;
}
if (args[0].equals("-package-info")) {
if (args.length < 3) {
printUsage();
return;
// System.exit(1);
}
if (args[1].equals("archive")) {
printPackageArchiveInfo(args[2]);
} else if (args[1].equals("installed")) {
printInstalledPackageInfo(args[2]);
} else if (args[1].equals("repository")) {
String version = "Latest";
if (args.length == 4) {
version = args[3];
}
try {
printRepositoryPackageInfo(args[2], version);
} catch (Exception ex) {
// problem with getting info on package from repository?
// Must not be an "official" repository package
System.out
.println("[WekaPackageManager] Nothing known about package "
+ args[2] + " at the repository!");
}
} else {
System.err
.println("[WekaPackageManager] Unknown argument " + args[2]);
printUsage();
return;
// System.exit(1);
}
} else if (args[0].equals("-install-package")) {
String targetLowerCase = args[1].toLowerCase();
if (targetLowerCase.startsWith("http://")
|| targetLowerCase.startsWith("https://")) {
URL packageURL = new URL(args[1]);
installPackageFromURL(packageURL, System.out);
} else if (targetLowerCase.endsWith(".zip")) {
installPackageFromArchive(args[1], System.out);
} else {
// assume a named package at the central repository
String version = "Latest";
if (args.length == 3) {
version = args[2];
}
installPackageFromRepository(args[1], version, false);
}
System.exit(0);
} else if (args[0].equals("-uninstall-package")) {
if (args.length < 2) {
printUsage();
return;
// System.exit(1);
}
boolean force = false;
if (args.length == 3) {
if (args[2].equals("-force")) {
force = true;
}
}
removeInstalledPackage(args[1], force, System.out);
// System.exit(0);
return;
} else if (args[0].equals("-list-packages")) {
if (args.length < 2) {
printUsage();
// System.exit(1);
return;
}
listPackages(args[1]);
} else if (args[0].equals("-toggle-load-status")) {
if (args.length == 1) {
printUsage();
return;
}
List<String> toToggle = new ArrayList<String>();
for (int i = 1; i < args.length; i++) {
toToggle.add(args[i].trim());
}
if (toToggle.size() >= 1) {
toggleLoadStatus(toToggle);
}
} else if (args[0].equals("-refresh-cache")) {
refreshCache(System.out);
} else {
System.err.println("Unknown option: " + args[0]);
printUsage();
}
// System.exit(0);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/AbstractFileLoader.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* AbstractFileLoader.java
* Copyright (C) 2006-2012 University of Waikato, Hamilton, New Zealand
*/
package weka.core.converters;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.GZIPInputStream;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Utils;
/**
* Abstract superclass for all file loaders.
*
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public abstract class AbstractFileLoader extends AbstractLoader implements
FileSourcedConverter, EnvironmentHandler {
/* ID to avoid warning */
private static final long serialVersionUID = 5535537461920594758L;
/** the file */
protected String m_File = (new File(System.getProperty("user.dir")))
.getAbsolutePath();
/** Holds the determined structure (header) of the data set. */
protected transient Instances m_structure = null;
/** Holds the source of the data set. */
protected File m_sourceFile = null;
/** the extension for compressed files */
public static String FILE_EXTENSION_COMPRESSED = ".gz";
/** use relative file paths */
protected boolean m_useRelativePath = false;
/** Environment variables */
protected transient Environment m_env;
/**
* get the File specified as the source
*
* @return the source file
*/
@Override
public File retrieveFile() {
return new File(m_File);
}
/**
* sets the source File
*
* @param file the source file
* @exception IOException if an error occurs
*/
@Override
public void setFile(File file) throws IOException {
m_structure = null;
setRetrieval(NONE);
// m_File = file.getAbsolutePath();
setSource(file);
}
/**
* Set the environment variables to use.
*
* @param env the environment variables to use
*/
@Override
public void setEnvironment(Environment env) {
m_env = env;
try {
// causes setSource(File) to be called and
// forces the input stream to be reset with a new file
// that has environment variables resolved with those
// in the new Environment object
reset();
} catch (IOException ex) {
// we won't complain about it here...
}
}
/**
* Resets the loader ready to read a new data set
*
* @throws IOException if something goes wrong
*/
@Override
public void reset() throws IOException {
m_structure = null;
setRetrieval(NONE);
}
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied File object.
*
* @param file the source file.
* @throws IOException if an error occurs
*/
@Override
public void setSource(File file) throws IOException {
File original = file;
m_structure = null;
setRetrieval(NONE);
if (file == null) {
throw new IOException("Source file object is null!");
}
// try {
String fName = file.getPath();
try {
if (m_env == null) {
m_env = Environment.getSystemWide();
}
fName = m_env.substitute(fName);
} catch (Exception e) {
// ignore any missing environment variables at this time
// as it is possible that these may be set by the time
// the actual file is processed
// throw new IOException(e.getMessage());
}
file = new File(fName);
// set the source only if the file exists
if (file.exists() && file.isFile()) {
if (file.getName().endsWith(
getFileExtension() + FILE_EXTENSION_COMPRESSED)) {
setSource(new GZIPInputStream(new FileInputStream(file)));
} else {
setSource(new FileInputStream(file));
}
} else {
// System.out.println("Looking in classpath....");
// look for it as a resource in the classpath
// forward slashes are platform independent for loading from the
// classpath...
String fnameWithCorrectSeparators = fName
.replace(File.separatorChar, '/');
if (this.getClass().getClassLoader()
.getResource(fnameWithCorrectSeparators) != null) {
// System.out.println("Found resource in classpath...");
setSource(this.getClass().getClassLoader()
.getResourceAsStream(fnameWithCorrectSeparators));
}
}
// }
/*
* catch (FileNotFoundException ex) { throw new
* IOException("File not found"); }
*/
if (m_useRelativePath) {
try {
m_sourceFile = Utils.convertToRelativePath(original);
m_File = m_sourceFile.getPath();
} catch (Exception ex) {
// System.err.println("[AbstractFileLoader] can't convert path to relative path.");
m_sourceFile = original;
m_File = m_sourceFile.getPath();
}
} else {
m_sourceFile = original;
m_File = m_sourceFile.getPath();
}
}
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied File object.
*
* @param file the source file.
* @exception IOException if an error occurs
*
* public void setSource(File file) throws IOException {
* m_structure = null; setRetrieval(NONE);
*
* if (file == null) { throw new
* IOException("Source file object is null!"); }
*
* try { setSource(new FileInputStream(file)); } catch
* (FileNotFoundException ex) { throw new
* IOException("File not found"); }
*
* m_sourceFile = file; m_File = file.getAbsolutePath(); }
*/
/**
* Tip text suitable for displaying int the GUI
*
* @return a description of this property as a String
*/
public String useRelativePathTipText() {
return "Use relative rather than absolute paths";
}
/**
* Set whether to use relative rather than absolute paths
*
* @param rp true if relative paths are to be used
*/
@Override
public void setUseRelativePath(boolean rp) {
m_useRelativePath = rp;
}
/**
* Gets whether relative paths are to be used
*
* @return true if relative paths are to be used
*/
@Override
public boolean getUseRelativePath() {
return m_useRelativePath;
}
/**
* generates a string suitable for output on the command line displaying all
* available options (currently only a simple usage).
*
* @param loader the loader to create the option string for
* @return the option string
*/
protected static String makeOptionStr(AbstractFileLoader loader) {
StringBuffer result;
Option option;
result = new StringBuffer("\nUsage:\n");
result.append("\t" + loader.getClass().getName().replaceAll(".*\\.", ""));
result.append(" <");
String[] ext = loader.getFileExtensions();
for (int i = 0; i < ext.length; i++) {
if (i > 0) {
result.append(" | ");
}
result.append("file" + ext[i]);
}
result.append(">");
if (loader instanceof OptionHandler) {
result.append(" [options]");
}
result.append("\n");
if (loader instanceof OptionHandler) {
result.append("\nOptions:\n\n");
Enumeration<Option> enm = ((OptionHandler) loader).listOptions();
while (enm.hasMoreElements()) {
option = enm.nextElement();
result.append(option.synopsis() + "\n");
result.append(option.description() + "\n");
}
}
return result.toString();
}
/**
* runs the given loader with the provided options
*
* @param loader the loader to run
* @param options the commandline options, first argument must be the file to
* load
*/
public static void runFileLoader(AbstractFileLoader loader, String[] options) {
// help request?
try {
String[] tmpOptions = options.clone();
if (Utils.getFlag('h', tmpOptions)) {
System.err.println("\nHelp requested\n" + makeOptionStr(loader));
return;
}
} catch (Exception e) {
// ignore it
}
if (options.length > 0) {
String fileName = options[0];
options[0] = "";
if (loader instanceof OptionHandler) {
// set options
try {
((OptionHandler) loader).setOptions(options);
// find file
for (int i = 0; i < options.length; i++) {
if (options[i].length() > 0) {
options = new String[] { options[i] };
break;
}
}
} catch (Exception ex) {
System.err.println(makeOptionStr(loader));
System.exit(1);
}
}
try {
loader.setFile(new File(fileName));
// incremental
if (loader instanceof IncrementalConverter) {
Instances structure = loader.getStructure();
System.out.println(structure);
Instance temp;
do {
temp = loader.getNextInstance(structure);
if (temp != null) {
System.out.println(temp);
}
} while (temp != null);
}
// batch
else {
System.out.println(loader.getDataSet());
}
} catch (Exception ex) {
ex.printStackTrace();
}
} else {
System.err.println(makeOptionStr(loader));
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/AbstractFileSaver.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* AbstractFileSaver.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Utils;
/**
* Abstract class for Savers that save to a file
*
* Valid options are:
*
* -i input arff file <br>
* The input filw in arff format.
* <p>
*
* -o the output file <br>
* The output file. The prefix of the output file is sufficient. If no output
* file is given, Saver tries to use standard out.
* <p>
*
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
*/
public abstract class AbstractFileSaver extends AbstractSaver implements
OptionHandler, FileSourcedConverter, EnvironmentHandler {
/** ID to avoid warning */
private static final long serialVersionUID = 2399441762235754491L;
/** The destination file. */
private File m_outputFile;
/** The writer. */
private transient BufferedWriter m_writer;
/** The file extension of the destination file. */
private String FILE_EXTENSION;
/** the extension for compressed files */
private final String FILE_EXTENSION_COMPRESSED = ".gz";
/** The prefix for the filename (chosen in the GUI). */
private String m_prefix;
/** The directory of the file (chosen in the GUI). */
private String m_dir;
/**
* Counter. In incremental mode after reading 100 instances they will be
* written to a file.
*/
protected int m_incrementalCounter;
/** use relative file paths */
protected boolean m_useRelativePath = false;
/** Environment variables */
protected transient Environment m_env;
/**
* resets the options
*
*/
@Override
public void resetOptions() {
super.resetOptions();
m_outputFile = null;
m_writer = null;
m_prefix = "";
m_dir = "";
m_incrementalCounter = 0;
}
/**
* Gets the writer
*
* @return the BufferedWriter
*/
public BufferedWriter getWriter() {
return m_writer;
}
/** Sets the writer to null. */
public void resetWriter() {
m_writer = null;
}
/**
* Gets ihe file extension.
*
* @return the file extension as a string.
*/
@Override
public String getFileExtension() {
return FILE_EXTENSION;
}
/**
* Gets all the file extensions used for this type of file
*
* @return the file extensions
*/
@Override
public String[] getFileExtensions() {
return new String[] { getFileExtension() };
}
/**
* Sets ihe file extension.
*
* @param ext the file extension as a string startin with '.'.
*/
protected void setFileExtension(String ext) {
FILE_EXTENSION = ext;
}
/**
* Gets the destination file.
*
* @return the destination file.
*/
@Override
public File retrieveFile() {
return m_outputFile;
}
/**
* Sets the destination file.
*
* @param outputFile the destination file.
* @throws IOException throws an IOException if file cannot be set
*/
@Override
public void setFile(File outputFile) throws IOException {
m_outputFile = outputFile;
setDestination(outputFile);
}
/**
* Sets the file name prefix
*
* @param prefix the file name prefix
*/
@Override
public void setFilePrefix(String prefix) {
m_prefix = prefix;
}
/**
* Gets the file name prefix
*
* @return the prefix of the filename
*/
@Override
public String filePrefix() {
return m_prefix;
}
/**
* Sets the directory where the instances should be stored
*
* @param dir a string containing the directory path and name
*/
@Override
public void setDir(String dir) {
m_dir = dir;
}
/**
* Gets the directory
*
* @return a string with the file name
*/
@Override
public String retrieveDir() {
return m_dir;
}
/**
* Set the environment variables to use.
*
* @param env the environment variables to use
*/
@Override
public void setEnvironment(Environment env) {
m_env = env;
if (m_outputFile != null) {
try {
// try and resolve any new environment variables
setFile(m_outputFile);
} catch (IOException ex) {
// we won't complain about it here...
}
}
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector =
Option.listOptionsForClassHierarchy(this.getClass(),
AbstractFileSaver.class);
// Vector<Option> newVector = new Vector<Option>();
newVector.addElement(new Option("\tThe input file", "i", 1,
"-i <the input file>"));
newVector.addElement(new Option("\tThe output file", "o", 1,
"-o <the output file>"));
return newVector.elements();
}
/**
* Parses a given list of options. Valid option is:
* <p>
*
* -i input arff file <br>
* The input filw in arff format.
* <p>
*
* -o the output file <br>
* The output file. The prefix of the output file is sufficient. If no output
* file is given, Saver tries to use standard out.
* <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 {
Option.setOptionsForHierarchy(options, this, AbstractFileSaver.class);
String outputString = Utils.getOption('o', options);
String inputString = Utils.getOption('i', options);
ArffLoader loader = new ArffLoader();
resetOptions();
if (inputString.length() != 0) {
try {
File input = new File(inputString);
loader.setFile(input);
setInstances(loader.getDataSet());
} catch (Exception ex) {
ex.printStackTrace();
throw new IOException(
"No data set loaded. Data set has to be in ARFF format.");
}
}
if (outputString.length() != 0) {
boolean validExt = false;
for (String ext : getFileExtensions()) {
if (outputString.endsWith(ext)) {
validExt = true;
break;
}
}
// add appropriate file extension
if (!validExt) {
if (outputString.lastIndexOf('.') != -1) {
outputString =
(outputString.substring(0, outputString.lastIndexOf('.')))
+ FILE_EXTENSION;
} else {
outputString = outputString + FILE_EXTENSION;
}
}
try {
File output = new File(outputString);
setFile(output);
} catch (Exception ex) {
throw new IOException("Cannot create output file (Reason: "
+ ex.toString() + "). Standard out is used.");
}
}
}
/**
* Gets the current settings of the Saver object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result;
result = new Vector<String>();
for (String s : Option
.getOptionsForHierarchy(this, AbstractFileSaver.class)) {
result.add(s);
}
if (m_outputFile != null) {
result.add("-o");
result.add("" + m_outputFile);
}
if (getInstances() != null) {
result.add("-i");
result.add("" + getInstances().relationName());
}
return result.toArray(new String[result.size()]);
}
/** Cancels the incremental saving process. */
@Override
public void cancel() {
if (getWriteMode() == CANCEL) {
if (m_outputFile != null && m_outputFile.exists()) {
if (m_outputFile.delete()) {
System.out.println("File deleted.");
}
}
resetOptions();
}
}
/**
* Sets the destination file (and directories if necessary).
*
* @param file the File
* @exception IOException always
*/
@Override
public void setDestination(File file) throws IOException {
boolean success = false;
String tempOut = file.getPath();
try {
if (m_env == null) {
m_env = Environment.getSystemWide();
}
tempOut = m_env.substitute(tempOut);
} catch (Exception ex) {
// don't complain about it here...
// throw new IOException("[AbstractFileSaver]: " + ex.getMessage());
}
file = new File(tempOut);
String out = file.getAbsolutePath();
if (m_outputFile != null) {
try {
if (file.exists()) {
if (!file.delete()) {
throw new IOException("File already exists.");
}
}
if (out.lastIndexOf(File.separatorChar) == -1) {
success = file.createNewFile();
} else {
String outPath =
out.substring(0, out.lastIndexOf(File.separatorChar));
File dir = new File(outPath);
if (dir.exists()) {
success = file.createNewFile();
} else {
dir.mkdirs();
success = file.createNewFile();
}
}
if (success) {
if (m_useRelativePath) {
try {
m_outputFile = Utils.convertToRelativePath(file);
} catch (Exception e) {
m_outputFile = file;
}
} else {
m_outputFile = file;
}
setDestination(new FileOutputStream(m_outputFile));
}
} catch (Exception ex) {
throw new IOException("Cannot create a new output file (Reason: "
+ ex.toString() + "). Standard out is used.");
} finally {
if (!success) {
System.err
.println("Cannot create a new output file. Standard out is used.");
m_outputFile = null; // use standard out
}
}
}
}
/**
* Sets the destination output stream.
*
* @param output the output stream.
* @throws IOException throws an IOException if destination cannot be set
*/
@Override
public void setDestination(OutputStream output) throws IOException {
m_writer = new BufferedWriter(new OutputStreamWriter(output));
}
/**
* Sets the directory and the file prefix. This method is used in the
* KnowledgeFlow GUI
*
* @param relationName the name of the relation to save
* @param add additional string which should be part of the filename
*/
@Override
public void setDirAndPrefix(String relationName, String add) {
try {
if (m_dir.equals("")) {
setDir(System.getProperty("user.dir"));
}
if (m_prefix.equals("")) {
if (relationName.length() == 0) {
throw new IOException("[Saver] Empty filename!!");
}
String concat =
(m_dir + File.separator + relationName + add + FILE_EXTENSION);
if (!concat.toLowerCase().endsWith(FILE_EXTENSION)
&& !concat.toLowerCase().endsWith(
FILE_EXTENSION + FILE_EXTENSION_COMPRESSED)) {
concat += FILE_EXTENSION;
}
setFile(new File(concat));
} else {
if (relationName.length() > 0) {
relationName = "_" + relationName;
}
String concat =
(m_dir + File.separator + m_prefix + relationName + add);
if (!concat.toLowerCase().endsWith(FILE_EXTENSION)
&& !concat.toLowerCase().endsWith(
FILE_EXTENSION + FILE_EXTENSION_COMPRESSED)) {
concat += FILE_EXTENSION;
}
setFile(new File(concat));
}
} catch (Exception ex) {
System.err
.println("File prefix and/or directory could not have been set.");
ex.printStackTrace();
}
}
/**
* to be pverridden
*
* @return the file type description.
*/
@Override
public abstract String getFileDescription();
/**
* Tip text suitable for displaying int the GUI
*
* @return a description of this property as a String
*/
public String useRelativePathTipText() {
return "Use relative rather than absolute paths";
}
/**
* Set whether to use relative rather than absolute paths
*
* @param rp true if relative paths are to be used
*/
@Override
public void setUseRelativePath(boolean rp) {
m_useRelativePath = rp;
}
/**
* Gets whether relative paths are to be used
*
* @return true if relative paths are to be used
*/
@Override
public boolean getUseRelativePath() {
return m_useRelativePath;
}
/**
* generates a string suitable for output on the command line displaying all
* available options.
*
* @param saver the saver to create the option string for
* @return the option string
*/
protected static String makeOptionStr(AbstractFileSaver saver) {
StringBuffer result;
Option option;
result = new StringBuffer();
// build option string
result.append("\n");
result.append(saver.getClass().getName().replaceAll(".*\\.", ""));
result.append(" options:\n\n");
Enumeration<Option> enm = saver.listOptions();
while (enm.hasMoreElements()) {
option = enm.nextElement();
result.append(option.synopsis() + "\n");
result.append(option.description() + "\n");
}
return result.toString();
}
/**
* runs the given saver with the specified options
*
* @param saver the saver to run
* @param options the commandline options
*/
public static void runFileSaver(AbstractFileSaver saver, String[] options) {
// help request?
try {
String[] tmpOptions = options.clone();
if (Utils.getFlag('h', tmpOptions)) {
System.err.println("\nHelp requested\n" + makeOptionStr(saver));
return;
}
} catch (Exception e) {
// ignore it
}
try {
// set options
try {
saver.setOptions(options);
} catch (Exception ex) {
System.err.println(makeOptionStr(saver));
System.exit(1);
}
saver.writeBatch();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/AbstractLoader.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* AbstractLoader.java
* Copyright (C) 2002-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import weka.core.CommandlineRunnable;
import weka.core.Instance;
import weka.core.Instances;
/**
* Abstract class gives default implementation of setSource methods. All other
* methods must be overridden.
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @version $Revision$
*/
public abstract class AbstractLoader implements Loader {
/** ID to avoid warning */
private static final long serialVersionUID = 2425432084900694551L;
/** The current retrieval mode */
protected int m_retrieval;
/**
* Sets the retrieval mode.
*
* @param mode the retrieval mode
*/
@Override
public void setRetrieval(int mode) {
m_retrieval = mode;
}
/**
* Gets the retrieval mode.
*
* @return the retrieval mode
*/
protected int getRetrieval() {
return m_retrieval;
}
/**
* Default implementation throws an IOException.
*
* @param file the File
* @exception IOException always
*/
@Override
public void setSource(File file) throws IOException {
throw new IOException("Setting File as source not supported");
}
/**
* Default implementation sets retrieval mode to NONE
*
* @exception never.
*/
@Override
public void reset() throws Exception {
m_retrieval = NONE;
}
/**
* Default implementation throws an IOException.
*
* @param input the input stream
* @exception IOException always
*/
@Override
public void setSource(InputStream input) throws IOException {
throw new IOException("Setting InputStream as source not supported");
}
/*
* To be overridden.
*/
@Override
public abstract Instances getStructure() throws IOException;
/*
* To be overridden.
*/
@Override
public abstract Instances getDataSet() throws IOException;
/*
* To be overridden.
*/
@Override
public abstract Instance getNextInstance(Instances structure)
throws IOException;
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/AbstractSaver.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* AbstractSaver.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import weka.core.Capabilities;
import weka.core.CapabilitiesHandler;
import weka.core.CapabilitiesIgnorer;
import weka.core.Instance;
import weka.core.Instances;
/**
* Abstract class for Saver
*
* @author Richard Kirkby (rkirkby@cs.waikato.ac.nz)
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
*/
public abstract class AbstractSaver implements Saver, CapabilitiesHandler, CapabilitiesIgnorer {
/** ID to avoid warning */
private static final long serialVersionUID = -27467499727819258L;
/** The write modes */
protected static final int WRITE = 0;
protected static final int WAIT = 1;
protected static final int CANCEL = 2;
protected static final int STRUCTURE_READY = 3;
/** The instances that should be stored */
private Instances m_instances;
/** The current retrieval mode */
protected int m_retrieval;
/** The current write mode */
private int m_writeMode;
/** Whether capabilities should not be checked */
protected boolean m_DoNotCheckCapabilities = false;
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String doNotCheckCapabilitiesTipText() {
return "If set, saver capabilities are not checked" + " (Use with caution to reduce runtime).";
}
/**
* Set whether not to check capabilities.
*
* @param doNotCheckCapabilities true if capabilities are not to be checked.
*/
@Override
public void setDoNotCheckCapabilities(final boolean doNotCheckCapabilities) {
this.m_DoNotCheckCapabilities = doNotCheckCapabilities;
}
/**
* Get whether capabilities checking is turned off.
*
* @return true if capabilities checking is turned off.
*/
@Override
public boolean getDoNotCheckCapabilities() {
return this.m_DoNotCheckCapabilities;
}
/**
* resets the options
*
*/
public void resetOptions() {
this.m_instances = null;
this.m_writeMode = WAIT;
}
/** Resets the structure (header information of the instances) */
public void resetStructure() {
this.m_instances = null;
this.m_writeMode = WAIT;
}
/**
* Sets the retrieval mode.
*
* @param mode the retrieval mode
*/
@Override
public void setRetrieval(final int mode) {
this.m_retrieval = mode;
}
/**
* Gets the retrieval mode.
*
* @return the retrieval mode
*/
protected int getRetrieval() {
return this.m_retrieval;
}
/**
* Sets the write mode.
*
* @param mode the write mode
*/
protected void setWriteMode(final int mode) {
this.m_writeMode = mode;
}
/**
* Gets the write mode.
*
* @return the write mode
*/
@Override
public int getWriteMode() {
return this.m_writeMode;
}
/**
* Sets instances that should be stored.
*
* @param instances the instances
* @throws InterruptedException
*/
@Override
public void setInstances(final Instances instances) throws InterruptedException {
Capabilities cap = this.getCapabilities();
if (!cap.test(instances)) {
throw new IllegalArgumentException(cap.getFailReason());
}
if (this.m_retrieval == INCREMENTAL) {
if (this.setStructure(instances) == CANCEL) {
this.cancel();
}
} else {
this.m_instances = instances;
}
}
/**
* Gets instances that should be stored.
*
* @return the instances
*/
public Instances getInstances() {
return this.m_instances;
}
/**
* Default implementation throws an IOException.
*
* @param file the File
* @exception IOException always
*/
@Override
public void setDestination(final File file) throws IOException {
throw new IOException("Writing to a file not supported");
}
/**
* Default implementation throws an IOException.
*
* @param output the OutputStream
* @exception IOException always
*/
@Override
public void setDestination(final OutputStream output) throws IOException {
throw new IOException("Writing to an outputstream not supported");
}
/**
* Returns the Capabilities of this saver. Derived savers have to override
* this method to enable capabilities.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = new Capabilities(this);
result.setMinimumNumberInstances(0);
return result;
}
/**
* Sets the strcuture of the instances for the first step of incremental
* saving. The instances only need to have a header.
*
* @param headerInfo an instances object.
* @return the appropriate write mode
* @throws InterruptedException
*/
public int setStructure(final Instances headerInfo) throws InterruptedException {
Capabilities cap = this.getCapabilities();
if (!cap.test(headerInfo)) {
throw new IllegalArgumentException(cap.getFailReason());
}
if (this.m_writeMode == WAIT && headerInfo != null) {
this.m_instances = headerInfo;
this.m_writeMode = STRUCTURE_READY;
} else {
if ((headerInfo == null) || !(this.m_writeMode == STRUCTURE_READY) || !headerInfo.equalHeaders(this.m_instances)) {
this.m_instances = null;
if (this.m_writeMode != WAIT) {
System.err.println("A structure cannot be set up during an active incremental saving process.");
}
this.m_writeMode = CANCEL;
}
}
return this.m_writeMode;
}
/** Cancels the incremental saving process if the write mode is CANCEL. */
public void cancel() {
if (this.m_writeMode == CANCEL) {
this.resetOptions();
}
}
/**
* Method for incremental saving. Standard behaviour: no incremental saving is
* possible, therefore throw an IOException. An incremental saving process is
* stopped by calling this method with null.
*
* @param i the instance to be saved
* @throws IOException IOEXception if the instance acnnot be written to the
* specified destination
*/
@Override
public void writeIncremental(final Instance i) throws IOException {
throw new IOException("No Incremental saving possible.");
}
/**
* Writes to a file in batch mode To be overridden.
*
* @throws IOException exception if writting is not possible
*/
@Override
public abstract void writeBatch() throws IOException;
/**
* Default implementation throws an IOException.
*
* @exception IOException always
*/
@Override
public String getFileExtension() throws Exception {
throw new Exception("Saving in a file not supported.");
}
/**
* Default implementation throws an IOException.
*
* @param file the File
* @exception IOException always
*/
@Override
public void setFile(final File file) throws IOException {
throw new IOException("Saving in a file not supported.");
}
/**
* Default implementation throws an IOException.
*
* @param prefix the file prefix
* @exception IOException always
*/
@Override
public void setFilePrefix(final String prefix) throws Exception {
throw new Exception("Saving in a file not supported.");
}
/**
* Default implementation throws an IOException.
*
* @exception IOException always
*/
@Override
public String filePrefix() throws Exception {
throw new Exception("Saving in a file not supported.");
}
/**
* Default implementation throws an IOException.
*
* @param dir the name of the directory to save in
* @exception IOException always
*/
@Override
public void setDir(final String dir) throws IOException {
throw new IOException("Saving in a file not supported.");
}
/**
* Default implementation throws an IOException.
*
* @param relationName
* @param add
* @exception IOException always
*/
@Override
public void setDirAndPrefix(final String relationName, final String add) throws IOException {
throw new IOException("Saving in a file not supported.");
}
/**
* Default implementation throws an IOException.
*
* @exception IOException always
*/
@Override
public String retrieveDir() throws IOException {
throw new IOException("Saving in a file not supported.");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/ArffLoader.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ArffLoader.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> Reads a source that is in arff (attribute relation
* file format) format.
* <p/>
* <!-- globalinfo-end -->
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Loader
*/
public class ArffLoader extends AbstractFileLoader implements BatchConverter,
IncrementalConverter, URLSourcedLoader {
/** for serialization */
static final long serialVersionUID = 2726929550544048587L;
/** the file extension */
public static String FILE_EXTENSION = Instances.FILE_EXTENSION;
public static String FILE_EXTENSION_COMPRESSED = FILE_EXTENSION + ".gz";
/** the url */
protected String m_URL = "http://";
/** The reader for the source file. */
protected transient Reader m_sourceReader = null;
/** The parser for the ARFF file */
protected transient ArffReader m_ArffReader = null;
/**
* Whether the values of string attributes should be retained in memory when
* reading incrementally
*/
protected boolean m_retainStringVals;
/**
* Reads data from an ARFF file, either in incremental or batch mode.
* <p/>
*
* Typical code for batch usage:
*
* <pre>
* BufferedReader reader =
* new BufferedReader(new FileReader("/some/where/file.arff"));
* ArffReader arff = new ArffReader(reader);
* Instances data = arff.getData();
* data.setClassIndex(data.numAttributes() - 1);
* </pre>
*
* Typical code for incremental usage:
*
* <pre>
* BufferedReader reader =
* new BufferedReader(new FileReader("/some/where/file.arff"));
* ArffReader arff = new ArffReader(reader, 1000);
* Instances data = arff.getStructure();
* data.setClassIndex(data.numAttributes() - 1);
* Instance inst;
* while ((inst = arff.readInstance(data)) != null) {
* data.add(inst);
* }
* </pre>
*
* @author Eibe Frank (eibe@cs.waikato.ac.nz)
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @author fracpete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public static class ArffReader implements RevisionHandler {
/** the tokenizer for reading the stream */
protected StreamTokenizer m_Tokenizer;
/** Buffer of values for sparse instance */
protected double[] m_ValueBuffer;
/** Buffer of indices for sparse instance */
protected int[] m_IndicesBuffer;
protected List<Integer> m_stringAttIndices;
/** the actual data */
protected Instances m_Data;
/** the number of lines read so far */
protected int m_Lines;
protected boolean m_batchMode = true;
/**
* Whether the values for string attributes will accumulate in the header
* when reading incrementally
*/
protected boolean m_retainStringValues = false;
/** Field separator (single character string) to use instead of the defaults */
protected String m_fieldSeparator;
/** List of (single character) enclosures to use instead of the defaults */
protected List<String> m_enclosures;
/**
* Reads the data completely from the reader. The data can be accessed via
* the <code>getData()</code> method.
*
* @param reader the reader to use
* @throws IOException if something goes wrong
* @see #getData()
*/
public ArffReader(Reader reader) throws IOException {
m_retainStringValues = true;
m_batchMode = true;
m_Tokenizer = new StreamTokenizer(reader);
initTokenizer();
readHeader(1000);
initBuffers();
Instance inst;
while ((inst = readInstance(m_Data)) != null) {
m_Data.add(inst);
}
compactify();
}
public ArffReader(Reader reader, int capacity) throws IOException {
this(reader, capacity, true);
}
/**
* Reads only the header and reserves the specified space for instances.
* Further instances can be read via <code>readInstance()</code>.
*
* @param reader the reader to use
* @param capacity the capacity of the new dataset
* @param batch true if reading in batch mode
* @throws IOException if something goes wrong
* @throws IOException if a problem occurs
* @see #getStructure()
* @see #readInstance(Instances)
*/
public ArffReader(Reader reader, int capacity, boolean batch)
throws IOException {
m_batchMode = batch;
if (batch) {
m_retainStringValues = true;
}
if (capacity < 0) {
throw new IllegalArgumentException("Capacity has to be positive!");
}
m_Tokenizer = new StreamTokenizer(reader);
initTokenizer();
readHeader(capacity);
initBuffers();
}
/**
* Reads the data without header according to the specified template. The
* data can be accessed via the <code>getData()</code> method.
*
* @param reader the reader to use
* @param template the template header
* @param lines the lines read so far
* @param fieldSepAndEnclosures an optional array of Strings containing the
* field separator and enclosures to use instead of the defaults.
* The first entry in the array is expected to be the single
* character field separator to use; the remaining entries (if any)
* are enclosure characters to use.
* @throws IOException if something goes wrong
* @see #getData()
*/
public ArffReader(Reader reader, Instances template, int lines,
String... fieldSepAndEnclosures) throws IOException {
this(reader, template, lines, 100, true, fieldSepAndEnclosures);
Instance inst;
while ((inst = readInstance(m_Data)) != null) {
m_Data.add(inst);
}
compactify();
}
/**
* Initializes the reader without reading the header according to the
* specified template. The data must be read via the
* <code>readInstance()</code> method.
*
* @param reader the reader to use
* @param template the template header
* @param lines the lines read so far
* @param capacity the capacity of the new dataset
* @param fieldSepAndEnclosures an optional array of Strings containing the
* field separator and enclosures to use instead of the defaults.
* The first entry in the array is expected to be the single
* character field separator to use; the remaining entries (if any)
* are enclosure characters to use.
* @throws IOException if something goes wrong
* @see #getData()
*/
public ArffReader(Reader reader, Instances template, int lines,
int capacity, String... fieldSepAndEnclosures) throws IOException {
this(reader, template, lines, capacity, false, fieldSepAndEnclosures);
}
/**
* Initializes the reader without reading the header according to the
* specified template. The data must be read via the
* <code>readInstance()</code> method.
*
* @param reader the reader to use
* @param template the template header
* @param lines the lines read so far
* @param capacity the capacity of the new dataset
* @param batch true if the data is going to be read in batch mode
* @param fieldSepAndEnclosures an optional array of Strings containing the
* field separator and enclosures to use instead of the defaults.
* The first entry in the array is expected to be the single
* character field separator to use; the remaining entries (if any)
* are enclosure characters to use.
* @throws IOException if something goes wrong
* @see #getData()
*/
public ArffReader(Reader reader, Instances template, int lines,
int capacity, boolean batch, String... fieldSepAndEnclosures)
throws IOException {
m_batchMode = batch;
if (batch) {
m_retainStringValues = true;
}
if (fieldSepAndEnclosures != null && fieldSepAndEnclosures.length > 0) {
if (fieldSepAndEnclosures[0] != null
&& fieldSepAndEnclosures[0].length() > 0) {
m_fieldSeparator = fieldSepAndEnclosures[0];
}
if (fieldSepAndEnclosures.length > 1) {
// the rest are assumed to be enclosure characters
m_enclosures = new ArrayList<String>();
for (int i = 1; i < fieldSepAndEnclosures.length; i++) {
if (fieldSepAndEnclosures[i] != null
&& fieldSepAndEnclosures[i].length() > 0) {
m_enclosures.add(fieldSepAndEnclosures[i]);
}
}
if (m_enclosures.size() == 0) {
m_enclosures = null;
}
}
}
m_Lines = lines;
m_Tokenizer = new StreamTokenizer(reader);
initTokenizer();
m_Data = new Instances(template, capacity);
initBuffers();
}
/**
* initializes the buffers for sparse instances to be read
*
* @see #m_ValueBuffer
* @see #m_IndicesBuffer
*/
protected void initBuffers() {
m_ValueBuffer = new double[m_Data.numAttributes()];
m_IndicesBuffer = new int[m_Data.numAttributes()];
m_stringAttIndices = new ArrayList<Integer>();
if (m_Data.checkForStringAttributes()) {
for (int i = 0; i < m_Data.numAttributes(); i++) {
if (m_Data.attribute(i).isString()) {
m_stringAttIndices.add(i);
}
}
}
}
/**
* compactifies the data
*/
protected void compactify() {
if (m_Data != null) {
m_Data.compactify();
}
}
/**
* Throws error message with line number and last token read.
*
* @param msg the error message to be thrown
* @throws IOException containing the error message
*/
protected void errorMessage(String msg) throws IOException {
String str = msg + ", read " + m_Tokenizer.toString();
if (m_Lines > 0) {
int line = Integer.parseInt(str.replaceAll(".* line ", ""));
str = str.replaceAll(" line .*", " line " + (m_Lines + line - 1));
}
throw new IOException(str);
}
/**
* returns the current line number
*
* @return the current line number
*/
public int getLineNo() {
return m_Lines + m_Tokenizer.lineno();
}
/**
* Gets next token, skipping empty lines.
*
* @throws IOException if reading the next token fails
*/
protected void getFirstToken() throws IOException {
while (m_Tokenizer.nextToken() == StreamTokenizer.TT_EOL) {
}
;
if ((m_Tokenizer.ttype == '\'') || (m_Tokenizer.ttype == '"')) {
m_Tokenizer.ttype = StreamTokenizer.TT_WORD;
} else if ((m_Tokenizer.ttype == StreamTokenizer.TT_WORD)
&& (m_Tokenizer.sval.equals("?"))) {
m_Tokenizer.ttype = '?';
}
}
/**
* Gets index, checking for a premature and of line.
*
* @throws IOException if it finds a premature end of line
*/
protected void getIndex() throws IOException {
if (m_Tokenizer.nextToken() == StreamTokenizer.TT_EOL) {
errorMessage("premature end of line");
}
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOF) {
errorMessage("premature end of file");
}
}
/**
* Gets token and checks if its end of line.
*
* @param endOfFileOk whether EOF is OK
* @throws IOException if it doesn't find an end of line
*/
protected void getLastToken(boolean endOfFileOk) throws IOException {
if ((m_Tokenizer.nextToken() != StreamTokenizer.TT_EOL)
&& ((m_Tokenizer.ttype != StreamTokenizer.TT_EOF) || !endOfFileOk)) {
errorMessage("end of line expected");
}
}
/**
* Gets the value of an instance's weight (if one exists)
*
* @return the value of the instance's weight, or NaN if no weight has been
* supplied in the file
*/
protected double getInstanceWeight() throws IOException {
double weight = Double.NaN;
m_Tokenizer.nextToken();
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOL
|| m_Tokenizer.ttype == StreamTokenizer.TT_EOF) {
return weight;
}
// see if we can read an instance weight
// m_Tokenizer.pushBack();
if (m_Tokenizer.ttype == '{') {
m_Tokenizer.nextToken();
String weightS = m_Tokenizer.sval;
// try to parse weight as a double
try {
weight = Double.parseDouble(weightS);
} catch (NumberFormatException e) {
// quietly ignore
return weight;
}
// see if we have the closing brace
m_Tokenizer.nextToken();
if (m_Tokenizer.ttype != '}') {
errorMessage("Problem reading instance weight: } expected");
}
}
return weight;
}
/**
* Gets next token, checking for a premature and of line.
*
* @throws IOException if it finds a premature end of line
*/
protected void getNextToken() throws IOException {
if (m_Tokenizer.nextToken() == StreamTokenizer.TT_EOL) {
errorMessage("premature end of line");
}
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOF) {
errorMessage("premature end of file");
} else if ((m_Tokenizer.ttype == '\'') || (m_Tokenizer.ttype == '"')) {
m_Tokenizer.ttype = StreamTokenizer.TT_WORD;
} else if ((m_Tokenizer.ttype == StreamTokenizer.TT_WORD)
&& (m_Tokenizer.sval.equals("?"))) {
m_Tokenizer.ttype = '?';
}
}
/**
* Initializes the StreamTokenizer used for reading the ARFF file.
*/
protected void initTokenizer() {
m_Tokenizer.resetSyntax();
m_Tokenizer.whitespaceChars(0, ' ');
m_Tokenizer.wordChars(' ' + 1, '\u00FF');
if (m_fieldSeparator != null) {
m_Tokenizer.whitespaceChars(m_fieldSeparator.charAt(0),
m_fieldSeparator.charAt(0));
} else {
m_Tokenizer.whitespaceChars(',', ',');
}
m_Tokenizer.commentChar('%');
if (m_enclosures != null && m_enclosures.size() > 0) {
for (String e : m_enclosures) {
m_Tokenizer.quoteChar(e.charAt(0));
}
} else {
m_Tokenizer.quoteChar('"');
m_Tokenizer.quoteChar('\'');
}
m_Tokenizer.ordinaryChar('{');
m_Tokenizer.ordinaryChar('}');
m_Tokenizer.eolIsSignificant(true);
}
/**
* Reads a single instance using the tokenizer and returns it.
*
* @param structure the dataset header information, will get updated in case
* of string or relational attributes
* @return null if end of file has been reached
* @throws IOException if the information is not read successfully
*/
public Instance readInstance(Instances structure) throws IOException {
return readInstance(structure, true);
}
/**
* Reads a single instance using the tokenizer and returns it.
*
* @param structure the dataset header information, will get updated in case
* of string or relational attributes
* @param flag if method should test for carriage return after each instance
* @return null if end of file has been reached
* @throws IOException if the information is not read successfully
*/
public Instance readInstance(Instances structure, boolean flag)
throws IOException {
return getInstance(structure, flag);
}
/**
* Reads a single instance using the tokenizer and returns it.
*
* @param structure the dataset header information, will get updated in case
* of string or relational attributes
* @param flag if method should test for carriage return after each instance
* @return null if end of file has been reached
* @throws IOException if the information is not read successfully
*/
protected Instance getInstance(Instances structure, boolean flag)
throws IOException {
m_Data = structure;
// Check if any attributes have been declared.
if (m_Data.numAttributes() == 0) {
errorMessage("no header information available");
}
// Check if end of file reached.
getFirstToken();
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOF) {
return null;
}
// Parse instance
if (m_Tokenizer.ttype == '{') {
return getInstanceSparse(flag);
} else {
return getInstanceFull(flag);
}
}
/**
* Reads a single instance using the tokenizer and returns it.
*
* @param flag if method should test for carriage return after each instance
* @return null if end of file has been reached
* @throws IOException if the information is not read successfully
*/
protected Instance getInstanceSparse(boolean flag) throws IOException {
int valIndex, numValues = 0, maxIndex = -1;
// if reading incrementally, and we have string values, make sure that all
// string attributes are initialized
if (!m_batchMode && !m_retainStringValues && m_stringAttIndices != null) {
for (int i = 0; i < m_stringAttIndices.size(); i++) {
m_Data.attribute(m_stringAttIndices.get(i)).setStringValue(null);
}
}
// Get values
do {
// Get index
getIndex();
if (m_Tokenizer.ttype == '}') {
break;
}
// Is index valid?
try {
m_IndicesBuffer[numValues] =
Integer.valueOf(m_Tokenizer.sval).intValue();
} catch (NumberFormatException e) {
errorMessage("index number expected");
}
if (m_IndicesBuffer[numValues] <= maxIndex) {
errorMessage("indices have to be ordered");
}
if ((m_IndicesBuffer[numValues] < 0)
|| (m_IndicesBuffer[numValues] >= m_Data.numAttributes())) {
errorMessage("index out of bounds");
}
maxIndex = m_IndicesBuffer[numValues];
// Get value;
getNextToken();
// Check if value is missing.
if (m_Tokenizer.ttype == '?') {
m_ValueBuffer[numValues] = Utils.missingValue();
} else {
// Check if token is valid.
if (m_Tokenizer.ttype != StreamTokenizer.TT_WORD) {
errorMessage("not a valid value");
}
switch (m_Data.attribute(m_IndicesBuffer[numValues]).type()) {
case Attribute.NOMINAL:
// Check if value appears in header.
valIndex =
m_Data.attribute(m_IndicesBuffer[numValues]).indexOfValue(
m_Tokenizer.sval);
if (valIndex == -1) {
errorMessage("nominal value not declared in header");
}
m_ValueBuffer[numValues] = valIndex;
break;
case Attribute.NUMERIC:
// Check if value is really a number.
try {
m_ValueBuffer[numValues] =
Double.valueOf(m_Tokenizer.sval).doubleValue();
} catch (NumberFormatException e) {
errorMessage("number expected");
}
break;
case Attribute.STRING:
if (m_batchMode || m_retainStringValues) {
m_ValueBuffer[numValues] =
m_Data.attribute(m_IndicesBuffer[numValues]).addStringValue(
m_Tokenizer.sval);
} else {
m_ValueBuffer[numValues] = 0;
m_Data.attribute(m_IndicesBuffer[numValues]).addStringValue(
m_Tokenizer.sval);
}
break;
case Attribute.DATE:
try {
m_ValueBuffer[numValues] =
m_Data.attribute(m_IndicesBuffer[numValues]).parseDate(
m_Tokenizer.sval);
} catch (ParseException e) {
errorMessage("unparseable date: " + m_Tokenizer.sval);
}
break;
case Attribute.RELATIONAL:
try {
ArffReader arff =
new ArffReader(new StringReader(m_Tokenizer.sval), m_Data
.attribute(m_IndicesBuffer[numValues]).relation(), 0);
Instances data = arff.getData();
m_ValueBuffer[numValues] =
m_Data.attribute(m_IndicesBuffer[numValues]).addRelation(data);
} catch (Exception e) {
throw new IOException(e.toString() + " of line " + getLineNo());
}
break;
default:
errorMessage("unknown attribute type in column "
+ m_IndicesBuffer[numValues]);
}
}
numValues++;
} while (true);
double weight = 1.0;
if (flag) {
// check for an instance weight
weight = getInstanceWeight();
if (!Double.isNaN(weight)) {
getLastToken(true);
} else {
weight = 1.0;
}
}
// Add instance to dataset
double[] tempValues = new double[numValues];
int[] tempIndices = new int[numValues];
System.arraycopy(m_ValueBuffer, 0, tempValues, 0, numValues);
System.arraycopy(m_IndicesBuffer, 0, tempIndices, 0, numValues);
Instance inst =
new SparseInstance(weight, tempValues, tempIndices,
m_Data.numAttributes());
inst.setDataset(m_Data);
return inst;
}
/**
* Reads a single instance using the tokenizer and returns it.
*
* @param flag if method should test for carriage return after each instance
* @return null if end of file has been reached
* @throws IOException if the information is not read successfully
*/
protected Instance getInstanceFull(boolean flag) throws IOException {
double[] instance = new double[m_Data.numAttributes()];
int index;
// Get values for all attributes.
for (int i = 0; i < m_Data.numAttributes(); i++) {
// Get next token
if (i > 0) {
getNextToken();
}
// Check if value is missing.
if (m_Tokenizer.ttype == '?') {
instance[i] = Utils.missingValue();
} else {
// Check if token is valid.
if (m_Tokenizer.ttype != StreamTokenizer.TT_WORD) {
errorMessage("not a valid value");
}
switch (m_Data.attribute(i).type()) {
case Attribute.NOMINAL:
// Check if value appears in header.
index = m_Data.attribute(i).indexOfValue(m_Tokenizer.sval);
if (index == -1) {
errorMessage("nominal value not declared in header");
}
instance[i] = index;
break;
case Attribute.NUMERIC:
// Check if value is really a number.
try {
instance[i] = Double.valueOf(m_Tokenizer.sval).doubleValue();
} catch (NumberFormatException e) {
errorMessage("number expected");
}
break;
case Attribute.STRING:
if (m_batchMode || m_retainStringValues) {
instance[i] =
m_Data.attribute(i).addStringValue(m_Tokenizer.sval);
} else {
instance[i] = 0;
m_Data.attribute(i).setStringValue(m_Tokenizer.sval);
}
break;
case Attribute.DATE:
try {
instance[i] = m_Data.attribute(i).parseDate(m_Tokenizer.sval);
} catch (ParseException e) {
errorMessage("unparseable date: " + m_Tokenizer.sval);
}
break;
case Attribute.RELATIONAL:
try {
ArffReader arff =
new ArffReader(new StringReader(m_Tokenizer.sval), m_Data
.attribute(i).relation(), 0);
Instances data = arff.getData();
instance[i] = m_Data.attribute(i).addRelation(data);
} catch (Exception e) {
throw new IOException(e.toString() + " of line " + getLineNo());
}
break;
default:
errorMessage("unknown attribute type in column " + i);
}
}
}
double weight = 1.0;
if (flag) {
// check for an instance weight
weight = getInstanceWeight();
if (!Double.isNaN(weight)) {
getLastToken(true);
} else {
weight = 1.0;
}
}
// Add instance to dataset
Instance inst = new DenseInstance(weight, instance);
inst.setDataset(m_Data);
return inst;
}
/**
* Reads and stores header of an ARFF file.
*
* @param capacity the number of instances to reserve in the data structure
* @throws IOException if the information is not read successfully
*/
protected void readHeader(int capacity) throws IOException {
m_Lines = 0;
String relationName = "";
// Get name of relation.
getFirstToken();
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOF) {
errorMessage("premature end of file");
}
if (Instances.ARFF_RELATION.equalsIgnoreCase(m_Tokenizer.sval)) {
getNextToken();
relationName = m_Tokenizer.sval;
getLastToken(false);
} else {
errorMessage("keyword " + Instances.ARFF_RELATION + " expected");
}
// Create vectors to hold information temporarily.
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
// Get attribute declarations.
getFirstToken();
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOF) {
errorMessage("premature end of file");
}
while (Attribute.ARFF_ATTRIBUTE.equalsIgnoreCase(m_Tokenizer.sval)) {
attributes = parseAttribute(attributes);
}
// Check if data part follows. We can't easily check for EOL.
if (!Instances.ARFF_DATA.equalsIgnoreCase(m_Tokenizer.sval)) {
errorMessage("keyword " + Instances.ARFF_DATA + " expected");
}
// Check if any attributes have been declared.
if (attributes.size() == 0) {
errorMessage("no attributes declared");
}
m_Data = new Instances(relationName, attributes, capacity);
}
/**
* Parses the attribute declaration.
*
* @param attributes the current attributes vector
* @return the new attributes vector
* @throws IOException if the information is not read successfully
*/
protected ArrayList<Attribute> parseAttribute(
ArrayList<Attribute> attributes) throws IOException {
String attributeName;
ArrayList<String> attributeValues;
// Get attribute name.
getNextToken();
attributeName = m_Tokenizer.sval;
getNextToken();
// Check if attribute is nominal.
if (m_Tokenizer.ttype == StreamTokenizer.TT_WORD) {
// Attribute is real, integer, or string.
if (m_Tokenizer.sval.equalsIgnoreCase(Attribute.ARFF_ATTRIBUTE_REAL)
|| m_Tokenizer.sval
.equalsIgnoreCase(Attribute.ARFF_ATTRIBUTE_INTEGER)
|| m_Tokenizer.sval
.equalsIgnoreCase(Attribute.ARFF_ATTRIBUTE_NUMERIC)) {
Attribute att = new Attribute(attributeName, attributes.size());
att.setWeight(getAttributeWeight());
attributes.add(att);
readTillEOL();
} else if (m_Tokenizer.sval
.equalsIgnoreCase(Attribute.ARFF_ATTRIBUTE_STRING)) {
Attribute att = new Attribute(attributeName, (ArrayList<String>) null, attributes.size());
att.setWeight(getAttributeWeight());
readTillEOL();
attributes.add(att);
} else if (m_Tokenizer.sval
.equalsIgnoreCase(Attribute.ARFF_ATTRIBUTE_DATE)) {
String format = null;
m_Tokenizer.nextToken();
if (m_Tokenizer.ttype == '{') { // No date format but it looks like there is an attribute weight
m_Tokenizer.pushBack();
Attribute att = new Attribute(attributeName, format, attributes.size());
att.setWeight(getAttributeWeight());
attributes.add(att);
readTillEOL();
} else if (m_Tokenizer.ttype != StreamTokenizer.TT_EOL) { // Looks like there is a date format
if ((m_Tokenizer.ttype != StreamTokenizer.TT_WORD)
&& (m_Tokenizer.ttype != '\'') && (m_Tokenizer.ttype != '\"')) {
errorMessage("not a valid date format");
}
format = m_Tokenizer.sval;
Attribute att = new Attribute(attributeName, format, attributes.size());
att.setWeight(getAttributeWeight()); // Now check for attribute weight
attributes.add(att);
readTillEOL();
} else {
m_Tokenizer.pushBack();
attributes.add(new Attribute(attributeName, format, attributes.size()));
}
} else if (m_Tokenizer.sval
.equalsIgnoreCase(Attribute.ARFF_ATTRIBUTE_RELATIONAL)) {
double weight = getAttributeWeight();
readTillEOL();
// Read attributes for subrelation
// First, save current set of attributes
ArrayList<Attribute> atts = attributes;
attributes = new ArrayList<Attribute>();
// Now, read attributes until we hit end of declaration of relational
// value
getFirstToken();
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOF) {
errorMessage("premature end of file");
}
do {
if (Attribute.ARFF_ATTRIBUTE.equalsIgnoreCase(m_Tokenizer.sval)) {
attributes = parseAttribute(attributes);
} else if (Attribute.ARFF_END_SUBRELATION
.equalsIgnoreCase(m_Tokenizer.sval)) {
getNextToken();
if (!attributeName.equalsIgnoreCase(m_Tokenizer.sval)) {
errorMessage("declaration of subrelation " + attributeName
+ " must be terminated by " + "@end " + attributeName);
}
break;
} else {
errorMessage("declaration of subrelation " + attributeName
+ " must be terminated by " + "@end " + attributeName);
}
} while (true);
// Make relation and restore original set of attributes
Instances relation = new Instances(attributeName, attributes, 0);
attributes = atts;
Attribute att = new Attribute(attributeName, relation, attributes.size());
att.setWeight(weight);
attributes.add(att);
} else {
errorMessage("no valid attribute type or invalid " + "enumeration");
}
} else {
// Attribute is nominal.
attributeValues = new ArrayList<String>();
m_Tokenizer.pushBack();
// Get values for nominal attribute.
if (m_Tokenizer.nextToken() != '{') {
errorMessage("{ expected at beginning of enumeration");
}
while (m_Tokenizer.nextToken() != '}') {
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOL) {
errorMessage("} expected at end of enumeration");
} else {
attributeValues.add(m_Tokenizer.sval);
}
}
Attribute att = new Attribute(attributeName, attributeValues, attributes.size());
att.setWeight(getAttributeWeight());
attributes.add(att);
readTillEOL();
}
getLastToken(false);
getFirstToken();
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOF) {
errorMessage("premature end of file");
}
return attributes;
}
/**
* Reads and skips all tokens before next end of line token.
*
* @throws IOException in case something goes wrong
*/
protected void readTillEOL() throws IOException {
while (m_Tokenizer.nextToken() != StreamTokenizer.TT_EOL) {
}
m_Tokenizer.pushBack();
}
/**
* Gets the value of an attribute's weight (if one exists).
*
* @return the value of the attribute's weight, or 1.0 if no weight has been
* supplied in the file
*/
protected double getAttributeWeight() throws IOException {
double weight = 1.0;
m_Tokenizer.nextToken();
if (m_Tokenizer.ttype == StreamTokenizer.TT_EOL || m_Tokenizer.ttype == StreamTokenizer.TT_EOF) {
m_Tokenizer.pushBack();
return weight;
}
// see if we can read an attribute weight
if (m_Tokenizer.ttype == '{') {
m_Tokenizer.nextToken();
try {
weight = Double.parseDouble(m_Tokenizer.sval);
} catch (NumberFormatException ex) {
errorMessage("Problem reading attribute weight " + ex.getMessage());
}
m_Tokenizer.nextToken();
if (m_Tokenizer.ttype != '}') {
errorMessage("Problem reading attribute weight: } expected");
}
}
return weight;
}
/**
* Returns the header format
*
* @return the header format
*/
public Instances getStructure() {
return new Instances(m_Data, 0);
}
/**
* Returns the data that was read
*
* @return the data
*/
public Instances getData() {
return m_Data;
}
/**
* Set whether to retain the values of string attributes in memory (in the
* header) when reading incrementally.
*
* @param retain true if string values are to be retained in memory when
* reading incrementally
*/
public void setRetainStringValues(boolean retain) {
m_retainStringValues = retain;
}
/**
* Get whether to retain the values of string attributes in memory (in the
* header) when reading incrementally.
*
* @return true if string values are to be retained in memory when reading
* incrementally
*/
public boolean getRetainStringValues() {
return m_retainStringValues;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* Returns a string describing this Loader
*
* @return a description of the Loader suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Reads a source that is in arff (attribute relation file format) "
+ "format. ";
}
/**
* Tool tip text for this property
*
* @return the tool tip for this property
*/
public String retainStringValsTipText() {
return "If true then the values of string attributes are "
+ "retained in memory when reading incrementally. Leave this "
+ "set to false when using incremental classifiers in the "
+ "Knowledge Flow.";
}
/**
* Set whether to retain the values of string attributes in memory (in the
* header) when reading incrementally.
*
* @param retain true if string values are to be retained in memory when
* reading incrementally
*/
public void setRetainStringVals(boolean retain) {
m_retainStringVals = retain;
}
/**
* Get whether to retain the values of string attributes in memory (in the
* header) when reading incrementally.
*
* @return true if string values are to be retained in memory when reading
* incrementally
*/
public boolean getRetainStringVals() {
return m_retainStringVals;
}
/**
* Get the file extension used for arff files
*
* @return the file extension
*/
@Override
public String getFileExtension() {
return FILE_EXTENSION;
}
/**
* Gets all the file extensions used for this type of file
*
* @return the file extensions
*/
@Override
public String[] getFileExtensions() {
return new String[] { FILE_EXTENSION, FILE_EXTENSION_COMPRESSED };
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "Arff data files";
}
/**
* Resets the Loader ready to read a new data set or the same data set again.
*
* @throws IOException if something goes wrong
*/
@Override
public void reset() throws IOException {
m_structure = null;
m_ArffReader = null;
setRetrieval(NONE);
if (m_File != null && !(new File(m_File).isDirectory())) {
setFile(new File(m_File));
} else if (m_URL != null && !m_URL.equals("http://")) {
setURL(m_URL);
}
}
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied url.
*
* @param url the source url.
* @throws IOException if an error occurs
*/
public void setSource(URL url) throws IOException {
m_structure = null;
setRetrieval(NONE);
setSource(url.openStream());
m_URL = url.toString();
// make sure that the file is null so that any calls to
// reset() work properly
m_File = null;
}
/**
* get the File specified as the source
*
* @return the source file
*/
@Override
public File retrieveFile() {
return new File(m_File);
}
/**
* sets the source File
*
* @param file the source file
* @throws IOException if an error occurs
*/
@Override
public void setFile(File file) throws IOException {
m_File = file.getPath();
setSource(file);
}
/**
* Set the url to load from
*
* @param url the url to load from
* @throws IOException if the url can't be set.
*/
@Override
public void setURL(String url) throws IOException {
m_URL = url;
setSource(new URL(url));
}
/**
* Return the current url
*
* @return the current url
*/
@Override
public String retrieveURL() {
return m_URL;
}
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied InputStream.
*
* @param in the source InputStream.
* @throws IOException always thrown.
*/
@Override
public void setSource(InputStream in) throws IOException {
m_File = (new File(System.getProperty("user.dir"))).getAbsolutePath();
m_URL = "http://";
m_sourceReader = new BufferedReader(new InputStreamReader(in));
}
/**
* Determines and returns (if possible) the structure (internally the header)
* of the data set as an empty set of instances.
*
* @return the structure of the data set as an empty set of Instances
* @throws IOException if an error occurs
*/
@Override
public Instances getStructure() throws IOException {
if (m_structure == null) {
if (m_sourceReader == null) {
throw new IOException("No source has been specified");
}
try {
m_ArffReader =
new ArffReader(m_sourceReader, 1, (getRetrieval() == BATCH));
m_ArffReader.setRetainStringValues(getRetainStringVals());
m_structure = m_ArffReader.getStructure();
} catch (Exception ex) {
throw new IOException("Unable to determine structure as arff (Reason: "
+ ex.toString() + ").");
}
}
return new Instances(m_structure, 0);
}
/**
* Return the full data set. If the structure hasn't yet been determined by a
* call to getStructure then method should do so before processing the rest of
* the data set.
*
* @return the structure of the data set as an empty set of Instances
* @throws IOException if there is no source or parsing fails
*/
@Override
public Instances getDataSet() throws IOException {
Instances insts = null;
try {
if (m_sourceReader == null) {
throw new IOException("No source has been specified");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException(
"Cannot mix getting Instances in both incremental and batch modes");
}
setRetrieval(BATCH);
if (m_structure == null) {
getStructure();
}
// Read all instances
insts = new Instances(m_structure, 0);
Instance inst;
while ((inst = m_ArffReader.readInstance(m_structure)) != null) {
insts.add(inst);
}
// Instances readIn = new Instances(m_structure);
} finally {
if (m_sourceReader != null) {
// close the stream
m_sourceReader.close();
}
}
return insts;
}
/**
* Read the data set incrementally---get the next instance in the data set or
* returns null if there are no more instances to get. If the structure hasn't
* yet been determined by a call to getStructure then method should do so
* before returning the next instance in the data set.
*
* @param structure the dataset header information, will get updated in case
* of string or relational attributes
* @return the next instance in the data set as an Instance object or null if
* there are no more instances to be read
* @throws IOException if there is an error during parsing
*/
@Override
public Instance getNextInstance(Instances structure) throws IOException {
m_structure = structure;
if (getRetrieval() == BATCH) {
throw new IOException(
"Cannot mix getting Instances in both incremental and batch modes");
}
setRetrieval(INCREMENTAL);
Instance current = null;
if (m_sourceReader != null) {
current = m_ArffReader.readInstance(m_structure);
}
if ((m_sourceReader != null) && (current == null)) {
try {
// close the stream
m_sourceReader.close();
m_sourceReader = null;
// reset();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return current;
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method.
*
* @param args should contain the name of an input file.
*/
public static void main(String[] args) {
runFileLoader(new ArffLoader(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/ArffSaver.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ArffSaver.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import java.util.zip.GZIPOutputStream;
import weka.core.AbstractInstance;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
* Writes to a destination in arff text format.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -i <the input file>
* The input file
* </pre>
*
* <pre>
* -o <the output file>
* The output file
* </pre>
*
* <pre>
* -compress
* Compresses the data (uses '.arff.gz' as extension instead of '.arff')
* (default: off)
* </pre>
*
* <pre>
* -decimal <num>
* The maximum number of digits to print after the decimal
* place for numeric values (default: 6)
* </pre>
*
* <!-- options-end -->
*
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
* @see Saver
*/
public class ArffSaver extends AbstractFileSaver implements BatchConverter,
IncrementalConverter {
/** for serialization */
static final long serialVersionUID = 2223634248900042228L;
/** whether to compress the output */
protected boolean m_CompressOutput = false;
/** Max number of decimal places for numeric values */
protected int m_MaxDecimalPlaces = AbstractInstance.s_numericAfterDecimalPoint;
/** Constructor */
public ArffSaver() {
resetOptions();
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tCompresses the data (uses '"
+ ArffLoader.FILE_EXTENSION_COMPRESSED + "' as extension instead of '"
+ ArffLoader.FILE_EXTENSION + "')\n" + "\t(default: off)", "compress", 0,
"-compress"));
result.addElement(new Option(
"\tThe maximum number of digits to print after the decimal\n"
+ "\tplace for numeric values (default: 6)", "decimal", 1,
"-decimal <num>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* returns the options of the current setup
*
* @return the current options
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (getCompressOutput()) {
result.add("-compress");
}
result.add("-decimal");
result.add("" + getMaxDecimalPlaces());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Parses the options for this object.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -i <the input file>
* The input file
* </pre>
*
* <pre>
* -o <the output file>
* The output file
* </pre>
*
* <pre>
* -compress
* Compresses the data (uses '.arff.gz' as extension instead of '.arff')
* (default: off)
* </pre>
*
* <pre>
* -decimal <num>
* The maximum number of digits to print after the decimal
* place for numeric values (default: 6)
* </pre>
*
* <!-- options-end -->
*
* @param options the options to use
* @throws Exception if setting of options fails
*/
@Override
public void setOptions(String[] options) throws Exception {
setCompressOutput(Utils.getFlag("compress", options));
String tmpStr = Utils.getOption("decimal", options);
if (tmpStr.length() > 0) {
setMaxDecimalPlaces(Integer.parseInt(tmpStr));
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Set the maximum number of decimal places to print
*
* @param maxDecimal the maximum number of decimal places to print
*/
public void setMaxDecimalPlaces(int maxDecimal) {
m_MaxDecimalPlaces = maxDecimal;
}
/**
* Get the maximum number of decimal places to print
*
* @return the maximum number of decimal places to print
*/
public int getMaxDecimalPlaces() {
return m_MaxDecimalPlaces;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String maxDecimalPlacesTipText() {
return "The maximum number of digits to print after the decimal "
+ "point for numeric values";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String compressOutputTipText() {
return "Optional compression of the output data";
}
/**
* Gets whether the output data is compressed.
*
* @return true if the output data is compressed
*/
public boolean getCompressOutput() {
return m_CompressOutput;
}
/**
* Sets whether to compress the output.
*
* @param value if truee the output will be compressed
*/
public void setCompressOutput(boolean value) {
m_CompressOutput = value;
}
/**
* Returns a string describing this Saver
*
* @return a description of the Saver suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Writes to a destination that is in arff (attribute relation file format) "
+ "format. The data can be compressed with gzip in order to save space.";
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "Arff data files";
}
/**
* Gets all the file extensions used for this type of file
*
* @return the file extensions
*/
@Override
public String[] getFileExtensions() {
return new String[] { ArffLoader.FILE_EXTENSION,
ArffLoader.FILE_EXTENSION_COMPRESSED };
}
/**
* Sets the destination file.
*
* @param outputFile the destination file.
* @throws IOException throws an IOException if file cannot be set
*/
@Override
public void setFile(File outputFile) throws IOException {
if (outputFile.getAbsolutePath().endsWith(
ArffLoader.FILE_EXTENSION_COMPRESSED)) {
setCompressOutput(true);
}
super.setFile(outputFile);
}
/**
* Sets the destination output stream.
*
* @param output the output stream.
* @throws IOException throws an IOException if destination cannot be set
*/
@Override
public void setDestination(OutputStream output) throws IOException {
if (getCompressOutput()) {
super.setDestination(new GZIPOutputStream(output));
} else {
super.setDestination(output);
}
}
/**
* Resets the Saver
*/
@Override
public void resetOptions() {
super.resetOptions();
setFileExtension(".arff");
}
/**
* Returns the Capabilities of this saver.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enableAllAttributes();
result.enable(Capability.MISSING_VALUES);
// class
result.enableAllClasses();
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Saves an instances incrementally. Structure has to be set by using the
* setStructure() method or setInstances() method.
*
* @param inst the instance to save
* @throws IOException throws IOEXception if an instance cannot be saved
* incrementally.
*/
@Override
public void writeIncremental(Instance inst) throws IOException {
int writeMode = getWriteMode();
Instances structure = getInstances();
PrintWriter outW = null;
if (getRetrieval() == BATCH || getRetrieval() == NONE) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
if (getWriter() != null) {
outW = new PrintWriter(getWriter());
}
if (writeMode == WAIT) {
if (structure == null) {
setWriteMode(CANCEL);
if (inst != null) {
System.err
.println("Structure(Header Information) has to be set in advance");
}
} else {
setWriteMode(STRUCTURE_READY);
}
writeMode = getWriteMode();
}
if (writeMode == CANCEL) {
if (outW != null) {
outW.close();
}
cancel();
}
if (writeMode == STRUCTURE_READY) {
setWriteMode(WRITE);
// write header
Instances header = new Instances(structure, 0);
if (retrieveFile() == null && outW == null) {
System.out.println(header.toString());
} else {
outW.print(header.toString());
outW.print("\n");
outW.flush();
}
writeMode = getWriteMode();
}
if (writeMode == WRITE) {
if (structure == null) {
throw new IOException("No instances information available.");
}
if (inst != null) {
// write instance
if (retrieveFile() == null && outW == null) {
System.out.println(inst.toStringMaxDecimalDigits(m_MaxDecimalPlaces));
} else {
outW.println(inst.toStringMaxDecimalDigits(m_MaxDecimalPlaces));
m_incrementalCounter++;
// flush every 100 instances
if (m_incrementalCounter > 100) {
m_incrementalCounter = 0;
outW.flush();
}
}
} else {
// close
if (outW != null) {
outW.flush();
outW.close();
}
m_incrementalCounter = 0;
resetStructure();
outW = null;
resetWriter();
}
}
}
/**
* Writes a Batch of instances
*
* @throws IOException throws IOException if saving in batch mode is not
* possible
*/
@Override
public void writeBatch() throws IOException {
if (getInstances() == null) {
throw new IOException("No instances to save");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
setRetrieval(BATCH);
setWriteMode(WRITE);
if (retrieveFile() == null && getWriter() == null) {
Instances data = getInstances();
System.out.println(new Instances(data, 0));
for (int i = 0; i < data.numInstances(); i++) {
System.out.println(data.instance(i).toStringMaxDecimalDigits(
m_MaxDecimalPlaces));
}
setWriteMode(WAIT);
return;
}
PrintWriter outW = new PrintWriter(getWriter());
Instances data = getInstances();
// header
Instances header = new Instances(data, 0);
outW.print(header.toString());
// data
for (int i = 0; i < data.numInstances(); i++) {
if (i % 1000 == 0) {
outW.flush();
}
outW.println(data.instance(i)
.toStringMaxDecimalDigits(m_MaxDecimalPlaces));
}
outW.flush();
outW.close();
setWriteMode(WAIT);
outW = null;
resetWriter();
setWriteMode(CANCEL);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method.
*
* @param args should contain the options of a Saver.
*/
public static void main(String[] args) {
runFileSaver(new ArffSaver(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/BatchConverter.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* BatchConverter.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
/**
* Marker interface for a loader/saver that can retrieve instances in batch mode
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision 1.0 $
*/
public interface BatchConverter {
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/C45Loader.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* C45Loader.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.util.ArrayList;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
<!-- globalinfo-start -->
* Reads a file that is C45 format. Can take a
* filestem or filestem with .names or .data appended. Assumes that
* path/<filestem>.names and path/<filestem>.data exist and contain
* the names and data respectively.
* <p/>
<!-- globalinfo-end -->
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @version $Revision$
* @see Loader
*/
public class C45Loader extends AbstractFileLoader implements BatchConverter,
IncrementalConverter {
/** for serialization */
static final long serialVersionUID = 5454329403218219L;
/** the file extension */
public static String FILE_EXTENSION = ".names";
/**
* Describe variable <code>m_sourceFileData</code> here.
*/
private File m_sourceFileData = null;
/**
* Reader for names file
*/
private transient Reader m_namesReader = null;
/**
* Reader for data file
*/
private transient Reader m_dataReader = null;
/**
* Holds the filestem.
*/
private String m_fileStem;
/**
* Number of attributes in the data (including ignore and label attributes).
*/
private int m_numAttribs;
/**
* Which attributes are ignore or label. These are *not* included in the arff
* representation.
*/
private boolean[] m_ignore;
/**
* Returns a string describing this attribute evaluator
*
* @return a description of the evaluator suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Reads a file that is C45 format. Can take a filestem or filestem "
+ "with .names or .data appended. Assumes that path/<filestem>.names and "
+ "path/<filestem>.data exist and contain the names and data "
+ "respectively.";
}
/**
* Resets the Loader ready to read a new data set or the same data set again.
*
* @throws IOException if something goes wrong
*/
@Override
public void reset() throws IOException {
m_structure = null;
setRetrieval(NONE);
if (m_File != null) {
setFile(new File(m_File));
}
}
/**
* Get the file extension used for arff files
*
* @return the file extension
*/
@Override
public String getFileExtension() {
return FILE_EXTENSION;
}
/**
* Gets all the file extensions used for this type of file
*
* @return the file extensions
*/
@Override
public String[] getFileExtensions() {
return new String[] { ".names", ".data" };
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "C4.5 data files";
}
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied File object.
*
* @param file the source file.
* @exception IOException if an error occurs
*/
@Override
public void setSource(File file) throws IOException {
m_structure = null;
setRetrieval(NONE);
if (file == null) {
throw new IOException("Source file object is null!");
}
String fname = file.getName();
String fileStem;
String path = file.getParent();
if (path != null) {
path += File.separator;
} else {
path = "";
}
if (fname.indexOf('.') < 0) {
fileStem = fname;
fname += ".names";
} else {
fileStem = fname.substring(0, fname.lastIndexOf('.'));
fname = fileStem + ".names";
}
m_fileStem = fileStem;
file = new File(path + fname);
m_sourceFile = file;
try {
BufferedReader br = new BufferedReader(new FileReader(file));
m_namesReader = br;
} catch (FileNotFoundException ex) {
throw new IOException("File not found : " + (path + fname));
}
m_sourceFileData = new File(path + fileStem + ".data");
try {
BufferedReader br = new BufferedReader(new FileReader(m_sourceFileData));
m_dataReader = br;
} catch (FileNotFoundException ex) {
throw new IOException("File not found : " + (path + fname));
}
m_File = file.getAbsolutePath();
}
/**
* Determines and returns (if possible) the structure (internally the header)
* of the data set as an empty set of instances.
*
* @return the structure of the data set as an empty set of Instances
* @exception IOException if an error occurs
*/
@Override
public Instances getStructure() throws IOException {
if (m_sourceFile == null) {
throw new IOException("No source has beenspecified");
}
if (m_structure == null) {
setSource(m_sourceFile);
StreamTokenizer st = new StreamTokenizer(m_namesReader);
initTokenizer(st);
readHeader(st);
}
return m_structure;
}
/**
* Return the full data set. If the structure hasn't yet been determined by a
* call to getStructure then method should do so before processing the rest of
* the data set.
*
* @return the structure of the data set as an empty set of Instances
* @exception IOException if there is no source or parsing fails
*/
@Override
public Instances getDataSet() throws IOException {
if (m_sourceFile == null) {
throw new IOException("No source has been specified");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException(
"Cannot mix getting Instances in both incremental and batch modes");
}
setRetrieval(BATCH);
if (m_structure == null) {
getStructure();
}
StreamTokenizer st = new StreamTokenizer(m_dataReader);
initTokenizer(st);
// st.ordinaryChar('.');
Instances result = new Instances(m_structure);
Instance current = getInstance(st);
while (current != null) {
result.add(current);
current = getInstance(st);
}
try {
// close the stream
m_dataReader.close();
// reset();
} catch (Exception ex) {
ex.printStackTrace();
}
return result;
}
/**
* Read the data set incrementally---get the next instance in the data set or
* returns null if there are no more instances to get. If the structure hasn't
* yet been determined by a call to getStructure then method should do so
* before returning the next instance in the data set.
*
* If it is not possible to read the data set incrementally (ie. in cases
* where the data set structure cannot be fully established before all
* instances have been seen) then an exception should be thrown.
*
* @param structure the dataset header information, will get updated in case
* of string or relational attributes
* @return the next instance in the data set as an Instance object or null if
* there are no more instances to be read
* @exception IOException if there is an error during parsing
*/
@Override
public Instance getNextInstance(Instances structure) throws IOException {
if (m_sourceFile == null) {
throw new IOException("No source has been specified");
}
if (getRetrieval() == BATCH) {
throw new IOException(
"Cannot mix getting Instances in both incremental and batch modes");
}
setRetrieval(INCREMENTAL);
if (m_structure == null) {
getStructure();
}
StreamTokenizer st = new StreamTokenizer(m_dataReader);
initTokenizer(st);
// st.ordinaryChar('.');
Instance nextI = getInstance(st);
if (nextI != null) {
nextI.setDataset(m_structure);
} else {
try {
// close the stream
m_dataReader.close();
// reset();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return nextI;
}
/**
* Reads an instance using the supplied tokenizer.
*
* @param tokenizer the tokenizer to use
* @return an Instance or null if there are no more instances to read
* @exception IOException if an error occurs
*/
private Instance getInstance(StreamTokenizer tokenizer) throws IOException {
double[] instance = new double[m_structure.numAttributes()];
StreamTokenizerUtils.getFirstToken(tokenizer);
if (tokenizer.ttype == StreamTokenizer.TT_EOF) {
return null;
}
int counter = 0;
for (int i = 0; i < m_numAttribs; i++) {
if (i > 0) {
StreamTokenizerUtils.getToken(tokenizer);
}
if (!m_ignore[i]) {
// Check if value is missing.
if (tokenizer.ttype == '?') {
instance[counter++] = Utils.missingValue();
} else {
String val = tokenizer.sval;
if (i == m_numAttribs - 1) {
// remove trailing period
if (val.charAt(val.length() - 1) == '.') {
val = val.substring(0, val.length() - 1);
}
}
if (m_structure.attribute(counter).isNominal()) {
int index = m_structure.attribute(counter).indexOfValue(val);
if (index == -1) {
StreamTokenizerUtils.errms(tokenizer,
"nominal value not declared in " + "header :" + val
+ " column " + i);
}
instance[counter++] = index;
} else if (m_structure.attribute(counter).isNumeric()) {
try {
instance[counter++] = Double.valueOf(val).doubleValue();
} catch (NumberFormatException e) {
StreamTokenizerUtils.errms(tokenizer, "number expected");
}
} else {
System.err.println("Shouldn't get here");
System.exit(1);
}
}
}
}
return new DenseInstance(1.0, instance);
}
/**
* removes the trailing period
*
* @param val the string to work on
* @return the processed string
*/
private String removeTrailingPeriod(String val) {
// remove trailing period
if (val.charAt(val.length() - 1) == '.') {
val = val.substring(0, val.length() - 1);
}
return val;
}
/**
* Reads header (from the names file) using the supplied tokenizer
*
* @param tokenizer the tokenizer to use
* @exception IOException if an error occurs
*/
private void readHeader(StreamTokenizer tokenizer) throws IOException {
ArrayList<Attribute> attribDefs = new ArrayList<Attribute>();
ArrayList<Integer> ignores = new ArrayList<Integer>();
StreamTokenizerUtils.getFirstToken(tokenizer);
if (tokenizer.ttype == StreamTokenizer.TT_EOF) {
StreamTokenizerUtils.errms(tokenizer, "premature end of file");
}
m_numAttribs = 1;
// Read the class values
ArrayList<String> classVals = new ArrayList<String>();
while (tokenizer.ttype != StreamTokenizer.TT_EOL) {
String val = tokenizer.sval.trim();
if (val.length() > 0) {
val = removeTrailingPeriod(val);
classVals.add(val);
}
StreamTokenizerUtils.getToken(tokenizer);
}
// read the attribute names and types
int counter = 0;
while (tokenizer.ttype != StreamTokenizer.TT_EOF) {
StreamTokenizerUtils.getFirstToken(tokenizer);
if (tokenizer.ttype != StreamTokenizer.TT_EOF) {
String attribName = tokenizer.sval;
StreamTokenizerUtils.getToken(tokenizer);
if (tokenizer.ttype == StreamTokenizer.TT_EOL) {
StreamTokenizerUtils.errms(tokenizer,
"premature end of line. Expected " + "attribute type.");
}
String temp = tokenizer.sval.toLowerCase().trim();
if (temp.startsWith("ignore") || temp.startsWith("label")) {
ignores.add(new Integer(counter));
counter++;
} else if (temp.startsWith("continuous")) {
attribDefs.add(new Attribute(attribName));
counter++;
} else {
counter++;
// read the values of the attribute
ArrayList<String> attribVals = new ArrayList<String>();
while (tokenizer.ttype != StreamTokenizer.TT_EOL
&& tokenizer.ttype != StreamTokenizer.TT_EOF) {
String val = tokenizer.sval.trim();
if (val.length() > 0) {
val = removeTrailingPeriod(val);
attribVals.add(val);
}
StreamTokenizerUtils.getToken(tokenizer);
}
attribDefs.add(new Attribute(attribName, attribVals));
}
}
}
boolean ok = true;
int i = -1;
if (classVals.size() == 1) {
// look to see if this is an attribute name (ala c5 names file style)
for (i = 0; i < attribDefs.size(); i++) {
if (attribDefs.get(i).name().compareTo(classVals.get(0)) == 0) {
ok = false;
m_numAttribs--;
break;
}
}
}
if (ok) {
attribDefs.add(new Attribute("Class", classVals));
}
m_structure = new Instances(m_fileStem, attribDefs, 0);
try {
if (ok) {
m_structure.setClassIndex(m_structure.numAttributes() - 1);
} else {
m_structure.setClassIndex(i);
}
} catch (Exception ex) {
ex.printStackTrace();
}
m_numAttribs = m_structure.numAttributes() + ignores.size();
m_ignore = new boolean[m_numAttribs];
for (i = 0; i < ignores.size(); i++) {
m_ignore[ignores.get(i).intValue()] = true;
}
}
/**
* Initializes the stream tokenizer
*
* @param tokenizer the tokenizer to initialize
*/
private void initTokenizer(StreamTokenizer tokenizer) {
tokenizer.resetSyntax();
tokenizer.whitespaceChars(0, (' ' - 1));
tokenizer.wordChars(' ', '\u00FF');
tokenizer.whitespaceChars(',', ',');
tokenizer.whitespaceChars(':', ':');
// tokenizer.whitespaceChars('.','.');
tokenizer.commentChar('|');
tokenizer.whitespaceChars('\t', '\t');
tokenizer.quoteChar('"');
tokenizer.quoteChar('\'');
tokenizer.eolIsSignificant(true);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method for testing this class.
*
* @param args should contain <filestem>[.names | data]
*/
public static void main(String[] args) {
runFileLoader(new C45Loader(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/C45Saver.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* C45Saver.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.RevisionUtils;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> Writes to a destination that is in the format used
* by the C4.5 algorithm.<br/>
* Therefore it outputs a names and a data file.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -i <the input file>
* The input file
* </pre>
*
* <pre>
* -o <the output file>
* The output file
* </pre>
*
* <pre>
* -c <the class index>
* The class index
* </pre>
*
* <!-- options-end -->
*
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
* @see Saver
*/
public class C45Saver extends AbstractFileSaver implements BatchConverter,
IncrementalConverter, OptionHandler {
/** for serialization */
static final long serialVersionUID = -821428878384253377L;
/** Constructor */
public C45Saver() {
resetOptions();
}
/**
* Returns a string describing this Saver
*
* @return a description of the Saver suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Writes to a destination that is in the format used by the C4.5 algorithm.\nTherefore it outputs a names and a data file.";
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "C4.5 file format";
}
/**
* Resets the Saver
*/
@Override
public void resetOptions() {
super.resetOptions();
setFileExtension(".names");
}
/**
* Returns the Capabilities of this saver.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
return result;
}
/**
* Saves an instances incrementally. Structure has to be set by using the
* setStructure() method or setInstances() method.
*
* @param inst the instance to save
* @throws IOException throws IOEXception if an instance cannot be saved
* incrementally.
*/
@Override
public void writeIncremental(Instance inst) throws IOException {
int writeMode = getWriteMode();
Instances structure = getInstances();
PrintWriter outW = null;
if (structure != null) {
if (structure.classIndex() == -1) {
structure.setClassIndex(structure.numAttributes() - 1);
System.err
.println("No class specified. Last attribute is used as class attribute.");
}
if (structure.attribute(structure.classIndex()).isNumeric()) {
throw new IOException(
"To save in C4.5 format the class attribute cannot be numeric.");
}
}
if (getRetrieval() == BATCH || getRetrieval() == NONE) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
if (retrieveFile() == null || getWriter() == null) {
throw new IOException(
"C4.5 format requires two files. Therefore no output to standard out can be generated.\nPlease specifiy output files using the -o option.");
}
outW = new PrintWriter(getWriter());
if (writeMode == WAIT) {
if (structure == null) {
setWriteMode(CANCEL);
if (inst != null) {
System.err
.println("Structure(Header Information) has to be set in advance");
}
} else {
setWriteMode(STRUCTURE_READY);
}
writeMode = getWriteMode();
}
if (writeMode == CANCEL) {
if (outW != null) {
outW.close();
}
cancel();
}
if (writeMode == STRUCTURE_READY) {
setWriteMode(WRITE);
// write header: here names file
for (int i = 0; i < structure.attribute(structure.classIndex())
.numValues(); i++) {
outW.write(structure.attribute(structure.classIndex()).value(i));
if (i < structure.attribute(structure.classIndex()).numValues() - 1) {
outW.write(",");
} else {
outW.write(".\n");
}
}
for (int i = 0; i < structure.numAttributes(); i++) {
if (i != structure.classIndex()) {
outW.write(structure.attribute(i).name() + ": ");
if (structure.attribute(i).isNumeric()
|| structure.attribute(i).isDate()) {
outW.write("continuous.\n");
} else {
Attribute temp = structure.attribute(i);
for (int j = 0; j < temp.numValues(); j++) {
outW.write(temp.value(j));
if (j < temp.numValues() - 1) {
outW.write(",");
} else {
outW.write(".\n");
}
}
}
}
}
outW.flush();
outW.close();
writeMode = getWriteMode();
String out = retrieveFile().getAbsolutePath();
setFileExtension(".data");
out = out.substring(0, out.lastIndexOf('.')) + getFileExtension();
File namesFile = new File(out);
try {
setFile(namesFile);
} catch (Exception ex) {
throw new IOException(
"Cannot create data file, only names file created.");
}
if (retrieveFile() == null || getWriter() == null) {
throw new IOException(
"Cannot create data file, only names file created.");
}
outW = new PrintWriter(getWriter());
}
if (writeMode == WRITE) {
if (structure == null) {
throw new IOException("No instances information available.");
}
if (inst != null) {
// write instance: here data file
for (int j = 0; j < inst.numAttributes(); j++) {
if (j != structure.classIndex()) {
if (inst.isMissing(j)) {
outW.write("?,");
} else if (structure.attribute(j).isNominal()
|| structure.attribute(j).isString()) {
outW.write(structure.attribute(j).value((int) inst.value(j))
+ ",");
} else {
outW.write("" + inst.value(j) + ",");
}
}
}
// write the class value
if (inst.isMissing(structure.classIndex())) {
outW.write("?");
} else {
outW.write(structure.attribute(structure.classIndex()).value(
(int) inst.value(structure.classIndex())));
}
outW.write("\n");
// flushes every 100 instances
m_incrementalCounter++;
if (m_incrementalCounter > 100) {
m_incrementalCounter = 0;
outW.flush();
}
} else {
// close
if (outW != null) {
outW.flush();
outW.close();
}
setFileExtension(".names");
m_incrementalCounter = 0;
resetStructure();
outW = null;
resetWriter();
}
}
}
/**
* Writes a Batch of instances
*
* @throws IOException throws IOException if saving in batch mode is not
* possible
*/
@Override
public void writeBatch() throws IOException {
Instances instances = getInstances();
if (instances == null) {
throw new IOException("No instances to save");
}
if (instances.classIndex() == -1) {
instances.setClassIndex(instances.numAttributes() - 1);
System.err
.println("No class specified. Last attribute is used as class attribute.");
}
if (instances.attribute(instances.classIndex()).isNumeric()) {
throw new IOException(
"To save in C4.5 format the class attribute cannot be numeric.");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
setRetrieval(BATCH);
if (retrieveFile() == null || getWriter() == null) {
throw new IOException(
"C4.5 format requires two files. Therefore no output to standard out can be generated.\nPlease specifiy output files using the -o option.");
}
setWriteMode(WRITE);
// print names file
setFileExtension(".names");
PrintWriter outW = new PrintWriter(getWriter());
for (int i = 0; i < instances.attribute(instances.classIndex()).numValues(); i++) {
outW.write(instances.attribute(instances.classIndex()).value(i));
if (i < instances.attribute(instances.classIndex()).numValues() - 1) {
outW.write(",");
} else {
outW.write(".\n");
}
}
for (int i = 0; i < instances.numAttributes(); i++) {
if (i != instances.classIndex()) {
outW.write(instances.attribute(i).name() + ": ");
if (instances.attribute(i).isNumeric()
|| instances.attribute(i).isDate()) {
outW.write("continuous.\n");
} else {
Attribute temp = instances.attribute(i);
for (int j = 0; j < temp.numValues(); j++) {
outW.write(temp.value(j));
if (j < temp.numValues() - 1) {
outW.write(",");
} else {
outW.write(".\n");
}
}
}
}
}
outW.flush();
outW.close();
// print data file
String out = retrieveFile().getAbsolutePath();
setFileExtension(".data");
out = out.substring(0, out.lastIndexOf('.')) + getFileExtension();
File namesFile = new File(out);
try {
setFile(namesFile);
} catch (Exception ex) {
throw new IOException(
"Cannot create data file, only names file created (Reason: "
+ ex.toString() + ").");
}
if (retrieveFile() == null || getWriter() == null) {
throw new IOException("Cannot create data file, only names file created.");
}
outW = new PrintWriter(getWriter());
// print data file
for (int i = 0; i < instances.numInstances(); i++) {
Instance temp = instances.instance(i);
for (int j = 0; j < temp.numAttributes(); j++) {
if (j != instances.classIndex()) {
if (temp.isMissing(j)) {
outW.write("?,");
} else if (instances.attribute(j).isNominal()
|| instances.attribute(j).isString()) {
outW.write(instances.attribute(j).value((int) temp.value(j)) + ",");
} else {
outW.write("" + temp.value(j) + ",");
}
}
}
// write the class value
if (temp.isMissing(instances.classIndex())) {
outW.write("?");
} else {
outW.write(instances.attribute(instances.classIndex()).value(
(int) temp.value(instances.classIndex())));
}
outW.write("\n");
}
outW.flush();
outW.close();
setFileExtension(".names");
setWriteMode(WAIT);
outW = null;
resetWriter();
setWriteMode(CANCEL);
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("The class index", "c", 1,
"-c <the class index>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* Parses a given list of options.
* <p/>
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -i <the input file>
* The input file
* </pre>
*
* <pre>
* -o <the output file>
* The output file
* </pre>
*
* <pre>
* -c <the class index>
* The class index
* </pre>
*
* <!-- 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 outputString = Utils.getOption('o', options);
String inputString = Utils.getOption('i', options);
String indexString = Utils.getOption('c', options);
ArffLoader loader = new ArffLoader();
resetOptions();
// parse index
int index = -1;
if (indexString.length() != 0) {
if (indexString.equals("first")) {
index = 0;
} else {
if (indexString.equals("last")) {
index = -1;
} else {
index = Integer.parseInt(indexString);
}
}
}
if (inputString.length() != 0) {
try {
File input = new File(inputString);
loader.setFile(input);
Instances inst = loader.getDataSet();
if (index == -1) {
inst.setClassIndex(inst.numAttributes() - 1);
} else {
inst.setClassIndex(index);
}
setInstances(inst);
} catch (Exception ex) {
throw new IOException(
"No data set loaded. Data set has to be arff format (Reason: "
+ ex.toString() + ").");
}
} else {
throw new IOException("No data set to save.");
}
if (outputString.length() != 0) {
// add appropriate file extension
if (!outputString.endsWith(getFileExtension())) {
if (outputString.lastIndexOf('.') != -1) {
outputString = (outputString.substring(0,
outputString.lastIndexOf('.')))
+ getFileExtension();
} else {
outputString = outputString + getFileExtension();
}
}
try {
File output = new File(outputString);
setFile(output);
} catch (Exception ex) {
throw new IOException("Cannot create output file.");
}
}
if (index == -1) {
index = getInstances().numAttributes() - 1;
}
getInstances().setClassIndex(index);
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the C45Saver object.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if (retrieveFile() != null) {
options.add("-o");
options.add("" + retrieveFile());
} else {
options.add("-o");
options.add("");
}
if (getInstances() != null) {
options.add("-i");
options.add("" + getInstances().relationName());
options.add("-c");
options.add("" + getInstances().classIndex());
} else {
options.add("-i");
options.add("");
options.add("-c");
options.add("");
}
Collections.addAll(options, super.getOptions());
return options.toArray(new String[0]);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method.
*
* @param args should contain the options of a Saver.
*/
public static void main(String[] args) {
runFileSaver(new C45Saver(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/CSVLoader.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* CSVLoader.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.Range;
import weka.core.Utils;
import weka.core.converters.ArffLoader.ArffReader;
/**
<!-- globalinfo-start -->
* Reads a source that is in comma separated format (the default). One can also change the column separator from comma to tab or another character, specify string enclosures, specify whether aheader row is present or not and specify which attributes are to beforced to be nominal or date. Can operate in batch or incremental mode. In batch mode, a buffer is used to process a fixed number of rows in memory at any one time and the data is dumped to a temporary file. This allows the legal values for nominal attributes to be automatically determined. The final ARFF file is produced in a second pass over the temporary file using the structure determined on the first pass. In incremental mode, the first buffer full of rows is used to determine the structure automatically. Following this all rows are read and output incrementally. An error will occur if a row containing nominal values not seen in the initial buffer is encountered. In this case, the size of the initial buffer can be increased, or the user can explicitly provide the legal values of all nominal attributes using the -L (setNominalLabelSpecs) option.
* <p/>
<!-- globalinfo-end -->
*
<!-- options-start -->
* Valid options are: <p/>
*
* <pre> -H
* No header row present in the data.</pre>
*
* <pre> -N <range>
* The range of attributes to force type to be NOMINAL.
* 'first' and 'last' are accepted as well.
* Examples: "first-last", "1,4,5-27,50-last"
* (default: -none-)</pre>
*
* <pre> -L <nominal label spec>
* Optional specification of legal labels for nominal
* attributes. May be specified multiple times.
* Batch mode can determine this
* automatically (and so can incremental mode if
* the first in memory buffer load of instances
* contains an example of each legal value). The
* spec contains two parts separated by a ":". The
* first part can be a range of attribute indexes or
* a comma-separated list off attruibute names; the
* second part is a comma-separated list of labels. E.g
* "1,2,4-6:red,green,blue" or "att1,att2:red,green,blue"</pre>
*
* <pre> -S <range>
* The range of attribute to force type to be STRING.
* 'first' and 'last' are accepted as well.
* Examples: "first-last", "1,4,5-27,50-last"
* (default: -none-)</pre>
*
* <pre> -D <range>
* The range of attribute to force type to be DATE.
* 'first' and 'last' are accepted as well.
* Examples: "first-last", "1,4,5-27,50-last"
* (default: -none-)</pre>
*
* <pre> -format <date format>
* The date formatting string to use to parse date values.
* (default: "yyyy-MM-dd'T'HH:mm:ss")</pre>
*
* <pre> -R <range>
* The range of attribute to force type to be NUMERIC.
* 'first' and 'last' are accepted as well.
* Examples: "first-last", "1,4,5-27,50-last"
* (default: -none-)</pre>
*
* <pre> -M <str>
* The string representing a missing value.
* (default: ?)</pre>
*
* <pre> -F <separator>
* The field separator to be used.
* '\t' can be used as well.
* (default: ',')</pre>
*
* <pre> -E <enclosures>
* The enclosure character(s) to use for strings.
* Specify as a comma separated list (e.g. ",' (default: ",')</pre>
*
* <pre> -B <num>
* The size of the in memory buffer (in rows).
* (default: 100)</pre>
*
<!-- options-end -->
*
* @author Mark Hall (mhall{[at]}pentaho{[dot]}com)
* @version $Revision$
*/
public class CSVLoader extends AbstractFileLoader implements BatchConverter,
IncrementalConverter, OptionHandler {
/** For serialization */
private static final long serialVersionUID = -1300595850715808438L;
/** the file extension. */
public static String FILE_EXTENSION = ".csv";
/** The reader for the data. */
protected transient BufferedReader m_sourceReader;
/** Tokenizer for the data. */
protected transient StreamTokenizer m_st;
protected transient File m_tempFile;
protected transient PrintWriter m_dataDumper;
/** the field separator. */
protected String m_FieldSeparator = ",";
/** The placeholder for missing values. */
protected String m_MissingValue = "?";
/** The range of attributes to force to type nominal. */
protected Range m_NominalAttributes = new Range();
/** The user-supplied legal nominal values - each entry in the list is a spec */
protected List<String> m_nominalLabelSpecs = new ArrayList<String>();
/** The range of attributes to force to type string. */
protected Range m_StringAttributes = new Range();
/** The range of attributes to force to type date */
protected Range m_dateAttributes = new Range();
/** The range of attributes to force to type numeric */
protected Range m_numericAttributes = new Range();
/** The formatting string to use to parse dates */
protected String m_dateFormat = "yyyy-MM-dd'T'HH:mm:ss";
/** The formatter to use on dates */
protected SimpleDateFormat m_formatter;
/** whether the csv file contains a header row with att names */
protected boolean m_noHeaderRow = false;
/** enclosure character(s) to use for strings */
protected String m_Enclosures = "\",\'";
/** The in memory row buffer */
protected List<String> m_rowBuffer;
/** The maximum number of rows to hold in memory at any one time */
protected int m_bufferSize = 100;
/** Lookup for nominal values */
protected Map<Integer, LinkedHashSet<String>> m_nominalVals;
/** Reader used to process and output data incrementally */
protected ArffReader m_incrementalReader;
protected transient int m_rowCount;
/**
* Array holding field separator and enclosures to pass through to the
* underlying ArffReader
*/
protected String[] m_fieldSeparatorAndEnclosures;
protected ArrayList<Object> m_current;
protected TYPE[] m_types;
private int m_numBufferedRows;
/**
* default constructor.
*/
public CSVLoader() {
// No instances retrieved yet
setRetrieval(NONE);
}
/**
* Main method.
*
* @param args should contain the name of an input file.
*/
public static void main(String[] args) {
runFileLoader(new CSVLoader(), args);
}
/**
* Returns a string describing this attribute evaluator.
*
* @return a description of the evaluator suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Reads a source that is in comma separated format (the default). "
+ "One can also change the column separator from comma to tab or "
+ "another character, specify string enclosures, specify whether a"
+ "header row is present or not and specify which attributes are to be"
+ "forced to be nominal or date. Can operate in batch or incremental mode. "
+ "In batch mode, a buffer is used to process a fixed number of rows in "
+ "memory at any one time and the data is dumped to a temporary file. This "
+ "allows the legal values for nominal attributes to be automatically "
+ "determined. The final ARFF file is produced in a second pass over the "
+ "temporary file using the structure determined on the first pass. In "
+ "incremental mode, the first buffer full of rows is used to determine "
+ "the structure automatically. Following this all rows are read and output "
+ "incrementally. An error will occur if a row containing nominal values not "
+ "seen in the initial buffer is encountered. In this case, the size of the "
+ "initial buffer can be increased, or the user can explicitly provide the "
+ "legal values of all nominal attributes using the -L (setNominalLabelSpecs) "
+ "option.";
}
@Override
public String getFileExtension() {
return FILE_EXTENSION;
}
@Override
public String[] getFileExtensions() {
return new String[] { getFileExtension() };
}
@Override
public String getFileDescription() {
return "CSV data files";
}
@Override
public String getRevision() {
return "$Revision$";
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String noHeaderRowPresentTipText() {
return "First row of data does not contain attribute names";
}
/**
* Get whether there is no header row in the data.
*
* @return true if there is no header row in the data
*/
public boolean getNoHeaderRowPresent() {
return m_noHeaderRow;
}
/**
* Set whether there is no header row in the data.
*
* @param b true if there is no header row in the data
*/
public void setNoHeaderRowPresent(boolean b) {
m_noHeaderRow = b;
}
/**
* Returns the current placeholder for missing values.
*
* @return the placeholder
*/
public String getMissingValue() {
return m_MissingValue;
}
/**
* Sets the placeholder for missing values.
*
* @param value the placeholder
*/
public void setMissingValue(String value) {
m_MissingValue = value;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String missingValueTipText() {
return "The placeholder for missing values, default is '?'.";
}
/**
* Returns the current attribute range to be forced to type string.
*
* @return the range
*/
public String getStringAttributes() {
return m_StringAttributes.getRanges();
}
/**
* Sets the attribute range to be forced to type string.
*
* @param value the range
*/
public void setStringAttributes(String value) {
m_StringAttributes.setRanges(value);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
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'.";
}
/**
* Returns the current attribute range to be forced to type nominal.
*
* @return the range
*/
public String getNominalAttributes() {
return m_NominalAttributes.getRanges();
}
/**
* Sets the attribute range to be forced to type nominal.
*
* @param value the range
*/
public void setNominalAttributes(String value) {
m_NominalAttributes.setRanges(value);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
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'.";
}
/**
* Gets the attribute range to be forced to type numeric
*
* @return the range
*/
public String getNumericAttributes() {
return m_numericAttributes.getRanges();
}
/**
* Sets the attribute range to be forced to type numeric
*
* @param value the range
*/
public void setNumericAttributes(String value) {
m_numericAttributes.setRanges(value);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String numericAttributesTipText() {
return "The range of attributes to force to be of type NUMERIC, example "
+ "ranges: 'first-last', '1,4,7-14,50-last'.";
}
/**
* Get the format to use for parsing date values.
*
* @return the format to use for parsing date values.
*
*/
public String getDateFormat() {
return m_dateFormat;
}
/**
* Set the format to use for parsing date values.
*
* @param value the format to use.
*/
public void setDateFormat(String value) {
m_dateFormat = value;
m_formatter = null;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String dateFormatTipText() {
return "The format to use for parsing date values.";
}
/**
* Returns the current attribute range to be forced to type date.
*
* @return the range.
*/
public String getDateAttributes() {
return m_dateAttributes.getRanges();
}
/**
* Set the attribute range to be forced to type date.
*
* @param value the range
*/
public void setDateAttributes(String value) {
m_dateAttributes.setRanges(value);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String dateAttributesTipText() {
return "The range of attributes to force to type DATE, example "
+ "ranges: 'first-last', '1,4,7-14, 50-last'.";
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String enclosureCharactersTipText() {
return "The characters to use as enclosures for strings. E.g. \",'";
}
/**
* Get the character(s) to use/recognize as string enclosures
*
* @return the characters to use as string enclosures
*/
public String getEnclosureCharacters() {
return m_Enclosures;
}
/**
* Set the character(s) to use/recognize as string enclosures
*
* @param enclosure the characters to use as string enclosures
*/
public void setEnclosureCharacters(String enclosure) {
m_Enclosures = enclosure;
}
/**
* Returns the character used as column separator.
*
* @return the character to use
*/
public String getFieldSeparator() {
return Utils.backQuoteChars(m_FieldSeparator);
}
/**
* Sets the character used as column separator.
*
* @param value the character to use
*/
public void setFieldSeparator(String value) {
m_FieldSeparator = Utils.unbackQuoteChars(value);
if (m_FieldSeparator.length() != 1) {
m_FieldSeparator = ",";
System.err
.println("Field separator can only be a single character (exception being '\t'), "
+ "defaulting back to '" + m_FieldSeparator + "'!");
}
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String fieldSeparatorTipText() {
return "The character to use as separator for the columns/fields (use '\\t' for TAB).";
}
/**
* Get the buffer size to use - i.e. the number of rows to load and process in
* memory at any one time
*
* @return
*/
public int getBufferSize() {
return m_bufferSize;
}
/**
* Set the buffer size to use - i.e. the number of rows to load and process in
* memory at any one time
*
* @param buff the buffer size (number of rows)
*/
public void setBufferSize(int buff) {
m_bufferSize = buff;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String bufferSizeTipText() {
return "The number of rows to process in memory at any one time.";
}
/**
* Get label specifications for nominal attributes.
*
* @return an array of label specifications
*/
public Object[] getNominalLabelSpecs() {
return m_nominalLabelSpecs.toArray(new String[0]);
}
/**
* Set label specifications for nominal attributes.
*
* @param specs an array of label specifications
*/
public void setNominalLabelSpecs(Object[] specs) {
m_nominalLabelSpecs.clear();
for (Object s : specs) {
m_nominalLabelSpecs.add(s.toString());
}
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String nominalLabelSpecsTipText() {
return "Optional specification of legal labels for nominal "
+ "attributes. May be specified multiple times. "
+ "Batch mode can determine this "
+ "automatically (and so can incremental mode if "
+ "the first in memory buffer load of instances "
+ "contains an example of each legal value). The "
+ "spec contains two parts separated by a \":\". The "
+ "first part can be a range of attribute indexes or "
+ "a comma-separated list off attruibute names; the "
+ "second part is a comma-separated list of labels. E.g "
+ "\"1,2,4-6:red,green,blue\" or \"att1,att2:red,green,blue\"";
}
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result
.add(new Option("\tNo header row present in the data.", "H", 0, "-H"));
result.add(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>"));
result.add(new Option(
"\tOptional specification of legal labels for nominal\n"
+ "\tattributes. May be specified multiple times.\n"
+ "\tBatch mode can determine this\n"
+ "\tautomatically (and so can incremental mode if\n"
+ "\tthe first in memory buffer load of instances\n"
+ "\tcontains an example of each legal value). The\n"
+ "\tspec contains two parts separated by a \":\". The\n"
+ "\tfirst part can be a range of attribute indexes or\n"
+ "\ta comma-separated list off attruibute names; the\n"
+ "\tsecond part is a comma-separated list of labels. E.g\n"
+ "\t\"1,2,4-6:red,green,blue\" or \"att1,att2:red,green," + "blue\"",
"L", 1, "-L <nominal label spec>"));
result.add(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>"));
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>"));
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>"));
result.add(new Option(
"\tThe range of attribute to force type to be NUMERIC.\n"
+ "\t'first' and 'last' are accepted as well.\n"
+ "\tExamples: \"first-last\", \"1,4,5-27,50-last\"\n"
+ "\t(default: -none-)", "R", 1, "-R <range>"));
result.add(new Option("\tThe string representing a missing value.\n"
+ "\t(default: ?)", "M", 1, "-M <str>"));
result.addElement(new Option("\tThe field separator to be used.\n"
+ "\t'\\t' can be used as well.\n" + "\t(default: ',')", "F", 1,
"-F <separator>"));
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>"));
result.add(new Option("\tThe size of the in memory buffer (in rows).\n"
+ "\t(default: 100)", "B", 1, "-B <num>"));
return result.elements();
}
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
if (getNominalAttributes().length() > 0) {
result.add("-N");
result.add(getNominalAttributes());
}
if (getStringAttributes().length() > 0) {
result.add("-S");
result.add(getStringAttributes());
}
if (getDateAttributes().length() > 0) {
result.add("-D");
result.add(getDateAttributes());
}
result.add("-format");
result.add(getDateFormat());
if (getNumericAttributes().length() > 0) {
result.add("-R");
result.add(getNumericAttributes());
}
result.add("-M");
result.add(getMissingValue());
result.add("-B");
result.add("" + getBufferSize());
result.add("-E");
result.add(getEnclosureCharacters());
result.add("-F");
result.add(getFieldSeparator());
for (String spec : m_nominalLabelSpecs) {
result.add("-L");
result.add(spec);
}
return result.toArray(new String[result.size()]);
}
@Override
public void setOptions(String[] options) throws Exception {
String tmpStr;
setNoHeaderRowPresent(Utils.getFlag('H', options));
tmpStr = Utils.getOption('N', options);
if (tmpStr.length() != 0) {
setNominalAttributes(tmpStr);
} else {
setNominalAttributes("");
}
tmpStr = Utils.getOption('S', options);
if (tmpStr.length() != 0) {
setStringAttributes(tmpStr);
} else {
setStringAttributes("");
}
tmpStr = Utils.getOption('D', options);
if (tmpStr.length() > 0) {
setDateAttributes(tmpStr);
}
tmpStr = Utils.getOption("format", options);
if (tmpStr.length() > 0) {
setDateFormat(tmpStr);
}
tmpStr = Utils.getOption( 'R', options );
if (tmpStr.length() > 0) {
setNumericAttributes( tmpStr );
}
tmpStr = Utils.getOption('M', options);
if (tmpStr.length() != 0) {
setMissingValue(tmpStr);
} else {
setMissingValue("?");
}
tmpStr = Utils.getOption('F', options);
if (tmpStr.length() != 0) {
setFieldSeparator(tmpStr);
} else {
setFieldSeparator(",");
}
tmpStr = Utils.getOption('B', options);
if (tmpStr.length() > 0) {
int buff = Integer.parseInt(tmpStr);
if (buff < 1) {
throw new Exception("Buffer size must be >= 1");
}
setBufferSize(buff);
}
tmpStr = Utils.getOption("E", options);
if (tmpStr.length() > 0) {
setEnclosureCharacters(tmpStr);
}
while (true) {
tmpStr = Utils.getOption('L', options);
if (tmpStr.length() == 0) {
break;
}
m_nominalLabelSpecs.add(tmpStr);
}
}
@Override
public Instance getNextInstance(Instances structure) throws IOException {
m_structure = structure;
if (getRetrieval() == BATCH) {
throw new IOException(
"Cannot mix getting instances in both incremental and batch modes");
}
setRetrieval(INCREMENTAL);
if (m_dataDumper != null) {
// close the uneeded temp files (if necessary)
m_dataDumper.close();
m_dataDumper = null;
}
if (m_rowBuffer.size() > 0 && m_incrementalReader == null) {
StringBuilder tempB = new StringBuilder();
for (String r : m_rowBuffer) {
tempB.append(r).append("\n");
}
m_numBufferedRows = m_rowBuffer.size();
Reader batchReader =
new BufferedReader(new StringReader(tempB.toString()));
m_incrementalReader =
new ArffReader(batchReader, m_structure, 0, 0,
m_fieldSeparatorAndEnclosures);
m_rowBuffer.clear();
}
if (m_numBufferedRows == 0) {
// m_incrementalReader = new ArffReader(m_sourceReader, m_structure, 0,
// 0);
m_numBufferedRows = -1;
m_st = new StreamTokenizer(m_sourceReader);
initTokenizer(m_st);
m_st.ordinaryChar(m_FieldSeparator.charAt(0));
//
m_incrementalReader = null;
}
Instance current = null;
if (m_sourceReader != null) {
if (m_incrementalReader != null) {
current = m_incrementalReader.readInstance(m_structure);
} else {
if (getInstance(m_st) != null) {
current = makeInstance();
}
}
if (current == null) {
}
if (m_numBufferedRows > 0) {
m_numBufferedRows--;
}
}
if ((m_sourceReader != null) && (current == null)) {
try {
// close the stream
m_sourceReader.close();
m_sourceReader = null;
// reset();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return current;
}
@Override
public Instances getDataSet() throws IOException {
if (m_sourceReader == null) {
throw new IOException("No source has been specified");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException(
"Cannot mix getting instances in both incremental and batch modes");
}
setRetrieval(BATCH);
if (m_structure == null) {
getStructure();
}
while (readData(true)) {
;
}
m_dataDumper.flush();
m_dataDumper.close();
// make final structure
makeStructure();
Reader sr = new BufferedReader(new FileReader(m_tempFile));
ArffReader initialArff =
new ArffReader(sr, m_structure, 0, m_fieldSeparatorAndEnclosures);
Instances initialInsts = initialArff.getData();
sr.close();
initialArff = null;
return initialInsts;
}
private boolean readData(boolean dump) throws IOException {
if (m_sourceReader == null) {
throw new IOException("No source has been specified");
}
boolean finished = false;
do {
String checked = getInstance(m_st);
if (checked == null) {
return false;
}
if (dump) {
dumpRow(checked);
}
m_rowBuffer.add(checked);
if (m_rowBuffer.size() == m_bufferSize) {
finished = true;
if (getRetrieval() == BATCH) {
m_rowBuffer.clear();
}
}
} while (!finished);
return true;
}
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied Stream object.
*
* @param input the input stream
* @exception IOException if an error occurs
*/
@Override
public void setSource(InputStream input) throws IOException {
m_structure = null;
m_sourceFile = null;
m_File = null;
m_sourceReader = new BufferedReader(new InputStreamReader(input));
}
/**
* Resets the Loader object and sets the source of the data set to be the
* supplied File object.
*
* @param file the source file.
* @exception IOException if an error occurs
*/
@Override
public void setSource(File file) throws IOException {
super.setSource(file);
}
@Override
public Instances getStructure() throws IOException {
if (m_sourceReader == null) {
throw new IOException("No source has been specified");
}
m_fieldSeparatorAndEnclosures = separatorAndEnclosuresToArray();
if (m_structure == null) {
readHeader();
}
return m_structure;
}
protected Instance makeInstance() throws IOException {
if (m_current == null) {
return null;
}
double[] vals = new double[m_structure.numAttributes()];
for (int i = 0; i < m_structure.numAttributes(); i++) {
Object val = m_current.get(i);
if (val.toString().equals("?")) {
vals[i] = Utils.missingValue();
} else if (m_structure.attribute(i).isString()) {
vals[i] = 0;
m_structure.attribute(i).setStringValue(Utils.unquote(val.toString()));
} else if (m_structure.attribute(i).isDate()) {
String format = m_structure.attribute(i).getDateFormat();
SimpleDateFormat sdf = new SimpleDateFormat(format);
String dateVal = Utils.unquote(val.toString());
try {
vals[i] = sdf.parse(dateVal).getTime();
} catch (ParseException e) {
throw new IOException("Unable to parse date value " + dateVal
+ " using date format " + format + " for date attribute "
+ m_structure.attribute(i) + " (line: " + m_rowCount + ")");
}
} else if (m_structure.attribute(i).isNumeric()) {
try {
Double v = Double.parseDouble(val.toString());
vals[i] = v.doubleValue();
} catch (NumberFormatException ex) {
throw new IOException("Was expecting a number for attribute "
+ m_structure.attribute(i).name() + " but read " + val.toString()
+ " instead. (line: " + m_rowCount + ")");
}
} else {
// nominal
double index =
m_structure.attribute(i).indexOfValue(Utils.unquote(val.toString()));
if (index < 0) {
throw new IOException("Read unknown nominal value " + val.toString()
+ "for attribute " + m_structure.attribute(i).name() + " (line: "
+ m_rowCount + "). Try increasing the size of the memory buffer"
+ " (-B option) or explicitly specify legal nominal values with "
+ "the -L option.");
}
vals[i] = index;
}
}
DenseInstance inst = new DenseInstance(1.0, vals);
inst.setDataset(m_structure);
return inst;
}
protected void makeStructure() {
// make final structure
ArrayList<Attribute> attribs = new ArrayList<Attribute>();
for (int i = 0; i < m_types.length; i++) {
if (m_types[i] == TYPE.STRING || m_types[i] == TYPE.UNDETERMINED) {
attribs.add(new Attribute(m_structure.attribute(i).name(),
(java.util.List<String>) null));
} else if (m_types[i] == TYPE.NUMERIC) {
attribs.add(new Attribute(m_structure.attribute(i).name()));
} else if (m_types[i] == TYPE.NOMINAL) {
LinkedHashSet<String> vals = m_nominalVals.get(i);
ArrayList<String> theVals = new ArrayList<String>();
if (vals.size() > 0) {
for (String v : vals) {
/*
* if (v.startsWith("'") || v.startsWith("\"")) { v = v.substring(1,
* v.length() - 1); }
*/
theVals.add(v);
}
} else {
theVals.add("*unknown*");
}
attribs.add(new Attribute(m_structure.attribute(i).name(), theVals));
} else {
attribs
.add(new Attribute(m_structure.attribute(i).name(), m_dateFormat));
}
}
m_structure = new Instances(m_structure.relationName(), attribs, 0);
}
private void readHeader() throws IOException {
m_rowCount = 1;
m_incrementalReader = null;
m_current = new ArrayList<Object>();
openTempFiles();
m_rowBuffer = new ArrayList<String>();
String firstRow = m_sourceReader.readLine();
if (firstRow == null) {
throw new IOException("No data in the file!");
}
if (m_noHeaderRow) {
m_rowBuffer.add(firstRow);
}
ArrayList<Attribute> attribNames = new ArrayList<Attribute>();
// now tokenize to determine attribute names (or create att names if
// no header row
StringReader sr = new StringReader(firstRow + "\n");
// System.out.print(firstRow + "\n");
m_st = new StreamTokenizer(sr);
initTokenizer(m_st);
m_st.ordinaryChar(m_FieldSeparator.charAt(0));
int attNum = 1;
StreamTokenizerUtils.getFirstToken(m_st);
if (m_st.ttype == StreamTokenizer.TT_EOF) {
StreamTokenizerUtils.errms(m_st, "premature end of file");
}
boolean first = true;
boolean wasSep;
while (m_st.ttype != StreamTokenizer.TT_EOL
&& m_st.ttype != StreamTokenizer.TT_EOF) {
// Get next token
if (!first) {
StreamTokenizerUtils.getToken(m_st);
}
if (m_st.ttype == m_FieldSeparator.charAt(0)
|| m_st.ttype == StreamTokenizer.TT_EOL) {
wasSep = true;
} else {
wasSep = false;
String attName = null;
if (m_noHeaderRow) {
attName = "att" + attNum;
attNum++;
} else {
attName = m_st.sval;
}
attribNames.add(new Attribute(attName, (java.util.List<String>) null));
}
if (!wasSep) {
StreamTokenizerUtils.getToken(m_st);
}
first = false;
}
String relationName;
if (m_sourceFile != null) {
relationName =
(m_sourceFile.getName()).replaceAll("\\.[cC][sS][vV]$", "");
} else {
relationName = "stream";
}
m_structure = new Instances(relationName, attribNames, 0);
m_NominalAttributes.setUpper(m_structure.numAttributes() - 1);
m_StringAttributes.setUpper(m_structure.numAttributes() - 1);
m_dateAttributes.setUpper(m_structure.numAttributes() - 1);
m_numericAttributes.setUpper(m_structure.numAttributes() - 1);
m_nominalVals = new HashMap<Integer, LinkedHashSet<String>>();
m_types = new TYPE[m_structure.numAttributes()];
for (int i = 0; i < m_structure.numAttributes(); i++) {
if (m_NominalAttributes.isInRange(i)) {
m_types[i] = TYPE.NOMINAL;
LinkedHashSet<String> ts = new LinkedHashSet<String>();
m_nominalVals.put(i, ts);
} else if (m_StringAttributes.isInRange(i)) {
m_types[i] = TYPE.STRING;
} else if (m_dateAttributes.isInRange(i)) {
m_types[i] = TYPE.DATE;
} else if (m_numericAttributes.isInRange(i)) {
m_types[i] = TYPE.NUMERIC;
} else {
m_types[i] = TYPE.UNDETERMINED;
}
}
if (m_nominalLabelSpecs.size() > 0) {
for (String spec : m_nominalLabelSpecs) {
String[] attsAndLabels = spec.split(":");
if (attsAndLabels.length == 2) {
String[] labels = attsAndLabels[1].split(",");
try {
// try as a range string first
Range tempR = new Range();
tempR.setRanges(attsAndLabels[0].trim());
tempR.setUpper(m_structure.numAttributes() - 1);
int[] rangeIndexes = tempR.getSelection();
for (int i = 0; i < rangeIndexes.length; i++) {
m_types[rangeIndexes[i]] = TYPE.NOMINAL;
LinkedHashSet<String> ts = new LinkedHashSet<String>();
for (String lab : labels) {
ts.add(lab);
}
m_nominalVals.put(rangeIndexes[i], ts);
}
} catch (IllegalArgumentException e) {
// one or more named attributes?
String[] attNames = attsAndLabels[0].split(",");
for (String attN : attNames) {
Attribute a = m_structure.attribute(attN.trim());
if (a != null) {
int attIndex = a.index();
m_types[attIndex] = TYPE.NOMINAL;
LinkedHashSet<String> ts = new LinkedHashSet<String>();
for (String lab : labels) {
ts.add(lab);
}
m_nominalVals.put(attIndex, ts);
}
}
}
}
}
}
// Prevents the first row from getting lost in the
// case where there is no header row and we're
// running in batch mode
if (m_noHeaderRow && getRetrieval() == BATCH) {
StreamTokenizer tempT = new StreamTokenizer(new StringReader(firstRow));
initTokenizer(tempT);
tempT.ordinaryChar(m_FieldSeparator.charAt(0));
String checked = getInstance(tempT);
dumpRow(checked);
}
m_st = new StreamTokenizer(m_sourceReader);
initTokenizer(m_st);
m_st.ordinaryChar(m_FieldSeparator.charAt(0));
// try and determine a more accurate structure from the first batch
readData(false || getRetrieval() == BATCH);
makeStructure();
}
protected void openTempFiles() throws IOException {
String tempPrefix = "" + Math.random() + "arffOut";
m_tempFile = File.createTempFile(tempPrefix, null);
m_tempFile.deleteOnExit();
Writer os2 = new FileWriter(m_tempFile);
m_dataDumper = new PrintWriter(new BufferedWriter(os2));
}
protected void dumpRow(String row) throws IOException {
m_dataDumper.println(row);
};
/**
* Assemble the field separator and enclosures into an array of Strings
*
* @return the field separator and enclosures as an array of strings
*/
private String[] separatorAndEnclosuresToArray() {
String[] parts = m_Enclosures.split(",");
String[] result = new String[parts.length + 1];
result[0] = m_FieldSeparator;
int index = 1;
for (String e : parts) {
if (e.length() > 1 || e.length() == 0) {
throw new IllegalArgumentException(
"Enclosures can only be single characters");
}
result[index++] = e;
}
return result;
}
/**
* Initializes the stream tokenizer.
*
* @param tokenizer the tokenizer to initialize
*/
private void initTokenizer(StreamTokenizer tokenizer) {
tokenizer.resetSyntax();
tokenizer.whitespaceChars(0, (' ' - 1));
tokenizer.wordChars(' ', '\u00FF');
tokenizer.whitespaceChars(m_FieldSeparator.charAt(0),
m_FieldSeparator.charAt(0));
// tokenizer.commentChar('%');
String[] parts = m_Enclosures.split(",");
for (String e : parts) {
if (e.length() > 1 || e.length() == 0) {
throw new IllegalArgumentException(
"Enclosures can only be single characters");
}
tokenizer.quoteChar(e.charAt(0));
}
tokenizer.eolIsSignificant(true);
}
/**
* Attempts to parse a line of the data set.
*
* @param tokenizer the tokenizer
* @return a String version of the instance that has had String and nominal
* attribute values quoted if necessary
* @exception IOException if an error occurs
*
* <pre>
* <jml>
* private_normal_behavior
* requires: tokenizer != null;
* ensures: \result != null;
* also
* private_exceptional_behavior
* requires: tokenizer == null
* || (* unsucessful parse *);
* signals: (IOException);
* </jml>
* </pre>
*/
private String getInstance(StreamTokenizer tokenizer) throws IOException {
try {
// Check if end of file reached.
StreamTokenizerUtils.getFirstToken(tokenizer);
if (tokenizer.ttype == StreamTokenizer.TT_EOF) {
return null;
}
boolean first = true;
boolean wasSep;
m_current.clear();
int i = 0;
while (tokenizer.ttype != StreamTokenizer.TT_EOL
&& tokenizer.ttype != StreamTokenizer.TT_EOF) {
// Get next token
if (!first) {
StreamTokenizerUtils.getToken(tokenizer);
}
if (tokenizer.ttype == m_FieldSeparator.charAt(0)
|| tokenizer.ttype == StreamTokenizer.TT_EOL) {
m_current.add("?");
wasSep = true;
} else {
wasSep = false;
if (tokenizer.sval.equals(m_MissingValue)
|| tokenizer.sval.trim().length() == 0) {
m_current.add("?");
} else if (m_types[i] == TYPE.NUMERIC
|| m_types[i] == TYPE.UNDETERMINED) {
// try to parse as a number
try {
Double.parseDouble(tokenizer.sval);
m_current.add(tokenizer.sval);
m_types[i] = TYPE.NUMERIC;
} catch (NumberFormatException e) {
// otherwise assume its an enumerated value
m_current.add(Utils.quote(tokenizer.sval));
if (m_types[i] == TYPE.UNDETERMINED) {
m_types[i] = TYPE.NOMINAL;
LinkedHashSet<String> ts = new LinkedHashSet<String>();
ts.add(tokenizer.sval);
m_nominalVals.put(i, ts);
} else {
m_types[i] = TYPE.STRING;
}
}
} else if (m_types[i] == TYPE.STRING || m_types[i] == TYPE.DATE) {
m_current.add(Utils.quote(tokenizer.sval));
} else if (m_types[i] == TYPE.NOMINAL) {
m_current.add(Utils.quote(tokenizer.sval));
m_nominalVals.get(i).add(tokenizer.sval);
}
}
if (!wasSep) {
StreamTokenizerUtils.getToken(tokenizer);
}
first = false;
i++;
}
// check number of values read
if (m_current.size() != m_structure.numAttributes()) {
for (Object o : m_current) {
System.out.print(o.toString() + "|||");
}
System.out.println();
StreamTokenizerUtils.errms(tokenizer, "wrong number of values. Read "
+ m_current.size() + ", expected " + m_structure.numAttributes());
}
} catch (Exception ex) {
throw new IOException(ex.getMessage() + " Problem encountered on line: "
+ (m_rowCount + 1));
}
StringBuilder temp = new StringBuilder();
for (Object o : m_current) {
temp.append(o.toString()).append(m_FieldSeparator);
}
m_rowCount++;
return temp.substring(0, temp.length() - 1);
}
@Override
public void reset() throws IOException {
m_structure = null;
m_rowBuffer = null;
if (m_dataDumper != null) {
// close the unneeded temp files (if necessary)
m_dataDumper.close();
m_dataDumper = null;
}
if (m_sourceReader != null) {
m_sourceReader.close();
}
if (m_File != null) {
setFile(new File(m_File));
}
}
enum TYPE {
UNDETERMINED, NUMERIC, NOMINAL, STRING, DATE
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/CSVSaver.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* CSVSaver.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Vector;
import weka.core.AbstractInstance;
import weka.core.Capabilities;
import weka.core.Capabilities.Capability;
import weka.core.DenseInstance;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
/**
* <!-- globalinfo-start --> Writes to a destination that is in CSV
* (comma-separated values) format. The column separator can be chosen (default
* is ',') as well as the value representing missing values (default is '?').
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -F <separator>
* The field separator to be used.
* '\t' can be used as well.
* (default: ',')
* </pre>
*
* <pre>
* -M <str>
* The string representing a missing value.
* (default: ?)
* </pre>
*
* <pre>
* -N
* Don't write a header row.
* </pre>
*
* <pre>
* -decimal <num>
* The maximum number of digits to print after the decimal
* place for numeric values (default: 6)
* </pre>
*
* <pre>
* -i <the input file>
* The input file
* </pre>
*
* <pre>
* -o <the output file>
* The output file
* </pre>
*
* <!-- options-end -->
*
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
* @see Saver
*/
public class CSVSaver extends AbstractFileSaver implements BatchConverter,
IncrementalConverter, FileSourcedConverter {
/** for serialization. */
static final long serialVersionUID = 476636654410701807L;
/** the field separator. */
protected String m_FieldSeparator = ",";
/** The placeholder for missing values. */
protected String m_MissingValue = "?";
/** Max number of decimal places for numeric values */
protected int m_MaxDecimalPlaces = AbstractInstance.s_numericAfterDecimalPoint;
/** Set to true to not write the header row */
protected boolean m_noHeaderRow = false;
/**
* Constructor.
*/
public CSVSaver() {
resetOptions();
}
/**
* Returns a string describing this Saver.
*
* @return a description of the Saver suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Writes to a destination that is in CSV (comma-separated values) format. "
+ "The column separator can be chosen (default is ',') as well as the value "
+ "representing missing values (default is '?').";
}
/**
* Returns an enumeration describing the available options.
*
* @return an enumeration of all the available options.
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> result = new Vector<Option>();
result.addElement(new Option("\tThe field separator to be used.\n"
+ "\t'\\t' can be used as well.\n" + "\t(default: ',')", "F", 1,
"-F <separator>"));
result.addElement(new Option("\tThe string representing a missing value.\n"
+ "\t(default: ?)", "M", 1, "-M <str>"));
result.addElement(new Option("\tDon't write a header row.", "N", 0, "-N"));
result.addElement(new Option(
"\tThe maximum number of digits to print after the decimal\n"
+ "\tplace for numeric values (default: 6)", "decimal", 1,
"-decimal <num>"));
result.addAll(Collections.list(super.listOptions()));
return result.elements();
}
/**
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -F <separator>
* The field separator to be used.
* '\t' can be used as well.
* (default: ',')
* </pre>
*
* <pre>
* -M <str>
* The string representing a missing value.
* (default: ?)
* </pre>
*
* <pre>
* -N
* Don't write a header row.
* </pre>
*
* <pre>
* -decimal <num>
* The maximum number of digits to print after the decimal
* place for numeric values (default: 6)
* </pre>
*
* <pre>
* -i <the input file>
* The input file
* </pre>
*
* <pre>
* -o <the output file>
* The output file
* </pre>
*
* <!-- 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;
tmpStr = Utils.getOption('F', options);
if (tmpStr.length() != 0) {
setFieldSeparator(tmpStr);
} else {
setFieldSeparator(",");
}
tmpStr = Utils.getOption('M', options);
if (tmpStr.length() != 0) {
setMissingValue(tmpStr);
} else {
setMissingValue("?");
}
setNoHeaderRow(Utils.getFlag('N', options));
tmpStr = Utils.getOption("decimal", options);
if (tmpStr.length() > 0) {
setMaxDecimalPlaces(Integer.parseInt(tmpStr));
}
super.setOptions(options);
Utils.checkForRemainingOptions(options);
}
/**
* Gets the current settings of the Classifier.
*
* @return an array of strings suitable for passing to setOptions
*/
@Override
public String[] getOptions() {
Vector<String> result = new Vector<String>();
result.add("-F");
result.add(getFieldSeparator());
result.add("-M");
result.add(getMissingValue());
if (getNoHeaderRow()) {
result.add("-N");
}
result.add("-decimal");
result.add("" + getMaxDecimalPlaces());
Collections.addAll(result, super.getOptions());
return result.toArray(new String[result.size()]);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String noHeaderRowTipText() {
return "If true then the header row is not written";
}
/**
* Set whether to not write the header row
*
* @param b true if no header row is to be written
*/
public void setNoHeaderRow(boolean b) {
m_noHeaderRow = b;
}
/**
* Get whether to not write the header row
*
* @return true if no header row is to be written
*/
public boolean getNoHeaderRow() {
return m_noHeaderRow;
}
/**
* Set the maximum number of decimal places to print
*
* @param maxDecimal the maximum number of decimal places to print
*/
public void setMaxDecimalPlaces(int maxDecimal) {
m_MaxDecimalPlaces = maxDecimal;
}
/**
* Get the maximum number of decimal places to print
*
* @return the maximum number of decimal places to print
*/
public int getMaxDecimalPlaces() {
return m_MaxDecimalPlaces;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String maxDecimalPlacesTipText() {
return "The maximum number of digits to print after the decimal "
+ "point for numeric values";
}
/**
* Sets the character used as column separator.
*
* @param value the character to use
*/
public void setFieldSeparator(String value) {
m_FieldSeparator = Utils.unbackQuoteChars(value);
/*
* if (m_FieldSeparator.length() != 1) { m_FieldSeparator = ","; System.err
* .println(
* "Field separator can only be a single character (exception being '\t'), "
* + "defaulting back to '" + m_FieldSeparator + "'!"); }
*/
}
/**
* Returns the character used as column separator.
*
* @return the character to use
*/
public String getFieldSeparator() {
return Utils.backQuoteChars(m_FieldSeparator);
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String fieldSeparatorTipText() {
return "The character to use as separator for the columns/fields (use '\\t' for TAB).";
}
/**
* Sets the placeholder for missing values.
*
* @param value the placeholder
*/
public void setMissingValue(String value) {
m_MissingValue = value;
}
/**
* Returns the current placeholder for missing values.
*
* @return the placeholder
*/
public String getMissingValue() {
return m_MissingValue;
}
/**
* Returns the tip text for this property.
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String missingValueTipText() {
return "The placeholder for missing values, default is '?'.";
}
/**
* Returns a description of the file type.
*
* @return a short file description
*/
@Override
public String getFileDescription() {
return "CSV file: comma separated files";
}
/**
* Resets the Saver.
*/
@Override
public void resetOptions() {
super.resetOptions();
setFileExtension(".csv");
}
/**
* Returns the Capabilities of this saver.
*
* @return the capabilities of this object
* @see Capabilities
*/
@Override
public Capabilities getCapabilities() {
Capabilities result = super.getCapabilities();
// attributes
result.enable(Capability.NOMINAL_ATTRIBUTES);
result.enable(Capability.NUMERIC_ATTRIBUTES);
result.enable(Capability.DATE_ATTRIBUTES);
result.enable(Capability.STRING_ATTRIBUTES);
result.enable(Capability.MISSING_VALUES);
// class
result.enable(Capability.NOMINAL_CLASS);
result.enable(Capability.NUMERIC_CLASS);
result.enable(Capability.DATE_CLASS);
result.enable(Capability.STRING_CLASS);
result.enable(Capability.MISSING_CLASS_VALUES);
result.enable(Capability.NO_CLASS);
return result;
}
/**
* Saves an instances incrementally. Structure has to be set by using the
* setStructure() method or setInstances() method.
*
* @param inst the instance to save
* @throws IOException throws IOEXception if an instance cannot be saved
* incrementally.
*/
@Override
public void writeIncremental(Instance inst) throws IOException {
int writeMode = getWriteMode();
Instances structure = getInstances();
PrintWriter outW = null;
if (getRetrieval() == BATCH || getRetrieval() == NONE) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
if (getWriter() != null) {
outW = new PrintWriter(getWriter());
}
if (writeMode == WAIT) {
if (structure == null) {
setWriteMode(CANCEL);
if (inst != null) {
System.err
.println("Structure(Header Information) has to be set in advance");
}
} else {
setWriteMode(STRUCTURE_READY);
}
writeMode = getWriteMode();
}
if (writeMode == CANCEL) {
if (outW != null) {
outW.close();
}
cancel();
}
if (writeMode == STRUCTURE_READY) {
setWriteMode(WRITE);
// write header
if (!getNoHeaderRow()) {
if (retrieveFile() == null && outW == null) {
// print out attribute names as first row
for (int i = 0; i < structure.numAttributes(); i++) {
System.out.print(structure.attribute(i).name());
if (i < structure.numAttributes() - 1) {
System.out.print(m_FieldSeparator);
} else {
System.out.println();
}
}
} else {
for (int i = 0; i < structure.numAttributes(); i++) {
outW.print(structure.attribute(i).name());
if (i < structure.numAttributes() - 1) {
outW.print(m_FieldSeparator);
} else {
outW.println();
}
}
outW.flush();
}
}
writeMode = getWriteMode();
}
if (writeMode == WRITE) {
if (structure == null) {
throw new IOException("No instances information available.");
}
if (inst != null) {
// write instance
if (retrieveFile() == null && outW == null) {
System.out.println(inst);
} else {
outW.println(instanceToString(inst));
// flushes every 100 instances
m_incrementalCounter++;
if (m_incrementalCounter > 100) {
m_incrementalCounter = 0;
outW.flush();
}
}
} else {
// close
if (outW != null) {
outW.flush();
outW.close();
}
m_incrementalCounter = 0;
resetStructure();
outW = null;
resetWriter();
}
}
}
/**
* Writes a Batch of instances.
*
* @throws IOException throws IOException if saving in batch mode is not
* possible
*/
@Override
public void writeBatch() throws IOException {
if (getInstances() == null) {
throw new IOException("No instances to save");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException("Batch and incremental saving cannot be mixed.");
}
setRetrieval(BATCH);
setWriteMode(WRITE);
if (retrieveFile() == null && getWriter() == null) {
if (!getNoHeaderRow()) {
// print out attribute names as first row
for (int i = 0; i < getInstances().numAttributes(); i++) {
System.out.print(getInstances().attribute(i).name());
if (i < getInstances().numAttributes() - 1) {
System.out.print(m_FieldSeparator);
} else {
System.out.println();
}
}
}
for (int i = 0; i < getInstances().numInstances(); i++) {
System.out.println(instanceToString(getInstances().instance(i)));
}
setWriteMode(WAIT);
return;
}
PrintWriter outW = new PrintWriter(getWriter());
if (!getNoHeaderRow()) {
// print out attribute names as first row
for (int i = 0; i < getInstances().numAttributes(); i++) {
outW.print(Utils.quote(getInstances().attribute(i).name()));
if (i < getInstances().numAttributes() - 1) {
outW.print(m_FieldSeparator);
} else {
outW.println();
}
}
}
for (int i = 0; i < getInstances().numInstances(); i++) {
outW.println(instanceToString((getInstances().instance(i))));
}
outW.flush();
outW.close();
setWriteMode(WAIT);
outW = null;
resetWriter();
setWriteMode(CANCEL);
}
/**
* turns an instance into a string. takes care of sparse instances as well.
*
* @param inst the instance to turn into a string
* @return the generated string
*/
protected String instanceToString(Instance inst) {
StringBuffer result;
Instance outInst;
int i;
String field;
result = new StringBuffer();
if (inst instanceof SparseInstance) {
outInst = new DenseInstance(inst.weight(), inst.toDoubleArray());
outInst.setDataset(inst.dataset());
} else {
outInst = inst;
}
for (i = 0; i < outInst.numAttributes(); i++) {
if (i > 0) {
result.append(m_FieldSeparator);
}
if (outInst.isMissing(i)) {
field = m_MissingValue;
} else {
field = outInst.toString(i, m_MaxDecimalPlaces);
}
// make sure that custom field separators, like ";" get quoted correctly
// as well (but only for single character field separators)
if (m_FieldSeparator.length() == 1
&& (field.indexOf(m_FieldSeparator) > -1) && !field.startsWith("'")
&& !field.endsWith("'")) {
field = "'" + field + "'";
}
result.append(field);
}
return result.toString();
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method.
*
* @param args should contain the options of a Saver.
*/
public static void main(String[] args) {
runFileSaver(new CSVSaver(), args);
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/ConverterResources.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* ConverterResources.java
* Copyright (C) 2017 University of Waikato, Hamilton, NZ
*/
package weka.core.converters;
import weka.core.InheritanceUtils;
import weka.core.PluginManager;
import weka.core.WekaPackageClassLoaderManager;
import weka.gui.GenericPropertiesCreator;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
/**
* Helper class for dealing with Converter resources.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
*/
public class ConverterResources {
/**
* the core loaders - hardcoded list necessary for RMI/Remote Experiments
* (comma-separated list).
*/
public final static String CORE_FILE_LOADERS = weka.core.converters.ArffLoader.class
.getName()
+ ","
// + weka.core.converters.C45Loader.class.getName() + ","
+ weka.core.converters.CSVLoader.class.getName()
+ ","
+ weka.core.converters.DatabaseConverter.class.getName()
+ ","
// + weka.core.converters.LibSVMLoader.class.getName() + ","
// + weka.core.converters.MatlabLoader.class.getName() + ","
// + weka.core.converters.SVMLightLoader.class.getName() + ","
+ weka.core.converters.SerializedInstancesLoader.class.getName()
+ ","
+ weka.core.converters.TextDirectoryLoader.class.getName()
+ ","
+ weka.core.converters.XRFFLoader.class.getName();
/**
* the core savers - hardcoded list necessary for RMI/Remote Experiments
* (comma-separated list).
*/
public final static String CORE_FILE_SAVERS = weka.core.converters.ArffSaver.class
.getName()
+ ","
// + weka.core.converters.C45Saver.class.getName() + ","
+ weka.core.converters.CSVSaver.class.getName()
+ ","
+ weka.core.converters.DatabaseConverter.class.getName()
+ ","
// + weka.core.converters.LibSVMSaver.class.getName() + ","
// + weka.core.converters.MatlabSaver.class.getName() + ","
// + weka.core.converters.SVMLightSaver.class.getName() + ","
+ weka.core.converters.SerializedInstancesSaver.class.getName()
+ ","
+ weka.core.converters.XRFFSaver.class.getName();
/** all available loaders (extension <-> classname). */
protected static Hashtable<String, String> m_FileLoaders;
/** all available URL loaders (extension <-> classname). */
protected static Hashtable<String, String> m_URLFileLoaders;
/** all available savers (extension <-> classname). */
protected static Hashtable<String, String> m_FileSavers;
/**
* checks whether the given class is one of the hardcoded core file loaders.
*
* @param classname the class to check
* @return true if the class is one of the core loaders
* @see ConverterResources#CORE_FILE_LOADERS
*/
public static boolean isCoreFileLoader(String classname) {
boolean result;
String[] classnames;
classnames = CORE_FILE_LOADERS.split(",");
result = (Arrays.binarySearch(classnames, classname) >= 0);
return result;
}
/**
* checks whether the given class is one of the hardcoded core file savers.
*
* @param classname the class to check
* @return true if the class is one of the core savers
* @see ConverterResources#CORE_FILE_SAVERS
*/
public static boolean isCoreFileSaver(String classname) {
boolean result;
String[] classnames;
classnames = CORE_FILE_SAVERS.split(",");
result = (Arrays.binarySearch(classnames, classname) >= 0);
return result;
}
/**
* Returns the file loaders.
*
* @return the file loaders
*/
public static Hashtable<String,String> getFileLoaders() {
return m_FileLoaders;
}
/**
* Returns the URL file loaders.
*
* @return the URL file loaders
*/
public static Hashtable<String,String> getURLFileLoaders() {
return m_URLFileLoaders;
}
/**
* Returns the file savers.
*
* @return the file savers
*/
public static Hashtable<String,String> getFileSavers() {
return m_FileSavers;
}
public static void initialize() {
List<String> classnames;
try {
// init
m_FileLoaders = new Hashtable<String, String>();
m_URLFileLoaders = new Hashtable<String, String>();
m_FileSavers = new Hashtable<String, String>();
// generate properties
// Note: does NOT work with RMI, hence m_FileLoadersCore/m_FileSaversCore
Properties props = GenericPropertiesCreator.getGlobalOutputProperties();
if (props == null) {
GenericPropertiesCreator creator = new GenericPropertiesCreator();
creator.execute(false);
props = creator.getOutputProperties();
}
// loaders
m_FileLoaders = getFileConverters(
props.getProperty(Loader.class.getName(), ConverterResources.CORE_FILE_LOADERS),
new String[] { FileSourcedConverter.class.getName() });
// URL loaders
m_URLFileLoaders = getFileConverters(
props.getProperty(Loader.class.getName(), ConverterResources.CORE_FILE_LOADERS),
new String[] { FileSourcedConverter.class.getName(),
URLSourcedLoader.class.getName() });
// savers
m_FileSavers = getFileConverters(
props.getProperty(Saver.class.getName(), ConverterResources.CORE_FILE_SAVERS),
new String[] { FileSourcedConverter.class.getName() });
} catch (Exception e) {
e.printStackTrace();
// ignore
} finally {
// loaders
if (m_FileLoaders.size() == 0) {
classnames = PluginManager.getPluginNamesOfTypeList(AbstractFileLoader.class
.getName());
if (classnames.size() > 0) {
m_FileLoaders = getFileConverters(classnames,
new String[] { FileSourcedConverter.class.getName() });
} else {
m_FileLoaders = getFileConverters(ConverterResources.CORE_FILE_LOADERS,
new String[] { FileSourcedConverter.class.getName() });
}
}
// URL loaders
if (m_URLFileLoaders.size() == 0) {
classnames = PluginManager.getPluginNamesOfTypeList(AbstractFileLoader.class
.getName());
if (classnames.size() > 0) {
m_URLFileLoaders = getFileConverters(classnames,
new String[] { FileSourcedConverter.class.getName(),
URLSourcedLoader.class.getName() });
} else {
m_URLFileLoaders = getFileConverters(ConverterResources.CORE_FILE_LOADERS,
new String[] { FileSourcedConverter.class.getName(),
URLSourcedLoader.class.getName() });
}
}
// savers
if (m_FileSavers.size() == 0) {
classnames = PluginManager.getPluginNamesOfTypeList(AbstractFileSaver.class
.getName());
if (classnames.size() > 0) {
m_FileSavers = getFileConverters(classnames,
new String[] { FileSourcedConverter.class.getName() });
} else {
m_FileSavers = getFileConverters(ConverterResources.CORE_FILE_SAVERS,
new String[] { FileSourcedConverter.class.getName() });
}
}
}
}
/**
* returns a hashtable with the association
* "file extension <-> converter classname" for the comma-separated list
* of converter classnames.
*
* @param classnames comma-separated list of converter classnames
* @param intf interfaces the converters have to implement
* @return hashtable with ExtensionFileFilters
*/
protected static Hashtable<String, String> getFileConverters(
String classnames, String[] intf) {
Vector<String> list;
String[] names;
int i;
list = new Vector<String>();
names = classnames.split(",");
for (i = 0; i < names.length; i++) {
list.add(names[i]);
}
return getFileConverters(list, intf);
}
/**
* returns a hashtable with the association
* "file extension <-> converter classname" for the list of converter
* classnames.
*
* @param classnames list of converter classnames
* @param intf interfaces the converters have to implement
* @return hashtable with ExtensionFileFilters
*/
protected static Hashtable<String, String> getFileConverters(
List<String> classnames, String[] intf) {
Hashtable<String, String> result;
String classname;
Class<?> cls;
String[] ext;
FileSourcedConverter converter;
int i;
int n;
result = new Hashtable<String, String>();
for (i = 0; i < classnames.size(); i++) {
classname = classnames.get(i);
// all necessary interfaces implemented?
for (n = 0; n < intf.length; n++) {
if (!InheritanceUtils.hasInterface(intf[n], classname)) {
continue;
}
}
// get data from converter
try {
cls = WekaPackageClassLoaderManager.forName(classname);
converter = (FileSourcedConverter) cls.newInstance();
ext = converter.getFileExtensions();
} catch (Exception e) {
cls = null;
converter = null;
ext = new String[0];
}
if (converter == null) {
continue;
}
for (n = 0; n < ext.length; n++) {
result.put(ext[n], classname);
}
}
return result;
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/ConverterUtils.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* ConverterUtils.java
* Copyright (C) 2000-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.RevisionHandler;
import weka.core.RevisionUtils;
import weka.core.WekaPackageClassLoaderManager;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.StreamTokenizer;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
/**
* Utility routines for the converter package.
*
* @author Mark Hall (mhall@cs.waikato.ac.nz)
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see Serializable
*/
public class ConverterUtils implements Serializable, RevisionHandler {
/** for serialization. */
static final long serialVersionUID = -2460855349276148760L;
/**
* Helper class for loading data from files and URLs. Via the ConverterUtils
* class it determines which converter to use for loading the data into
* memory. If the chosen converter is an incremental one, then the data will
* be loaded incrementally, otherwise as batch. In both cases the same
* interface will be used (<code>hasMoreElements</code>,
* <code>nextElement</code>). Before the data can be read again, one has to
* call the <code>reset</code> method. The data source can also be initialized
* with an Instances object, in order to provide a unified interface to files
* and already loaded datasets.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see #hasMoreElements(Instances)
* @see #nextElement(Instances)
* @see #reset()
* @see DataSink
*/
public static class DataSource implements Serializable, RevisionHandler {
/** for serialization. */
private static final long serialVersionUID = -613122395928757332L;
/** the file to load. */
protected File m_File;
/** the URL to load. */
protected URL m_URL;
/** the loader. */
protected Loader m_Loader;
/** whether the loader is incremental. */
protected boolean m_Incremental;
/** the instance counter for the batch case. */
protected int m_BatchCounter;
/** the last internally read instance. */
protected Instance m_IncrementalBuffer;
/** the batch buffer. */
protected Instances m_BatchBuffer;
/**
* Tries to load the data from the file. Can be either a regular file or a
* web location (http://, https://, ftp:// or file://).
*
* @param location the name of the file to load
* @throws Exception if initialization fails
*/
public DataSource(String location) throws Exception {
super();
// file or URL?
if (location.startsWith("http://") || location.startsWith("https://")
|| location.startsWith("ftp://") || location.startsWith("file://")) {
m_URL = new URL(location);
} else {
m_File = new File(location);
}
// quick check: is it ARFF?
if (isArff(location)) {
m_Loader = new ArffLoader();
} else {
if (m_File != null) {
m_Loader = ConverterUtils.getLoaderForFile(location);
} else {
m_Loader = ConverterUtils.getURLLoaderForFile(location);
}
// do we have a converter?
if (m_Loader == null) {
throw new IllegalArgumentException(
"No suitable converter found for '" + location + "'!");
}
}
// incremental loader?
m_Incremental = (m_Loader instanceof IncrementalConverter);
reset();
}
/**
* Initializes the datasource with the given dataset.
*
* @param inst the dataset to use
*/
public DataSource(Instances inst) {
super();
m_BatchBuffer = inst;
m_Loader = null;
m_File = null;
m_URL = null;
m_Incremental = false;
}
/**
* Initializes the datasource with the given Loader.
*
* @param loader the Loader to use
*/
public DataSource(Loader loader) {
super();
m_BatchBuffer = null;
m_Loader = loader;
m_File = null;
m_URL = null;
m_Incremental = (m_Loader instanceof IncrementalConverter);
initBatchBuffer();
}
/**
* Initializes the datasource with the given input stream. This stream is
* always interpreted as ARFF.
*
* @param stream the stream to use
*/
public DataSource(InputStream stream) {
super();
m_BatchBuffer = null;
m_Loader = new ArffLoader();
try {
m_Loader.setSource(stream);
} catch (Exception e) {
m_Loader = null;
}
m_File = null;
m_URL = null;
m_Incremental = (m_Loader instanceof IncrementalConverter);
initBatchBuffer();
}
/**
* initializes the batch buffer if necessary, i.e., for non-incremental
* loaders.
*/
protected void initBatchBuffer() {
try {
if (!isIncremental()) {
m_BatchBuffer = m_Loader.getDataSet();
} else {
m_BatchBuffer = null;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* returns whether the extension of the location is likely to be of ARFF
* format, i.e., ending in ".arff" or ".arff.gz" (case-insensitive).
*
* @param location the file location to check
* @return true if the location seems to be of ARFF format
*/
public static boolean isArff(String location) {
if (location.toLowerCase().endsWith(
ArffLoader.FILE_EXTENSION.toLowerCase())
|| location.toLowerCase().endsWith(
ArffLoader.FILE_EXTENSION_COMPRESSED.toLowerCase())) {
return true;
} else {
return false;
}
}
/**
* returns whether the loader is an incremental one.
*
* @return true if the loader is a true incremental one
*/
public boolean isIncremental() {
return m_Incremental;
}
/**
* returns the determined loader, null if the DataSource was initialized
* with data alone and not a file/URL.
*
* @return the loader used for retrieving the data
*/
public Loader getLoader() {
return m_Loader;
}
/**
* returns the full dataset, can be null in case of an error.
*
* @return the full dataset
* @throws Exception if resetting of loader fails
*/
public Instances getDataSet() throws Exception {
Instances result;
result = null;
// reset the loader
reset();
try {
if (m_BatchBuffer == null) {
result = m_Loader.getDataSet();
} else {
result = m_BatchBuffer;
}
} catch (Exception e) {
e.printStackTrace();
result = null;
}
return result;
}
/**
* returns the full dataset with the specified class index set, can be null
* in case of an error.
*
* @param classIndex the class index for the dataset
* @return the full dataset
* @throws Exception if resetting of loader fails
*/
public Instances getDataSet(int classIndex) throws Exception {
Instances result;
result = getDataSet();
if (result != null) {
result.setClassIndex(classIndex);
}
return result;
}
/**
* resets the loader.
*
* @throws Exception if resetting fails
*/
public void reset() throws Exception {
if (m_File != null) {
((AbstractFileLoader) m_Loader).setFile(m_File);
} else if (m_URL != null) {
((URLSourcedLoader) m_Loader).setURL(m_URL.toString());
} else if (m_Loader != null) {
m_Loader.reset();
}
m_BatchCounter = 0;
m_IncrementalBuffer = null;
if (m_Loader != null) {
if (!isIncremental()) {
m_BatchBuffer = m_Loader.getDataSet();
} else {
m_BatchBuffer = null;
}
}
}
/**
* returns the structure of the data.
*
* @return the structure of the data
* @throws Exception if something goes wrong
*/
public Instances getStructure() throws Exception {
if (m_BatchBuffer == null) {
return m_Loader.getStructure();
} else {
return new Instances(m_BatchBuffer, 0);
}
}
/**
* returns the structure of the data, with the defined class index.
*
* @param classIndex the class index for the dataset
* @return the structure of the data
* @throws Exception if something goes wrong
*/
public Instances getStructure(int classIndex) throws Exception {
Instances result;
result = getStructure();
if (result != null) {
result.setClassIndex(classIndex);
}
return result;
}
/**
* returns whether there are more Instance objects in the data.
*
* @param structure the structure of the dataset
* @return true if there are more Instance objects available
* @see #nextElement(Instances)
*/
public boolean hasMoreElements(Instances structure) {
boolean result;
result = false;
if (isIncremental()) {
// user still hasn't collected the last one?
if (m_IncrementalBuffer != null) {
result = true;
} else {
try {
m_IncrementalBuffer = m_Loader.getNextInstance(structure);
result = (m_IncrementalBuffer != null);
} catch (Exception e) {
e.printStackTrace();
result = false;
}
}
} else {
result = (m_BatchCounter < m_BatchBuffer.numInstances());
}
return result;
}
/**
* returns the next element and sets the specified dataset, null if none
* available.
*
* @param dataset the dataset to set for the instance
* @return the next Instance
*/
public Instance nextElement(Instances dataset) {
Instance result;
result = null;
if (isIncremental()) {
// is there still an instance in the buffer?
if (m_IncrementalBuffer != null) {
result = m_IncrementalBuffer;
m_IncrementalBuffer = null;
} else {
try {
result = m_Loader.getNextInstance(dataset);
} catch (Exception e) {
e.printStackTrace();
result = null;
}
}
} else {
if (m_BatchCounter < m_BatchBuffer.numInstances()) {
result = m_BatchBuffer.instance(m_BatchCounter);
m_BatchCounter++;
}
}
if (result != null) {
result.setDataset(dataset);
}
return result;
}
/**
* convencience method for loading a dataset in batch mode.
*
* @param location the dataset to load
* @return the dataset
* @throws Exception if loading fails
*/
public static Instances read(String location) throws Exception {
DataSource source;
Instances result;
source = new DataSource(location);
result = source.getDataSet();
return result;
}
/**
* convencience method for loading a dataset in batch mode from a stream.
*
* @param stream the stream to load the dataset from
* @return the dataset
* @throws Exception if loading fails
*/
public static Instances read(InputStream stream) throws Exception {
DataSource source;
Instances result;
source = new DataSource(stream);
result = source.getDataSet();
return result;
}
/**
* convencience method for loading a dataset in batch mode.
*
* @param loader the loader to get the dataset from
* @return the dataset
* @throws Exception if loading fails
*/
public static Instances read(Loader loader) throws Exception {
DataSource source;
Instances result;
source = new DataSource(loader);
result = source.getDataSet();
return result;
}
/**
* for testing only - takes a data file as input.
*
* @param args the commandline arguments
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.out.println("\nUsage: " + DataSource.class.getName()
+ " <file>\n");
System.exit(1);
}
DataSource loader = new DataSource(args[0]);
System.out.println("Incremental? " + loader.isIncremental());
System.out.println("Loader: " + loader.getLoader().getClass().getName());
System.out.println("Data:\n");
Instances structure = loader.getStructure();
System.out.println(structure);
while (loader.hasMoreElements(structure)) {
System.out.println(loader.nextElement(structure));
}
Instances inst = loader.getDataSet();
loader = new DataSource(inst);
System.out.println("\n\nProxy-Data:\n");
System.out.println(loader.getStructure());
while (loader.hasMoreElements(structure)) {
System.out.println(loader.nextElement(inst));
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/**
* Helper class for saving data to files. Via the ConverterUtils class it
* determines which converter to use for saving the data. It is the logical
* counterpart to <code>DataSource</code>.
*
* @author FracPete (fracpete at waikato dot ac dot nz)
* @version $Revision$
* @see DataSource
*/
public static class DataSink implements Serializable, RevisionHandler {
/** for serialization. */
private static final long serialVersionUID = -1504966891136411204L;
/** the saver to use for storing the data. */
protected Saver m_Saver = null;
/** the stream to store the data in (always in ARFF format). */
protected OutputStream m_Stream = null;
/**
* initializes the sink to save the data to the given file.
*
* @param filename the file to save data to
* @throws Exception if set of saver fails
*/
public DataSink(String filename) throws Exception {
m_Stream = null;
if (DataSource.isArff(filename)) {
m_Saver = new ArffSaver();
} else {
m_Saver = getSaverForFile(filename);
}
((AbstractFileSaver) m_Saver).setFile(new File(filename));
}
/**
* initializes the sink to save the data to the given Saver (expected to be
* fully configured).
*
* @param saver the saver to use for saving the data
*/
public DataSink(Saver saver) {
m_Saver = saver;
m_Stream = null;
}
/**
* initializes the sink to save the data in the stream (always in ARFF
* format).
*
* @param stream the output stream to use for storing the data in ARFF
* format
*/
public DataSink(OutputStream stream) {
m_Saver = null;
m_Stream = stream;
}
/**
* writes the given data either via the saver or to the defined output
* stream (depending on the constructor). In case of the stream, the stream
* is only flushed, but not closed.
*
* @param data the data to save
* @throws Exception if saving fails
*/
public void write(Instances data) throws Exception {
if (m_Saver != null) {
m_Saver.setInstances(data);
m_Saver.writeBatch();
} else {
m_Stream.write(data.toString().getBytes());
m_Stream.flush();
}
}
/**
* writes the data to the given file.
*
* @param filename the file to write the data to
* @param data the data to store
* @throws Exception if writing fails
*/
public static void write(String filename, Instances data) throws Exception {
DataSink sink;
sink = new DataSink(filename);
sink.write(data);
}
/**
* writes the data via the given saver.
*
* @param saver the saver to use for writing the data
* @param data the data to store
* @throws Exception if writing fails
*/
public static void write(Saver saver, Instances data) throws Exception {
DataSink sink;
sink = new DataSink(saver);
sink.write(data);
}
/**
* writes the data to the given stream (always in ARFF format).
*
* @param stream the stream to write the data to (ARFF format)
* @param data the data to store
* @throws Exception if writing fails
*/
public static void write(OutputStream stream, Instances data)
throws Exception {
DataSink sink;
sink = new DataSink(stream);
sink.write(data);
}
/**
* for testing only - takes a data file as input and a data file for the
* output.
*
* @param args the commandline arguments
* @throws Exception if something goes wrong
*/
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.out.println("\nUsage: " + DataSource.class.getName()
+ " <input-file> <output-file>\n");
System.exit(1);
}
// load data
Instances data = DataSource.read(args[0]);
// save data
DataSink.write(args[1], data);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
/** all available loaders (extension <-> classname). */
protected static Hashtable<String, String> m_FileLoaders;
/** all available URL loaders (extension <-> classname). */
protected static Hashtable<String, String> m_URLFileLoaders;
/** all available savers (extension <-> classname). */
protected static Hashtable<String, String> m_FileSavers;
// determine all loaders/savers
static {
initialize();
}
public static void initialize() {
ConverterResources.initialize();
m_FileLoaders = ConverterResources.getFileLoaders();
m_URLFileLoaders = ConverterResources.getURLFileLoaders();
m_FileSavers = ConverterResources.getFileSavers();
}
/**
* Gets token, skipping empty lines.
*
* @param tokenizer the stream tokenizer
* @throws IOException if reading the next token fails
*/
public static void getFirstToken(StreamTokenizer tokenizer)
throws IOException {
StreamTokenizerUtils.getFirstToken(tokenizer);
}
/**
* Gets token.
*
* @param tokenizer the stream tokenizer
* @throws IOException if reading the next token fails
*/
public static void getToken(StreamTokenizer tokenizer) throws IOException {
StreamTokenizerUtils.getToken(tokenizer);
}
/**
* Throws error message with line number and last token read.
*
* @param theMsg the error message to be thrown
* @param tokenizer the stream tokenizer
* @throws IOException containing the error message
*/
public static void errms(StreamTokenizer tokenizer, String theMsg)
throws IOException {
throw new IOException(theMsg + ", read " + tokenizer.toString());
}
/**
* returns a vector with the classnames of all the loaders from the given
* hashtable.
*
* @param ht the hashtable with the extension/converter relation
* @return the classnames of the loaders
*/
protected static Vector<String> getConverters(Hashtable<String, String> ht) {
Vector<String> result;
Enumeration<String> enm;
String converter;
result = new Vector<String>();
// get all classnames
enm = ht.elements();
while (enm.hasMoreElements()) {
converter = enm.nextElement();
if (!result.contains(converter)) {
result.add(converter);
}
}
// sort names
Collections.sort(result);
return result;
}
/**
* tries to determine the converter to use for this kind of file, returns null
* if none can be found in the given hashtable.
*
* @param filename the file to return a converter for
* @param ht the hashtable with the relation extension/converter
* @return the converter if one was found, null otherwise
*/
protected static Object getConverterForFile(String filename,
Hashtable<String, String> ht) {
Object result;
String extension;
int index;
result = null;
index = filename.lastIndexOf('.');
if (index > -1) {
extension = filename.substring(index).toLowerCase();
result = getConverterForExtension(extension, ht);
// is it a compressed format?
if (extension.equals(".gz") && result == null) {
index = filename.lastIndexOf('.', index - 1);
extension = filename.substring(index).toLowerCase();
result = getConverterForExtension(extension, ht);
}
}
return result;
}
/**
* tries to determine the loader to use for this kind of extension, returns
* null if none can be found.
*
* @param extension the file extension to return a converter for
* @param ht the hashtable with the relation extension/converter
* @return the converter if one was found, null otherwise
*/
protected static Object getConverterForExtension(String extension,
Hashtable<String, String> ht) {
Object result;
String classname;
result = null;
classname = ht.get(extension);
if (classname != null) {
try {
result = WekaPackageClassLoaderManager.forName(classname).newInstance();
} catch (Exception e) {
result = null;
e.printStackTrace();
}
}
return result;
}
/**
* returns a vector with the classnames of all the file loaders.
*
* @return the classnames of the loaders
*/
public static Vector<String> getFileLoaders() {
return getConverters(m_FileLoaders);
}
/**
* tries to determine the loader to use for this kind of file, returns null if
* none can be found.
*
* @param filename the file to return a converter for
* @return the converter if one was found, null otherwise
*/
public static AbstractFileLoader getLoaderForFile(String filename) {
return (AbstractFileLoader) getConverterForFile(filename, m_FileLoaders);
}
/**
* tries to determine the loader to use for this kind of file, returns null if
* none can be found.
*
* @param file the file to return a converter for
* @return the converter if one was found, null otherwise
*/
public static AbstractFileLoader getLoaderForFile(File file) {
return getLoaderForFile(file.getAbsolutePath());
}
/**
* tries to determine the loader to use for this kind of extension, returns
* null if none can be found.
*
* @param extension the file extension to return a converter for
* @return the converter if one was found, null otherwise
*/
public static AbstractFileLoader getLoaderForExtension(String extension) {
return (AbstractFileLoader) getConverterForExtension(extension,
m_FileLoaders);
}
/**
* returns a vector with the classnames of all the URL file loaders.
*
* @return the classnames of the loaders
*/
public static Vector<String> getURLFileLoaders() {
return getConverters(m_URLFileLoaders);
}
/**
* tries to determine the URL loader to use for this kind of file, returns
* null if none can be found.
*
* @param filename the file to return a URL converter for
* @return the converter if one was found, null otherwise
*/
public static AbstractFileLoader getURLLoaderForFile(String filename) {
return (AbstractFileLoader) getConverterForFile(filename, m_URLFileLoaders);
}
/**
* tries to determine the URL loader to use for this kind of file, returns
* null if none can be found.
*
* @param file the file to return a URL converter for
* @return the converter if one was found, null otherwise
*/
public static AbstractFileLoader getURLLoaderForFile(File file) {
return getURLLoaderForFile(file.getAbsolutePath());
}
/**
* tries to determine the URL loader to use for this kind of extension,
* returns null if none can be found.
*
* @param extension the file extension to return a URL converter for
* @return the converter if one was found, null otherwise
*/
public static AbstractFileLoader getURLLoaderForExtension(String extension) {
return (AbstractFileLoader) getConverterForExtension(extension,
m_URLFileLoaders);
}
/**
* returns a vector with the classnames of all the file savers.
*
* @return the classnames of the savers
*/
public static Vector<String> getFileSavers() {
return getConverters(m_FileSavers);
}
/**
* tries to determine the saver to use for this kind of file, returns null if
* none can be found.
*
* @param filename the file to return a converter for
* @return the converter if one was found, null otherwise
*/
public static AbstractFileSaver getSaverForFile(String filename) {
return (AbstractFileSaver) getConverterForFile(filename, m_FileSavers);
}
/**
* tries to determine the saver to use for this kind of file, returns null if
* none can be found.
*
* @param file the file to return a converter for
* @return the converter if one was found, null otherwise
*/
public static AbstractFileSaver getSaverForFile(File file) {
return getSaverForFile(file.getAbsolutePath());
}
/**
* tries to determine the saver to use for this kind of extension, returns
* null if none can be found.
*
* @param extension the file extension to return a converter for
* @return the converter if one was found, null otherwise
*/
public static AbstractFileSaver getSaverForExtension(String extension) {
return (AbstractFileSaver) getConverterForExtension(extension, m_FileSavers);
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/DatabaseConnection.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* DatabaseConnection.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import java.io.File;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Properties;
import weka.core.RevisionUtils;
import weka.experiment.DatabaseUtils;
/**
* Connects to a database.
*
* @author Len Trigg (trigg@cs.waikato.ac.nz)
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
*/
public class DatabaseConnection
extends DatabaseUtils {
/** for serialization */
static final long serialVersionUID = 1673169848863178695L;
/**
* Sets up the database drivers.
*
* @throws Exception if an error occurs
*/
public DatabaseConnection() throws Exception {
super();
}
/**
* Reads the properties from the specified file and sets up the database drivers.
*
* @param propsFile the props file to load, ignored if null or pointing
* to a directory
* @throws Exception if an error occurs
*/
public DatabaseConnection(File propsFile) throws Exception {
super(propsFile);
}
/**
* Uses the specified properties to set up the database drivers.
*
* @param props the properties to use, ignored if null
* @throws Exception if an error occurs
*/
public DatabaseConnection(Properties props) throws Exception {
super(props);
}
/**
* Returns the underlying properties object.
*
* @return the properties object
*/
public Properties getProperties() {
return PROPERTIES;
}
/**
* Check if the property checkUpperCaseNames in the DatabaseUtils file is
* set to true or false.
*
* @return true if the property checkUpperCaseNames in the DatabaseUtils
* file is set to true, false otherwise.
*/
public boolean getUpperCase(){
return m_checkForUpperCaseNames;
}
/**
* Gets meta data for the database connection object.
*
* @return the meta data.
* @throws Exception if an error occurs
*/
public DatabaseMetaData getMetaData() throws Exception{
if (!isConnected())
throw new IllegalStateException("Not connected, please connect first!");
return m_Connection.getMetaData();
}
/**
* Dewtermines if the current query retrieves a result set or updates a table
*
* @return the update count (-1 if the query retrieves a result set).
* @throws SQLException if an error occurs
*/
public int getUpdateCount() throws SQLException {
if (!isConnected())
throw new IllegalStateException("Not connected, please connect first!");
return m_PreparedStatement.getUpdateCount();
}
/**
* Returns the revision string.
*
* @return the revision
*/
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/DatabaseConverter.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* DatabaseConverter.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
/**
* Marker interface for a loader/saver that uses a database
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision 1.0 $
*/
public interface DatabaseConverter {
public String getUrl();
public String getUser();
public void setUrl(String url);
public void setUser(String user);
public void setPassword(String password);
}
|
0
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core
|
java-sources/ai/libs/thirdparty/interruptible-weka/0.1.6/weka/core/converters/DatabaseLoader.java
|
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* DatabaseLoader.java
* Copyright (C) 2004-2012 University of Waikato, Hamilton, New Zealand
*
*/
package weka.core.converters;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Environment;
import weka.core.EnvironmentHandler;
import weka.core.Instance;
import weka.core.Instances;
import weka.core.Option;
import weka.core.OptionHandler;
import weka.core.OptionMetadata;
import weka.core.RevisionUtils;
import weka.core.SparseInstance;
import weka.core.Utils;
import weka.experiment.InstanceQuery;
import weka.gui.FilePropertyMetadata;
import weka.gui.PasswordProperty;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.sql.DatabaseMetaData;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
/**
* <!-- globalinfo-start --> Reads Instances from a Database. Can read a
* database in batch or incremental mode.<br/>
* In inremental mode MySQL and HSQLDB are supported.<br/>
* For all other DBMS set a pseudoincremental mode is used:<br/>
* In pseudo incremental mode the instances are read into main memory all at
* once and then incrementally provided to the user.<br/>
* For incremental loading the rows in the database table have to be ordered
* uniquely.<br/>
* The reason for this is that every time only a single row is fetched by
* extending the user query by a LIMIT clause.<br/>
* If this extension is impossible instances will be loaded pseudoincrementally.
* To ensure that every row is fetched exaclty once, they have to ordered.<br/>
* Therefore a (primary) key is necessary.This approach is chosen, instead of
* using JDBC driver facilities, because the latter one differ betweeen
* different drivers.<br/>
* If you use the DatabaseSaver and save instances by generating automatically a
* primary key (its name is defined in DtabaseUtils), this primary key will be
* used for ordering but will not be part of the output. The user defined SQL
* query to extract the instances should not contain LIMIT and ORDER BY clauses
* (see -Q option).<br/>
* In addition, for incremental loading, you can define in the DatabaseUtils
* file how many distinct values a nominal attribute is allowed to have. If this
* number is exceeded, the column will become a string attribute.<br/>
* In batch mode no string attributes will be created.
* <p/>
* <!-- globalinfo-end -->
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -url <JDBC URL>
* The JDBC URL to connect to.
* (default: from DatabaseUtils.props file)
* </pre>
*
* <pre>
* -user <name>
* The user to connect with to the database.
* (default: none)
* </pre>
*
* <pre>
* -password <password>
* The password to connect with to the database.
* (default: none)
* </pre>
*
* <pre>
* -Q <query>
* SQL query of the form
* SELECT <list of columns>|* FROM <table> [WHERE]
* to execute.
* (default: Select * From Results0)
* </pre>
*
* <pre>
* -P <list of column names>
* List of column names uniquely defining a DB row
* (separated by ', ').
* Used for incremental loading.
* If not specified, the key will be determined automatically,
* if possible with the used JDBC driver.
* The auto ID column created by the DatabaseSaver won't be loaded.
* </pre>
*
* <pre>
* -I
* Sets incremental loading
* </pre>
*
* <!-- options-end -->
*
* @author Stefan Mutter (mutter@cs.waikato.ac.nz)
* @version $Revision$
* @see Loader
*/
public class DatabaseLoader extends AbstractLoader implements BatchConverter,
IncrementalConverter, DatabaseConverter, OptionHandler, EnvironmentHandler {
/** for serialization */
static final long serialVersionUID = -7936159015338318659L;
/**
* The header information that is retrieved in the beginning of incremental
* loading
*/
protected Instances m_structure;
/**
* Used in pseudoincremental mode. The whole dataset from which instances will
* be read incrementally.
*/
protected Instances m_datasetPseudoInc;
/**
* Set of instances that equals m_structure except that the auto_generated_id
* column is not included as an attribute
*/
protected Instances m_oldStructure;
/** The database connection */
protected DatabaseConnection m_DataBaseConnection;
/**
* The user defined query to load instances. (form: SELECT
* *|<column-list> FROM <table> [WHERE <condition>])
*/
protected String m_query = "Select * from Results0";
/**
* Flag indicating that pseudo incremental mode is used (all instances load at
* once into main memeory and then incrementally from main memory instead of
* the database)
*/
protected boolean m_pseudoIncremental;
/**
* If true it checks whether or not the table exists in the database before
* loading depending on jdbc metadata information. Set flag to false if no
* check is required or if jdbc metadata is not complete.
*/
protected boolean m_checkForTable;
/**
* Limit when an attribute is treated as string attribute and not as a nominal
* one because it has to many values.
*/
protected int m_nominalToStringLimit;
/**
* The number of rows obtained by m_query, eg the size of the ResultSet to
* load
*/
protected int m_rowCount;
/** Indicates how many rows has already been loaded incrementally */
protected int m_counter;
/**
* Decides which SQL statement to limit the number of rows should be used.
* DBMS dependent. Algorithm just tries several possibilities.
*/
protected int m_choice;
/** Flag indicating that incremental process wants to read first instance */
protected boolean m_firstTime;
/**
* Flag indicating that incremental mode is chosen (for command line use only)
*/
protected boolean m_inc;
/**
* Contains the name of the columns that uniquely define a row in the
* ResultSet. Ensures a unique ordering of instances for indremental loading.
*/
protected ArrayList<String> m_orderBy;
/** Stores the index of a nominal value */
protected Hashtable<String, Double>[] m_nominalIndexes;
/** Stores the nominal value */
protected ArrayList<String>[] m_nominalStrings;
/**
* Name of the primary key column that will allow unique ordering necessary
* for incremental loading. The name is specified in the DatabaseUtils file.
*/
protected String m_idColumn;
/** the JDBC URL to use */
protected String m_URL = null;
/** the database user to use */
protected String m_User = "";
/** the database password to use */
protected String m_Password = "";
/** the keys for unique ordering */
protected String m_Keys = "";
/** the custom props file to use instead of default one. */
protected File m_CustomPropsFile = new File("${user.home}");
/** Determines whether sparse data is created */
protected boolean m_CreateSparseData = false;
/** Environment variables */
protected transient Environment m_env;
/**
* Constructor
*
* @throws Exception if initialization fails
*/
public DatabaseLoader() throws Exception {
resetOptions();
}
/**
* Returns a string describing this Loader
*
* @return a description of the Loader suitable for displaying in the
* explorer/experimenter gui
*/
public String globalInfo() {
return "Reads Instances from a Database. "
+ "Can read a database in batch or incremental mode.\n"
+ "In inremental mode MySQL and HSQLDB are supported.\n"
+ "For all other DBMS set a pseudoincremental mode is used:\n"
+ "In pseudo incremental mode the instances are read into main memory all at once and then incrementally provided to the user.\n"
+ "For incremental loading the rows in the database table have to be ordered uniquely.\n"
+ "The reason for this is that every time only a single row is fetched by extending the user query by a LIMIT clause.\n"
+ "If this extension is impossible instances will be loaded pseudoincrementally. To ensure that every row is fetched exaclty once, they have to ordered.\n"
+ "Therefore a (primary) key is necessary.This approach is chosen, instead of using JDBC driver facilities, because the latter one differ betweeen different drivers.\n"
+ "If you use the DatabaseSaver and save instances by generating automatically a primary key (its name is defined in DtabaseUtils), this primary key will "
+ "be used for ordering but will not be part of the output. The user defined SQL query to extract the instances should not contain LIMIT and ORDER BY clauses (see -Q option).\n"
+ "In addition, for incremental loading, you can define in the DatabaseUtils file how many distinct values a nominal attribute is allowed to have. If this number is exceeded, the column will become a string attribute.\n"
+ "In batch mode no string attributes will be created.";
}
/**
* Set the environment variables to use.
*
* @param env the environment variables to use
*/
@Override
public void setEnvironment(Environment env) {
m_env = env;
try {
// force a new connection and setting of all parameters
// with environment variables resolved
m_DataBaseConnection = newDatabaseConnection();
setUrl(m_URL);
setUser(m_User);
setPassword(m_Password);
} catch (Exception ex) {
// we won't complain about it here...
}
}
private void checkEnv() {
if (m_env == null) {
m_env = Environment.getSystemWide();
}
}
/**
* Initializes a new DatabaseConnection object, either default one or from
* custom props file.
*
* @return the DatabaseConnection object
* @see #m_CustomPropsFile
*/
protected DatabaseConnection newDatabaseConnection() throws Exception {
DatabaseConnection result;
checkEnv();
if (m_CustomPropsFile != null) {
File pFile = new File(m_CustomPropsFile.getPath());
String pPath = m_CustomPropsFile.getPath();
try {
pPath = m_env.substitute(pPath);
pFile = new File(pPath);
} catch (Exception ex) {
}
result = new DatabaseConnection(pFile);
} else {
result = new DatabaseConnection();
}
m_pseudoIncremental = false;
m_checkForTable = true;
String props = result.getProperties().getProperty("nominalToStringLimit");
m_nominalToStringLimit = Integer.parseInt(props);
m_idColumn = result.getProperties().getProperty("idColumn");
if (result.getProperties().getProperty("checkForTable", "")
.equalsIgnoreCase("FALSE")) {
m_checkForTable = false;
}
return result;
}
/**
* Resets the Loader to the settings in either the default DatabaseUtils.props
* or any property file that the user has specified via setCustomPropsFile().
*/
public void resetOptions() {
resetStructure();
try {
if (m_DataBaseConnection != null && m_DataBaseConnection.isConnected()) {
m_DataBaseConnection.disconnectFromDatabase();
}
m_DataBaseConnection = newDatabaseConnection();
} catch (Exception ex) {
printException(ex);
}
m_URL = m_DataBaseConnection.getDatabaseURL();
if (m_URL == null) {
m_URL = "none set!";
}
m_User = m_DataBaseConnection.getUsername();
if (m_User == null) {
m_User = "";
}
m_Password = m_DataBaseConnection.getPassword();
if (m_Password == null) {
m_Password = "";
}
m_orderBy = new ArrayList<String>();
}
/**
* Resets the Loader ready to read a new data set using set options
*
* @throws Exception if an error occurs while disconnecting from the database
*/
@Override
public void reset() {
resetStructure();
try {
if (m_DataBaseConnection != null && m_DataBaseConnection.isConnected()) {
m_DataBaseConnection.disconnectFromDatabase();
}
m_DataBaseConnection = newDatabaseConnection();
} catch (Exception ex) {
printException(ex);
}
// don't lose previously set connection data!
if (m_URL != null) {
setUrl(m_URL);
}
if (m_User != null) {
setUser(m_User);
}
if (m_Password != null) {
setPassword(m_Password);
}
m_orderBy = new ArrayList<String>();
// don't lose previously set key columns!
if (m_Keys != null) {
String k = m_Keys;
try {
k = m_env.substitute(k);
} catch (Exception ex) {
}
setKeys(k);
}
m_inc = false;
}
/**
* Resets the structure of instances
*/
public void resetStructure() {
m_structure = null;
m_datasetPseudoInc = null;
m_oldStructure = null;
m_rowCount = 0;
m_counter = 0;
m_choice = 0;
m_firstTime = true;
setRetrieval(NONE);
}
/**
* Sets the query to execute against the database
*
* @param q the query to execute
*/
public void setQuery(String q) {
q = q.replaceAll("[fF][rR][oO][mM]", "FROM");
q = q.replaceFirst("[sS][eE][lL][eE][cC][tT]", "SELECT");
m_query = q;
}
/**
* Gets the query to execute against the database
*
* @return the query
*/
@OptionMetadata(displayName = "Query", description = "The query to execute",
displayOrder = 4)
public String getQuery() {
return m_query;
}
/**
* the tip text for this property
*
* @return the tip text
*/
public String queryTipText() {
return "The query that should load the instances."
+ "\n The query has to be of the form SELECT <column-list>|* FROM <table> [WHERE <conditions>]";
}
/**
* Sets the key columns of a database table
*
* @param keys a String containing the key columns in a comma separated list.
*/
public void setKeys(String keys) {
m_Keys = keys;
m_orderBy.clear();
StringTokenizer st = new StringTokenizer(keys, ",");
while (st.hasMoreTokens()) {
String column = st.nextToken();
column = column.replaceAll(" ", "");
m_orderBy.add(column);
}
}
/**
* Gets the key columns' name
*
* @return name of the key columns'
*/
@OptionMetadata(
displayName = "Key columns",
description = "Specific key columns to use if "
+ "a primary key cannot be automatically detected. Used in incremental loading.",
displayOrder = 5)
public
String getKeys() {
StringBuffer key = new StringBuffer();
for (int i = 0; i < m_orderBy.size(); i++) {
key.append(m_orderBy.get(i));
if (i != m_orderBy.size() - 1) {
key.append(", ");
}
}
return key.toString();
}
/**
* the tip text for this property
*
* @return the tip text
*/
public String keysTipText() {
return "For incremental loading a unique identiefer has to be specified."
+ "\nIf the query includes all columns of a table (SELECT *...) a primary key"
+ "\ncan be detected automatically depending on the JDBC driver. If that is not possible"
+ "\nspecify the key columns here in a comma separated list.";
}
/**
* Sets the custom properties file to use.
*
* @param value the custom props file to load database parameters from, use
* null or directory to disable custom properties.
*/
public void setCustomPropsFile(File value) {
m_CustomPropsFile = value;
}
/**
* Returns the custom properties file in use, if any.
*
* @return the custom props file, null if none used
*/
@OptionMetadata(
displayName = "DB config file",
description = "The custom properties that the user can use to override the default ones.",
displayOrder = 8)
@FilePropertyMetadata(fileChooserDialogType = JFileChooser.OPEN_DIALOG,
directoriesOnly = false)
public
File getCustomPropsFile() {
return m_CustomPropsFile;
}
/**
* The tip text for this property.
*
* @return the tip text
*/
public String customPropsFileTipText() {
return "The custom properties that the user can use to override the default ones.";
}
/**
* Sets the database URL
*
* @param url string with the database URL
*/
@Override
public void setUrl(String url) {
checkEnv();
m_URL = url;
String dbU = m_URL;
try {
dbU = m_env.substitute(dbU);
} catch (Exception ex) {
}
m_DataBaseConnection.setDatabaseURL(dbU);
}
/**
* Gets the URL
*
* @return the URL
*/
@OptionMetadata(displayName = "Database URL",
description = "The URL of the database", displayOrder = 1)
@Override
public String getUrl() {
// return m_DataBaseConnection.getDatabaseURL();
return m_URL;
}
/**
* the tip text for this property
*
* @return the tip text
*/
public String urlTipText() {
return "The URL of the database";
}
/**
* Sets the database user
*
* @param user the database user name
*/
@Override
public void setUser(String user) {
checkEnv();
m_User = user;
String userCopy = user;
try {
userCopy = m_env.substitute(userCopy);
} catch (Exception ex) {
}
m_DataBaseConnection.setUsername(userCopy);
}
/**
* Gets the user name
*
* @return name of database user
*/
@OptionMetadata(displayName = "Username",
description = "The user name for the database", displayOrder = 2)
@Override
public String getUser() {
// return m_DataBaseConnection.getUsername();
return m_User;
}
/**
* the tip text for this property
*
* @return the tip text
*/
public String userTipText() {
return "The user name for the database";
}
/**
* Sets user password for the database
*
* @param password the password
*/
@Override
public void setPassword(String password) {
checkEnv();
m_Password = password;
String passCopy = password;
try {
passCopy = m_env.substitute(passCopy);
} catch (Exception ex) {
}
m_DataBaseConnection.setPassword(password);
}
/**
* Returns the database password
*
* @return the database password
*/
@OptionMetadata(displayName = "Password",
description = "The database password", displayOrder = 3)
@PasswordProperty
public String getPassword() {
// return m_DataBaseConnection.getPassword();
return m_Password;
}
/**
* the tip text for this property
*
* @return the tip text
*/
public String passwordTipText() {
return "The database password";
}
/**
* Returns the tip text for this property
*
* @return tip text for this property suitable for displaying in the
* explorer/experimenter gui
*/
public String sparseDataTipText() {
return "Encode data as sparse instances.";
}
/**
* Sets whether data should be encoded as sparse instances
*
* @param s true if data should be encoded as a set of sparse instances
*/
public void setSparseData(boolean s) {
m_CreateSparseData = s;
}
/**
* Gets whether data is to be returned as a set of sparse instances
*
* @return true if data is to be encoded as sparse instances
*/
@OptionMetadata(displayName = "Create sparse instances", description = "Return sparse "
+ "rather than normal instances", displayOrder = 6)
public boolean getSparseData() {
return m_CreateSparseData;
}
/**
* Sets the database url, user and pw
*
* @param url the database url
* @param userName the user name
* @param password the password
*/
public void setSource(String url, String userName, String password) {
try {
m_DataBaseConnection = newDatabaseConnection();
setUrl(url);
setUser(userName);
setPassword(password);
} catch (Exception ex) {
printException(ex);
}
}
/**
* Sets the database url
*
* @param url the database url
*/
public void setSource(String url) {
try {
m_DataBaseConnection = newDatabaseConnection();
setUrl(url);
m_User = m_DataBaseConnection.getUsername();
m_Password = m_DataBaseConnection.getPassword();
} catch (Exception ex) {
printException(ex);
}
}
/**
* Sets the database url using the DatabaseUtils file
*
* @throws Exception if something goes wrong
*/
public void setSource() throws Exception {
m_DataBaseConnection = newDatabaseConnection();
m_URL = m_DataBaseConnection.getDatabaseURL();
m_User = m_DataBaseConnection.getUsername();
m_Password = m_DataBaseConnection.getPassword();
}
/**
* Opens a connection to the database
*/
public void connectToDatabase() {
try {
if (!m_DataBaseConnection.isConnected()) {
m_DataBaseConnection.connectToDatabase();
}
} catch (Exception ex) {
printException(ex);
}
}
/**
* Returns the table name or all after the FROM clause of the user specified
* query to retrieve instances.
*
* @param onlyTableName true if only the table name should be returned, false
* otherwise
* @return the end of the query
*/
private String endOfQuery(boolean onlyTableName) {
String table;
int beginIndex, endIndex;
beginIndex = m_query.indexOf("FROM ") + 5;
while (m_query.charAt(beginIndex) == ' ') {
beginIndex++;
}
endIndex = m_query.indexOf(" ", beginIndex);
if (endIndex != -1 && onlyTableName) {
table = m_query.substring(beginIndex, endIndex);
} else {
table = m_query.substring(beginIndex);
}
if (m_DataBaseConnection.getUpperCase()) {
table = table.toUpperCase();
}
return table;
}
/**
* Checks for a unique key using the JDBC driver's method: getPrimaryKey(),
* getBestRowIdentifier(). Depending on their implementation a key can be
* detected. The key is needed to order the instances uniquely for an
* inremental loading. If an existing key cannot be detected, use -P option.
*
* @throws Exception if database error occurs
* @return true, if a key could have been detected, false otherwise
*/
private boolean checkForKey() throws Exception {
String query = m_query;
query = query.replaceAll(" +", " ");
// query has to use all columns
if (!query.startsWith("SELECT *")) {
return false;
}
m_orderBy.clear();
if (!m_DataBaseConnection.isConnected()) {
m_DataBaseConnection.connectToDatabase();
}
DatabaseMetaData dmd = m_DataBaseConnection.getMetaData();
String table = endOfQuery(true);
// System.out.println(table);
// check for primary keys
ResultSet rs = dmd.getPrimaryKeys(null, null, table);
while (rs.next()) {
m_orderBy.add(rs.getString(4));
}
rs.close();
if (m_orderBy.size() != 0) {
return true;
}
// check for unique keys
rs =
dmd.getBestRowIdentifier(null, null, table,
DatabaseMetaData.bestRowSession, false);
ResultSetMetaData rmd = rs.getMetaData();
int help = 0;
while (rs.next()) {
m_orderBy.add(rs.getString(2));
help++;
}
rs.close();
if (help == rmd.getColumnCount()) {
m_orderBy.clear();
}
if (m_orderBy.size() != 0) {
return true;
}
return false;
}
/**
* Converts string attribute into nominal ones for an instance read during
* incremental loading
*
* @param rs The result set
* @param i the index of the nominal attribute
* @throws Exception exception if it cannot be converted
*/
private void stringToNominal(ResultSet rs, int i) throws Exception {
while (rs.next()) {
String str = rs.getString(1);
if (!rs.wasNull()) {
Double index = m_nominalIndexes[i - 1].get(str);
if (index == null) {
index = new Double(m_nominalStrings[i - 1].size());
m_nominalIndexes[i - 1].put(str, index);
m_nominalStrings[i - 1].add(str);
}
}
}
}
/**
* Used in incremental loading. Modifies the SQL statement, so that only one
* instance per time is tretieved and the instances are ordered uniquely.
*
* @param query the query to modify for incremental loading
* @param offset sets which tuple out of the uniquely ordered ones should be
* returned
* @param choice the kind of query that is suitable for the used DBMS
* @return the modified query that returns only one result tuple.
*/
private String limitQuery(String query, int offset, int choice) {
String limitedQuery;
StringBuffer order = new StringBuffer();
String orderByString = "";
if (m_orderBy.size() != 0) {
order.append(" ORDER BY ");
for (int i = 0; i < m_orderBy.size() - 1; i++) {
if (m_DataBaseConnection.getUpperCase()) {
order.append(m_orderBy.get(i).toUpperCase());
} else {
order.append(m_orderBy.get(i));
}
order.append(", ");
}
if (m_DataBaseConnection.getUpperCase()) {
order.append(m_orderBy.get(m_orderBy.size() - 1).toUpperCase());
} else {
order.append(m_orderBy.get(m_orderBy.size() - 1));
}
orderByString = order.toString();
}
if (choice == 0) {
limitedQuery =
query.replaceFirst("SELECT", "SELECT LIMIT " + offset + " 1");
limitedQuery = limitedQuery.concat(orderByString);
return limitedQuery;
}
if (choice == 1) {
limitedQuery = query.concat(orderByString + " LIMIT 1 OFFSET " + offset);
return limitedQuery;
}
limitedQuery = query.concat(orderByString + " LIMIT " + offset + ", 1");
// System.out.println(limitedQuery);
return limitedQuery;
}
/**
* Counts the number of rows that are loaded from the database
*
* @throws Exception if the number of rows cannot be calculated
* @return the entire number of rows
*/
private int getRowCount() throws Exception {
String query = "SELECT COUNT(*) FROM " + endOfQuery(false);
if (m_DataBaseConnection.execute(query) == false) {
throw new Exception("Cannot count results tuples.");
}
ResultSet rs = m_DataBaseConnection.getResultSet();
rs.next();
int i = rs.getInt(1);
rs.close();
return i;
}
/**
* Determines and returns (if possible) the structure (internally the header)
* of the data set as an empty set of instances.
*
* @return the structure of the data set as an empty set of Instances
* @throws IOException if an error occurs
*/
@Override
public Instances getStructure() throws IOException {
if (m_DataBaseConnection == null) {
throw new IOException("No source database has been specified");
}
connectToDatabase();
pseudo: try {
if (m_pseudoIncremental && m_structure == null) {
if (getRetrieval() == BATCH) {
throw new IOException(
"Cannot mix getting instances in both incremental and batch modes");
}
setRetrieval(NONE);
m_datasetPseudoInc = getDataSet();
m_structure = new Instances(m_datasetPseudoInc, 0);
setRetrieval(NONE);
return m_structure;
}
if (m_structure == null) {
if (m_checkForTable) {
if (!m_DataBaseConnection.tableExists(endOfQuery(true))) {
throw new IOException(
"Table does not exist according to metadata from JDBC driver. "
+ "If you are convinced the table exists, set 'checkForTable' "
+ "to 'False' in your DatabaseUtils.props file and try again.");
}
}
// finds out which SQL statement to use for the DBMS to limit the number
// of resulting rows to one
int choice = 0;
boolean rightChoice = false;
while (!rightChoice) {
try {
String limitQ = limitQuery(m_query, 0, choice);
if (m_DataBaseConnection.execute(limitQ) == false) {
throw new IOException("Query didn't produce results");
}
m_choice = choice;
rightChoice = true;
} catch (SQLException ex) {
choice++;
if (choice == 3) {
System.out
.println("Incremental loading not supported for that DBMS. Pseudoincremental mode is used if you use incremental loading.\nAll rows are loaded into memory once and retrieved incrementally from memory instead of from the database.");
m_pseudoIncremental = true;
break pseudo;
}
}
}
String end = endOfQuery(false);
ResultSet rs = m_DataBaseConnection.getResultSet();
ResultSetMetaData md = rs.getMetaData();
// rs.close();
int numAttributes = md.getColumnCount();
int[] attributeTypes = new int[numAttributes];
m_nominalIndexes = Utils.cast(new Hashtable[numAttributes]);
m_nominalStrings = Utils.cast(new ArrayList[numAttributes]);
for (int i = 1; i <= numAttributes; i++) {
switch (m_DataBaseConnection.translateDBColumnType(md
.getColumnTypeName(i))) {
case DatabaseConnection.STRING:
String columnName = md.getColumnLabel(i);
if (m_DataBaseConnection.getUpperCase()) {
columnName = columnName.toUpperCase();
}
m_nominalIndexes[i - 1] = new Hashtable<String, Double>();
m_nominalStrings[i - 1] = new ArrayList<String>();
// fast incomplete structure for batch mode - actual
// structure is determined by InstanceQuery in getDataSet()
if (getRetrieval() != INCREMENTAL) {
attributeTypes[i - 1] = Attribute.STRING;
break;
}
// System.err.println("String --> nominal");
ResultSet rs1;
String query =
"SELECT COUNT(DISTINCT( " + columnName + " )) FROM " + end;
if (m_DataBaseConnection.execute(query) == true) {
rs1 = m_DataBaseConnection.getResultSet();
rs1.next();
int count = rs1.getInt(1);
rs1.close();
// if(count > m_nominalToStringLimit ||
// m_DataBaseConnection.execute("SELECT DISTINCT ( "+columnName+" ) FROM "+
// end) == false){
if (count > m_nominalToStringLimit
|| m_DataBaseConnection.execute("SELECT DISTINCT ( "
+ columnName + " ) FROM " + end + " ORDER BY " + columnName) == false) {
attributeTypes[i - 1] = Attribute.STRING;
break;
}
rs1 = m_DataBaseConnection.getResultSet();
} else {
// System.err.println("Count for nominal values cannot be calculated. Attribute "+columnName+" treated as String.");
attributeTypes[i - 1] = Attribute.STRING;
break;
}
attributeTypes[i - 1] = Attribute.NOMINAL;
stringToNominal(rs1, i);
rs1.close();
break;
case DatabaseConnection.TEXT:
// System.err.println("boolean --> string");
columnName = md.getColumnLabel(i);
if (m_DataBaseConnection.getUpperCase()) {
columnName = columnName.toUpperCase();
}
m_nominalIndexes[i - 1] = new Hashtable<String, Double>();
m_nominalStrings[i - 1] = new ArrayList<String>();
// fast incomplete structure for batch mode - actual
// structure is determined by InstanceQuery in getDataSet()
if (getRetrieval() != INCREMENTAL) {
attributeTypes[i - 1] = Attribute.STRING;
break;
}
query = "SELECT COUNT(DISTINCT( " + columnName + " )) FROM " + end;
if (m_DataBaseConnection.execute(query) == true) {
rs1 = m_DataBaseConnection.getResultSet();
stringToNominal(rs1, i);
rs1.close();
}
attributeTypes[i - 1] = Attribute.STRING;
break;
case DatabaseConnection.BOOL:
// System.err.println("boolean --> nominal");
attributeTypes[i - 1] = Attribute.NOMINAL;
m_nominalIndexes[i - 1] = new Hashtable<String, Double>();
m_nominalIndexes[i - 1].put("false", new Double(0));
m_nominalIndexes[i - 1].put("true", new Double(1));
m_nominalStrings[i - 1] = new ArrayList<String>();
m_nominalStrings[i - 1].add("false");
m_nominalStrings[i - 1].add("true");
break;
case DatabaseConnection.DOUBLE:
// System.err.println("BigDecimal --> numeric");
attributeTypes[i - 1] = Attribute.NUMERIC;
break;
case DatabaseConnection.BYTE:
// System.err.println("byte --> numeric");
attributeTypes[i - 1] = Attribute.NUMERIC;
break;
case DatabaseConnection.SHORT:
// System.err.println("short --> numeric");
attributeTypes[i - 1] = Attribute.NUMERIC;
break;
case DatabaseConnection.INTEGER:
// System.err.println("int --> numeric");
attributeTypes[i - 1] = Attribute.NUMERIC;
break;
case DatabaseConnection.LONG:
// System.err.println("long --> numeric");
attributeTypes[i - 1] = Attribute.NUMERIC;
break;
case DatabaseConnection.FLOAT:
// System.err.println("float --> numeric");
attributeTypes[i - 1] = Attribute.NUMERIC;
break;
case DatabaseConnection.DATE:
attributeTypes[i - 1] = Attribute.DATE;
break;
case DatabaseConnection.TIME:
attributeTypes[i - 1] = Attribute.DATE;
break;
default:
// System.err.println("Unknown column type");
attributeTypes[i - 1] = Attribute.STRING;
}
}
ArrayList<Attribute> attribInfo = new ArrayList<Attribute>();
for (int i = 0; i < numAttributes; i++) {
/* Fix for databases that uppercase column names */
// String attribName = attributeCaseFix(md.getColumnName(i + 1));
String attribName = md.getColumnLabel(i + 1);
switch (attributeTypes[i]) {
case Attribute.NOMINAL:
attribInfo.add(new Attribute(attribName, m_nominalStrings[i]));
break;
case Attribute.NUMERIC:
attribInfo.add(new Attribute(attribName));
break;
case Attribute.STRING:
Attribute att = new Attribute(attribName, (ArrayList<String>) null);
for (int n = 0; n < m_nominalStrings[i].size(); n++) {
att.addStringValue(m_nominalStrings[i].get(n));
}
attribInfo.add(att);
break;
case Attribute.DATE:
attribInfo.add(new Attribute(attribName, (String) null));
break;
default:
throw new IOException("Unknown attribute type");
}
}
m_structure = new Instances(endOfQuery(true), attribInfo, 0);
// get rid of m_idColumn
if (m_DataBaseConnection.getUpperCase()) {
m_idColumn = m_idColumn.toUpperCase();
}
// System.out.println(m_structure.attribute(0).name().equals(idColumn));
if (m_structure.attribute(0).name().equals(m_idColumn)) {
m_oldStructure = new Instances(m_structure, 0);
m_oldStructure.deleteAttributeAt(0);
// System.out.println(m_structure);
} else {
m_oldStructure = new Instances(m_structure, 0);
}
if (m_DataBaseConnection.getResultSet() != null) {
rs.close();
}
} else {
if (m_oldStructure == null) {
m_oldStructure = new Instances(m_structure, 0);
}
}
m_DataBaseConnection.disconnectFromDatabase();
} catch (Exception ex) {
ex.printStackTrace();
printException(ex);
}
return m_oldStructure;
}
/**
* Return the full data set in batch mode (header and all intances at once).
*
* @return the structure of the data set as an empty set of Instances
* @throws IOException if there is no source or parsing fails
*/
@Override
public Instances getDataSet() throws IOException {
if (m_DataBaseConnection == null) {
throw new IOException("No source database has been specified");
}
if (getRetrieval() == INCREMENTAL) {
throw new IOException(
"Cannot mix getting Instances in both incremental and batch modes");
}
setRetrieval(BATCH);
Instances result = null;
checkEnv();
try {
InstanceQuery iq = new InstanceQuery();
iq.initialize(m_CustomPropsFile);
String realURL = m_URL;
try {
realURL = m_env.substitute(realURL);
} catch (Exception ex) {
}
iq.setDatabaseURL(realURL);
String realUser = m_User;
try {
realUser = m_env.substitute(realUser);
} catch (Exception ex) {
}
iq.setUsername(realUser);
String realPass = m_Password;
try {
realPass = m_env.substitute(realPass);
} catch (Exception ex) {
}
iq.setPassword(realPass);
String realQuery = m_query;
try {
realQuery = m_env.substitute(realQuery);
} catch (Exception ex) {
}
iq.setQuery(realQuery);
iq.setSparseData(m_CreateSparseData);
result = iq.retrieveInstances();
if (m_DataBaseConnection.getUpperCase()) {
m_idColumn = m_idColumn.toUpperCase();
}
if (result.attribute(0).name().equals(m_idColumn)) {
result.deleteAttributeAt(0);
}
m_structure = new Instances(result, 0);
iq.disconnectFromDatabase();
} catch (Exception ex) {
printException(ex);
StringBuffer text = new StringBuffer();
if (m_query.equals("Select * from Results0")) {
text.append("\n\nDatabaseLoader options:\n");
Enumeration<Option> enumi = listOptions();
while (enumi.hasMoreElements()) {
Option option = enumi.nextElement();
text.append(option.synopsis() + '\n');
text.append(option.description() + '\n');
}
System.out.println(text);
}
}
return result;
}
/**
* Reads an instance from a database.
*
* @param rs the ReusltSet to load
* @throws Exception if instance cannot be read
* @return an instance read from the database
*/
private Instance readInstance(ResultSet rs) throws Exception {
ResultSetMetaData md = rs.getMetaData();
int numAttributes = md.getColumnCount();
double[] vals = new double[numAttributes];
m_structure.delete();
for (int i = 1; i <= numAttributes; i++) {
switch (m_DataBaseConnection.translateDBColumnType(md
.getColumnTypeName(i))) {
case DatabaseConnection.STRING:
String str = rs.getString(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
Double index = m_nominalIndexes[i - 1].get(str);
if (index == null) {
index =
new Double(m_structure.attribute(i - 1).addStringValue(str));
}
vals[i - 1] = index.doubleValue();
}
break;
case DatabaseConnection.TEXT:
str = rs.getString(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
Double index = m_nominalIndexes[i - 1].get(str);
if (index == null) {
index =
new Double(m_structure.attribute(i - 1).addStringValue(str));
}
vals[i - 1] = index.doubleValue();
}
break;
case DatabaseConnection.BOOL:
boolean boo = rs.getBoolean(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
vals[i - 1] = (boo ? 1.0 : 0.0);
}
break;
case DatabaseConnection.DOUBLE:
// BigDecimal bd = rs.getBigDecimal(i, 4);
double dd = rs.getDouble(i);
// Use the column precision instead of 4?
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
// newInst.setValue(i - 1, bd.doubleValue());
vals[i - 1] = dd;
}
break;
case DatabaseConnection.BYTE:
byte by = rs.getByte(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
vals[i - 1] = by;
}
break;
case DatabaseConnection.SHORT:
short sh = rs.getShort(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
vals[i - 1] = sh;
}
break;
case DatabaseConnection.INTEGER:
int in = rs.getInt(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
vals[i - 1] = in;
}
break;
case DatabaseConnection.LONG:
long lo = rs.getLong(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
vals[i - 1] = lo;
}
break;
case DatabaseConnection.FLOAT:
float fl = rs.getFloat(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
vals[i - 1] = fl;
}
break;
case DatabaseConnection.DATE:
Date date = rs.getDate(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
// TODO: Do a value check here.
vals[i - 1] = date.getTime();
}
break;
case DatabaseConnection.TIME:
Time time = rs.getTime(i);
if (rs.wasNull()) {
vals[i - 1] = Utils.missingValue();
} else {
// TODO: Do a value check here.
vals[i - 1] = time.getTime();
}
break;
default:
vals[i - 1] = Utils.missingValue();
}
}
Instance inst;
if (m_CreateSparseData) {
inst = new SparseInstance(1.0, vals);
} else {
inst = new DenseInstance(1.0, vals);
}
// get rid of m_idColumn
if (m_DataBaseConnection.getUpperCase()) {
m_idColumn = m_idColumn.toUpperCase();
}
if (m_structure.attribute(0).name().equals(m_idColumn)) {
inst.deleteAttributeAt(0);
m_oldStructure.add(inst);
inst = m_oldStructure.instance(0);
m_oldStructure.delete(0);
} else {
// instances is added to and deleted from the structure to get the true
// nominal values instead of the index of the values.
m_structure.add(inst);
inst = m_structure.instance(0);
m_structure.delete(0);
}
return inst;
}
/**
* Read the data set incrementally---get the next instance in the data set or
* returns null if there are no more instances to get. If the structure hasn't
* yet been determined by a call to getStructure then method does so before
* returning the next instance in the data set.
*
* @param structure the dataset header information, will get updated in case
* of string or relational attributes
* @return the next instance in the data set as an Instance object or null if
* there are no more instances to be read
* @throws IOException if there is an error during parsing
*/
@Override
public Instance getNextInstance(Instances structure) throws IOException {
m_structure = structure;
if (m_DataBaseConnection == null) {
throw new IOException("No source database has been specified");
}
if (getRetrieval() == BATCH) {
throw new IOException(
"Cannot mix getting Instances in both incremental and batch modes");
}
// pseudoInremental: Load all instances into main memory in batch mode and
// give them incrementally to user
if (m_pseudoIncremental) {
setRetrieval(INCREMENTAL);
if (m_datasetPseudoInc.numInstances() > 0) {
Instance current = m_datasetPseudoInc.instance(0);
m_datasetPseudoInc.delete(0);
return current;
} else {
resetStructure();
return null;
}
}
// real incremental mode. At the moment(version 1.0) only for MySQL and
// HSQLDB (Postgres not tested, should work)
setRetrieval(INCREMENTAL);
try {
if (!m_DataBaseConnection.isConnected()) {
connectToDatabase();
}
// if no key columns specified by user, try to detect automatically
if (m_firstTime && m_orderBy.size() == 0) {
if (!checkForKey()) {
throw new Exception(
"A unique order cannot be detected automatically.\nYou have to use SELECT * in your query to enable this feature.\nMaybe JDBC driver is not able to detect key.\nDefine primary key in your database or use -P option (command line) or enter key columns in the GUI.");
}
}
if (m_firstTime) {
m_firstTime = false;
m_rowCount = getRowCount();
}
// as long as not all rows has been loaded
if (m_counter < m_rowCount) {
if (m_DataBaseConnection.execute(limitQuery(m_query, m_counter,
m_choice)) == false) {
throw new Exception("Tuple could not be retrieved.");
}
m_counter++;
ResultSet rs = m_DataBaseConnection.getResultSet();
rs.next();
Instance current = readInstance(rs);
rs.close();
return current;
} else {
m_DataBaseConnection.disconnectFromDatabase();
resetStructure();
return null;
}
} catch (Exception ex) {
printException(ex);
}
return null;
}
/**
* Gets the setting
*
* @return the current setting
*/
@Override
public String[] getOptions() {
Vector<String> options = new Vector<String>();
if ((getUrl() != null) && (getUrl().length() != 0)) {
options.add("-url");
options.add(getUrl());
}
if ((getUser() != null) && (getUser().length() != 0)) {
options.add("-user");
options.add(getUser());
}
if ((getPassword() != null) && (getPassword().length() != 0)) {
options.add("-password");
options.add(getPassword());
}
options.add("-Q");
options.add(getQuery());
StringBuffer text = new StringBuffer();
for (int i = 0; i < m_orderBy.size(); i++) {
if (i > 0) {
text.append(", ");
}
text.append(m_orderBy.get(i));
}
if (text.length() > 0) {
options.add("-P");
options.add(text.toString());
}
if (m_inc) {
options.add("-I");
}
if ((m_CustomPropsFile != null) && !m_CustomPropsFile.isDirectory()) {
options.add("-custom-props");
options.add(m_CustomPropsFile.toString());
}
return options.toArray(new String[options.size()]);
}
/**
* Lists the available options
*
* @return an enumeration of the available options
*/
@Override
public Enumeration<Option> listOptions() {
Vector<Option> newVector = new Vector<Option>();
newVector.add(new Option("\tThe JDBC URL to connect to.\n"
+ "\t(default: from DatabaseUtils.props file)", "url", 1,
"-url <JDBC URL>"));
newVector.add(new Option("\tThe user to connect with to the database.\n"
+ "\t(default: none)", "user", 1, "-user <name>"));
newVector
.add(new Option("\tThe password to connect with to the database.\n"
+ "\t(default: none)", "password", 1, "-password <password>"));
newVector.add(new Option("\tSQL query of the form\n"
+ "\t\tSELECT <list of columns>|* FROM <table> [WHERE]\n"
+ "\tto execute.\n" + "\t(default: Select * From Results0)", "Q", 1,
"-Q <query>"));
newVector.add(new Option(
"\tList of column names uniquely defining a DB row\n"
+ "\t(separated by ', ').\n" + "\tUsed for incremental loading.\n"
+ "\tIf not specified, the key will be determined automatically,\n"
+ "\tif possible with the used JDBC driver.\n"
+ "\tThe auto ID column created by the DatabaseSaver won't be loaded.",
"P", 1, "-P <list of column names>"));
newVector.add(new Option("\tSets incremental loading", "I", 0, "-I"));
newVector.addElement(new Option(
"\tReturn sparse rather than normal instances.", "S", 0, "-S"));
newVector.add(new Option(
"\tThe custom properties file to use instead of default ones,\n"
+ "\tcontaining the database parameters.\n" + "\t(default: none)",
"custom-props", 1, "-custom-props <file>"));
return newVector.elements();
}
/**
* Sets the options.
*
* <!-- options-start --> Valid options are:
* <p/>
*
* <pre>
* -url <JDBC URL>
* The JDBC URL to connect to.
* (default: from DatabaseUtils.props file)
* </pre>
*
* <pre>
* -user <name>
* The user to connect with to the database.
* (default: none)
* </pre>
*
* <pre>
* -password <password>
* The password to connect with to the database.
* (default: none)
* </pre>
*
* <pre>
* -Q <query>
* SQL query of the form
* SELECT <list of columns>|* FROM <table> [WHERE]
* to execute.
* (default: Select * From Results0)
* </pre>
*
* <pre>
* -P <list of column names>
* List of column names uniquely defining a DB row
* (separated by ', ').
* Used for incremental loading.
* If not specified, the key will be determined automatically,
* if possible with the used JDBC driver.
* The auto ID column created by the DatabaseSaver won't be loaded.
* </pre>
*
* <pre>
* -I
* Sets incremental loading
* </pre>
*
* <!-- options-end -->
*
* @param options the options
* @throws Exception if options cannot be set
*/
@Override
public void setOptions(String[] options) throws Exception {
String optionString, keyString, tmpStr;
optionString = Utils.getOption('Q', options);
keyString = Utils.getOption('P', options);
reset();
tmpStr = Utils.getOption("url", options);
if (tmpStr.length() != 0) {
setUrl(tmpStr);
}
tmpStr = Utils.getOption("user", options);
if (tmpStr.length() != 0) {
setUser(tmpStr);
}
tmpStr = Utils.getOption("password", options);
if (tmpStr.length() != 0) {
setPassword(tmpStr);
}
if (optionString.length() != 0) {
setQuery(optionString);
}
m_orderBy.clear();
m_inc = Utils.getFlag('I', options);
if (m_inc) {
StringTokenizer st = new StringTokenizer(keyString, ",");
while (st.hasMoreTokens()) {
String column = st.nextToken();
column = column.replaceAll(" ", "");
m_orderBy.add(column);
}
}
tmpStr = Utils.getOption("custom-props", options);
if (tmpStr.length() == 0) {
setCustomPropsFile(null);
} else {
setCustomPropsFile(new File(tmpStr));
}
}
/**
* Prints an exception
*
* @param ex the exception to print
*/
private void printException(Exception ex) {
System.out.println("\n--- Exception caught ---\n");
while (ex != null) {
System.out.println("Message: " + ex.getMessage());
if (ex instanceof SQLException) {
System.out.println("SQLState: " + ((SQLException) ex).getSQLState());
System.out.println("ErrorCode: " + ((SQLException) ex).getErrorCode());
ex = ((SQLException) ex).getNextException();
} else {
ex = null;
}
System.out.println("");
}
}
/**
* Returns the revision string.
*
* @return the revision
*/
@Override
public String getRevision() {
return RevisionUtils.extract("$Revision$");
}
/**
* Main method.
*
* @param options the options
*/
public static void main(String[] options) {
DatabaseLoader atf;
try {
atf = new DatabaseLoader();
atf.setOptions(options);
atf.setSource(atf.getUrl(), atf.getUser(), atf.getPassword());
if (!atf.m_inc) {
System.out.println(atf.getDataSet());
} else {
Instances structure = atf.getStructure();
System.out.println(structure);
Instance temp;
do {
temp = atf.getNextInstance(structure);
if (temp != null) {
System.out.println(temp);
}
} while (temp != null);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("\n" + e.getMessage());
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.